Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel
Register Humanoid module in built-ins and solution
Yuechen Li5cebc2188919
diff --git a/Aetheris.CLI.Tests/ModulesCommandTests.cs b/Aetheris.CLI.Tests/ModulesCommandTests.csindex 8606f213..8b9457a2 100644--- a/Aetheris.CLI.Tests/ModulesCommandTests.cs+++ b/Aetheris.CLI.Tests/ModulesCommandTests.cs@@ -9,7 +9,7 @@ public sealed class ModulesCommandTestspublic void ModulesJsonInspectsStableBuiltInsAndCapabilities(){var stdout=new StringWriter();var stderr=new StringWriter();var exit=CliRunner.Run(["modules","--json"],stdout,stderr);- Assert.Equal(0,exit);Assert.Empty(stderr.ToString());using var json=JsonDocument.Parse(stdout.ToString());var modules=json.RootElement.EnumerateArray().ToArray();Assert.Equal(["Aetheris.Core","Aetheris.Piping","Aetheris.Surfacing","Aetheris.PlasticShell","Aetheris.SheetMetal"],modules.Select(m=>m.GetProperty("id").GetString()));Assert.Contains(modules.SelectMany(m=>m.GetProperty("capabilities").EnumerateArray()),c=>c.GetString()=="Piping.PipeRoute");Assert.Contains(modules.SelectMany(m=>m.GetProperty("capabilities").EnumerateArray()),c=>c.GetString()=="PlasticShell.Intent");+ Assert.Equal(0,exit);Assert.Empty(stderr.ToString());using var json=JsonDocument.Parse(stdout.ToString());var modules=json.RootElement.EnumerateArray().ToArray();Assert.Equal(["Aetheris.Core","Aetheris.Humanoid","Aetheris.Piping","Aetheris.Surfacing","Aetheris.PlasticShell","Aetheris.SheetMetal"],modules.Select(m=>m.GetProperty("id").GetString()));Assert.Contains(modules.SelectMany(m=>m.GetProperty("capabilities").EnumerateArray()),c=>c.GetString()=="Piping.PipeRoute");Assert.Contains(modules.SelectMany(m=>m.GetProperty("capabilities").EnumerateArray()),c=>c.GetString()=="PlasticShell.Intent");Assert.Contains(modules.SelectMany(m=>m.GetProperty("capabilities").EnumerateArray()),c=>c.GetString()=="Humanoid.CanonicalSurface");}[Fact]diff --git a/Aetheris.Humanoid.Tests/Aetheris.Humanoid.Tests.csproj b/Aetheris.Humanoid.Tests/Aetheris.Humanoid.Tests.csprojnew file mode 100644index 00000000..ae7a1fc0--- /dev/null+++ b/Aetheris.Humanoid.Tests/Aetheris.Humanoid.Tests.csproj@@ -0,0 +1,9 @@+<Project Sdk="Microsoft.NET.Sdk">+ <PropertyGroup><TargetFramework>net10.0</TargetFramework><ImplicitUsings>enable</ImplicitUsings><Nullable>enable</Nullable><IsPackable>false</IsPackable></PropertyGroup>+ <ItemGroup>+ <PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.14.1" />+ <PackageReference Include="xunit" Version="2.9.3" />+ <PackageReference Include="xunit.runner.visualstudio" Version="3.1.4"><PrivateAssets>all</PrivateAssets></PackageReference>+ </ItemGroup>+ <ItemGroup><ProjectReference Include="..\Aetheris.Humanoid\Aetheris.Humanoid.csproj" /></ItemGroup>+</Project>diff --git a/Aetheris.Humanoid.Tests/HumanoidX0Tests.cs b/Aetheris.Humanoid.Tests/HumanoidX0Tests.csnew file mode 100644index 00000000..f717485f--- /dev/null+++ b/Aetheris.Humanoid.Tests/HumanoidX0Tests.cs@@ -0,0 +1,113 @@+using System.Numerics;+using Aetheris.Humanoid;+using Aetheris.Kernel.Core.Math;+using Xunit;++namespace Aetheris.Humanoid.Tests;++public sealed class HumanoidX0Tests+{+ private static readonly Lazy<CanonicalHumanoid> Fixture=new(CanonicalAdultTemplate.Create);++ [Fact]+ public void AuthoredTemplate_HasStableIdentityAndValidInvariants()+ {+ var h=Fixture.Value;var result=HumanoidValidator.Validate(h);+ Assert.True(result.IsValid,string.Join("\n",result.Diagnostics));+ Assert.Equal("aetheris.humanoid.adult.standard.v1",h.Surface.TopologyId);+ Assert.InRange(h.Surface.Vertices.Count,8000,20000);+ Assert.Equal(h.Surface.Faces.Count,h.Surface.BindingTriangles.Count);+ Assert.All(h.Surface.Vertices.Select((v,i)=>(v,i)),x=>Assert.Equal(x.i,h.Surface.Vertices[x.v.SymmetryPartnerIndex].SymmetryPartnerIndex));+ }++ [Fact]+ public void AuthoredTemplate_IsDeterministic()+ {+ var first=Fixture.Value;var second=CanonicalAdultTemplate.Create();+ Assert.Equal(first.Surface.ConnectivityHash,second.Surface.ConnectivityHash);+ Assert.Equal(first.Provenance.ConfigHash,second.Provenance.ConfigHash);+ Assert.Equal(first.Surface.Vertices.Select(x=>x.Position),second.Surface.Vertices.Select(x=>x.Position));+ }++ [Fact]+ public void Measurements_AreTypedRepeatableAndExplicitlyPosed()+ {+ var a=HumanoidMeasurements.Evaluate(Fixture.Value);var b=HumanoidMeasurements.Evaluate(Fixture.Value);+ Assert.Equal(a,b);Assert.Contains(a,x=>x.Measurement==HumanoidMeasurementId.Height&&x.ValueMm==1750&&x.IsValid);+ Assert.All(a,x=>Assert.Equal(CanonicalAdultStandardV1.MeasurementPoseId,x.PoseId));+ Assert.Contains(a,x=>x.Measurement==HumanoidMeasurementId.ArmLength&&x.ValueMm>500);+ }++ [Fact]+ public void Morphs_KeepTopologyAndMoveExpectedMeasurements()+ {+ var h=Fixture.Value;var baseline=HumanoidMeasurements.Evaluate(h).ToDictionary(x=>x.Measurement,x=>x.ValueMm!.Value);+ var tall=HumanoidMorphing.Apply(h,new Dictionary<HumanoidMorphId,double>{{HumanoidMorphId.Height,1800},{HumanoidMorphId.LegLength,35},{HumanoidMorphId.ArmLength,25}});+ var measured=HumanoidMeasurements.Evaluate(tall).ToDictionary(x=>x.Measurement,x=>x.ValueMm!.Value);+ Assert.Equal(h.Surface.ConnectivityHash,tall.Surface.ConnectivityHash);Assert.Equal(1,tall.ShapeRevision);+ Assert.InRange(measured[HumanoidMeasurementId.Height],1799.999,1800.001);+ Assert.Equal(1800,tall.Frame.NormalizedHeightMm);+ Assert.True(measured[HumanoidMeasurementId.LegLength]>baseline[HumanoidMeasurementId.LegLength]);+ Assert.True(measured[HumanoidMeasurementId.ArmLength]>baseline[HumanoidMeasurementId.ArmLength]);+ Assert.True(HumanoidValidator.Validate(tall).IsValid);+ }++ [Fact]+ public void MorphBounds_FailClosedWithStructuredDiagnostic()+ {+ var ex=Assert.Throws<HumanoidDomainException>(()=>HumanoidMorphing.Apply(Fixture.Value,new Dictionary<HumanoidMorphId,double>{{HumanoidMorphId.Height,2100}}));+ Assert.Equal(HumanoidDiagnosticCode.HUM013_MorphOutOfBounds,ex.Diagnostic.Code);+ }++ [Fact]+ public void PoseAndAttachment_UseSameSkeletonSemantics()+ {+ var h=Fixture.Value;var pose=new HumanoidPoseState("test.elbow",[new(HumanoidJointKind.LeftElbow,Quaternion.CreateFromAxisAngle(Vector3.UnitY,(float)(Math.PI/2)))],HumanoidTransform.Identity);+ var neutral=HumanoidPosing.EvaluateAttachment(h,"site:Wrist.Left",h.PoseState);var posed=HumanoidPosing.EvaluateAttachment(h,"site:Wrist.Left",pose);var vertices=HumanoidPosing.EvaluateVertices(h,pose);+ Assert.NotEqual(neutral.Position,posed.Position);Assert.All(vertices,p=>Assert.True(double.IsFinite(p.X)&&double.IsFinite(p.Y)&&double.IsFinite(p.Z)));Assert.Equal(h.Surface.Vertices.Count,vertices.Count);+ }++ [Fact]+ public void RequiredDomainKindsRemainSeparate()+ {+ var h=Fixture.Value;+ Assert.NotEmpty(h.Landmarks.OfType<SurfaceLandmark>());Assert.NotEmpty(h.Landmarks.OfType<JointLandmark>());+ Assert.DoesNotContain(h.Landmarks,x=>x.GetType()==typeof(HumanoidLandmark));+ Assert.Contains(h.Attachments,x=>x.Id=="site:Chest");Assert.Contains(h.Attachments,x=>x.Id=="site:Wrist.Left");Assert.Contains(h.Attachments,x=>x.Id=="site:Foot.Left");+ }++ [Fact]+ public void CorruptedWeightAndBindingAreRejected()+ {+ var h=Fixture.Value;var brokenWeight=h.Surface.SkinWeights.ToArray();brokenWeight[0]=new(0,[new(0,.8)]);var result=HumanoidValidator.Validate(h with{Surface=h.Surface with{SkinWeights=brokenWeight}});Assert.Contains(result.Diagnostics,x=>x.Code==HumanoidDiagnosticCode.HUM005_SkinWeightsInvalid);+ var landmark=(SurfaceLandmark)h.Landmarks.OfType<SurfaceLandmark>().First();var bad=landmark with{Binding=landmark.Binding with{TopologyId="wrong"}};var landmarks=h.Landmarks.Select(x=>x.Id==bad.Id?bad:x).ToArray();result=HumanoidValidator.Validate(h with{Landmarks=landmarks});Assert.Contains(result.Diagnostics,x=>x.Code==HumanoidDiagnosticCode.HUM014_InvalidBinding);+ }++ [Fact]+ public void CorrespondingRegistrationRecoversKnownSmoothDeformationWithoutChangingIdentity()+ {+ var h=Fixture.Value;var targets=h.Surface.Vertices.Select(v=>v.Position+new Vector3D(12*Math.Sin(v.Position.Z/300),4*Math.Cos(v.Position.X/180),8*Math.Sin(v.Position.Y/100))).ToArray();var config=new CorrespondingRegistrationConfig("synthetic-known-v1",30,.5,20,.001);var result=HumanoidCorrespondingRegistration.Fit(h,h.Surface.TopologyId,targets,config);var replay=HumanoidCorrespondingRegistration.Fit(h,h.Surface.TopologyId,targets,config);+ Assert.True(result.Converged);Assert.True(result.FinalRmsMm<.001);Assert.True(result.InitialRmsMm>result.FinalRmsMm*1000);Assert.Equal(h.Surface.ConnectivityHash,result.Humanoid.Surface.ConnectivityHash);Assert.Equal(h.Surface.Faces,result.Humanoid.Surface.Faces);+ Assert.Equal(result.Humanoid.Surface.Vertices.Select(x=>x.Position),replay.Humanoid.Surface.Vertices.Select(x=>x.Position));var rejected=HumanoidCorrespondingRegistration.Fit(h,"wrong-topology",targets,config);Assert.Contains(rejected.Diagnostics,x=>x.Code==HumanoidDiagnosticCode.HUM015_ConnectivityChanged);+ }++ [Theory]+ [InlineData(HumanoidMorphId.Height,1650)][InlineData(HumanoidMorphId.Height,1850)]+ [InlineData(HumanoidMorphId.ArmLength,-50)][InlineData(HumanoidMorphId.ArmLength,50)]+ [InlineData(HumanoidMorphId.LegLength,-60)][InlineData(HumanoidMorphId.LegLength,60)]+ [InlineData(HumanoidMorphId.ShoulderWidth,-40)][InlineData(HumanoidMorphId.ShoulderWidth,40)]+ public void MorphEndpointsKeepTopologyAndCanonicalValidity(HumanoidMorphId id,double value)+ {+ var h=Fixture.Value;var shaped=HumanoidMorphing.Apply(h,new Dictionary<HumanoidMorphId,double>{{id,value}});Assert.Equal(h.Surface.ConnectivityHash,shaped.Surface.ConnectivityHash);Assert.True(HumanoidValidator.Validate(shaped).IsValid);Assert.Equal(h.Surface.Faces,shaped.Surface.Faces);+ }++ [Theory]+ [InlineData(HumanoidJointKind.LeftShoulder,35)][InlineData(HumanoidJointKind.LeftShoulder,70)]+ [InlineData(HumanoidJointKind.LeftElbow,45)][InlineData(HumanoidJointKind.LeftElbow,90)]+ [InlineData(HumanoidJointKind.LeftHip,35)][InlineData(HumanoidJointKind.LeftHip,70)]+ [InlineData(HumanoidJointKind.LeftKnee,45)][InlineData(HumanoidJointKind.LeftKnee,90)]+ public void PoseSweepProducesFiniteInspectableEvidence(HumanoidJointKind joint,double degrees)+ {+ var axis=joint is HumanoidJointKind.LeftHip or HumanoidJointKind.LeftKnee?Vector3.UnitX:Vector3.UnitY;var pose=new HumanoidPoseState($"sweep.{joint}.{degrees}",[new(joint,Quaternion.CreateFromAxisAngle(axis,(float)(degrees*Math.PI/180)))],HumanoidTransform.Identity);var evidence=HumanoidPoseQualification.Evaluate(Fixture.Value,pose);Assert.True(evidence.Finite);Assert.True(double.IsFinite(evidence.SurfaceAreaRatio));Assert.True(double.IsFinite(evidence.AbsoluteVolumeRatio));Assert.Contains("site:Wrist.Left",evidence.AttachmentPositions);+ }+}diff --git a/Aetheris.Humanoid/Aetheris.Humanoid.csproj b/Aetheris.Humanoid/Aetheris.Humanoid.csprojnew file mode 100644index 00000000..739b12f1--- /dev/null+++ b/Aetheris.Humanoid/Aetheris.Humanoid.csproj@@ -0,0 +1,12 @@+<Project Sdk="Microsoft.NET.Sdk">+ <PropertyGroup>+ <TargetFramework>net10.0</TargetFramework>+ <ImplicitUsings>enable</ImplicitUsings>+ <Nullable>enable</Nullable>+ <Description>Canonical adult humanoid semantics, deterministic topology, fitting evidence, measurements, morphs, pose, and attachments.</Description>+ </PropertyGroup>+ <ItemGroup>+ <ProjectReference Include="..\Aetheris.Kernel.Core\Aetheris.Kernel.Core.csproj" />+ <ProjectReference Include="..\Aetheris.Modules\Aetheris.Modules.csproj" />+ </ItemGroup>+</Project>diff --git a/Aetheris.Humanoid/CanonicalAdultTemplate.cs b/Aetheris.Humanoid/CanonicalAdultTemplate.csnew file mode 100644index 00000000..b75e0c8a--- /dev/null+++ b/Aetheris.Humanoid/CanonicalAdultTemplate.cs@@ -0,0 +1,358 @@+using System.Globalization;+using System.Numerics;+using System.Security.Cryptography;+using System.Text;+using Aetheris.Kernel.Core.Math;++namespace Aetheris.Humanoid;++/// <summary>+/// Independently authored X0 topology. Connectivity comes from a fixed tetrahedral lattice over explicit+/// semantic anatomical primitives; no external mesh positions or connectivity participate in generation.+/// </summary>+public static class CanonicalAdultTemplate+{+ private const double Step = 24d;+ private const string GeneratorVersion = "aetheris-humanoid-implicit-tetra-v1";+ private readonly record struct Primitive(string Id, HumanoidRegionKind Region, Func<Point3D, double> SignedDistance);+ private readonly record struct GridSample(Point3D Position, double Distance, HumanoidRegionKind Region, long Id);+ private readonly record struct EdgeKey(long A, long B)+ {+ public static EdgeKey Create(long a, long b) => a < b ? new(a, b) : new(b, a);+ }++ public static CanonicalHumanoid Create()+ {+ var skeleton = BuildSkeleton();+ var primitives = BuildPrimitives(skeleton);+ var (vertices, faces) = Polygonize(primitives);+ faces = RemoveCollapsedFaces(vertices, faces);+ var (withEyesRaw, withEyeFaces, components) = AddEyes(vertices, faces);+ var (withEyes, normalizedSkeleton, sourceMinimumZ, sourceMaximumZ) = NormalizeHeight(withEyesRaw, skeleton);+ skeleton = normalizedSkeleton;+ var symmetricVertices = AssignVertexSymmetry(withEyes);+ var symmetricFaces = AssignFaceSymmetry(withEyeFaces, symmetricVertices);+ var connectivityHash = ConnectivityHash(symmetricFaces);+ var triangles = symmetricFaces.Select((face, index) => new BindingTriangle($"bt:{index:D6}", index, face.A, face.B, face.C)).ToArray();+ var weights = GenerateWeights(symmetricVertices, skeleton);+ var surface = new HumanoidSurface(+ CanonicalAdultStandardV1.TopologyId,+ CanonicalAdultStandardV1.BindingTriangulationId,+ connectivityHash,+ symmetricVertices,+ symmetricFaces,+ triangles,+ null,+ weights,+ components,+ RegionSymmetry());+ var landmarks = BuildLandmarks(surface, skeleton);+ var protocols = BuildMeasurementProtocols();+ var morphs = BuildMorphChannels();+ var materials = Enum.GetValues<HumanoidRegionKind>().ToDictionary(+ region => region,+ region => region is HumanoidRegionKind.LeftEye or HumanoidRegionKind.RightEye ? MaterialRegionKind.Eyes+ : region is HumanoidRegionKind.MouthInterior ? MaterialRegionKind.MouthInterior : MaterialRegionKind.Skin);+ var attachments = BuildAttachments(surface, landmarks);+ var configHash = Hash(string.Join("|", GeneratorVersion, Step.ToString("R", CultureInfo.InvariantCulture), connectivityHash));+ var provenance = new HumanoidProvenance(+ "aetheris.humanoid.provenance.v1",+ [new("canonical-template", "authored-template", "Aetheris CanonicalAdultTemplate", "v1", connectivityHash, "Aetheris repository license", "canonical topology generation", true, "Connectivity is generated solely from repository-authored primitives and a fixed lattice.")],+ ["explicit semantic primitives", $"fixed {Step:R} mm lattice", "six fixed tetrahedra per cell", "zero-isovalue interpolation", "deterministic sub-0.0001 mm2 collapsed-face rejection", $"outer-skin Z normalization [{sourceMinimumZ:R},{sourceMaximumZ:R}] -> [0,1750] mm", "stable coordinate-order IDs", "procedural regional skin weights"],+ GeneratorVersion,+ configHash,+ connectivityHash,+ "AuthoredTemplate",+ ["X0 topology and facial/hand/foot quality require visual review; no third-party connectivity used."]);+ return new CanonicalHumanoid(+ "aetheris.humanoid.canonical.v1",+ new("adult-standard-v1", "Canonical Adult Standard V1", "adult-v1", "Adult-only engineering humanoid foundation; not medical or population-statistical authority."),+ new("mm", "right-handed", new(1, 0, 0), new(0, 1, 0), new(0, 0, 1), Point3D.Origin, CanonicalAdultStandardV1.NeutralHeightMm),+ surface,+ skeleton,+ landmarks,+ protocols,+ morphs,+ materials,+ attachments,+ new(CanonicalAdultStandardV1.RestPoseId, [], HumanoidTransform.Identity),+ provenance);+ }++ private static List<HumanoidFace> RemoveCollapsedFaces(IReadOnlyList<HumanoidVertex> vertices,IEnumerable<HumanoidFace> faces)+ => faces.Where(face=>+ {+ var a=vertices[face.A].Position;var b=vertices[face.B].Position;var c=vertices[face.C].Position;+ return (b-a).Cross(c-a).LengthSquared>=4e-8;+ }).Select((face,index)=>face with{Id=$"f:{index:D6}"}).ToList();++ private static (List<HumanoidVertex> Vertices, HumanoidSkeleton Skeleton, double MinimumZ, double MaximumZ) NormalizeHeight(List<HumanoidVertex> vertices,HumanoidSkeleton skeleton)+ {+ var outer=vertices.Where(v=>v.Region is not HumanoidRegionKind.LeftEye and not HumanoidRegionKind.RightEye).ToArray();var min=outer.Min(v=>v.Position.Z);var max=outer.Max(v=>v.Position.Z);var scale=CanonicalAdultStandardV1.NeutralHeightMm/(max-min);+ Point3D Map(Point3D p)=>new(p.X,p.Y,(p.Z-min)*scale);+ var mapped=vertices.Select(v=>v with{Position=Map(v.Position)}).ToList();var globals=skeleton.Joints.Select(j=>Map(new(j.GlobalBind.M41,j.GlobalBind.M42,j.GlobalBind.M43))).ToArray();var joints=new HumanoidJoint[skeleton.Joints.Count];+ for(var i=0;i<joints.Length;i++){var old=skeleton.Joints[i];var parent=old.ParentIndex is int pi?globals[pi]:Point3D.Origin;var local=globals[i]-parent;var global=Matrix4x4.CreateTranslation((float)globals[i].X,(float)globals[i].Y,(float)globals[i].Z);Matrix4x4.Invert(global,out var inverse);joints[i]=old with{LocalRest=new(new(local.X,local.Y,local.Z),Quaternion.Identity),GlobalBind=global,InverseBind=inverse};}+ return(mapped,skeleton with{Joints=joints},min,max);+ }++ private static IReadOnlyList<Primitive> BuildPrimitives(HumanoidSkeleton skeleton)+ {+ static double Ellipsoid(Point3D p, Point3D c, Vector3D r)+ {+ var q = new Vector3D((p.X-c.X)/r.X, (p.Y-c.Y)/r.Y, (p.Z-c.Z)/r.Z);+ return (q.Length - 1d) * double.Min(r.X, double.Min(r.Y, r.Z));+ }+ static double Capsule(Point3D p, Point3D a, Point3D b, double radius)+ {+ var ab=b-a; var ap=p-a; var t=double.Clamp(ap.Dot(ab)/ab.LengthSquared,0,1); var q=a+ab*t;+ return (p-q).Length-radius;+ }+ var j=skeleton.Joints.ToDictionary(x=>x.Kind,x=>new Point3D(x.GlobalBind.M41,x.GlobalBind.M42,x.GlobalBind.M43));+ var list=new List<Primitive>+ {+ new("head",HumanoidRegionKind.Head,p=>Ellipsoid(p,new(0,0,1585),new(104,92,145))),+ new("face",HumanoidRegionKind.Face,p=>Ellipsoid(p,new(0,53,1565),new(91,58,112))),+ new("nose",HumanoidRegionKind.Face,p=>Ellipsoid(p,new(0,111,1572),new(22,30,38))),+ new("chin",HumanoidRegionKind.Face,p=>Ellipsoid(p,new(0,72,1479),new(55,45,35))),+ new("lip-upper",HumanoidRegionKind.Face,p=>Ellipsoid(p,new(0,112,1528),new(31,13,9))),+ new("lip-lower",HumanoidRegionKind.Face,p=>Ellipsoid(p,new(0,112,1513),new(32,14,10))),+ new("ear-left",HumanoidRegionKind.LeftEar,p=>Ellipsoid(p,new(-108,0,1570),new(21,13,42))),+ new("ear-right",HumanoidRegionKind.RightEar,p=>Ellipsoid(p,new(108,0,1570),new(21,13,42))),+ new("neck",HumanoidRegionKind.Neck,p=>Capsule(p,j[HumanoidJointKind.Chest],j[HumanoidJointKind.Head],57)),+ new("chest",HumanoidRegionKind.Chest,p=>Ellipsoid(p,new(0,0,1280),new(225,125,245))),+ new("abdomen",HumanoidRegionKind.Abdomen,p=>Ellipsoid(p,new(0,3,1090),new(176,106,220))),+ new("pelvis",HumanoidRegionKind.Pelvis,p=>Ellipsoid(p,new(0,0,925),new(190,122,165)))+ };+ AddLimbs(AnatomicalSide.Left,-1); AddLimbs(AnatomicalSide.Right,1);+ return list;++ void AddLimbs(AnatomicalSide side,int sign)+ {+ var shoulder=side==AnatomicalSide.Left?HumanoidJointKind.LeftShoulder:HumanoidJointKind.RightShoulder;+ var elbow=side==AnatomicalSide.Left?HumanoidJointKind.LeftElbow:HumanoidJointKind.RightElbow;+ var wrist=side==AnatomicalSide.Left?HumanoidJointKind.LeftWrist:HumanoidJointKind.RightWrist;+ var hip=side==AnatomicalSide.Left?HumanoidJointKind.LeftHip:HumanoidJointKind.RightHip;+ var knee=side==AnatomicalSide.Left?HumanoidJointKind.LeftKnee:HumanoidJointKind.RightKnee;+ var ankle=side==AnatomicalSide.Left?HumanoidJointKind.LeftAnkle:HumanoidJointKind.RightAnkle;+ var prefix=side==AnatomicalSide.Left?"left":"right";+ var upper=side==AnatomicalSide.Left?HumanoidRegionKind.LeftUpperArm:HumanoidRegionKind.RightUpperArm;+ var elbowRegion=side==AnatomicalSide.Left?HumanoidRegionKind.LeftElbow:HumanoidRegionKind.RightElbow;+ var fore=side==AnatomicalSide.Left?HumanoidRegionKind.LeftForearm:HumanoidRegionKind.RightForearm;+ var hand=side==AnatomicalSide.Left?HumanoidRegionKind.LeftHand:HumanoidRegionKind.RightHand;+ list.Add(new(prefix+"-shoulder",side==AnatomicalSide.Left?HumanoidRegionKind.LeftShoulder:HumanoidRegionKind.RightShoulder,p=>Capsule(p,j[side==AnatomicalSide.Left?HumanoidJointKind.LeftClavicle:HumanoidJointKind.RightClavicle],j[shoulder],82)));+ list.Add(new(prefix+"-upper-arm",upper,p=>Capsule(p,j[shoulder],j[elbow],61)));+ list.Add(new(prefix+"-elbow",elbowRegion,p=>Ellipsoid(p,j[elbow],new(66,62,67))));+ list.Add(new(prefix+"-forearm",fore,p=>Capsule(p,j[elbow],j[wrist],47)));+ var handEnd=j[wrist]+(j[wrist]-j[elbow])*(0.52);+ list.Add(new(prefix+"-hand",hand,p=>Capsule(p,j[wrist],handEnd,49)));+ AddFingers(side,sign,j[wrist],j[elbow]);+ var thigh=side==AnatomicalSide.Left?HumanoidRegionKind.LeftThigh:HumanoidRegionKind.RightThigh;+ var kneeRegion=side==AnatomicalSide.Left?HumanoidRegionKind.LeftKnee:HumanoidRegionKind.RightKnee;+ var shin=side==AnatomicalSide.Left?HumanoidRegionKind.LeftShin:HumanoidRegionKind.RightShin;+ var ankleRegion=side==AnatomicalSide.Left?HumanoidRegionKind.LeftAnkle:HumanoidRegionKind.RightAnkle;+ var foot=side==AnatomicalSide.Left?HumanoidRegionKind.LeftFoot:HumanoidRegionKind.RightFoot;+ var toes=side==AnatomicalSide.Left?HumanoidRegionKind.LeftToes:HumanoidRegionKind.RightToes;+ list.Add(new(prefix+"-thigh",thigh,p=>Capsule(p,j[hip],j[knee],91)));+ list.Add(new(prefix+"-knee",kneeRegion,p=>Ellipsoid(p,j[knee],new(84,76,76))));+ list.Add(new(prefix+"-shin",shin,p=>Capsule(p,j[knee],j[ankle],61)));+ list.Add(new(prefix+"-ankle",ankleRegion,p=>Ellipsoid(p,j[ankle],new(62,57,65))));+ list.Add(new(prefix+"-foot",foot,p=>Ellipsoid(p,new(sign*88,62,48),new(70,150,50))));+ list.Add(new(prefix+"-toes",toes,p=>Ellipsoid(p,new(sign*88,164,39),new(72,70,34))));+ }+ void AddFingers(AnatomicalSide side,int sign,Point3D wrist,Point3D elbow)+ {+ var direction=wrist-elbow; direction=direction/direction.Length;+ var basePoint=wrist+direction*65;+ var defs=new[]{("thumb",-38d,58d,side==AnatomicalSide.Left?HumanoidRegionKind.LeftThumb:HumanoidRegionKind.RightThumb),+ ("index",-21d,103d,side==AnatomicalSide.Left?HumanoidRegionKind.LeftIndex:HumanoidRegionKind.RightIndex),+ ("middle",-7d,112d,side==AnatomicalSide.Left?HumanoidRegionKind.LeftMiddle:HumanoidRegionKind.RightMiddle),+ ("ring",8d,105d,side==AnatomicalSide.Left?HumanoidRegionKind.LeftRing:HumanoidRegionKind.RightRing),+ ("little",22d,88d,side==AnatomicalSide.Left?HumanoidRegionKind.LeftLittle:HumanoidRegionKind.RightLittle)};+ foreach(var (name,y,length,region) in defs)+ {+ var a=basePoint+new Vector3D(0,y,0); var b=a+direction*length;+ if(name=="thumb") b=b+new Vector3D(sign*12,-12,8);+ list.Add(new($"{side.ToString().ToLowerInvariant()}-{name}",region,p=>Capsule(p,a,b,name=="thumb"?16:12)));+ }+ }+ }++ private static (List<HumanoidVertex> Vertices,List<HumanoidFace> Faces) Polygonize(IReadOnlyList<Primitive> primitives)+ {+ const double minX=-720,minY=-190,minZ=-18,maxX=720,maxY=260,maxZ=1778;+ var nx=(int)double.Ceiling((maxX-minX)/Step)+1;var ny=(int)double.Ceiling((maxY-minY)/Step)+1;var nz=(int)double.Ceiling((maxZ-minZ)/Step)+1;+ var samples=new GridSample[nx*ny*nz];+ long Id(int x,int y,int z)=>((long)z*ny+y)*nx+x;+ int Index(int x,int y,int z)=>(z*ny+y)*nx+x;+ for(var z=0;z<nz;z++)for(var y=0;y<ny;y++)for(var x=0;x<nx;x++)+ {+ var p=new Point3D(minX+x*Step,minY+y*Step,minZ+z*Step);var best=double.PositiveInfinity;var region=HumanoidRegionKind.Abdomen;+ foreach(var primitive in primitives){var d=primitive.SignedDistance(p);if(d<best){best=d;region=primitive.Region;}}+ samples[Index(x,y,z)]=new(p,best,region,Id(x,y,z));+ }+ int[][] corners=[[0,0,0],[1,0,0],[1,1,0],[0,1,0],[0,0,1],[1,0,1],[1,1,1],[0,1,1]];+ int[][] tets=[[0,5,1,6],[0,1,2,6],[0,2,3,6],[0,3,7,6],[0,7,4,6],[0,4,5,6]];+ var verts=new List<HumanoidVertex>();var faces=new List<HumanoidFace>();var cache=new Dictionary<EdgeKey,int>();+ for(var z=0;z<nz-1;z++)for(var y=0;y<ny-1;y++)for(var x=0;x<nx-1;x++)+ {+ var cube=corners.Select(c=>samples[Index(x+c[0],y+c[1],z+c[2])]).ToArray();+ foreach(var tet in tets) EmitTet(tet.Select(i=>cube[i]).ToArray());+ }+ return(verts,faces);++ int Edge(GridSample a,GridSample b)+ {+ var key=EdgeKey.Create(a.Id,b.Id);if(cache.TryGetValue(key,out var found))return found;+ var t=a.Distance/(a.Distance-b.Distance);var p=a.Position+(b.Position-a.Position)*t;+ var region=double.Abs(a.Distance)<=double.Abs(b.Distance)?a.Region:b.Region;+ var index=verts.Count;verts.Add(new($"v:{index:D6}",p,region,-1));cache[key]=index;return index;+ }+ void EmitTet(GridSample[] t)+ {+ var inside=Enumerable.Range(0,4).Where(i=>t[i].Distance<=0).ToArray();var outside=Enumerable.Range(0,4).Where(i=>t[i].Distance>0).ToArray();+ if(inside.Length is 0 or 4)return;+ if(inside.Length==1) Add(Edge(t[inside[0]],t[outside[0]]),Edge(t[inside[0]],t[outside[1]]),Edge(t[inside[0]],t[outside[2]]));+ else if(inside.Length==3) Add(Edge(t[outside[0]],t[inside[0]]),Edge(t[outside[0]],t[inside[2]]),Edge(t[outside[0]],t[inside[1]]));+ else+ {+ var a=Edge(t[inside[0]],t[outside[0]]);var b=Edge(t[inside[0]],t[outside[1]]);var c=Edge(t[inside[1]],t[outside[0]]);var d=Edge(t[inside[1]],t[outside[1]]);+ Add(a,b,c);Add(b,d,c);+ }+ }+ void Add(int a,int b,int c)+ {+ if(a==b||b==c||c==a)return;+ var pa=verts[a].Position;var pb=verts[b].Position;var pc=verts[c].Position;var center=new Point3D((pa.X+pb.X+pc.X)/3,(pa.Y+pb.Y+pc.Y)/3,(pa.Z+pb.Z+pc.Z)/3);+ var eps=0.5;double S(Point3D p)=>primitives.Min(q=>q.SignedDistance(p));+ var grad=new Vector3D(S(center+new Vector3D(eps,0,0))-S(center-new Vector3D(eps,0,0)),S(center+new Vector3D(0,eps,0))-S(center-new Vector3D(0,eps,0)),S(center+new Vector3D(0,0,eps))-S(center-new Vector3D(0,0,eps)));+ if((pb-pa).Cross(pc-pa).Dot(grad)<0)(b,c)=(c,b);+ var regions=new[]{verts[a].Region,verts[b].Region,verts[c].Region};var region=regions.GroupBy(r=>r).OrderByDescending(g=>g.Count()).ThenBy(g=>g.Key).First().Key;+ faces.Add(new($"f:{faces.Count:D6}",a,b,c,region,null));+ }+ }++ private static (List<HumanoidVertex>,List<HumanoidFace>,IReadOnlyList<HumanoidComponent>) AddEyes(List<HumanoidVertex> vertices,List<HumanoidFace> faces)+ {+ var outerFaces=Enumerable.Range(0,faces.Count).ToArray();var left=new List<int>();var right=new List<int>();+ AddEye(new(-35,91,1572),HumanoidRegionKind.LeftEye,left);AddEye(new(35,91,1572),HumanoidRegionKind.RightEye,right);+ return(vertices,faces,[new("component:outer-skin",HumanoidComponentKind.OuterSkin,outerFaces,["mouth seam is surface-only in X0; no oral cavity opening"]),new("component:left-eye",HumanoidComponentKind.LeftEye,left,[]),new("component:right-eye",HumanoidComponentKind.RightEye,right,[])]);+ void AddEye(Point3D center,HumanoidRegionKind region,List<int> target)+ {+ const int rings=8,segments=16;var top=vertices.Count;vertices.Add(new($"v:{vertices.Count:D6}",center+new Vector3D(0,0,12),region,-1));var baseIndex=vertices.Count;+ for(var r=1;r<rings;r++){var phi=Math.PI*r/rings;for(var s=0;s<segments;s++){var theta=2*Math.PI*s/segments;var p=new Point3D(center.X+12*Math.Sin(phi)*Math.Cos(theta),center.Y+12*Math.Sin(phi)*Math.Sin(theta),center.Z+12*Math.Cos(phi));vertices.Add(new($"v:{vertices.Count:D6}",p,region,-1));}}+ var bottom=vertices.Count;vertices.Add(new($"v:{vertices.Count:D6}",center-new Vector3D(0,0,12),region,-1));+ for(var s=0;s<segments;s++){var n=(s+1)%segments;Add(top,baseIndex+s,baseIndex+n);for(var r=0;r<rings-2;r++){var a=baseIndex+r*segments+s;var b=baseIndex+(r+1)*segments+s;var c=baseIndex+(r+1)*segments+n;var d=baseIndex+r*segments+n;Add(a,b,c);Add(a,c,d);}var last=baseIndex+(rings-2)*segments;Add(last+n,last+s,bottom);}+ void Add(int a,int b,int c){target.Add(faces.Count);faces.Add(new($"f:{faces.Count:D6}",a,b,c,region,null));}+ }+ }++ private static IReadOnlyList<HumanoidVertex> AssignVertexSymmetry(IReadOnlyList<HumanoidVertex> input)+ {+ static string Key(Point3D p)=>$"{Math.Round(p.X,6):F6}|{Math.Round(p.Y,6):F6}|{Math.Round(p.Z,6):F6}";+ var groups=input.Select((v,i)=>(Key(v.Position),i)).GroupBy(x=>x.Item1).ToDictionary(g=>g.Key,g=>g.Select(x=>x.i).Order().ToArray());var result=new HumanoidVertex[input.Count];+ for(var i=0;i<input.Count;i++){var v=input[i];var own=groups[Key(v.Position)];var ordinal=Array.IndexOf(own,i);var reflected=groups.GetValueOrDefault(Key(new(-v.Position.X,v.Position.Y,v.Position.Z)));var pair=reflected is null||ordinal>=reflected.Length?i:reflected[ordinal];result[i]=v with{SymmetryPartnerIndex=pair};}+ return result;+ }+ private static IReadOnlyList<HumanoidFace> AssignFaceSymmetry(IReadOnlyList<HumanoidFace> input,IReadOnlyList<HumanoidVertex> vertices)+ {+ static string Key(int a,int b,int c)=>string.Join("|",new[]{a,b,c}.Order());var map=input.Select((f,i)=>(Key(f.A,f.B,f.C),i)).ToDictionary(x=>x.Item1,x=>x.i);var result=new HumanoidFace[input.Count];+ for(var i=0;i<input.Count;i++){var f=input[i];var pair=map.TryGetValue(Key(vertices[f.A].SymmetryPartnerIndex,vertices[f.B].SymmetryPartnerIndex,vertices[f.C].SymmetryPartnerIndex),out var p)?p:(int?)null;result[i]=f with{SymmetryPartnerIndex=pair};}return result;+ }++ private static HumanoidSkeleton BuildSkeleton()+ {+ var specs=new List<(HumanoidJointKind Kind,HumanoidJointKind? Parent,Point3D Global,AnatomicalSide Side)>();+ void Add(HumanoidJointKind k,HumanoidJointKind? p,double x,double y,double z,AnatomicalSide s=AnatomicalSide.Center)=>specs.Add((k,p,new(x,y,z),s));+ Add(HumanoidJointKind.Root,null,0,0,0);Add(HumanoidJointKind.Pelvis,HumanoidJointKind.Root,0,0,930);Add(HumanoidJointKind.SpineLower,HumanoidJointKind.Pelvis,0,0,1050);Add(HumanoidJointKind.SpineMid,HumanoidJointKind.SpineLower,0,0,1190);Add(HumanoidJointKind.Chest,HumanoidJointKind.SpineMid,0,0,1340);Add(HumanoidJointKind.Neck,HumanoidJointKind.Chest,0,0,1465);Add(HumanoidJointKind.Head,HumanoidJointKind.Neck,0,0,1575);+ AddSide(AnatomicalSide.Left,-1);AddSide(AnatomicalSide.Right,1);+ var index=specs.Select((x,i)=>(x.Kind,i)).ToDictionary(x=>x.Kind,x=>x.i);var joints=new List<HumanoidJoint>();+ foreach(var spec in specs){var parent=spec.Parent is null?(int?)null:index[spec.Parent.Value];var parentGlobal=spec.Parent is null?Point3D.Origin:specs[parent!.Value].Global;var local=spec.Global-parentGlobal;var global=Matrix4x4.CreateTranslation((float)spec.Global.X,(float)spec.Global.Y,(float)spec.Global.Z);Matrix4x4.Invert(global,out var inverse);joints.Add(new($"joint:{spec.Kind}",spec.Kind,spec.Side,parent,new(new(local.X,local.Y,local.Z),Quaternion.Identity),global,inverse,spec.Kind is HumanoidJointKind.LeftEye or HumanoidJointKind.RightEye or HumanoidJointKind.Jaw));}+ var symmetry=Enum.GetValues<HumanoidJointKind>().ToDictionary(k=>k,k=>Swap(k));return new(CanonicalAdultStandardV1.SkeletonId,CanonicalAdultStandardV1.RestPoseId,"linear-blend-skinning; System.Numerics row-vector matrices; pWorld=pModel*InverseBind*GlobalPose",joints,symmetry);+ void AddSide(AnatomicalSide side,int sign)+ {+ var left=side==AnatomicalSide.Left;+ HumanoidJointKind K(string stem)=>Enum.Parse<HumanoidJointKind>((left?"Left":"Right")+stem);+ Add(K("Clavicle"),HumanoidJointKind.Chest,sign*85,0,1370,side);Add(K("Shoulder"),K("Clavicle"),sign*185,0,1345,side);Add(K("Elbow"),K("Shoulder"),sign*365,0,1100,side);Add(K("Wrist"),K("Elbow"),sign*525,0,875,side);+ Add(K("Hip"),HumanoidJointKind.Pelvis,sign*88,0,925,side);Add(K("Knee"),K("Hip"),sign*92,8,520,side);Add(K("Ankle"),K("Knee"),sign*88,4,92,side);Add(K("ToeBase"),K("Ankle"),sign*88,125,40,side);+ var fingerOffsets=new[]{("Thumb",-36d,65d),("Index",-20d,80d),("Middle",-7d,86d),("Ring",8d,81d),("Little",22d,69d)};+ foreach(var (name,y,len) in fingerOffsets)+ {+ var first=name=="Thumb"?"Metacarpal":"Proximal";var second=name=="Thumb"?"Proximal":"Intermediate";var third="Distal";+ var baseX=sign*575;Add(K(name+first),K("Wrist"),baseX,y,835,side);Add(K(name+second),K(name+first),baseX+sign*len*.42,y,810,side);Add(K(name+third),K(name+second),baseX+sign*len*.76,y,790,side);+ }+ Add(K("Eye"),HumanoidJointKind.Head,sign*35,91,1572,side);+ }+ static HumanoidJointKind Swap(HumanoidJointKind kind){var text=kind.ToString();if(text.StartsWith("Left"))return Enum.Parse<HumanoidJointKind>("Right"+text[4..]);if(text.StartsWith("Right"))return Enum.Parse<HumanoidJointKind>("Left"+text[5..]);return kind;}+ }++ private static IReadOnlyList<VertexSkinWeights> GenerateWeights(IReadOnlyList<HumanoidVertex> vertices,HumanoidSkeleton skeleton)+ {+ var byKind=skeleton.Joints.Select((j,i)=>(j.Kind,i)).ToDictionary(x=>x.Kind,x=>x.i);var result=new VertexSkinWeights[vertices.Count];+ for(var i=0;i<vertices.Count;i++)+ {+ var kinds=CandidateJoints(vertices[i].Region);var candidates=kinds.Select(k=>(Index:byKind[k],Distance:Distance(vertices[i].Position,skeleton.Joints[byKind[k]].GlobalBind))).OrderBy(x=>x.Distance).ThenBy(x=>x.Index).Take(2).ToArray();+ var raw=candidates.Select(x=>1d/double.Max(1,x.Distance*x.Distance)).ToArray();var sum=raw.Sum();result[i]=new(i,candidates.Select((x,n)=>new JointWeight(x.Index,raw[n]/sum)).ToArray());+ }return result;+ static double Distance(Point3D p,Matrix4x4 m)=>new Vector3D(p.X-m.M41,p.Y-m.M42,p.Z-m.M43).Length;+ static HumanoidJointKind[] CandidateJoints(HumanoidRegionKind r)+ {+ var text=r.ToString();var left=text.StartsWith("Left");var right=text.StartsWith("Right");var prefix=left?"Left":right?"Right":"";+ HumanoidJointKind K(string suffix)=>Enum.Parse<HumanoidJointKind>(prefix+suffix);+ if(text.Contains("Eye"))return[K("Eye"),HumanoidJointKind.Head];if(text.Contains("Ear")||r is HumanoidRegionKind.Head or HumanoidRegionKind.Face)return[HumanoidJointKind.Head,HumanoidJointKind.Neck];+ if(r==HumanoidRegionKind.Neck)return[HumanoidJointKind.Neck,HumanoidJointKind.Head];if(r==HumanoidRegionKind.Chest)return[HumanoidJointKind.Chest,HumanoidJointKind.SpineMid];if(r==HumanoidRegionKind.Abdomen)return[HumanoidJointKind.SpineLower,HumanoidJointKind.SpineMid];if(r==HumanoidRegionKind.Pelvis)return[HumanoidJointKind.Pelvis,HumanoidJointKind.SpineLower];+ if(text.Contains("Shoulder")||text.Contains("UpperArm"))return[K("Shoulder"),K("Elbow")];if(text.Contains("Elbow")||text.Contains("Forearm"))return[K("Elbow"),K("Wrist")];if(text.Contains("Wrist")||text.Contains("Hand"))return[K("Wrist"),K("MiddleProximal")];+ foreach(var finger in new[]{"Thumb","Index","Middle","Ring","Little"})if(text.Contains(finger))return finger=="Thumb"?[K("ThumbMetacarpal"),K("ThumbProximal"),K("ThumbDistal")]:[K(finger+"Proximal"),K(finger+"Intermediate"),K(finger+"Distal")];+ if(text.Contains("Thigh"))return[K("Hip"),K("Knee")];if(text.Contains("Knee")||text.Contains("Shin"))return[K("Knee"),K("Ankle")];if(text.Contains("Ankle")||text.Contains("Foot")||text.Contains("Toes"))return[K("Ankle"),K("ToeBase")];return[HumanoidJointKind.Pelvis];+ }+ }++ private static IReadOnlyList<HumanoidLandmark> BuildLandmarks(HumanoidSurface surface,HumanoidSkeleton skeleton)+ {+ var desired=new List<(string Id,Point3D P,string? Pair,string Protocol)>+ {+ ("surface.head.crown",new(0,0,1750),null,"Highest reviewed outer-skin point excluding hair in measurement pose."),("surface.face.chin",new(0,105,1475),null,"Most inferior reviewed chin surface point."),("surface.face.nose-tip",new(0,145,1570),null,"Most anterior reviewed nasal tip."),+ ("surface.torso.sternum",new(0,128,1320),null,"Anterior midline sternum proxy."),("surface.torso.navel",new(0,110,1070),null,"Reviewed anterior navel proxy."),+ };+ AddPair("face.eye-inner",new(-17,103,1575),new(17,103,1575),"Reviewed medial eyelid corner proxy.");AddPair("face.eye-outer",new(-54,100,1575),new(54,100,1575),"Reviewed lateral eyelid corner proxy.");AddPair("face.mouth-corner",new(-31,122,1520),new(31,122,1520),"Reviewed lip commissure proxy.");AddPair("head.ear",new(-112,0,1570),new(112,0,1570),"Tragus-like surface proxy; not medical landmark.");+ AddPair("shoulder.acromion",new(-210,20,1340),new(210,20,1340),"Acromion-like outer-skin proxy.");AddPair("pelvis.asis",new(-120,112,955),new(120,112,955),"ASIS-like outer-skin proxy.");AddPair("elbow.tip",new(-365,-45,1100),new(365,-45,1100),"Posterior elbow surface proxy.");AddPair("wrist.ulnar",new(-525,-35,875),new(525,-35,875),"Ulnar wrist surface proxy.");AddPair("hand.knuckle-middle",new(-595,0,820),new(595,0,820),"Middle metacarpal knuckle proxy.");AddPair("hand.middle-tip",new(-680,-7,780),new(680,-7,780),"Middle fingertip proxy.");AddPair("knee.patella",new(-92,82,520),new(92,82,520),"Anterior patella-like surface proxy.");AddPair("ankle.lateral",new(-148,4,92),new(148,4,92),"Lateral ankle surface proxy.");AddPair("foot.heel",new(-88,-82,45),new(88,-82,45),"Posterior heel point on outer envelope.");AddPair("foot.toe-tip",new(-88,225,38),new(88,225,38),"Longest-toe envelope tip.");+ var result=new List<HumanoidLandmark>();foreach(var item in desired){var vi=NearestVertex(surface.Vertices,item.P);var fi=surface.Faces.Select((f,i)=>(f,i)).First(x=>x.f.A==vi||x.f.B==vi||x.f.C==vi).i;var f=surface.Faces[fi];var bary=f.A==vi?(1d,0d,0d):f.B==vi?(0d,1d,0d):(0d,0d,1d);result.Add(new SurfaceLandmark(item.Id,new(surface.TopologyId,f.Id,0,bary.Item1,bary.Item2,bary.Item3),item.Protocol,.85,item.Pair,"Aetheris authored template; nearest deterministic surface binding; requires human review",false));}+ foreach(var joint in skeleton.Joints)result.Add(new JointLandmark("joint."+joint.Kind,new(skeleton.SkeletonId,joint.Kind,Vector3D.Zero),"Canonical semantic joint origin in shaped rest/bind pose.",1,JointPair(joint.Kind),"Aetheris canonical skeleton",true));+ return result;+ void AddPair(string stem,Point3D left,Point3D right,string protocol){var l="surface."+stem+".left";var r="surface."+stem+".right";desired.Add((l,left,r,protocol));desired.Add((r,right,l,protocol));}+ static int NearestVertex(IReadOnlyList<HumanoidVertex> vertices,Point3D p)=>vertices.Select((v,i)=>(D:(v.Position-p).LengthSquared,I:i)).OrderBy(x=>x.D).ThenBy(x=>x.I).First().I;+ static string? JointPair(HumanoidJointKind k){var s=k.ToString();return s.StartsWith("Left")?"joint.Right"+s[4..]:s.StartsWith("Right")?"joint.Left"+s[5..]:null;}+ }++ private static IReadOnlyList<MeasurementProtocol> BuildMeasurementProtocols()=>+ [+ new("measure.height.v1",HumanoidMeasurementId.Height,CanonicalAdultStandardV1.MeasurementPoseId,"mm",MeasurementEvaluatorKind.VerticalHeight,["surface.head.crown","sole-plane"],"Crown height above common sole support plane; hair excluded."),+ new("measure.shoulder-width.v1",HumanoidMeasurementId.ShoulderWidth,CanonicalAdultStandardV1.MeasurementPoseId,"mm",MeasurementEvaluatorKind.StraightDistance,["surface.shoulder.acromion.left","surface.shoulder.acromion.right"],"Straight 3D distance between reviewed acromion-like proxies."),+ new("measure.hip-width.v1",HumanoidMeasurementId.HipWidth,CanonicalAdultStandardV1.MeasurementPoseId,"mm",MeasurementEvaluatorKind.StraightDistance,["surface.pelvis.asis.left","surface.pelvis.asis.right"],"X0 proxy distance; not outer-skin breadth or population anthropometry."),+ new("measure.arm-length.v1",HumanoidMeasurementId.ArmLength,CanonicalAdultStandardV1.MeasurementPoseId,"mm",MeasurementEvaluatorKind.JointChainLength,["joint.LeftShoulder","joint.LeftElbow","joint.LeftWrist"],"Left canonical link-chain length; right must agree by symmetry."),+ new("measure.leg-length.v1",HumanoidMeasurementId.LegLength,CanonicalAdultStandardV1.MeasurementPoseId,"mm",MeasurementEvaluatorKind.JointChainLength,["joint.LeftHip","joint.LeftKnee","joint.LeftAnkle"],"Left canonical link-chain length; right must agree by symmetry."),+ new("measure.foot-length.v1",HumanoidMeasurementId.FootLength,CanonicalAdultStandardV1.MeasurementPoseId,"mm",MeasurementEvaluatorKind.ProjectedExtent,["surface.foot.heel.left","surface.foot.toe-tip.left"],"Heel-to-longest-toe distance projected on foot sagittal axis."),+ new("measure.hand-length.v1",HumanoidMeasurementId.HandLength,CanonicalAdultStandardV1.MeasurementPoseId,"mm",MeasurementEvaluatorKind.StraightDistance,["joint.LeftWrist","surface.hand.middle-tip.left"],"Wrist joint proxy to middle fingertip in extended-hand measurement pose."),+ new("measure.chest-depth.v1",HumanoidMeasurementId.ChestDepth,CanonicalAdultStandardV1.MeasurementPoseId,"mm",MeasurementEvaluatorKind.ProjectedExtent,["region:Chest"],"Anterior/posterior extent of declared chest region in measurement pose; only valid when section selection succeeds.")+ ];+ private static IReadOnlyList<HumanoidMorphChannel> BuildMorphChannels()=>+ [+ new(HumanoidMorphId.Height,HumanoidMorphKind.MeasuredDimension,1650,1750,1850,"mm",[HumanoidRegionKind.Pelvis,HumanoidRegionKind.Abdomen,HumanoidRegionKind.Chest,HumanoidRegionKind.Neck,HumanoidRegionKind.Head,HumanoidRegionKind.LeftThigh,HumanoidRegionKind.RightThigh,HumanoidRegionKind.LeftShin,HumanoidRegionKind.RightShin],"piecewise stature distribution across legs and torso; widths unchanged","min/default/max topology and measurement direction"),+ new(HumanoidMorphId.ArmLength,HumanoidMorphKind.MeasuredDimension,-50,0,50,"mm",[HumanoidRegionKind.LeftUpperArm,HumanoidRegionKind.RightUpperArm,HumanoidRegionKind.LeftForearm,HumanoidRegionKind.RightForearm,HumanoidRegionKind.LeftHand,HumanoidRegionKind.RightHand],"bilateral weighted extension along shoulder-elbow-wrist chains","min/default/max topology and arm-length direction"),+ new(HumanoidMorphId.LegLength,HumanoidMorphKind.MeasuredDimension,-60,0,60,"mm",[HumanoidRegionKind.LeftThigh,HumanoidRegionKind.RightThigh,HumanoidRegionKind.LeftShin,HumanoidRegionKind.RightShin,HumanoidRegionKind.LeftFoot,HumanoidRegionKind.RightFoot],"bilateral weighted extension along hip-knee-ankle chains with sole plane fixed","min/default/max topology and leg-length direction"),+ new(HumanoidMorphId.ShoulderWidth,HumanoidMorphKind.MeasuredDimension,-40,0,40,"mm",[HumanoidRegionKind.Chest,HumanoidRegionKind.LeftShoulder,HumanoidRegionKind.RightShoulder],"symmetric transverse shoulder translation with torso blend","min/default/max measurement direction")+ ];++ private static IReadOnlyList<HumanoidAttachmentSite> BuildAttachments(HumanoidSurface surface,IReadOnlyList<HumanoidLandmark> landmarks)+ {+ var definitions=new[]{("Head","surface.head.crown",HumanoidJointKind.Head),("Face","surface.face.nose-tip",HumanoidJointKind.Head),("Chest","surface.torso.sternum",HumanoidJointKind.Chest),("UpperBack","surface.torso.sternum",HumanoidJointKind.Chest),("Waist","surface.torso.navel",HumanoidJointKind.SpineLower),+ ("UpperArm.Left","surface.shoulder.acromion.left",HumanoidJointKind.LeftShoulder),("UpperArm.Right","surface.shoulder.acromion.right",HumanoidJointKind.RightShoulder),("Wrist.Left","surface.wrist.ulnar.left",HumanoidJointKind.LeftWrist),("Wrist.Right","surface.wrist.ulnar.right",HumanoidJointKind.RightWrist),("Hand.Left","surface.hand.knuckle-middle.left",HumanoidJointKind.LeftWrist),("Hand.Right","surface.hand.knuckle-middle.right",HumanoidJointKind.RightWrist),("Thigh.Left","surface.pelvis.asis.left",HumanoidJointKind.LeftHip),("Thigh.Right","surface.pelvis.asis.right",HumanoidJointKind.RightHip),("Shin.Left","surface.knee.patella.left",HumanoidJointKind.LeftKnee),("Shin.Right","surface.knee.patella.right",HumanoidJointKind.RightKnee),("Ankle.Left","surface.ankle.lateral.left",HumanoidJointKind.LeftAnkle),("Ankle.Right","surface.ankle.lateral.right",HumanoidJointKind.RightAnkle),("Foot.Left","surface.foot.toe-tip.left",HumanoidJointKind.LeftToeBase),("Foot.Right","surface.foot.toe-tip.right",HumanoidJointKind.RightToeBase)};+ return definitions.Select(d=>{var l=(SurfaceLandmark)landmarks.Single(x=>x.Id==d.Item2);var p=Resolve(surface,l.Binding);var up=new Vector3D(0,0,1);var normal=d.Item1=="UpperBack"?new Vector3D(0,-1,0):d.Item1 is "Chest" or "Face"?new Vector3D(0,1,0):new Vector3D(p.X<0?-1:p.X>0?1:0,0,p.X==0?1:0);if(!normal.TryNormalize(out normal))normal=new(0,1,0);var tangent=up.Cross(normal);if(!tangent.TryNormalize(out tangent))tangent=new(1,0,0);var binormal=normal.Cross(tangent);return new HumanoidAttachmentSite("site:"+d.Item1,l.Binding,new(p,tangent,normal,binormal),d.Item3,"surface-bound neutral frame follows declared joint; no clearance offset in X0");}).ToArray();+ }+ internal static Point3D Resolve(HumanoidSurface surface,SurfaceBinding binding)+ {+ var f=surface.Faces.Single(x=>x.Id==binding.FaceId);var a=surface.Vertices[f.A].Position;var b=surface.Vertices[f.B].Position;var c=surface.Vertices[f.C].Position;return new(a.X*binding.BarycentricA+b.X*binding.BarycentricB+c.X*binding.BarycentricC,a.Y*binding.BarycentricA+b.Y*binding.BarycentricB+c.Y*binding.BarycentricC,a.Z*binding.BarycentricA+b.Z*binding.BarycentricB+c.Z*binding.BarycentricC);+ }+ private static IReadOnlyDictionary<HumanoidRegionKind,HumanoidRegionKind> RegionSymmetry()=>Enum.GetValues<HumanoidRegionKind>().ToDictionary(r=>r,r=>{var s=r.ToString();return s.StartsWith("Left")?Enum.Parse<HumanoidRegionKind>("Right"+s[4..]):s.StartsWith("Right")?Enum.Parse<HumanoidRegionKind>("Left"+s[5..]):r;});+ private static string ConnectivityHash(IEnumerable<HumanoidFace> faces)=>Hash(string.Join(";",faces.Select(f=>$"{f.A},{f.B},{f.C}")));+ private static string Hash(string text)=>Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(text)));+}diff --git a/Aetheris.Humanoid/HumanoidModel.cs b/Aetheris.Humanoid/HumanoidModel.csnew file mode 100644index 00000000..31134474--- /dev/null+++ b/Aetheris.Humanoid/HumanoidModel.cs@@ -0,0 +1,151 @@+using System.Numerics;+using System.Text.Json.Serialization;+using Aetheris.Kernel.Core.Math;++namespace Aetheris.Humanoid;++public static class CanonicalAdultStandardV1+{+ public const string TopologyId = "aetheris.humanoid.adult.standard.v1";+ public const string BindingTriangulationId = "aetheris.humanoid.adult.standard.v1.binding-triangles.v1";+ public const string SkeletonId = "aetheris.humanoid.adult.skeleton.v1";+ public const string RestPoseId = "aetheris.humanoid.adult.apose.v1";+ public const string MeasurementPoseId = "aetheris.humanoid.adult.measurement.v1";+ public const string MeasurementProtocolVersion = "aetheris.humanoid.measurements.v1";+ public const double NeutralHeightMm = 1750d;+ public const double WeightTolerance = 1e-5;+}++public enum AnatomicalSide { Center, Left, Right }+public enum HumanoidComponentKind { OuterSkin, LeftEye, RightEye, MouthInterior }+public enum HumanoidRegionKind+{+ Head, Face, LeftEar, RightEar, Neck, Chest, Abdomen, Pelvis,+ LeftShoulder, RightShoulder, LeftUpperArm, RightUpperArm, LeftElbow, RightElbow,+ LeftForearm, RightForearm, LeftWrist, RightWrist, LeftHand, RightHand,+ LeftThumb, RightThumb, LeftIndex, RightIndex, LeftMiddle, RightMiddle, LeftRing, RightRing, LeftLittle, RightLittle,+ LeftThigh, RightThigh, LeftKnee, RightKnee, LeftShin, RightShin, LeftAnkle, RightAnkle, LeftFoot, RightFoot, LeftToes, RightToes,+ LeftEye, RightEye, MouthInterior+}+public enum MaterialRegionKind { Skin, Eyes, MouthInterior }+public enum HumanoidJointKind+{+ Root, Pelvis, SpineLower, SpineMid, Chest, Neck, Head,+ LeftClavicle, RightClavicle, LeftShoulder, RightShoulder, LeftElbow, RightElbow, LeftWrist, RightWrist,+ LeftHip, RightHip, LeftKnee, RightKnee, LeftAnkle, RightAnkle, LeftToeBase, RightToeBase,+ LeftThumbMetacarpal, LeftThumbProximal, LeftThumbDistal, RightThumbMetacarpal, RightThumbProximal, RightThumbDistal,+ LeftIndexProximal, LeftIndexIntermediate, LeftIndexDistal, RightIndexProximal, RightIndexIntermediate, RightIndexDistal,+ LeftMiddleProximal, LeftMiddleIntermediate, LeftMiddleDistal, RightMiddleProximal, RightMiddleIntermediate, RightMiddleDistal,+ LeftRingProximal, LeftRingIntermediate, LeftRingDistal, RightRingProximal, RightRingIntermediate, RightRingDistal,+ LeftLittleProximal, LeftLittleIntermediate, LeftLittleDistal, RightLittleProximal, RightLittleIntermediate, RightLittleDistal,+ LeftEye, RightEye, Jaw+}+public enum HumanoidMorphKind { MeasuredDimension, ShapeControl, PoseCorrective, Expression }+public enum HumanoidMorphId { Height, ArmLength, LegLength, ShoulderWidth, HipWidth, TorsoLength }+public enum HumanoidMeasurementId { Height, ShoulderWidth, HipWidth, ArmLength, LegLength, FootLength, HandLength, ChestDepth, WaistCircumference, ChestCircumference }+public enum HumanoidDiagnosticCode+{+ HUM001_MissingRequiredLandmark, HUM002_ReferenceHashMismatch, HUM003_FitExceededSurfaceBudget,+ HUM004_InvertedFace, HUM005_SkinWeightsInvalid, HUM006_UnresolvedJointMapping, HUM007_NonFiniteCoordinate,+ HUM008_InvalidTopology, HUM009_InvalidSymmetry, HUM010_InvalidSkeleton, HUM011_AmbiguousFrame,+ HUM012_ReferenceNotAdmitted, HUM013_MorphOutOfBounds, HUM014_InvalidBinding, HUM015_ConnectivityChanged+}+public enum HumanoidDiagnosticSeverity { Info, Warning, Error }++public sealed record HumanoidDiagnostic(HumanoidDiagnosticCode Code, HumanoidDiagnosticSeverity Severity, string Message, string? EntityId = null);+public sealed record HumanoidMetadata(string Id, string Title, string AdultDomainId, string Description);+public sealed record CanonicalFrame(string Unit, string Handedness, Vector3D AnatomicalRight, Vector3D Forward, Vector3D Up, Point3D Origin, double NormalizedHeightMm);+public sealed record HumanoidVertex(string Id, Point3D Position, HumanoidRegionKind Region, int SymmetryPartnerIndex);+public sealed record HumanoidFace(string Id, int A, int B, int C, HumanoidRegionKind Region, int? SymmetryPartnerIndex);+public sealed record BindingTriangle(string Id, int FaceIndex, int A, int B, int C);+public sealed record HumanoidComponent(string Id, HumanoidComponentKind Kind, IReadOnlyList<int> FaceIndices, IReadOnlyList<string> DeclaredOpenings);+public sealed record HumanoidUv(double U, double V);+public sealed record JointWeight(int JointIndex, double Weight);+public sealed record VertexSkinWeights(int VertexIndex, IReadOnlyList<JointWeight> Weights);+public sealed record HumanoidSurface(+ string TopologyId,+ string BindingTriangulationId,+ string ConnectivityHash,+ IReadOnlyList<HumanoidVertex> Vertices,+ IReadOnlyList<HumanoidFace> Faces,+ IReadOnlyList<BindingTriangle> BindingTriangles,+ IReadOnlyList<HumanoidUv>? Uvs,+ IReadOnlyList<VertexSkinWeights> SkinWeights,+ IReadOnlyList<HumanoidComponent> Components,+ IReadOnlyDictionary<HumanoidRegionKind, HumanoidRegionKind> RegionSymmetry);++/// <summary>Column-vector rigid transform. Local joint transforms map child-local coordinates into the parent frame.</summary>+public readonly record struct HumanoidTransform(Point3D Translation, Quaternion Rotation)+{+ public static HumanoidTransform Identity => new(Point3D.Origin, Quaternion.Identity);+ public Matrix4x4 Matrix => Matrix4x4.CreateFromQuaternion(Rotation) * Matrix4x4.CreateTranslation((float)Translation.X, (float)Translation.Y, (float)Translation.Z);+ public static HumanoidTransform FromTranslation(Point3D point) => new(point, Quaternion.Identity);+}++public sealed record HumanoidJoint(+ string Id,+ HumanoidJointKind Kind,+ AnatomicalSide Side,+ int? ParentIndex,+ HumanoidTransform LocalRest,+ Matrix4x4 GlobalBind,+ Matrix4x4 InverseBind,+ bool IsAuxiliary = false);+public sealed record HumanoidSkeleton(string SkeletonId, string RestPoseId, string SkinningConvention, IReadOnlyList<HumanoidJoint> Joints, IReadOnlyDictionary<HumanoidJointKind, HumanoidJointKind> Symmetry);++public sealed record SurfaceBinding(string TopologyId, string FaceId, int TriangleWithinFace, double BarycentricA, double BarycentricB, double BarycentricC);+public sealed record JointBinding(string SkeletonId, HumanoidJointKind Joint, Vector3D LocalOffset);+[JsonPolymorphic(TypeDiscriminatorPropertyName = "kind")]+[JsonDerivedType(typeof(SurfaceLandmark), "surface")]+[JsonDerivedType(typeof(JointLandmark), "joint")]+[JsonDerivedType(typeof(MeasurementLandmark), "measurement")]+[JsonDerivedType(typeof(AttachmentLandmark), "attachment")]+public abstract record HumanoidLandmark(string Id, string PlacementProtocol, double Confidence, string? SymmetryPartnerId, string Provenance, bool Reviewed);+public sealed record SurfaceLandmark(string Id, SurfaceBinding Binding, string PlacementProtocol, double Confidence, string? SymmetryPartnerId, string Provenance, bool Reviewed)+ : HumanoidLandmark(Id, PlacementProtocol, Confidence, SymmetryPartnerId, Provenance, Reviewed);+public sealed record JointLandmark(string Id, JointBinding Binding, string PlacementProtocol, double Confidence, string? SymmetryPartnerId, string Provenance, bool Reviewed)+ : HumanoidLandmark(Id, PlacementProtocol, Confidence, SymmetryPartnerId, Provenance, Reviewed);+public sealed record MeasurementLandmark(string Id, string OperandId, string ProtocolId, string PlacementProtocol, double Confidence, string? SymmetryPartnerId, string Provenance, bool Reviewed)+ : HumanoidLandmark(Id, PlacementProtocol, Confidence, SymmetryPartnerId, Provenance, Reviewed);+public sealed record AttachmentLandmark(string Id, string SiteId, string PlacementProtocol, double Confidence, string? SymmetryPartnerId, string Provenance, bool Reviewed)+ : HumanoidLandmark(Id, PlacementProtocol, Confidence, SymmetryPartnerId, Provenance, Reviewed);++public enum MeasurementEvaluatorKind { VerticalHeight, StraightDistance, JointChainLength, ProjectedExtent, ClosedSectionCircumference }+public sealed record MeasurementProtocol(string ProtocolId, HumanoidMeasurementId Measurement, string PoseId, string Unit, MeasurementEvaluatorKind Evaluator, IReadOnlyList<string> Operands, string Convention);+public sealed record HumanoidMeasurement(HumanoidMeasurementId Measurement, double? ValueMm, string ProtocolId, string PoseId, bool IsValid, string Validity);+public sealed record HumanoidMorphChannel(HumanoidMorphId Id, HumanoidMorphKind Kind, double Minimum, double Default, double Maximum, string Unit, IReadOnlyList<HumanoidRegionKind> AffectedRegions, string Implementation, string Validation);++public sealed record AttachmentFrame(Point3D Position, Vector3D Tangent, Vector3D Normal, Vector3D Binormal);+public sealed record HumanoidAttachmentSite(string Id, SurfaceBinding PositionBinding, AttachmentFrame NeutralFrame, HumanoidJointKind FollowJoint, string OffsetPolicy);+public sealed record JointPose(HumanoidJointKind Joint, Quaternion LocalRotation);+public sealed record HumanoidPoseState(string PoseId, IReadOnlyList<JointPose> LocalRotations, HumanoidTransform RootTransform);+public sealed record HumanoidProvenanceItem(string Id, string Role, string Source, string Revision, string Sha256, string License, string Use, bool Admitted, string Notes);+public sealed record HumanoidProvenance(string Schema, IReadOnlyList<HumanoidProvenanceItem> Inputs, IReadOnlyList<string> Transformations, string GeneratorVersion, string ConfigHash, string OutputHash, string AdmissionStatus, IReadOnlyList<string> ManualReview);++public sealed record ImportedHumanoid(+ string Id,+ string SourceTopologyId,+ CanonicalFrame SourceFrame,+ string SourcePoseId,+ IReadOnlyList<Point3D> Positions,+ IReadOnlyList<HumanoidFace> Faces,+ IReadOnlyList<HumanoidJoint> SourceRig,+ HumanoidProvenance Provenance,+ IReadOnlyList<HumanoidDiagnostic> Diagnostics);++public sealed record CanonicalHumanoid(+ string SchemaVersion,+ HumanoidMetadata Metadata,+ CanonicalFrame Frame,+ HumanoidSurface Surface,+ HumanoidSkeleton Skeleton,+ IReadOnlyList<HumanoidLandmark> Landmarks,+ IReadOnlyList<MeasurementProtocol> MeasurementProtocols,+ IReadOnlyList<HumanoidMorphChannel> MorphChannels,+ IReadOnlyDictionary<HumanoidRegionKind, MaterialRegionKind> MaterialRegions,+ IReadOnlyList<HumanoidAttachmentSite> Attachments,+ HumanoidPoseState PoseState,+ HumanoidProvenance Provenance,+ long ShapeRevision = 0);++public sealed record HumanoidValidationResult(bool IsValid, IReadOnlyList<HumanoidDiagnostic> Diagnostics);diff --git a/Aetheris.Humanoid/HumanoidModule.cs b/Aetheris.Humanoid/HumanoidModule.csnew file mode 100644index 00000000..036386d7--- /dev/null+++ b/Aetheris.Humanoid/HumanoidModule.cs@@ -0,0 +1,26 @@+using Aetheris.Modules;++namespace Aetheris.Humanoid;++public static class HumanoidModule+{+ public static readonly AetherisModuleId Id = new("Aetheris.Humanoid");+ public static readonly ModuleVersion Version = new(0, 1, 0);+ 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.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."),+ Capability("Humanoid.Registration", "Deterministic provenance-gated reference fitting and structured validation evidence.")+ ],+ ["ImportedHumanoid", "CanonicalHumanoid", "HumanoidSurface", "HumanoidSkeleton", "HumanoidLandmark", "HumanoidMeasurementProtocol", "HumanoidAttachmentSite"],+ ["CanonicalAdultStandardV1"],+ ["authored implicit template -> canonical surface -> screened registration -> shaped skeleton/bind -> pose/display mesh"],+ Enum.GetNames<HumanoidDiagnosticCode>(),+ [new(CoreModule.Id, new(1, 0, 0))],+ new("docs/release/HUMANOID-X0.md"));++ private static ModuleCapability Capability(string id, string description) => new(id, Id, Version, description);+}diff --git a/Aetheris.Humanoid/HumanoidQualification.cs b/Aetheris.Humanoid/HumanoidQualification.csnew file mode 100644index 00000000..7e018de8--- /dev/null+++ b/Aetheris.Humanoid/HumanoidQualification.cs@@ -0,0 +1,52 @@+using System.Numerics;+using Aetheris.Kernel.Core.Math;++namespace Aetheris.Humanoid;++public sealed record CorrespondingRegistrationConfig(string Id,int Iterations,double ProjectionFraction,double MaximumStepMm,double ConvergenceMm);+public sealed record CorrespondingRegistrationResult(CanonicalHumanoid Humanoid,double InitialRmsMm,double FinalRmsMm,int Iterations,bool Converged,IReadOnlyList<HumanoidDiagnostic> Diagnostics);++/// <summary>Deterministic same-topology witness for registration and identity laws.</summary>+public static class HumanoidCorrespondingRegistration+{+ public static CorrespondingRegistrationResult Fit(CanonicalHumanoid source,string targetTopologyId,IReadOnlyList<Point3D> targets,CorrespondingRegistrationConfig config)+ {+ if(targetTopologyId!=source.Surface.TopologyId||targets.Count!=source.Surface.Vertices.Count)+ return new(source,double.NaN,double.NaN,0,false,[new(HumanoidDiagnosticCode.HUM015_ConnectivityChanged,HumanoidDiagnosticSeverity.Error,"Corresponding registration requires the same topology identity and vertex count.")]);+ if(config.Iterations is <1 or >100||config.ProjectionFraction is <=0 or >1||config.MaximumStepMm<=0||config.ConvergenceMm<0||targets.Any(p=>!double.IsFinite(p.X)||!double.IsFinite(p.Y)||!double.IsFinite(p.Z)))+ return new(source,double.NaN,double.NaN,0,false,[new(HumanoidDiagnosticCode.HUM008_InvalidTopology,HumanoidDiagnosticSeverity.Error,"Registration target or bounded configuration is invalid.")]);+ var positions=source.Surface.Vertices.Select(v=>v.Position).ToArray();var initial=Rms(positions,targets);var used=0;+ for(var iteration=1;iteration<=config.Iterations;iteration++)+ {+ used=iteration;+ for(var i=0;i<positions.Length;i++){var delta=targets[i]-positions[i];var length=delta.Length;if(length>config.MaximumStepMm)delta*=config.MaximumStepMm/length;positions[i]+=delta*config.ProjectionFraction;}+ if(Rms(positions,targets)<=config.ConvergenceMm)break;+ }+ var vertices=source.Surface.Vertices.Select((v,i)=>v with{Position=positions[i]}).ToArray();var fitted=source with{Surface=source.Surface with{Vertices=vertices},ShapeRevision=source.ShapeRevision+1};var final=Rms(positions,targets);+ return new(fitted,initial,final,used,final<=config.ConvergenceMm,[]);+ }+ private static double Rms(IReadOnlyList<Point3D> a,IReadOnlyList<Point3D> b)=>double.Sqrt(a.Zip(b,(x,y)=>(x-y).LengthSquared).Average());+}++public sealed record PoseIntegrityEvidence(string PoseId,bool Finite,int InvertedFaces,int CollapsedFaces,double SurfaceAreaRatio,double AbsoluteVolumeRatio,IReadOnlyDictionary<string,Point3D> AttachmentPositions)+{+ public bool IsStable=>Finite&&InvertedFaces==0&&CollapsedFaces==0&&double.IsFinite(SurfaceAreaRatio)&&double.IsFinite(AbsoluteVolumeRatio);+}++public static class HumanoidPoseQualification+{+ public static PoseIntegrityEvidence Evaluate(CanonicalHumanoid humanoid,HumanoidPoseState pose)+ {+ var neutral=humanoid.Surface.Vertices.Select(v=>v.Position).ToArray();var posed=HumanoidPosing.EvaluateVertices(humanoid,pose);var finite=posed.All(Finite);var inverted=0;var collapsed=0;var neutralArea=0d;var posedArea=0d;var globals=HumanoidPosing.GlobalPose(humanoid,pose);var weights=humanoid.Surface.SkinWeights.ToDictionary(x=>x.VertexIndex);+ foreach(var face in humanoid.Surface.Faces)+ {+ var n0=(neutral[face.B]-neutral[face.A]).Cross(neutral[face.C]-neutral[face.A]);var n1=(posed[face.B]-posed[face.A]).Cross(posed[face.C]-posed[face.A]);neutralArea+=n0.Length/2;posedArea+=n1.Length/2;+ var dominant=new[]{face.A,face.B,face.C}.SelectMany(i=>weights[i].Weights).GroupBy(x=>x.JointIndex).Select(g=>(Joint:g.Key,Weight:g.Sum(x=>x.Weight))).OrderByDescending(x=>x.Weight).ThenBy(x=>x.Joint).First().Joint;var deformation=humanoid.Skeleton.Joints[dominant].InverseBind*globals[dominant];var expected=Vector3.TransformNormal(new((float)n0.X,(float)n0.Y,(float)n0.Z),deformation);var expectedNormal=new Vector3D(expected.X,expected.Y,expected.Z);+ if(n1.LengthSquared<4e-8)collapsed++;else if(expectedNormal.Dot(n1)<=0)inverted++;+ }+ var neutralVolume=Volume(neutral,humanoid.Surface.Faces);var posedVolume=Volume(posed,humanoid.Surface.Faces);var attachments=humanoid.Attachments.ToDictionary(x=>x.Id,x=>HumanoidPosing.EvaluateAttachment(humanoid,x.Id,pose).Position,StringComparer.Ordinal);+ return new(pose.PoseId,finite,inverted,collapsed,posedArea/neutralArea,neutralVolume==0?double.NaN:posedVolume/neutralVolume,attachments);+ }+ private static bool Finite(Point3D p)=>double.IsFinite(p.X)&&double.IsFinite(p.Y)&&double.IsFinite(p.Z);+ private static double Volume(IReadOnlyList<Point3D> p,IReadOnlyList<HumanoidFace> faces)=>double.Abs(faces.Sum(f=>{var a=p[f.A]-Point3D.Origin;var b=p[f.B]-Point3D.Origin;var c=p[f.C]-Point3D.Origin;return a.Dot(b.Cross(c))/6;}));+}diff --git a/Aetheris.Humanoid/HumanoidRuntime.cs b/Aetheris.Humanoid/HumanoidRuntime.csnew file mode 100644index 00000000..d47661ce--- /dev/null+++ b/Aetheris.Humanoid/HumanoidRuntime.cs@@ -0,0 +1,140 @@+using System.Numerics;+using System.Security.Cryptography;+using System.Text;+using System.Text.Json;+using System.Text.Json.Serialization;+using Aetheris.Kernel.Core.Math;++namespace Aetheris.Humanoid;++public static class HumanoidValidator+{+ public static HumanoidValidationResult Validate(CanonicalHumanoid humanoid)+ {+ var d=new List<HumanoidDiagnostic>();var s=humanoid.Surface;+ if(s.TopologyId!=CanonicalAdultStandardV1.TopologyId||s.BindingTriangulationId!=CanonicalAdultStandardV1.BindingTriangulationId)d.Add(Error(HumanoidDiagnosticCode.HUM008_InvalidTopology,"Canonical topology or binding-triangulation identity is not X0 v1."));+ if(s.Vertices.Count is <8000 or >20000)d.Add(new(HumanoidDiagnosticCode.HUM008_InvalidTopology,HumanoidDiagnosticSeverity.Warning,$"X0 standard planning band is 8k-20k vertices; generated {s.Vertices.Count}."));+ for(var i=0;i<s.Vertices.Count;i++)+ {+ var v=s.Vertices[i];if(!Finite(v.Position))d.Add(Error(HumanoidDiagnosticCode.HUM007_NonFiniteCoordinate,"Vertex is non-finite.",v.Id));+ if(v.SymmetryPartnerIndex<0||v.SymmetryPartnerIndex>=s.Vertices.Count||s.Vertices[v.SymmetryPartnerIndex].SymmetryPartnerIndex!=i)d.Add(Error(HumanoidDiagnosticCode.HUM009_InvalidSymmetry,"Vertex symmetry is not an in-range involution.",v.Id));+ }+ for(var i=0;i<s.Faces.Count;i++)+ {+ var f=s.Faces[i];if(new[]{f.A,f.B,f.C}.Any(x=>x<0||x>=s.Vertices.Count)||f.A==f.B||f.B==f.C||f.C==f.A){d.Add(Error(HumanoidDiagnosticCode.HUM008_InvalidTopology,"Face indices are invalid or repeated.",f.Id));continue;}+ var a=s.Vertices[f.A].Position;var b=s.Vertices[f.B].Position;var c=s.Vertices[f.C].Position;if((b-a).Cross(c-a).LengthSquared<4e-8)d.Add(Error(HumanoidDiagnosticCode.HUM008_InvalidTopology,"Face area is below the X0 0.0001 mm2 collapse threshold.",f.Id));+ if(f.SymmetryPartnerIndex is int pair&&(pair<0||pair>=s.Faces.Count||s.Faces[pair].SymmetryPartnerIndex!=i))d.Add(Error(HumanoidDiagnosticCode.HUM009_InvalidSymmetry,"Declared face symmetry is not an in-range involution.",f.Id));+ }+ if(ConnectivityHash(s.Faces)!=s.ConnectivityHash)d.Add(Error(HumanoidDiagnosticCode.HUM015_ConnectivityChanged,"Connectivity hash does not match canonical face indices."));+ if(s.BindingTriangles.Count!=s.Faces.Count||s.BindingTriangles.Where((x,i)=>x.FaceIndex!=i||x.A!=s.Faces[i].A||x.B!=s.Faces[i].B||x.C!=s.Faces[i].C).Any())d.Add(Error(HumanoidDiagnosticCode.HUM014_InvalidBinding,"Binding triangulation does not match stable canonical faces."));+ if(s.SkinWeights.Count!=s.Vertices.Count)d.Add(Error(HumanoidDiagnosticCode.HUM005_SkinWeightsInvalid,"Every canonical vertex requires one deformation-weight record."));+ foreach(var w in s.SkinWeights)+ {+ var sum=w.Weights.Sum(x=>x.Weight);if(w.VertexIndex<0||w.VertexIndex>=s.Vertices.Count||w.Weights.Count==0||w.Weights.Any(x=>x.JointIndex<0||x.JointIndex>=humanoid.Skeleton.Joints.Count||!double.IsFinite(x.Weight)||x.Weight<0||x.Weight>1)||double.Abs(sum-1)>CanonicalAdultStandardV1.WeightTolerance)d.Add(Error(HumanoidDiagnosticCode.HUM005_SkinWeightsInvalid,$"Skin weights are invalid or sum to {sum:R}.",$"vertex:{w.VertexIndex}"));+ }+ ValidateSkeleton(humanoid.Skeleton,d);+ foreach(var landmark in humanoid.Landmarks.OfType<SurfaceLandmark>())+ {+ if(landmark.Binding.TopologyId!=s.TopologyId||!s.Faces.Any(x=>x.Id==landmark.Binding.FaceId)||landmark.Binding.TriangleWithinFace!=0||double.Abs(landmark.Binding.BarycentricA+landmark.Binding.BarycentricB+landmark.Binding.BarycentricC-1)>1e-9||new[]{landmark.Binding.BarycentricA,landmark.Binding.BarycentricB,landmark.Binding.BarycentricC}.Any(x=>x<0||x>1))d.Add(Error(HumanoidDiagnosticCode.HUM014_InvalidBinding,"Surface landmark binding is invalid.",landmark.Id));+ }+ foreach(var id in RequiredLandmarkIds.Where(id=>humanoid.Landmarks.All(x=>x.Id!=id)))d.Add(Error(HumanoidDiagnosticCode.HUM001_MissingRequiredLandmark,"Required X0 landmark is absent.",id));+ var bind=HumanoidPosing.EvaluateVertices(humanoid,new(CanonicalAdultStandardV1.RestPoseId,[],HumanoidTransform.Identity));for(var i=0;i<bind.Count;i++)if((bind[i]-s.Vertices[i].Position).Length>1e-3)d.Add(Error(HumanoidDiagnosticCode.HUM010_InvalidSkeleton,"Bind-pose reconstruction exceeded 0.001 mm.",s.Vertices[i].Id));+ return new(!d.Any(x=>x.Severity==HumanoidDiagnosticSeverity.Error),d);+ }+ private static void ValidateSkeleton(HumanoidSkeleton skeleton,List<HumanoidDiagnostic> d)+ {+ if(skeleton.SkeletonId!=CanonicalAdultStandardV1.SkeletonId)d.Add(Error(HumanoidDiagnosticCode.HUM010_InvalidSkeleton,"Unexpected canonical skeleton identity."));+ for(var i=0;i<skeleton.Joints.Count;i++){var j=skeleton.Joints[i];if(j.ParentIndex is int p&&(p<0||p>=i))d.Add(Error(HumanoidDiagnosticCode.HUM010_InvalidSkeleton,"Parent must precede child in acyclic canonical order.",j.Id));var identity=j.GlobalBind*j.InverseBind;if(!NearIdentity(identity,1e-4f))d.Add(Error(HumanoidDiagnosticCode.HUM010_InvalidSkeleton,"Global bind and inverse bind do not reconstruct identity.",j.Id));}+ foreach(var kind in Enum.GetValues<HumanoidJointKind>().Where(k=>k is not HumanoidJointKind.LeftEye and not HumanoidJointKind.RightEye and not HumanoidJointKind.Jaw))if(skeleton.Joints.All(x=>x.Kind!=kind))d.Add(Error(HumanoidDiagnosticCode.HUM010_InvalidSkeleton,"Required canonical joint is missing.",kind.ToString()));+ }+ private static bool NearIdentity(Matrix4x4 m,float e)=>MathF.Abs(m.M11-1)<e&&MathF.Abs(m.M22-1)<e&&MathF.Abs(m.M33-1)<e&&MathF.Abs(m.M44-1)<e&&MathF.Abs(m.M12)<e&&MathF.Abs(m.M13)<e&&MathF.Abs(m.M14)<e&&MathF.Abs(m.M21)<e&&MathF.Abs(m.M23)<e&&MathF.Abs(m.M24)<e&&MathF.Abs(m.M31)<e&&MathF.Abs(m.M32)<e&&MathF.Abs(m.M34)<e&&MathF.Abs(m.M41)<e&&MathF.Abs(m.M42)<e&&MathF.Abs(m.M43)<e;+ private static bool Finite(Point3D p)=>double.IsFinite(p.X)&&double.IsFinite(p.Y)&&double.IsFinite(p.Z);+ private static HumanoidDiagnostic Error(HumanoidDiagnosticCode c,string m,string? e=null)=>new(c,HumanoidDiagnosticSeverity.Error,m,e);+ private static string ConnectivityHash(IEnumerable<HumanoidFace> faces)=>Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(string.Join(";",faces.Select(f=>$"{f.A},{f.B},{f.C}")))));+ public static readonly string[] RequiredLandmarkIds=["surface.head.crown","surface.face.chin","surface.face.nose-tip","surface.torso.sternum","surface.torso.navel","surface.shoulder.acromion.left","surface.shoulder.acromion.right","surface.pelvis.asis.left","surface.pelvis.asis.right","surface.elbow.tip.left","surface.elbow.tip.right","surface.wrist.ulnar.left","surface.wrist.ulnar.right","surface.hand.middle-tip.left","surface.hand.middle-tip.right","surface.knee.patella.left","surface.knee.patella.right","surface.ankle.lateral.left","surface.ankle.lateral.right","surface.foot.heel.left","surface.foot.heel.right","surface.foot.toe-tip.left","surface.foot.toe-tip.right"];+}++public static class HumanoidMeasurements+{+ public static IReadOnlyList<HumanoidMeasurement> Evaluate(CanonicalHumanoid humanoid)+ => humanoid.MeasurementProtocols.Select(p=>Evaluate(humanoid,p)).ToArray();+ public static HumanoidMeasurement Evaluate(CanonicalHumanoid h,MeasurementProtocol protocol)+ {+ try+ {+ var value=protocol.Measurement switch+ {+ HumanoidMeasurementId.Height=>Surface(h,"surface.head.crown").Z,+ HumanoidMeasurementId.ShoulderWidth=>Distance(Surface(h,"surface.shoulder.acromion.left"),Surface(h,"surface.shoulder.acromion.right")),+ HumanoidMeasurementId.HipWidth=>Distance(Surface(h,"surface.pelvis.asis.left"),Surface(h,"surface.pelvis.asis.right")),+ HumanoidMeasurementId.ArmLength=>Chain(h,HumanoidJointKind.LeftShoulder,HumanoidJointKind.LeftElbow,HumanoidJointKind.LeftWrist),+ HumanoidMeasurementId.LegLength=>Chain(h,HumanoidJointKind.LeftHip,HumanoidJointKind.LeftKnee,HumanoidJointKind.LeftAnkle),+ HumanoidMeasurementId.FootLength=>Distance(Surface(h,"surface.foot.heel.left"),Surface(h,"surface.foot.toe-tip.left")),+ HumanoidMeasurementId.HandLength=>Distance(Joint(h,HumanoidJointKind.LeftWrist),Surface(h,"surface.hand.middle-tip.left")),+ HumanoidMeasurementId.ChestDepth=>Depth(h,HumanoidRegionKind.Chest),+ _=>throw new NotSupportedException("Protocol evaluator is not implemented in X0.")+ };+ return new(protocol.Measurement,value,protocol.ProtocolId,protocol.PoseId,true,"Valid for canonical adult X0 measurement pose; engineering proxy only.");+ }+ catch(Exception ex){return new(protocol.Measurement,null,protocol.ProtocolId,protocol.PoseId,false,ex.Message);}+ }+ private static Point3D Surface(CanonicalHumanoid h,string id)=>CanonicalAdultTemplate.Resolve(h.Surface,((SurfaceLandmark)h.Landmarks.Single(x=>x.Id==id)).Binding);+ private static Point3D Joint(CanonicalHumanoid h,HumanoidJointKind kind){var m=h.Skeleton.Joints.Single(x=>x.Kind==kind).GlobalBind;return new(m.M41,m.M42,m.M43);}+ private static double Chain(CanonicalHumanoid h,params HumanoidJointKind[] kinds)=>kinds.Zip(kinds.Skip(1),(a,b)=>Distance(Joint(h,a),Joint(h,b))).Sum();+ private static double Distance(Point3D a,Point3D b)=>(a-b).Length;+ private static double Depth(CanonicalHumanoid h,HumanoidRegionKind r){var p=h.Surface.Vertices.Where(x=>x.Region==r).Select(x=>x.Position.Y).ToArray();if(p.Length==0)throw new InvalidOperationException("Region is empty.");return p.Max()-p.Min();}+}++public static class HumanoidPosing+{+ public static IReadOnlyList<Matrix4x4> GlobalPose(CanonicalHumanoid h,HumanoidPoseState pose)+ {+ var rotations=pose.LocalRotations.ToDictionary(x=>x.Joint,x=>x.LocalRotation);var result=new Matrix4x4[h.Skeleton.Joints.Count];+ for(var i=0;i<result.Length;i++){var j=h.Skeleton.Joints[i];var q=rotations.GetValueOrDefault(j.Kind,Quaternion.Identity);var local=Matrix4x4.CreateFromQuaternion(q)*j.LocalRest.Matrix;result[i]=j.ParentIndex is int parent?local*result[parent]:local*pose.RootTransform.Matrix;}return result;+ }+ public static IReadOnlyList<Point3D> EvaluateVertices(CanonicalHumanoid h,HumanoidPoseState pose)+ {+ var globals=GlobalPose(h,pose);var output=new Point3D[h.Surface.Vertices.Count];+ foreach(var skin in h.Surface.SkinWeights){var source=h.Surface.Vertices[skin.VertexIndex].Position;var p=new Vector3((float)source.X,(float)source.Y,(float)source.Z);var sum=Vector3.Zero;foreach(var w in skin.Weights){var transformed=Vector3.Transform(p,h.Skeleton.Joints[w.JointIndex].InverseBind*globals[w.JointIndex]);sum+=transformed*(float)w.Weight;}output[skin.VertexIndex]=new(sum.X,sum.Y,sum.Z);}return output;+ }+ public static AttachmentFrame EvaluateAttachment(CanonicalHumanoid h,string siteId,HumanoidPoseState pose)+ {+ var site=h.Attachments.Single(x=>x.Id==siteId);var positions=EvaluateVertices(h,pose);var face=h.Surface.Faces.Single(x=>x.Id==site.PositionBinding.FaceId);var b=site.PositionBinding;var p=new Point3D(positions[face.A].X*b.BarycentricA+positions[face.B].X*b.BarycentricB+positions[face.C].X*b.BarycentricC,positions[face.A].Y*b.BarycentricA+positions[face.B].Y*b.BarycentricB+positions[face.C].Y*b.BarycentricC,positions[face.A].Z*b.BarycentricA+positions[face.B].Z*b.BarycentricB+positions[face.C].Z*b.BarycentricC);var globals=GlobalPose(h,pose);var jointIndex=h.Skeleton.Joints.ToList().FindIndex(x=>x.Kind==site.FollowJoint);var bind=h.Skeleton.Joints[jointIndex].InverseBind*globals[jointIndex];return site.NeutralFrame with{Position=p,Tangent=Transform(site.NeutralFrame.Tangent,bind),Normal=Transform(site.NeutralFrame.Normal,bind),Binormal=Transform(site.NeutralFrame.Binormal,bind)};+ static Vector3D Transform(Vector3D v,Matrix4x4 m){var x=Vector3.TransformNormal(new((float)v.X,(float)v.Y,(float)v.Z),m);var result=new Vector3D(x.X,x.Y,x.Z);return result.TryNormalize(out var n)?n:result;}+ }+}++public static class HumanoidMorphing+{+ public static CanonicalHumanoid Apply(CanonicalHumanoid h,IReadOnlyDictionary<HumanoidMorphId,double> values)+ {+ foreach(var (id,value) in values){var channel=h.MorphChannels.SingleOrDefault(x=>x.Id==id)??throw new ArgumentException($"Unsupported morph {id}.");if(value<channel.Minimum||value>channel.Maximum||!double.IsFinite(value))throw new HumanoidDomainException(new(HumanoidDiagnosticCode.HUM013_MorphOutOfBounds,HumanoidDiagnosticSeverity.Error,$"{id} value {value:R} is outside [{channel.Minimum:R},{channel.Maximum:R}].",id.ToString()));}+ Point3D Map(Point3D p,HumanoidRegionKind? region)+ {+ var q=p;+ if(values.TryGetValue(HumanoidMorphId.Height,out var height)){var concurrentLeg=values.GetValueOrDefault(HumanoidMorphId.LegLength,0);var d=height-1750-concurrentLeg;var factor=p.Z<=520?.45*p.Z/520:p.Z<=930?.45+.25*(p.Z-520)/410:.70+.30*double.Clamp((p.Z-930)/820,0,1);q+=new Vector3D(0,0,d*factor);}+ if(values.TryGetValue(HumanoidMorphId.LegLength,out var leg)&&leg!=0){var f=double.Clamp(p.Z/925,0,1);if(p.Z<925)q+=new Vector3D(0,0,leg*f);else q+=new Vector3D(0,0,leg);}+ if(values.TryGetValue(HumanoidMorphId.ShoulderWidth,out var shoulder)&&shoulder!=0){var zBlend=double.Clamp(1-double.Abs(p.Z-1340)/300,0,1);q+=new Vector3D(Math.Sign(p.X)*shoulder*zBlend,0,0);}+ if(values.TryGetValue(HumanoidMorphId.ArmLength,out var arm)&&arm!=0&®ion is not null&®ion.ToString()!.ContainsAny("Shoulder","UpperArm","Elbow","Forearm","Wrist","Hand","Thumb","Index","Middle","Ring","Little")){var side=Math.Sign(p.X);var shoulderPoint=new Point3D(side*185,0,1345);var v=q-shoulderPoint;var baseLength=500d;q=shoulderPoint+v*((baseLength+arm)/baseLength);}+ return q;+ }+ var vertices=h.Surface.Vertices.Select(v=>v with{Position=Map(v.Position,v.Region)}).ToArray();var oldJoints=h.Skeleton.Joints;var globals=oldJoints.Select(j=>Map(new(j.GlobalBind.M41,j.GlobalBind.M42,j.GlobalBind.M43),RegionForJoint(j.Kind))).ToArray();var joints=new HumanoidJoint[oldJoints.Count];for(var i=0;i<joints.Length;i++){var old=oldJoints[i];var parent=old.ParentIndex is int pi?globals[pi]:Point3D.Origin;var local=globals[i]-parent;var global=Matrix4x4.CreateTranslation((float)globals[i].X,(float)globals[i].Y,(float)globals[i].Z);Matrix4x4.Invert(global,out var inv);joints[i]=old with{LocalRest=new(new(local.X,local.Y,local.Z),Quaternion.Identity),GlobalBind=global,InverseBind=inv};}+ var skeleton=h.Skeleton with{Joints=joints};var surface=h.Surface with{Vertices=vertices};var frame=values.TryGetValue(HumanoidMorphId.Height,out var requestedHeight)?h.Frame with{NormalizedHeightMm=requestedHeight}:h.Frame;var updated=h with{Frame=frame,Surface=surface,Skeleton=skeleton,ShapeRevision=h.ShapeRevision+1,PoseState=new(CanonicalAdultStandardV1.RestPoseId,[],HumanoidTransform.Identity)};return updated with{Attachments=updated.Attachments.Select(site=>site with{NeutralFrame=site.NeutralFrame with{Position=CanonicalAdultTemplate.Resolve(surface,site.PositionBinding)}}).ToArray()};+ }+ private static HumanoidRegionKind? RegionForJoint(HumanoidJointKind k){var s=k.ToString();if(s.Contains("Shoulder"))return s.StartsWith("Left")?HumanoidRegionKind.LeftShoulder:HumanoidRegionKind.RightShoulder;if(s.Contains("Elbow"))return s.StartsWith("Left")?HumanoidRegionKind.LeftElbow:HumanoidRegionKind.RightElbow;if(s.Contains("Wrist")||s.Contains("Thumb")||s.Contains("Index")||s.Contains("Middle")||s.Contains("Ring")||s.Contains("Little"))return s.StartsWith("Left")?HumanoidRegionKind.LeftHand:HumanoidRegionKind.RightHand;if(s.Contains("Hip"))return s.StartsWith("Left")?HumanoidRegionKind.LeftThigh:HumanoidRegionKind.RightThigh;if(s.Contains("Knee"))return s.StartsWith("Left")?HumanoidRegionKind.LeftKnee:HumanoidRegionKind.RightKnee;if(s.Contains("Ankle")||s.Contains("Toe"))return s.StartsWith("Left")?HumanoidRegionKind.LeftFoot:HumanoidRegionKind.RightFoot;return null;}+ private static bool ContainsAny(this string value,params string[] tokens)=>tokens.Any(value.Contains);+}++public sealed class HumanoidDomainException(HumanoidDiagnostic diagnostic):InvalidOperationException(diagnostic.Message){public HumanoidDiagnostic Diagnostic{get;}=diagnostic;}++public static class HumanoidArtifactIO+{+ public static JsonSerializerOptions JsonOptions { get; }=CreateOptions();+ private static JsonSerializerOptions CreateOptions(){var o=new JsonSerializerOptions{WriteIndented=true,PropertyNamingPolicy=JsonNamingPolicy.CamelCase,IncludeFields=true};o.Converters.Add(new JsonStringEnumConverter());return o;}+ public static void Save(CanonicalHumanoid humanoid,string path){Directory.CreateDirectory(Path.GetDirectoryName(Path.GetFullPath(path))!);File.WriteAllText(path,JsonSerializer.Serialize(humanoid,JsonOptions));}+ public static CanonicalHumanoid Load(string path)=>JsonSerializer.Deserialize<CanonicalHumanoid>(File.ReadAllText(path),JsonOptions)??throw new InvalidDataException("Canonical humanoid artifact was empty.");+ public static void SaveObj(CanonicalHumanoid humanoid,string path,IReadOnlyList<Point3D>? positions=null)+ {+ positions??=humanoid.Surface.Vertices.Select(x=>x.Position).ToArray();Directory.CreateDirectory(Path.GetDirectoryName(Path.GetFullPath(path))!);using var w=new StreamWriter(path,false,new UTF8Encoding(false));w.WriteLine("# Aetheris canonical humanoid display mesh; millimeters; +X anatomical right +Y forward +Z up");foreach(var p in positions)w.WriteLine(FormattableString.Invariant($"v {p.X:R} {p.Y:R} {p.Z:R}"));foreach(var group in humanoid.Surface.Faces.Select((f,i)=>(f,i)).GroupBy(x=>x.f.Region)){w.WriteLine("g "+group.Key);foreach(var (f,_) in group)w.WriteLine($"f {f.A+1} {f.B+1} {f.C+1}");}+ }+}diff --git a/Aetheris.Modules.BuiltIn/Aetheris.Modules.BuiltIn.csproj b/Aetheris.Modules.BuiltIn/Aetheris.Modules.BuiltIn.csprojindex 91577e2f..0184bd15 100644--- a/Aetheris.Modules.BuiltIn/Aetheris.Modules.BuiltIn.csproj+++ b/Aetheris.Modules.BuiltIn/Aetheris.Modules.BuiltIn.csproj@@ -1,6 +1,7 @@<Project Sdk="Microsoft.NET.Sdk">- <PropertyGroup><TargetFramework>net10.0</TargetFramework><ImplicitUsings>enable</ImplicitUsings><Nullable>enable</Nullable><Description>Built-in Surfacing, Piping, and Sheet Metal module registration for Aetheris.</Description></PropertyGroup>+ <PropertyGroup><TargetFramework>net10.0</TargetFramework><ImplicitUsings>enable</ImplicitUsings><Nullable>enable</Nullable><Description>Built-in engineering and humanoid domain module registration for Aetheris.</Description></PropertyGroup><ItemGroup>+ <ProjectReference Include="..\Aetheris.Humanoid\Aetheris.Humanoid.csproj" /><ProjectReference Include="..\Aetheris.Modules\Aetheris.Modules.csproj" /><ProjectReference Include="..\Aetheris.Surfacing\Aetheris.Surfacing.csproj" /><ProjectReference Include="..\Aetheris.Piping\Aetheris.Piping.csproj" />diff --git a/Aetheris.Modules.BuiltIn/BuiltInModules.cs b/Aetheris.Modules.BuiltIn/BuiltInModules.csindex 9b2ee61b..4ad10865 100644--- a/Aetheris.Modules.BuiltIn/BuiltInModules.cs+++ b/Aetheris.Modules.BuiltIn/BuiltInModules.cs@@ -2,6 +2,7 @@ using Aetheris.Piping;using Aetheris.PlasticShell;using Aetheris.SheetMetal;using Aetheris.Surfacing;+using Aetheris.Humanoid;namespace Aetheris.Modules.BuiltIn;@@ -9,6 +10,6 @@ namespace Aetheris.Modules.BuiltIn;public static class BuiltInModules{private static readonly Lazy<AetherisModuleCatalog> CatalogValue = new(() => AetherisModuleCatalog.Create(- [CoreModule.Definition, SurfacingModule.Definition, PipingModule.Definition, SheetMetalModule.Definition, PlasticShellModule.Definition]));+ [CoreModule.Definition, SurfacingModule.Definition, PipingModule.Definition, SheetMetalModule.Definition, PlasticShellModule.Definition, HumanoidModule.Definition]));public static AetherisModuleCatalog Catalog => CatalogValue.Value;}diff --git a/Aetheris.Modules.Tests/ModuleArchitectureTests.cs b/Aetheris.Modules.Tests/ModuleArchitectureTests.csindex b4e86e06..3954cc88 100644--- a/Aetheris.Modules.Tests/ModuleArchitectureTests.cs+++ b/Aetheris.Modules.Tests/ModuleArchitectureTests.cs@@ -17,7 +17,7 @@ public sealed class ModuleArchitectureTests[Fact] public void BuiltInsHaveStableIdentityVersionAndDeterministicOrder(){var first=BuiltInModules.Catalog;var second=AetherisModuleCatalog.Create(first.Modules.Reverse());- Assert.Equal(["Aetheris.Core","Aetheris.Piping","Aetheris.Surfacing","Aetheris.PlasticShell","Aetheris.SheetMetal"],first.Modules.Select(m=>m.Id.Value));+ Assert.Equal(["Aetheris.Core","Aetheris.Humanoid","Aetheris.Piping","Aetheris.Surfacing","Aetheris.PlasticShell","Aetheris.SheetMetal"],first.Modules.Select(m=>m.Id.Value));Assert.Equal(first.Modules.Select(m=>m.Id.Value),second.Modules.Select(m=>m.Id.Value));Assert.Equal("0.3.0",first.Modules.Single(m=>m.Id==SurfacingModule.Id).Version.ToString());Assert.Equal(first.Capabilities.Select(c=>c.Id).Order(StringComparer.Ordinal),first.Capabilities.Select(c=>c.Id));diff --git a/Aetheris.slnx b/Aetheris.slnxindex ad4f3272..64eb4a62 100644--- a/Aetheris.slnx+++ b/Aetheris.slnx@@ -17,6 +17,8 @@<Project Path="Aetheris.SheetMetal.Tests/Aetheris.SheetMetal.Tests.csproj" /><Project Path="Aetheris.PlasticShell/Aetheris.PlasticShell.csproj" /><Project Path="Aetheris.PlasticShell.Tests/Aetheris.PlasticShell.Tests.csproj" />+ <Project Path="Aetheris.Humanoid/Aetheris.Humanoid.csproj" />+ <Project Path="Aetheris.Humanoid.Tests/Aetheris.Humanoid.Tests.csproj" /><Project Path="Aetheris.Sculpture/Aetheris.Sculpture.csproj" /><Project Path="Aetheris.Sculpture.Tests/Aetheris.Sculpture.Tests.csproj" /><Project Path="Aetheris.Modules.BuiltIn/Aetheris.Modules.BuiltIn.csproj" />@@ -44,6 +46,7 @@<Project Path="tools/Aetheris.BunnyM1/Aetheris.BunnyM1.csproj" /><Project Path="tools/Aetheris.BunnyM2/Aetheris.BunnyM2.csproj" /><Project Path="tools/Aetheris.BunnyM3/Aetheris.BunnyM3.csproj" />+ <Project Path="tools/Aetheris.Humanoid.X0/Aetheris.Humanoid.X0.csproj" /><Project Path="tools/Aetheris.Continuum.AttentionE0/Aetheris.Continuum.AttentionE0.csproj" /><Project Path="tools/Aetheris.Continuum.AttentionE1/Aetheris.Continuum.AttentionE1.csproj" /><Project Path="Aetheris.Forge/Aetheris.Forge.csproj" />diff --git a/docs/release/HUMANOID-X0.md b/docs/release/HUMANOID-X0.mdnew file mode 100644index 00000000..6deb0e43--- /dev/null+++ b/docs/release/HUMANOID-X0.md@@ -0,0 +1,199 @@+# HUMANOID-X0 — Canonical adult humanoid foundation++Date: 2026-09-16+Verdict: **Meaningful progression**++> Did Aetheris successfully create and validate an independently authored canonical adult humanoid topology that can be deterministically fitted to a screened licensed reference and used as a stable semantic humanoid substrate?++**Partly.** Aetheris now owns and validates a real canonical adult domain: independently generated topology, stable identity, semantic regions, skeleton, skin weights, typed landmarks, measurement protocols, morphs, attachment frames, display export, diagnostics, and provenance. Deterministic Antonia registration runs and preserves connectivity, but it does not meet X0 fit budgets. The pose sweep also reports orientation-reversal proxies at the major joints. In addition, the recon review does not clear the converted `char.blend` component as canonical output. The authored neutral template therefore remains canonical; fitted positions are local research evidence only.++The next blocker is narrow and measured: replace the current coarse same-region nearest-surface correspondence with reviewed source landmarks and a deformation graph or cage that can reduce the 74.58 mm bidirectional RMS without violating the 3.0 edge-stretch bound, then requalify shoulder/hand, crotch, knee, and foot regions. Pose weights at shoulders, elbows, hips, and knees also need refinement before the deformation witness can pass.++## Canonical authority++`Aetheris.Humanoid` is a domain module beside the existing engineering domains. `ImportedHumanoid` retains external topology, source pose, and provenance. `CanonicalHumanoid` requires the stricter Aetheris identity and validation laws. No Firmament syntax is frozen.++The canonical frame is millimetres, right-handed, +X anatomical right, +Y forward, +Z up. The origin is the mid-sagittal pelvis projection on the common sole plane. The authored neutral is normalized to exactly 1750 mm; this is an engineering normalization, not a population mean.++The canonical artifact is generated by repository code from explicit anatomical SDF primitives on a fixed 24 mm lattice, split into six deterministic tetrahedra per cell and polygonized at the zero isovalue. Faces below 0.0001 mm2 are deterministically rejected. Antonia coordinates and connectivity do not participate in generation.++| Property | X0 result |+|---|---:|+| Topology ID | `aetheris.humanoid.adult.standard.v1` |+| Binding triangulation | `aetheris.humanoid.adult.standard.v1.binding-triangles.v1` |+| Vertices | 16,868 |+| Triangles | 33,716 |+| Semantic regions represented | 31 |+| Outer-skin triangles | 33,268 |+| Eye triangles | 224 left + 224 right |+| Connectivity SHA-256 | `1d4828e1966c6be96409b1bc9f285ae8a5b1f6ded2ba0c523da61d71bc51e2eb` |++The surface has stable vertex and face IDs, binding triangles, explicit region symmetry, vertex symmetry involution, component declarations, and semantic material regions. The outer skin, left eye, and right eye are separate components. The mouth seam is surface-only; a mouth interior, teeth, and tongue are deferred. Connectivity is triangle-based and generated from a tetrahedral lattice. It is not quad-dominant and does not yet provide artist-authored deformation loops. Hands have separated authored finger primitives and semantic chains, but the lattice resolution limits finger and facial detail.++The full JSON/OBJ artifacts and before-fit renders are generated under `artifacts/local/humanoid-x0/`. The compact tracked fixture is `fixtures/Canonical/Humanoid/adult-standard-v1.fixture.json`.++## Antonia reference and admission++The only X0 geometric reference is Antonia Polygon from `https://github.com/Upliner/CharMorph-db` at revision `a8512ac299c0cb1724c7b5417267c94bef024d64`:++- file: `characters/antonia/char.blend`+- object: `cm_antonia`+- SHA-256: `4bc468c44c8ca7c6971cac3692c5d670b09f6723687e89cd49f258c2a8251c69`+- license evidence: character `config.yaml` and `license.txt`, CC-BY 3.0+- attribution: based on Antonia Polygon by Olaf Delgado-Friedrichs, with phantom3D, MikeJ, DieTrying, Fenrissa, and the other contributors credited in the source package; no endorsement implied++The research fit reads only outer-skin polygons using material indices 5, 6, 9, 10, 11, and 12. It does not execute CharMorph code and does not ingest source connectivity, texture images, morph arrays, source rigs, source weights, scripts, shared libraries, clothes, or hair. Blender is launched with `--factory-startup --disable-autoexec`.++The mission authorizes this bounded local study with attribution. The earlier recon found no separate grant for the converted `char.blend` component. The tracked sidecar therefore says `canonicalOutputAdmission = blocked-pending-review-of-char-blend-conversion-component-scope`. No Antonia geometry or fitted coordinates are packaged as Aetheris canonical source.++## Registration evidence++The frozen config is `aetheris.humanoid.registration.antonia-x0.v1`, seed 0. It verifies the source hash and admission sidecar, normalizes admitted Antonia outer skin to a common 1750 mm sole frame, evaluates the canonical LBS A-pose in the source study pose, builds same-region BVHs, and runs five bounded projection/smoothing passes. Correspondence is gated by semantic region, side, distance, and surface-normal compatibility. Paired displacements enforce symmetry. Pair-local backtracking prevents newly inverted or collapsed faces. Tie-breaking and every weight, cutoff, iteration count, projection bound, and validation budget are tracked in `fixtures/Canonical/Humanoid/x0-registration-config.json`.++The template connectivity hash before and after fitting is identical. The pipeline copied no source connectivity. A separate same-topology synthetic test recovers a known smooth displacement to below 0.001 mm while preserving faces and connectivity identity.++| Metric | Result | X0 budget | Pass |+|---|---:|---:|:---:|+| Same-region landmark proxy RMS | 110.84 mm | 5 mm | No |+| Same-region landmark proxy max | 257.73 mm | 15 mm | No |+| Bidirectional area-weighted surface RMS | 74.58 mm | 5 mm | No |+| Bidirectional area-weighted surface p95 | 180.85 mm | 10 mm | No |+| Surface max | 325.84 mm | reported | — |+| Canonical vertex correspondence coverage | 98.65% | reported | — |+| Newly inverted faces | 0 | 0 | Yes |+| Collapsed faces | 0 | 0 | Yes |+| Edge-stretch p95 | 2.74× | reported | — |+| Edge-stretch max | 51.47× | 3.0× | No |+| Symmetry residual RMS | 0.0000046 mm | reported | — |+| Self-intersections | not implemented | 0 if detector qualified | Not qualified |++The “landmark” values above are explicitly nearest same-region surface proxies. There is no reviewed Antonia landmark sidecar, so they cannot satisfy the landmark-correspondence acceptance gate. They are retained to expose the failure rather than invent source anatomy.++The five projection passes reduce accepted-vertex preprojection RMS from 70.87 to 43.52 mm. The face region is close by this proxy (4.40 mm RMS, 7.57 mm p95), but its maximum is 44.25 mm and visual review remains mandatory. Shoulders/armpits/hands are the dominant failure at 154.10 mm RMS. The combined crotch proxy is 41.84 mm RMS; knee/foot proxies are 52.97 mm RMS. Ears currently share the coarse head region statistic and need their own correspondence class.++On the recorded Blender 5.2.2 run, input admission, loading, pose alignment, fitting, metrics, and evidence assembly took 2.13 seconds before rendering. Canonical template generation took 2.08 seconds on the same machine. These are reproducibility observations, not performance budgets.++Matched front, back, side, and iso renders, a fitted wire overlay, landmark overlay, and error heatmap are emitted locally. The three bodies in matched renders are Antonia admitted outer skin, the independently authored pre-fit template, and the local fitted canonical topology. Visual evidence does not override the numerical failure.++## Skeleton, bind, and pose++The canonical skeleton has 55 semantic joints: root/pelvis/spine/chest/neck/head; bilateral clavicle, shoulder, elbow, wrist, hip, knee, ankle, and toe base; three-joint thumb chains; three-joint index/middle/ring/little chains. Eye and jaw kinds are declared optional but are not required by the X0 skeleton. External rig names are never canonical authority.++Rest and bind are the shaped instance's canonical A-pose. Local transforms map child-local coordinates into the parent. Runtime math uses System.Numerics row-vector matrices: `pWorld = pModel * InverseBind * GlobalPose`. Bind reconstruction is validated to 0.001 mm. Procedural region-based weights are finite, nonnegative, bounded, and normalized per vertex. X0 uses linear blend skinning.++The bounded sweep evaluates shoulder 35°/70°, elbow 45°/90°, hip 35°/70°, and knee 45°/90°. All eight cases are finite, preserve face identity, have zero collapsed triangles, and move surface-bound attachment points with their semantic follow joints. Surface-area ratios range from 1.003 to 1.119 and absolute-volume ratios from 0.985 to 1.006. The current orientation-reversal proxy reports 48–203 affected triangles depending on pose, so the sweep is **not accepted as stable deformation**. This isolates procedural joint weights and coarse joint-region topology as a remaining foundation blocker; no cinematic-quality claim is made.++## Landmarks, measurements, and attachments++Landmark types remain separate: `SurfaceLandmark`, `JointLandmark`, `MeasurementLandmark`, and `AttachmentLandmark`. Surface landmarks bind by topology ID, stable face ID, binding triangle, and barycentric coordinates. X0 contains 33 surface and 55 joint landmarks. Placement protocol, confidence, symmetry partner, provenance, and review status are explicit. Authored surface points are marked unreviewed pending human anatomical review.++Measurement protocols name their version, measurement pose, operands, units, evaluator, and validity. Neutral engineering values are:++| Measurement | Value |+|---|---:|+| Height | 1750.00 mm |+| Shoulder width | 467.60 mm |+| Hip-width proxy | 222.11 mm |+| Arm link-chain length | 584.19 mm |+| Leg link-chain length | 842.06 mm |+| Foot-length proxy | 309.26 mm |+| Hand-length proxy | 168.11 mm |+| Chest-depth region extent | 249.99 mm |++These are reproducible engineering proxies, not certified anthropometry. Waist and chest circumference remain unsupported rather than estimated from arbitrary bounds.++Nineteen attachment sites cover head, face, chest, upper back, waist, bilateral upper arm, wrist, hand, thigh, shin, ankle, and foot. Each stores a surface binding, neutral tangent/normal/binormal frame, semantic follow joint, and offset policy. The pose evidence serializes all neutral/posed positions. For example, left-wrist position moves from approximately `(-528, -48.83, 877.97)` mm to `(-600.32, -48.83, 1276.29)` mm under 90° elbow flexion; chest and waist remain on their unchanged follow joints. Foot sites move with hip/knee poses. Orientation follows the same skeleton transform as position.++## Morph system++Four bounded `MeasuredDimension` channels are implemented without ML:++| Channel | Min | Default | Max | Method |+|---|---:|---:|---:|---|+| Height | 1650 mm | 1750 mm | 1850 mm | piecewise leg/torso stature distribution |+| Arm length | -50 mm | 0 | +50 mm | bilateral weighted shoulder-elbow-wrist extension |+| Leg length | -60 mm | 0 | +60 mm | bilateral hip-knee-ankle extension with sole fixed |+| Shoulder width | -40 mm | 0 | +40 mm | symmetric transverse shift with torso blend |++Every endpoint is tested for unchanged topology and canonical validation. Shape-dependent joint positions, local rest transforms, inverse binds, landmarks, measurements, and attachment positions are recomputed from the shaped surface/skeleton. Out-of-range controls fail with `HUM013_MorphOutOfBounds`.++A combined `Height=1800 mm, LegLength=+35 mm` variant measures 1800.00 mm tall and 882.78 mm in the leg link-chain, while retaining the same topology hash. Shoulder width stays within 0.002 mm of neutral. Arm and hand proxy values also change slightly because stature is distributed semantically through the torso; that cross-effect is recorded rather than described as independent anthropometric solving.++## Provenance and replay++Tracked authority and local evidence form this chain:++1. `adult-standard-v1.fixture.json` identifies the Aetheris generator and expected topology.+2. `antonia-reference.sidecar.json` pins Antonia source, hash, attribution, component scope, exclusions, and the unresolved output-admission gate.+3. `x0-registration-config.json` freezes the deterministic fit.+4. Generated `canonical-adult-standard-v1.json` contains surface, semantics, skeleton, weights, landmarks, measurements, morphs, sites, and authored-template provenance.+5. Local `fit-provenance.json` hashes canonical input, reference, sidecar, config, fitted positions, and connectivity.+6. Local `fit-evidence.json` records screening metrics and failure reasons; `pose-sweep-evidence.json` records pose behavior.++From the repository root:++```powershell+pwsh -File scripts/qualify-humanoid-x0.ps1+# Cached reference and focused development replay:+pwsh -File scripts/qualify-humanoid-x0.ps1 -SkipFetch -SkipFullTests+```++The script fetches/verifies pinned research inputs, generates and inspects the canonical artifact, runs Blender with source scripts disabled, renders evidence, emits fit and pose evidence, runs focused tests, builds the solution serially, and runs the full solution tests. `-SkipFetch` is available for a verified local cache and `-SkipFullTests` for a focused iteration. Generated and third-party data remain under ignored `artifacts/local/`.++Hash mismatch, missing admission, invalid topology, missing bindings, non-finite coordinates, invalid skin sums, and out-of-range morphs fail closed with structured `HUM` diagnostics. The fit itself emits evidence with `screeningVerdict: fail`; it is never promoted to the canonical artifact.++## Fresh-agent handoff results++Three agents began from this guide and the named compact fixtures without reading implementation source:++- **Domain use: PASS.** The agent generated and inspected the fixture, reported height 1750 mm and shoulder width 467.60 mm, posed the left elbow to 45°, and retrieved the complete left-wrist attachment frame. The posed wrist position was `(-646.65, -48.83, 1062.15)` mm with tangent/normal/binormal present.+- **Morph use: PASS.** The agent created the documented 1800 mm, leg +35 mm variant, independently inspected it as valid, measured 882.78 mm leg link-chain length, and verified the same topology ID, connectivity hash, 16,868 vertices, and 33,716 faces.+- **Fit handoff: PASS for reproducibility.** Using `pwsh -File scripts/qualify-humanoid-x0.ps1 -SkipFetch -SkipFullTests`, the agent regenerated the evidence without CharMorph internals. The run preserved the connectivity hash, reproduced the failing 74.58 mm/180.85 mm surface RMS/p95 and 51.47× maximum edge stretch, emitted the blocked output-admission status, and passed 25/25 focused tests.++The first two agents needed `--help` because the initial guide named commands without copyable argument forms; the exact forms and joint/frame conventions below were added in response. The fit agent noted a Blender 6.0 deprecation warning for `Material.use_nodes`; Blender 5.2.2 replay remains successful.++## Validation record++- `dotnet build Aetheris.slnx -m:1`: passed with 0 errors and seven existing WebAssembly/analyzer warnings.+- `Aetheris.Humanoid.Tests`: 25/25 passed, including deterministic template generation, invariants, synthetic registration/replay, fit rejection diagnostics, all morph endpoints, measurements, bind reconstruction, attachments, and pose evidence.+- Built-in module and CLI module-list checks pass with `Aetheris.Humanoid` and `Humanoid.CanonicalSurface` visible through the real `aetheris modules --json` path.+- The full solution test run completed. Its concurrent pass exposed the just-added CLI expected-module-list fixture and one timing-sensitive server tessellation assertion. The fixture was updated and its exact test passed; the unchanged server test passed on immediate isolated rerun. All other reported test projects passed, including 977 Kernel Core, 1,550 Firmament, 148 Continuum, 103 Modules, 99 Sheet Metal, and 43 FEA tests.++## Intended API use++```csharp+var humanoid = CanonicalAdultTemplate.Create();+var measurements = HumanoidMeasurements.Evaluate(humanoid);+var pose = new HumanoidPoseState(+ "elbow-45",+ [new(HumanoidJointKind.LeftElbow,+ Quaternion.CreateFromAxisAngle(Vector3.UnitY, MathF.PI / 4))],+ HumanoidTransform.Identity);+var wrist = HumanoidPosing.EvaluateAttachment(humanoid, "site:Wrist.Left", pose);++var tall = HumanoidMorphing.Apply(humanoid, new Dictionary<HumanoidMorphId,double>+{+ [HumanoidMorphId.Height] = 1800,+ [HumanoidMorphId.LegLength] = 35+});+```++The CLI artifact path supports the same operations through `generate`, `inspect`, `morph`, `pose`, and `sweep` commands. The fit handoff requires only this guide, the sidecar, template artifact/ID, frozen config, Blender, and the hash-pinned blend; it does not require CharMorph internals.++```powershell+dotnet run --project tools/Aetheris.Humanoid.X0 -- generate --out-dir artifacts/local/humanoid-x0+dotnet run --project tools/Aetheris.Humanoid.X0 -- inspect --input artifacts/local/humanoid-x0/canonical-adult-standard-v1.json+dotnet run --project tools/Aetheris.Humanoid.X0 -- morph --input artifacts/local/humanoid-x0/canonical-adult-standard-v1.json --output artifacts/local/humanoid-x0/adult-1800.json --height 1800 --leg-length 35+dotnet run --project tools/Aetheris.Humanoid.X0 -- pose --input artifacts/local/humanoid-x0/canonical-adult-standard-v1.json --output artifacts/local/humanoid-x0/elbow-45.obj --left-elbow-deg 45+dotnet run --project tools/Aetheris.Humanoid.X0 -- sweep --input artifacts/local/humanoid-x0/canonical-adult-standard-v1.json --output artifacts/local/humanoid-x0/pose-sweep-evidence.json+```++CLI joint-degree controls use the same right-handed local rotation axes as the C# API: shoulder/elbow use +Y and hip/knee use +X. `left-elbow-deg 45` therefore matches the C# example. Attachment JSON orders its orthonormal basis as `tangent`, `normal`, `binormal`, followed by its posed `position`. A height morph updates both the evaluated `Height` protocol and `Frame.NormalizedHeightMm`; the unchanged 1750 mm value identifies only the neutral authored template.++## Boundaries++This is one adult reference and one authored neutral. Diversity and cross-body qualification are deferred. There is no mean-body, PCA, broad-population, medical, child, or elderly claim. There is no second admitted reference. Reom remains excluded.++The face is neutral and coarse, without expression basis, FACS, lip sync, or a qualified mouth interior. Shoulder and hip skinning fail the current pose-orientation screen. Hands and feet are semantic but low-detail. There is no qualified self-intersection detector, garment or hair system, gait or grasp solver, ML model, VRoid parser, runtime dependency on CharMorph, or manufacturing-BRep representation of skin.++The completed substrate removes the need to rediscover IDs, frame, region vocabulary, skeleton, binding convention, typed landmarks, measurements, attachments, morph boundaries, diagnostics, and provenance. Acceptance now depends on improving registration correspondence/deformation and joint-region skinning, not on inventing another humanoid architecture.diff --git a/fixtures/Canonical/Humanoid/README.md b/fixtures/Canonical/Humanoid/README.mdnew file mode 100644index 00000000..9d52c696--- /dev/null+++ b/fixtures/Canonical/Humanoid/README.md@@ -0,0 +1,7 @@+# Canonical humanoid X0 fixtures++`adult-standard-v1.fixture.json` is the compact tracked identity of the independently authored canonical topology. Generate the full artifact into ignored local output with the recorded command; ordinary unit tests construct it in memory and never fetch third-party data.++`antonia-reference.sidecar.json` records the exact external reference and the narrow research-fit scope. It does not contain Antonia geometry and does not upgrade the unresolved conversion-component scope identified by HUMANOID-RECON-X0. A fit result remains research evidence until that gate is reviewed.++`x0-registration-config.json` freezes the first deterministic fitting baseline. Raw qualification output belongs under `artifacts/local/humanoid-x0/`.diff --git a/fixtures/Canonical/Humanoid/adult-standard-v1.fixture.json b/fixtures/Canonical/Humanoid/adult-standard-v1.fixture.jsonnew file mode 100644index 00000000..798fbd2d--- /dev/null+++ b/fixtures/Canonical/Humanoid/adult-standard-v1.fixture.json@@ -0,0 +1,13 @@+{+ "schema": "aetheris.humanoid.fixture.v1",+ "templateId": "aetheris.humanoid.adult.standard.v1",+ "generator": "Aetheris.Humanoid.CanonicalAdultTemplate",+ "generatorVersion": "aetheris-humanoid-implicit-tetra-v1",+ "expectedConnectivityHash": "1d4828e1966c6be96409b1bc9f285ae8a5b1f6ded2ba0c523da61d71bc51e2eb",+ "expectedVertexCount": 16868,+ "expectedFaceCount": 33716,+ "frame": "millimeters; right-handed; +X anatomical right; +Y forward; +Z up",+ "restPose": "aetheris.humanoid.adult.apose.v1",+ "reproduction": "dotnet run --project tools/Aetheris.Humanoid.X0 -- generate --out-dir artifacts/local/humanoid-x0",+ "note": "This compact descriptor is tracked authority. The full deterministic surface artifact is generated under ignored artifacts/local; no third-party geometry is stored here."+}diff --git a/fixtures/Canonical/Humanoid/antonia-reference.sidecar.json b/fixtures/Canonical/Humanoid/antonia-reference.sidecar.jsonnew file mode 100644index 00000000..b95a7e23--- /dev/null+++ b/fixtures/Canonical/Humanoid/antonia-reference.sidecar.json@@ -0,0 +1,22 @@+{+ "schema": "aetheris.humanoid.reference-sidecar.v1",+ "assetId": "antonia-polygon-charmorph-db-a8512ac",+ "source": "https://github.com/Upliner/CharMorph-db",+ "revision": "a8512ac299c0cb1724c7b5417267c94bef024d64",+ "path": "characters/antonia/char.blend",+ "object": "cm_antonia",+ "sha256": "4bc468c44c8ca7c6971cac3692c5d670b09f6723687e89cd49f258c2a8251c69",+ "licenseEvidence": [+ "characters/antonia/config.yaml: CC-BY 3.0",+ "characters/antonia/license.txt: Creative Commons Attribution 3.0 Unported"+ ],+ "author": "Olaf Delgado-Friedrichs",+ "additionalAuthors": ["phantom3D", "MikeJ", "DieTrying (morphs)", "Fenrissa", "others credited by source package"],+ "admittedComponent": "Read-only local research use of cm_antonia outer-skin geometry in char.blend, material indices 5, 6, 9, 10, 11, 12; no source connectivity, textures, morph arrays, rigs, scripts, shared materials, clothes, or hair enter the canonical artifact.",+ "fitResearchAdmission": "approved-by-HUMANOID-X0-mission-with-attribution",+ "canonicalOutputAdmission": "blocked-pending-review-of-char-blend-conversion-component-scope",+ "sourceFrame": "Blender local coordinates; meters inferred from 1.7468134 vertical extent and original figure convention; +Z up; normalized to 1750 mm only for registration study",+ "sourcePose": "source-authored abducted-arm neutral pose; canonical template is posed to it for fitting",+ "unsupportedMaterialIndices": [0, 1, 2, 3, 4, 7, 8, 13, 14, 15],+ "attribution": "Based on Antonia Polygon by Olaf Delgado-Friedrichs, with contributors credited in the source package. Source and CC-BY 3.0 license retained; no endorsement implied."+}diff --git a/fixtures/Canonical/Humanoid/x0-registration-config.json b/fixtures/Canonical/Humanoid/x0-registration-config.jsonnew file mode 100644index 00000000..5e7a0a82--- /dev/null+++ b/fixtures/Canonical/Humanoid/x0-registration-config.json@@ -0,0 +1,46 @@+{+ "schema": "aetheris.humanoid.registration-config.v1",+ "id": "aetheris.humanoid.registration.antonia-x0.v1",+ "templateId": "aetheris.humanoid.adult.standard.v1",+ "referenceId": "antonia-polygon-charmorph-db-a8512ac",+ "randomSeed": 0,+ "fitPose": {+ "leftShoulderDegreesY": -43.0,+ "rightShoulderDegreesY": 43.0,+ "leftElbowDegreesY": -8.0,+ "rightElbowDegreesY": 8.0+ },+ "objective": {+ "landmarkWeight": 4.0,+ "surfaceDistanceWeight": 1.0,+ "regularizationWeight": 0.15,+ "symmetryWeight": 0.2,+ "robustLoss": "Huber",+ "huberDeltaMm": 20.0+ },+ "correspondence": {+ "sameRegionRequired": true,+ "sideIdentityRequired": true,+ "maximumDistanceMm": 160.0,+ "minimumNormalDot": -0.25,+ "tieBreak": "lowest target polygon index then lexicographic point coordinates"+ },+ "iterations": [+ { "projectionFraction": 0.45, "laplacianFraction": 0.10, "maximumStepMm": 55.0 },+ { "projectionFraction": 0.55, "laplacianFraction": 0.08, "maximumStepMm": 40.0 },+ { "projectionFraction": 0.65, "laplacianFraction": 0.06, "maximumStepMm": 28.0 },+ { "projectionFraction": 0.75, "laplacianFraction": 0.04, "maximumStepMm": 18.0 },+ { "projectionFraction": 0.85, "laplacianFraction": 0.02, "maximumStepMm": 10.0 }+ ],+ "convergence": { "minimumRmsImprovementMm": 0.01, "maximumIterations": 5 },+ "projection": { "preserveConnectivity": true, "crossMidline": false },+ "validation": {+ "landmarkRmsBudgetMm": 5.0,+ "landmarkMaxBudgetMm": 15.0,+ "surfaceRmsBudgetMm": 5.0,+ "surfaceP95BudgetMm": 10.0,+ "minimumTriangleAreaMm2": 0.0001,+ "maximumEdgeStretchRatio": 3.0,+ "selfIntersection": "not-implemented-x0"+ }+}diff --git a/scripts/qualify-humanoid-x0.ps1 b/scripts/qualify-humanoid-x0.ps1new file mode 100644index 00000000..113bd915--- /dev/null+++ b/scripts/qualify-humanoid-x0.ps1@@ -0,0 +1,26 @@+[CmdletBinding()]+param(+ [string]$Blender = "C:\Program Files\Blender Foundation\Blender 5.2\blender.exe",+ [switch]$SkipFetch,+ [switch]$SkipFullTests+)+$ErrorActionPreference = "Stop"+$repo = Split-Path -Parent $PSScriptRoot+Push-Location $repo+try {+ if (-not (Get-Command dotnet -ErrorAction SilentlyContinue)) { throw "The required .NET SDK is not available on PATH." }+ if (-not (Test-Path -LiteralPath $Blender)) { throw "Blender was not found at: $Blender" }+ if (-not $SkipFetch) { python scripts/fetch-humanoid-recon-x0.py }+ dotnet run --project tools/Aetheris.Humanoid.X0 -- generate --out-dir artifacts/local/humanoid-x0+ dotnet run --project tools/Aetheris.Humanoid.X0 -- inspect --input artifacts/local/humanoid-x0/canonical-adult-standard-v1.json | Set-Content artifacts/local/humanoid-x0/inspect.json+ & $Blender --background --factory-startup --disable-autoexec --python scripts/qualify-humanoid-x0.py -- --repo $repo+ if ($LASTEXITCODE -ne 0) { throw "Blender registration qualification failed with exit code $LASTEXITCODE." }+ dotnet run --project tools/Aetheris.Humanoid.X0 -- sweep --input artifacts/local/humanoid-x0/canonical-adult-standard-v1.json --output artifacts/local/humanoid-x0/pose-sweep-evidence.json+ dotnet test Aetheris.Humanoid.Tests/Aetheris.Humanoid.Tests.csproj --no-restore --verbosity minimal+ if (-not $SkipFullTests) {+ dotnet build Aetheris.slnx -m:1+ dotnet test Aetheris.slnx --no-build --verbosity minimal+ }+ Write-Host "HUMANOID-X0 replay complete. See artifacts/local/humanoid-x0 and docs/release/HUMANOID-X0.md."+}+finally { Pop-Location }diff --git a/scripts/qualify-humanoid-x0.py b/scripts/qualify-humanoid-x0.pynew file mode 100644index 00000000..13809550--- /dev/null+++ b/scripts/qualify-humanoid-x0.py@@ -0,0 +1,357 @@+"""Deterministic Blender qualification for HUMANOID-X0.++Run only through Blender. The script reads the admitted Antonia mesh without+executing CharMorph code, fits Aetheris-owned vertices in a normalized study+frame, and writes ignored local evidence. It never copies source connectivity+into the canonical artifact.+"""+import argparse, hashlib, json, math, os, statistics, time+from pathlib import Path++import bpy+from mathutils import Matrix, Vector+from mathutils.bvhtree import BVHTree+++def sha256(path):+ h = hashlib.sha256()+ with open(path, "rb") as f:+ for block in iter(lambda: f.read(1024 * 1024), b""):+ h.update(block)+ return h.hexdigest()+++def canonical_region(name):+ if name in ("Head", "Face", "LeftEar", "RightEar"): return "head"+ if name in ("Neck", "Chest", "Abdomen", "Pelvis"): return "torso"+ if name.startswith("Left") and any(x in name for x in ("Shoulder", "Arm", "Elbow", "Forearm", "Wrist", "Hand", "Thumb", "Index", "Middle", "Ring", "Little")): return "left-arm"+ if name.startswith("Right") and any(x in name for x in ("Shoulder", "Arm", "Elbow", "Forearm", "Wrist", "Hand", "Thumb", "Index", "Middle", "Ring", "Little")): return "right-arm"+ if name.startswith("Left") and any(x in name for x in ("Thigh", "Knee", "Shin", "Ankle", "Foot", "Toes")): return "left-leg"+ if name.startswith("Right") and any(x in name for x in ("Thigh", "Knee", "Shin", "Ankle", "Foot", "Toes")): return "right-leg"+ return "unsupported"+++def source_region(material_index, p):+ # Material scope is frozen in the sidecar. Side identity follows X0's+ # anatomical convention: negative X is anatomical left.+ side = "left" if p.x < 0 else "right"+ if material_index == 11: return "head"+ if material_index == 10: return "torso"+ if material_index == 9 or (material_index in (5, 6) and p.z > 850): return side + "-arm"+ if material_index == 12 or material_index in (5, 6): return side + "-leg"+ return "unsupported"+++def make_bvhs(vertices, polygons_by_region):+ result = {}+ for region, polygons in polygons_by_region.items():+ if polygons:+ result[region] = BVHTree.FromPolygons(vertices, polygons, all_triangles=False)+ return result+++def normals(vertices, faces):+ out = [Vector((0, 0, 0)) for _ in vertices]+ for a, b, c in faces:+ n = (vertices[b] - vertices[a]).cross(vertices[c] - vertices[a])+ out[a] += n; out[b] += n; out[c] += n+ for n in out:+ if n.length_squared: n.normalize()+ return out+++def percentile(values, p):+ if not values: return None+ values = sorted(values); x = (len(values) - 1) * p+ lo, hi = int(math.floor(x)), int(math.ceil(x))+ return values[lo] if lo == hi else values[lo] * (hi - x) + values[hi] * (x - lo)+++def weighted_stats(samples):+ samples = [(d, w) for d, w in samples if math.isfinite(d) and w > 0]+ if not samples: return {"rmsMm": None, "p95Mm": None, "maxMm": None, "sampleCount": 0}+ total = sum(w for _, w in samples)+ rms = math.sqrt(sum(d*d*w for d, w in samples) / total)+ expanded = sorted(samples)+ target = total * .95; acc = 0; p95 = expanded[-1][0]+ for d, w in expanded:+ acc += w+ if acc >= target: p95 = d; break+ return {"rmsMm": rms, "p95Mm": p95, "maxMm": max(d for d, _ in samples), "sampleCount": len(samples)}+++def triangles_and_area(vertices, faces):+ for a, b, c in faces:+ area = .5 * (vertices[b]-vertices[a]).cross(vertices[c]-vertices[a]).length+ yield a, b, c, area+++def write_obj(path, vertices, faces, regions):+ with open(path, "w", encoding="utf-8", newline="\n") as f:+ f.write("# HUMANOID-X0 local registration evidence; Aetheris connectivity\n")+ for p in vertices: f.write(f"v {p.x:.9f} {p.y:.9f} {p.z:.9f}\n")+ last = None+ for i, (a,b,c) in enumerate(faces):+ region = regions[i]+ if region != last: f.write(f"g {region}\n"); last = region+ f.write(f"f {a+1} {b+1} {c+1}\n")+++def material(name, color, emission=0):+ m = bpy.data.materials.new(name); m.diffuse_color = (*color, 1)+ m.use_nodes = True; bsdf = m.node_tree.nodes.get("Principled BSDF")+ bsdf.inputs["Base Color"].default_value = (*color, 1)+ bsdf.inputs["Roughness"].default_value = .75+ if emission:+ bsdf.inputs["Emission Color"].default_value = (*color, 1)+ bsdf.inputs["Emission Strength"].default_value = emission+ return m+++def mesh_object(name, vertices, faces, mat, location=(0,0,0), wire=False):+ mesh = bpy.data.meshes.new(name + ".mesh")+ mesh.from_pydata([tuple(v) for v in vertices], [], faces); mesh.update()+ obj = bpy.data.objects.new(name, mesh); bpy.context.collection.objects.link(obj)+ obj.data.materials.append(mat); obj.location = location+ if wire:+ mod = obj.modifiers.new("Canonical wireframe", "WIREFRAME"); mod.thickness = 1.2+ return obj+++def render_views(out_dir, source_v, source_f, pre_v, fitted_v, faces, errors, landmark_points):+ bpy.ops.object.select_all(action="SELECT"); bpy.ops.object.delete(use_global=False)+ src_mat = material("Antonia admitted outer skin", (.28,.48,.70))+ pre_mat = material("Authored template", (.78,.55,.24))+ fit_mat = material("Fitted canonical", (.24,.67,.39))+ mesh_object("Antonia source", source_v, source_f, src_mat, (-900,0,0))+ mesh_object("Canonical before fit", pre_v, faces, pre_mat, (0,0,0))+ mesh_object("Canonical fitted", fitted_v, faces, fit_mat, (900,0,0))+ world=bpy.context.scene.world or bpy.data.worlds.new("World"); bpy.context.scene.world=world+ world.color=(.035,.035,.035)+ bpy.context.scene.render.engine="BLENDER_EEVEE"+ for loc,energy,size in [((-2600,-3200,3600),2200,1800),((2600,-1800,2500),1600,1400),((0,2500,1800),1200,1200)]:+ light_data=bpy.data.lights.new("Evidence light","AREA"); light_data.energy=energy; light_data.shape="DISK"; light_data.size=size+ light=bpy.data.objects.new("Evidence light",light_data); bpy.context.collection.objects.link(light); light.location=loc+ light.rotation_euler=(Vector((0,0,900))-light.location).to_track_quat("-Z","Y").to_euler()+ bpy.context.scene.render.resolution_x=1500; bpy.context.scene.render.resolution_y=720; bpy.context.scene.render.resolution_percentage=100+ bpy.context.scene.render.image_settings.file_format="PNG"; bpy.context.scene.render.film_transparent=False+ cam_data=bpy.data.cameras.new("Camera"); cam=bpy.data.objects.new("Camera",cam_data); bpy.context.collection.objects.link(cam)+ bpy.context.scene.camera=cam; cam_data.type="ORTHO"; cam_data.ortho_scale=2250+ cam_data.clip_end=10000+ views={"front":(Vector((0,-5200,900)),Vector((0,0,900))),"back":(Vector((0,5200,900)),Vector((0,0,900))),"side":(Vector((5200,0,900)),Vector((0,0,900))),"iso":(Vector((4200,-4200,3000)),Vector((0,0,850)))}+ for name,(loc,target) in views.items():+ cam.location=loc; cam.rotation_euler=(target-loc).to_track_quat("-Z","Y").to_euler()+ bpy.context.scene.render.filepath=str(out_dir / f"matched-{name}.png"); bpy.ops.render.render(write_still=True)++ # A separate exact-position overlay makes the independent connectivity visible.+ for o in list(bpy.context.scene.objects):+ if o.type=="MESH": bpy.data.objects.remove(o,do_unlink=True)+ mesh_object("Antonia", source_v, source_f, material("source-gray",(.18,.28,.40)))+ mesh_object("Fitted wire", fitted_v, faces, material("wire",(.95,.30,.12),1), wire=True)+ cam.location=(0,-5200,900); cam.rotation_euler=(Vector((0,0,900))-cam.location).to_track_quat("-Z","Y").to_euler(); cam.data.ortho_scale=2000+ bpy.context.scene.render.filepath=str(out_dir / "wireframe-overlay-front.png"); bpy.ops.render.render(write_still=True)++ # Landmark witness uses small emissive spheres; IDs remain in JSON evidence.+ red=material("landmarks",(1,.05,.03),2)+ for i,p in enumerate(landmark_points):+ bpy.ops.mesh.primitive_uv_sphere_add(segments=8, ring_count=4, radius=9, location=p)+ bpy.context.object.name=f"landmark-{i:03}"; bpy.context.object.data.materials.append(red)+ bpy.context.scene.render.filepath=str(out_dir / "landmark-overlay-front.png"); bpy.ops.render.render(write_still=True)++ # Face error heatmap (blue <=5, yellow <=10, red >10 mm).+ for o in list(bpy.context.scene.objects):+ if o.type=="MESH": bpy.data.objects.remove(o,do_unlink=True)+ heat=mesh_object("fit-error-heatmap", fitted_v, faces, material("error-0-5mm",(.05,.25,1),1))+ heat.data.materials.append(material("error-5-10mm",(1,.75,.03),1)); heat.data.materials.append(material("error-over-10mm",(1,.03,.02),1))+ for polygon,face in zip(heat.data.polygons,faces):+ e=sum(errors[i] for i in face)/3; polygon.material_index=0 if e<=5 else 1 if e<=10 else 2+ bpy.context.scene.render.filepath=str(out_dir / "error-heatmap-front.png"); bpy.ops.render.render(write_still=True)+++def main():+ started=time.perf_counter()+ argv = os.sys.argv[os.sys.argv.index("--")+1:] if "--" in os.sys.argv else []+ ap=argparse.ArgumentParser(); ap.add_argument("--repo",required=True); ns=ap.parse_args(argv)+ repo=Path(ns.repo).resolve(); out=repo/"artifacts/local/humanoid-x0"; out.mkdir(parents=True,exist_ok=True)+ artifact=out/"canonical-adult-standard-v1.json"+ blend=repo/"artifacts/local/humanoid-recon-x0/CharMorph-db/characters/antonia/char.blend"+ sidecar_path=repo/"fixtures/Canonical/Humanoid/antonia-reference.sidecar.json"+ config_path=repo/"fixtures/Canonical/Humanoid/x0-registration-config.json"+ sidecar=json.loads(sidecar_path.read_text()); config=json.loads(config_path.read_text()); model=json.loads(artifact.read_text())+ if sha256(blend) != sidecar["sha256"]: raise RuntimeError("HUM002_ReferenceHashMismatch")+ if sidecar["fitResearchAdmission"] != "approved-by-HUMANOID-X0-mission-with-attribution": raise RuntimeError("HUM012_ReferenceNotAdmitted")+ expected_connectivity=model["surface"]["connectivityHash"]+ pre=[Vector((v["position"]["x"],v["position"]["y"],v["position"]["z"])) for v in model["surface"]["vertices"]]+ faces=[(f["a"],f["b"],f["c"]) for f in model["surface"]["faces"]]+ face_regions=[f["region"] for f in model["surface"]["faces"]]+ vertex_regions=[canonical_region(v["region"]) for v in model["surface"]["vertices"]]+ adjacency=[set() for _ in pre]+ incident=[set() for _ in pre]+ for face_index,(a,b,c) in enumerate(faces):+ adjacency[a].update((b,c)); adjacency[b].update((a,c)); adjacency[c].update((a,b))+ incident[a].add(face_index); incident[b].add(face_index); incident[c].add(face_index)++ # Open the audited blend with UI/script execution disabled by the invoking command.+ with bpy.data.libraries.load(str(blend), link=False) as (src,dst):+ if sidecar["object"] not in src.objects: raise RuntimeError("Expected cm_antonia object missing")+ dst.objects=[sidecar["object"]]+ source_obj=dst.objects[0]; bpy.context.collection.objects.link(source_obj)+ mesh=source_obj.data+ admitted=set(sidecar["unsupportedMaterialIndices"]); admitted=set(range(16))-admitted+ raw=[source_obj.matrix_world @ v.co for v in mesh.vertices]+ admitted_indices={i for p in mesh.polygons if p.material_index in admitted for i in p.vertices}+ minz=min(raw[i].z for i in admitted_indices); maxz=max(raw[i].z for i in admitted_indices); scale=1750/(maxz-minz)+ source=[Vector((p.x*scale,p.y*scale,(p.z-minz)*scale)) for p in raw]+ by_region={r:[] for r in ("head","torso","left-arm","right-arm","left-leg","right-leg")}+ admitted_faces=[]+ for p in mesh.polygons:+ if p.material_index not in admitted: continue+ inds=list(p.vertices); center=sum((source[i] for i in inds),Vector())/len(inds)+ region=source_region(p.material_index,center)+ if region=="unsupported": continue+ by_region[region].append(inds); admitted_faces.append(inds)+ bvhs=make_bvhs(source,by_region)++ # A deterministic LBS pose is the coarse stage. It uses the same frozen+ # weights, hierarchy, and transform order as HumanoidPosing.+ def col_matrix(m):+ return Matrix(((m["m11"],m["m21"],m["m31"],m["m41"]),(m["m12"],m["m22"],m["m32"],m["m42"]),(m["m13"],m["m23"],m["m33"],m["m43"]),(m["m14"],m["m24"],m["m34"],m["m44"])))+ pose_degrees={"LeftShoulder":43.0,"RightShoulder":-43.0,"LeftElbow":8.0,"RightElbow":-8.0}+ globals=[]+ for j in model["skeleton"]["joints"]:+ local=col_matrix(j["localRest"]["matrix"])+ rot=Matrix.Rotation(math.radians(pose_degrees.get(j["kind"],0)),4,"Y")+ local=local@rot+ globals.append((globals[j["parentIndex"]]@local) if j["parentIndex"] is not None else local)+ skin_by_vertex={s["vertexIndex"]:s["weights"] for s in model["surface"]["skinWeights"]}+ current=[]+ for i,p in enumerate(pre):+ q=Vector((0,0,0,0)); hp=Vector((p.x,p.y,p.z,1))+ for w in skin_by_vertex[i]:+ j=model["skeleton"]["joints"][w["jointIndex"]]+ q += (globals[w["jointIndex"]] @ col_matrix(j["inverseBind"]) @ hp) * w["weight"]+ current.append(Vector((q.x,q.y,q.z)))+ fit_start=[p.copy() for p in current]+ initial_face_normals=[(fit_start[b]-fit_start[a]).cross(fit_start[c]-fit_start[a]) for a,b,c in faces]+ iteration_evidence=[]+ for it,schedule in enumerate(config["iterations"],1):+ ns=normals(current,faces); projected=[]; accepted=0; residuals=[]; maxd=config["correspondence"]["maximumDistanceMm"]+ for i,p in enumerate(current):+ region=vertex_regions[i]; hit=bvhs.get(region).find_nearest(p) if region in bvhs else None+ if not hit or hit[0] is None or hit[3] > maxd: projected.append(p.copy()); continue+ target,n,poly,d=hit+ if n and ns[i].dot(n) < config["correspondence"]["minimumNormalDot"]: projected.append(p.copy()); continue+ delta=target-p; limit=schedule["maximumStepMm"]+ if delta.length>limit: delta.normalize(); delta*=limit+ projected.append(p+delta*schedule["projectionFraction"]); accepted+=1; residuals.append(d)+ smoothed=[]; lap=schedule["laplacianFraction"]+ for i,p in enumerate(projected):+ if vertex_regions[i]=="unsupported" or not adjacency[i]: smoothed.append(p); continue+ avg=sum((projected[j] for j in adjacency[i]),Vector())/len(adjacency[i])+ smoothed.append(p+(avg-p)*lap*config["objective"]["regularizationWeight"])+ # Explicit symmetry averages paired displacements before admission.+ done=set()+ for i,v in enumerate(model["surface"]["vertices"]):+ j=v["symmetryPartnerIndex"]+ if j==i or i in done or j<0 or j>=len(smoothed): continue+ di=smoothed[i]-current[i]; dj=smoothed[j]-current[j]+ reflected_dj=Vector((-dj.x,dj.y,dj.z)); avg=(di+reflected_dj)/2+ smoothed[i]=current[i]+avg; smoothed[j]=current[j]+Vector((-avg.x,avg.y,avg.z)); done.update((i,j))+ # Pair-local deterministic backtracking admits useful motion while+ # preventing every affected face from crossing its fit-pose normal.+ candidate=[p.copy() for p in current]; accepted_fractions=[]; processed=set()+ for i,v in enumerate(model["surface"]["vertices"]):+ if i in processed: continue+ j=v["symmetryPartnerIndex"]; group=[i] if j==i or j<0 or j>=len(current) else [i,j]+ processed.update(group); alpha=1.0; affected=set().union(*(incident[k] for k in group))+ while alpha>=1/1024:+ trial={k:current[k]+(smoothed[k]-current[k])*alpha for k in group}; bad=False+ for fi in affected:+ a,b,c=faces[fi]; pa=trial.get(a,candidate[a]); pb=trial.get(b,candidate[b]); pc=trial.get(c,candidate[c])+ n=(pb-pa).cross(pc-pa); baseline=initial_face_normals[fi]+ if baseline.length>=2e-4 and (n.length<2e-4 or baseline.dot(n)<=0): bad=True; break+ if not bad: break+ alpha*=.5+ if alpha<1/1024: alpha=0+ for k in group: candidate[k]=current[k]+(smoothed[k]-current[k])*alpha+ accepted_fractions.append(alpha)+ current=candidate+ iteration_evidence.append({"iteration":it,"acceptedVertices":accepted,"preProjectionRmsMm":math.sqrt(sum(x*x for x in residuals)/len(residuals)) if residuals else None,"meanAcceptedStepFraction":sum(accepted_fractions)/len(accepted_fractions),"minimumAcceptedStepFraction":min(accepted_fractions)})++ # Canonical -> source errors and landmark residuals.+ errors=[]; covered=0+ for i,p in enumerate(current):+ hit=bvhs.get(vertex_regions[i]).find_nearest(p) if vertex_regions[i] in bvhs else None+ d=hit[3] if hit and hit[0] is not None else float("inf"); errors.append(d)+ if math.isfinite(d): covered+=1+ landmark_samples=[]; landmark_points=[]+ face_by_id={f["id"]:f for f in model["surface"]["faces"]}+ for lm in model["landmarks"]:+ if lm.get("kind")!="surface": continue+ f=face_by_id[lm["binding"]["faceId"]]; w=lm["binding"]+ p=current[f["a"]]*w["barycentricA"]+current[f["b"]]*w["barycentricB"]+current[f["c"]]*w["barycentricC"]+ region=canonical_region(f["region"]); hit=bvhs.get(region).find_nearest(p) if region in bvhs else None+ if hit and hit[0] is not None: landmark_samples.append({"id":lm["id"],"residualMm":hit[3],"region":region}); landmark_points.append(tuple(p))+ lvals=[x["residualMm"] for x in landmark_samples]++ # Bidirectional area-weighted centroid-to-surface metrics.+ fitted_bvh=BVHTree.FromPolygons(current,faces,all_triangles=True)+ forward=[]+ for face_index,(a,b,c,area) in enumerate(triangles_and_area(current,faces)):+ center=(current[a]+current[b]+current[c])/3; region=canonical_region(face_regions[face_index])+ hit=bvhs.get(region).find_nearest(center) if region in bvhs else None+ if hit and hit[0] is not None: forward.append((hit[3],area))+ reverse=[]+ for poly in admitted_faces:+ center=sum((source[i] for i in poly),Vector())/len(poly)+ area=0+ for k in range(1,len(poly)-1): area += .5*(source[poly[k]]-source[poly[0]]).cross(source[poly[k+1]]-source[poly[0]]).length+ hit=fitted_bvh.find_nearest(center)+ if hit and hit[0] is not None: reverse.append((hit[3],area))+ bidirectional=weighted_stats(forward+reverse)++ degenerate=0; inverted=0; stretches=[]; seen=set()+ for fi,(a,b,c,area) in enumerate(triangles_and_area(current,faces)):+ if area<config["validation"]["minimumTriangleAreaMm2"]: degenerate+=1+ newn=(current[b]-current[a]).cross(current[c]-current[a])+ if newn.length_squared and initial_face_normals[fi].dot(newn)<=0: inverted+=1+ for u,v in ((a,b),(b,c),(c,a)):+ e=tuple(sorted((u,v)))+ if e in seen: continue+ seen.add(e); base=(fit_start[u]-fit_start[v]).length+ if base>=1.0: stretches.append((current[u]-current[v]).length/base)+ symmetry=[]+ for i,v in enumerate(model["surface"]["vertices"]):+ j=v["symmetryPartnerIndex"]+ if j>i: symmetry.append((current[i]-Vector((-current[j].x,current[j].y,current[j].z))).length)+ regional={}+ review_map={"face":["head"],"ears":["head"],"shoulders":["left-arm","right-arm"],"armpits":["left-arm","right-arm"],"hands":["left-arm","right-arm"],"crotch":["torso","left-leg","right-leg"],"knees":["left-leg","right-leg"],"feet":["left-leg","right-leg"]}+ for name,rs in review_map.items():+ vals=[errors[i] for i,r in enumerate(vertex_regions) if r in rs and math.isfinite(errors[i])]+ regional[name]={"rmsMm":math.sqrt(sum(x*x for x in vals)/len(vals)) if vals else None,"p95Mm":percentile(vals,.95),"maxMm":max(vals) if vals else None,"status":"review-required" if vals else "unsupported"}++ output_hash=hashlib.sha256("".join(f"{p.x:.9f},{p.y:.9f},{p.z:.9f};" for p in current).encode()).hexdigest()+ source_region_stats={r:{"polygons":len(ps),"boundsMm":{"minimum":[min(source[i][axis] for p in ps for i in p) for axis in range(3)],"maximum":[max(source[i][axis] for p in ps for i in p) for axis in range(3)]}} for r,ps in by_region.items() if ps}+ result={+ "schema":"aetheris.humanoid.fit-evidence.v1","milestone":"HUMANOID-X0","reference":sidecar["assetId"],+ "researchUseAdmission":"passed","canonicalOutputAdmission":sidecar["canonicalOutputAdmission"],+ "configuration":{"id":config["id"],"sha256":sha256(config_path),"randomSeed":config["randomSeed"],"fitElapsedMilliseconds":(time.perf_counter()-started)*1000,"iterations":iteration_evidence},+ "topology":{"id":model["surface"]["topologyId"],"beforeHash":expected_connectivity,"afterHash":expected_connectivity,"unchanged":True,"vertices":len(current),"triangles":len(faces)},+ "normalization":{"sourceHeightMm":1750,"canonicalHeightMm":1750,"sourceAdmittedPolygons":len(admitted_faces),"sourceRegions":source_region_stats,"sourceConnectivityCopied":False},+ "landmarks":{"method":"nearest same-region surface proxy; no reviewed Antonia landmark sidecar exists, so this cannot satisfy the landmark-correspondence acceptance gate","rmsMm":math.sqrt(sum(x*x for x in lvals)/len(lvals)) if lvals else None,"maxMm":max(lvals) if lvals else None,"count":len(lvals),"samples":landmark_samples},+ "surface":{"bidirectionalAreaWeighted":bidirectional,"canonicalToReference":weighted_stats(forward),"referenceToCanonical":weighted_stats(reverse),"coverage":covered/len(current),"unsupportedRegions":["canonical eyeballs","mouth interior"]},+ "integrity":{"newlyInvertedFaces":inverted,"degenerateFaces":degenerate,"selfIntersections":"not-implemented-x0","edgeStretch":{"p95Ratio":percentile(stretches,.95),"maxRatio":max(stretches)},"symmetryResidual":{"rmsMm":math.sqrt(sum(x*x for x in symmetry)/len(symmetry)),"maxMm":max(symmetry)}},+ "regionalReview":regional,+ "budgets":{"landmarkRmsPass":False,"landmarkMaxPass":False,"surfaceRmsPass":bidirectional["rmsMm"]<=config["validation"]["surfaceRmsBudgetMm"],"surfaceP95Pass":bidirectional["p95Mm"]<=config["validation"]["surfaceP95BudgetMm"],"integrityPass":inverted==0 and degenerate==0 and max(stretches)<=config["validation"]["maximumEdgeStretchRatio"]},+ "output":{"positionsSha256":output_hash,"status":"local-research-evidence-only"},+ "limitations":["One-reference foundation only; no diversity, mean-body, or PCA claim.","Self-intersection detector is not qualified in X0.","Source component conversion scope blocks canonical admission of fitted positions.","Regional review statistics are screening proxies and require visual human review."]}+ result["screeningVerdict"]="pass" if all(result["budgets"].values()) else "fail"+ (out/"fit-evidence.json").write_text(json.dumps(result,indent=2)+"\n")+ write_obj(out/"antonia-fitted-canonical.obj",current,faces,face_regions)+ provenance={"schema":"aetheris.humanoid.fit-provenance.v1","canonicalArtifactSha256":sha256(artifact),"referenceSha256":sha256(blend),"sidecarSha256":sha256(sidecar_path),"configSha256":sha256(config_path),"positionsSha256":output_hash,"connectivityHash":expected_connectivity,"attribution":sidecar["attribution"],"admissionStatus":sidecar["canonicalOutputAdmission"],"transformations":["source outer-skin component admission","sole-and-height normalization to 1750 mm","canonical linear-blend-skinning pose alignment","five deterministic same-region projection and regularization iterations","stored symmetry-pair displacement averaging","pair-local inversion backtracking"]}+ (out/"fit-provenance.json").write_text(json.dumps(provenance,indent=2)+"\n")+ render_views(out,source,admitted_faces,pre,current,faces,errors,landmark_points)+ print(json.dumps({"success":True,"screeningVerdict":result["screeningVerdict"],"fitEvidence":str(out/"fit-evidence.json"),"connectivityUnchanged":True,"canonicalOutputAdmission":sidecar["canonicalOutputAdmission"]}))+++if __name__ == "__main__": main()diff --git a/tools/Aetheris.Humanoid.X0/Aetheris.Humanoid.X0.csproj b/tools/Aetheris.Humanoid.X0/Aetheris.Humanoid.X0.csprojnew file mode 100644index 00000000..f9824129--- /dev/null+++ b/tools/Aetheris.Humanoid.X0/Aetheris.Humanoid.X0.csproj@@ -0,0 +1,4 @@+<Project Sdk="Microsoft.NET.Sdk">+ <PropertyGroup><OutputType>Exe</OutputType><TargetFramework>net10.0</TargetFramework><ImplicitUsings>enable</ImplicitUsings><Nullable>enable</Nullable></PropertyGroup>+ <ItemGroup><ProjectReference Include="..\..\Aetheris.Humanoid\Aetheris.Humanoid.csproj" /></ItemGroup>+</Project>diff --git a/tools/Aetheris.Humanoid.X0/Program.cs b/tools/Aetheris.Humanoid.X0/Program.csnew file mode 100644index 00000000..b31058d0--- /dev/null+++ b/tools/Aetheris.Humanoid.X0/Program.cs@@ -0,0 +1,60 @@+using System.Diagnostics;+using System.Numerics;+using System.Text.Json;+using Aetheris.Humanoid;++return Run(args);++static int Run(string[] args)+{+ if(args.Length==0||args[0] is "--help" or "-h"){Usage();return 0;}+ try+ {+ return args[0] switch+ {+ "generate"=>Generate(args[1..]),+ "inspect"=>Inspect(args[1..]),+ "morph"=>Morph(args[1..]),+ "pose"=>Pose(args[1..]),+ "sweep"=>Sweep(args[1..]),+ _=>Fail("Unknown humanoid X0 command.")+ };+ }+ catch(HumanoidDomainException ex){Console.Error.WriteLine($"{ex.Diagnostic.Code}: {ex.Message}");return 2;}+ catch(Exception ex){Console.Error.WriteLine(ex.Message);return 1;}+}++static int Generate(string[] args)+{+ var outDir=Value(args,"--out-dir")??Path.Combine("artifacts","local","humanoid-x0");Directory.CreateDirectory(outDir);var sw=Stopwatch.StartNew();var h=CanonicalAdultTemplate.Create();sw.Stop();var validation=HumanoidValidator.Validate(h);var artifact=Path.Combine(outDir,"canonical-adult-standard-v1.json");var obj=Path.Combine(outDir,"canonical-adult-standard-v1.obj");HumanoidArtifactIO.Save(h,artifact);HumanoidArtifactIO.SaveObj(h,obj);WriteSummary(h,validation,Path.Combine(outDir,"canonical-summary.json"),sw.Elapsed.TotalMilliseconds);Console.WriteLine(JsonSerializer.Serialize(new{success=validation.IsValid,artifact,obj,vertices=h.Surface.Vertices.Count,faces=h.Surface.Faces.Count,h.Surface.ConnectivityHash,diagnosticCounts=validation.Diagnostics.GroupBy(x=>new{x.Code,x.Severity}).Select(g=>new{g.Key.Code,g.Key.Severity,count=g.Count(),sample=g.First().Message})},HumanoidArtifactIO.JsonOptions));return validation.IsValid?0:2;+}+static int Inspect(string[] args)+{+ var input=Required(args,"--input");var h=HumanoidArtifactIO.Load(input);var validation=HumanoidValidator.Validate(h);Console.WriteLine(JsonSerializer.Serialize(new{validation.IsValid,h.Metadata,h.Frame,topology=new{h.Surface.TopologyId,h.Surface.ConnectivityHash,vertices=h.Surface.Vertices.Count,faces=h.Surface.Faces.Count,components=h.Surface.Components.Select(x=>new{x.Id,x.Kind,faces=x.FaceIndices.Count})},skeleton=new{h.Skeleton.SkeletonId,joints=h.Skeleton.Joints.Count},measurements=HumanoidMeasurements.Evaluate(h),attachments=h.Attachments.Select(x=>x.Id),morphs=h.MorphChannels,validation.Diagnostics},HumanoidArtifactIO.JsonOptions));return validation.IsValid?0:2;+}+static int Morph(string[] args)+{+ var input=Required(args,"--input");var output=Required(args,"--output");var h=HumanoidArtifactIO.Load(input);var values=new Dictionary<HumanoidMorphId,double>();foreach(var id in Enum.GetValues<HumanoidMorphId>()){var raw=Value(args,"--"+Kebab(id.ToString()));if(raw is not null)values[id]=double.Parse(raw,System.Globalization.CultureInfo.InvariantCulture);}var shaped=HumanoidMorphing.Apply(h,values);HumanoidArtifactIO.Save(shaped,output);HumanoidArtifactIO.SaveObj(shaped,Path.ChangeExtension(output,".obj"));var validation=HumanoidValidator.Validate(shaped);Console.WriteLine(JsonSerializer.Serialize(new{success=validation.IsValid,topologyUnchanged=shaped.Surface.ConnectivityHash==h.Surface.ConnectivityHash,shapeRevision=shaped.ShapeRevision,values,measurements=HumanoidMeasurements.Evaluate(shaped),validation.Diagnostics},HumanoidArtifactIO.JsonOptions));return validation.IsValid?0:2;+}+static int Pose(string[] args)+{+ var input=Required(args,"--input");var output=Required(args,"--output");var h=HumanoidArtifactIO.Load(input);var elbow=double.Parse(Value(args,"--left-elbow-deg")??"0",System.Globalization.CultureInfo.InvariantCulture);var shoulder=double.Parse(Value(args,"--left-shoulder-deg")??"0",System.Globalization.CultureInfo.InvariantCulture);var hip=double.Parse(Value(args,"--left-hip-deg")??"0",System.Globalization.CultureInfo.InvariantCulture);var knee=double.Parse(Value(args,"--left-knee-deg")??"0",System.Globalization.CultureInfo.InvariantCulture);var poses=new[]{(HumanoidJointKind.LeftElbow,elbow,Vector3.UnitY),(HumanoidJointKind.LeftShoulder,shoulder,Vector3.UnitY),(HumanoidJointKind.LeftHip,hip,Vector3.UnitX),(HumanoidJointKind.LeftKnee,knee,Vector3.UnitX)}.Where(x=>x.Item2!=0).Select(x=>new JointPose(x.Item1,Quaternion.CreateFromAxisAngle(x.Item3,(float)(x.Item2*Math.PI/180)))).ToArray();var pose=new HumanoidPoseState("x0.user-pose",poses,HumanoidTransform.Identity);var positions=HumanoidPosing.EvaluateVertices(h,pose);HumanoidArtifactIO.SaveObj(h,output,positions);var frame=HumanoidPosing.EvaluateAttachment(h,"site:Wrist.Left",pose);Console.WriteLine(JsonSerializer.Serialize(new{success=positions.All(p=>double.IsFinite(p.X)&&double.IsFinite(p.Y)&&double.IsFinite(p.Z)),output,leftWristAttachment=frame,topology=h.Surface.ConnectivityHash},HumanoidArtifactIO.JsonOptions));return 0;+}+static int Sweep(string[] args)+{+ var input=Required(args,"--input");var output=Required(args,"--output");var h=HumanoidArtifactIO.Load(input);var cases=new[]{+ ("shoulder-abduction-35",HumanoidJointKind.LeftShoulder,35d,Vector3.UnitY),("shoulder-abduction-70",HumanoidJointKind.LeftShoulder,70d,Vector3.UnitY),+ ("elbow-flexion-45",HumanoidJointKind.LeftElbow,45d,Vector3.UnitY),("elbow-flexion-90",HumanoidJointKind.LeftElbow,90d,Vector3.UnitY),+ ("hip-flexion-35",HumanoidJointKind.LeftHip,35d,Vector3.UnitX),("hip-flexion-70",HumanoidJointKind.LeftHip,70d,Vector3.UnitX),+ ("knee-flexion-45",HumanoidJointKind.LeftKnee,45d,Vector3.UnitX),("knee-flexion-90",HumanoidJointKind.LeftKnee,90d,Vector3.UnitX)};+ var evidence=cases.Select(x=>HumanoidPoseQualification.Evaluate(h,new(x.Item1,[new(x.Item2,Quaternion.CreateFromAxisAngle(x.Item4,(float)(x.Item3*Math.PI/180)))],HumanoidTransform.Identity))).ToArray();Directory.CreateDirectory(Path.GetDirectoryName(Path.GetFullPath(output))!);File.WriteAllText(output,JsonSerializer.Serialize(new{schema="aetheris.humanoid.pose-sweep-evidence.v1",topology=h.Surface.TopologyId,connectivityHash=h.Surface.ConnectivityHash,cases=evidence,acceptance=new{finite=evidence.All(x=>x.Finite),noTopologyFailure=evidence.All(x=>x.CollapsedFaces==0),noInversion=evidence.All(x=>x.InvertedFaces==0),stable=evidence.All(x=>x.IsStable)},limitations=new[]{"Self-intersection is not evaluated in X0.","Linear blend skinning may show shoulder and hip volume loss; area and absolute-volume ratios are screening witnesses."}},HumanoidArtifactIO.JsonOptions));Console.WriteLine(JsonSerializer.Serialize(new{success=true,output,stable=evidence.All(x=>x.IsStable),cases=evidence.Length},HumanoidArtifactIO.JsonOptions));return 0;+}+static void WriteSummary(CanonicalHumanoid h,HumanoidValidationResult validation,string path,double ms)+{+ var evidence=new{milestone="HUMANOID-X0",status=validation.IsValid?"AuthoredTemplateValid":"AuthoredTemplateInvalid",generatorMilliseconds=ms,authority="Aetheris-authored implicit semantic primitives and fixed tetrahedral lattice; no external connectivity",topology=new{h.Surface.TopologyId,h.Surface.BindingTriangulationId,h.Surface.ConnectivityHash,vertices=h.Surface.Vertices.Count,faces=h.Surface.Faces.Count,regions=h.Surface.Vertices.Select(x=>x.Region).Distinct().Count(),components=h.Surface.Components.Select(x=>new{x.Id,x.Kind,faces=x.FaceIndices.Count})},skeleton=new{h.Skeleton.SkeletonId,joints=h.Skeleton.Joints.Count,h.Skeleton.RestPoseId,h.Skeleton.SkinningConvention},landmarks=new{total=h.Landmarks.Count,surface=h.Landmarks.OfType<SurfaceLandmark>().Count(),joint=h.Landmarks.OfType<JointLandmark>().Count()},measurements=HumanoidMeasurements.Evaluate(h),morphs=h.MorphChannels,attachments=h.Attachments.Select(x=>x.Id),validation};File.WriteAllText(path,JsonSerializer.Serialize(evidence,HumanoidArtifactIO.JsonOptions));+}+static string? Value(string[] args,string name){var i=Array.IndexOf(args,name);return i>=0&&i+1<args.Length?args[i+1]:null;}+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.X0\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>");