Skip to content

Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel

fixed unit conversion and more display bugs.

Yuechen Li0701d2cedeca
diff --git a/Aetheris.Kernel.Core.Tests/Step242/Step242LengthUnitTests.cs b/Aetheris.Kernel.Core.Tests/Step242/Step242LengthUnitTests.cs
new file mode 100644
index 00000000..52dda560
--- /dev/null
+++ b/Aetheris.Kernel.Core.Tests/Step242/Step242LengthUnitTests.cs
@@ -0,0 +1,66 @@
+using Aetheris.Kernel.Core.Brep;
+using Aetheris.Kernel.Core.Step242;
+
+namespace Aetheris.Kernel.Core.Tests.Step242;
+
+public sealed class Step242LengthUnitTests
+{
+ private const string MillimetreUnit = "(LENGTH_UNIT()NAMED_UNIT(*)SI_UNIT(.MILLI.,.METRE.))";
+
+ [Fact]
+ public void Import_InchDeclaredFile_IsScaledToMillimetres()
+ {
+ var box = BrepPrimitives.CreateBox(2d, 2d, 2d).Value;
+ var millimetreText = Step242Exporter.ExportBody(box).Value;
+ Assert.Contains(MillimetreUnit, millimetreText);
+ var inchText = ReplaceLengthUnit(millimetreText, MillimetreUnit,
+ "(CONVERSION_BASED_UNIT('INCH',#9001)LENGTH_UNIT()NAMED_UNIT(#9002))",
+ "#9001=LENGTH_MEASURE_WITH_UNIT(LENGTH_MEASURE(0.0254),#9003);\n#9002=DIMENSIONAL_EXPONENTS(1.,0.,0.,0.,0.,0.,0.);\n#9003=(LENGTH_UNIT()NAMED_UNIT(*)SI_UNIT($,.METRE.));\n");
+
+ var millimetreExtent = MaxAbsVertexCoordinate(Step242Importer.ImportBody(millimetreText).Value);
+ var inchExtent = MaxAbsVertexCoordinate(Step242Importer.ImportBody(inchText).Value);
+
+ Assert.Equal(millimetreExtent * 25.4d, inchExtent, 9);
+ }
+
+ [Fact]
+ public void Import_MetreDeclaredFile_IsScaledToMillimetres()
+ {
+ var box = BrepPrimitives.CreateBox(2d, 2d, 2d).Value;
+ var millimetreText = Step242Exporter.ExportBody(box).Value;
+ var metreText = millimetreText.Replace(MillimetreUnit, "(LENGTH_UNIT()NAMED_UNIT(*)SI_UNIT($,.METRE.))", StringComparison.Ordinal);
+
+ var millimetreExtent = MaxAbsVertexCoordinate(Step242Importer.ImportBody(millimetreText).Value);
+ var metreExtent = MaxAbsVertexCoordinate(Step242Importer.ImportBody(metreText).Value);
+
+ Assert.Equal(millimetreExtent * 1000d, metreExtent, 9);
+ }
+
+ [Fact]
+ public void Parse_FileWithoutUnitContext_IsLeftUnscaled()
+ {
+ var parse = Step242SubsetParser.Parse(Step242FixtureCorpus.CylindricalFaceWithTwoLoops);
+
+ Assert.True(parse.IsSuccess);
+ Assert.Equal(1d, parse.Value.SourceMillimetresPerUnit);
+ }
+
+ private static string ReplaceLengthUnit(string text, string oldUnit, string newUnit, string extraEntities)
+ {
+ var replaced = text.Replace(oldUnit, newUnit, StringComparison.Ordinal);
+ var endsec = replaced.LastIndexOf("ENDSEC;", StringComparison.Ordinal);
+ return replaced.Insert(endsec, extraEntities);
+ }
+
+ private static double MaxAbsVertexCoordinate(BrepBody body)
+ {
+ var max = 0d;
+ foreach (var vertex in body.Topology.Vertices)
+ {
+ Assert.True(body.TryGetVertexPoint(vertex.Id, out var point));
+ max = double.Max(max, double.Max(double.Abs(point.X), double.Max(double.Abs(point.Y), double.Abs(point.Z))));
+ }
+
+ return max;
+ }
+}
diff --git a/Aetheris.Kernel.Core/Brep/Tessellation/BrepDisplayTessellator.cs b/Aetheris.Kernel.Core/Brep/Tessellation/BrepDisplayTessellator.cs
index b694705a..57e54e58 100644
--- a/Aetheris.Kernel.Core/Brep/Tessellation/BrepDisplayTessellator.cs
+++ b/Aetheris.Kernel.Core/Brep/Tessellation/BrepDisplayTessellator.cs
@@ -1609,7 +1609,11 @@ public static class BrepDisplayTessellator
var maxY = points.Max(point => point.Y);
var maxZ = points.Max(point => point.Z);
var diagonal = new Vector3D(maxX - minX, maxY - minY, maxZ - minZ).Length;
- return System.Math.Max(1e-5d, diagonal * 1e-4d);
+ // Vendor STEP files carry edge curves that only agree with their face surfaces to the exporting CAD
+ // system's accuracy; measured on a McMaster bevel pinion the worst edge-to-surface gap is about 7 microns.
+ // Loop samples that close to a surface are still unambiguously on it, so the tolerance has a 20 micron
+ // floor (model units are mm after import normalization).
+ return System.Math.Max(2e-2d, diagonal * 1e-4d);
}
private static Vector3D EvaluateBSplineNormal(BSplineSurfaceWithKnots surface, double u, double v)
diff --git a/Aetheris.Kernel.Core/Step242/Step242LengthUnitNormalizer.cs b/Aetheris.Kernel.Core/Step242/Step242LengthUnitNormalizer.cs
new file mode 100644
index 00000000..1fb78a70
--- /dev/null
+++ b/Aetheris.Kernel.Core/Step242/Step242LengthUnitNormalizer.cs
@@ -0,0 +1,187 @@
+using System.Globalization;
+
+namespace Aetheris.Kernel.Core.Step242;
+
+/// <summary>
+/// Aetheris works in millimetres internally (the exporter always writes SI milli-metre). STEP files may declare any
+/// length unit (McMaster/SolidWorks parts are frequently in inches), so the parsed entity list is rewritten once, right
+/// after parsing, so that every length-valued attribute is expressed in millimetres. Angles are handled separately by
+/// <see cref="Step242ParsedDocument.PlaneAngleToRadiansScale"/>.
+/// </summary>
+internal static class Step242LengthUnitNormalizer
+{
+ private const double MillimetresPerMetre = 1000d;
+
+ // Entity name -> zero-based argument indices holding a length (radii, semi-axes, vector magnitudes).
+ private static readonly Dictionary<string, int[]> ScalarLengthArguments = new(StringComparer.OrdinalIgnoreCase)
+ {
+ ["VECTOR"] = [1],
+ ["CIRCLE"] = [2],
+ ["ELLIPSE"] = [2, 3],
+ ["HYPERBOLA"] = [2, 3],
+ ["PARABOLA"] = [2],
+ ["CYLINDRICAL_SURFACE"] = [2],
+ ["CONICAL_SURFACE"] = [2],
+ ["SPHERICAL_SURFACE"] = [2],
+ ["TOROIDAL_SURFACE"] = [2, 3],
+ ["DEGENERATE_TOROIDAL_SURFACE"] = [2, 3],
+ ["OFFSET_SURFACE"] = [2],
+ ["OFFSET_CURVE_3D"] = [2],
+ };
+
+ /// <summary>Resolves the millimetres-per-file-unit factor from the first length unit found in a unit-assigned context.</summary>
+ public static double ResolveMillimetresPerUnit(IReadOnlyList<Step242ParsedEntity> entities)
+ {
+ var byId = entities.ToDictionary(e => e.Id);
+ foreach (var entity in entities)
+ {
+ var context = Step242SubsetDecoder.TryGetConstructor(entity.Instance, "GLOBAL_UNIT_ASSIGNED_CONTEXT");
+ if (context is null || context.Arguments.Count == 0 || context.Arguments[0] is not Step242ListValue units)
+ {
+ continue;
+ }
+
+ foreach (var unit in units.Items)
+ {
+ if (unit is Step242EntityReference reference
+ && TryResolveMetresPerUnit(byId, reference.TargetId, new HashSet<int>(), out var metres))
+ {
+ return metres * MillimetresPerMetre;
+ }
+ }
+ }
+
+ return 1d;
+ }
+
+ public static IReadOnlyList<Step242ParsedEntity> Normalize(IReadOnlyList<Step242ParsedEntity> entities, double scale)
+ {
+ if (double.Abs(scale - 1d) <= 1e-12d || scale <= 0d || !double.IsFinite(scale))
+ {
+ return entities;
+ }
+
+ return entities.Select(entity => entity with { Instance = ScaleInstance(entity.Instance, scale) }).ToList();
+ }
+
+ private static Step242EntityInstance ScaleInstance(Step242EntityInstance instance, double scale)
+ {
+ switch (instance)
+ {
+ case Step242SimpleEntityInstance simple:
+ return simple with { Constructor = ScaleConstructor(simple.Constructor, scale) };
+ case Step242ComplexEntityInstance complex:
+ return complex with { Constructors = complex.Constructors.Select(c => ScaleConstructor(c, scale)).ToList() };
+ default:
+ return instance;
+ }
+ }
+
+ private static Step242EntityConstructor ScaleConstructor(Step242EntityConstructor constructor, double scale)
+ {
+ var name = constructor.Name;
+ var arguments = constructor.Arguments;
+
+ if (string.Equals(name, "CARTESIAN_POINT", StringComparison.OrdinalIgnoreCase))
+ {
+ // 2D cartesian points are parametric (pcurve) coordinates, not lengths.
+ if (arguments.Count >= 2 && arguments[1] is Step242ListValue coordinates && coordinates.Items.Count == 3)
+ {
+ return constructor with { Arguments = Replace(arguments, 1, ScaleNumberList(coordinates, scale)) };
+ }
+
+ return constructor;
+ }
+
+ if (string.Equals(name, "COORDINATES_LIST", StringComparison.OrdinalIgnoreCase))
+ {
+ if (arguments.Count >= 3 && arguments[2] is Step242ListValue tuples)
+ {
+ var scaled = tuples.Items.Select(item => item is Step242ListValue tuple ? ScaleNumberList(tuple, scale) : item).ToList();
+ return constructor with { Arguments = Replace(arguments, 2, new Step242ListValue(scaled)) };
+ }
+
+ return constructor;
+ }
+
+ if (ScalarLengthArguments.TryGetValue(name, out var indices))
+ {
+ var updated = arguments.ToList();
+ foreach (var index in indices)
+ {
+ if (index < updated.Count && updated[index] is Step242NumberValue number)
+ {
+ updated[index] = new Step242NumberValue(number.Value * scale);
+ }
+ }
+
+ return constructor with { Arguments = updated };
+ }
+
+ return constructor;
+ }
+
+ private static Step242ListValue ScaleNumberList(Step242ListValue list, double scale)
+ => new(list.Items.Select(item => item is Step242NumberValue number ? new Step242NumberValue(number.Value * scale) : item).ToList());
+
+ private static IReadOnlyList<Step242Value> Replace(IReadOnlyList<Step242Value> arguments, int index, Step242Value value)
+ {
+ var updated = arguments.ToList();
+ updated[index] = value;
+ return updated;
+ }
+
+ private static bool TryResolveMetresPerUnit(Dictionary<int, Step242ParsedEntity> byId, int unitEntityId, HashSet<int> visited, out double metres)
+ {
+ metres = default;
+ if (!visited.Add(unitEntityId) || !byId.TryGetValue(unitEntityId, out var unitEntity))
+ {
+ return false;
+ }
+
+ if (Step242SubsetDecoder.TryGetConstructor(unitEntity.Instance, "LENGTH_UNIT") is null)
+ {
+ return false;
+ }
+
+ var si = Step242SubsetDecoder.TryGetConstructor(unitEntity.Instance, "SI_UNIT");
+ if (si is not null
+ && si.Arguments.Count >= 2
+ && si.Arguments[1] is Step242EnumValue unitName
+ && string.Equals(unitName.Value, "METRE", StringComparison.Ordinal))
+ {
+ metres = si.Arguments[0] is Step242EnumValue prefix ? PrefixScale(prefix.Value) : 1d;
+ return metres > 0d;
+ }
+
+ var conversion = Step242SubsetDecoder.TryGetConstructor(unitEntity.Instance, "CONVERSION_BASED_UNIT");
+ if (conversion is null
+ || conversion.Arguments.Count < 2
+ || conversion.Arguments[1] is not Step242EntityReference measureRef
+ || !byId.TryGetValue(measureRef.TargetId, out var measureEntity))
+ {
+ return false;
+ }
+
+ var measure = measureEntity.Instance.PrimaryConstructor;
+ if (measure.Arguments.Count < 2
+ || measure.Arguments[0] is not Step242TypedValue typed
+ || typed.Arguments.Count != 1
+ || typed.Arguments[0] is not Step242NumberValue magnitude
+ || measure.Arguments[1] is not Step242EntityReference baseUnitRef
+ || !TryResolveMetresPerUnit(byId, baseUnitRef.TargetId, visited, out var baseMetres))
+ {
+ return false;
+ }
+
+ metres = magnitude.Value * baseMetres;
+ return metres > 0d;
+ }
+
+ private static double PrefixScale(string prefix) => prefix switch
+ {
+ "EXA" => 1e18, "PETA" => 1e15, "TERA" => 1e12, "GIGA" => 1e9, "MEGA" => 1e6, "KILO" => 1e3,
+ "HECTO" => 1e2, "DECA" => 1e1, "DECI" => 1e-1, "CENTI" => 1e-2, "MILLI" => 1e-3, "MICRO" => 1e-6,
+ "NANO" => 1e-9, "PICO" => 1e-12, "FEMTO" => 1e-15, "ATTO" => 1e-18, _ => 1d,
+ };
+}
diff --git a/Aetheris.Kernel.Core/Step242/Step242SubsetParser.cs b/Aetheris.Kernel.Core/Step242/Step242SubsetParser.cs
index 7cf28a1a..2541a9b1 100644
--- a/Aetheris.Kernel.Core/Step242/Step242SubsetParser.cs
+++ b/Aetheris.Kernel.Core/Step242/Step242SubsetParser.cs
@@ -55,7 +55,9 @@ internal static class Step242SubsetParser
return Failure($"Duplicate entity id #{duplicateId.Key} detected.", "Parser.Semantics");
}
- return KernelResult<Step242ParsedDocument>.Success(new Step242ParsedDocument(entities));
+ var millimetresPerUnit = Step242LengthUnitNormalizer.ResolveMillimetresPerUnit(entities);
+ var normalizedEntities = Step242LengthUnitNormalizer.Normalize(entities, millimetresPerUnit);
+ return KernelResult<Step242ParsedDocument>.Success(new Step242ParsedDocument(normalizedEntities, millimetresPerUnit));
}
private static KernelResult<Step242ParsedDocument> Failure(string message, string source)
@@ -580,9 +582,10 @@ internal sealed class Step242ParsedDocument
{
private readonly Dictionary<int, Step242ParsedEntity> _entitiesById;
- public Step242ParsedDocument(IReadOnlyList<Step242ParsedEntity> entities)
+ public Step242ParsedDocument(IReadOnlyList<Step242ParsedEntity> entities, double sourceMillimetresPerUnit = 1d)
{
Entities = entities;
+ SourceMillimetresPerUnit = sourceMillimetresPerUnit;
_entitiesById = entities.ToDictionary(e => e.Id);
PlaneAngleToRadiansScale = ResolvePlaneAngleToRadiansScale();
}
@@ -591,6 +594,9 @@ internal sealed class Step242ParsedDocument
public double PlaneAngleToRadiansScale { get; }
+ /// <summary>Millimetres per length unit declared by the source file; entity lengths have already been multiplied by this.</summary>
+ public double SourceMillimetresPerUnit { get; }
+
public KernelResult<Step242ParsedEntity> TryGetEntity(int id, string? expectedName = null)
{
if (!_entitiesById.TryGetValue(id, out var entity))
diff --git a/testdata/step242/manifests/nist.v0.report.json b/testdata/step242/manifests/nist.v0.report.json
index 545ca59c..1e0a79e7 100644
--- a/testdata/step242/manifests/nist.v0.report.json
+++ b/testdata/step242/manifests/nist.v0.report.json
@@ -97,7 +97,7 @@
"edges": 331,
"faces": 156
},
- "canonicalSha256": "0ee52c68b6a1a34ec19b2a7ef4f04bec4a41e86c64ea5a279803d47e1d61c3b9"
+ "canonicalSha256": "677c52bac98905f0a8ca68b5163d641820aa6ee633016181d96a6db0be6912c6"
},
{
"fileId": "testdata_step242_nist_FTC_nist_ftc_06_asme1_ap242-e2",
@@ -137,7 +137,7 @@
"edges": 871,
"faces": 306
},
- "canonicalSha256": "19a9d4cc2f393da4cd6a2e25fc68aa4da6c1e7b670871cf09096070fe86938ee"
+ "canonicalSha256": "8d8fb42d6a9cbd874509dcdc71b3ed4579fe26240c8298874e5b7bebb138953b"
},
{
"fileId": "testdata_step242_nist_FTC_nist_ftc_08_asme1_ap242-e1-tg",
@@ -317,7 +317,7 @@
"edges": 392,
"faces": 125
},
- "canonicalSha256": "785c5df0baba6407bd716620d9cb7a11666a2207f8f56cb714b1719baf66d4f7"
+ "canonicalSha256": "ba2caabdb9ce89cea76a8789f45fbede49396f281a01301be6aa7076a84e473a"
},
{
"fileId": "testdata_step242_nist_STC_nist_stc_10_asme1_ap242-e2",