diff --git a/CHANGELOG.md b/CHANGELOG.md index 92288cad..e6c75f2e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -134,6 +134,8 @@ The text of a sheet prints too: a text note's RTF string (class 0x0F83 block) is - Export report and diagnostics: `streams[].unpackedBytes` (`StreamRecord.UnpackedBytes`) records the inflated byte size of every decoded stream alongside `rawBytes`, and `export.geometry` (`exact`, `approximated`, `boxOnly`, `none`) and `export.elements[]` (`GeometryQualityClass`, `ElementGeometryQuality`, `IfcExporter.ExportedElementQualities`) report the geometry quality class of each exported element in IFC, compact JSON and full JSON exports with totals that sum to `export.exported`. (Closes #96) - Adds `--ifc-timestamp ` (an ISO-8601 timestamp or Unix epoch seconds; `IfcExporter.Timestamp` in the library) to write a fixed UTC timestamp into the STEP `FILE_NAME` header so repeated IFC exports of the same input are byte-for-byte identical, and adds CI-runnable corruption and fuzz tests over synthetic `.rvt` containers and inner streams with execution-time and memory-allocation bounds alongside full Windows, Linux and macOS CI test matrices. (Closes #39) +- IFC export, current profile: a ceiling in pieces takes the area of the piece Revit's export names (rvt-rs RE-486, #1209): where a ceiling has no computed host area, `GrossCeilingArea` is the area of the piece holding its first top face (faces grouped by serialized `SourceFace`/`MeshMarker` within their geometry node), required to face a bottom piece of the same area within 0.1%, instead of the whole upper surface. With a sketch area or a single piece nothing changes. New tests: `CoveringFirstPieceTests`. + ### Changed - Reading: a profile roof's own area is no longer computed from the faces of its geometry (`ProfileRoof` step history and G-element graph, read for the current IFC profile only). Since the current profile writes the stored host area as `ProjectedArea`, as Revit's exports do, nothing read it. Measured on six project files of Revit 2020, 2022 and 2024: the IFC of both profiles is identical. diff --git a/src/RvtIO/Ifc/IfcExporter.QuantitiesCurrent.cs b/src/RvtIO/Ifc/IfcExporter.QuantitiesCurrent.cs index 4b990b97..22a533e3 100644 --- a/src/RvtIO/Ifc/IfcExporter.QuantitiesCurrent.cs +++ b/src/RvtIO/Ifc/IfcExporter.QuantitiesCurrent.cs @@ -1439,19 +1439,166 @@ private List SlabQuantitiesCurrent(QuantityContextCurrent context /// A ceiling or floor finish: GrossCeilingArea is the computed host area (HOST_AREA_COMPUTED), the area of the ceiling /// surface. The parser derives it from the sketch of the ceiling, which fails for a ceiling made of several loops or without - /// a sketch; then the area of the upper surface of the solids stands in. The insulation and the lining of a pipe or duct + /// a sketch; then the area of the upper surface of the solids stands in, and where that surface is in several pieces the + /// area of the piece Revit's export names (the first part of its first face, RE-486). The insulation and the lining of a pipe or duct /// (written as IfcCovering as well) hold no such parameter. private List CoveringQuantitiesCurrent(Element element) { var result = new List(); if (element.CategoryId is PipeInsulationCategoryId or DuctInsulationCategoryId or DuctLiningCategoryId) return result; + var shells = ShellsOfCurrent(element.Geometry); double? area = ComputedHostAreaCurrent(element); - double surface = TopSurfaceAreaCurrent(ShellsOfCurrent(element.Geometry)) * SquareFeetToSquareMetres; - if (surface > 1e-9 && (area == null || Math.Abs(area.Value - surface) > 0.005 * surface)) area = surface; + if (area == null) + { + // No sketch area: a ceiling in pieces takes the piece Revit's export names (RE-486), not the whole surface. + double surface = TopSurfaceAreaCurrent(shells) * SquareFeetToSquareMetres; + double? piece = FirstTopPieceAreaCurrent(shells) * SquareFeetToSquareMetres; + area = piece ?? (surface > 1e-9 ? surface : null); + } + else + { + double surface = TopSurfaceAreaCurrent(shells) * SquareFeetToSquareMetres; + if (surface > 1e-9 && (Math.Abs(area.Value - surface) > 0.005 * surface)) area = surface; + } AddIfPositive(result, QuantityKind.Area, "GrossCeilingArea", area); return result; } + /// The area of the piece of the top surface that holds its first face (rvt-rs RE-486): Revit's export gives a + /// ceiling sketched in several pieces the area of the piece its body exporter creates last, which the saved mesh stores + /// first (the part of its top face holding the face's first triangle). Null unless the first top face itself is + /// horizontal at one height and the top surface is in more than one connected piece, and exactly one connected + /// underside piece at the same plan footprint has the same area (within 0.1%); a sloped first face, a stepped or + /// partial solid keeps the whole upper surface — a later horizontal part never stands in for it. Pieces are + /// connected components by shared vertices, not serialized face handles: one handle can cut into several regions. + /// In feet. + internal static double? FirstTopPieceAreaCurrent(IEnumerable shells) + { + var all = shells as IReadOnlyList ?? shells.ToList(); + var arcs = VerticalCylinderChordsCurrent(all.SelectMany(shell => shell.Faces)); + foreach (var shell in all) + { + if (MiddleHeightCurrent(shell.Faces) is not { } middle) continue; + // The rule replaces the area with the first top face's own piece, so it applies only when + // that face is horizontal: a sloped first face keeps the whole surface even where later + // horizontal parts with matching undersides follow. + var firstTop = shell.Faces.FirstOrDefault(face => !face.CurvedSurface + && face.OuterVertices is { Count: >= 3 } + && FaceUnitNormal(face) is { } n && Math.Abs(n[2]) > 1e-9 + && MeanHeightCurrent(face) >= middle); + if (firstTop == null + || FaceUnitNormal(firstTop) is not { } firstNormal + || Math.Abs(firstNormal[2]) <= 1 - 1e-9) continue; + var top = HorizontalFaces(shell.Faces, middle, above: true); + if (top.Count == 0 || !ConstantHeight(top)) continue; + var bottom = HorizontalFaces(shell.Faces, middle, above: false); + if (bottom.Count == 0 || !ConstantHeight(bottom)) continue; + var topPieces = ConnectedPieces(top); + if (topPieces.Count < 2) continue; + var first = topPieces.First(piece => piece.Contains(top[0])); + double topPiece = PieceArea(first, arcs); + if (!(topPiece > 1e-9)) return null; + // The counterpart below: the same area where the first top piece stands, and only there. + var (tx0, ty0, tx1, ty1) = PlanBounds(first); + int matches = ConnectedPieces(bottom) + .Where(piece => Math.Abs(PieceArea(piece, arcs) - topPiece) <= 0.001 * topPiece) + .Count(piece => Overlaps(piece, tx0, ty0, tx1, ty1)); + if (matches != 1) return null; + return topPiece; + } + return null; + } + + /// Plan extent of faces, in feet. + private static (double X0, double Y0, double X1, double Y1) PlanBounds(IEnumerable faces) + { + double x0 = double.MaxValue, y0 = double.MaxValue, x1 = double.MinValue, y1 = double.MinValue; + foreach (var face in faces) + { + if (face.OuterVertices is not { } ring) continue; + foreach (var p in ring) + { + if (p is not { Length: >= 2 }) continue; + x0 = Math.Min(x0, p[0]); y0 = Math.Min(y0, p[1]); + x1 = Math.Max(x1, p[0]); y1 = Math.Max(y1, p[1]); + } + } + return (x0, y0, x1, y1); + } + + /// True when the plan extent of a piece overlaps a box with positive area. + private static bool Overlaps(List piece, double x0, double y0, double x1, double y1) + { + var (px0, py0, px1, py1) = PlanBounds(piece); + return px0 < x1 && x0 < px1 && py0 < y1 && y0 < py1; + } + + /// Planar horizontal faces on one side of a height: at or above it (), + /// or strictly below it. + private static List HorizontalFaces(IEnumerable faces, double aboveOrAt, bool above) => + faces.Where(face => !face.CurvedSurface + && face.OuterVertices is { Count: >= 3 } + && FaceUnitNormal(face) is { } n && Math.Abs(n[2]) > 1 - 1e-9 + && (above ? MeanHeightCurrent(face) >= aboveOrAt : MeanHeightCurrent(face) < aboveOrAt)) + .ToList(); + + /// True when every face lies at the same height (within a micrometre): one constant-height primitive. + private static bool ConstantHeight(IReadOnlyList faces) + { + double height = MeanHeightCurrent(faces[0]); + return faces.All(face => Math.Abs(MeanHeightCurrent(face) - height) <= 1e-6); + } + + /// Connected components of faces by shared vertices, in order of first appearance. + private static List> ConnectedPieces(List faces) + { + int count = faces.Count; + int[] parent = Enumerable.Range(0, count).ToArray(); + int Find(int x) + { + while (parent[x] != x) + { + parent[x] = parent[parent[x]]; + x = parent[x]; + } + return x; + } + static bool SharesVertex(GeoFace left, GeoFace right) + { + if (left.OuterVertices is not { } a || right.OuterVertices is not { } b) return false; + foreach (var p in a) + { + if (p is not { Length: >= 3 }) continue; + foreach (var q in b) + { + if (q is { Length: >= 3 } && p[0] == q[0] && p[1] == q[1] && p[2] == q[2]) return true; + } + } + return false; + } + for (int i = 0; i < count; i++) + for (int j = i + 1; j < count; j++) + if (SharesVertex(faces[i], faces[j])) + { + int a = Find(i), b = Find(j); + if (a != b) parent[a] = b; + } + var groups = new Dictionary>(); + for (int i = 0; i < count; i++) + { + int root = Find(i); + if (!groups.TryGetValue(root, out var group)) groups[root] = group = new List(); + group.Add(faces[i]); + } + return groups.Values.OrderBy(group => faces.IndexOf(group[0])).ToList(); + } + + /// Net face areas of a piece, with the arc bulges of its outline, in feet. + private static double PieceArea( + IEnumerable piece, + Dictionary<(long, long, long, long), (double Cx, double Cy, double R)> arcs) => + piece.Sum(face => (NetFaceArea(face) ?? 0) + ArcSegmentCorrectionCurrent(face, arcs) / Math.Abs(FaceUnitNormal(face)![2])); + /// Column quantities. A column written as a prism carries its extrusion data: /// Length, CrossSectionArea (the profile), OuterSurfaceArea (the length times the perimeter) and GrossVolume (the length times /// the area), where the length and the perimeter are numbers of the length unit of the file: a file in millimetres has the two diff --git a/tests/RvtIO.Tests/CoveringFirstPieceTests.cs b/tests/RvtIO.Tests/CoveringFirstPieceTests.cs new file mode 100644 index 00000000..43934230 --- /dev/null +++ b/tests/RvtIO.Tests/CoveringFirstPieceTests.cs @@ -0,0 +1,266 @@ +using RvtIO.Ifc; +using RvtIO.Model; +using Xunit; + +namespace RvtIO.Tests; + +/// RE-486: a ceiling in pieces takes the piece holding its first top face, not the whole surface. +/// The piece is a connected component of the horizontal top at one height; a solid whose first top face +/// is sloped, a stepped solid, or one without a single matching underside piece, keeps the whole upper surface. +public class CoveringFirstPieceTests +{ + private const double SquareFeet = 0.3048 * 0.3048; + + private static GeoFace Square(double x0, double y0, double size, double z, uint source = 0) + { + var face = new GeoFace(); + face.OuterVertices = new List + { + new double[3] { x0, y0, z }, + new double[3] { x0 + size, y0, z }, + new double[3] { x0 + size, y0 + size, z }, + new double[3] { x0, y0 + size, z }, + }; + face.GeometryNode = 1; + face.SourceFace = source; + return face; + } + + private static GeometryData Slabs(params GeoFace[] faces) => new() { Faces = faces.ToList() }; + + private static GeometryData TwoPieceSlab() => Slabs( + Square(0, 0, 10, 10, 1), + Square(20, 0, 10, 10, 2), + Square(0, 0, 10, 0, 1), + Square(20, 0, 10, 0, 2)); + + [Fact] + public void FirstPiece_IsOnePieceNotTheWholeSurface() + { + var shells = IfcExporter.ShellsOfCurrent(TwoPieceSlab()); + + double? piece = IfcExporter.FirstTopPieceAreaCurrent(shells); + double whole = IfcExporter.TopSurfaceAreaCurrent(shells); + + Assert.NotNull(piece); + Assert.Equal(100, piece!.Value, 6); + Assert.Equal(200, whole, 6); + } + + [Fact] + public void SharedSerializedFace_StillCountsConnectedComponents() + { + // Two disconnected top regions cut from one serialized face, with matching undersides. + var geometry = Slabs( + Square(0, 0, 10, 10, 1), + Square(20, 0, 15, 10, 1), + Square(0, 0, 10, 0, 2), + Square(20, 0, 15, 0, 2)); + var shells = IfcExporter.ShellsOfCurrent(geometry); + + double? piece = IfcExporter.FirstTopPieceAreaCurrent(shells); + + Assert.NotNull(piece); + Assert.Equal(100, piece!.Value, 6); + } + + [Fact] + public void BottomOrder_DoesNotDecideTheMatch() + { + // The underside piece matching the first top piece is listed last. + var geometry = Slabs( + Square(0, 0, 10, 10, 1), + Square(20, 0, 15, 10, 2), + Square(20, 0, 15, 0, 3), + Square(0, 0, 10, 0, 4)); + var shells = IfcExporter.ShellsOfCurrent(geometry); + + double? piece = IfcExporter.FirstTopPieceAreaCurrent(shells); + + Assert.NotNull(piece); + Assert.Equal(100, piece!.Value, 6); + } + + [Fact] + public void SinglePiece_ReturnsNullSoCallerKeepsTheWholeSurface() + { + var geometry = Slabs( + Square(0, 0, 10, 10, 1), + Square(0, 0, 10, 0, 1)); + var shells = IfcExporter.ShellsOfCurrent(geometry); + + Assert.Null(IfcExporter.FirstTopPieceAreaCurrent(shells)); + } + + [Fact] + public void MismatchedBottom_ReturnsNull() + { + var geometry = Slabs( + Square(0, 0, 10, 10, 1), + Square(20, 0, 10, 10, 2), + Square(0, 0, 5, 0, 3)); + var shells = IfcExporter.ShellsOfCurrent(geometry); + + Assert.Null(IfcExporter.FirstTopPieceAreaCurrent(shells)); + } + + [Fact] + public void SteppedTop_ReturnsNull() + { + // Two top pieces at different heights are not one constant-height primitive. + var geometry = Slabs( + Square(0, 0, 10, 10, 1), + Square(20, 0, 10, 12, 2), + Square(0, 0, 10, 0, 3), + Square(20, 0, 10, 2, 4)); + var shells = IfcExporter.ShellsOfCurrent(geometry); + + Assert.Null(IfcExporter.FirstTopPieceAreaCurrent(shells)); + } + + private static GeoFace Sloped(double x, double size, double z, uint source, double slope) + { + var face = new GeoFace(); + face.OuterVertices = new List + { + new double[3] { x, 0, z }, + new double[3] { x + size, 0, z }, + new double[3] { x + size, size, z + slope * size }, + new double[3] { x, size, z + slope * size }, + }; + face.GeometryNode = 1; + face.SourceFace = source; + return face; + } + + private static GeometryData SlopedBox(double x, double size, double z, uint source, double slope) + { + var top = Sloped(x, size, z, source, slope); + var bottom = Sloped(x, size, 0, source + 1, slope); + var result = new List + { + top, + new GeoFace + { + GeometryNode = 1, + SourceFace = source + 1, + OuterVertices = bottom.OuterVertices!.AsEnumerable().Reverse().ToList(), + }, + }; + for (int i = 0; i < 4; i++) + { + int j = (i + 1) % 4; + result.Add(new GeoFace + { + GeometryNode = 1, + SourceFace = source + 2 + (uint)i, + OuterVertices = [bottom.OuterVertices![i], bottom.OuterVertices[j], top.OuterVertices![j], top.OuterVertices[i]], + }); + } + return new GeometryData + { + Faces = result, + BrepSolids = [new GeoBrepSolid { IsClosed = true, FaceIndices = Enumerable.Range(0, result.Count).ToList() }], + }; + } + + [Fact] + public void SlopedSolid_KeepsTheWholeUpperSurface() + { + // Two disjoint closed sloped boxes: the top is not horizontal, so no piece is taken. + var first = SlopedBox(0, 10, 10, 1, 0.5); + var second = SlopedBox(20, 15, 10, 10, 0.5); + var geometry = new GeometryData + { + Faces = first.Faces.Concat(second.Faces).ToList(), + BrepSolids = + [ + new GeoBrepSolid { IsClosed = true, FaceIndices = Enumerable.Range(0, first.Faces.Count).ToList() }, + new GeoBrepSolid { IsClosed = true, FaceIndices = Enumerable.Range(first.Faces.Count, second.Faces.Count).ToList() }, + ], + }; + var shells = IfcExporter.ShellsOfCurrent(geometry); + + Assert.Null(IfcExporter.FirstTopPieceAreaCurrent(shells)); + Assert.Equal(111.803398875 + 251.557647469, IfcExporter.TopSurfaceAreaCurrent(shells), 6); + } + + private static List<(string Name, double Value)> QuantitiesOf(Element element) + { + var w = new StepWriter(); + int owner = w.Add("IFCOWNERHISTORY", "$,$,$,.NOCHANGE.,$,$,$,0"); + int origin = w.Add("IFCCARTESIANPOINT", "(0.,0.,0.)"); + int axis = w.Add("IFCAXIS2PLACEMENT3D", $"#{origin},$,$"); + int placement = w.Add("IFCLOCALPLACEMENT", $"$,#{axis}"); + int product = w.Add("IFCCOVERING", $"'QZGD7y6S5209$mGLi_sPlj',#{owner},'P',$,$,#{placement},$,'1'"); + new IfcExporter().ApplyCurrentBaseQuantities( + w, new Dictionary { [element.Id] = element }, new Dictionary { [product] = element.Id }, + new Dictionary(), owner, null); + return Enumerable.Range(0, w.EntityCount).Select(w.EntityAt).Where(e => e.Type.StartsWith("IFCQUANTITY", StringComparison.Ordinal)) + .Select(e => + { + var parts = IfcExporter.SplitStepArguments(e.Args); + return (parts[0].Trim('\''), double.Parse(parts[3], System.Globalization.CultureInfo.InvariantCulture)); + }).ToList(); + } + + [Fact] + public void Caller_TwoPiecesWithoutHostArea_WritesTheFirstPiece() + { + var ceiling = new Element { Id = 3, CategoryId = -2000038, Geometry = TwoPieceSlab() }; + + var quantities = QuantitiesOf(ceiling); + + Assert.Equal(100 * SquareFeet, quantities.Single(q => q.Name == "GrossCeilingArea").Value, 9); + } + + [Fact] + public void Caller_SlopedFirstThenHorizontalPieces_WritesTheWholeUpperSurface() + { + // A sloped first top face disqualifies the piece rule even where later horizontal parts + // with matching undersides follow: the whole upper surface stays. + var sloped = SlopedBox(50, 10, 10, 20, 0.5); + var first = SlopedBox(0, 10, 10, 1, 0); + var second = SlopedBox(20, 15, 10, 10, 0); + var geometry = new GeometryData + { + Faces = sloped.Faces.Concat(first.Faces).Concat(second.Faces).ToList(), + BrepSolids = + [ + new GeoBrepSolid { IsClosed = true, FaceIndices = Enumerable.Range(0, sloped.Faces.Count + first.Faces.Count + second.Faces.Count).ToList() }, + ], + }; + + Assert.Null(IfcExporter.FirstTopPieceAreaCurrent(IfcExporter.ShellsOfCurrent(geometry))); + var ceiling = new Element { Id = 5, CategoryId = -2000038, Geometry = geometry }; + + var quantities = QuantitiesOf(ceiling); + + Assert.Equal((111.803398875 + 100 + 225) * SquareFeet, quantities.Single(q => q.Name == "GrossCeilingArea").Value, 6); + } + + [Fact] + public void Caller_SlopedSolidWithoutHostArea_WritesTheWholeUpperSurface() + { + var first = SlopedBox(0, 10, 10, 1, 0.5); + var second = SlopedBox(20, 15, 10, 10, 0.5); + var ceiling = new Element + { + Id = 4, + CategoryId = -2000038, + Geometry = new GeometryData + { + Faces = first.Faces.Concat(second.Faces).ToList(), + BrepSolids = + [ + new GeoBrepSolid { IsClosed = true, FaceIndices = Enumerable.Range(0, first.Faces.Count).ToList() }, + new GeoBrepSolid { IsClosed = true, FaceIndices = Enumerable.Range(first.Faces.Count, second.Faces.Count).ToList() }, + ], + }, + }; + + var quantities = QuantitiesOf(ceiling); + + Assert.Equal((111.803398875 + 251.557647469) * SquareFeet, quantities.Single(q => q.Name == "GrossCeilingArea").Value, 6); + } +}