diff --git a/CHANGELOG.md b/CHANGELOG.md index 99f3b5a..7273f32 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,12 @@ All notable changes to the `IfcIO` library are documented in this file. ## [Unreleased] ### Fixed +- Swept-solid import applies the profile, solid and object placements to inclined extrusions, revolutions and + both Boolean operands. IFC re-export preserves world placement and multiple swept body items when a single + parametric solid cannot represent the result. Mesh export distinguishes open surfaces from closed shells. +- IFC export rejects unsupported compound or incomplete Boolean bodies instead of silently dropping operations + or writing missing operand references. +- IFC4 `IfcTriangulatedFaceSet` import reads nested coordinate and triangle lists, including `PnIndex`. - STEP import indexes entities by type once, reuses repeated type names, and reads typed arguments from lazy slices. - Faceted face import triangulates concave polygons and holes, keeps disjoint bounds as separate regions, and omits invalid contours rather than substituting zero coordinates. diff --git a/docs/public-api.md b/docs/public-api.md index 0352841..d1d1348 100644 --- a/docs/public-api.md +++ b/docs/public-api.md @@ -49,6 +49,19 @@ among generated product GlobalIds and does not rewrite explicit GlobalIds. For faceted faces, the reader triangulates planar concave bounds and holes without adding vertices. Disjoint bounds remain separate regions. Invalid contours or faces that exceed the triangulation work limit are omitted. +Imported meshes use world coordinates. If a swept body cannot be represented by one equivalent parametric +solid, the reader keeps its placed mesh instead; IFC export writes that mesh rather than a partial or +misplaced solid. Boolean operands also use placed meshes where necessary. Applying arbitrary solid-to-solid +Boolean operations to the mesh is not supported; the mesher clips against half-spaces only. +IFC export rejects compound Boolean bodies and Boolean results with missing operands rather than +writing a mesh that drops the operations or an invalid STEP reference. + +The reader uses standard IFC sweep coordinates. Older IfcIO exports that encoded a tilted authored extrusion +without its profile frame, or a translated revolution's axis in absolute coordinates, may reopen differently. +New exports write the extrusion frame and the revolution's local axis explicitly. +Revolutions whose axis does not lie in the authored profile plane are exported as a mesh. +For non-tessellated mesh export, disconnected closed shells are written separately and open meshes use a surface model. + ## Import & Export | Type | Description | diff --git a/docs/scene-adapter.md b/docs/scene-adapter.md index b702ecd..ef6731f 100644 --- a/docs/scene-adapter.md +++ b/docs/scene-adapter.md @@ -79,10 +79,6 @@ rebases them, for example on `ComputeBounds().Center`, before narrowing them to ## Limits -- **IFC4 tessellated geometry is not read.** IfcIO's reader returns no mesh for `IfcTriangulatedFaceSet`, including - the one IfcIO itself writes for IFC4 models: the point and index lists lose their inner brackets while being parsed, - so no triangle is found. Such elements are in the scene without geometry and reported as `no-geometry`. Verified - with an IFC4 model saved by IfcIO and opened again; a test pins this behaviour. - Mapped items (`IfcMappedItem`) are baked into each element's world mesh, so shared geometry is not shared in the scene. - IfcIO places an element in a storey only through `IfcRelContainedInSpatialStructure`. Elements contained in the site diff --git a/src/IfcIO/Core/StepWriter.cs b/src/IfcIO/Core/StepWriter.cs index 5a0c73e..603a1b9 100644 --- a/src/IfcIO/Core/StepWriter.cs +++ b/src/IfcIO/Core/StepWriter.cs @@ -102,11 +102,9 @@ public static string Real(double v) public static string RealExact(double v) { string text = v.ToString("G15", CultureInfo.InvariantCulture); - if (!text.Contains('.') && !text.Contains('E') && !text.Contains('e')) - { - text += "."; - } - return text; + if (text.Contains('.')) return text; + int exponent = text.IndexOf('E'); + return exponent < 0 ? text + "." : text.Insert(exponent, "."); } /// diff --git a/src/IfcIO/Geometry/CsgTypes.cs b/src/IfcIO/Geometry/CsgTypes.cs index 6120b58..a38ad37 100644 --- a/src/IfcIO/Geometry/CsgTypes.cs +++ b/src/IfcIO/Geometry/CsgTypes.cs @@ -91,7 +91,8 @@ public sealed class IfcBooleanResult /// /// True if this represents an IFCBOOLEANCLIPPINGRESULT (difference with a half-space solid). /// - public bool IsClippingResult => SecondHalfSpace is not null || Operator == IfcBooleanOperator.Difference; + public bool IsClippingResult => Operator == IfcBooleanOperator.Difference + && SecondHalfSpace is not null && (FirstSolid is not null || FirstRevolved is not null); public IfcBooleanResult() { } diff --git a/src/IfcIO/Geometry/SweptSolidTypes.cs b/src/IfcIO/Geometry/SweptSolidTypes.cs index 820b018..7414528 100644 --- a/src/IfcIO/Geometry/SweptSolidTypes.cs +++ b/src/IfcIO/Geometry/SweptSolidTypes.cs @@ -123,35 +123,31 @@ public IfcExtrudedAreaSolid(IfcProfileDef profile, double depth, IfcVector3? pos Direction = direction ?? IfcVector3.UnitZ; } + // The authoring API defines the profile in a plane perpendicular to Direction. + internal IfcTransform GetProfileFrame() + { + var z = Direction.Normalized(); + if (z.Length < 1e-6) z = IfcVector3.UnitZ; + + var x = Math.Abs(z.Z) > 0.999 + ? IfcVector3.Cross(IfcVector3.Cross(z, IfcVector3.UnitX).Normalized(), z).Normalized() + : IfcVector3.Cross(IfcVector3.UnitZ, z).Normalized(); + return new IfcTransform(x, IfcVector3.Cross(z, x).Normalized(), z, Position); + } + /// /// Converts the extruded swept solid into a triangulated 3D polygon mesh. /// public IfcMesh ToMesh(int segments = 16, string meshName = "ExtrudedSolid") { - var boundary2D = Profile.GetBoundaryPoints(segments); + var boundary2D = GetCounterClockwiseBoundary(Profile.GetBoundaryPoints(segments)); int n = boundary2D.Count; if (n < 3) { return IfcMesh.Create(0, meshName, Array.Empty(), Array.Empty()); } - // Construct orthonormal coordinate frame - var dirNorm = Direction.Normalized(); - if (dirNorm.Length < 1e-6) dirNorm = IfcVector3.UnitZ; - - IfcVector3 xAxis, yAxis; - if (Math.Abs(dirNorm.Z) > 0.999) - { - xAxis = IfcVector3.UnitX; - yAxis = IfcVector3.Cross(dirNorm, xAxis).Normalized(); - xAxis = IfcVector3.Cross(yAxis, dirNorm).Normalized(); - } - else - { - xAxis = IfcVector3.Cross(IfcVector3.UnitZ, dirNorm).Normalized(); - yAxis = IfcVector3.Cross(dirNorm, xAxis).Normalized(); - } - + var frame = GetProfileFrame(); var vertices = new List(n * 2); var indices = new List(n * 6 + (n - 2) * 6); @@ -159,11 +155,11 @@ public IfcMesh ToMesh(int segments = 16, string meshName = "ExtrudedSolid") for (int i = 0; i < n; i++) { var p2 = boundary2D[i]; - var basePt = Position + (p2.X * xAxis) + (p2.Y * yAxis); + var basePt = frame.Origin + (p2.X * frame.X) + (p2.Y * frame.Y); vertices.Add(basePt); } - var extrudeOffset = dirNorm * Depth; + var extrudeOffset = frame.Z * Depth; for (int i = 0; i < n; i++) { vertices.Add(vertices[i] + extrudeOffset); @@ -212,6 +208,22 @@ public IfcMesh ToMesh(int segments = 16, string meshName = "ExtrudedSolid") internal readonly record struct Vector2D(double X, double Y); + internal static IReadOnlyList GetCounterClockwiseBoundary(IReadOnlyList points) + { + int count = points.Count; + while (count > 1 && points[0] == points[count - 1]) count--; + if (count < 3) return points.Take(count).ToArray(); + + double area = 0; + var origin = points[0]; + for (int i = 1; i < count - 1; i++) + area += IfcVector3.Cross(points[i] - origin, points[i + 1] - origin).Z; + + if (area < 0) + return [points[0], ..points.Skip(1).Take(count - 1).Reverse()]; + return count == points.Count ? points : points.Take(count).ToArray(); + } + internal static List TriangulatePolygon(IReadOnlyList poly) { int n = poly.Count; @@ -378,7 +390,7 @@ public IfcRevolvedAreaSolid(IfcProfileDef profile, double angle = 2.0 * Math.PI, /// public IfcMesh ToMesh(int profileSegments = 16, int radialSegments = 24, string meshName = "RevolvedSolid") { - var boundary2D = Profile.GetBoundaryPoints(profileSegments); + var boundary2D = IfcExtrudedAreaSolid.GetCounterClockwiseBoundary(Profile.GetBoundaryPoints(profileSegments)); int n = boundary2D.Count; if (n < 3) { @@ -402,6 +414,14 @@ public IfcMesh ToMesh(int profileSegments = 16, int radialSegments = 24, string basePoints.Add(Position + new IfcVector3(p.X, p.Y, 0)); } + // The sweep can start on either side of the XY profile plane. Match the winding to its motion. + double normalVelocity = 0; + foreach (var point in basePoints) + { + double velocity = IfcVector3.Cross(axisDir, point - axisLoc).Z; + if (Math.Abs(velocity) > Math.Abs(normalVelocity)) normalVelocity = velocity; + } + var vertices = new List(ringCount * n); var indices = new List(); @@ -472,6 +492,11 @@ public IfcMesh ToMesh(int profileSegments = 16, int radialSegments = 24, string } } + if (normalVelocity * Angle < 0) + { + for (int i = 0; i < indices.Count; i += 3) + (indices[i + 1], indices[i + 2]) = (indices[i + 2], indices[i + 1]); + } return IfcMesh.Create(0, meshName, vertices, indices); } } diff --git a/src/IfcIO/IfcModel.MeshExport.cs b/src/IfcIO/IfcModel.MeshExport.cs new file mode 100644 index 0000000..b15aafa --- /dev/null +++ b/src/IfcIO/IfcModel.MeshExport.cs @@ -0,0 +1,100 @@ +using IfcIO.Core; +using IfcIO.Geometry; + +namespace IfcIO; + +public sealed partial class IfcModel +{ + private static (string Type, List Ids) WriteBodyMesh(StepWriter w, IfcMesh mesh, bool tessellate) + { + var parts = GetMeshParts(mesh); + if (parts.Count == 0) throw new InvalidDataException("Cannot write a mesh without valid triangles."); + + bool closed = parts.All(part => part.Closed); + if (tessellate) + return ("Tessellation", [WriteMeshTriangulatedFaceSet(w, mesh.Vertices, parts.SelectMany(p => p.Indices).ToArray(), closed)]); + + var shells = parts.Select(p => WriteMeshShell(w, mesh.Vertices, p.Indices, p.Closed)).ToList(); + return closed + ? ("Brep", shells.Select(id => w.Add("IFCFACETEDBREP", StepWriter.Ref(id))).ToList()) + : ("SurfaceModel", [w.Add("IFCSHELLBASEDSURFACEMODEL", StepWriter.List(shells.Select(StepWriter.Ref)))]); + } + + private static int WriteBooleanMesh(StepWriter w, IfcMesh mesh, bool tessellate) + { + var parts = GetMeshParts(mesh); + if (parts.Count == 0 || parts.Any(part => !part.Closed)) + throw new InvalidDataException("A Boolean mesh operand must be closed."); + if (tessellate) + return WriteMeshTriangulatedFaceSet(w, mesh.Vertices, parts.SelectMany(p => p.Indices).ToArray(), true); + if (parts.Count != 1) + throw new InvalidDataException("A faceted Boolean mesh operand must have one connected shell."); + return w.Add("IFCFACETEDBREP", StepWriter.Ref(WriteMeshShell(w, mesh.Vertices, parts[0].Indices, true))); + } + + private sealed class MeshPart + { + public List Indices { get; } = []; + public bool Closed { get; set; } = true; + } + + /// Groups triangles by shared edges. A closed shell requires paired, oppositely directed edges. + private static List GetMeshParts(IfcMesh mesh) + { + var parents = new int[mesh.TriangleCount]; + Array.Fill(parents, -1); + var edges = new Dictionary<(int, int), (int Face, int Count, int Balance)>(); + for (int i = 0; i < parents.Length; i++) + { + int a = mesh.Indices[i * 3], b = mesh.Indices[i * 3 + 1], c = mesh.Indices[i * 3 + 2]; + if ((uint)a >= (uint)mesh.Vertices.Count || (uint)b >= (uint)mesh.Vertices.Count + || (uint)c >= (uint)mesh.Vertices.Count || a == b || b == c || a == c) continue; + parents[i] = i; + JoinEdge(a, b, i); + JoinEdge(b, c, i); + JoinEdge(c, a, i); + } + + var byRoot = new Dictionary(); + for (int i = 0; i < parents.Length; i++) + { + if (parents[i] < 0) continue; + int root = Find(i); + if (!byRoot.TryGetValue(root, out var part)) + byRoot.Add(root, part = new MeshPart()); + part.Indices.Add(mesh.Indices[i * 3]); + part.Indices.Add(mesh.Indices[i * 3 + 1]); + part.Indices.Add(mesh.Indices[i * 3 + 2]); + } + foreach (var edge in edges.Values) + if (edge.Count != 2 || edge.Balance != 0) + byRoot[Find(edge.Face)].Closed = false; + return byRoot.Values.ToList(); + + int Find(int face) + { + while (parents[face] != face) + { + parents[face] = parents[parents[face]]; + face = parents[face]; + } + return face; + } + + void JoinEdge(int first, int second, int face) + { + bool forward = first < second; + var key = forward ? (first, second) : (second, first); + int sign = forward ? 1 : -1; + if (edges.TryGetValue(key, out var existing)) + { + parents[Find(face)] = Find(existing.Face); + edges[key] = (existing.Face, existing.Count + 1, existing.Balance + sign); + } + else + { + edges.Add(key, (face, 1, sign)); + } + } + } +} diff --git a/src/IfcIO/IfcModel.cs b/src/IfcIO/IfcModel.cs index 6bbc02f..e8bbf42 100644 --- a/src/IfcIO/IfcModel.cs +++ b/src/IfcIO/IfcModel.cs @@ -1858,7 +1858,9 @@ public static IfcModel Open(TextReader reader, string? modelName, IfcReadOptions int? shapeDefId = entity.GetRef(6); if (shapeDefId.HasValue && ResolveObjectPlacement(geometry, entity.GetRef(5)) is { } placement) { - var mesh = ParseGeometry(geometry, shapeDefId.Value, name, placement, out var mat, out var solid, out var revSolid, out var boolResult); + var mesh = ParseGeometry(geometry, shapeDefId.Value, name, placement, out var mat, out var solid, out var revSolid, + out var boolResult, out bool unwritableBooleanBody); + element.HasUnwritableBooleanBody = unwritableBooleanBody; if (mesh is not null) { element.Mesh = mesh; @@ -2373,7 +2375,7 @@ openElem is IfcOpeningElement opening && string? mpName = mpEnt.GetString(0); int? matId = mpEnt.GetRef(2); int? profId = mpEnt.GetRef(3); - var prof = ParseProfile(step, profId); + var prof = ParseProfile(step, profId, out _); if (prof is not null) { IfcMaterial? mat = (matId.HasValue && materialMap.TryGetValue(matId.Value, out var m)) ? m : null; @@ -2539,6 +2541,9 @@ private static bool IsIfc4x3Identifier(string? identifier) => private int WriteElementShape(StepWriter w, IfcElement element, int bodySubContextId, Dictionary styleCache, bool useTessellation) { + if (element.HasUnwritableBooleanBody && element.BooleanResult is null) + throw new InvalidDataException($"Element '{element.Name}' has a Boolean body that cannot be written without losing operands."); + int? styleId = null; var appearance = element.GetEffectiveMaterial(); if (appearance is not null) @@ -2559,9 +2564,9 @@ private int WriteElementShape(StepWriter w, IfcElement element, int bodySubConte $"$,$,({StepWriter.Ref(shapeRepId)})"); } - if (element.RevolvedSolid is not null) + if (element.RevolvedSolid is { } revolution && CanWriteRevolution(revolution)) { - int solidGeomId = WriteRevolvedAreaSolid(w, element.RevolvedSolid); + int solidGeomId = WriteRevolvedAreaSolid(w, revolution); if (styleId.HasValue) { w.Add("IFCSTYLEDITEM", $"{StepWriter.Ref(solidGeomId)},({StepWriter.Ref(styleId.Value)}),{StepWriter.Str(appearance?.Name)}"); @@ -2579,36 +2584,26 @@ private int WriteElementShape(StepWriter w, IfcElement element, int bodySubConte { w.Add("IFCSTYLEDITEM", $"{StepWriter.Ref(solidGeomId)},({StepWriter.Ref(styleId.Value)}),{StepWriter.Str(appearance?.Name)}"); } - string repType = element.BooleanResult.IsClippingResult ? "Clipping" : "CSG"; + string repType = CanWriteClipping(element.BooleanResult) ? "Clipping" : "CSG"; int shapeRepId = w.Add("IFCSHAPEREPRESENTATION", $"{StepWriter.Ref(bodySubContextId)},'Body',{StepWriter.Str(repType)},({StepWriter.Ref(solidGeomId)})"); return w.Add("IFCPRODUCTDEFINITIONSHAPE", $"$,$,({StepWriter.Ref(shapeRepId)})"); } - if (element.Mesh is not null && element.Mesh.Vertices.Count >= 3 && element.Mesh.Indices.Count >= 3) + var mesh = element.Mesh ?? element.RevolvedSolid?.ToMesh(); + if (mesh is not null && mesh.Vertices.Count >= 3 && mesh.Indices.Count >= 3) { - int geomId; - string repType; - - if (useTessellation) - { - geomId = WriteMeshTriangulatedFaceSet(w, element.Mesh.Vertices, element.Mesh.Indices); - repType = "Tessellation"; - } - else - { - geomId = WriteMeshFacetedBrep(w, element.Mesh.Vertices, element.Mesh.Indices); - repType = "Brep"; - } + var (repType, geomIds) = WriteBodyMesh(w, mesh, useTessellation); if (styleId.HasValue) { - w.Add("IFCSTYLEDITEM", $"{StepWriter.Ref(geomId)},({StepWriter.Ref(styleId.Value)}),{StepWriter.Str(appearance?.Name)}"); + foreach (int geomId in geomIds) + w.Add("IFCSTYLEDITEM", $"{StepWriter.Ref(geomId)},({StepWriter.Ref(styleId.Value)}),{StepWriter.Str(appearance?.Name)}"); } int shapeRepId = w.Add("IFCSHAPEREPRESENTATION", - $"{StepWriter.Ref(bodySubContextId)},'Body',{StepWriter.Str(repType)},({StepWriter.Ref(geomId)})"); + $"{StepWriter.Ref(bodySubContextId)},'Body',{StepWriter.Str(repType)},{StepWriter.List(geomIds.Select(StepWriter.Ref))}"); return w.Add("IFCPRODUCTDEFINITIONSHAPE", $"$,$,({StepWriter.Ref(shapeRepId)})"); } @@ -2686,12 +2681,10 @@ private int WriteBooleanResult(StepWriter w, IfcBooleanResult csg, bool useTesse int firstId = 0; if (csg.FirstSolid is not null) firstId = WriteExtrudedAreaSolid(w, csg.FirstSolid); - else if (csg.FirstRevolved is not null) - firstId = WriteRevolvedAreaSolid(w, csg.FirstRevolved); - else if (csg.FirstMesh is not null) - firstId = useTessellation - ? WriteMeshTriangulatedFaceSet(w, csg.FirstMesh.Vertices, csg.FirstMesh.Indices) - : WriteMeshFacetedBrep(w, csg.FirstMesh.Vertices, csg.FirstMesh.Indices); + else if (csg.FirstRevolved is { } revolution && CanWriteRevolution(revolution)) + firstId = WriteRevolvedAreaSolid(w, revolution); + else if ((csg.FirstMesh ?? csg.FirstRevolved?.ToMesh()) is { } firstMesh) + firstId = WriteBooleanMesh(w, firstMesh, useTessellation); int secondId = 0; if (csg.SecondHalfSpace is not null) @@ -2699,8 +2692,9 @@ private int WriteBooleanResult(StepWriter w, IfcBooleanResult csg, bool useTesse var hs = csg.SecondHalfSpace; var plane = hs.BaseSurface; int locPtId = w.Add("IFCCARTESIANPOINT", StepWriter.List(StepWriter.Real(plane.Location.X), StepWriter.Real(plane.Location.Y), StepWriter.Real(plane.Location.Z))); - int axisDirId = w.Add("IFCDIRECTION", StepWriter.List(StepWriter.Real(plane.Normal.X), StepWriter.Real(plane.Normal.Y), StepWriter.Real(plane.Normal.Z))); - int pl3dId = w.Add("IFCAXIS2PLACEMENT3D", $"{StepWriter.Ref(locPtId)},{StepWriter.Ref(axisDirId)},$"); + int axisDirId = WriteDirection(w, plane.Normal); + int refDirId = WriteDirection(w, FirstProjAxis(plane.Normal.Normalized(), null)); + int pl3dId = w.Add("IFCAXIS2PLACEMENT3D", $"{StepWriter.Ref(locPtId)},{StepWriter.Ref(axisDirId)},{StepWriter.Ref(refDirId)}"); int planeId = w.Add("IFCPLANE", StepWriter.Ref(pl3dId)); string flag = hs.AgreementFlag ? ".T." : ".F."; secondId = w.Add("IFCHALFSPACESOLID", $"{StepWriter.Ref(planeId)},{flag}"); @@ -2711,9 +2705,7 @@ private int WriteBooleanResult(StepWriter w, IfcBooleanResult csg, bool useTesse } else if (csg.SecondMesh is not null) { - secondId = useTessellation - ? WriteMeshTriangulatedFaceSet(w, csg.SecondMesh.Vertices, csg.SecondMesh.Indices) - : WriteMeshFacetedBrep(w, csg.SecondMesh.Vertices, csg.SecondMesh.Indices); + secondId = WriteBooleanMesh(w, csg.SecondMesh, useTessellation); } string op = csg.Operator switch @@ -2723,28 +2715,49 @@ private int WriteBooleanResult(StepWriter w, IfcBooleanResult csg, bool useTesse _ => ".DIFFERENCE.", }; - string entityType = csg.IsClippingResult ? "IFCBOOLEANCLIPPINGRESULT" : "IFCBOOLEANRESULT"; + if (firstId == 0 || secondId == 0) + throw new InvalidDataException("Cannot write a Boolean result without both operands."); + + string entityType = CanWriteClipping(csg) ? "IFCBOOLEANCLIPPINGRESULT" : "IFCBOOLEANRESULT"; return w.Add(entityType, $"{op},{StepWriter.Ref(firstId)},{StepWriter.Ref(secondId)}"); } private int WriteExtrudedAreaSolid(StepWriter w, IfcExtrudedAreaSolid solid) { int profileId = WriteProfileDef(w, solid.Profile); + var frame = solid.GetProfileFrame(); int solidPtId = w.Add("IFCCARTESIANPOINT", StepWriter.List(StepWriter.Real(solid.Position.X), StepWriter.Real(solid.Position.Y), StepWriter.Real(solid.Position.Z))); - int solidPlacementId = w.Add("IFCAXIS2PLACEMENT3D", $"{StepWriter.Ref(solidPtId)},$,$"); - int dirId = w.Add("IFCDIRECTION", StepWriter.List(StepWriter.Real(solid.Direction.X), StepWriter.Real(solid.Direction.Y), StepWriter.Real(solid.Direction.Z))); + string axis = "$", refDirection = "$"; + if (frame.Z != IfcVector3.UnitZ) + { + axis = StepWriter.Ref(WriteDirection(w, frame.Z)); + refDirection = StepWriter.Ref(WriteDirection(w, frame.X)); + } + int solidPlacementId = w.Add("IFCAXIS2PLACEMENT3D", $"{StepWriter.Ref(solidPtId)},{axis},{refDirection}"); + int dirId = WriteDirection(w, IfcVector3.UnitZ); return w.Add("IFCEXTRUDEDAREASOLID", $"{StepWriter.Ref(profileId)},{StepWriter.Ref(solidPlacementId)},{StepWriter.Ref(dirId)},{StepWriter.Real(solid.Depth)}"); } + private static int WriteDirection(StepWriter w, IfcVector3 direction) => + w.Add("IFCDIRECTION", StepWriter.List(StepWriter.RealExact(direction.X), StepWriter.RealExact(direction.Y), StepWriter.RealExact(direction.Z))); + + private static bool CanWriteRevolution(IfcRevolvedAreaSolid solid) => + solid.Axis.Location.Z == solid.Position.Z && solid.Axis.Axis.Z == 0 && solid.Axis.Axis != IfcVector3.Zero; + + private static bool CanWriteClipping(IfcBooleanResult result) => result.IsClippingResult + && (result.FirstSolid is not null || result.FirstRevolved is { } revolution && CanWriteRevolution(revolution)); + private int WriteRevolvedAreaSolid(StepWriter w, IfcRevolvedAreaSolid solid) { int profileId = WriteProfileDef(w, solid.Profile); int solidPtId = w.Add("IFCCARTESIANPOINT", StepWriter.List(StepWriter.Real(solid.Position.X), StepWriter.Real(solid.Position.Y), StepWriter.Real(solid.Position.Z))); int solidPlacementId = w.Add("IFCAXIS2PLACEMENT3D", $"{StepWriter.Ref(solidPtId)},$,$"); - int axisLocPtId = w.Add("IFCCARTESIANPOINT", StepWriter.List(StepWriter.Real(solid.Axis.Location.X), StepWriter.Real(solid.Axis.Location.Y), StepWriter.Real(solid.Axis.Location.Z))); - int axisDirId = w.Add("IFCDIRECTION", StepWriter.List(StepWriter.Real(solid.Axis.Axis.X), StepWriter.Real(solid.Axis.Axis.Y), StepWriter.Real(solid.Axis.Axis.Z))); + // The authored axis is absolute; IFC expresses it relative to Position. + var axisLocation = solid.Axis.Location - solid.Position; + int axisLocPtId = w.Add("IFCCARTESIANPOINT", StepWriter.List(StepWriter.Real(axisLocation.X), StepWriter.Real(axisLocation.Y), StepWriter.Real(axisLocation.Z))); + int axisDirId = WriteDirection(w, solid.Axis.Axis); int axisPlacementId = w.Add("IFCAXIS1PLACEMENT", $"{StepWriter.Ref(axisLocPtId)},{StepWriter.Ref(axisDirId)}"); double angle = AngleUnit == IfcPlaneAngleUnit.Degree ? solid.Angle * (180.0 / Math.PI) : solid.Angle; @@ -2801,7 +2814,7 @@ public void ChargeVertices(int count) /// /// Reads the product shape into one world-space mesh (all items of the body representation merged). - /// Parametric outputs describe the first item in its own coordinates, as before (no placement applied). + /// Parametric outputs are kept only when they represent the complete body in model coordinates. /// private static IfcMesh? ParseGeometry( GeometryReadContext ctx, @@ -2811,12 +2824,14 @@ public void ChargeVertices(int count) out IfcMaterial? material, out IfcExtrudedAreaSolid? solid, out IfcRevolvedAreaSolid? revolvedSolid, - out IfcBooleanResult? booleanResult) + out IfcBooleanResult? booleanResult, + out bool unwritableBooleanBody) { material = null; solid = null; revolvedSolid = null; booleanResult = null; + unwritableBooleanBody = false; var shapeDef = ctx.Step.Find(shapeDefId); if (shapeDef is null) return null; @@ -2831,17 +2846,27 @@ public void ChargeVertices(int count) foreach (var rep in reps.Where(IsBody).Concat(reps.Where(r => !IsBody(r)))) { IfcMaterial? repMaterial = null; - var mesh = ParseRepresentationItems(ctx, rep, meshName, ref repMaterial, out var parametric); + var mesh = ParseRepresentationItems(ctx, rep, meshName, ref repMaterial, out var parametric, out bool hasBoolean); if (mesh is null) continue; material = repMaterial; - if (parametric is { } body && ctx.KeepParametric) + booleanResult = parametric?.Boolean; + unwritableBooleanBody = hasBoolean && booleanResult is null; + if (parametric is { } body && ctx.KeepParametric && placement.IsTranslationOnly) { solid = body.Solid; + if (solid is not null) solid.Position += placement.Origin; revolvedSolid = body.Revolved; - booleanResult = body.Boolean; + if (revolvedSolid is not null) + { + revolvedSolid.Position += placement.Origin; + revolvedSolid.Axis.Location += placement.Origin; + } } + if (booleanResult is not null && !placement.IsIdentity) + PlaceBooleanOperands(booleanResult, placement); + var world = placement.ApplyTo(mesh); return IfcMesh.Create(world.Id, meshName, world.Vertices, world.Indices); } @@ -2855,9 +2880,11 @@ public void ChargeVertices(int count) StepEntity? repEnt, string meshName, ref IfcMaterial? material, - out ParametricBody? parametric) + out ParametricBody? parametric, + out bool hasBoolean) { parametric = null; + hasBoolean = false; if (repEnt is null) return null; var itemIds = repEnt.GetRefList(3); @@ -2872,7 +2899,8 @@ public void ChargeVertices(int count) if (mesh is null) continue; material ??= itemMaterial; ctx.ChargeVertices(mesh.Vertices.Count); - if (parts.Count == 0) parametric = itemParametric; + hasBoolean |= itemParametric?.Boolean is not null; + parametric = parts.Count == 0 ? itemParametric : null; parts.Add(mesh); } @@ -2906,10 +2934,11 @@ public void ChargeVertices(int count) if (mesh is not null) return mesh; // C/D. IFCEXTRUDEDAREASOLID / IFCREVOLVEDAREASOLID - var swept = ParseSweptSolid(step, itemEnt, meshName, ctx.RadiansPerAngleUnit, out var extruded, out var revolved, out _); + var swept = ParseSweptSolid(step, itemEnt, meshName, ctx.RadiansPerAngleUnit, out var extruded, out var revolved); if (swept is not null) { - parametric = new ParametricBody(extruded, revolved, null); + if (extruded is not null || revolved is not null) + parametric = new ParametricBody(extruded, revolved, null); return swept; } @@ -2941,51 +2970,48 @@ public void ChargeVertices(int count) } /// - /// Meshes an IfcExtrudedAreaSolid or IfcRevolvedAreaSolid in the coordinates of its representation and returns - /// its parametric form, which keeps only the Position location (as IfcModel stores and writes it). + /// Meshes a swept solid in representation coordinates and returns its parametric form + /// only when the public solid can reproduce that geometry. /// /// The STEP file that holds the solid and the entities it references. /// The IfcExtrudedAreaSolid or IfcRevolvedAreaSolid entity. /// The name given to the returned mesh. /// Conversion from project plane angle units to radians. - /// The parametric extrusion, or null when the entity is not an extrusion or cannot be read. - /// The parametric revolution, or null when the entity is not a revolution or cannot be read. - /// True when Position or the profile Position rotates, so the parametric form does not describe the mesh. + /// The equivalent parametric extrusion, if any. + /// The equivalent parametric revolution, if any. private static IfcMesh? ParseSweptSolid( StepFile step, StepEntity ent, string meshName, double radiansPerAngleUnit, out IfcExtrudedAreaSolid? extruded, - out IfcRevolvedAreaSolid? revolved, - out bool fullPlacement) + out IfcRevolvedAreaSolid? revolved) { extruded = null; revolved = null; - fullPlacement = false; bool isExtruded = ent.Type.Equals("IFCEXTRUDEDAREASOLID", StringComparison.OrdinalIgnoreCase); if (!isExtruded && !ent.Type.Equals("IFCREVOLVEDAREASOLID", StringComparison.OrdinalIgnoreCase)) return null; - var profile = ParseProfile(step, ent.GetRef(0)); + var profile = ParseProfile(step, ent.GetRef(0), out var profileRotation); if (profile is null) return null; var position = ParseAxis2Placement(step, ent.GetRef(1)); - var profileRotation = ParseProfileRotation(step, ent.GetRef(0)); - fullPlacement = !position.IsTranslationOnly || !profileRotation.IsIdentity; - - // shortcut: with a location-only Position the parametric solid's own meshing is used, so files written by - // IfcModel read back unchanged; it differs from IFC for non-+Z extrusion directions (profile frame) and - // for revolution axes away from the origin (Axis taken as absolute). Use the IFC path below for both if needed. if (isExtruded) { double depth = ent.GetReal(3) ?? 0.0; - extruded = new IfcExtrudedAreaSolid(profile, depth, position.Origin, ParseDirection(step, ent.GetRef(2))); - if (!fullPlacement) return extruded.ToMesh(16, meshName); + var direction = ParseOptionalDirection(step, ent.GetRef(2)) ?? IfcVector3.UnitZ; + if (direction == IfcVector3.UnitZ && profileRotation.IsIdentity) + { + var solid = new IfcExtrudedAreaSolid(profile, depth, position.Origin, position.Z); + var frame = solid.GetProfileFrame(); + if ((frame.X - position.X).Length <= 1e-9 && (frame.Y - position.Y).Length <= 1e-9) + { + extruded = solid; + return solid.ToMesh(16, meshName); + } + } - // IFC: profile in the XY plane of Position, swept along ExtrudedDirection (Position coordinates): - // extrude along local Z, then shear Z onto the direction. - var direction = ParseCoordinates(step.Find(ent.GetRef(2))).Normalized(); - if (direction == IfcVector3.Zero) direction = IfcVector3.UnitZ; + // IFC keeps the profile in the XY plane of Position. Sweep along local Z, then shear Z onto ExtrudedDirection. var shear = new IfcTransform(IfcVector3.UnitX, IfcVector3.UnitY, direction, IfcVector3.Zero); var local = new IfcExtrudedAreaSolid(profile, depth).ToMesh(16, meshName); return position.Multiply(shear).Multiply(profileRotation).ApplyTo(local); @@ -2993,10 +3019,15 @@ public void ChargeVertices(int count) double angle = ent.GetReal(3) is double fileAngle ? fileAngle * radiansPerAngleUnit : 2.0 * Math.PI; var axis = ParseAxis1Placement(step, ent.GetRef(2)); - revolved = new IfcRevolvedAreaSolid(profile, angle, position.Origin, axis); - if (!fullPlacement) return revolved.ToMesh(16, 24, meshName); + if (position.IsTranslationOnly && profileRotation.IsIdentity) + { + axis.Location += position.Origin; + revolved = new IfcRevolvedAreaSolid(profile, angle, position.Origin, axis); + return revolved.ToMesh(16, 24, meshName); + } - // shortcut: a rotated profile Position is ignored for revolved solids (rare); rotate the profile points first if a model needs it. + if (!profileRotation.IsIdentity) + profile = new IfcArbitraryClosedProfileDef(profile.GetBoundaryPoints().Select(profileRotation.Apply), profile.ProfileName); return position.ApplyTo(new IfcRevolvedAreaSolid(profile, angle, IfcVector3.Zero, axis).ToMesh(16, 24, meshName)); } @@ -3022,7 +3053,7 @@ private static (IfcMesh? Mesh, IfcMaterial? Material) ParseMappedRepresentation( } IfcMaterial? material = null; - var mesh = ParseRepresentationItems(ctx, ctx.Step.Find(mapEnt.GetRef(1)), meshName, ref material, out _); + var mesh = ParseRepresentationItems(ctx, ctx.Step.Find(mapEnt.GetRef(1)), meshName, ref material, out _, out _); var result = (mesh is null ? null : ParseAxis2Placement(ctx.Step, mapEnt.GetRef(0)).ApplyTo(mesh), material); ctx.MapsInProgress.Remove(mapId); @@ -3087,15 +3118,14 @@ private static IfcTransform ParseAxis2Placement(StepFile step, int? placementId) var location = ParseCoordinates(step.Find(ent.GetRef(0))); if (ent.Type.Equals("IFCAXIS2PLACEMENT2D", StringComparison.OrdinalIgnoreCase)) { - var x2 = FirstProjAxis(IfcVector3.UnitZ, ParseOptionalVector(step, ent.GetRef(1))); + var x2 = FirstProjAxis(IfcVector3.UnitZ, ParseOptionalDirection(step, ent.GetRef(1))); return new IfcTransform(x2, IfcVector3.Cross(IfcVector3.UnitZ, x2), IfcVector3.UnitZ, location); } if (!ent.Type.Equals("IFCAXIS2PLACEMENT3D", StringComparison.OrdinalIgnoreCase)) return IfcTransform.Identity; - var z = ParseOptionalVector(step, ent.GetRef(1))?.Normalized() ?? IfcVector3.UnitZ; - if (z == IfcVector3.Zero) z = IfcVector3.UnitZ; - var x = FirstProjAxis(z, ParseOptionalVector(step, ent.GetRef(2))); + var z = ParseOptionalDirection(step, ent.GetRef(1)) ?? IfcVector3.UnitZ; + var x = FirstProjAxis(z, ParseOptionalDirection(step, ent.GetRef(2))); return new IfcTransform(x, IfcVector3.Cross(z, x), z, location); } @@ -3110,8 +3140,8 @@ private static IfcTransform ParseCartesianTransformationOperator(StepFile step, bool is3D = ent.Type.Contains("3D", StringComparison.OrdinalIgnoreCase); bool nonUniform = ent.Type.EndsWith("NONUNIFORM", StringComparison.OrdinalIgnoreCase); - var axis1 = ParseOptionalVector(step, ent.GetRef(0)); - var axis2 = ParseOptionalVector(step, ent.GetRef(1)); + var axis1 = ParseOptionalDirection(step, ent.GetRef(0)); + var axis2 = ParseOptionalDirection(step, ent.GetRef(1)); var origin = ParseCoordinates(step.Find(ent.GetRef(2))); double scale = ent.GetReal(3) ?? 1.0; @@ -3119,8 +3149,7 @@ private static IfcTransform ParseCartesianTransformationOperator(StepFile step, double scaleY = scale, scaleZ = scale; if (is3D) { - z = ParseOptionalVector(step, ent.GetRef(4))?.Normalized() ?? IfcVector3.UnitZ; - if (z == IfcVector3.Zero) z = IfcVector3.UnitZ; + z = ParseOptionalDirection(step, ent.GetRef(4)) ?? IfcVector3.UnitZ; if (nonUniform) { scaleY = ent.GetReal(5) ?? scale; @@ -3153,19 +3182,13 @@ private static IfcVector3 FirstProjAxis(IfcVector3 z, IfcVector3? reference) return IfcVector3.UnitY; } - /// Rotation of a parameterized profile about its Position (ParseProfile already applies the Position offset). - private static IfcTransform ParseProfileRotation(StepFile step, int? profileId) + private static IfcVector3? ParseOptionalDirection(StepFile step, int? id) { - var profEnt = step.Find(profileId); - if (profEnt is null) return IfcTransform.Identity; - var placement = ParseAxis2Placement(step, profEnt.GetRef(2)); - return placement.Multiply(IfcTransform.Translation(-placement.Origin)); - } - - private static IfcVector3? ParseOptionalVector(StepFile step, int? id) - { - var ent = step.Find(id); - return ent is null ? null : ParseCoordinates(ent); + var direction = ParseCoordinates(step.Find(id)); + double scale = Math.Max(Math.Abs(direction.X), Math.Max(Math.Abs(direction.Y), Math.Abs(direction.Z))); + if (scale == 0 || !double.IsFinite(scale)) return null; + // Direction ratios are scale-free, including values too small or large to normalize directly. + return new IfcVector3(direction.X / scale, direction.Y / scale, direction.Z / scale).Normalized(); } /// Coordinates of an IfcCartesianPoint or IfcDirection; missing components are 0. @@ -3294,45 +3317,73 @@ private static int WritePlaneAngleUnit(StepWriter w, IfcPlaneAngleUnit unit) if (ptListEnt is null) return null; var vertices = new List(); - string rawCoords = ptListEnt.GetRaw(0) ?? string.Empty; - - foreach (var tuple in StepEntity.ParseArguments(rawCoords.Trim('(', ')'))) + foreach (var tuple in ParseStepList(ptListEnt.GetRaw(0))) { - var parts = StepEntity.ParseArguments(tuple.Trim('(', ')')); - double x = parts.Count > 0 && double.TryParse(parts[0], NumberStyles.Float, CultureInfo.InvariantCulture, out double px) ? px : 0.0; - double y = parts.Count > 1 && double.TryParse(parts[1], NumberStyles.Float, CultureInfo.InvariantCulture, out double py) ? py : 0.0; - double z = parts.Count > 2 && double.TryParse(parts[2], NumberStyles.Float, CultureInfo.InvariantCulture, out double pz) ? pz : 0.0; + var parts = ParseStepList(tuple); + if (parts.Count != 3 || !TryCoordinate(parts[0], out double x) + || !TryCoordinate(parts[1], out double y) || !TryCoordinate(parts[2], out double z)) return null; vertices.Add(new IfcVector3(x, y, z)); } + var pointNumbers = ParseStepList(itemEnt.GetRaw(4)); + // Before IFC4 Addendum 2 this attribute was NormalIndex (a list of triplets). + if (pointNumbers.Count > 0 && pointNumbers[0].StartsWith('(')) + pointNumbers.Clear(); var indices = new List(); - string rawTriangles = itemEnt.GetRaw(3) ?? string.Empty; - foreach (var triTuple in StepEntity.ParseArguments(rawTriangles.Trim('(', ')'))) + foreach (var triTuple in ParseStepList(itemEnt.GetRaw(3))) { - var parts = StepEntity.ParseArguments(triTuple.Trim('(', ')')); - if (parts.Count >= 3) + var parts = ParseStepList(triTuple); + if (parts.Count == 3 && TryVertexIndex(parts[0], out int i0) + && TryVertexIndex(parts[1], out int i1) && TryVertexIndex(parts[2], out int i2)) { - if (int.TryParse(parts[0], NumberStyles.Integer, CultureInfo.InvariantCulture, out int i0) && - int.TryParse(parts[1], NumberStyles.Integer, CultureInfo.InvariantCulture, out int i1) && - int.TryParse(parts[2], NumberStyles.Integer, CultureInfo.InvariantCulture, out int i2)) - { - // STEP 1-based to 0-based - indices.Add(i0 - 1); - indices.Add(i1 - 1); - indices.Add(i2 - 1); - } + indices.Add(i0); + indices.Add(i1); + indices.Add(i2); } } if (vertices.Count >= 3 && indices.Count >= 3) { + var remap = new int[vertices.Count]; + foreach (int index in indices) remap[index] = 1; + int count = 0; + for (int i = 0; i < vertices.Count; i++) + { + if (remap[i] == 0) continue; + remap[i] = count; + vertices[count++] = vertices[i]; + } + if (count != vertices.Count) + { + vertices.RemoveRange(count, vertices.Count - count); + for (int i = 0; i < indices.Count; i++) indices[i] = remap[indices[i]]; + } return IfcMesh.Create(itemEnt.Id, meshName, vertices, indices); } + + static bool TryCoordinate(string text, out double value) => + double.TryParse(text, NumberStyles.Float, CultureInfo.InvariantCulture, out value) && double.IsFinite(value); + + bool TryVertexIndex(string text, out int index) + { + index = 0; + if (!int.TryParse(text, NumberStyles.Integer, CultureInfo.InvariantCulture, out int number) || number <= 0) + return false; + if (pointNumbers.Count > 0 && (number > pointNumbers.Count + || !int.TryParse(pointNumbers[number - 1], NumberStyles.Integer, CultureInfo.InvariantCulture, out number))) + return false; + if (number <= 0 || number > vertices.Count) return false; + index = number - 1; + return true; + } } return null; } + private static List ParseStepList(string? raw) => + raw is { Length: >= 2 } && raw[0] == '(' && raw[^1] == ')' ? StepEntity.ParseArguments(raw[1..^1]) : []; + private static IfcBooleanResult? ParseBooleanResult(StepFile step, StepEntity itemEnt, double radiansPerAngleUnit) { string? opStr = itemEnt.GetRaw(0); @@ -3353,21 +3404,11 @@ private static int WritePlaneAngleUnit(StepWriter w, IfcPlaneAngleUnit unit) if (firstEnt is not null) { var sweptMesh = ParseSweptSolid(step, firstEnt, "BooleanOperand", radiansPerAngleUnit, - out var extruded, out var revolved, out bool fullPlacement); - if (sweptMesh is null) - { - boolResult.FirstMesh = ParseMeshEntity(step, firstEnt); - } - else if (fullPlacement) - { - // The parametric operand cannot hold a rotated Position: keep the placed mesh (also written back as such). - boolResult.FirstMesh = sweptMesh; - } - else - { - boolResult.FirstSolid = extruded; - boolResult.FirstRevolved = revolved; - } + out var extruded, out var revolved); + boolResult.FirstSolid = extruded; + boolResult.FirstRevolved = revolved; + if (extruded is null && revolved is null) + boolResult.FirstMesh = sweptMesh ?? ParseMeshEntity(step, firstEnt); } } @@ -3380,21 +3421,13 @@ private static int WritePlaneAngleUnit(StepWriter w, IfcPlaneAngleUnit unit) { boolResult.SecondHalfSpace = ParseHalfSpaceSolid(step, secondOpId.Value); } - else if (secondEnt.Type.Equals("IFCEXTRUDEDAREASOLID", StringComparison.OrdinalIgnoreCase)) - { - int? profId = secondEnt.GetRef(0); - var prof = ParseProfile(step, profId); - if (prof is not null) - { - var pos = ParsePlacement3D(step, secondEnt.GetRef(1)); - var dir = ParseDirection(step, secondEnt.GetRef(2)); - double depth = secondEnt.GetReal(3) ?? 0.0; - boolResult.SecondSolid = new IfcExtrudedAreaSolid(prof, depth, pos, dir); - } - } else { - boolResult.SecondMesh = ParseMeshEntity(step, secondEnt); + var sweptMesh = ParseSweptSolid(step, secondEnt, "BooleanOperand", radiansPerAngleUnit, + out var extruded, out _); + boolResult.SecondSolid = extruded; + if (extruded is null) + boolResult.SecondMesh = sweptMesh ?? ParseMeshEntity(step, secondEnt); } } } @@ -3402,25 +3435,42 @@ private static int WritePlaneAngleUnit(StepWriter w, IfcPlaneAngleUnit unit) return boolResult; } + private static void PlaceBooleanOperands(IfcBooleanResult result, IfcTransform placement) + { + // The exporter writes identity product placements, so both operands need the same world transform. + if (placement.IsTranslationOnly) + { + if (result.FirstSolid is { } first) first.Position += placement.Origin; + if (result.SecondSolid is { } second) second.Position += placement.Origin; + if (result.FirstRevolved is { } revolved) + { + revolved.Position += placement.Origin; + revolved.Axis.Location += placement.Origin; + } + } + else + { + result.FirstMesh ??= result.FirstSolid?.ToMesh() ?? result.FirstRevolved?.ToMesh(); + result.SecondMesh ??= result.SecondSolid?.ToMesh(); + result.FirstSolid = null; + result.FirstRevolved = null; + result.SecondSolid = null; + } + if (result.FirstMesh is { } firstMesh) result.FirstMesh = placement.ApplyTo(firstMesh); + if (result.SecondMesh is { } secondMesh) result.SecondMesh = placement.ApplyTo(secondMesh); + + if (result.SecondHalfSpace?.BaseSurface is { } plane) + result.SecondHalfSpace.BaseSurface = new IfcPlane(placement.Apply(plane.Location), placement.ApplyVector(plane.Normal)); + } + private static IfcPlane? ParsePlane(StepFile step, int? planeId) { if (!planeId.HasValue) return null; var planeEnt = step.Find(planeId.Value); if (planeEnt is null) return null; - int? pl3dId = planeEnt.GetRef(0); - var loc = ParsePlacement3D(step, pl3dId); - var normal = IfcVector3.UnitZ; - if (pl3dId.HasValue) - { - var plEnt = step.Find(pl3dId.Value); - if (plEnt is not null) - { - int? axisDirId = plEnt.GetRef(1); - if (axisDirId.HasValue) normal = ParseDirection(step, axisDirId); - } - } - return new IfcPlane(loc, normal); + var placement = ParseAxis2Placement(step, planeEnt.GetRef(0)); + return new IfcPlane(placement.Origin, placement.Z); } private static IfcHalfSpaceSolid? ParseHalfSpaceSolid(StepFile step, int? halfSpaceId) @@ -3437,38 +3487,38 @@ private static int WritePlaneAngleUnit(StepWriter w, IfcPlaneAngleUnit unit) return new IfcHalfSpaceSolid(plane, flag); } - private static IfcProfileDef? ParseProfile(StepFile step, int? profileId) + private static IfcProfileDef? ParseProfile(StepFile step, int? profileId, out IfcTransform rotation) { - if (!profileId.HasValue) return null; - var profEnt = step.Find(profileId.Value); + rotation = IfcTransform.Identity; + var profEnt = step.Find(profileId); if (profEnt is null) return null; string pName = profEnt.GetString(1) ?? "Profile"; + if (profEnt.Type.Equals("IFCARBITRARYCLOSEDPROFILEDEF", StringComparison.OrdinalIgnoreCase)) + { + var pts = ParsePolylinePoints(step, profEnt.GetRef(2)); + return new IfcArbitraryClosedProfileDef(pts, pName); + } + + var placement = ParseAxis2Placement(step, profEnt.GetRef(2)); + var pos2d = placement.Origin; + // The parameterized profile already includes its offset. Rotate about that offset, not about (0,0). + rotation = placement.Multiply(IfcTransform.Translation(-pos2d)); if (profEnt.Type.Equals("IFCRECTANGLEPROFILEDEF", StringComparison.OrdinalIgnoreCase)) { double xDim = profEnt.GetReal(3) ?? 0.0; double yDim = profEnt.GetReal(4) ?? 0.0; - var pos2d = ParsePlacement2D(step, profEnt.GetRef(2)); return new IfcRectangleProfileDef(xDim, yDim, pos2d, pName); } if (profEnt.Type.Equals("IFCCIRCLEPROFILEDEF", StringComparison.OrdinalIgnoreCase)) { double radius = profEnt.GetReal(3) ?? 0.0; - var pos2d = ParsePlacement2D(step, profEnt.GetRef(2)); return new IfcCircleProfileDef(radius, pos2d, pName); } - if (profEnt.Type.Equals("IFCARBITRARYCLOSEDPROFILEDEF", StringComparison.OrdinalIgnoreCase)) - { - int? curveId = profEnt.GetRef(2); - var pts = ParsePolylinePoints(step, curveId); - return new IfcArbitraryClosedProfileDef(pts, pName); - } - if (profEnt.Type.Equals("IFCISHAPEPROFILEDEF", StringComparison.OrdinalIgnoreCase)) { - var pos2d = ParsePlacement2D(step, profEnt.GetRef(2)); double overallWidth = profEnt.GetReal(3) ?? 0.0; double overallDepth = profEnt.GetReal(4) ?? 0.0; double webThickness = profEnt.GetReal(5) ?? 0.0; @@ -3479,7 +3529,6 @@ private static int WritePlaneAngleUnit(StepWriter w, IfcPlaneAngleUnit unit) if (profEnt.Type.Equals("IFCLSHAPEPROFILEDEF", StringComparison.OrdinalIgnoreCase)) { - var pos2d = ParsePlacement2D(step, profEnt.GetRef(2)); double depth = profEnt.GetReal(3) ?? 0.0; double width = profEnt.GetReal(4) ?? depth; double thickness = profEnt.GetReal(5) ?? 0.0; @@ -3489,7 +3538,6 @@ private static int WritePlaneAngleUnit(StepWriter w, IfcPlaneAngleUnit unit) if (profEnt.Type.Equals("IFCUSHAPEPROFILEDEF", StringComparison.OrdinalIgnoreCase)) { - var pos2d = ParsePlacement2D(step, profEnt.GetRef(2)); double depth = profEnt.GetReal(3) ?? 0.0; double flangeWidth = profEnt.GetReal(4) ?? 0.0; double webThickness = profEnt.GetReal(5) ?? 0.0; @@ -3511,64 +3559,10 @@ private static IfcAxis1Placement ParseAxis1Placement(StepFile step, int? axisPla int? dirId = ent.GetRef(1); var loc = ParseCoordinates(step.Find(locId)); - var dir = ParseDirection(step, dirId); + var dir = ParseOptionalDirection(step, dirId) ?? IfcVector3.UnitZ; return new IfcAxis1Placement(loc, dir); } - private static IfcVector3 ParsePlacement2D(StepFile step, int? placementId) - { - if (!placementId.HasValue) return IfcVector3.Zero; - var plEnt = step.Find(placementId.Value); - if (plEnt is null) return IfcVector3.Zero; - - int? ptId = plEnt.GetRef(0); - if (!ptId.HasValue) return IfcVector3.Zero; - var ptEnt = step.Find(ptId.Value); - if (ptEnt is null) return IfcVector3.Zero; - - string coordStr = ptEnt.GetRaw(0) ?? string.Empty; - var coords = StepEntity.ParseArguments(coordStr.Trim('(', ')')); - double x = 0.0, y = 0.0; - if (coords.Count > 0 && double.TryParse(coords[0], NumberStyles.Float, CultureInfo.InvariantCulture, out double cx)) x = cx; - if (coords.Count > 1 && double.TryParse(coords[1], NumberStyles.Float, CultureInfo.InvariantCulture, out double cy)) y = cy; - return new IfcVector3(x, y, 0); - } - - private static IfcVector3 ParsePlacement3D(StepFile step, int? placementId) - { - if (!placementId.HasValue) return IfcVector3.Zero; - var plEnt = step.Find(placementId.Value); - if (plEnt is null) return IfcVector3.Zero; - - int? ptId = plEnt.GetRef(0); - if (!ptId.HasValue) return IfcVector3.Zero; - var ptEnt = step.Find(ptId.Value); - if (ptEnt is null) return IfcVector3.Zero; - - string coordStr = ptEnt.GetRaw(0) ?? string.Empty; - var coords = StepEntity.ParseArguments(coordStr.Trim('(', ')')); - double x = 0.0, y = 0.0, z = 0.0; - if (coords.Count > 0 && double.TryParse(coords[0], NumberStyles.Float, CultureInfo.InvariantCulture, out double cx)) x = cx; - if (coords.Count > 1 && double.TryParse(coords[1], NumberStyles.Float, CultureInfo.InvariantCulture, out double cy)) y = cy; - if (coords.Count > 2 && double.TryParse(coords[2], NumberStyles.Float, CultureInfo.InvariantCulture, out double cz)) z = cz; - return new IfcVector3(x, y, z); - } - - private static IfcVector3 ParseDirection(StepFile step, int? dirId) - { - if (!dirId.HasValue) return IfcVector3.UnitZ; - var dirEnt = step.Find(dirId.Value); - if (dirEnt is null) return IfcVector3.UnitZ; - - string raw = dirEnt.GetRaw(0) ?? string.Empty; - var parts = StepEntity.ParseArguments(raw.Trim('(', ')')); - double x = 0.0, y = 0.0, z = 1.0; - if (parts.Count > 0 && double.TryParse(parts[0], NumberStyles.Float, CultureInfo.InvariantCulture, out double dx)) x = dx; - if (parts.Count > 1 && double.TryParse(parts[1], NumberStyles.Float, CultureInfo.InvariantCulture, out double dy)) y = dy; - if (parts.Count > 2 && double.TryParse(parts[2], NumberStyles.Float, CultureInfo.InvariantCulture, out double dz)) z = dz; - return new IfcVector3(x, y, z); - } - private static List ParsePolylinePoints(StepFile step, int? curveId) { var result = new List(); @@ -3631,7 +3625,7 @@ private static string ExtractNominalValue(string? rawVal) private static bool IsBimProductType(string type) => BimProductTypes.Contains(type); - private static int WriteMeshTriangulatedFaceSet(StepWriter w, IReadOnlyList vertices, IReadOnlyList indices) + private static int WriteMeshTriangulatedFaceSet(StepWriter w, IReadOnlyList vertices, int[] indices, bool closed) { var coords = new StringBuilder(); for (int v = 0; v < vertices.Count; v++) @@ -3647,7 +3641,7 @@ private static int WriteMeshTriangulatedFaceSet(StepWriter w, IReadOnlyList 0) coordIndex.Append(','); @@ -3657,16 +3651,17 @@ private static int WriteMeshTriangulatedFaceSet(StepWriter w, IReadOnlyList vertices, IReadOnlyList indices) + private static int WriteMeshShell(StepWriter w, IReadOnlyList vertices, List indices, bool closed) { - var pointIds = new int[vertices.Count]; - for (int v = 0; v < vertices.Count; v++) + var pointIds = new Dictionary(); + int PointId(int index) { - var pt = vertices[v]; - pointIds[v] = w.Add("IFCCARTESIANPOINT", + if (pointIds.TryGetValue(index, out int id)) return id; + var pt = vertices[index]; + return pointIds[index] = w.Add("IFCCARTESIANPOINT", StepWriter.List(StepWriter.Real(pt.X), StepWriter.Real(pt.Y), StepWriter.Real(pt.Z))); } @@ -3677,19 +3672,13 @@ private static int WriteMeshFacetedBrep(StepWriter w, IReadOnlyList int i1 = indices[i + 1]; int i2 = indices[i + 2]; - if ((uint)i0 >= (uint)pointIds.Length || (uint)i1 >= (uint)pointIds.Length || (uint)i2 >= (uint)pointIds.Length) - { - continue; - } - int loopId = w.Add("IFCPOLYLOOP", - StepWriter.List(StepWriter.Ref(pointIds[i0]), StepWriter.Ref(pointIds[i1]), StepWriter.Ref(pointIds[i2]))); + StepWriter.List(StepWriter.Ref(PointId(i0)), StepWriter.Ref(PointId(i1)), StepWriter.Ref(PointId(i2)))); int boundId = w.Add("IFCFACEOUTERBOUND", $"{StepWriter.Ref(loopId)},.T."); faceIds.Add(w.Add("IFCFACE", StepWriter.List(StepWriter.Ref(boundId)))); } - int shellId = w.Add("IFCCLOSEDSHELL", StepWriter.List(faceIds.Select(StepWriter.Ref))); - return w.Add("IFCFACETEDBREP", StepWriter.Ref(shellId)); + return w.Add(closed ? "IFCCLOSEDSHELL" : "IFCOPENSHELL", StepWriter.List(faceIds.Select(StepWriter.Ref))); } private readonly record struct SurfaceStyleKey(string Name, double R, double G, double B, double Alpha); diff --git a/src/IfcIO/Model/IfcModelTypes.cs b/src/IfcIO/Model/IfcModelTypes.cs index 36ad8bf..689b6c8 100644 --- a/src/IfcIO/Model/IfcModelTypes.cs +++ b/src/IfcIO/Model/IfcModelTypes.cs @@ -348,6 +348,7 @@ public class IfcElement public IfcExtrudedAreaSolid? Solid { get; set; } public IfcRevolvedAreaSolid? RevolvedSolid { get; set; } public IfcBooleanResult? BooleanResult { get; set; } + internal bool HasUnwritableBooleanBody { get; set; } private IfcMaterial? _material; /// The assigned material, or the surface style when no material is assigned. public IfcMaterial? Material { get => _material ?? SurfaceMaterial; set => _material = value; } diff --git a/src/IfcIO/Patch/IfcPatch.cs b/src/IfcIO/Patch/IfcPatch.cs index 0898aa7..163f90f 100644 --- a/src/IfcIO/Patch/IfcPatch.cs +++ b/src/IfcIO/Patch/IfcPatch.cs @@ -311,6 +311,7 @@ private static IfcElement CloneElement(IfcElement source, int newId) Solid = source.Solid, RevolvedSolid = source.RevolvedSolid, BooleanResult = source.BooleanResult, + HasUnwritableBooleanBody = source.HasUnwritableBooleanBody, }; foreach (var pset in source.PropertySets) diff --git a/tests/IfcIO.Scene.Tests/IfcSceneReaderTests.cs b/tests/IfcIO.Scene.Tests/IfcSceneReaderTests.cs index 7df9302..c906eea 100644 --- a/tests/IfcIO.Scene.Tests/IfcSceneReaderTests.cs +++ b/tests/IfcIO.Scene.Tests/IfcSceneReaderTests.cs @@ -428,10 +428,8 @@ public void Read_WorkSchedule_BecomesScheduleWithElements() } [Fact] - public void Read_Ifc4TriangulatedFaceSet_IsReportedWithoutGeometry() + public void Read_Ifc4TriangulatedFaceSet_ConvertsGeometry() { - // Documented limit: IfcIO's reader returns no mesh for IfcTriangulatedFaceSet, even the one it writes itself. - // When this test fails, IfcIO reads it, and the limit in docs/scene-adapter.md goes. var model = IfcModel.Create("Tessellated", IfcSchema.Ifc4); model.AddMesh("Slab", Mm(Triangle), [0, 1, 2], ifcType: "IFCSLAB"); using var writer = new StringWriter(); @@ -440,8 +438,8 @@ public void Read_Ifc4TriangulatedFaceSet_IsReportedWithoutGeometry() var result = Valid(Read(OpenText(writer.ToString()))); - Assert.Empty(result.Document.Geometries); - Assert.Equal("no-geometry", Assert.Single(result.Diagnostics).Code); + Assert.Equal([0, 1, 2], Assert.Single(result.Document.Geometries).Indices); + Assert.Empty(result.Diagnostics); } [IfcFileFact] @@ -478,8 +476,6 @@ private static IfcModel OpenText(string ifc) return IfcModel.Open(reader); } - // Models are saved as IFC2x3 (faceted breps) unless a test needs IFC4: IfcIO does not read back the - // IfcTriangulatedFaceSet it writes for IFC4. private static IfcModel SaveAndOpen(IfcModel model) { using var writer = new StringWriter(); diff --git a/tests/IfcIO.Tests/IfcModelTests.cs b/tests/IfcIO.Tests/IfcModelTests.cs index 13ec9b1..bd7c4ae 100644 --- a/tests/IfcIO.Tests/IfcModelTests.cs +++ b/tests/IfcIO.Tests/IfcModelTests.cs @@ -268,7 +268,7 @@ public void StepReader_ParsesGeneratedStepFile() Assert.NotEmpty(step.Entities); Assert.Single(step.OfType("IFCPROJECT")); Assert.Single(step.OfType("IFCCOLUMN")); - Assert.Single(step.OfType("IFCFACETEDBREP")); + Assert.Single(step.OfType("IFCSHELLBASEDSURFACEMODEL")); } [Fact] @@ -285,6 +285,7 @@ public void IfcModel_Ifc4Schema_EmitsIfc4HeaderAndTessellation() Assert.Contains("FILE_SCHEMA(('IFC4'));", ifc); Assert.Contains("DesignTransferView", ifc); Assert.Contains("IFCTRIANGULATEDFACESET(", ifc); + Assert.Equal(".F.", Assert.Single(StepReader.Read(new StringReader(ifc)).OfType("IFCTRIANGULATEDFACESET")).GetRaw(2)); Assert.Contains("IFCCARTESIANPOINTLIST3D(", ifc); Assert.Contains("'Tessellation'", ifc); } diff --git a/tests/IfcIO.Tests/PlacementGeometryTests.cs b/tests/IfcIO.Tests/PlacementGeometryTests.cs index 8f81692..aef2dfd 100644 --- a/tests/IfcIO.Tests/PlacementGeometryTests.cs +++ b/tests/IfcIO.Tests/PlacementGeometryTests.cs @@ -2,6 +2,7 @@ using System.Globalization; using System.Text; using System.Text.Json; +using IfcIO.Core; using IfcIO.Exporters; using IfcIO.Geometry; using IfcIO.Model; @@ -187,26 +188,264 @@ public void Open_RotatedExtrusionAndProfile_PlacesPipeInWorldCoordinates() var pipe = Element(model, "Pipe"); Assert.Equal("IFCFLOWSEGMENT", pipe.IfcType); Assert.NotNull(pipe.Mesh); + Assert.Null(pipe.Solid); var box = pipe.Mesh.BoundingBox; AssertPoints([new(1095, 2000, 2990), new(1105, 3000, 3010)], [box.Min, box.Max]); + } + + [Fact] + public void Open_ScaledDirectionRatios_PreservePlacement() + { + string ifc = BuildIfc(Millimetre) + .Replace("#33=IFCDIRECTION((0.,1.));", "#33=IFCDIRECTION((0.,1.E-200));", StringComparison.Ordinal) + .Replace("#31=IFCDIRECTION((0.,1.,0.));", "#31=IFCDIRECTION((0.,1.E200,0.));", StringComparison.Ordinal); + var mesh = Element(Open(ifc), "Pipe").Mesh!; + AssertPoints([new(1095, 2000, 2990), new(1105, 3000, 3010)], [mesh.BoundingBox.Min, mesh.BoundingBox.Max]); + } + + [Theory] + [InlineData("4.", 30, 38)] + [InlineData("-4.", 22, 30)] + public void Open_InclinedExtrusion_KeepsProfileInPlacementPlane(string zDirection, double minZ, double maxZ) + { + string ifc = BuildIfc(Millimetre) + .Replace("#201=IFCLOCALPLACEMENT(#61,#202);", "#201=IFCLOCALPLACEMENT($,#202);", StringComparison.Ordinal) + .Replace("#206=IFCEXTRUDEDAREASOLID(#207,#209,#30,1000.);", + $"#206=IFCEXTRUDEDAREASOLID(#207,#209,#211,10.); #211=IFCDIRECTION((0.,3.,{zDirection}));", StringComparison.Ordinal) + .Replace("#209=IFCAXIS2PLACEMENT3D(#204,#32,#31);", + "#209=IFCAXIS2PLACEMENT3D(#212,$,$); #212=IFCCARTESIANPOINT((10.,20.,30.));", StringComparison.Ordinal) + .Replace("#208=IFCAXIS2PLACEMENT2D(#210,#33);", "#208=IFCAXIS2PLACEMENT2D(#210,$);", StringComparison.Ordinal); + + var mesh = Element(Open(ifc), "Pipe").Mesh!; + AssertPoints([new(0, 15, minZ), new(20, 31, maxZ)], [mesh.BoundingBox.Min, mesh.BoundingBox.Max]); + Assert.All(mesh.Vertices.Take(4), point => Assert.Equal(30, point.Z, 9)); + var cap = mesh.Indices.Skip(24).Take(3).Select(i => mesh.Vertices[i]).ToArray(); + Assert.True(IfcVector3.Dot(IfcVector3.Cross(cap[1] - cap[0], cap[2] - cap[0]), + mesh.Vertices[4] - mesh.Vertices[0]) < 0); + } + + [Theory] + [InlineData(false, false, 13, 24, 11, 24, 28)] + [InlineData(true, false, 6, 23, 6, 21, 28)] + [InlineData(false, true, 16, 25, 11, 25, 25)] + [InlineData(true, true, 5, 26, 5, 21, 25)] + public void Open_Revolution_AppliesProfileAndSolidPlacementsBeforeObjectPlacement( + bool rotateSolid, bool rotateProfile, double startX, double startY, double endX, double endY, double endZ) + { + string ifc = BuildIfc(Millimetre) + .Replace("#206=IFCEXTRUDEDAREASOLID(#207,#209,#30,1000.);", + "#206=IFCREVOLVEDAREASOLID(#207,#214,#211,1.5707963267948966); #211=IFCAXIS1PLACEMENT(#213,#31);", StringComparison.Ordinal) + .Replace("#207=IFCRECTANGLEPROFILEDEF(.AREA.,$,#208,20.,10.);", "#207=IFCRECTANGLEPROFILEDEF(.AREA.,$,#208,2.,4.);", StringComparison.Ordinal) + .Replace("#208=IFCAXIS2PLACEMENT2D(#210,#33);", + $"#208=IFCAXIS2PLACEMENT2D(#212,{(rotateProfile ? "#33" : "$")}); #212=IFCCARTESIANPOINT((4.,6.));", StringComparison.Ordinal) + .Replace("#209=IFCAXIS2PLACEMENT3D(#204,#32,#31);", + $"#209=IFCAXIS2PLACEMENT3D(#204,#32,#31); #213=IFCCARTESIANPOINT((1.,0.,0.)); #214=IFCAXIS2PLACEMENT3D(#215,$,{(rotateSolid ? "#31" : "$")}); #215=IFCCARTESIANPOINT((10.,20.,30.));", + StringComparison.Ordinal); + + // The last ring is 90 degrees about the solid-local Y axis through (1,0,0). + // The element's parent chain then takes (x,y,z) to (1100-y,2000+x,3000+z). + var mesh = Element(Open(ifc), "Pipe").Mesh!; + AssertPoints([new(1100 - startY, 2000 + startX, 3030), new(1100 - endY, 2000 + endX, 3000 + endZ)], + [mesh.Vertices[0], mesh.Vertices[96]]); + var cap = mesh.Indices.Skip(24 * 4 * 6).Take(3).Select(i => mesh.Vertices[i]).ToArray(); + Assert.True(IfcVector3.Cross(cap[1] - cap[0], cap[2] - cap[0]).Z > 0); + } - // The parametric solid keeps the item's own definition, as before. - Assert.NotNull(pipe.Solid); - Assert.Equal(1000.0, pipe.Solid.Depth); + [Theory] + [InlineData(IfcSchema.Ifc2x3)] + [InlineData(IfcSchema.Ifc4)] + public void SaveAndOpen_PlacedExtrusion_PreservesWorldGeometry(IfcSchema schema) + { + string ifc = BuildIfc(Millimetre); + if (schema == IfcSchema.Ifc4) + ifc = ifc.Replace("FILE_SCHEMA(('IFC2X3'));", "FILE_SCHEMA(('IFC4'));", StringComparison.Ordinal); + var model = Open(ifc); + + var mesh = Element(Open(model.ToStepString()), "Pipe").Mesh!; + Assert.Equal(12, mesh.Indices.Count / 3); + AssertPoints([new(1095, 2000, 2990), new(1105, 3000, 3010)], [mesh.BoundingBox.Min, mesh.BoundingBox.Max]); + } + + [Fact] + public void SaveAndOpen_MultipleSweptItems_PreservesBothMeshes() + { + string ifc = BuildIfc(Millimetre) + .Replace("#201=IFCLOCALPLACEMENT(#61,#202);", "#201=IFCLOCALPLACEMENT($,#202);", StringComparison.Ordinal) + .Replace("'SweptSolid',(#206));", "'SweptSolid',(#206,#211));", StringComparison.Ordinal) + .Replace("#206=IFCEXTRUDEDAREASOLID(#207,#209,#30,1000.);", + """ + #206=IFCEXTRUDEDAREASOLID(#207,#202,#30,1000.); + #211=IFCEXTRUDEDAREASOLID(#207,#212,#30,1000.); + #212=IFCAXIS2PLACEMENT3D(#213,$,$); + #213=IFCCARTESIANPOINT((100.,0.,0.)); + """, StringComparison.Ordinal) + .Replace("#208=IFCAXIS2PLACEMENT2D(#210,#33);", "#208=IFCAXIS2PLACEMENT2D(#210,$);", StringComparison.Ordinal); + var model = Open(ifc); + + string saved = model.ToStepString(); + var step = StepReader.Read(new StringReader(saved)); + var rep = Assert.Single(step.OfType("IFCSHAPEREPRESENTATION"), + e => e.GetString(2) == "Brep" && e.GetRefList(3).Count == 2); + Assert.All(rep.GetRefList(3), id => + { + var brep = step.Find(id)!; + Assert.Equal("IFCFACETEDBREP", brep.Type); + Assert.Equal(12, step.Find(brep.GetRef(0))!.GetRefList(0).Count); + }); + var mesh = Element(Open(saved), "Pipe").Mesh!; + Assert.Equal(24, mesh.TriangleCount); + AssertPoints([new(-10, -5, 0), new(110, 5, 1000)], [mesh.BoundingBox.Min, mesh.BoundingBox.Max]); + } + + [Fact] + public void SaveAndOpen_TranslatedExtrusion_KeepsWorldSpaceParametricSolid() + { + string ifc = BuildIfc(Millimetre) + .Replace("#201=IFCLOCALPLACEMENT(#61,#202);", "#201=IFCLOCALPLACEMENT(#41,#202);", StringComparison.Ordinal) + .Replace("IFCEXTRUDEDAREASOLID(#207,#209,#30,1000.)", "IFCEXTRUDEDAREASOLID(#207,#202,#30,1000.)", StringComparison.Ordinal) + .Replace("#208=IFCAXIS2PLACEMENT2D(#210,#33);", "#208=IFCAXIS2PLACEMENT2D(#210,$);", StringComparison.Ordinal); + var model = Open(ifc); + + var pipe = Element(model, "Pipe"); + Assert.Equal(new IfcVector3(1000, 2000, 0), pipe.Solid!.Position); + AssertPoints(pipe.Mesh!.Vertices.ToArray(), Element(Open(model.ToStepString()), "Pipe").Mesh!.Vertices); + } + + [Fact] + public void SaveAndOpen_TranslatedClipping_KeepsSweptOperandAndPlane() + { + string ifc = BuildIfc(Millimetre) + .Replace("#321=IFCLOCALPLACEMENT($,#322);", "#321=IFCLOCALPLACEMENT(#41,#322);", StringComparison.Ordinal) + .Replace("#607=IFCEXTRUDEDAREASOLID(#608,#209,#30,1000.);", + "#607=IFCEXTRUDEDAREASOLID(#608,#202,#30,1000.);", StringComparison.Ordinal); + + var model = Open(ifc); + var csg = Element(model, "Beam").BooleanResult!; + Assert.Equal(new(1000, 2000, 0), csg.FirstSolid!.Position); + Assert.Equal(new(1000, 2000, 5000), csg.SecondHalfSpace!.BaseSurface.Location); + + var reopened = Element(Open(model.ToStepString()), "Beam").BooleanResult!; + Assert.True(reopened.IsClippingResult); + Assert.Equal(csg.FirstSolid.Position, reopened.FirstSolid!.Position); + Assert.Equal(csg.SecondHalfSpace.BaseSurface.Location, reopened.SecondHalfSpace!.BaseSurface.Location); + } + + [Fact] + public void Save_MultipleBooleanItems_RejectsLosingOperands() + { + string ifc = BuildIfc(Millimetre) + .Replace("'Clipping',(#606));", "'CSG',(#606,#614));", StringComparison.Ordinal) + .Replace("#606=IFCBOOLEANCLIPPINGRESULT(.DIFFERENCE.,#607,#610);", + "#606=IFCBOOLEANRESULT(.DIFFERENCE.,#607,#206); #614=IFCBOOLEANRESULT(.UNION.,#206,#607);", StringComparison.Ordinal); + var model = Open(ifc); + Assert.True(Element(model, "Beam").Mesh!.TriangleCount > 0); + var error = Assert.Throws(() => model.ToStepString()); + Assert.Contains("losing operands", error.Message, StringComparison.Ordinal); + } + + [Fact] + public void Save_NestedUnsupportedBoolean_RejectsMissingOperandInsteadOfWritingRefZero() + { + string ifc = BuildIfc(Millimetre) + .Replace("'Clipping',(#606));", "'Clipping',(#614));", StringComparison.Ordinal) + .Replace("#606=IFCBOOLEANCLIPPINGRESULT(.DIFFERENCE.,#607,#610);", + "#606=IFCBOOLEANCLIPPINGRESULT(.DIFFERENCE.,#607,#610); #614=IFCBOOLEANCLIPPINGRESULT(.DIFFERENCE.,#606,#610);", + StringComparison.Ordinal); + + var error = Assert.Throws(() => Open(ifc).ToStepString()); + Assert.Contains("without both operands", error.Message, StringComparison.Ordinal); + } + + [Theory] + [InlineData(".UNION.")] + [InlineData(".DIFFERENCE.")] + public void Open_BooleanWithRotatedSecondExtrusion_PlacesOperand(string operation) + { + string ifc = BuildIfc(Millimetre).Replace("#606=IFCBOOLEANCLIPPINGRESULT(.DIFFERENCE.,#607,#610);", + $"#606=IFCBOOLEANRESULT({operation},#607,#206);", StringComparison.Ordinal); + var model = Open(ifc); + var boolean = Element(model, "Beam").BooleanResult!; + + Assert.Null(boolean.SecondSolid); + Assert.NotNull(boolean.SecondMesh); + AssertPoints([new(0, -5, -10), new(1000, 5, 10)], [boolean.SecondMesh.BoundingBox.Min, boolean.SecondMesh.BoundingBox.Max]); + + string saved = model.ToStepString(); + var reopened = Element(Open(saved), "Beam").BooleanResult!; + Assert.NotNull(reopened.SecondMesh); + AssertPoints([new(0, -5, -10), new(1000, 5, 10)], [reopened.SecondMesh.BoundingBox.Min, reopened.SecondMesh.BoundingBox.Max]); + Assert.Contains($"=IFCBOOLEANRESULT({operation},", saved, StringComparison.Ordinal); + } + + [Theory] + [InlineData(1, 2, 3)] + [InlineData(1, 0, 0)] + [InlineData(1, 1e-8, 0)] + public void SaveAndOpen_AuthoredExtrusion_WritesItsProfileFrame(double x, double y, double z) + { + var model = IfcModel.Create("Authored extrusion"); + var element = model.AddExtrudedRectangle("Extrusion", 20, 10, 30, new(10, 20, 30), new(x, y, z)); + string ifc = model.ToStepString(); + var step = StepReader.Read(new StringReader(ifc)); + var extrusion = Assert.Single(step.OfType("IFCEXTRUDEDAREASOLID")); + var placement = step.Find(extrusion.GetRef(1))!; + Assert.NotNull(placement.GetRef(1)); + if (y == 1e-8) + Assert.Equal("(1.,1.E-08,0.)", step.Find(placement.GetRef(1))!.GetRaw(0)); + Assert.Equal("(0.,0.,1.)", step.Find(extrusion.GetRef(2))!.GetRaw(0)); + var reopened = Element(Open(ifc), "Extrusion"); + + Assert.NotNull(reopened.Solid); + AssertPoints(element.GetEffectiveMesh()!.Vertices.ToArray(), reopened.Mesh!.Vertices, 1e-9); } [Fact] public void Open_ClippingResult_AppliesRotatedOperandPosition() { - var model = Open(BuildIfc(Millimetre)); + string ifc = BuildIfc(Millimetre).Replace("#600=IFCBEAM('CYvctVUKr0kugbFTf53O9L',$,'Beam',$,$,#321", + "#600=IFCBEAM('CYvctVUKr0kugbFTf53O9L',$,'Beam',$,$,#201", StringComparison.Ordinal) + .Replace("#613=IFCCARTESIANPOINT((0.,0.,5000.));", "#613=IFCCARTESIANPOINT((500.,0.,0.));", StringComparison.Ordinal) + .Replace("#612=IFCAXIS2PLACEMENT3D(#613,$,$);", "#612=IFCAXIS2PLACEMENT3D(#613,#32,$);", StringComparison.Ordinal); + var model = Open(ifc); var beam = Element(model, "Beam"); Assert.NotNull(beam.Mesh); var box = beam.Mesh.BoundingBox; - AssertPoints([new(0, -10, -5), new(1000, 10, 5)], [box.Min, box.Max]); + AssertPoints([new(1090, 2000, 2995), new(1110, 2500, 3005)], [box.Min, box.Max]); Assert.NotNull(beam.BooleanResult); Assert.NotNull(beam.BooleanResult.FirstMesh); Assert.Null(beam.BooleanResult.FirstSolid); + + var plane = beam.BooleanResult.SecondHalfSpace!.BaseSurface; + AssertPoints([new(1100, 2500, 3000), IfcVector3.UnitY], [plane.Location, plane.Normal]); + string saved = model.ToStepString(); + var step = StepReader.Read(new StringReader(saved)); + var planePlacement = step.Find(Assert.Single(step.OfType("IFCPLANE")).GetRef(0))!; + Assert.NotNull(planePlacement.GetRef(1)); + Assert.NotNull(planePlacement.GetRef(2)); + var reopened = Element(Open(saved), "Beam"); + var reopenedBox = reopened.Mesh!.BoundingBox; + AssertPoints([box.Min, box.Max], [reopenedBox.Min, reopenedBox.Max]); + } + + [Theory] + [InlineData("$", "(3,1,2)", 2, 0, 1)] + [InlineData("((0.,0.,1.))", "((1,1,1))", 0, 1, 2)] + public void Open_TriangulatedFaceSet_ResolvesOneBasedPointNumbersAndSkipsInvalidFaces( + string normals, string indexAttribute, int first, int second, int third) + { + string ifc = BuildIfc(Millimetre) + .Replace("FILE_SCHEMA(('IFC2X3'));", "FILE_SCHEMA(('IFC4'));", StringComparison.Ordinal) + .Replace("'SurfaceModel',(#106)", "'Tessellation',(#106)", StringComparison.Ordinal) + .Replace("#106=IFCFACEBASEDSURFACEMODEL((#107));", + $""" + #106=IFCTRIANGULATEDFACESET(#114,{normals},.F.,((1,2,3), (1,0,2), (3,2,5)),{indexAttribute}); + #114=IFCCARTESIANPOINTLIST3D(((0.,0.,0.),(1.,0.,0.),(0.,1.,0.),(1000000.,0.,0.))); + """, StringComparison.Ordinal); + + var mesh = Element(Open(ifc), "Panel").Mesh!; + AssertPoints(PanelWorld, mesh.Vertices); + Assert.Equal([first, second, third], mesh.Indices); } [Fact] diff --git a/tests/IfcIO.Tests/RevolvedSolidTests.cs b/tests/IfcIO.Tests/RevolvedSolidTests.cs index edbcbfe..7d1a667 100644 --- a/tests/IfcIO.Tests/RevolvedSolidTests.cs +++ b/tests/IfcIO.Tests/RevolvedSolidTests.cs @@ -48,7 +48,7 @@ public void RevolvedSolid_StepRoundtrip_PreservesGeometryAndSolid() { var model = IfcModel.Create("Revolved Roundtrip"); var profile = new IfcCircleProfileDef(radius: 150, position: new IfcVector3(600, 0, 0)); - var axis = new IfcAxis1Placement(IfcVector3.Zero, IfcVector3.UnitZ); + var axis = new IfcAxis1Placement(IfcVector3.Zero, IfcVector3.UnitY); var elem = model.AddRevolvedSolid("Circular Torus", profile, angle: Math.PI, axis: axis, ifcType: "IFCPIPEFITTING"); string tempPath = Path.Combine(Path.GetTempPath(), $"rev_test_{Guid.NewGuid():N}.ifc"); @@ -133,6 +133,45 @@ public void SaveAndOpen_PreservesImperialLengthsAndUsesTheDeclaredAngleUnit( Assert.Equal(originalBox.Max.Z, reopenedBox.Max.Z, 4); } + [Fact] + public void SaveAndOpen_TranslatedAuthoredRevolution_WritesAxisRelativeToPosition() + { + var model = IfcModel.Create("Revolution axis", IfcSchema.Ifc4); + var absoluteAxis = new IfcVector3(11, 20, 30); + var element = model.AddRevolvedSolid("Bend", new IfcRectangleProfileDef(2, 4, new(4, 6, 0)), + Math.PI / 2, new(10, 20, 30), new(absoluteAxis, IfcVector3.UnitY)); + + string ifc = model.ToStepString(); + var step = StepReader.Read(new StringReader(ifc)); + var revolution = Assert.Single(step.OfType("IFCREVOLVEDAREASOLID")); + var axis = step.Find(revolution.GetRef(2))!; + Assert.Equal("(1.,0.,0.)", step.Find(axis.GetRef(0))!.GetRaw(0)); + + var reopened = Assert.Single(IfcModel.Open(new StringReader(ifc)).AllElements); + Assert.Equal(absoluteAxis, reopened.RevolvedSolid!.Axis.Location); + var mesh = element.GetEffectiveMesh()!; + Assert.Equal(mesh.TriangleCount, reopened.Mesh!.TriangleCount); + Assert.All(mesh.Vertices.Zip(reopened.Mesh.Vertices), pair => + Assert.True((pair.First - pair.Second).Length < 1e-5)); + } + + [Fact] + public void SaveAndOpen_AuthoredRevolutionWithOffPlaneAxis_PreservesMeshWithoutInvalidSweep() + { + var model = IfcModel.Create("Off-plane revolution", IfcSchema.Ifc4); + var element = model.AddRevolvedSolid("Bend", new IfcRectangleProfileDef(2, 4, new(4, 6, 0)), + Math.PI / 2, new(10, 20, 30), new(new(11, 20, 0), IfcVector3.UnitY)); + string ifc = model.ToStepString(); + var step = StepReader.Read(new StringReader(ifc)); + Assert.Empty(step.OfType("IFCREVOLVEDAREASOLID")); + Assert.Single(step.OfType("IFCTRIANGULATEDFACESET")); + var before = element.GetEffectiveMesh()!; + var after = Assert.Single(IfcModel.Open(new StringReader(ifc)).AllElements).Mesh!; + Assert.Equal(before.TriangleCount, after.TriangleCount); + Assert.Equal(before.Vertices.Count, after.Vertices.Count); + Assert.All(before.Vertices.Zip(after.Vertices), pair => Assert.True((pair.First - pair.Second).Length < 1e-5)); + } + [Fact] public void LegacyMislabeledAngle_RequiresExplicitOptInAndSavesWithCorrectUnits() { @@ -177,7 +216,8 @@ public void Save_PreservesSmallPositiveRevolutionAngles() { var model = IfcModel.Create("Small angle", IfcSchema.Ifc4); model.AngleUnit = IfcPlaneAngleUnit.Radian; - model.AddRevolvedSolid("Short sweep", new IfcCircleProfileDef(2), angle: 1e-8); + model.AddRevolvedSolid("Short sweep", new IfcCircleProfileDef(2, new(5, 0, 0)), angle: 1e-8, + axis: new(IfcVector3.Zero, IfcVector3.UnitY)); var step = StepReader.Read(new StringReader(model.ToStepString()));