From 7226151451a0c15bcc7ad3e4b9298c303f830bd4 Mon Sep 17 00:00:00 2001 From: mie Date: Mon, 16 Nov 2026 16:22:44 +0300 Subject: [PATCH 001/259] ifc: ceiling in pieces takes the area of its first top-face piece (RE-486) Port rvt-rs RE-486 (#1209): where a ceiling has no computed host area, GrossCeilingArea is the piece holding its first top face (grouped by SourceFace/MeshMarker within its node, bottom piece within 0.1%) instead of the whole upper surface. Sketch area and single-piece behavior unchanged. Tests: CoveringFirstPieceTests; BaseQuantities suites green. --- CHANGELOG.md | 2 + .../Ifc/IfcExporter.QuantitiesCurrent.cs | 60 +++++++++++++++- tests/RvtIO.Tests/CoveringFirstPieceTests.cs | 72 +++++++++++++++++++ 3 files changed, 131 insertions(+), 3 deletions(-) create mode 100644 tests/RvtIO.Tests/CoveringFirstPieceTests.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index 92288cad..a2ff61e1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,8 @@ API between minor releases. ### Added +- 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`. + - CLI and API: `rvtio print [--level ] [--scale ] [--paper A4|A3|A2|A1|A0] [--list-levels]` and `RvtIO.Print.PlanPrinter` render the plan of one level to a PDF page from the decoded model: walls as their stored location line drawn two sides of the stored width apart (`WALL_ATTR_WIDTH_PARAM`; 100 mm when neither the wall nor its type stores one), columns as their bounding-box footprint, and grids clipped to the extent of the level. `--list-levels` prints the levels with a drawable wall or column and their stored elevation; without `--level` the level with the most of them is printed. The page is the smallest landscape A4 to A0 that holds the drawing at the scale (a larger drawing is scaled down to fit), with a frame at the margin and the drawing centred. A wall is cut at the openings of its hosted doors and windows: the cut loop of each insert, transformed to the model, leaves its stretch out, the wall is drawn in the pieces between the openings with a jamb at each cut, and a window gets a light line across the opening. The title (level name and scale) is written with an embedded TrueType font found on the machine (Arial, Segoe UI or Tahoma on Windows, DejaVu Sans on Linux, Arial or Helvetica Neue on macOS), which also makes Cyrillic text real, selectable PDF text; without such a font the page is drawn without a title. Sheets print too: `rvtio print --sheet [--list-sheets]` renders a sheet page from the location curves of the elements the sheet owns (the page border, the title block frame and rules, tables), on the paper the linework spans (snapped to A4-A0 within 8 mm), with the sheet number and name written in a corner; `RvtIO.Print.SheetPrinter` is the API. A level line ends in the marker the reference export uses: a circle with an arrow head at the right of the drawing, the level name above and its height in millimetres below (Roof Line 6000, Level 2 3000, Ceiling 2700, Level 1 0, Level 1 Living Rm. -550, Foundation -800), each height printed once even though the project holds many level elements at the same height; the drawing reserves a label margin on the right. A level line of an elevation ends in a level marker: a white circle with the height in metres (+0.000, +3.000, +6.000), as a Revit elevation notes its levels. diff --git a/src/RvtIO/Ifc/IfcExporter.QuantitiesCurrent.cs b/src/RvtIO/Ifc/IfcExporter.QuantitiesCurrent.cs index 4b990b97..bc6a28f5 100644 --- a/src/RvtIO/Ifc/IfcExporter.QuantitiesCurrent.cs +++ b/src/RvtIO/Ifc/IfcExporter.QuantitiesCurrent.cs @@ -1439,19 +1439,73 @@ 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 the top face holding the face's first triangle). Faces are grouped by their serialized face + /// (SourceFace, else MeshMarker) within their geometry node, as does; + /// the piece is the group of the first top face in serialized order. Null unless the top surface is in more than one + /// piece and a bottom piece of the same area (within 0.1%) faces it, so a sloped or partial solid keeps the whole + /// surface. 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; + var top = shell.Faces + .Where(face => !face.CurvedSurface && FaceUnitNormal(face) is { } n && Math.Abs(n[2]) > 1e-9 && MeanHeightCurrent(face) >= middle) + .ToList(); + if (top.Count == 0) continue; + static (int Node, uint Face, uint Marker) Key(GeoFace face) => + (face.GeometryNode, face.SourceFace, face.MeshMarker); + var firstKey = Key(top[0]); + double PieceArea(IEnumerable faces, (int Node, uint Face, uint Marker) key) => faces + .Where(face => Key(face).Equals(key)) + .Sum(face => (NetFaceArea(face) ?? 0) + ArcSegmentCorrectionCurrent(face, arcs) / Math.Abs(FaceUnitNormal(face)![2])); + double topPiece = PieceArea(top, firstKey); + if (!(topPiece > 1e-9)) return null; + double topWhole = top.Sum(face => (NetFaceArea(face) ?? 0) + ArcSegmentCorrectionCurrent(face, arcs) / Math.Abs(FaceUnitNormal(face)![2])); + // A single-piece surface is not a pieces case; the caller then uses the whole surface as before. + if (Math.Abs(topWhole - topPiece) <= 1e-9) return null; + var bottom = shell.Faces + .Where(face => !face.CurvedSurface && FaceUnitNormal(face) is { } n && Math.Abs(n[2]) > 1e-9 && MeanHeightCurrent(face) < middle) + .ToList(); + if (bottom.Count == 0) continue; + double bottomPiece = PieceArea(bottom, Key(bottom[0])); + if (!(bottomPiece > 1e-9)) return null; + // The saved-mesh rule applies where the faces facing each way hold a part of the same area (RE-480/RE-486). + if (Math.Abs(bottomPiece - topPiece) > 0.001 * topPiece) return null; + return topPiece; + } + return null; + } + /// 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..0b87820d --- /dev/null +++ b/tests/RvtIO.Tests/CoveringFirstPieceTests.cs @@ -0,0 +1,72 @@ +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. +public class CoveringFirstPieceTests +{ + private static GeoFace MakeFace(double x0, double y0, double size, double z, int node, uint source) + { + var face = new GeoFace(); + face.OuterVertices = new List(); + face.OuterVertices.Add(new double[3] { x0, y0, z }); + face.OuterVertices.Add(new double[3] { x0 + size, y0, z }); + face.OuterVertices.Add(new double[3] { x0 + size, y0 + size, z }); + face.OuterVertices.Add(new double[3] { x0, y0 + size, z }); + face.GeometryNode = node; + face.SourceFace = source; + return face; + } + + private static GeometryData TwoPieceGeometry() + { + var geometry = new GeometryData(); + geometry.Faces = new List(); + geometry.Faces.Add(MakeFace(0, 0, 10, 10, 1, 1)); + geometry.Faces.Add(MakeFace(20, 0, 10, 10, 1, 2)); + geometry.Faces.Add(MakeFace(0, 0, 10, 0, 1, 1)); + geometry.Faces.Add(MakeFace(20, 0, 10, 0, 1, 2)); + return geometry; + } + + [Fact] + public void FirstPiece_IsOnePieceNotTheWholeSurface() + { + var shells = IfcExporter.ShellsOfCurrent(TwoPieceGeometry()); + + 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 SinglePiece_ReturnsNullSoCallerKeepsTheWholeSurface() + { + var geometry = new GeometryData(); + geometry.Faces = new List(); + geometry.Faces.Add(MakeFace(0, 0, 10, 10, 1, 1)); + geometry.Faces.Add(MakeFace(0, 0, 10, 0, 1, 1)); + var shells = IfcExporter.ShellsOfCurrent(geometry); + + Assert.Null(IfcExporter.FirstTopPieceAreaCurrent(shells)); + } + + [Fact] + public void MismatchedBottom_ReturnsNull() + { + // Bottom piece of a different area: no matching counterpart, keep the whole surface. + var geometry = new GeometryData(); + geometry.Faces = new List(); + geometry.Faces.Add(MakeFace(0, 0, 10, 10, 1, 1)); + geometry.Faces.Add(MakeFace(20, 0, 10, 10, 1, 2)); + geometry.Faces.Add(MakeFace(0, 0, 5, 0, 1, 1)); + var shells = IfcExporter.ShellsOfCurrent(geometry); + + Assert.Null(IfcExporter.FirstTopPieceAreaCurrent(shells)); + } +} From 5aa3944c103b6f447110d0661c0b3b83b7467272 Mon Sep 17 00:00:00 2001 From: mie Date: Mon, 16 Nov 2026 16:27:34 +0300 Subject: [PATCH 002/259] print: prefer metric-compatible font substitutes, support RVTIO_FONTS Port rvt-prt font lookup: Liberation Sans and Arimo (Arial-compatible widths, titles wrap the same everywhere) before DejaVu Sans on Linux; RVTIO_FONTS names extra font folders searched first. Tests: PdfFontsTests; docs updated. --- CHANGELOG.md | 2 + docs/printing.md | 5 ++- docs/public-api.md | 2 +- src/RvtIO/Pdf/PdfFonts.cs | 62 +++++++++++++++++++++++++++--- tests/RvtIO.Tests/PdfFontsTests.cs | 42 ++++++++++++++++++++ 5 files changed, 105 insertions(+), 8 deletions(-) create mode 100644 tests/RvtIO.Tests/PdfFontsTests.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index 92288cad..0a8c1b7e 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) +- Printing: the embedded title font prefers Arial's metric-compatible substitutes (Liberation Sans, Arimo) over DejaVu Sans on Linux, so a title wraps the same on every machine, and `RVTIO_FONTS` names extra folders of font files searched first (`:` on Linux/macOS, `;` on Windows), as in rvt-prt's `RVT_PRT_FONTS`. New tests: `PdfFontsTests`. + ### 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/docs/printing.md b/docs/printing.md index eb33d764..7641e5b1 100644 --- a/docs/printing.md +++ b/docs/printing.md @@ -176,8 +176,9 @@ stays empty. | Room legend | below the plan: a colour swatch and the name of every kind of room on it | The page is white with a frame at the margin, and the drawing is centred. The title (the level name and the scale) is -written with an embedded TrueType font found on the machine (Arial, Segoe UI or Tahoma on Windows, DejaVu Sans on Linux, -Arial or Helvetica Neue on macOS); without such a font the page is drawn without a title, because the standard PDF font +written with an embedded TrueType font found on the machine (Arial or its metric-compatible substitutes +Liberation Sans and Arimo on Linux, Arial on macOS, Arial, Segoe UI or Tahoma on Windows; `RVTIO_FONTS` names extra +folders searched first, `:` on Linux/macOS and `;` on Windows, as in rvt-prt's `RVT_PRT_FONTS`); without such a font the page is drawn without a title, because the standard PDF font holds no Cyrillic. Elements are selected by their level (`LEVEL_PARAM`); a wall without a location line or a column without a footprint is left out and counted by neither selection nor drawing. diff --git a/docs/public-api.md b/docs/public-api.md index 06f28005..c744eb6f 100644 --- a/docs/public-api.md +++ b/docs/public-api.md @@ -101,7 +101,7 @@ See [printing a plan](printing.md) for what is drawn, what is not, and the roadm | `PdfPageSize` | Paper sizes A4 to A0 in millimetres, `Landscape` for the turned page. | | `PdfTextAlignment` | `Left`, `Center`, `Right`: where the text anchor sits. | | `PdfTrueTypeFont` | A TrueType font parsed for embedding (`UnitsPerEm`, `GlyphOf`, `AdvanceOf`), drawn as a Type0 font with Identity-H encoding and a ToUnicode map, so text in the scripts it covers (Cyrillic included) is real, selectable PDF text. | -| `PdfFonts` | `TryFind` loads the first TrueType font found on the machine (Arial, Segoe UI, Tahoma, DejaVu Sans, Helvetica Neue). | +| `PdfFonts` | `TryFind` loads the first TrueType font found on the machine (Arial, its metric-compatible substitutes Liberation Sans and Arimo, Segoe UI, Tahoma, DejaVu Sans, Helvetica Neue); `RVTIO_FONTS` names extra folders searched first. | Without `PdfDocument.Font` the writer uses the standard Helvetica font, which holds printable ASCII only, and a text with another character is refused. With it, every text is written with the embedded font. diff --git a/src/RvtIO/Pdf/PdfFonts.cs b/src/RvtIO/Pdf/PdfFonts.cs index c0592f57..284a1023 100644 --- a/src/RvtIO/Pdf/PdfFonts.cs +++ b/src/RvtIO/Pdf/PdfFonts.cs @@ -3,10 +3,32 @@ namespace RvtIO.Pdf; /// Where the print pipeline finds a TrueType font to embed. public static class PdfFonts { - /// The font files tried in order: Arial, Segoe UI and Tahoma on Windows, DejaVu Sans on Linux, Arial and - /// Helvetica Neue on macOS. + /// Environment variable with extra folders of font files, searched first. + /// Several folders are separated by : on Linux/macOS and ; on Windows, + /// as in rvt-prt's RVT_PRT_FONTS. + public const string FontsEnvVar = "RVTIO_FONTS"; + + /// File names tried in each extra folder first: Arial and its metric-compatible + /// substitutes (Liberation Sans, Arimo), which wrap and fit text as Arial does. + private static readonly string[] ExtraFileNames = + [ + "arial.ttf", + "Arial.ttf", + "LiberationSans-Regular.ttf", + "Arimo-Regular.ttf", + "DejaVuSans.ttf", + ]; + + /// The font files tried in order: Arial and its metric-compatible substitutes + /// (Liberation Sans, Arimo) on Linux, Arial on macOS and Windows, then Segoe UI and Tahoma + /// on Windows, DejaVu Sans and Helvetica Neue. A substitute keeps the widths of Arial, + /// so a title wraps the same on every machine. private static readonly string[] Candidates = [ + "/usr/share/fonts/truetype/liberation/LiberationSans-Regular.ttf", + "/usr/share/fonts/TTF/LiberationSans-Regular.ttf", + "/usr/share/fonts/truetype/arimo/Arimo-Regular.ttf", + "/usr/share/fonts/TTF/Arimo-Regular.ttf", "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", "/usr/share/fonts/TTF/DejaVuSans.ttf", "/System/Library/Fonts/Supplemental/Arial.ttf", @@ -16,13 +38,17 @@ public static class PdfFonts @"C:\Windows\Fonts\tahoma.ttf", ]; - /// Loads the first font file of that exists and parses. + /// Loads the first font file of that exists and parses, + /// after the folders of . /// The file that was used, or null when none exists. /// The font, or null when no candidate is a TrueType font this reader supports. - public static PdfTrueTypeFont? TryFind(out string? path) + public static PdfTrueTypeFont? TryFind(out string? path) => + TryFind(Environment.GetEnvironmentVariable, out path); + + internal static PdfTrueTypeFont? TryFind(Func getEnv, out string? path) { path = null; - foreach (string candidate in Candidates) + foreach (string candidate in CandidateFiles(getEnv)) { if (!File.Exists(candidate)) continue; try @@ -38,4 +64,30 @@ public static class PdfFonts } return null; } + + /// Every font file tried in order, without touching the disk: the files of the + /// folders first, then . + internal static IReadOnlyList CandidateFiles(Func getEnv) + { + var files = new List(); + string? extra = null; + try + { + extra = getEnv(FontsEnvVar); + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) + { + // No extra folders then; the machine candidates still stand. + } + if (!string.IsNullOrWhiteSpace(extra)) + { + foreach (string folder in extra.Split(Path.PathSeparator, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)) + { + foreach (string name in ExtraFileNames) + files.Add(Path.Combine(folder, name)); + } + } + files.AddRange(Candidates); + return files; + } } diff --git a/tests/RvtIO.Tests/PdfFontsTests.cs b/tests/RvtIO.Tests/PdfFontsTests.cs new file mode 100644 index 00000000..16deb436 --- /dev/null +++ b/tests/RvtIO.Tests/PdfFontsTests.cs @@ -0,0 +1,42 @@ +using RvtIO.Pdf; +using Xunit; + +namespace RvtIO.Tests; + +/// The font search of the print pipeline: metric-compatible substitutes and extra folders. +public class PdfFontsTests +{ + [Fact] + public void CandidateFiles_ListsSubstitutesBeforeDejaVu() + { + var files = PdfFonts.CandidateFiles(_ => null).ToList(); + + int liberation = files.FindIndex(f => f.Contains("LiberationSans-Regular", StringComparison.Ordinal)); + int arimo = files.FindIndex(f => f.Contains("Arimo-Regular", StringComparison.Ordinal)); + int dejavu = files.FindIndex(f => f.Contains("DejaVuSans", StringComparison.Ordinal)); + Assert.True(liberation >= 0 && arimo >= 0 && dejavu >= 0); + Assert.True(liberation < dejavu && arimo < dejavu); + } + + [Fact] + public void CandidateFiles_ExtraFoldersComeFirst() + { + string extra = string.Join(Path.PathSeparator, ["/fonts/a", "/fonts/b"]); + var files = PdfFonts.CandidateFiles(name => name == PdfFonts.FontsEnvVar ? extra : null).ToList(); + + Assert.StartsWith("/fonts/a", files[0]); + Assert.StartsWith("/fonts/b", files[5]); + Assert.True(files.Count > 10); + int systemFirst = files.FindIndex(f => !f.StartsWith("/fonts/", StringComparison.Ordinal)); + Assert.Equal(10, systemFirst); + } + + [Fact] + public void CandidateFiles_EmptyEnvGivesMachineCandidatesOnly() + { + var files = PdfFonts.CandidateFiles(_ => " "); + + Assert.DoesNotContain(files, f => f.StartsWith("/fonts/", StringComparison.Ordinal)); + Assert.Contains(files, f => f.Contains("DejaVuSans", StringComparison.Ordinal)); + } +} From 29aa08608c0905d18fd3808423c080cd0f4989fb Mon Sep 17 00:00:00 2001 From: mie Date: Mon, 16 Nov 2026 16:28:14 +0300 Subject: [PATCH 003/259] changelog: move RE-486 entry to end of Unreleased Added --- CHANGELOG.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a2ff61e1..e6c75f2e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,8 +15,6 @@ API between minor releases. ### Added -- 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`. - - CLI and API: `rvtio print [--level ] [--scale ] [--paper A4|A3|A2|A1|A0] [--list-levels]` and `RvtIO.Print.PlanPrinter` render the plan of one level to a PDF page from the decoded model: walls as their stored location line drawn two sides of the stored width apart (`WALL_ATTR_WIDTH_PARAM`; 100 mm when neither the wall nor its type stores one), columns as their bounding-box footprint, and grids clipped to the extent of the level. `--list-levels` prints the levels with a drawable wall or column and their stored elevation; without `--level` the level with the most of them is printed. The page is the smallest landscape A4 to A0 that holds the drawing at the scale (a larger drawing is scaled down to fit), with a frame at the margin and the drawing centred. A wall is cut at the openings of its hosted doors and windows: the cut loop of each insert, transformed to the model, leaves its stretch out, the wall is drawn in the pieces between the openings with a jamb at each cut, and a window gets a light line across the opening. The title (level name and scale) is written with an embedded TrueType font found on the machine (Arial, Segoe UI or Tahoma on Windows, DejaVu Sans on Linux, Arial or Helvetica Neue on macOS), which also makes Cyrillic text real, selectable PDF text; without such a font the page is drawn without a title. Sheets print too: `rvtio print --sheet [--list-sheets]` renders a sheet page from the location curves of the elements the sheet owns (the page border, the title block frame and rules, tables), on the paper the linework spans (snapped to A4-A0 within 8 mm), with the sheet number and name written in a corner; `RvtIO.Print.SheetPrinter` is the API. A level line ends in the marker the reference export uses: a circle with an arrow head at the right of the drawing, the level name above and its height in millimetres below (Roof Line 6000, Level 2 3000, Ceiling 2700, Level 1 0, Level 1 Living Rm. -550, Foundation -800), each height printed once even though the project holds many level elements at the same height; the drawing reserves a label margin on the right. A level line of an elevation ends in a level marker: a white circle with the height in metres (+0.000, +3.000, +6.000), as a Revit elevation notes its levels. @@ -136,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. From 5976a8d15abe70e91783a39a90770a302b718ff7 Mon Sep 17 00:00:00 2001 From: mie Date: Mon, 16 Nov 2026 16:28:47 +0300 Subject: [PATCH 004/259] changelog: anchor font entry after SheetCatalog entry --- CHANGELOG.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0a8c1b7e..06b1e8d6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -129,13 +129,13 @@ The text of a sheet prints too: a text note's RTF string (class 0x0F83 block) is - API: `RvtIO.Pdf.PdfDocument` writes PDF 1.4 without a third-party library: pages of A4 to A0 or any size in millimetres, vector lines, polylines and rectangles with millimetre line widths, and single-line text in the standard Helvetica font (printable ASCII only; an embedded font for Cyrillic comes with the sheet renderer). `PdfPage.DrawLine`, `DrawPolyline`, `DrawRectangle` and `DrawText` work in millimetres from the lower-left corner, y up, the frame a printed sheet uses. This is the output layer of the sheet printing work (#18); no reader data is rendered into a page yet. Measured: a page of the decoded title block linework of one sheet is written as an A2 landscape PDF; the 10 tests parse the document back from its bytes and check the operators, the page boxes and the cross-reference offsets. No existing output changes. - API and CLI: `RvtIO.Sheets.SheetCatalog` lists the sheets of a file and the viewports placed on them, and reports what the release does not decode. A sheet is an element that carries the `Sheet Number` or `Sheet Name` parameter (class 995 of the Revit 2022 schema); the `OST_Sheets` category is not used, because every block whose class word is 0x03E3 takes it and one architectural sample has 14,354 elements of that category against 100 sheets. A `SheetRecord` carries the number, name, issue date, the drawn/designed/checked/approved by-lines, the view scale, the viewports of the sheet and the elements the sheet owns; a `ViewportRecord` carries its sheet and detail number. Ownership comes from the stored `m_ownerDBViewId`, now exposed as `Element.OwnerViewId` (null when no view owns the element). `SheetCatalog.Issues` names the missing pieces instead of hiding them: page size (kept in the title block family), view placement (the viewport block stores only the view title label origin), the displayed view (reached through the viewer element, schema class 621, which is not decoded), 2D content and the crop region. `rvtio sheets [output.json]` writes the same catalog as JSON (exit code 0 written, 1 usage or an unwritable output path, 2 an unreadable file). The catalog exposes no coordinate, size or unit, because no sheet coordinate is decoded yet. Measured on one architectural sample of Revit 2022: 100 sheets, 97 viewports placed on sheets, 97 sheets with owned elements (12 to 143 each); on a second sample 17 sheets and 17 viewports, every sheet without a number. In a Revit 2024 and a Revit 2025 save of the same project the catalog is empty: the reader reads those files by their own class schema, maps neither the sheet class nor any viewport reference, and the tool reports the empty result on standard error; covering those view classes is future work. The full JSON and the compact JSON of the sample are byte-for-byte identical to the build before this entry (the public property is not serialized), and the 16 new library tests (one of them on a private project fixture, skipped without it) and 3 new CLI tests pass. +- Printing: the embedded title font prefers Arial's metric-compatible substitutes (Liberation Sans, Arimo) over DejaVu Sans on Linux, so a title wraps the same on every machine, and `RVTIO_FONTS` names extra folders of font files searched first (`:` on Linux/macOS, `;` on Windows), as in rvt-prt's `RVT_PRT_FONTS`. New tests: `PdfFontsTests`. + - Tests: adds `IndependentInflaterCrossCheckTests` to cross-check every compressed `Formats/*`, `Global/*` and `Partitions/*` stream and gzip member (checked-in fixtures and synthetic multi-page `.rvt` containers in CI, plus public `.rvt` and `.rfa` samples when `RVTIO_TEST_FILES` is set) against `System.IO.Compression.DeflateStream`, asserting equal byte length, SHA-256 digest, CRC-32, gzip `ISIZE` trailer and format-9 segment `unc` and record counts while failing strictly on integrity mismatches independently of dictionary-chained or Deflate64 skip classification and reporting compared and skipped counts with reasons. (Closes #95) - Adds `--ifc-length-unit ` (`IfcExporter.LengthUnit` in the library) to override the length unit family declared in the IFC file (`Millimetre`, `Metre` or `Foot`), scale all coordinates, areas, volumes and base quantities consistently, and name `.SQUARE_METRE.` and `.CUBIC_METRE.` on the SI base units referenced by `Foot` area and volume conversion units across both profiles; omitting the setting keeps the project's stored length unit (or millimetres in the legacy profile) byte-for-byte unchanged, and unsupported unit names exit with code 1. Compact JSON keeps the project's formatted display units and full JSON keeps Revit's internal units. (Refs #51) - 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) -- Printing: the embedded title font prefers Arial's metric-compatible substitutes (Liberation Sans, Arimo) over DejaVu Sans on Linux, so a title wraps the same on every machine, and `RVTIO_FONTS` names extra folders of font files searched first (`:` on Linux/macOS, `;` on Windows), as in rvt-prt's `RVT_PRT_FONTS`. New tests: `PdfFontsTests`. - ### 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. From 6d000a5703b935c6daaa1c75b542fe0959b53cb7 Mon Sep 17 00:00:00 2001 From: mie Date: Mon, 16 Nov 2026 17:03:21 +0300 Subject: [PATCH 005/259] print: stop a joined wall end flat at the partner near face Port rvt-rs #1474 / RE-488 to PlanPrinter.CollectLevel: a butt join (JoinType 0) to another wall of the level cuts back the overshoot past the partner near face. Orthogonal joins only; mutual end-to-end L corners, mitre joins, roof-joined walls and ambiguous/off-level ends keep the stored line; only shortening, never extension. Tests: PlanWallJoinCutbackTests (5 synthetic); fixture check on 2022/2025 projects shows every joined end there is a mutual L corner, so their plans are unchanged. --- CHANGELOG.md | 2 + docs/printing.md | 2 +- src/RvtIO/Print/PlanPrinter.cs | 82 ++++++++- tests/RvtIO.Tests/PlanWallJoinCutbackTests.cs | 156 ++++++++++++++++++ 4 files changed, 239 insertions(+), 3 deletions(-) create mode 100644 tests/RvtIO.Tests/PlanWallJoinCutbackTests.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index 92288cad..dbe9732f 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) +- Printing: a plan stops a wall flat at the near face of the wall it joins (rvt-rs #1474, RE-488): a butt join (JoinType 0) to another wall of the level cuts back the overshoot past the partner's near face, orthogonal joins only, mutual end-to-end L corners, mitre joins, roof-joined walls and ambiguous ends keep the stored line. New tests: `PlanWallJoinCutbackTests` (5, synthetic T/L/mitre/roof-joined/start-end); on the 2022 and 2025 fixture projects every joined end is a mutual L corner, so no printed plan changes there. + ### 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/docs/printing.md b/docs/printing.md index eb33d764..dc0e9c28 100644 --- a/docs/printing.md +++ b/docs/printing.md @@ -163,7 +163,7 @@ stays empty. | Content | Source | |---|---| -| Walls | the stored location line, drawn as two sides its stored width apart, the stretch between them poche (filled grey) with end caps (`WALL_ATTR_WIDTH_PARAM` of the wall or its type; 100 mm when neither stores one) | +| Walls | the stored location line, drawn as two sides its stored width apart, the stretch between them poche (filled grey) with end caps (`WALL_ATTR_WIDTH_PARAM` of the wall or its type; 100 mm when neither stores one); a stopping end joined to another wall (butt join) is cut back flat at the partner's near face instead of running through it, as in rvt-rs #1474 and RE-488 (orthogonal joins only; mutual end-to-end L corners, mitre joins, roof-joined walls and ambiguous ends keep the stored line) | | Openings | the cut loop of a hosted door or window, transformed to the model, leaves its stretch of wall out; the wall is drawn in the pieces between its openings, with a jamb at every cut, and a window gets a light line across the opening | | Columns | the stored bounding box footprint, as a filled rectangle | | Grids | the stored location lines, clipped to the extent of the level (a grid line can run far beyond the building), with a white bubble and the grid name at both ends | diff --git a/src/RvtIO/Print/PlanPrinter.cs b/src/RvtIO/Print/PlanPrinter.cs index 5e2cee00..dc7a964f 100644 --- a/src/RvtIO/Print/PlanPrinter.cs +++ b/src/RvtIO/Print/PlanPrinter.cs @@ -208,11 +208,86 @@ public static PdfDocument RenderViews(RvtDocument document, IReadOnlyList v return pdf; } + /// Shortens the ends of walls that stop at a joined wall, drawing them flat at the partner's near face + /// instead of through it (rvt-rs #1474 and RE-488): a butt join (JoinType 0, m_wallJoinType) whose end is not shared + /// with the partner's own end (a T stop, not an L corner both walls end at), on a wall with no top attachment and a + /// partner drawn on the same level with a straight location line. Only orthogonal joins move, only the overshoot past + /// the near face is taken back (never extended), and at most to a stub of the wall's own width. Mitre joins and + /// ambiguous ends (no single butt join, a partner off the level or without a line) keep the stored location line. + internal static List<(int Id, double X1, double Y1, double X2, double Y2, double Width)> CutBackJoinedEnds( + List<(int Id, double X1, double Y1, double X2, double Y2, double Width)> walls, + IReadOnlyDictionary elements) + { + if (walls.Count == 0) return walls; + var byId = new Dictionary(); + for (int i = 0; i < walls.Count; i++) byId[walls[i].Id] = i; + var result = walls.ToList(); + for (int i = 0; i < result.Count; i++) + { + var wall = result[i]; + if (!elements.TryGetValue(wall.Id, out var element)) continue; + if (element.SerializedWallJoinedToTop == true) continue; + if (element.SerializedWallEndJoins is not { Count: > 0 } joins) continue; + double dx = wall.X2 - wall.X1, dy = wall.Y2 - wall.Y1; + double length = Math.Sqrt(dx * dx + dy * dy); + if (length < 1e-6) continue; + double ux = dx / length, uy = dy / length; + for (int end = 0; end < 2; end++) + { + var candidates = joins.Where(join => join.End == end && join.JoinType == 0).ToList(); + if (candidates.Count != 1) continue; + var join = candidates[0]; + if (!byId.TryGetValue(join.ElementId, out int partnerIndex) || partnerIndex == i) continue; + var partner = result[partnerIndex]; + if (!elements.TryGetValue(partner.Id, out var partnerElement)) continue; + double pdx = partner.X2 - partner.X1, pdy = partner.Y2 - partner.Y1; + double partnerLength = Math.Sqrt(pdx * pdx + pdy * pdy); + if (partnerLength < 1e-6) continue; + double vx = pdx / partnerLength, vy = pdy / partnerLength; + // Orthogonal butt joins only: an angled join keeps the stored line. + if (Math.Abs(ux * vx + uy * vy) > 0.02) continue; + // An L corner both walls end at keeps the overlap: the partner names this wall back at one of its ends. + bool mutualEnd = partnerElement.SerializedWallEndJoins?.Any(partnerJoin => + partnerJoin.ElementId == wall.Id && partnerJoin.JoinedEnd is 0 or 1 && partnerJoin.JoinType == 0) == true; + if (mutualEnd && join.JoinedEnd is 0 or 1) continue; + // The near face of the partner on the side of this end: the face a point just inside + // the wall stands on (an end exactly on the partner's axis faces both sides at once). + double nx = -vy, ny = vx; + double ex = end == 0 ? wall.X1 : wall.X2, ey = end == 0 ? wall.Y1 : wall.Y2; + double s = (ex - partner.X1) * nx + (ey - partner.Y1) * ny; + double denom = ux * nx + uy * ny; + if (Math.Abs(denom) < 0.98) continue; + double probe = s - denom * 1e-3; + if (Math.Abs(probe) < 1e-9) continue; + double facing = Math.Sign(probe) * partner.Width / 2; + double t = (facing - s) / denom; + // The end must stand on the partner's span, and only an overshoot past the face is taken back. + double along = (ex - partner.X1) * vx + (ey - partner.Y1) * vy; + if (along < -partner.Width / 2 - 1 || along > partnerLength + partner.Width / 2 + 1) continue; + if (t >= -1) continue; + double newLength = length + t; + if (newLength < Math.Max(wall.Width, 10)) continue; + // t < 0 shortens the wall: the start moves forward along +u, the end moves back. + double newX = end == 0 ? ex - ux * t : ex + ux * t; + double newY = end == 0 ? ey - uy * t : ey + uy * t; + result[i] = end == 0 ? (wall.Id, newX, newY, wall.X2, wall.Y2, wall.Width) + : (wall.Id, wall.X1, wall.Y1, newX, newY, wall.Width); + wall = result[i]; + dx = wall.X2 - wall.X1; dy = wall.Y2 - wall.Y1; + length = Math.Sqrt(dx * dx + dy * dy); + if (length < 1e-6) break; + ux = dx / length; uy = dy / length; + } + } + return result; + } + /// Collects what the plan of a level draws: its walls (cut at the openings of their doors and windows), /// columns and grids, and the extents they span in model millimetres. Null when the level has nothing to draw. internal static PlanContent? CollectLevel(RvtDocument document, int levelId) { var walls = new List<(int Id, double X1, double Y1, double X2, double Y2, double Width)>(); + var wallElements = new Dictionary(); var columns = new List<(double X, double Y, double Width, double Height)>(); double minX = double.MaxValue, minY = double.MaxValue, maxX = double.MinValue, maxY = double.MinValue; void Grow(double x, double y) @@ -232,7 +307,7 @@ void Grow(double x, double y) double x2 = line.EndPoint[0] * FeetToMillimetres, y2 = line.EndPoint[1] * FeetToMillimetres; double width = WidthOf(element) ?? 100; walls.Add((element.Id, x1, y1, x2, y2, width)); - Grow(x1, y1); Grow(x2, y2); + wallElements[element.Id] = element; continue; } @@ -243,10 +318,13 @@ void Grow(double x, double y) double x = box[0] * FeetToMillimetres, y = box[1] * FeetToMillimetres; double width = (box[3] - box[0]) * FeetToMillimetres, height = (box[4] - box[1]) * FeetToMillimetres; columns.Add((x, y, width, height)); - Grow(x, y); Grow(x + width, y + height); } } + walls = CutBackJoinedEnds(walls, wallElements); + foreach (var wall in walls) { Grow(wall.X1, wall.Y1); Grow(wall.X2, wall.Y2); } + foreach (var column in columns) { Grow(column.X, column.Y); Grow(column.X + column.Width, column.Y + column.Height); } + if (walls.Count == 0 && columns.Count == 0) return null; // Openings: the cut loop of a hosted door or window, transformed to the model, gives the stretch of its wall to diff --git a/tests/RvtIO.Tests/PlanWallJoinCutbackTests.cs b/tests/RvtIO.Tests/PlanWallJoinCutbackTests.cs new file mode 100644 index 00000000..4d1fa577 --- /dev/null +++ b/tests/RvtIO.Tests/PlanWallJoinCutbackTests.cs @@ -0,0 +1,156 @@ +using RvtIO.BuiltIns; +using RvtIO.Model; +using RvtIO.Parsing; +using RvtIO.Print; +using Xunit; + +namespace RvtIO.Tests; + +/// The plan stops a wall flat at the near face of the wall it joins (rvt-rs #1474, RE-488): +/// a butt join (JoinType 0) to another wall of the level, orthogonal, mutual end-to-end L corners and +/// roof-joined, mitre and ambiguous ends left out. +public class PlanWallJoinCutbackTests +{ + private static void Add(Element element, BuiltInParameter id, StorageType storage, object value) => + element.Parameters.Add(BipHelpers.MakeBipParam((int)id, id.ToString(), storage, value)); + + private static Element Level(int id, string name, double elevationFeet) + { + var level = new Element { Id = id, Name = name, CategoryId = (int)BuiltInCategory.OST_Levels }; + Add(level, BuiltInParameter.LEVEL_ELEV, StorageType.Double, elevationFeet); + return level; + } + + private static Element Wall(int id, int levelId, double x1, double y1, double x2, double y2, + double widthFeet = 0.656168, bool roofJoined = false, + IReadOnlyList? joins = null) + { + var wall = new Element + { + Id = id, + CategoryId = (int)BuiltInCategory.OST_Walls, + Location = new LocationCurve + { + CurveType = "Line", + StartPoint = [x1, y1, 0], + EndPoint = [x2, y2, 0], + }, + }; + Add(wall, BuiltInParameter.LEVEL_PARAM, StorageType.ElementId, levelId); + Add(wall, BuiltInParameter.WALL_ATTR_WIDTH_PARAM, StorageType.Double, widthFeet); + if (roofJoined) wall.SerializedWallJoinedToTop = true; + if (joins != null) wall.SerializedWallEndJoins = joins; + return wall; + } + + private static double Feet(double feet) => feet * 304.8; + + [Fact] + public void StoppingEnd_IsCutAtThePartnerNearFace() + { + // Wall 600 runs into the middle of the vertical wall 601 (a T stop). + var document = RvtDocument.FromInfo(new RevitFileInfo + { + Elements = + [ + Level(500, "Level 1", 0), + Wall(600, 500, 0, 0, 10, 0, joins: [new TfBlockDeserializer.WallEndJoin(1, 601, 2, 0)]), + Wall(601, 500, 10, -5, 10, 5), + ], + }); + + var content = PlanPrinter.CollectLevel(document, 500); + + Assert.NotNull(content); + var wall = Assert.Single(content!.Walls, w => w.Id == 600); + // Partner half width 100 mm back from x = 10 ft. + Assert.Equal(Feet(0), wall.X1, 3); + Assert.Equal(Feet(10) - 100, wall.X2, 3); + Assert.Equal(Feet(0), wall.Y1, 3); + Assert.Equal(Feet(0), wall.Y2, 3); + } + + [Fact] + public void MutualEndJoin_KeepsTheOverlap() + { + // An L corner both walls end at: each names the other's end. + var document = RvtDocument.FromInfo(new RevitFileInfo + { + Elements = + [ + Level(500, "Level 1", 0), + Wall(600, 500, 0, 0, 10, 0, joins: [new TfBlockDeserializer.WallEndJoin(1, 601, 0, 0)]), + Wall(601, 500, 10, 0, 10, 10, joins: [new TfBlockDeserializer.WallEndJoin(0, 600, 1, 0)]), + ], + }); + + var content = PlanPrinter.CollectLevel(document, 500); + + Assert.NotNull(content); + var wall = Assert.Single(content!.Walls, w => w.Id == 600); + Assert.Equal(Feet(10), wall.X2, 3); + } + + [Fact] + public void MitreJoin_KeepsTheStoredLine() + { + var document = RvtDocument.FromInfo(new RevitFileInfo + { + Elements = + [ + Level(500, "Level 1", 0), + Wall(600, 500, 0, 0, 10, 0, joins: [new TfBlockDeserializer.WallEndJoin(1, 601, 2, 1)]), + Wall(601, 500, 10, -5, 10, 5), + ], + }); + + var content = PlanPrinter.CollectLevel(document, 500); + + Assert.NotNull(content); + var wall = Assert.Single(content!.Walls, w => w.Id == 600); + Assert.Equal(Feet(10), wall.X2, 3); + } + + [Fact] + public void RoofJoinedWall_KeepsTheStoredLine() + { + var document = RvtDocument.FromInfo(new RevitFileInfo + { + Elements = + [ + Level(500, "Level 1", 0), + Wall(600, 500, 0, 0, 10, 0, roofJoined: true, + joins: [new TfBlockDeserializer.WallEndJoin(1, 601, 2, 0)]), + Wall(601, 500, 10, -5, 10, 5), + ], + }); + + var content = PlanPrinter.CollectLevel(document, 500); + + Assert.NotNull(content); + var wall = Assert.Single(content!.Walls, w => w.Id == 600); + Assert.Equal(Feet(10), wall.X2, 3); + } + + [Fact] + public void StartEnd_IsCutToo() + { + // The wall runs from inside the partner outwards: its start is the stopping end. + var document = RvtDocument.FromInfo(new RevitFileInfo + { + Elements = + [ + Level(500, "Level 1", 0), + Wall(600, 500, 10, 0, 20, 0, joins: [new TfBlockDeserializer.WallEndJoin(0, 601, 2, 0)]), + Wall(601, 500, 10, -5, 10, 5), + ], + }); + + var content = PlanPrinter.CollectLevel(document, 500); + + Assert.NotNull(content); + var wall = Assert.Single(content!.Walls, w => w.Id == 600); + Assert.Equal(Feet(10) + 100, wall.X1, 3); + Assert.Equal(Feet(20), wall.X2, 3); + } +} From f972b6b9cc3f079263a5a8b6639ae1f7d28c981a Mon Sep 17 00:00:00 2001 From: mie Date: Mon, 16 Nov 2026 18:14:42 +0300 Subject: [PATCH 006/259] ifc: first-piece ceiling area requires horizontal constant-height connected pieces Review #249: TopSurfaceArea admitted any non-vertical face, so a closed sloped solid classified as pieces and shrank GrossCeilingArea. Require horizontal faces at one height per side. Group faces into connected components by shared vertices instead of serialized SourceFace handles, and search every underside piece for the single same-area counterpart at the top piece footprint. Caller-level regression tests through CoveringQuantitiesCurrent for sloped (whole surface) and two-piece (first piece) solids without a host area. --- .../Ifc/IfcExporter.QuantitiesCurrent.cs | 136 ++++++++--- tests/RvtIO.Tests/CoveringFirstPieceTests.cs | 229 +++++++++++++++--- 2 files changed, 308 insertions(+), 57 deletions(-) diff --git a/src/RvtIO/Ifc/IfcExporter.QuantitiesCurrent.cs b/src/RvtIO/Ifc/IfcExporter.QuantitiesCurrent.cs index bc6a28f5..b7b9598b 100644 --- a/src/RvtIO/Ifc/IfcExporter.QuantitiesCurrent.cs +++ b/src/RvtIO/Ifc/IfcExporter.QuantitiesCurrent.cs @@ -1466,11 +1466,11 @@ private List CoveringQuantitiesCurrent(Element element) /// 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 the top face holding the face's first triangle). Faces are grouped by their serialized face - /// (SourceFace, else MeshMarker) within their geometry node, as does; - /// the piece is the group of the first top face in serialized order. Null unless the top surface is in more than one - /// piece and a bottom piece of the same area (within 0.1%) faces it, so a sloped or partial solid keeps the whole - /// surface. In feet. + /// first (the part of its top face holding the face's first triangle). Null unless the top surface is horizontal at one + /// height and 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, stepped or partial solid keeps the whole upper surface. 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(); @@ -1478,34 +1478,116 @@ private List CoveringQuantitiesCurrent(Element element) foreach (var shell in all) { if (MiddleHeightCurrent(shell.Faces) is not { } middle) continue; - var top = shell.Faces - .Where(face => !face.CurvedSurface && FaceUnitNormal(face) is { } n && Math.Abs(n[2]) > 1e-9 && MeanHeightCurrent(face) >= middle) - .ToList(); - if (top.Count == 0) continue; - static (int Node, uint Face, uint Marker) Key(GeoFace face) => - (face.GeometryNode, face.SourceFace, face.MeshMarker); - var firstKey = Key(top[0]); - double PieceArea(IEnumerable faces, (int Node, uint Face, uint Marker) key) => faces - .Where(face => Key(face).Equals(key)) - .Sum(face => (NetFaceArea(face) ?? 0) + ArcSegmentCorrectionCurrent(face, arcs) / Math.Abs(FaceUnitNormal(face)![2])); - double topPiece = PieceArea(top, firstKey); + 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; - double topWhole = top.Sum(face => (NetFaceArea(face) ?? 0) + ArcSegmentCorrectionCurrent(face, arcs) / Math.Abs(FaceUnitNormal(face)![2])); - // A single-piece surface is not a pieces case; the caller then uses the whole surface as before. - if (Math.Abs(topWhole - topPiece) <= 1e-9) return null; - var bottom = shell.Faces - .Where(face => !face.CurvedSurface && FaceUnitNormal(face) is { } n && Math.Abs(n[2]) > 1e-9 && MeanHeightCurrent(face) < middle) - .ToList(); - if (bottom.Count == 0) continue; - double bottomPiece = PieceArea(bottom, Key(bottom[0])); - if (!(bottomPiece > 1e-9)) return null; - // The saved-mesh rule applies where the faces facing each way hold a part of the same area (RE-480/RE-486). - if (Math.Abs(bottomPiece - topPiece) > 0.001 * topPiece) 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 index 0b87820d..b31a0107 100644 --- a/tests/RvtIO.Tests/CoveringFirstPieceTests.cs +++ b/tests/RvtIO.Tests/CoveringFirstPieceTests.cs @@ -4,53 +4,89 @@ namespace RvtIO.Tests; -/// RE-486: a ceiling in pieces takes the piece holding its first top face, not the whole surface. +/// 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 sloped or stepped solid, +/// or one without a single matching underside piece, keeps the whole upper surface. public class CoveringFirstPieceTests { - private static GeoFace MakeFace(double x0, double y0, double size, double z, int node, uint source) + 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(); - face.OuterVertices.Add(new double[3] { x0, y0, z }); - face.OuterVertices.Add(new double[3] { x0 + size, y0, z }); - face.OuterVertices.Add(new double[3] { x0 + size, y0 + size, z }); - face.OuterVertices.Add(new double[3] { x0, y0 + size, z }); - face.GeometryNode = node; + 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 TwoPieceGeometry() - { - var geometry = new GeometryData(); - geometry.Faces = new List(); - geometry.Faces.Add(MakeFace(0, 0, 10, 10, 1, 1)); - geometry.Faces.Add(MakeFace(20, 0, 10, 10, 1, 2)); - geometry.Faces.Add(MakeFace(0, 0, 10, 0, 1, 1)); - geometry.Faces.Add(MakeFace(20, 0, 10, 0, 1, 2)); - return geometry; - } + 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(TwoPieceGeometry()); + 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(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 = new GeometryData(); - geometry.Faces = new List(); - geometry.Faces.Add(MakeFace(0, 0, 10, 10, 1, 1)); - geometry.Faces.Add(MakeFace(0, 0, 10, 0, 1, 1)); + 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)); @@ -59,14 +95,147 @@ public void SinglePiece_ReturnsNullSoCallerKeepsTheWholeSurface() [Fact] public void MismatchedBottom_ReturnsNull() { - // Bottom piece of a different area: no matching counterpart, keep the whole surface. - var geometry = new GeometryData(); - geometry.Faces = new List(); - geometry.Faces.Add(MakeFace(0, 0, 10, 10, 1, 1)); - geometry.Faces.Add(MakeFace(20, 0, 10, 10, 1, 2)); - geometry.Faces.Add(MakeFace(0, 0, 5, 0, 1, 1)); + 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_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); } } From c91ec534496cc4a1085b19d66364893ad3134175 Mon Sep 17 00:00:00 2001 From: mie Date: Mon, 16 Nov 2026 18:21:25 +0300 Subject: [PATCH 007/259] pdf: validate font tables and fall through corrupt preferred fonts Review #250: a 16-byte RVTIO_FONTS arial.ttf threw ArgumentOutOfRangeException and aborted TryFind instead of falling back to system Arial. PdfTrueTypeFont now bounds-checks the table directory and each table/cmap read (Need helper) and reports truncation as NotSupportedException (out-of-range reads also mapped). TryFind also tolerates ArgumentException from malformed input. Adds Debian Bookworm liberation2 candidate path. Tests cover truncated rejection and corrupt-preferred fallback. --- src/RvtIO/Pdf/PdfFonts.cs | 9 ++- src/RvtIO/Pdf/PdfTrueTypeFont.cs | 106 +++++++++++++++++++---------- tests/RvtIO.Tests/PdfFontsTests.cs | 36 ++++++++++ 3 files changed, 113 insertions(+), 38 deletions(-) diff --git a/src/RvtIO/Pdf/PdfFonts.cs b/src/RvtIO/Pdf/PdfFonts.cs index 284a1023..8919cd9e 100644 --- a/src/RvtIO/Pdf/PdfFonts.cs +++ b/src/RvtIO/Pdf/PdfFonts.cs @@ -25,6 +25,8 @@ public static class PdfFonts /// so a title wraps the same on every machine. private static readonly string[] Candidates = [ + // Debian Bookworm and later ship Liberation Sans in fonts-liberation2. + "/usr/share/fonts/truetype/liberation2/LiberationSans-Regular.ttf", "/usr/share/fonts/truetype/liberation/LiberationSans-Regular.ttf", "/usr/share/fonts/TTF/LiberationSans-Regular.ttf", "/usr/share/fonts/truetype/arimo/Arimo-Regular.ttf", @@ -57,9 +59,12 @@ public static class PdfFonts path = candidate; return font; } - catch (Exception exception) when (exception is NotSupportedException or IOException or UnauthorizedAccessException) + catch (Exception exception) when (exception is NotSupportedException or IOException or UnauthorizedAccessException + // A corrupt candidate must not abort the search: every out-of-range table read already + // reports NotSupportedException, this covers any other malformed-input failure. + or ArgumentException) { - // A .ttc collection or a font without a Unicode cmap: try the next candidate. + // A .ttc collection, a font without a Unicode cmap or a corrupt file: try the next candidate. } } return null; diff --git a/src/RvtIO/Pdf/PdfTrueTypeFont.cs b/src/RvtIO/Pdf/PdfTrueTypeFont.cs index f67a5e3b..18f6cf2a 100644 --- a/src/RvtIO/Pdf/PdfTrueTypeFont.cs +++ b/src/RvtIO/Pdf/PdfTrueTypeFont.cs @@ -23,49 +23,76 @@ public PdfTrueTypeFont(string path) : this(File.ReadAllBytes(path), Path.GetFile /// Parses TrueType font bytes. /// The font file. /// The PostScript base name written into the PDF. - /// The file is not a TrueType font with a Unicode cmap. + /// The file is not a TrueType font with a Unicode cmap, + /// or its tables are truncated or corrupt. public PdfTrueTypeFont(byte[] file, string name) { ArgumentNullException.ThrowIfNull(file); _file = file; Name = string.IsNullOrWhiteSpace(name) ? "RvtIOFont" : name; - if (file.Length < 12 || BinaryPrimitives.ReadUInt32BigEndian(file) != 0x00010000) - throw new NotSupportedException("Only a TrueType font (0x00010000) is supported."); - - var tables = new Dictionary(StringComparer.Ordinal); - int count = BinaryPrimitives.ReadUInt16BigEndian(file.AsSpan(4)); - for (int i = 0; i < count; i++) + try { - int at = 12 + i * 16; - string tag = Encoding.ASCII.GetString(file, at, 4); - tables[tag] = ((int)BinaryPrimitives.ReadUInt32BigEndian(file.AsSpan(at + 8)), - (int)BinaryPrimitives.ReadUInt32BigEndian(file.AsSpan(at + 12))); + if (file.Length < 12 || BinaryPrimitives.ReadUInt32BigEndian(file) != 0x00010000) + throw new NotSupportedException("Only a TrueType font (0x00010000) is supported."); + + var tables = new Dictionary(StringComparer.Ordinal); + int count = BinaryPrimitives.ReadUInt16BigEndian(file.AsSpan(4)); + for (int i = 0; i < count; i++) + { + int at = 12 + i * 16; + Need(file, at, 16, "table directory"); + string tag = Encoding.ASCII.GetString(file, at, 4); + int offset = (int)BinaryPrimitives.ReadUInt32BigEndian(file.AsSpan(at + 8)); + int length = (int)BinaryPrimitives.ReadUInt32BigEndian(file.AsSpan(at + 12)); + Need(file, offset, length, tag); + tables[tag] = (offset, length); + } + if (!tables.TryGetValue("head", out var head) || !tables.TryGetValue("hhea", out var hhea) + || !tables.TryGetValue("maxp", out var maxp) || !tables.TryGetValue("hmtx", out var hmtx) + || !tables.TryGetValue("cmap", out var cmap)) + throw new NotSupportedException("The font lacks head, hhea, maxp, hmtx or cmap."); + Need(file, head.Offset, 44, "head"); + Need(file, hhea.Offset, 36, "hhea"); + Need(file, maxp.Offset, 6, "maxp"); + Need(file, cmap.Offset, 4, "cmap"); + + _unitsPerEm = BinaryPrimitives.ReadUInt16BigEndian(file.AsSpan(head.Offset + 18)); + if (_unitsPerEm == 0) throw new NotSupportedException("The font declares no units per em."); + XMin = BinaryPrimitives.ReadInt16BigEndian(file.AsSpan(head.Offset + 36)); + YMin = BinaryPrimitives.ReadInt16BigEndian(file.AsSpan(head.Offset + 38)); + XMax = BinaryPrimitives.ReadInt16BigEndian(file.AsSpan(head.Offset + 40)); + YMax = BinaryPrimitives.ReadInt16BigEndian(file.AsSpan(head.Offset + 42)); + + Ascent = BinaryPrimitives.ReadInt16BigEndian(file.AsSpan(hhea.Offset + 4)); + Descent = BinaryPrimitives.ReadInt16BigEndian(file.AsSpan(hhea.Offset + 6)); + int metrics = BinaryPrimitives.ReadUInt16BigEndian(file.AsSpan(hhea.Offset + 34)); + int glyphs = BinaryPrimitives.ReadUInt16BigEndian(file.AsSpan(maxp.Offset + 4)); + if (metrics < 1) throw new NotSupportedException("The font has no horizontal metrics."); + Need(file, hmtx.Offset, (long)(metrics - 1) * 4 + 2, "hmtx"); + _advances = new int[Math.Max(glyphs, 1)]; + for (int gid = 0; gid < glyphs; gid++) + { + int at = hmtx.Offset + Math.Min(gid, metrics - 1) * 4; + _advances[gid] = BinaryPrimitives.ReadUInt16BigEndian(file.AsSpan(at)); + } + + ReadCmap(file, cmap); + if (_glyphByCode.Count == 0) throw new NotSupportedException("The font has no Unicode cmap for the BMP."); } - if (!tables.TryGetValue("head", out var head) || !tables.TryGetValue("hhea", out var hhea) - || !tables.TryGetValue("maxp", out var maxp) || !tables.TryGetValue("hmtx", out var hmtx) - || !tables.TryGetValue("cmap", out var cmap)) - throw new NotSupportedException("The font lacks head, hhea, maxp, hmtx or cmap."); - - _unitsPerEm = BinaryPrimitives.ReadUInt16BigEndian(file.AsSpan(head.Offset + 18)); - if (_unitsPerEm == 0) throw new NotSupportedException("The font declares no units per em."); - XMin = BinaryPrimitives.ReadInt16BigEndian(file.AsSpan(head.Offset + 36)); - YMin = BinaryPrimitives.ReadInt16BigEndian(file.AsSpan(head.Offset + 38)); - XMax = BinaryPrimitives.ReadInt16BigEndian(file.AsSpan(head.Offset + 40)); - YMax = BinaryPrimitives.ReadInt16BigEndian(file.AsSpan(head.Offset + 42)); - - Ascent = BinaryPrimitives.ReadInt16BigEndian(file.AsSpan(hhea.Offset + 4)); - Descent = BinaryPrimitives.ReadInt16BigEndian(file.AsSpan(hhea.Offset + 6)); - int metrics = BinaryPrimitives.ReadUInt16BigEndian(file.AsSpan(hhea.Offset + 34)); - int glyphs = BinaryPrimitives.ReadUInt16BigEndian(file.AsSpan(maxp.Offset + 4)); - _advances = new int[Math.Max(glyphs, 1)]; - for (int gid = 0; gid < glyphs; gid++) + catch (ArgumentOutOfRangeException exception) { - int at = hmtx.Offset + Math.Min(gid, metrics - 1) * 4; - _advances[gid] = BinaryPrimitives.ReadUInt16BigEndian(file.AsSpan(at)); + // Every out-of-range table read is a truncated or corrupt font, reported as + // unsupported so a caller trying candidates falls through to the next one. + throw new NotSupportedException("Truncated or corrupt TrueType font.", exception); } + } - ReadCmap(file, cmap); - if (_glyphByCode.Count == 0) throw new NotSupportedException("The font has no Unicode cmap for the BMP."); + /// Requires [offset, offset + length) to lie inside the file. + /// The font is truncated: the table does not fit. + private static void Need(byte[] file, long offset, long length, string what) + { + if (offset < 0 || length < 0 || offset + length > file.Length) + throw new NotSupportedException($"Truncated TrueType font: {what} runs past the end of the file."); } /// The PostScript base name of the font. @@ -99,9 +126,11 @@ private void ReadCmap(byte[] file, (int Offset, int Length) cmap) for (int i = 0; i < count; i++) { int at = cmap.Offset + 4 + i * 8; + Need(file, at, 8, "cmap encoding record"); int platform = BinaryPrimitives.ReadUInt16BigEndian(file.AsSpan(at)); int encoding = BinaryPrimitives.ReadUInt16BigEndian(file.AsSpan(at + 2)); int offset = cmap.Offset + (int)BinaryPrimitives.ReadUInt32BigEndian(file.AsSpan(at + 4)); + Need(file, offset, 2, "cmap subtable"); int format = BinaryPrimitives.ReadUInt16BigEndian(file.AsSpan(offset)); int score = (platform, encoding, format) switch { @@ -121,7 +150,9 @@ private void ReadCmap(byte[] file, (int Offset, int Length) cmap) private void ReadFormat4(byte[] file, int at) { + Need(file, at, 8, "cmap format 4 header"); int segments = BinaryPrimitives.ReadUInt16BigEndian(file.AsSpan(at + 6)) / 2; + Need(file, at, 16L + segments * 8L, "cmap format 4"); int endCodes = at + 14; int startCodes = endCodes + segments * 2 + 2; int deltas = startCodes + segments * 2; @@ -154,10 +185,13 @@ private void ReadFormat4(byte[] file, int at) private void ReadFormat12(byte[] file, int at) { - int groups = (int)BinaryPrimitives.ReadUInt32BigEndian(file.AsSpan(at + 12)); - for (int g = 0; g < groups; g++) + Need(file, at, 16, "cmap format 12 header"); + long groups = BinaryPrimitives.ReadUInt32BigEndian(file.AsSpan(at + 12)); + if (groups < 0 || 16 + groups * 12 > file.Length - (long)at) + throw new NotSupportedException("Truncated TrueType font: cmap format 12 lists more groups than fit."); + for (long g = 0; g < groups; g++) { - int entry = at + 16 + g * 12; + int entry = at + 16 + (int)(g * 12); int start = (int)BinaryPrimitives.ReadUInt32BigEndian(file.AsSpan(entry)); int end = (int)BinaryPrimitives.ReadUInt32BigEndian(file.AsSpan(entry + 4)); int glyph = (int)BinaryPrimitives.ReadUInt32BigEndian(file.AsSpan(entry + 8)); diff --git a/tests/RvtIO.Tests/PdfFontsTests.cs b/tests/RvtIO.Tests/PdfFontsTests.cs index 16deb436..546d1732 100644 --- a/tests/RvtIO.Tests/PdfFontsTests.cs +++ b/tests/RvtIO.Tests/PdfFontsTests.cs @@ -16,6 +16,8 @@ public void CandidateFiles_ListsSubstitutesBeforeDejaVu() int dejavu = files.FindIndex(f => f.Contains("DejaVuSans", StringComparison.Ordinal)); Assert.True(liberation >= 0 && arimo >= 0 && dejavu >= 0); Assert.True(liberation < dejavu && arimo < dejavu); + // Debian Bookworm's fonts-liberation2 path, ahead of the older liberation path. + Assert.Contains("/usr/share/fonts/truetype/liberation2/LiberationSans-Regular.ttf", files); } [Fact] @@ -39,4 +41,38 @@ public void CandidateFiles_EmptyEnvGivesMachineCandidatesOnly() Assert.DoesNotContain(files, f => f.StartsWith("/fonts/", StringComparison.Ordinal)); Assert.Contains(files, f => f.Contains("DejaVuSans", StringComparison.Ordinal)); } + + [Fact] + public void TruncatedFont_ReportsUnsupportedInsteadOfOverrunningTables() + { + // The review's repro: a 16-byte file with a valid magic and one declared + // but truncated table directory entry. + byte[] truncated = new byte[16]; + truncated[1] = 1; + truncated[5] = 1; + + var error = Assert.Throws(() => new PdfTrueTypeFont(truncated, "bad")); + Assert.Contains("runcated", error.Message, StringComparison.OrdinalIgnoreCase); + } + + [Fact] + public void TryFind_InvalidPreferredFontFallsThroughWithoutThrowing() + { + string folder = Path.Combine(Path.GetTempPath(), "rvtio-bad-font-" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(folder); + try + { + byte[] truncated = new byte[16]; + truncated[1] = 1; + truncated[5] = 1; + File.WriteAllBytes(Path.Combine(folder, "arial.ttf"), truncated); + + // Must not throw: a corrupt preferred font is skipped like an unsupported one. + PdfFonts.TryFind(_ => folder, out string? _); + } + finally + { + Directory.Delete(folder, true); + } + } } From ae4acb3d691c6ee9f420c2b8d53d84253e8d14ff Mon Sep 17 00:00:00 2001 From: mie Date: Mon, 16 Nov 2026 18:30:38 +0300 Subject: [PATCH 008/259] print: cut joined wall ends to the retained-side near face Review #252: an end past the partner axis kept the far face (end stayed at 3050 instead of 2900) and starts moved to the axis (3000) instead of the face (3100). Choose the near face from the retained wall side (direction sign per end) and solve the +u displacement with per-end overshoot (end shortens on -t, start on +t). Offset tests cover both sides of the axis for starts and ends. --- src/RvtIO/Print/PlanPrinter.cs | 30 ++++++++++------- tests/RvtIO.Tests/PlanWallJoinCutbackTests.cs | 32 +++++++++++++++++++ 2 files changed, 51 insertions(+), 11 deletions(-) diff --git a/src/RvtIO/Print/PlanPrinter.cs b/src/RvtIO/Print/PlanPrinter.cs index dc7a964f..bc6381e3 100644 --- a/src/RvtIO/Print/PlanPrinter.cs +++ b/src/RvtIO/Print/PlanPrinter.cs @@ -250,26 +250,34 @@ public static PdfDocument RenderViews(RvtDocument document, IReadOnlyList v bool mutualEnd = partnerElement.SerializedWallEndJoins?.Any(partnerJoin => partnerJoin.ElementId == wall.Id && partnerJoin.JoinedEnd is 0 or 1 && partnerJoin.JoinType == 0) == true; if (mutualEnd && join.JoinedEnd is 0 or 1) continue; - // The near face of the partner on the side of this end: the face a point just inside - // the wall stands on (an end exactly on the partner's axis faces both sides at once). + // The near face of the partner on the side the wall comes from: travelling along + // the wall into the join first meets that face. For the end (tip in +u) the wall + // approaches along +u, so the retained interior lies behind (-denom side); for the + // start the wall leaves along +u, so the interior lies ahead (+denom side). A probe + // just inside the tip fails once the tip has crossed the partner axis, choosing the + // far face instead. double nx = -vy, ny = vx; double ex = end == 0 ? wall.X1 : wall.X2, ey = end == 0 ? wall.Y1 : wall.Y2; double s = (ex - partner.X1) * nx + (ey - partner.Y1) * ny; double denom = ux * nx + uy * ny; if (Math.Abs(denom) < 0.98) continue; - double probe = s - denom * 1e-3; - if (Math.Abs(probe) < 1e-9) continue; - double facing = Math.Sign(probe) * partner.Width / 2; + double side = end == 0 ? Math.Sign(denom) : -Math.Sign(denom); + if (side == 0) continue; + double facing = side * partner.Width / 2; + // Displacement along +u that plants the tip on the face. The start moves forward + // (+t shortens), the end moves back (-t shortens); only an overshoot past the face + // is taken back, never an extension, and at least a millimetre. double t = (facing - s) / denom; - // The end must stand on the partner's span, and only an overshoot past the face is taken back. + // The tip must stand on the partner's span, and only an overshoot past the face + // is taken back, never an extension, and at least a millimetre. double along = (ex - partner.X1) * vx + (ey - partner.Y1) * vy; if (along < -partner.Width / 2 - 1 || along > partnerLength + partner.Width / 2 + 1) continue; - if (t >= -1) continue; - double newLength = length + t; + bool overshoot = end == 0 ? t >= 1 : t <= -1; + if (!overshoot) continue; + double newLength = end == 0 ? length - t : length + t; if (newLength < Math.Max(wall.Width, 10)) continue; - // t < 0 shortens the wall: the start moves forward along +u, the end moves back. - double newX = end == 0 ? ex - ux * t : ex + ux * t; - double newY = end == 0 ? ey - uy * t : ey + uy * t; + double newX = ex + ux * t; + double newY = ey + uy * t; result[i] = end == 0 ? (wall.Id, newX, newY, wall.X2, wall.Y2, wall.Width) : (wall.Id, wall.X1, wall.Y1, newX, newY, wall.Width); wall = result[i]; diff --git a/tests/RvtIO.Tests/PlanWallJoinCutbackTests.cs b/tests/RvtIO.Tests/PlanWallJoinCutbackTests.cs index 4d1fa577..0e29dce0 100644 --- a/tests/RvtIO.Tests/PlanWallJoinCutbackTests.cs +++ b/tests/RvtIO.Tests/PlanWallJoinCutbackTests.cs @@ -153,4 +153,36 @@ public void StartEnd_IsCutToo() Assert.Equal(Feet(10) + 100, wall.X1, 3); Assert.Equal(Feet(20), wall.X2, 3); } + + private static double CutEnd(double x1, double x2, int end, bool checkStart) + { + var source = new Element + { + Id = 600, + SerializedWallEndJoins = [new TfBlockDeserializer.WallEndJoin(end, 601, 2, 0)], + }; + var partner = new Element { Id = 601 }; + var walls = new List<(int Id, double X1, double Y1, double X2, double Y2, double Width)> + { + (600, x1, 0, x2, 0, 200), + (601, 3000, -1000, 3000, 1000, 200), + }; + var result = PlanPrinter.CutBackJoinedEnds( + walls, new Dictionary { [600] = source, [601] = partner })[0]; + return checkStart ? result.X1 : result.X2; + } + + [Fact] + public void OffsetEnds_AreCutToTheNearFaceOnBothSides() + { + // Vertical partner centred at x=3000, width 200: the near face is 2900 for a wall + // ending from the west and 3100 for a wall starting to the east. The on-axis + // controls already pass through CollectLevel above. + Assert.Equal(2900, CutEnd(0, 3000, 1, checkStart: false), 3); + Assert.Equal(2900, CutEnd(0, 3050, 1, checkStart: false), 3); + Assert.Equal(2900, CutEnd(0, 2950, 1, checkStart: false), 3); + Assert.Equal(3100, CutEnd(3000, 6000, 0, checkStart: true), 3); + Assert.Equal(3100, CutEnd(2950, 6000, 0, checkStart: true), 3); + Assert.Equal(3100, CutEnd(3050, 6000, 0, checkStart: true), 3); + } } From cac14be5ce292de379943441900d38078423b213 Mon Sep 17 00:00:00 2001 From: mie Date: Mon, 16 Nov 2026 19:45:28 +0300 Subject: [PATCH 009/259] ifc: keep whole ceiling area when the first top face is sloped Recheck #249: with a sloped first top face followed by horizontal pieces, the rule picked the later 100 ft2 part (9.29 m2) instead of keeping the whole 436.80 ft2 (40.58 m2). The piece rule now applies only when the first top face itself is horizontal, per RE-486; otherwise the whole upper surface stays. Caller-level regression test covers sloped-first with later horizontal pieces. --- .../Ifc/IfcExporter.QuantitiesCurrent.cs | 17 +++++++++-- tests/RvtIO.Tests/CoveringFirstPieceTests.cs | 29 +++++++++++++++++-- 2 files changed, 41 insertions(+), 5 deletions(-) diff --git a/src/RvtIO/Ifc/IfcExporter.QuantitiesCurrent.cs b/src/RvtIO/Ifc/IfcExporter.QuantitiesCurrent.cs index b7b9598b..22a533e3 100644 --- a/src/RvtIO/Ifc/IfcExporter.QuantitiesCurrent.cs +++ b/src/RvtIO/Ifc/IfcExporter.QuantitiesCurrent.cs @@ -1466,9 +1466,10 @@ private List CoveringQuantitiesCurrent(Element element) /// 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 top surface is horizontal at one - /// height and 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, stepped or partial solid keeps the whole upper surface. Pieces are + /// 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) @@ -1478,6 +1479,16 @@ private List CoveringQuantitiesCurrent(Element element) 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); diff --git a/tests/RvtIO.Tests/CoveringFirstPieceTests.cs b/tests/RvtIO.Tests/CoveringFirstPieceTests.cs index b31a0107..43934230 100644 --- a/tests/RvtIO.Tests/CoveringFirstPieceTests.cs +++ b/tests/RvtIO.Tests/CoveringFirstPieceTests.cs @@ -5,8 +5,8 @@ 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 sloped or stepped solid, -/// or one without a single matching underside piece, keeps the whole upper 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; @@ -214,6 +214,31 @@ public void Caller_TwoPiecesWithoutHostArea_WritesTheFirstPiece() 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() { From e4f3595fb22e351212e828ccbf3ddb4124c60d05 Mon Sep 17 00:00:00 2001 From: mahach666 <79989386+mahach666@users.noreply.github.com> Date: Wed, 18 Nov 2026 03:03:13 +0300 Subject: [PATCH 010/259] Separate shared geometry and file identity from exporters --- CONTRIBUTING.md | 5 + src/RvtIO.Cli/CoverageCommand.cs | 3 +- src/RvtIO.Cli/DowngradeCommand.cs | 3 +- src/RvtIO.Cli/ExportCommand.cs | 13 +- src/RvtIO.Cli/PrintCommand.cs | 7 +- src/RvtIO.Cli/SaveAsCommand.cs | 3 +- src/RvtIO.Cli/SheetsCommand.cs | 3 +- src/RvtIO/Diagnostics/ExportReport.cs | 129 +----------------- src/RvtIO/Geometry/GeometryValidation.cs | 55 ++++++++ .../Ifc/IfcExporter.FaceBoundsCurrent.cs | 45 +----- .../Ifc/IfcExporter.PlanSpaceBodyCurrent.cs | 3 +- src/RvtIO/Ifc/IfcExporter.cs | 16 +-- src/RvtIO/Internal/FileIdentity.cs | 127 +++++++++++++++++ .../Parsing/GRepParserV2.SpaceLiteral.cs | 3 +- src/RvtIO/Writing/RvtWriter.cs | 5 +- tests/RvtIO.Tests/ExportReportTests.cs | 39 +++--- .../IfcExporterBodylessProductGateTests.cs | 3 +- .../IfcExporterCurrentFaceBoundsTests.cs | 13 +- tests/RvtIO.Tests/RvtWriterTests.cs | 13 +- 19 files changed, 257 insertions(+), 231 deletions(-) create mode 100644 src/RvtIO/Geometry/GeometryValidation.cs create mode 100644 src/RvtIO/Internal/FileIdentity.cs diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 7b82c7a9..275ae7db 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -52,6 +52,11 @@ dotnet test The library is in `src/RvtIO`, the CLI in `src/RvtIO.Cli`, and tests in `tests/RvtIO.Tests`. +Keep file and geometry operations shared by the reader, writer and exporters +in the library's format or geometry code. For example, polygon and bounds +validation belong in `Geometry`, and path identity belongs in `Internal`. +`RvtIO.Scene` builds on the public RvtIO API and references IOScene separately. + Tests that need real Revit files are skipped with a message when private fixtures are unavailable. Set `RVTIO_TEST_FILES` to the folder containing your private fixtures to run them. The repository ships no Revit models. diff --git a/src/RvtIO.Cli/CoverageCommand.cs b/src/RvtIO.Cli/CoverageCommand.cs index ef7328fd..f764a3ff 100644 --- a/src/RvtIO.Cli/CoverageCommand.cs +++ b/src/RvtIO.Cli/CoverageCommand.cs @@ -1,4 +1,5 @@ using System.Globalization; +using RvtIO.Internal; namespace RvtIO.Cli; @@ -132,7 +133,7 @@ private static string Percent(long part, long whole) Path.GetFullPath(file); if (report == null) return null; if (Directory.Exists(report)) return "--report names a directory, not a file."; - return ExportReport.SameFile(report, file) ? "--report must not name the input file." : null; + return FileIdentity.SameFile(report, file) ? "--report must not name the input file." : null; } catch (Exception exception) when (exception is ArgumentException or NotSupportedException or PathTooLongException or IOException or UnauthorizedAccessException) { diff --git a/src/RvtIO.Cli/DowngradeCommand.cs b/src/RvtIO.Cli/DowngradeCommand.cs index 46affa18..346702c7 100644 --- a/src/RvtIO.Cli/DowngradeCommand.cs +++ b/src/RvtIO.Cli/DowngradeCommand.cs @@ -2,6 +2,7 @@ using System.Text; using System.Text.Json; using System.Text.Json.Serialization; +using RvtIO.Internal; using RvtIO.Writing; namespace RvtIO.Cli; @@ -100,7 +101,7 @@ internal static int Run(string[] args, TextWriter output, TextWriter error) Path.GetFullPath(profile); if (report == null) return null; if (Directory.Exists(report)) return "--report names a directory, not a file."; - if (ExportReport.SameFile(report, source) || ExportReport.SameFile(report, profile)) return "--report must not name the source file or the profile file."; + if (FileIdentity.SameFile(report, source) || FileIdentity.SameFile(report, profile)) return "--report must not name the source file or the profile file."; return null; } catch (Exception exception) when (exception is ArgumentException or NotSupportedException or PathTooLongException or IOException or UnauthorizedAccessException) diff --git a/src/RvtIO.Cli/ExportCommand.cs b/src/RvtIO.Cli/ExportCommand.cs index adb4beb3..89dddf00 100644 --- a/src/RvtIO.Cli/ExportCommand.cs +++ b/src/RvtIO.Cli/ExportCommand.cs @@ -1,5 +1,6 @@ using System.Text.Json; using System.Text.Json.Serialization; +using RvtIO.Internal; using RvtIO; using RvtIO.Compact; using RvtIO.BuiltIns; @@ -33,7 +34,7 @@ private static int Export(ExportArguments arguments) Console.Error.WriteLine($"{opt} requires a non-empty path."); return 1; } - if (ExportReport.SameFile(outPath, rvtPath)) + if (FileIdentity.SameFile(outPath, rvtPath)) { Console.Error.WriteLine($"An export destination must not name the input file: '{outPath}'. Nothing was read or written."); return 1; @@ -44,7 +45,7 @@ private static int Export(ExportArguments arguments) { for (int j = i + 1; j < exportOutputs.Count; j++) { - if (ExportReport.SameFile(exportOutputs[i].Path, exportOutputs[j].Path)) + if (FileIdentity.SameFile(exportOutputs[i].Path, exportOutputs[j].Path)) { Console.Error.WriteLine($"Export destinations must not name the same file: '{exportOutputs[i].Path}'. Nothing was read or written."); return 1; @@ -88,10 +89,10 @@ private static int Export(ExportArguments arguments) Console.Error.WriteLine("--report requires one value: the path of the JSON report."); return 1; } - if (reportPath != null && (ExportReport.SameFile(reportPath, rvtPath) - || exportOutputs.Any(outPath => ExportReport.SameFile(reportPath, outPath.Path)) - || (externalDumpPath != null && ExportReport.SameFile(reportPath, externalDumpPath)) - || RvtIO.Cli.ReportPathOption.OutputPaths(args, rvtPath, exportOutputs.FirstOrDefault().Path, externalDumpPath).Any(path => ExportReport.SameFile(reportPath, path)))) + if (reportPath != null && (FileIdentity.SameFile(reportPath, rvtPath) + || exportOutputs.Any(outPath => FileIdentity.SameFile(reportPath, outPath.Path)) + || (externalDumpPath != null && FileIdentity.SameFile(reportPath, externalDumpPath)) + || RvtIO.Cli.ReportPathOption.OutputPaths(args, rvtPath, exportOutputs.FirstOrDefault().Path, externalDumpPath).Any(path => FileIdentity.SameFile(reportPath, path)))) { Console.Error.WriteLine("--report must not name the input file or an output of the run; nothing was read or written."); return 1; diff --git a/src/RvtIO.Cli/PrintCommand.cs b/src/RvtIO.Cli/PrintCommand.cs index 04370655..5ba6af91 100644 --- a/src/RvtIO.Cli/PrintCommand.cs +++ b/src/RvtIO.Cli/PrintCommand.cs @@ -1,4 +1,5 @@ using System.Globalization; +using RvtIO.Internal; using RvtIO; using RvtIO.Pdf; using RvtIO.Print; @@ -89,10 +90,8 @@ internal static int Run(string[] args, TextWriter output, TextWriter error) return Usage(error, "--where selects sheets; it needs --sheet, --all-sheets or --list-sheets."); bool listing = listLevels || listViews || listSheets; if (!listing && outputPath == null) return Usage(error, "print requires the output PDF path."); - // The comparison is the file's identity, not the spelling of the paths: an output path that is a hard link, - // symbolic link or junction to the input PDF would truncate the model. ExportReport.SameFile guards the other - // writing commands the same way. - if (outputPath != null && ExportReport.SameFile(outputPath, file)) + // File identity also catches when a link in the output path points to the input model. + if (outputPath != null && FileIdentity.SameFile(outputPath, file)) { error.WriteLine("The output path is the input file. Nothing was read or written."); return RvtExitCodes.Usage; diff --git a/src/RvtIO.Cli/SaveAsCommand.cs b/src/RvtIO.Cli/SaveAsCommand.cs index 6ac81d60..6d1572f2 100644 --- a/src/RvtIO.Cli/SaveAsCommand.cs +++ b/src/RvtIO.Cli/SaveAsCommand.cs @@ -1,4 +1,5 @@ using System.Globalization; +using RvtIO.Internal; namespace RvtIO.Cli; @@ -112,7 +113,7 @@ private static void PrintCapabilities(TextWriter output, string sourceName, RvtW if (report is null) return null; Path.GetFullPath(report); if (Directory.Exists(report)) return "--report names a directory, not a file."; - if (ExportReport.SameFile(report, source) || (destination is not null && ExportReport.SameFile(report, destination))) + if (FileIdentity.SameFile(report, source) || (destination is not null && FileIdentity.SameFile(report, destination))) return "--report must not name the source or output file."; return null; } diff --git a/src/RvtIO.Cli/SheetsCommand.cs b/src/RvtIO.Cli/SheetsCommand.cs index 0a04938c..97f73a8a 100644 --- a/src/RvtIO.Cli/SheetsCommand.cs +++ b/src/RvtIO.Cli/SheetsCommand.cs @@ -1,6 +1,7 @@ using System.Text.Json; using System.Text.Json.Serialization; using RvtIO; +using RvtIO.Internal; using RvtIO.Sheets; namespace RvtIO.Cli; @@ -85,7 +86,7 @@ internal static int Run(string[] args, TextWriter output, TextWriter error) error.WriteLine(Usage); return RvtExitCodes.Usage; } - if (outputPath != null && ExportReport.SameFile(file, outputPath)) + if (outputPath != null && FileIdentity.SameFile(file, outputPath)) { error.WriteLine("The output path is the input file. Nothing was read or written."); return RvtExitCodes.Usage; diff --git a/src/RvtIO/Diagnostics/ExportReport.cs b/src/RvtIO/Diagnostics/ExportReport.cs index 794bad6d..8e574cf1 100644 --- a/src/RvtIO/Diagnostics/ExportReport.cs +++ b/src/RvtIO/Diagnostics/ExportReport.cs @@ -1,5 +1,6 @@ using System.Text.Json; using System.Text.Json.Serialization; +using RvtIO.Geometry; using RvtIO.Model; namespace RvtIO; @@ -308,130 +309,6 @@ public sealed class ReportSkipped public List Examples { get; set; } = new(); } - /// True when both paths name the same file. Existing files are compared by file identity (volume and file index on Windows, - /// device and inode on Linux and macOS), which catches hard links, file links and directory links (junctions, directory symbolic links) - /// anywhere in the path. Otherwise, or when a file does not exist yet, the real paths are compared: every existing component is resolved - /// through its links, so a report path below a linked directory is recognised before the file is created. Used to refuse a report path - /// that would overwrite the input or the export output. - internal static bool SameFile(string first, string second) - { - string a = Path.GetFullPath(first), b = Path.GetFullPath(second); - if (File.Exists(a) && File.Exists(b) && FileIdentity(a) is { } ia && FileIdentity(b) is { } ib) return ia == ib; - var comparison = OperatingSystem.IsWindows() || OperatingSystem.IsMacOS() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal; - return string.Equals(RealPath(a), RealPath(b), comparison); - } - - /// The path with every existing component resolved through its symbolic links and junctions; components that do not exist are kept. - internal static string RealPath(string fullPath, int depth = 0) - { - string root = Path.GetPathRoot(fullPath) ?? ""; - string current = root; - foreach (string part in fullPath[root.Length..].Split(new[] { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar }, StringSplitOptions.RemoveEmptyEntries)) - { - current = Path.Combine(current, part); - FileSystemInfo info = Directory.Exists(current) ? new DirectoryInfo(current) : new FileInfo(current); - // a link loop has no real path: stop resolving and compare what is left - if (depth < 32 && info.Exists && info.LinkTarget != null && info.ResolveLinkTarget(returnFinalTarget: true) is { } target) - current = RealPath(target.FullName, depth + 1); - } - return current; - } - - // Volume serial number and file index on Windows, or device and inode on Linux and macOS; null where the platform call is not available. - private static (ulong Device, ulong Inode)? FileIdentity(string path) - { - try - { - using var handle = File.OpenHandle(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete); - if (OperatingSystem.IsWindows()) - return GetFileInformationByHandle(handle, out var info) - ? (info.VolumeSerialNumber, ((ulong)info.FileIndexHigh << 32) | info.FileIndexLow) - : null; - if (OperatingSystem.IsLinux()) - return LinuxFileIdentity(handle); - if (OperatingSystem.IsMacOS()) - return DarwinFileIdentity(handle); - return null; - } - // a file that cannot be opened or queried is compared by path - catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or EntryPointNotFoundException or DllNotFoundException) - { - return null; - } - } - - private static (ulong Device, ulong Inode)? LinuxFileIdentity(Microsoft.Win32.SafeHandles.SafeFileHandle handle) - { - const int AtEmptyPath = 0x1000; - const uint StatxIno = 0x00000100u; - byte emptyPath = 0; - byte[] buffer = new byte[256]; - bool added = false; - try - { - handle.DangerousAddRef(ref added); - if (LinuxStatx((int)handle.DangerousGetHandle(), ref emptyPath, AtEmptyPath, StatxIno, ref buffer[0]) != 0) - return null; - } - finally - { - if (added) handle.DangerousRelease(); - } - uint mask = BitConverter.ToUInt32(buffer, 0); - if ((mask & StatxIno) == 0) return null; - ulong inode = BitConverter.ToUInt64(buffer, 32); - uint devMajor = BitConverter.ToUInt32(buffer, 136); - uint devMinor = BitConverter.ToUInt32(buffer, 140); - return (((ulong)devMajor << 32) | devMinor, inode); - } - - private static (ulong Device, ulong Inode)? DarwinFileIdentity(Microsoft.Win32.SafeHandles.SafeFileHandle handle) - { - byte[] buffer = new byte[256]; - bool added = false; - try - { - handle.DangerousAddRef(ref added); - int fd = (int)handle.DangerousGetHandle(); - int rc = System.Runtime.InteropServices.RuntimeInformation.ProcessArchitecture switch - { - System.Runtime.InteropServices.Architecture.Arm64 => DarwinFstatArm64(fd, ref buffer[0]), - System.Runtime.InteropServices.Architecture.X64 => DarwinFstatInode64(fd, ref buffer[0]), - _ => -1, - }; - if (rc != 0) return null; - } - finally - { - if (added) handle.DangerousRelease(); - } - // __DARWIN_STRUCT_STAT64: int32 st_dev at 0, uint16 st_mode at 4, uint16 st_nlink at 6, uint64 st_ino at 8. - uint device = BitConverter.ToUInt32(buffer, 0); - ulong inode = BitConverter.ToUInt64(buffer, 8); - return (device, inode); - } - - [System.Runtime.InteropServices.StructLayout(System.Runtime.InteropServices.LayoutKind.Sequential)] - private struct ByHandleFileInformation - { - public uint FileAttributes; - public System.Runtime.InteropServices.ComTypes.FILETIME CreationTime, LastAccessTime, LastWriteTime; - public uint VolumeSerialNumber, FileSizeHigh, FileSizeLow, NumberOfLinks, FileIndexHigh, FileIndexLow; - } - - [System.Runtime.InteropServices.DllImport("kernel32.dll", SetLastError = true)] - [return: System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.Bool)] - private static extern bool GetFileInformationByHandle(Microsoft.Win32.SafeHandles.SafeFileHandle file, out ByHandleFileInformation information); - - [System.Runtime.InteropServices.DllImport("libc", EntryPoint = "statx", SetLastError = true)] - private static extern int LinuxStatx(int dirfd, ref byte pathname, int flags, uint mask, ref byte statxbuf); - - [System.Runtime.InteropServices.DllImport("libSystem.dylib", EntryPoint = "fstat", SetLastError = true)] - private static extern int DarwinFstatArm64(int fd, ref byte statbuf); - - [System.Runtime.InteropServices.DllImport("libSystem.dylib", EntryPoint = "fstat$INODE64", SetLastError = true)] - private static extern int DarwinFstatInode64(int fd, ref byte statbuf); - // A stack trace names the source files of the build machine: keep the frames, drop the paths. internal static string StripSourcePaths(string trace) => System.Text.RegularExpressions.Regex.Replace(trace, @" in [^\r\n]*?:line \d+", ""); @@ -622,10 +499,10 @@ internal static GeometryQualityClass ClassifyJsonElementGeometry( } return approximated ? GeometryQualityClass.Approximated : GeometryQualityClass.Exact; } - if (Ifc.IfcExporter.BoundsAreValid(geo.BoundingBox)) + if (GeometryValidation.BoundsAreValid(geo.BoundingBox)) return GeometryQualityClass.BoxOnly; } - if (Ifc.IfcExporter.BoundsAreValid(element.DecodedBox)) + if (GeometryValidation.BoundsAreValid(element.DecodedBox)) return GeometryQualityClass.BoxOnly; return GeometryQualityClass.None; } diff --git a/src/RvtIO/Geometry/GeometryValidation.cs b/src/RvtIO/Geometry/GeometryValidation.cs new file mode 100644 index 00000000..9d715f7e --- /dev/null +++ b/src/RvtIO/Geometry/GeometryValidation.cs @@ -0,0 +1,55 @@ +namespace RvtIO.Geometry; + +internal static class GeometryValidation +{ + /// Checks that the six bounds coordinates are finite and each minimum is at or below its maximum. + internal static bool BoundsAreValid(double[]? bounds) + { + if (bounds is not { Length: >= 6 }) return false; + for (int i = 0; i < 6; i++) + if (!double.IsFinite(bounds[i])) return false; + return bounds[0] <= bounds[3] && bounds[1] <= bounds[4] && bounds[2] <= bounds[5]; + } + + internal static bool AllVerticesStrictlyInside(IReadOnlyList inner, IReadOnlyList outer) + { + double nx = 0, ny = 0, nz = 0; + for (int index = 0; index < outer.Count; index++) + { + var a = outer[index]; + var b = outer[(index + 1) % outer.Count]; + nx += (a[1] - b[1]) * (a[2] + b[2]); + ny += (a[2] - b[2]) * (a[0] + b[0]); + nz += (a[0] - b[0]) * (a[1] + b[1]); + } + int drop = Math.Abs(nx) >= Math.Abs(ny) && Math.Abs(nx) >= Math.Abs(nz) ? 0 : Math.Abs(ny) >= Math.Abs(nz) ? 1 : 2; + (double U, double V) Project(double[] point) => drop switch + { + 0 => (point[1], point[2]), + 1 => (point[0], point[2]), + _ => (point[0], point[1]), + }; + var polygon = outer.Select(Project).ToArray(); + const double tolerance = 1e-9; + foreach (var vertex in inner) + { + var (u, v) = Project(vertex); + bool inside = false; + for (int index = 0; index < polygon.Length; index++) + { + var (u1, v1) = polygon[index]; + var (u2, v2) = polygon[(index + 1) % polygon.Length]; + double dx = u2 - u1, dy = v2 - v1, length = Math.Sqrt(dx * dx + dy * dy); + if (length > 0) + { + double along = ((u - u1) * dx + (v - v1) * dy) / length; + double across = Math.Abs((u - u1) * dy - (v - v1) * dx) / length; + if (across <= tolerance && along >= -tolerance && along <= length + tolerance) return false; + } + if ((v1 > v) != (v2 > v) && u < (u2 - u1) * (v - v1) / (v2 - v1) + u1) inside = !inside; + } + if (!inside) return false; + } + return true; + } +} diff --git a/src/RvtIO/Ifc/IfcExporter.FaceBoundsCurrent.cs b/src/RvtIO/Ifc/IfcExporter.FaceBoundsCurrent.cs index de91e88d..a0e51a36 100644 --- a/src/RvtIO/Ifc/IfcExporter.FaceBoundsCurrent.cs +++ b/src/RvtIO/Ifc/IfcExporter.FaceBoundsCurrent.cs @@ -1,3 +1,4 @@ +using RvtIO.Geometry; using RvtIO.Model; namespace RvtIO.Ifc; @@ -63,7 +64,7 @@ private sealed record PreparedFaceCurrent(GeoFace Face, uint SourceFace, IReadOn { bool inner = false; for (int earlier = 0; earlier < index && !inner; earlier++) - inner = AllVerticesStrictlyInside(ordered[index]!, ordered[earlier]!); + inner = GeometryValidation.AllVerticesStrictlyInside(ordered[index]!, ordered[earlier]!); if (!inner) outer = index; } return ordered.Select((ring, index) => (ring!, index == outer)).ToList(); @@ -84,46 +85,4 @@ private sealed record PreparedFaceCurrent(GeoFace Face, uint SourceFace, IReadOn static double Dot(double[] a, double[] b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; } - - internal static bool AllVerticesStrictlyInside(IReadOnlyList inner, IReadOnlyList outer) - { - double nx = 0, ny = 0, nz = 0; - for (int index = 0; index < outer.Count; index++) - { - var a = outer[index]; - var b = outer[(index + 1) % outer.Count]; - nx += (a[1] - b[1]) * (a[2] + b[2]); - ny += (a[2] - b[2]) * (a[0] + b[0]); - nz += (a[0] - b[0]) * (a[1] + b[1]); - } - int drop = Math.Abs(nx) >= Math.Abs(ny) && Math.Abs(nx) >= Math.Abs(nz) ? 0 : Math.Abs(ny) >= Math.Abs(nz) ? 1 : 2; - (double U, double V) Project(double[] point) => drop switch - { - 0 => (point[1], point[2]), - 1 => (point[0], point[2]), - _ => (point[0], point[1]), - }; - var polygon = outer.Select(Project).ToArray(); - const double tolerance = 1e-9; - foreach (var vertex in inner) - { - var (u, v) = Project(vertex); - bool inside = false; - for (int index = 0; index < polygon.Length; index++) - { - var (u1, v1) = polygon[index]; - var (u2, v2) = polygon[(index + 1) % polygon.Length]; - double dx = u2 - u1, dy = v2 - v1, length = Math.Sqrt(dx * dx + dy * dy); - if (length > 0) - { - double along = ((u - u1) * dx + (v - v1) * dy) / length; - double across = Math.Abs((u - u1) * dy - (v - v1) * dx) / length; - if (across <= tolerance && along >= -tolerance && along <= length + tolerance) return false; - } - if ((v1 > v) != (v2 > v) && u < (u2 - u1) * (v - v1) / (v2 - v1) + u1) inside = !inside; - } - if (!inside) return false; - } - return true; - } } diff --git a/src/RvtIO/Ifc/IfcExporter.PlanSpaceBodyCurrent.cs b/src/RvtIO/Ifc/IfcExporter.PlanSpaceBodyCurrent.cs index bdfe05ea..4b390782 100644 --- a/src/RvtIO/Ifc/IfcExporter.PlanSpaceBodyCurrent.cs +++ b/src/RvtIO/Ifc/IfcExporter.PlanSpaceBodyCurrent.cs @@ -1,3 +1,4 @@ +using RvtIO.Geometry; using RvtIO.Model; namespace RvtIO.Ifc; @@ -54,7 +55,7 @@ private bool TryWriteLiteralSpaceBodyCurrent(StepWriter w, GeometryData boundary var loops = face.SourceLoops!; int outer = 0; for (int index = 1; index < loops.Count; index++) - if (!Enumerable.Range(0, index).Any(earlier => AllVerticesStrictlyInside(loops[index], loops[earlier]))) outer = index; + if (!Enumerable.Range(0, index).Any(earlier => GeometryValidation.AllVerticesStrictlyInside(loops[index], loops[earlier]))) outer = index; var bounds = new List(); for (int index = 0; index < loops.Count; index++) { diff --git a/src/RvtIO/Ifc/IfcExporter.cs b/src/RvtIO/Ifc/IfcExporter.cs index cd485604..6945f385 100644 --- a/src/RvtIO/Ifc/IfcExporter.cs +++ b/src/RvtIO/Ifc/IfcExporter.cs @@ -1,5 +1,6 @@ using System.Globalization; using System.Text.RegularExpressions; +using RvtIO.Geometry; using RvtIO.Lookup; using RvtIO.Model; using RvtIO.Parsing; @@ -1724,13 +1725,13 @@ bool HasCompetingExactHostedWriterAuthority( !e.IsBlockOnly && visibleWallIds.Contains(e.Id) && e.Location is { ArcRadius: null }).ToList(); // Robust model centre: median of element bbox centres. - bool InvalidBbox(double[] b) => !BoundsAreValid(b); + bool InvalidBbox(double[] b) => !GeometryValidation.BoundsAreValid(b); void Skip(Element skipped, string why) { skippedCount++; SkipLog?.Add(skipped.Id, RvtIO.SkipLog.ClassOf(skipped), why); } // The bounds of a 64-bit-id file count as decoded when any element carries valid ones: damaged bounds are a failure of the // decoder of that element, not a sign that the bounds of the file are read. bool boundsDecoded = info.GeometryUndecoded - && info.Elements.Any(e => BoundsAreValid(e.DecodedBox ?? e.Geometry?.BoundingBox)); + && info.Elements.Any(e => GeometryValidation.BoundsAreValid(e.DecodedBox ?? e.Geometry?.BoundingBox)); // A 64-bit-id file read without the R22 layout decodes no geometry at all, and then a wall without a body is the rule, not a // finding: the bodies of the file count as decoded when any element holds one. bool bodiesDecoded = info.GeometryUndecoded && AnyElementHoldsABody(info.Elements); @@ -1909,7 +1910,7 @@ bool HasCompetingExactHostedWriterAuthority( || ResolveHostedElementHostIds( elem, elemById, visibleWallIds, inverseHostedHostIds).Count > 0; // A freestanding door or window that has a body is a real product; one without valid bounds has nothing to write. - if (!hasHost && !BoundsAreValid(elem.DecodedBox ?? elem.Geometry?.BoundingBox)) + if (!hasHost && !GeometryValidation.BoundsAreValid(elem.DecodedBox ?? elem.Geometry?.BoundingBox)) { Skip(elem, "hosted-element-without-host"); continue; } } else @@ -63873,15 +63874,6 @@ internal static bool ShouldSuppressGeometrylessElementProduct( && !isEmittedAggregateParent && IsIfcElementSubclassProduct(ifcType); - /// Whether bounds are six finite values, each minimum not above its maximum. Bounds of an element whose decoding failed are not. - internal static bool BoundsAreValid(double[]? bounds) - { - if (bounds is not { Length: >= 6 }) return false; - for (int i = 0; i < 6; i++) - if (!double.IsFinite(bounds[i])) return false; - return bounds[0] <= bounds[3] && bounds[1] <= bounds[4] && bounds[2] <= bounds[5]; - } - /// The classes that are written without a representation because they only group other products. internal static bool IsRepresentationlessContainerClass(string ifcType) => ifcType is "IFCCURTAINWALL" or "IFCROOF" or "IFCSTAIR" or "IFCRAMP" or "IFCELEMENTASSEMBLY"; diff --git a/src/RvtIO/Internal/FileIdentity.cs b/src/RvtIO/Internal/FileIdentity.cs new file mode 100644 index 00000000..479d0070 --- /dev/null +++ b/src/RvtIO/Internal/FileIdentity.cs @@ -0,0 +1,127 @@ +namespace RvtIO.Internal; + +internal static class FileIdentity +{ + /// True when both paths name the same file. Existing files are compared by file identity (volume and file index on Windows, + /// device and inode on Linux and macOS), which catches hard links, file links and directory links (junctions, directory symbolic links) + /// anywhere in the path. Otherwise, or when a file does not exist yet, the real paths are compared: every existing component is resolved + /// through its links, so a path below a linked directory is recognised before the file is created. + internal static bool SameFile(string first, string second) + { + string a = Path.GetFullPath(first), b = Path.GetFullPath(second); + if (File.Exists(a) && File.Exists(b) && TryGetIdentity(a) is { } ia && TryGetIdentity(b) is { } ib) return ia == ib; + var comparison = OperatingSystem.IsWindows() || OperatingSystem.IsMacOS() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal; + return string.Equals(RealPath(a), RealPath(b), comparison); + } + + /// The path with every existing component resolved through its symbolic links and junctions; components that do not exist are kept. + internal static string RealPath(string fullPath, int depth = 0) + { + string root = Path.GetPathRoot(fullPath) ?? ""; + string current = root; + foreach (string part in fullPath[root.Length..].Split(new[] { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar }, StringSplitOptions.RemoveEmptyEntries)) + { + current = Path.Combine(current, part); + FileSystemInfo info = Directory.Exists(current) ? new DirectoryInfo(current) : new FileInfo(current); + // a link loop has no real path: stop resolving and compare what is left + if (depth < 32 && info.Exists && info.LinkTarget != null && info.ResolveLinkTarget(returnFinalTarget: true) is { } target) + current = RealPath(target.FullName, depth + 1); + } + return current; + } + + // Volume serial number and file index on Windows, or device and inode on Linux and macOS; null where the platform call is not available. + private static (ulong Device, ulong Inode)? TryGetIdentity(string path) + { + try + { + using var handle = File.OpenHandle(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete); + if (OperatingSystem.IsWindows()) + return GetFileInformationByHandle(handle, out var info) + ? (info.VolumeSerialNumber, ((ulong)info.FileIndexHigh << 32) | info.FileIndexLow) + : null; + if (OperatingSystem.IsLinux()) + return LinuxFileIdentity(handle); + if (OperatingSystem.IsMacOS()) + return DarwinFileIdentity(handle); + return null; + } + // a file that cannot be opened or queried is compared by path + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or EntryPointNotFoundException or DllNotFoundException) + { + return null; + } + } + + private static (ulong Device, ulong Inode)? LinuxFileIdentity(Microsoft.Win32.SafeHandles.SafeFileHandle handle) + { + const int AtEmptyPath = 0x1000; + const uint StatxIno = 0x00000100u; + byte emptyPath = 0; + byte[] buffer = new byte[256]; + bool added = false; + try + { + handle.DangerousAddRef(ref added); + if (LinuxStatx((int)handle.DangerousGetHandle(), ref emptyPath, AtEmptyPath, StatxIno, ref buffer[0]) != 0) + return null; + } + finally + { + if (added) handle.DangerousRelease(); + } + uint mask = BitConverter.ToUInt32(buffer, 0); + if ((mask & StatxIno) == 0) return null; + ulong inode = BitConverter.ToUInt64(buffer, 32); + uint devMajor = BitConverter.ToUInt32(buffer, 136); + uint devMinor = BitConverter.ToUInt32(buffer, 140); + return (((ulong)devMajor << 32) | devMinor, inode); + } + + private static (ulong Device, ulong Inode)? DarwinFileIdentity(Microsoft.Win32.SafeHandles.SafeFileHandle handle) + { + byte[] buffer = new byte[256]; + bool added = false; + try + { + handle.DangerousAddRef(ref added); + int fd = (int)handle.DangerousGetHandle(); + int rc = System.Runtime.InteropServices.RuntimeInformation.ProcessArchitecture switch + { + System.Runtime.InteropServices.Architecture.Arm64 => DarwinFstatArm64(fd, ref buffer[0]), + System.Runtime.InteropServices.Architecture.X64 => DarwinFstatInode64(fd, ref buffer[0]), + _ => -1, + }; + if (rc != 0) return null; + } + finally + { + if (added) handle.DangerousRelease(); + } + // __DARWIN_STRUCT_STAT64: int32 st_dev at 0, uint16 st_mode at 4, uint16 st_nlink at 6, uint64 st_ino at 8. + uint device = BitConverter.ToUInt32(buffer, 0); + ulong inode = BitConverter.ToUInt64(buffer, 8); + return (device, inode); + } + + [System.Runtime.InteropServices.StructLayout(System.Runtime.InteropServices.LayoutKind.Sequential)] + private struct ByHandleFileInformation + { + public uint FileAttributes; + public System.Runtime.InteropServices.ComTypes.FILETIME CreationTime, LastAccessTime, LastWriteTime; + public uint VolumeSerialNumber, FileSizeHigh, FileSizeLow, NumberOfLinks, FileIndexHigh, FileIndexLow; + } + + [System.Runtime.InteropServices.DllImport("kernel32.dll", SetLastError = true)] + [return: System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.Bool)] + private static extern bool GetFileInformationByHandle(Microsoft.Win32.SafeHandles.SafeFileHandle file, out ByHandleFileInformation information); + + [System.Runtime.InteropServices.DllImport("libc", EntryPoint = "statx", SetLastError = true)] + private static extern int LinuxStatx(int dirfd, ref byte pathname, int flags, uint mask, ref byte statxbuf); + + [System.Runtime.InteropServices.DllImport("libSystem.dylib", EntryPoint = "fstat", SetLastError = true)] + private static extern int DarwinFstatArm64(int fd, ref byte statbuf); + + [System.Runtime.InteropServices.DllImport("libSystem.dylib", EntryPoint = "fstat$INODE64", SetLastError = true)] + private static extern int DarwinFstatInode64(int fd, ref byte statbuf); +} diff --git a/src/RvtIO/Parsing/GRepParserV2.SpaceLiteral.cs b/src/RvtIO/Parsing/GRepParserV2.SpaceLiteral.cs index 3968c6c6..2333d09a 100644 --- a/src/RvtIO/Parsing/GRepParserV2.SpaceLiteral.cs +++ b/src/RvtIO/Parsing/GRepParserV2.SpaceLiteral.cs @@ -1,3 +1,4 @@ +using RvtIO.Geometry; using RvtIO.Internal; namespace RvtIO.Parsing; @@ -30,7 +31,7 @@ internal static partial class GRepParserV2 // int outer = 0; for (int index = 1; index < rings.Count; index++) - if (!Enumerable.Range(0, index).Any(earlier => Ifc.IfcExporter.AllVerticesStrictlyInside(rings[index], rings[earlier]))) outer = index; + if (!Enumerable.Range(0, index).Any(earlier => GeometryValidation.AllVerticesStrictlyInside(rings[index], rings[earlier]))) outer = index; var (normal, _) = NewellNormalArea(rings[outer]); faces.Add(new GRepFace { diff --git a/src/RvtIO/Writing/RvtWriter.cs b/src/RvtIO/Writing/RvtWriter.cs index d1ad3662..c65cd30b 100644 --- a/src/RvtIO/Writing/RvtWriter.cs +++ b/src/RvtIO/Writing/RvtWriter.cs @@ -4,6 +4,7 @@ using System.Xml; using ICSharpCode.SharpZipLib.Checksum; using OpenMcdf; +using RvtIO.Internal; using RvtIO.Parsing; using RvtIO.Writing; @@ -744,7 +745,7 @@ private static void CheckRelativeReferenceTarget( ex); } - if (!ExportReport.SameFile(sourceTarget, outputTarget)) + if (!FileIdentity.SameFile(sourceTarget, outputTarget)) { throw new RvtWriteRefusedException( "relative-reference-relocation", @@ -833,7 +834,7 @@ private static bool SameDirectory(string sourceDir, string outputDir) string trimmedSource = Path.TrimEndingDirectorySeparator(Path.GetFullPath(sourceDir)); string trimmedOutput = Path.TrimEndingDirectorySeparator(Path.GetFullPath(outputDir)); return string.Equals(trimmedSource, trimmedOutput, comparison) - && ExportReport.SameFile(trimmedSource, trimmedOutput); + && FileIdentity.SameFile(trimmedSource, trimmedOutput); } private static bool IsRootedOrUriLikePath(string rawPath) diff --git a/tests/RvtIO.Tests/ExportReportTests.cs b/tests/RvtIO.Tests/ExportReportTests.cs index b95835e4..a599581a 100644 --- a/tests/RvtIO.Tests/ExportReportTests.cs +++ b/tests/RvtIO.Tests/ExportReportTests.cs @@ -1,5 +1,6 @@ using System.Text.Json; using OpenMcdf; +using RvtIO.Internal; using RvtIO.Model; using RvtIO.Parsing; using Xunit; @@ -47,16 +48,16 @@ public void SameFileComparesTheFullPathsAndTellsDifferentFilesApart() File.WriteAllText(input, "x"); string viaDots = Path.Combine(folder, "sub", "..", "a.rvt"); - Assert.True(ExportReport.SameFile(input, input)); - Assert.True(ExportReport.SameFile(input, viaDots)); - Assert.False(ExportReport.SameFile(input, other)); + Assert.True(FileIdentity.SameFile(input, input)); + Assert.True(FileIdentity.SameFile(input, viaDots)); + Assert.False(FileIdentity.SameFile(input, other)); if (OperatingSystem.IsWindows()) - Assert.True(ExportReport.SameFile(input, input.ToUpperInvariant())); + Assert.True(FileIdentity.SameFile(input, input.ToUpperInvariant())); string link = Path.Combine(folder, "link.rvt"); try { File.CreateSymbolicLink(link, input); } catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { throw new SkipException("symbolic links cannot be created here"); } - Assert.True(ExportReport.SameFile(link, input)); + Assert.True(FileIdentity.SameFile(link, input)); } finally { Directory.Delete(folder, true); } } @@ -108,14 +109,14 @@ public void SameFileSeesThroughAJunctionToTheParentDirectory() File.WriteAllText(input, "x"); string alias = Junction(Path.Combine(folder, "alias"), real); - Assert.True(ExportReport.SameFile(Path.Combine(alias, "model.rvt"), input)); - Assert.True(ExportReport.SameFile(input, Path.Combine(alias, "model.rvt"))); + Assert.True(FileIdentity.SameFile(Path.Combine(alias, "model.rvt"), input)); + Assert.True(FileIdentity.SameFile(input, Path.Combine(alias, "model.rvt"))); // a report that does not exist yet is resolved through its existing parent - Assert.True(ExportReport.SameFile(Path.Combine(alias, "out.ifc"), Path.Combine(real, "out.ifc"))); - Assert.False(ExportReport.SameFile(Path.Combine(alias, "report.json"), input)); + Assert.True(FileIdentity.SameFile(Path.Combine(alias, "out.ifc"), Path.Combine(real, "out.ifc"))); + Assert.False(FileIdentity.SameFile(Path.Combine(alias, "report.json"), input)); // a junction to a junction string nested = Junction(Path.Combine(folder, "nested"), alias); - Assert.True(ExportReport.SameFile(Path.Combine(nested, "model.rvt"), input)); + Assert.True(FileIdentity.SameFile(Path.Combine(nested, "model.rvt"), input)); } finally { Cleanup(folder); } } @@ -132,9 +133,9 @@ public void SameFileSeesThroughADirectorySymbolicLinkToTheParentDirectory() File.WriteAllText(input, "x"); string alias = DirectorySymlink(Path.Combine(folder, "alias"), real); - Assert.True(ExportReport.SameFile(Path.Combine(alias, "model.rvt"), input)); - Assert.True(ExportReport.SameFile(Path.Combine(alias, "out.ifc"), Path.Combine(real, "out.ifc"))); - Assert.False(ExportReport.SameFile(Path.Combine(alias, "report.json"), input)); + Assert.True(FileIdentity.SameFile(Path.Combine(alias, "model.rvt"), input)); + Assert.True(FileIdentity.SameFile(Path.Combine(alias, "out.ifc"), Path.Combine(real, "out.ifc"))); + Assert.False(FileIdentity.SameFile(Path.Combine(alias, "report.json"), input)); } finally { Cleanup(folder); } } @@ -181,9 +182,9 @@ public void SameFileSeesAHardLinkAndRefusesReportPath() File.Copy(input, copy); CreateHardLink(hard, input); - Assert.True(ExportReport.SameFile(hard, input)); - Assert.True(ExportReport.SameFile(input, hard)); - Assert.False(ExportReport.SameFile(copy, input)); + Assert.True(FileIdentity.SameFile(hard, input)); + Assert.True(FileIdentity.SameFile(input, hard)); + Assert.False(FileIdentity.SameFile(copy, input)); var coverageError = new StringWriter(); Assert.Equal(RvtExitCodes.Usage, RvtIO.Cli.CoverageCommand.Run([input, "--report", hard], TextWriter.Null, coverageError)); @@ -201,11 +202,11 @@ public void SameFileSeesAHardLinkAndRefusesReportPath() [Fact] public void RealPathKeepsAPathWithoutLinksAndTheComponentsThatDoNotExist() { - string tempRoot = ExportReport.RealPath(Path.GetFullPath(Path.GetTempPath())); + string tempRoot = FileIdentity.RealPath(Path.GetFullPath(Path.GetTempPath())); string folder = Path.Combine(tempRoot, "rvt-realpath-" + Guid.NewGuid().ToString("N"), "a", "b.json"); - Assert.Equal(folder, ExportReport.RealPath(folder)); + Assert.Equal(folder, FileIdentity.RealPath(folder)); string root = Path.GetPathRoot(folder)!; - Assert.Equal(root, ExportReport.RealPath(root)); + Assert.Equal(root, FileIdentity.RealPath(root)); } [Fact] diff --git a/tests/RvtIO.Tests/IfcExporterBodylessProductGateTests.cs b/tests/RvtIO.Tests/IfcExporterBodylessProductGateTests.cs index 3c9d5884..babd1e0e 100644 --- a/tests/RvtIO.Tests/IfcExporterBodylessProductGateTests.cs +++ b/tests/RvtIO.Tests/IfcExporterBodylessProductGateTests.cs @@ -2,6 +2,7 @@ using RvtIO.Model; using System.Text.RegularExpressions; using Xunit; +using RvtIO.Geometry; namespace RvtIO.Tests; @@ -127,7 +128,7 @@ public void ProductWithDamagedBounds_IsRejectedNotSkippedAsBodyless_WhenOtherBou [InlineData(new double[] { 0, 0, 0, double.NegativeInfinity, 1, 1 }, false)] [InlineData(new double[] { 1, 0, 0, 0, 1, 1 }, false)] public void Bounds_AreValidWhenSixFiniteValuesInOrder(double[]? bounds, bool expected) => - Assert.Equal(expected, IfcExporter.BoundsAreValid(bounds)); + Assert.Equal(expected, GeometryValidation.BoundsAreValid(bounds)); [Fact] public void FootingWithBounds_IsWrittenAsAnIfcFooting() diff --git a/tests/RvtIO.Tests/IfcExporterCurrentFaceBoundsTests.cs b/tests/RvtIO.Tests/IfcExporterCurrentFaceBoundsTests.cs index 990fff64..6d463db6 100644 --- a/tests/RvtIO.Tests/IfcExporterCurrentFaceBoundsTests.cs +++ b/tests/RvtIO.Tests/IfcExporterCurrentFaceBoundsTests.cs @@ -1,4 +1,5 @@ using System.Text.RegularExpressions; +using RvtIO.Geometry; using RvtIO.Ifc; using RvtIO.Model; using Xunit; @@ -80,15 +81,15 @@ public void RegionsThatAreNotTheLoopsOfTheSerializedFace_GiveNoBounds() public void AllVerticesStrictlyInside_ABoundaryVertexIsNotInside() { var outer = Square(0, 4); - Assert.True(IfcExporter.AllVerticesStrictlyInside(Square(1, 3), outer)); - Assert.False(IfcExporter.AllVerticesStrictlyInside(Square(5, 6), outer)); - Assert.False(IfcExporter.AllVerticesStrictlyInside(Square(0, 2), outer)); // shares the corner with the outer loop - Assert.False(IfcExporter.AllVerticesStrictlyInside(Square(2, 6), outer)); // one vertex inside, the others out + Assert.True(GeometryValidation.AllVerticesStrictlyInside(Square(1, 3), outer)); + Assert.False(GeometryValidation.AllVerticesStrictlyInside(Square(5, 6), outer)); + Assert.False(GeometryValidation.AllVerticesStrictlyInside(Square(0, 2), outer)); // shares the corner with the outer loop + Assert.False(GeometryValidation.AllVerticesStrictlyInside(Square(2, 6), outer)); // one vertex inside, the others out // a polygon of a vertical plane: the projection drops the axis along which the plane is flat var wall = new List { new[] { 0.0, 0, 0 }, new[] { 0.0, 4, 0 }, new[] { 0.0, 4, 4 }, new[] { 0.0, 0, 4 } }; var window = new List { new[] { 0.0, 1, 1 }, new[] { 0.0, 3, 1 }, new[] { 0.0, 3, 3 }, new[] { 0.0, 1, 3 } }; - Assert.True(IfcExporter.AllVerticesStrictlyInside(window, wall)); - Assert.False(IfcExporter.AllVerticesStrictlyInside(wall, window)); + Assert.True(GeometryValidation.AllVerticesStrictlyInside(window, wall)); + Assert.False(GeometryValidation.AllVerticesStrictlyInside(wall, window)); } diff --git a/tests/RvtIO.Tests/RvtWriterTests.cs b/tests/RvtIO.Tests/RvtWriterTests.cs index 48803e7e..467e6098 100644 --- a/tests/RvtIO.Tests/RvtWriterTests.cs +++ b/tests/RvtIO.Tests/RvtWriterTests.cs @@ -2,6 +2,7 @@ using System.Security.Cryptography; using System.Text; using OpenMcdf; +using RvtIO.Internal; using RvtIO.Parsing; using RvtIO.Writing; using Xunit; @@ -833,7 +834,7 @@ public void SaveAs_AndRewrite_WithValidRelativeLink_PreserveTargetInSameDirector // Precondition: the relative reference in input/host.rvt resolves to the real linked.rvt file on disk. string initialResolved = ResolveExternalReferenceTarget(hostFile); Assert.True(File.Exists(initialResolved)); - Assert.True(ExportReport.SameFile(linkedFile, initialResolved)); + Assert.True(FileIdentity.SameFile(linkedFile, initialResolved)); byte[] schemaBytes = BuildSchemaBytesForRelease(2022); ushort itemTag = (ushort)TfSchemaReader.Parse(schemaBytes).Classes.Single(c => c.Name == "SyntheticItem").Id; @@ -853,25 +854,25 @@ public void SaveAs_AndRewrite_WithValidRelativeLink_PreserveTargetInSameDirector Assert.Equal(0, saveAsRes.ReplacedStreamCount); string sameSaveAsResolved = ResolveExternalReferenceTarget(sameSaveAs); Assert.True(File.Exists(sameSaveAsResolved)); - Assert.True(ExportReport.SameFile(linkedFile, sameSaveAsResolved)); + Assert.True(FileIdentity.SameFile(linkedFile, sameSaveAsResolved)); string sameDocSaveAs = Path.Combine(inputDir, "host_doc_saveas.rvt"); RvtDocument.Open(hostFile).SaveAs(sameDocSaveAs); string sameDocResolved = ResolveExternalReferenceTarget(sameDocSaveAs); Assert.True(File.Exists(sameDocResolved)); - Assert.True(ExportReport.SameFile(linkedFile, sameDocResolved)); + Assert.True(FileIdentity.SameFile(linkedFile, sameDocResolved)); string sameRewrite = Path.Combine(inputDir, "host_rewrite.rvt"); var rewriteRes = RvtWriter.Rewrite(hostFile, sameRewrite, rewriteRequest); Assert.Equal(1, rewriteRes.RewrittenRecordCount); string sameRewriteResolved = ResolveExternalReferenceTarget(sameRewrite); Assert.True(File.Exists(sameRewriteResolved)); - Assert.True(ExportReport.SameFile(linkedFile, sameRewriteResolved)); + Assert.True(FileIdentity.SameFile(linkedFile, sameRewriteResolved)); // 2. Different-directory destinations would break ../links/linked.rvt resolution and must be refused before publishing output. string brokenCandidateTarget = Path.GetFullPath(Path.Combine(nestedDir, "..", "links", "linked.rvt")); Assert.False(File.Exists(brokenCandidateTarget)); - Assert.False(ExportReport.SameFile(linkedFile, brokenCandidateTarget)); + Assert.False(FileIdentity.SameFile(linkedFile, brokenCandidateTarget)); string nestedSaveAs = Path.Combine(nestedDir, "host_saveas.rvt"); var exSaveAs = Assert.Throws(() => RvtWriter.SaveAs(hostFile, nestedSaveAs)); @@ -931,7 +932,7 @@ public void SaveAs_AndRewrite_ToDifferentDirectory_SucceedForNonRelativeLinks_An Assert.Equal(2, reopenedAbs.TransmissionData!.ExternalReferences.Count); string resolvedAbs = Path.GetFullPath(reopenedAbs.TransmissionData.ExternalReferences[0].Path!); Assert.True(File.Exists(resolvedAbs)); - Assert.True(ExportReport.SameFile(linkedFile, resolvedAbs)); + Assert.True(FileIdentity.SameFile(linkedFile, resolvedAbs)); string nestedAbsRewrite = Path.Combine(nestedDir, "host_abs_rewrite.rvt"); RvtWriter.Rewrite(absHost, nestedAbsRewrite, new RvtWriteRequest From 2d6cb236f1a3d93d07034f6d9304504bbac7b063 Mon Sep 17 00:00:00 2001 From: mahach666 <79989386+mahach666@users.noreply.github.com> Date: Wed, 18 Nov 2026 03:11:09 +0300 Subject: [PATCH 011/259] Move Revit shell and extrusion geometry out of IFC exporting --- src/RvtIO.Cli/ExportCommand.cs | 6 +- src/RvtIO/Compact/CompactElementNames.cs | 1 + src/RvtIO/Compact/CompactJsonExporter.cs | 2 +- src/RvtIO/Compact/CompactSolidQuantities.cs | 8 +- .../ValidatedElementNames.cs | 3 +- src/RvtIO/Geometry/ArcRuns.cs | 82 ++ src/RvtIO/Geometry/BrepMeasures.cs | 198 +++++ src/RvtIO/Geometry/FacetedShell.cs | 747 ++++++++++++++++++ .../{Ifc => Geometry}/WallExtrusion.Axis.cs | 2 +- src/RvtIO/{Ifc => Geometry}/WallExtrusion.cs | 6 +- src/RvtIO/Ifc/IfcExporter.ArcWallsCurrent.cs | 1 + .../Ifc/IfcExporter.CurveLoopAreaCurrent.cs | 2 + src/RvtIO/Ifc/IfcExporter.CutPairOpenings.cs | 1 + .../Ifc/IfcExporter.ExtrusionBodiesCurrent.cs | 1 + .../Ifc/IfcExporter.ExtrusionOthersCurrent.cs | 1 + .../IfcExporter.ExtrusionProfilesCurrent.cs | 77 +- .../Ifc/IfcExporter.FaceBoundsCurrent.cs | 1 + .../Ifc/IfcExporter.QuantitiesCurrent.cs | 15 +- .../IfcExporter.QuantityGeometryCurrent.cs | 180 +---- src/RvtIO/Ifc/IfcExporter.RampCurrent.cs | 1 + src/RvtIO/Ifc/IfcExporter.RoofSlabCurrent.cs | 1 + src/RvtIO/Ifc/IfcExporter.SlopeCurrent.cs | 1 + src/RvtIO/Ifc/IfcExporter.cs | 741 +---------------- .../Parsing/ElementBuilder.CoarseSurface.cs | 6 +- .../ElementBuilder.OwnWallPlanarBody.cs | 3 +- .../RvtFileReader.OwnWallPlanarBodies.cs | 4 +- .../RvtIO.Tests/AnalyticSolidMeasureTests.cs | 5 +- tests/RvtIO.Tests/ArcProfileTests.cs | 3 +- tests/RvtIO.Tests/AxisExtrusionTests.cs | 1 + tests/RvtIO.Tests/CompactIdentityTests.cs | 1 + .../RvtIO.Tests/CompactOwnValueRulesTests.cs | 1 + tests/RvtIO.Tests/CoveringFirstPieceTests.cs | 17 +- tests/RvtIO.Tests/EdgeBoundsTests.cs | 1 + tests/RvtIO.Tests/FaceAreaTests.cs | 1 + ...cExporterBaseQuantitiesCurrentTailTests.cs | 5 +- .../IfcExporterBaseQuantitiesCurrentTests.cs | 29 +- .../RvtIO.Tests/IfcExporterInsetCapsTests.cs | 3 +- .../RvtIO.Tests/IfcExporterJoinNotchTests.cs | 3 +- .../IfcExporterPlainWallBodyCurrentTests.cs | 1 + .../IfcExporterSideSheetInsetCapsTests.cs | 3 +- .../IfcExporterWallGeometryTests.cs | 51 +- .../NonVisibleQuantityGeometryTests.cs | 3 +- .../PlanarSpaceShellContactTests.cs | 3 +- tests/RvtIO.Tests/SchemaReleaseExportTests.cs | 4 +- .../RvtIO.Tests/ValidatedElementNamesTests.cs | 1 + tests/RvtIO.Tests/WallExtrusionTests.cs | 1 + tests/RvtIO.Tests/WideElementRecordsTests.cs | 1 + 47 files changed, 1149 insertions(+), 1080 deletions(-) rename src/RvtIO/{Parsing => Export}/ValidatedElementNames.cs (99%) create mode 100644 src/RvtIO/Geometry/ArcRuns.cs create mode 100644 src/RvtIO/Geometry/BrepMeasures.cs create mode 100644 src/RvtIO/Geometry/FacetedShell.cs rename src/RvtIO/{Ifc => Geometry}/WallExtrusion.Axis.cs (99%) rename src/RvtIO/{Ifc => Geometry}/WallExtrusion.cs (99%) diff --git a/src/RvtIO.Cli/ExportCommand.cs b/src/RvtIO.Cli/ExportCommand.cs index adb4beb3..ca17770f 100644 --- a/src/RvtIO.Cli/ExportCommand.cs +++ b/src/RvtIO.Cli/ExportCommand.cs @@ -190,7 +190,7 @@ private static int Export(ExportArguments arguments) if (roomPhase != null) Console.Error.WriteLine($"IFC room export phase: {roomPhase}"); // A 64-bit-id file has no scanned fallback names: the exporter reads the validated ones, as the JSON dump does. if (ifcModel.GeometryUndecoded) - RvtIO.Parsing.ValidatedElementNames.Apply(ifcModel, ifcState); + RvtIO.Export.ValidatedElementNames.Apply(ifcModel, ifcState); var skipLog = new SkipLog(); var exporter = new IfcExporter(Console.Error, includeIfcRevitParameters) { SkipLog = skipLog, ExportPhaseId = exportPhase, ExportAllPhases = exportPhaseOption == "all", RoomExportPhaseId = roomPhase, ExportRoomsOfAllPhases = roomPhaseOption == "all", RevitParameterGroups = revitParameterGroups, Profile = profile, BaseQuantities = baseQuantities, OpeningQuantitiesSwapped = openingLegacyAxes, Timestamp = ifcTimestamp, LengthUnit = ifcLengthUnit }; var swExport = System.Diagnostics.Stopwatch.StartNew(); @@ -203,7 +203,7 @@ private static int Export(ExportArguments arguments) if (compactJsonPath != null) { // The compact export reads Element.Name only where it is validated (the IFC branch above keeps the fallback names). - RvtIO.Parsing.ValidatedElementNames.Apply(jsonModel, jsonState); + RvtIO.Export.ValidatedElementNames.Apply(jsonModel, jsonState); var compactIdentity = new CompactIdentity(CompactUniverse.Select(jsonModel)); // --dev-candidates : measurement run without the value gate; writes (id, parameter, stored text, derived text, class) of every // listed parameter for the value gate. --dev-trace : writes (id, class, parameter, reason) of every listed parameter @@ -318,7 +318,7 @@ static string TsvText(string? text) => text == null ? "\\N" // "Name" is the Revit API element name: keep the validated names and omit the rest (null is not written). // Element.Name is a fallback value that scanned strings can fill with another element's name; the IFC branch above // keeps reading it, so only the JSON branch replaces it. - int validatedNames = RvtIO.Parsing.ValidatedElementNames.Apply(jsonModel, jsonState); + int validatedNames = RvtIO.Export.ValidatedElementNames.Apply(jsonModel, jsonState); Console.Error.WriteLine($"JSON names: {validatedNames} of {jsonModel.Elements.Count} elements have a validated name"); // De-duplicate parameter definitions into a shared table so each element parameter only stores its value (keyed by id). diff --git a/src/RvtIO/Compact/CompactElementNames.cs b/src/RvtIO/Compact/CompactElementNames.cs index ab4ea6b3..21453f1a 100644 --- a/src/RvtIO/Compact/CompactElementNames.cs +++ b/src/RvtIO/Compact/CompactElementNames.cs @@ -1,3 +1,4 @@ +using RvtIO.Export; using RvtIO.Internal; using RvtIO.Model; using RvtIO.Parsing; diff --git a/src/RvtIO/Compact/CompactJsonExporter.cs b/src/RvtIO/Compact/CompactJsonExporter.cs index e41e5122..28fc9288 100644 --- a/src/RvtIO/Compact/CompactJsonExporter.cs +++ b/src/RvtIO/Compact/CompactJsonExporter.cs @@ -31,7 +31,7 @@ public static void Export(string rvtPath, string outputPath, RvtReaderOptions? r var info = reader.Read(rvtPath); var state = reader.LastParsingState ?? throw new InvalidOperationException("The reader kept no parsing state."); // The compact export reads Element.Name only where it is validated. - Parsing.ValidatedElementNames.Apply(info, state); + RvtIO.Export.ValidatedElementNames.Apply(info, state); var identity = new CompactIdentity(CompactUniverse.Select(info)); // A wide layout does not decode geometry or curves: their quantities come from a second read in the Revit 2022 layout. var gate = CompactValueGate.ForLayout(info.GeometryUndecoded); diff --git a/src/RvtIO/Compact/CompactSolidQuantities.cs b/src/RvtIO/Compact/CompactSolidQuantities.cs index 69bb458e..af32160d 100644 --- a/src/RvtIO/Compact/CompactSolidQuantities.cs +++ b/src/RvtIO/Compact/CompactSolidQuantities.cs @@ -1,4 +1,4 @@ -using RvtIO.Ifc; +using RvtIO.Geometry; using RvtIO.Internal; using RvtIO.Model; using RvtIO.Parsing; @@ -81,11 +81,11 @@ internal static Solids Measure(Element element, ParsingState state) internal static Solids Measure(GeometryData geometry, int level) { int count = geometry.BrepSolids?.Count ?? 0; - var shells = IfcExporter.ShellsOfCurrent(geometry); + var shells = BrepMeasures.ShellsOfCurrent(geometry); bool plane = geometry.Faces.All(face => face.PlaneSurface); string shape = count == 0 ? "none" : shells.All(shell => shell.Closed) && plane ? count == 1 ? "one" : "many" : "other"; - double largest = geometry.Faces.Select(face => IfcExporter.NetFaceArea(face) ?? 0).DefaultIfEmpty(0).Max(); - double? depth = shells.Count == 1 && shells[0].Closed && IfcExporter.FindPrismCurrent(shells[0]) is { } prism ? prism.Depth : null; + double largest = geometry.Faces.Select(face => BrepMeasures.NetFaceArea(face) ?? 0).DefaultIfEmpty(0).Max(); + double? depth = shells.Count == 1 && shells[0].Closed && BrepMeasures.FindPrismCurrent(shells[0]) is { } prism ? prism.Depth : null; return new Solids(shape, level, count, shells.Sum(shell => shell.Volume), shells.Sum(shell => shell.Area), largest, depth); } diff --git a/src/RvtIO/Parsing/ValidatedElementNames.cs b/src/RvtIO/Export/ValidatedElementNames.cs similarity index 99% rename from src/RvtIO/Parsing/ValidatedElementNames.cs rename to src/RvtIO/Export/ValidatedElementNames.cs index 430e2c61..8c6cd437 100644 --- a/src/RvtIO/Parsing/ValidatedElementNames.cs +++ b/src/RvtIO/Export/ValidatedElementNames.cs @@ -1,8 +1,9 @@ using RvtIO.Ifc; using RvtIO.Internal; using RvtIO.Model; +using RvtIO.Parsing; -namespace RvtIO.Parsing; +namespace RvtIO.Export; /// /// The Name of the JSON dump: the Revit API Element.Name where the file confirms it, null elsewhere. diff --git a/src/RvtIO/Geometry/ArcRuns.cs b/src/RvtIO/Geometry/ArcRuns.cs new file mode 100644 index 00000000..1a5208ec --- /dev/null +++ b/src/RvtIO/Geometry/ArcRuns.cs @@ -0,0 +1,82 @@ +namespace RvtIO.Geometry; + +internal static class ArcRuns +{ + private static double[] CrossCurrent(double[] a, double[] b) => [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]]; + private static double DotCurrent(double[] a, double[] b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; + + /// One circular edge of a ring: the ring vertices First..First+Steps (cyclic, in ring order) are samples of + /// Arc, whose stored parameter runs against the ring order when Reversed. EitherWay: the other way round + /// the ring passed as the arc too, so the run is the shorter of the two, not a known one. + internal readonly record struct ArcRunCurrent(int First, int Steps, Internal.Arc Arc, bool Reversed, bool EitherWay = false); + + /// Finds the circular edges of a ring: the arcs whose two ends are vertices of the ring and whose vertices between + /// them lie on the circle. An arc that closes on itself or has no such run is left out (the ring keeps its own points). + internal static List FindArcRunsCurrent(IReadOnlyList ring, IReadOnlyList arcs) + { + var runs = new List(); + int n = ring.Count; + foreach (var arc in arcs) + { + double radius = Math.Abs(arc.Radius), tolerance = 1e-6 * Math.Max(radius, 1e-3); + double[] normal = CrossCurrent(arc.X, arc.Y); + bool Near(double[] p, double[] q) => Math.Abs(p[0] - q[0]) <= tolerance && Math.Abs(p[1] - q[1]) <= tolerance + && Math.Abs(p[2] - q[2]) <= tolerance; + bool OnCircle(double[] p) + { + double[] d = [p[0] - arc.Centre[0], p[1] - arc.Centre[1], p[2] - arc.Centre[2]]; + double axial = DotCurrent(d, normal); + return Math.Abs(axial) <= tolerance && Math.Abs(Math.Sqrt(DotCurrent(d, d) - axial * axial) - radius) <= tolerance; + } + // a vertex between two samples of the circle that lies on the straight segment joining them: the mesh of the neighbouring + // cylinder added it to the ring + bool OnChord(double[] p, double[] a, double[] b) + { + double[] ab = [b[0] - a[0], b[1] - a[1], b[2] - a[2]], ap = [p[0] - a[0], p[1] - a[1], p[2] - a[2]]; + double length2 = DotCurrent(ab, ab); + if (!(length2 > 0)) return false; + double t = DotCurrent(ap, ab) / length2; + if (t < -1e-9 || t > 1 + 1e-9) return false; + double[] off = [ap[0] - t * ab[0], ap[1] - t * ab[1], ap[2] - t * ab[2]]; + return Math.Sqrt(DotCurrent(off, off)) <= tolerance; + } + bool IsArcRoute(List route) + { + int previous = 0; + for (int i = 1; i < route.Count; i++) + { + if (!OnCircle(route[i])) continue; + for (int between = previous + 1; between < i; between++) + if (!OnChord(route[between], route[previous], route[i])) return false; + previous = i; + } + return previous == route.Count - 1; + } + double[] start = arc.At(arc.First), end = arc.At(arc.Last); + int s = -1, e = -1; + for (int i = 0; i < n; i++) + { + if (s < 0 && Near(ring[i], start)) s = i; + if (e < 0 && Near(ring[i], end)) e = i; + } + if (s < 0 || e < 0 || s == e) continue; + // forward from s to e, or backward (the ring runs against the stored parameter): the way that is the arc + int bestSteps = int.MaxValue, bestDirection = 0, ways = 0; + for (int direction = 1; direction >= -1; direction -= 2) + { + var route = new List { ring[s] }; + for (int i = (s + direction + n) % n; ; i = (i + direction + n) % n) + { + route.Add(ring[i]); + if (i == e || route.Count > n) break; + } + if (route.Count > n || !IsArcRoute(route)) continue; + ways++; + if (route.Count - 1 < bestSteps) (bestSteps, bestDirection) = (route.Count - 1, direction); + } + if (bestDirection != 0) + runs.Add(bestDirection == 1 ? new ArcRunCurrent(s, bestSteps, arc, false, ways == 2) : new ArcRunCurrent(e, bestSteps, arc, true, ways == 2)); + } + return runs; + } +} diff --git a/src/RvtIO/Geometry/BrepMeasures.cs b/src/RvtIO/Geometry/BrepMeasures.cs new file mode 100644 index 00000000..d93d5def --- /dev/null +++ b/src/RvtIO/Geometry/BrepMeasures.cs @@ -0,0 +1,198 @@ +using RvtIO.Model; + +namespace RvtIO.Geometry; + +/// Measures decoded Revit faces, shells and solid nodes. +internal static class BrepMeasures +{ + private const double FeetToMetres = 0.3048; + internal const double SquareFeetToSquareMetres = FeetToMetres * FeetToMetres; + internal const double CubicFeetToCubicMetres = FeetToMetres * FeetToMetres * FeetToMetres; + + /// One decoded shell: its faces, its volume (the divergence theorem over its planar faces) and the sum of + /// its face areas (holes subtracted), in feet. Complete analytic nodes use source surface integrals. + internal sealed record ShellInfo(IReadOnlyList Faces, bool Closed, double Volume, double Area) + { + public bool SourceMeasured { get; init; } + } + + /// The prism a shell is, in feet: Depth is the distance of the two end faces, ProfileArea the net area of an + /// end face, OuterPerimeter the length of its outer loop and ExtentX/ExtentY the world extents of the loop that is measured + /// (they describe the profile only for a vertical prism): the first loop of the lower end face as the Face serializes its loops, + /// which is a hole when the Face lists one first. + internal readonly record struct ShellPrism( + double Depth, double ProfileArea, double OuterPerimeter, double ExtentX, double ExtentY, bool Vertical, + double InnerPerimeter = 0); + + /// The total surface area (feet squared) of the solids of a geometry: the sum over its shells, the holes of the faces + /// subtracted. + internal static double SurfaceAreaCurrent(GeometryData? geometry) => ShellsOfCurrent(geometry).Sum(shell => shell.SourceMeasured ? shell.Area : + shell.Faces.GroupBy(face => (face.GeometryNode, Marker: face.SourceFace != 0 ? face.SourceFace : face.MeshMarker)) + .Sum(group => group.Key.Marker != 0 && group.First().QuadratureArea is { } exact + ? exact : group.Sum(face => NetFaceArea(face) ?? 0))); + + private static double[] RingNormal(IReadOnlyList ring) + { + double nx = 0, ny = 0, nz = 0; + for (int i = 0; i < ring.Count; i++) + { + var a = ring[i]; + var b = ring[(i + 1) % ring.Count]; + nx += (a[1] - b[1]) * (a[2] + b[2]); + ny += (a[2] - b[2]) * (a[0] + b[0]); + nz += (a[0] - b[0]) * (a[1] + b[1]); + } + return [nx, ny, nz]; + } + + /// Area of the polygon of a (planar) ring. + internal static double RingArea(IReadOnlyList ring) + { + if (ring.Count < 3) return 0; + var n = RingNormal(ring); + return 0.5 * Math.Sqrt(n[0] * n[0] + n[1] * n[1] + n[2] * n[2]); + } + + internal static double RingPerimeter(IReadOnlyList ring) + { + double length = 0; + for (int i = 0; i < ring.Count; i++) + { + var a = ring[i]; + var b = ring[(i + 1) % ring.Count]; + length += Math.Sqrt((b[0] - a[0]) * (b[0] - a[0]) + (b[1] - a[1]) * (b[1] - a[1]) + (b[2] - a[2]) * (b[2] - a[2])); + } + return length; + } + + /// Face area with its inner loops subtracted; null when the face has no outer loop. + internal static double? NetFaceArea(GeoFace face) + { + if (face.OuterVertices is not { Count: >= 3 } outer) return null; + double area = RingArea(outer); + if (face.InnerVertices != null) + foreach (var hole in face.InnerVertices) area -= RingArea(hole); + return area; + } + + /// Unit normal of the outer loop by its winding; null for a degenerate loop. + internal static double[]? FaceUnitNormal(GeoFace face) + { + if (face.OuterVertices is not { Count: >= 3 } outer) return null; + var n = RingNormal(outer); + double length = Math.Sqrt(n[0] * n[0] + n[1] * n[1] + n[2] * n[2]); + return length < 1e-12 ? null : [n[0] / length, n[1] / length, n[2] / length]; + } + + /// The shells of an element geometry (all faces as one shell when none are listed). + internal static List ShellsOfCurrent(GeometryData? geometry) + { + var result = new List(); + if (geometry?.Faces is not { Count: > 0 } faces) return result; + IEnumerable<(List Faces, bool Closed)> shells = geometry.BrepSolids is { Count: > 0 } solids + ? solids.Select(solid => (solid.FaceIndices.Where(i => (uint)i < (uint)faces.Count).Select(i => faces[i]).ToList(), solid.IsClosed)) + : [(faces, false)]; + foreach (var (shellFaces, closed) in shells) + { + double volume = 0, area = 0; + // The signed volume needs every face wound the same way (outward); a closed shell that orients exactly is summed oriented. + IReadOnlyList computationFaces = shellFaces; + if (closed && shellFaces.Count >= 4 + && FacetedShell.TryOrientExactFacetedShell(shellFaces, Enumerable.Range(0, shellFaces.Count).ToList(), out var orientedShell, triangulateNonPlanarFaces: false)) + computationFaces = orientedShell; + foreach (var face in computationFaces) + { + if (NetFaceArea(face) is not { } net || FaceUnitNormal(face) is not { } normal) continue; + area += net; + var p = face.OuterVertices![0]; + volume += (p[0] * normal[0] + p[1] * normal[1] + p[2] * normal[2]) * net / 3; + } + bool sourceMeasured = false; + if (closed && shellFaces.Select(face => face.GeometryNode).Distinct().ToList() is [var nodeId] + && geometry.NodeMeasures?.Any(measure => measure.Node == nodeId && measure.Volume < 0) != true // a cutting node has no solid to measure + && geometry.MeshNodes?.FirstOrDefault(node => node.Node == nodeId) is { SourceMeasures: { } measures } source + && shellFaces.Select(face => face.SourceFace != 0 ? face.SourceFace : face.MeshMarker).ToHashSet() + .SetEquals(source.Faces.Select(face => (uint)face.Marker))) + { + area = measures.Area; + volume = measures.Volume; + sourceMeasured = true; + } + result.Add(new ShellInfo(shellFaces, closed, Math.Abs(volume), area) { SourceMeasured = sourceMeasured }); + } + return result; + } + + /// The prism of a shell: two planar faces of equal net area (within 1e-4 ft2) facing each other on + /// different planes, with every other face parallel to their common normal. Null for any other shape, a curved face + /// included. + /// With the vertical cylinders that tessellate the arcs of the outline are allowed as sides and left + /// out of the search (the perimeters stay those of the chords), and a shell with any other curved face is no prism. + internal static ShellPrism? FindPrismCurrent(ShellInfo shell, bool verticalOnly = false, bool arcSides = false) + { + var faces = shell.Faces; + if (faces.Count < 4) return null; + if (arcSides) + { + var cylinders = faces.Where(face => face.CurvedSurface).ToList(); + if (cylinders.Any(face => face.AnalyticCylinderAxis is not { Length: >= 3 } axis || Math.Abs(Math.Abs(axis[2]) - 1) > 1e-9 + || !(face.AnalyticCylinderRadius > 0))) return null; + faces = faces.Where(face => !face.CurvedSurface).ToList(); + } + int count = faces.Count; + if (count < 2 || faces.Any(face => face.CurvedSurface)) return null; + var normals = new double[count][]; + var areas = new double[count]; + for (int i = 0; i < count; i++) + { + if (FaceUnitNormal(faces[i]) is not { } n || NetFaceArea(faces[i]) is not { } a) return null; + normals[i] = n; + areas[i] = a; + } + ShellPrism? best = null; + for (int i = 0; i < count; i++) + { + for (int j = i + 1; j < count; j++) + { + var a = normals[i]; + var b = normals[j]; + if (a[0] * b[0] + a[1] * b[1] + a[2] * b[2] > -1 + 1e-9 || Math.Abs(areas[i] - areas[j]) > 1e-4) continue; + bool vertical = Math.Abs(a[2]) > 1 - 1e-9; + if (verticalOnly && !vertical) continue; + bool others = true; + for (int k = 0; k < count && others; k++) + if (k != i && k != j) + others = Math.Abs(normals[k][0] * a[0] + normals[k][1] * a[1] + normals[k][2] * a[2]) < 1e-6; + if (!others) continue; + var pi = faces[i].OuterVertices![0]; + var pj = faces[j].OuterVertices![0]; + double depth = Math.Abs((pj[0] - pi[0]) * a[0] + (pj[1] - pi[1]) * a[1] + (pj[2] - pi[2]) * a[2]); + // A box is a prism along each of its three axes; its long axis is the one a bar is extruded along. + if (depth < 1e-9 || best is { } known && known.Depth >= depth) continue; + var outer = faces[i].OuterVertices!; + var lower = vertical && MeanHeightCurrent(faces[j]) < MeanHeightCurrent(faces[i]) ? faces[j] : faces[i]; + var measured = lower.FirstSourceLoop ?? lower.OuterVertices!; + best = new ShellPrism(depth, areas[i], RingPerimeter(outer), + measured.Max(p => p[0]) - measured.Min(p => p[0]), measured.Max(p => p[1]) - measured.Min(p => p[1]), vertical, + faces[i].InnerVertices?.Sum(RingPerimeter) ?? 0); + } + } + return best; + } + + /// Mean height of the vertices of a face, in feet. + internal static double MeanHeightCurrent(GeoFace face) => face.OuterVertices!.Average(point => point[2]); + + /// Volume (m3) and surface area (m2) of the solid geometry nodes, summed from their surface integrals + /// (a cutting node, whose measure has a negative volume, is not taken). Null unless every node of the geometry has its integrals. + internal static (double Volume, double Area)? NodeSolidTotalsCurrent(GeometryData? geometry) + { + if (geometry?.NodeMeasures is not { Count: > 0 } measures || geometry.Faces.Count == 0) return null; + var byNode = new Dictionary(); + foreach (var measure in measures) byNode.TryAdd(measure.Node, measure); + if (geometry.Faces.Any(face => face.GeometryNode > 0 && !byNode.ContainsKey(face.GeometryNode))) return null; + var taken = byNode.Values.Where(measure => measure.Volume > 0).ToList(); + if (taken.Count == 0) return null; + return (taken.Sum(measure => measure.Volume) * CubicFeetToCubicMetres, taken.Sum(measure => measure.Area) * SquareFeetToSquareMetres); + } +} diff --git a/src/RvtIO/Geometry/FacetedShell.cs b/src/RvtIO/Geometry/FacetedShell.cs new file mode 100644 index 00000000..21aad647 --- /dev/null +++ b/src/RvtIO/Geometry/FacetedShell.cs @@ -0,0 +1,747 @@ +using RvtIO.Model; + +namespace RvtIO.Geometry; + +/// Validates and orients faceted shells on the metric lattice used for IFC serialization. +internal static class FacetedShell +{ + private const double FeetToMetres = 0.3048; + internal const double IfcGeometryPrecisionMetres = 1.0e-5; + + internal static (long X, long Y, long Z) IfcPrecisionKeyFeet(double[] point) => + (IfcPrecisionBinMetres(point[0] * FeetToMetres), + IfcPrecisionBinMetres(point[1] * FeetToMetres), + IfcPrecisionBinMetres(point[2] * FeetToMetres)); + + internal static (long X, long Y, long Z) IfcPrecisionKeyMetres( + double x, double y, double z) => + (IfcPrecisionBinMetres(x), IfcPrecisionBinMetres(y), IfcPrecisionBinMetres(z)); + + internal static long IfcPrecisionBinMetres(double value) => checked((long)Math.Round( + value / IfcGeometryPrecisionMetres, MidpointRounding.ToEven)); + + internal static bool FaceCollapsesAtIfcPrecision(GeoFace face) + { + if (face.OuterVertices is not { Count: >= 3 } source + || source.Any(point => point.Length < 3 + || !double.IsFinite(point[0]) || !double.IsFinite(point[1]) + || !double.IsFinite(point[2]))) + return false; + var vertices = new List<(long X, long Y, long Z)>(); + foreach (var point in source) + { + var key = IfcPrecisionKeyFeet(point); + if (vertices.Count == 0 || vertices[^1] != key) vertices.Add(key); + } + if (vertices.Count > 1 && vertices[0] == vertices[^1]) vertices.RemoveAt(vertices.Count - 1); + if (vertices.Count < 3) return true; + var first = vertices[0]; + for (int index = 1; index + 1 < vertices.Count; index++) + { + var second = vertices[index]; + var third = vertices[index + 1]; + var ux = (System.Numerics.BigInteger)second.X - first.X; + var uy = (System.Numerics.BigInteger)second.Y - first.Y; + var uz = (System.Numerics.BigInteger)second.Z - first.Z; + var vx = (System.Numerics.BigInteger)third.X - first.X; + var vy = (System.Numerics.BigInteger)third.Y - first.Y; + var vz = (System.Numerics.BigInteger)third.Z - first.Z; + if (!(uy * vz - uz * vy).IsZero + || !(uz * vx - ux * vz).IsZero + || !(ux * vy - uy * vx).IsZero) + return false; + } + return true; + } + + /// + /// Orients every face of one closed component consistently and then chooses the outward global + /// orientation from its signed volume. + /// + internal static bool TryOrientExactFacetedShell(IReadOnlyList faces, + IReadOnlyCollection faceIndices, out List orientedFaces, + bool triangulateNonPlanarFaces) + { + orientedFaces = []; + var indices = faceIndices.Distinct().Order().ToList(); + if (indices.Count < 4 || indices.Any(index => (uint)index >= faces.Count)) + return false; + var normalizedFaces = new Dictionary(); + foreach (int faceIndex in indices) + { + var normalized = CloneFace(faces[faceIndex], false); + if (normalized.OuterVertices is not { Count: >= 3 } outer + || outer.Any(point => point.Length < 3 + || !double.IsFinite(point[0]) || !double.IsFinite(point[1]) + || !double.IsFinite(point[2]))) + return false; + normalized.OuterVertices = CleanPrecisionLoop(outer); + if (normalized.OuterVertices.Count < 3 + || FaceCollapsesAtIfcPrecision(normalized)) + return false; + normalized.InnerVertices = normalized.InnerVertices? + .Where(ring => ring.Count >= 3 && ring.All(point => point.Length >= 3 + && double.IsFinite(point[0]) && double.IsFinite(point[1]) + && double.IsFinite(point[2]))) + .Select(CleanPrecisionLoop) + .Where(ring => ring.Count >= 3 + && !FaceCollapsesAtIfcPrecision(new GeoFace + { OuterVertices = ring })) + .ToList(); + if (!TryNormalizeInnerBounds(normalized)) + return false; + normalizedFaces[faceIndex] = normalized; + } + if (!TryGetFacetedAtomicEdgeUses(normalizedFaces, indices, out var edgeUses)) + return false; + + var constraints = indices.ToDictionary(index => index, + _ => new List<(int Other, bool OppositeFlip)>()); + foreach (var uses in edgeUses.Values) + { + bool oppositeFlip = uses[0].Direction == uses[1].Direction; + constraints[uses[0].FaceIndex].Add((uses[1].FaceIndex, oppositeFlip)); + constraints[uses[1].FaceIndex].Add((uses[0].FaceIndex, oppositeFlip)); + } + + var flips = new Dictionary(); + foreach (int seed in indices) + { + if (flips.ContainsKey(seed)) continue; + flips[seed] = false; + var queue = new Queue(); + queue.Enqueue(seed); + while (queue.Count > 0) + { + int current = queue.Dequeue(); + foreach (var (other, oppositeFlip) in constraints[current]) + { + bool required = flips[current] ^ oppositeFlip; + if (flips.TryGetValue(other, out bool existing)) + { + if (existing != required) + return false; + } + else + { + flips[other] = required; + queue.Enqueue(other); + } + } + } + } + + orientedFaces = indices.Select(index => + CloneFace(normalizedFaces[index], flips[index])).ToList(); + SplitFacetedLoopsAtSharedVertices(orientedFaces); + var compactIndices = Enumerable.Range(0, orientedFaces.Count).ToList(); + if (!IsExactFacetedShell(orientedFaces, compactIndices)) + { + orientedFaces = []; + return false; + } + + var points = orientedFaces.SelectMany(face => + (face.OuterVertices ?? []).Concat((face.InnerVertices ?? []).SelectMany(ring => ring))) + .ToList(); + double[] origin = + [ + points.Average(point => point[0]), + points.Average(point => point[1]), + points.Average(point => point[2]), + ]; + double signedVolume = orientedFaces.Sum(face => + SignedFaceVolume(face.OuterVertices!, origin) + + (face.InnerVertices?.Sum(ring => SignedFaceVolume(ring, origin)) ?? 0)); + if (!double.IsFinite(signedVolume) || signedVolume == 0) + { + orientedFaces = []; + return false; + } + if (signedVolume < 0) + orientedFaces = orientedFaces.Select(face => CloneFace(face, true)).ToList(); + if (!triangulateNonPlanarFaces) + return true; + var triangulatedFaces = TriangulateNonPlanarFacetedFaces(orientedFaces); + SplitFacetedLoopsAtSharedVertices(triangulatedFaces); + if (IsExactFacetedShell(triangulatedFaces, + Enumerable.Range(0, triangulatedFaces.Count).ToList())) + orientedFaces = triangulatedFaces; + return true; + + static double SignedFaceVolume(IReadOnlyList ring, double[] origin) + { + double volume = 0; + var first = ring[0]; + for (int index = 1; index + 1 < ring.Count; index++) + { + double ax = first[0] - origin[0], ay = first[1] - origin[1], az = first[2] - origin[2]; + double bx = ring[index][0] - origin[0], by = ring[index][1] - origin[1], bz = ring[index][2] - origin[2]; + double cx = ring[index + 1][0] - origin[0], cy = ring[index + 1][1] - origin[1], cz = ring[index + 1][2] - origin[2]; + volume += (ax * (by * cz - bz * cy) - ay * (bx * cz - bz * cx) + + az * (bx * cy - by * cx)) / 6; + } + return volume; + } + + static bool TryNormalizeInnerBounds(GeoFace face) + { + if (face.InnerVertices is not { Count: > 0 }) return true; + if (face.OuterVertices is not { Count: >= 3 } outer + || !TryNewellNormal(outer, out var outerNormal)) + return false; + foreach (var inner in face.InnerVertices) + { + if (inner.Count < 3 || !TryNewellNormal(inner, out var innerNormal)) + return false; + double dot = outerNormal.X * innerNormal.X + + outerNormal.Y * innerNormal.Y + outerNormal.Z * innerNormal.Z; + if (!double.IsFinite(dot) || dot == 0) return false; + bool isStrictlyContained = IsStrictlyContainedAtIfcPrecision( + inner, outer, outerNormal); + bool hasSameDirection = dot > 0; + if (isStrictlyContained == hasSameDirection) inner.Reverse(); + } + return true; + } + + static bool IsStrictlyContainedAtIfcPrecision(IReadOnlyList inner, + IReadOnlyList outer, (double X, double Y, double Z) outerNormal) + { + int droppedAxis = Math.Abs(outerNormal.X) >= Math.Abs(outerNormal.Y) + && Math.Abs(outerNormal.X) >= Math.Abs(outerNormal.Z) ? 0 + : Math.Abs(outerNormal.Y) >= Math.Abs(outerNormal.Z) ? 1 : 2; + static (long U, long V) Project(double[] point, int droppedAxis) + { + var key = IfcPrecisionKeyFeet(point); + return droppedAxis == 0 ? (key.Y, key.Z) + : droppedAxis == 1 ? (key.X, key.Z) : (key.X, key.Y); + } + static Int128 Orientation((long U, long V) first, (long U, long V) second, + (long U, long V) point) => + ((Int128)second.U - first.U) * ((Int128)point.V - first.V) + - ((Int128)second.V - first.V) * ((Int128)point.U - first.U); + static bool OnSegment((long U, long V) point, (long U, long V) first, + (long U, long V) second) => Orientation(first, second, point) == 0 + && point.U >= Math.Min(first.U, second.U) + && point.U <= Math.Max(first.U, second.U) + && point.V >= Math.Min(first.V, second.V) + && point.V <= Math.Max(first.V, second.V); + static bool StrictlyInside((long U, long V) point, + IReadOnlyList<(long U, long V)> polygon) + { + int winding = 0; + for (int index = 0; index < polygon.Count; index++) + { + var first = polygon[index]; + var second = polygon[(index + 1) % polygon.Count]; + Int128 orientation = Orientation(first, second, point); + if (orientation == 0 && OnSegment(point, first, second)) return false; + if (first.V <= point.V && point.V < second.V && orientation > 0) winding++; + else if (second.V <= point.V && point.V < first.V && orientation < 0) winding--; + } + return winding != 0; + } + static bool Intersects((long U, long V) firstA, (long U, long V) secondA, + (long U, long V) firstB, (long U, long V) secondB) + { + Int128 ab1 = Orientation(firstA, secondA, firstB); + Int128 ab2 = Orientation(firstA, secondA, secondB); + Int128 ba1 = Orientation(firstB, secondB, firstA); + Int128 ba2 = Orientation(firstB, secondB, secondA); + if (ab1 == 0 && OnSegment(firstB, firstA, secondA)) return true; + if (ab2 == 0 && OnSegment(secondB, firstA, secondA)) return true; + if (ba1 == 0 && OnSegment(firstA, firstB, secondB)) return true; + if (ba2 == 0 && OnSegment(secondA, firstB, secondB)) return true; + return (ab1 < 0) != (ab2 < 0) && (ba1 < 0) != (ba2 < 0); + } + + var outer2d = outer.Select(point => Project(point, droppedAxis)).ToList(); + var inner2d = inner.Select(point => Project(point, droppedAxis)).ToList(); + if (outer2d.Distinct().Count() < 3 || inner2d.Distinct().Count() < 3 + || inner2d.Any(point => !StrictlyInside(point, outer2d))) + return false; + for (int innerIndex = 0; innerIndex < inner2d.Count; innerIndex++) + for (int outerIndex = 0; outerIndex < outer2d.Count; outerIndex++) + if (Intersects(inner2d[innerIndex], inner2d[(innerIndex + 1) % inner2d.Count], + outer2d[outerIndex], outer2d[(outerIndex + 1) % outer2d.Count])) + return false; + return true; + } + + static bool TryNewellNormal(IReadOnlyList ring, + out (double X, double Y, double Z) normal) + { + double x = 0, y = 0, z = 0; + for (int index = 0; index < ring.Count; index++) + { + var current = ring[index]; + var next = ring[(index + 1) % ring.Count]; + if (current.Length < 3 || next.Length < 3 + || !double.IsFinite(current[0]) || !double.IsFinite(current[1]) + || !double.IsFinite(current[2]) || !double.IsFinite(next[0]) + || !double.IsFinite(next[1]) || !double.IsFinite(next[2])) + { + normal = default; + return false; + } + x += (current[1] - next[1]) * (current[2] + next[2]); + y += (current[2] - next[2]) * (current[0] + next[0]); + z += (current[0] - next[0]) * (current[1] + next[1]); + } + normal = (x, y, z); + return double.IsFinite(x) && double.IsFinite(y) && double.IsFinite(z) + && (x != 0 || y != 0 || z != 0); + } + + static List CleanPrecisionLoop(IEnumerable source) + { + var clean = new List(); + foreach (var point in source) + if (clean.Count == 0 + || IfcPrecisionKeyFeet(clean[^1]) != IfcPrecisionKeyFeet(point)) + clean.Add((double[])point.Clone()); + if (clean.Count > 1 + && IfcPrecisionKeyFeet(clean[0]) == IfcPrecisionKeyFeet(clean[^1])) + clean.RemoveAt(clean.Count - 1); + return clean; + } + + static GeoFace CloneFace(GeoFace source, bool reverse) + { + List CopyRing(IEnumerable ring) + { + var copy = ring.Select(point => (double[])point.Clone()).ToList(); + if (reverse) copy.Reverse(); + return copy; + } + return new GeoFace + { + Origin = (double[])source.Origin.Clone(), + XVector = (double[])source.XVector.Clone(), + YVector = (double[])source.YVector.Clone(), + Normal = reverse ? source.Normal.Select(value => -value).ToArray() + : (double[])source.Normal.Clone(), + Envelope = source.Envelope is null ? null : (double[])source.Envelope.Clone(), + Area = source.Area, + InnerLoops = source.InnerLoops?.Select(loop => (double[])loop.Clone()).ToList(), + OuterVertices = source.OuterVertices is null ? null : CopyRing(source.OuterVertices), + InnerVertices = source.InnerVertices?.Select(CopyRing).ToList(), + AlternativeOuterVertices = source.AlternativeOuterVertices is null ? null + : source.AlternativeOuterVertices.Select(point => (double[])point.Clone()).ToList(), + EdgeIndices = source.EdgeIndices?.ToList(), + }; + } + } + + /// + /// Converts precision-nonplanar polygon faces to triangles using exact projected ear clipping. + /// + private static List TriangulateNonPlanarFacetedFaces( + IReadOnlyList faces) + { + + static GeoFace Triangle(GeoFace source, params double[][] vertices) => new() + { + Origin = (double[])source.Origin.Clone(), + XVector = (double[])source.XVector.Clone(), + YVector = (double[])source.YVector.Clone(), + Normal = (double[])source.Normal.Clone(), + Envelope = source.Envelope is null ? null : (double[])source.Envelope.Clone(), + Area = source.Area, + InnerLoops = source.InnerLoops?.Select(loop => (double[])loop.Clone()).ToList(), + OuterVertices = vertices.Select(point => (double[])point.Clone()).ToList(), + EdgeIndices = source.EdgeIndices?.ToList(), + }; + static bool TryProjectedShape(IReadOnlyList ring, + out bool planar, out bool convex) + { + planar = false; + convex = false; + var points = ring.Select(IfcPrecisionKeyFeet).ToList(); + if (points.Count < 4 || points.Distinct().Count() != points.Count) return false; + System.Numerics.BigInteger nx = 0, ny = 0, nz = 0; + for (int index = 0; index < points.Count; index++) + { + var current = points[index]; + var next = points[(index + 1) % points.Count]; + nx += ((System.Numerics.BigInteger)current.Y - next.Y) * (current.Z + next.Z); + ny += ((System.Numerics.BigInteger)current.Z - next.Z) * (current.X + next.X); + nz += ((System.Numerics.BigInteger)current.X - next.X) * (current.Y + next.Y); + } + if (nx.IsZero && ny.IsZero && nz.IsZero) return false; + var absX = System.Numerics.BigInteger.Abs(nx); + var absY = System.Numerics.BigInteger.Abs(ny); + var absZ = System.Numerics.BigInteger.Abs(nz); + int droppedAxis = absX >= absY && absX >= absZ ? 0 : absY >= absZ ? 1 : 2; + static (long U, long V) Project((long X, long Y, long Z) point, int axis) => + axis == 0 ? (point.Y, point.Z) + : axis == 1 ? (point.X, point.Z) : (point.X, point.Y); + int sign = 0; + for (int index = 0; index < points.Count; index++) + { + var first = Project(points[index], droppedAxis); + var second = Project(points[(index + 1) % points.Count], droppedAxis); + var third = Project(points[(index + 2) % points.Count], droppedAxis); + var turn = ((System.Numerics.BigInteger)second.U - first.U) + * (third.V - second.V) + - ((System.Numerics.BigInteger)second.V - first.V) + * (third.U - second.U); + if (turn.IsZero) continue; + int currentSign = turn.Sign; + if (sign != 0 && currentSign != sign) return true; + sign = currentSign; + } + convex = sign != 0; + + var origin = points[0]; + (System.Numerics.BigInteger X, System.Numerics.BigInteger Y, + System.Numerics.BigInteger Z)? normal = null; + for (int index = 1; index + 1 < points.Count && normal == null; index++) + { + var first = points[index]; + var second = points[index + 1]; + var ux = (System.Numerics.BigInteger)first.X - origin.X; + var uy = (System.Numerics.BigInteger)first.Y - origin.Y; + var uz = (System.Numerics.BigInteger)first.Z - origin.Z; + var vx = (System.Numerics.BigInteger)second.X - origin.X; + var vy = (System.Numerics.BigInteger)second.Y - origin.Y; + var vz = (System.Numerics.BigInteger)second.Z - origin.Z; + var cross = (X: uy * vz - uz * vy, Y: uz * vx - ux * vz, + Z: ux * vy - uy * vx); + if (!cross.X.IsZero || !cross.Y.IsZero || !cross.Z.IsZero) + normal = cross; + } + if (normal == null) return false; + planar = points.All(point => + normal.Value.X * ((System.Numerics.BigInteger)point.X - origin.X) + + normal.Value.Y * ((System.Numerics.BigInteger)point.Y - origin.Y) + + normal.Value.Z * ((System.Numerics.BigInteger)point.Z - origin.Z) == 0); + return true; + } + + static List? EarClip(GeoFace face, IReadOnlyList ring) + { + var points = ring.Select(IfcPrecisionKeyFeet).ToList(); + System.Numerics.BigInteger nx = 0, ny = 0, nz = 0; + for (int index = 0; index < points.Count; index++) + { + var current = points[index]; + var next = points[(index + 1) % points.Count]; + nx += ((System.Numerics.BigInteger)current.Y - next.Y) * (current.Z + next.Z); + ny += ((System.Numerics.BigInteger)current.Z - next.Z) * (current.X + next.X); + nz += ((System.Numerics.BigInteger)current.X - next.X) * (current.Y + next.Y); + } + var absX = System.Numerics.BigInteger.Abs(nx); + var absY = System.Numerics.BigInteger.Abs(ny); + var absZ = System.Numerics.BigInteger.Abs(nz); + if (absX.IsZero && absY.IsZero && absZ.IsZero) return null; + int droppedAxis = absX >= absY && absX >= absZ ? 0 : absY >= absZ ? 1 : 2; + static (long U, long V) Project((long X, long Y, long Z) point, int axis) => + axis == 0 ? (point.Y, point.Z) + : axis == 1 ? (point.X, point.Z) : (point.X, point.Y); + var projected = points.Select(point => Project(point, droppedAxis)).ToList(); + static System.Numerics.BigInteger Turn((long U, long V) first, + (long U, long V) second, (long U, long V) third) => + ((System.Numerics.BigInteger)second.U - first.U) * (third.V - first.V) + - ((System.Numerics.BigInteger)second.V - first.V) * (third.U - first.U); + System.Numerics.BigInteger twiceArea = 0; + for (int index = 0; index < projected.Count; index++) + { + var current = projected[index]; + var next = projected[(index + 1) % projected.Count]; + twiceArea += (System.Numerics.BigInteger)current.U * next.V + - (System.Numerics.BigInteger)next.U * current.V; + } + if (twiceArea.IsZero) return null; + int orientation = twiceArea.Sign; + var remaining = Enumerable.Range(0, ring.Count).ToList(); + var result = new List(); + int guard = ring.Count * ring.Count; + while (remaining.Count > 3 && guard-- > 0) + { + bool removed = false; + for (int offset = 0; offset < remaining.Count; offset++) + { + int previous = remaining[(offset - 1 + remaining.Count) % remaining.Count]; + int current = remaining[offset]; + int next = remaining[(offset + 1) % remaining.Count]; + var turn = Turn(projected[previous], projected[current], projected[next]); + if (turn.Sign != orientation) continue; + bool contains = remaining.Any(candidate => candidate != previous + && candidate != current && candidate != next + && new[] + { + Turn(projected[previous], projected[current], projected[candidate]), + Turn(projected[current], projected[next], projected[candidate]), + Turn(projected[next], projected[previous], projected[candidate]), + }.All(value => value.IsZero || value.Sign == orientation)); + if (contains) continue; + var triangle = Triangle(face, + ring[previous], ring[current], ring[next]); + if (FaceCollapsesAtIfcPrecision(triangle)) continue; + result.Add(triangle); + remaining.RemoveAt(offset); + removed = true; + break; + } + if (!removed) return null; + } + if (remaining.Count != 3) return null; + var finalTriangle = Triangle(face, + ring[remaining[0]], ring[remaining[1]], ring[remaining[2]]); + if (FaceCollapsesAtIfcPrecision(finalTriangle)) return null; + result.Add(finalTriangle); + return result; + } + + var result = new List(); + foreach (var face in faces) + { + if (face.OuterVertices is not { Count: > 3 } ring + || face.InnerVertices is { Count: > 0 } + || !TryProjectedShape(ring, out bool planar, out _) + || planar) + { + result.Add(face); + continue; + } + result.AddRange(EarClip(face, ring) ?? [face]); + } + return result; + } + + /// + /// Materializes the same atomic edge partition used by shell validation in the actual polygon + /// loops written to IFC. + /// + private static void SplitFacetedLoopsAtSharedVertices(IReadOnlyList faces) + { + static long Axis((long X, long Y, long Z) point, int axis) => + axis == 0 ? point.X : axis == 1 ? point.Y : point.Z; + static int LowerBound(List<(long X, long Y, long Z)> points, int axis, long value) + { + int low = 0, high = points.Count; + while (low < high) + { + int middle = low + (high - low) / 2; + if (Axis(points[middle], axis) < value) low = middle + 1; + else high = middle; + } + return low; + } + static bool OnSegment((long X, long Y, long Z) point, + (long X, long Y, long Z) first, (long X, long Y, long Z) second) + { + if (point.X < Math.Min(first.X, second.X) || point.X > Math.Max(first.X, second.X) + || point.Y < Math.Min(first.Y, second.Y) || point.Y > Math.Max(first.Y, second.Y) + || point.Z < Math.Min(first.Z, second.Z) || point.Z > Math.Max(first.Z, second.Z)) + return false; + Int128 dx = (Int128)second.X - first.X; + Int128 dy = (Int128)second.Y - first.Y; + Int128 dz = (Int128)second.Z - first.Z; + Int128 px = (Int128)point.X - first.X; + Int128 py = (Int128)point.Y - first.Y; + Int128 pz = (Int128)point.Z - first.Z; + return dy * pz - dz * py == 0 + && dz * px - dx * pz == 0 + && dx * py - dy * px == 0; + } + + var representative = new Dictionary<(long X, long Y, long Z), double[]>(); + foreach (var face in faces) + foreach (var ring in (face.OuterVertices is { Count: > 0 } outer + ? new[] { outer } + : Enumerable.Empty>()) + .Concat(face.InnerVertices ?? [])) + foreach (var point in ring) + representative.TryAdd(IfcPrecisionKeyFeet(point), point); + var vertices = representative.Keys.ToList(); + var verticesByAxis = Enumerable.Range(0, 3) + .Select(axis => vertices.OrderBy(point => Axis(point, axis)) + .ThenBy(point => point.X).ThenBy(point => point.Y).ThenBy(point => point.Z) + .ToList()).ToArray(); + + List Split(IReadOnlyList ring) + { + var result = new List(); + for (int edgeIndex = 0; edgeIndex < ring.Count; edgeIndex++) + { + var sourceFirst = ring[edgeIndex]; + var sourceSecond = ring[(edgeIndex + 1) % ring.Count]; + var first = IfcPrecisionKeyFeet(sourceFirst); + var second = IfcPrecisionKeyFeet(sourceSecond); + result.Add(sourceFirst); + if (first == second) continue; + Int128 dx = (Int128)second.X - first.X; + Int128 dy = (Int128)second.Y - first.Y; + Int128 dz = (Int128)second.Z - first.Z; + Int128 absX = Int128.Abs(dx), absY = Int128.Abs(dy), absZ = Int128.Abs(dz); + int axis = absX >= absY && absX >= absZ ? 0 : absY >= absZ ? 1 : 2; + long low = Math.Min(Axis(first, axis), Axis(second, axis)); + long high = Math.Max(Axis(first, axis), Axis(second, axis)); + var split = new List<(long X, long Y, long Z)>(); + var sorted = verticesByAxis[axis]; + for (int index = LowerBound(sorted, axis, low); + index < sorted.Count && Axis(sorted[index], axis) <= high; index++) + if (sorted[index] != first && sorted[index] != second + && OnSegment(sorted[index], first, second)) + split.Add(sorted[index]); + split.Sort((left, right) => Axis(left, axis).CompareTo(Axis(right, axis))); + if (Axis(first, axis) > Axis(second, axis)) split.Reverse(); + result.AddRange(split.Select(point => representative[point])); + } + var clean = new List(); + foreach (var point in result) + if (clean.Count == 0 + || IfcPrecisionKeyFeet(clean[^1]) != IfcPrecisionKeyFeet(point)) + clean.Add(point); + if (clean.Count > 1 + && IfcPrecisionKeyFeet(clean[0]) == IfcPrecisionKeyFeet(clean[^1])) + clean.RemoveAt(clean.Count - 1); + return clean; + } + + foreach (var face in faces) + { + if (face.OuterVertices is { Count: >= 3 } outer) + face.OuterVertices = Split(outer); + if (face.InnerVertices is { Count: > 0 } inner) + face.InnerVertices = inner.Select(Split).ToList(); + } + } + + /// Builds exact shared-edge uses on the serialized IFC coordinate lattice. + internal static bool TryGetFacetedAtomicEdgeUses(IReadOnlyDictionary faces, + IReadOnlyCollection faceIndices, + out Dictionary<((long X, long Y, long Z) A, (long X, long Y, long Z) B), + List<(int FaceIndex, int Direction)>> edgeUses) + { + static ((long X, long Y, long Z) A, (long X, long Y, long Z) B) EdgeKey( + (long X, long Y, long Z) first, (long X, long Y, long Z) second) + => first.CompareTo(second) <= 0 ? (first, second) : (second, first); + static long Axis((long X, long Y, long Z) point, int axis) => + axis == 0 ? point.X : axis == 1 ? point.Y : point.Z; + static int LowerBound(List<(long X, long Y, long Z)> points, int axis, long value) + { + int low = 0, high = points.Count; + while (low < high) + { + int middle = low + (high - low) / 2; + if (Axis(points[middle], axis) < value) low = middle + 1; + else high = middle; + } + return low; + } + static bool OnSegment((long X, long Y, long Z) point, + (long X, long Y, long Z) first, (long X, long Y, long Z) second) + { + if (point.X < Math.Min(first.X, second.X) || point.X > Math.Max(first.X, second.X) + || point.Y < Math.Min(first.Y, second.Y) || point.Y > Math.Max(first.Y, second.Y) + || point.Z < Math.Min(first.Z, second.Z) || point.Z > Math.Max(first.Z, second.Z)) + return false; + Int128 dx = (Int128)second.X - first.X; + Int128 dy = (Int128)second.Y - first.Y; + Int128 dz = (Int128)second.Z - first.Z; + Int128 px = (Int128)point.X - first.X; + Int128 py = (Int128)point.Y - first.Y; + Int128 pz = (Int128)point.Z - first.Z; + return dy * pz - dz * py == 0 + && dz * px - dx * pz == 0 + && dx * py - dy * px == 0; + } + + var usesByEdge = new Dictionary< + ((long X, long Y, long Z) A, (long X, long Y, long Z) B), + List<(int FaceIndex, int Direction)>>(); + edgeUses = usesByEdge; + var segments = new List<(int FaceIndex, (long X, long Y, long Z) First, + (long X, long Y, long Z) Second)>(); + foreach (int faceIndex in faceIndices) + { + if (!faces.TryGetValue(faceIndex, out var face) + || face.OuterVertices is not { Count: >= 3 } outer) + return false; + IEnumerable> rings = + new[] { (IReadOnlyList)outer } + .Concat(face.InnerVertices ?? Enumerable.Empty>()); + foreach (var ring in rings) + { + if (ring.Count < 3 || ring.Any(point => point.Length < 3 + || !double.IsFinite(point[0]) || !double.IsFinite(point[1]) + || !double.IsFinite(point[2]))) + return false; + for (int index = 0; index < ring.Count; index++) + { + var first = IfcPrecisionKeyFeet(ring[index]); + var second = IfcPrecisionKeyFeet(ring[(index + 1) % ring.Count]); + if (first == second) return false; + segments.Add((faceIndex, first, second)); + } + } + } + if (segments.Count == 0) return false; + + void AddUse(int faceIndex, (long X, long Y, long Z) first, + (long X, long Y, long Z) second) + { + var edge = EdgeKey(first, second); + if (!usesByEdge.TryGetValue(edge, out var uses)) usesByEdge[edge] = uses = []; + uses.Add((faceIndex, first.CompareTo(second) <= 0 ? 1 : -1)); + } + bool HasClosedMultiplicity() => usesByEdge.Count > 0 + && usesByEdge.Values.All(uses => uses.Count == 2 + && uses[0].FaceIndex != uses[1].FaceIndex); + + foreach (var segment in segments) + AddUse(segment.FaceIndex, segment.First, segment.Second); + if (HasClosedMultiplicity()) return true; + + usesByEdge.Clear(); + var vertices = segments.SelectMany(segment => new[] { segment.First, segment.Second }) + .Distinct().ToList(); + var verticesByAxis = Enumerable.Range(0, 3) + .Select(axis => vertices.OrderBy(point => Axis(point, axis)) + .ThenBy(point => point.X).ThenBy(point => point.Y).ThenBy(point => point.Z) + .ToList()) + .ToArray(); + foreach (var segment in segments) + { + Int128 dx = (Int128)segment.Second.X - segment.First.X; + Int128 dy = (Int128)segment.Second.Y - segment.First.Y; + Int128 dz = (Int128)segment.Second.Z - segment.First.Z; + Int128 absX = Int128.Abs(dx), absY = Int128.Abs(dy), absZ = Int128.Abs(dz); + int axis = absX >= absY && absX >= absZ ? 0 : absY >= absZ ? 1 : 2; + long low = Math.Min(Axis(segment.First, axis), Axis(segment.Second, axis)); + long high = Math.Max(Axis(segment.First, axis), Axis(segment.Second, axis)); + var sorted = verticesByAxis[axis]; + var split = new List<(long X, long Y, long Z)>(); + for (int index = LowerBound(sorted, axis, low); + index < sorted.Count && Axis(sorted[index], axis) <= high; index++) + if (OnSegment(sorted[index], segment.First, segment.Second)) + split.Add(sorted[index]); + if (Axis(segment.First, axis) > Axis(segment.Second, axis)) split.Reverse(); + if (split.Count < 2 || split[0] != segment.First || split[^1] != segment.Second) + return false; + for (int index = 0; index + 1 < split.Count; index++) + AddUse(segment.FaceIndex, split[index], split[index + 1]); + } + return HasClosedMultiplicity(); + } + + /// + /// Checks whether the emitted polygon loops satisfy IFC closed-shell topology using the same + /// declared-precision identity as the IFC point cache. + /// + internal static bool IsExactFacetedShell( + IReadOnlyList faces, IReadOnlyCollection faceIndices) + { + var faceMap = faceIndices.Distinct().ToDictionary(index => index, + index => (uint)index < faces.Count ? faces[index] : null); + if (faceMap.Values.Any(face => face == null)) return false; + return TryGetFacetedAtomicEdgeUses( + faceMap.ToDictionary(pair => pair.Key, pair => pair.Value!), + faceIndices, out var edgeUses) + && edgeUses.Values.All(uses => uses[0].Direction + uses[1].Direction == 0); + } +} diff --git a/src/RvtIO/Ifc/WallExtrusion.Axis.cs b/src/RvtIO/Geometry/WallExtrusion.Axis.cs similarity index 99% rename from src/RvtIO/Ifc/WallExtrusion.Axis.cs rename to src/RvtIO/Geometry/WallExtrusion.Axis.cs index e7193703..647dadda 100644 --- a/src/RvtIO/Ifc/WallExtrusion.Axis.cs +++ b/src/RvtIO/Geometry/WallExtrusion.Axis.cs @@ -1,6 +1,6 @@ using RvtIO.Model; -namespace RvtIO.Ifc; +namespace RvtIO.Geometry; /// The search for a vertical-style extrusion along one axis of any direction (Z for a wall, the custom axis /// across the host wall for an opening), keeping the face the extrusion starts diff --git a/src/RvtIO/Ifc/WallExtrusion.cs b/src/RvtIO/Geometry/WallExtrusion.cs similarity index 99% rename from src/RvtIO/Ifc/WallExtrusion.cs rename to src/RvtIO/Geometry/WallExtrusion.cs index 73c25eab..f259818f 100644 --- a/src/RvtIO/Ifc/WallExtrusion.cs +++ b/src/RvtIO/Geometry/WallExtrusion.cs @@ -1,6 +1,6 @@ using RvtIO.Model; -namespace RvtIO.Ifc; +namespace RvtIO.Geometry; /// /// The two geometric tests the current profile wall exporter applies to a wall body before it writes an IfcWallStandardCase: @@ -93,7 +93,7 @@ internal static double ExactFaceArea(GeoFace face, out bool exact) { exact = face.MeshArcs is not { Count: > 0 }; if (face.OuterVertices is { Count: >= 3 } outer && face.MeshArcs is { Count: > 0 } arcs - && IfcExporter.FindArcRunsCurrent(outer, arcs) is var runs && runs.Count == arcs.Count) + && ArcRuns.FindArcRunsCurrent(outer, arcs) is var runs && runs.Count == arcs.Count) { exact = true; return ExactLoopArea(outer, runs); @@ -101,7 +101,7 @@ internal static double ExactFaceArea(GeoFace face, out bool exact) return LoopArea(face.OuterVertices); } - private static double ExactLoopArea(IReadOnlyList ring, IReadOnlyList runs) + private static double ExactLoopArea(IReadOnlyList ring, IReadOnlyList runs) { double[] total = [0, 0, 0]; void Add(double[] a, double[] b, double sign) diff --git a/src/RvtIO/Ifc/IfcExporter.ArcWallsCurrent.cs b/src/RvtIO/Ifc/IfcExporter.ArcWallsCurrent.cs index 811f3ef3..c004556e 100644 --- a/src/RvtIO/Ifc/IfcExporter.ArcWallsCurrent.cs +++ b/src/RvtIO/Ifc/IfcExporter.ArcWallsCurrent.cs @@ -1,3 +1,4 @@ +using RvtIO.Geometry; using RvtIO.Model; namespace RvtIO.Ifc; diff --git a/src/RvtIO/Ifc/IfcExporter.CurveLoopAreaCurrent.cs b/src/RvtIO/Ifc/IfcExporter.CurveLoopAreaCurrent.cs index 3c2b69a5..37c4ebb9 100644 --- a/src/RvtIO/Ifc/IfcExporter.CurveLoopAreaCurrent.cs +++ b/src/RvtIO/Ifc/IfcExporter.CurveLoopAreaCurrent.cs @@ -1,5 +1,7 @@ +using static RvtIO.Geometry.ArcRuns; using RvtIO.Geometry.Meshing; using RvtIO.Model; +using static RvtIO.Geometry.BrepMeasures; namespace RvtIO.Ifc; diff --git a/src/RvtIO/Ifc/IfcExporter.CutPairOpenings.cs b/src/RvtIO/Ifc/IfcExporter.CutPairOpenings.cs index 86191cd4..0e979e47 100644 --- a/src/RvtIO/Ifc/IfcExporter.CutPairOpenings.cs +++ b/src/RvtIO/Ifc/IfcExporter.CutPairOpenings.cs @@ -1,3 +1,4 @@ +using RvtIO.Geometry; using RvtIO.Model; namespace RvtIO.Ifc; diff --git a/src/RvtIO/Ifc/IfcExporter.ExtrusionBodiesCurrent.cs b/src/RvtIO/Ifc/IfcExporter.ExtrusionBodiesCurrent.cs index 36f12bb5..c50e3e5c 100644 --- a/src/RvtIO/Ifc/IfcExporter.ExtrusionBodiesCurrent.cs +++ b/src/RvtIO/Ifc/IfcExporter.ExtrusionBodiesCurrent.cs @@ -1,3 +1,4 @@ +using RvtIO.Geometry; using RvtIO.Model; namespace RvtIO.Ifc; diff --git a/src/RvtIO/Ifc/IfcExporter.ExtrusionOthersCurrent.cs b/src/RvtIO/Ifc/IfcExporter.ExtrusionOthersCurrent.cs index a9310106..22de6861 100644 --- a/src/RvtIO/Ifc/IfcExporter.ExtrusionOthersCurrent.cs +++ b/src/RvtIO/Ifc/IfcExporter.ExtrusionOthersCurrent.cs @@ -1,3 +1,4 @@ +using RvtIO.Geometry; using System.Globalization; using RvtIO.Model; diff --git a/src/RvtIO/Ifc/IfcExporter.ExtrusionProfilesCurrent.cs b/src/RvtIO/Ifc/IfcExporter.ExtrusionProfilesCurrent.cs index 6091e9b8..b5befe0e 100644 --- a/src/RvtIO/Ifc/IfcExporter.ExtrusionProfilesCurrent.cs +++ b/src/RvtIO/Ifc/IfcExporter.ExtrusionProfilesCurrent.cs @@ -1,3 +1,5 @@ +using static RvtIO.Geometry.ArcRuns; + namespace RvtIO.Ifc; /// The profile, position and direction of an IfcExtrudedAreaSolid written for the extrusion of the curve loops of a face. @@ -27,81 +29,6 @@ internal static List CurveLoopCurrent(IReadOnlyList ring, do return flipped; } - /// One circular edge of a ring: the ring vertices First..First+Steps (cyclic, in ring order) are samples of - /// Arc, whose stored parameter runs against the ring order when Reversed. EitherWay: the other way round - /// the ring passed as the arc too, so the run is the shorter of the two, not a known one. - internal readonly record struct ArcRunCurrent(int First, int Steps, Internal.Arc Arc, bool Reversed, bool EitherWay = false); - - /// Finds the circular edges of a ring: the arcs whose two ends are vertices of the ring and whose vertices between - /// them lie on the circle. An arc that closes on itself or has no such run is left out (the ring keeps its own points). - internal static List FindArcRunsCurrent(IReadOnlyList ring, IReadOnlyList arcs) - { - var runs = new List(); - int n = ring.Count; - foreach (var arc in arcs) - { - double radius = Math.Abs(arc.Radius), tolerance = 1e-6 * Math.Max(radius, 1e-3); - double[] normal = CrossCurrent(arc.X, arc.Y); - bool Near(double[] p, double[] q) => Math.Abs(p[0] - q[0]) <= tolerance && Math.Abs(p[1] - q[1]) <= tolerance - && Math.Abs(p[2] - q[2]) <= tolerance; - bool OnCircle(double[] p) - { - double[] d = [p[0] - arc.Centre[0], p[1] - arc.Centre[1], p[2] - arc.Centre[2]]; - double axial = DotCurrent(d, normal); - return Math.Abs(axial) <= tolerance && Math.Abs(Math.Sqrt(DotCurrent(d, d) - axial * axial) - radius) <= tolerance; - } - // a vertex between two samples of the circle that lies on the straight segment joining them: the mesh of the neighbouring - // cylinder added it to the ring - bool OnChord(double[] p, double[] a, double[] b) - { - double[] ab = [b[0] - a[0], b[1] - a[1], b[2] - a[2]], ap = [p[0] - a[0], p[1] - a[1], p[2] - a[2]]; - double length2 = DotCurrent(ab, ab); - if (!(length2 > 0)) return false; - double t = DotCurrent(ap, ab) / length2; - if (t < -1e-9 || t > 1 + 1e-9) return false; - double[] off = [ap[0] - t * ab[0], ap[1] - t * ab[1], ap[2] - t * ab[2]]; - return Math.Sqrt(DotCurrent(off, off)) <= tolerance; - } - bool IsArcRoute(List route) - { - int previous = 0; - for (int i = 1; i < route.Count; i++) - { - if (!OnCircle(route[i])) continue; - for (int between = previous + 1; between < i; between++) - if (!OnChord(route[between], route[previous], route[i])) return false; - previous = i; - } - return previous == route.Count - 1; - } - double[] start = arc.At(arc.First), end = arc.At(arc.Last); - int s = -1, e = -1; - for (int i = 0; i < n; i++) - { - if (s < 0 && Near(ring[i], start)) s = i; - if (e < 0 && Near(ring[i], end)) e = i; - } - if (s < 0 || e < 0 || s == e) continue; - // forward from s to e, or backward (the ring runs against the stored parameter): the way that is the arc - int bestSteps = int.MaxValue, bestDirection = 0, ways = 0; - for (int direction = 1; direction >= -1; direction -= 2) - { - var route = new List { ring[s] }; - for (int i = (s + direction + n) % n; ; i = (i + direction + n) % n) - { - route.Add(ring[i]); - if (i == e || route.Count > n) break; - } - if (route.Count > n || !IsArcRoute(route)) continue; - ways++; - if (route.Count - 1 < bestSteps) (bestSteps, bestDirection) = (route.Count - 1, direction); - } - if (bestDirection != 0) - runs.Add(bestDirection == 1 ? new ArcRunCurrent(s, bestSteps, arc, false, ways == 2) : new ArcRunCurrent(e, bestSteps, arc, true, ways == 2)); - } - return runs; - } - /// An arc of a resampled ring: the Chords equal chords that start at the point First of the ring (cyclic) /// stand for one circular arc of the angle Sweep, positive where the arc bulges out of the ring. internal readonly record struct ArcChordsCurrent(int First, int Chords, double Sweep); diff --git a/src/RvtIO/Ifc/IfcExporter.FaceBoundsCurrent.cs b/src/RvtIO/Ifc/IfcExporter.FaceBoundsCurrent.cs index de91e88d..19c1ba2f 100644 --- a/src/RvtIO/Ifc/IfcExporter.FaceBoundsCurrent.cs +++ b/src/RvtIO/Ifc/IfcExporter.FaceBoundsCurrent.cs @@ -1,4 +1,5 @@ using RvtIO.Model; +using static RvtIO.Geometry.FacetedShell; namespace RvtIO.Ifc; diff --git a/src/RvtIO/Ifc/IfcExporter.QuantitiesCurrent.cs b/src/RvtIO/Ifc/IfcExporter.QuantitiesCurrent.cs index 22a533e3..9f92fc4b 100644 --- a/src/RvtIO/Ifc/IfcExporter.QuantitiesCurrent.cs +++ b/src/RvtIO/Ifc/IfcExporter.QuantitiesCurrent.cs @@ -1,5 +1,7 @@ +using RvtIO.Geometry; using System.Globalization; using RvtIO.Model; +using static RvtIO.Geometry.BrepMeasures; namespace RvtIO.Ifc; @@ -924,19 +926,6 @@ private static (double Volume, double Area)? SolidTotalsCurrent(IReadOnlyList shell.Volume) * CubicFeetToCubicMetres, shells.Sum(shell => shell.Area) * SquareFeetToSquareMetres); - /// Volume (m3) and surface area (m2) of the solids the exporter takes: the sum of the surface integrals of the Geometry nodes it takes - /// (a cutting node, whose measure has a negative volume, is not taken). Null unless every node of the geometry has its integrals. - internal static (double Volume, double Area)? NodeSolidTotalsCurrent(GeometryData? geometry) - { - if (geometry?.NodeMeasures is not { Count: > 0 } measures || geometry.Faces.Count == 0) return null; - var byNode = new Dictionary(); - foreach (var measure in measures) byNode.TryAdd(measure.Node, measure); - if (geometry.Faces.Any(face => face.GeometryNode > 0 && !byNode.ContainsKey(face.GeometryNode))) return null; - var taken = byNode.Values.Where(measure => measure.Volume > 0).ToList(); - if (taken.Count == 0) return null; - return (taken.Sum(measure => measure.Volume) * CubicFeetToCubicMetres, taken.Sum(measure => measure.Area) * SquareFeetToSquareMetres); - } - /// Volume (m3) of a foundation of several solids, node by node: the measure of the node when it has surface integrals, else the /// volume of its closed shells, else the volume of its open straight prism (), else nothing. /// A node below zero and a cutting node (a negative measure) take no part. Null when the sum is not positive. diff --git a/src/RvtIO/Ifc/IfcExporter.QuantityGeometryCurrent.cs b/src/RvtIO/Ifc/IfcExporter.QuantityGeometryCurrent.cs index f3aca7fa..41f33fda 100644 --- a/src/RvtIO/Ifc/IfcExporter.QuantityGeometryCurrent.cs +++ b/src/RvtIO/Ifc/IfcExporter.QuantityGeometryCurrent.cs @@ -1,4 +1,6 @@ +using RvtIO.Geometry; using RvtIO.Model; +using static RvtIO.Geometry.BrepMeasures; namespace RvtIO.Ifc; @@ -7,123 +9,6 @@ namespace RvtIO.Ifc; /// normal), taken here from the decoded BRep shells in feet. public partial class IfcExporter { - private const double SquareFeetToSquareMetres = FeetToMetres * FeetToMetres; - private const double CubicFeetToCubicMetres = FeetToMetres * FeetToMetres * FeetToMetres; - - /// One decoded shell: its faces, its volume (the divergence theorem over its planar faces) and the sum of - /// its face areas (holes subtracted), in feet. Complete analytic nodes use source surface integrals. - internal sealed record ShellInfo(IReadOnlyList Faces, bool Closed, double Volume, double Area) - { - public bool SourceMeasured { get; init; } - } - - /// The prism a shell is, in feet: Depth is the distance of the two end faces, ProfileArea the net area of an - /// end face, OuterPerimeter the length of its outer loop and ExtentX/ExtentY the world extents of the loop that is measured - /// (they describe the profile only for a vertical prism): the first loop of the lower end face as the Face serializes its loops, - /// which is a hole when the Face lists one first. - internal readonly record struct ShellPrism( - double Depth, double ProfileArea, double OuterPerimeter, double ExtentX, double ExtentY, bool Vertical, - double InnerPerimeter = 0); - - /// The total surface area (feet squared) of the solids of a geometry: the sum over its shells, the holes of the faces - /// subtracted. - internal static double SurfaceAreaCurrent(GeometryData? geometry) => ShellsOfCurrent(geometry).Sum(shell => shell.SourceMeasured ? shell.Area : - shell.Faces.GroupBy(face => (face.GeometryNode, Marker: face.SourceFace != 0 ? face.SourceFace : face.MeshMarker)) - .Sum(group => group.Key.Marker != 0 && group.First().QuadratureArea is { } exact - ? exact : group.Sum(face => NetFaceArea(face) ?? 0))); - - private static double[] RingNormal(IReadOnlyList ring) - { - double nx = 0, ny = 0, nz = 0; - for (int i = 0; i < ring.Count; i++) - { - var a = ring[i]; - var b = ring[(i + 1) % ring.Count]; - nx += (a[1] - b[1]) * (a[2] + b[2]); - ny += (a[2] - b[2]) * (a[0] + b[0]); - nz += (a[0] - b[0]) * (a[1] + b[1]); - } - return [nx, ny, nz]; - } - - /// Area of the polygon of a (planar) ring. - private static double RingArea(IReadOnlyList ring) - { - if (ring.Count < 3) return 0; - var n = RingNormal(ring); - return 0.5 * Math.Sqrt(n[0] * n[0] + n[1] * n[1] + n[2] * n[2]); - } - - private static double RingPerimeter(IReadOnlyList ring) - { - double length = 0; - for (int i = 0; i < ring.Count; i++) - { - var a = ring[i]; - var b = ring[(i + 1) % ring.Count]; - length += Math.Sqrt((b[0] - a[0]) * (b[0] - a[0]) + (b[1] - a[1]) * (b[1] - a[1]) + (b[2] - a[2]) * (b[2] - a[2])); - } - return length; - } - - /// Face area with its inner loops subtracted; null when the face has no outer loop. - internal static double? NetFaceArea(GeoFace face) - { - if (face.OuterVertices is not { Count: >= 3 } outer) return null; - double area = RingArea(outer); - if (face.InnerVertices != null) - foreach (var hole in face.InnerVertices) area -= RingArea(hole); - return area; - } - - /// Unit normal of the outer loop by its winding; null for a degenerate loop. - private static double[]? FaceUnitNormal(GeoFace face) - { - if (face.OuterVertices is not { Count: >= 3 } outer) return null; - var n = RingNormal(outer); - double length = Math.Sqrt(n[0] * n[0] + n[1] * n[1] + n[2] * n[2]); - return length < 1e-12 ? null : [n[0] / length, n[1] / length, n[2] / length]; - } - - /// The shells of an element geometry (all faces as one shell when none are listed). - internal static List ShellsOfCurrent(GeometryData? geometry) - { - var result = new List(); - if (geometry?.Faces is not { Count: > 0 } faces) return result; - IEnumerable<(List Faces, bool Closed)> shells = geometry.BrepSolids is { Count: > 0 } solids - ? solids.Select(solid => (solid.FaceIndices.Where(i => (uint)i < (uint)faces.Count).Select(i => faces[i]).ToList(), solid.IsClosed)) - : [(faces, false)]; - foreach (var (shellFaces, closed) in shells) - { - double volume = 0, area = 0; - // The signed volume needs every face wound the same way (outward); a closed shell that orients exactly is summed oriented. - IReadOnlyList computationFaces = shellFaces; - if (closed && shellFaces.Count >= 4 - && TryOrientExactFacetedShell(shellFaces, Enumerable.Range(0, shellFaces.Count).ToList(), out var orientedShell, triangulateNonPlanarFaces: false)) - computationFaces = orientedShell; - foreach (var face in computationFaces) - { - if (NetFaceArea(face) is not { } net || FaceUnitNormal(face) is not { } normal) continue; - area += net; - var p = face.OuterVertices![0]; - volume += (p[0] * normal[0] + p[1] * normal[1] + p[2] * normal[2]) * net / 3; - } - bool sourceMeasured = false; - if (closed && shellFaces.Select(face => face.GeometryNode).Distinct().ToList() is [var nodeId] - && geometry.NodeMeasures?.Any(measure => measure.Node == nodeId && measure.Volume < 0) != true // a cutting node has no solid to measure - && geometry.MeshNodes?.FirstOrDefault(node => node.Node == nodeId) is { SourceMeasures: { } measures } source - && shellFaces.Select(face => face.SourceFace != 0 ? face.SourceFace : face.MeshMarker).ToHashSet() - .SetEquals(source.Faces.Select(face => (uint)face.Marker))) - { - area = measures.Area; - volume = measures.Volume; - sourceMeasured = true; - } - result.Add(new ShellInfo(shellFaces, closed, Math.Abs(volume), area) { SourceMeasured = sourceMeasured }); - } - return result; - } - /// The net areas of the faces: one face per serialized Face handle, whereas the parser cuts a face /// into several regions (); the regions of one face count as one. private static IEnumerable FaceAreasCurrent(IEnumerable faces) @@ -149,63 +34,6 @@ internal static double LargestVerticalFaceAreaCurrent(IEnumerable she shells.Sum(shell => FaceAreasCurrent(shell.Faces.Where(face => !face.CurvedSurface && FaceUnitNormal(face) is { } n && Math.Abs(n[2]) < 1e-9)) .DefaultIfEmpty(0).Max()); - /// The prism of a shell: two planar faces of equal net area (within 1e-4 ft2) facing each other on - /// different planes, with every other face parallel to their common normal. Null for any other shape, a curved face - /// included. - /// With the vertical cylinders that tessellate the arcs of the outline are allowed as sides and left - /// out of the search (the perimeters stay those of the chords), and a shell with any other curved face is no prism. - internal static ShellPrism? FindPrismCurrent(ShellInfo shell, bool verticalOnly = false, bool arcSides = false) - { - var faces = shell.Faces; - if (faces.Count < 4) return null; - if (arcSides) - { - var cylinders = faces.Where(face => face.CurvedSurface).ToList(); - if (cylinders.Any(face => face.AnalyticCylinderAxis is not { Length: >= 3 } axis || Math.Abs(Math.Abs(axis[2]) - 1) > 1e-9 - || !(face.AnalyticCylinderRadius > 0))) return null; - faces = faces.Where(face => !face.CurvedSurface).ToList(); - } - int count = faces.Count; - if (count < 2 || faces.Any(face => face.CurvedSurface)) return null; - var normals = new double[count][]; - var areas = new double[count]; - for (int i = 0; i < count; i++) - { - if (FaceUnitNormal(faces[i]) is not { } n || NetFaceArea(faces[i]) is not { } a) return null; - normals[i] = n; - areas[i] = a; - } - ShellPrism? best = null; - for (int i = 0; i < count; i++) - { - for (int j = i + 1; j < count; j++) - { - var a = normals[i]; - var b = normals[j]; - if (a[0] * b[0] + a[1] * b[1] + a[2] * b[2] > -1 + 1e-9 || Math.Abs(areas[i] - areas[j]) > 1e-4) continue; - bool vertical = Math.Abs(a[2]) > 1 - 1e-9; - if (verticalOnly && !vertical) continue; - bool others = true; - for (int k = 0; k < count && others; k++) - if (k != i && k != j) - others = Math.Abs(normals[k][0] * a[0] + normals[k][1] * a[1] + normals[k][2] * a[2]) < 1e-6; - if (!others) continue; - var pi = faces[i].OuterVertices![0]; - var pj = faces[j].OuterVertices![0]; - double depth = Math.Abs((pj[0] - pi[0]) * a[0] + (pj[1] - pi[1]) * a[1] + (pj[2] - pi[2]) * a[2]); - // A box is a prism along each of its three axes; its long axis is the one a bar is extruded along. - if (depth < 1e-9 || best is { } known && known.Depth >= depth) continue; - var outer = faces[i].OuterVertices!; - var lower = vertical && MeanHeightCurrent(faces[j]) < MeanHeightCurrent(faces[i]) ? faces[j] : faces[i]; - var measured = lower.FirstSourceLoop ?? lower.OuterVertices!; - best = new ShellPrism(depth, areas[i], RingPerimeter(outer), - measured.Max(p => p[0]) - measured.Min(p => p[0]), measured.Max(p => p[1]) - measured.Min(p => p[1]), vertical, - faces[i].InnerVertices?.Sum(RingPerimeter) ?? 0); - } - } - return best; - } - /// An exact end face: a planar face that carries the area of the Revit face (). private static bool IsExactCap(GeoFace face) => face.PlaneSurface && face.QuadratureArea != null && face.OuterVertices is { Count: >= 3 }; @@ -283,10 +111,6 @@ private static (double X, double Y, double R)? CircleOfCorners(IReadOnlyList Math.Abs(Math.Sqrt((p[0] - x) * (p[0] - x) + (p[1] - y) * (p[1] - y)) - radius) <= Math.Max(1e-6 * radius, slack)) ? (x, y, radius) : null; } - /// Mean height of a face and the height range of a set of faces, in feet. The windings of decoded faces do not say - /// which side is outside, so "top" and "bottom" are told by the height of a face against the middle of the range. - private static double MeanHeightCurrent(GeoFace face) => face.OuterVertices!.Average(point => point[2]); - private static double? MiddleHeightCurrent(IEnumerable faces) { var heights = faces.Where(face => face.OuterVertices is { Count: > 0 }).SelectMany(face => face.OuterVertices!).Select(point => point[2]).ToList(); diff --git a/src/RvtIO/Ifc/IfcExporter.RampCurrent.cs b/src/RvtIO/Ifc/IfcExporter.RampCurrent.cs index e35bf53c..f09e5a2d 100644 --- a/src/RvtIO/Ifc/IfcExporter.RampCurrent.cs +++ b/src/RvtIO/Ifc/IfcExporter.RampCurrent.cs @@ -1,3 +1,4 @@ +using RvtIO.Geometry; using System.Globalization; using RvtIO.Model; diff --git a/src/RvtIO/Ifc/IfcExporter.RoofSlabCurrent.cs b/src/RvtIO/Ifc/IfcExporter.RoofSlabCurrent.cs index 099d63ec..7f94fc4a 100644 --- a/src/RvtIO/Ifc/IfcExporter.RoofSlabCurrent.cs +++ b/src/RvtIO/Ifc/IfcExporter.RoofSlabCurrent.cs @@ -1,3 +1,4 @@ +using RvtIO.Geometry; using System.Text; using RvtIO.Model; diff --git a/src/RvtIO/Ifc/IfcExporter.SlopeCurrent.cs b/src/RvtIO/Ifc/IfcExporter.SlopeCurrent.cs index 7f0cef42..0d41110c 100644 --- a/src/RvtIO/Ifc/IfcExporter.SlopeCurrent.cs +++ b/src/RvtIO/Ifc/IfcExporter.SlopeCurrent.cs @@ -1,3 +1,4 @@ +using RvtIO.Geometry; using System.Globalization; using RvtIO.Model; diff --git a/src/RvtIO/Ifc/IfcExporter.cs b/src/RvtIO/Ifc/IfcExporter.cs index cd485604..86dd517e 100644 --- a/src/RvtIO/Ifc/IfcExporter.cs +++ b/src/RvtIO/Ifc/IfcExporter.cs @@ -1,8 +1,10 @@ using System.Globalization; using System.Text.RegularExpressions; +using RvtIO.Geometry; using RvtIO.Lookup; using RvtIO.Model; using RvtIO.Parsing; +using static RvtIO.Geometry.FacetedShell; namespace RvtIO.Ifc; @@ -208,8 +210,6 @@ private readonly record struct RepresentationMapCacheEntry( // Feet to metres conversion private const double FeetToMetres = 0.3048; - // Geometry coordinates are emitted on this exact metric lattice. - private const double IfcGeometryPrecisionMetres = 1.0e-5; private const double IfcDeclaredPrecisionMetres = IfcGeometryPrecisionMetres / 2; private static readonly Guid AdskSizeHeightParameterGuid = Guid.Parse("da753fe3-ecfa-465b-9a2c-02f55d0c2ff1"); @@ -224,52 +224,6 @@ private readonly record struct RepresentationMapCacheEntry( private static readonly Guid HostedOpeningDepthParameterGuid = Guid.Parse("e140a591-7a59-4036-b7e4-074fbd8222ff"); - private static (long X, long Y, long Z) IfcPrecisionKeyFeet(double[] point) => - (IfcPrecisionBinMetres(point[0] * FeetToMetres), - IfcPrecisionBinMetres(point[1] * FeetToMetres), - IfcPrecisionBinMetres(point[2] * FeetToMetres)); - - private static (long X, long Y, long Z) IfcPrecisionKeyMetres( - double x, double y, double z) => - (IfcPrecisionBinMetres(x), IfcPrecisionBinMetres(y), IfcPrecisionBinMetres(z)); - - private static long IfcPrecisionBinMetres(double value) => checked((long)Math.Round( - value / IfcGeometryPrecisionMetres, MidpointRounding.ToEven)); - - private static bool FaceCollapsesAtIfcPrecision(GeoFace face) - { - if (face.OuterVertices is not { Count: >= 3 } source - || source.Any(point => point.Length < 3 - || !double.IsFinite(point[0]) || !double.IsFinite(point[1]) - || !double.IsFinite(point[2]))) - return false; - var vertices = new List<(long X, long Y, long Z)>(); - foreach (var point in source) - { - var key = IfcPrecisionKeyFeet(point); - if (vertices.Count == 0 || vertices[^1] != key) vertices.Add(key); - } - if (vertices.Count > 1 && vertices[0] == vertices[^1]) vertices.RemoveAt(vertices.Count - 1); - if (vertices.Count < 3) return true; - var first = vertices[0]; - for (int index = 1; index + 1 < vertices.Count; index++) - { - var second = vertices[index]; - var third = vertices[index + 1]; - var ux = (System.Numerics.BigInteger)second.X - first.X; - var uy = (System.Numerics.BigInteger)second.Y - first.Y; - var uz = (System.Numerics.BigInteger)second.Z - first.Z; - var vx = (System.Numerics.BigInteger)third.X - first.X; - var vy = (System.Numerics.BigInteger)third.Y - first.Y; - var vz = (System.Numerics.BigInteger)third.Z - first.Z; - if (!(uy * vz - uz * vy).IsZero - || !(uz * vx - ux * vz).IsZero - || !(ux * vy - uy * vx).IsZero) - return false; - } - return true; - } - /// Creates an exporter that writes diagnostics to (null for none) and, with , the Revit parameters as property sets. public IfcExporter(TextWriter? diagnosticOutput = null, bool includeRevitPropertySets = false) { @@ -9737,696 +9691,11 @@ void AddIncident((long X, long Y, long Z) vertex, return true; } - /// - /// Orients every face of one closed component consistently and then chooses the outward global - /// orientation from its signed volume. - /// internal static bool TryOrientExactFacetedShell(IReadOnlyList faces, IReadOnlyCollection faceIndices, out List orientedFaces, - bool triangulateNonPlanarFaces = true) - { - orientedFaces = []; - var indices = faceIndices.Distinct().Order().ToList(); - if (indices.Count < 4 || indices.Any(index => (uint)index >= faces.Count)) - return false; - var normalizedFaces = new Dictionary(); - foreach (int faceIndex in indices) - { - var normalized = CloneFace(faces[faceIndex], false); - if (normalized.OuterVertices is not { Count: >= 3 } outer - || outer.Any(point => point.Length < 3 - || !double.IsFinite(point[0]) || !double.IsFinite(point[1]) - || !double.IsFinite(point[2]))) - return false; - normalized.OuterVertices = CleanPrecisionLoop(outer); - if (normalized.OuterVertices.Count < 3 - || FaceCollapsesAtIfcPrecision(normalized)) - return false; - normalized.InnerVertices = normalized.InnerVertices? - .Where(ring => ring.Count >= 3 && ring.All(point => point.Length >= 3 - && double.IsFinite(point[0]) && double.IsFinite(point[1]) - && double.IsFinite(point[2]))) - .Select(CleanPrecisionLoop) - .Where(ring => ring.Count >= 3 - && !FaceCollapsesAtIfcPrecision(new GeoFace - { OuterVertices = ring })) - .ToList(); - if (!TryNormalizeInnerBounds(normalized)) - return false; - normalizedFaces[faceIndex] = normalized; - } - if (!TryGetFacetedAtomicEdgeUses(normalizedFaces, indices, out var edgeUses)) - return false; - - var constraints = indices.ToDictionary(index => index, - _ => new List<(int Other, bool OppositeFlip)>()); - foreach (var uses in edgeUses.Values) - { - bool oppositeFlip = uses[0].Direction == uses[1].Direction; - constraints[uses[0].FaceIndex].Add((uses[1].FaceIndex, oppositeFlip)); - constraints[uses[1].FaceIndex].Add((uses[0].FaceIndex, oppositeFlip)); - } - - var flips = new Dictionary(); - foreach (int seed in indices) - { - if (flips.ContainsKey(seed)) continue; - flips[seed] = false; - var queue = new Queue(); - queue.Enqueue(seed); - while (queue.Count > 0) - { - int current = queue.Dequeue(); - foreach (var (other, oppositeFlip) in constraints[current]) - { - bool required = flips[current] ^ oppositeFlip; - if (flips.TryGetValue(other, out bool existing)) - { - if (existing != required) - return false; - } - else - { - flips[other] = required; - queue.Enqueue(other); - } - } - } - } - - orientedFaces = indices.Select(index => - CloneFace(normalizedFaces[index], flips[index])).ToList(); - SplitFacetedLoopsAtSharedVertices(orientedFaces); - var compactIndices = Enumerable.Range(0, orientedFaces.Count).ToList(); - if (!IsExactFacetedShell(orientedFaces, compactIndices)) - { - orientedFaces = []; - return false; - } - - var points = orientedFaces.SelectMany(face => - (face.OuterVertices ?? []).Concat((face.InnerVertices ?? []).SelectMany(ring => ring))) - .ToList(); - double[] origin = - [ - points.Average(point => point[0]), - points.Average(point => point[1]), - points.Average(point => point[2]), - ]; - double signedVolume = orientedFaces.Sum(face => - SignedFaceVolume(face.OuterVertices!, origin) - + (face.InnerVertices?.Sum(ring => SignedFaceVolume(ring, origin)) ?? 0)); - if (!double.IsFinite(signedVolume) || signedVolume == 0) - { - orientedFaces = []; - return false; - } - if (signedVolume < 0) - orientedFaces = orientedFaces.Select(face => CloneFace(face, true)).ToList(); - if (!triangulateNonPlanarFaces || s_keepNonPlanarPolygons) - return true; - var triangulatedFaces = TriangulateNonPlanarFacetedFaces(orientedFaces); - SplitFacetedLoopsAtSharedVertices(triangulatedFaces); - if (IsExactFacetedShell(triangulatedFaces, - Enumerable.Range(0, triangulatedFaces.Count).ToList())) - orientedFaces = triangulatedFaces; - return true; - - static double SignedFaceVolume(IReadOnlyList ring, double[] origin) - { - double volume = 0; - var first = ring[0]; - for (int index = 1; index + 1 < ring.Count; index++) - { - double ax = first[0] - origin[0], ay = first[1] - origin[1], az = first[2] - origin[2]; - double bx = ring[index][0] - origin[0], by = ring[index][1] - origin[1], bz = ring[index][2] - origin[2]; - double cx = ring[index + 1][0] - origin[0], cy = ring[index + 1][1] - origin[1], cz = ring[index + 1][2] - origin[2]; - volume += (ax * (by * cz - bz * cy) - ay * (bx * cz - bz * cx) - + az * (bx * cy - by * cx)) / 6; - } - return volume; - } - - static bool TryNormalizeInnerBounds(GeoFace face) - { - if (face.InnerVertices is not { Count: > 0 }) return true; - if (face.OuterVertices is not { Count: >= 3 } outer - || !TryNewellNormal(outer, out var outerNormal)) - return false; - foreach (var inner in face.InnerVertices) - { - if (inner.Count < 3 || !TryNewellNormal(inner, out var innerNormal)) - return false; - double dot = outerNormal.X * innerNormal.X - + outerNormal.Y * innerNormal.Y + outerNormal.Z * innerNormal.Z; - if (!double.IsFinite(dot) || dot == 0) return false; - bool isStrictlyContained = IsStrictlyContainedAtIfcPrecision( - inner, outer, outerNormal); - bool hasSameDirection = dot > 0; - if (isStrictlyContained == hasSameDirection) inner.Reverse(); - } - return true; - } - - static bool IsStrictlyContainedAtIfcPrecision(IReadOnlyList inner, - IReadOnlyList outer, (double X, double Y, double Z) outerNormal) - { - int droppedAxis = Math.Abs(outerNormal.X) >= Math.Abs(outerNormal.Y) - && Math.Abs(outerNormal.X) >= Math.Abs(outerNormal.Z) ? 0 - : Math.Abs(outerNormal.Y) >= Math.Abs(outerNormal.Z) ? 1 : 2; - static (long U, long V) Project(double[] point, int droppedAxis) - { - var key = IfcPrecisionKeyFeet(point); - return droppedAxis == 0 ? (key.Y, key.Z) - : droppedAxis == 1 ? (key.X, key.Z) : (key.X, key.Y); - } - static Int128 Orientation((long U, long V) first, (long U, long V) second, - (long U, long V) point) => - ((Int128)second.U - first.U) * ((Int128)point.V - first.V) - - ((Int128)second.V - first.V) * ((Int128)point.U - first.U); - static bool OnSegment((long U, long V) point, (long U, long V) first, - (long U, long V) second) => Orientation(first, second, point) == 0 - && point.U >= Math.Min(first.U, second.U) - && point.U <= Math.Max(first.U, second.U) - && point.V >= Math.Min(first.V, second.V) - && point.V <= Math.Max(first.V, second.V); - static bool StrictlyInside((long U, long V) point, - IReadOnlyList<(long U, long V)> polygon) - { - int winding = 0; - for (int index = 0; index < polygon.Count; index++) - { - var first = polygon[index]; - var second = polygon[(index + 1) % polygon.Count]; - Int128 orientation = Orientation(first, second, point); - if (orientation == 0 && OnSegment(point, first, second)) return false; - if (first.V <= point.V && point.V < second.V && orientation > 0) winding++; - else if (second.V <= point.V && point.V < first.V && orientation < 0) winding--; - } - return winding != 0; - } - static bool Intersects((long U, long V) firstA, (long U, long V) secondA, - (long U, long V) firstB, (long U, long V) secondB) - { - Int128 ab1 = Orientation(firstA, secondA, firstB); - Int128 ab2 = Orientation(firstA, secondA, secondB); - Int128 ba1 = Orientation(firstB, secondB, firstA); - Int128 ba2 = Orientation(firstB, secondB, secondA); - if (ab1 == 0 && OnSegment(firstB, firstA, secondA)) return true; - if (ab2 == 0 && OnSegment(secondB, firstA, secondA)) return true; - if (ba1 == 0 && OnSegment(firstA, firstB, secondB)) return true; - if (ba2 == 0 && OnSegment(secondA, firstB, secondB)) return true; - return (ab1 < 0) != (ab2 < 0) && (ba1 < 0) != (ba2 < 0); - } - - var outer2d = outer.Select(point => Project(point, droppedAxis)).ToList(); - var inner2d = inner.Select(point => Project(point, droppedAxis)).ToList(); - if (outer2d.Distinct().Count() < 3 || inner2d.Distinct().Count() < 3 - || inner2d.Any(point => !StrictlyInside(point, outer2d))) - return false; - for (int innerIndex = 0; innerIndex < inner2d.Count; innerIndex++) - for (int outerIndex = 0; outerIndex < outer2d.Count; outerIndex++) - if (Intersects(inner2d[innerIndex], inner2d[(innerIndex + 1) % inner2d.Count], - outer2d[outerIndex], outer2d[(outerIndex + 1) % outer2d.Count])) - return false; - return true; - } - - static bool TryNewellNormal(IReadOnlyList ring, - out (double X, double Y, double Z) normal) - { - double x = 0, y = 0, z = 0; - for (int index = 0; index < ring.Count; index++) - { - var current = ring[index]; - var next = ring[(index + 1) % ring.Count]; - if (current.Length < 3 || next.Length < 3 - || !double.IsFinite(current[0]) || !double.IsFinite(current[1]) - || !double.IsFinite(current[2]) || !double.IsFinite(next[0]) - || !double.IsFinite(next[1]) || !double.IsFinite(next[2])) - { - normal = default; - return false; - } - x += (current[1] - next[1]) * (current[2] + next[2]); - y += (current[2] - next[2]) * (current[0] + next[0]); - z += (current[0] - next[0]) * (current[1] + next[1]); - } - normal = (x, y, z); - return double.IsFinite(x) && double.IsFinite(y) && double.IsFinite(z) - && (x != 0 || y != 0 || z != 0); - } - - static List CleanPrecisionLoop(IEnumerable source) - { - var clean = new List(); - foreach (var point in source) - if (clean.Count == 0 - || IfcPrecisionKeyFeet(clean[^1]) != IfcPrecisionKeyFeet(point)) - clean.Add((double[])point.Clone()); - if (clean.Count > 1 - && IfcPrecisionKeyFeet(clean[0]) == IfcPrecisionKeyFeet(clean[^1])) - clean.RemoveAt(clean.Count - 1); - return clean; - } - - static GeoFace CloneFace(GeoFace source, bool reverse) - { - List CopyRing(IEnumerable ring) - { - var copy = ring.Select(point => (double[])point.Clone()).ToList(); - if (reverse) copy.Reverse(); - return copy; - } - return new GeoFace - { - Origin = (double[])source.Origin.Clone(), - XVector = (double[])source.XVector.Clone(), - YVector = (double[])source.YVector.Clone(), - Normal = reverse ? source.Normal.Select(value => -value).ToArray() - : (double[])source.Normal.Clone(), - Envelope = source.Envelope is null ? null : (double[])source.Envelope.Clone(), - Area = source.Area, - InnerLoops = source.InnerLoops?.Select(loop => (double[])loop.Clone()).ToList(), - OuterVertices = source.OuterVertices is null ? null : CopyRing(source.OuterVertices), - InnerVertices = source.InnerVertices?.Select(CopyRing).ToList(), - AlternativeOuterVertices = source.AlternativeOuterVertices is null ? null - : source.AlternativeOuterVertices.Select(point => (double[])point.Clone()).ToList(), - EdgeIndices = source.EdgeIndices?.ToList(), - }; - } - } - - /// - /// Converts precision-nonplanar polygon faces to triangles using exact projected ear clipping. - /// - private static List TriangulateNonPlanarFacetedFaces( - IReadOnlyList faces) - { - - static GeoFace Triangle(GeoFace source, params double[][] vertices) => new() - { - Origin = (double[])source.Origin.Clone(), - XVector = (double[])source.XVector.Clone(), - YVector = (double[])source.YVector.Clone(), - Normal = (double[])source.Normal.Clone(), - Envelope = source.Envelope is null ? null : (double[])source.Envelope.Clone(), - Area = source.Area, - InnerLoops = source.InnerLoops?.Select(loop => (double[])loop.Clone()).ToList(), - OuterVertices = vertices.Select(point => (double[])point.Clone()).ToList(), - EdgeIndices = source.EdgeIndices?.ToList(), - }; - static bool TryProjectedShape(IReadOnlyList ring, - out bool planar, out bool convex) - { - planar = false; - convex = false; - var points = ring.Select(IfcPrecisionKeyFeet).ToList(); - if (points.Count < 4 || points.Distinct().Count() != points.Count) return false; - System.Numerics.BigInteger nx = 0, ny = 0, nz = 0; - for (int index = 0; index < points.Count; index++) - { - var current = points[index]; - var next = points[(index + 1) % points.Count]; - nx += ((System.Numerics.BigInteger)current.Y - next.Y) * (current.Z + next.Z); - ny += ((System.Numerics.BigInteger)current.Z - next.Z) * (current.X + next.X); - nz += ((System.Numerics.BigInteger)current.X - next.X) * (current.Y + next.Y); - } - if (nx.IsZero && ny.IsZero && nz.IsZero) return false; - var absX = System.Numerics.BigInteger.Abs(nx); - var absY = System.Numerics.BigInteger.Abs(ny); - var absZ = System.Numerics.BigInteger.Abs(nz); - int droppedAxis = absX >= absY && absX >= absZ ? 0 : absY >= absZ ? 1 : 2; - static (long U, long V) Project((long X, long Y, long Z) point, int axis) => - axis == 0 ? (point.Y, point.Z) - : axis == 1 ? (point.X, point.Z) : (point.X, point.Y); - int sign = 0; - for (int index = 0; index < points.Count; index++) - { - var first = Project(points[index], droppedAxis); - var second = Project(points[(index + 1) % points.Count], droppedAxis); - var third = Project(points[(index + 2) % points.Count], droppedAxis); - var turn = ((System.Numerics.BigInteger)second.U - first.U) - * (third.V - second.V) - - ((System.Numerics.BigInteger)second.V - first.V) - * (third.U - second.U); - if (turn.IsZero) continue; - int currentSign = turn.Sign; - if (sign != 0 && currentSign != sign) return true; - sign = currentSign; - } - convex = sign != 0; - - var origin = points[0]; - (System.Numerics.BigInteger X, System.Numerics.BigInteger Y, - System.Numerics.BigInteger Z)? normal = null; - for (int index = 1; index + 1 < points.Count && normal == null; index++) - { - var first = points[index]; - var second = points[index + 1]; - var ux = (System.Numerics.BigInteger)first.X - origin.X; - var uy = (System.Numerics.BigInteger)first.Y - origin.Y; - var uz = (System.Numerics.BigInteger)first.Z - origin.Z; - var vx = (System.Numerics.BigInteger)second.X - origin.X; - var vy = (System.Numerics.BigInteger)second.Y - origin.Y; - var vz = (System.Numerics.BigInteger)second.Z - origin.Z; - var cross = (X: uy * vz - uz * vy, Y: uz * vx - ux * vz, - Z: ux * vy - uy * vx); - if (!cross.X.IsZero || !cross.Y.IsZero || !cross.Z.IsZero) - normal = cross; - } - if (normal == null) return false; - planar = points.All(point => - normal.Value.X * ((System.Numerics.BigInteger)point.X - origin.X) - + normal.Value.Y * ((System.Numerics.BigInteger)point.Y - origin.Y) - + normal.Value.Z * ((System.Numerics.BigInteger)point.Z - origin.Z) == 0); - return true; - } - - static List? EarClip(GeoFace face, IReadOnlyList ring) - { - var points = ring.Select(IfcPrecisionKeyFeet).ToList(); - System.Numerics.BigInteger nx = 0, ny = 0, nz = 0; - for (int index = 0; index < points.Count; index++) - { - var current = points[index]; - var next = points[(index + 1) % points.Count]; - nx += ((System.Numerics.BigInteger)current.Y - next.Y) * (current.Z + next.Z); - ny += ((System.Numerics.BigInteger)current.Z - next.Z) * (current.X + next.X); - nz += ((System.Numerics.BigInteger)current.X - next.X) * (current.Y + next.Y); - } - var absX = System.Numerics.BigInteger.Abs(nx); - var absY = System.Numerics.BigInteger.Abs(ny); - var absZ = System.Numerics.BigInteger.Abs(nz); - if (absX.IsZero && absY.IsZero && absZ.IsZero) return null; - int droppedAxis = absX >= absY && absX >= absZ ? 0 : absY >= absZ ? 1 : 2; - static (long U, long V) Project((long X, long Y, long Z) point, int axis) => - axis == 0 ? (point.Y, point.Z) - : axis == 1 ? (point.X, point.Z) : (point.X, point.Y); - var projected = points.Select(point => Project(point, droppedAxis)).ToList(); - static System.Numerics.BigInteger Turn((long U, long V) first, - (long U, long V) second, (long U, long V) third) => - ((System.Numerics.BigInteger)second.U - first.U) * (third.V - first.V) - - ((System.Numerics.BigInteger)second.V - first.V) * (third.U - first.U); - System.Numerics.BigInteger twiceArea = 0; - for (int index = 0; index < projected.Count; index++) - { - var current = projected[index]; - var next = projected[(index + 1) % projected.Count]; - twiceArea += (System.Numerics.BigInteger)current.U * next.V - - (System.Numerics.BigInteger)next.U * current.V; - } - if (twiceArea.IsZero) return null; - int orientation = twiceArea.Sign; - var remaining = Enumerable.Range(0, ring.Count).ToList(); - var result = new List(); - int guard = ring.Count * ring.Count; - while (remaining.Count > 3 && guard-- > 0) - { - bool removed = false; - for (int offset = 0; offset < remaining.Count; offset++) - { - int previous = remaining[(offset - 1 + remaining.Count) % remaining.Count]; - int current = remaining[offset]; - int next = remaining[(offset + 1) % remaining.Count]; - var turn = Turn(projected[previous], projected[current], projected[next]); - if (turn.Sign != orientation) continue; - bool contains = remaining.Any(candidate => candidate != previous - && candidate != current && candidate != next - && new[] - { - Turn(projected[previous], projected[current], projected[candidate]), - Turn(projected[current], projected[next], projected[candidate]), - Turn(projected[next], projected[previous], projected[candidate]), - }.All(value => value.IsZero || value.Sign == orientation)); - if (contains) continue; - var triangle = Triangle(face, - ring[previous], ring[current], ring[next]); - if (FaceCollapsesAtIfcPrecision(triangle)) continue; - result.Add(triangle); - remaining.RemoveAt(offset); - removed = true; - break; - } - if (!removed) return null; - } - if (remaining.Count != 3) return null; - var finalTriangle = Triangle(face, - ring[remaining[0]], ring[remaining[1]], ring[remaining[2]]); - if (FaceCollapsesAtIfcPrecision(finalTriangle)) return null; - result.Add(finalTriangle); - return result; - } - - var result = new List(); - foreach (var face in faces) - { - if (face.OuterVertices is not { Count: > 3 } ring - || face.InnerVertices is { Count: > 0 } - || !TryProjectedShape(ring, out bool planar, out _) - || planar) - { - result.Add(face); - continue; - } - result.AddRange(EarClip(face, ring) ?? [face]); - } - return result; - } - - /// - /// Materializes the same atomic edge partition used by shell validation in the actual polygon - /// loops written to IFC. - /// - private static void SplitFacetedLoopsAtSharedVertices(IReadOnlyList faces) - { - static long Axis((long X, long Y, long Z) point, int axis) => - axis == 0 ? point.X : axis == 1 ? point.Y : point.Z; - static int LowerBound(List<(long X, long Y, long Z)> points, int axis, long value) - { - int low = 0, high = points.Count; - while (low < high) - { - int middle = low + (high - low) / 2; - if (Axis(points[middle], axis) < value) low = middle + 1; - else high = middle; - } - return low; - } - static bool OnSegment((long X, long Y, long Z) point, - (long X, long Y, long Z) first, (long X, long Y, long Z) second) - { - if (point.X < Math.Min(first.X, second.X) || point.X > Math.Max(first.X, second.X) - || point.Y < Math.Min(first.Y, second.Y) || point.Y > Math.Max(first.Y, second.Y) - || point.Z < Math.Min(first.Z, second.Z) || point.Z > Math.Max(first.Z, second.Z)) - return false; - Int128 dx = (Int128)second.X - first.X; - Int128 dy = (Int128)second.Y - first.Y; - Int128 dz = (Int128)second.Z - first.Z; - Int128 px = (Int128)point.X - first.X; - Int128 py = (Int128)point.Y - first.Y; - Int128 pz = (Int128)point.Z - first.Z; - return dy * pz - dz * py == 0 - && dz * px - dx * pz == 0 - && dx * py - dy * px == 0; - } - - var representative = new Dictionary<(long X, long Y, long Z), double[]>(); - foreach (var face in faces) - foreach (var ring in (face.OuterVertices is { Count: > 0 } outer - ? new[] { outer } - : Enumerable.Empty>()) - .Concat(face.InnerVertices ?? [])) - foreach (var point in ring) - representative.TryAdd(IfcPrecisionKeyFeet(point), point); - var vertices = representative.Keys.ToList(); - var verticesByAxis = Enumerable.Range(0, 3) - .Select(axis => vertices.OrderBy(point => Axis(point, axis)) - .ThenBy(point => point.X).ThenBy(point => point.Y).ThenBy(point => point.Z) - .ToList()).ToArray(); - - List Split(IReadOnlyList ring) - { - var result = new List(); - for (int edgeIndex = 0; edgeIndex < ring.Count; edgeIndex++) - { - var sourceFirst = ring[edgeIndex]; - var sourceSecond = ring[(edgeIndex + 1) % ring.Count]; - var first = IfcPrecisionKeyFeet(sourceFirst); - var second = IfcPrecisionKeyFeet(sourceSecond); - result.Add(sourceFirst); - if (first == second) continue; - Int128 dx = (Int128)second.X - first.X; - Int128 dy = (Int128)second.Y - first.Y; - Int128 dz = (Int128)second.Z - first.Z; - Int128 absX = Int128.Abs(dx), absY = Int128.Abs(dy), absZ = Int128.Abs(dz); - int axis = absX >= absY && absX >= absZ ? 0 : absY >= absZ ? 1 : 2; - long low = Math.Min(Axis(first, axis), Axis(second, axis)); - long high = Math.Max(Axis(first, axis), Axis(second, axis)); - var split = new List<(long X, long Y, long Z)>(); - var sorted = verticesByAxis[axis]; - for (int index = LowerBound(sorted, axis, low); - index < sorted.Count && Axis(sorted[index], axis) <= high; index++) - if (sorted[index] != first && sorted[index] != second - && OnSegment(sorted[index], first, second)) - split.Add(sorted[index]); - split.Sort((left, right) => Axis(left, axis).CompareTo(Axis(right, axis))); - if (Axis(first, axis) > Axis(second, axis)) split.Reverse(); - result.AddRange(split.Select(point => representative[point])); - } - var clean = new List(); - foreach (var point in result) - if (clean.Count == 0 - || IfcPrecisionKeyFeet(clean[^1]) != IfcPrecisionKeyFeet(point)) - clean.Add(point); - if (clean.Count > 1 - && IfcPrecisionKeyFeet(clean[0]) == IfcPrecisionKeyFeet(clean[^1])) - clean.RemoveAt(clean.Count - 1); - return clean; - } - - foreach (var face in faces) - { - if (face.OuterVertices is { Count: >= 3 } outer) - face.OuterVertices = Split(outer); - if (face.InnerVertices is { Count: > 0 } inner) - face.InnerVertices = inner.Select(Split).ToList(); - } - } - - /// Builds exact shared-edge uses on the serialized IFC coordinate lattice. - private static bool TryGetFacetedAtomicEdgeUses(IReadOnlyDictionary faces, - IReadOnlyCollection faceIndices, - out Dictionary<((long X, long Y, long Z) A, (long X, long Y, long Z) B), - List<(int FaceIndex, int Direction)>> edgeUses) - { - static ((long X, long Y, long Z) A, (long X, long Y, long Z) B) EdgeKey( - (long X, long Y, long Z) first, (long X, long Y, long Z) second) - => first.CompareTo(second) <= 0 ? (first, second) : (second, first); - static long Axis((long X, long Y, long Z) point, int axis) => - axis == 0 ? point.X : axis == 1 ? point.Y : point.Z; - static int LowerBound(List<(long X, long Y, long Z)> points, int axis, long value) - { - int low = 0, high = points.Count; - while (low < high) - { - int middle = low + (high - low) / 2; - if (Axis(points[middle], axis) < value) low = middle + 1; - else high = middle; - } - return low; - } - static bool OnSegment((long X, long Y, long Z) point, - (long X, long Y, long Z) first, (long X, long Y, long Z) second) - { - if (point.X < Math.Min(first.X, second.X) || point.X > Math.Max(first.X, second.X) - || point.Y < Math.Min(first.Y, second.Y) || point.Y > Math.Max(first.Y, second.Y) - || point.Z < Math.Min(first.Z, second.Z) || point.Z > Math.Max(first.Z, second.Z)) - return false; - Int128 dx = (Int128)second.X - first.X; - Int128 dy = (Int128)second.Y - first.Y; - Int128 dz = (Int128)second.Z - first.Z; - Int128 px = (Int128)point.X - first.X; - Int128 py = (Int128)point.Y - first.Y; - Int128 pz = (Int128)point.Z - first.Z; - return dy * pz - dz * py == 0 - && dz * px - dx * pz == 0 - && dx * py - dy * px == 0; - } - - var usesByEdge = new Dictionary< - ((long X, long Y, long Z) A, (long X, long Y, long Z) B), - List<(int FaceIndex, int Direction)>>(); - edgeUses = usesByEdge; - var segments = new List<(int FaceIndex, (long X, long Y, long Z) First, - (long X, long Y, long Z) Second)>(); - foreach (int faceIndex in faceIndices) - { - if (!faces.TryGetValue(faceIndex, out var face) - || face.OuterVertices is not { Count: >= 3 } outer) - return false; - IEnumerable> rings = - new[] { (IReadOnlyList)outer } - .Concat(face.InnerVertices ?? Enumerable.Empty>()); - foreach (var ring in rings) - { - if (ring.Count < 3 || ring.Any(point => point.Length < 3 - || !double.IsFinite(point[0]) || !double.IsFinite(point[1]) - || !double.IsFinite(point[2]))) - return false; - for (int index = 0; index < ring.Count; index++) - { - var first = IfcPrecisionKeyFeet(ring[index]); - var second = IfcPrecisionKeyFeet(ring[(index + 1) % ring.Count]); - if (first == second) return false; - segments.Add((faceIndex, first, second)); - } - } - } - if (segments.Count == 0) return false; - - void AddUse(int faceIndex, (long X, long Y, long Z) first, - (long X, long Y, long Z) second) - { - var edge = EdgeKey(first, second); - if (!usesByEdge.TryGetValue(edge, out var uses)) usesByEdge[edge] = uses = []; - uses.Add((faceIndex, first.CompareTo(second) <= 0 ? 1 : -1)); - } - bool HasClosedMultiplicity() => usesByEdge.Count > 0 - && usesByEdge.Values.All(uses => uses.Count == 2 - && uses[0].FaceIndex != uses[1].FaceIndex); - - foreach (var segment in segments) - AddUse(segment.FaceIndex, segment.First, segment.Second); - if (HasClosedMultiplicity()) return true; - - usesByEdge.Clear(); - var vertices = segments.SelectMany(segment => new[] { segment.First, segment.Second }) - .Distinct().ToList(); - var verticesByAxis = Enumerable.Range(0, 3) - .Select(axis => vertices.OrderBy(point => Axis(point, axis)) - .ThenBy(point => point.X).ThenBy(point => point.Y).ThenBy(point => point.Z) - .ToList()) - .ToArray(); - foreach (var segment in segments) - { - Int128 dx = (Int128)segment.Second.X - segment.First.X; - Int128 dy = (Int128)segment.Second.Y - segment.First.Y; - Int128 dz = (Int128)segment.Second.Z - segment.First.Z; - Int128 absX = Int128.Abs(dx), absY = Int128.Abs(dy), absZ = Int128.Abs(dz); - int axis = absX >= absY && absX >= absZ ? 0 : absY >= absZ ? 1 : 2; - long low = Math.Min(Axis(segment.First, axis), Axis(segment.Second, axis)); - long high = Math.Max(Axis(segment.First, axis), Axis(segment.Second, axis)); - var sorted = verticesByAxis[axis]; - var split = new List<(long X, long Y, long Z)>(); - for (int index = LowerBound(sorted, axis, low); - index < sorted.Count && Axis(sorted[index], axis) <= high; index++) - if (OnSegment(sorted[index], segment.First, segment.Second)) - split.Add(sorted[index]); - if (Axis(segment.First, axis) > Axis(segment.Second, axis)) split.Reverse(); - if (split.Count < 2 || split[0] != segment.First || split[^1] != segment.Second) - return false; - for (int index = 0; index + 1 < split.Count; index++) - AddUse(segment.FaceIndex, split[index], split[index + 1]); - } - return HasClosedMultiplicity(); - } - - /// - /// Checks whether the emitted polygon loops satisfy IFC closed-shell topology using the same - /// declared-precision identity as the IFC point cache. - /// - internal static bool IsExactFacetedShell( - IReadOnlyList faces, IReadOnlyCollection faceIndices) - { - var faceMap = faceIndices.Distinct().ToDictionary(index => index, - index => (uint)index < faces.Count ? faces[index] : null); - if (faceMap.Values.Any(face => face == null)) return false; - return TryGetFacetedAtomicEdgeUses( - faceMap.ToDictionary(pair => pair.Key, pair => pair.Value!), - faceIndices, out var edgeUses) - && edgeUses.Values.All(uses => uses[0].Direction + uses[1].Direction == 0); - } + bool triangulateNonPlanarFaces = true) => + FacetedShell.TryOrientExactFacetedShell(faces, faceIndices, out orientedFaces, + triangulateNonPlanarFaces && !s_keepNonPlanarPolygons); /// Recover a closed gable roof from a surviving six-point end face. private bool TryCreatePitchedRoofShape(StepWriter w, Element elem, double[] bbox, diff --git a/src/RvtIO/Parsing/ElementBuilder.CoarseSurface.cs b/src/RvtIO/Parsing/ElementBuilder.CoarseSurface.cs index ba904689..770b67b6 100644 --- a/src/RvtIO/Parsing/ElementBuilder.CoarseSurface.cs +++ b/src/RvtIO/Parsing/ElementBuilder.CoarseSurface.cs @@ -1,4 +1,4 @@ -using RvtIO.Ifc; +using RvtIO.Geometry; using RvtIO.Internal; using RvtIO.Model; @@ -41,7 +41,7 @@ internal static void ApplyCoarseDoorWindowSurfaces(RevitFileInfo info, ParsingSt ExpandInstanceGeometry(coarse, own, element.TypeId, state); } ExpandTransformOnlyInstanceGeometry(coarse, id, element.TypeId, state); - element.CoarseSurfaceArea = IfcExporter.SurfaceAreaCurrent(coarse.Geometry); + element.CoarseSurfaceArea = BrepMeasures.SurfaceAreaCurrent(coarse.Geometry); } finally { @@ -75,7 +75,7 @@ private static void ApplyMediumLevelVolume(Element element, ParsingState state) ExpandInstanceGeometry(alternative, block, element.TypeId, state); } ExpandTransformOnlyInstanceGeometry(alternative, id, element.TypeId, state); - element.MediumSolidTotals = IfcExporter.NodeSolidTotalsCurrent(alternative.Geometry); + element.MediumSolidTotals = BrepMeasures.NodeSolidTotalsCurrent(alternative.Geometry); } finally { state.DetailView = 0; } } diff --git a/src/RvtIO/Parsing/ElementBuilder.OwnWallPlanarBody.cs b/src/RvtIO/Parsing/ElementBuilder.OwnWallPlanarBody.cs index eb43060c..33ebd455 100644 --- a/src/RvtIO/Parsing/ElementBuilder.OwnWallPlanarBody.cs +++ b/src/RvtIO/Parsing/ElementBuilder.OwnWallPlanarBody.cs @@ -1,3 +1,4 @@ +using RvtIO.Geometry; using RvtIO.Internal; using RvtIO.Model; @@ -26,7 +27,7 @@ internal static bool ApplyOwnWallPlanarBody(Element element, ParsingState state) || geometry.BrepSolids is not { Count: > 0 } solids || solids.Sum(solid => solid.FaceIndices.Count) != geometry.Faces.Count || solids.SelectMany(solid => solid.FaceIndices).Distinct().Count() != geometry.Faces.Count - || solids.Any(solid => !solid.IsClosed || !Ifc.IfcExporter.TryOrientExactFacetedShell( + || solids.Any(solid => !solid.IsClosed || !FacetedShell.TryOrientExactFacetedShell( geometry.Faces, solid.FaceIndices, out _, triangulateNonPlanarFaces: false))) return false; // Body selection does not reinterpret legacy graphics-style/header metadata. geometry.GStyleElemId = element.Geometry?.GStyleElemId ?? 0; diff --git a/src/RvtIO/RvtFileReader.OwnWallPlanarBodies.cs b/src/RvtIO/RvtFileReader.OwnWallPlanarBodies.cs index d859ad5d..87507d97 100644 --- a/src/RvtIO/RvtFileReader.OwnWallPlanarBodies.cs +++ b/src/RvtIO/RvtFileReader.OwnWallPlanarBodies.cs @@ -1,6 +1,6 @@ +using RvtIO.Geometry; using RvtIO.Internal; using RvtIO.Parsing; -using RvtIO.Ifc; namespace RvtIO; @@ -85,7 +85,7 @@ private static void ReadOwnWallPlanarBodies(ParsingState state) || WallExtrusion.IsStandardCaseBody(nativeGeometry, helper) != false || WallExtrusion.TryFindVerticalExtrusion(nativeGeometry.Faces, out string reason, true, nativeGeometry.Faces.Select(face => face.MeshEdgeBounds!).ToList()) || reason != "bbox" - || !IfcExporter.TryOrientExactFacetedShell(nativeGeometry.Faces, solid.FaceIndices, out _)) return null; + || !FacetedShell.TryOrientExactFacetedShell(nativeGeometry.Faces, solid.FaceIndices, out _, triangulateNonPlanarFaces: false)) return null; return body; } diff --git a/tests/RvtIO.Tests/AnalyticSolidMeasureTests.cs b/tests/RvtIO.Tests/AnalyticSolidMeasureTests.cs index cf322f78..0a9a72ac 100644 --- a/tests/RvtIO.Tests/AnalyticSolidMeasureTests.cs +++ b/tests/RvtIO.Tests/AnalyticSolidMeasureTests.cs @@ -1,3 +1,4 @@ +using RvtIO.Geometry; using RvtIO.Geometry.Meshing; using RvtIO.Ifc; using RvtIO.Model; @@ -90,13 +91,13 @@ public void ShellMeasures_RequireAClosedShellAndEverySourceFace(bool complete, b { SourceMeasures = (12, 5) }], }; - var shell = Assert.Single(IfcExporter.ShellsOfCurrent(geometry)); + var shell = Assert.Single(BrepMeasures.ShellsOfCurrent(geometry)); Assert.Equal(expected, shell.SourceMeasured); Assert.Equal(expected ? 12 : 4, shell.Area, 12); if (expected) { Assert.Equal(5, shell.Volume, 12); - Assert.Equal(12, IfcExporter.SurfaceAreaCurrent(geometry), 12); + Assert.Equal(12, BrepMeasures.SurfaceAreaCurrent(geometry), 12); } } diff --git a/tests/RvtIO.Tests/ArcProfileTests.cs b/tests/RvtIO.Tests/ArcProfileTests.cs index 7bf5dc6d..b0c9ab7c 100644 --- a/tests/RvtIO.Tests/ArcProfileTests.cs +++ b/tests/RvtIO.Tests/ArcProfileTests.cs @@ -1,3 +1,4 @@ +using RvtIO.Geometry; using RvtIO.Ifc; using RvtIO.Internal; using RvtIO.Parsing; @@ -145,7 +146,7 @@ public void TheEndFaceOfAnArcWallOfSampleGivesTheProfileWrites() Assert.True(extrusion != null, reason + string.Join(" | ", solidFaces.Where(f => !f.CurvedSurface).Select(f => { double a = WallExtrusion.ExactFaceArea(f, out bool e); return $"n.z={f.Normal[2]:F1} exact={a:F6} ({e}) polygon={WallExtrusion.LoopArea(f.OuterVertices):F6} arcs={f.MeshArcs?.Count}"; }))); Assert.Equal(5, extrusion!.Arcs!.Count); var ring = extrusion.Loops[0]; - Assert.Equal(5, IfcExporter.FindArcRunsCurrent(ring, extrusion.Arcs).Count); + Assert.Equal(5, ArcRuns.FindArcRunsCurrent(ring, extrusion.Arcs).Count); double area = 0; for (int i = 0; i < ring.Count; i++) area += ring[i][0] * ring[(i + 1) % ring.Count][1] - ring[(i + 1) % ring.Count][0] * ring[i][1]; diff --git a/tests/RvtIO.Tests/AxisExtrusionTests.cs b/tests/RvtIO.Tests/AxisExtrusionTests.cs index f073faed..948f0ffb 100644 --- a/tests/RvtIO.Tests/AxisExtrusionTests.cs +++ b/tests/RvtIO.Tests/AxisExtrusionTests.cs @@ -1,3 +1,4 @@ +using RvtIO.Geometry; using System.Globalization; using RvtIO.Ifc; using RvtIO.Model; diff --git a/tests/RvtIO.Tests/CompactIdentityTests.cs b/tests/RvtIO.Tests/CompactIdentityTests.cs index 341908fb..a33ae043 100644 --- a/tests/RvtIO.Tests/CompactIdentityTests.cs +++ b/tests/RvtIO.Tests/CompactIdentityTests.cs @@ -1,3 +1,4 @@ +using RvtIO.Export; using RvtIO.Compact; using RvtIO.Model; using RvtIO.Parsing; diff --git a/tests/RvtIO.Tests/CompactOwnValueRulesTests.cs b/tests/RvtIO.Tests/CompactOwnValueRulesTests.cs index 310a2fd3..d924da43 100644 --- a/tests/RvtIO.Tests/CompactOwnValueRulesTests.cs +++ b/tests/RvtIO.Tests/CompactOwnValueRulesTests.cs @@ -1,3 +1,4 @@ +using RvtIO.Export; using RvtIO.Compact; using RvtIO.Internal; using RvtIO.Model; diff --git a/tests/RvtIO.Tests/CoveringFirstPieceTests.cs b/tests/RvtIO.Tests/CoveringFirstPieceTests.cs index 43934230..5a1de09c 100644 --- a/tests/RvtIO.Tests/CoveringFirstPieceTests.cs +++ b/tests/RvtIO.Tests/CoveringFirstPieceTests.cs @@ -1,3 +1,4 @@ +using RvtIO.Geometry; using RvtIO.Ifc; using RvtIO.Model; using Xunit; @@ -37,7 +38,7 @@ private static GeometryData TwoPieceSlab() => Slabs( [Fact] public void FirstPiece_IsOnePieceNotTheWholeSurface() { - var shells = IfcExporter.ShellsOfCurrent(TwoPieceSlab()); + var shells = BrepMeasures.ShellsOfCurrent(TwoPieceSlab()); double? piece = IfcExporter.FirstTopPieceAreaCurrent(shells); double whole = IfcExporter.TopSurfaceAreaCurrent(shells); @@ -56,7 +57,7 @@ public void SharedSerializedFace_StillCountsConnectedComponents() Square(20, 0, 15, 10, 1), Square(0, 0, 10, 0, 2), Square(20, 0, 15, 0, 2)); - var shells = IfcExporter.ShellsOfCurrent(geometry); + var shells = BrepMeasures.ShellsOfCurrent(geometry); double? piece = IfcExporter.FirstTopPieceAreaCurrent(shells); @@ -73,7 +74,7 @@ public void BottomOrder_DoesNotDecideTheMatch() Square(20, 0, 15, 10, 2), Square(20, 0, 15, 0, 3), Square(0, 0, 10, 0, 4)); - var shells = IfcExporter.ShellsOfCurrent(geometry); + var shells = BrepMeasures.ShellsOfCurrent(geometry); double? piece = IfcExporter.FirstTopPieceAreaCurrent(shells); @@ -87,7 +88,7 @@ public void SinglePiece_ReturnsNullSoCallerKeepsTheWholeSurface() var geometry = Slabs( Square(0, 0, 10, 10, 1), Square(0, 0, 10, 0, 1)); - var shells = IfcExporter.ShellsOfCurrent(geometry); + var shells = BrepMeasures.ShellsOfCurrent(geometry); Assert.Null(IfcExporter.FirstTopPieceAreaCurrent(shells)); } @@ -99,7 +100,7 @@ public void MismatchedBottom_ReturnsNull() Square(0, 0, 10, 10, 1), Square(20, 0, 10, 10, 2), Square(0, 0, 5, 0, 3)); - var shells = IfcExporter.ShellsOfCurrent(geometry); + var shells = BrepMeasures.ShellsOfCurrent(geometry); Assert.Null(IfcExporter.FirstTopPieceAreaCurrent(shells)); } @@ -113,7 +114,7 @@ public void SteppedTop_ReturnsNull() Square(20, 0, 10, 12, 2), Square(0, 0, 10, 0, 3), Square(20, 0, 10, 2, 4)); - var shells = IfcExporter.ShellsOfCurrent(geometry); + var shells = BrepMeasures.ShellsOfCurrent(geometry); Assert.Null(IfcExporter.FirstTopPieceAreaCurrent(shells)); } @@ -179,7 +180,7 @@ public void SlopedSolid_KeepsTheWholeUpperSurface() new GeoBrepSolid { IsClosed = true, FaceIndices = Enumerable.Range(first.Faces.Count, second.Faces.Count).ToList() }, ], }; - var shells = IfcExporter.ShellsOfCurrent(geometry); + var shells = BrepMeasures.ShellsOfCurrent(geometry); Assert.Null(IfcExporter.FirstTopPieceAreaCurrent(shells)); Assert.Equal(111.803398875 + 251.557647469, IfcExporter.TopSurfaceAreaCurrent(shells), 6); @@ -231,7 +232,7 @@ public void Caller_SlopedFirstThenHorizontalPieces_WritesTheWholeUpperSurface() ], }; - Assert.Null(IfcExporter.FirstTopPieceAreaCurrent(IfcExporter.ShellsOfCurrent(geometry))); + Assert.Null(IfcExporter.FirstTopPieceAreaCurrent(BrepMeasures.ShellsOfCurrent(geometry))); var ceiling = new Element { Id = 5, CategoryId = -2000038, Geometry = geometry }; var quantities = QuantitiesOf(ceiling); diff --git a/tests/RvtIO.Tests/EdgeBoundsTests.cs b/tests/RvtIO.Tests/EdgeBoundsTests.cs index 51abb00b..d7708092 100644 --- a/tests/RvtIO.Tests/EdgeBoundsTests.cs +++ b/tests/RvtIO.Tests/EdgeBoundsTests.cs @@ -1,3 +1,4 @@ +using RvtIO.Geometry; using RvtIO.Parsing; using RvtIO.Ifc; using RvtIO.Internal; diff --git a/tests/RvtIO.Tests/FaceAreaTests.cs b/tests/RvtIO.Tests/FaceAreaTests.cs index 0d4ef18f..68d6b52d 100644 --- a/tests/RvtIO.Tests/FaceAreaTests.cs +++ b/tests/RvtIO.Tests/FaceAreaTests.cs @@ -1,3 +1,4 @@ +using RvtIO.Geometry; using RvtIO.Geometry.Meshing; using RvtIO.Ifc; using RvtIO.Internal; diff --git a/tests/RvtIO.Tests/IfcExporterBaseQuantitiesCurrentTailTests.cs b/tests/RvtIO.Tests/IfcExporterBaseQuantitiesCurrentTailTests.cs index 5608b2ce..afa6eeb9 100644 --- a/tests/RvtIO.Tests/IfcExporterBaseQuantitiesCurrentTailTests.cs +++ b/tests/RvtIO.Tests/IfcExporterBaseQuantitiesCurrentTailTests.cs @@ -1,3 +1,4 @@ +using RvtIO.Geometry; using RvtIO.Ifc; using RvtIO.Internal; using RvtIO.Model; @@ -74,7 +75,7 @@ public void VerticalFaceArea_RegionsOfOneSerializedFace_AreOneFace() Face(5, [0, 0, 0], [0, 0, 2], [0, 1, 2], [0, 1, 0]), Face(6, [10, 0, 0], [10, 1, 0], [10, 1, 2], [10, 0, 2])); - double area = IfcExporter.LargestVerticalFaceAreaCurrent(IfcExporter.ShellsOfCurrent(wall)); + double area = IfcExporter.LargestVerticalFaceAreaCurrent(BrepMeasures.ShellsOfCurrent(wall)); Assert.Equal(20, area, 9); } @@ -90,7 +91,7 @@ public void VerticalFaceArea_FacesOfDifferentSerializedFacesOrOfNoKnownOne_StayS Face(7, [0, 1, 0], [0, 1, 2], [4, 1, 2], [4, 1, 0]), Face(8, [4, 1, 0], [4, 1, 2], [10, 1, 2], [10, 1, 0])); - Assert.Equal(12, IfcExporter.LargestVerticalFaceAreaCurrent(IfcExporter.ShellsOfCurrent(wall)), 9); + Assert.Equal(12, IfcExporter.LargestVerticalFaceAreaCurrent(BrepMeasures.ShellsOfCurrent(wall)), 9); } diff --git a/tests/RvtIO.Tests/IfcExporterBaseQuantitiesCurrentTests.cs b/tests/RvtIO.Tests/IfcExporterBaseQuantitiesCurrentTests.cs index f565f008..b5450319 100644 --- a/tests/RvtIO.Tests/IfcExporterBaseQuantitiesCurrentTests.cs +++ b/tests/RvtIO.Tests/IfcExporterBaseQuantitiesCurrentTests.cs @@ -1,3 +1,4 @@ +using RvtIO.Geometry; using RvtIO.Geometry.Meshing; using RvtIO.Parsing; using System.Globalization; @@ -47,7 +48,7 @@ private static GeoFace Face(params double[][] ring) BrepSolids = [new GeoBrepSolid { IsClosed = true, FaceIndices = [0, 1, 2, 3, 4, 5] }], }; - private static IfcExporter.ShellInfo SoleShell(GeometryData geometry) => Assert.Single(IfcExporter.ShellsOfCurrent(geometry)); + private static BrepMeasures.ShellInfo SoleShell(GeometryData geometry) => Assert.Single(BrepMeasures.ShellsOfCurrent(geometry)); [Fact] @@ -91,7 +92,7 @@ public void Shells_FaceWithAHole_SubtractsTheHoleFromTheFaceAndTheSurface() // A square hole of 1 ft2 in the top face: the face keeps 15 ft2 of its 16. geometry.Faces[1].InnerVertices = [[[1, 1, 1], [2, 1, 1], [2, 2, 1], [1, 2, 1]]]; - Assert.Equal(15, IfcExporter.NetFaceArea(geometry.Faces[1])!.Value, 9); + Assert.Equal(15, BrepMeasures.NetFaceArea(geometry.Faces[1])!.Value, 9); Assert.Equal(16 + 15 + 16, SoleShell(geometry).Area, 9); } @@ -108,13 +109,13 @@ public void Shells_WithoutBrepSolids_AreOneOpenShell() } [Fact] - public void Shells_NoFaces_NoShells() => Assert.Empty(IfcExporter.ShellsOfCurrent(new GeometryData())); + public void Shells_NoFaces_NoShells() => Assert.Empty(BrepMeasures.ShellsOfCurrent(new GeometryData())); [Fact] public void Prism_Box_IsExtrudedAlongItsLongAxis() { - var prism = IfcExporter.FindPrismCurrent(SoleShell(Box(1, 2, 5))); + var prism = BrepMeasures.FindPrismCurrent(SoleShell(Box(1, 2, 5))); Assert.NotNull(prism); Assert.Equal(5, prism!.Value.Depth, 9); @@ -127,8 +128,8 @@ public void Prism_VerticalOnly_IgnoresALongerHorizontalAxis() { var shell = SoleShell(Box(5, 2, 1)); - var any = IfcExporter.FindPrismCurrent(shell); - var vertical = IfcExporter.FindPrismCurrent(shell, verticalOnly: true); + var any = BrepMeasures.FindPrismCurrent(shell); + var vertical = BrepMeasures.FindPrismCurrent(shell, verticalOnly: true); Assert.Equal(5, any!.Value.Depth, 9); Assert.False(any.Value.Vertical); @@ -155,7 +156,7 @@ public void Prism_ATetrahedron_IsNotAPrism() BrepSolids = [new GeoBrepSolid { IsClosed = true, FaceIndices = [0, 1, 2, 3] }], }; - Assert.Null(IfcExporter.FindPrismCurrent(SoleShell(geometry))); + Assert.Null(BrepMeasures.FindPrismCurrent(SoleShell(geometry))); } [Fact] @@ -174,7 +175,7 @@ public void Prism_ATriangularWedge_IsAPrismAlongItsEdge() BrepSolids = [new GeoBrepSolid { IsClosed = true, FaceIndices = [0, 1, 2, 3, 4] }], }; - var prism = IfcExporter.FindPrismCurrent(SoleShell(geometry)); + var prism = BrepMeasures.FindPrismCurrent(SoleShell(geometry)); Assert.Equal(2, prism!.Value.Depth, 9); Assert.Equal(1, prism.Value.ProfileArea, 9); @@ -186,7 +187,7 @@ public void Prism_ACurvedFace_IsNotAPrism() var geometry = Box(1, 2, 3); geometry.Faces[2] = new GeoFace { OuterVertices = geometry.Faces[2].OuterVertices, CurvedSurface = true }; - Assert.Null(IfcExporter.FindPrismCurrent(SoleShell(geometry))); + Assert.Null(BrepMeasures.FindPrismCurrent(SoleShell(geometry))); } @@ -2673,7 +2674,7 @@ public void NodeSolidTotals_SumTheMeasuresOfTheTakenNodesWhateverTheirNumbers(in var geometry = TakenAndUntakenBoxes(taken, untaken); geometry.NodeMeasures = [new RvtIO.Parsing.MeshNodeMeasure(taken, 40, 7)]; - var totals = IfcExporter.NodeSolidTotalsCurrent(geometry); + var totals = BrepMeasures.NodeSolidTotalsCurrent(geometry); Assert.Equal(7 * CubicFeet, totals!.Value.Volume, 12); Assert.Equal(40 * SquareFeet, totals.Value.Area, 12); @@ -2685,8 +2686,8 @@ public void NodeSolidTotals_AreUnknownWhileATakenNodeHasNoMeasure() var geometry = TakenAndUntakenBoxes(3, -4); geometry.NodeMeasures = [new RvtIO.Parsing.MeshNodeMeasure(9, 40, 7)]; - Assert.Null(IfcExporter.NodeSolidTotalsCurrent(geometry)); - Assert.Null(IfcExporter.NodeSolidTotalsCurrent(TakenAndUntakenBoxes(3, -4))); + Assert.Null(BrepMeasures.NodeSolidTotalsCurrent(geometry)); + Assert.Null(BrepMeasures.NodeSolidTotalsCurrent(TakenAndUntakenBoxes(3, -4))); } [Theory] @@ -2769,7 +2770,7 @@ private static GeometryData BoxesInNodes(int taken, int cutting) [InlineData(12, 5)] public void NodeSolidTotals_LeaveOutTheCuttingNodes(int taken, int cutting) { - var totals = IfcExporter.NodeSolidTotalsCurrent(BoxesInNodes(taken, cutting)); + var totals = BrepMeasures.NodeSolidTotalsCurrent(BoxesInNodes(taken, cutting)); Assert.Equal(7 * CubicFeet, totals!.Value.Volume, 12); Assert.Equal(40 * SquareFeet, totals.Value.Area, 12); @@ -2781,7 +2782,7 @@ public void NodeSolidTotals_AreUnknownWhenOnlyCuttingNodesAreMeasured() var geometry = TakenAndUntakenBoxes(3, 4); geometry.NodeMeasures = [new RvtIO.Parsing.MeshNodeMeasure(3, 100, -9), new RvtIO.Parsing.MeshNodeMeasure(4, 100, -9)]; - Assert.Null(IfcExporter.NodeSolidTotalsCurrent(geometry)); + Assert.Null(BrepMeasures.NodeSolidTotalsCurrent(geometry)); } [Fact] diff --git a/tests/RvtIO.Tests/IfcExporterInsetCapsTests.cs b/tests/RvtIO.Tests/IfcExporterInsetCapsTests.cs index 9dc1d165..bf9016a3 100644 --- a/tests/RvtIO.Tests/IfcExporterInsetCapsTests.cs +++ b/tests/RvtIO.Tests/IfcExporterInsetCapsTests.cs @@ -3,6 +3,7 @@ using System.Reflection; using System.Text.Json; using System.Text.RegularExpressions; +using RvtIO.Geometry; using RvtIO.Ifc; using RvtIO.Model; using Xunit; @@ -32,7 +33,7 @@ public void DualAlternativeInsetCaps_RecoversSourceRectangle() var f = Create(); Assert.True(f.Recover(out var gross)); Assert.Equal(6, gross.Faces.Count); - Assert.True(IfcExporter.IsExactFacetedShell(gross.Faces, gross.BrepSolids![0].FaceIndices)); + Assert.True(FacetedShell.IsExactFacetedShell(gross.Faces, gross.BrepSolids![0].FaceIndices)); Assert.True(IfcExporter.TryGetExactVerticalRectangularPrismSweptOpening(gross, out var box)); Assert.Equal(1690, Math.Max(box.WidthFt, box.DepthFt) * 304.8, 5); Assert.Equal(80, Math.Min(box.WidthFt, box.DepthFt) * 304.8, 5); diff --git a/tests/RvtIO.Tests/IfcExporterJoinNotchTests.cs b/tests/RvtIO.Tests/IfcExporterJoinNotchTests.cs index ae30bdc0..4d37fab8 100644 --- a/tests/RvtIO.Tests/IfcExporterJoinNotchTests.cs +++ b/tests/RvtIO.Tests/IfcExporterJoinNotchTests.cs @@ -3,6 +3,7 @@ using System.Reflection; using System.Text.Json; using System.Text.RegularExpressions; +using RvtIO.Geometry; using RvtIO.Ifc; using RvtIO.Model; using Xunit; @@ -32,7 +33,7 @@ public void JoinNotch_RecoversRectangleWithoutChangingDoor() var original=f.Operands[f.Wall.Id][0]; Assert.True(f.Recover(out var gross)); Assert.Equal(original,f.Operands[f.Wall.Id][0]); - Assert.True(IfcExporter.IsExactFacetedShell(gross.Faces,gross.BrepSolids![0].FaceIndices)); + Assert.True(FacetedShell.IsExactFacetedShell(gross.Faces,gross.BrepSolids![0].FaceIndices)); Assert.True(IfcExporter.TryGetExactVerticalRectangularPrismSweptOpening(gross,out var box)); Assert.Equal(2500,Math.Max(box.WidthFt,box.DepthFt)*304.8,5); Assert.Equal(200,Math.Min(box.WidthFt,box.DepthFt)*304.8,5); diff --git a/tests/RvtIO.Tests/IfcExporterPlainWallBodyCurrentTests.cs b/tests/RvtIO.Tests/IfcExporterPlainWallBodyCurrentTests.cs index f0e00cc0..3e6306b7 100644 --- a/tests/RvtIO.Tests/IfcExporterPlainWallBodyCurrentTests.cs +++ b/tests/RvtIO.Tests/IfcExporterPlainWallBodyCurrentTests.cs @@ -1,3 +1,4 @@ +using RvtIO.Geometry; using RvtIO.Ifc; using RvtIO.Model; using RvtIO.Parsing; diff --git a/tests/RvtIO.Tests/IfcExporterSideSheetInsetCapsTests.cs b/tests/RvtIO.Tests/IfcExporterSideSheetInsetCapsTests.cs index e6e68255..21484b23 100644 --- a/tests/RvtIO.Tests/IfcExporterSideSheetInsetCapsTests.cs +++ b/tests/RvtIO.Tests/IfcExporterSideSheetInsetCapsTests.cs @@ -3,6 +3,7 @@ using System.Reflection; using System.Text.Json; using System.Text.RegularExpressions; +using RvtIO.Geometry; using RvtIO.Ifc; using RvtIO.Model; using Xunit; @@ -32,7 +33,7 @@ public void SideSheetInsetCaps_RecoversExactCapRectangle() var f = Create(); Assert.True(f.Recover(out var gross)); Assert.Equal(6, gross.Faces.Count); - Assert.True(IfcExporter.IsExactFacetedShell(gross.Faces, gross.BrepSolids![0].FaceIndices)); + Assert.True(FacetedShell.IsExactFacetedShell(gross.Faces, gross.BrepSolids![0].FaceIndices)); Assert.True(IfcExporter.TryGetExactVerticalRectangularPrismSweptOpening(gross, out var box)); Assert.Equal(1800, Math.Max(box.WidthFt, box.DepthFt) * 304.8, 5); Assert.Equal(80, Math.Min(box.WidthFt, box.DepthFt) * 304.8, 5); diff --git a/tests/RvtIO.Tests/IfcExporterWallGeometryTests.cs b/tests/RvtIO.Tests/IfcExporterWallGeometryTests.cs index 53a9fe78..8f84e47e 100644 --- a/tests/RvtIO.Tests/IfcExporterWallGeometryTests.cs +++ b/tests/RvtIO.Tests/IfcExporterWallGeometryTests.cs @@ -1,3 +1,4 @@ +using RvtIO.Geometry; using RvtIO.Ifc; using RvtIO.Internal; using RvtIO.Model; @@ -2008,7 +2009,7 @@ GeometryData GeometryFromFaces(IEnumerable sourceFaces) var subdivided = Geometry(low, high); Assert.False(IfcExporter.IsExactVerticalExtrusionBoundary(subdivided)); - Assert.True(IfcExporter.IsExactFacetedShell( + Assert.True(FacetedShell.IsExactFacetedShell( subdivided.Faces, subdivided.BrepSolids![0].FaceIndices)); Assert.True(IfcExporter.TryGetExactStraightWallVerticalExtrusionDefinition( subdivided, location, 1, bounds, @@ -2031,7 +2032,7 @@ GeometryData GeometryFromFaces(IEnumerable sourceFaces) var singleSubdivision = Geometry(singleLow, singleHigh); Assert.False(IfcExporter.IsExactVerticalExtrusionBoundary( singleSubdivision)); - Assert.True(IfcExporter.IsExactFacetedShell( + Assert.True(FacetedShell.IsExactFacetedShell( singleSubdivision.Faces, singleSubdivision.BrepSolids![0].FaceIndices)); Assert.True(IfcExporter.TryGetExactStraightWallVerticalExtrusionDefinition( @@ -2083,7 +2084,7 @@ GeometryData GeometryFromFaces(IEnumerable sourceFaces) mismatchedSingleHigh[^1][2] = 0.1; var mismatchedSingleSubdivision = Geometry(singleLow, mismatchedSingleHigh); - Assert.True(IfcExporter.IsExactFacetedShell( + Assert.True(FacetedShell.IsExactFacetedShell( mismatchedSingleSubdivision.Faces, mismatchedSingleSubdivision.BrepSolids![0].FaceIndices)); Assert.False(IfcExporter.TryGetExactStraightWallVerticalExtrusionDefinition( @@ -2107,7 +2108,7 @@ GeometryData GeometryFromFaces(IEnumerable sourceFaces) [2.25, 0.5, -0.15], [1.25, 0.5, -0.15], ]; var horizontalSubdivision = Geometry(horizontalLow, horizontalHigh); - Assert.True(IfcExporter.IsExactFacetedShell( + Assert.True(FacetedShell.IsExactFacetedShell( horizontalSubdivision.Faces, horizontalSubdivision.BrepSolids![0].FaceIndices)); Assert.False(IfcExporter.TryGetExactStraightWallVerticalExtrusionDefinition( @@ -10612,7 +10613,7 @@ static GeometryData OrientedBox( ], }; var standalone = new Dictionary>(); - Assert.True(IfcExporter.IsExactFacetedShell( + Assert.True(FacetedShell.IsExactFacetedShell( rebuiltFaces, Enumerable.Range(0, 12).ToList())); bool TryValidation() => IfcExporter .TryGetVerifiedGrossWallBoundaryFromCompleteOpenFifteenFaceContainedRedundantOpenings( @@ -10907,7 +10908,7 @@ bool TryValidation() => IfcExporter inverseHosts, emittedCutters, emittedOperands, standalone, exactPairs, out _, out _); - Assert.True(IfcExporter.IsExactFacetedShell( + Assert.True(FacetedShell.IsExactFacetedShell( rebuiltFaces, Enumerable.Range(0, 10).ToList())); Assert.True(IfcExporter .TryGetVerifiedGrossWallBoundaryFromCompleteOpenThirteenFaceDualAlternativeBottomCoincidentFamilyOpening( @@ -11273,7 +11274,7 @@ public void CompleteOpenTwelveFaceDetachedAlternativeFullHeightGap_RequiresExact BaseZFt: 0, HeightFt: WriterHeight, ExactDepth: true, IsFamilyCutLoop: true); - Assert.True(IfcExporter.IsExactFacetedShell( + Assert.True(FacetedShell.IsExactFacetedShell( rebuiltFaces, Enumerable.Range(0, 10).ToList())); Assert.True(IfcExporter .TryGetExactGrossWallBoundaryFromCompleteOpenTwelveFaceDetachedAlternativeFullHeightGapSource( @@ -18728,7 +18729,7 @@ public void EmbeddedSingleFamilyCutBrep_CompletesExactSourceAndJoinedCapTopology .SelectMany(face => face.OuterVertices!) .Select(point => (point[0], point[1], point[2])) .Distinct().Count()); - Assert.True(IfcExporter.IsExactFacetedShell( + Assert.True(FacetedShell.IsExactFacetedShell( completed.Faces, completed.BrepSolids!.Single().FaceIndices)); Assert.Contains(completed.Faces, face => face.OuterVertices!.Any(point => point[0] == 0 && point[1] == NormalMinimum @@ -23988,7 +23989,7 @@ public void StraightWallBoundary_PreservesAuthoredThroughOpening() Assert.True(Assert.Single(boundary.BrepSolids!).IsClosed); Assert.True(IfcExporter.TryOrientExactFacetedShell(boundary.Faces, Enumerable.Range(0, boundary.Faces.Count).ToArray(), out var oriented)); - Assert.True(IfcExporter.IsExactFacetedShell(oriented, + Assert.True(FacetedShell.IsExactFacetedShell(oriented, Enumerable.Range(0, oriented.Count).ToArray())); static (double X, double Y, double Z) Newell(IReadOnlyList ring) @@ -24927,10 +24928,10 @@ public void ExactFacetedShell_AcceptsOppositelyDirectedSharedEdges() Face([c, a, d]), }; - Assert.True(IfcExporter.IsExactFacetedShell(faces, [0, 1, 2, 3])); + Assert.True(FacetedShell.IsExactFacetedShell(faces, [0, 1, 2, 3])); Assert.True(IfcExporter.TryOrientExactFacetedShell( faces, [0, 1, 2, 3], out var oriented)); - Assert.True(IfcExporter.IsExactFacetedShell(oriented, [0, 1, 2, 3])); + Assert.True(FacetedShell.IsExactFacetedShell(oriented, [0, 1, 2, 3])); } [Fact] @@ -24949,7 +24950,7 @@ public void ExactFacetedShell_OrientsLongEdgeAcrossExactTjunctions() Assert.True(IfcExporter.TryOrientExactFacetedShell( faces, Enumerable.Range(0, faces.Count).ToArray(), out var oriented)); - Assert.True(IfcExporter.IsExactFacetedShell( + Assert.True(FacetedShell.IsExactFacetedShell( oriented, Enumerable.Range(0, oriented.Count).ToArray())); } @@ -24984,7 +24985,7 @@ public void ExactFacetedShell_OrientsNonContainedCycleAsCoplanarPatch() Assert.True(IfcExporter.TryOrientExactFacetedShell( faces, Enumerable.Range(0, faces.Count).ToArray(), out var oriented)); - Assert.True(IfcExporter.IsExactFacetedShell( + Assert.True(FacetedShell.IsExactFacetedShell( oriented, Enumerable.Range(0, oriented.Count).ToArray())); var coplanarFace = oriented.Single(face => face.InnerVertices is { Count: 1 }); @@ -25131,10 +25132,10 @@ public void ExactFacetedShell_ClosesRoundoffGapBelowDeclaredIfcPrecision() Face([c, a, d]), }; - Assert.True(IfcExporter.IsExactFacetedShell(faces, [0, 1, 2, 3])); + Assert.True(FacetedShell.IsExactFacetedShell(faces, [0, 1, 2, 3])); Assert.True(IfcExporter.TryOrientExactFacetedShell( faces, [0, 1, 2, 3], out var oriented)); - Assert.True(IfcExporter.IsExactFacetedShell(oriented, [0, 1, 2, 3])); + Assert.True(FacetedShell.IsExactFacetedShell(oriented, [0, 1, 2, 3])); } [Fact] @@ -25150,10 +25151,10 @@ public void ExactFacetedShell_OrientsAfterRemovingPrecisionCollapsedLoopEdge() Face([c, a, d]), }; - Assert.False(IfcExporter.IsExactFacetedShell(faces, [0, 1, 2, 3])); + Assert.False(FacetedShell.IsExactFacetedShell(faces, [0, 1, 2, 3])); Assert.True(IfcExporter.TryOrientExactFacetedShell( faces, [0, 1, 2, 3], out var oriented)); - Assert.True(IfcExporter.IsExactFacetedShell(oriented, [0, 1, 2, 3])); + Assert.True(FacetedShell.IsExactFacetedShell(oriented, [0, 1, 2, 3])); Assert.All(oriented, face => Assert.Equal(3, face.OuterVertices!.Count)); } @@ -25180,7 +25181,7 @@ public void ExactFacetedShell_ContractsUniqueSubPrecisionBoundaryWedge() Assert.True(IfcExporter.TryOrientPrecisionContractedFacetedShell( faces, [0, 1, 2, 3], out var retained, out var oriented)); Assert.Equal([0, 1, 2, 3], retained); - Assert.True(IfcExporter.IsExactFacetedShell(oriented, [0, 1, 2, 3])); + Assert.True(FacetedShell.IsExactFacetedShell(oriented, [0, 1, 2, 3])); } [Fact] @@ -25229,7 +25230,7 @@ public void ExactFacetedShell_RejectsCoordinateGapAboveDeclaredIfcPrecision() Face([c, a, d]), }; - Assert.False(IfcExporter.IsExactFacetedShell(faces, [0, 1, 2, 3])); + Assert.False(FacetedShell.IsExactFacetedShell(faces, [0, 1, 2, 3])); Assert.False(IfcExporter.TryOrientPrecisionContractedFacetedShell( faces, [0, 1, 2, 3], out _, out _)); } @@ -25248,7 +25249,7 @@ public void ExactFacetedShell_RecoversConsistentOutwardOrientationFromSharedEdge Assert.True(IfcExporter.TryOrientExactFacetedShell( faces, [0, 1, 2, 3], out var oriented)); - Assert.True(IfcExporter.IsExactFacetedShell(oriented, [0, 1, 2, 3])); + Assert.True(FacetedShell.IsExactFacetedShell(oriented, [0, 1, 2, 3])); double volume = 0; foreach (var face in oriented) @@ -25549,7 +25550,7 @@ public void FamilyComplexCut_UsesMappedInstanceTransformWhenClosurePlaneIsAbsent FamilyCutGeometry = BoxGeometry(-1, -0.1, 0, 1, 0.5, 4), }; type.FamilyCutGeometry.Faces[0].OuterVertices!.Reverse(); - Assert.False(IfcExporter.IsExactFacetedShell( + Assert.False(FacetedShell.IsExactFacetedShell( type.FamilyCutGeometry.Faces, type.FamilyCutGeometry.BrepSolids!.Single().FaceIndices)); var instance = new Element @@ -25648,7 +25649,7 @@ public void FamilyComplexCut_ClosesSerializedDummyHostIntervalFromExactProfiles( Assert.NotNull(opening.Boundary); Assert.Equal(6, opening.Boundary!.Faces.Count); Assert.Equal([-1, -2.25, 0, 1, 2.25, 4], opening.Boundary.BoundingBox!); - Assert.True(IfcExporter.IsExactFacetedShell( + Assert.True(FacetedShell.IsExactFacetedShell( opening.Boundary.Faces, opening.Boundary.BrepSolids!.Single().FaceIndices)); } @@ -26392,7 +26393,7 @@ public void ExactMappedSideTangentCollinearCapGate_RecoversEightPointGrossProfil var solid = Assert.Single(gross.BrepSolids!); Assert.True(solid.IsClosed); Assert.Equal(Enumerable.Range(0, 10), solid.FaceIndices); - Assert.True(IfcExporter.IsExactFacetedShell( + Assert.True(FacetedShell.IsExactFacetedShell( gross.Faces, solid.FaceIndices)); Assert.True(IfcExporter .TryGetExactStraightWallVerticalExtrusionDefinition( @@ -26584,7 +26585,7 @@ public void CompleteOpenSixteenFaceSplitRevealGate_RecoversGrossAndEightExactWri var solid = Assert.Single(gross.BrepSolids!); Assert.True(solid.IsClosed); Assert.Equal(Enumerable.Range(0, 6), solid.FaceIndices); - Assert.True(IfcExporter.IsExactFacetedShell( + Assert.True(FacetedShell.IsExactFacetedShell( gross.Faces, solid.FaceIndices)); Assert.True(IfcExporter.CanExportStandardCaseWallAsSweptSolid( data.Wall, data.Wall.BoundingBox!, gross)); @@ -27202,7 +27203,7 @@ public void CompleteOpenFiftyTwoFaceInsetCapsGate_RecoversExactGrossWall() var grossSolid = Assert.Single(gross.BrepSolids!); Assert.True(grossSolid.IsClosed); Assert.Equal(Enumerable.Range(0, 6), grossSolid.FaceIndices); - Assert.True(IfcExporter.IsExactFacetedShell( + Assert.True(FacetedShell.IsExactFacetedShell( gross.Faces, grossSolid.FaceIndices)); var grossTopology = ExactTopology(gross, grossSolid.FaceIndices); Assert.Equal((8, 12, 1), grossTopology.Summary); diff --git a/tests/RvtIO.Tests/NonVisibleQuantityGeometryTests.cs b/tests/RvtIO.Tests/NonVisibleQuantityGeometryTests.cs index aa7e659b..69a4874c 100644 --- a/tests/RvtIO.Tests/NonVisibleQuantityGeometryTests.cs +++ b/tests/RvtIO.Tests/NonVisibleQuantityGeometryTests.cs @@ -1,3 +1,4 @@ +using RvtIO.Geometry; using RvtIO.Ifc; using RvtIO.Internal; using RvtIO.Model; @@ -94,6 +95,6 @@ public void SurfaceArea_CountsSourceSurfaceOnceAcrossFacetsAndSeparatelyAcrossNo ], }; - Assert.Equal(6, IfcExporter.SurfaceAreaCurrent(geometry), 12); + Assert.Equal(6, BrepMeasures.SurfaceAreaCurrent(geometry), 12); } } diff --git a/tests/RvtIO.Tests/PlanarSpaceShellContactTests.cs b/tests/RvtIO.Tests/PlanarSpaceShellContactTests.cs index d2444bc1..6287ff40 100644 --- a/tests/RvtIO.Tests/PlanarSpaceShellContactTests.cs +++ b/tests/RvtIO.Tests/PlanarSpaceShellContactTests.cs @@ -1,3 +1,4 @@ +using RvtIO.Geometry; using RvtIO.Ifc; using RvtIO.Model; using System.Text.Json; @@ -35,7 +36,7 @@ public void CompleteConnectedBoundary_WithFourFacesAtOneEdge_IsNotAnExactShell( if (visited.Add(other)) queue.Enqueue(other); Assert.Equal(29, visited.Count); Assert.True(boundary.BrepSolids[0].IsClosed); // source declaration alone is insufficient - Assert.False(IfcExporter.IsExactFacetedShell(faces, indices)); + Assert.False(FacetedShell.IsExactFacetedShell(faces, indices)); Assert.False(IfcExporter.TryOrientExactFacetedShell(faces, indices, out var oriented)); Assert.Empty(oriented); Assert.Equal(before, JsonSerializer.Serialize(boundary)); diff --git a/tests/RvtIO.Tests/SchemaReleaseExportTests.cs b/tests/RvtIO.Tests/SchemaReleaseExportTests.cs index af6eeecb..1d626f87 100644 --- a/tests/RvtIO.Tests/SchemaReleaseExportTests.cs +++ b/tests/RvtIO.Tests/SchemaReleaseExportTests.cs @@ -56,8 +56,8 @@ public void ChangingTheSavingYearPreservesTheFullReadAndExports(string variable, Assert.True(originalIfc.ExportedProducts > 0); Assert.Equal(originalIfc.ExportedProducts, copyIfc.ExportedProducts); - Parsing.ValidatedElementNames.Apply(expected, originalReader.LastParsingState!); - Parsing.ValidatedElementNames.Apply(actual, copyReader.LastParsingState!); + RvtIO.Export.ValidatedElementNames.Apply(expected, originalReader.LastParsingState!); + RvtIO.Export.ValidatedElementNames.Apply(actual, copyReader.LastParsingState!); var expectedIdentity = new CompactIdentity(CompactUniverse.Select(expected)); var actualIdentity = new CompactIdentity(CompactUniverse.Select(actual)); var expectedSource = CompactPropertySources.Create(expected, originalReader.LastParsingState, true, identity: expectedIdentity); diff --git a/tests/RvtIO.Tests/ValidatedElementNamesTests.cs b/tests/RvtIO.Tests/ValidatedElementNamesTests.cs index 4f20f44a..f2a97b9a 100644 --- a/tests/RvtIO.Tests/ValidatedElementNamesTests.cs +++ b/tests/RvtIO.Tests/ValidatedElementNamesTests.cs @@ -1,3 +1,4 @@ +using RvtIO.Export; using RvtIO.Ifc; using RvtIO.Internal; using RvtIO.Model; diff --git a/tests/RvtIO.Tests/WallExtrusionTests.cs b/tests/RvtIO.Tests/WallExtrusionTests.cs index 4dc95e5e..52802a1f 100644 --- a/tests/RvtIO.Tests/WallExtrusionTests.cs +++ b/tests/RvtIO.Tests/WallExtrusionTests.cs @@ -1,3 +1,4 @@ +using RvtIO.Geometry; using RvtIO.Ifc; using RvtIO.Model; using Xunit; diff --git a/tests/RvtIO.Tests/WideElementRecordsTests.cs b/tests/RvtIO.Tests/WideElementRecordsTests.cs index 178e0d77..847d2025 100644 --- a/tests/RvtIO.Tests/WideElementRecordsTests.cs +++ b/tests/RvtIO.Tests/WideElementRecordsTests.cs @@ -1,3 +1,4 @@ +using RvtIO.Export; using System.Text; using RvtIO.BuiltIns; using RvtIO.Internal; From 883ab218beb25da8624397f54dc6266346a2f089 Mon Sep 17 00:00:00 2001 From: mahach666 <79989386+mahach666@users.noreply.github.com> Date: Wed, 18 Nov 2026 03:19:12 +0300 Subject: [PATCH 012/259] Keep Revit raster decoding outside the PDF renderer --- src/RvtIO/Internal/JpegHeader.cs | 29 +++++++++++++++++++++ src/RvtIO/{Print => Parsing}/RvtRaster.cs | 25 +++++++++--------- src/RvtIO/Pdf/PdfDocument.cs | 31 +++-------------------- src/RvtIO/Print/SheetComposer.cs | 12 +++++---- src/RvtIO/Print/ViewPrinter.cs | 5 ++-- tests/RvtIO.Tests/PdfWriterTests.cs | 7 +++++ tests/RvtIO.Tests/RvtRasterTests.cs | 11 ++++---- 7 files changed, 68 insertions(+), 52 deletions(-) create mode 100644 src/RvtIO/Internal/JpegHeader.cs rename src/RvtIO/{Print => Parsing}/RvtRaster.cs (93%) diff --git a/src/RvtIO/Internal/JpegHeader.cs b/src/RvtIO/Internal/JpegHeader.cs new file mode 100644 index 00000000..1c311a3b --- /dev/null +++ b/src/RvtIO/Internal/JpegHeader.cs @@ -0,0 +1,29 @@ +namespace RvtIO.Internal; + +internal readonly record struct JpegHeader(int Width, int Height, int Components) +{ + /// Reads the size and the components from the JPEG start-of-frame marker. + internal static JpegHeader Read(byte[] jpeg) + { + ArgumentNullException.ThrowIfNull(jpeg); + if (jpeg.Length < 4 || jpeg[0] != 0xFF || jpeg[1] != 0xD8) return default; + int at = 2; + while (at + 4 <= jpeg.Length) + { + if (jpeg[at] != 0xFF) { at++; continue; } + byte marker = jpeg[at + 1]; + if (marker is 0xD8 or 0xD9 or 0x01 || marker is >= 0xD0 and <= 0xD7) { at += 2; continue; } + int length = (jpeg[at + 2] << 8) | jpeg[at + 3]; + bool isFrame = marker is >= 0xC0 and <= 0xCF && marker is not 0xC4 and not 0xC8 and not 0xCC; + if (isFrame && at + 9 < jpeg.Length) + { + int height = (jpeg[at + 5] << 8) | jpeg[at + 6]; + int width = (jpeg[at + 7] << 8) | jpeg[at + 8]; + int components = jpeg[at + 9]; + return new(width, height, components); + } + at += 2 + length; + } + return default; + } +} diff --git a/src/RvtIO/Print/RvtRaster.cs b/src/RvtIO/Parsing/RvtRaster.cs similarity index 93% rename from src/RvtIO/Print/RvtRaster.cs rename to src/RvtIO/Parsing/RvtRaster.cs index 55aff259..0270f4a5 100644 --- a/src/RvtIO/Print/RvtRaster.cs +++ b/src/RvtIO/Parsing/RvtRaster.cs @@ -1,17 +1,16 @@ using System.Buffers.Binary; using System.IO.Compression; using OpenMcdf; -using RvtIO.Parsing; -using RvtIO.Pdf; +using RvtIO.Internal; -namespace RvtIO.Print; +namespace RvtIO.Parsing; /// Reads a raster image out of a Revit file and decodes a PNG to an RGB raster: Revit keeps the image files it -/// places in the partition streams, and the print writer embeds them with Flate compression. +/// places in the partition streams. internal static class RvtRaster { /// Finds and decodes the PNG of the given size in the file's streams, or null when there is none. - internal static PdfRasterImage? FindPng(string path, int width, int height) + internal static (int Width, int Height, byte[] Rgb)? FindPng(string path, int width, int height) { try { @@ -50,10 +49,9 @@ internal static class RvtRaster return null; } - /// Finds the JPEG that Revit stores in the block of the given element (class 0x0890) and returns it as an - /// image the PDF writer embeds as it is. A rendering of a 3D view is stored that way, in the block of its image - /// symbol's type. - internal static PdfJpegImage? FindJpeg(string path, int elementId) + /// Finds the encoded JPEG Revit stores in the given element's block (class 0x0890). + /// A 3D rendering stores its image in the block of the image symbol's type. + internal static (byte[] Bytes, JpegHeader Header)? FindJpeg(string path, int elementId) { try { @@ -84,7 +82,8 @@ internal static class RvtRaster int end = jpeg.AsSpan().LastIndexOf(new byte[] { 0xFF, 0xD9 }); if (end < 0) return null; Array.Resize(ref jpeg, end + 2); - return new PdfJpegImage(jpeg); + var header = JpegHeader.Read(jpeg); + return header.Width > 0 && header.Height > 0 ? (jpeg, header) : null; } } } @@ -99,7 +98,7 @@ internal static class RvtRaster /// Finds the logo of the file: the widest PNG whose aspect (four to eight to one) is that of a title block /// logo, decoded to an RGB raster. Null when the file has no such image. - internal static PdfRasterImage? FindLogo(string path) + internal static (int Width, int Height, byte[] Rgb)? FindLogo(string path) { try { @@ -145,7 +144,7 @@ internal static class RvtRaster /// Decodes a PNG (8 bits per channel, RGB, RGBA or palette, non-interlaced) to an RGB raster, alpha /// composited over white. - internal static PdfRasterImage? DecodePng(byte[] png) + internal static (int Width, int Height, byte[] Rgb)? DecodePng(byte[] png) { if (png.Length < 8 || png[0] != 0x89 || png[1] != 0x50 || png[2] != 0x4E || png[3] != 0x47) return null; @@ -242,7 +241,7 @@ internal static class RvtRaster rgb[target + 2] = (byte)((b * a + 255 * (255 - a)) / 255); } } - return new PdfRasterImage(width, height, rgb); + return (width, height, rgb); } /// The decompressed chunks of a stream; a stream that does not decode yields none. diff --git a/src/RvtIO/Pdf/PdfDocument.cs b/src/RvtIO/Pdf/PdfDocument.cs index 61577753..65f84486 100644 --- a/src/RvtIO/Pdf/PdfDocument.cs +++ b/src/RvtIO/Pdf/PdfDocument.cs @@ -1,5 +1,6 @@ using System.Globalization; using System.Text; +using RvtIO.Internal; namespace RvtIO.Pdf; @@ -66,15 +67,15 @@ public sealed class PdfJpegImage : IPdfImage /// Creates a JPEG image, reading the size and the components from its header. /// The JPEG file bytes. - public PdfJpegImage(byte[] jpeg) : this(jpeg, 0, 0, 0) + public PdfJpegImage(byte[] jpeg) : this(jpeg, JpegHeader.Read(jpeg)) { } - private PdfJpegImage(byte[] jpeg, int width, int height, int components) + internal PdfJpegImage(byte[] jpeg, JpegHeader header) { ArgumentNullException.ThrowIfNull(jpeg); Jpeg = jpeg; - (Width, Height, Components) = ReadHeader(jpeg); + (Width, Height, Components) = header; if (Width <= 0 || Height <= 0) throw new ArgumentException("The bytes are not a JPEG.", nameof(jpeg)); } @@ -86,30 +87,6 @@ private PdfJpegImage(byte[] jpeg, int width, int height, int components) /// The DCTDecode filter. public string? Filter => "DCTDecode"; - - /// Reads the size and the components from the JPEG start-of-frame marker. - internal static (int Width, int Height, int Components) ReadHeader(byte[] jpeg) - { - if (jpeg.Length < 4 || jpeg[0] != 0xFF || jpeg[1] != 0xD8) return (0, 0, 0); - int at = 2; - while (at + 4 <= jpeg.Length) - { - if (jpeg[at] != 0xFF) { at++; continue; } - byte marker = jpeg[at + 1]; - if (marker is 0xD8 or 0xD9 or 0x01 || marker is >= 0xD0 and <= 0xD7) { at += 2; continue; } - int length = (jpeg[at + 2] << 8) | jpeg[at + 3]; - bool isFrame = marker is >= 0xC0 and <= 0xCF && marker is not 0xC4 and not 0xC8 and not 0xCC; - if (isFrame && at + 9 < jpeg.Length) - { - int height = (jpeg[at + 5] << 8) | jpeg[at + 6]; - int width = (jpeg[at + 7] << 8) | jpeg[at + 8]; - int components = jpeg[at + 9]; - return (width, height, components); - } - at += 2 + length; - } - return (0, 0, 0); - } } /// An RGB raster image of the document, 8 bits per channel, written with Flate compression. diff --git a/src/RvtIO/Print/SheetComposer.cs b/src/RvtIO/Print/SheetComposer.cs index a166329e..42ee628a 100644 --- a/src/RvtIO/Print/SheetComposer.cs +++ b/src/RvtIO/Print/SheetComposer.cs @@ -1,5 +1,6 @@ using RvtIO.BuiltIns; using RvtIO.Model; +using RvtIO.Parsing; using RvtIO.Pdf; namespace RvtIO.Print; @@ -512,8 +513,8 @@ void ClipFrame(double frameX, double frameY, double frameWidth, double frameHeig { if (element.OwnerViewId != key.ViewId || element.RootClassName != "ImageSymbol") continue; if (element.TypeId <= 0) continue; - var image = RvtRaster.FindJpeg(key.Path, element.TypeId); - if (image != null) return image; + if (RvtRaster.FindJpeg(key.Path, element.TypeId) is { } jpeg) + return new PdfJpegImage(jpeg.Bytes, jpeg.Header); } return null; }); @@ -532,11 +533,12 @@ void ClipFrame(double frameX, double frameY, double frameWidth, double frameHeig || element.ImageHeight is not int height) continue; if (element.Name is not { Length: > 0 } name || !name.Contains("logo", StringComparison.OrdinalIgnoreCase)) continue; - var image = RvtRaster.FindPng(key, width, height); - if (image != null) return image; + if (RvtRaster.FindPng(key, width, height) is { } image) + return new PdfRasterImage(image.Width, image.Height, image.Rgb); } // The image-symbol sizes are not decoded for every file: fall back to the widest logo-shaped PNG. - return RvtRaster.FindLogo(key); + return RvtRaster.FindLogo(key) is { } logo + ? new PdfRasterImage(logo.Width, logo.Height, logo.Rgb) : null; }); } diff --git a/src/RvtIO/Print/ViewPrinter.cs b/src/RvtIO/Print/ViewPrinter.cs index 72e50175..5a977def 100644 --- a/src/RvtIO/Print/ViewPrinter.cs +++ b/src/RvtIO/Print/ViewPrinter.cs @@ -1,5 +1,6 @@ using RvtIO.BuiltIns; using RvtIO.Model; +using RvtIO.Parsing; using RvtIO.Pdf; namespace RvtIO.Print; @@ -108,8 +109,8 @@ private static void AddRenderingPage(PdfDocument pdf, RvtDocument document, Elem { if (element.OwnerViewId != viewId || element.RootClassName != "ImageSymbol") continue; if (element.TypeId <= 0) continue; - var image = RvtRaster.FindJpeg(path, element.TypeId); - if (image != null) return image; + if (RvtRaster.FindJpeg(path, element.TypeId) is { } jpeg) + return new PdfJpegImage(jpeg.Bytes, jpeg.Header); } return null; } diff --git a/tests/RvtIO.Tests/PdfWriterTests.cs b/tests/RvtIO.Tests/PdfWriterTests.cs index b7870c12..09a8e69a 100644 --- a/tests/RvtIO.Tests/PdfWriterTests.cs +++ b/tests/RvtIO.Tests/PdfWriterTests.cs @@ -176,6 +176,13 @@ public void JpegImage_IsWrittenWithDctDecode() Assert.Contains("/Subtype /Image", pdf); } + [Fact] + public void JpegImage_RejectsMissingDataOrFrame() + { + Assert.Throws("jpeg", () => new PdfJpegImage(null!)); + Assert.Throws("jpeg", () => new PdfJpegImage([0xFF, 0xD8, 0xFF, 0xD9])); + } + [Fact] public void Compress_WritesFlateStreamsThatShrinkTheFile() { diff --git a/tests/RvtIO.Tests/RvtRasterTests.cs b/tests/RvtIO.Tests/RvtRasterTests.cs index b0605743..8914fdf6 100644 --- a/tests/RvtIO.Tests/RvtRasterTests.cs +++ b/tests/RvtIO.Tests/RvtRasterTests.cs @@ -1,12 +1,12 @@ using System.Buffers.Binary; using System.IO.Compression; using System.Text; -using RvtIO.Print; +using RvtIO.Parsing; using Xunit; namespace RvtIO.Tests; -/// The raster reader (src/RvtIO/Print/RvtRaster): a PNG decoded to the RGB raster the PDF writer embeds. +/// The raster reader decodes PNG data to RGB pixels. /// public class RvtRasterTests { @@ -59,9 +59,10 @@ public void DecodePng_ReadsThePixels() var image = RvtRaster.DecodePng(png); Assert.NotNull(image); - Assert.Equal(2, image!.Width); - Assert.Equal(1, image.Height); - Assert.Equal([255, 0, 0, 0, 0, 255], image.Rgb); + var (width, height, rgb) = image.Value; + Assert.Equal(2, width); + Assert.Equal(1, height); + Assert.Equal([255, 0, 0, 0, 0, 255], rgb); } [Fact] From 1746952b65198e616d0e7225fca9cc7b06139b46 Mon Sep 17 00:00:00 2001 From: mahach666 <79989386+mahach666@users.noreply.github.com> Date: Wed, 18 Nov 2026 04:29:24 +0300 Subject: [PATCH 013/259] Keep stored Revit length units in the parser --- CONTRIBUTING.md | 2 ++ src/RvtIO/Ifc/IfcLengthUnitChoice.cs | 21 ---------------- src/RvtIO/Ifc/IfcNumericUnitPlan.cs | 3 +-- src/RvtIO/Internal/ParsingState.cs | 5 ---- .../ElementBuilder.ColumnLocationMark.cs | 2 +- src/RvtIO/Parsing/ProjectLengthUnits.cs | 25 +++++++++++++++++++ src/RvtIO/RvtFileReader.cs | 4 +-- tests/RvtIO.Tests/IfcNumericUnitPlanTests.cs | 17 +++++++------ tests/RvtIO.Tests/ProjectLengthUnitTests.cs | 12 ++++----- 9 files changed, 47 insertions(+), 44 deletions(-) create mode 100644 src/RvtIO/Parsing/ProjectLengthUnits.cs diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 275ae7db..7be63a46 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -55,6 +55,8 @@ The library is in `src/RvtIO`, the CLI in `src/RvtIO.Cli`, and tests in Keep file and geometry operations shared by the reader, writer and exporters in the library's format or geometry code. For example, polygon and bounds validation belong in `Geometry`, and path identity belongs in `Internal`. +Read the project's stored length unit in `Parsing`. Choosing the unit +declared in an IFC file belongs to the IFC exporter. `RvtIO.Scene` builds on the public RvtIO API and references IOScene separately. Tests that need real Revit files are skipped with a message when private diff --git a/src/RvtIO/Ifc/IfcLengthUnitChoice.cs b/src/RvtIO/Ifc/IfcLengthUnitChoice.cs index acf1e414..2936930d 100644 --- a/src/RvtIO/Ifc/IfcLengthUnitChoice.cs +++ b/src/RvtIO/Ifc/IfcLengthUnitChoice.cs @@ -17,27 +17,6 @@ internal static class IfcLengthUnitChoice { private const string UnitPrefix = "autodesk.unit.unit:"; - /// The unit id of the single Length option, null when it is missing, ambiguous or the library default. - internal static string? StoredLengthUnit(TfBlockDeserializer.UnitOptions? options) => StoredLengthUnit(options, out _); - - /// says why the option is not usable (null when it is). - internal static string? StoredLengthUnit(TfBlockDeserializer.UnitOptions? options, out string? issue) - { - issue = "the document unit options were not read"; - if (options == null) return null; - var matches = options.Options.Where(option => - UnitSchemaEvaluator.DisplayNameKey(option.Spec) == IfcNumericUnitPlan.LengthSpecName).ToArray(); - if (matches.Length != 1) issue = matches.Length == 0 ? "no Length format option" : "several Length format options"; - else if (matches[0].UseDefault != 0) issue = "the Length format option follows the library default"; - else if (string.IsNullOrEmpty(matches[0].Unit)) issue = "the Length format option has no unit"; - else - { - issue = null; - return matches[0].Unit; - } - return null; - } - /// The family the stored unit is written in, as Revit's own IFC export declares it: feet, feet-and-fractional-inches /// and US survey feet as FOOT, meters and meters-and-centimeters as METRE, millimeters as MILLI METRE. Null for every /// other unit (centimeters and inches among them, which have no family here) and for an unreadable option. diff --git a/src/RvtIO/Ifc/IfcNumericUnitPlan.cs b/src/RvtIO/Ifc/IfcNumericUnitPlan.cs index 266da53e..efa58722 100644 --- a/src/RvtIO/Ifc/IfcNumericUnitPlan.cs +++ b/src/RvtIO/Ifc/IfcNumericUnitPlan.cs @@ -12,7 +12,6 @@ internal sealed record IfcNumericUnitPlan( IfcNumericUnitPlan.CachedUnit Length, IfcNumericUnitPlan.CachedUnit ThermalTransmittance) { - internal const string LengthSpecName = "autodesk.spec.aec:length"; internal const string ThermalSpecName = "autodesk.spec.aec.energy:heatTransferCoefficient"; private const string UnitPrefix = "autodesk.unit.unit:"; private const string Feet = UnitPrefix + "feet-1.0.1"; @@ -53,7 +52,7 @@ internal bool TryUnscale(double value, out double result) // The spec map compares ordinally (UTF-16) up to the // first dash. Reject ambiguity instead of choosing a version or a family root. var matches = options.Options.Where(x => - UnitSchemaEvaluator.DisplayNameKey(x.Spec) == LengthSpecName).ToArray(); + UnitSchemaEvaluator.DisplayNameKey(x.Spec) == ProjectLengthUnits.LengthSpecName).ToArray(); if (matches.Length != 1) return Reject("Length option absent or name-ambiguous; library fallback not reproduced", out failure); var format = matches[0]; if (format.Spec.Contains('\0')) return Reject("Invalid length option spec ID", out failure); diff --git a/src/RvtIO/Internal/ParsingState.cs b/src/RvtIO/Internal/ParsingState.cs index 82b77fa1..447e4a04 100644 --- a/src/RvtIO/Internal/ParsingState.cs +++ b/src/RvtIO/Internal/ParsingState.cs @@ -82,11 +82,6 @@ public TfBlockDeserializer.UnitsElemOptions? OwnDocumentUnitOptions return null; } - /// Numeric length/thermal export plan, not emitted IFC units. Computed - /// so later duplicate roots or rejected display projections revoke acceptance. - public Ifc.IfcNumericUnitPlan? OwnDocumentIfcNumericUnitPlan - => Ifc.IfcNumericUnitPlan.Create(OwnDocumentUnitOptions?.Value, OwnDocumentUnitConversions, out _); - /// First block classId (low16) seen per element in the continuous walk. Used to /// assign category from the empirical high-purity classIdx->category table, applied late. public Dictionary ElemClassIdx { get; } = new(); diff --git a/src/RvtIO/Parsing/ElementBuilder.ColumnLocationMark.cs b/src/RvtIO/Parsing/ElementBuilder.ColumnLocationMark.cs index 7ae294d1..89d6ff54 100644 --- a/src/RvtIO/Parsing/ElementBuilder.ColumnLocationMark.cs +++ b/src/RvtIO/Parsing/ElementBuilder.ColumnLocationMark.cs @@ -36,7 +36,7 @@ internal static void ApplyColumnLocationMarks(RevitFileInfo info, TfBlockDeseria IReadOnlyDictionary? classByElement) { var lengthOptions = units?.Options - .Where(option => UnitSchemaEvaluator.DisplayNameKey(option.Spec) == Ifc.IfcNumericUnitPlan.LengthSpecName).ToArray(); + .Where(option => UnitSchemaEvaluator.DisplayNameKey(option.Spec) == ProjectLengthUnits.LengthSpecName).ToArray(); if (units == null || lengthOptions is not { Length: 1 } || units.DecimalSymbol != 0) return; var length = lengthOptions[0]; if (length.UseDefault != 0 || length.Accuracy <= 0) return; diff --git a/src/RvtIO/Parsing/ProjectLengthUnits.cs b/src/RvtIO/Parsing/ProjectLengthUnits.cs new file mode 100644 index 00000000..21b81adb --- /dev/null +++ b/src/RvtIO/Parsing/ProjectLengthUnits.cs @@ -0,0 +1,25 @@ +namespace RvtIO.Parsing; + +internal static class ProjectLengthUnits +{ + internal const string LengthSpecName = "autodesk.spec.aec:length"; + + /// The unit id of the single Length option, null when it is missing, ambiguous or the library default. + /// says why the option is not usable (null when it is). + internal static string? StoredLengthUnit(TfBlockDeserializer.UnitOptions? options, out string? issue) + { + issue = "the document unit options were not read"; + if (options == null) return null; + var matches = options.Options.Where(option => + UnitSchemaEvaluator.DisplayNameKey(option.Spec) == LengthSpecName).ToArray(); + if (matches.Length != 1) issue = matches.Length == 0 ? "no Length format option" : "several Length format options"; + else if (matches[0].UseDefault != 0) issue = "the Length format option follows the library default"; + else if (string.IsNullOrEmpty(matches[0].Unit)) issue = "the Length format option has no unit"; + else + { + issue = null; + return matches[0].Unit; + } + return null; + } +} diff --git a/src/RvtIO/RvtFileReader.cs b/src/RvtIO/RvtFileReader.cs index a64c3819..896211dd 100644 --- a/src/RvtIO/RvtFileReader.cs +++ b/src/RvtIO/RvtFileReader.cs @@ -808,7 +808,7 @@ public RevitFileInfo Read(string rvtPath) state.OwnDocumentUnitOptions, state.OwnDocumentUnitConversions, state.OwnDocumentSchemas); var lengthOptions = state.OwnDocumentLengthUnitOptions(out string? lengthUnitIssue); rvtInfo.SerializedLengthUnit = state.WideLengthUnit - ?? (lengthOptions == null ? null : Ifc.IfcLengthUnitChoice.StoredLengthUnit(lengthOptions.Value, out lengthUnitIssue)); + ?? (lengthOptions == null ? null : ProjectLengthUnits.StoredLengthUnit(lengthOptions.Value, out lengthUnitIssue)); if (rvtInfo.SerializedLengthUnit == null) rvtInfo.SerializedLengthUnitIssue = state.WideLengthUnitIssue ?? lengthUnitIssue; // BasicFileInfo "Worksharing: Not enabled | Local | Central"; any other text is not decided. @@ -1180,7 +1180,7 @@ void Fail(string reason) } // kept apart from OwnUnitOptions, which the continuous walk revokes for these files (it counts the block a second time) string? issue = "the UnitsElem is not document accessible"; - if (access == 1) state.WideLengthUnit = Ifc.IfcLengthUnitChoice.StoredLengthUnit(options, out issue); + if (access == 1) state.WideLengthUnit = ProjectLengthUnits.StoredLengthUnit(options, out issue); if (state.WideLengthUnit == null) state.WideLengthUnitIssue = issue; state.OwnUnitOptions[document.UnitsElemId] = (1, new TfBlockDeserializer.UnitsElemOptions(document.UnitsElemId, family, access, 0, 0, options)); diag?.WriteLine($"Wide document units: UnitsElem {document.UnitsElemId}, {options.Options.Length} format options, unit schemas {document.Units.Entries.Length}"); diff --git a/tests/RvtIO.Tests/IfcNumericUnitPlanTests.cs b/tests/RvtIO.Tests/IfcNumericUnitPlanTests.cs index 1db4a6f0..b555d939 100644 --- a/tests/RvtIO.Tests/IfcNumericUnitPlanTests.cs +++ b/tests/RvtIO.Tests/IfcNumericUnitPlanTests.cs @@ -222,13 +222,16 @@ public void ComputedOwnedPlanRevokesOnDuplicateMalformedForeignOrMissingSource() { var owned=new TfBlockDeserializer.UnitsElemOptions(77,-1,1,10,50,Options(Option())); var state=new ParsingState { OwnDocumentUnitsElemId=77,OwnDocumentUnitConversions=Sdk }; - state.OwnUnitOptions.Add(77,(1,owned));Assert.NotNull(state.OwnDocumentIfcNumericUnitPlan); - state.OwnUnitOptions[77]=(2,owned);Assert.Null(state.OwnDocumentIfcNumericUnitPlan); - state.OwnUnitOptions[77]=(1,null);Assert.Null(state.OwnDocumentIfcNumericUnitPlan); - state.OwnUnitOptions[77]=(1,owned with {FamilyId=321});Assert.Null(state.OwnDocumentIfcNumericUnitPlan); - state.OwnUnitOptions[77]=(1,owned with {DocumentAccess=2});Assert.Null(state.OwnDocumentIfcNumericUnitPlan); - state.OwnUnitOptions[77]=(1,owned);state.OwnDocumentUnitConversions=null;Assert.Null(state.OwnDocumentIfcNumericUnitPlan); + IfcNumericUnitPlan? PlanFromState() => + IfcNumericUnitPlan.Create(state.OwnDocumentUnitOptions?.Value, state.OwnDocumentUnitConversions, out _); + + state.OwnUnitOptions.Add(77,(1,owned));Assert.NotNull(PlanFromState()); + state.OwnUnitOptions[77]=(2,owned);Assert.Null(PlanFromState()); + state.OwnUnitOptions[77]=(1,null);Assert.Null(PlanFromState()); + state.OwnUnitOptions[77]=(1,owned with {FamilyId=321});Assert.Null(PlanFromState()); + state.OwnUnitOptions[77]=(1,owned with {DocumentAccess=2});Assert.Null(PlanFromState()); + state.OwnUnitOptions[77]=(1,owned);state.OwnDocumentUnitConversions=null;Assert.Null(PlanFromState()); state.OwnDocumentUnitConversions=Sdk;state.OwnDocumentUnitsElemId=88; - Assert.Null(state.OwnDocumentIfcNumericUnitPlan); + Assert.Null(PlanFromState()); } } diff --git a/tests/RvtIO.Tests/ProjectLengthUnitTests.cs b/tests/RvtIO.Tests/ProjectLengthUnitTests.cs index dfe81cc3..1cf07935 100644 --- a/tests/RvtIO.Tests/ProjectLengthUnitTests.cs +++ b/tests/RvtIO.Tests/ProjectLengthUnitTests.cs @@ -22,7 +22,7 @@ private static TfBlockDeserializer.UnitOptions Options(params (string Spec, stri public void StoredOption_GivesTheFamilyOfTheProject(string unit, IfcUnitFamily expected) { var options = Options(("autodesk.spec.aec:area-1.0.0", "autodesk.unit.unit:squareMeters-1.0.1", 0), (LengthSpec, unit, 0)); - Assert.Equal(unit, IfcLengthUnitChoice.StoredLengthUnit(options, out string? issue)); + Assert.Equal(unit, ProjectLengthUnits.StoredLengthUnit(options, out string? issue)); Assert.Null(issue); Assert.Equal(expected, IfcLengthUnitChoice.Family(unit)); } @@ -30,13 +30,13 @@ public void StoredOption_GivesTheFamilyOfTheProject(string unit, IfcUnitFamily e [Fact] public void UnusableOptions_AreNullWithTheirReason() { - Assert.Null(IfcLengthUnitChoice.StoredLengthUnit(null, out string? issue)); + Assert.Null(ProjectLengthUnits.StoredLengthUnit(null, out string? issue)); Assert.Contains("not read", issue); - Assert.Null(IfcLengthUnitChoice.StoredLengthUnit(Options(("autodesk.spec.aec:area-1.0.0", "x", 0)), out issue)); + Assert.Null(ProjectLengthUnits.StoredLengthUnit(Options(("autodesk.spec.aec:area-1.0.0", "x", 0)), out issue)); Assert.Contains("no Length", issue); - Assert.Null(IfcLengthUnitChoice.StoredLengthUnit(Options((LengthSpec, "autodesk.unit.unit:meters-1.0.0", 1)), out issue)); + Assert.Null(ProjectLengthUnits.StoredLengthUnit(Options((LengthSpec, "autodesk.unit.unit:meters-1.0.0", 1)), out issue)); Assert.Contains("default", issue); - Assert.Null(IfcLengthUnitChoice.StoredLengthUnit(Options((LengthSpec, "", 0)), out issue)); + Assert.Null(ProjectLengthUnits.StoredLengthUnit(Options((LengthSpec, "", 0)), out issue)); Assert.Contains("no unit", issue); } @@ -94,7 +94,7 @@ public void SelectedUnitsElem_ServesProjectAndFamilyDocuments(int family) state.OwnUnitOptions[542] = (1, Elem(542, family, 1)); var options = state.OwnDocumentLengthUnitOptions(out string? issue); Assert.Null(issue); - Assert.Equal(FeetInches, IfcLengthUnitChoice.StoredLengthUnit(options!.Value)); + Assert.Equal(FeetInches, ProjectLengthUnits.StoredLengthUnit(options!.Value, out _)); } [Theory] From 71bb77a3a38f7ac23a6b8a395821d5e4cc5f4c47 Mon Sep 17 00:00:00 2001 From: mahach666 <79989386+mahach666@users.noreply.github.com> Date: Wed, 18 Nov 2026 04:49:15 +0300 Subject: [PATCH 014/259] Prove RvtIO native code builds without output layers --- .github/workflows/ci.yml | 1 + CONTRIBUTING.md | 8 ++++++++ src/RvtIO/Model/RevitFileInfo.cs | 2 +- src/RvtIO/{Compact => Parsing}/CompactFormatSettings.cs | 0 src/RvtIO/{Compact => Parsing}/CompactHeaderCategory.cs | 0 src/RvtIO/{Compact => Parsing}/CompactLabels.cs | 0 src/RvtIO/{Compact => Parsing}/CompactUniverse.cs | 0 src/RvtIO/RvtIO.csproj | 8 ++++++++ 8 files changed, 18 insertions(+), 1 deletion(-) rename src/RvtIO/{Compact => Parsing}/CompactFormatSettings.cs (100%) rename src/RvtIO/{Compact => Parsing}/CompactHeaderCategory.cs (100%) rename src/RvtIO/{Compact => Parsing}/CompactLabels.cs (100%) rename src/RvtIO/{Compact => Parsing}/CompactUniverse.cs (100%) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c3a9ade2..48f61e29 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -26,6 +26,7 @@ jobs: - run: dotnet build RvtIO.slnx -c Release --no-restore - run: dotnet test RvtIO.slnx -c Release --no-build - run: dotnet pack RvtIO.slnx -c Release --no-build -o artifacts + - run: dotnet build src/RvtIO/RvtIO.csproj -c Release -p:BuildNativeCoreOnly=true --artifacts-path native-core-check - uses: actions/upload-artifact@v7 with: name: packages-${{ matrix.os }} diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 7be63a46..127f4bb1 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -59,6 +59,14 @@ Read the project's stored length unit in `Parsing`. Choosing the unit declared in an IFC file belongs to the IFC exporter. `RvtIO.Scene` builds on the public RvtIO API and references IOScene separately. +CI also compiles the native library without the Compact JSON, IFC and PDF +output code. Use a separate artifact path for this compile check. It keeps +the regular build available for testing and produces no NuGet package. + +```sh +dotnet build src/RvtIO/RvtIO.csproj -c Release -p:BuildNativeCoreOnly=true --artifacts-path ./artifacts/native-core-check +``` + Tests that need real Revit files are skipped with a message when private fixtures are unavailable. Set `RVTIO_TEST_FILES` to the folder containing your private fixtures to run them. The repository ships no Revit models. diff --git a/src/RvtIO/Model/RevitFileInfo.cs b/src/RvtIO/Model/RevitFileInfo.cs index be367410..4f060c8a 100644 --- a/src/RvtIO/Model/RevitFileInfo.cs +++ b/src/RvtIO/Model/RevitFileInfo.cs @@ -58,7 +58,7 @@ public class RevitFileInfo internal Parsing.UserParameterCatalog? UserParameters { get; set; } /// Last authored project phase, when the unique ordered source is known. - /// The phase of the command line option --ifc-phase last; the exporter's own default is the last phase that is a phase element (). + /// The phase of the command line option --ifc-phase last. The exporter's default instead selects the last phase element. [System.Text.Json.Serialization.JsonIgnore] internal int? SerializedDefaultExportPhaseId { get; set; } diff --git a/src/RvtIO/Compact/CompactFormatSettings.cs b/src/RvtIO/Parsing/CompactFormatSettings.cs similarity index 100% rename from src/RvtIO/Compact/CompactFormatSettings.cs rename to src/RvtIO/Parsing/CompactFormatSettings.cs diff --git a/src/RvtIO/Compact/CompactHeaderCategory.cs b/src/RvtIO/Parsing/CompactHeaderCategory.cs similarity index 100% rename from src/RvtIO/Compact/CompactHeaderCategory.cs rename to src/RvtIO/Parsing/CompactHeaderCategory.cs diff --git a/src/RvtIO/Compact/CompactLabels.cs b/src/RvtIO/Parsing/CompactLabels.cs similarity index 100% rename from src/RvtIO/Compact/CompactLabels.cs rename to src/RvtIO/Parsing/CompactLabels.cs diff --git a/src/RvtIO/Compact/CompactUniverse.cs b/src/RvtIO/Parsing/CompactUniverse.cs similarity index 100% rename from src/RvtIO/Compact/CompactUniverse.cs rename to src/RvtIO/Parsing/CompactUniverse.cs diff --git a/src/RvtIO/RvtIO.csproj b/src/RvtIO/RvtIO.csproj index 30387258..421848dc 100644 --- a/src/RvtIO/RvtIO.csproj +++ b/src/RvtIO/RvtIO.csproj @@ -11,6 +11,14 @@ $(NoWarn);CS1573 + + false + + + + + + From d0aa50739f545ca863fb7c4d9490ba20f48557f3 Mon Sep 17 00:00:00 2001 From: mahach666 <79989386+mahach666@users.noreply.github.com> Date: Wed, 18 Nov 2026 04:52:53 +0300 Subject: [PATCH 015/259] Verify the scene adapter against the native engine --- .github/workflows/ci.yml | 2 +- CONTRIBUTING.md | 6 +++--- src/RvtIO.Scene/RvtIO.Scene.csproj | 4 ++++ 3 files changed, 8 insertions(+), 4 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 48f61e29..770a69c9 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -26,7 +26,7 @@ jobs: - run: dotnet build RvtIO.slnx -c Release --no-restore - run: dotnet test RvtIO.slnx -c Release --no-build - run: dotnet pack RvtIO.slnx -c Release --no-build -o artifacts - - run: dotnet build src/RvtIO/RvtIO.csproj -c Release -p:BuildNativeCoreOnly=true --artifacts-path native-core-check + - run: dotnet build src/RvtIO.Scene/RvtIO.Scene.csproj -c Release -p:BuildNativeCoreOnly=true --artifacts-path native-core-check - uses: actions/upload-artifact@v7 with: name: packages-${{ matrix.os }} diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 127f4bb1..fffe34a1 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -59,12 +59,12 @@ Read the project's stored length unit in `Parsing`. Choosing the unit declared in an IFC file belongs to the IFC exporter. `RvtIO.Scene` builds on the public RvtIO API and references IOScene separately. -CI also compiles the native library without the Compact JSON, IFC and PDF -output code. Use a separate artifact path for this compile check. It keeps +CI also compiles the native library and its scene adapter without the Compact +JSON, IFC and PDF output code. Use a separate artifact path for this check. It keeps the regular build available for testing and produces no NuGet package. ```sh -dotnet build src/RvtIO/RvtIO.csproj -c Release -p:BuildNativeCoreOnly=true --artifacts-path ./artifacts/native-core-check +dotnet build src/RvtIO.Scene/RvtIO.Scene.csproj -c Release -p:BuildNativeCoreOnly=true --artifacts-path ./artifacts/native-core-check ``` Tests that need real Revit files are skipped with a message when private diff --git a/src/RvtIO.Scene/RvtIO.Scene.csproj b/src/RvtIO.Scene/RvtIO.Scene.csproj index adcb17fe..df9027d5 100644 --- a/src/RvtIO.Scene/RvtIO.Scene.csproj +++ b/src/RvtIO.Scene/RvtIO.Scene.csproj @@ -1,5 +1,9 @@ + + false + + Turns a Revit project read by RvtIO into an IOScene scene document. net8.0;net10.0 From 793d754092a7ba7a87ccff2758aa318465e1d461 Mon Sep 17 00:00:00 2001 From: mahach666 <79989386+mahach666@users.noreply.github.com> Date: Wed, 18 Nov 2026 06:47:14 +0300 Subject: [PATCH 016/259] Keep export reports and label tables out of the native Revit build --- CONTRIBUTING.md | 5 +- .../{Parsing => Compact}/CompactLabels.cs | 49 +------------- src/RvtIO/Diagnostics/RvtReadDiagnostics.cs | 65 +++++++++++++++++++ .../{Diagnostics => Export}/ExportReport.cs | 64 ------------------ src/RvtIO/Lookup/ParameterGroupLabels.cs | 54 +++++++++++++++ src/RvtIO/Parsing/UserParameterCatalog.cs | 2 +- src/RvtIO/RvtIO.csproj | 8 +-- src/RvtIO/RvtReaderOptions.cs | 2 +- tests/RvtIO.Tests/CompactLabelsTests.cs | 6 +- .../EmbeddedTableIntegrityTests.cs | 5 +- 10 files changed, 135 insertions(+), 125 deletions(-) rename src/RvtIO/{Parsing => Compact}/CompactLabels.cs (60%) create mode 100644 src/RvtIO/Diagnostics/RvtReadDiagnostics.cs rename src/RvtIO/{Diagnostics => Export}/ExportReport.cs (88%) create mode 100644 src/RvtIO/Lookup/ParameterGroupLabels.cs diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index fffe34a1..145ac2b0 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -60,8 +60,9 @@ declared in an IFC file belongs to the IFC exporter. `RvtIO.Scene` builds on the public RvtIO API and references IOScene separately. CI also compiles the native library and its scene adapter without the Compact -JSON, IFC and PDF output code. Use a separate artifact path for this check. It keeps -the regular build available for testing and produces no NuGet package. +JSON, IFC and PDF output code or export reporting. Reader diagnostics and exceptions +belong in `Diagnostics`; the export report and CLI exit codes belong in `Export`. +Use a separate artifact path for the compile check. The check produces no NuGet package. ```sh dotnet build src/RvtIO.Scene/RvtIO.Scene.csproj -c Release -p:BuildNativeCoreOnly=true --artifacts-path ./artifacts/native-core-check diff --git a/src/RvtIO/Parsing/CompactLabels.cs b/src/RvtIO/Compact/CompactLabels.cs similarity index 60% rename from src/RvtIO/Parsing/CompactLabels.cs rename to src/RvtIO/Compact/CompactLabels.cs index 6fe9d2bf..87b246db 100644 --- a/src/RvtIO/Parsing/CompactLabels.cs +++ b/src/RvtIO/Compact/CompactLabels.cs @@ -1,18 +1,12 @@ -using System.Globalization; using RvtIO.Lookup; +using static RvtIO.Lookup.ParameterGroupLabels; namespace RvtIO.Compact; /// The English labels of the compact JSON export: parameter captions, parameter group names, category names. internal static class CompactLabels { - internal const string InvalidGroup = "Invalid group"; - - /// BuiltInParameterGroup.INVALID. - internal const int InvalidGroupId = -1; - private static readonly Lazy> Parameters = new(LoadParameters); - private static readonly Lazy> Groups = new(LoadGroups); // group label and caption the current profile prints where they differ from the Revit 2022 text (compact_label_overrides.tsv) private static readonly Lazy> Overrides = new(LoadOverrides); @@ -51,20 +45,6 @@ internal static bool TryGetParameterGroupLabel(int builtinId, out string label) return Parameters.Value.TryGetValue(builtinId, out var parameter) && TryGetGroupLabel(parameter.Group, out label); } - /// The label of a BuiltInParameterGroup value (-1 gives "Invalid group"); false for a value the Revit 2022 - /// sources do not know (the current profile has two more groups, -5000232 and -5000233). - internal static bool TryGetGroupLabel(int groupId, out string label) - { - if (groupId == InvalidGroupId) - { - label = InvalidGroup; - return true; - } - bool found = Groups.Value.TryGetValue(groupId, out string? known); - label = known ?? ""; - return found; - } - internal static string GroupLabel(int groupId) => TryGetGroupLabel(groupId, out string label) ? label : InvalidGroup; /// The English name of a builtin category (a negative BuiltInCategory value). @@ -89,31 +69,4 @@ internal static bool TryGetCategoryLabel(int builtinCategoryId, out string label table.Add(ParseInt(row[0], "compact_label_overrides.tsv"), (row[1], row[2])); return table; } - - private static IReadOnlyDictionary LoadGroups() - { - var table = new Dictionary(); - foreach (string[] row in Rows("compact_parameter_groups.tsv", 2)) - table.Add(ParseInt(row[0], "compact_parameter_groups.tsv"), row[1]); - return table; - } - - private static int ParseInt(string text, string resource) => - int.TryParse(text, NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out int value) - ? value - : throw new InvalidDataException($"Malformed number '{text}' in {resource}."); - - private static IEnumerable Rows(string resource, int columns) - { - using var stream = typeof(CompactLabels).Assembly.GetManifestResourceStream("RvtIO.Resources." + resource) - ?? throw new InvalidOperationException($"Missing resource {resource}."); - using var reader = new StreamReader(stream); - for (string? line; (line = reader.ReadLine()) != null;) - { - if (line.Length == 0 || line[0] == '#') continue; - string[] fields = line.Split('\t'); - if (fields.Length != columns) throw new InvalidDataException($"Malformed line in {resource}: {line}"); - yield return fields; - } - } } diff --git a/src/RvtIO/Diagnostics/RvtReadDiagnostics.cs b/src/RvtIO/Diagnostics/RvtReadDiagnostics.cs new file mode 100644 index 00000000..6d64eb12 --- /dev/null +++ b/src/RvtIO/Diagnostics/RvtReadDiagnostics.cs @@ -0,0 +1,65 @@ +namespace RvtIO; + +/// The input cannot be read at all (missing, empty, not a compound file, or a stream ends before its declared length). +public sealed class RvtInputException : Exception +{ + /// Stable code: cannot-open, empty-file, not-a-compound-file or truncated-or-damaged. + public string Kind { get; } + + /// Creates the exception with its stable code. + public RvtInputException(string kind, string message, Exception? inner = null) : base(message, inner) => Kind = kind; +} + +/// A stream exceeds a limit of the reader that cannot be read around (see ). +public sealed class RvtLimitException : Exception +{ + /// The limit that was exceeded. + public ReaderLimitHit Hit { get; } + + /// Creates the exception for a limit hit. + public RvtLimitException(ReaderLimitHit hit) : base(hit.Detail) => Hit = hit; +} + +/// A limit of the reader that cut a stream. +/// The stream, as storage/name. +/// Stable limit code, see docs/export-report.md. +/// The value of the limit in force. +/// True when raises this limit. +public sealed record ReaderLimitHit(string Stream, string Limit, long Value, bool Raisable, string Detail); + +/// How much of one partition stream decoded. Members are the gzip members the stream is cut into. +public sealed record StreamRecord(string Name, long RawBytes, int Members, int Decoded, int Failed, int Recovered, int Unverified) +{ + /// The inflated byte length of the decoded members (0 when nothing decoded). + public long UnpackedBytes { get; init; } + + /// Creates a stream decode record including the inflated byte length of its decoded members. + public StreamRecord(string Name, long RawBytes, int Members, int Decoded, int Failed, int Recovered, int Unverified, long UnpackedBytes) + : this(Name, RawBytes, Members, Decoded, Failed, Recovered, Unverified) + { + this.UnpackedBytes = UnpackedBytes; + } + + /// Deconstructs the stream decode record including the inflated byte length. + public void Deconstruct(out string Name, out long RawBytes, out int Members, out int Decoded, out int Failed, out int Recovered, out int Unverified, out long UnpackedBytes) + { + Name = this.Name; + RawBytes = this.RawBytes; + Members = this.Members; + Decoded = this.Decoded; + Failed = this.Failed; + Recovered = this.Recovered; + Unverified = this.Unverified; + UnpackedBytes = this.UnpackedBytes; + } +} + +/// What the reader collects while it reads a file (). +public sealed class RvtReadDiagnostics +{ + /// The partition streams read, in the order they were read. + public List Streams { get; } = new(); + + /// The streams cut by a limit of the reader. + public List LimitHits { get; } = new(); +} diff --git a/src/RvtIO/Diagnostics/ExportReport.cs b/src/RvtIO/Export/ExportReport.cs similarity index 88% rename from src/RvtIO/Diagnostics/ExportReport.cs rename to src/RvtIO/Export/ExportReport.cs index 8e574cf1..96534cd4 100644 --- a/src/RvtIO/Diagnostics/ExportReport.cs +++ b/src/RvtIO/Export/ExportReport.cs @@ -40,60 +40,6 @@ public static int ForRead(RvtReadDiagnostics diagnostics, bool allowPartial, boo : Success; } -/// The input cannot be read at all (missing, empty, not a compound file, or a stream ends before its declared length). -public sealed class RvtInputException : Exception -{ - /// Stable code: cannot-open, empty-file, not-a-compound-file or truncated-or-damaged. - public string Kind { get; } - - /// Creates the exception with its stable code. - public RvtInputException(string kind, string message, Exception? inner = null) : base(message, inner) => Kind = kind; -} - -/// A stream exceeds a limit of the reader that cannot be read around (see ). -public sealed class RvtLimitException : Exception -{ - /// The limit that was exceeded. - public ReaderLimitHit Hit { get; } - - /// Creates the exception for a limit hit. - public RvtLimitException(ReaderLimitHit hit) : base(hit.Detail) => Hit = hit; -} - -/// A limit of the reader that cut a stream. -/// The stream, as storage/name. -/// Stable limit code, see docs/export-report.md. -/// The value of the limit in force. -/// True when raises this limit. -public sealed record ReaderLimitHit(string Stream, string Limit, long Value, bool Raisable, string Detail); - -/// How much of one partition stream decoded. Members are the gzip members the stream is cut into. -public sealed record StreamRecord(string Name, long RawBytes, int Members, int Decoded, int Failed, int Recovered, int Unverified) -{ - /// The inflated byte length of the decoded members (0 when nothing decoded). - public long UnpackedBytes { get; init; } - - /// Creates a stream decode record including the inflated byte length of its decoded members. - public StreamRecord(string Name, long RawBytes, int Members, int Decoded, int Failed, int Recovered, int Unverified, long UnpackedBytes) - : this(Name, RawBytes, Members, Decoded, Failed, Recovered, Unverified) - { - this.UnpackedBytes = UnpackedBytes; - } - - /// Deconstructs the stream decode record including the inflated byte length. - public void Deconstruct(out string Name, out long RawBytes, out int Members, out int Decoded, out int Failed, out int Recovered, out int Unverified, out long UnpackedBytes) - { - Name = this.Name; - RawBytes = this.RawBytes; - Members = this.Members; - Decoded = this.Decoded; - Failed = this.Failed; - Recovered = this.Recovered; - Unverified = this.Unverified; - UnpackedBytes = this.UnpackedBytes; - } -} - /// How the geometry of one exported element was obtained (). public enum GeometryQualityClass { @@ -113,16 +59,6 @@ public enum GeometryQualityClass /// How its geometry was obtained. public sealed record ElementGeometryQuality(int Id, string Class, GeometryQualityClass Quality); -/// What the reader collects while it reads a file, for the report (). -public sealed class RvtReadDiagnostics -{ - /// The partition streams read, in the order they were read. - public List Streams { get; } = new(); - - /// The streams cut by a limit of the reader. - public List LimitHits { get; } = new(); -} - /// The machine-readable report of one export run (docs/export-report.md). Serialize with . public sealed class ExportReport { diff --git a/src/RvtIO/Lookup/ParameterGroupLabels.cs b/src/RvtIO/Lookup/ParameterGroupLabels.cs new file mode 100644 index 00000000..53fec522 --- /dev/null +++ b/src/RvtIO/Lookup/ParameterGroupLabels.cs @@ -0,0 +1,54 @@ +using System.Globalization; + +namespace RvtIO.Lookup; + +internal static class ParameterGroupLabels +{ + internal const string InvalidGroup = "Invalid group"; + + /// BuiltInParameterGroup.INVALID. + internal const int InvalidGroupId = -1; + + private static readonly Lazy> Groups = new(LoadGroups); + + /// The label of a BuiltInParameterGroup value (-1 gives "Invalid group"); false for a value the Revit 2022 + /// sources do not know (the current profile has two more groups, -5000232 and -5000233). + internal static bool TryGetGroupLabel(int groupId, out string label) + { + if (groupId == InvalidGroupId) + { + label = InvalidGroup; + return true; + } + bool found = Groups.Value.TryGetValue(groupId, out string? known); + label = known ?? ""; + return found; + } + + private static IReadOnlyDictionary LoadGroups() + { + var table = new Dictionary(); + foreach (string[] row in Rows("compact_parameter_groups.tsv", 2)) + table.Add(ParseInt(row[0], "compact_parameter_groups.tsv"), row[1]); + return table; + } + + internal static int ParseInt(string text, string resource) => + int.TryParse(text, NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out int value) + ? value + : throw new InvalidDataException($"Malformed number '{text}' in {resource}."); + + internal static IEnumerable Rows(string resource, int columns) + { + using var stream = typeof(ParameterGroupLabels).Assembly.GetManifestResourceStream("RvtIO.Resources." + resource) + ?? throw new InvalidOperationException($"Missing resource {resource}."); + using var reader = new StreamReader(stream); + for (string? line; (line = reader.ReadLine()) != null;) + { + if (line.Length == 0 || line[0] == '#') continue; + string[] fields = line.Split('\t'); + if (fields.Length != columns) throw new InvalidDataException($"Malformed line in {resource}: {line}"); + yield return fields; + } + } +} diff --git a/src/RvtIO/Parsing/UserParameterCatalog.cs b/src/RvtIO/Parsing/UserParameterCatalog.cs index 1862be05..f39f2626 100644 --- a/src/RvtIO/Parsing/UserParameterCatalog.cs +++ b/src/RvtIO/Parsing/UserParameterCatalog.cs @@ -187,7 +187,7 @@ public IReadOnlyList BoundTo(int categoryId, bool instance) => definition.GroupTypeId == null ? GroupLabel(definition.GroupId) ?? InvalidGroup : definition.GroupTypeId.Length == 0 ? InvalidGroup : GroupOfForgeTypeId.TryGetValue(definition.GroupTypeId, out var group) - && (group.ToEnglishLabel(out string label) || Compact.CompactLabels.TryGetGroupLabel((int)group, out label)) ? label : null; + && (group.ToEnglishLabel(out string label) || Lookup.ParameterGroupLabels.TryGetGroupLabel((int)group, out label)) ? label : null; /// Classes (by name) whose element category the reader reads exactly, so that the project /// and shared parameters bound to that category can be listed. The reader's CategoryId is a scan of the record body diff --git a/src/RvtIO/RvtIO.csproj b/src/RvtIO/RvtIO.csproj index 421848dc..25e3091f 100644 --- a/src/RvtIO/RvtIO.csproj +++ b/src/RvtIO/RvtIO.csproj @@ -35,11 +35,11 @@ - + - - - + + + diff --git a/src/RvtIO/RvtReaderOptions.cs b/src/RvtIO/RvtReaderOptions.cs index 89bbcf3b..63fbb131 100644 --- a/src/RvtIO/RvtReaderOptions.cs +++ b/src/RvtIO/RvtReaderOptions.cs @@ -45,7 +45,7 @@ public class RvtReaderOptions /// For very large models. Off by default. public bool RaiseLimits { get; set; } - /// Collects the streams read, how much of each decoded, and the limits that cut a stream (see ). Null to collect nothing. + /// Collects the streams read, how much of each decoded, and the limits that cut a stream. Null to collect nothing. public RvtReadDiagnostics? Diagnostics { get; set; } /// Write diagnostic/progress messages to this TextWriter. Null for silent operation. diff --git a/tests/RvtIO.Tests/CompactLabelsTests.cs b/tests/RvtIO.Tests/CompactLabelsTests.cs index 49346530..b37fe900 100644 --- a/tests/RvtIO.Tests/CompactLabelsTests.cs +++ b/tests/RvtIO.Tests/CompactLabelsTests.cs @@ -86,7 +86,7 @@ public void InvalidGroupOfAParameterIsLabelledInvalidGroup() { // Category (ELEM_CATEGORY_PARAM): its definition has no group. Assert.True(CompactLabels.TryGetParameterGroupId(-1140362, out int group)); - Assert.Equal(CompactLabels.InvalidGroupId, group); + Assert.Equal(ParameterGroupLabels.InvalidGroupId, group); Assert.True(CompactLabels.TryGetParameterGroupLabel(-1140362, out string label)); Assert.Equal("Invalid group", label); } @@ -127,12 +127,12 @@ public void GroupLabelsAgreeWithTheEnumExtension() { int known = 0; for (int group = -5000300; group <= -5000001; group++) - if (CompactLabels.TryGetGroupLabel(group, out _)) known++; + if (ParameterGroupLabels.TryGetGroupLabel(group, out _)) known++; Assert.Equal(120, known); foreach (var group in Enum.GetValues().Where(g => g != BuiltInParameterGroup.INVALID)) if (group.ToEnglishLabel(out string enumLabel)) { - Assert.True(CompactLabels.TryGetGroupLabel((int)group, out string label), group.ToString()); + Assert.True(ParameterGroupLabels.TryGetGroupLabel((int)group, out string label), group.ToString()); Assert.Equal(enumLabel, label); } } diff --git a/tests/RvtIO.Tests/EmbeddedTableIntegrityTests.cs b/tests/RvtIO.Tests/EmbeddedTableIntegrityTests.cs index 7cce2a2c..b1ecb234 100644 --- a/tests/RvtIO.Tests/EmbeddedTableIntegrityTests.cs +++ b/tests/RvtIO.Tests/EmbeddedTableIntegrityTests.cs @@ -1,5 +1,6 @@ using System.Globalization; using RvtIO.Compact; +using RvtIO.Lookup; using Xunit; namespace RvtIO.Tests; @@ -44,11 +45,11 @@ public void GroupTableHasUniqueIdsAndEveryGroupOfTheParameterTableIsKnown() Assert.Equal(groups.Count, groups.Select(r => r[0]).Distinct().Count()); foreach (var row in groups) { - Assert.True(CompactLabels.TryGetGroupLabel(int.Parse(row[0], CultureInfo.InvariantCulture), out string label), row[0]); + Assert.True(ParameterGroupLabels.TryGetGroupLabel(int.Parse(row[0], CultureInfo.InvariantCulture), out string label), row[0]); Assert.Equal(row[1], label); } foreach (int group in EmbeddedTables.Rows("compact_builtin_parameters.tsv", 3).Select(r => int.Parse(r[1], CultureInfo.InvariantCulture)).Distinct()) - Assert.True(group == CompactLabels.InvalidGroupId || CompactLabels.TryGetGroupLabel(group, out _), group.ToString()); + Assert.True(group == ParameterGroupLabels.InvalidGroupId || ParameterGroupLabels.TryGetGroupLabel(group, out _), group.ToString()); } [Fact] From 06ce5a47a228a4a52b3a66b4da118ffbdeb56fc5 Mon Sep 17 00:00:00 2001 From: mahach666 <79989386+mahach666@users.noreply.github.com> Date: Wed, 18 Nov 2026 06:53:41 +0300 Subject: [PATCH 017/259] Keep Compact presentation metadata with the exporter --- .../CompactFormatSettings.cs | 0 src/RvtIO/Compact/RevitFileInfo.Compact.cs | 11 +++++++++++ src/RvtIO/Compact/RvtFileReader.Compact.cs | 17 +++++++++++++++++ src/RvtIO/Model/RevitFileInfo.cs | 13 +------------ src/RvtIO/RvtFileReader.cs | 10 +++++----- 5 files changed, 34 insertions(+), 17 deletions(-) rename src/RvtIO/{Parsing => Compact}/CompactFormatSettings.cs (100%) create mode 100644 src/RvtIO/Compact/RevitFileInfo.Compact.cs create mode 100644 src/RvtIO/Compact/RvtFileReader.Compact.cs diff --git a/src/RvtIO/Parsing/CompactFormatSettings.cs b/src/RvtIO/Compact/CompactFormatSettings.cs similarity index 100% rename from src/RvtIO/Parsing/CompactFormatSettings.cs rename to src/RvtIO/Compact/CompactFormatSettings.cs diff --git a/src/RvtIO/Compact/RevitFileInfo.Compact.cs b/src/RvtIO/Compact/RevitFileInfo.Compact.cs new file mode 100644 index 00000000..29b50132 --- /dev/null +++ b/src/RvtIO/Compact/RevitFileInfo.Compact.cs @@ -0,0 +1,11 @@ +namespace RvtIO.Model; + +public partial class RevitFileInfo +{ + /// The document's unit formatting, or null when its units element or schemas are incomplete. + [System.Text.Json.Serialization.JsonIgnore] + internal Compact.CompactFormatSettings? SerializedFormatSettings { get; set; } + + /// The empty lookup entry ("<None>") in the file's saved locale, or null without its resources. + internal string? SerializedLookupNoneText { get; set; } +} diff --git a/src/RvtIO/Compact/RvtFileReader.Compact.cs b/src/RvtIO/Compact/RvtFileReader.Compact.cs new file mode 100644 index 00000000..b191fb4c --- /dev/null +++ b/src/RvtIO/Compact/RvtFileReader.Compact.cs @@ -0,0 +1,17 @@ +using RvtIO.Internal; +using RvtIO.Lookup; +using RvtIO.Model; + +namespace RvtIO; + +public partial class RvtFileReader +{ + // Use the locale of the stored lookup entries even when export selects a different locale for names. + static partial void ReadCompactLookupText(RevitFileInfo info) => + info.SerializedLookupNoneText = RevitSystemFamilyNames.Load( + info.Metadata.RevitVersion, info.Metadata.SavedLocale)?.Get(RevitUiText.LookupNone); + + static partial void ReadCompactFormatSettings(RevitFileInfo info, ParsingState state) => + info.SerializedFormatSettings = Compact.CompactFormatSettings.Create( + state.OwnDocumentUnitOptions, state.OwnDocumentUnitConversions, state.OwnDocumentSchemas); +} diff --git a/src/RvtIO/Model/RevitFileInfo.cs b/src/RvtIO/Model/RevitFileInfo.cs index 4f060c8a..d28c08d3 100644 --- a/src/RvtIO/Model/RevitFileInfo.cs +++ b/src/RvtIO/Model/RevitFileInfo.cs @@ -1,7 +1,7 @@ namespace RvtIO.Model { /// Everything the reader decodes from one Revit file. - public class RevitFileInfo + public partial class RevitFileInfo { /// A copy that shares all members with this instance; the caller replaces what it changes. internal RevitFileInfo ShallowCopy() => (RevitFileInfo)MemberwiseClone(); @@ -76,13 +76,6 @@ public class RevitFileInfo [System.Text.Json.Serialization.JsonIgnore] internal Guid? SerializedDocumentGuid { get; set; } - /// The document's unit format options per spec with the decimal and digit grouping - /// symbols, the numeric unit conversions and the unit symbol labels: what the display-value - /// formatter (Compact.CompactValueFormatter) needs. Null when the document's own units element or - /// persisted unit schemas could not be read completely. - [System.Text.Json.Serialization.JsonIgnore] - internal Compact.CompactFormatSettings? SerializedFormatSettings { get; set; } - /// The unit id of the document's stored Length format option (for example "autodesk.unit.unit:feetFractionalInches-1.0.1"); /// null when the units element has no single, non-default Length option. [System.Text.Json.Serialization.JsonIgnore] @@ -110,10 +103,6 @@ public class RevitFileInfo /// True when is the exactly resolved active project location (not the older fallback). internal bool SharedTransformIsActiveLocation { get; set; } - /// The text of the empty lookup table entry ("<None>") in the locale the file was saved in; null when the - /// Revit resources of that locale are not available. - internal string? SerializedLookupNoneText { get; set; } - /// Latitude and longitude (radians) of the GeoSite of the active project location; /// null when the file has no readable active location. public double? SiteLatitudeRadians { get; set; } diff --git a/src/RvtIO/RvtFileReader.cs b/src/RvtIO/RvtFileReader.cs index 896211dd..9d12a076 100644 --- a/src/RvtIO/RvtFileReader.cs +++ b/src/RvtIO/RvtFileReader.cs @@ -10,6 +10,9 @@ public partial class RvtFileReader { private readonly RvtReaderOptions _options; + static partial void ReadCompactLookupText(RevitFileInfo info); + static partial void ReadCompactFormatSettings(RevitFileInfo info, ParsingState state); + /// Creates a reader with the given options; null uses the defaults. public RvtFileReader(RvtReaderOptions? options = null) { @@ -767,9 +770,7 @@ public RevitFileInfo Read(string rvtPath) var familyNames = systemFamilyNames ?? Lookup.RevitSystemFamilyNames.LoadPreviousReleaseFamilies(rvtInfo.Metadata.RevitVersion, systemFamilyLocale, _options.SystemFamilyNameLocale); int systemFamilyTypes = ElementBuilder.ApplyValidatedSystemFamilyNames(rvtInfo.Elements, state, familyNames); - // the stored lookup entries are in the language the file was saved in, whatever locale the exported names use - rvtInfo.SerializedLookupNoneText = Lookup.RevitSystemFamilyNames.Load( - rvtInfo.Metadata.RevitVersion, rvtInfo.Metadata.SavedLocale)?.Get(Lookup.RevitUiText.LookupNone); + ReadCompactLookupText(rvtInfo); ElementBuilder.ApplyValidatedStairOccurrenceNames(rvtInfo.Elements, familyNames); ElementBuilder.ApplyHostLabels(rvtInfo, systemFamilyNames, state.ElemClassIdx); ElementBuilder.ApplyWorkPlaneLabels(rvtInfo, systemFamilyNames); @@ -804,8 +805,7 @@ public RevitFileInfo Read(string rvtPath) int wallThicknessOccurrences = ElementBuilder.ApplyBasicWallTypeThickness(rvtInfo.Elements, state); diag?.WriteLine($"Own computed wall thickness: occurrences={wallThicknessOccurrences}/{state.BasicWallTypeThicknessFeet.Count}"); rvtInfo.SerializedDocumentGuid = state.DocumentDetachGuid; - rvtInfo.SerializedFormatSettings = Compact.CompactFormatSettings.Create( - state.OwnDocumentUnitOptions, state.OwnDocumentUnitConversions, state.OwnDocumentSchemas); + ReadCompactFormatSettings(rvtInfo, state); var lengthOptions = state.OwnDocumentLengthUnitOptions(out string? lengthUnitIssue); rvtInfo.SerializedLengthUnit = state.WideLengthUnit ?? (lengthOptions == null ? null : ProjectLengthUnits.StoredLengthUnit(lengthOptions.Value, out lengthUnitIssue)); From d67965004a27364b95a6622c12468fca67f92917 Mon Sep 17 00:00:00 2001 From: mahach666 <79989386+mahach666@users.noreply.github.com> Date: Wed, 18 Nov 2026 10:43:48 +0300 Subject: [PATCH 018/259] Prepare RvtIO 0.5.0 --- CHANGELOG.md | 5 +++++ Directory.Build.props | 2 +- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8b8e353c..31b2dcbb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,8 +6,13 @@ API between minor releases. ## [Unreleased] +## [0.5.0] - 2026-11-18 + ### Changed +- The native Revit reader, writer and scene adapter build independently of IFC, Compact JSON and PDF output. + The regular packages retain the public output APIs and CLI commands. + - The printing docs say what is still not drawn (the plane of a section, the detail views without linework, the graphic of the title block family, the schedules, the images other than the logo and the renderings, the crop region) and the next steps; the public API docs list the image types, `PdfPage.DrawImage`, the 3D and rendering pages of diff --git a/Directory.Build.props b/Directory.Build.props index 16193775..59181be8 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -6,7 +6,7 @@ enable true true - 0.4.0 + 0.5.0 true true snupkg From 9cac10b66e767bf58718b580e7d74af54acdedb0 Mon Sep 17 00:00:00 2001 From: mahach666 <79989386+mahach666@users.noreply.github.com> Date: Thu, 19 Nov 2026 10:52:17 +0300 Subject: [PATCH 019/259] Improve Revit 2027 reader parity and geometry performance --- CHANGELOG.md | 14 + docs/public-api.md | 39 ++ docs/test-fixtures.md | 17 + src/RvtIO/Geometry/BrepMeasures.cs | 6 +- src/RvtIO/Geometry/FacetedShell.cs | 489 +++++++++++------- .../Geometry/Meshing/ConformingDelaunay.cs | 387 ++++++++++++++ src/RvtIO/Geometry/Meshing/DelaunaySeed.cs | 236 +++++++++ src/RvtIO/Geometry/Meshing/FaceArea.cs | 90 +++- .../Geometry/Meshing/PlanarPredicates.cs | 53 ++ src/RvtIO/Internal/GRepData.cs | 9 + src/RvtIO/Model/Element.cs | 5 +- src/RvtIO/Parsing/ElementBuilder.cs | 27 +- src/RvtIO/Parsing/GRepParserV2.FaceAreas.cs | 46 +- .../Parsing/GRepParserV2.HermiteMeasure.cs | 297 +++++++++++ src/RvtIO/Parsing/GRepParserV2.MeshFaces.cs | 54 +- src/RvtIO/Parsing/GRepParserV2.MeshNodes.cs | 17 +- .../Parsing/GRepParserV2.SolidMeasures.cs | 429 ++++++++++++++- src/RvtIO/Parsing/GRepParserV2.cs | 238 +++++++-- src/RvtIO/Parsing/NativeTypePointers.cs | 4 + src/RvtIO/Parsing/RebarReader.ShapeDriven.cs | 3 +- src/RvtIO/Parsing/RebarReader.cs | 6 +- .../Revit2027ApiValues.HostQuantities.cs | 203 ++++++++ .../Parsing/Revit2027ApiValues.TypeNames.cs | 60 +++ src/RvtIO/Parsing/Revit2027ApiValues.cs | 223 ++++++++ src/RvtIO/Parsing/TfBlockDeserializer.cs | 1 + .../Parsing/WideNativeParams.SketchArea.cs | 79 +++ src/RvtIO/Parsing/WideNativeParams.cs | 99 +++- src/RvtIO/Parsing/WideSolidQuantities.cs | 440 ++++++++++++++++ src/RvtIO/RvtFileReader.cs | 17 +- .../RvtIO.Tests/AnalyticSolidMeasureTests.cs | 134 +++++ tests/RvtIO.Tests/EdgePointTests.cs | 14 + tests/RvtIO.Tests/FaceAreaTests.cs | 41 ++ tests/RvtIO.Tests/Format2027SchemaTests.cs | 50 ++ tests/RvtIO.Tests/FormatCorpusTests.cs | 58 +++ .../IfcExporterWallGeometryTests.cs | 170 +++++- tests/RvtIO.Tests/NativeTypePointersTests.cs | 4 + tests/RvtIO.Tests/Revit2027ApiValuesTests.cs | 222 ++++++++ tests/RvtIO.Tests/SchemaReleaseTests.cs | 2 +- .../TessellationAllocationTests.cs | 44 ++ .../RvtIO.Tests/WideBlockWalkerEntityTests.cs | 21 + tests/RvtIO.Tests/WideElementRecordsTests.cs | 17 + tests/RvtIO.Tests/WideSolidQuantitiesTests.cs | 171 ++++++ 42 files changed, 4186 insertions(+), 350 deletions(-) create mode 100644 src/RvtIO/Geometry/Meshing/ConformingDelaunay.cs create mode 100644 src/RvtIO/Geometry/Meshing/DelaunaySeed.cs create mode 100644 src/RvtIO/Geometry/Meshing/PlanarPredicates.cs create mode 100644 src/RvtIO/Parsing/GRepParserV2.HermiteMeasure.cs create mode 100644 src/RvtIO/Parsing/Revit2027ApiValues.HostQuantities.cs create mode 100644 src/RvtIO/Parsing/Revit2027ApiValues.TypeNames.cs create mode 100644 src/RvtIO/Parsing/Revit2027ApiValues.cs create mode 100644 src/RvtIO/Parsing/WideNativeParams.SketchArea.cs create mode 100644 src/RvtIO/Parsing/WideSolidQuantities.cs create mode 100644 tests/RvtIO.Tests/FormatCorpusTests.cs create mode 100644 tests/RvtIO.Tests/Revit2027ApiValuesTests.cs create mode 100644 tests/RvtIO.Tests/WideSolidQuantitiesTests.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index 31b2dcbb..510fe679 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,20 @@ API between minor releases. ## [Unreleased] +### Fixed + +- The Revit 2027 reader computes Area and Volume for closed bodies with full ruled faces between + aligned circular arcs. It also recovers missing family volumes from visible closed bodies, + including straight extrusions with elliptical profile edges. +- The Revit 2027 reader computes Area for straight extrusions with elliptical profile edges from + the distinct UV samples of both caps and the extruded length of each boundary. +- Closed bodies with revolved elliptical and Hermite profiles contribute Area and Volume. +- Supported closed bodies with rectangular Hermite faces now compute Area and Volume from the + refined facets. +- The Revit 2027 reader measures trimmed ruled bodies from their original coedges before mesh + refinement. It also reads extrusion-roof Area from the tagged lower faces and measures planar + masses using the mean area of the upper and lower faces. + ## [0.5.0] - 2026-11-18 ### Changed diff --git a/docs/public-api.md b/docs/public-api.md index 6c8f04a1..ee2512ac 100644 --- a/docs/public-api.md +++ b/docs/public-api.md @@ -45,6 +45,45 @@ position the file stores for it (feet) and the font size its RTF declares; they `Element.ViewportScale` is the view scale (the denominator) decoded from a viewport record; `Element.ViewportViewId` and `Element.ViewportOffset` are what that record places on the sheet. `Element.OwnerViewId` is the stored `m_ownerDBViewId` of the element: the view or sheet whose annotations and view-specific graphics hold it (a text note on a sheet names the sheet), null when no view owns it. `SheetCatalog` uses it for the elements a sheet owns. +In a non-workshared Revit 2027 file, the default workset is represented by 0 in `Element.WorksetId` +and by -1 in the built-in `ELEM_PARTITION_PARAM` value. A property set element has a `WorksetId` +and omits `ELEM_PARTITION_PARAM` in these files. The schema-driven reader uses the stored header +category for Revit 2027 elements with a decoded category. + +For Revit 2027, the reader follows the stored links from stair runs and landings to their stair's +type. Elevation views without a direct type use their linked elevation marker's type when the +view and arrow point to each other. + +The Revit 2027 reader recovers the `Type Name` of tile patterns from the owned pattern and +uses the built-in English labels for conceptual constructions, site data and internal stair symbols. +It derives `Area` in square feet from the linked filled-region sketch when it contains one closed +line loop and `Volume` in cubic feet from the stored dimensions and drive line of a straight +rectangular duct. +For supported Revit 2027 categories the reader also measures closed bodies from the project's +saved geometry, including geometry reused at rigid placements. Mullion and lighting fixture area is +half the summed solid surface area. Lighting fixture quantities include the closed bodies saved for +different viewing directions at Coarse detail. Curtain panel area is the largest planar face. +Straight basic wall area is the larger net area of its two finish sides. Straight curtain wall +area comes from the stored closed wall profile. + +The reader integrates supported circular and straight profiles of revolution along the saved trim +loops. Pipe fitting volume uses the detailed solids and excludes coarse proxies when their complete +source faces are reused. Supported MEP center lines get quantities from their linked physical owner. + +The reader measures horizontal floors, ceilings, and foundations at their saved cap faces, with trim +loops applied. Door area uses the coarse source bodies for ordinary wall-hosted doors and the opening +spanned by the rectangular leaves for curtain wall doors. For 2D components the reader measures the +filled faces of the instance's geometry symbol, including stretched variants. Filled regions use the +area of their own loops. + +Duct fitting volume integrates ruled faces with a collapsed end and excludes complete reused coarse +bodies. For the supported trimmed structural framing, volume uses the closed body retained by the cut. +For supported single-body masses, area comes from matching horizontal caps or from the planar faces +of a body with a horizontal base and no horizontal top. + +The schema-driven reader uses the owned compound structure of host types to populate `Element.Layers` in stored +order. It also resolves `Element.TypeId` for decoded reinforcement when the stored target is a rebar bar type. + ## Built-in identifiers `BuiltInCategory`, `BuiltInParameter`, `BuiltInParameterGroup`, `ParameterType`, `UnitType`, `DisplayUnitType`, diff --git a/docs/test-fixtures.md b/docs/test-fixtures.md index 5efb61b2..4c1fc459 100644 --- a/docs/test-fixtures.md +++ b/docs/test-fixtures.md @@ -48,6 +48,23 @@ needs no code of its own to skip. Tests that write diagnostic dumps write them t system temporary folder (`TestFiles.Scratch`), one folder per test process, so concurrent runs (both target frameworks of one `dotnet test`, or runs from other checkouts) never share a file; no test uses a fixed absolute path. +## Format corpus regression check + +Set `RVTIO_FORMAT_CORPUS` to a local JSON manifest and run the format corpus test. + +```sh +dotnet test tests/RvtIO.Tests/RvtIO.Tests.csproj -c Release -f net10.0 --filter FullyQualifiedName~FormatCorpusTests +``` + +The manifest contains one object per file with `path` (absolute or relative to the manifest), `sha256`, +`partitionStreams`, `pagedStreams`, `records`, `payloadBytes`, and `elemTableRows`. Take the stream and record +counts from a verified `rvtio coverage --report` run and the row count from the stored `Global/ElemTable`. +Keep the manifest with the local files and reuse it on later runs. Without the environment variable the test skips. +A configured manifest must be readable and contain at least one file. + +The test verifies the source hash, every partition boundary, paged stream inflation, exact walks, +record checksums, and the number of rows used by the production element table reader. + ## What runs without the private files With no private file at all, 10529 of the 10976 test cases run and pass on net8.0 and 447 are skipped (net10.0: 10533 of diff --git a/src/RvtIO/Geometry/BrepMeasures.cs b/src/RvtIO/Geometry/BrepMeasures.cs index d93d5def..53b21a0c 100644 --- a/src/RvtIO/Geometry/BrepMeasures.cs +++ b/src/RvtIO/Geometry/BrepMeasures.cs @@ -85,7 +85,8 @@ internal static double RingPerimeter(IReadOnlyList ring) } /// The shells of an element geometry (all faces as one shell when none are listed). - internal static List ShellsOfCurrent(GeometryData? geometry) + internal static List ShellsOfCurrent(GeometryData? geometry, + HashSet<(long X, long Y, long Z)>? splitVertices = null) { var result = new List(); if (geometry?.Faces is not { Count: > 0 } faces) return result; @@ -98,7 +99,8 @@ internal static List ShellsOfCurrent(GeometryData? geometry) // The signed volume needs every face wound the same way (outward); a closed shell that orients exactly is summed oriented. IReadOnlyList computationFaces = shellFaces; if (closed && shellFaces.Count >= 4 - && FacetedShell.TryOrientExactFacetedShell(shellFaces, Enumerable.Range(0, shellFaces.Count).ToList(), out var orientedShell, triangulateNonPlanarFaces: false)) + && FacetedShell.TryOrientExactFacetedShell(shellFaces, Enumerable.Range(0, shellFaces.Count).ToList(), + out var orientedShell, triangulateNonPlanarFaces: false, splitVertices)) computationFaces = orientedShell; foreach (var face in computationFaces) { diff --git a/src/RvtIO/Geometry/FacetedShell.cs b/src/RvtIO/Geometry/FacetedShell.cs index 21aad647..df98c046 100644 --- a/src/RvtIO/Geometry/FacetedShell.cs +++ b/src/RvtIO/Geometry/FacetedShell.cs @@ -1,3 +1,4 @@ +using System.Runtime.InteropServices; using RvtIO.Model; namespace RvtIO.Geometry; @@ -60,16 +61,17 @@ internal static bool FaceCollapsesAtIfcPrecision(GeoFace face) /// internal static bool TryOrientExactFacetedShell(IReadOnlyList faces, IReadOnlyCollection faceIndices, out List orientedFaces, - bool triangulateNonPlanarFaces) + bool triangulateNonPlanarFaces, HashSet<(long X, long Y, long Z)>? splitVertices = null) { orientedFaces = []; var indices = faceIndices.Distinct().Order().ToList(); if (indices.Count < 4 || indices.Any(index => (uint)index >= faces.Count)) return false; var normalizedFaces = new Dictionary(); + long edgeUseCount = 0; foreach (int faceIndex in indices) { - var normalized = CloneFace(faces[faceIndex], false); + var normalized = CloneFace(faces[faceIndex]); if (normalized.OuterVertices is not { Count: >= 3 } outer || outer.Any(point => point.Length < 3 || !double.IsFinite(point[0]) || !double.IsFinite(point[1]) @@ -90,18 +92,25 @@ internal static bool TryOrientExactFacetedShell(IReadOnlyList faces, .ToList(); if (!TryNormalizeInnerBounds(normalized)) return false; + edgeUseCount += normalized.OuterVertices.Count; + if (normalized.InnerVertices is { } holes) + foreach (var ring in holes) + edgeUseCount += ring.Count; normalizedFaces[faceIndex] = normalized; } - if (!TryGetFacetedAtomicEdgeUses(normalizedFaces, indices, out var edgeUses)) + // In a closed shell with matched loops, two incidences share each edge. + long closedEdgeCount = edgeUseCount / 2; + int initialCapacity = closedEdgeCount <= int.MaxValue ? (int)closedEdgeCount : 0; + if (!TryGetFacetedAtomicEdgeUses(normalizedFaces, indices, out var edgeUses, initialCapacity, splitVertices)) return false; var constraints = indices.ToDictionary(index => index, _ => new List<(int Other, bool OppositeFlip)>()); foreach (var uses in edgeUses.Values) { - bool oppositeFlip = uses[0].Direction == uses[1].Direction; - constraints[uses[0].FaceIndex].Add((uses[1].FaceIndex, oppositeFlip)); - constraints[uses[1].FaceIndex].Add((uses[0].FaceIndex, oppositeFlip)); + bool oppositeFlip = uses.First.Direction == uses.Second.Direction; + constraints[uses.First.FaceIndex].Add((uses.Second.FaceIndex, oppositeFlip)); + constraints[uses.Second.FaceIndex].Add((uses.First.FaceIndex, oppositeFlip)); } var flips = new Dictionary(); @@ -131,11 +140,16 @@ internal static bool TryOrientExactFacetedShell(IReadOnlyList faces, } } - orientedFaces = indices.Select(index => - CloneFace(normalizedFaces[index], flips[index])).ToList(); + orientedFaces = new List(indices.Count); + foreach (int index in indices) + { + var face = normalizedFaces[index]; + if (flips[index]) ReverseFace(face, detachVertices: false); + orientedFaces.Add(face); + } SplitFacetedLoopsAtSharedVertices(orientedFaces); var compactIndices = Enumerable.Range(0, orientedFaces.Count).ToList(); - if (!IsExactFacetedShell(orientedFaces, compactIndices)) + if (!IsExactFacetedShell(orientedFaces, compactIndices, edgeUses, splitVertices)) { orientedFaces = []; return false; @@ -159,13 +173,14 @@ internal static bool TryOrientExactFacetedShell(IReadOnlyList faces, return false; } if (signedVolume < 0) - orientedFaces = orientedFaces.Select(face => CloneFace(face, true)).ToList(); + foreach (var face in orientedFaces) + ReverseFace(face, detachVertices: true); if (!triangulateNonPlanarFaces) return true; var triangulatedFaces = TriangulateNonPlanarFacetedFaces(orientedFaces); SplitFacetedLoopsAtSharedVertices(triangulatedFaces); if (IsExactFacetedShell(triangulatedFaces, - Enumerable.Range(0, triangulatedFaces.Count).ToList())) + Enumerable.Range(0, triangulatedFaces.Count).ToList(), edgeUses, splitVertices)) orientedFaces = triangulatedFaces; return true; @@ -294,34 +309,56 @@ static bool TryNewellNormal(IReadOnlyList ring, && (x != 0 || y != 0 || z != 0); } - static List CleanPrecisionLoop(IEnumerable source) - { - var clean = new List(); - foreach (var point in source) - if (clean.Count == 0 - || IfcPrecisionKeyFeet(clean[^1]) != IfcPrecisionKeyFeet(point)) - clean.Add((double[])point.Clone()); - if (clean.Count > 1 - && IfcPrecisionKeyFeet(clean[0]) == IfcPrecisionKeyFeet(clean[^1])) - clean.RemoveAt(clean.Count - 1); - return clean; + static List CleanPrecisionLoop(List ring) + { + var first = IfcPrecisionKeyFeet(ring[0]); + var last = first; + int count = 1; + for (int index = 1; index < ring.Count; index++) + { + var point = ring[index]; + var key = IfcPrecisionKeyFeet(point); + if (last == key) continue; + if (count != index) ring[count] = point; + count++; + last = key; + } + if (count > 1 && first == last) count--; + ring.RemoveRange(count, ring.Count - count); + return ring; } - static GeoFace CloneFace(GeoFace source, bool reverse) + static void ReverseFace(GeoFace face, bool detachVertices) { - List CopyRing(IEnumerable ring) + ReverseRing(face.OuterVertices!); + if (face.InnerVertices is { } holes) + foreach (var ring in holes) + ReverseRing(ring); + var normal = face.Normal; + for (int i = 0; i < normal.Length; i++) + normal[i] = -normal[i]; + + void ReverseRing(List ring) { - var copy = ring.Select(point => (double[])point.Clone()).ToList(); - if (reverse) copy.Reverse(); - return copy; + ring.Reverse(); + // Splitting can insert a vertex array owned by a different face. + if (detachVertices) + for (int i = 0; i < ring.Count; i++) + ring[i] = (double[])ring[i].Clone(); } + } + + static GeoFace CloneFace(GeoFace source) + { + static List CopyRing(List ring) => + ring.Select(point => (double[])point.Clone()).ToList(); + return new GeoFace { Origin = (double[])source.Origin.Clone(), XVector = (double[])source.XVector.Clone(), YVector = (double[])source.YVector.Clone(), - Normal = reverse ? source.Normal.Select(value => -value).ToArray() - : (double[])source.Normal.Clone(), + Normal = (double[])source.Normal.Clone(), Envelope = source.Envelope is null ? null : (double[])source.Envelope.Clone(), Area = source.Area, InnerLoops = source.InnerLoops?.Select(loop => (double[])loop.Clone()).ToList(), @@ -511,43 +548,88 @@ static System.Numerics.BigInteger Turn((long U, long V) first, return result; } - /// - /// Materializes the same atomic edge partition used by shell validation in the actual polygon - /// loops written to IFC. - /// - private static void SplitFacetedLoopsAtSharedVertices(IReadOnlyList faces) + internal static (long X, long Y, long Z)[][] BuildVertexAxisIndex( + ICollection<(long X, long Y, long Z)> vertices) { - static long Axis((long X, long Y, long Z) point, int axis) => - axis == 0 ? point.X : axis == 1 ? point.Y : point.Z; - static int LowerBound(List<(long X, long Y, long Z)> points, int axis, long value) + var byX = vertices.ToArray(); + var byY = ((long X, long Y, long Z)[])byX.Clone(); + var byZ = ((long X, long Y, long Z)[])byX.Clone(); + Array.Sort(byX); + Array.Sort(byY, static (a, b) => (a.Y, a.X, a.Z).CompareTo((b.Y, b.X, b.Z))); + Array.Sort(byZ, static (a, b) => (a.Z, a.X, a.Y).CompareTo((b.Z, b.X, b.Y))); + return [byX, byY, byZ]; + } + + private static long Axis((long X, long Y, long Z) point, int axis) => + axis == 0 ? point.X : axis == 1 ? point.Y : point.Z; + + private static int AxisBound((long X, long Y, long Z)[] points, int axis, long value, bool afterEqual) + { + int low = 0, high = points.Length; + while (low < high) { - int low = 0, high = points.Count; - while (low < high) - { - int middle = low + (high - low) / 2; - if (Axis(points[middle], axis) < value) low = middle + 1; - else high = middle; - } - return low; + int middle = low + (high - low) / 2; + long coordinate = Axis(points[middle], axis); + if (coordinate < value || (afterEqual && coordinate == value)) low = middle + 1; + else high = middle; + } + return low; + } + + internal readonly struct LatticeSegment + { + private readonly (long X, long Y, long Z) _first; + private readonly (long X, long Y, long Z) _min; + private readonly (long X, long Y, long Z) _max; + private readonly Int128 _dx, _dy, _dz; + private readonly bool _axisAligned; + private readonly bool _fitsLongProducts; + + internal int DominantAxis { get; } + + internal LatticeSegment((long X, long Y, long Z) first, (long X, long Y, long Z) second) + { + _first = first; + _min = (Math.Min(first.X, second.X), Math.Min(first.Y, second.Y), Math.Min(first.Z, second.Z)); + _max = (Math.Max(first.X, second.X), Math.Max(first.Y, second.Y), Math.Max(first.Z, second.Z)); + _dx = (Int128)second.X - first.X; + _dy = (Int128)second.Y - first.Y; + _dz = (Int128)second.Z - first.Z; + Int128 absX = Int128.Abs(_dx), absY = Int128.Abs(_dy), absZ = Int128.Abs(_dz); + DominantAxis = absX >= absY && absX >= absZ ? 0 : absY >= absZ ? 1 : 2; + _axisAligned = first.X == second.X + ? first.Y == second.Y || first.Z == second.Z + : first.Y == second.Y && first.Z == second.Z; + _fitsLongProducts = absX <= int.MaxValue && absY <= int.MaxValue && absZ <= int.MaxValue; } - static bool OnSegment((long X, long Y, long Z) point, - (long X, long Y, long Z) first, (long X, long Y, long Z) second) + + internal bool OnSegment((long X, long Y, long Z) point) { - if (point.X < Math.Min(first.X, second.X) || point.X > Math.Max(first.X, second.X) - || point.Y < Math.Min(first.Y, second.Y) || point.Y > Math.Max(first.Y, second.Y) - || point.Z < Math.Min(first.Z, second.Z) || point.Z > Math.Max(first.Z, second.Z)) + if (point.X < _min.X || point.X > _max.X || point.Y < _min.Y || point.Y > _max.Y + || point.Z < _min.Z || point.Z > _max.Z) return false; - Int128 dx = (Int128)second.X - first.X; - Int128 dy = (Int128)second.Y - first.Y; - Int128 dz = (Int128)second.Z - first.Z; - Int128 px = (Int128)point.X - first.X; - Int128 py = (Int128)point.Y - first.Y; - Int128 pz = (Int128)point.Z - first.Z; - return dy * pz - dz * py == 0 - && dz * px - dx * pz == 0 - && dx * py - dy * px == 0; + if (_axisAligned) return true; + if (_fitsLongProducts) + { + // The bounds also limit each point offset to the signed 32-bit span. + long x = point.X - _first.X, y = point.Y - _first.Y, z = point.Z - _first.Z; + return (long)_dy * z == (long)_dz * y + && (long)_dz * x == (long)_dx * z + && (long)_dx * y == (long)_dy * x; + } + Int128 px = (Int128)point.X - _first.X; + Int128 py = (Int128)point.Y - _first.Y; + Int128 pz = (Int128)point.Z - _first.Z; + return _dy * pz == _dz * py && _dz * px == _dx * pz && _dx * py == _dy * px; } + } + /// + /// Materializes the same atomic edge partition used by shell validation in the actual polygon + /// loops written to IFC. + /// + private static void SplitFacetedLoopsAtSharedVertices(IReadOnlyList faces) + { var representative = new Dictionary<(long X, long Y, long Z), double[]>(); foreach (var face in faces) foreach (var ring in (face.OuterVertices is { Count: > 0 } outer @@ -556,50 +638,48 @@ static bool OnSegment((long X, long Y, long Z) point, .Concat(face.InnerVertices ?? [])) foreach (var point in ring) representative.TryAdd(IfcPrecisionKeyFeet(point), point); - var vertices = representative.Keys.ToList(); - var verticesByAxis = Enumerable.Range(0, 3) - .Select(axis => vertices.OrderBy(point => Axis(point, axis)) - .ThenBy(point => point.X).ThenBy(point => point.Y).ThenBy(point => point.Z) - .ToList()).ToArray(); + var verticesByAxis = BuildVertexAxisIndex(representative.Keys); List Split(IReadOnlyList ring) { - var result = new List(); + var result = new List(ring.Count); + if (ring.Count == 0) return result; + var start = IfcPrecisionKeyFeet(ring[0]); + var second = start; + var last = start; for (int edgeIndex = 0; edgeIndex < ring.Count; edgeIndex++) { - var sourceFirst = ring[edgeIndex]; - var sourceSecond = ring[(edgeIndex + 1) % ring.Count]; - var first = IfcPrecisionKeyFeet(sourceFirst); - var second = IfcPrecisionKeyFeet(sourceSecond); - result.Add(sourceFirst); + var first = second; + int nextIndex = edgeIndex + 1; + second = nextIndex < ring.Count ? IfcPrecisionKeyFeet(ring[nextIndex]) : start; + Append(ring[edgeIndex], first); if (first == second) continue; - Int128 dx = (Int128)second.X - first.X; - Int128 dy = (Int128)second.Y - first.Y; - Int128 dz = (Int128)second.Z - first.Z; - Int128 absX = Int128.Abs(dx), absY = Int128.Abs(dy), absZ = Int128.Abs(dz); - int axis = absX >= absY && absX >= absZ ? 0 : absY >= absZ ? 1 : 2; - long low = Math.Min(Axis(first, axis), Axis(second, axis)); - long high = Math.Max(Axis(first, axis), Axis(second, axis)); - var split = new List<(long X, long Y, long Z)>(); + var segment = new LatticeSegment(first, second); + int axis = segment.DominantAxis; + long from = Axis(first, axis), to = Axis(second, axis); + bool forward = from < to; var sorted = verticesByAxis[axis]; - for (int index = LowerBound(sorted, axis, low); - index < sorted.Count && Axis(sorted[index], axis) <= high; index++) - if (sorted[index] != first && sorted[index] != second - && OnSegment(sorted[index], first, second)) - split.Add(sorted[index]); - split.Sort((left, right) => Axis(left, axis).CompareTo(Axis(right, axis))); - if (Axis(first, axis) > Axis(second, axis)) split.Reverse(); - result.AddRange(split.Select(point => representative[point])); + int index = AxisBound(sorted, axis, from, afterEqual: !forward) - (forward ? 0 : 1); + int step = forward ? 1 : -1; + // Along a segment the dominant coordinate uniquely orders its collinear vertices. + for (; (uint)index < (uint)sorted.Length; index += step) + { + var point = sorted[index]; + long coordinate = Axis(point, axis); + if (forward ? coordinate > to : coordinate < to) break; + if (point != first && point != second && segment.OnSegment(point)) + Append(representative[point], point); + } + } + if (result.Count > 1 && start == last) result.RemoveAt(result.Count - 1); + return result; + + void Append(double[] point, (long X, long Y, long Z) key) + { + if (result.Count != 0 && last == key) return; + result.Add(point); + last = key; } - var clean = new List(); - foreach (var point in result) - if (clean.Count == 0 - || IfcPrecisionKeyFeet(clean[^1]) != IfcPrecisionKeyFeet(point)) - clean.Add(point); - if (clean.Count > 1 - && IfcPrecisionKeyFeet(clean[0]) == IfcPrecisionKeyFeet(clean[^1])) - clean.RemoveAt(clean.Count - 1); - return clean; } foreach (var face in faces) @@ -611,122 +691,137 @@ List Split(IReadOnlyList ring) } } + internal struct EdgeUses + { + private List<(int FaceIndex, int Direction)>? _overflow; + internal (int FaceIndex, int Direction) First { get; private set; } + internal (int FaceIndex, int Direction) Second { get; private set; } + + // Valid directions are ±1, leaving zero for an unused slot. + internal readonly int Count => Second.Direction != 0 + ? 2 + (_overflow?.Count ?? 0) + : First.Direction != 0 ? 1 : 0; + + internal readonly (int FaceIndex, int Direction) this[int index] => index switch + { + 0 when First.Direction != 0 => First, + 1 when Second.Direction != 0 => Second, + >= 2 when _overflow != null => _overflow[index - 2], + _ => throw new ArgumentOutOfRangeException(nameof(index)), + }; + + internal void Add((int FaceIndex, int Direction) use) + { + if (First.Direction == 0) First = use; + else if (Second.Direction == 0) Second = use; + else (_overflow ??= []).Add(use); + } + } + /// Builds exact shared-edge uses on the serialized IFC coordinate lattice. internal static bool TryGetFacetedAtomicEdgeUses(IReadOnlyDictionary faces, IReadOnlyCollection faceIndices, - out Dictionary<((long X, long Y, long Z) A, (long X, long Y, long Z) B), - List<(int FaceIndex, int Direction)>> edgeUses) + out Dictionary<((long X, long Y, long Z) A, (long X, long Y, long Z) B), EdgeUses> edgeUses, + int initialCapacity = 0, HashSet<(long X, long Y, long Z)>? splitVertices = null) { - static ((long X, long Y, long Z) A, (long X, long Y, long Z) B) EdgeKey( - (long X, long Y, long Z) first, (long X, long Y, long Z) second) - => first.CompareTo(second) <= 0 ? (first, second) : (second, first); - static long Axis((long X, long Y, long Z) point, int axis) => - axis == 0 ? point.X : axis == 1 ? point.Y : point.Z; - static int LowerBound(List<(long X, long Y, long Z)> points, int axis, long value) - { - int low = 0, high = points.Count; - while (low < high) - { - int middle = low + (high - low) / 2; - if (Axis(points[middle], axis) < value) low = middle + 1; - else high = middle; - } - return low; - } - static bool OnSegment((long X, long Y, long Z) point, - (long X, long Y, long Z) first, (long X, long Y, long Z) second) + edgeUses = new(initialCapacity); + return TryGetFacetedAtomicEdgeUses(faces, faceIndices, edgeUses, splitVertices); + } + + private static bool TryGetFacetedAtomicEdgeUses(IReadOnlyDictionary faces, + IReadOnlyCollection faceIndices, + Dictionary<((long X, long Y, long Z) A, (long X, long Y, long Z) B), EdgeUses> usesByEdge, + HashSet<(long X, long Y, long Z)>? splitVertices) + { + usesByEdge.Clear(); + (long X, long Y, long Z)[][]? verticesByAxis = null; + if (!BuildEdgeUses()) { - if (point.X < Math.Min(first.X, second.X) || point.X > Math.Max(first.X, second.X) - || point.Y < Math.Min(first.Y, second.Y) || point.Y > Math.Max(first.Y, second.Y) - || point.Z < Math.Min(first.Z, second.Z) || point.Z > Math.Max(first.Z, second.Z)) - return false; - Int128 dx = (Int128)second.X - first.X; - Int128 dy = (Int128)second.Y - first.Y; - Int128 dz = (Int128)second.Z - first.Z; - Int128 px = (Int128)point.X - first.X; - Int128 py = (Int128)point.Y - first.Y; - Int128 pz = (Int128)point.Z - first.Z; - return dy * pz - dz * py == 0 - && dz * px - dx * pz == 0 - && dx * py - dy * px == 0; + usesByEdge.Clear(); + return false; } + if (usesByEdge.Count == 0) return false; + if (HasClosedMultiplicity()) return true; - var usesByEdge = new Dictionary< - ((long X, long Y, long Z) A, (long X, long Y, long Z) B), - List<(int FaceIndex, int Direction)>>(); - edgeUses = usesByEdge; - var segments = new List<(int FaceIndex, (long X, long Y, long Z) First, - (long X, long Y, long Z) Second)>(); - foreach (int faceIndex in faceIndices) + var vertices = splitVertices ?? new HashSet<(long X, long Y, long Z)>(); + vertices.Clear(); + foreach (var (first, second) in usesByEdge.Keys) { - if (!faces.TryGetValue(faceIndex, out var face) - || face.OuterVertices is not { Count: >= 3 } outer) - return false; - IEnumerable> rings = - new[] { (IReadOnlyList)outer } - .Concat(face.InnerVertices ?? Enumerable.Empty>()); - foreach (var ring in rings) - { - if (ring.Count < 3 || ring.Any(point => point.Length < 3 - || !double.IsFinite(point[0]) || !double.IsFinite(point[1]) - || !double.IsFinite(point[2]))) - return false; - for (int index = 0; index < ring.Count; index++) - { - var first = IfcPrecisionKeyFeet(ring[index]); - var second = IfcPrecisionKeyFeet(ring[(index + 1) % ring.Count]); - if (first == second) return false; - segments.Add((faceIndex, first, second)); - } - } + vertices.Add(first); + vertices.Add(second); } - if (segments.Count == 0) return false; + verticesByAxis = BuildVertexAxisIndex(vertices); + usesByEdge.Clear(); + return BuildEdgeUses() && HasClosedMultiplicity(); void AddUse(int faceIndex, (long X, long Y, long Z) first, (long X, long Y, long Z) second) { - var edge = EdgeKey(first, second); - if (!usesByEdge.TryGetValue(edge, out var uses)) usesByEdge[edge] = uses = []; - uses.Add((faceIndex, first.CompareTo(second) <= 0 ? 1 : -1)); + bool forward = first.CompareTo(second) <= 0; + var edge = forward ? (first, second) : (second, first); + ref var uses = ref CollectionsMarshal.GetValueRefOrAddDefault(usesByEdge, edge, out _); + uses.Add((faceIndex, forward ? 1 : -1)); } bool HasClosedMultiplicity() => usesByEdge.Count > 0 && usesByEdge.Values.All(uses => uses.Count == 2 - && uses[0].FaceIndex != uses[1].FaceIndex); + && uses.First.FaceIndex != uses.Second.FaceIndex); - foreach (var segment in segments) - AddUse(segment.FaceIndex, segment.First, segment.Second); - if (HasClosedMultiplicity()) return true; + bool BuildEdgeUses() + { + foreach (int faceIndex in faceIndices) + { + if (!faces.TryGetValue(faceIndex, out var face) + || face.OuterVertices is not { } outer || !AddRingUses(outer, faceIndex)) + return false; + if (face.InnerVertices is { } holes) + foreach (var ring in holes) + if (!AddRingUses(ring, faceIndex)) return false; + } + return true; + } - usesByEdge.Clear(); - var vertices = segments.SelectMany(segment => new[] { segment.First, segment.Second }) - .Distinct().ToList(); - var verticesByAxis = Enumerable.Range(0, 3) - .Select(axis => vertices.OrderBy(point => Axis(point, axis)) - .ThenBy(point => point.X).ThenBy(point => point.Y).ThenBy(point => point.Z) - .ToList()) - .ToArray(); - foreach (var segment in segments) - { - Int128 dx = (Int128)segment.Second.X - segment.First.X; - Int128 dy = (Int128)segment.Second.Y - segment.First.Y; - Int128 dz = (Int128)segment.Second.Z - segment.First.Z; - Int128 absX = Int128.Abs(dx), absY = Int128.Abs(dy), absZ = Int128.Abs(dz); - int axis = absX >= absY && absX >= absZ ? 0 : absY >= absZ ? 1 : 2; - long low = Math.Min(Axis(segment.First, axis), Axis(segment.Second, axis)); - long high = Math.Max(Axis(segment.First, axis), Axis(segment.Second, axis)); - var sorted = verticesByAxis[axis]; - var split = new List<(long X, long Y, long Z)>(); - for (int index = LowerBound(sorted, axis, low); - index < sorted.Count && Axis(sorted[index], axis) <= high; index++) - if (OnSegment(sorted[index], segment.First, segment.Second)) - split.Add(sorted[index]); - if (Axis(segment.First, axis) > Axis(segment.Second, axis)) split.Reverse(); - if (split.Count < 2 || split[0] != segment.First || split[^1] != segment.Second) + bool AddRingUses(List ring, int faceIndex) + { + if (ring.Count < 3 || verticesByAxis is null && ring.Any(point => point.Length < 3 + || !double.IsFinite(point[0]) || !double.IsFinite(point[1]) + || !double.IsFinite(point[2]))) return false; - for (int index = 0; index + 1 < split.Count; index++) - AddUse(segment.FaceIndex, split[index], split[index + 1]); + var start = IfcPrecisionKeyFeet(ring[0]); + var first = start; + for (int index = 1; index <= ring.Count; index++) + { + var second = index < ring.Count ? IfcPrecisionKeyFeet(ring[index]) : start; + if (first == second) return false; + if (verticesByAxis is null) AddUse(faceIndex, first, second); + else AddSplitUses(faceIndex, first, second, verticesByAxis); + first = second; + } + return true; + } + + void AddSplitUses(int faceIndex, (long X, long Y, long Z) first, + (long X, long Y, long Z) second, (long X, long Y, long Z)[][] byAxis) + { + var segment = new LatticeSegment(first, second); + int axis = segment.DominantAxis; + long from = Axis(first, axis), to = Axis(second, axis); + bool forward = from < to; + var sorted = byAxis[axis]; + int index = AxisBound(sorted, axis, from, afterEqual: forward) - (forward ? 0 : 1); + int step = forward ? 1 : -1; + var previous = first; + // Both endpoints are in the index from the validated first pass. + for (; (uint)index < (uint)sorted.Length; index += step) + { + var point = sorted[index]; + long coordinate = Axis(point, axis); + if (forward ? coordinate >= to : coordinate <= to) break; + if (!segment.OnSegment(point)) continue; + AddUse(faceIndex, previous, point); + previous = point; + } + AddUse(faceIndex, previous, second); } - return HasClosedMultiplicity(); } /// @@ -734,14 +829,20 @@ bool HasClosedMultiplicity() => usesByEdge.Count > 0 /// declared-precision identity as the IFC point cache. /// internal static bool IsExactFacetedShell( - IReadOnlyList faces, IReadOnlyCollection faceIndices) + IReadOnlyList faces, IReadOnlyCollection faceIndices) => + IsExactFacetedShell(faces, faceIndices, new()); + + private static bool IsExactFacetedShell( + IReadOnlyList faces, IReadOnlyCollection faceIndices, + Dictionary<((long X, long Y, long Z) A, (long X, long Y, long Z) B), EdgeUses> edgeUses, + HashSet<(long X, long Y, long Z)>? splitVertices = null) { var faceMap = faceIndices.Distinct().ToDictionary(index => index, index => (uint)index < faces.Count ? faces[index] : null); if (faceMap.Values.Any(face => face == null)) return false; return TryGetFacetedAtomicEdgeUses( faceMap.ToDictionary(pair => pair.Key, pair => pair.Value!), - faceIndices, out var edgeUses) - && edgeUses.Values.All(uses => uses[0].Direction + uses[1].Direction == 0); + faceIndices, edgeUses, splitVertices) + && edgeUses.Values.All(uses => uses.First.Direction + uses.Second.Direction == 0); } } diff --git a/src/RvtIO/Geometry/Meshing/ConformingDelaunay.cs b/src/RvtIO/Geometry/Meshing/ConformingDelaunay.cs new file mode 100644 index 00000000..5a6f4403 --- /dev/null +++ b/src/RvtIO/Geometry/Meshing/ConformingDelaunay.cs @@ -0,0 +1,387 @@ +namespace RvtIO.Geometry.Meshing; + +internal readonly record struct TriangulationEdge(int A, int B) +{ + internal static TriangulationEdge Of(int a, int b) => a < b ? new(a, b) : new(b, a); +} + +internal sealed class ConformingDelaunay +{ + private sealed class Cell + { + internal int[] V { get; } = new int[3]; + internal bool Live; + } + + private readonly record struct Side(Cell Cell, int I) + { + internal int A => Cell.V[I]; + internal int B => Cell.V[(I + 1) % 3]; + internal int C => Cell.V[(I + 2) % 3]; + internal Side Next => new(Cell, (I + 1) % 3); + internal Side Back => new(Cell, (I + 2) % 3); + internal TriangulationEdge Edge => TriangulationEdge.Of(A, B); + internal void Set(int a, int b, int c) + { + Cell.V[I] = a; + Cell.V[(I + 1) % 3] = b; + Cell.V[(I + 2) % 3] = c; + } + } + + // Validate by oriented slot and vertex identities. A cancelled site can be followed by a + // boundary split that reuses those identities, making a previously queued test valid again. + private readonly record struct Candidate(Side Side, int A, int B, int C) + { + internal bool Matches => Side.Cell.Live && A == Side.A && B == Side.B && C == Side.C; + } + + // Repair competing boundary edges in slot order. New entries can reuse an earlier slot. + private sealed class BoundaryWork + { + private readonly List slots = []; + private readonly Stack free = []; + internal int Count { get; private set; } + + internal void Add(TriangulationEdge edge) + { + if (free.TryPop(out int index)) slots[index] = edge; + else slots.Add(edge); + Count++; + } + + internal IEnumerable Sweep() + { + for (int i = 0; i < slots.Count; i++) + { + if (slots[i] is not TriangulationEdge edge) continue; + yield return edge; + slots[i] = null; + free.Push(i); + Count--; + } + } + } + + private readonly List points; + private readonly List cells = []; + private readonly Stack free = []; + private readonly Dictionary> adjacency = []; + private readonly List boundary = []; + private readonly HashSet constrained = []; + private readonly PriorityQueue bad = new(); + private readonly UvPoint limits; + private int sequence; + private bool refining; + + + internal UvPoint[] Points => points.ToArray(); + internal int[][] Faces => cells.Where(c => c.Live).Select(c => c.V.ToArray()).ToArray(); + + internal ConformingDelaunay(UvPoint[] ring, UvPoint limits) + { + this.limits = limits; + points = [.. ring]; + for (int i = 0; i < ring.Length; i++) RecordBoundary(TriangulationEdge.Of(i, (i + 1) % ring.Length)); + foreach (var tri in DelaunaySeed.Compute(ring)) Create(tri[0], tri[1], tri[2]); + if (cells.Count != ring.Length - 2 || constrained.Any(e => !adjacency.TryGetValue(e, out var a) || a.Count != 1)) + throw new InvalidDataException("Seed does not cover an isolated simple contour."); + + } + + private void RecordBoundary(TriangulationEdge e) { boundary.Add(e); constrained.Add(e); } + + private static IEnumerable Around(Cell c) + { + for (int i = 0; i < 3; i++) yield return new(c, i); + } + + private void Attach(Cell cell) + { + foreach (var side in Around(cell)) + { + if (!adjacency.TryGetValue(side.Edge, out var ring)) adjacency.Add(side.Edge, ring = []); + ring.Add(side); + } + } + private void Detach(Cell cell) + { + foreach (var side in Around(cell)) + { + var ring = adjacency[side.Edge]; + ring.Remove(side); + if (ring.Count == 0) adjacency.Remove(side.Edge); + } + } + private Side? Across(Side edge) + { + if (!adjacency.TryGetValue(edge.Edge, out var ring)) throw new InvalidDataException("Missing facet adjacency."); + if (ring.Count == 1) return null; + if (ring.Count != 2) throw new InvalidDataException("Nonmanifold facet."); + return ring[0].Cell == edge.Cell ? ring[1] : ring[0]; + } + + private Side Create(int a, int b, int c) + { + Cell o; + if (!free.TryPop(out o!)) { o = new(); cells.Add(o); } + o.Live = true; + var side = new Side(o, 0); + side.Set(a, b, c); + Attach(o); + return side; + } + private void Replace(Side side, int a, int b, int c) + { + Detach(side.Cell); + side.Set(a, b, c); + Attach(side.Cell); + } + private void Deallocate(Cell cell) + { + Detach(cell); + cell.Live = false; + free.Push(cell); + } + + private void Flip(Side seam, Side outer) + { + int a = seam.A, b = seam.B, p = seam.C, c = outer.C; + Detach(seam.Cell); Detach(outer.Cell); + seam.Set(c, p, a); + outer.Set(p, c, b); + Attach(seam.Cell); Attach(outer.Cell); + } + + private double Orientation(int a, int b, UvPoint p) => PlanarPredicates.Orientation(points[a], points[b], p); + private bool Encroaches(UvPoint p, TriangulationEdge e) => (p - points[e.A]).Dot(p - points[e.B]) < 0; + private double SideLength(Side h) => (points[h.A] - points[h.B]).LengthSquared; + + private void QueueIfWide(Side side) + { + UvPoint a = points[side.A], b = points[side.B], c = points[side.C]; + double u = Math.Max(a.X, Math.Max(b.X, c.X)) - Math.Min(a.X, Math.Min(b.X, c.X)); + double v = Math.Max(a.Y, Math.Max(b.Y, c.Y)) - Math.Min(a.Y, Math.Min(b.Y, c.Y)); + if (u <= limits.X && v <= limits.Y) return; + var shortEdge = Shortest(side); + var e = points[shortEdge.A] - points[shortEdge.C]; + var f = points[shortEdge.B] - points[shortEdge.C]; + double dot = e.Dot(f); + double ratio = constrained.Contains(shortEdge.Next.Edge) && constrained.Contains(shortEdge.Back.Edge) + ? 0 : dot * dot / (e.LengthSquared * f.LengthSquared); + int k = Math.Clamp((int)((ratio - 0.6) * 160), 0, 63); + bad.Enqueue(new(side, side.A, side.B, side.C), (-k, sequence++)); + } + + private Side Shortest(Side e) + { + double x = SideLength(e), y = SideLength(e.Next), z = SideLength(e.Back); + if (y < x && y < z) return e.Next; + return x < z ? e : e.Back; + } + + private (Side Seat, bool Outside) Locate(Side start, UvPoint p) + { + var side = start; + for (int remaining = cells.Count; remaining > 0; remaining--) + { + int a = side.A, b = side.B, c = side.C; + double left = Orientation(a, c, p), right = Orientation(c, b, p); + if (left <= 0 && right <= 0) + return (left == 0 ? side.Back : right == 0 ? side.Next : side, false); + bool chooseLeft = left > 0 && (right <= 0 || (points[c] - p).Dot(points[b] - points[a]) > 0); + var wall = chooseLeft ? side.Back : side.Next; + var other = Across(wall); + if (other is null) return (wall, true); + side = other.Value; + } + throw new InvalidDataException("Point location failed."); + } + + private UvPoint Circumcenter(Side side) + { + UvPoint a = points[side.A], b = points[side.B], c = points[side.C], d = b - a, e = c - a; + double half = 0.5 / PlanarPredicates.Orientation(b, c, a); + return new(a.X - (d.Y * e.LengthSquared - e.Y * d.LengthSquared) * half, + a.Y + (d.X * e.LengthSquared - e.X * d.LengthSquared) * half); + } + + private Side Insert(Side seat, int index, bool onEdge, BoundaryWork encroached) + { + int a = seat.A, b = seat.B, c = seat.C; + Side walk; + if (!onEdge) + { + Replace(seat, a, b, index); + Create(b, c, index); + Create(c, a, index); + walk = seat; + } + else + { + var opposite = Across(seat); + if (opposite is { } other) + { + int d = other.C; + Replace(other.Next, index, d, b); + Create(a, d, index); + } + Replace(seat, index, b, c); + Create(c, a, index); + walk = seat.Next; + } + + int first = walk.A; + for (int remaining = cells.Count * 8; remaining > 0; remaining--) + { + var far = Across(walk); + if (constrained.Contains(walk.Edge)) + { + if (Encroaches(points[index], walk.Edge)) encroached.Add(walk.Edge); + } + else if (far is { } f && + PlanarPredicates.Disk(points[walk.A], points[walk.B], points[index], points[f.C]) > 0) + { + Flip(walk, f); + walk = walk.Back; + continue; + } + if (refining) QueueIfWide(walk); + var next = Across(walk.Next); + if (walk.B == first || next == null) + return walk.Back; + walk = next.Value.Next; + } + throw new InvalidDataException("Edge legalization failed."); + } + + private void DeleteSite(Side del) + { + int center = del.A; + Side first = Across(del.Back) ?? throw new InvalidDataException("Open cancellation polygon."); + var fan = new List(); + Side current = first; + do + { + if (current.A != center) throw new InvalidDataException("Open cancellation polygon."); + fan.Add(current); + current = Across(current.Back) ?? throw new InvalidDataException("Open cancellation polygon."); + } while (current != del && fan.Count <= 256); + if (current != del || fan.Count is < 2 or > 256) throw new InvalidDataException("Invalid cancellation polygon."); + var rim = fan.Select(a => a.B).Append(fan[^1].C).ToArray(); + var (right, left, pivot) = Fill(0, rim.Length - 1, false); + Replace(del, pivot, del.B, del.C); + Deallocate(right.Cell); + Deallocate(left.Cell); + QueueIfWide(del); + + (Side Right, Side Left, int Pivot) Fill(int from, int to, bool flip) + { + if (to == from + 1) return (fan[from], default, -1); + int a = rim[from], b = rim[to], k = from + 1; + for (int i = k + 1; i < to; i++) + if (PlanarPredicates.Disk(points[b], points[a], points[rim[k]], points[rim[i]]) > 0) k = i; + var left = Fill(from, k, true).Right; + var right = Fill(k, to, true).Right; + if (!flip) return (right, left, rim[k]); + Flip(right, left.Back); + QueueIfWide(left.Back); + return (right.Back, default, rim[k]); + } + } + + private void Split(TriangulationEdge edge, BoundaryWork encroached) + { + if (!constrained.Contains(edge)) return; + if (!adjacency.TryGetValue(edge, out var incident) || incident.Count != 1) throw new InvalidDataException("Invalid boundary edge."); + var wall = incident[0]; + UvPoint a = points[wall.A], b = points[wall.B]; + bool nearA = constrained.Contains(wall.Back.Edge), nearB = constrained.Contains(wall.Next.Edge); + double ratio = 0.5; + if (nearA != nearB) + { + double length = Math.Sqrt((b - a).LengthSquared); + double scale = Math.ScaleB(1.0, (int)Math.Floor(Math.Log2(length) + 0.5) - 1); + ratio = nearA ? scale / length : 1 - scale / length; + } + // Use the boundary direction, opposite the incident triangle. + double reverse = 1 - ratio; + var p = b * (1 - reverse) + a * reverse; + if (!double.IsFinite(p.X) || !double.IsFinite(p.Y) || p == a || p == b) + throw new InvalidDataException("Degenerate boundary split."); + int n = points.Count, slot = boundary.IndexOf(edge); + int head = wall.A, tail = wall.B; + points.Add(p); + constrained.Remove(edge); + var unchanged = TriangulationEdge.Of(n, tail); + constrained.Add(unchanged); + boundary[slot] = unchanged; + RecordBoundary(TriangulationEdge.Of(head, n)); + Insert(wall, n, true, encroached); + } + + internal void Refine() + { + var encroached = new BoundaryWork(); + foreach (var edge in boundary) + if (adjacency[edge].Any(s => Encroaches(points[s.C], edge))) encroached.Add(edge); + RepairBoundary(); + refining = true; + foreach (var c in cells) + if (c.Live) QueueIfWide(new(c, 0)); + int attempts = 0; + while (bad.TryDequeue(out var candidate, out _)) + { + if (++attempts > 250000) throw new InvalidDataException("Refinement queue did not converge."); + if (!candidate.Matches) continue; + if (points.Count > 12000) throw new InvalidDataException("Too many inserted vertices."); + var t = candidate.Side; + var p = Circumcenter(t); + if (!double.IsFinite(p.X) || !double.IsFinite(p.Y) || p == points[t.A] || p == points[t.B] || p == points[t.C]) + throw new InvalidDataException("Degenerate circumcenter."); + var (seat, outside) = Locate(Shortest(t), p); + bool onEdge = Orientation(seat.A, seat.B, p) == 0; + if ((outside || onEdge) && constrained.Contains(seat.Edge)) + { + encroached.Add(seat.Edge); + RepairBoundary(); + continue; + } + if (outside) throw new InvalidDataException("Unbounded circumcenter."); + int count = points.Count; + points.Add(p); + var placed = Insert(seat, count, onEdge, encroached); + bool accepted = encroached.Count == 0; + if (!accepted) + { + DeleteSite(placed); + points.RemoveAt(count); + RepairBoundary(); + } + } + void RepairBoundary() + { + while (encroached.Count > 0) + { + foreach (var edge in encroached.Sweep()) + { + if (points.Count > 12000) throw new InvalidDataException("Too many boundary vertices."); + Split(edge, encroached); + } + } + } + } +} + + + +internal readonly record struct UvPoint(double X, double Y) +{ + public static UvPoint operator +(UvPoint a, UvPoint b) => new(a.X + b.X, a.Y + b.Y); + public static UvPoint operator -(UvPoint a, UvPoint b) => new(a.X - b.X, a.Y - b.Y); + public static UvPoint operator *(UvPoint a, double k) => new(a.X * k, a.Y * k); + internal double Dot(UvPoint b) => X * b.X + Y * b.Y; + internal double Cross(UvPoint b) => X * b.Y - Y * b.X; + internal double LengthSquared => Dot(this); + internal bool IsFinite => double.IsFinite(X) && double.IsFinite(Y); +} diff --git a/src/RvtIO/Geometry/Meshing/DelaunaySeed.cs b/src/RvtIO/Geometry/Meshing/DelaunaySeed.cs new file mode 100644 index 00000000..061c2872 --- /dev/null +++ b/src/RvtIO/Geometry/Meshing/DelaunaySeed.cs @@ -0,0 +1,236 @@ +namespace RvtIO.Geometry.Meshing; + +// Divide and conquer on the planar input. Each hull has a fan to a virtual +// vertex. Slots stay fixed as a merge consumes a hull edge. +internal sealed class DelaunaySeed +{ + private const int Infinity = -1; + private readonly UvPoint[] points; + private readonly List slots = []; + + private sealed class Triangle(int a, int b, int c) + { + internal int[] Vertices { get; } = [a, b, c]; + internal EdgeRef[] Flat { get; } = new EdgeRef[3]; + } + + private readonly record struct EdgeRef(Triangle Cell, int Side) + { + internal EdgeRef Next => new(Cell, (Side + 1) % 3); + internal EdgeRef Back => new(Cell, (Side + 2) % 3); + internal EdgeRef Across => Cell.Flat[Side]; + internal int A => Cell.Vertices[Side]; + internal int B => Cell.Vertices[(Side + 1) % 3]; + internal int C => Cell.Vertices[(Side + 2) % 3]; + internal void Write(int a, int b, int c) + { + Cell.Vertices[Side] = a; + Cell.Vertices[(Side + 1) % 3] = b; + Cell.Vertices[(Side + 2) % 3] = c; + } + internal void Pair(EdgeRef b) + { + Cell.Flat[Side] = b; + b.Cell.Flat[b.Side] = this; + } + } + + private DelaunaySeed(UvPoint[] points) => this.points = points; + internal static int[][] Compute(UvPoint[] points) + { + var plan = new DelaunaySeed(points); + var hull = Enumerable.Range(0, points.Length).ToArray(); + plan.Partition(hull, 0); + var seed = plan.slots.Where(t => t.Vertices.All(v => v >= 0) && plan.Inside(t.Vertices)) + .Select(t => t.Vertices).ToArray(); + return seed; + } + + private static IEnumerable HalfEdges(Triangle t) => + Enumerable.Range(0, 3).Select(i => new EdgeRef(t, i)); + + private double Turn(int a, int b, int c) => + (points[b] - points[a]).Cross(points[c] - points[a]); + private double Disk(int a, int b, int c, int d) + { + var x = points[a] - points[d]; var y = points[b] - points[d]; var z = points[c] - points[d]; + return x.LengthSquared * y.Cross(z) + y.LengthSquared * z.Cross(x) + z.LengthSquared * x.Cross(y); + } + + private EdgeRef Slot(int a = Infinity, int b = Infinity, int c = Infinity) + { + var triangle = new Triangle(a, b, c); + slots.Add(triangle); + return new(triangle, 0); + } + + private void PairLeaf(int first) + { + var sides = slots.Skip(first).SelectMany(HalfEdges).ToArray(); + foreach (var arc in sides) + { + if (arc.Across.Cell != null) continue; + var otherSides = sides.Where(other => other.Cell != arc.Cell && other.A == arc.B && other.B == arc.A).ToArray(); + if (otherSides.Length != 1) throw new InvalidDataException("Invalid seed hull."); + var inverse = otherSides[0]; + arc.Pair(inverse); + } + } + + private void Partition(int[] p, int axis) + { + int start = slots.Count; + if (p.Length <= 3) + { + p = p.OrderBy(i => points[i].X).ThenBy(i => points[i].Y).ToArray(); + int a = p[0], b = p[1]; + if (p.Length == 2) + { + Slot(a, b); + Slot(b, a); + } + else + { + int c = p[2]; + double winding = Turn(a, b, c); + if (winding == 0) + { + Slot(a, b); + Slot(b, a); + Slot(c, b); + Slot(b, c); + PairLeaf(start); + return; + } + if (winding < 0) (b, c) = (c, b); + Slot(a, b, c); + Slot(b, a); Slot(c, b); Slot(a, c); + } + PairLeaf(start); + return; + } + var order = axis == 0 ? p.OrderBy(i => points[i].X).ThenBy(i => points[i].Y).ToArray() + : p.OrderBy(i => points[i].Y).ThenBy(i => points[i].X).ToArray(); + int mid = order.Length / 2; + var left = order[..mid]; var right = order[mid..]; + Partition(left, 1 - axis); + int split = slots.Count; + Partition(right, 1 - axis); + Stitch(left, right, start, split, slots.Count); + } + + private EdgeRef FindGhost(int lo, int hi, int a, int b) + { + var matches = slots.Skip(lo).Take(hi - lo).Where(f => f.Vertices.Contains(Infinity)) + .SelectMany(HalfEdges).Where(e => e.A == a && e.B == b).ToArray(); + if (matches.Length != 1) throw new InvalidDataException("Ambiguous seed hull."); + return matches[0]; + } + + private void Stitch(int[] left, int[] right, int begin, int split, int end) + { + var tangents = (from a in left + from b in right + where left.All(p => Turn(a, b, p) >= 0) && right.All(p => Turn(a, b, p) >= 0) + select (a, b)).Take(2).ToArray(); + if (tangents.Length != 1) throw new InvalidDataException("Ambiguous seed tangent."); + var tangent = tangents[0]; + int lowerL = tangent.a, lowerR = tangent.b; + var leftHull = FindGhost(begin, split, Infinity, lowerL); + var rightHull = FindGhost(split, end, lowerR, Infinity); + var l = leftHull.Across; + var r = rightHull.Across; + var bottom = Slot(lowerL, Infinity, lowerR); + bottom.Pair(leftHull); + bottom.Next.Pair(rightHull); + var seam = bottom.Back; + int remaining = (left.Length + right.Length) * 4; + while (remaining-- > 0) + { + bool canL = l.C >= 0 && Turn(lowerL, lowerR, l.C) > 0; + bool canR = r.C >= 0 && Turn(lowerL, lowerR, r.C) > 0; + if (!canL && !canR) + { + var upper = Slot(lowerL, lowerR); + upper.Pair(seam); + upper.Next.Pair(r); + upper.Back.Pair(l); + return; + } + + if (canL) RollLeft(ref l, lowerL, lowerR); + if (canR) RollRight(ref r, lowerL, lowerR); + if (!canL || canR && Disk(l.C, lowerL, lowerR, r.C) > 0) + { + seam.Pair(r); + int top = r.C; + seam = r.Back; + seam.Write(top, lowerL, lowerR); + lowerR = top; + r = seam.Across; + } + else + { + seam.Pair(l); + int top = l.C; + seam = l.Next; + seam.Write(lowerR, top, lowerL); + lowerL = top; + l = seam.Across; + } + } + throw new InvalidDataException("Delaunay seam failed to close."); + } + + private void RollLeft(ref EdgeRef choice, int left, int right) + { + var peel = choice.Back.Across; + int remaining = slots.Count; + while (peel.C >= 0 && Disk(left, right, choice.C, peel.C) > 0) + { + if (--remaining == 0) throw new InvalidDataException("Invalid left seed hull."); + int top = choice.C, replacement = peel.C; + var far = peel.Next.Across; + var upcoming = peel.Back.Across; + peel.Back.Pair(far); + choice.Pair(upcoming); + choice = choice.Next; + peel.Next.Pair(choice.Across); + choice.Write(left, Infinity, replacement); + peel.Next.Write(Infinity, top, replacement); + peel = upcoming; + } + } + + private void RollRight(ref EdgeRef choice, int left, int right) + { + var peel = choice.Next.Across; + int remaining = slots.Count; + while (peel.C >= 0 && Disk(left, right, choice.C, peel.C) > 0) + { + if (--remaining == 0) throw new InvalidDataException("Invalid right seed hull."); + int top = choice.C, replacement = peel.C; + var far = peel.Back.Across; + var upcoming = peel.Next.Across; + peel.Next.Pair(far); + choice.Pair(upcoming); + choice = choice.Back; + peel.Back.Pair(choice.Across); + choice.Write(Infinity, right, replacement); + peel.Back.Write(top, Infinity, replacement); + peel = upcoming; + } + } + + private bool Inside(int[] triangle) + { + var p = (points[triangle[0]] + points[triangle[1]] + points[triangle[2]]) * (1.0 / 3); + bool contained = false; + for (int i = 0; i < points.Length; i++) + { + var a = points[i]; var b = points[(i + 1) % points.Length]; + if ((a.Y > p.Y) != (b.Y > p.Y) && p.X < (b.X - a.X) * (p.Y - a.Y) / (b.Y - a.Y) + a.X) contained = !contained; + } + return contained; + } +} diff --git a/src/RvtIO/Geometry/Meshing/FaceArea.cs b/src/RvtIO/Geometry/Meshing/FaceArea.cs index c5f81eb0..906def40 100644 --- a/src/RvtIO/Geometry/Meshing/FaceArea.cs +++ b/src/RvtIO/Geometry/Meshing/FaceArea.cs @@ -4,10 +4,14 @@ internal static class FaceArea { private const double Tolerance = 1e-6; private const int MaxLevels = 20; + private const int WindowSize = 5; /// One coedge of a loop: the points of its Edge as stored for this Face, the Edge flags, and whether this is the second /// Face of the Edge. - internal readonly record struct Coedge(IReadOnlyList<(double U, double V)> Points, int Flags, bool SecondFace); + internal readonly record struct Coedge(IReadOnlyList<(double U, double V)> Points, int Flags, bool SecondFace, uint SourceEdge = 0) + { + internal bool Reversed => (Flags & 1) != (SecondFace ? 1 : 0); + } /// /// The area of the Face whose loops are the coedges, in the square of the unit of its (u, v); null when the quadrature does @@ -16,6 +20,28 @@ internal static class FaceArea internal static double? Compute(IEnumerable coedges) => Integrate(coedges, null) is { } area ? Math.Abs(area) : null; + internal static double? ComputeWithDistinctSamples(IEnumerable coedges) + => Compute(coedges.Select(edge => + { + const double tolerance = 1e-9; + var points = new List<(double U, double V)>(edge.Points.Count); + foreach (var point in edge.Points) + { + if (!double.IsFinite(point.U) || !double.IsFinite(point.V)) return edge; + if (points.Count == 0 || Math.Abs(point.U - points[^1].U) > tolerance || Math.Abs(point.V - points[^1].V) > tolerance) + points.Add(point); + } + return edge with { Points = points }; + })); + + internal static double? EllipticalArcLength(double major, double minor, double from, double to) + => Integrate(new Coedge([(from, 0), (to, 0)], 0, false), (t, _, dt, _) => + { + var (sin, cos) = Math.SinCos(t); + double x = major * sin, y = minor * cos; + return Math.Sqrt(x * x + y * y) * Math.Abs(dt); + }); + internal delegate double SurfaceIntegrand(double u, double v, double du, double dv); internal static double? Integrate(IEnumerable coedges, SurfaceIntegrand? integrand) @@ -29,14 +55,20 @@ internal static class FaceArea return double.IsFinite(total) ? total : null; } - internal static (double[] Value, double[] Derivative) HermiteBasis(double s) + internal static void HermiteBasis(double s, Span value, Span derivative) { double twoSquare = (s + s) * s, threeSquare = s * 3.0 * s, cube = s * s * s, sixSquare = s * 6.0 * s; - return ([twoSquare * s - threeSquare + 1.0, threeSquare - twoSquare * s, cube - twoSquare + s, cube - s * s], - [sixSquare - s * 6.0, s * 6.0 - sixSquare, threeSquare - s * 4.0 + 1.0, threeSquare - (s + s)]); + value[0] = twoSquare * s - threeSquare + 1.0; + value[1] = threeSquare - twoSquare * s; + value[2] = cube - twoSquare + s; + value[3] = cube - s * s; + derivative[0] = sixSquare - s * 6.0; + derivative[1] = s * 6.0 - sixSquare; + derivative[2] = threeSquare - s * 4.0 + 1.0; + derivative[3] = threeSquare - (s + s); } - private static (double U, double V)[] Coefficients(IReadOnlyList<(double U, double V)> points, int segment) + private static void Coefficients(IReadOnlyList<(double U, double V)> points, int segment, Span<(double U, double V)> coefficients) { int interior = points.Count - 2; var a = points[segment]; @@ -69,7 +101,10 @@ private static (double U, double V)[] Coefficients(IReadOnlyList<(double U, doub tangentA = ((b.U * 4.0 - a.U * 3.0 - after.U) * 0.5, (b.V * 4.0 - a.V * 3.0 - after.V) * 0.5); } } - return [a, b, tangentA, tangentB]; + coefficients[0] = a; + coefficients[1] = b; + coefficients[2] = tangentA; + coefficients[3] = tangentB; } private static ((double U, double V) Point, (double U, double V) Derivative) Evaluate(IReadOnlyList<(double U, double V)> points, double t) @@ -82,8 +117,11 @@ private static ((double U, double V) Point, (double U, double V) Derivative) Eva } double intervals = count - 1; int segment = Math.Min((int)Math.Floor(intervals * t), count - 2); - var (basis, derivative) = HermiteBasis(intervals * t - segment); - var c = Coefficients(points, segment); + Span basis = stackalloc double[4]; + Span derivative = stackalloc double[4]; + Span<(double U, double V)> c = stackalloc (double, double)[4]; + HermiteBasis(intervals * t - segment, basis, derivative); + Coefficients(points, segment, c); double u = basis[0] * c[0].U, v = basis[0] * c[0].V, du = derivative[0] * c[0].U, dv = derivative[0] * c[0].V; for (int k = 1; k < 4; k++) { @@ -97,7 +135,7 @@ private static ((double U, double V) Point, (double U, double V) Derivative) Eva private static double Integrand(Coedge coedge, double t, SurfaceIntegrand? integrand) { - bool reverse = (coedge.Flags & 1) != (coedge.SecondFace ? 1 : 0); + bool reverse = coedge.Reversed; var (point, derivative) = Evaluate(coedge.Points, reverse ? 1.0 - t : t); if (reverse) derivative = (-derivative.U, -derivative.V); return integrand != null ? integrand(point.U, point.V, derivative.U, derivative.V) @@ -106,25 +144,27 @@ private static double Integrand(Coedge coedge, double t, SurfaceIntegrand? integ private static double? Integrate(Coedge coedge, SurfaceIntegrand? integrand) { - double previous = (Integrand(coedge, 0.0, integrand) + Integrand(coedge, 1.0, integrand)) * 0.5; - var step = new List { 1.0 }; - var estimate = new List { previous }; + Span step = stackalloc double[WindowSize]; + Span estimate = stackalloc double[WindowSize]; + step[0] = 1.0; + estimate[0] = (Integrand(coedge, 0.0, integrand) + Integrand(coedge, 1.0, integrand)) * 0.5; int level = 1; - for (; level <= 4; level++) + for (; level < WindowSize; level++) { - previous = Refine(coedge, level, estimate[^1], integrand); - step.Add(step[^1] * 0.25); - estimate.Add(previous); + estimate[level] = Refine(coedge, level, estimate[level - 1], integrand); + step[level] = step[level - 1] * 0.25; } var (value, error) = Extrapolate(step, estimate); if (Math.Abs(value) <= Tolerance) return value; while (Math.Abs(error) > Math.Abs(value) * Tolerance) { if (level >= MaxLevels) return null; - step.Add(step[^1] * 0.25); - estimate.Add(Refine(coedge, level, estimate[^1], integrand)); - step.RemoveAt(0); - estimate.RemoveAt(0); + double nextStep = step[^1] * 0.25; + double nextEstimate = Refine(coedge, level, estimate[^1], integrand); + step[1..].CopyTo(step); + estimate[1..].CopyTo(estimate); + step[^1] = nextStep; + estimate[^1] = nextEstimate; (value, error) = Extrapolate(step, estimate); level++; if (Math.Abs(value) <= Tolerance) break; @@ -144,11 +184,13 @@ private static double Refine(Coedge coedge, int level, double previous, SurfaceI return (sum * 1.0 / panels + previous) * 0.5; } - private static (double Value, double Error) Extrapolate(List step, List estimate) + private static (double Value, double Error) Extrapolate(ReadOnlySpan step, ReadOnlySpan estimate) { - int n = step.Count; - var c = estimate.ToArray(); - var d = estimate.ToArray(); + int n = step.Length; + Span c = stackalloc double[WindowSize]; + Span d = stackalloc double[WindowSize]; + estimate.CopyTo(c); + estimate.CopyTo(d); double value = estimate[n - 1], error = 0; for (int m = 1; m < n; m++) { diff --git a/src/RvtIO/Geometry/Meshing/PlanarPredicates.cs b/src/RvtIO/Geometry/Meshing/PlanarPredicates.cs new file mode 100644 index 00000000..bf03bc76 --- /dev/null +++ b/src/RvtIO/Geometry/Meshing/PlanarPredicates.cs @@ -0,0 +1,53 @@ +using System.Numerics; + +namespace RvtIO.Geometry.Meshing; + +internal static class PlanarPredicates +{ + internal static double Orientation(UvPoint a, UvPoint b, UvPoint c) + { + UvPoint u = a - c, v = b - c; + double left = u.X * v.Y, right = u.Y * v.X, area = left - right; + if (Math.Abs(area) > 1e-14 * (Math.Abs(left) + Math.Abs(right))) return area; + var (n, exponent) = Exact(a, b, c); + BigInteger exact = (n[0] - n[4]) * (n[3] - n[5]) - (n[1] - n[5]) * (n[2] - n[4]); + return Math.ScaleB((double)exact, 2 * exponent); + } + + internal static double Disk(UvPoint a, UvPoint b, UvPoint c, UvPoint d) + { + UvPoint u = a - d, v = b - d, w = c - d; + double u2 = u.LengthSquared, v2 = v.LengthSquared, w2 = w.LengthSquared; + double value = u2 * v.Cross(w) + v2 * w.Cross(u) + w2 * u.Cross(v); + double bound = u2 * (Math.Abs(v.X * w.Y) + Math.Abs(v.Y * w.X)) + + v2 * (Math.Abs(w.X * u.Y) + Math.Abs(w.Y * u.X)) + + w2 * (Math.Abs(u.X * v.Y) + Math.Abs(u.Y * v.X)); + if (Math.Abs(value) > 1e-14 * bound) return value; + var (n, _) = Exact(a, b, c, d); + BigInteger ux = n[0] - n[6], uy = n[1] - n[7], vx = n[2] - n[6], vy = n[3] - n[7], wx = n[4] - n[6], wy = n[5] - n[7]; + return ((ux * ux + uy * uy) * (vx * wy - vy * wx) + (vx * vx + vy * vy) * (wx * uy - wy * ux) + (wx * wx + wy * wy) * (ux * vy - uy * vx)).Sign; + } + + private static (BigInteger[] Values, int Exponent) Exact(params UvPoint[] p) + { + var numbers = new (long Significand, int Exp)[p.Length * 2]; + int exponent = 0; + for (int i = 0; i < p.Length; i++) + { + numbers[i * 2] = Extract(p[i].X); + numbers[i * 2 + 1] = Extract(p[i].Y); + exponent = Math.Min(exponent, Math.Min(numbers[i * 2].Exp, numbers[i * 2 + 1].Exp)); + } + return (numbers.Select(x => new BigInteger(x.Significand) << (x.Exp - exponent)).ToArray(), exponent); + } + + private static (long Significand, int Exp) Extract(double p) + { + long bits = BitConverter.DoubleToInt64Bits(p); + int exp = (int)((bits >> 52) & 2047); + long sig = bits & ((1L << 52) - 1); + if (exp != 0) sig |= 1L << 52; + if (sig == 0) return (0, 0); + return (bits < 0 ? -sig : sig, (exp == 0 ? 1 : exp) - 1075); + } +} diff --git a/src/RvtIO/Internal/GRepData.cs b/src/RvtIO/Internal/GRepData.cs index 73d8fe47..9416a8aa 100644 --- a/src/RvtIO/Internal/GRepData.cs +++ b/src/RvtIO/Internal/GRepData.cs @@ -42,6 +42,12 @@ internal record GRepData /// solid-only cleanup must not remove coplanar triangulation facets. public bool IsOpenSurface { get; set; } + internal (double Volume, double Area, int Count)? LightingBodyMeasures { get; set; } + internal (double Volume, double Area, int Count)? SourceBodyMeasures { get; set; } + internal (double Top, double Bottom)? SourceCapAreas { get; set; } + internal (double Area, double Volume)? TrimmedBodyMeasures { get; set; } + internal double? FilledArea { get; set; } + /// Faces left out because the triangulation of their trim loops ran out of its work budget (see /// GRepParserV2.TrimWorkBudget); they have no polygon here rather than one without their trim. public int UntriangulatedFaces { get; set; } @@ -186,6 +192,9 @@ internal record GRepFace /// GInfo flags of the serialized Face (null when not read). public uint? GInfoFlags { get; init; } + + /// Face tag used by the owning element's geometry history. + public int? GInfoTag { get; init; } } /// A circular Edge as the file stores it: the circle (centre, unit X and Y, radius, in feet) and the parameters of its two diff --git a/src/RvtIO/Model/Element.cs b/src/RvtIO/Model/Element.cs index 787eb22b..2f1a7416 100644 --- a/src/RvtIO/Model/Element.cs +++ b/src/RvtIO/Model/Element.cs @@ -1040,8 +1040,9 @@ internal bool RootClassIs(string className) => NativeRootClassName != null public int? SerializedHostId { get; set; } /// - /// The workset ID of the element (equal to ELEM_PARTITION_PARAM / Autodesk.Revit.DB.Element.WorksetId). - /// Non-null in workshared files where a partition is assigned; null in non-workshared files. + /// The workset ID of the element as returned by Autodesk.Revit.DB.Element.WorksetId. + /// Revit 2027 uses 0 for the default workset of a non-workshared file and -1 for its ELEM_PARTITION_PARAM. + /// Null when no workset can be resolved. /// public int? WorksetId { get; set; } diff --git a/src/RvtIO/Parsing/ElementBuilder.cs b/src/RvtIO/Parsing/ElementBuilder.cs index 954e7b73..debf936b 100644 --- a/src/RvtIO/Parsing/ElementBuilder.cs +++ b/src/RvtIO/Parsing/ElementBuilder.cs @@ -1189,6 +1189,10 @@ public static void BuildElemTableElement( // a file with 64-bit ids: the rest of this method is the Revit 2022 record and stream // heuristics. The element is what the file's own tables and the schema-driven block // walk give: the header category is exact. + if (elem.NativeRootClassName is "Rebar" or "RebarInSystem" + && elem.RebarBars is { BarTypeId: > 0 } bars + && state.NativeRootClassNames.GetValueOrDefault((uint)bars.BarTypeId) == "RebarBarType") + elem.TypeId = bars.BarTypeId; if (wideHeaderCategory is int resolvedHeader) { elem.CategoryId = resolvedHeader; @@ -3082,15 +3086,23 @@ private static void ApplyBlockSignatureCategories(RevitFileInfo info, ParsingSta private static void ApplyWorksets(RevitFileInfo info, ParsingState? state) { if (state == null || state.ElemWorksets.Count == 0) return; + bool nonWorkshared2027 = state.WideSchema?.Release == 2027 && info.SerializedIsWorkshared == false; foreach (var e in info.Elements) { var existing = e.Parameters.FirstOrDefault(p => p.Id == -1002053); if (state.ElemWorksets.TryGetValue((uint)e.Id, out uint ws)) { - // ElemTable workset is authoritative - force-override any stale value. - if (existing != null) { existing.Value = (int)ws; existing.StorageType = StorageType.Integer; } - else e.Parameters.Add(BipHelpers.MakeBipParam(-1002053, "ELEM_PARTITION_PARAM", StorageType.Integer, (int)ws)); e.WorksetId = (int)ws; + // In a non-workshared Revit 2027 file, PropertySetElement has a WorksetId but no Workset parameter. + if (nonWorkshared2027 && e.NativeRootClassName == "PropertySetElement") + { + if (existing != null) e.Parameters.Remove(existing); + continue; + } + // Revit 2027 reports the default local workset as 0 through WorksetId and -1 through the parameter. + int value = nonWorkshared2027 && ws == 0 ? -1 : (int)ws; + if (existing != null) { existing.Value = value; existing.StorageType = StorageType.Integer; } + else e.Parameters.Add(BipHelpers.MakeBipParam(-1002053, "ELEM_PARTITION_PARAM", StorageType.Integer, value)); } else if (existing is { Value: int pv } && pv < 0) { @@ -6496,6 +6508,7 @@ void ReportDistinctMissing(string label, Dictionary counts) // Runs LAST: needs WALL_BASE_CONSTRAINT / WALL_HEIGHT_TYPE emitted by the passes above. ApplyComputedHeights(rvtInfo, state); ApplyBipKeyedStrings(rvtInfo, state); + if (state != null) Revit2027ApiValues.Apply(rvtInfo, state, elemByIdLookup); ApplyWorksets(rvtInfo, state); TraceElement(rvtInfo, "before-fixphase"); FixUnresolvedPhaseCreated(rvtInfo); @@ -6802,10 +6815,14 @@ private static void FixCategoryFromClassIdx(RevitFileInfo info, ParsingState? st if (e.CategoryId is int c && c != -1 && e.Category != null && !nameByCat.ContainsKey(c)) nameByCat[c] = e.Category; + bool useHeader = state.WideSchema?.Release == 2027 && !state.R22View; foreach (var e in info.Elements) { - if (e.Id < 0 || !state.ElemClassIdx.TryGetValue((uint)e.Id, out var cls)) continue; - if (!TfClassRegistry.HighPurityClassCategory.TryGetValue(cls, out int cat)) continue; + if (e.Id < 0) continue; + int cat; + if (useHeader && e.NativeHeaderCategoryId is int header && header != -1) cat = header; + else if (!state.ElemClassIdx.TryGetValue((uint)e.Id, out var cls) + || !TfClassRegistry.HighPurityClassCategory.TryGetValue(cls, out cat)) continue; if (e.CategoryId == cat && (e.Id != 0 || e.Parameters.Any(p => p.Id == -1140362))) continue; e.CategoryId = cat; if (nameByCat.TryGetValue(cat, out var nm) || BuiltInCategoryNames.Lookup.TryGetValue(cat, out nm)) e.Category = nm; diff --git a/src/RvtIO/Parsing/GRepParserV2.FaceAreas.cs b/src/RvtIO/Parsing/GRepParserV2.FaceAreas.cs index 9601f165..44fb5c75 100644 --- a/src/RvtIO/Parsing/GRepParserV2.FaceAreas.cs +++ b/src/RvtIO/Parsing/GRepParserV2.FaceAreas.cs @@ -4,6 +4,23 @@ namespace RvtIO.Parsing; internal static partial class GRepParserV2 { + private static double? MeasureFilledFaces(Cur c, Dictionary surfaces, Dictionary> loopsByFace) + { + var edges = EdgesByHandle(c); + double area = 0; + for (int i = 0; i < c.Queue.Count; i++) + { + if (c.Queue[i].Cls != 2014 || c.QueueLinks[i] is not (int parent and >= 0, "m_pGFilling") + || c.Queue[parent].Cls != GFaceClass) continue; + uint face = (uint)c.Queue[parent].V; + if (!surfaces.TryGetValue(face, out var surface) || surface.Kind != SurfKind.Plane + || !loopsByFace.TryGetValue(face, out var loops) || SurfaceCoedges(c, face, loops, edges) is not { } coedges + || FaceArea.Compute(coedges) is not double measure) return null; + area += measure; + } + return area > 0 && double.IsFinite(area) ? area : null; + } + /// The area computeAreaOfFace gives each planar Face with curved Edges, and each cylindrical Face: the /// quadrature of over the coedges of its loops in file order, with the Edge points as the file stores them. /// A planar Face of straight Edges has no entry: the quadrature of a line is its exact value, the polygon area. A Face with an open loop or @@ -28,7 +45,7 @@ private static Dictionary ComputeFaceAreas(Cur c, Dictionary? SurfaceCoedges(Cur c, uint face, List indices, - Dictionary edges) + Dictionary edges, bool rawOnly = false, bool closeEndPole = false) { var coedges = new List(); foreach (int index in indices) @@ -36,6 +53,7 @@ private static Dictionary ComputeFaceAreas(Cur c, Dictionary ComputeFaceAreas(Cur c, Dictionary firstFace ? (point.UA, point.VA) : (point.UB, point.VB)).ToList(); - coedges.Add(new FaceArea.Coedge(points, edge.Flags, !firstFace)); + // The original coedges precede the mesh refinements shared with neighbouring faces. + if (rawOnly && edge.RawInterior == null) return null; + var samples = rawOnly ? edge.RawInterior!.Prepend(edge.RawStart).Append(edge.RawEndP) : edge.AuthoredPoints(); + var points = samples.Select(point => firstFace ? (point.UA, point.VA) : (point.UB, point.VB)).ToList(); + coedges.Add(new FaceArea.Coedge(points, edge.Flags, !firstFace, edge.Handle)); current = firstFace ? edge.NextA : edge.NextB; } + if (closeEndPole && !CloseRuledEndPole(coedges, first)) return null; } return coedges; } + + internal static bool CloseRuledEndPole(List coedges, int first) + { + const double tolerance = 1e-9; + int end = coedges.Count; + for (int i = first; i < end; i++) + { + var edge = coedges[i]; + var next = coedges[i + 1 == end ? first : i + 1]; + var a = edge.Reversed ? edge.Points[0] : edge.Points[^1]; + var b = next.Reversed ? next.Points[^1] : next.Points[0]; + if (Math.Abs(a.U - b.U) <= tolerance && Math.Abs(a.V - b.V) <= tolerance) continue; + if (Math.Abs(a.V - 1) > tolerance || Math.Abs(b.V - 1) > tolerance) return false; + // The two UV endpoints at the end profile are one 3D point and have no saved edge. + coedges.Add(new FaceArea.Coedge([a, b], 0, false)); + } + return true; + } } diff --git a/src/RvtIO/Parsing/GRepParserV2.HermiteMeasure.cs b/src/RvtIO/Parsing/GRepParserV2.HermiteMeasure.cs new file mode 100644 index 00000000..58af878c --- /dev/null +++ b/src/RvtIO/Parsing/GRepParserV2.HermiteMeasure.cs @@ -0,0 +1,297 @@ +using RvtIO.Geometry.Meshing; + +namespace RvtIO.Parsing; + +internal static partial class GRepParserV2 +{ + internal static (double Area, double Volume)? MeasureHermiteFace(SurfaceRec surface, double[] reference, + IReadOnlyList coedges) + { + const double tolerance = 1e-9; + if (surface.Kind != SurfKind.Hermite || surface.Orient != 1 || surface.Env is not { Length: 4 } env + || surface.UParams is not { Length: >= 2 } u || surface.VParams is not { Length: >= 2 } v + || surface.HermiteNodes is not { Count: <= 256 } nodes || nodes.Count != (long)u.Length * v.Length + || reference is not { Length: 3 } || !reference.All(double.IsFinite) + || !env.All(double.IsFinite) || env[2] <= env[0] || env[3] <= env[1] + || !Near(env[0], u[0]) || !Near(env[2], u[^1]) || !Near(env[1], v[0]) || !Near(env[3], v[^1]) + || coedges.Count != 4) + return null; + + // The reconstructed mapping covers a single, positively oriented full knot domain. + UvPoint[] corners = [new(env[0], env[1]), new(env[2], env[1]), new(env[2], env[3]), new(env[0], env[3])]; + var contour = new List(); + int start = Array.FindIndex(corners, corner => Matches(Read(coedges[0], 0), corner)); + if (start < 0) return null; + for (int i = 0; i < 4; i++) + { + var edge = coedges[i]; + var a = corners[(start + i) % 4]; + var b = corners[(start + i + 1) % 4]; + int last = edge.Points.Count - 1; + if (last < 1 || last > 64 - contour.Count || !Matches(Read(edge, 0), a) || !Matches(Read(edge, last), b)) + return null; + + bool alongU = a.Y == b.Y; + double direction = Math.Sign(alongU ? b.X - a.X : b.Y - a.Y); + double previous = double.NegativeInfinity; + double end = (alongU ? b.X : b.Y) * direction; + for (int j = 0; j < last; j++) + { + var point = Read(edge, j); + double parameter = (alongU ? point.X : point.Y) * direction; + if (!Near(alongU ? point.Y : point.X, alongU ? a.Y : a.X) + || !double.IsFinite(parameter) || parameter <= previous || parameter >= end) return null; + contour.Add(point); + previous = parameter; + } + } + + try + { + var face = new PreparedFace(new PatchGrid(u, v, nodes), env, contour.ToArray(), Pt3.From(reference)); + if (!double.IsFinite(face.Step.X) || !double.IsFinite(face.Step.Y) || face.Step.X <= 0 || face.Step.Y <= 0 + || face.Contour.Any(p => !double.IsFinite(p.X) || !double.IsFinite(p.Y))) return null; + var mesh = new ConformingDelaunay(face.Contour, face.Step); + mesh.Refine(); + var measure = face.Measure(mesh.Points, mesh.Faces); + return double.IsFinite(measure.Area) && measure.Area > 0 && double.IsFinite(measure.Volume) ? measure : null; + } + catch (InvalidDataException) + { + return null; + } + + static UvPoint Read(FaceArea.Coedge edge, int i) + { + if (edge.Points.Count == 0) return new(double.NaN, double.NaN); + var (u, v) = edge.Points[edge.Reversed ? edge.Points.Count - 1 - i : i]; + return new(u, v); + } + + static bool Near(double a, double b) => Math.Abs(a - b) <= tolerance; + static bool Matches(UvPoint a, UvPoint b) => Near(a.X, b.X) && Near(a.Y, b.Y); + } + + private readonly record struct SurfaceJet(Pt3 Position, Pt3 Du, Pt3 Dv, Pt3 Duu, Pt3 Duv, Pt3 Dvv); + + private sealed class PatchGrid + { + private readonly Pt3[][] nets; + internal readonly double[] UKnots; + internal readonly double[] VKnots; + + internal PatchGrid(double[] uKnots, double[] vKnots, IReadOnlyList nodes) + { + UKnots = uKnots; + VKnots = vKnots; + if (UKnots.Length < 2 || VKnots.Length < 2 || nodes.Count != UKnots.Length * VKnots.Length || + !OrderedFinite(UKnots) || !OrderedFinite(VKnots)) + throw new InvalidDataException("Invalid Hermite knot grid."); + nets = new Pt3[(UKnots.Length - 1) * (VKnots.Length - 1)][]; + for (int i = 0; i + 1 < UKnots.Length; i++) + for (int j = 0; j + 1 < VKnots.Length; j++) + { + var net = new Pt3[16]; + double h = UKnots[i + 1] - UKnots[i], k = VKnots[j + 1] - VKnots[j]; + for (int a = 0; a < 2; a++) + for (int b = 0; b < 2; b++) + { + var node = nodes[(j + b) * UKnots.Length + i + a]; + net[a * 4 + b] = Pt3.From(node.Point); + net[(a + 2) * 4 + b] = Pt3.From(node.Du) * h; + net[a * 4 + b + 2] = Pt3.From(node.Dv) * k; + net[(a + 2) * 4 + b + 2] = Pt3.From(node.Duv) * h * k; + } + nets[j * (UKnots.Length - 1) + i] = net; + } + } + + private static bool OrderedFinite(double[] values) => + values.All(double.IsFinite) && Enumerable.Range(1, values.Length - 1).All(i => values[i] > values[i - 1]); + + private static int Interval(double[] knots, double t) + { + int pos = Array.BinarySearch(knots, t); + return Math.Clamp(pos >= 0 ? pos : ~pos - 1, 0, knots.Length - 2); + } + + private static void Basis(double s, double h, Span b) + { + double sq = s * s, hh = h * h; + b[0] = (2 * s - 3) * sq + 1; b[1] = (3 - 2 * s) * sq; + b[2] = (s - 2) * sq + s; b[3] = (s - 1) * sq; + b[4] = (6 * sq - 6 * s) / h; b[5] = (6 * s - 6 * sq) / h; + b[6] = (3 * sq - 4 * s + 1) / h; b[7] = (3 * sq - 2 * s) / h; + b[8] = (12 * s - 6) / hh; b[9] = (6 - 12 * s) / hh; + b[10] = (6 * s - 4) / hh; b[11] = (6 * s - 2) / hh; + } + + internal SurfaceJet Evaluate(double u, double v) + { + int i = Interval(UKnots, u), j = Interval(VKnots, v); + var net = nets[j * (UKnots.Length - 1) + i]; + double h = UKnots[i + 1] - UKnots[i], k = VKnots[j + 1] - VKnots[j]; + Span b = stackalloc double[12], c = stackalloc double[12]; + Basis((u - UKnots[i]) / h, h, b); + Basis((v - VKnots[j]) / k, k, c); + Pt3 p = default, pu = default, pv = default, puu = default, puv = default, pvv = default; + for (int a = 0; a < 4; a++) + for (int d = 0; d < 4; d++) + { + var entry = net[a * 4 + d]; + p += entry * (b[a] * c[d]); + pu += entry * (b[4 + a] * c[d]); + pv += entry * (b[a] * c[4 + d]); + puu += entry * (b[8 + a] * c[d]); + puv += entry * (b[4 + a] * c[4 + d]); + pvv += entry * (b[a] * c[8 + d]); + } + return new(p, pu, pv, puu, puv, pvv); + } + } + + private sealed class PreparedFace + { + private readonly PatchGrid grid; + private readonly UvPoint midpoint; + private readonly UvPoint perturbationCenter; + private readonly Pt3 fluxOrigin; + private readonly double curvature; + private readonly double slope; + private readonly double width; + private readonly double scaleU; + private readonly double scaleV; + internal UvPoint[] Contour { get; } + internal UvPoint Step { get; } + private readonly bool linearScaling; + + internal PreparedFace(PatchGrid grid, double[] envelope, UvPoint[] contour, Pt3 origin) + { + this.grid = grid; + double u0 = envelope[0], u1 = envelope[2]; + double v0 = envelope[1], v1 = envelope[3]; + midpoint = new((u0 + u1) * 0.5, (v0 + v1) * 0.5); + perturbationCenter = new(u0 * 0.500043219876 + u1 * 0.499956780124, v0 * 0.500067894321 + v1 * 0.499932105679); + fluxOrigin = origin; + var mid = grid.Evaluate(midpoint.X, midpoint.Y); + Span radii = stackalloc double[5]; + radii[0] = CurvatureRadius(mid); + int at = 1; + foreach (double u in new[] { u0, u1 }) + foreach (double v in new[] { v0, v1 }) + radii[at++] = CurvatureRadius(grid.Evaluate(u * 0.9 + midpoint.X * 0.1, v * 0.9 + midpoint.Y * 0.1)); + double radiusMax = 0, radiusMin = double.PositiveInfinity; + foreach (var r in radii) + { + radiusMin = Math.Min(radiusMin, r); + radiusMax = Math.Max(radiusMax, r); + } + bool fine = radiusMax < 1.0 / 12 && radiusMin / 3000 >= 1e-7; + double chordTolerance = fine ? radiusMin / 3000 : 1.0 / 24; + var rawStep = DeriveRawStep(grid, chordTolerance); + double speedU = mid.Du.Norm, speedV = mid.Dv.Norm; + double accelerationU = mid.Duu.Norm, accelerationV = mid.Dvv.Norm; + if (Math.Min(speedU, speedV) <= 1e-9) + throw new InvalidDataException("Singular parameter center."); + double minAngle = (fine ? 1 : 8) * Math.PI / 180; + double bendAngle = (fine ? 5 : 20) * Math.PI / 180; + double distance = Math.Min(rawStep.X * speedU, rawStep.Y * speedV) / Math.Tan(minAngle); + double du = LimitAngle(Math.Min(rawStep.X, distance / speedU), speedU, accelerationU, bendAngle); + double dv = LimitAngle(Math.Min(rawStep.Y, distance / speedV), speedV, accelerationV, bendAngle); + double physicalU = du * speedU, physicalV = dv * speedV; + double stretchU = Math.Max(1, physicalV / physicalU), stretchV = Math.Max(1, physicalU / physicalV); + double lowerWidth = grid.Evaluate(midpoint.X, v0).Du.Norm / speedV; + double midWidth = speedU / speedV; + double upperWidth = grid.Evaluate(midpoint.X, v1).Du.Norm / speedV; + double half = (v1 - v0) * 0.5; + double quadratic = (lowerWidth + upperWidth - 2 * midWidth) / (2 * half * half); + double linear = (upperWidth - lowerWidth) / (2 * half); + linearScaling = quadratic > 1e-9; + double mean = Math.Sqrt(speedU * speedV); + scaleU = linearScaling ? speedU / mean * stretchU : stretchU; + scaleV = linearScaling ? speedV / mean * stretchV : stretchV; + // Scale the global UV polynomial before evaluating it. Rounding changes the order of tied insertions. + width = (midWidth + midpoint.Y * (quadratic * midpoint.Y - linear)) * scaleU; + slope = (linear - 2 * quadratic * midpoint.Y) * scaleU; + curvature = quadratic * scaleU; + Step = new(du * scaleU * (linearScaling ? 1 : midWidth), dv * scaleV); + Contour = contour.Select(p => Move(Project(p), -1)).ToArray(); + } + + private static double LimitAngle(double step, double speed, double acceleration, double angle) => + acceleration > 0 && speed * speed > acceleration / 24 ? Math.Min(step, angle * speed / acceleration) : step; + + private static double CurvatureRadius(SurfaceJet e) + { + var normal = Pt3.Cross(e.Du, e.Dv); + double n = normal.Norm; + if (!(n > 0)) throw new InvalidDataException("Singular surface sample."); + normal *= 1 / n; + double E = e.Du.Dot(e.Du), F = e.Du.Dot(e.Dv), G = e.Dv.Dot(e.Dv); + double L = normal.Dot(e.Duu), M = normal.Dot(e.Duv), N = normal.Dot(e.Dvv); + double det = E * G - F * F; + if (!(det > 0)) throw new InvalidDataException("Singular metric."); + double trace = (G * L + E * N - 2 * F * M) / det; + double gaussian = (L * N - M * M) / det; + double maxCurvature = (Math.Abs(trace) + Math.Sqrt(Math.Max(0, trace * trace - 4 * gaussian))) * 0.5; + return 1 / maxCurvature; + } + + private static UvPoint DeriveRawStep(PatchGrid grid, double tolerance) + { + double uMax = 0, vMax = 0; + void Sample(double u, double v) + { + var e = grid.Evaluate(u, v); + double mixed = e.Duv.Norm; + uMax = Math.Max(uMax, Math.Max(e.Duu.Norm, mixed)); + vMax = Math.Max(vMax, Math.Max(e.Dvv.Norm, mixed)); + } + for (int i = 0; i < grid.UKnots.Length; i++) + for (int j = 0; j < grid.VKnots.Length; j++) + { + Sample(grid.UKnots[i], grid.VKnots[j]); + if (i + 1 < grid.UKnots.Length && j + 1 < grid.VKnots.Length) + Sample((grid.UKnots[i] + grid.UKnots[i + 1]) * 0.5, (grid.VKnots[j] + grid.VKnots[j + 1]) * 0.5); + } + double spanU = grid.UKnots[^1] - grid.UKnots[0], spanV = grid.VKnots[^1] - grid.VKnots[0]; + double Divide(double span, double bound) => + span / Math.Clamp(Math.Ceiling(span * Math.Sqrt(bound / (8 * tolerance))) + 1, 2, 60); + return new(Divide(spanU, uMax), Divide(spanV, vMax)); + } + + private UvPoint Move(UvPoint p, double sign) + { + var diff = p - perturbationCenter; + double norm = Math.Sqrt(diff.LengthSquared); + return norm < 1e-9 ? p : p + diff * (sign * 1e-7 / norm); + } + + private double WidthAt(double v) => (curvature * v + slope) * v + width; + + private UvPoint Project(UvPoint p) => linearScaling + ? new(p.X * scaleU, p.Y * scaleV) : new((p.X - midpoint.X) * WidthAt(p.Y), p.Y * scaleV); + + private Pt3 Reconstruct(UvPoint p) + { + p = Move(p, 1); + double v = p.Y / scaleV; + double u = linearScaling ? p.X / scaleU : p.X / WidthAt(v) + midpoint.X; + var xyz = grid.Evaluate(u, v).Position; + return new((float)xyz.X, (float)xyz.Y, (float)xyz.Z); + } + + internal (double Area, double Volume) Measure(UvPoint[] points, int[][] faces) + { + var p = points.Select(Reconstruct).ToArray(); + double area = 0, volume = 0; + foreach (var f in faces) + { + var cross = Pt3.Cross(p[f[1]] - p[f[0]], p[f[2]] - p[f[0]]); + area += cross.Norm * 0.5; + volume += (p[f[0]] - fluxOrigin).Dot(cross) / 6; + } + return (area, volume); + } + } +} diff --git a/src/RvtIO/Parsing/GRepParserV2.MeshFaces.cs b/src/RvtIO/Parsing/GRepParserV2.MeshFaces.cs index dd5a6c43..31dc48e4 100644 --- a/src/RvtIO/Parsing/GRepParserV2.MeshFaces.cs +++ b/src/RvtIO/Parsing/GRepParserV2.MeshFaces.cs @@ -59,19 +59,22 @@ internal static void MeshMarkFreeformEdges(Dictionary edges, Dic // point that is not finite (List Uv, List Points)? EdgePointsOf(EdgeRec e, bool sideA, List uvs) { - var uv = uvs.Select(p => sideA ? new[] { p.UA, p.VA } : new[] { p.UB, p.VB }).ToList(); - if (uv.Any(p => !double.IsFinite(p[0]) || !double.IsFinite(p[1]))) return null; - var points = uv.Select(p => freeform ? freeEval!(p[0], p[1]) : revolved ? MeshRevolvedPoint(surface, profile, p[0], p[1]) - : cone ? MeshConePoint(surface, p[0], p[1]) - : cylinder ? MeshCylinderPoint(surface, p[0], p[1]) - : Enumerable.Range(0, 3).Select(k => surface.O[k] + p[0] * surface.X[k] + p[1] * surface.Y[k]).ToArray()).ToList(); - // Revit evaluates the points of an Edge on its first active Face (a point - // shared by the faces of a vertex is one point) - if (activeFaces != null && !cylinder && !revolved && !freeform && MeshEdgeEvaluationFace(e, face, activeFaces, surfaces) is { } evalFace && evalFace != face + var uv = new List(uvs.Count); + foreach (var p in uvs) + { + double u = sideA ? p.UA : p.UB, v = sideA ? p.VA : p.VB; + if (!double.IsFinite(u) || !double.IsFinite(v)) return null; + uv.Add([u, v]); + } + + // Both paths prefer the edge's first active face. The current face is the fallback. + List? points = null; + if (activeFaces != null && (vertices != null || surface.Kind == SurfKind.Plane) + && MeshEdgeEvaluationFace(e, face, activeFaces, surfaces) is { } evalFace && evalFace != face && surfaces.TryGetValue(evalFace, out var evalSurface)) { bool evalA = e.FaceA == evalFace; - var evalPoints = new List(); + var evalPoints = new List(uvs.Count); for (int i = 0; i < uvs.Count; i++) { double eu = evalA ? uvs[i].UA : uvs[i].UB, ev = evalA ? uvs[i].VA : uvs[i].VB; @@ -81,23 +84,17 @@ internal static void MeshMarkFreeformEdges(Dictionary edges, Dic } if (evalPoints != null) points = evalPoints; } + if (points == null) + { + points = new List(uv.Count); + foreach (var p in uv) + points.Add(freeform ? freeEval!(p[0], p[1]) : revolved ? MeshRevolvedPoint(surface, profile, p[0], p[1]) + : cone ? MeshConePoint(surface, p[0], p[1]) + : cylinder ? MeshCylinderPoint(surface, p[0], p[1]) + : MeshPlanePoint(surface, p[0], p[1])); + } if (vertices != null && activeFaces != null) { - // the interior points come from the Edge's first active Face, the end points - // are the shared vertices - if (MeshEdgeEvaluationFace(e, face, activeFaces, surfaces) is { } vertexEvalFace && surfaces.TryGetValue(vertexEvalFace, out var vertexEvalSurface)) - { - bool vertexEvalA = e.FaceA == vertexEvalFace; - var viaFace = new List(); - for (int i = 0; i < uvs.Count; i++) - { - double eu = vertexEvalA ? uvs[i].UA : uvs[i].UB, ev = vertexEvalA ? uvs[i].VA : uvs[i].VB; - var evaluated = MeshEvaluate(c, vertexEvalFace, vertexEvalSurface, eu, ev); - if (evaluated == null) { viaFace = null!; break; } - viaFace.Add(evaluated); - } - if (viaFace != null) points = viaFace; - } if (vertices.TryGet(e.Handle, 0, out var vertexFirst)) points[0] = vertexFirst; if (vertices.TryGet(e.Handle, 1, out var vertexLast)) points[^1] = vertexLast; } @@ -440,7 +437,7 @@ private static bool MeshFlipped(Cur c, uint face, SurfaceRec surface) => switch (s.Kind) { case SurfKind.Plane: - return Enumerable.Range(0, 3).Select(k => s.O[k] + u * s.X[k] + v * s.Y[k]).ToArray(); + return MeshPlanePoint(s, u, v); case SurfKind.Cylinder: return MeshCylinderPoint(s, u, v); case SurfKind.Rev: @@ -450,6 +447,11 @@ private static bool MeshFlipped(Cur c, uint face, SurfaceRec surface) => } } + internal static double[] MeshPlanePoint(SurfaceRec s, double u, double v) => + [s.O[0] + u * s.X[0] + v * s.Y[0], + s.O[1] + u * s.X[1] + v * s.Y[1], + s.O[2] + u * s.X[2] + v * s.Y[2]]; + /// /// RVTIO_X_EVAL=0 returns the point formulas of the surfaces to the plain sums. /// diff --git a/src/RvtIO/Parsing/GRepParserV2.MeshNodes.cs b/src/RvtIO/Parsing/GRepParserV2.MeshNodes.cs index 7ce81132..40377575 100644 --- a/src/RvtIO/Parsing/GRepParserV2.MeshNodes.cs +++ b/src/RvtIO/Parsing/GRepParserV2.MeshNodes.cs @@ -27,7 +27,8 @@ internal static partial class GRepParserV2 private static List? BuildNodes(Cur c, Dictionary surfaces, HashSet bodyFaces, IEnumerable inactiveBodyFaces, Dictionary> loopsByFace, Dictionary nodeByFace, Dictionary nodeOrders, - List<(int Node, int Style, int RenderStyleId)>? displayOnlyNodes = null, List? nodeMeasures = null) + List<(int Node, int Style, int RenderStyleId)>? displayOnlyNodes = null, List? nodeMeasures = null, + bool measureSourceNodes = false) { var edges = EdgesByHandle(c); MeshMarkFreeformEdges(edges, surfaces); @@ -45,10 +46,15 @@ internal static partial class GRepParserV2 bool curved = false, usable = true; // The surface integrals of the node. A closed node whose faces point into it (negative signed volume, a cutting body) is not a // solid the exporter takes: its measure keeps the negative volume, which the quantities read as "not taken"; its geometry is exported as ever. - var measured = MeasureAnalyticSolid(c, group, surfaces, loopsByFace, edges); + var measured = MeasureAnalyticSolid(c, group, surfaces, loopsByFace, edges, measureSourceNodes); + if (measured == null && measureSourceNodes && closedNodes.Contains(group.Key)) + measured = MeasureEllipticalExtrusion(c, group, surfaces, loopsByFace, edges, volumeOnly: false); if (nodeMeasures != null && group.Key > 0 && measured is { } integrals && (integrals.Volume > 0 || integrals.Volume < 0 && !c.IncludeNonVisible && closedNodes.Contains(group.Key))) - nodeMeasures.Add(new MeshNodeMeasure(group.Key, integrals.Area, integrals.Volume)); + nodeMeasures.Add(new MeshNodeMeasure(group.Key, integrals.Area, integrals.Volume) + { + SourceFaces = measureSourceNodes ? group.ToHashSet() : null, + }); if (MeshNodeLog) DiagnosticSink.WriteLine($"[meshnode] eid={c.ElementId} node={group.Key} active {string.Join(",", group.GroupBy(h => surfaces.TryGetValue(h, out var sx) ? sx.Kind.ToString() : "none").Select(g => $"{g.Key}:{g.Count()}"))}" + $" inactive {(inactiveByNode.TryGetValue(group.Key, out var inx) ? string.Join(",", inx.GroupBy(h => c.DirectSurfaceByFace.TryGetValue(h, out var sy) ? sy.Kind.ToString() : "none").Select(g => $"{g.Key}:{g.Count()}")) : "-")}"); @@ -182,7 +188,10 @@ void Add(double[] p) /// The surface integrals of a Geometry node (square feet, cubic feet): its area and its signed volume. A negative volume is that of a closed /// node whose faces point into it; the exporter takes no solid from it. -internal sealed record MeshNodeMeasure(int Node, double Area, double Volume); +internal sealed record MeshNodeMeasure(int Node, double Area, double Volume) +{ + internal IReadOnlySet? SourceFaces { get; init; } +} /// /// One Geometry node written as a triangle set: its faces in the terms of the Revit face diff --git a/src/RvtIO/Parsing/GRepParserV2.SolidMeasures.cs b/src/RvtIO/Parsing/GRepParserV2.SolidMeasures.cs index 91a1036c..312eaa01 100644 --- a/src/RvtIO/Parsing/GRepParserV2.SolidMeasures.cs +++ b/src/RvtIO/Parsing/GRepParserV2.SolidMeasures.cs @@ -4,12 +4,225 @@ namespace RvtIO.Parsing; internal static partial class GRepParserV2 { + private static (double Volume, double Area, int Count)? MeasureClosedSourceBodies(Cur c, HashSet faces, + Dictionary surfaces, Dictionary> loopsByFace, bool volumeOnly = false, bool rawCoedges = false) + { + var nodeByFace = ResolveGeometryNodes(c.Queue, c.QueueLinks, c.ObjectGInfo); + if (faces.Any(face => !nodeByFace.ContainsKey(face))) return null; + var selected = faces.ToDictionary(face => face, face => nodeByFace[face]); + // Edges with neither next link are detached from the saved contour after a cut. + var closed = ClosedNodes(c.Edges.Where(edge => edge.NextA != 0 || edge.NextB != 0) + .Select(edge => (edge.FaceA, edge.FaceB)), selected); + var edges = EdgesByHandle(c); + double volume = 0, area = 0; + int count = 0; + foreach (var group in c.FaceOrder.Where(faces.Contains).GroupBy(face => nodeByFace[face].Node)) + { + if (!closed.Contains(group.Key)) return null; + var solid = MeasureAnalyticSolid(c, group, surfaces, loopsByFace, edges, true, rawCoedges); + if (solid == null && !rawCoedges) + solid = MeasureEllipticalExtrusion(c, group, surfaces, loopsByFace, edges, volumeOnly); + if (solid is not { Volume: > 0 } body) return null; + volume += body.Volume; + if (!volumeOnly) area += body.Area; + count++; + } + return count > 0 && double.IsFinite(volume) && double.IsFinite(area) ? (volume, area, count) : null; + } + + private static (double Area, double Volume)? MeasureTrimmedRuledFace(Cur c, SurfaceRec surface, Pt3 reference, + IReadOnlyList coedges) + { + var start = RuledProfile(c, surface.ProfileHandle, surface.P1); + var end = RuledProfile(c, surface.ProfileHandle2, surface.P2); + if (start == null || end == null) return null; + double anchor = surface.ProfileHandle2 is 0 or uint.MaxValue ? 1 : 0; + var area = MeasureRuledArea(start, end, coedges); + var volume = FaceArea.Integrate(coedges, (u, v, du, _) => + { + if (du == 0 || v == anchor) return 0; + var (a, da) = start(u); + var (b, db) = end(u); + var ruling = b - a; + var normal = Pt3.Cross(da, ruling); + var change = Pt3.Cross(db - da, ruling); + return -(a - reference).Dot(normal + (v + anchor) / 2 * change) * (v - anchor) * du / 3; + }); + return area is double surfaceArea && volume is double signedVolume ? (surfaceArea, signedVolume) : null; + } + + private static Func? RuledProfile(Cur c, uint handle, double[]? pole) + { + if (handle is 0 or uint.MaxValue) + return pole is { Length: 3 } && Pt3.From(pole).IsFinite ? _ => (Pt3.From(pole), default) : null; + if (!c.Curves.TryGetValue(handle, out var profile) || profile.NurbControlPoints is { Count: > 0 } + || !(profile.T1 > profile.T0)) return null; + double interval = profile.T1 - profile.T0; + if (profile.HermiteNodes is { Count: > 0 } nodes) + { + if (!ValidHermiteProfile(nodes)) return null; + return u => + { + var (p, d) = EvaluateHermiteProfile(nodes, profile.T0 + u * interval); + return (p, interval * d); + }; + } + var center = Pt3.From(profile.C); + var x = Pt3.From(profile.X); + var y = Pt3.From(profile.Y); + if (!center.IsFinite || !x.IsFinite || !y.IsFinite + || !double.IsFinite(profile.R) || !double.IsFinite(profile.RY) || profile.R < 0 || profile.RY < 0) return null; + if (profile.R == 0) return u => (center + (profile.T0 + u * interval) * x, interval * x); + x *= profile.R; + y *= profile.RY == 0 ? profile.R : profile.RY; + return u => + { + var (sin, cos) = Math.SinCos(profile.T0 + u * interval); + return (center + cos * x + sin * y, interval * (cos * y - sin * x)); + }; + } + + private static double? MeasureRuledArea(Func start, + Func end, IReadOnlyList coedges) + { + var area = FaceArea.Integrate(coedges, (u, v, du, _) => + { + if (du == 0 || v == 0) return 0; + var (a, da) = start(u); + var (b, db) = end(u); + var ruling = b - a; + var change = Pt3.Cross(db - da, ruling); + var normal = Pt3.Cross(da, ruling); + double length = change.Norm; + if (length == 0 || length <= 1e-8 * normal.Norm) + return -(normal + v / 2 * change).Norm * v * du; + double projection = normal.Dot(change) / length; + double perpendicular = Pt3.Cross(normal, change).Norm / length; + double Primitive(double x) => perpendicular == 0 ? x * Math.Abs(x) + : x * double.Hypot(x, perpendicular) + perpendicular * perpendicular * Math.Asinh(x / perpendicular); + return -(Primitive(projection + v * length) - Primitive(projection)) / (2 * length) * du; + }); + return area is double value ? Math.Abs(value) : null; + } + + private static (double Area, double Volume)? MeasureEllipticalExtrusion(Cur c, IEnumerable handles, + Dictionary surfaces, Dictionary> loopsByFace, Dictionary edges, + bool volumeOnly) + { + const double tolerance = 1e-9; + var faces = handles.ToList(); + var extrusions = new Dictionary(); + foreach (uint face in faces) + { + if (!surfaces.TryGetValue(face, out var surface)) return null; + if (surface.Kind != SurfKind.Ruled) continue; + if (!c.Curves.TryGetValue(surface.ProfileHandle, out var a) || !c.Curves.TryGetValue(surface.ProfileHandle2, out var b) + || a.HermiteNodes != null || a.NurbControlPoints != null || b.HermiteNodes != null || b.NurbControlPoints != null + || a.R <= 0 || a.RY <= 0 || !(a.T1 > a.T0) || Math.Abs(a.R - b.R) > tolerance || Math.Abs(a.RY - b.RY) > tolerance + || Math.Abs(a.T0 - b.T0) > tolerance || Math.Abs(a.T1 - b.T1) > tolerance + || (Pt3.From(a.X) - Pt3.From(b.X)).Norm > tolerance || (Pt3.From(a.Y) - Pt3.From(b.Y)).Norm > tolerance) + return null; + extrusions.Add(face, (a, Pt3.From(b.C) - Pt3.From(a.C))); + } + if (extrusions.Count == 0) return null; + var ruling = extrusions.Values.First().Ruling; + double height = ruling.Norm; + if (!double.IsFinite(height) || height <= tolerance) return null; + var axis = ruling / height; + if (extrusions.Values.Any(value => (value.Ruling - ruling).Norm > tolerance && (value.Ruling + ruling).Norm > tolerance + || Math.Abs(axis.Dot(Pt3.From(value.Profile.X))) > tolerance || Math.Abs(axis.Dot(Pt3.From(value.Profile.Y))) > tolerance)) + return null; + + var caps = new List<(double Offset, double SignedArea, double SurfaceArea, double Perimeter)>(); + foreach (uint face in faces) + { + var surface = surfaces[face]; + if (surface.Kind == SurfKind.Ruled) continue; + if (surface.Kind == SurfKind.Cylinder && Math.Abs(Math.Abs(axis.Dot(Pt3.From(surface.Z))) - 1) <= tolerance) continue; + if (surface.Kind != SurfKind.Plane) return null; + var x = Pt3.From(surface.X); + var y = Pt3.From(surface.Y); + var normal = Pt3.Cross(x, y); + double direction = Math.Abs(axis.Dot(normal)); + if (direction <= tolerance) continue; + if (Math.Abs(direction - 1) > tolerance || !loopsByFace.TryGetValue(face, out var loops) + || SurfaceCoedges(c, face, loops, edges) is not { Count: > 0 } coedges) return null; + + double signedArea = 0, perimeter = 0; + foreach (var coedge in coedges) + { + var (u0, v0) = coedge.Points[0]; + var (u1, v1) = coedge.Points[^1]; + var edge = edges[coedge.SourceEdge]!; + uint neighbor = coedge.SecondFace ? edge.FaceA : edge.FaceB; + if (!surfaces.TryGetValue(neighbor, out var side)) return null; + var uv = edge.AuthoredPoints().Select(point => coedge.SecondFace ? (point.UA, point.VA) : (point.UB, point.VB)).ToList(); + double segment = 0, length = Math.Sqrt((u1 - u0) * (u1 - u0) + (v1 - v0) * (v1 - v0)); + if (side.Kind == SurfKind.Cylinder || extrusions.ContainsKey(neighbor)) + { + double sweep = uv[^1].Item1 - uv[0].Item1; + if (uv.Any(point => Math.Abs(point.Item2 - uv[0].Item2) > tolerance)) return null; + double orientedRadii = side.R * side.R * normal.Dot(Pt3.Cross(Pt3.From(side.X), Pt3.From(side.Y))); + length = Math.Abs(sweep * side.R); + if (extrusions.TryGetValue(neighbor, out var ellipse)) + { + var p = ellipse.Profile; + double interval = p.T1 - p.T0; + sweep *= interval; + orientedRadii = p.R * p.RY * normal.Dot(Pt3.Cross(Pt3.From(p.X), Pt3.From(p.Y))); + if (!volumeOnly) + { + if (FaceArea.EllipticalArcLength(p.R, p.RY, p.T0 + uv[0].Item1 * interval, + p.T0 + uv[^1].Item1 * interval) is not double arcLength) return null; + length = arcLength; + } + } + // Green's formula for the segment between a conic arc and its chord. + segment = orientedRadii * (sweep - Math.Sin(sweep)); + } + else if (side.Kind != SurfKind.Plane || coedge.Points.Count != 2) return null; + signedArea += (coedge.Reversed ? -1 : 1) * (u0 * v1 - v0 * u1 + segment) / 2; + perimeter += length; + } + // Volume uses the geometric cross-section. Revit reports cap area by quadrature over the distinct UV samples. + double? area = volumeOnly ? 0 : FaceArea.ComputeWithDistinctSamples(coedges); + if (area is not double capArea || !double.IsFinite(signedArea)) return null; + caps.Add((axis.Dot(Pt3.From(surface.O)), signedArea * axis.Dot(normal) * (surface.Orient == 0 ? -1 : 1), + capArea, perimeter)); + } + if (caps is not [var first, var second] || first.SignedArea * second.SignedArea >= 0 + || Math.Abs(first.SignedArea + second.SignedArea) > tolerance + || (!volumeOnly && Math.Abs(first.Perimeter - second.Perimeter) > tolerance) + || Math.Abs(Math.Abs(first.Offset - second.Offset) - height) > tolerance) return null; + double volume = (first.Offset > second.Offset ? first.SignedArea : second.SignedArea) * height; + double surfaceArea = volumeOnly ? 0 : first.SurfaceArea + second.SurfaceArea + height * first.Perimeter; + return double.IsFinite(surfaceArea) && double.IsFinite(volume) ? (surfaceArea, volume) : null; + } + + private static (double Top, double Bottom)? MeasureHorizontalCaps(Cur c, HashSet faces, + Dictionary surfaces, Dictionary> loopsByFace) + { + double top = 0, bottom = 0; + var edges = EdgesByHandle(c); + foreach (uint face in faces) + { + if (!surfaces.TryGetValue(face, out var surface) || surface.Kind != SurfKind.Plane) continue; + double normal = MeshCross(surface.X, surface.Y)[2] * (MeshFlipped(c, face, surface) ? -1 : 1); + if (Math.Abs(normal) < 1 - 1e-9) continue; + if (!loopsByFace.TryGetValue(face, out var loops) || SurfaceCoedges(c, face, loops, edges) is not { } coedges + || FaceArea.Compute(coedges) is not double area) return null; + if (normal > 0) top += area; + else bottom += area; + } + return double.IsFinite(top) && double.IsFinite(bottom) ? (top, bottom) : null; + } + /// Area and SIGNED volume (negative when the faces point into the body, as the ones of a cutting body do) of a Geometry node - /// made of planes, cylinders and cones. + /// made of planes, cylinders, cones and supported surfaces of revolution, ruled surfaces or Hermite surfaces. // shortcut: unsupported surface kinds retain polygon quantities until their surface integrals are decoded. private static (double Area, double Volume)? MeasureAnalyticSolid(Cur c, IEnumerable handles, Dictionary surfaces, Dictionary> loopsByFace, - Dictionary edges) + Dictionary edges, bool measureRevolved, bool rawCoedges = false) { var faces = handles.ToList(); if (faces.Count == 0 || !surfaces.TryGetValue(faces[0], out var first) @@ -22,12 +235,22 @@ private static (double Area, double Volume)? MeasureAnalyticSolid(Cur c, IEnumer foreach (uint handle in faces) { if (!surfaces.TryGetValue(handle, out var surface) - || surface.Kind is not (SurfKind.Plane or SurfKind.Cylinder or SurfKind.Cone) || !loopsByFace.TryGetValue(handle, out var loops) - || SurfaceCoedges(c, handle, loops, edges) is not { Count: > 0 } coedges) + || SurfaceCoedges(c, handle, loops, edges, rawOnly: rawCoedges, + closeEndPole: rawCoedges && surface.Kind == SurfKind.Ruled && surface.P2 != null + && surface.ProfileHandle2 is 0 or uint.MaxValue) is not { Count: > 0 } coedges) return null; - if (MeasureAnalyticFace(surface, reference, coedges) is not { } measure) return null; + var result = surface.Kind switch + { + SurfKind.Rev when measureRevolved && c.Curves.TryGetValue(surface.ProfileHandle, out var profile) + => MeasureRevolvedFace(surface, profile, reference, coedges), + SurfKind.Ruled when rawCoedges => MeasureTrimmedRuledFace(c, surface, Pt3.From(reference), coedges), + SurfKind.Ruled when measureRevolved => MeasureRuledFace(c, surface, reference, coedges), + SurfKind.Hermite when rawCoedges && loops.Count == 1 => MeasureHermiteFace(surface, reference, coedges), + _ => MeasureAnalyticFace(surface, reference, coedges), + }; + if (result is not { } measure || rawCoedges && measure.Area <= 0) return null; double a = measure.Area, v = measure.Volume; area += a; volume += v; @@ -84,4 +307,200 @@ internal static (double Area, double Volume)? MeasureAnalyticFace(SurfaceRec sur return faceArea is { } a && faceVolume is { } v && double.IsFinite(a) && a >= 0 ? (a, v) : null; } + internal static (double Area, double Volume)? MeasureRevolvedFace(SurfaceRec surface, ArcRec profile, double[] reference, + IReadOnlyList coedges) + { + if (surface.Kind != SurfKind.Rev || surface.Env is not { Length: 4 } env || reference.Length != 3 + || coedges.Count == 0 || MeridionalProfile(profile, env[1], env[3]) is not { } evaluate) return null; + bool circle = profile.R > 0 && MeshProfileIsLineOrCircle(profile); + double[] delta = [reference[0] - surface.O[0], reference[1] - surface.O[1], reference[2] - surface.O[2]]; + double x = Dot3(delta, surface.X), y = Dot3(delta, surface.Y), z = Dot3(delta, surface.Z); + double handedness = Dot3(surface.X, MeshCross(surface.Y, surface.Z)) < 0 ? -1 : 1; + + // Integrate the area and the flux of (point - reference)/3 over the trimmed UV region via its coedges. + var area = FaceArea.Integrate(coedges, (u, v, _, dv) => + { + if (dv == 0) return 0; + var (point, tangent) = evaluate(v); + double speed = circle ? profile.R : Math.Sqrt(tangent.X * tangent.X + tangent.Z * tangent.Z); + return u * point.X * speed * dv; + }); + var volume = FaceArea.Integrate(coedges, (u, v, _, dv) => + { + if (dv == 0) return 0; + var (point, tangent) = evaluate(v); + return handedness * point.X / 3 * ((point.X * tangent.Z - (point.Z - z) * tangent.X) * u + - tangent.Z * (x * Math.Sin(u) - y * Math.Cos(u))) * dv; + }); + return area is { } a && volume is { } b ? (Math.Abs(a), b) : null; + } + + private static Func? MeridionalProfile(ArcRec profile, double from, double to) + { + const double tolerance = 1e-9; + if (!double.IsFinite(from) || !double.IsFinite(to) || from > to || profile.NurbControlPoints is { Count: > 0 }) + return null; + if (profile.HermiteNodes is { Count: > 0 } nodes) + { + if (!ValidHermiteProfile(nodes) || from < nodes[0].T - tolerance || to > nodes[^1].T + tolerance + || nodes.Any(node => Math.Abs(node.Point[1]) > tolerance || Math.Abs(node.Tangent[1]) > tolerance)) return null; + for (int i = 1; i < nodes.Count; i++) + { + var a = nodes[i - 1]; + var b = nodes[i]; + double dt = b.T - a.T; + // The Bernstein control radii bound each cubic span on the positive side of the axis. + if (Math.Min(a.Point[0], b.Point[0]) < -tolerance + || Math.Min(a.Point[0] + dt * a.Tangent[0] / 3, b.Point[0] - dt * b.Tangent[0] / 3) < -tolerance) + return null; + } + return v => EvaluateHermiteProfile(nodes, v); + } + + var center = Pt3.From(profile.C); + var x = Pt3.From(profile.X); + var y = Pt3.From(profile.Y); + if (!center.IsFinite || !x.IsFinite || !y.IsFinite || Math.Abs(x.Y) > tolerance || Math.Abs(y.Y) > tolerance + || !double.IsFinite(profile.R) || !double.IsFinite(profile.RY) || profile.R < 0 || profile.RY < 0) return null; + if (profile.R == 0) + return Math.Min(center.X + from * x.X, center.X + to * x.X) < -tolerance ? null : v => (center + v * x, x); + bool circle = MeshProfileIsLineOrCircle(profile); + var radialX = profile.R * x; + var radialY = (circle ? profile.R : profile.RY) * y; + double Radius(double v) => center.X + Math.Cos(v) * radialX.X + Math.Sin(v) * radialY.X; + double trough = Math.Atan2(radialY.X, radialX.X) + Math.PI; + trough += Math.Ceiling((from - trough) / (2 * Math.PI)) * (2 * Math.PI); + double minimum = Math.Min(Radius(from), Radius(to)); + if (trough < to) minimum = Math.Min(minimum, Radius(trough)); + if (!double.IsFinite(minimum) || minimum < -tolerance) return null; + if (circle) + return v => + { + double cos = Math.Cos(v), sin = Math.Sin(v); + return (center + profile.R * (cos * x + sin * y), profile.R * (-sin * x + cos * y)); + }; + return v => + { + var (sin, cos) = Math.SinCos(v); + return (center + cos * radialX + sin * radialY, cos * radialY - sin * radialX); + }; + } + + private static bool ValidHermiteProfile(IReadOnlyList nodes) + => nodes.Count >= 2 && nodes.All(node => double.IsFinite(node.T) && Pt3.From(node.Point).IsFinite && Pt3.From(node.Tangent).IsFinite) + && nodes.Zip(nodes.Skip(1)).All(pair => pair.First.T < pair.Second.T); + + private static (Pt3 Point, Pt3 Tangent) EvaluateHermiteProfile(IReadOnlyList nodes, double v) + { + int i = 1; + while (i < nodes.Count - 1 && v > nodes[i].T) i++; + var a = nodes[i - 1]; + var b = nodes[i]; + double dt = b.T - a.T; + Span weights = stackalloc double[4]; + Span derivatives = stackalloc double[4]; + FaceArea.HermiteBasis((v - a.T) / dt, weights, derivatives); + Pt3 pa = Pt3.From(a.Point), pb = Pt3.From(b.Point); + Pt3 ta = dt * Pt3.From(a.Tangent), tb = dt * Pt3.From(b.Tangent); + return (weights[0] * pa + weights[1] * pb + weights[2] * ta + weights[3] * tb, + (derivatives[0] * pa + derivatives[1] * pb + derivatives[2] * ta + derivatives[3] * tb) / dt); + } + + private static (double Area, double Volume)? MeasureRuledFace(Cur c, SurfaceRec surface, double[] reference, + IReadOnlyList coedges) + { + bool firstIsApex = surface.ProfileHandle is 0 or uint.MaxValue; + bool secondIsApex = surface.ProfileHandle2 is 0 or uint.MaxValue; + if (!firstIsApex && !secondIsApex + && c.Curves.TryGetValue(surface.ProfileHandle, out var first) + && c.Curves.TryGetValue(surface.ProfileHandle2, out var second)) + return MeasureRuledProfiles(first, second, Pt3.From(reference), coedges); + if (firstIsApex == secondIsApex || (firstIsApex ? surface.P1 : surface.P2) is not { Length: 3 } apex + || !c.Curves.TryGetValue(firstIsApex ? surface.ProfileHandle2 : surface.ProfileHandle, out var profile)) return null; + return MeasureRuledApex(profile, Pt3.From(apex), secondIsApex, Pt3.From(reference), coedges); + } + + internal static (double Area, double Volume)? MeasureRuledProfiles(ArcRec first, ArcRec second, Pt3 reference, + IReadOnlyList coedges) + { + const double tolerance = 1e-9; + if (first.R <= 0 || second.R <= 0 || !MeshProfileIsLineOrCircle(first) || !MeshProfileIsLineOrCircle(second) + || !(first.T1 > first.T0) || Math.Abs(first.T0 - second.T0) > tolerance || Math.Abs(first.T1 - second.T1) > tolerance + || (Pt3.From(first.X) - Pt3.From(second.X)).Norm > tolerance + || (Pt3.From(first.Y) - Pt3.From(second.Y)).Norm > tolerance + || coedges.Count != 4) return null; + + int sides = 0; + foreach (var edge in coedges) + { + if (edge.Points.Count < 2) return null; + var (u0, v0) = edge.Points[0]; + var (u1, v1) = edge.Points[^1]; + if (Math.Abs(u0 - u1) <= tolerance && Math.Abs(Math.Abs(v0 - v1) - 1) <= tolerance + && (Math.Abs(u0) <= tolerance || Math.Abs(u0 - 1) <= tolerance) + && edge.Points.All(point => Math.Abs(point.U - u0) <= tolerance)) + sides |= Math.Abs(u0) <= tolerance ? 1 : 2; + else if (Math.Abs(v0 - v1) <= tolerance && Math.Abs(Math.Abs(u0 - u1) - 1) <= tolerance + && (Math.Abs(v0) <= tolerance || Math.Abs(v0 - 1) <= tolerance) + && edge.Points.All(point => Math.Abs(point.V - v0) <= tolerance)) + sides |= Math.Abs(v0) <= tolerance ? 4 : 8; + } + if (sides != 15) return null; + + static Func Profile(ArcRec curve) + { + var center = Pt3.From(curve.C); + var x = curve.R * Pt3.From(curve.X); + var y = curve.R * Pt3.From(curve.Y); + double interval = curve.T1 - curve.T0; + return u => + { + var (sin, cos) = Math.SinCos(curve.T0 + u * interval); + return (center + cos * x + sin * y, interval * (cos * y - sin * x)); + }; + } + + var a = Profile(first); + var b = Profile(second); + (Pt3 Point, Pt3 Normal, Pt3 Change) Section(double u) + { + var (point, tangent) = a(u); + var (end, endTangent) = b(u); + var ruling = end - point; + return (point, Pt3.Cross(tangent, ruling), Pt3.Cross(endTangent - tangent, ruling)); + } + + var area = MeasureRuledArea(a, b, coedges); + var volume = FaceArea.Integrate(coedges, (u, v, du, _) => + { + var (point, normal, change) = Section(u); + return -(point - reference).Dot(normal + v / 2 * change) * v * du / 3; + }); + return area is { } surface && volume is { } solid ? (surface, solid) : null; + } + + internal static (double Area, double Volume)? MeasureRuledApex(ArcRec profile, Pt3 apex, bool apexAtEnd, Pt3 reference, + IReadOnlyList coedges) + { + if (!MeshProfileIsLineOrCircle(profile) || !(profile.T1 > profile.T0)) return null; + var center = Pt3.From(profile.C); + var x = Pt3.From(profile.X); + var y = Pt3.From(profile.Y); + double interval = profile.T1 - profile.T0; + double collapsedV = apexAtEnd ? 1 : 0; + Pt3 Normal(double u) + { + double t = profile.T0 + u * interval; + if (profile.R == 0) return Pt3.Cross(interval * x, center + t * x - apex); + var (sin, cos) = Math.SinCos(t); + var point = center + profile.R * (cos * x + sin * y); + return Pt3.Cross((profile.R * interval) * (cos * y - sin * x), point - apex); + } + + // A collapsed edge has no authored coedge, so integrate from that edge to make its contribution zero. + double Primitive(double v) => (v - collapsedV) * (v - collapsedV); + double? area = FaceArea.Integrate(coedges, (u, v, du, _) => Normal(u).Norm * Primitive(v) * du / 2); + double? volume = FaceArea.Integrate(coedges, (u, v, du, _) => -(apex - reference).Dot(Normal(u)) * Primitive(v) * du / 6); + return area is { } a && volume is { } b ? (Math.Abs(a), b) : null; + } } diff --git a/src/RvtIO/Parsing/GRepParserV2.cs b/src/RvtIO/Parsing/GRepParserV2.cs index a90f342b..a4be085b 100644 --- a/src/RvtIO/Parsing/GRepParserV2.cs +++ b/src/RvtIO/Parsing/GRepParserV2.cs @@ -785,22 +785,32 @@ static double Distance(double[] a, double[] b) => Math.Sqrt((a[0] - b[0]) * (a[0 } } + internal enum BodyMeasure { None, VisibleVolume, RawBodies, DirectionalRawSurface } + /// /// Decodes a GRep block at the Fine detail level, and also at the Coarse level when the block /// holds detail-level alternatives that differ (). /// /// Use native Low edge sampling only after confirming a unique own wall root and GRep. - public static GRepData? Parse(byte[] d, int blockStart, uint dataSize, bool nativeWallBody = false) + public static GRepData? Parse(byte[] d, int blockStart, uint dataSize, bool nativeWallBody = false, bool requireCompleteWalk = false, + bool measureSourceNodes = false, bool measureLighting = false, bool measureFills = false, BodyMeasure bodyMeasure = BodyMeasure.None) { - var fine = ParseCore(d, blockStart, dataSize, nativeWallBody); + var fine = ParseCore(d, blockStart, dataSize, nativeWallBody, requireCompleteWalk: requireCompleteWalk, measureSourceNodes: measureSourceNodes, + measureLighting: measureLighting, measureFills: measureFills, bodyMeasure: bodyMeasure); if (fine is not { HasDetailLevelAlternatives: true }) return fine; try { t_detailLevel = CoarseDetailLevel; - var coarse = ParseCore(d, blockStart, dataSize, nativeWallBody) ?? new GRepData(); + var coarse = ParseCore(d, blockStart, dataSize, nativeWallBody, requireCompleteWalk: requireCompleteWalk, measureSourceNodes: measureSourceNodes, + measureLighting: measureLighting, measureFills: measureFills, bodyMeasure: bodyMeasure); + if (coarse == null && requireCompleteWalk) return null; + coarse ??= new GRepData(); if (!IsSameDetailLevelGeometry(fine, coarse)) fine.Coarse = coarse; t_detailLevel = 2; - var medium = ParseCore(d, blockStart, dataSize, nativeWallBody) ?? new GRepData(); + var medium = ParseCore(d, blockStart, dataSize, nativeWallBody, requireCompleteWalk: requireCompleteWalk, measureSourceNodes: measureSourceNodes, + measureLighting: measureLighting, measureFills: measureFills, bodyMeasure: bodyMeasure); + if (medium == null && requireCompleteWalk) return null; + medium ??= new GRepData(); if (!IsSameDetailLevelGeometry(fine, medium)) fine.Medium = medium; } finally { t_detailLevel = 0; } @@ -822,13 +832,19 @@ private static bool SameVertices(List? a, List? b) /// Coarse level need not be kept. /// internal static bool IsSameDetailLevelGeometry(GRepData fine, GRepData coarse) => - fine.Faces.Count == coarse.Faces.Count + fine.LightingBodyMeasures == coarse.LightingBodyMeasures + && fine.SourceBodyMeasures == coarse.SourceBodyMeasures && fine.SourceCapAreas == coarse.SourceCapAreas + && fine.TrimmedBodyMeasures == coarse.TrimmedBodyMeasures + && fine.FilledArea == coarse.FilledArea + && fine.Faces.Count == coarse.Faces.Count && fine.Faces.Zip(coarse.Faces).All(pair => SameVertices(pair.First.Vertices, pair.Second.Vertices)) && fine.Instances.Count == coarse.Instances.Count && fine.Instances.Zip(coarse.Instances).All(pair => pair.First.SymbolElemId == pair.Second.SymbolElemId && pair.First.Transform.SequenceEqual(pair.Second.Transform)); - private static GRepData? ParseCore(byte[] d, int blockStart, uint dataSize, bool nativeWallBody, bool includeNonVisible = false) + private static GRepData? ParseCore(byte[] d, int blockStart, uint dataSize, bool nativeWallBody, bool includeNonVisible = false, + bool requireCompleteWalk = false, bool measureSourceNodes = false, bool measureLighting = false, bool measureFills = false, + BodyMeasure bodyMeasure = BodyMeasure.None) { int payloadStart = blockStart + 14; int payloadEnd = (int)Math.Min((long)blockStart + 16 + dataSize, d.Length); @@ -871,6 +887,7 @@ internal static bool IsSameDetailLevelGeometry(GRepData fine, GRepData coarse) = try { WalkQueueItem(c, qi); } catch (DecodeStop) { + if (requireCompleteWalk) return null; if (dbg) { var failed = qi < c.Queue.Count ? c.Queue[qi] : default; @@ -893,8 +910,10 @@ internal static bool IsSameDetailLevelGeometry(GRepData fine, GRepData coarse) = } } } - catch (DecodeStop) { if (dbg) DiagnosticSink.WriteLine($" V2 stop at pos={c.Pos}/{c.End} faces={c.FaceCount} edges={c.Edges.Count} queue={c.Queue.Count}"); } - catch (Exception ex) { if (dbg) DiagnosticSink.WriteLine($" V2 exc {ex.GetType().Name}: {ex.Message} at pos={c.Pos} faces={c.FaceCount} edges={c.Edges.Count}"); } + catch (DecodeStop) { if (requireCompleteWalk) return null; if (dbg) DiagnosticSink.WriteLine($" V2 stop at pos={c.Pos}/{c.End} faces={c.FaceCount} edges={c.Edges.Count} queue={c.Queue.Count}"); } + catch (Exception ex) { if (requireCompleteWalk) return null; if (dbg) DiagnosticSink.WriteLine($" V2 exc {ex.GetType().Name}: {ex.Message} at pos={c.Pos} faces={c.FaceCount} edges={c.Edges.Count}"); } + + if (requireCompleteWalk && c.Pos != c.End) return null; // Grammar-first harvest of a large unwalked tail: post-gap objects belong to queue entries // whose parents were never walked (never enqueued) - the queue can't reach them, but the @@ -1001,10 +1020,12 @@ string Number(double value) => value.ToString("G17", } } } - var built = BuildGeometry(c); + var built = BuildGeometry(c, requireCompleteWalk, measureSourceNodes, measureLighting, measureFills, bodyMeasure); if (built != null) { built.QueueClassCounts = c.Queue.GroupBy(item => item.Cls).ToDictionary(group => group.Key, group => group.Count()); + if (measureLighting && !built.QueueClassCounts.ContainsKey(GFaceClass)) built.LightingBodyMeasures = (0, 0, 0); + if (bodyMeasure != BodyMeasure.None && !built.QueueClassCounts.ContainsKey(GFaceClass)) built.SourceBodyMeasures = (0, 0, 0); built.HasDetailLevelAlternatives = c.SawDetailCondition; built.RootBoundingBox = ValidBox(c.RootBoundingBox) ? c.RootBoundingBox : null; } @@ -2362,14 +2383,15 @@ private static bool ValidBox(double[]? box) => box is { Length: 6 } && box[0] <= box[3] && box[1] <= box[4] && box[2] <= box[5]; - private static GRepData? BuildGeometry(Cur c) + private static GRepData? BuildGeometry(Cur c, bool requireCompleteWalk = false, bool measureSourceNodes = false, bool measureLighting = false, + bool measureFills = false, BodyMeasure bodyMeasure = BodyMeasure.None) { t_coarseTessellation = false; int enclosingUntriangulated = t_untriangulatedFaces; t_untriangulatedFaces = 0; try { - var geometry = BuildGeometryCore(c); + var geometry = BuildGeometryCore(c, requireCompleteWalk, measureSourceNodes, measureLighting, measureFills, bodyMeasure); if (geometry != null) geometry.UntriangulatedFaces = t_untriangulatedFaces; return geometry; } @@ -2380,7 +2402,8 @@ private static bool ValidBox(double[]? box) => box is { Length: 6 } } } - private static GRepData? BuildGeometryCore(Cur c) + private static GRepData? BuildGeometryCore(Cur c, bool requireCompleteWalk, bool measureSourceNodes, bool measureLighting, bool measureFills, + BodyMeasure bodyMeasure) { if (c.Edges.Count == 0 || (c.FaceOrder.Count == 0 && c.HarvestSurf.Count == 0)) return PolyMeshGeometry(c) ?? (c.Instances.Count > 0 ? InstanceGeometry(c) : null); @@ -2684,6 +2707,7 @@ void AddFractions(double start, double end, // faces that only the display-surface bit keeps out of the body (see // GRepData.DisplayOnlyNodes) var displayFaceHandles = new HashSet(); + var lightingFaceHandles = measureLighting || bodyMeasure == BodyMeasure.DirectionalRawSurface ? new HashSet() : null; var regionFaces = new HashSet(); var walkedFaceHandles = c.FaceOrder.ToHashSet(); var complexCutGeometryIndices = c.RootClass == 1829 @@ -2727,11 +2751,29 @@ void AddFractions(double start, double end, if (body) bodyFaceHandles.Add((uint)item.V); else if (IsPhysicalModelBranch(c, faceQueueIndex, allowDisplaySurface: true)) displayFaceHandles.Add((uint)item.V); + if (lightingFaceHandles != null && (body || IsPhysicalModelBranch(c, faceQueueIndex, forLightingQuantity: true))) + lightingFaceHandles.Add((uint)item.V); } var inactiveBodyFaceHandles = bodyFaceHandles.Where(deadFaces.Contains).ToArray(); bodyFaceHandles.ExceptWith(deadFaces); displayFaceHandles.ExceptWith(deadFaces); var loopsByFace = c.ExactPlanarSpaceBoundary && !c.CurvedSpaceBoundary ? new Dictionary>() : CompleteFaceLoops(c); + if (bodyMeasure != BodyMeasure.None) + { + var selected = lightingFaceHandles ?? bodyFaceHandles; + if (lightingFaceHandles == null) + { + var nodes = ResolveGeometryNodes(c.Queue, c.QueueLinks, c.ObjectGInfo); + selected.RemoveWhere(face => nodes.TryGetValue(face, out var node) && node.Node < 0); + } + else selected.ExceptWith(deadFaces); + gd.SourceBodyMeasures = selected.Count == 0 ? (0, 0, 0) + : MeasureClosedSourceBodies(c, selected, handleToSurf, loopsByFace, + volumeOnly: bodyMeasure == BodyMeasure.VisibleVolume, rawCoedges: bodyMeasure != BodyMeasure.VisibleVolume); + AttachInstances(gd, c, selected.Count != 0); + return gd; + } + if (measureFills) gd.FilledArea = MeasureFilledFaces(c, handleToSurf, loopsByFace); // The rings of an exact space boundary come from its segment graph; its serialized loops // only name the bounds of the IfcFace Revit writes for each Face (one bound per // loop, however many disjoint regions the Face owns). @@ -2745,6 +2787,15 @@ void AddFractions(double start, double end, var chainEdges = new HashSet(); if (c.Debug) DiagnosticSink.WriteLine($" V2 eid={c.ElementId} body-selection={bodyFaceHandles.Count}/{c.FaceOrder.Count} faces dead={deadFaces.Count} loop-lists={loopsByFace.Count}"); + if (lightingFaceHandles != null) + { + lightingFaceHandles.ExceptWith(deadFaces); + gd.LightingBodyMeasures = lightingFaceHandles.Count == 0 ? (0, 0, 0) + : MeasureClosedSourceBodies(c, lightingFaceHandles, handleToSurf, loopsByFace); + // A directional quantity with no nested instances needs only the source integral. + if (gd.LightingBodyMeasures.HasValue && c.Instances.Count == 0 && !c.ExactPlanarSpaceBoundary) + return gd; + } // Revit's solid is a Geometry node, whatever number of disjoint shells it holds, // and a node it does not take is marked with a negative id (the faces stay in the geometry @@ -2786,7 +2837,8 @@ void AddFractions(double start, double end, : displayFaceHandles.Where(handle => geometryNodeByFace.TryGetValue(handle, out var owner) && displayNodeSet.Contains(owner.Node)).ToHashSet(); var nodeMeasures = new List(); gd.MeshNodes = BuildNodes(c, handleToSurf, displayFaces.Count > 0 ? bodyFaceHandles.Concat(displayFaces).ToHashSet() : bodyFaceHandles, - inactiveBodyFaceHandles, loopsByFace, geometryNodeByFace, nodeOrders, displayFaces.Count > 0 ? displayOnlyNodes : null, nodeMeasures); + inactiveBodyFaceHandles, loopsByFace, geometryNodeByFace, nodeOrders, displayFaces.Count > 0 ? displayOnlyNodes : null, nodeMeasures, + measureSourceNodes: measureSourceNodes); if (nodeMeasures.Count > 0) gd.NodeMeasures = nodeMeasures; } if (displayOnlyNodes.Count > 0) gd.DisplayOnlyNodes = displayOnlyNodes; @@ -2827,12 +2879,14 @@ void AddFace(uint handle, GRepFace face) } if (!ReferenceEquals(boundedFace, face)) rejectedFaceHandles.Add(handle); var (faceNode, faceStyle) = geometryNodeByFace.GetValueOrDefault(handle, (0, -1)); + bool hasFaceGInfo = c.ObjectGInfo.TryGetValue((int)handle, out var faceGInfo); face = boundedFace with { SourceFace = handle, GeometryNode = faceNode, NodeOrder = faceNode != 0 ? nodeOrders.GetValueOrDefault(Math.Abs(faceNode) - 1) : 0, GeometryStyle = faceStyle, - GInfoFlags = c.ObjectGInfo.TryGetValue((int)handle, out var faceGInfo) ? faceGInfo.Flags : null, + GInfoFlags = hasFaceGInfo ? faceGInfo.Flags : null, + GInfoTag = hasFaceGInfo ? faceGInfo.Tag : null, MeshEdgeBounds = meshEdgeBounds.GetValueOrDefault(handle), // (the circular Edges of the loops the face was built from; the others are // leftovers of an earlier state of the join) @@ -3135,7 +3189,16 @@ bool InCore(List poly) } } - if (gd.Faces.Count == 0) + if (requireCompleteWalk && gd.LightingBodyMeasures == null && !bodyFaceHandles.SetEquals(faceIndicesByHandle.Keys)) + { + // The display bounds can clip a complete body, including the ends of circular piles. + if (!measureSourceNodes || MeasureClosedSourceBodies(c, bodyFaceHandles, handleToSurf, loopsByFace) is not { } measures) return null; + gd.SourceBodyMeasures = measures; + gd.SourceCapAreas = MeasureHorizontalCaps(c, bodyFaceHandles, handleToSurf, loopsByFace); + } + + if (gd.Faces.Count == 0 && gd.LightingBodyMeasures == null && gd.SourceBodyMeasures == null + && !(requireCompleteWalk && bodyFaceHandles.Count == 0)) return PolyMeshGeometry(c) ?? (c.Instances.Count > 0 ? InstanceGeometry(c) : null); if (c.ExactPlanarSpaceBoundary) @@ -3232,13 +3295,21 @@ bool InCore(List poly) && !regionFaces.Contains(edge.FaceA) && !regionFaces.Contains(edge.FaceB) && !chainFaces.Contains(edge.FaceA) && !chainFaces.Contains(edge.FaceB)) .Select(edge => (edge.FaceA, edge.FaceB)))); + if (measureSourceNodes && gd.Solids.Count > 1) + { + // The saved framing cut keeps the trimmed body's faces and the detached pieces in separate shells. + var keptFaces = bodyFaceHandles.Where(face => (c.ObjectGInfo.GetValueOrDefault((int)face).Flags & 0x00080000u) != 0).ToHashSet(); + if (keptFaces.Count > 0 && keptFaces.Count < bodyFaceHandles.Count + && gd.Solids.Any(solid => solid.IsClosed && keptFaces.SetEquals(solid.FaceIndices.Select(index => gd.Faces[index].SourceFace)))) + gd.TrimmedBodyMeasures = MeasureAnalyticSolid(c, c.FaceOrder.Where(keptFaces.Contains), handleToSurf, loopsByFace, EdgesByHandle(c), true); + } int polyMeshFaceCount = AppendPolyMeshes(gd, c); gd.BoundingBox = authoritativeBounds is { Length: 6 } ? (double[])authoritativeBounds.Clone() : GeometryBounds(gd.Faces) ?? new[] { minx, miny, minz, maxx, maxy, maxz }; bool hasCompleteResolvedBody = bodyFaceHandles.Count > 0 - && bodyFaceHandles.All(faceIndicesByHandle.ContainsKey) + && (gd.SourceBodyMeasures.HasValue || bodyFaceHandles.All(faceIndicesByHandle.ContainsKey)) && polyMeshFaceCount == 0; AttachInstances(gd, c, hasCompleteResolvedBody); System.Threading.Interlocked.Increment(ref DbgWorldElems); @@ -3508,7 +3579,7 @@ internal static uint NodeSurfaceFlags(int nodeClass, bool exactPlanarSpaceBounda => exactPlanarSpaceBoundary && nodeClass == 1589 || nodeClass == 2038 ? flags & ~0x40000000u : flags; /// Evaluate the serialized ownership path of a drawable GNode. - private static bool IsPhysicalModelBranch(Cur c, int nodeQueueIndex, bool allowDisplaySurface = false) + private static bool IsPhysicalModelBranch(Cur c, int nodeQueueIndex, bool allowDisplaySurface = false, bool forLightingQuantity = false) { // (a display surface is taken only below filters whose every condition is one this decoder // evaluates) @@ -3519,7 +3590,7 @@ private static bool IsPhysicalModelBranch(Cur c, int nodeQueueIndex, bool allowD var node = c.Queue[nodeQueueIndex]; if (c.ObjectGInfo.TryGetValue(node.V, out var nodeInfo) && !IsPhysicalBodySurface(NodeSurfaceFlags(node.Cls, c.ExactPlanarSpaceBoundary, nodeInfo.Flags) - & (allowDisplaySurface ? ~DisplaySurfaceBit : ~0u))) + & (allowDisplaySurface ? ~DisplaySurfaceBit : ~0u) & (forLightingQuantity ? ~0x40000000u : ~0u))) return false; bool body = true; @@ -3537,7 +3608,7 @@ private static bool IsPhysicalModelBranch(Cur c, int nodeQueueIndex, bool allowD if (c.ObjectGInfo.TryGetValue(ancestorItem.V, out var geometryInfo)) { graphicalGeometryState = (geometryInfo.Flags & 0x000000E0u) != 0; - body = IsPhysicalBodyGeometry(geometryInfo.Flags, c.IncludeNonVisible); + body = forLightingQuantity || IsPhysicalBodyGeometry(geometryInfo.Flags, c.IncludeNonVisible); } } if (ancestorItem.Cls != 2015) continue; @@ -3570,8 +3641,8 @@ private static bool IsPhysicalModelBranch(Cur c, int nodeQueueIndex, bool allowD && (!c.ObjectGInfo.TryGetValue( c.Queue[instance.OwnerQueueIndex].V, out var instanceInfo) || IsPhysicalBodySurface(instanceInfo.Flags))); - body = IsPhysicalBodyGeometryState( - graphicalGeometryState, hasRootMappedSource, conditions) + // Lighting quantities include solids from every direction at the selected detail level. + body = (forLightingQuantity || IsPhysicalBodyGeometryState(graphicalGeometryState, hasRootMappedSource, conditions)) && AllowsFineUncutModelBranch(conditions) && (!allowDisplaySurface || conditions.All(IsEvaluatedModelCondition)); } @@ -4205,10 +4276,9 @@ double[] P(double u, double v) s.O[2] + radial * (Math.Cos(u) * s.X[2] + Math.Sin(u) * s.Y[2]) + axial * s.Z[2], }; } - double[] TrimPoint(double u, double v) => EvaluateTrimBoundaryChord( - u, v, samplingEdges, P, worldBoundary); + var trimPoint = TrimBoundaryEvaluator(samplingEdges, P, worldBoundary); var trimmed = TessellateTrimmedGrid( - edges, uSamples, vSamples, TrimPoint, refineV: false); + edges, uSamples, vSamples, trimPoint, refineV: false); if (trimmed != null) { foreach (var polygon in trimmed) yield return polygon; @@ -4310,10 +4380,9 @@ double[] Point(double u, double v) Math.Max(Math.Abs(arc.R), Math.Abs(arc.RY))); } } - double[] TrimPoint(double u, double v) => EvaluateTrimBoundaryChord( - u, v, samplingEdges, Point); + var trimPoint = TrimBoundaryEvaluator(samplingEdges, Point); var trimmed = TessellateTrimmedGrid( - edges, uSamples, vSamples, TrimPoint, refineV: true); + edges, uSamples, vSamples, trimPoint, refineV: true); if (trimmed != null) { foreach (var polygon in trimmed) yield return polygon; @@ -4586,26 +4655,42 @@ internal static double MaxAbsIgnoringNaN(double a, double b, double c, double d, return value; } - private static double[] EvaluateTrimBoundaryChord(double u, double v, + internal static Func TrimBoundaryEvaluator( IReadOnlyList<(double U1, double V1, double U2, double V2)> authoredEdges, Func evaluate, IReadOnlyList<(double[] First, double[] Second)>? worldBoundary = null) { - const double machineEpsilon = 2.2204460492503131e-16; + double edgeScale = 1.0; + foreach (var edge in authoredEdges) + edgeScale = Math.Max(edgeScale, MaxAbsIgnoringNaN(edge.U1, edge.V1, edge.U2, edge.V2, 0, 0)); + return (u, v) => EvaluateTrimBoundaryChord(u, v, authoredEdges, evaluate, worldBoundary, edgeScale); + } + + private static double[] EvaluateTrimBoundaryChord(double u, double v, + IReadOnlyList<(double U1, double V1, double U2, double V2)> authoredEdges, + Func evaluate, IReadOnlyList<(double[] First, double[] Second)>? worldBoundary, + double edgeScale) + { + const double toleranceFactor = 128 * 2.2204460492503131e-16; + double scale = Math.Max(edgeScale, Math.Max(Math.Abs(u), Math.Abs(v))); + bool useBounds = IsFinite(scale); + double maxTolerance = toleranceFactor * scale; + double maxDistanceSquared = maxTolerance * maxTolerance; int bestEdge = -1; - double bestFraction = 0; double bestDistanceSquared = double.PositiveInfinity; for (int edgeIndex = 0; edgeIndex < authoredEdges.Count; edgeIndex++) { var edge = authoredEdges[edgeIndex]; double du = edge.U2 - edge.U1, dv = edge.V2 - edge.V1; + if (useBounds && (Outside(u, edge.U1, du, maxDistanceSquared) || Outside(v, edge.V1, dv, maxDistanceSquared))) + continue; double lengthSquared = du * du + dv * dv; if (lengthSquared == 0 || !IsFinite(lengthSquared)) continue; double fraction = ((u - edge.U1) * du + (v - edge.V1) * dv) / lengthSquared; double parameterScale = Math.Max(1, MaxAbsIgnoringNaN(u, v, edge.U1, edge.V1, edge.U2, edge.V2)); - double parameterTolerance = 128 * machineEpsilon * parameterScale; + double parameterTolerance = toleranceFactor * parameterScale; if (fraction < -parameterTolerance || fraction > 1 + parameterTolerance) continue; fraction = Math.Clamp(fraction, 0, 1); @@ -4617,7 +4702,6 @@ private static double[] EvaluateTrimBoundaryChord(double u, double v, || distanceSquared >= bestDistanceSquared) continue; bestEdge = edgeIndex; - bestFraction = fraction; bestDistanceSquared = distanceSquared; } if (bestEdge < 0) return evaluate(u, v); @@ -4627,7 +4711,7 @@ private static double[] EvaluateTrimBoundaryChord(double u, double v, // Orthogonal projection mixes both rounded coordinates; two adjacent clipping cells can // then produce fractions separated by one floating-point bit for the same topological // point. - bestFraction = Math.Abs(boundaryDu) >= Math.Abs(boundaryDv) + double bestFraction = Math.Abs(boundaryDu) >= Math.Abs(boundaryDv) ? (u - boundary.U1) / boundaryDu : (v - boundary.V1) / boundaryDv; bestFraction = Math.Clamp(bestFraction, 0, 1); @@ -4639,6 +4723,14 @@ private static double[] EvaluateTrimBoundaryChord(double u, double v, first[1] + (second[1] - first[1]) * bestFraction, first[2] + (second[2] - first[2]) * bestFraction, ]; + + static bool Outside(double point, double start, double direction, double limitSquared) + { + // Use the rounded projection endpoints to bound the same arithmetic as the exact test. + double end = start + direction; + double distance = Math.Max(Math.Min(start, end) - point, point - Math.Max(start, end)); + return distance > 0 && distance * distance > limitSquared; + } } @@ -5188,6 +5280,7 @@ internal static List> ClipGridCells(List> sourcePo { int uTempCount = ClipFlat(buffers.Source, sourceCount, 0, uSamples[uIndex], true, ref buffers.UTemp); int uCount = ClipFlat(buffers.UTemp, uTempCount, 0, uSamples[uIndex + 1], false, ref buffers.UClipped); + if (uCount == 0) continue; int vCellCount = allVCells ? vSamples.Count - 1 : 1; for (int vIndex = 0; vIndex < vCellCount; vIndex++) { @@ -5499,12 +5592,11 @@ double[] Point(double u, double v) (1 - v) * p1[2] + v * p2[2], }; } - double[] TrimPoint(double u, double v) => EvaluateTrimBoundaryChord( - u, v, samplingEdges, Point); + var trimPoint = TrimBoundaryEvaluator(samplingEdges, Point); // Clip the frozen interior grid by the refined trim loop. var trimmed = TessellateTrimmedGrid(edges, uSamples, - [vMin, vMax], TrimPoint, refineV: false); + [vMin, vMax], trimPoint, refineV: false); if (trimmed != null) { foreach (var polygon in trimmed) yield return polygon; @@ -5516,8 +5608,8 @@ double[] TrimPoint(double u, double v) => EvaluateTrimBoundaryChord( double ua = uSamples[i], ub = uSamples[i + 1]; var quad = new List { - TrimPoint(ua, vMin), TrimPoint(ub, vMin), - TrimPoint(ub, vMax), TrimPoint(ua, vMax), + trimPoint(ua, vMin), trimPoint(ub, vMin), + trimPoint(ub, vMax), trimPoint(ua, vMax), }; bool ok = true; foreach (var q in quad) if (!IsFinite(q[0]) || !IsFinite(q[1]) || !IsFinite(q[2])) { ok = false; break; } @@ -5609,16 +5701,19 @@ int Node(double[] p) } var componentByNode = Enumerable.Repeat(-1, points.Count).ToArray(); - int componentCount = 0; + var branchedComponents = new List(); for (int seed = 0; seed < points.Count; seed++) { if (degree[seed] < 2 || componentByNode[seed] >= 0) continue; + int component = branchedComponents.Count; + bool branched = false; var queue = new Queue(); - componentByNode[seed] = componentCount; + componentByNode[seed] = component; queue.Enqueue(seed); while (queue.Count > 0) { int node = queue.Dequeue(); + branched |= degree[node] > 2; for (int slot = adjacentStart[node]; slot < adjacentStart[node + 1]; slot++) { int edgeIndex = adjacentEdges[slot]; @@ -5626,27 +5721,54 @@ int Node(double[] p) var edge = graphEdges[edgeIndex]; int other = edge.A == node ? edge.B : edge.A; if (componentByNode[other] >= 0) continue; - componentByNode[other] = componentCount; + componentByNode[other] = component; queue.Enqueue(other); } } - componentCount++; + branchedComponents.Add(branched); } + int componentCount = branchedComponents.Count; // For every surviving edge, find the shortest alternate path between its ends. Together - // they form the smallest cycle containing that edge. Dedup by edge set; on ordinary - // degree-2 loops every edge discovers the exact same boundary. - var candidates = new List<(List Ring, HashSet Edges, double Area, int Component)>(); + // they form the smallest cycle containing that edge. In a degree-2 component only the + // first edge needs a search, and it fixes the original order and direction of the loop. + var candidates = new List<(List Ring, HashSet? Edges, double Area, int Component)>(); var seenCycles = new HashSet(); - var pathPrevNode = new int[points.Count]; - var pathPrevEdge = new int[points.Count]; + var visitedSimpleLoops = new bool[componentCount]; + bool hasBranches = branchedComponents.Contains(true); + var pathPrevNode = hasBranches ? new int[points.Count] : []; + var pathPrevEdge = hasBranches ? new int[points.Count] : []; var pathQueue = new Queue(); for (int excluded = 0; excluded < graphEdges.Count; excluded++) { if (!active[excluded]) continue; var target = graphEdges[excluded]; + int component = componentByNode[target.A]; + if (!branchedComponents[component]) + { + if (visitedSimpleLoops[component]) continue; + visitedSimpleLoops[component] = true; + var simpleRing = new List { points[target.A] }; + // Follow the unique alternate path, in the same direction as the general search. + int previousEdge = excluded, node = target.A; + while (node != target.B) + { + for (int slot = adjacentStart[node]; slot < adjacentStart[node + 1]; slot++) + { + int nextEdge = adjacentEdges[slot]; + if (nextEdge == previousEdge || !active[nextEdge]) continue; + var edge = graphEdges[nextEdge]; + node = edge.A == node ? edge.B : edge.A; + simpleRing.Add(points[node]); + previousEdge = nextEdge; + break; + } + } + double simpleArea = NewellNormalArea(simpleRing).Area; + if (simpleArea >= 1e-8) candidates.Add((simpleRing, null, simpleArea, component)); + continue; + } Array.Fill(pathPrevNode, -1); - Array.Fill(pathPrevEdge, -1); pathQueue.Clear(); pathPrevNode[target.A] = target.A; pathQueue.Enqueue(target.A); @@ -5681,13 +5803,13 @@ int Node(double[] p) if (!seenCycles.Add(cycleKey)) continue; var ring = cycleNodes.Select(i => points[i]).ToList(); double area = NewellNormalArea(ring).Area; - if (area >= 1e-8) candidates.Add((ring, cycleEdges, area, componentByNode[target.A])); + if (area >= 1e-8) candidates.Add((ring, cycleEdges, area, component)); } // Shortest paths can prefer a collinear zero-area shortcut and never expose the real inner // cycle (roof reveals are a common example). int activeEdgeCount = active.Count(x => x); - if (points.Count <= 48 && activeEdgeCount <= 64) + if (hasBranches && points.Count <= 48 && activeEdgeCount <= 64) { int cycleBudget = 4096; var visited = new bool[points.Count]; @@ -5728,7 +5850,8 @@ void SearchCycles(int start, int node, List pathNodes, List pathEdges) for (int start = 0; start < points.Count && cycleBudget > 0; start++) { - if (componentByNode[start] < 0) continue; + int component = componentByNode[start]; + if (component < 0 || !branchedComponents[component]) continue; visited[start] = true; SearchCycles(start, start, new List { start }, new List()); visited[start] = false; @@ -5767,12 +5890,17 @@ static double ExtentScore(List ring) } foreach (var component in candidates.GroupBy(c => c.Component).OrderBy(g => g.Key)) { + if (!branchedComponents[component.Key]) + { + result.Add(component.First().Ring); + continue; + } var cycles = component.OrderBy(c => c.Area) .ThenBy(c => ExtentScore(c.Ring)) .ThenBy(c => c.Ring.Count).ToList(); var primary = cycles[0]; var outerMatch = cycles.Skip(1) - .Where(cycle => !cycle.Edges.Overlaps(primary.Edges)) + .Where(cycle => !cycle.Edges!.Overlaps(primary.Edges!)) .Select(cycle => { bool contains = RingContains(cycle.Ring, primary.Ring, out bool touchesBoundary); @@ -5794,11 +5922,11 @@ static double ExtentScore(List ring) // describes a notch/opening cut and must not become an IfcFaceBound. if (!outerMatch.TouchesBoundary) result.Add(primary.Ring); var selectedEdges = new HashSet(); - selectedEdges.UnionWith(outer.Edges); - selectedEdges.UnionWith(primary.Edges); + selectedEdges.UnionWith(outer.Edges!); + selectedEdges.UnionWith(primary.Edges!); foreach (var cycle in cycles) { - if (cycle.Edges.Overlaps(selectedEdges) + if (cycle.Edges!.Overlaps(selectedEdges) || !RingContains(outer.Ring, cycle.Ring, out bool touchesBoundary) || touchesBoundary) continue; result.Add(cycle.Ring); diff --git a/src/RvtIO/Parsing/NativeTypePointers.cs b/src/RvtIO/Parsing/NativeTypePointers.cs index 578978fd..2802e238 100644 --- a/src/RvtIO/Parsing/NativeTypePointers.cs +++ b/src/RvtIO/Parsing/NativeTypePointers.cs @@ -12,11 +12,13 @@ internal static class NativeTypePointers [332] = "160:m_styleSymbolId", [380] = "381:m_symbolId", [485] = "485:m_stairsRailingAttrId", + [527] = "527:m_symbolId", [565] = "565:m_buildingPadTypeId", [598] = "602:m_idType", [642] = "642:m_ceilingAttributesId", [689] = "689:m_symbolId", [754] = "604:m_typeId", + [804] = "804:m_typeId", [838] = "3430:m_symbolId", [986] = "108:m_dbViewTypeId", [993] = "108:m_dbViewTypeId", @@ -42,6 +44,7 @@ internal static class NativeTypePointers [2534] = "2534:m_typeId", [3054] = "1605:m_roofAttributesId", [3095] = "160:m_styleSymbolId", + [3111] = "3111:m_stairsAttrId", [3134] = "602:m_idType", [3148] = "602:m_idType", [3177] = "602:m_idType", @@ -60,6 +63,7 @@ internal static class NativeTypePointers [3727] = "3727:m_typeId", [3892] = "3892:m_typeId", [3971] = "3928:m_attrId", + [3989] = "823:m_typeId", [4157] = "4157:m_typeId", }; diff --git a/src/RvtIO/Parsing/RebarReader.ShapeDriven.cs b/src/RvtIO/Parsing/RebarReader.ShapeDriven.cs index 127ad71d..b5575ffa 100644 --- a/src/RvtIO/Parsing/RebarReader.ShapeDriven.cs +++ b/src/RvtIO/Parsing/RebarReader.ShapeDriven.cs @@ -301,6 +301,7 @@ private static bool ConstraintsValid(WideBlockWalker walker, WideBlockWalker.Wal if (bar.Included.Count != 0 && bar.Included[i] == 0) continue; bars.Add(first.Select(s => bar.Held ? s.Moved(bar.Positions[i]) : s.Moved(bar.Positions[i]).Moved(bar.Positions[i])).ToList()); } - return new RebarBars(bar.BarTypeId, 0, bar.BarLength, bars, ShapeName: bar.ShapeId.ToString(CultureInfo.InvariantCulture), InAssembly: bar.InAssembly); + return new RebarBars(bar.BarTypeId, 0, bar.BarLength, bars, ShapeName: bar.ShapeId.ToString(CultureInfo.InvariantCulture), + InAssembly: bar.InAssembly, ShapeId: bar.ShapeId); } } diff --git a/src/RvtIO/Parsing/RebarReader.cs b/src/RvtIO/Parsing/RebarReader.cs index a452c80d..ee238979 100644 --- a/src/RvtIO/Parsing/RebarReader.cs +++ b/src/RvtIO/Parsing/RebarReader.cs @@ -49,7 +49,7 @@ private static double[] Point(double[] t, double[] p) /// is true for a RebarInSystem that is the one RebarInSystem of its system. internal sealed record RebarBars(int BarTypeId, int SystemId, double? BarLength, IReadOnlyList> Bars, double NominalDiameter = 0, double ModelDiameter = 0, string? BarTypeName = null, double LengthRoundingMillimetres = 0, string? ShapeName = null, - bool InAssembly = false, IReadOnlyList? Items = null, int ItemIndex = -1, bool OnlyBarOfSystem = false); + bool InAssembly = false, IReadOnlyList? Items = null, int ItemIndex = -1, bool OnlyBarOfSystem = false, int ShapeId = 0); /// A beam system (JoistSystem): its type (JoistSystemAttr, from SymbolInfo.m_name) and the beams it holds /// (HeldBeam.m_existingBeamId, in stored order, deleted ones left out). @@ -547,8 +547,10 @@ private static List WithCuts(WideBlockWalker walker, WideBlockWalker.Walk } double? length = caps.FirstOrDefault(c => c.Key == "RebarInstBase.m_barLength" && c.Kind == WideBlockWalker.CaptureKind.Real) is { } l ? l.Real : null; // the shape id travels in ShapeName until the shapes are read + long shape = Integer(caps, "RebarInstBase.m_shapeId") ?? 0; return new RebarBars((int)(Integer(caps, "RebarInstBase.m_barTypeId") ?? -1), 0, length, bars, - ShapeName: (Integer(caps, "RebarInstBase.m_shapeId") ?? 0).ToString(CultureInfo.InvariantCulture), InAssembly: InAssembly(walker, walk, byQueue)); + ShapeName: shape.ToString(CultureInfo.InvariantCulture), InAssembly: InAssembly(walker, walk, byQueue), + ShapeId: shape is > 0 and <= int.MaxValue ? (int)shape : 0); } /// The queue indexes the queued object appended while it was read. diff --git a/src/RvtIO/Parsing/Revit2027ApiValues.HostQuantities.cs b/src/RvtIO/Parsing/Revit2027ApiValues.HostQuantities.cs new file mode 100644 index 00000000..55337be7 --- /dev/null +++ b/src/RvtIO/Parsing/Revit2027ApiValues.HostQuantities.cs @@ -0,0 +1,203 @@ +using RvtIO.BuiltIns; +using RvtIO.Internal; +using RvtIO.Model; + +namespace RvtIO.Parsing; + +internal static partial class Revit2027ApiValues +{ + private const int Coarse = 0, Medium = 1, Fine = 2; + + private static void ApplyHostQuantities(RevitFileInfo info, ParsingState state, IReadOnlyDictionary elementsById) + { + if (!info.ElemTableIsExact || state.WideSchema is not { } schema + || state.FramedPartitions is not { Count: > 0 } frames || frames.Any(frame => frame?.IdWidth != 8)) return; + WideSolidQuantities? geometry = null; + foreach (var element in info.Elements) + { + var (areaLevel, volumeLevel) = QuantityLevels(element); + bool horizontal = UsesHorizontalHostArea(element); + bool extrusionRoof = element is { NativeRootClassName: "Roof", CategoryId: (int)BuiltInCategory.OST_Roofs }; + bool rawSurface = element.NativeRootClassName == "FamilyInstance" && (BuiltInCategory?)element.CategoryId is + BuiltInCategory.OST_GenericModel or BuiltInCategory.OST_PlumbingFixtures or BuiltInCategory.OST_Mass + or BuiltInCategory.OST_Site or BuiltInCategory.OST_Furniture; + bool rawVolume = rawSurface && element.CategoryId != (int)BuiltInCategory.OST_Mass; + bool door = element is { NativeRootClassName: "FamilyInstance", CategoryId: (int)BuiltInCategory.OST_Doors }; + bool filled = element.NativeRootClassName == "FilledRegion" || element.NativeRootClassName == "FamilyInstance" + && (BuiltInCategory?)element.CategoryId is BuiltInCategory.OST_GenericAnnotation or BuiltInCategory.OST_SpotElevSymbols + or BuiltInCategory.OST_DetailComponents; + string? wallType = element.NativeRootClassName == "SWall" && element.CategoryId == (int)BuiltInCategory.OST_Walls + && ExactRoot(state, element.TypeId) != null ? state.NativeRootClassNames.GetValueOrDefault((uint)element.TypeId) : null; + bool wallArea = wallType is "BasicWallType" or "NewCurtainWallType"; + if (wallType == "BasicWallType") volumeLevel = Coarse; + bool areaMissing = (areaLevel.HasValue || wallArea || horizontal || extrusionRoof || door || filled || rawSurface) + && !HasValue(element, BuiltInParameter.HOST_AREA_COMPUTED); + bool volumeMissing = (volumeLevel.HasValue || rawVolume) && !HasValue(element, BuiltInParameter.HOST_VOLUME_COMPUTED); + if ((!areaMissing && !volumeMissing) || ExactRoot(state, element.Id) is not { } root) continue; + + geometry ??= new WideSolidQuantities(schema, frames); + bool curtainDoor = false; + if (wallArea && areaMissing) + { + bool curtain = wallType == "NewCurtainWallType"; + double? width = state.CompoundLayers.GetValueOrDefault((uint)element.TypeId)?.Sum(layer => layer.ThicknessFt); + if ((curtain || width is > 0) && root.DoubleFields.TryGetValue("87:m_pCrv.dirVec@0", out double dx) + && root.DoubleFields.TryGetValue("87:m_pCrv.dirVec@1", out double dy) + && root.DoubleFields.TryGetValue("87:m_pCrv.dirVec@2", out double dz)) + SetQuantity(element, BuiltInParameter.HOST_AREA_COMPUTED, geometry.WallArea(element.Id, dx, dy, dz, curtain ? null : width, curtain)); + } + if (horizontal && areaMissing) + SetQuantity(element, BuiltInParameter.HOST_AREA_COMPUTED, geometry.HorizontalArea(element.Id, + bottom: element.CategoryId == (int)BuiltInCategory.OST_StructuralFoundation)); + if (extrusionRoof && areaMissing && root.RoofExtrusionFaceTags is { Count: > 0 } tags) + SetQuantity(element, BuiltInParameter.HOST_AREA_COMPUTED, geometry.RoofArea(element.Id, tags)); + if (door) + { + Element? host = element.SerializedHostId is > 0 and int hostId ? elementsById.GetValueOrDefault(hostId) : null; + curtainDoor = state.CurtainFamilyHostSource.TryGetValue((uint)element.Id, out var curtainSource) + && curtainSource.BlockCount == 1 && curtainSource.Host is { ReferenceClass: 897, HostId: > 0, ReplacementElementId: null } + || host != null && RootIs(state, host.TypeId, "NewCurtainWallType"); + if (areaMissing) + { + if (curtainDoor) SetQuantity(element, BuiltInParameter.HOST_AREA_COMPUTED, geometry.CurtainDoorArea(element.Id)); + else if (host != null && RootIs(state, host.TypeId, "BasicWallType")) + SetQuantity(element, BuiltInParameter.HOST_AREA_COMPUTED, + geometry.Measure(element.Id, WideSolidQuantities.Source.Directional)?[Coarse]?.Surface / 2); + } + } + if (filled && areaMissing) + { + double? filledArea = element.NativeRootClassName == "FilledRegion" ? geometry.FilledArea(element.Id) + : root.Fields.TryGetValue("2237:m_symbolId", out int symbol) && RootIs(state, symbol, "FamilySymbol") + ? geometry.FilledArea(symbol) / 2 : null; + SetQuantity(element, BuiltInParameter.HOST_AREA_COMPUTED, filledArea); + } + if (!volumeMissing && (!areaMissing || areaLevel == null && !rawSurface)) continue; + var source = (BuiltInCategory?)element.CategoryId switch + { + BuiltInCategory.OST_LightingFixtures => WideSolidQuantities.Source.Directional, + BuiltInCategory.OST_PipeFitting or BuiltInCategory.OST_DuctFitting => WideSolidQuantities.Source.Fitting, + BuiltInCategory.OST_StructuralFraming => WideSolidQuantities.Source.StructuralFraming, + BuiltInCategory.OST_Doors when curtainDoor => WideSolidQuantities.Source.Analytic, + BuiltInCategory.OST_Floors or BuiltInCategory.OST_Walls or BuiltInCategory.OST_GenericModel + or BuiltInCategory.OST_SpecialityEquipment or BuiltInCategory.OST_PlumbingFixtures + or BuiltInCategory.OST_ConduitFitting or BuiltInCategory.OST_StructuralFoundation + or BuiltInCategory.OST_Furniture or BuiltInCategory.OST_MechanicalEquipment or BuiltInCategory.OST_Casework or BuiltInCategory.OST_Mass + => WideSolidQuantities.Source.Analytic, + _ => WideSolidQuantities.Source.Default, + }; + var levels = geometry.Measure(element.Id, source); + if (areaMissing && areaLevel is int detail && levels?[detail] is { } area) + { + double? amount = (BuiltInCategory?)element.CategoryId switch + { + BuiltInCategory.OST_CurtainWallPanels => area.LargestFace, + BuiltInCategory.OST_Mass => geometry.MassArea(element.Id, area), + _ => area.Surface / 2, + }; + SetQuantity(element, BuiltInParameter.HOST_AREA_COMPUTED, amount); + } + if (levels != null && areaMissing && (BuiltInCategory?)element.CategoryId is BuiltInCategory.OST_PipeFitting + or BuiltInCategory.OST_PlumbingFixtures or BuiltInCategory.OST_MechanicalEquipment + && !HasValue(element, BuiltInParameter.HOST_AREA_COMPUTED)) + SetQuantity(element, BuiltInParameter.HOST_AREA_COMPUTED, + geometry.Measure(element.Id, WideSolidQuantities.Source.Directional)?[Coarse]?.Surface / 2); + if (rawSurface && areaMissing && !HasValue(element, BuiltInParameter.HOST_AREA_COMPUTED)) + { + var surfaceSource = element.CategoryId == (int)BuiltInCategory.OST_PlumbingFixtures + ? WideSolidQuantities.Source.DirectionalRawSurface : WideSolidQuantities.Source.RawBodies; + if (geometry.Measure(element.Id, surfaceSource)?[Coarse] is { } surface + && (element.CategoryId != (int)BuiltInCategory.OST_Mass + || surface.BodyCount == 1 && geometry.HasOneHorizontalCap(element.Id))) + SetQuantity(element, BuiltInParameter.HOST_AREA_COMPUTED, surface.Surface / 2); + } + var volumeMeasure = volumeLevel is int index ? levels?[index] : null; + if (element.CategoryId == (int)BuiltInCategory.OST_ConduitFitting && volumeMeasure is null or { BodyCount: 0 }) + volumeMeasure = levels?[Fine]; + if (volumeMissing && volumeMeasure is null or { BodyCount: 0 } + && (BuiltInCategory?)element.CategoryId is BuiltInCategory.OST_PlumbingFixtures + or BuiltInCategory.OST_MechanicalEquipment or BuiltInCategory.OST_Doors + or BuiltInCategory.OST_GenericModel or BuiltInCategory.OST_SpecialityEquipment + && geometry.Measure(element.Id, WideSolidQuantities.Source.VisibleVolume) is { } visible) + { + volumeMeasure = visible[Coarse]; + if (element.CategoryId == (int)BuiltInCategory.OST_PlumbingFixtures && volumeMeasure is { BodyCount: 0 }) + volumeMeasure = visible[Medium]; + } + if (rawVolume && volumeMissing && volumeMeasure is null or { BodyCount: 0 }) + volumeMeasure = geometry.Measure(element.Id, WideSolidQuantities.Source.RawBodies)?[Coarse]; + if (volumeMissing && volumeMeasure is { } volume) + { + double? amount = (BuiltInCategory?)element.CategoryId switch + { + BuiltInCategory.OST_DuctFitting or BuiltInCategory.OST_PipeFitting => volume.Volume - volume.SharedCoarseVolume, + _ => volume.Volume, + }; + SetQuantity(element, BuiltInParameter.HOST_VOLUME_COMPUTED, amount); + } + } + + foreach (var line in info.Elements) + { + if (line.NativeRootClassName is not ("SegmentCenterLine" or "FlexCenterLine" or "PipeFittingCenterLine" + or "DuctFittingCenterLine" or "ConduitFittingCenterLine") || ExactRoot(state, line.Id) is not { } root + || !root.Fields.TryGetValue(CenterLineOwner, out int ownerId) || ownerId == line.Id + || ExactRoot(state, ownerId) == null || !elementsById.TryGetValue(ownerId, out var owner) + || QuantityLevels(owner).Volume == null) continue; + CopyParameter(line, owner, BuiltInParameter.HOST_VOLUME_COMPUTED); + if (line.NativeRootClassName is "PipeFittingCenterLine" or "DuctFittingCenterLine" or "ConduitFittingCenterLine") + CopyParameter(line, owner, BuiltInParameter.HOST_AREA_COMPUTED); + } + } + + private static bool UsesHorizontalHostArea(Element element) => (element.NativeRootClassName, (BuiltInCategory?)element.CategoryId) is + ("Floor", BuiltInCategory.OST_Floors or BuiltInCategory.OST_StructuralFoundation) + or ("Ceiling", BuiltInCategory.OST_Ceilings) + or ("ContFooting" or "FamilyInstance", BuiltInCategory.OST_StructuralFoundation) + or ("FamilyInstance", BuiltInCategory.OST_FurnitureSystems) + or ("BuildingPad", BuiltInCategory.OST_BuildingPad) or ("ProfileRoof", BuiltInCategory.OST_Roofs); + + private static (int? Area, int? Volume) QuantityLevels(Element element) + { + switch (element.NativeRootClassName, (BuiltInCategory?)element.CategoryId) + { + case ("RbsDuctCurve", BuiltInCategory.OST_DuctCurves): + case ("RbsFlexDuctCurve", BuiltInCategory.OST_FlexDuctCurves): + case ("RbsPipeCurve", BuiltInCategory.OST_PipeCurves): + case ("RbsConduitCurve", BuiltInCategory.OST_Conduit): + case ("Floor", BuiltInCategory.OST_Floors or BuiltInCategory.OST_StructuralFoundation): + case ("Ceiling", BuiltInCategory.OST_Ceilings): + case ("ContFooting" or "FamilyInstance", BuiltInCategory.OST_StructuralFoundation): + case ("BuildingPad", BuiltInCategory.OST_BuildingPad): + case ("ProfileRoof" or "Roof", BuiltInCategory.OST_Roofs): + case ("FamilyInstance", BuiltInCategory.OST_FurnitureSystems): + return (null, Coarse); + case ("FamilyInstance", BuiltInCategory.OST_Doors): + return (null, Coarse); + case ("FamilyInstance", BuiltInCategory.OST_Mass): + return (Coarse, null); + case ("FamilyInstance", BuiltInCategory.OST_StructuralFraming): + return (null, Fine); + case ("FamilyInstance", BuiltInCategory.OST_DuctFitting): + return (Coarse, Medium); + case ("FamilyInstance", BuiltInCategory.OST_PipeFitting or BuiltInCategory.OST_StructuralColumns): + return (Coarse, Fine); + case ("FamilyInstance", BuiltInCategory.OST_CurtainWallMullions or BuiltInCategory.OST_CurtainWallPanels + or BuiltInCategory.OST_DuctTerminal or BuiltInCategory.OST_ElectricalFixtures or BuiltInCategory.OST_ElectricalEquipment + or BuiltInCategory.OST_LightingDevices or BuiltInCategory.OST_LightingFixtures or BuiltInCategory.OST_StairsRailingBaluster or BuiltInCategory.OST_BoundaryConditions + or BuiltInCategory.OST_Furniture or BuiltInCategory.OST_MechanicalEquipment or BuiltInCategory.OST_Windows + or BuiltInCategory.OST_ConduitFitting or BuiltInCategory.OST_GenericModel or BuiltInCategory.OST_SpecialityEquipment + or BuiltInCategory.OST_PlumbingFixtures or BuiltInCategory.OST_Sprinklers or BuiltInCategory.OST_Columns or BuiltInCategory.OST_Casework): + return (Coarse, Coarse); + default: + return (null, null); + } + } + + private static bool HasValue(Element element, BuiltInParameter id) => element.Parameters.Any(p => p.Id == (int)id && p.HasRevitValue); + + private static void SetQuantity(Element element, BuiltInParameter id, double? value) + { + if (value is > 0 and double amount && double.IsFinite(amount)) SetParameter(element, id, StorageType.Double, amount); + } +} diff --git a/src/RvtIO/Parsing/Revit2027ApiValues.TypeNames.cs b/src/RvtIO/Parsing/Revit2027ApiValues.TypeNames.cs new file mode 100644 index 00000000..415bedac --- /dev/null +++ b/src/RvtIO/Parsing/Revit2027ApiValues.TypeNames.cs @@ -0,0 +1,60 @@ +using RvtIO.BuiltIns; +using RvtIO.Internal; + +namespace RvtIO.Parsing; + +internal static partial class Revit2027ApiValues +{ + private static string? TypeName(ParsingState state, string? kind, TfBlockDeserializer.NativeParams root) => kind switch + { + "TilePatternType" => root.StringFields.GetValueOrDefault(WideNativeParams.TilePatternName), + "GeoSite" => "Location Data", + "StairsTriserSymbol" when root.Fields.TryGetValue(TriserHost, out int host) => + RootIs(state, host, "StairsRun") ? "Run(Internal)" : RootIs(state, host, "StairsLanding") ? "Landing(Internal)" : null, + "ConceptualConstructionType" when root.Fields.TryGetValue(ConstructionCategory, out int category) + && root.Fields.TryGetValue(ConstructionKind, out int index) => + ConstructionNames.TryGetValue((BuiltInCategory)category, out var names) && (uint)index < names.Length ? names[index] : null, + _ => null, + }; + + // The same ordinal labels different constructions in each mass subcategory. + private static readonly IReadOnlyDictionary ConstructionNames = + new Dictionary + { + [BuiltInCategory.OST_MassWallsAll] = + [ + "Lightweight Construction - High Insulation", + "Lightweight Construction - Typical Cold Climate Insulation", + "Lightweight Construction - Typical Mild Climate Insulation", + "Lightweight Construction - Low Insulation", + "Lightweight Construction - No Insulation", + "High Mass Construction - High Insulation", + "High Mass Construction - Typical Cold Climate Insulation", + "High Mass Construction - Typical Mild Climate Insulation", + "High Mass Construction - No Insulation", + ], + [BuiltInCategory.OST_MassRoof] = + [ + "High Insulation - Cool Roof", "High Insulation - Dark Roof", + "Typical Insulation - Cool Roof", "Typical Insulation - Dark Roof", + "Low Insulation - Cool Roof", "Low Insulation - Dark Roof", "No Insulation - Dark Roof", + ], + [BuiltInCategory.OST_MassFloorsAll] = + [ + "Lightweight Construction - High Insulation", "Lightweight Construction - Typical Insulation", + "Lightweight Construction - Low Insulation", "Lightweight Construction - No Insulation", + "High Mass Construction - Frigid Climate Slab Insulation", "High Mass Construction - Cold Climate Slab Insulation", + "High Mass Construction - No Insulation", + ], + [BuiltInCategory.OST_MassShade] = ["Basic Shade"], + [BuiltInCategory.OST_MassGlazingAll] = + [ + "Single Pane Clear - No Coating", "Single Pane - Tinted", "Single Pane - Reflective", + "Double Pane Clear - No Coating", "Double Pane - Tinted", "Double Pane - Reflective", + "Double Pane Clear - LowE Cold Climate, High SHGC", "Double Pane Clear - LowE Hot Climate, Low SHGC", + "Double Pane Clear - High Performance, LowE, High Tvis, Low SHGC", + "Triple Pane Clear - LowE Hot or Cold Climate", "Quad Pane Clear - LowE Hot or Cold Climate", + ], + [BuiltInCategory.OST_MassOpening] = ["Air"], + }; +} diff --git a/src/RvtIO/Parsing/Revit2027ApiValues.cs b/src/RvtIO/Parsing/Revit2027ApiValues.cs new file mode 100644 index 00000000..1dded6d6 --- /dev/null +++ b/src/RvtIO/Parsing/Revit2027ApiValues.cs @@ -0,0 +1,223 @@ +using RvtIO.BuiltIns; +using RvtIO.Internal; +using RvtIO.Model; + +namespace RvtIO.Parsing; + +/// Revit 2027 API values backed by an element's exact record or a link from that record. +internal static partial class Revit2027ApiValues +{ + private static readonly string ZoneType = TfClassNames.Key("GenericZone", "m_typeId"); + private static readonly string StructuralMaterial = TfClassNames.Key("AnalyticalElement", "m_materialId"); + private static readonly string CenterLineOwner = TfClassNames.Key("CenterLine", "m_OwnerId"); + private static readonly string ViewMarker = TfClassNames.Key("DBView", "m_viewerId"); + private static readonly string ElevationParent = TfClassNames.Key("InteriorElevArrow", "m_parentId"); + private static readonly string ElevationType = TfClassNames.Key("InteriorElev", "m_symbolId"); + private static readonly string StairOwner = TfClassNames.Key("StairsRunAndLanding", "m_stairsId"); + private static readonly string StairType = TfClassNames.Key("StairsElement", "m_typeId"); + private static readonly string RunType = TfClassNames.Key("StairsType", "m_runTypeId"); + private static readonly string LandingType = TfClassNames.Key("StairsType", "m_landingTypeId"); + private static readonly string ConstructionCategory = TfClassNames.Key("ConceptualConstructionType", "m_massSurfaceSubCategoryId"); + private static readonly string ConstructionKind = TfClassNames.Key("ConceptualConstructionType", "m_conceptualConstructionTypeEnumAsInt"); + private static readonly string TriserHost = TfClassNames.Key("StairsTriserSymbol", "m_hostId"); + private static readonly string RegionSketch = TfClassNames.Key("SketchedRegion", "m_sketchId"); + private static readonly string SketchUser = TfClassNames.Key("SketchBase", "m_userId"); + + internal static readonly IReadOnlySet RootFields = + new HashSet([ZoneType, StructuralMaterial, CenterLineOwner, ViewMarker, ElevationParent, + ElevationType, StairOwner, StairType, RunType, LandingType, + ConstructionCategory, ConstructionKind, TriserHost, RegionSketch, SketchUser], StringComparer.Ordinal); + + internal static void Apply(RevitFileInfo info, ParsingState state, IReadOnlyDictionary elementsById) + { + if (state.WideSchema?.Release != 2027 || state.R22View) return; + foreach (var element in info.Elements) + { + if (ExactRoot(state, element.Id) is not { } root) continue; + string? kind = element.NativeRootClassName; + var fields = root.Fields; + if (kind == "GenericZone" && fields.TryGetValue(ZoneType, out int zoneType) + && RootIs(state, zoneType, "MEPSystemZoneElementType")) + { + element.TypeId = zoneType; + SetTypeParameters(element, zoneType); + } + if (element.NativeRootClassChain?.Contains("Viewer") == true + && fields.TryGetValue(WideNativeParams.ViewerViewKey, out int view) + && ExactRoot(state, view) is { } viewRoot + && viewRoot.Fields.TryGetValue("m_dbViewTypeId", out int viewType)) + { + if (viewType == -1 && kind == "InteriorElevArrow" + && state.NativeRootClassNames.GetValueOrDefault((uint)view) == "DBViewSection" + && viewRoot.Fields.GetValueOrDefault(ViewMarker) == element.Id) + viewType = LinkedElevationType(state, view, viewRoot); + if (RootIs(state, viewType, "DBViewType")) + { + element.TypeId = viewType; + if (kind is "Viewer3d" or "Section" or "GraphSchedColumnTable" or "InteriorElevArrow") + SetTypeParameters(element, viewType); + } + } + if (kind == "DBViewSection" && element.TypeId <= 0 && fields.GetValueOrDefault("m_dbViewTypeId") == -1) + { + int sectionType = LinkedElevationType(state, element.Id, root); + if (RootIs(state, sectionType, "DBViewType")) + { + element.TypeId = sectionType; + SetTypeParameters(element, sectionType); + } + } + if (element.NativeIsSymbol == true) + { + string? storedName = state.WideNames.GetValueOrDefault((uint)element.Id); + string? ownName = TypeName(state, kind, root) ?? storedName; + if (ownName != null) + SetTypeName(element, ownName, kind == "StairsTriserSymbol" && root.Strings.All(p => p.ParamId != (int)BuiltInParameter.ALL_MODEL_TYPE_NAME) + ? storedName : null); + } + + switch (kind) + { + case "FilledRegion" when fields.TryGetValue(RegionSketch, out int sketchId) + && ExactRootOf(state, sketchId, "VarSketch") is { } sketch + && sketch.Fields.GetValueOrDefault(SketchUser) == element.Id + && sketch.DoubleFields.TryGetValue(WideNativeParams.SketchLineArea, out double area): + SetParameter(element, BuiltInParameter.HOST_AREA_COMPUTED, StorageType.Double, area); + break; + case "RbsDuctCurve": + ApplyRectangularDuctVolume(state, element, root); + break; + case "StairsRun" or "StairsLanding" when element.TypeId <= 0: + if (fields.TryGetValue(StairOwner, out int stairId) + && ExactRootOf(state, stairId, "StairsElement") is { } stair + && stair.Fields.TryGetValue(StairType, out int stairTypeId) + && ExactRootOf(state, stairTypeId, "StairsType") is { } stairType + && stairType.Fields.TryGetValue(kind == "StairsRun" ? RunType : LandingType, out int partType) + && RootIs(state, partType, kind + "Type")) + { + element.TypeId = partType; + SetTypeParameters(element, partType); + } + break; + case "Property" when element.TypeId > 0: + // Property.m_attrId is the property line's attributes and GetTypeId returns InvalidElementId. + element.TypeId = -1; + foreach (var parameter in element.Parameters.Where(p => p.Id is -1002050 or -1002000 or -1002052 or -1002051)) + { + parameter.Value = -1; + parameter.HasNoRevitValue = true; + } + break; + case "Rebar" or "RebarInSystem" when element.RebarBars is { Bars.Count: > 0 } bar: + if (RootIs(state, bar.BarTypeId, "RebarBarType")) + SetTypeParameters(element, bar.BarTypeId); + SetParameter(element, BuiltInParameter.REBAR_ELEM_QUANTITY_OF_BARS, StorageType.Integer, bar.Bars.Count); + if (bar.BarLength is double length && double.IsFinite(length) && length > 0) + SetParameter(element, BuiltInParameter.REBAR_ELEM_LENGTH, StorageType.Double, length); + if (RootIs(state, bar.ShapeId, "RebarShape")) + SetParameter(element, BuiltInParameter.REBAR_SHAPE, StorageType.ElementId, bar.ShapeId); + break; + case "AnalyticalMember" or "AnalyticalPanel" when fields.TryGetValue(StructuralMaterial, out int material) + && (material == -1 || RootIs(state, material, "MaterialElem")): + SetParameter(element, BuiltInParameter.STRUCTURAL_MATERIAL_PARAM, StorageType.ElementId, material); + break; + } + + if (element.NativeRootClassChain?.Contains("CenterLine") == true + && fields.TryGetValue(CenterLineOwner, out int ownerId) && ownerId != element.Id + && ExactRoot(state, ownerId) != null && elementsById.TryGetValue(ownerId, out var owner) + && owner.NativeRootClassChain?.Contains("CenterLine") != true) + { + CopyParameter(element, owner, BuiltInParameter.ALL_MODEL_MARK); + if (ExactRoot(state, owner.TypeId) != null) + { + SetTypeParameters(element, owner.TypeId); + if (state.WideNames.TryGetValue((uint)owner.TypeId, out string? typeName)) + SetTypeName(element, typeName); + } + if (kind == "SegmentCenterLine" && owner.NativeRootClassName == "RbsPipeCurve") + CopyParameter(element, owner, BuiltInParameter.RBS_PIPE_DIAMETER_PARAM); + } + } + ApplyHostQuantities(info, state, elementsById); + } + + private static void ApplyRectangularDuctVolume(ParsingState state, Element element, TfBlockDeserializer.NativeParams root) + { + if (element.CategoryId != (int)BuiltInCategory.OST_DuctCurves + || !root.Fields.TryGetValue("602:m_idType", out int type) || !RootIs(state, type, "AbsDuctType") + || !state.SystemTypeRoots.TryGetValue((uint)type, out var typeRoot) || typeRoot != (1, 110, 127)) return; + var dimensions = root.DoubleFields; + if (!dimensions.ContainsKey("87:m_pCrv.endParams@0") + || !dimensions.TryGetValue("602:m_dWidthOrDiameter", out double width) + || !dimensions.TryGetValue("602:m_dHeight", out double height) + || element.Parameters.FirstOrDefault(p => p.Id == (int)BuiltInParameter.CURVE_ELEM_LENGTH) + is not { HasRevitValue: true, Value: double length }) return; + double volume = width * height * length; + if (width > 0 && height > 0 && length > 0 && double.IsFinite(volume)) + SetParameter(element, BuiltInParameter.HOST_VOLUME_COMPUTED, StorageType.Double, volume); + } + + private static int LinkedElevationType(ParsingState state, int viewId, TfBlockDeserializer.NativeParams view) + { + if (view.Fields.TryGetValue(ViewMarker, out int arrowId) + && ExactRootOf(state, arrowId, "InteriorElevArrow") is { } arrow + && arrow.Fields.GetValueOrDefault(WideNativeParams.ViewerViewKey) == viewId + && arrow.Fields.TryGetValue(ElevationParent, out int markerId) + && ExactRootOf(state, markerId, "InteriorElev") is { } marker + && marker.Fields.TryGetValue(ElevationType, out int typeId)) + return typeId; + return -1; + } + + private static TfBlockDeserializer.NativeParams? ExactRoot(ParsingState state, int id) => + id > 0 && state.NativeParamsFromRootClass.Contains((uint)id) + && state.NativeParams.TryGetValue((uint)id, out var root) + && root.TailWalkComplete && root.Fields.GetValueOrDefault("m_id") == id ? root : null; + + private static bool RootIs(ParsingState state, int id, string kind) => + ExactRootOf(state, id, kind) != null; + + private static TfBlockDeserializer.NativeParams? ExactRootOf(ParsingState state, int id, string kind) => + state.NativeRootClassNames.GetValueOrDefault((uint)id) == kind ? ExactRoot(state, id) : null; + + private static void CopyParameter(Element element, Element owner, BuiltInParameter parameter) + { + if (owner.Parameters.FirstOrDefault(p => p.Id == (int)parameter) is { HasRevitValue: true, Value: { } value } source) + SetParameter(element, parameter, source.StorageType, value); + } + + private static void SetTypeParameters(Element element, int typeId) + { + SetParameter(element, BuiltInParameter.ELEM_TYPE_PARAM, StorageType.ElementId, typeId); + SetParameter(element, BuiltInParameter.ELEM_FAMILY_PARAM, StorageType.ElementId, typeId); + } + + private static void SetTypeName(Element element, string name, string? storedAlias = null) + { + if (element.Parameters.FirstOrDefault(p => p.Id == (int)BuiltInParameter.ALL_MODEL_TYPE_NAME) + is { Value: string currentName } parameter && (currentName.Length == 0 || currentName == storedAlias)) + { + parameter.Value = name; + parameter.FromNativeFields = true; + } + } + + private static void SetParameter(Element element, BuiltInParameter id, StorageType type, object value) + { + var parameter = element.Parameters.FirstOrDefault(p => p.Id == (int)id); + if (parameter is { HasRevitValue: true }) return; + if (parameter == null) + { + parameter = BipHelpers.MakeBipParam((int)id, id.ToString(), type, value); + element.Parameters.Add(parameter); + } + else + { + parameter.StorageType = type; + parameter.Value = value; + } + parameter.FromNativeFields = true; + parameter.HasNoRevitValue = type == StorageType.ElementId && value is -1; + } +} diff --git a/src/RvtIO/Parsing/TfBlockDeserializer.cs b/src/RvtIO/Parsing/TfBlockDeserializer.cs index cfcbebad..4f52f083 100644 --- a/src/RvtIO/Parsing/TfBlockDeserializer.cs +++ b/src/RvtIO/Parsing/TfBlockDeserializer.cs @@ -37,6 +37,7 @@ internal sealed class NativeParams public bool RootParameterStoresComplete { get; set; } /// Class tags of the cells of the element's CellList, when the deferred walk reached that object. public List? CellClasses { get; set; } + public HashSet? RoofExtrusionFaceTags { get; set; } /// The deferred walk consumed every queued object of the record (so the NamedParams and cells are complete). public bool TailWalkComplete { get; set; } public List<(int ParamId, double Value)> Doubles { get; } = new(); diff --git a/src/RvtIO/Parsing/WideNativeParams.SketchArea.cs b/src/RvtIO/Parsing/WideNativeParams.SketchArea.cs new file mode 100644 index 00000000..65171359 --- /dev/null +++ b/src/RvtIO/Parsing/WideNativeParams.SketchArea.cs @@ -0,0 +1,79 @@ +using RvtIO.Geometry; + +namespace RvtIO.Parsing; + +internal sealed partial class WideNativeParams +{ + private const string SketchAbsorbedCurves = WideBlockWalker.AllItemsKeyPrefix + "sketch:m_absorbedCurves"; + internal const string SketchLineArea = "sketch:lineArea"; + + private double? ReadSketchLineArea(WideBlockWalker.Walk walk) + { + if (!walk.Exact || walk.Captures.Where(c => c.AtRoot && c.Key == SketchAbsorbedCurves + "#") + .Take(2).ToArray() is not [{ Integer: >= 3 } count]) return null; + var pointers = walk.Captures.Where(c => c.AtRoot && c.Kind == WideBlockWalker.CaptureKind.PointerClass + && c.Key.StartsWith(SketchAbsorbedCurves + "@", StringComparison.Ordinal)).ToArray(); + var owned = Enumerable.Range(0, walk.QueueCountAtStart.FirstOrDefault()); + int[] queue = owned.Where(i => _walker.IsA(walk.Queue[i], "GCurve")).ToArray(); + int[] curveData = owned.Where(i => _walker.Class(walk.Queue[i])?.Name == "CurveElemData").ToArray(); + if (pointers.Length != count.Integer || queue.Length != pointers.Length || curveData.Length != queue.Length) return null; + foreach (int entry in curveData) + { + int first = walk.QueueCountAtStart[entry]; + if (walk.QueueEnd[entry] != first + 1 || _walker.Class(walk.Queue[first])?.Name != "FilledRegionCurveData") return null; + } + + var byCurve = walk.Captures.Where(c => c.Kind == WideBlockWalker.CaptureKind.Real + && c.Key.StartsWith(LineKeyPrefix, StringComparison.Ordinal)).ToLookup(c => c.QueueIndex); + var lines = new List<(double[] Start, double[] End)>(queue.Length); + for (int i = 0; i < queue.Length; i++) + { + int entry = queue[i]; + if (pointers[i].Integer != walk.Queue[entry] || _walker.Class(walk.Queue[entry])?.Name != "GLine") return null; + var fields = byCurve[entry].ToArray(); + if (fields.Length != 8 || fields.Any(c => !double.IsFinite(c.Real))) return null; + var ends = fields.Where(c => c.Field == "m_endParams").Select(c => c.Real).ToArray(); + var origin = fields.Where(c => c.Field == "m_origin").Select(c => c.Real).ToArray(); + var direction = fields.Where(c => c.Field == "m_dirVec").Select(c => c.Real).ToArray(); + if (ends.Length != 2 || origin.Length != 3 || direction.Length != 3) return null; + lines.Add((PointAt(ends[0]), PointAt(ends[1]))); + + double[] PointAt(double parameter) => [origin[0] + parameter * direction[0], + origin[1] + parameter * direction[1], origin[2] + parameter * direction[2]]; + } + return ClosedLineLoopArea(lines); + } + + internal static double? ClosedLineLoopArea(List<(double[] Start, double[] End)> lines) + { + if (lines.Count < 3) return null; + const double tolerance = 1e-8; + var origin = lines[0].Start; + if (lines.Any(e => Math.Abs(e.Start[2] - origin[2]) > tolerance || Math.Abs(e.End[2] - origin[2]) > tolerance + || SamePoint(e.Start, e.End))) return null; + + var last = lines[0].End; + var points = new List(lines.Count) { new double[3] }; + for (int i = 1; i < lines.Count; i++) + { + if (SamePoint(last, origin)) return null; + int next = -1; + for (int j = i; j < lines.Count; j++) + { + if (!SamePoint(lines[j].Start, last) && !SamePoint(lines[j].End, last)) continue; + if (next != -1) return null; + next = j; + } + if (next == -1) return null; + (lines[i], lines[next]) = (lines[next], lines[i]); + points.Add([last[0] - origin[0], last[1] - origin[1], 0]); + last = SamePoint(lines[i].Start, last) ? lines[i].End : lines[i].Start; + } + if (!SamePoint(last, origin)) return null; + double area = WallExtrusion.LoopArea(points); + return area > 0 && double.IsFinite(area) ? area : null; + + static bool SamePoint(double[] a, double[] b) => Math.Abs(a[0] - b[0]) <= tolerance + && Math.Abs(a[1] - b[1]) <= tolerance && Math.Abs(a[2] - b[2]) <= tolerance; + } +} diff --git a/src/RvtIO/Parsing/WideNativeParams.cs b/src/RvtIO/Parsing/WideNativeParams.cs index 42cb69b0..456390d7 100644 --- a/src/RvtIO/Parsing/WideNativeParams.cs +++ b/src/RvtIO/Parsing/WideNativeParams.cs @@ -1,4 +1,5 @@ using System.Globalization; +using RvtIO.Internal; namespace RvtIO.Parsing; @@ -11,7 +12,7 @@ namespace RvtIO.Parsing; /// number by NAME, and only when the 2022 class declares a field of that name; a field or class tag without a 2022 /// counterpart is left out (the rules then see "not decoded"), never guessed. /// -internal sealed class WideNativeParams +internal sealed partial class WideNativeParams { private static readonly string[] StoreNames = ["ParamValueSetDouble", "ParamValueSetInt", "ParamValueSetAString", "ParamValueSetElementId"]; @@ -40,6 +41,12 @@ internal sealed class WideNativeParams internal const string ViewerViewKey = "viewer:m_dbViewId"; + private static readonly string HostLayerPointer = TfClassNames.Key("HostObjAttr", "m_pCompoundStructure"); + private static readonly string HostLayerArray = TfClassNames.Key("CompoundStructure", "m_layers"); + private const string TilePatternPointer = "tile:m_oTilePattern"; + private const string TilePatternId = "tile:m_revitPatternId"; + internal const string TilePatternName = "tile:m_name"; + private const string RailTopHeightKey = "490:m_topRailHeight"; private const string PlaneOriginKey = "plane:m_origin"; @@ -79,12 +86,13 @@ internal WideNativeParams(SchemaDocument schema) _bases.Add(GroupTypeKey); _bases.Add(ParamDefPointerKey); _bases.Add(ViewerViewKey); + _bases.UnionWith(Revit2027ApiValues.RootFields); foreach (var c in schema.Classes) _toR22[c.Id] = _r22ByName.GetValueOrDefault(c.Name); _storeIds = schema.Classes.Where(c => StoreNames.Contains(c.Name)).Select(c => c.Id).ToHashSet(); _namedParam = schema.Classes.FirstOrDefault(c => c.Name == "NamedParam")?.Id ?? -1; _walker = new WideBlockWalker(schema, KeyOf, ["ParamValueDouble", "ParamValueInt", "ParamValueAString", "ParamValueElementId", "NamedParam", "ForgeTypeId", "FormatOptions", "AUnits", - "Connector", "ConnectorId", "SegmentConnectorCalculation", "MEPFamilyConnectorCalculationHvac", + "CompoundStructureLayer", "Connector", "ConnectorId", "SegmentConnectorCalculation", "MEPFamilyConnectorCalculationHvac", "MEPFamilyConnectorCalculationPiping", "MEPFamilyConnectorCalculationElectrical"]); } @@ -96,6 +104,12 @@ internal WideNativeParams(SchemaDocument schema) private string? KeyOf(SchemaClass declaring, SchemaField field) { if (field.Type is 9 or 13) return null; + if (declaring.Name == "HostObjAttr" && field.Name == "m_pCompoundStructure") return HostLayerPointer; + if (declaring.Name == "CompoundStructure" && field.Name == "m_layers") return HostLayerArray; + if ((declaring.Name, field.Name) == ("TilePatternType", "m_oTilePattern")) return TilePatternPointer; + if ((declaring.Name, field.Name) == ("TilePattern", "m_revitPatternId")) return TilePatternId; + if ((declaring.Name, field.Name) == ("TilePattern", "m_name")) return TilePatternName; + if ((declaring.Name, field.Name) == ("Sketch", "m_absorbedCurves")) return SketchAbsorbedCurves; // The Revit 2022 rule that reads the Material parameter of a wall sweep type from its render style does not hold for every // type of a Revit 2025 file (Revit prints "None" for some with the same field set), so the field is not validated if (declaring.Name == "Symbol" && field.Name == "m_renderStyleId") return null; @@ -111,14 +125,15 @@ internal WideNativeParams(SchemaDocument schema) // ElementBuilder.ApplySerializedRailingData reads bare as the shipped 2022 walk stores it if (declaring.Name == "BaseRailingAttr" && field.Name == "m_topRailHeight") return RailTopHeightKey; int r22 = _toR22.GetValueOrDefault(declaring.Id); - bool keyed = r22 != 0 && _r22[r22].Fields.Any(f => f.Name == field.Name) - && _bases.Contains(r22.ToString(CultureInfo.InvariantCulture) + ":" + field.Name); + string key = r22.ToString(CultureInfo.InvariantCulture) + ":" + field.Name; + if (Revit2027ApiValues.RootFields.Contains(key)) return key; + bool keyed = r22 != 0 && _r22[r22].Fields.Any(f => f.Name == field.Name) && _bases.Contains(key); bool rootName = TfBlockDeserializer.CapturedFieldNames.Contains(field.Name); bool name = field.Type == 8 && _nameFields.Contains(declaring.Name + "." + field.Name); - if (keyed || rootName || name) return r22.ToString(CultureInfo.InvariantCulture) + ":" + field.Name; + if (keyed || rootName || name) return key; // the origin of the plane a datum plane (a Level) stands on, read by LevelElevation if (declaring.Name == "Plane" && field.Name == "m_origin") return PlaneOriginKey; - // the straight drive curve of an MEP curve (AddMepCurveLine) + // the straight drive curve (AddDriveLine) if ((declaring.Name, field.Name) is ("GLine", "m_origin" or "m_dirVec") or ("GCurve", "m_endParams")) return LineKeyPrefix + field.Name; // the nodes of the Hermite spline that drives a flexible duct or pipe (AddFlexCurveNodes) @@ -130,6 +145,34 @@ internal WideNativeParams(SchemaDocument schema) return SystemDiscriminatorFields.Contains(field.Name) ? DiscriminatorKey : null; } + /// Ordered layers from the unique CompoundStructure owned by the exact host type root. + internal List? HostTypeLayers(WideBlockWalker.Walk walk, int rootClassId) + { + if (!walk.Exact || !_walker.IsA(rootClassId, "HostObjAttr") + || walk.Captures.Where(c => c.AtRoot && c.Key == HostLayerPointer && c.Kind == WideBlockWalker.CaptureKind.PointerClass) + .Take(2).ToArray() is not [{ Integer: > 0 and <= ushort.MaxValue } pointer]) + return null; + + int rootQueueSize = walk.QueueCountAtStart.FirstOrDefault(); + if (Enumerable.Range(0, rootQueueSize).Where(i => walk.Queue[i] == pointer.Integer).Take(2).ToArray() is not [int index] + || _walker.Class(walk.Queue[index])?.Name != "CompoundStructure" + || walk.Captures.Where(c => c.QueueIndex == index && c.Key == HostLayerArray + "#").Take(2).ToArray() is not [{ Integer: > 0 } count]) + return null; + + var layers = new List(); + foreach (var record in walk.Records) + { + if (record.QueueIndex != index || _walker.Class(record.ClassId)?.Name != "CompoundStructureLayer") continue; + var values = record.Values; + if (values.GetValueOrDefault("m_layerWidth") is not double width || !double.IsFinite(width) || width < 0 + || values.GetValueOrDefault("m_layerFunction") is not long function || function is < int.MinValue or > int.MaxValue + || values.GetValueOrDefault("m_materialId") is not long material || material is < int.MinValue or > int.MaxValue) + return null; + layers.Add(new() { ThicknessFt = width, Function = (int)function, MaterialId = (int)material, LayerIndex = layers.Count }); + } + return layers.Count == count.Integer ? layers : null; + } + /// The own name of the element: the first non-empty text at the first field the walk reached. internal string? OwnName(WideBlockWalker.Walk walk, int rootClassId) { @@ -205,7 +248,8 @@ internal WideNativeParams(SchemaDocument schema) int colon = c.Key.IndexOf(':'); string name = c.Key[(colon + 1)..]; string key = c.Key; - bool keyed = !c.Key.StartsWith("0:", StringComparison.Ordinal) && _bases.Contains(c.Key.Split('@', '#')[0]); + bool keyed = !c.Key.StartsWith("0:", StringComparison.Ordinal) && _bases.Contains(c.Key.Split('@', '#')[0]) + && (c.AtRoot || !Revit2027ApiValues.RootFields.Contains(c.Key)); bool bare = (c.AtRoot || c.Key == "0:m_docAccess") && TfBlockDeserializer.CapturedFieldNames.Contains(name.Split('@', '#')[0]); if (c.Kind == WideBlockWalker.CaptureKind.PointerClass) { @@ -281,8 +325,20 @@ internal WideNativeParams(SchemaDocument schema) } AddConnectorRecords(np, walk); - AddMepCurveLine(np, walk, rootClassId); + AddDriveLine(np, walk, rootClassId); AddFlexCurveNodes(np, walk, rootClassId); + if (rootClassId >= 0 && _walker.Class(rootClassId)?.Name == "TilePatternType") ReadTilePatternName(np, walk); + if (rootClassId >= 0 && _walker.Class(rootClassId)?.Name == "VarSketch" && ReadSketchLineArea(walk) is double area) + np.DoubleFields[SketchLineArea] = area; + if (walk.Exact && rootClassId >= 0 && _walker.Class(rootClassId)?.Name == "Roof") + { + var extrusions = Enumerable.Range(0, walk.Queue.Count) + .Where(slot => _walker.Class(walk.Queue[slot])?.Name == "ExtrusionGStep").Take(2).ToArray(); + if (extrusions is [var step]) + np.RoofExtrusionFaceTags = walk.Captures.Where(c => c.QueueIndex == step && c.DeclaringClass == "FaceHistEntry" + && c.Field == "m_id" && c.Kind == WideBlockWalker.CaptureKind.Integer && c.Integer is >= 0 and <= int.MaxValue) + .Select(c => (int)c.Integer).ToHashSet(); + } // cell classes: what the CellList object queued for (int qi = 0; qi < walk.QueueEnd.Count; qi++) @@ -296,17 +352,38 @@ internal WideNativeParams(SchemaDocument schema) return np; } - /// The straight drive curve of a duct, pipe, conduit or cable tray (the GLine its CurveDriver queued) under the keys the + private void ReadTilePatternName(TfBlockDeserializer.NativeParams np, WideBlockWalker.Walk walk) + { + if (!walk.Exact || walk.Captures.Where(c => c.AtRoot && c.Key == TilePatternPointer + && c.Kind == WideBlockWalker.CaptureKind.PointerClass).Take(2).ToArray() is not [{ Integer: > 0 } pointer]) return; + int rootQueueSize = walk.QueueCountAtStart.FirstOrDefault(); + if (Enumerable.Range(0, rootQueueSize).Where(i => walk.Queue[i] == pointer.Integer).Take(2).ToArray() is not [int index] + || !_walker.IsA(walk.Queue[index], "TilePattern")) return; + if (walk.Captures.Where(c => c.QueueIndex == index && c.Key == TilePatternName && c.Kind == WideBlockWalker.CaptureKind.Text) + .Take(2).ToArray() is not [{ Text: { Length: > 0 } name }]) return; + if (walk.Captures.Where(c => c.QueueIndex == index && c.Key == TilePatternId && c.Kind == WideBlockWalker.CaptureKind.Integer) + .Take(2).ToArray() is not [{ Integer: var pattern }]) return; + np.StringFields[TilePatternName] = (pattern, name) switch + { + (0, "") => "_No Pattern", + (2, "Triangle") or (7, "Triangle Checkerboard") or (10, "Triangle Step") => name + " (bent)", + _ => name, + }; + } + + /// The straight drive curve of a wall, duct, pipe, conduit or cable tray (the GLine its CurveDriver queued) under the keys the /// Revit 2022 walk gives it ("87:m_pCrv.origin@i", ".dirVec@i", ".endParams@i"), which ElementBuilder.ApplyMepCurveGeometry reads for /// the length of the element. Nothing is written when the driver queued no GLine, more than one, or one with a value missing /// (an arc or a spline driver). - private void AddMepCurveLine(TfBlockDeserializer.NativeParams np, WideBlockWalker.Walk walk, int rootClassId) + private void AddDriveLine(TfBlockDeserializer.NativeParams np, WideBlockWalker.Walk walk, int rootClassId) { - if (rootClassId < 0 || R22Id(rootClassId) is not (3148 or 3210 or 3134 or 598)) return; + if (rootClassId < 0 || R22Id(rootClassId) is not (3148 or 3210 or 3134 or 598 or 3524)) return; + bool wall = R22Id(rootClassId) == 3524; int line = -1; for (int owner = 0; owner < walk.QueueEnd.Count; owner++) { if (!_walker.IsA(walk.Queue[owner], "CurveDriver")) continue; + if (wall && (owner >= walk.QueueCountAtStart[0] || _walker.Class(walk.Queue[owner])?.Name != "VWallDriver")) continue; for (int child = walk.QueueCountAtStart[owner]; child < walk.QueueEnd[owner]; child++) { if (_walker.Class(walk.Queue[child])?.Name != "GLine") continue; diff --git a/src/RvtIO/Parsing/WideSolidQuantities.cs b/src/RvtIO/Parsing/WideSolidQuantities.cs new file mode 100644 index 00000000..db79e188 --- /dev/null +++ b/src/RvtIO/Parsing/WideSolidQuantities.cs @@ -0,0 +1,440 @@ +using RvtIO.Geometry; +using RvtIO.Internal; +using RvtIO.Model; + +namespace RvtIO.Parsing; + +/// Measures the closed bodies in the current project's saved geometry blocks. +internal sealed class WideSolidQuantities +{ + internal enum Source { Default, Analytic, Directional, Fitting, StructuralFraming, FilledSurface, VisibleVolume, RawBodies, DirectionalRawSurface } + + internal readonly record struct Solid(double Volume, double Surface, double? LargestFace, int BodyCount, double? SharedCoarseVolume = 0) + { + internal Solid Add(Solid inner) => new(Volume + inner.Volume, Surface + inner.Surface, + LargestFace is double a && inner.LargestFace is double b ? Math.Max(a, b) : null, + BodyCount + inner.BodyCount, SharedCoarseVolume + inner.SharedCoarseVolume); + } + + private static readonly Lazy GeometrySchema = new(() => + { + using var source = typeof(WideSolidQuantities).Assembly.GetManifestResourceStream("RvtIO.Resources.r22_schemas.json")!; + return TfSchemaReader.ReadShipped2022(source); + }); + + private readonly R22Transcoder _geometryLayout; + private readonly Dictionary _records = []; + private readonly Dictionary<(int Id, Source Source), Solid?[]?> _results = []; + private readonly Dictionary _massAreas = []; + private readonly HashSet<(long X, long Y, long Z)> _splitVertices = []; + + internal WideSolidQuantities(FileSchema schema, IReadOnlyList frames) + { + _geometryLayout = new(schema.Document, GeometrySchema.Value, 8); + var ambiguous = new HashSet(); + foreach (var frame in frames) + { + if (frame?.IdWidth != 8) continue; + foreach (var item in frame.Items) + { + if (item.Channel != 103 || item.Owner is 0 or > int.MaxValue) continue; + int id = (int)item.Owner; + if (!_records.TryAdd(id, (frame, item))) ambiguous.Add(id); + } + } + foreach (int id in ambiguous) _records.Remove(id); + } + + internal Solid?[]? Measure(int id, Source source = Source.Default) => Measure(id, source, []); + + internal double? WallArea(int id, double dx, double dy, double dz, double? width, bool curtain) + { + if (Read(id) is not { } fine) return null; + return WallSideArea(fine.Coarse ?? fine, dx, dy, dz, width, curtain); + } + + internal double? HorizontalArea(int id, bool bottom) => HorizontalArea(id, bottom, []); + + internal double? MassArea(int id, Solid solid) + { + var areas = MassAreas(id); + return MassArea(solid, areas.Top, areas.Bottom) ?? areas.Planar / 2; + } + + internal bool HasOneHorizontalCap(int id) + { + var (top, bottom, _) = MassAreas(id); + return top is > 0 && bottom == 0 || bottom is > 0 && top == 0; + } + + private (double? Top, double? Bottom, double? Planar) MassAreas(int id) + { + if (_massAreas.TryGetValue(id, out var known)) return known; + return _massAreas[id] = Collect(id, []); + + (double? Top, double? Bottom, double? Planar) Collect(int elementId, HashSet visiting) + { + if (visiting.Count >= 32 || !visiting.Add(elementId)) return default; + try + { + if (Read(elementId, Source.Analytic) is not { } fine) return default; + var source = fine.Coarse ?? fine; + var top = HorizontalArea(source, bottom: false); + var bottom = HorizontalArea(source, bottom: true); + var planar = HorizontalArea(source, bottom: false, planarMass: true); + foreach (var instance in source.Instances) + { + var placement = instance.Transform; + if (!ElementBuilder.IsRigidPlacement(placement) || Math.Abs(placement[8]) < 1 - 1e-9) return default; + var child = Collect(instance.SymbolElemId, visiting); + bool reversed = placement[8] < 0; + top += reversed ? child.Bottom : child.Top; + bottom += reversed ? child.Top : child.Bottom; + planar += child.Planar; + } + return (top, bottom, planar); + } + finally { visiting.Remove(elementId); } + } + } + + internal double? RoofArea(int id, IReadOnlySet faceTags) + { + if (Read(id, Source.Analytic) is not { } fine) return null; + return RoofArea(fine.Coarse ?? fine, faceTags); + } + + internal static double? RoofArea(GRepData source, IReadOnlySet faceTags) + { + if (source.Instances.Count != 0 || source.Solids.Count != 1 || !HasCompletePlanarShells(source) + || source.Faces.Any(face => face.GInfoTag == null)) return null; + var measured = new HashSet(); + double area = 0; + foreach (var face in source.Faces) + if (face.XVector[2] < -1e-9 && face.GInfoTag is int tag && faceTags.Contains(tag)) + area += PlanarArea(face, measured); + return area > 0 && double.IsFinite(area) ? area : null; + } + + internal double? FilledArea(int id) => Read(id, Source.FilledSurface)?.FilledArea; + + internal double? CurtainDoorArea(int id) + { + if (Read(id) is not { } own || (own.Coarse ?? own).Instances is not [var mapped] + || (own.Coarse ?? own).Faces.Count != 0 || !ElementBuilder.IsRigidPlacement(mapped.Transform) + || Read(mapped.SymbolElemId) is not { } symbol) return null; + return CurtainDoorArea(symbol.Coarse ?? symbol); + } + + internal static double? CurtainDoorArea(GRepData geometry) + { + const double tolerance = 1e-7; + if (geometry.IsOpenSurface || geometry.UntriangulatedFaces != 0 || geometry.Instances.Count != 0) return null; + var panels = new List<(double Left, double Right, double Bottom, double Top, double Front)>(); + foreach (var solid in geometry.Solids.Where(solid => solid.IsClosed && solid.FaceIndices.Count == 6)) + { + var faces = solid.FaceIndices.Select(index => geometry.Faces[index]).ToList(); + if (!faces.All(face => face.PlaneSurface && face.Vertices is { Count: 4 } && face.InnerVertices is not { Count: > 0 } + && face.MeshArcs is not { Count: > 0 })) continue; + if (faces.Where(face => face.XVector[1] > 1 - tolerance).ToList() is not [var front]) continue; + var points = front.Vertices!; + double left = points.Min(point => point[0]), right = points.Max(point => point[0]); + double bottom = points.Min(point => point[2]), top = points.Max(point => point[2]); + if (Math.Abs(BrepMeasures.RingArea(points) - (right - left) * (top - bottom)) > tolerance) return null; + panels.Add((left, right, bottom, top, front.Origin[1])); + } + if (panels.Count is < 1 or > 2) return null; + var first = panels[0]; + if (panels.Any(panel => Math.Abs(panel.Bottom - first.Bottom) > tolerance || Math.Abs(panel.Top - first.Top) > tolerance + || Math.Abs(panel.Front - first.Front) > tolerance)) return null; + return (panels.Max(panel => panel.Right) - panels.Min(panel => panel.Left)) * (first.Top - first.Bottom); + } + + private double? HorizontalArea(int id, bool bottom, HashSet visiting) + { + if (visiting.Count >= 32 || !visiting.Add(id)) return null; + try + { + if (Read(id, Source.Analytic) is not { } fine) return null; + var source = fine.Coarse ?? fine; + double? area = HorizontalArea(source, bottom); + foreach (var instance in source.Instances) + { + var placement = instance.Transform; + if (!ElementBuilder.IsRigidPlacement(placement) || Math.Abs(placement[8]) < 1 - 1e-9) return null; + area += HorizontalArea(instance.SymbolElemId, bottom ^ (placement[8] < 0), visiting); + } + return area; + } + finally { visiting.Remove(id); } + } + + internal static double? HorizontalArea(GRepData source, bool bottom, bool planarMass = false) + { + if (planarMass && !HasCompletePlanarShells(source)) return null; + if (source.SourceBodyMeasures.HasValue) + return source.SourceCapAreas is { } caps ? (bottom ? caps.Bottom : caps.Top) : null; + if (source.UntriangulatedFaces != 0 || source.IsOpenSurface) return null; + var measured = new HashSet(); + double area = 0; + foreach (var face in source.Faces) + { + if (!face.PlaneSurface || (planarMass ? Math.Abs(face.XVector[2]) <= 1e-9 + : (bottom ? -face.XVector[2] : face.XVector[2]) < 1 - 1e-9)) continue; + area += PlanarArea(face, measured); + if (!double.IsFinite(area)) return null; + } + return area; + } + + private static bool HasCompletePlanarShells(GRepData source) + => !source.IsOpenSurface && source.UntriangulatedFaces == 0 && !source.SourceBodyMeasures.HasValue + && source.Faces.All(face => face.PlaneSurface) + && source.Solids.All(solid => solid.IsClosed) + && source.Solids.SelectMany(solid => solid.FaceIndices).ToHashSet().SetEquals(Enumerable.Range(0, source.Faces.Count)); + + internal static double? MassArea(Solid solid, double? top, double? bottom) + { + if (solid.BodyCount != 1 || bottom is not > 0) return null; + if (top is > 0 && Math.Abs(top.Value - bottom.Value) <= 1e-8 * bottom.Value) return top; + return top == 0 && solid.LargestFace.HasValue ? solid.Surface / 2 : null; + } + + private static double PlanarArea(GRepFace face, HashSet measured) + { + if (face.SourceFace == 0 || face.Vertices is not { Count: >= 3 } outer) return double.NaN; + if (face.QuadratureArea is double area) return measured.Add(face.SourceFace) ? area : 0; + if (face.MeshArcs is { Count: > 0 }) return double.NaN; + return BrepMeasures.RingArea(outer) - (face.InnerVertices?.Sum(BrepMeasures.RingArea) ?? 0); + } + + internal static double? WallSideArea(GRepData source, double dx, double dy, double dz, double? width, bool curtain) + { + const double tolerance = 1e-6; + double length = Math.Sqrt(dx * dx + dy * dy); + if (source.UntriangulatedFaces > 0 || source.Instances.Count != 0 || source.IsOpenSurface + || !double.IsFinite(length) || length <= 0 || !double.IsFinite(dz) || Math.Abs(dz) > tolerance + || width is double w && (!double.IsFinite(w) || w <= 0)) return null; + double nx = -dy / length, ny = dx / length; + + if (!curtain) return Sides(source.Faces)?.Area; + + // The curtain wall's closed profile occurs twice; the open faces describe its panel grid. + var profiles = source.Solids.Where(solid => solid.IsClosed).ToList(); + if (profiles.Count != 2) return null; + var a = Sides(profiles[0].FaceIndices.Select(index => source.Faces[index])); + var b = Sides(profiles[1].FaceIndices.Select(index => source.Faces[index])); + return a is { } first && b is { } second && Math.Abs(first.Min - second.Min) <= tolerance + && Math.Abs(first.Max - second.Max) <= tolerance + && Math.Abs(first.Area - second.Area) <= tolerance ? first.Area : null; + + (double Min, double Max, double Area)? Sides(IEnumerable faces) + { + var measured = new HashSet(); + var planes = new List<(double Offset, double Area)>(); + foreach (var face in faces) + { + if (!face.PlaneSurface) continue; + var normal = face.XVector; + if (Math.Abs(normal[2]) > tolerance || Math.Abs(normal[0] * nx + normal[1] * ny) < 1 - tolerance) continue; + double area = PlanarArea(face, measured); + if (!double.IsFinite(area) || area < 0) return null; + if (area == 0) continue; + double offset = face.Origin[0] * nx + face.Origin[1] * ny; + int index = planes.FindIndex(plane => Math.Abs(plane.Offset - offset) <= tolerance); + if (index < 0) planes.Add((offset, area)); + else planes[index] = (planes[index].Offset, planes[index].Area + area); + } + if (planes.Count < 2) return null; + var low = planes.MinBy(plane => plane.Offset); + var high = planes.MaxBy(plane => plane.Offset); + if (width is double stored && Math.Abs(high.Offset - low.Offset - stored) > tolerance) return null; + if (curtain && (planes.Count != 2 || Math.Abs(high.Area - low.Area) > tolerance)) return null; + return (low.Offset, high.Offset, Math.Max(low.Area, high.Area)); + } + } + + private Solid?[]? Measure(int id, Source source, HashSet visiting) + { + var key = (id, source); + if (_results.TryGetValue(key, out var known)) return known; + if (visiting.Count >= 32 || !visiting.Add(id)) return null; + try + { + if (Read(id, source) is not { } fine) return _results[key] = null; + GRepData[] levels = [fine.Coarse ?? fine, fine.Medium ?? fine, fine]; + var localFine = Local(fine, source, _splitVertices); + Solid?[] result = [fine.Coarse == null ? localFine : Local(fine.Coarse, source, _splitVertices), + fine.Medium == null ? localFine : Local(fine.Medium, source, _splitVertices), localFine]; + var localCoarse = result[0]; + for (int detail = 0; detail < levels.Length; detail++) + { + if (detail > 0 && source is not (Source.Directional or Source.VisibleVolume or Source.RawBodies or Source.DirectionalRawSurface) + && result[detail] is { } measured) + result[detail] = measured with { SharedCoarseVolume = SharedLocalVolume(levels[0], levels[detail], localCoarse) }; + if (source == Source.Fitting && detail > 0 && result[detail]?.SharedCoarseVolume == null + && WithoutReusedCoarseBodies(levels[0], levels[detail]) is { } body) + result[detail] = Local(body, splitVertices: _splitVertices); + foreach (var instance in levels[detail].Instances) + { + if (result[detail] is not { } local) break; + if (!ElementBuilder.IsRigidPlacement(instance.Transform) + || Measure(instance.SymbolElemId, source, visiting)?[detail] is not { } placed) + { + result[detail] = null; + break; + } + double? shared = detail == 0 || levels[0].Instances.Count == 0 ? 0 + : levels[0].Instances is [var coarse] && levels[detail].Instances.Count == 1 + && coarse.SymbolElemId == instance.SymbolElemId && coarse.Transform.SequenceEqual(instance.Transform) + ? placed.SharedCoarseVolume : null; + result[detail] = local.Add(placed with { SharedCoarseVolume = shared }); + } + } + if (source == Source.StructuralFraming && result[2] is { BodyCount: > 1 } && (fine.Instances.Count != 1 || fine.Faces.Count != 0)) + { + // A detailed frame can repeat the complete Medium bodies and add detail solids. + var medium = result[1]; + result[2] = fine.Instances.Count == 0 && levels[0].Faces.Count == 0 && medium is { Volume: > 0 } body + && SharedLocalVolume(levels[1], fine, body) == body.Volume ? medium : null; + } + return _results[key] = result; + } + finally { visiting.Remove(id); } + } + + internal static double? SharedLocalVolume(GRepData coarse, GRepData detailed, Solid? coarseMeasure) + { + if (coarse.Faces.Count == 0 || detailed.Faces.Count == 0) return 0; + if (coarseMeasure == null) return null; + if (ReferenceEquals(coarse, detailed)) return coarseMeasure.Value.Volume; + var coarseFaces = coarse.Faces.Select(face => face.SourceFace).ToHashSet(); + var detailedFaces = detailed.Faces.Select(face => face.SourceFace).ToHashSet(); + if (coarseFaces.Contains(0) || detailedFaces.Contains(0)) return null; + if (!coarseFaces.Overlaps(detailedFaces)) return 0; + + // A fitting's coarse proxy can also occur in a detailed view. Its complete solid must match by source face. + if (coarse.Solids.Count != coarseMeasure.Value.BodyCount || detailed.Solids.Count == 0 + || coarse.Solids.Any(body => body.FaceIndices.Any(index => (uint)index >= (uint)coarse.Faces.Count)) + || detailed.Solids.Any(body => body.FaceIndices.Any(index => (uint)index >= (uint)detailed.Faces.Count))) return null; + var detailedBodies = detailed.Solids.Select(body => body.FaceIndices.Select(index => detailed.Faces[index].SourceFace).ToHashSet()).ToArray(); + foreach (var body in coarse.Solids) + { + var faces = body.FaceIndices.Select(index => coarse.Faces[index].SourceFace).ToHashSet(); + if (detailedBodies.Count(other => other.SetEquals(faces)) != 1) return null; + } + return coarseMeasure.Value.Volume; + } + + private static GRepData? WithoutReusedCoarseBodies(GRepData coarse, GRepData detailed) + { + if (coarse.Solids.Count == 0 || detailed.Solids.Count == 0 || ReferenceEquals(coarse, detailed) + || coarse.Solids.Any(body => !body.IsClosed) || detailed.Solids.Any(body => !body.IsClosed) + || coarse.Solids.SelectMany(body => body.FaceIndices).Distinct().Count() != coarse.Faces.Count + || detailed.Solids.SelectMany(body => body.FaceIndices).Distinct().Count() != detailed.Faces.Count) return null; + + var excluded = new HashSet(); + var fineFaces = detailed.Solids.Select(body => body.FaceIndices.Select(index => detailed.Faces[index].SourceFace).ToHashSet()).ToArray(); + foreach (var body in coarse.Solids) + { + var ids = body.FaceIndices.Select(index => coarse.Faces[index].SourceFace).ToHashSet(); + if (ids.Contains(0)) return null; + var matches = Enumerable.Range(0, fineFaces.Length).Where(index => fineFaces[index].Overlaps(ids)).ToList(); + if (matches.Count != 1 || !fineFaces[matches[0]].SetEquals(ids) || !excluded.Add(matches[0])) return null; + } + + var faces = new List(); + var solids = new List(); + for (int i = 0; i < detailed.Solids.Count; i++) + { + if (excluded.Contains(i)) continue; + var indices = detailed.Solids[i].FaceIndices; + solids.Add(new GRepSolid { IsClosed = true, FaceIndices = Enumerable.Range(faces.Count, indices.Count).ToList() }); + faces.AddRange(indices.Select(index => detailed.Faces[index])); + } + return detailed with { Faces = faces, Solids = solids }; + } + + private GRepData? Read(int id, Source source = Source.Default) + { + if (!_records.TryGetValue(id, out var record) || record.Item.Length is < 22 or > (int)BlockParser.MaxBlockSize + 20) + return null; + var (data, start, _) = record.Frame.Bytes(record.Item); + int size = record.Item.Length - 20; + if (_geometryLayout.TargetId(BitConverter.ToUInt16(data, start + 16)) is not (2006 or 2007) + || _geometryLayout.Payload(data, start + 16, size) is not { } payload || payload.Length > BlockParser.MaxBlockSize) + return null; + + byte[] block = new byte[payload.Length + 16]; + BitConverter.TryWriteBytes(block, id); + BitConverter.TryWriteBytes(block.AsSpan(8), payload.Length); + payload.CopyTo(block, 12); + BitConverter.TryWriteBytes(block.AsSpan(12 + payload.Length), payload.Length); + return GRepParserV2.Parse(block, 0, (uint)payload.Length, requireCompleteWalk: true, + measureSourceNodes: source is Source.Analytic or Source.Fitting or Source.StructuralFraming, + measureLighting: source == Source.Directional, measureFills: source == Source.FilledSurface, + bodyMeasure: source switch + { + Source.VisibleVolume => GRepParserV2.BodyMeasure.VisibleVolume, + Source.RawBodies => GRepParserV2.BodyMeasure.RawBodies, + Source.DirectionalRawSurface => GRepParserV2.BodyMeasure.DirectionalRawSurface, + _ => GRepParserV2.BodyMeasure.None, + }); + } + + internal static Solid? Local(GRepData source, Source quantitySource = Source.Default, + HashSet<(long X, long Y, long Z)>? splitVertices = null) + { + if (quantitySource == Source.Directional) + return source.LightingBodyMeasures is { } analytic + ? new Solid(analytic.Volume, analytic.Area, null, analytic.Count) : null; + if (quantitySource == Source.StructuralFraming && source.TrimmedBodyMeasures is { Volume: > 0 } trimmed) + return new Solid(trimmed.Volume, trimmed.Area, null, 1); + if (source.SourceBodyMeasures is { } complete && !source.IsOpenSurface) + return new Solid(complete.Volume, complete.Area, null, complete.Count); + if (quantitySource is Source.VisibleVolume or Source.RawBodies or Source.DirectionalRawSurface) return null; + if (source.NodeMeasures?.Any(measure => measure.SourceFaces != null) == true) + source = source with { PreserveSourceFaceIdentity = true }; + if (source.UntriangulatedFaces > 0 || source.IsOpenSurface) return null; + if (source.Faces.Count == 0) return new Solid(0, 0, 0, 0); + if (ElementBuilder.BuildGeometryData(source, separateFacesWithDistinctOpenings: true) is not { } geometry + || geometry.BrepSolids is not { Count: > 0 } solids || solids.Any(solid => !solid.IsClosed) + || !solids.SelectMany(solid => solid.FaceIndices).ToHashSet().SetEquals(Enumerable.Range(0, geometry.Faces.Count))) + return null; + + if (geometry.Faces.All(face => face.PlaneSurface && face.MeshArcs is not { Count: > 0 }) + && SolidQuantities.OfAllSolids(geometry) is { } polyhedron) + return new Solid(polyhedron.Volume, polyhedron.SurfaceArea, polyhedron.LargestFaceArea, solids.Count); + + var shells = BrepMeasures.ShellsOfCurrent(geometry, splitVertices); + if (shells.Count != solids.Count) return null; + Solid total = new(0, 0, 0, 0); + var measuredBodies = new HashSet(); + if (source.NodeMeasures is { Count: > 0 } measures) + { + var shellFaces = shells.Select(shell => shell.Faces.Select(face => face.SourceFace).ToHashSet()).ToArray(); + foreach (var measure in measures) + { + if (measure.SourceFaces is not { } sourceFaces || measure.Volume <= 0) continue; + var bodies = Enumerable.Range(0, shells.Count).Where(index => !shellFaces[index].Contains(0) + && shellFaces[index].IsSubsetOf(sourceFaces)).ToList(); + if (bodies.Count == 0 || bodies.Any(measuredBodies.Contains) + || !bodies.SelectMany(index => shellFaces[index]).ToHashSet().SetEquals(sourceFaces)) continue; + measuredBodies.UnionWith(bodies); + total = total.Add(new Solid(measure.Volume, measure.Area, null, bodies.Count)); + } + } + for (int i = 0; i < shells.Count; i++) + { + if (measuredBodies.Contains(i)) continue; + var shell = shells[i]; + if (shell.SourceMeasured) + total = total.Add(new Solid(shell.Volume, shell.Area, null, 1)); + else if (shell.Faces.All(face => face.PlaneSurface && face.MeshArcs is not { Count: > 0 }) + && SolidQuantities.OfSingleClosedShell(new GeometryData { Faces = geometry.Faces, BrepSolids = [solids[i]] }) is { } flat) + total = total.Add(new Solid(flat.Volume, flat.SurfaceArea, flat.LargestFaceArea, 1)); + else return null; + } + return total; + } +} diff --git a/src/RvtIO/RvtFileReader.cs b/src/RvtIO/RvtFileReader.cs index 9d12a076..c37ad57d 100644 --- a/src/RvtIO/RvtFileReader.cs +++ b/src/RvtIO/RvtFileReader.cs @@ -751,6 +751,13 @@ public RevitFileInfo Read(string rvtPath) diag?.WriteLine($"Wall type functions: {state.WallTypeFunctions.Count} entries"); LogPhase("Block-only elements built"); + // BasicFileInfo "Worksharing: Not enabled | Local | Central"; any other text is not decided. + rvtInfo.SerializedIsWorkshared = fileMetadata.GetValueOrDefault("Worksharing") switch + { + "Not enabled" => false, + "Local" or "Central" => true, + _ => null, + }; ElementBuilder.PostProcess(rvtInfo, state, diag); LogPhase("Post-processed"); ElementBuilder.ApplyValidatedStairComponentTypeNames(rvtInfo.Elements, state); @@ -811,13 +818,6 @@ public RevitFileInfo Read(string rvtPath) ?? (lengthOptions == null ? null : ProjectLengthUnits.StoredLengthUnit(lengthOptions.Value, out lengthUnitIssue)); if (rvtInfo.SerializedLengthUnit == null) rvtInfo.SerializedLengthUnitIssue = state.WideLengthUnitIssue ?? lengthUnitIssue; - // BasicFileInfo "Worksharing: Not enabled | Local | Central"; any other text is not decided. - rvtInfo.SerializedIsWorkshared = fileMetadata.GetValueOrDefault("Worksharing") switch - { - "Not enabled" => false, - "Local" or "Central" => true, - _ => null, - }; var (exportIds, replacedUniqueIds) = ElementBuilder.ApplyExportIds(rvtInfo.Elements, state); diag?.WriteLine($"Element export ids: episodes={state.HistoryEpisodeGuids.Count}/{state.EpisodeTableX?.ToString() ?? "?"}, " + $"records={state.ElemRecHistories?.Count.ToString() ?? "unavailable"}, elements={exportIds}, " @@ -1087,6 +1087,9 @@ private static void ReadWideElementIndex(RootStorage root, ParsingState state, np.DoubleFields["__levelElevation"] = levelElevation; } if (fields.OwnName(list[0].Walk, rootClass) is { } ownName) state.WideNames[id] = ownName; + if (!state.R22View && np.Fields.TryGetValue("m_id", out int layerOwner) && layerOwner == (int)id + && fields.HostTypeLayers(list[0].Walk, rootClass) is { } layers) + state.CompoundLayers[id] = layers; if (fields.ProjectPhaseOrder(list[0].Walk, rootClass) is { } phaseOrder) { var priorOrder = state.ProjectPhaseOrderSource; diff --git a/tests/RvtIO.Tests/AnalyticSolidMeasureTests.cs b/tests/RvtIO.Tests/AnalyticSolidMeasureTests.cs index 0a9a72ac..1e93d041 100644 --- a/tests/RvtIO.Tests/AnalyticSolidMeasureTests.cs +++ b/tests/RvtIO.Tests/AnalyticSolidMeasureTests.cs @@ -37,6 +37,30 @@ public void PlaneIntegral_PreservesSignedVolumeAndSurfaceOrientation() Assert.Equal(-measure.Volume, reversed.Volume, 12); } + [Fact] + public void HermiteFacets_MeasureAreaAndSignedFluxOfFullKnotDomain() + { + var surface = Surface(GRepParserV2.SurfKind.Hermite); + surface.Env = [0, 0, 1, 1]; + surface.UParams = [0, 1]; + surface.VParams = [0, 1]; + surface.HermiteNodes = + [ + Node(0, 0), Node(3, 0), Node(0, 2), Node(3, 2), + ]; + var edges = Rectangle(1, 0, 1); + var measure = GRepParserV2.MeasureHermiteFace(surface, [0, 0, 0], edges)!.Value; + // The facet vertices are rounded to float before accumulating the quantities. + Assert.Equal(6, measure.Area, tolerance: 1e-6); + Assert.Equal(measure.Area, measure.Volume, 12); + Assert.Null(GRepParserV2.MeasureHermiteFace(surface, [0, 0, 0], Rectangle(0.5, 0, 1))); + + static GRepParserV2.HermiteSurfaceNode Node(double x, double y) => new() + { + Point = [x, y, 3], Du = [3, 0, 0], Dv = [0, 2, 0], + }; + } + [Fact] public void CylinderIntegral_UsesTheSurfaceInsteadOfFacetedChordsAndIsTranslationInvariant() { @@ -62,6 +86,116 @@ public void ConeIntegral_UsesSlantDistanceAndHasZeroFluxAboutItsApex() Assert.Equal(0, measure.Volume, 12); } + [Fact] + public void RevolvedArcIntegral_MeasuresHalfATorus() + { + var surface = Surface(GRepParserV2.SurfKind.Rev); + surface.Env = [0, 0, Math.PI, 2 * Math.PI]; + var profile = new GRepParserV2.ArcRec { C = [3, 0, 0], X = [1, 0, 0], Y = [0, 0, 1], R = 1 }; + var edges = Rectangle(Math.PI, 0, 2 * Math.PI); + var measure = GRepParserV2.MeasureRevolvedFace(surface, profile, [0, 0, 0], edges)!.Value; + Assert.InRange(measure.Area / (6 * Math.PI * Math.PI), 1 - 1e-6, 1 + 1e-6); + Assert.InRange(measure.Volume / (3 * Math.PI * Math.PI), 1 - 1e-6, 1 + 1e-6); + Assert.Null(GRepParserV2.MeasureRevolvedFace(surface, profile with { C = [0, 0, 0] }, [0, 0, 0], edges)); + } + + [Fact] + public void RevolvedLineIntegral_UsesTheRadiusAtTheTrimmedEndpoints() + { + var surface = Surface(GRepParserV2.SurfKind.Rev); + surface.Env = [0, 1, Math.PI, 3]; + var profile = new GRepParserV2.ArcRec { C = [0, 0, 0], X = [0.6, 0, 0.8] }; + var measure = GRepParserV2.MeasureRevolvedFace(surface, profile, [0, 0, 0], Rectangle(Math.PI, 1, 3))!.Value; + Assert.Equal(2.4 * Math.PI, measure.Area, 10); + Assert.Equal(0, measure.Volume, 12); + } + + [Fact] + public void RevolvedArcIntegral_AllowsTrimEndpointsOnTheAxis() + { + var surface = Surface(GRepParserV2.SurfKind.Rev); + surface.Env = [0, 0, 2 * Math.PI, Math.PI]; + var profile = new GRepParserV2.ArcRec { X = [0, 0, -1], Y = [1, 0, 0], R = 1 }; + var measure = GRepParserV2.MeasureRevolvedFace(surface, profile, [0, 0, 0], Rectangle(2 * Math.PI, 0, Math.PI))!.Value; + Assert.InRange(measure.Area / (4 * Math.PI), 1 - 1e-6, 1 + 1e-6); + Assert.InRange(measure.Volume / (4 * Math.PI / 3), 1 - 1e-6, 1 + 1e-6); + } + + [Fact] + public void RevolvedEllipseIntegral_MeasuresAnOblateSpheroid() + { + var surface = Surface(GRepParserV2.SurfKind.Rev); + surface.Env = [0, 0, 2 * Math.PI, Math.PI]; + var profile = new GRepParserV2.ArcRec { X = [0, 0, -1], Y = [1, 0, 0], R = 1, RY = 2 }; + var measure = GRepParserV2.MeasureRevolvedFace(surface, profile, [0, 0, 0], Rectangle(2 * Math.PI, 0, Math.PI))!.Value; + double eccentricity = Math.Sqrt(0.75); + double area = 8 * Math.PI * (1 + 0.25 / eccentricity * Math.Atanh(eccentricity)); + + Assert.InRange(measure.Area / area, 1 - 1e-6, 1 + 1e-6); + Assert.InRange(measure.Volume / (16 * Math.PI / 3), 1 - 1e-6, 1 + 1e-6); + } + + [Fact] + public void RevolvedHermiteIntegral_UsesTheStoredProfileTangents() + { + var surface = Surface(GRepParserV2.SurfKind.Rev); + surface.Env = [0, 0, Math.PI, 1]; + var profile = new GRepParserV2.ArcRec + { + HermiteNodes = + [ + new() { T = 0, Point = [1, 0, 0], Tangent = [1, 0, 3] }, + new() { T = 1, Point = [2, 0, 3], Tangent = [1, 0, 3] }, + ], + }; + var measure = GRepParserV2.MeasureRevolvedFace(surface, profile, [0, 0, 0], Rectangle(Math.PI, 0, 1))!.Value; + + Assert.Equal(1.5 * Math.PI * Math.Sqrt(10), measure.Area, 11); + Assert.Equal(1.5 * Math.PI, measure.Volume, 11); + profile.HermiteNodes[0].Tangent[0] = -4; + Assert.Null(GRepParserV2.MeasureRevolvedFace(surface, profile, [0, 0, 0], Rectangle(Math.PI, 0, 1))); + } + + [Theory] + [InlineData(false, -1)] + [InlineData(true, 1)] + public void RuledApexIntegral_DoesNotRequireAnEdgeAtTheCollapsedEnd(bool apexAtEnd, double volume) + { + var profile = new GRepParserV2.ArcRec { C = [0, 0, 3], X = [1, 0, 0], T1 = 2 }; + var edges = Rectangle(1, 0, 1); + edges.RemoveAt(apexAtEnd ? 2 : 0); + var face = GRepParserV2.MeasureRuledApex(profile, new Pt3(0, 1, 3), apexAtEnd, default, edges)!.Value; + Assert.Equal(1, face.Area, 12); + Assert.Equal(volume, face.Volume, 12); + } + + [Fact] + public void RawRuledLoopRestoresOnlyTheImplicitEdgeAtThePole() + { + var pole = Rectangle(1, 0, 1); + pole.RemoveAt(2); + Assert.True(GRepParserV2.CloseRuledEndPole(pole, 0)); + Assert.Equal(new[] { (1d, 1d), (0d, 1d) }, pole[^1].Points); + + var open = Rectangle(1, 0, 0.75); + open.RemoveAt(2); + Assert.False(GRepParserV2.CloseRuledEndPole(open, 0)); + } + + [Fact] + public void RuledArcPairIntegral_MeasuresAConicalFrustumSide() + { + var bottom = new GRepParserV2.ArcRec { X = [1, 0, 0], Y = [0, 1, 0], R = 1, T1 = Math.PI }; + var top = bottom with { C = [0, 0, 3], R = 2 }; + var edges = Rectangle(1, 0, 1); + var measure = GRepParserV2.MeasureRuledProfiles(bottom, top, default, edges)!.Value; + + Assert.Equal(1.5 * Math.PI * Math.Sqrt(10), measure.Area, 11); + Assert.Equal(1.5 * Math.PI, measure.Volume, 11); + Assert.Null(GRepParserV2.MeasureRuledProfiles(bottom, top, default, Rectangle(1, 0, 0.9))); + Assert.Null(GRepParserV2.MeasureRuledProfiles(bottom, top with { T0 = 0.1 }, default, edges)); + } + [Fact] public void SurfaceIntegral_RejectsIncompleteOrUnsupportedInputs() { diff --git a/tests/RvtIO.Tests/EdgePointTests.cs b/tests/RvtIO.Tests/EdgePointTests.cs index 5a593e6a..19fb0c95 100644 --- a/tests/RvtIO.Tests/EdgePointTests.cs +++ b/tests/RvtIO.Tests/EdgePointTests.cs @@ -80,6 +80,20 @@ public void A_coedge_runs_along_its_edge_by_the_side_and_bit_0_of_the_edge_flags Assert.Equal(forward, GRepParserV2.MeshCoedgeForward(new GRepParserV2.EdgeRec { Flags = flags }, sideA)); } + [Fact] + public void Plane_point_preserves_rounding_order_with_only_the_result_allocation() + { + var surface = Frame([6e15, 8e15, 2], [0.6, 0.8, 0], [-0.8, 0.6, 0], [0, 0, 1], 0); + Assert.Equal([-0.8, 0.6, 2], GRepParserV2.MeshPlanePoint(surface, -1e16, 1)); + + var points = new double[256][]; + long before = GC.GetAllocatedBytesForCurrentThread(); + for (int i = 0; i < points.Length; i++) points[i] = GRepParserV2.MeshPlanePoint(surface, -1e16, i); + long allocated = GC.GetAllocatedBytesForCurrentThread() - before; + GC.KeepAlive(points); + Assert.InRange(allocated, 0, 64L * points.Length); + } + [Theory] [InlineData(4.712388980384685, 0.04152515010747385, 0.21247801399732427, -0.06250799034779941, 0.2056640577410033)] [InlineData(2.8955361930263255, 0.08314499133618838, 0.17085817276860957, 0.015225765113994889, 0.14503877478090532)] diff --git a/tests/RvtIO.Tests/FaceAreaTests.cs b/tests/RvtIO.Tests/FaceAreaTests.cs index 68d6b52d..0e19d104 100644 --- a/tests/RvtIO.Tests/FaceAreaTests.cs +++ b/tests/RvtIO.Tests/FaceAreaTests.cs @@ -63,6 +63,47 @@ public void AHalfDiscWithAFewArcPoints_IsNotItsExactArea() Assert.NotEqual(Math.PI / 2, area, 9); } + [Fact] + public void EllipticalCapQuadratureUsesEachAdjacentSampleOnce() + { + var arc = new FaceArea.Coedge([(2, 0), (1.4, 0.7), (0, 1), (-1.4, 0.7), (-2, 0)], 6, false); + var duplicate = arc with { Points = [(2, 0), (1.4, 0.7), (1.4 + 1e-12, 0.7), (0, 1), (-1.4, 0.7), (-2, 0)] }; + var diameter = Line((-2, 0), (2, 0)); + + Assert.Equal(FaceArea.Compute([arc, diameter]), FaceArea.ComputeWithDistinctSamples([duplicate, diameter])); + Assert.Null(FaceArea.ComputeWithDistinctSamples([Line((0, 0), (0, 0)), diameter])); + } + + [Fact] + public void EllipticalArcLengthIsIndependentOfTraversalDirection() + { + const double quarter = 2.422112055136919; + Assert.InRange(FaceArea.EllipticalArcLength(2, 1, 0, Math.PI / 2)!.Value, quarter - 3e-6, quarter + 3e-6); + Assert.Equal(FaceArea.EllipticalArcLength(2, 1, 0, Math.PI / 2)!.Value, + FaceArea.EllipticalArcLength(2, 1, Math.PI / 2, 0)!.Value, 12); + } + + [Fact] + public void AdaptiveHermiteQuadratureReusesItsWorkingBuffers() + { + FaceArea.Coedge[] edges = [new([(0, 0), (0.5, 0), (1, 0)], 0, false)]; + int samples = 0; + FaceArea.SurfaceIntegrand integrand = (u, _, du, _) => + { + samples++; + return Math.Pow(u, 20) * du; + }; + var integral = FaceArea.Integrate(edges, integrand); + Assert.InRange(integral!.Value, 1.0 / 21 - 1e-8, 1.0 / 21 + 1e-8); + Assert.True(samples > 17); // More than the initial five estimates. + + const int runs = 128; + long before = GC.GetAllocatedBytesForCurrentThread(); + for (int i = 0; i < runs; i++) FaceArea.Integrate(edges, integrand); + long allocated = GC.GetAllocatedBytesForCurrentThread() - before; + Assert.InRange(allocated, 0, 128L * runs); // The coedge enumerable may still allocate an enumerator. + } + [SkippableFact] public void TheCapsOfRoom8964053_HaveTheAreasReferenceComputes_AndAreNotPaired() { diff --git a/tests/RvtIO.Tests/Format2027SchemaTests.cs b/tests/RvtIO.Tests/Format2027SchemaTests.cs index 960ac308..5c6b1c87 100644 --- a/tests/RvtIO.Tests/Format2027SchemaTests.cs +++ b/tests/RvtIO.Tests/Format2027SchemaTests.cs @@ -51,6 +51,56 @@ public void Walk_SkipsTheFieldsTheStreamDoesNotCarry() Assert.Equal(1, walk.Captures.Single(c => c.Key == "Table.m_table#").Integer); } + [Theory] + [InlineData(false)] + [InlineData(true)] + public void HostTypeLayersFollowItsCompleteUnambiguousOwnedStructure(bool duplicate) + { + var pointer = new SchemaField("m_pCompoundStructure", 14, 1, 0, null, null, null, null); + var schema = new SchemaDocument + { + Classes = + [ + new(1, "Identifier", 0, 1, [Field("m_id64", 11)], []), + new(2, "ElementId", 0, 1, [new("m_id", 14, 0, 0, null, 1, null, null)], []), + new(3, "HostObjAttr", 0, 1, duplicate ? [pointer, pointer with { Name = "m_other" }] : [pointer], []), + new(4, "CompoundStructure", 0, 1, [new("m_layers", 14, 0x50, 0, null, 5, null, null)], []), + new(5, "CompoundStructureLayer", 0, 1, + [Field("m_layerWidth", 7), new("m_materialId", 14, 0, 0, null, 2, null, null), Field("m_layerFunction", 4)], []), + ], + }; + using var stream = new MemoryStream(); + using var writer = new BinaryWriter(stream); + writer.Write((ushort)3); + writer.Write(uint.MaxValue); + writer.Write((ushort)4); + if (duplicate) + { + writer.Write(uint.MaxValue); + writer.Write((ushort)4); + } + writer.Write(2u); + writer.Write(0.25); writer.Write(420L); writer.Write(4); + writer.Write(0.0); writer.Write(-1L); writer.Write(100); + if (duplicate) writer.Write(0u); + var block = stream.ToArray(); + var reader = new WideNativeParams(schema); + var walk = reader.Walker.Run(block, 0, block.Length, 3); + + Assert.True(walk.Exact, walk.Error); + Assert.Equal(TfClassNames.IdOf("CompoundStructure"), + reader.Build(walk, 3)!.Fields[TfClassNames.Key("HostObjAttr", "m_pCompoundStructure")]); + var layers = reader.HostTypeLayers(walk, 3); + if (duplicate) Assert.Null(layers); + else + { + Assert.NotNull(layers); + Assert.Equal([(420, 4, 0.25, 0), (-1, 100, 0.0, 1)], + layers.Select(layer => (layer.MaterialId, layer.Function, layer.ThicknessFt, layer.LayerIndex))); + } + Assert.Null(reader.HostTypeLayers(reader.Walker.Run(block, 0, block.Length - 1, 3), 3)); + } + [Fact] public void CategoryNames_KnowTheMembersAddedAfter2022() { diff --git a/tests/RvtIO.Tests/FormatCorpusTests.cs b/tests/RvtIO.Tests/FormatCorpusTests.cs new file mode 100644 index 00000000..86902cac --- /dev/null +++ b/tests/RvtIO.Tests/FormatCorpusTests.cs @@ -0,0 +1,58 @@ +using System.Security.Cryptography; +using System.Text.Json; +using OpenMcdf; +using RvtIO.Parsing; +using Xunit; +using Xunit.Abstractions; + +namespace RvtIO.Tests; + +public sealed class FormatCorpusTests(ITestOutputHelper output) +{ + private sealed record Sample(string Path, string Sha256, int PartitionStreams, int PagedStreams, + long Records, long PayloadBytes, int ElemTableRows); + + [SkippableFact] + public void EachFileMatchesItsStructuralBaseline() + { + string? configured = Environment.GetEnvironmentVariable("RVTIO_FORMAT_CORPUS"); + if (string.IsNullOrWhiteSpace(configured)) + throw new SkipException("Set RVTIO_FORMAT_CORPUS to the format baseline JSON file."); + + string manifest = Path.GetFullPath(configured); + var samples = JsonSerializer.Deserialize(File.ReadAllText(manifest), + new JsonSerializerOptions { PropertyNameCaseInsensitive = true }); + Assert.NotNull(samples); + Assert.NotEmpty(samples); + + var paths = new HashSet(OperatingSystem.IsWindows() ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal); + foreach (var sample in samples) + { + string path = Path.GetFullPath(sample.Path, Path.GetDirectoryName(manifest)!); + output.WriteLine(path); + Assert.True(paths.Add(path), $"Duplicate sample path: {path}"); + using (var input = File.OpenRead(path)) + Assert.Equal(sample.Sha256.ToUpperInvariant(), Convert.ToHexString(SHA256.HashData(input))); + + var census = CoverageCensus.Read(path); + Assert.Null(census.RecordsFailure); + Assert.True(sample.PartitionStreams > 0 && sample.PagedStreams > 0 && sample.Records > 0 && sample.ElemTableRows > 0); + var partitions = census.Streams.Where(stream => stream.Kind == "partition").ToList(); + var paged = census.Streams.Where(stream => stream.Kind == "paged").ToList(); + Assert.Equal(sample.PartitionStreams, partitions.Count); + Assert.Equal(sample.PagedStreams, paged.Count); + Assert.All(partitions, stream => Assert.True(stream.Framing == "ok", $"{stream.Path}: {stream.Framing}")); + Assert.All(paged, stream => Assert.True(stream.Decoded == true, $"{stream.Path}: failed to inflate")); + Assert.Equal(sample.Records, census.Totals.Items); + Assert.Equal(sample.Records, census.Totals.Exact); + Assert.Equal(sample.PayloadBytes, census.Totals.PayloadBytes); + Assert.Equal(sample.PayloadBytes, census.Totals.ExactBytes); + Assert.Equal(0, census.Totals.ChecksumMismatches); + + using var root = RootStorage.OpenRead(path); + var table = ElemTableReader.Read(root, out _, out _, out bool exact); + Assert.True(exact, "The production element table reader did not read the table exactly."); + Assert.Equal(sample.ElemTableRows, table.Count); + } + } +} diff --git a/tests/RvtIO.Tests/IfcExporterWallGeometryTests.cs b/tests/RvtIO.Tests/IfcExporterWallGeometryTests.cs index 8f84e47e..70e1fe6e 100644 --- a/tests/RvtIO.Tests/IfcExporterWallGeometryTests.cs +++ b/tests/RvtIO.Tests/IfcExporterWallGeometryTests.cs @@ -24916,6 +24916,51 @@ public void HostedOpeningBoundary_ProjectsAuthoredReturnToClearSpan() Assert.Equal(2, height); } + [Fact] + public void FacetedLatticeSegment_PreservesExactBoundsAndCollinearity() + { + var axis = new FacetedShell.LatticeSegment((long.MaxValue, 4, 5), (long.MinValue, 4, 5)); + Assert.Equal(0, axis.DominantAxis); + Assert.True(axis.OnSegment((0, 4, 5))); + Assert.False(axis.OnSegment((0, 5, 5))); + + var diagonal = new FacetedShell.LatticeSegment( + (long.MaxValue, long.MaxValue, long.MaxValue), (long.MinValue, long.MinValue, long.MinValue)); + Assert.Equal(0, diagonal.DominantAxis); + Assert.True(diagonal.OnSegment((long.MinValue, long.MinValue, long.MinValue))); + Assert.True(diagonal.OnSegment((0, 0, 0))); + Assert.False(diagonal.OnSegment((0, 1, 0))); + + var wide = new FacetedShell.LatticeSegment((0, 0, 0), (1L << 33, 1L << 33, 0)); + Assert.False(wide.OnSegment((1L << 31, 1L << 32, 0))); + + var bounded = new FacetedShell.LatticeSegment((-3, -6, 0), (3, 6, 0)); + Assert.Equal(1, bounded.DominantAxis); + Assert.True(bounded.OnSegment((2, 4, 0))); + Assert.False(bounded.OnSegment((4, 8, 0))); + } + + [Fact] + public void FacetedVertexAxisIndex_PreservesLexicographicTies() + { + (long X, long Y, long Z)[] vertices = + [ + (1, 0, 1), (0, 1, 1), (1, 1, 0), (0, 0, 1), (1, 0, 0), + (long.MaxValue, 0, long.MinValue), (long.MinValue, long.MaxValue, 0), + ]; + var original = vertices.ToArray(); + + var index = FacetedShell.BuildVertexAxisIndex(vertices); + + for (int axis = 0; axis < 3; axis++) + { + var expected = original.OrderBy(point => axis == 0 ? point.X : axis == 1 ? point.Y : point.Z) + .ThenBy(point => point.X).ThenBy(point => point.Y).ThenBy(point => point.Z).ToArray(); + Assert.Equal(expected, index[axis]); + } + Assert.Equal(original, vertices); + } + [Fact] public void ExactFacetedShell_AcceptsOppositelyDirectedSharedEdges() { @@ -24935,23 +24980,125 @@ public void ExactFacetedShell_AcceptsOppositelyDirectedSharedEdges() } [Fact] - public void ExactFacetedShell_OrientsLongEdgeAcrossExactTjunctions() + public void FacetedAtomicEdgeUses_RetainsOpenBoundariesButRejectsCollapsedEdges() + { + var face = Face([[0, 0, 0], [1, 0, 0], [0, 1, 0]]); + var malformed = Face([[0, 0, 0], [1, 0, 0], [0, 0, 1]]); + malformed.InnerVertices = [[[0, 0, 0], [1e-8, 0, 0], [1, 0, 0]]]; + var faces = new Dictionary { [4] = face, [5] = malformed }; + + Assert.False(FacetedShell.TryGetFacetedAtomicEdgeUses(faces, [4], out var boundary)); + Assert.Equal(3, boundary.Count); + Assert.All(boundary.Values, uses => + { + Assert.Equal(1, uses.Count); + Assert.Equal(4, uses.First.FaceIndex); + }); + + Assert.False(FacetedShell.TryGetFacetedAtomicEdgeUses(faces, [4, 5], out var rejected)); + Assert.Empty(rejected); + } + + [Fact] + public void FacetedAtomicEdgeUses_RetainsAllUsesOfNonmanifoldEdgeInOrder() + { + double[] a = [0, 0, 0], b = [1, 0, 0]; + var faces = new Dictionary + { + [2] = Face([a, b, [0, 1, 0]]), + [7] = Face([b, a, [0, -1, 0]]), + [9] = Face([a, b, [0, 0, 1]]), + [0] = Face([b, a, [0, 0, -1]]), + }; + + Assert.False(FacetedShell.TryGetFacetedAtomicEdgeUses(faces, [7, 2, 9, 0], out var edges)); + var key = (FacetedShell.IfcPrecisionKeyFeet(a), FacetedShell.IfcPrecisionKeyFeet(b)); + var uses = edges[key]; + Assert.Equal(new[] { (7, -1), (2, 1), (9, 1), (0, -1) }, + Enumerable.Range(0, uses.Count).Select(i => uses[i])); + } + + [Theory] + [InlineData(false, 0)] + [InlineData(false, 3)] + [InlineData(true, 0)] + [InlineData(true, 3)] + public void FacetedAtomicEdgeUses_RecordsDiagonalSplitsInTraversalOrder(bool reverse, int initialCapacity) + { + double[] a = [3, 0, 0], b = [0, 6, 0], p = [2, 2, 0], q = [1, 4, 0], c = [0, 0, 0]; + var faces = new Dictionary + { + [4] = Face(reverse ? [b, a, c] : [a, b, c]), + [5] = Face([p, q, [1, 2, 0]]), + }; + var ka = FacetedShell.IfcPrecisionKeyFeet(a); + var kb = FacetedShell.IfcPrecisionKeyFeet(b); + var kp = FacetedShell.IfcPrecisionKeyFeet(p); + var kq = FacetedShell.IfcPrecisionKeyFeet(q); + var expected = new[] { (kp, ka), (kq, kp), (kb, kq) }; + if (reverse) Array.Reverse(expected); + + var splitVertices = new HashSet<(long X, long Y, long Z)> + { + FacetedShell.IfcPrecisionKeyFeet([1.5, 3, 0]), + }; + Assert.False(FacetedShell.TryGetFacetedAtomicEdgeUses( + faces, [4, 5], out var boundary, initialCapacity, splitVertices)); + Assert.Equal(expected, boundary.Keys.Take(expected.Length)); + Assert.All(expected, edge => + { + var uses = boundary[edge]; + var use = Assert.Single(Enumerable.Range(0, uses.Count).Select(i => uses[i]), + use => use.FaceIndex == 4); + Assert.Equal(reverse ? 1 : -1, use.Direction); + }); + } + + [Theory] + [InlineData(false, false)] + [InlineData(false, true)] + [InlineData(true, false)] + [InlineData(true, true)] + public void ExactFacetedShell_OrientsLongEdgeAcrossExactTjunctions(bool inward, bool triangulate) { var faces = new List { - Face([[0, 0, 0], [0, 1, 0], [2, 1, 0], [2, 0, 0]]), - Face([[0, 0, 1], [2, 0, 1], [2, 1, 1], [0, 1, 1]]), + Face([[0, 0, 0], [0, 1, 0], [3, 1, 0], [3, 0, 0]]), + Face([[0, 0, 1], [3, 0, 1], [3, 1, 1], [0, 1, 1]]), Face([[0, 0, 0], [1, 0, 0], [1, 0, 1], [0, 0, 1]]), Face([[1, 0, 0], [2, 0, 0], [2, 0, 1], [1, 0, 1]]), - Face([[0, 1, 0], [0, 1, 1], [2, 1, 1], [2, 1, 0]]), + Face([[2, 0, 0], [3, 0, 0], [3, 0, 1], [2, 0, 1]]), + Face([[0, 1, 0], [0, 1, 1], [3, 1, 1], [3, 1, 0]]), Face([[0, 0, 0], [0, 0, 1], [0, 1, 1], [0, 1, 0]]), - Face([[2, 0, 0], [2, 1, 0], [2, 1, 1], [2, 0, 1]]), + Face([[3, 0, 0], [3, 1, 0], [3, 1, 1], [3, 0, 1]]), }; + if (inward) + foreach (var face in faces) + face.OuterVertices!.Reverse(); - Assert.True(IfcExporter.TryOrientExactFacetedShell( - faces, Enumerable.Range(0, faces.Count).ToArray(), out var oriented)); + Assert.True(FacetedShell.TryOrientExactFacetedShell( + faces, Enumerable.Range(0, faces.Count).ToArray(), out var oriented, triangulate)); Assert.True(FacetedShell.IsExactFacetedShell( oriented, Enumerable.Range(0, oriented.Count).ToArray())); + AssertFrontEdge(oriented[0].OuterVertices!, [3, 2, 1, 0]); + AssertFrontEdge(oriented[1].OuterVertices!, [0, 1, 2, 3]); + var sourcePoints = faces.SelectMany(face => face.OuterVertices!).ToHashSet(ReferenceEqualityComparer.Instance); + var orientedPoints = oriented.SelectMany(face => face.OuterVertices!).ToList(); + Assert.DoesNotContain(orientedPoints, sourcePoints.Contains); + if (inward) + Assert.Equal(orientedPoints.Count, orientedPoints.Distinct(ReferenceEqualityComparer.Instance).Count()); + + static void AssertFrontEdge(List ring, double[] expected) + { + int start = ring.FindIndex(point => point[0] == expected[0] && point[1] == 0); + Assert.True(start >= 0); + for (int i = 0; i < expected.Length; i++) + { + var point = ring[(start + i) % ring.Count]; + Assert.Equal(expected[i], point[0]); + Assert.Equal(0, point[1]); + } + } } [Fact] @@ -25145,7 +25292,7 @@ public void ExactFacetedShell_OrientsAfterRemovingPrecisionCollapsedLoopEdge() double[] b = [1, 0, 0], c = [0, 1, 0], d = [0, 0, 1]; var faces = new List { - Face([a, nearA, c, b]), + Face([a, nearA, c, b, nearA]), Face([a, b, d]), Face([b, c, d]), Face([c, a, d]), @@ -25156,6 +25303,8 @@ public void ExactFacetedShell_OrientsAfterRemovingPrecisionCollapsedLoopEdge() faces, [0, 1, 2, 3], out var oriented)); Assert.True(FacetedShell.IsExactFacetedShell(oriented, [0, 1, 2, 3])); Assert.All(oriented, face => Assert.Equal(3, face.OuterVertices!.Count)); + Assert.Equal(5, faces[0].OuterVertices!.Count); + Assert.Equal(a, oriented[0].OuterVertices![0]); } [Fact] @@ -25246,10 +25395,15 @@ public void ExactFacetedShell_RecoversConsistentOutwardOrientationFromSharedEdge Face([b, c, d]), Face([c, a, d]), }; + var reversedInput = faces[1].OuterVertices!.ToArray(); + faces[1].Normal = [0, 2, 0]; Assert.True(IfcExporter.TryOrientExactFacetedShell( faces, [0, 1, 2, 3], out var oriented)); Assert.True(FacetedShell.IsExactFacetedShell(oriented, [0, 1, 2, 3])); + Assert.True(reversedInput.SequenceEqual(faces[1].OuterVertices!)); + Assert.Equal(2, faces[1].Normal[1]); + Assert.Equal(-2, oriented[1].Normal[1]); double volume = 0; foreach (var face in oriented) diff --git a/tests/RvtIO.Tests/NativeTypePointersTests.cs b/tests/RvtIO.Tests/NativeTypePointersTests.cs index 4cadce58..fe308b41 100644 --- a/tests/RvtIO.Tests/NativeTypePointersTests.cs +++ b/tests/RvtIO.Tests/NativeTypePointersTests.cs @@ -17,6 +17,10 @@ private static TfBlockDeserializer.NativeParams With(string key, int value) [InlineData(3681, "3681:m_typeId")] // stairs [InlineData(485, "485:m_stairsRailingAttrId")] // railing [InlineData(3475, "3475:m_symbolId")] // room tag + [InlineData(527, "527:m_symbolId")] // independent tag + [InlineData(804, "804:m_typeId")] // continuous footing + [InlineData(3111, "3111:m_stairsAttrId")] // stairs in the wide schema + [InlineData(3989, "823:m_typeId")] // continuous rail type public void TypeIdIsTheFieldOfTheRootClass(ushort rootClass, string key) => Assert.Equal(1234, NativeTypePointers.Of(rootClass, With(key, 1234))); diff --git a/tests/RvtIO.Tests/Revit2027ApiValuesTests.cs b/tests/RvtIO.Tests/Revit2027ApiValuesTests.cs new file mode 100644 index 00000000..bd03c93d --- /dev/null +++ b/tests/RvtIO.Tests/Revit2027ApiValuesTests.cs @@ -0,0 +1,222 @@ +using System.Reflection; +using OpenMcdf; +using RvtIO.BuiltIns; +using RvtIO.Internal; +using RvtIO.Model; +using RvtIO.Parsing; +using Xunit; + +namespace RvtIO.Tests; + +public sealed class Revit2027ApiValuesTests +{ + private static ParsingState Wide2027() + { + string path = TestFiles.Scratch($"schema-api-values-{Guid.NewGuid():N}.rvt"); + try + { + SchemaReleaseTests.WriteSyntheticFile(path, wide: true, marker: 951, saved: 2027); + using var root = RootStorage.OpenRead(path); + var schema = FileSchema.Read(root)!; + Assert.Equal(2027, schema.Release); + return new ParsingState { WideSchema = schema }; + } + finally { File.Delete(path); } + } + + [Theory] + [InlineData(false, 0, -1)] + [InlineData(true, 0, 0)] + [InlineData(true, 55, 55)] + [InlineData(null, 0, 0)] + public void WorksetMembershipAndParameterHaveSeparateValues(bool? workshared, int stored, int shown) + { + var state = Wide2027(); + var element = new Element { Id = 10 }; + state.ElemWorksets[10] = (uint)stored; + var info = new RevitFileInfo { Elements = [element], SerializedIsWorkshared = workshared }; + + typeof(ElementBuilder).GetMethod("ApplyWorksets", BindingFlags.NonPublic | BindingFlags.Static)! + .Invoke(null, [info, state]); + + Assert.Equal(stored, element.WorksetId); + var parameter = Assert.Single(element.Parameters); + Assert.Equal(-1002053, parameter.Id); + Assert.Equal(StorageType.Integer, parameter.StorageType); + Assert.Equal(shown, parameter.Value); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void PropertySetOnlyHasWorksetMembershipInLocal2027Files(bool workshared) + { + var state = Wide2027(); + state.ElemWorksets[10] = 0; + var element = new Element { Id = 10, NativeRootClassName = "PropertySetElement" }; + element.Parameters.Add(BipHelpers.MakeBipParam(-1002053, "ELEM_PARTITION_PARAM", StorageType.Integer, 0)); + var info = new RevitFileInfo { Elements = [element], SerializedIsWorkshared = workshared }; + + typeof(ElementBuilder).GetMethod("ApplyWorksets", BindingFlags.NonPublic | BindingFlags.Static)! + .Invoke(null, [info, state]); + + Assert.Equal(0, element.WorksetId); + Assert.Equal(workshared, element.Parameters.Any(p => p.Id == -1002053)); + } + + [Theory] + [InlineData(false, -2000485)] + [InlineData(true, -2000480)] + public void KnownWideHeaderCategoryTakesPrecedenceOverTheLegacyClassDefault(bool legacy, int expected) + { + var state = Wide2027(); + state.R22View = legacy; + state.ElemClassIdx[10] = (ushort)TfClassNames.IdOf("RoomTag"); + var element = new Element { Id = 10, NativeHeaderCategoryId = -2000485, CategoryId = -2000485 }; + var info = new RevitFileInfo { Elements = [element] }; + + typeof(ElementBuilder).GetMethod("FixCategoryFromClassIdx", BindingFlags.NonPublic | BindingFlags.Static)! + .Invoke(null, [info, state]); + + Assert.Equal(expected, element.CategoryId); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public void ExactViewAndCenterLineLinksReadValuesFromTheirOwners(bool exact) + { + var state = Wide2027(); + var viewType = ElementRoot(state, 1, "DBViewType"); + var view = ElementRoot(state, 2, "DBViewPlan", ("m_dbViewTypeId", 1)); + var viewer = ElementRoot(state, 3, "Viewer", (WideNativeParams.ViewerViewKey, 2)); + viewer.NativeRootClassChain = ["Viewer", "Element"]; + var pipe = ElementRoot(state, 4, "RbsPipeCurve"); + pipe.Parameters.Add(BipHelpers.MakeBipParam(-1001203, "ALL_MODEL_MARK", StorageType.String, "P01")); + pipe.Parameters.Add(BipHelpers.MakeBipParam(-1140225, "RBS_PIPE_DIAMETER_PARAM", StorageType.Double, 0.25)); + var centerline = ElementRoot(state, 5, "SegmentCenterLine", (TfClassNames.Key("CenterLine", "m_OwnerId"), 4)); + centerline.NativeRootClassChain = ["SegmentCenterLine", "CenterLine", "Element"]; + state.NativeParams[2].TailWalkComplete = exact; + state.NativeParams[4].TailWalkComplete = exact; + var info = new RevitFileInfo { Elements = [viewType, view, viewer, pipe, centerline] }; + + Revit2027ApiValues.Apply(info, state, info.Elements.ToDictionary(element => element.Id)); + + Assert.Equal(exact ? 1 : -1, viewer.TypeId); + if (exact) + Assert.Equal(new object?[] { "P01", 0.25 }, centerline.Parameters.Select(p => p.Value)); + else + Assert.Empty(centerline.Parameters); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public void ElevationAndStairPartsUseTheirLinkedTypes(bool linked) + { + var state = Wide2027(); + var viewType = ElementRoot(state, 1, "DBViewType"); + var marker = ElementRoot(state, 2, "InteriorElev", (TfClassNames.Key("InteriorElev", "m_symbolId"), 1)); + var arrow = ElementRoot(state, 3, "InteriorElevArrow", (WideNativeParams.ViewerViewKey, 4), + (TfClassNames.Key("InteriorElevArrow", "m_parentId"), marker.Id)); + arrow.NativeRootClassChain = ["InteriorElevArrow", "Viewer", "Element"]; + var section = ElementRoot(state, 4, "DBViewSection", ("m_dbViewTypeId", -1), + (TfClassNames.Key("DBView", "m_viewerId"), linked ? arrow.Id : -1)); + var runType = ElementRoot(state, 5, linked ? "StairsRunType" : "StairsLandingType"); + var stairsType = ElementRoot(state, 6, "StairsType", (TfClassNames.Key("StairsType", "m_runTypeId"), 5)); + var stairs = ElementRoot(state, 7, "StairsElement", (TfClassNames.Key("StairsElement", "m_typeId"), 6)); + var run = ElementRoot(state, 8, "StairsRun", (TfClassNames.Key("StairsRunAndLanding", "m_stairsId"), 7)); + var info = new RevitFileInfo { Elements = [viewType, marker, arrow, section, runType, stairsType, stairs, run] }; + + Revit2027ApiValues.Apply(info, state, info.Elements.ToDictionary(element => element.Id)); + + Assert.Equal(linked ? viewType.Id : -1, arrow.TypeId); + Assert.Equal(linked ? viewType.Id : -1, section.TypeId); + Assert.Equal(linked ? runType.Id : -1, run.TypeId); + if (linked) + Assert.Equal(new object?[] { runType.Id, runType.Id }, run.Parameters.Select(p => p.Value)); + else + Assert.Empty(run.Parameters); + } + + [Theory] + [InlineData(BuiltInCategory.OST_MassRoof, 0, "High Insulation - Cool Roof")] + [InlineData(BuiltInCategory.OST_MassWallsAll, 0, "Lightweight Construction - High Insulation")] + [InlineData(BuiltInCategory.OST_MassRoof, -1, "")] + public void ConstructionNameRequiresBothStoredDiscriminators(BuiltInCategory category, int index, string expected) + { + var state = Wide2027(); + var type = ElementRoot(state, 1, "ConceptualConstructionType", + (TfClassNames.Key("ConceptualConstructionType", "m_massSurfaceSubCategoryId"), (int)category), + (TfClassNames.Key("ConceptualConstructionType", "m_conceptualConstructionTypeEnumAsInt"), index)); + type.NativeIsSymbol = true; + type.Parameters.Add(BipHelpers.MakeBipParam((int)BuiltInParameter.ALL_MODEL_TYPE_NAME, "ALL_MODEL_TYPE_NAME", StorageType.String, "")); + var info = new RevitFileInfo { Elements = [type] }; + + Revit2027ApiValues.Apply(info, state, info.Elements.ToDictionary(element => element.Id)); + + Assert.Equal(expected, Assert.Single(type.Parameters).Value); + } + + [Theory] + [InlineData(127, true)] + [InlineData(128, false)] + public void StraightDuctVolumeRequiresTheRectangularProfile(int profile, bool hasVolume) + { + var state = Wide2027(); + var type = ElementRoot(state, 1, "AbsDuctType"); + state.SystemTypeRoots[1] = (1, 110, profile); + var duct = ElementRoot(state, 2, "RbsDuctCurve", ("602:m_idType", type.Id)); + duct.CategoryId = (int)BuiltInCategory.OST_DuctCurves; + duct.Parameters.Add(BipHelpers.MakeBipParam((int)BuiltInParameter.CURVE_ELEM_LENGTH, "CURVE_ELEM_LENGTH", StorageType.Double, 5d)); + var fields = state.NativeParams[2].DoubleFields; + fields["87:m_pCrv.endParams@0"] = 0; + fields["602:m_dWidthOrDiameter"] = 2; + fields["602:m_dHeight"] = 2; + var info = new RevitFileInfo { Elements = [type, duct] }; + + Revit2027ApiValues.Apply(info, state, info.Elements.ToDictionary(element => element.Id)); + + var volume = duct.Parameters.SingleOrDefault(p => p.Id == (int)BuiltInParameter.HOST_VOLUME_COMPUTED); + if (hasVolume) Assert.Equal(20d, volume?.Value); + else Assert.Null(volume); + } + + [Theory] + [InlineData(true, 6d)] + [InlineData(false, null)] + public void RegionAreaRequiresOneClosedLineLoop(bool closed, double? expected) + { + double[] a = [1200, 800, 0], b = [1203, 800, 0], c = [1203, 802, 0], d = [1200, 802, 0]; + var area = WideNativeParams.ClosedLineLoopArea([(a, b), (c, d), (c, b), (d, closed ? a : [1199, 800, 0])]); + Assert.Equal(expected, area); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public void RegionAreaRequiresItsOwnSketch(bool linked) + { + var state = Wide2027(); + var sketch = ElementRoot(state, 1, "VarSketch", (TfClassNames.Key("SketchBase", "m_userId"), linked ? 2 : 3)); + state.NativeParams[1].DoubleFields[WideNativeParams.SketchLineArea] = 6; + var region = ElementRoot(state, 2, "FilledRegion", (TfClassNames.Key("SketchedRegion", "m_sketchId"), sketch.Id)); + var info = new RevitFileInfo { Elements = [sketch, region] }; + + Revit2027ApiValues.Apply(info, state, info.Elements.ToDictionary(element => element.Id)); + + if (linked) Assert.Equal(6d, Assert.Single(region.Parameters).Value); + else Assert.Empty(region.Parameters); + } + + private static Element ElementRoot(ParsingState state, uint id, string kind, params (string Key, int Value)[] fields) + { + var root = new TfBlockDeserializer.NativeParams { TailWalkComplete = true }; + root.Fields["m_id"] = (int)id; + foreach (var (key, value) in fields) root.Fields[key] = value; + state.NativeParams[id] = root; + state.NativeParamsFromRootClass.Add(id); + state.NativeRootClassNames[id] = kind; + return new Element { Id = (int)id, TypeId = -1, NativeRootClassName = kind }; + } +} diff --git a/tests/RvtIO.Tests/SchemaReleaseTests.cs b/tests/RvtIO.Tests/SchemaReleaseTests.cs index f3809aec..cf16a856 100644 --- a/tests/RvtIO.Tests/SchemaReleaseTests.cs +++ b/tests/RvtIO.Tests/SchemaReleaseTests.cs @@ -152,7 +152,7 @@ public void ContradictoryDeclaredWidthsRemainUndecoded(bool wide, int marker, in finally { File.Delete(path); } } - private static void WriteSyntheticFile(string path, bool wide, int marker, int? saved) + internal static void WriteSyntheticFile(string path, bool wide, int marker, int? saved) { using var root = RootStorage.Create(path, OpenMcdf.Version.V3); using var formats = root.CreateStorage("Formats").CreateStream("Latest"); diff --git a/tests/RvtIO.Tests/TessellationAllocationTests.cs b/tests/RvtIO.Tests/TessellationAllocationTests.cs index e56bbfdb..4e0eb04f 100644 --- a/tests/RvtIO.Tests/TessellationAllocationTests.cs +++ b/tests/RvtIO.Tests/TessellationAllocationTests.cs @@ -39,6 +39,18 @@ public void MaxAbsIgnoringNaN_matches_Select_Abs_Max() } } + [Fact] + public void TrimBoundaryBoundsPreserveTheEdgeToleranceAndFirstMatch() + { + (double, double, double, double)[] edges = [(0, 0, 1, 0), (1e6, 3, 1e6 + 1, 3), (1e6, 3, 1e6 + 1, 3)]; + (double[], double[])[] world = [([0, 0, 0], [1, 0, 0]), ([0, 0, 10], [2, 0, 10]), ([0, 0, 20], [2, 0, 20])]; + var point = GRepParserV2.TrimBoundaryEvaluator(edges, (u, v) => [u, v, -1], world); + + Assert.Equal(new[] { 1.0, 0, 10 }, point(1e6 + 0.5, 3 + 1e-8)); + // The large edge raises the pruning bound, while the small edge keeps its own tolerance. + Assert.Equal(new[] { 0.5, 1e-9, -1 }, point(0.5, 1e-9)); + } + [Fact] public void MaxIgnoringNaN_and_MinPropagatingNaN_match_Max_and_Min_of_a_projection() { @@ -219,4 +231,36 @@ public void OrderRingsW_ties_between_components_keep_the_earlier_ring() Assert.Equal(2, rings.Count); Assert.Equal(Describe(TessellationReference.OrderRingsW(segments), segments), Describe(rings, segments)); } + + [Fact] + public void OrderRingsW_preserves_simple_components_beside_branches() + { + double[] P(double x, double y) => [x, y, 0]; + var a = P(0, 0); var b = P(1, 0); var c = P(1, 1); var d = P(0, 1); + var e = P(3, 0); var f = P(4, 0); var g = P(4, 1); var h = P(3, 1); + List<(double[] A, double[] B)> segments = + [ + (b, P(2, -1)), (f, h), (c, b), (g, h), (d, c), (h, e), (a, d), (f, g), (b, a), (e, f), (c, d), + ]; + foreach (bool containing in new[] { false, true }) + { + var expected = TessellationReference.OrderRingsW(segments, containing); + var actual = GRepParserV2.OrderRingsW(segments, containing); + Assert.True(expected.Count >= 2); + Assert.Equal(Describe(expected, segments), Describe(actual, segments)); + } + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void OrderRingsW_preserves_the_first_surviving_edge_direction(bool containing) + { + double[] a = [0, 0, 0], b = [1, 0, 0], c = [1, 1, 0], d = [0, 1, 0], spur = [2, 1, 0]; + var ring = Assert.Single(GRepParserV2.OrderRingsW( + [(c, spur), (c, b), (b, c), (a, d), (a, b), (d, c)], containing)); + + Assert.Collection(ring, p => Assert.Same(c, p), p => Assert.Same(d, p), + p => Assert.Same(a, p), p => Assert.Same(b, p)); + } } diff --git a/tests/RvtIO.Tests/WideBlockWalkerEntityTests.cs b/tests/RvtIO.Tests/WideBlockWalkerEntityTests.cs index 900f2c83..c58bde24 100644 --- a/tests/RvtIO.Tests/WideBlockWalkerEntityTests.cs +++ b/tests/RvtIO.Tests/WideBlockWalkerEntityTests.cs @@ -151,6 +151,27 @@ public void Walk_ReadsTheValuesOfAnEntityByItsSchema_WhereTheQueueReachesThem(bo Assert.Equal(0, walk.EmptyEntityAt); } + [Fact] + public void ProductionFieldReaderPreservesANameQueuedAfterANestedEntity() + { + var schema = Schema(usageMap: true); + schema.Classes[schema.Classes.FindIndex(c => c.Id == DataId)] = new(DataId, "SymbolInfo", 0, 1, + [Field("m_name", 8, 0x60), Field("m_value", 8, 0x60)], []); + (string Name, string Type, int Container, int Index)[] outer = [("Inner", "ESEntity", 0, 0)]; + (string Name, string Type, int Container, int Index)[] inner = [("Value", "int", 0, 0)]; + var reader = new WideNativeParams(schema); + reader.Walker.UseEntitySchemas(EntitySchemaReader.Read(Latest(true, (SchemaA, outer), (SchemaB, inner)), schema)!, + passUnknown: true); + var block = HostBlock(w => { w.Write(0xFFFFFFFFu); w.Write(SchemaB.ToByteArray()); }, behind: w => w.Write(123)); + + var walk = reader.Walker.Run(block, 0, block.Length, HostId); + + Assert.True(walk.Exact, walk.Error); + Assert.Equal(["ESEntityCell", "Model", "ESBlob", "SymbolInfo", "ESBlob"], walk.Queue.Select(id => reader.Walker.Class(id)!.Name)); + Assert.Equal("FieldName", reader.OwnName(walk, HostId)); + Assert.False(reader.Walker.Run(block[..^1], 0, block.Length - 1, HostId).Exact); + } + [Fact] public void Walk_AnEntityWithTheHandle0_HasNoValues_AndQueuesNothing() { diff --git a/tests/RvtIO.Tests/WideElementRecordsTests.cs b/tests/RvtIO.Tests/WideElementRecordsTests.cs index 847d2025..49644558 100644 --- a/tests/RvtIO.Tests/WideElementRecordsTests.cs +++ b/tests/RvtIO.Tests/WideElementRecordsTests.cs @@ -192,6 +192,23 @@ public void ParseElemTable_KeepsIdZeroSkipsIdsOutsideTheModelIdSpaceAndRejectsBr Assert.Null(WideElementRecords.ParseElemTable(good, FileSchema.Parse(OnlyOther())!)); // schema without the table classes } + [Theory] + [InlineData("Rebar", "RebarBarType", 7)] + [InlineData("RebarInSystem", "RebarBarType", 7)] + [InlineData("Rebar", "Level", -1)] + public void WideElementUsesTheDecodedBarTypeWhenItsTargetIsARebarBarType(string root, string target, int expected) + { + var state = new ParsingState { WideSchema = new FileSchema(new SchemaDocument()) }; + state.NativeRootClassNames[8] = root; + state.NativeRootClassNames[7] = target; + state.RebarBars[8] = new RebarBars(7, 0, null, []); + var info = new RevitFileInfo(); + + ElementBuilder.BuildElemTableElement(8, 0, state, info); + + Assert.Equal(expected, Assert.Single(info.Elements).TypeId); + } + private static byte[] OnlyOther() { var w = new SchemaWriter(); diff --git a/tests/RvtIO.Tests/WideSolidQuantitiesTests.cs b/tests/RvtIO.Tests/WideSolidQuantitiesTests.cs new file mode 100644 index 00000000..58223a01 --- /dev/null +++ b/tests/RvtIO.Tests/WideSolidQuantitiesTests.cs @@ -0,0 +1,171 @@ +using RvtIO.Internal; +using RvtIO.Parsing; +using Xunit; + +namespace RvtIO.Tests; + +public sealed class WideSolidQuantitiesTests +{ + [Theory] + [InlineData(1, 2, 5d)] + [InlineData(3, 4, 0d)] + [InlineData(1, 3, null)] + public void ExcludesCoarseVolumeOnlyWhenTheCompleteSourceBodyIsReused(uint firstFace, uint secondFace, double? expected) + { + var coarse = Body(1, 2); + var detailed = Body(firstFace, secondFace); + detailed.Faces.AddRange([new GRepFace { SourceFace = 8 }, new GRepFace { SourceFace = 9 }]); + detailed.Solids.Add(new GRepSolid { IsClosed = true, FaceIndices = [2, 3] }); + + double? excluded = WideSolidQuantities.SharedLocalVolume(coarse, detailed, new WideSolidQuantities.Solid(5, 12, 4, 1)); + + Assert.Equal(expected, excluded); + } + + [Fact] + public void OpenRepresentationHasNoSolidQuantities() + { + var representation = Body(1, 2); + representation.Solids[0].IsClosed = false; + + Assert.Null(WideSolidQuantities.Local(representation)); + } + + [Fact] + public void BasicWallUsesTheLargerNetAreaOfTheTwoFinishPlanes() + { + var inner = Side(1, 0, 2) with { InnerVertices = [[[1, 0, 0], [1, 0, 1], [2, 0, 1], [2, 0, 0]]] }; + var source = new GRepData { Faces = [inner, Side(2, 1, 1), Side(3, 1, 1, 3), Side(4, 0.5, 20)] }; + Assert.Equal(6, WideSolidQuantities.WallSideArea(source, 1, 0, 0, 1, false)); + Assert.Null(WideSolidQuantities.WallSideArea(source, 1, 0, 0, 2, false)); + } + + [Fact] + public void CurtainWallUsesOneCompleteProfileAndIgnoresGridFaces() + { + var source = new GRepData + { + Faces = [Side(1, 0, 2), Side(2, 1, 2), Side(3, 0, 2), Side(4, 1, 2), Side(5, 1, 3)], + Solids = [new() { IsClosed = true, FaceIndices = [0, 1] }, new() { IsClosed = true, FaceIndices = [2, 3] }, + new() { IsClosed = false, FaceIndices = [4] }], + }; + Assert.Equal(6, WideSolidQuantities.WallSideArea(source, 1, 0, 0, null, true)); + source.Faces[3] = Side(4, 1, 3); + Assert.Null(WideSolidQuantities.WallSideArea(source, 1, 0, 0, null, true)); + } + + [Fact] + public void LightingFixtureUsesMeasuredBodiesWithAnOpenMeshPresent() + { + var source = new GRepData + { + Faces = [new() { Vertices = [[0, 0, 4], [1, 0, 4], [0, 1, 4]] }], + LightingBodyMeasures = (6, 22, 1), + IsOpenSurface = true, + }; + Assert.Null(WideSolidQuantities.Local(source)); + var measured = WideSolidQuantities.Local(source, WideSolidQuantities.Source.Directional)!.Value; + Assert.Equal(6, measured.Volume, 12); + Assert.Equal(22, measured.Surface, 12); + source.LightingBodyMeasures = null; + Assert.Null(WideSolidQuantities.Local(source, WideSolidQuantities.Source.Directional)); + } + + [Fact] + public void VisibleVolumeRequiresACompleteSourceBodyMeasurement() + { + var source = Body(1, 2); + Assert.Null(WideSolidQuantities.Local(source, WideSolidQuantities.Source.VisibleVolume)); + + source.SourceBodyMeasures = (4, 0, 1); + var measured = WideSolidQuantities.Local(source, WideSolidQuantities.Source.VisibleVolume)!.Value; + Assert.Equal(4, measured.Volume); + Assert.Equal(1, measured.BodyCount); + } + + [Fact] + public void ExtrusionRoofUsesTaggedLowerFacesAndIgnoresCutReveals() + { + var bottom = Side(1, 0, 2) with { GInfoTag = 19, XVector = [0, 0.6, -0.8], QuadratureArea = 7 }; + var reveal = bottom with { SourceFace = 2, GInfoTag = 20, QuadratureArea = 2 }; + var top = bottom with { SourceFace = 3, GInfoTag = 21, XVector = [0, -0.6, 0.8] }; + var source = new GRepData + { + Faces = [bottom, reveal, top], + Solids = [new() { IsClosed = true, FaceIndices = [0, 1, 2] }], + }; + Assert.Equal(7, WideSolidQuantities.RoofArea(source, new HashSet { 19, 21 })); + Assert.Null(WideSolidQuantities.RoofArea(source with { Faces = [bottom, reveal, top with { GInfoTag = null }] }, + new HashSet { 19, 21 })); + } + + [Fact] + public void PlanarMassUsesBothInclinedAndHorizontalFacesOfCompleteShells() + { + var slope = Side(1, 0, 1) with { XVector = [0, 0.6, 0.8], QuadratureArea = 7 }; + var baseFace = slope with { SourceFace = 2, XVector = [0, 0, -1], QuadratureArea = 4 }; + var wall = slope with { SourceFace = 3, XVector = [0, 1, 0], QuadratureArea = 25 }; + var source = new GRepData + { + Faces = [slope, baseFace, wall], + Solids = [new() { IsClosed = true, FaceIndices = [0, 1, 2] }], + }; + Assert.Equal(11, WideSolidQuantities.HorizontalArea(source, bottom: false, planarMass: true)); + source.Solids[0].IsClosed = false; + Assert.Null(WideSolidQuantities.HorizontalArea(source, bottom: false, planarMass: true)); + } + + [Fact] + public void HorizontalAreaCountsEachTrimmedSourceFaceOnce() + { + var top = new GRepFace { SourceFace = 1, PlaneSurface = true, XVector = [0, 0, 1], QuadratureArea = 7, + Vertices = [[0, 0, 2], [3, 0, 2], [3, 2, 2], [0, 2, 2]] }; + var bottom = top with { SourceFace = 2, XVector = [0, 0, -1], QuadratureArea = 3 }; + var source = new GRepData { Faces = [top, top, bottom, Side(3, 0, 2)] }; + Assert.Equal(7, WideSolidQuantities.HorizontalArea(source, bottom: false)); + Assert.Equal(3, WideSolidQuantities.HorizontalArea(source, bottom: true)); + } + + [Fact] + public void CurtainDoorAreaUsesTheOpeningSpannedByRectangularLeaves() + { + var source = new GRepData + { + Faces = [.. Leaf(0, 3, 2), .. Leaf(3.1, 6.1, 2)], + Solids = [new() { IsClosed = true, FaceIndices = [0, 1, 2, 3, 4, 5] }, + new() { IsClosed = true, FaceIndices = [6, 7, 8, 9, 10, 11] }], + }; + Assert.Equal(12.2, WideSolidQuantities.CurtainDoorArea(source)!.Value, 12); + source.Faces = [.. Leaf(0, 3, 2), .. Leaf(3.1, 6.1, 3)]; + Assert.Null(WideSolidQuantities.CurtainDoorArea(source)); + + static IEnumerable Leaf(double left, double right, double height) => + SolidQuantitiesTests.Box(left, 0, 0, right, 0.1, height).Faces.Select((face, i) => new GRepFace + { + PlaneSurface = true, Vertices = face.OuterVertices, Origin = face.OuterVertices![0], + XVector = i == 3 ? [0, 1, 0] : [0, 0, 0], + }); + } + + [Fact] + public void MassAreaSelectsMatchingCapsOrTheSurfaceOfAPitchedPlanarBody() + { + var solid = new WideSolidQuantities.Solid(12, 40, 10, 1); + Assert.Equal(10, WideSolidQuantities.MassArea(solid, 10, 10)); + Assert.Equal(20, WideSolidQuantities.MassArea(solid, 0, 10)); + Assert.Null(WideSolidQuantities.MassArea(solid, 9, 10)); + Assert.Null(WideSolidQuantities.MassArea(solid with { BodyCount = 2 }, 10, 10)); + } + + private static GRepFace Side(uint id, double offset, double height, double start = 0) => new() + { + PlaneSurface = true, SourceFace = id, Origin = [start, offset, 0], XVector = [0, 1, 0], + Vertices = [[start, offset, 0], [start + 3, offset, 0], [start + 3, offset, height], [start, offset, height]], + }; + + private static GRepData Body(uint first, uint second) => new() + { + Faces = [new GRepFace { SourceFace = first }, new GRepFace { SourceFace = second }], + Solids = [new GRepSolid { IsClosed = true, FaceIndices = [0, 1] }], + }; +} From cc699039b2642e62da656ce5cd9b79029fa8d811 Mon Sep 17 00:00:00 2001 From: mahach666 <79989386+mahach666@users.noreply.github.com> Date: Thu, 19 Nov 2026 11:57:52 +0300 Subject: [PATCH 020/259] Export straight Revit grid axes to IOScene --- CHANGELOG.md | 4 ++ docs/scene.md | 5 ++- src/RvtIO.Scene/RvtSceneReader.cs | 23 ++++++++++- src/RvtIO/Model/Element.cs | 2 +- src/RvtIO/Model/Geometry.cs | 3 +- tests/RvtIO.Tests/RvtSceneReaderTests.cs | 49 ++++++++++++++++++++++++ 6 files changed, 80 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 510fe679..693dd549 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,10 @@ API between minor releases. ## [Unreleased] +### Added + +- `RvtIO.Scene` exports decoded straight Revit grid axes and their labels in scene coordinates. + ### Fixed - The Revit 2027 reader computes Area and Volume for closed bodies with full ruled faces between diff --git a/docs/scene.md b/docs/scene.md index 90ec4cf5..58746925 100644 --- a/docs/scene.md +++ b/docs/scene.md @@ -1,7 +1,7 @@ # Scene adapter `RvtIO.Scene` turns a Revit project read by RvtIO into a scene of the `IOScene` package: a `SceneDocument` with one -model, the drawable elements, their triangle meshes in metres, their names and their parameters. A viewer or another +model, the drawable elements, their triangle meshes in metres, their names and parameters, and the decoded straight grid axes. A viewer or another consumer of the scene reads it without knowing Revit. The scene itself is specified in the contract of the `IOScene` repository (`docs/contract.md`), and the property keys it writes are registered there in `docs/keys.md`. @@ -53,6 +53,7 @@ rvtio project.rvt --ifc project.ifc --compact-json project.compact.json --scene |---|---| | `SceneModel.Key` | `RvtSceneOptions.ModelKey`, else the file name without its directory (`project.rvt`). This derivation does not change. | | `SceneModel` | `SourceFormat` `rvt`, `SourceLengthUnit` `ft`, `Producer` `RvtIO.Scene `. | +| `SceneGridSystem`, `SceneGridLine` | One grid system named `Grids` when the model has valid straight grid axes. Each axis uses its element name and the endpoints of its decoded location curve, converted from feet to metres in the document's internal coordinates. Elevation is the start point's Z. | | `SceneElement` | One per drawable element of `ElementMeshes.Extract` (the elements the IFC export would consider products, see the remarks of `ElementMeshes`). `Id` is the element id. | | `SourceId` | The Revit `UniqueId`. This derivation does not change; a golden test pins it on a fixture file. | | `IfcGuid` | The GlobalId Revit's IFC export gives the element: the value of its built-in IfcGUID parameter (`IFC_GUID`, matched by id as RvtIO's IFC export matches it) when it is a valid 22-character GlobalId; else the export id of the `UniqueId` (the episode GUID with its last 32 bits XORed with the element id the `UniqueId` ends with) in the IFC base-64 form. It depends on the element only, never on export order or options. This derivation does not change; the golden test pins it. | @@ -98,7 +99,7 @@ The text a value is written with under a key is frozen with the key: changing it - Shared, project and family parameters have no key yet. Their formats (for example `revit:shared:`) are registered in the IOScene key registry when the adapter first writes them; that is an addition. - No levels (`LevelId` and the `Levels` table stay empty): RvtIO has no public level of an element. -- No tree: every element is a top-level element of the model. No links, grids or views. +- Every element is a top-level element of its model. Linked models, views and curved grid axes are omitted. - Materials have a name and a colour; no roughness, metalness or textures. - Element names are those of `RvtDocument`; the validated names the IFC export applies to files read by their own class schema are not public API. diff --git a/src/RvtIO.Scene/RvtSceneReader.cs b/src/RvtIO.Scene/RvtSceneReader.cs index 259d397b..63bb0faa 100644 --- a/src/RvtIO.Scene/RvtSceneReader.cs +++ b/src/RvtIO.Scene/RvtSceneReader.cs @@ -10,7 +10,7 @@ namespace RvtIO.Scene; /// /// Turns a Revit document into a scene (): one model, one element per drawable element of the document -/// with its triangle meshes (), its names and its parameters. +/// with its triangle meshes (), its names and its parameters, plus decoded straight grid axes. /// /// /// Lengths are converted from feet to metres (x 0.3048) into the internal coordinates of the document, Z up. A symbol that @@ -128,6 +128,7 @@ private static RvtSceneResult Map(RvtDocument document, MeshSet meshes, string m { Id = ModelId, Key = modelKey, Name = modelKey, SourceFormat = "rvt", SourceLengthUnit = "ft", Producer = Producer, }); + AddGrids(scene, document); var report = new List(diagnostics ?? []); if (meshes.GeometryUndecoded) report.Add(new(SceneSeverity.Error, "geometry-undecoded", @@ -217,6 +218,26 @@ private static RvtSceneResult Map(RvtDocument document, MeshSet meshes, string m }; } + private static void AddGrids(SceneDocument scene, RvtDocument document) + { + var grid = new SceneGridSystem { ModelId = ModelId }; + foreach (var element in document.Collector().OfCategory(BuiltInCategory.OST_Grids) + .WhereElementIsNotElementType().OrderBy(element => element.Id)) + { + if (element.Location is not { CurveType: "Line", StartPoint: [var x0, var y0, var z0], EndPoint: [var x1, var y1, var z1] } + || !double.IsFinite(x0) || !double.IsFinite(y0) || !double.IsFinite(z0) + || !double.IsFinite(x1) || !double.IsFinite(y1) || !double.IsFinite(z1)) + continue; + + var start = new Vector3d(x0, y0, z0) * MetresPerFoot; + var end = new Vector3d(x1, y1, z1) * MetresPerFoot; + if (start == end) continue; + grid.Lines.Add(new SceneGridLine { Name = element.Name ?? string.Empty, Start = start, End = end, Elevation = start.Z }); + } + + if (grid.Lines.Count > 0) scene.Grids.Add(grid); + } + /// "RvtIO.Scene" and the version of this assembly without the source revision. private static string Producer { get; } = "RvtIO.Scene " + (typeof(RvtSceneReader).Assembly .GetCustomAttribute()?.InformationalVersion.Split('+')[0] diff --git a/src/RvtIO/Model/Element.cs b/src/RvtIO/Model/Element.cs index 2f1a7416..dbac10f9 100644 --- a/src/RvtIO/Model/Element.cs +++ b/src/RvtIO/Model/Element.cs @@ -1003,7 +1003,7 @@ internal bool RootClassIs(string className) => NativeRootClassName != null [JsonIgnore] internal List<(ushort ClassId, int ElementId, bool Cutout)>? CutOutSteps { get; set; } - /// Location curve for wall elements (line/arc with start/end/direction). + /// The element's location curve, such as a wall axis or a grid datum line. public LocationCurve? Location { get; set; } /// For a grid: its datum plane. diff --git a/src/RvtIO/Model/Geometry.cs b/src/RvtIO/Model/Geometry.cs index 4bf5036f..00b9395b 100644 --- a/src/RvtIO/Model/Geometry.cs +++ b/src/RvtIO/Model/Geometry.cs @@ -282,8 +282,7 @@ public class GeoOpening } /// - /// Location curve for wall elements (equivalent to Revit LocationCurve). - /// Coordinates are in LOCAL space - apply GRep Transform to get world coordinates. + /// An element location curve in the document's world coordinates, in feet. /// public class LocationCurve { diff --git a/tests/RvtIO.Tests/RvtSceneReaderTests.cs b/tests/RvtIO.Tests/RvtSceneReaderTests.cs index 7e595740..a0efd981 100644 --- a/tests/RvtIO.Tests/RvtSceneReaderTests.cs +++ b/tests/RvtIO.Tests/RvtSceneReaderTests.cs @@ -121,6 +121,7 @@ private static void AssertClose(Vector3d expected, Vector3d actual) public void ScenePassesValidation() { var result = Map(); + Assert.Empty(result.Document.Grids); Assert.Empty(result.Document.Validate()); Assert.Empty(SceneJson.Read(SceneJson.Write(result.Document)).Validate()); } @@ -137,6 +138,54 @@ public void ModelCarriesKeyFormatUnitAndProducer() Assert.DoesNotContain('+', model.Producer); } + [Fact] + public void SceneExportsDecodedStraightGridAxesWithoutMeshes() + { + int category = (int)BuiltInCategory.OST_Grids; + var b = Axis(22, "Б", [4, -2, 3], [4, 8, 3]); + var a = Axis(11, "A", [-5, 1, 2], [5, 1, 2]); + var arc = Axis(30, "Arc", [1, 0, 0], [0, 1, 0]); + arc.Location!.CurveType = "Arc"; + var wall = Axis(40, "Wall", [0, 0, 0], [5, 0, 0]); + wall.CategoryId = (int)BuiltInCategory.OST_Walls; + var info = new RevitFileInfo + { + Elements = + [ + b, a, arc, wall, + new Element { Id = 50, CategoryId = category }, + Axis(60, "Invalid", [0, 0, 0], [double.NaN, 1, 2]), + Axis(70, "Short point", [0, 0], [4, 0, 0]), + Axis(80, "Collapsed", [2, 2, 2], [2, 2, 2]), + ], + }; + var result = RvtSceneReader.Read(RvtDocument.FromInfo(info), new MeshSet(), new RvtSceneOptions { ModelKey = "model.rvt" }); + var scene = SceneJson.Read(SceneJson.Write(result.Document)); + + Assert.Empty(scene.Validate()); + Assert.Empty(scene.Elements); + var grid = Assert.Single(scene.Grids); + Assert.Equal(Assert.Single(scene.Models).Id, grid.ModelId); + Assert.Equal("Grids", grid.Name); + Assert.Collection(grid.Lines, + line => CheckAxis(line, "A", new(-5, 1, 2), new(5, 1, 2)), + line => CheckAxis(line, "Б", new(4, -2, 3), new(4, 8, 3))); + + Element Axis(int id, string name, double[] start, double[] end) => new() + { + Id = id, Name = name, CategoryId = category, + Location = new LocationCurve { StartPoint = start, EndPoint = end }, + }; + + static void CheckAxis(SceneGridLine line, string name, Vector3d start, Vector3d end) + { + Assert.Equal(name, line.Name); + AssertClose(start * Foot, line.Start); + AssertClose(end * Foot, line.End); + Assert.Equal(start.Z * Foot, line.Elevation, 9); + } + } + [Fact] public void SymbolIsOneGeometryPlacedOncePerPlacement() { From b7dbc09ecc2db2f274390f3d47d8a96601972076 Mon Sep 17 00:00:00 2001 From: mie <79989386+mahach666@users.noreply.github.com> Date: Thu, 19 Nov 2026 12:22:15 +0300 Subject: [PATCH 021/259] Export Revit building storeys to IOScene --- CHANGELOG.md | 2 + docs/public-api.md | 1 + docs/scene.md | 7 +- src/RvtIO.Scene/RvtSceneReader.cs | 14 +- src/RvtIO/BuildingStoreyCatalog.cs | 44 +++ src/RvtIO/Ifc/IfcExporter.Rebar.cs | 16 +- src/RvtIO/Ifc/IfcExporter.cs | 254 ++--------------- src/RvtIO/Internal/BuildingStoreyResolver.cs | 256 ++++++++++++++++++ src/RvtIO/RvtDocument.cs | 3 + .../IfcExporterCurrentContainmentTests.cs | 29 +- tests/RvtIO.Tests/RvtSceneReaderTests.cs | 59 ++++ 11 files changed, 434 insertions(+), 251 deletions(-) create mode 100644 src/RvtIO/BuildingStoreyCatalog.cs create mode 100644 src/RvtIO/Internal/BuildingStoreyResolver.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index 693dd549..930a3c9f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,8 @@ API between minor releases. ### Added - `RvtIO.Scene` exports decoded straight Revit grid axes and their labels in scene coordinates. +- `RvtDocument.GetBuildingStoreyCatalog()` exposes project building storeys and their assignments. + `RvtIO.Scene` writes those levels and the storey of each drawable element using the current IFC rules. ### Fixed diff --git a/docs/public-api.md b/docs/public-api.md index ee2512ac..79c39688 100644 --- a/docs/public-api.md +++ b/docs/public-api.md @@ -15,6 +15,7 @@ projects through `InternalsVisibleTo`. | `ExportReport`, `SkipLog`, `GeometryQualityClass`, `ElementGeometryQuality` | The machine-readable report of a run (`ToJson`), the per-element geometry quality classification and totals, and the elements an export left out; see [the export report](export-report.md). | | `RvtExitCodes`, `RvtInputException`, `RvtLimitException`, `RvtContainerCheck` | The exit codes 0 to 4 and 6 of the command line tool (code 5 is returned by `downgrade --check` and `save-as` when refused), the exceptions `RvtFileReader.Read` throws for a file it cannot read, and the check that raises them. | | `FilteredElementCollector` | Query over the elements of a document (`OfCategory`, `WhereElementIsNotElementType`, `Where`, ...). | +| `BuildingStoreyCatalog`, `BuildingStorey` | `RvtDocument.GetBuildingStoreyCatalog()` lists native project building storeys in order of elevation and Revit ID. Each storey carries its ID, name and resolved elevation in internal feet. `GetStoreyId(elementId)` uses the current IFC storey rules and returns null for an unknown element or one assigned to the building itself. Obtain a new catalog after editing levels. | ## Model diff --git a/docs/scene.md b/docs/scene.md index 58746925..2f247981 100644 --- a/docs/scene.md +++ b/docs/scene.md @@ -1,8 +1,8 @@ # Scene adapter `RvtIO.Scene` turns a Revit project read by RvtIO into a scene of the `IOScene` package: a `SceneDocument` with one -model, the drawable elements, their triangle meshes in metres, their names and parameters, and the decoded straight grid axes. A viewer or another -consumer of the scene reads it without knowing Revit. The scene itself is specified in the contract of the `IOScene` +model, the drawable elements, their triangle meshes in metres, their names and parameters, the building storeys, and +the decoded straight grid axes. A viewer or another consumer of the scene reads it without knowing Revit. The scene itself is specified in the contract of the `IOScene` repository (`docs/contract.md`), and the property keys it writes are registered there in `docs/keys.md`. The adapter is a preview. It is published as the package `RvtIO.Scene` on each RvtIO release tag, depends on exactly @@ -54,6 +54,8 @@ rvtio project.rvt --ifc project.ifc --compact-json project.compact.json --scene | `SceneModel.Key` | `RvtSceneOptions.ModelKey`, else the file name without its directory (`project.rvt`). This derivation does not change. | | `SceneModel` | `SourceFormat` `rvt`, `SourceLengthUnit` `ft`, `Producer` `RvtIO.Scene `. | | `SceneGridSystem`, `SceneGridLine` | One grid system named `Grids` when the model has valid straight grid axes. Each axis uses its element name and the endpoints of its decoded location curve, converted from feet to metres in the document's internal coordinates. Elevation is the start point's Z. | +| `SceneLevel` | Project levels marked as building storeys, ordered by elevation and Revit element ID. Names and resolved elevations, including elevations inferred by the reader, use the same level selection as IFC. Elevations are written in metres. | +| `SceneElement.LevelId` | The building-storey assignment from `RvtDocument.GetBuildingStoreyCatalog()`, using the current IFC rules for stored level references and geometry fallback. Assignments to the building itself leave this field empty. The scene assigns a storey to each drawable element independently of IFC product aggregation. | | `SceneElement` | One per drawable element of `ElementMeshes.Extract` (the elements the IFC export would consider products, see the remarks of `ElementMeshes`). `Id` is the element id. | | `SourceId` | The Revit `UniqueId`. This derivation does not change; a golden test pins it on a fixture file. | | `IfcGuid` | The GlobalId Revit's IFC export gives the element: the value of its built-in IfcGUID parameter (`IFC_GUID`, matched by id as RvtIO's IFC export matches it) when it is a valid 22-character GlobalId; else the export id of the `UniqueId` (the episode GUID with its last 32 bits XORed with the element id the `UniqueId` ends with) in the IFC base-64 form. It depends on the element only, never on export order or options. This derivation does not change; the golden test pins it. | @@ -98,7 +100,6 @@ The text a value is written with under a key is frozen with the key: changing it (numbers in SI units, booleans, element references) wait for public RvtIO API. - Shared, project and family parameters have no key yet. Their formats (for example `revit:shared:`) are registered in the IOScene key registry when the adapter first writes them; that is an addition. -- No levels (`LevelId` and the `Levels` table stay empty): RvtIO has no public level of an element. - Every element is a top-level element of its model. Linked models, views and curved grid axes are omitted. - Materials have a name and a colour; no roughness, metalness or textures. - Element names are those of `RvtDocument`; the validated names the IFC export applies to files read by their own class diff --git a/src/RvtIO.Scene/RvtSceneReader.cs b/src/RvtIO.Scene/RvtSceneReader.cs index 63bb0faa..ed8b8186 100644 --- a/src/RvtIO.Scene/RvtSceneReader.cs +++ b/src/RvtIO.Scene/RvtSceneReader.cs @@ -10,7 +10,7 @@ namespace RvtIO.Scene; /// /// Turns a Revit document into a scene (): one model, one element per drawable element of the document -/// with its triangle meshes (), its names and its parameters, plus decoded straight grid axes. +/// with its triangle meshes (), its names and its parameters, plus building storeys and decoded straight grid axes. /// /// /// Lengths are converted from feet to metres (x 0.3048) into the internal coordinates of the document, Z up. A symbol that @@ -32,7 +32,7 @@ namespace RvtIO.Scene; /// factor converts Revit's internal unit, and is left out otherwise (no spec, as for every built-in double, whose unit the /// reader only guesses from the parameter name, or a unit the reader converts with a factor that is not Revit's); an integer of a shared, project or family /// parameter (a plain integer or a Yes/No, shown as 1 or 0) is the number in decimal; a built-in integer, which may be an -/// enumeration, and an element id are left out. Levels and typed values are not written. +/// enumeration, and an element id are left out. Typed property values are not written. /// public static class RvtSceneReader { @@ -129,6 +129,15 @@ private static RvtSceneResult Map(RvtDocument document, MeshSet meshes, string m Id = ModelId, Key = modelKey, Name = modelKey, SourceFormat = "rvt", SourceLengthUnit = "ft", Producer = Producer, }); AddGrids(scene, document); + var storeys = document.GetBuildingStoreyCatalog(); + foreach (var storey in storeys.Storeys) + scene.Levels.Add(new SceneLevel + { + Id = storey.Id, + ModelId = ModelId, + Name = storey.Name, + Elevation = double.IsFinite(storey.ElevationFeet) ? storey.ElevationFeet * MetresPerFoot : null, + }); var report = new List(diagnostics ?? []); if (meshes.GeometryUndecoded) report.Add(new(SceneSeverity.Error, "geometry-undecoded", @@ -156,6 +165,7 @@ private static RvtSceneResult Map(RvtDocument document, MeshSet meshes, string m { Id = mesh.ElementId, ModelId = ModelId, + LevelId = storeys.GetStoreyId(mesh.ElementId), SourceId = element?.UniqueId, IfcGuid = element != null ? IfcGuidOf(element) : null, Kind = SceneNodeKind.Element, diff --git a/src/RvtIO/BuildingStoreyCatalog.cs b/src/RvtIO/BuildingStoreyCatalog.cs new file mode 100644 index 00000000..92f416f9 --- /dev/null +++ b/src/RvtIO/BuildingStoreyCatalog.cs @@ -0,0 +1,44 @@ +using RvtIO.Internal; +using RvtIO.Model; + +namespace RvtIO; + +/// A project's building-storey levels and the assignments used by the scene and current IFC exporters. +/// Build a new catalog after editing a document's levels. +public sealed class BuildingStoreyCatalog +{ + private readonly IReadOnlyDictionary _elements; + private readonly BuildingStoreyResolver _resolver; + + /// Project building storeys, ordered by elevation and then by Revit element ID. + public IReadOnlyList Storeys { get; } + + internal BuildingStoreyCatalog(IReadOnlyDictionary elements) + { + _elements = elements; + var levels = BuildingStoreyResolver.GetBuildingStoreyLevels(elements.Values); + Storeys = Array.AsReadOnly(levels.Select(level => new BuildingStorey( + level.Id, level.Name!, BuildingStoreyResolver.GetElevation(level))).ToArray()); + + // The resolver reserves zero for the building, independent of the authored level IDs. + var ids = new Dictionary(levels.Count); + for (int index = 0; index < levels.Count; index++) + ids.Add(levels[index].Id, index + 1); + _resolver = new BuildingStoreyResolver(ids, elements, ids.Count == 0 ? 0 : 1, buildingId: 0, currentProfile: true); + } + + /// The Revit ID of the building storey assigned to this element, or null if the element is unknown + /// or its assignment is to the building itself. A stored level takes precedence over placement by geometry. + public int? GetStoreyId(int elementId) + { + if (Storeys.Count == 0 || !_elements.TryGetValue(elementId, out var element)) return null; + int slot = _resolver.Resolve(element, out _); + return slot > 0 ? Storeys[slot - 1].Id : null; + } +} + +/// A building storey selected from the native project levels of a Revit document. +/// The Revit element ID of the level. +/// The name of the level. +/// The reader's resolved elevation in the document's internal coordinates, in feet. +public readonly record struct BuildingStorey(int Id, string Name, double ElevationFeet); diff --git a/src/RvtIO/Ifc/IfcExporter.Rebar.cs b/src/RvtIO/Ifc/IfcExporter.Rebar.cs index ef4b8700..66e1691c 100644 --- a/src/RvtIO/Ifc/IfcExporter.Rebar.cs +++ b/src/RvtIO/Ifc/IfcExporter.Rebar.cs @@ -1,4 +1,5 @@ using System.Globalization; +using RvtIO.Internal; using RvtIO.Model; using RvtIO.Parsing; @@ -31,11 +32,11 @@ public partial class IfcExporter /// Writes the product of a reinforcement element; false (nothing written) when its type has no usable name. private bool WriteRebarProduct(StepWriter w, Element elem, IReadOnlyDictionary elemById, int ownerHistId, int axisId, int parentPlacementId, int bodySubCtxId, Dictionary<(string PropertyName, string ValueExpr), int> propertySingleValueIds, - bool shapeInName, Dictionary storeyIds, int defaultStoreyId, Dictionary> storeyContents) + bool shapeInName, Dictionary storeyIds, BuildingStoreyResolver storeyResolver, Dictionary> storeyContents) { var data = elem.RebarBars!; if (data.Items != null) - return WriteRebarContainer(w, elem, data, elemById, ownerHistId, axisId, parentPlacementId, bodySubCtxId, propertySingleValueIds, storeyIds, defaultStoreyId, storeyContents); + return WriteRebarContainer(w, elem, data, elemById, ownerHistId, axisId, parentPlacementId, bodySubCtxId, propertySingleValueIds, storeyIds, storeyResolver, storeyContents); string? barTypeName = data.BarTypeName; if (data.Bars.Count == 0 || data.Bars.Any(bar => bar.Count == 0) || string.IsNullOrEmpty(barTypeName)) return false; // For shape driven bars of Revit 2026 files the shape follows the type @@ -48,7 +49,7 @@ private bool WriteRebarProduct(StepWriter w, Element elem, IReadOnlyDictionary 0 ? data.Bars.Count + 3 : 0, globalIdOf: system); ExportQuantityTakeOffPropertySet(w, elem, entityId, ownerHistId, barTypeName, propertySingleValueIds); - PlaceRebarInStorey(elem, data, elemById, entityId, storeyIds, defaultStoreyId, storeyContents); + PlaceRebarInStorey(elem, data, elemById, entityId, storeyIds, storeyResolver, storeyContents); // No group of their system is written for the bars of an assembly, nor for the one bar of a system, which carries its GlobalId if (data.SystemId > 0 && !data.InAssembly && system == null) { @@ -69,7 +70,7 @@ private bool WriteRebarProduct(StepWriter w, Element elem, IReadOnlyDictionary private bool WriteRebarContainer(StepWriter w, Element elem, RebarBars data, IReadOnlyDictionary elemById, int ownerHistId, int axisId, int parentPlacementId, int bodySubCtxId, Dictionary<(string PropertyName, string ValueExpr), int> propertySingleValueIds, - Dictionary storeyIds, int defaultStoreyId, Dictionary> storeyContents) + Dictionary storeyIds, BuildingStoreyResolver storeyResolver, Dictionary> storeyContents) { string? typeName = data.BarTypeName; if (string.IsNullOrEmpty(typeName)) return false; @@ -81,7 +82,7 @@ private bool WriteRebarContainer(StepWriter w, Element elem, RebarBars data, IRe int entityId = WriteRebarBar(w, elem, item, ownerHistId, axisId, parentPlacementId, bodySubCtxId, $"{label}:{elem.Id.ToString(CultureInfo.InvariantCulture)}: {item.ItemIndex.ToString(CultureInfo.InvariantCulture)}", label, item.ItemIndex + 4, IfcGuid.FromName($"rebar-container-item:{elem.Id}:{item.ItemIndex}")); - PlaceRebarInStorey(elem, item, elemById, entityId, storeyIds, defaultStoreyId, storeyContents); + PlaceRebarInStorey(elem, item, elemById, entityId, storeyIds, storeyResolver, storeyContents); members.Add(entityId); } if (members.Count == 0) return false; @@ -132,7 +133,7 @@ private int WriteRebarBar(StepWriter w, Element elem, RebarBars data, int ownerH /// (parts assemblies) are not written, so nothing aggregates them. Aggregate them instead when those assemblies are written. /// The assembly goes to the highest storey at or below the bottom of the Part that hosts the bar, so its bars follow that rule. private void PlaceRebarInStorey(Element elem, RebarBars data, IReadOnlyDictionary elemById, int entityId, - Dictionary storeyIds, int defaultStoreyId, Dictionary> storeyContents) + Dictionary storeyIds, BuildingStoreyResolver storeyResolver, Dictionary> storeyContents) { int storeyId = 0; if (data.InAssembly && storeyIds.Count > 0 && HostPartBottom(elem, elemById) is double partBottomFt) @@ -140,8 +141,7 @@ private void PlaceRebarInStorey(Element elem, RebarBars data, IReadOnlyDictionar if (storeyId == 0) { double bottomFt = data.Bars.SelectMany(bar => bar).Min(piece => piece.MinZ()) - data.ModelDiameter / 2; - int byBottom = storeyIds.Count > 0 ? ResolveStoreyByBottomCurrent(bottomFt, storeyIds, elemById) : 0; - storeyId = byBottom != 0 ? byBottom : defaultStoreyId; + storeyId = storeyResolver.ResolveByBottom(bottomFt); } if (!storeyContents.TryGetValue(storeyId, out var contents)) storeyContents[storeyId] = contents = []; contents.Add(entityId); diff --git a/src/RvtIO/Ifc/IfcExporter.cs b/src/RvtIO/Ifc/IfcExporter.cs index bfabddd7..6d3fcbe4 100644 --- a/src/RvtIO/Ifc/IfcExporter.cs +++ b/src/RvtIO/Ifc/IfcExporter.cs @@ -1,6 +1,7 @@ using System.Globalization; using System.Text.RegularExpressions; using RvtIO.Geometry; +using RvtIO.Internal; using RvtIO.Lookup; using RvtIO.Model; using RvtIO.Parsing; @@ -741,6 +742,14 @@ string SiteCoordinate(double feet) => elementIdOccurrenceCounts[e.Id] = occurrenceCount + 1; elementOrderById.TryAdd(e.Id, elementIndex); } + var storeyResolver = new BuildingStoreyResolver(storeyIds, elemById, defaultStoreyId, buildingId, CurrentProfile); + int ResolveStorey(Element element, double[]? outline = null) + { + int id = storeyResolver.Resolve(element, out bool hasOffStoreyLevel, outline); + if (hasOffStoreyLevel) _offStoreyLevelElementIds.Add(element.Id); + return id; + } + _elementsByIdCurrent = elemById; _axisExtrusionBodyCurrent.Clear(); // The elements that the writers outside the product loop may write: the product loop leaves out the ones whose export flags say No @@ -1708,7 +1717,7 @@ bool HasCompetingExactHostedWriterAuthority( if (CurrentProfile && elem.RebarBars != null) { if (!WriteRebarProduct(w, elem, elemById, ownerHistId, axisId, bldgLocalPlacementId, bodySubCtxId, propertySingleValueIds, - int.TryParse(info.Metadata?.RevitVersion, out int revitRelease) && revitRelease >= 2026, storeyIds, defaultStoreyId, storeyContents)) + int.TryParse(info.Metadata?.RevitVersion, out int revitRelease) && revitRelease >= 2026, storeyIds, storeyResolver, storeyContents)) Skip(elem, "rebar-product-not-written"); else { @@ -1895,7 +1904,7 @@ bool HasCompetingExactHostedWriterAuthority( isEmittedAggregateParent: _emittedAggregateParentElementIds.Contains(elem.Id))) { Skip(elem, "product-without-body"); continue; } - int elemStoreyId = ResolveStorey(elem, storeyIds, defaultStoreyId, elemById, buildingId); + int elemStoreyId = ResolveStorey(elem); if (Environment.GetEnvironmentVariable("RVTIO_STOREY_DIAG") is { Length: > 0 } storeyDiag) File.AppendAllText(storeyDiag, string.Join(';', elem.Id, ifcType, elem.CategoryId, elem.SuperInstanceId, elem.NativeMasterSymbolId, (elem.DecodedBox ?? elem.Geometry?.BoundingBox) is { Length: >= 6 } diagBox ? diagBox[2].ToString("R", CultureInfo.InvariantCulture) : "-", @@ -5023,7 +5032,7 @@ fallbackSourceOwnerTagId is null // the main loop left the beam system out; its assembly is a product of the file foreach (int systemId in WriteJoistAssemblies(w, exportableElements, ownerHistId, bldgLocalPlacementId, axisId, exportedIfcElements, exportedStoreyIds, storeyContents, propertySingleValueIds, - system => ResolveStorey(system, storeyIds, defaultStoreyId, elemById, buildingId, system.BoundingBox))) + system => ResolveStorey(system, system.BoundingBox))) { // counted with or without a skip log; the log entry is only there to be taken out string systemClass = elemById.TryGetValue(systemId, out var sysElem) ? RvtIO.SkipLog.ClassOf(sysElem) : "OST_StructuralFramingSystem"; @@ -68118,7 +68127,7 @@ private Dictionary WriteSpaces( // it is not written where no storey is that low. else if (CurrentProfile && levelElemId is int offStoreyLevelId && _elementsByIdCurrent is { } elementsById && elementsById.TryGetValue(offStoreyLevelId, out var offStoreyLevel) && offStoreyLevel.CategoryId == -2000240 - && HighestStoreyAtOrBelow(offStoreyLevel, storeyIds, elementsById, 0) is > 0 and int storeyBelowId) + && BuildingStoreyResolver.HighestStoreyAtOrBelow(offStoreyLevel, storeyIds, elementsById, 0) is > 0 and int storeyBelowId) storeyId = storeyBelowId; else continue; @@ -69223,225 +69232,12 @@ List Groups(IEnumerable values) => values private static bool IsNonPhysicalCategory(string? category) => ProductRules.IsNonPhysicalCategory(category); - /// - /// The storey of an element, replaying the storey rule: the base-level - /// parameter of its kind (a nested family instance reads its top-level instance), then any - /// stored level reference. is the box of an element that has no body of its own. - /// - private int ResolveStorey(Element elem, Dictionary storeyIds, int defaultStoreyId, - IReadOnlyDictionary elemById, int buildingId, double[]? outline = null) - { - // The current profile reads STAIRS_BASE_LEVEL_PARAM, which is StairsElement.m_baseLevelId. - if (CurrentProfile && elem.CategoryId == -2000120 && elem.SerializedStairBaseLevelId is int stairBaseLevelId - && storeyIds.TryGetValue(stairBaseLevelId, out int stairBaseStoreyId)) - return stairBaseStoreyId; - Element parameterSource = elem.SuperInstanceId is > 0 && elemById.TryGetValue(elem.SuperInstanceId.Value, out var top) - ? top : elem; - int[] baseLevelParameters = elem.CategoryId switch - { - -2000011 => [-1001107], // WALL_BASE_CONSTRAINT - -2000035 => [-1001651], // ROOF_CONSTRAINT_LEVEL_PARAM - -2000120 => [-1007200], // STAIRS_BASE_LEVEL_PARAM - _ when elem.NativeMasterSymbolId is > 0 => [-1001350, -1001365, -1001383], - _ => [], - }; - // An element whose level is a Level that is not a project storey stands in the highest storey at or below - // that level, in the building where no storey is that low. - Element? offStoreyLevel = null; - foreach (int parameterId in baseLevelParameters) - if (parameterSource.Parameters.FirstOrDefault(parameter => parameter.Id == parameterId)?.Value is int levelId) - { - if (storeyIds.TryGetValue(levelId, out int storeyId)) return storeyId; - if (CurrentProfile && offStoreyLevel == null - && elemById.TryGetValue(levelId, out var baseLevel) && baseLevel.CategoryId == -2000240) - offStoreyLevel = baseLevel; - } - // A base level that is not a storey outranks the element's own level parameters below, as one that is a - // storey does. Among the base-level parameters one on a storey still outranks an earlier one that is not. - if (offStoreyLevel != null) - { - _offStoreyLevelElementIds.Add(elem.Id); - return HighestStoreyAtOrBelow(offStoreyLevel, storeyIds, elemById, buildingId); - } - - // A column whose base level is a Level that is not a project storey stands in the highest storey at or - // below that level, and in the building where no storey is that low. - if (CurrentProfile && elem.CategoryId is -2001330 or -2000100 - && parameterSource.Parameters.FirstOrDefault(parameter => parameter.Id == -1001350)?.Value is int columnBaseLevelId - && elemById.TryGetValue(columnBaseLevelId, out var columnBaseLevel) && columnBaseLevel.CategoryId == -2000240) - return storeyIds.TryGetValue(columnBaseLevelId, out int baseStoreyId) - ? baseStoreyId - : HighestStoreyAtOrBelow(columnBaseLevel, storeyIds, elemById, buildingId); - - if (CurrentProfile) - { - // LEVEL_PARAM, SCHEDULE_LEVEL_PARAM, RBS_START_LEVEL_PARAM, FAMILY_BASE_LEVEL_PARAM, - // INSTANCE_SCHEDULE_ONLY_LEVEL_PARAM, INSTANCE_REFERENCE_LEVEL_PARAM, - // SCHEDULE_BASE_LEVEL_PARAM. - foreach (int parameterId in elem.CategoryId is -2000035 or -2000120 - ? new[] { -1001952, -1002062, -1114000, -1001350, -1001365, -1001383, -1002063, -1001352 } - : new[] { -1001952, -1002062, -1114000, -1001350, -1001365, -1001383, -1002063 }) - if (elem.Parameters.FirstOrDefault(parameter => parameter.Id == parameterId)?.Value is int assocLevelId) - { - if (storeyIds.TryGetValue(assocLevelId, out int assocStoreyId)) return assocStoreyId; - if (offStoreyLevel == null - && elemById.TryGetValue(assocLevelId, out var assocLevel) && assocLevel.CategoryId == -2000240) - offStoreyLevel = assocLevel; - } - if (offStoreyLevel != null) - { - _offStoreyLevelElementIds.Add(elem.Id); - return HighestStoreyAtOrBelow(offStoreyLevel, storeyIds, elemById, buildingId); - } - } - // Try to find LEVEL_PARAM or BASE_LEVEL_PARAM in element's parameters - else foreach (var p in elem.Parameters) - { - if (p.StorageType == StorageType.ElementId && p.Value is int refId && refId > 0) - { - string? pName = p.Definition?.Name; - if (pName != null && (pName.Contains("LEVEL") || pName.Contains("CONSTRAINT") || pName.Contains("Level"))) - { - if (storeyIds.TryGetValue(refId, out int sid)) - return sid; - } - } - } + internal static bool IsProjectLevel(Element level) => BuildingStoreyResolver.IsProjectLevel(level); - // No stored level: the highest storey at or below the bottom of the element. - if (CurrentProfile && storeyIds.Count > 0) - { - int byBottom = ResolveStoreyByBottomCurrent( - (outline ?? elem.DecodedBox ?? elem.Geometry?.BoundingBox) is { Length: >= 6 } box ? box[2] : null, - storeyIds, elemById); - return byBottom != 0 ? byBottom : defaultStoreyId; - } - if ((elem.DecodedBox ?? elem.Geometry?.BoundingBox) is { Length: >= 6 } bounds && storeyIds.Count > 0) - { - const double Tolerance = 1e-6; - int best = defaultStoreyId; - double bestElevation = double.NegativeInfinity; - foreach (var (levelId, storeyId) in storeyIds) - if (elemById.TryGetValue(levelId, out var level)) - { - double elevation = GetElevation(level); - if (elevation <= bounds[2] + Tolerance && elevation > bestElevation) - { - best = storeyId; - bestElevation = elevation; - } - } - return best; - } + internal static List GetBuildingStoreyLevels(IEnumerable elements) => + BuildingStoreyResolver.GetBuildingStoreyLevels(elements); - return defaultStoreyId; - } - - /// The storey of the highest project level at or below this level (the later level on a tie), the building where no storey is that low. - private static int HighestStoreyAtOrBelow(Element level, Dictionary storeyIds, - IReadOnlyDictionary elemById, int buildingId) - { - const double Tolerance = 1e-6; - double baseElevation = GetElevation(level); - int chosen = buildingId; - double chosenElevation = double.NegativeInfinity; - int chosenLevelId = 0; - foreach (var (levelId, storeyId) in storeyIds) - if (elemById.TryGetValue(levelId, out var storeyLevel)) - { - double elevation = GetElevation(storeyLevel); - if (elevation <= baseElevation + Tolerance - && (elevation > chosenElevation || elevation == chosenElevation && levelId > chosenLevelId)) - { - chosen = storeyId; - chosenElevation = elevation; - chosenLevelId = levelId; - } - } - return chosen; - } - - /// 10 cm in feet: the storey rule, how far below a level its storey starts. - private const double StoreyExtensionFeet = 10.0 / (12.0 * 2.54); - - private Dictionary? _storeyRangeSource; - private (int StoreyId, double Start, double Height)[] _storeyRanges = []; - private int _storeyRangeBottom; - - /// The placement rule for an element without a stored level. - private int ResolveStoreyByBottomCurrent(double? bottom, Dictionary storeyIds, - IReadOnlyDictionary elemById) - { - if (!ReferenceEquals(_storeyRangeSource, storeyIds)) - { - var levels = storeyIds - .Where(pair => elemById.ContainsKey(pair.Key)) - .Select(pair => (LevelId: pair.Key, StoreyId: pair.Value, Elevation: GetElevation(elemById[pair.Key]))) - .OrderBy(level => level.Elevation).ThenBy(level => level.LevelId).ToList(); - var ranges = new List<(int LevelId, int StoreyId, double Start, double Height)>(); - for (int i = 0; i < levels.Count; i++) - { - double height = 0; - for (int j = i + 1; j < levels.Count; j++) - if (Math.Abs(levels[j].Elevation - levels[i].Elevation) > 1e-7) - { - height = levels[j].Elevation - levels[i].Elevation; - break; - } - ranges.Add((levels[i].LevelId, levels[i].StoreyId, levels[i].Elevation - StoreyExtensionFeet, height)); - } - ranges.Sort((a, b) => a.LevelId.CompareTo(b.LevelId)); - _storeyRanges = ranges.Select(range => (range.StoreyId, range.Start, range.Height)).ToArray(); - _storeyRangeBottom = 0; - double lowest = double.MaxValue; - foreach (var range in _storeyRanges) - if (range.Start < lowest + 1e-8) - { - _storeyRangeBottom = range.StoreyId; - lowest = range.Start; - } - _storeyRangeSource = storeyIds; - } - int chosen = 0; - if (bottom is double z) - foreach (var (storeyId, start, height) in _storeyRanges) - // Both bounds move by the same tolerance, so no bottom falls between two ranges. - if (z > start + 1e-9 && (Math.Abs(height) < 1e-10 || z <= start + height + 1e-9)) - chosen = storeyId; - return chosen != 0 ? chosen : _storeyRangeBottom; - } - - // A project Level (building story or not) has no owning family, unplaced instance or DB view; - // loaded-family reference levels carry an exact owner in one of these serialized fields. - internal static bool IsProjectLevel(Element level) => level.IsNativeLevel - && level.SerializedFamilyId == -1 - && level.SerializedUnplacedOwnerId == -1 - && level.SerializedOwnerDbViewId == -1; - - internal static List GetBuildingStoreyLevels(IEnumerable elements) - { - var candidates = elements - .Where(element => element.IsNativeLevel - // A project Level has no owning family, unplaced instance, or DB view. - && element.SerializedFamilyId == -1 - && element.SerializedUnplacedOwnerId == -1 - && element.SerializedOwnerDbViewId == -1 - && !string.IsNullOrWhiteSpace(element.Name) - && element.Parameters.Any(parameter => parameter.Id == -1007102 - && parameter.StorageType == StorageType.Double - && parameter.Value is double elevation - && double.IsFinite(elevation)) - && element.Parameters.Any(parameter => parameter.Id == -1007111 - && parameter.StorageType == StorageType.Integer - && parameter.Value is int isBuildingStory - && isBuildingStory == 1)) - .ToList(); - - return candidates - .OrderBy(GetElevation) - .ThenBy(element => element.Id) - .ToList(); - } + private static double GetElevation(Element level) => BuildingStoreyResolver.GetElevation(level); /// The height of the storey placement of a level, in metres. private static double StoreyElevationMetres(Element level) @@ -69450,22 +69246,6 @@ private static double StoreyElevationMetres(Element level) return Math.Abs(metres) < 1e-6 ? 0.0 : metres; // avoid -0. } - private static double GetElevation(Element level) - { - // Look for LEVEL_ELEV parameter - foreach (var p in level.Parameters) - { - string? pName = p.Definition?.Name; - if (pName != null && pName.Contains("LEVEL_ELEV") && p.StorageType == StorageType.Double && p.Value is double d) - return d; - } - // Fallback: bbox Z - if (level.DecodedBox != null && level.DecodedBox.Length >= 3) - return level.DecodedBox[2]; - return 0; - } - - /// Get door/window height in mm from params, frame extent, or bbox. internal static double GetDoorWindowHeight(Element elem, Element? type) { diff --git a/src/RvtIO/Internal/BuildingStoreyResolver.cs b/src/RvtIO/Internal/BuildingStoreyResolver.cs new file mode 100644 index 00000000..9c32f50e --- /dev/null +++ b/src/RvtIO/Internal/BuildingStoreyResolver.cs @@ -0,0 +1,256 @@ +using RvtIO.Model; + +namespace RvtIO.Internal; + +/// Building-storey selection and the assignment rules shared by the scene and IFC exporters. +internal sealed class BuildingStoreyResolver +{ + private readonly Dictionary _storeyIds; + private readonly IReadOnlyDictionary _elemById; + private readonly int _defaultStoreyId; + private readonly int _buildingId; + private readonly bool _currentProfile; + private readonly Lazy<((int StoreyId, double Start, double Height)[] Ranges, int Lowest)> _bottomRanges; + + internal BuildingStoreyResolver(Dictionary storeyIds, IReadOnlyDictionary elemById, + int defaultStoreyId, int buildingId, bool currentProfile) + { + _storeyIds = storeyIds; + _elemById = elemById; + _defaultStoreyId = defaultStoreyId; + _buildingId = buildingId; + _currentProfile = currentProfile; + _bottomRanges = new(() => BuildBottomRanges(_storeyIds, _elemById)); + } + + /// + /// The storey of an element, replaying the storey rule: the base-level + /// parameter of its kind (a nested family instance reads its top-level instance), then any + /// stored level reference. is the box of an element that has no body of its own. + /// + internal int Resolve(Element elem, out bool hasOffStoreyLevel, double[]? outline = null) + { + hasOffStoreyLevel = false; + // The current profile reads STAIRS_BASE_LEVEL_PARAM, which is StairsElement.m_baseLevelId. + if (_currentProfile && elem.CategoryId == -2000120 && elem.SerializedStairBaseLevelId is int stairBaseLevelId + && _storeyIds.TryGetValue(stairBaseLevelId, out int stairBaseStoreyId)) + return stairBaseStoreyId; + Element parameterSource = elem.SuperInstanceId is > 0 && _elemById.TryGetValue(elem.SuperInstanceId.Value, out var top) + ? top : elem; + int[] baseLevelParameters = elem.CategoryId switch + { + -2000011 => [-1001107], // WALL_BASE_CONSTRAINT + -2000035 => [-1001651], // ROOF_CONSTRAINT_LEVEL_PARAM + -2000120 => [-1007200], // STAIRS_BASE_LEVEL_PARAM + _ when elem.NativeMasterSymbolId is > 0 => [-1001350, -1001365, -1001383], + _ => [], + }; + // An element whose level is a Level that is not a project storey stands in the highest storey at or below + // that level, in the building where no storey is that low. + Element? offStoreyLevel = null; + foreach (int parameterId in baseLevelParameters) + if (parameterSource.Parameters.FirstOrDefault(parameter => parameter.Id == parameterId)?.Value is int levelId) + { + if (_storeyIds.TryGetValue(levelId, out int storeyId)) return storeyId; + if (_currentProfile && offStoreyLevel == null + && _elemById.TryGetValue(levelId, out var baseLevel) && baseLevel.CategoryId == -2000240) + offStoreyLevel = baseLevel; + } + // A base level that is not a storey outranks the element's own level parameters below, as one that is a + // storey does. Among the base-level parameters one on a storey still outranks an earlier one that is not. + if (offStoreyLevel != null) + { + hasOffStoreyLevel = true; + return HighestStoreyAtOrBelow(offStoreyLevel, _storeyIds, _elemById, _buildingId); + } + + // A column whose base level is a Level that is not a project storey stands in the highest storey at or + // below that level, and in the building where no storey is that low. + if (_currentProfile && elem.CategoryId is -2001330 or -2000100 + && parameterSource.Parameters.FirstOrDefault(parameter => parameter.Id == -1001350)?.Value is int columnBaseLevelId + && _elemById.TryGetValue(columnBaseLevelId, out var columnBaseLevel) && columnBaseLevel.CategoryId == -2000240) + return _storeyIds.TryGetValue(columnBaseLevelId, out int baseStoreyId) + ? baseStoreyId + : HighestStoreyAtOrBelow(columnBaseLevel, _storeyIds, _elemById, _buildingId); + + if (_currentProfile) + { + // LEVEL_PARAM, SCHEDULE_LEVEL_PARAM, RBS_START_LEVEL_PARAM, FAMILY_BASE_LEVEL_PARAM, + // INSTANCE_SCHEDULE_ONLY_LEVEL_PARAM, INSTANCE_REFERENCE_LEVEL_PARAM, + // SCHEDULE_BASE_LEVEL_PARAM. + foreach (int parameterId in elem.CategoryId is -2000035 or -2000120 + ? new[] { -1001952, -1002062, -1114000, -1001350, -1001365, -1001383, -1002063, -1001352 } + : new[] { -1001952, -1002062, -1114000, -1001350, -1001365, -1001383, -1002063 }) + if (elem.Parameters.FirstOrDefault(parameter => parameter.Id == parameterId)?.Value is int assocLevelId) + { + if (_storeyIds.TryGetValue(assocLevelId, out int assocStoreyId)) return assocStoreyId; + if (offStoreyLevel == null + && _elemById.TryGetValue(assocLevelId, out var assocLevel) && assocLevel.CategoryId == -2000240) + offStoreyLevel = assocLevel; + } + if (offStoreyLevel != null) + { + hasOffStoreyLevel = true; + return HighestStoreyAtOrBelow(offStoreyLevel, _storeyIds, _elemById, _buildingId); + } + } + // Try to find LEVEL_PARAM or BASE_LEVEL_PARAM in element's parameters + else foreach (var p in elem.Parameters) + { + if (p.StorageType == StorageType.ElementId && p.Value is int refId && refId > 0) + { + string? pName = p.Definition?.Name; + if (pName != null && (pName.Contains("LEVEL") || pName.Contains("CONSTRAINT") || pName.Contains("Level"))) + { + if (_storeyIds.TryGetValue(refId, out int sid)) + return sid; + } + } + } + + // No stored level: the highest storey at or below the bottom of the element. + if (_currentProfile) + return ResolveByBottom( + (outline ?? elem.DecodedBox ?? elem.Geometry?.BoundingBox) is { Length: >= 6 } box ? box[2] : null); + if ((elem.DecodedBox ?? elem.Geometry?.BoundingBox) is { Length: >= 6 } bounds && _storeyIds.Count > 0) + { + const double Tolerance = 1e-6; + int best = _defaultStoreyId; + double bestElevation = double.NegativeInfinity; + foreach (var (levelId, storeyId) in _storeyIds) + if (_elemById.TryGetValue(levelId, out var level)) + { + double elevation = GetElevation(level); + if (elevation <= bounds[2] + Tolerance && elevation > bestElevation) + { + best = storeyId; + bestElevation = elevation; + } + } + return best; + } + + return _defaultStoreyId; + } + + /// The storey of the highest project level at or below this level (the later level on a tie), the building where no storey is that low. + internal static int HighestStoreyAtOrBelow(Element level, Dictionary storeyIds, + IReadOnlyDictionary elemById, int buildingId) + { + const double Tolerance = 1e-6; + double baseElevation = GetElevation(level); + int chosen = buildingId; + double chosenElevation = double.NegativeInfinity; + int chosenLevelId = 0; + foreach (var (levelId, storeyId) in storeyIds) + if (elemById.TryGetValue(levelId, out var storeyLevel)) + { + double elevation = GetElevation(storeyLevel); + if (elevation <= baseElevation + Tolerance + && (elevation > chosenElevation || elevation == chosenElevation && levelId > chosenLevelId)) + { + chosen = storeyId; + chosenElevation = elevation; + chosenLevelId = levelId; + } + } + return chosen; + } + + /// 10 cm in feet: the storey rule, how far below a level its storey starts. + private const double StoreyExtensionFeet = 10.0 / (12.0 * 2.54); + + private static ((int StoreyId, double Start, double Height)[] Ranges, int Lowest) + BuildBottomRanges(IReadOnlyDictionary storeyIds, IReadOnlyDictionary elemById) + { + var levels = storeyIds + .Where(pair => elemById.ContainsKey(pair.Key)) + .Select(pair => (LevelId: pair.Key, StoreyId: pair.Value, Elevation: GetElevation(elemById[pair.Key]))) + .OrderBy(level => level.Elevation).ThenBy(level => level.LevelId).ToList(); + var ranges = new List<(int LevelId, int StoreyId, double Start, double Height)>(); + for (int i = 0; i < levels.Count; i++) + { + double height = 0; + for (int j = i + 1; j < levels.Count; j++) + if (Math.Abs(levels[j].Elevation - levels[i].Elevation) > 1e-7) + { + height = levels[j].Elevation - levels[i].Elevation; + break; + } + ranges.Add((levels[i].LevelId, levels[i].StoreyId, levels[i].Elevation - StoreyExtensionFeet, height)); + } + ranges.Sort((a, b) => a.LevelId.CompareTo(b.LevelId)); + var storeyRanges = ranges.Select(range => (range.StoreyId, range.Start, range.Height)).ToArray(); + int storeyRangeBottom = 0; + double lowest = double.MaxValue; + foreach (var range in storeyRanges) + if (range.Start < lowest + 1e-8) + { + storeyRangeBottom = range.StoreyId; + lowest = range.Start; + } + return (storeyRanges, storeyRangeBottom); + } + + /// The placement rule for an element without a stored level. + internal int ResolveByBottom(double? bottom) + { + int id = _storeyIds.Count > 0 ? ResolveStoreyByBottomCurrent(bottom) : 0; + return id != 0 ? id : _defaultStoreyId; + } + + private int ResolveStoreyByBottomCurrent(double? bottom) + { + var (ranges, lowest) = _bottomRanges.Value; + int chosen = 0; + if (bottom is double z) + foreach (var (storeyId, start, height) in ranges) + // Both bounds move by the same tolerance, so no bottom falls between two ranges. + if (z > start + 1e-9 && (Math.Abs(height) < 1e-10 || z <= start + height + 1e-9)) + chosen = storeyId; + return chosen != 0 ? chosen : lowest; + } + + // A project Level (building story or not) has no owning family, unplaced instance or DB view; + // loaded-family reference levels carry an exact owner in one of these serialized fields. + internal static bool IsProjectLevel(Element level) => level.IsNativeLevel + && level.SerializedFamilyId == -1 + && level.SerializedUnplacedOwnerId == -1 + && level.SerializedOwnerDbViewId == -1; + + internal static List GetBuildingStoreyLevels(IEnumerable elements) + { + var candidates = elements + .Where(element => IsProjectLevel(element) + && !string.IsNullOrWhiteSpace(element.Name) + && element.Parameters.Any(parameter => parameter.Id == -1007102 + && parameter.StorageType == StorageType.Double + && parameter.Value is double elevation + && double.IsFinite(elevation)) + && element.Parameters.Any(parameter => parameter.Id == -1007111 + && parameter.StorageType == StorageType.Integer + && parameter.Value is int isBuildingStory + && isBuildingStory == 1)) + .ToList(); + + return candidates + .OrderBy(GetElevation) + .ThenBy(element => element.Id) + .ToList(); + } + + internal static double GetElevation(Element level) + { + // Look for LEVEL_ELEV parameter + foreach (var p in level.Parameters) + { + string? pName = p.Definition?.Name; + if (pName != null && pName.Contains("LEVEL_ELEV") && p.StorageType == StorageType.Double && p.Value is double d) + return d; + } + // Fallback: bbox Z + if (level.DecodedBox != null && level.DecodedBox.Length >= 3) + return level.DecodedBox[2]; + return 0; + } +} diff --git a/src/RvtIO/RvtDocument.cs b/src/RvtIO/RvtDocument.cs index 1ef7d745..137e548d 100644 --- a/src/RvtIO/RvtDocument.cs +++ b/src/RvtIO/RvtDocument.cs @@ -435,6 +435,9 @@ public IList GetElements(BuiltInCategory category) public IList GetElements(int categoryId) => Collector().OfCategory(categoryId).ToElements(); + /// Gets the project building storeys and resolves element assignments with the current IFC storey rules. + public BuildingStoreyCatalog GetBuildingStoreyCatalog() => new(_elemById); + /// Get all distinct category IDs present in the document. public IReadOnlyList GetCategories() { diff --git a/tests/RvtIO.Tests/IfcExporterCurrentContainmentTests.cs b/tests/RvtIO.Tests/IfcExporterCurrentContainmentTests.cs index e7585bd8..e7f72524 100644 --- a/tests/RvtIO.Tests/IfcExporterCurrentContainmentTests.cs +++ b/tests/RvtIO.Tests/IfcExporterCurrentContainmentTests.cs @@ -1,6 +1,8 @@ +using System.Globalization; using System.Text.RegularExpressions; using RvtIO.Ifc; using RvtIO.Model; +using RvtIO.Scene; using Xunit; namespace RvtIO.Tests; @@ -117,6 +119,31 @@ public void LevelParameter_BeatsTheBoundingBox() Assert.Equal("Level A", StoreyOf(ifc, "IFCBUILDINGELEMENTPROXY", 100)); } + [Fact] + public void SceneLevelsAndElementAssignmentsMatchCurrentIfc() + { + var constrained = AtBottom(Product(100, GenericModel, "OST_GenericModel", 200), 9.8); + constrained.Parameters.Add(LevelParameter(-1001952, "LEVEL_PARAM", 10)); + var byGeometry = AtBottom(Product(101, GenericModel, "OST_GenericModel", 200), 9.8); + var info = new RevitFileInfo { Elements = [.. Levels(), constrained, byGeometry] }; + var scene = RvtSceneReader.Read(RvtDocument.FromInfo(info), new RvtSceneOptions { ModelKey = "levels.rvt" }).Document; + + using var step = new StringWriter(CultureInfo.InvariantCulture); + new IfcExporter { Profile = IfcProfile.Current, LengthUnit = IfcUnitFamily.Metre }.Export(info, step); + string ifc = step.ToString(); + var ifcLevels = Regex.Matches(ifc, @"=IFCBUILDINGSTOREY\('[^']*',#\d+,'([^']*)',[^\r\n]*,\.ELEMENT\.,([^)]*)\);") + .ToDictionary(match => match.Groups[1].Value, match => double.Parse(match.Groups[2].Value, CultureInfo.InvariantCulture)); + + Assert.Equal(3, ifcLevels.Count); + Assert.Equal(ifcLevels.Count, scene.Levels.Count); + foreach (var level in scene.Levels) + Assert.Equal(ifcLevels[level.Name], level.Elevation!.Value, 9); + Assert.Equal(2, scene.Elements.Count); + foreach (var element in scene.Elements) + Assert.Equal(StoreyOf(ifc, "IFCBUILDINGELEMENTPROXY", element.Id), + Assert.Single(scene.Levels, level => level.Id == element.LevelId).Name); + } + [Theory] [InlineData(IfcProfile.Current, "Level B")] // FAMILY_LEVEL_PARAM is not the associated level: the box decides [InlineData(IfcProfile.Legacy, "Level C")] @@ -311,7 +338,7 @@ private static string Export(IfcProfile version, params Element[] elements) } /// The name of the storey that IfcRelContainedInSpatialStructure gives the product with this tag. - private static string? StoreyOf(string ifc, string ifcType, int tag) + private static string? StoreyOf(string ifc, string ifcType, long tag) { var product = Regex.Match(ifc, $@"#(\d+)={ifcType}\([^\r\n]*,'{tag}'[,)]"); if (!product.Success) return null; diff --git a/tests/RvtIO.Tests/RvtSceneReaderTests.cs b/tests/RvtIO.Tests/RvtSceneReaderTests.cs index a0efd981..96d1e705 100644 --- a/tests/RvtIO.Tests/RvtSceneReaderTests.cs +++ b/tests/RvtIO.Tests/RvtSceneReaderTests.cs @@ -122,6 +122,8 @@ public void ScenePassesValidation() { var result = Map(); Assert.Empty(result.Document.Grids); + Assert.Empty(result.Document.Levels); + Assert.All(result.Document.Elements, element => Assert.Null(element.LevelId)); Assert.Empty(result.Document.Validate()); Assert.Empty(SceneJson.Read(SceneJson.Write(result.Document)).Validate()); } @@ -186,6 +188,63 @@ static void CheckAxis(SceneGridLine line, string name, Vector3d start, Vector3d } } + [Fact] + public void SceneExportsProjectStoreysAndAssignsElementsWithTheCurrentIfcRules() + { + var ground = Level(10, "Ground", 0); + var upper = Level(20, "Upper", 12); + var landing = Level(15, "Landing", 6, story: false); + var below = Level(5, "Below the building", -3, story: false); + var family = Level(30, "Family reference", 12); + family.SerializedFamilyId = 900; + + var wall = Instance(Wall, (int)BuiltInCategory.OST_Walls, "OST_Walls", + Bip(BuiltInParameter.WALL_BASE_CONSTRAINT, upper.Id, StorageType.ElementId), + Bip(BuiltInParameter.LEVEL_PARAM, ground.Id, StorageType.ElementId)); + var onLanding = Instance(Door, (int)BuiltInCategory.OST_Doors, "OST_Doors", + Bip(BuiltInParameter.LEVEL_PARAM, landing.Id, StorageType.ElementId)); + var withoutLevel = Instance(Empty, (int)BuiltInCategory.OST_Doors, "OST_Doors"); + withoutLevel.BoundingBox = [0, 0, 11.9, 2, 2, 18]; + var onBelow = Instance(Broken, (int)BuiltInCategory.OST_Doors, "OST_Doors", + Bip(BuiltInParameter.LEVEL_PARAM, below.Id, StorageType.ElementId)); + + var document = RvtDocument.FromInfo(new RevitFileInfo + { + Elements = [wall, onLanding, withoutLevel, onBelow, upper, family, below, ground, landing], + }); + var catalog = document.GetBuildingStoreyCatalog(); + Assert.Equal(new[] { ground.Id, upper.Id }, catalog.Storeys.Select(level => level.Id)); + Assert.Null(catalog.GetStoreyId(999)); + + var result = RvtSceneReader.Read(document, Meshes(), new RvtSceneOptions { ModelKey = "model.rvt" }); + var scene = SceneJson.Read(SceneJson.Write(result.Document)); + Assert.Empty(scene.Validate()); + int modelId = Assert.Single(scene.Models).Id; + Assert.Collection(scene.Levels, + level => CheckLevel(level, ground.Id, "Ground", 0, modelId), + level => CheckLevel(level, upper.Id, "Upper", 12 * Foot, modelId)); + var elements = scene.Elements.ToDictionary(element => element.Id); + Assert.Equal(upper.Id, elements[Wall].LevelId); + Assert.Equal(ground.Id, elements[Door].LevelId); + Assert.Equal(upper.Id, elements[Empty].LevelId); + Assert.Null(elements[Broken].LevelId); + + static Element Level(int id, string name, double elevation, bool story = true) => new() + { + Id = id, Name = name, CategoryId = (int)BuiltInCategory.OST_Levels, + IsNativeLevel = true, SerializedFamilyId = -1, SerializedUnplacedOwnerId = -1, SerializedOwnerDbViewId = -1, + Parameters = [Bip(BuiltInParameter.LEVEL_ELEV, elevation), Bip(BuiltInParameter.LEVEL_IS_BUILDING_STORY, story ? 1 : 0)], + }; + + static void CheckLevel(SceneLevel level, int id, string name, double elevation, int modelId) + { + Assert.Equal(id, level.Id); + Assert.Equal(modelId, level.ModelId); + Assert.Equal(name, level.Name); + Assert.Equal(elevation, level.Elevation!.Value, 9); + } + } + [Fact] public void SymbolIsOneGeometryPlacedOncePerPlacement() { From e78b7e59cdfc3f5294e275768d4a38013cf0b088 Mon Sep 17 00:00:00 2001 From: mie <79989386+mahach666@users.noreply.github.com> Date: Thu, 19 Nov 2026 13:15:04 +0300 Subject: [PATCH 022/259] Export curved and multi-segment Revit grids to IOScene --- CHANGELOG.md | 1 + Directory.Packages.props | 2 +- docs/public-api.md | 1 + docs/scene.md | 8 +- src/RvtIO.Scene/RvtSceneReader.cs | 34 +++-- src/RvtIO/Internal/ParsingState.cs | 1 + src/RvtIO/Model/GridAxis.cs | 54 +++++++ src/RvtIO/Model/RevitFileInfo.cs | 3 + src/RvtIO/Parsing/GridAxisReader.cs | 179 ++++++++++++++++++++++++ src/RvtIO/Parsing/WideBlockWalker.cs | 10 +- src/RvtIO/RvtDocument.cs | 13 ++ src/RvtIO/RvtFileReader.cs | 57 +++++++- tests/RvtIO.Tests/SceneGridPathTests.cs | 163 +++++++++++++++++++++ 13 files changed, 508 insertions(+), 18 deletions(-) create mode 100644 src/RvtIO/Model/GridAxis.cs create mode 100644 src/RvtIO/Parsing/GridAxisReader.cs create mode 100644 tests/RvtIO.Tests/SceneGridPathTests.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index 930a3c9f..9ba67aa4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,7 @@ API between minor releases. ### Added - `RvtIO.Scene` exports decoded straight Revit grid axes and their labels in scene coordinates. +- `RvtIO.Scene` exports circular and multi-segment grid axes as connected paths with one datum label per axis. - `RvtDocument.GetBuildingStoreyCatalog()` exposes project building storeys and their assignments. `RvtIO.Scene` writes those levels and the storey of each drawable element using the current IFC rules. diff --git a/Directory.Packages.props b/Directory.Packages.props index cdadd7e1..019e9a7c 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -12,7 +12,7 @@ - + diff --git a/docs/public-api.md b/docs/public-api.md index 79c39688..45085f91 100644 --- a/docs/public-api.md +++ b/docs/public-api.md @@ -16,6 +16,7 @@ projects through `InternalsVisibleTo`. | `RvtExitCodes`, `RvtInputException`, `RvtLimitException`, `RvtContainerCheck` | The exit codes 0 to 4 and 6 of the command line tool (code 5 is returned by `downgrade --check` and `save-as` when refused), the exceptions `RvtFileReader.Read` throws for a file it cannot read, and the check that raises them. | | `FilteredElementCollector` | Query over the elements of a document (`OfCategory`, `WhereElementIsNotElementType`, `Where`, ...). | | `BuildingStoreyCatalog`, `BuildingStorey` | `RvtDocument.GetBuildingStoreyCatalog()` lists native project building storeys in order of elevation and Revit ID. Each storey carries its ID, name and resolved elevation in internal feet. `GetStoreyId(elementId)` uses the current IFC storey rules and returns null for an unknown element or one assigned to the building itself. Obtain a new catalog after editing levels. | +| `GridAxis` | `RvtDocument.GetGridAxes()` lists decoded project axes in Revit ID order. A circular or multi-segment axis has ordered analytic segments. `GridAxis.Tessellate(maxErrorFeet)` returns path points in internal feet. | ## Model diff --git a/docs/scene.md b/docs/scene.md index 2f247981..1a268cb3 100644 --- a/docs/scene.md +++ b/docs/scene.md @@ -2,7 +2,7 @@ `RvtIO.Scene` turns a Revit project read by RvtIO into a scene of the `IOScene` package: a `SceneDocument` with one model, the drawable elements, their triangle meshes in metres, their names and parameters, the building storeys, and -the decoded straight grid axes. A viewer or another consumer of the scene reads it without knowing Revit. The scene itself is specified in the contract of the `IOScene` +the decoded grid axes. A viewer or another consumer of the scene reads it without knowing Revit. The scene itself is specified in the contract of the `IOScene` repository (`docs/contract.md`), and the property keys it writes are registered there in `docs/keys.md`. The adapter is a preview. It is published as the package `RvtIO.Scene` on each RvtIO release tag, depends on exactly @@ -53,7 +53,8 @@ rvtio project.rvt --ifc project.ifc --compact-json project.compact.json --scene |---|---| | `SceneModel.Key` | `RvtSceneOptions.ModelKey`, else the file name without its directory (`project.rvt`). This derivation does not change. | | `SceneModel` | `SourceFormat` `rvt`, `SourceLengthUnit` `ft`, `Producer` `RvtIO.Scene `. | -| `SceneGridSystem`, `SceneGridLine` | One grid system named `Grids` when the model has valid straight grid axes. Each axis uses its element name and the endpoints of its decoded location curve, converted from feet to metres in the document's internal coordinates. Elevation is the start point's Z. | +| `SceneGridSystem`, `SceneGridLine` | One grid system named `Grids` when the model has decoded axes. Standalone straight axes use the element name and endpoints of the location curve, converted from feet to metres in the document's internal coordinates. Elevation is the start point's Z. | +| `SceneGridPath` | One path and datum label per standalone circular arc or complete multi-segment grid. Points follow the stored segment order at model Z=0, as in Revit's grid curves. Arcs are sampled with at most 1 mm of chord error. Viewers place the label only at the two outer endpoints. | | `SceneLevel` | Project levels marked as building storeys, ordered by elevation and Revit element ID. Names and resolved elevations, including elevations inferred by the reader, use the same level selection as IFC. Elevations are written in metres. | | `SceneElement.LevelId` | The building-storey assignment from `RvtDocument.GetBuildingStoreyCatalog()`, using the current IFC rules for stored level references and geometry fallback. Assignments to the building itself leave this field empty. The scene assigns a storey to each drawable element independently of IFC product aggregation. | | `SceneElement` | One per drawable element of `ElementMeshes.Extract` (the elements the IFC export would consider products, see the remarks of `ElementMeshes`). `Id` is the element id. | @@ -100,7 +101,8 @@ The text a value is written with under a key is frozen with the key: changing it (numbers in SI units, booleans, element references) wait for public RvtIO API. - Shared, project and family parameters have no key yet. Their formats (for example `revit:shared:`) are registered in the IOScene key registry when the adapter first writes them; that is an addition. -- Every element is a top-level element of its model. Linked models, views and curved grid axes are omitted. +- Every element is a top-level element of its model. Linked models and views are omitted. +- The grid path reader accepts vertical cylindrical grid surfaces and complete, connected chains of straight and circular segments. It omits unsupported surfaces, incomplete chains and paths requiring more than 65,536 vertices at the documented tolerance. - Materials have a name and a colour; no roughness, metalness or textures. - Element names are those of `RvtDocument`; the validated names the IFC export applies to files read by their own class schema are not public API. diff --git a/src/RvtIO.Scene/RvtSceneReader.cs b/src/RvtIO.Scene/RvtSceneReader.cs index ed8b8186..f2a35bfd 100644 --- a/src/RvtIO.Scene/RvtSceneReader.cs +++ b/src/RvtIO.Scene/RvtSceneReader.cs @@ -10,7 +10,7 @@ namespace RvtIO.Scene; /// /// Turns a Revit document into a scene (): one model, one element per drawable element of the document -/// with its triangle meshes (), its names and its parameters, plus building storeys and decoded straight grid axes. +/// with its triangle meshes (), its names and its parameters, plus building storeys and decoded grid axes. /// /// /// Lengths are converted from feet to metres (x 0.3048) into the internal coordinates of the document, Z up. A symbol that @@ -230,22 +230,34 @@ private static RvtSceneResult Map(RvtDocument document, MeshSet meshes, string m private static void AddGrids(SceneDocument scene, RvtDocument document) { + const double GridChordErrorMetres = 0.001; var grid = new SceneGridSystem { ModelId = ModelId }; - foreach (var element in document.Collector().OfCategory(BuiltInCategory.OST_Grids) - .WhereElementIsNotElementType().OrderBy(element => element.Id)) + foreach (var axis in document.GetGridAxes()) { - if (element.Location is not { CurveType: "Line", StartPoint: [var x0, var y0, var z0], EndPoint: [var x1, var y1, var z1] } - || !double.IsFinite(x0) || !double.IsFinite(y0) || !double.IsFinite(z0) - || !double.IsFinite(x1) || !double.IsFinite(y1) || !double.IsFinite(z1)) + if (axis.Segments is [{ CurveType: "Line" } line]) + { + if (ReadPoint(line.StartPoint) is not { } start || ReadPoint(line.EndPoint) is not { } end || start == end) + continue; + grid.Lines.Add(new SceneGridLine { Name = axis.Name, Start = start, End = end, Elevation = start.Z }); continue; + } - var start = new Vector3d(x0, y0, z0) * MetresPerFoot; - var end = new Vector3d(x1, y1, z1) * MetresPerFoot; - if (start == end) continue; - grid.Lines.Add(new SceneGridLine { Name = element.Name ?? string.Empty, Start = start, End = end, Elevation = start.Z }); + if (axis.Tessellate(GridChordErrorMetres / MetresPerFoot) is not { } samples) continue; + var points = new List(samples.Count); + foreach (var sample in samples) + { + if (ReadPoint(sample) is not { } point) break; + points.Add(point); + } + if (points.Count == samples.Count) + (grid.Paths ??= []).Add(new SceneGridPath { Name = axis.Name, Points = points }); } - if (grid.Lines.Count > 0) scene.Grids.Add(grid); + if (grid.Lines.Count > 0 || grid.Paths is { Count: > 0 }) scene.Grids.Add(grid); + + static Vector3d? ReadPoint(double[] point) => + point is [var x, var y, var z] && double.IsFinite(x) && double.IsFinite(y) && double.IsFinite(z) + ? new Vector3d(x, y, z) * MetresPerFoot : null; } /// "RvtIO.Scene" and the version of this assembly without the source revision. diff --git a/src/RvtIO/Internal/ParsingState.cs b/src/RvtIO/Internal/ParsingState.cs index 447e4a04..567ba35b 100644 --- a/src/RvtIO/Internal/ParsingState.cs +++ b/src/RvtIO/Internal/ParsingState.cs @@ -389,6 +389,7 @@ public TfBlockDeserializer.UnitsElemOptions? OwnDocumentUnitOptions /// the serialized datum text, free end, bubble end and cut vector. The element-level /// name remains authoritative for the grid mark because datum text may name its head type. public Dictionary GridDatums { get; } = new(); + public (List Paths, HashSet Members)? GridAxes { get; set; } /// Line-style element id for 0x0346 curves whose GStyleElemId was a real id /// (not -1): these are detail/model lines, keyed by owner eid. diff --git a/src/RvtIO/Model/GridAxis.cs b/src/RvtIO/Model/GridAxis.cs new file mode 100644 index 00000000..41ab8b23 --- /dev/null +++ b/src/RvtIO/Model/GridAxis.cs @@ -0,0 +1,54 @@ +namespace RvtIO.Model; + +/// A project grid axis, with its authored name and ordered curves in internal feet. +public sealed class GridAxis +{ + internal GridAxis(int id, string name, LocationCurve[] segments) + { + Id = id; + Name = name; + Segments = Array.AsReadOnly(segments); + } + + /// Revit element ID of the grid or multi-segment grid. + public int Id { get; } + /// Datum label of the axis. + public string Name { get; } + /// Line and circular arc segments in order from the first end to the last. + public IReadOnlyList Segments { get; } + + /// Samples the axis as an ordered polyline in feet, with the requested maximum arc-to-chord error. + /// Returns null if the tolerance would require more than 65,536 vertices or the curve is incomplete. + public List? Tessellate(double maxErrorFeet) + { + if (!double.IsFinite(maxErrorFeet) || maxErrorFeet <= 0) + throw new ArgumentOutOfRangeException(nameof(maxErrorFeet)); + const int MaxVertices = 65_536; + var points = new List { Segments[0].StartPoint }; + foreach (var curve in Segments) + { + if (curve.CurveType == "Arc") + { + if (curve.ArcRadius is not double radius || curve.ArcCenter is not { } center + || curve.ArcXDirection is not { } x || curve.ArcYDirection is not { } y) + return null; + double start = curve.ArcStartParameter, sweep = curve.ArcEndParameter - start; + double step = 4 * Math.Asin(Math.Sqrt(Math.Min(1, maxErrorFeet / (2 * radius)))); + double count = Math.Ceiling(Math.Abs(sweep) / Math.Min(Math.PI / 2, step)); + if (!(count >= 1 && count <= MaxVertices - points.Count)) return null; + for (int j = 1; j < (int)count; j++) + points.Add(PointOnArc(center, radius, x, y, start + sweep * j / count)); + } + else if (points.Count == MaxVertices) + return null; + points.Add(curve.EndPoint); + } + return points; + } + + internal static double[] PointOnArc(double[] center, double radius, double[] x, double[] y, double angle) + { + double cos = Math.Cos(angle) * radius, sin = Math.Sin(angle) * radius; + return [center[0] + cos * x[0] + sin * y[0], center[1] + cos * x[1] + sin * y[1], center[2] + cos * x[2] + sin * y[2]]; + } +} diff --git a/src/RvtIO/Model/RevitFileInfo.cs b/src/RvtIO/Model/RevitFileInfo.cs index d28c08d3..1c7a2cd1 100644 --- a/src/RvtIO/Model/RevitFileInfo.cs +++ b/src/RvtIO/Model/RevitFileInfo.cs @@ -6,6 +6,9 @@ public partial class RevitFileInfo /// A copy that shares all members with this instance; the caller replaces what it changes. internal RevitFileInfo ShallowCopy() => (RevitFileInfo)MemberwiseClone(); + internal IReadOnlyList CurvedGridAxes { get; set; } = []; + internal IReadOnlySet? GridChainMemberIds { get; set; } + /// The basic file information. public FileMetadata Metadata { get; set; } = new(); /// The project information. diff --git a/src/RvtIO/Parsing/GridAxisReader.cs b/src/RvtIO/Parsing/GridAxisReader.cs new file mode 100644 index 00000000..387d37f3 --- /dev/null +++ b/src/RvtIO/Parsing/GridAxisReader.cs @@ -0,0 +1,179 @@ +using RvtIO.Model; + +namespace RvtIO.Parsing; + +/// Reads the authoritative surface of a Grid and the ordered members of a GridChain. +internal sealed class GridAxisReader +{ + private const string SurfaceKey = "DatumPlane.m_pSurface"; + private const string MembershipKey = "Grid.m_pGridChainMembershipCell"; + private const string ChainMap = "GridChain.m_curveTagToGridsInChain"; + private const string Pair = "std::pair< int, ElementId >"; + private readonly WideBlockWalker _walker; + private readonly Dictionary _segments = []; + private readonly Dictionary _chains = []; + + internal GridAxisReader(SchemaDocument schema, IReadOnlyDictionary entities) + { + _walker = new(schema, static (type, field) => type.Name switch + { + "Element" when field.Name == "m_id" => "Element.m_id", + "DatumPlane" when field.Name is "m_text" or "m_pSurface" => type.Name + "." + field.Name, + "Grid" when field.Name == "m_pGridChainMembershipCell" => MembershipKey, + "GridChain" when field.Name is "commonText" or "m_curveTagToGridsInChain" => type.Name + "." + field.Name, + "GridChainMembershipCell" when field.Name == "m_gridChainId" => type.Name + "." + field.Name, + "Envelope" when field.Name == "m_corners" => type.Name + "." + field.Name, + "Plane" or "CylSurf" => type.Name + "." + field.Name, + _ => null, + }, [Pair], captureRootPointers: true); + _walker.UseEntitySchemas(entities, passUnknown: true); + } + + internal bool IsGrid(int classId) => _walker.Class(classId)?.Name is "Grid" or "GridChain"; + + internal void Read(uint id, byte[] data, int offset, int size, int classId) + { + if (id is 0 or > int.MaxValue || offset < 0 || size < 2 || (long)offset + size > data.Length) return; + var walk = _walker.Run(data, offset, size, classId); + if (!walk.RootRead || Field("Element.m_id", -1).Integer != id) return; + if (_walker.Class(classId)?.Name == "GridChain") + { + if (!walk.Exact || Field("GridChain.commonText", -1).Text is not { } label || string.IsNullOrWhiteSpace(label)) + return; + var order = new SortedDictionary(); + foreach (var pair in walk.Records) + { + if (pair.Values.GetValueOrDefault(WideBlockWalker.RootFieldKey) is not ChainMap) continue; + if (pair.Values.GetValueOrDefault("first") is not long tag || tag is < 0 or > int.MaxValue + || pair.Values.GetValueOrDefault("second") is not long member || member is <= 0 or > int.MaxValue + || !order.TryAdd((int)tag, (int)member)) + return; + } + if (order.Count >= 2 && order.Count == Field(ChainMap + "#", -1).Integer + && order.Values.Distinct().Count() == order.Count) + _chains.Add((int)id, (label, order.Values.ToArray())); + return; + } + + int? chainId = null; + if (walk.RootPointers?.TryGetValue(MembershipKey, out int membership) == true) + { + long owner = Field("GridChainMembershipCell.m_gridChainId", membership).Integer; + // An unfinished membership object still identifies the element as part of a chain. + chainId = owner is > 0 and <= int.MaxValue ? (int)owner : 0; + } + var name = Field("DatumPlane.m_text", -1).Text; + LocationCurve? curve = null; + if (walk.RootPointers?.TryGetValue(SurfaceKey, out int surface) == true && surface < walk.QueueEnd.Count) + { + double start = Real("Envelope.m_corners@0/0", surface), end = Real("Envelope.m_corners@1/0", surface); + string? type = _walker.Class(walk.Queue[surface])?.Name; + if (double.IsFinite(start) && double.IsFinite(end) && end > start) + { + if (type == "CylSurf") + curve = Arc(Vector("CylSurf.m_center", surface), Vector("CylSurf.m_xVec", surface), + Vector("CylSurf.m_yVec", surface), Vector("CylSurf.m_zVec", surface), + Real("CylSurf.m_radius", surface), start, end); + else if (type == "Plane" && chainId != null) + { + var origin = Vector("Plane.m_origin", surface); + var direction = Vector("Plane.m_xVec", surface); + if (double.IsFinite(origin[2]) && Math.Abs(direction[2]) <= 1e-8) + { + // Like the arcs, chain members use Grid.Curve's model plan even when the sketch is elevated. + direction[2] = 0; + double[] Point(double t) => [origin[0] + t * direction[0], origin[1] + t * direction[1], 0]; + var a = Point(start); + var b = Point(end); + double length = Math.Sqrt(DistanceSquared(a, b)); + if (double.IsFinite(length) && length > 0) + curve = new LocationCurve { StartPoint = a, EndPoint = b, Direction = direction, Length = length }; + } + } + } + } + if (curve != null || chainId != null) _segments.Add((int)id, (name, chainId, curve)); + + WideBlockWalker.Capture Field(string key, int queue) => + walk.Captures.FirstOrDefault(field => field.Key == key && field.QueueIndex == queue); + double Real(string key, int queue) => Field(key, queue) is { Kind: WideBlockWalker.CaptureKind.Real } field ? field.Real : double.NaN; + double[] Vector(string key, int queue) => [Real(key + "@0", queue), Real(key + "@1", queue), Real(key + "@2", queue)]; + } + + internal (List Paths, HashSet Members) Build() + { + var paths = new List(); + var members = _segments.Where(pair => pair.Value.Owner.HasValue).Select(pair => pair.Key).ToHashSet(); + foreach (var (id, segment) in _segments) + if (segment is { Owner: null, Curve: { } curve, Name: { } name } && !string.IsNullOrWhiteSpace(name)) + paths.Add(new GridAxis(id, name, [curve])); + foreach (var (id, chain) in _chains) + { + members.UnionWith(chain.Members); + var curves = new List(chain.Members.Length); + foreach (int member in chain.Members) + { + if (!_segments.TryGetValue(member, out var segment) || segment.Owner != id || segment.Curve == null) break; + curves.Add(segment.Curve); + } + if (curves.Count == chain.Members.Length && Orient(curves)) + paths.Add(new GridAxis(id, chain.Name, curves.ToArray())); + } + return (paths, members); + } + + private static LocationCurve? Arc(double[] center, double[] x, double[] y, double[] axis, double radius, double start, double end) + { + const double Epsilon = 1e-8; + double sweep = end - start; + if (!center.Concat(x).Concat(y).Concat(axis).All(double.IsFinite) || !double.IsFinite(radius) || radius <= 0 + || sweep > 2 * Math.PI + Epsilon || Math.Abs(axis[0]) > Epsilon || Math.Abs(axis[1]) > Epsilon + || Math.Abs(Math.Abs(axis[2]) - 1) > Epsilon || Math.Abs(x[2]) > Epsilon || Math.Abs(y[2]) > Epsilon + || Math.Abs(x[0] * y[0] + x[1] * y[1]) > Epsilon + || Math.Abs(x[0] * x[0] + x[1] * x[1] - 1) > Epsilon + || Math.Abs(y[0] * y[0] + y[1] * y[1] - 1) > Epsilon) + return null; + // Grid.Curve is the horizontal datum curve at model Z=0, even when the cylinder's origin is offset. + center[2] = x[2] = y[2] = 0; + var first = GridAxis.PointOnArc(center, radius, x, y, start); + var last = GridAxis.PointOnArc(center, radius, x, y, end); + if (!first.Concat(last).All(double.IsFinite) || !double.IsFinite(radius * sweep)) return null; + return new LocationCurve + { + CurveType = "Arc", StartPoint = first, EndPoint = last, Length = radius * sweep, + ArcCenter = center, ArcRadius = radius, ArcXDirection = x, ArcYDirection = y, + ArcStartParameter = start, ArcEndParameter = end, + }; + } + + internal static bool Orient(List curves) + { + // Analytic endpoints of consecutive stored segments can differ by floating-point rounding. + static bool Meets(double[] a, double[] b) => DistanceSquared(a, b) <= 1e-12; + static bool Touches(double[] point, LocationCurve curve) => Meets(point, curve.StartPoint) || Meets(point, curve.EndPoint); + bool start = Touches(curves[0].StartPoint, curves[1]), end = Touches(curves[0].EndPoint, curves[1]); + if (start == end) return false; + if (start) Reverse(curves[0]); + for (int i = 1; i < curves.Count; i++) + { + start = Meets(curves[i - 1].EndPoint, curves[i].StartPoint); + end = Meets(curves[i - 1].EndPoint, curves[i].EndPoint); + if (start == end) return false; + if (end) Reverse(curves[i]); + } + return true; + } + + private static void Reverse(LocationCurve curve) + { + (curve.StartPoint, curve.EndPoint) = (curve.EndPoint, curve.StartPoint); + (curve.ArcStartParameter, curve.ArcEndParameter) = (curve.ArcEndParameter, curve.ArcStartParameter); + if (curve.Direction is [var x, var y, var z]) curve.Direction = [-x, -y, -z]; + } + + private static double DistanceSquared(double[] a, double[] b) + { + double x = a[0] - b[0], y = a[1] - b[1], z = a[2] - b[2]; + return x * x + y * y + z * z; + } +} diff --git a/src/RvtIO/Parsing/WideBlockWalker.cs b/src/RvtIO/Parsing/WideBlockWalker.cs index 5150bc40..54ae16a9 100644 --- a/src/RvtIO/Parsing/WideBlockWalker.cs +++ b/src/RvtIO/Parsing/WideBlockWalker.cs @@ -36,6 +36,7 @@ internal sealed class Walk public int Position; public readonly List Queue = []; public readonly List Captures = []; + public Dictionary? RootPointers; /// Per queued object (same index as ) the first position of its fields, -1 when not reached. public readonly List QueueStart = []; /// The values of the objects of the requested record classes, in stored order (inline items of arrays and queued objects). @@ -89,6 +90,7 @@ private sealed class Fail(string message) : Exception(message); private readonly ConcurrentDictionary<(int, string), string?> _keys = new(); private readonly bool[] _isIdentifier; private readonly int _idWidth; + private readonly bool _captureRootPointers; private readonly SchemaClass _entityBlob; private Dictionary? _entityLayoutOf; private SchemaField[]?[] _entityLayouts = []; @@ -100,10 +102,12 @@ private sealed class Fail(string message) : Exception(message); /// The capture key of a scalar field (null: not captured); a fixed array adds "@index". /// Classes whose objects are returned as . - internal WideBlockWalker(SchemaDocument schema, Func keyOf, IEnumerable recordClassNames) + internal WideBlockWalker(SchemaDocument schema, Func keyOf, IEnumerable recordClassNames, + bool captureRootPointers = false) { _classes = schema.Classes.GroupBy(c => c.Id).ToDictionary(g => g.Key, g => g.First()); _keyOf = keyOf; + _captureRootPointers = captureRootPointers; var names = recordClassNames.ToHashSet(StringComparer.Ordinal); _recordClasses = _classes.Values.Where(c => names.Contains(c.Name)).Select(c => c.Id).ToHashSet(); int max = _classes.Keys.Max(); @@ -505,7 +509,9 @@ private void ReadReference(Context c, SchemaClass declaring, SchemaField f, stri { if (!_classes.ContainsKey(tag)) throw new Fail("class tag " + tag); if (walk.Queue.Count >= 1_000_000) throw new Fail("queue"); - walk.Queue.Add(tag); + if (_captureRootPointers && c.AtRoot && depth == 0 && key != null) + (walk.RootPointers ??= new())[key] = walk.Queue.Count; + walk.Queue.Add(tag); } } if (key != null) walk.Captures.Add(new(key, CaptureKind.PointerClass, handle == 0 ? 0 : tag == 0 ? -1 : tag, 0, null, c.AtRoot && depth == 0, c.QueueIndex, declaring.Name, f.Name)); diff --git a/src/RvtIO/RvtDocument.cs b/src/RvtIO/RvtDocument.cs index 137e548d..f45f535f 100644 --- a/src/RvtIO/RvtDocument.cs +++ b/src/RvtIO/RvtDocument.cs @@ -438,6 +438,19 @@ public IList GetElements(int categoryId) /// Gets the project building storeys and resolves element assignments with the current IFC storey rules. public BuildingStoreyCatalog GetBuildingStoreyCatalog() => new(_elemById); + /// Gets project grid axes in Revit ID order. Multi-segment grids are one axis with ordered curves. + public IReadOnlyList GetGridAxes() + { + var axes = new List(_info.CurvedGridAxes); + foreach (var element in Collector().OfCategory(BuiltInCategory.OST_Grids).WhereElementIsNotElementType()) + { + if (element.Location is { CurveType: "Line" } line && _info.GridChainMemberIds?.Contains(element.Id) != true) + axes.Add(new GridAxis(element.Id, element.Name ?? string.Empty, [line])); + } + axes.Sort((a, b) => a.Id.CompareTo(b.Id)); + return axes; + } + /// Get all distinct category IDs present in the document. public IReadOnlyList GetCategories() { diff --git a/src/RvtIO/RvtFileReader.cs b/src/RvtIO/RvtFileReader.cs index c37ad57d..c6af8e4b 100644 --- a/src/RvtIO/RvtFileReader.cs +++ b/src/RvtIO/RvtFileReader.cs @@ -176,6 +176,8 @@ public RevitFileInfo Read(string rvtPath) // per-chunk walk. Extracts native parameter stores and re-runs the key block-driven signals at full coverage. RunTfStreamWalk(state); if (state.WideSchema == null) ReadOwnDocumentUnits(root, state, diag); + if (wideSchema == null && state.ElemClassIdx.Values.Any(id => id is 2108 or 2111)) + ReadNarrowGridAxes(root, state, diag); LogPhase("Tf stream walked"); diag?.WriteLine($"Grid datums: {state.GridDatums.Count}"); @@ -759,6 +761,11 @@ public RevitFileInfo Read(string rvtPath) _ => null, }; ElementBuilder.PostProcess(rvtInfo, state, diag); + if (state.GridAxes is { } axes) + { + rvtInfo.CurvedGridAxes = axes.Paths; + rvtInfo.GridChainMemberIds = axes.Members; + } LogPhase("Post-processed"); ElementBuilder.ApplyValidatedStairComponentTypeNames(rvtInfo.Elements, state); ElementBuilder.ApplyValidatedCorniceTypeNames(rvtInfo.Elements, state); @@ -1023,6 +1030,7 @@ private static void ReadWideElementIndex(RootStorage root, ParsingState state, state.WideSchema = schema; // the field walk of the root blocks (schema by class and field name); a file whose schema table does not parse a second time has none WideNativeParams? fields = null; + GridAxisReader? gridReader = null; SchemaDocument? schemaDocument = null; if (PagedGzipStream.Read(root, "Formats", "Latest") is { } schemaBytes) { @@ -1030,11 +1038,14 @@ private static void ReadWideElementIndex(RootStorage root, ParsingState state, { fields = new WideNativeParams(schemaDocument = TfSchemaReader.Parse(schemaBytes)); // the values of an extensible storage entity are read by its schema, so the objects behind them are read in place - fields.Walker.UseEntitySchemas(EntitySchemaReader.Read(root, schemaDocument), passUnknown: true); + var entitySchemas = EntitySchemaReader.Read(root, schemaDocument); + fields.Walker.UseEntitySchemas(entitySchemas, passUnknown: true); + gridReader = new GridAxisReader(schemaDocument, entitySchemas); } catch (FormatException) { diag?.WriteLine("Wide element records: Formats/Latest does not parse for the field walk"); } } var walks = new Dictionary>(); + var gridBlocks = new Dictionary(); var drivers = new Dictionary>(); var wallShim = new Dictionary(); var index = WideElementRecords.BuildIndexWithPartitions(partitionStreams, schema, state.AllKnownIds, @@ -1042,6 +1053,8 @@ private static void ReadWideElementIndex(RootStorage root, ParsingState state, { if (!walks.TryGetValue(id, out var list)) walks[id] = list = []; list.Add((fields.Walker.Run(data, offset, size, cls), cls, partition)); + if (list.Count == 1 && gridReader?.IsGrid(cls) == true) + gridBlocks.Add(id, (data, offset, size)); // the roots of a straight or an arc wall: the block of the drive curve (the classes the Revit 2022 reader names) if (state.StaleCopiesRemoved && fields.R22Id(cls) is 3524 or 361) { @@ -1078,6 +1091,8 @@ private static void ReadWideElementIndex(RootStorage root, ParsingState state, } // a copy of the element in two streams is decoded only when it is one record if (list.Count != 1 || !index.RootClasses.TryGetValue(id, out int rootClass) || list[0].Class != rootClass) continue; + if (gridBlocks.TryGetValue(id, out var grid)) + gridReader!.Read(id, grid.Data, grid.Offset, grid.Size, rootClass); if (drivers.TryGetValue(id, out var exactDrivers) && exactDrivers.Count > 0) state.ExactCurveDrivers[id] = exactDrivers; var np = fields.Build(list[0].Walk, rootClass); if (np == null) continue; @@ -1131,10 +1146,50 @@ private static void ReadWideElementIndex(RootStorage root, ParsingState state, foreach (var (reason, count) in walkFailures.OrderByDescending(f => f.Value).Take(15)) diag?.WriteLine($" walk stopped x{count}: {reason}"); if (fields != null && schemaDocument != null) ReadWideDocumentUnits(root, state, schemaDocument, fields, walks, diag); + if (gridBlocks.Count > 0) state.GridAxes = gridReader!.Build(); diag?.WriteLine($"Wide element records: {index.Records} headers, {index.Blocks} blocks, " + $"categories={index.HeaderCategories.Count}, root classes={index.RootClasses.Count} of {state.AllKnownIds.Count} elements"); } + private static void ReadNarrowGridAxes(RootStorage root, ParsingState state, TextWriter? diag) + { + if (PagedGzipStream.Read(root, "Formats", "Latest") is not { } schemaBytes) return; + GridAxisReader reader; + try + { + var schema = TfSchemaReader.Parse(schemaBytes); + reader = new GridAxisReader(schema, EntitySchemaReader.Read(root, schema)); + } + catch (FormatException) + { + diag?.WriteLine("Grid paths: Formats/Latest does not parse for the datum field walk"); + return; + } + var blocks = new Dictionary(); + void Collect(byte[] data, int start, uint size, ushort classId, uint owner) + { + if (size < 4 || !state.AllKnownIds.Contains(owner) || !reader.IsGrid(classId)) return; + if (!blocks.TryAdd(owner, (data, start + 12, (int)size, classId))) blocks[owner] = null; + } + if (state.ReadsFramedRecords) + { + foreach (var frame in state.FramedPartitions!) + foreach (var record in frame!.Items) + { + if (record.Channel != 102 || record.Length < 20 || record.Owner > int.MaxValue) continue; + var (data, start, _) = frame.Bytes(record); + Collect(data, start, (uint)(record.Length - 16), BitConverter.ToUInt16(data, start + 12), (uint)record.Owner); + } + } + else + TfStreamWalker.Walk(state.Chunks, state.AllKnownIds, (data, start, size, cls, owner) => + Collect(data, start, (uint)size, cls, owner)); + foreach (var (id, block) in blocks) + if (block is { } b) + reader.Read(id, b.Data, b.Offset, b.Size, b.Class); + state.GridAxes = reader.Build(); + } + /// The document units of a file read by the schema walk: the units element named by Global/Latest, its FormatOptions and the /// persisted schema maps (see ), recorded where the Revit 2022 reader records the same facts. A file of the /// Revit 2020 layout has no schema maps; its Length option is the first display unit of the units element. diff --git a/tests/RvtIO.Tests/SceneGridPathTests.cs b/tests/RvtIO.Tests/SceneGridPathTests.cs new file mode 100644 index 00000000..379c8fa7 --- /dev/null +++ b/tests/RvtIO.Tests/SceneGridPathTests.cs @@ -0,0 +1,163 @@ +using System.Text; +using IOScene; +using RvtIO.Meshes; +using RvtIO.Model; +using RvtIO.Parsing; +using RvtIO.Scene; +using Xunit; + +namespace RvtIO.Tests; + +public class SceneGridPathTests +{ + private const double Foot = 0.3048; + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void SceneExportsNativeArcsAndTheOrderedMixedAxis(bool wide) + { + var reader = new GridAxisReader(GridSchema(wide), new Dictionary()); + Read(100, 5, w => Grid(w, "Arc", 0, 8, + [0, -1, Math.PI * 1.5, 1, -36, -30, 2.5, 1, 0, 0, 0, -1, 0, 0, 0, 1, 6])); + Read(201, 5, w => Grid(w, "Mixed", 200, 7, [0, -1, 10, 1, 10, 0, 5, -1, 0, 0])); + Read(202, 5, w => Grid(w, "Mixed", 200, 8, + [-Math.PI / 2, -1, 0, 1, 10, 10, 5, 1, 0, 0, 0, 1, 0, 0, 0, 1, 10])); + Read(203, 5, w => Grid(w, "Mixed", 200, 7, [0, -1, 10, 1, 26, 18, 5, -.6, -.8, 0])); + Read(200, 9, w => Chain(w, "Mixed", [(2, 203), (0, 201), (1, 202)])); + Read(300, 9, w => Chain(w, "Incomplete", [(0, 301), (1, 302)])); + Read(301, 5, w => Grid(w, "Incomplete", 300, 7, [0, -1, 10, 1, 10, 0, 0, -1, 0, 0])); + + var (paths, members) = reader.Build(); + Assert.Equal(new[] { 201, 202, 203, 301, 302 }, members.Order()); + var info = new RevitFileInfo + { + CurvedGridAxes = paths, + GridChainMemberIds = members, + Elements = [LineElement(201, "Mixed"), LineElement(301, "Incomplete"), LineElement(400, "Straight")], + }; + var scene = RvtSceneReader.Read(RvtDocument.FromInfo(info), new MeshSet(), new RvtSceneOptions { ModelKey = "grid.rvt" }).Document; + var grid = Assert.Single(SceneJson.Read(SceneJson.Write(scene)).Grids); + Assert.Equal("Straight", Assert.Single(grid.Lines).Name); + Assert.Collection(grid.Paths!, + arc => + { + Assert.Equal("Arc", arc.Name); + CheckPoint(arc.Points[0], -30, -30); + CheckPoint(arc.Points[^1], -36, -24); + Assert.Contains(arc.Points, point => point.X < -41 * Foot); + CheckChordError(arc.Points, new(-36 * Foot, -30 * Foot, 0), 6 * Foot); + }, + mixed => + { + Assert.Equal("Mixed", mixed.Name); + CheckPoint(mixed.Points[0], 0, 0); + CheckPoint(mixed.Points[1], 10, 0); + CheckPoint(mixed.Points[^2], 20, 10); + CheckPoint(mixed.Points[^1], 26, 18); + CheckChordError(mixed.Points.GetRange(1, mixed.Points.Count - 2), new(10 * Foot, 10 * Foot, 0), 10 * Foot); + Assert.Equal(mixed.Points.Count, mixed.Points.Distinct().Count()); + }); + + void Id(BinaryWriter w, int id) + { + if (wide) w.Write((long)id); + else w.Write(id); + } + + void Read(int id, ushort type, Action payload) + { + using var bytes = new MemoryStream(); + using var writer = new BinaryWriter(bytes); + writer.Write(type); + Id(writer, id); + payload(writer); + reader.Read((uint)id, bytes.ToArray(), 0, (int)bytes.Length, type); + } + + void Grid(BinaryWriter w, string name, int owner, ushort surface, double[] values) + { + Text(w, name); + // The same surface class occurs twice. Only the queue entry owned by m_pSurface is the datum. + Pointer(w, surface); + Pointer(w, surface); + Pointer(w, owner == 0 ? (ushort)0 : (ushort)11); + foreach (double value in values) w.Write(0.0); + foreach (double value in values) w.Write(value); + if (owner != 0) Id(w, owner); + } + + void Chain(BinaryWriter w, string label, (int Tag, int Member)[] entries) + { + Text(w, label); + w.Write(entries.Length); + foreach (var (tag, member) in entries) + { + w.Write(tag); + Id(w, member); + } + } + } + + private static Element LineElement(int id, string name) => new() + { + Id = id, Name = name, CategoryId = -2000220, + Location = new LocationCurve { StartPoint = [0, 0, 0], EndPoint = [1, 0, 0] }, + }; + + private static void CheckPoint(Vector3d point, double x, double y) + { + Assert.Equal(x * Foot, point.X, 10); + Assert.Equal(y * Foot, point.Y, 10); + Assert.Equal(0, point.Z); + } + + private static void CheckChordError(List points, Vector3d center, double radius) + { + Assert.True(points.Count > 3); + for (int i = 1; i < points.Count; i++) + { + Assert.Equal(radius, (points[i] - center).Length, 9); + double sagitta = radius - ((points[i - 1] + points[i]) * .5 - center).Length; + Assert.InRange(sagitta, 0, .001); + } + } + + private static void Text(BinaryWriter writer, string text) + { + writer.Write(text.Length); + writer.Write(Encoding.Unicode.GetBytes(text)); + } + + private static void Pointer(BinaryWriter writer, ushort type) + { + writer.Write(type == 0 ? 0u : uint.MaxValue); + if (type != 0) writer.Write(type); + } + + private static SchemaDocument GridSchema(bool wide) + { + static SchemaField F(string name, byte type, byte mods = 0, int? count = null, int? target = null, List? args = null) => + new(name, type, mods, 0, count, target, null, args); + static SchemaClass C(int id, string name, int parent = 0, params SchemaField[] fields) => + new(id, name, parent, 0, fields.ToList(), []); + return new SchemaDocument + { + Classes = + [ + C(1, "Identifier", 0, F("m_id", wide ? (byte)11 : (byte)4)), + C(2, "ElementId", 1), + C(3, "Element", 0, F("m_id", 14, target: 2)), + C(4, "DatumPlane", 3, F("m_text", 8, 96), F("m_pFace", 14, 1), F("m_pSurface", 14, 1)), + C(5, "Grid", 4, F("m_pGridChainMembershipCell", 14, 1)), + C(6, "Envelope", 0, F("m_corners", 13, 16, 2, args: [F("", 7, 16, 2)])), + C(7, "Plane", 6, F("m_origin", 7, 16, 3), F("m_xVec", 7, 16, 3)), + C(8, "CylSurf", 6, F("m_center", 7, 16, 3), F("m_xVec", 7, 16, 3), F("m_yVec", 7, 16, 3), + F("m_zVec", 7, 16, 3), F("m_radius", 7)), + C(9, "GridChain", 3, F("commonText", 8, 96), F("m_curveTagToGridsInChain", 14, 80, target: 10)), + C(10, "std::pair< int, ElementId >", 0, F("first", 4), F("second", 14, target: 2)), + C(11, "GridChainMembershipCell", 0, F("m_gridChainId", 14, target: 2)), + ], + }; + } +} From 8156efeba290559700b44a2c0ae0471de868655d Mon Sep 17 00:00:00 2001 From: mahach666 <79989386+mahach666@users.noreply.github.com> Date: Thu, 19 Nov 2026 13:20:10 +0300 Subject: [PATCH 023/259] Add an optional RVT to NWC preview tool --- CHANGELOG.md | 3 + Directory.Packages.props | 5 + README.md | 2 + RvtIO.slnx | 3 + docs/rvt-to-nwc.md | 24 ++++ tests/RvtIO.Tests/NwcExportTests.cs | 104 +++++++++++++++++ tests/RvtIO.Tests/RvtIO.Tests.csproj | 1 + tools/RvtIO.Nwc/NwcExport.cs | 168 +++++++++++++++++++++++++++ tools/RvtIO.Nwc/Program.cs | 51 ++++++++ tools/RvtIO.Nwc/RvtIO.Nwc.csproj | 16 +++ 10 files changed, 377 insertions(+) create mode 100644 docs/rvt-to-nwc.md create mode 100644 tests/RvtIO.Tests/NwcExportTests.cs create mode 100644 tools/RvtIO.Nwc/NwcExport.cs create mode 100644 tools/RvtIO.Nwc/Program.cs create mode 100644 tools/RvtIO.Nwc/RvtIO.Nwc.csproj diff --git a/CHANGELOG.md b/CHANGELOG.md index 930a3c9f..79156ac8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,9 @@ API between minor releases. ## [Unreleased] +The optional [RvtIO.Nwc tool](docs/rvt-to-nwc.md) exports Revit project geometry and element properties to NWC +using the NwcIO writer layout. + ### Added - `RvtIO.Scene` exports decoded straight Revit grid axes and their labels in scene coordinates. diff --git a/Directory.Packages.props b/Directory.Packages.props index cdadd7e1..8f98506b 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -15,6 +15,11 @@ + + + + + diff --git a/README.md b/README.md index d1ab3c91..112507ab 100644 --- a/README.md +++ b/README.md @@ -35,6 +35,8 @@ dotnet add package RvtIO `RvtIO.Scene` (a separate package released with RvtIO) turns a Revit project into an `IOScene` scene document for viewers; see the [scene adapter](docs/scene.md) for usage and limits. +The optional [RvtIO.Nwc tool](docs/rvt-to-nwc.md) exports Revit projects to the cache layout written by NwcIO. + The library targets .NET 8 and .NET 10. It uses managed code without native dependencies or Windows-only APIs and is tested on Windows, Linux and macOS. ## Command line diff --git a/RvtIO.slnx b/RvtIO.slnx index fab0412a..8634a4f5 100644 --- a/RvtIO.slnx +++ b/RvtIO.slnx @@ -4,5 +4,8 @@ + + + diff --git a/docs/rvt-to-nwc.md b/docs/rvt-to-nwc.md new file mode 100644 index 00000000..4ce96ef0 --- /dev/null +++ b/docs/rvt-to-nwc.md @@ -0,0 +1,24 @@ +# RVT to NWC preview + +The optional `RvtIO.Nwc` tool uses `RvtIO.Scene` and the NwcIO writer. Run it from the repository with +the SDK in `global.json` and either supported .NET runtime. + +```sh +dotnet run --project tools/RvtIO.Nwc -c Release -f net10.0 -- model.rvt model.nwc +nwcio model.nwc model.json +``` + +The tool writes placed triangle meshes in metres, with one mesh per scene instance. It applies rotation, +scale and reflection to the local vertices, corrects reflected triangle winding, and keeps the translation +separate from the float32 vertex buffer. The cache includes the element tree and available storeys, Revit +element IDs and UniqueIds, IFC GlobalIds, and instance and type parameter display text. Mesh names include +the Revit element ID so that meshes can be matched to the element tree. + +The cache marks its coordinates as metres and records mesh ownership in the writer metadata. A build of +NwcIO with linked-cache support can open it and export the placed geometry and property tabs with +`nwcio model.nwc --scene model.scene.json`. NwcIO 0.14 can inspect the raw meshes and element tree via +its JSON export. Autodesk Navisworks import is unverified. The cache layout omits materials, normals and +line geometry. + +Use a new output path. Reader errors, an empty model, or geometry that the writer rejects stop the export. +Reader warnings are printed to standard error. The tool moves the completed cache into place after writing. diff --git a/tests/RvtIO.Tests/NwcExportTests.cs b/tests/RvtIO.Tests/NwcExportTests.cs new file mode 100644 index 00000000..56201ee8 --- /dev/null +++ b/tests/RvtIO.Tests/NwcExportTests.cs @@ -0,0 +1,104 @@ +using IOScene; +using NwcIO; +using NwcIO.Model; +using RvtIO.Nwc; +using Xunit; +using NwcVector = NwcIO.Model.Vector3d; + +namespace RvtIO.Tests; + +public class NwcExportTests +{ + [Fact] + public void RoundTripKeepsPlacedTrianglesAndRevitProperties() + { + var scene = new SceneDocument(); + scene.Models.Add(new() { Id = 1, Key = "test" }); + scene.Levels.Add(new() { Id = 90, ModelId = 1, Name = "First floor", Elevation = 3 }); + scene.Elements.Add(new() + { + Id = 42, ModelId = 1, LevelId = 90, Name = "Wall", Category = "Walls", + SourceId = "revit-id", PropertySetIds = [1], + }); + scene.PropertySets.Add(new() + { + Id = 1, Name = "Instance", + Properties = [new() { Name = "Fire rating", Value = SceneValue.FromText("EI 60") }], + }); + scene.Geometries.Add(new() { Id = 1, Vertices = [new(0.25, 0, 0), new(1, 0, 0), new(0, 1, 0)] }); + scene.Instances.Add(new() + { + ElementId = 42, GeometryId = 1, + Transform = new(new(-2, 0, 0), new(0, 1, 0), new(0, 0, 1), new(10_000_000.125, 3, 4)), + }); + scene.Instances.Add(new() { ElementId = 42, GeometryId = 1 }); + + var directory = Directory.CreateTempSubdirectory(); + try + { + string path = Path.Combine(directory.FullName, "model.nwc"); + var timestamp = new DateTime(2026, 1, 1, 0, 0, 0, DateTimeKind.Utc); + NwcExport.Save(NwcExport.Build(scene, "model.rvt", 1024, timestamp), path); + + var reopened = NwcDocument.Open(path, new() { Strict = true, LengthUnit = NwcLengthUnit.Meters }); + Assert.Equal("model.rvt", reopened.FileInfo.SourcePath); + Assert.Equal(1024L, reopened.FileInfo.SourceByteSize); + Assert.Equal(timestamp, reopened.FileInfo.SourceTimestampUtc); + Assert.Contains("IOExtend.NwcWriter.Scene/1", reopened.FileInfo.Options); + Assert.Equal(2, reopened.Meshes.Count); + Assert.All(reopened.Meshes, mesh => Assert.Equal("Wall [RVT 42]", mesh.Name)); + Assert.Equal(new[] { 0, 2, 1 }, reopened.Meshes[0].Indices); + Assert.Equal(new NwcVector(9_999_999.625, 3, 4), reopened.Meshes[0].GetWorldVertices()[0]); + Assert.Equal(new[] { 0, 1, 2 }, reopened.Meshes[1].Indices); + Assert.Equal(new NwcVector(0.25, 0, 0), reopened.Meshes[1].GetWorldVertices()[0]); + Assert.DoesNotContain(reopened.Diagnostics, diagnostic => diagnostic.Code is "meshes-skipped" or "property-scan-failed"); + + var level = Assert.Single(reopened.RootNode!.Children); + Assert.Equal("First floor", level.Name); + Assert.Null(level.Transform); + var element = Assert.Single(level.Children); + Assert.Null(element.Transform); + Assert.Contains(element.Properties, p => p.Name == "Element ID" && p.Value == "42"); + Assert.Contains(element.Properties, p => p.Name == "UniqueId" && p.Value == "revit-id"); + Assert.Contains(element.Properties, p => p.Name == "Fire rating" && p.Value == "EI 60"); + Assert.Equal(new long?[] { 1, 2 }, element.Properties + .Where(p => p.Class == "IOExtend.NwcWriter.Link" && p.Name == "Mesh ID") + .Select(p => p.IntValue)); + } + finally + { + directory.Delete(recursive: true); + } + } + + [Fact] + public void BuildRejectsNamesBeyondTheNwcReadersUtf8Limit() + { + var scene = new SceneDocument(); + scene.AddMesh(new string('é', 32_769), [new(0, 0, 0), new(1, 0, 0), new(0, 1, 0)], [0, 1, 2]); + var error = Assert.Throws(() => + NwcExport.Build(scene, "model.rvt", 0, DateTime.UnixEpoch)); + Assert.Contains("65536", error.Message); + } + + [Fact] + public void SaveFailurePreservesTheDestinationAndRemovesTheTemporaryFile() + { + var directory = Directory.CreateTempSubdirectory(); + try + { + string path = Path.Combine(directory.FullName, "existing.nwc"); + File.WriteAllText(path, "original"); + Assert.ThrowsAny(() => NwcExport.Save(new NwcDocumentBuilder().Build(), path)); + Assert.Equal("original", File.ReadAllText(path)); + + var invalid = new NwcDocumentBuilder().AddMesh(new NwcMesh { Id = 1, Vertices = [], Indices = [] }).Build(); + Assert.Throws(() => NwcExport.Save(invalid, Path.Combine(directory.FullName, "invalid.nwc"))); + Assert.Equal(path, Assert.Single(Directory.GetFiles(directory.FullName))); + } + finally + { + directory.Delete(recursive: true); + } + } +} diff --git a/tests/RvtIO.Tests/RvtIO.Tests.csproj b/tests/RvtIO.Tests/RvtIO.Tests.csproj index cb1a4804..ff2d88d3 100644 --- a/tests/RvtIO.Tests/RvtIO.Tests.csproj +++ b/tests/RvtIO.Tests/RvtIO.Tests.csproj @@ -24,6 +24,7 @@ + diff --git a/tools/RvtIO.Nwc/NwcExport.cs b/tools/RvtIO.Nwc/NwcExport.cs new file mode 100644 index 00000000..b9dc90f9 --- /dev/null +++ b/tools/RvtIO.Nwc/NwcExport.cs @@ -0,0 +1,168 @@ +using System.Globalization; +using System.Text; +using IOScene; +using NwcIO; +using NwcIO.Model; +using NwcVector = NwcIO.Model.Vector3d; +using SceneVector = IOScene.Vector3d; + +namespace RvtIO.Nwc; + +internal static class NwcExport +{ + // The optional metadata is written by NwcIO 0.14 and interpreted by the linked-cache reader. + private const string MetreCacheOption = "IOExtend.NwcWriter.Scene/1"; + private const string LinkClass = "IOExtend.NwcWriter.Link"; + internal static NwcDocument Build(SceneDocument scene, string sourceName, long sourceLength, DateTime timestamp) + { + if (scene.Validate().FirstOrDefault(d => d.Severity == SceneSeverity.Error) is { } error) + throw new InvalidDataException(error.Message); + if (scene.Instances.Count == 0) + throw new InvalidDataException("The model has no triangle geometry to export."); + + var root = new NwcNode { Id = 0, Name = sourceName, Class = "Model" }; + int nextNodeId = 1; + var levels = new Dictionary(); + foreach (var level in scene.Levels) + { + var node = AddNode(root, nextNodeId++, level.Name, "RvtIO.Level"); + if (level.Elevation is double elevation) + AddText(node, "Revit", "Elevation (m)", elevation.ToString("R", CultureInfo.InvariantCulture)); + levels.Add(level.Id, node); + } + + var nodes = new Dictionary(scene.Elements.Count); + var propertySets = scene.PropertySets.ToDictionary(set => set.Id); + foreach (var element in scene.Elements) + { + string id = element.Id.ToString(CultureInfo.InvariantCulture); + var parent = element.LevelId is int levelId ? levels[levelId] : root; + var node = AddNode(parent, nextNodeId++, element.Name, "RvtIO.Element"); + nodes.Add(element.Id, node); + + AddText(node, "Revit", "Element ID", id); + AddText(node, "Revit", "UniqueId", element.SourceId); + AddText(node, "Revit", "IFC GlobalId", element.IfcGuid); + AddText(node, "Revit", "Category", element.Category); + AddText(node, "Revit", "Type", element.TypeName); + foreach (int setId in element.PropertySetIds) + { + var set = propertySets[setId]; + foreach (var property in set.Properties) + AddText(node, $"Revit {set.Name} Property", property.Name, property.Value.Text); + } + } + + var geometries = scene.Geometries.ToDictionary(geometry => geometry.Id); + var meshes = new List(scene.Instances.Count); + foreach (var instance in scene.Instances) + { + var geometry = geometries[instance.GeometryId]; + if (geometry.Topology != SceneTopology.Triangles || geometry.Vertices.Count < 3) + throw new InvalidDataException($"Geometry {geometry.Id} is not a triangle mesh."); + + var transform = instance.Transform ?? Transform3d.Identity; + var linear = new Transform3d(transform.XAxis, transform.YAxis, transform.ZAxis, SceneVector.Zero); + var vertices = geometry.Vertices.Select(point => ToNwc(linear.Apply(point))).ToArray(); + var indices = geometry.Indices.Count == 0 + ? Enumerable.Range(0, vertices.Length).ToArray() + : geometry.Indices.ToArray(); + if (SceneVector.Dot(transform.XAxis, SceneVector.Cross(transform.YAxis, transform.ZAxis)) < 0) + { + for (int i = 0; i < indices.Length; i += 3) + (indices[i + 1], indices[i + 2]) = (indices[i + 2], indices[i + 1]); + } + + int meshId = meshes.Count + 1; + var node = nodes[instance.ElementId]; + node.Properties.Add(new NwcPropertyRecord + { + FirstInt = node.Id, Tag = 52, Name = "Mesh ID", Class = LinkClass, ValueType = 2, IntValue = meshId, + }); + meshes.Add(new NwcMesh + { + Id = meshId, + Name = string.Create(CultureInfo.InvariantCulture, $"{node.Name} [RVT {instance.ElementId}]"), + Vertices = vertices, + Indices = indices, + // The read-back tree also looks for transforms by node ID. + Transform = new NwcTransform { Id = nextNodeId++, Translation = ToNwc(transform.Translation) }, + }); + } + + return NwcDocument.Create( + fileInfo: new NwcFileInfo + { + SourcePath = sourceName, + SourceByteSize = sourceLength, + SourceTimestampUtc = timestamp, + LoaderPlugin = "LcOpRvtIONwc", + LengthUnit = NwcLengthUnit.Meters, + Options = [MetreCacheOption], + }, + meshes: meshes, + rootNode: root); + } + + internal static void Save(NwcDocument cache, string path) + { + string destination = Path.GetFullPath(path); + string temporary = Path.Combine(Path.GetDirectoryName(destination)!, $"rvtio-nwc-{Guid.NewGuid():N}.tmp"); + var stream = new FileStream(temporary, FileMode.CreateNew, FileAccess.Write, FileShare.None); + bool moved = false; + try + { + using (stream) + NwcWriter.Write(cache, stream); + File.Move(temporary, destination); + moved = true; + } + finally + { + if (!moved) + File.Delete(temporary); + } + } + + private static NwcVector ToNwc(SceneVector point) => new(point.X, point.Y, point.Z); + + private static NwcNode AddNode(NwcNode parent, int id, string name, string type) + { + ValidateString(name, id); + var node = new NwcNode + { + Id = id, + Name = string.IsNullOrWhiteSpace(name) ? type : name, + Class = type, + Parent = parent, + }; + parent.Children.Add(node); + return node; + } + + private static void AddText(NwcNode node, string group, string name, string? text) + { + if (string.IsNullOrEmpty(name) || text is null) + return; + + ValidateString(group, node.Id); + ValidateString(name, node.Id); + ValidateString(text, node.Id); + node.Properties.Add(new NwcPropertyRecord + { + FirstInt = node.Id, + Tag = 52, + Name = name, + Class = group, + ValueType = 4, + Value = text, + }); + } + + private static void ValidateString(string text, int nodeId) + { + const int maxBytes = 65_536; // NwcIO's property record scanner limit. + if (Encoding.UTF8.GetByteCount(text) > maxBytes) + throw new InvalidDataException($"Node {nodeId} has a name or property that exceeds the NWC reader's {maxBytes}-byte limit."); + } +} diff --git a/tools/RvtIO.Nwc/Program.cs b/tools/RvtIO.Nwc/Program.cs new file mode 100644 index 00000000..6f164ddf --- /dev/null +++ b/tools/RvtIO.Nwc/Program.cs @@ -0,0 +1,51 @@ +using IOScene; +using RvtIO.Scene; + +namespace RvtIO.Nwc; + +internal static class Program +{ + private const string Usage = "Usage: RvtIO.Nwc "; + + public static int Main(string[] args) + { + if (args is ["--help"] or ["-h"]) + { + Console.Out.WriteLine(Usage); + return 0; + } + + if (args is not [var input, var output] || + !string.Equals(Path.GetExtension(input), ".rvt", StringComparison.OrdinalIgnoreCase) || + !string.Equals(Path.GetExtension(output), ".nwc", StringComparison.OrdinalIgnoreCase)) + { + Console.Error.WriteLine(Usage); + return 1; + } + + try + { + if (File.Exists(output)) + throw new IOException($"The output file already exists: '{output}'."); + + var source = new FileInfo(input); + long length = source.Length; + var scene = RvtSceneReader.Read(input); + foreach (var diagnostic in scene.Diagnostics.Where(d => d.Severity != SceneSeverity.Info)) + Console.Error.WriteLine($"RVT {diagnostic.Severity} [{diagnostic.Code}]: {diagnostic.Message}"); + if (scene.Diagnostics.Any(d => d.Severity == SceneSeverity.Error)) + return 2; + + var cache = NwcExport.Build(scene.Document, source.Name, length, source.LastWriteTimeUtc); + NwcExport.Save(cache, output); + Console.Out.WriteLine($"Exported {cache.Meshes.Count} triangle meshes to '{output}'."); + return 0; + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException or + InvalidDataException or NotSupportedException or RvtInputException or RvtLimitException) + { + Console.Error.WriteLine(ex.Message); + return 2; + } + } +} diff --git a/tools/RvtIO.Nwc/RvtIO.Nwc.csproj b/tools/RvtIO.Nwc/RvtIO.Nwc.csproj new file mode 100644 index 00000000..7f7db290 --- /dev/null +++ b/tools/RvtIO.Nwc/RvtIO.Nwc.csproj @@ -0,0 +1,16 @@ + + + + Exe + net8.0;net10.0 + false + true + + + + + + + + + From e3af92089141557346e41b4a21474621a84ea8e4 Mon Sep 17 00:00:00 2001 From: mahach666 <79989386+mahach666@users.noreply.github.com> Date: Thu, 19 Nov 2026 13:20:36 +0300 Subject: [PATCH 024/259] Specify coordinates and JSON inspection in the preview guide --- docs/rvt-to-nwc.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/docs/rvt-to-nwc.md b/docs/rvt-to-nwc.md index 4ce96ef0..b7367dfe 100644 --- a/docs/rvt-to-nwc.md +++ b/docs/rvt-to-nwc.md @@ -8,7 +8,8 @@ dotnet run --project tools/RvtIO.Nwc -c Release -f net10.0 -- model.rvt model.nw nwcio model.nwc model.json ``` -The tool writes placed triangle meshes in metres, with one mesh per scene instance. It applies rotation, +The tool writes placed triangle meshes in metres in the internal model coordinates, Z up, with one +mesh per scene instance. It applies rotation, scale and reflection to the local vertices, corrects reflected triangle winding, and keeps the translation separate from the float32 vertex buffer. The cache includes the element tree and available storeys, Revit element IDs and UniqueIds, IFC GlobalIds, and instance and type parameter display text. Mesh names include @@ -16,7 +17,7 @@ the Revit element ID so that meshes can be matched to the element tree. The cache marks its coordinates as metres and records mesh ownership in the writer metadata. A build of NwcIO with linked-cache support can open it and export the placed geometry and property tabs with -`nwcio model.nwc --scene model.scene.json`. NwcIO 0.14 can inspect the raw meshes and element tree via +`nwcio model.nwc --scene model.scene.json`. NwcIO 0.14 can inspect the mesh summaries and element tree via its JSON export. Autodesk Navisworks import is unverified. The cache layout omits materials, normals and line geometry. From 06d40e11f8e7b0aaa0a83207c3e990e89afd369e Mon Sep 17 00:00:00 2001 From: mie <79989386+mahach666@users.noreply.github.com> Date: Thu, 19 Nov 2026 15:02:59 +0300 Subject: [PATCH 025/259] Prepare RvtIO 0.5.1 release --- CHANGELOG.md | 2 ++ Directory.Build.props | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a1db4993..ca38bbc8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,8 @@ API between minor releases. ## [Unreleased] +## [0.5.1] - 2026-11-19 + The optional [RvtIO.Nwc tool](docs/rvt-to-nwc.md) exports Revit project geometry and element properties to NWC using the NwcIO writer layout. diff --git a/Directory.Build.props b/Directory.Build.props index 59181be8..c2f206cb 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -6,7 +6,7 @@ enable true true - 0.5.0 + 0.5.1 true true snupkg From 8853ed4b7d27a4f18fad6f3c24d27f9901acf600 Mon Sep 17 00:00:00 2001 From: mahach666 <79989386+mahach666@users.noreply.github.com> Date: Thu, 19 Nov 2026 15:39:07 +0300 Subject: [PATCH 026/259] Add an opt-in Navisworks cache export to RvtIO.Nwc --- README.md | 2 +- docs/rvt-to-nwc.md | 21 ++++++- tests/RvtIO.Tests/NwcExportTests.cs | 37 ++++++++++++ tools/RvtIO.Nwc/NavisworksExport.cs | 91 +++++++++++++++++++++++++++++ tools/RvtIO.Nwc/Program.cs | 16 ++++- 5 files changed, 163 insertions(+), 4 deletions(-) create mode 100644 tools/RvtIO.Nwc/NavisworksExport.cs diff --git a/README.md b/README.md index 112507ab..2dd3f38b 100644 --- a/README.md +++ b/README.md @@ -35,7 +35,7 @@ dotnet add package RvtIO `RvtIO.Scene` (a separate package released with RvtIO) turns a Revit project into an `IOScene` scene document for viewers; see the [scene adapter](docs/scene.md) for usage and limits. -The optional [RvtIO.Nwc tool](docs/rvt-to-nwc.md) exports Revit projects to the cache layout written by NwcIO. +The optional [RvtIO.Nwc tool](docs/rvt-to-nwc.md) exports Revit projects to NWC using Autodesk Navisworks on Windows or writes a preview cache for NwcIO. The library targets .NET 8 and .NET 10. It uses managed code without native dependencies or Windows-only APIs and is tested on Windows, Linux and macOS. diff --git a/docs/rvt-to-nwc.md b/docs/rvt-to-nwc.md index b7367dfe..d9288408 100644 --- a/docs/rvt-to-nwc.md +++ b/docs/rvt-to-nwc.md @@ -1,4 +1,21 @@ -# RVT to NWC preview +# RVT to NWC + +## Autodesk Navisworks + +On Windows, pass the installed Navisworks Manage or Simulate executable to export a cache for Navisworks. + +```powershell +dotnet run --project tools/RvtIO.Nwc -c Release -f net10.0 -- model.rvt model.nwc --navisworks "C:\Program Files\Autodesk\Navisworks Manage 2027\Roamer.exe" +``` + +RvtIO reads the RVT and exports a temporary IFC using its current IFC profile and Revit property sets. +Navisworks creates the NWC and opens it before the tool moves it to the requested path. +The cache's geometry and selection tree follow Navisworks' IFC import. The command requires a working +Navisworks installation. Tested with Navisworks Manage 2027. + +Autodesk documents the [command-line switches](https://help.autodesk.com/cloudhelp/2022/ENU/Navisworks/files/GUID-3891FB9F-7BF1-4510-A1EE-121E975C0ACE.htm) used to create and open the cache. + +## NwcIO preview The optional `RvtIO.Nwc` tool uses `RvtIO.Scene` and the NwcIO writer. Run it from the repository with the SDK in `global.json` and either supported .NET runtime. @@ -18,7 +35,7 @@ the Revit element ID so that meshes can be matched to the element tree. The cache marks its coordinates as metres and records mesh ownership in the writer metadata. A build of NwcIO with linked-cache support can open it and export the placed geometry and property tabs with `nwcio model.nwc --scene model.scene.json`. NwcIO 0.14 can inspect the mesh summaries and element tree via -its JSON export. Autodesk Navisworks import is unverified. The cache layout omits materials, normals and +its JSON export. This preview layout is for NwcIO. The cache layout omits materials, normals and line geometry. Use a new output path. Reader errors, an empty model, or geometry that the writer rejects stop the export. diff --git a/tests/RvtIO.Tests/NwcExportTests.cs b/tests/RvtIO.Tests/NwcExportTests.cs index 56201ee8..2cb6574e 100644 --- a/tests/RvtIO.Tests/NwcExportTests.cs +++ b/tests/RvtIO.Tests/NwcExportTests.cs @@ -9,6 +9,43 @@ namespace RvtIO.Tests; public class NwcExportTests { + [Fact] + public void NavisworksCommandOpensTheExactCacheItCreates() + { + string directory = Path.GetFullPath(Path.GetTempPath()); + string executable = Path.Combine(directory, "Navisworks Manage", "Roamer.exe"); + string ifc = Path.Combine(directory, "sample model.ifc"); + string cache = Path.ChangeExtension(ifc, ".nwc"); + string log = Path.Combine(directory, "native trace.log"); + + var command = NavisworksExport.CreateStartInfo(executable, ifc, cache, log); + + Assert.False(command.UseShellExecute); + Assert.Equal(executable, command.FileName); + Assert.Equal(Path.GetDirectoryName(executable), command.WorkingDirectory); + Assert.Equal(new[] { "-NoGui", "-log", log, "-CreateCache", ifc, "-OpenFile", cache, "-Exit" }, + command.ArgumentList); + } + + [Fact] + public void NavisworksModeRejectsAnExistingDestinationBeforeStartingTheApplication() + { + var directory = Directory.CreateTempSubdirectory(); + try + { + string path = Path.Combine(directory.FullName, "existing.nwc"); + File.WriteAllText(path, "original"); + + Assert.Equal(2, global::RvtIO.Nwc.Program.Main(["missing.rvt", path, "--navisworks", "missing.exe"])); + Assert.Equal("original", File.ReadAllText(path)); + Assert.Equal(path, Assert.Single(Directory.GetFiles(directory.FullName))); + } + finally + { + directory.Delete(recursive: true); + } + } + [Fact] public void RoundTripKeepsPlacedTrianglesAndRevitProperties() { diff --git a/tools/RvtIO.Nwc/NavisworksExport.cs b/tools/RvtIO.Nwc/NavisworksExport.cs new file mode 100644 index 00000000..baddc04c --- /dev/null +++ b/tools/RvtIO.Nwc/NavisworksExport.cs @@ -0,0 +1,91 @@ +using System.ComponentModel; +using System.Diagnostics; +using RvtIO.Ifc; + +namespace RvtIO.Nwc; + +internal static class NavisworksExport +{ + internal static void Save(string input, string output, string navisworks) + { + if (!OperatingSystem.IsWindows()) + throw new PlatformNotSupportedException("The --navisworks export requires Autodesk Navisworks on Windows."); + + string executable = Path.GetFullPath(navisworks); + if (!string.Equals(Path.GetFileName(executable), "Roamer.exe", StringComparison.OrdinalIgnoreCase) || + !File.Exists(executable)) + throw new FileNotFoundException("Pass the installed Navisworks Manage or Simulate Roamer.exe to --navisworks.", executable); + + string destination = Path.GetFullPath(output); + string directory = Path.GetDirectoryName(destination)!; + if (!Directory.Exists(directory)) + throw new DirectoryNotFoundException($"The output directory does not exist: '{directory}'."); + + string staging = Path.Combine(directory, $"rvtio-nwc-{Guid.NewGuid():N}"); + string ifcPath = Path.Combine(staging, Path.GetFileNameWithoutExtension(input) + ".ifc"); + string cachePath = Path.ChangeExtension(ifcPath, ".nwc"); + string logPath = Path.Combine(staging, "navisworks.log"); + + var diagnostic = new RvtReadDiagnostics(); + var reader = new RvtFileReader(new RvtReaderOptions + { + R22Layout = true, + SystemFamilyNameLocale = "ENU", + SeparateFacesWithDistinctOpenings = true, + Diagnostics = diagnostic, + }); + var model = reader.Read(input); + if (diagnostic.LimitHits.Count != 0 || diagnostic.Streams.Any(stream => stream.Failed != 0)) + throw new InvalidDataException("The RVT read was incomplete. Nothing was exported."); + + Directory.CreateDirectory(staging); + try + { + var exporter = new IfcExporter(Console.Error, includeRevitPropertySets: true); + exporter.Export(model, ifcPath); + if (exporter.ExportedProducts == 0) + throw new InvalidDataException("The RVT has no IFC products to convert."); + + using var process = Process.Start(CreateStartInfo(executable, ifcPath, cachePath, logPath)) + ?? throw new IOException("Could not start Autodesk Navisworks."); + process.WaitForExit(); + + if (process.ExitCode != 0 || !File.Exists(cachePath)) + { + string? detail = File.Exists(logPath) + ? File.ReadLines(logPath).LastOrDefault(line => line.Contains("exception_message:", StringComparison.Ordinal)) + : null; + throw new IOException($"Navisworks failed to create or open the NWC (exit {process.ExitCode}). {detail}".TrimEnd()); + } + + File.Move(cachePath, destination); + } + catch (Win32Exception ex) + { + throw new IOException($"Could not run Autodesk Navisworks. {ex.Message}", ex); + } + finally + { + try + { + Directory.Delete(staging, recursive: true); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + Console.Error.WriteLine($"Could not remove the temporary export directory '{staging}'. {ex.Message}"); + } + } + } + + internal static ProcessStartInfo CreateStartInfo(string executable, string ifc, string cache, string log) + { + var info = new ProcessStartInfo(executable) + { + UseShellExecute = false, + WorkingDirectory = Path.GetDirectoryName(executable)!, + }; + foreach (string argument in new[] { "-NoGui", "-log", log, "-CreateCache", ifc, "-OpenFile", cache, "-Exit" }) + info.ArgumentList.Add(argument); + return info; + } +} diff --git a/tools/RvtIO.Nwc/Program.cs b/tools/RvtIO.Nwc/Program.cs index 6f164ddf..d2372eb0 100644 --- a/tools/RvtIO.Nwc/Program.cs +++ b/tools/RvtIO.Nwc/Program.cs @@ -5,7 +5,7 @@ namespace RvtIO.Nwc; internal static class Program { - private const string Usage = "Usage: RvtIO.Nwc "; + private const string Usage = "Usage: RvtIO.Nwc [--navisworks ]"; public static int Main(string[] args) { @@ -15,6 +15,13 @@ public static int Main(string[] args) return 0; } + string? navisworks = null; + if (args is [_, _, "--navisworks", var executable]) + { + navisworks = executable; + args = args[..2]; + } + if (args is not [var input, var output] || !string.Equals(Path.GetExtension(input), ".rvt", StringComparison.OrdinalIgnoreCase) || !string.Equals(Path.GetExtension(output), ".nwc", StringComparison.OrdinalIgnoreCase)) @@ -28,6 +35,13 @@ public static int Main(string[] args) if (File.Exists(output)) throw new IOException($"The output file already exists: '{output}'."); + if (navisworks is not null) + { + NavisworksExport.Save(input, output, navisworks); + Console.Out.WriteLine($"Exported '{output}' with Autodesk Navisworks."); + return 0; + } + var source = new FileInfo(input); long length = source.Length; var scene = RvtSceneReader.Read(input); From 5d852f4828a52806b36b97eb8c2f3aa25e36ecf3 Mon Sep 17 00:00:00 2001 From: mahach666 <79989386+mahach666@users.noreply.github.com> Date: Thu, 19 Nov 2026 15:41:55 +0300 Subject: [PATCH 027/259] Document the managed reader limit for Navisworks 2027 IFC caches --- docs/rvt-to-nwc.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/rvt-to-nwc.md b/docs/rvt-to-nwc.md index d9288408..5b4d490d 100644 --- a/docs/rvt-to-nwc.md +++ b/docs/rvt-to-nwc.md @@ -12,6 +12,7 @@ RvtIO reads the RVT and exports a temporary IFC using its current IFC profile an Navisworks creates the NWC and opens it before the tool moves it to the requested path. The cache's geometry and selection tree follow Navisworks' IFC import. The command requires a working Navisworks installation. Tested with Navisworks Manage 2027. +The tested 2027 cache uses an IFC property record layout that NwcIO's managed reader does not yet support. Autodesk documents the [command-line switches](https://help.autodesk.com/cloudhelp/2022/ENU/Navisworks/files/GUID-3891FB9F-7BF1-4510-A1EE-121E975C0ACE.htm) used to create and open the cache. From 99e357149bdb890e7fd76648e26f81824e10515f Mon Sep 17 00:00:00 2001 From: mie <79989386+mahach666@users.noreply.github.com> Date: Thu, 19 Nov 2026 15:58:47 +0300 Subject: [PATCH 028/259] Report element IDs outside the public Int32 range --- CHANGELOG.md | 5 +++ docs/export-report.md | 9 +++-- src/RvtIO.Cli/ExportCommand.cs | 2 +- src/RvtIO/Parsing/ElemTableReader.cs | 9 ++++- src/RvtIO/Parsing/WideElementRecords.cs | 19 +++++----- src/RvtIO/RvtFileReader.cs | 3 +- tests/RvtIO.Tests/CliExitCodeTests.cs | 39 ++++++++++++++++++++ tests/RvtIO.Tests/SchemaReleaseTests.cs | 22 ++++++++++- tests/RvtIO.Tests/WideElementRecordsTests.cs | 33 ++++++++++++++--- 9 files changed, 116 insertions(+), 25 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ca38bbc8..f4762d85 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,11 @@ API between minor releases. ## [Unreleased] +### Fixed + +- Reading an RVT whose element table contains an ID above `Int32.MaxValue` fails with `element-id-range` + and reports the offending ID before export. + ## [0.5.1] - 2026-11-19 The optional [RvtIO.Nwc tool](docs/rvt-to-nwc.md) exports Revit project geometry and element properties to NWC diff --git a/docs/export-report.md b/docs/export-report.md index a98c3b79..a6b6bf8b 100644 --- a/docs/export-report.md +++ b/docs/export-report.md @@ -8,7 +8,7 @@ Without the new options the output (IFC, JSON, standard error text) and the exit | Option | Effect | | --- | --- | | `--report ` | Write the JSON report of the run to this path. Written on success and on failure. | -| `--allow-partial` | Export what was read when a reader limit cut a stream. The exit code is then 0 and the report says `"status": "partial"`. Cannot be combined with `--strict`. | +| `--allow-partial` | Export what was read when a recoverable reader limit cut a stream. The exit code is then 0 and the report says `"status": "partial"`. Cannot be combined with `--strict`. | | `--strict` | Fail with exit code 6 instead of 0 when the read is partial even without hitting a limit (a member failed to decode, was rebuilt by structural recovery, or decoded without a matching checksum, or the element table decoded no row). Nothing is exported; the report lists the streams and the reason. Cannot be combined with `--allow-partial`. | | `--raise-limits` | Raise the limits listed below for a very large model. | @@ -19,7 +19,7 @@ Without the new options the output (IFC, JSON, standard error text) and the exit | 0 | success | The export was written. With `--allow-partial` or, without `--strict`, after members of a stream failed to decode or were recovered, the report can still say `"status": "partial"`: read it when you need to know, or pass `--strict` to make partial reads fail. | | 1 | usage | The command line is wrong (unchanged from earlier versions). | | 2 | input error | The input cannot be read: the file does not exist or cannot be opened, is empty, is not a compound file, or is cut or damaged so that a stream ends before its declared length. One line on standard error, no stack trace, nothing exported. | -| 3 | limit exceeded | A stream exceeded a limit of the reader and the read was cut. Nothing is exported unless `--allow-partial` is given. A stream longer than the platform allows in one array cannot be read at all: that case exits with 3 even with `--allow-partial`. | +| 3 | limit exceeded | A stream exceeded a reader limit. For a recoverable limit, `--allow-partial` permits export. Hard limits (`array-length`, `element-id-range`) stop export with exit code 3 regardless of options. | | 4 | decode error | The compound file is readable but a decoder failed on its content (damaged or unsupported data). One line on standard error; the report holds the exception with its stack trace. | | 5 | refused | `downgrade --check` refused the request (for example a source newer than release 2026, a profile not older than the source, a saving release that does not match the class table, or an ambiguous class name). One line on standard error. | | 6 | partial read | `--strict` was given and the read finished partial without exceeding a limit (members of a stream failed to decode, were rebuilt by structural recovery, or decoded without a matching checksum, or the element table decoded no row). One line on standard error naming the streams and the reason, nothing exported; the report holds the stream counts and `issues[]`. | @@ -28,13 +28,14 @@ A crash that is none of these (a defect in the exporter after the read) still en ## Limits of the reader -These are the limits the reader has. A stream that reaches one is cut, listed under `limits.hit` and counted as partial. +The report lists reader limits under `limits.hit`. Reaching a recoverable limit makes the read partial. A hard limit ends the read with status `failed`. | Code | Default | Raised by `--raise-limits` | What is cut | | --- | --- | --- | --- | | `elem-table-recovery-bytes` | 268435456 (256 MiB) | the platform array length | The output of the recovery of a damaged `Global/ElemTable`. The table keeps what the ordinary decoders produced. | | `elem-table-recovery-iterations` | 4096 | unbounded (each iteration moves forward in the stream) | The number of relocks the recovery of a damaged `Global/ElemTable` makes. | | `array-length` | the platform array length | cannot be raised | A stream of the compound file longer than one array. Exit code 3 whatever the options. | +| `element-id-range` | 2147483647 (`Int32.MaxValue`) | cannot be raised | An authoritative `Global/ElemTable` contains an element ID above the public range. The diagnostic includes that ID. Exit code 3 whatever the options. | ## Report format @@ -68,7 +69,7 @@ The report is one JSON object, UTF-8, property names in camelCase. `schema` name | Property | Meaning | | --- | --- | -| `status` | `complete`: no limit cut a stream and every member of every stream decoded and verified. `partial`: a limit cut a stream, a member did not decode, a member decoded without its checksum matching, a member was rebuilt by structural recovery, or the element table decoded no row. `failed`: the file could not be read at all (exit codes 2 and 4, and 3 for a stream over the platform array length). A read cut by a limit that is not accepted (exit code 3) or a partial read refused by `--strict` (exit code 6) is `partial` and has no `export` property, because nothing was exported. | +| `status` | `complete`: no limit cut a stream and every member of every stream decoded and verified. `partial`: a recoverable limit cut a stream, a member did not decode, a member decoded without its checksum matching, a member was rebuilt by structural recovery, or the element table decoded no row. `failed`: the file could not be read at all (exit codes 2 and 4, and 3 for hard limits). A read cut by a recoverable limit that is not accepted (exit code 3) or a partial read refused by `--strict` (exit code 6) is `partial` and has no `export` property, because nothing was exported. | | `exitCode` | The exit code of the process. | | `input.file`, `input.bytes` | File name (no directory) and size of the input. | | `error` | Only when `status` is `failed`: `kind` (`cannot-open`, `empty-file`, `not-a-compound-file`, `truncated-or-damaged`, `limit-exceeded`, `decode-failure`), `message`, and for `decode-failure` the `detail` with the stack trace. | diff --git a/src/RvtIO.Cli/ExportCommand.cs b/src/RvtIO.Cli/ExportCommand.cs index 21e771e5..9260fa61 100644 --- a/src/RvtIO.Cli/ExportCommand.cs +++ b/src/RvtIO.Cli/ExportCommand.cs @@ -116,7 +116,7 @@ private static int Export(ExportArguments arguments) { readDiagnostics.LimitHits.Add(ex.Hit); return EndRun(reportPath, ExportReport.Failed(inputName, inputBytes, "limit-exceeded", ex.Message, RvtExitCodes.LimitExceeded, readDiagnostics, raiseLimits, allowPartial, null, strict), - $"error: {ex.Message}. The limit cannot be raised. Nothing was exported (exit code {RvtExitCodes.LimitExceeded})."); + $"error ({ex.Hit.Limit}): {ex.Message}. The limit cannot be raised. Nothing was exported (exit code {RvtExitCodes.LimitExceeded})."); } // The container is readable, so this is a decoder failure on damaged or unsupported content: one line on the console, the stack trace in the report. catch (Exception ex) when (ex is not OutOfMemoryException) diff --git a/src/RvtIO/Parsing/ElemTableReader.cs b/src/RvtIO/Parsing/ElemTableReader.cs index 22bab043..61a57d19 100644 --- a/src/RvtIO/Parsing/ElemTableReader.cs +++ b/src/RvtIO/Parsing/ElemTableReader.cs @@ -69,7 +69,7 @@ public static Dictionary Read(RootStorage root, foreach (var row in rows) { // Id 0 is a real row (ProjectPhase / DimensionStyle) in ElemTable across wide and 32-bit schemas. - if (row.Id > uint.MaxValue || !(ElementIdEncoding.IsSupported((uint)row.Id) || row.Id == 0)) continue; + if (row.Id > int.MaxValue) ThrowUnsupportedId(row.Id); result[(uint)row.Id] = 0; creationDates[(uint)row.Id] = row.CreationDate; if (row.PartitionId >= 0) worksets[(uint)row.Id] = (uint)row.PartitionId; @@ -81,6 +81,7 @@ public static Dictionary Read(RootStorage root, && FileSchema.Read(root) is { } wideSchema && WideElementRecords.ParseElemTable(exactTable, wideSchema) is { } wide) { + if (wide.UnsupportedId is long idOutsideRange) ThrowUnsupportedId(idOutsideRange); foreach (var (id, history) in wide.Histories) { result[id] = 0; // ElemRec holds history and ownership, not a class id. @@ -188,7 +189,7 @@ public static Dictionary Read(RootStorage root, ParseRows(decompressed, result, out worksets, out creationDates); } - catch (Exception ex) + catch (Exception ex) when (ex is not RvtLimitException) { DiagnosticSink.WriteLine($"ElemTable: {ex.Message}"); RecordStream(diagnostics, "Global/ElemTable", 0, 1, 0, 1, 0, 0); @@ -196,6 +197,10 @@ public static Dictionary Read(RootStorage root, return result; } + private static void ThrowUnsupportedId(long id) => + throw new RvtLimitException(new ReaderLimitHit("Global/ElemTable", "element-id-range", int.MaxValue, Raisable: false, + FormattableString.Invariant($"Element ID {id} in Global/ElemTable exceeds the supported maximum of {int.MaxValue}"))); + private static void ParseDecompressedElemTable(byte[] decompressed, Dictionary result) { ParseRows(decompressed, result, out var worksets, out var creationDates); diff --git a/src/RvtIO/Parsing/WideElementRecords.cs b/src/RvtIO/Parsing/WideElementRecords.cs index bfa572ec..c929c8ce 100644 --- a/src/RvtIO/Parsing/WideElementRecords.cs +++ b/src/RvtIO/Parsing/WideElementRecords.cs @@ -28,7 +28,7 @@ internal static class WideElementRecords internal sealed record Result( Dictionary Histories, Dictionary OwningElementIds, - int SkippedRows); + long? UnsupportedId); /// Byte width of the element id of this schema (ElemRec.m_id): 4 up to Revit 2023, 8 from Revit 2024; null otherwise. internal static int? IdWidth(FileSchema schema) @@ -71,25 +71,26 @@ private static ulong ReadId(byte[] data, int at, int width) var histories = new Dictionary((int)count); var owners = new Dictionary((int)count); long previous = -1; - int skipped = 0; + long? unsupportedId = null; for (int i = 0; i < count; i++) { int at = 6 + i * length; - ulong id = ReadId(data, at + idAt, width); - if (previous >= 0 && (long)id <= previous) return null; - previous = (long)id; - ulong original = ReadId(data, at + historyAt, width); - if (!(ElementIdEncoding.IsSupported(unchecked((uint)id)) || id == 0) || id > uint.MaxValue || original > uint.MaxValue) + long id = width == 8 ? BitConverter.ToInt64(data, at + idAt) : BitConverter.ToUInt32(data, at + idAt); + if (id <= previous) return null; + previous = id; + if (id > int.MaxValue) { - skipped++; // an id beyond the 32-bit model id space is not representable + unsupportedId ??= id; continue; } + ulong original = ReadId(data, at + historyAt, width); + if (original > uint.MaxValue) continue; histories[(uint)id] = new ElemRecHistory( (uint)original, BitConverter.ToInt32(data, at + historyAt + creationAt)); long owner = width == 8 ? BitConverter.ToInt64(data, at + ownerAt) : BitConverter.ToInt32(data, at + ownerAt); if (owner >= int.MinValue && owner <= int.MaxValue) owners[(uint)id] = (int)owner; } - return new Result(histories, owners, skipped); + return new Result(histories, owners, unsupportedId); } /// Header category and root class of the elements of the partition streams. diff --git a/src/RvtIO/RvtFileReader.cs b/src/RvtIO/RvtFileReader.cs index c6af8e4b..65090198 100644 --- a/src/RvtIO/RvtFileReader.cs +++ b/src/RvtIO/RvtFileReader.cs @@ -33,7 +33,8 @@ public RvtFileReader(RvtReaderOptions? options = null) /// Read and parse a Revit file, returning structured element data. /// The file cannot be read: missing, empty, not a compound file, cut or damaged. - /// A stream is longer than one array can hold. + /// A stream is longer than one array can hold, or the element table + /// contains an ID above . public RevitFileInfo Read(string rvtPath) { RvtContainerCheck.Verify(rvtPath); diff --git a/tests/RvtIO.Tests/CliExitCodeTests.cs b/tests/RvtIO.Tests/CliExitCodeTests.cs index 2d4327a0..2fea4b70 100644 --- a/tests/RvtIO.Tests/CliExitCodeTests.cs +++ b/tests/RvtIO.Tests/CliExitCodeTests.cs @@ -127,6 +127,45 @@ public void AnIntactFileWithStrictOption_ExitsZeroAndWritesOutputAndCompleteRepo finally { Directory.Delete(directory, recursive: true); } } + [Theory] + [InlineData(2147483648L)] + [InlineData(4294967305L)] + public void AnElementIdOutsideInt32_StopsEveryExportEvenWithExplicitReaderOptions(long id) + { + string directory = Path.Combine(Path.GetTempPath(), "rvtio-cli-" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(directory); + try + { + string rvt = Path.Combine(directory, "input.rvt"); + string ifc = Path.Combine(directory, "output.ifc"); + string scene = Path.Combine(directory, "scene.json"); + string compact = Path.Combine(directory, "compact.json"); + string full = Path.Combine(directory, "full.json"); + string report = Path.Combine(directory, "report.json"); + SchemaReleaseTests.WriteSyntheticFile(rvt, wide: true, marker: 891, saved: 2024, FormatsSchemaTests.Rows(true, + (0, 0, 0, 0, -1), (int.MaxValue, int.MaxValue, 1, 0, 0), (id, id, 2, 0, 0))); + + var failure = Assert.Throws(() => new RvtFileReader(new RvtReaderOptions { RaiseLimits = true }).Read(rvt)); + Assert.Equal(("Global/ElemTable", "element-id-range", (long)int.MaxValue, false), + (failure.Hit.Stream, failure.Hit.Limit, failure.Hit.Value, failure.Hit.Raisable)); + Assert.Contains(FormattableString.Invariant($"Element ID {id}"), failure.Message); + Assert.Equal(failure.Hit, Assert.Throws(() => RvtIO.Scene.RvtSceneReader.Read(rvt)).Hit); + + var (exit, error) = RunWithOutput(rvt, "--ifc", ifc, "--scene", scene, "--compact-json", compact, "--full-json", full, + "--allow-partial", "--raise-limits", "--report", report); + Assert.Equal(RvtExitCodes.LimitExceeded, exit); + Assert.Contains("element-id-range", error); + Assert.Contains(failure.Message, error); + Assert.All(new[] { ifc, scene, compact, full }, output => Assert.False(File.Exists(output))); + using var json = JsonDocument.Parse(File.ReadAllText(report)); + Assert.Equal("failed", json.RootElement.GetProperty("status").GetString()); + var hit = Assert.Single(json.RootElement.GetProperty("limits").GetProperty("hit").EnumerateArray()); + Assert.Equal(failure.Hit.Limit, hit.GetProperty("limit").GetString()); + Assert.Equal(failure.Message, hit.GetProperty("detail").GetString()); + } + finally { Directory.Delete(directory, recursive: true); } + } + [Fact] public void AFileWithADamagedMember_ExitsZeroWithoutStrictAndPartialReadCodeWithStrict() { diff --git a/tests/RvtIO.Tests/SchemaReleaseTests.cs b/tests/RvtIO.Tests/SchemaReleaseTests.cs index cf16a856..be1e9c8f 100644 --- a/tests/RvtIO.Tests/SchemaReleaseTests.cs +++ b/tests/RvtIO.Tests/SchemaReleaseTests.cs @@ -152,13 +152,31 @@ public void ContradictoryDeclaredWidthsRemainUndecoded(bool wide, int marker, in finally { File.Delete(path); } } - internal static void WriteSyntheticFile(string path, bool wide, int marker, int? saved) + [Fact] + public void WideElementTableRetainsZeroAndTheMaximumPublicId() + { + string path = TestFiles.Scratch($"schema-id-range-{Guid.NewGuid():N}.rvt"); + try + { + WriteSyntheticFile(path, wide: true, marker: 891, saved: 2024, FormatsSchemaTests.Rows(true, + (0, 0, 0, 0, -1), (int.MaxValue, int.MaxValue, 64, 7, 0))); + using var root = RootStorage.OpenRead(path); + var elements = ElemTableReader.Read(root, out var worksets, out var dates, out bool exact); + Assert.True(exact); + Assert.Equal(new uint[] { 0, int.MaxValue }, elements.Keys.Order().ToArray()); + Assert.Equal(7u, worksets[int.MaxValue]); + Assert.Equal(64, dates[int.MaxValue]); + } + finally { File.Delete(path); } + } + + internal static void WriteSyntheticFile(string path, bool wide, int marker, int? saved, byte[]? elemTable = null) { using var root = RootStorage.Create(path, OpenMcdf.Version.V3); using var formats = root.CreateStorage("Formats").CreateStream("Latest"); formats.Write(PageCodec.EncodePadded(GzipMember.Write(FormatsSchemaTests.ElemTableSchema(wide, marker)))); using var table = root.CreateStorage("Global").CreateStream("ElemTable"); - table.Write(PageCodec.EncodePadded(GzipMember.Write(FormatsSchemaTests.Rows(wide, + table.Write(PageCodec.EncodePadded(GzipMember.Write(elemTable ?? FormatsSchemaTests.Rows(wide, (0, 0, 0, 0, -1), (700, 500, 64, 7, 1))))); using var info = root.CreateStream("BasicFileInfo"); info.Write(RvtWriterTests.BuildBasicFileInfoBytes(saved)); diff --git a/tests/RvtIO.Tests/WideElementRecordsTests.cs b/tests/RvtIO.Tests/WideElementRecordsTests.cs index 49644558..aaef5bb2 100644 --- a/tests/RvtIO.Tests/WideElementRecordsTests.cs +++ b/tests/RvtIO.Tests/WideElementRecordsTests.cs @@ -53,12 +53,12 @@ public byte[] ToArray() private sealed record Ids(int Identifier, int ElementId, int ElemRec, int ElemTable, int Header, int Element, int Wall, int Other, int Level); - private static (byte[] Stream, Ids Ids) BuildSchema() + private static (byte[] Stream, Ids Ids) BuildSchema(string originalClassName = "OriginalElementId") { var w = new SchemaWriter(); int identifier = w.Add("Identifier", 0, Scalar("m_id64", 11)); int elementId = w.Add("ElementId", 0, Ref("m_id", identifier)); - int original = w.Add("OriginalElementId", 0, Scalar("m_id64", 11)); + int original = w.Add(originalClassName, 0, Scalar("m_id64", 11)); int episode = w.Add("EpisodeId", 0, Scalar("m_id", 4)); int partition = w.Add("PartitionId", 0, Scalar("m_id", 4)); int history = w.Add("ElementHistory", 0, Ref("m_originalElementId", original), Ref("m_creationDate", episode), @@ -176,14 +176,14 @@ public void ParseElemTable_ReadsTheFourByteIdLayoutOfRevit2023() } [Fact] - public void ParseElemTable_KeepsIdZeroSkipsIdsOutsideTheModelIdSpaceAndRejectsBrokenTables() + public void ParseElemTable_KeepsIdZeroReportsTheFirstIdOutsideTheModelRangeAndRejectsBrokenTables() { var (stream, ids) = BuildSchema(); var schema = FileSchema.Parse(stream)!; var wide = WideElementRecords.ParseElemTable( - ElemTable(ids, (0, 0, 0, -1), (5, 0, 5, -1), (9, 0, 0x1_0000_0009UL, -1)), schema)!; - Assert.Equal([0u, 5u], wide.Histories.Keys.ToArray()); // id 0 is a real row (ProjectPhase / DimensionStyle) - Assert.Equal(1, wide.SkippedRows); + ElemTable(ids, (0, 0, 0, -1), (5, 0, int.MaxValue, -1), (9, 0, 0x1_0000_0009UL, -1)), schema)!; + Assert.Equal([0u, int.MaxValue], wide.Histories.Keys.ToArray()); // id 0 is a real row (ProjectPhase / DimensionStyle) + Assert.Equal(4294967305L, wide.UnsupportedId); var good = ElemTable(ids, (5, 0, 5, -1), (6, 0, 6, -1)); Assert.Null(WideElementRecords.ParseElemTable(ElemTable(ids, (6, 0, 6, -1), (5, 0, 5, -1)), schema)); // not increasing Assert.Null(WideElementRecords.ParseElemTable(good[..^30], schema)); // truncated @@ -192,6 +192,27 @@ public void ParseElemTable_KeepsIdZeroSkipsIdsOutsideTheModelIdSpaceAndRejectsBr Assert.Null(WideElementRecords.ParseElemTable(good, FileSchema.Parse(OnlyOther())!)); // schema without the table classes } + [Fact] + public void ElementTableFallbackRejectsAnIdOutsideInt32() + { + // Only the fallback accepts a schema without an OriginalElementId class by that name. + var (stream, ids) = BuildSchema("StoredOriginalId"); + byte[] table = ElemTable(ids, (0, 0, 0, -1), (9, 0, 0x1_0000_0009UL, -1)); + var formats = FormatsSchema.TryParse(stream)!; + Assert.Null(ElemTableLayout.TryParse(table, formats)); + string path = TestFiles.Scratch($"wide-id-range-{Guid.NewGuid():N}.rvt"); + try + { + CoverageCensusTests.WriteFile(path, + ("Formats/Latest", RvtIO.Writing.PageCodec.EncodePadded(RvtIO.Writing.GzipMember.Write(stream))), + ("Global/ElemTable", RvtIO.Writing.PageCodec.EncodePadded(RvtIO.Writing.GzipMember.Write(table)))); + var exception = Assert.Throws(() => new RvtFileReader().Read(path)); + Assert.Equal("element-id-range", exception.Hit.Limit); + Assert.Contains("4294967305", exception.Message); + } + finally { File.Delete(path); } + } + [Theory] [InlineData("Rebar", "RebarBarType", 7)] [InlineData("RebarInSystem", "RebarBarType", 7)] From 00c93027be8d4070e1ee460e4a5206129f983af4 Mon Sep 17 00:00:00 2001 From: mahach666 <79989386+mahach666@users.noreply.github.com> Date: Thu, 19 Nov 2026 16:42:44 +0300 Subject: [PATCH 029/259] Expose standalone native NWC export for RVT models --- README.md | 2 +- docs/rvt-to-nwc.md | 14 ++++++++++ tests/RvtIO.Tests/NwcExportTests.cs | 18 ++++++++++++ tools/RvtIO.Nwc/NwcExport.cs | 43 +++++++++++++++++++++++++---- tools/RvtIO.Nwc/Program.cs | 16 +++++++++-- tools/RvtIO.Nwc/RvtIO.Nwc.csproj | 7 ++++- 6 files changed, 89 insertions(+), 11 deletions(-) diff --git a/README.md b/README.md index 2dd3f38b..b72dfe15 100644 --- a/README.md +++ b/README.md @@ -35,7 +35,7 @@ dotnet add package RvtIO `RvtIO.Scene` (a separate package released with RvtIO) turns a Revit project into an `IOScene` scene document for viewers; see the [scene adapter](docs/scene.md) for usage and limits. -The optional [RvtIO.Nwc tool](docs/rvt-to-nwc.md) exports Revit projects to NWC using Autodesk Navisworks on Windows or writes a preview cache for NwcIO. +The optional [RvtIO.Nwc tool](docs/rvt-to-nwc.md) exports Revit projects to NWC with a managed writer. The library targets .NET 8 and .NET 10. It uses managed code without native dependencies or Windows-only APIs and is tested on Windows, Linux and macOS. diff --git a/docs/rvt-to-nwc.md b/docs/rvt-to-nwc.md index 5b4d490d..b6e27e23 100644 --- a/docs/rvt-to-nwc.md +++ b/docs/rvt-to-nwc.md @@ -1,5 +1,19 @@ # RVT to NWC +## Autonomous export + +Build the optional tool against the NwcIO checkout that includes `NwcWriter.WriteNative`. +Pass the absolute path of its project file and use `--native`. + +```sh +dotnet run --project tools/RvtIO.Nwc -c Release -f net10.0 \ + --property:NwcIOProject=/path/to/NwcIO/src/NwcIO/NwcIO.csproj -- model.rvt model.nwc --native +``` + +This mode writes placed triangle geometry, face normals, diffuse colours, the element tree, IFC GlobalIds +and Revit property display text. The cache uses feet internally. It opens in NwcIO and was validated in +Navisworks Manage 2027. Export uses managed .NET code on Windows and Linux. + ## Autodesk Navisworks On Windows, pass the installed Navisworks Manage or Simulate executable to export a cache for Navisworks. diff --git a/tests/RvtIO.Tests/NwcExportTests.cs b/tests/RvtIO.Tests/NwcExportTests.cs index 2cb6574e..023b4c9d 100644 --- a/tests/RvtIO.Tests/NwcExportTests.cs +++ b/tests/RvtIO.Tests/NwcExportTests.cs @@ -9,6 +9,24 @@ namespace RvtIO.Tests; public class NwcExportTests { + [Fact] + public void NativeModelCarriesTheMeshOwnerAndSourceMaterial() + { + var scene = new SceneDocument(); + scene.AddMesh("Wall", [new(0, 0, 0), new(1, 0, 0), new(0, 1, 0)], [0, 1, 2]); + var element = Assert.Single(scene.Elements); + element.IfcGuid = "0000000000000000000001"; + scene.Materials.Add(new() { Id = 1, Name = "Red", Color = new(255, 0, 0) }); + Assert.Single(scene.Instances).MaterialId = 1; + + var document = NwcExport.Build(scene, "model.rvt", 0, DateTime.UnixEpoch, native: true); + var mesh = Assert.Single(document.Meshes); + + Assert.Equal(element.IfcGuid, mesh.Node?.IfcGlobalId); + Assert.Equal(new NwcIO.Model.RgbaColor(1, 0, 0), mesh.Material?.Color); + Assert.DoesNotContain(mesh.Node!.Properties, record => record.Class == "IOExtend.NwcWriter.Link"); + } + [Fact] public void NavisworksCommandOpensTheExactCacheItCreates() { diff --git a/tools/RvtIO.Nwc/NwcExport.cs b/tools/RvtIO.Nwc/NwcExport.cs index b9dc90f9..5856cc46 100644 --- a/tools/RvtIO.Nwc/NwcExport.cs +++ b/tools/RvtIO.Nwc/NwcExport.cs @@ -13,7 +13,7 @@ internal static class NwcExport // The optional metadata is written by NwcIO 0.14 and interpreted by the linked-cache reader. private const string MetreCacheOption = "IOExtend.NwcWriter.Scene/1"; private const string LinkClass = "IOExtend.NwcWriter.Link"; - internal static NwcDocument Build(SceneDocument scene, string sourceName, long sourceLength, DateTime timestamp) + internal static NwcDocument Build(SceneDocument scene, string sourceName, long sourceLength, DateTime timestamp, bool native = false) { if (scene.Validate().FirstOrDefault(d => d.Severity == SceneSeverity.Error) is { } error) throw new InvalidDataException(error.Message); @@ -40,6 +40,11 @@ internal static NwcDocument Build(SceneDocument scene, string sourceName, long s var node = AddNode(parent, nextNodeId++, element.Name, "RvtIO.Element"); nodes.Add(element.Id, node); + if (native) + { + node.Class = "LcRevitElement"; + node.IfcGlobalId = element.IfcGuid; + } AddText(node, "Revit", "Element ID", id); AddText(node, "Revit", "UniqueId", element.SourceId); AddText(node, "Revit", "IFC GlobalId", element.IfcGuid); @@ -54,6 +59,14 @@ internal static NwcDocument Build(SceneDocument scene, string sourceName, long s } var geometries = scene.Geometries.ToDictionary(geometry => geometry.Id); + var materials = native + ? scene.Materials.ToDictionary(m => m.Id, m => new NwcMaterial + { + Id = m.Id, + Name = m.Name, + Color = new(m.Color.R / 255f, m.Color.G / 255f, m.Color.B / 255f, m.Color.A / 255f), + }) + : null; var meshes = new List(scene.Instances.Count); foreach (var instance in scene.Instances) { @@ -75,16 +88,21 @@ internal static NwcDocument Build(SceneDocument scene, string sourceName, long s int meshId = meshes.Count + 1; var node = nodes[instance.ElementId]; - node.Properties.Add(new NwcPropertyRecord + if (!native) { - FirstInt = node.Id, Tag = 52, Name = "Mesh ID", Class = LinkClass, ValueType = 2, IntValue = meshId, - }); + node.Properties.Add(new NwcPropertyRecord + { + FirstInt = node.Id, Tag = 52, Name = "Mesh ID", Class = LinkClass, ValueType = 2, IntValue = meshId, + }); + } meshes.Add(new NwcMesh { Id = meshId, Name = string.Create(CultureInfo.InvariantCulture, $"{node.Name} [RVT {instance.ElementId}]"), Vertices = vertices, Indices = indices, + Node = native ? node : null, + Material = instance.MaterialId is int materialId ? materials?.GetValueOrDefault(materialId) : null, // The read-back tree also looks for transforms by node ID. Transform = new NwcTransform { Id = nextNodeId++, Translation = ToNwc(transform.Translation) }, }); @@ -104,7 +122,7 @@ internal static NwcDocument Build(SceneDocument scene, string sourceName, long s rootNode: root); } - internal static void Save(NwcDocument cache, string path) + internal static void Save(NwcDocument cache, string path, bool native = false) { string destination = Path.GetFullPath(path); string temporary = Path.Combine(Path.GetDirectoryName(destination)!, $"rvtio-nwc-{Guid.NewGuid():N}.tmp"); @@ -113,7 +131,20 @@ internal static void Save(NwcDocument cache, string path) try { using (stream) - NwcWriter.Write(cache, stream); + { + if (native) + { +#if MANAGED_NWC + NwcWriter.WriteNative(cache, stream); +#else + throw new InvalidOperationException("Native NWC export requires a build with the NwcIO project."); +#endif + } + else + { + NwcWriter.Write(cache, stream); + } + } File.Move(temporary, destination); moved = true; } diff --git a/tools/RvtIO.Nwc/Program.cs b/tools/RvtIO.Nwc/Program.cs index d2372eb0..3e67752e 100644 --- a/tools/RvtIO.Nwc/Program.cs +++ b/tools/RvtIO.Nwc/Program.cs @@ -5,7 +5,7 @@ namespace RvtIO.Nwc; internal static class Program { - private const string Usage = "Usage: RvtIO.Nwc [--navisworks ]"; + private const string Usage = "Usage: RvtIO.Nwc [--native | --navisworks ]"; public static int Main(string[] args) { @@ -16,6 +16,16 @@ public static int Main(string[] args) } string? navisworks = null; + bool native = args is [_, _, "--native"]; + if (native) + { +#if !MANAGED_NWC + Console.Error.WriteLine("Rebuild with -p:NwcIOProject= to use --native."); + return 2; +#else + args = args[..2]; +#endif + } if (args is [_, _, "--navisworks", var executable]) { navisworks = executable; @@ -50,8 +60,8 @@ public static int Main(string[] args) if (scene.Diagnostics.Any(d => d.Severity == SceneSeverity.Error)) return 2; - var cache = NwcExport.Build(scene.Document, source.Name, length, source.LastWriteTimeUtc); - NwcExport.Save(cache, output); + var cache = NwcExport.Build(scene.Document, source.Name, length, source.LastWriteTimeUtc, native); + NwcExport.Save(cache, output, native); Console.Out.WriteLine($"Exported {cache.Meshes.Count} triangle meshes to '{output}'."); return 0; } diff --git a/tools/RvtIO.Nwc/RvtIO.Nwc.csproj b/tools/RvtIO.Nwc/RvtIO.Nwc.csproj index 7f7db290..6e50e334 100644 --- a/tools/RvtIO.Nwc/RvtIO.Nwc.csproj +++ b/tools/RvtIO.Nwc/RvtIO.Nwc.csproj @@ -7,9 +7,14 @@ true + + $(DefineConstants);MANAGED_NWC + + - + + From 19f0524686f495ba60adbafb8038fa03dde372f2 Mon Sep 17 00:00:00 2001 From: mahach666 <79989386+mahach666@users.noreply.github.com> Date: Thu, 19 Nov 2026 17:02:39 +0300 Subject: [PATCH 030/259] Use published NwcIO for autonomous RVT export --- Directory.Packages.props | 2 +- docs/rvt-to-nwc.md | 6 ++---- tests/RvtIO.Tests/NwcExportTests.cs | 19 ++++++++++++++++++- tools/RvtIO.Nwc/NwcExport.cs | 8 -------- tools/RvtIO.Nwc/Program.cs | 9 +-------- tools/RvtIO.Nwc/RvtIO.Nwc.csproj | 7 +------ 6 files changed, 23 insertions(+), 28 deletions(-) diff --git a/Directory.Packages.props b/Directory.Packages.props index cab8ceaf..dedc7313 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -17,7 +17,7 @@ - + diff --git a/docs/rvt-to-nwc.md b/docs/rvt-to-nwc.md index b6e27e23..3eda280c 100644 --- a/docs/rvt-to-nwc.md +++ b/docs/rvt-to-nwc.md @@ -2,12 +2,10 @@ ## Autonomous export -Build the optional tool against the NwcIO checkout that includes `NwcWriter.WriteNative`. -Pass the absolute path of its project file and use `--native`. +Run the optional tool from the RvtIO repository. The build restores NwcIO from NuGet. ```sh -dotnet run --project tools/RvtIO.Nwc -c Release -f net10.0 \ - --property:NwcIOProject=/path/to/NwcIO/src/NwcIO/NwcIO.csproj -- model.rvt model.nwc --native +dotnet run --project tools/RvtIO.Nwc -c Release -f net10.0 -- model.rvt model.nwc --native ``` This mode writes placed triangle geometry, face normals, diffuse colours, the element tree, IFC GlobalIds diff --git a/tests/RvtIO.Tests/NwcExportTests.cs b/tests/RvtIO.Tests/NwcExportTests.cs index 023b4c9d..b0a0c46e 100644 --- a/tests/RvtIO.Tests/NwcExportTests.cs +++ b/tests/RvtIO.Tests/NwcExportTests.cs @@ -10,7 +10,7 @@ namespace RvtIO.Tests; public class NwcExportTests { [Fact] - public void NativeModelCarriesTheMeshOwnerAndSourceMaterial() + public void NativeRoundTripKeepsTheMeshOwnerAndSourceMaterial() { var scene = new SceneDocument(); scene.AddMesh("Wall", [new(0, 0, 0), new(1, 0, 0), new(0, 1, 0)], [0, 1, 2]); @@ -25,6 +25,23 @@ public void NativeModelCarriesTheMeshOwnerAndSourceMaterial() Assert.Equal(element.IfcGuid, mesh.Node?.IfcGlobalId); Assert.Equal(new NwcIO.Model.RgbaColor(1, 0, 0), mesh.Material?.Color); Assert.DoesNotContain(mesh.Node!.Properties, record => record.Class == "IOExtend.NwcWriter.Link"); + + var directory = Directory.CreateTempSubdirectory(); + try + { + string path = Path.Combine(directory.FullName, "model.nwc"); + NwcExport.Save(document, path, native: true); + + var reopened = NwcDocument.Open(path, new() { Strict = true }); + var loaded = Assert.Single(reopened.Meshes); + Assert.Equal(NwcLengthUnit.Feet, reopened.LengthUnit); + Assert.Equal(element.IfcGuid, loaded.Node?.IfcGlobalId); + Assert.Equal(mesh.Material!.Color, loaded.Material?.Color); + } + finally + { + directory.Delete(recursive: true); + } } [Fact] diff --git a/tools/RvtIO.Nwc/NwcExport.cs b/tools/RvtIO.Nwc/NwcExport.cs index 5856cc46..b208444a 100644 --- a/tools/RvtIO.Nwc/NwcExport.cs +++ b/tools/RvtIO.Nwc/NwcExport.cs @@ -133,17 +133,9 @@ internal static void Save(NwcDocument cache, string path, bool native = false) using (stream) { if (native) - { -#if MANAGED_NWC NwcWriter.WriteNative(cache, stream); -#else - throw new InvalidOperationException("Native NWC export requires a build with the NwcIO project."); -#endif - } else - { NwcWriter.Write(cache, stream); - } } File.Move(temporary, destination); moved = true; diff --git a/tools/RvtIO.Nwc/Program.cs b/tools/RvtIO.Nwc/Program.cs index 3e67752e..a3882f0d 100644 --- a/tools/RvtIO.Nwc/Program.cs +++ b/tools/RvtIO.Nwc/Program.cs @@ -18,15 +18,8 @@ public static int Main(string[] args) string? navisworks = null; bool native = args is [_, _, "--native"]; if (native) - { -#if !MANAGED_NWC - Console.Error.WriteLine("Rebuild with -p:NwcIOProject= to use --native."); - return 2; -#else args = args[..2]; -#endif - } - if (args is [_, _, "--navisworks", var executable]) + else if (args is [_, _, "--navisworks", var executable]) { navisworks = executable; args = args[..2]; diff --git a/tools/RvtIO.Nwc/RvtIO.Nwc.csproj b/tools/RvtIO.Nwc/RvtIO.Nwc.csproj index 6e50e334..7f7db290 100644 --- a/tools/RvtIO.Nwc/RvtIO.Nwc.csproj +++ b/tools/RvtIO.Nwc/RvtIO.Nwc.csproj @@ -7,14 +7,9 @@ true - - $(DefineConstants);MANAGED_NWC - - - - + From 9b230dfe9df3e3b0317e0a78d7ed44aa56291c35 Mon Sep 17 00:00:00 2001 From: mahach666 <79989386+mahach666@users.noreply.github.com> Date: Thu, 19 Nov 2026 17:30:15 +0300 Subject: [PATCH 031/259] Bundle the RVT-to-NWC exporter in the 0.6.0 release --- CHANGELOG.md | 8 ++++++++ Directory.Build.props | 2 +- README.md | 1 + THIRD-PARTY-NOTICES.md | 2 ++ docs/rvt-to-nwc.md | 21 +++++++++++++++------ tools/pack-release.ps1 | 17 ++++++++++++++--- 6 files changed, 41 insertions(+), 10 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f4762d85..18c0e268 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,14 @@ API between minor releases. ## [Unreleased] +## [0.6.0] - 2026-11-19 + +### Added + +- GitHub releases include ready-to-run `RvtIO.Nwc` archives for .NET 8 and .NET 10. + Use `--native` to export an NWC file that opens in Navisworks and NwcIO without Autodesk software on the export machine. +- On Windows, the optional `--navisworks` mode can also generate a cache through an installed Navisworks Manage or Simulate. + ### Fixed - Reading an RVT whose element table contains an ID above `Int32.MaxValue` fails with `element-id-range` diff --git a/Directory.Build.props b/Directory.Build.props index c2f206cb..07a97ec3 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -6,7 +6,7 @@ enable true true - 0.5.1 + 0.6.0 true true snupkg diff --git a/README.md b/README.md index b72dfe15..5250bc8d 100644 --- a/README.md +++ b/README.md @@ -36,6 +36,7 @@ dotnet add package RvtIO viewers; see the [scene adapter](docs/scene.md) for usage and limits. The optional [RvtIO.Nwc tool](docs/rvt-to-nwc.md) exports Revit projects to NWC with a managed writer. +Download the ready-to-run tool from [RvtIO releases](https://github.com/IOExtend/RvtIO/releases/latest). The library targets .NET 8 and .NET 10. It uses managed code without native dependencies or Windows-only APIs and is tested on Windows, Linux and macOS. diff --git a/THIRD-PARTY-NOTICES.md b/THIRD-PARTY-NOTICES.md index 09a0459f..82e38dba 100644 --- a/THIRD-PARTY-NOTICES.md +++ b/THIRD-PARTY-NOTICES.md @@ -6,6 +6,8 @@ RvtIO uses the following components. |---|---|---| | [OpenMcdf](https://github.com/ironfede/openmcdf) 3.4.0 | reads the compound file container of Revit files | MPL-2.0 | | [SharpZipLib](https://github.com/icsharpcode/SharpZipLib) 1.4.2 | stream decompression | MIT | +| [IOScene](https://github.com/IOExtend/IOScene) | scene contract used by RvtIO.Scene and RvtIO.Nwc | MIT, copyright (c) 2026 mahach666 | +| [NwcIO](https://github.com/IOExtend/NwcIO) 0.15.0 | NWC writer bundled with RvtIO.Nwc | MIT, copyright (c) 2026 mahach666 | | .NET runtime libraries (DeflateManaged sources, `src/RvtIO/DeflateManaged`) | managed inflate implementation adapted for tolerant decoding | MIT, copyright (c) .NET Foundation and Contributors | Development and build-time packages (xunit, Microsoft.NET.Test.Sdk, Microsoft.SourceLink.GitHub) are not part of the diff --git a/docs/rvt-to-nwc.md b/docs/rvt-to-nwc.md index 3eda280c..1db2f203 100644 --- a/docs/rvt-to-nwc.md +++ b/docs/rvt-to-nwc.md @@ -2,10 +2,12 @@ ## Autonomous export -Run the optional tool from the RvtIO repository. The build restores NwcIO from NuGet. +Download and extract `RvtIO-Nwc--net10.0.zip` or `RvtIO-Nwc--net8.0.zip` from the +[RvtIO releases](https://github.com/IOExtend/RvtIO/releases/latest). The archive includes the tool and its dependencies. +Install the .NET runtime that matches the archive and run the command from the extracted directory. ```sh -dotnet run --project tools/RvtIO.Nwc -c Release -f net10.0 -- model.rvt model.nwc --native +dotnet RvtIO.Nwc.dll model.rvt model.nwc --native ``` This mode writes placed triangle geometry, face normals, diffuse colours, the element tree, IFC GlobalIds @@ -17,7 +19,7 @@ Navisworks Manage 2027. Export uses managed .NET code on Windows and Linux. On Windows, pass the installed Navisworks Manage or Simulate executable to export a cache for Navisworks. ```powershell -dotnet run --project tools/RvtIO.Nwc -c Release -f net10.0 -- model.rvt model.nwc --navisworks "C:\Program Files\Autodesk\Navisworks Manage 2027\Roamer.exe" +dotnet RvtIO.Nwc.dll model.rvt model.nwc --navisworks "C:\Program Files\Autodesk\Navisworks Manage 2027\Roamer.exe" ``` RvtIO reads the RVT and exports a temporary IFC using its current IFC profile and Revit property sets. @@ -30,11 +32,10 @@ Autodesk documents the [command-line switches](https://help.autodesk.com/cloudhe ## NwcIO preview -The optional `RvtIO.Nwc` tool uses `RvtIO.Scene` and the NwcIO writer. Run it from the repository with -the SDK in `global.json` and either supported .NET runtime. +Run the tool with two positional arguments to write the NwcIO preview layout. ```sh -dotnet run --project tools/RvtIO.Nwc -c Release -f net10.0 -- model.rvt model.nwc +dotnet RvtIO.Nwc.dll model.rvt model.nwc nwcio model.nwc model.json ``` @@ -53,3 +54,11 @@ line geometry. Use a new output path. Reader errors, an empty model, or geometry that the writer rejects stop the export. Reader warnings are printed to standard error. The tool moves the completed cache into place after writing. + +## Build from source + +Run the optional tool from the RvtIO repository with the SDK in `global.json`. The build restores NwcIO from NuGet. + +```sh +dotnet run --project tools/RvtIO.Nwc -c Release -f net10.0 -- model.rvt model.nwc --native +``` diff --git a/tools/pack-release.ps1 b/tools/pack-release.ps1 index 0f7fdd91..c09335a1 100644 --- a/tools/pack-release.ps1 +++ b/tools/pack-release.ps1 @@ -105,7 +105,18 @@ Copy-Item (Join-Path $root 'README.md') $cli10Stage Copy-Item (Join-Path $root 'LICENSE') $cli10Stage New-Zip $cli10Stage (Join-Path $Output "RvtIO-Cli-$version-net10.0.zip") -# 4. NuGet packages +# 4. Portable RVT-to-NWC tool (.NET 8 and .NET 10 runtimes) +foreach ($framework in 'net8.0', 'net10.0') { + Write-Host "Publishing RvtIO.Nwc ($framework)..." + $nwcStage = Join-Path $stage "nwc-$framework" + Invoke-DotNet publish (Join-Path $root 'tools\RvtIO.Nwc\RvtIO.Nwc.csproj') -c Release -f $framework --self-contained false -p:UseAppHost=false -o $nwcStage + Invoke-DotNet (Join-Path $nwcStage 'RvtIO.Nwc.dll') --help + Copy-Item (Join-Path $root 'docs\rvt-to-nwc.md') (Join-Path $nwcStage 'README.md') + Copy-Item (Join-Path $root 'LICENSE'), (Join-Path $root 'THIRD-PARTY-NOTICES.md') $nwcStage + New-Zip $nwcStage (Join-Path $Output "RvtIO-Nwc-$version-$framework.zip") +} + +# 5. NuGet packages Write-Host "Packing NuGet packages..." Invoke-DotNet pack (Join-Path $root 'RvtIO.slnx') -c Release --no-build -o $Output @@ -121,7 +132,7 @@ try { } Assert-SceneDependencies $nuspec $version -# 5. Source code archive +# 6. Source code archive Write-Host "Creating source code archive..." $sourceZip = Join-Path $Output "RvtIO-$version-source.zip" if (Test-Path -LiteralPath $sourceZip) { Remove-Item -LiteralPath $sourceZip } @@ -130,7 +141,7 @@ if ($LASTEXITCODE -ne 0) { throw "git archive failed with exit code $LASTEXITCOD Remove-Item -LiteralPath $stage -Recurse -Force -# 6. Checksums +# 7. Checksums Write-Host "Computing SHA256..." $files = @(Get-ChildItem -LiteralPath $Output -File | Where-Object { $_.Extension -in '.zip', '.nupkg', '.snupkg' } | Sort-Object Name) $sums = $files | ForEach-Object { '{0} {1}' -f (Get-FileHash -LiteralPath $_.FullName -Algorithm SHA256).Hash.ToLowerInvariant(), $_.Name } From 2cc1ac1d6cbf124b90912aa080e4ca503bfbaeea Mon Sep 17 00:00:00 2001 From: mie <79989386+mahach666@users.noreply.github.com> Date: Thu, 19 Nov 2026 17:30:31 +0300 Subject: [PATCH 032/259] Preserve 64-bit Revit element IDs in reads and exports --- CHANGELOG.md | 9 +- README.md | 10 + docs/export-report.md | 2 +- src/RvtIO.Scene/RvtSceneReader.cs | 15 +- src/RvtIO/Compact/CompactJsonWriter.cs | 4 +- src/RvtIO/Compact/CompactNode.cs | 2 +- src/RvtIO/Compact/CompactNodeBuilder.cs | 14 +- src/RvtIO/Ifc/IfcExporter.cs | 17 +- src/RvtIO/Ifc/IfcGuid.cs | 6 +- src/RvtIO/Internal/ParsingState.cs | 1 + src/RvtIO/Model/Element.cs | 40 +++- src/RvtIO/Model/Parameter.cs | 14 +- src/RvtIO/Model/ParameterListConverter.cs | 5 +- src/RvtIO/Model/RevitFileInfo.cs | 28 +++ src/RvtIO/Parsing/ElemTableReader.cs | 48 ++--- src/RvtIO/Parsing/ElementBuilder.cs | 16 +- src/RvtIO/Parsing/ElementExportIds.cs | 2 +- src/RvtIO/Parsing/ElementHeaderCategory.cs | 3 +- src/RvtIO/Parsing/ElementIdMap.cs | 50 +++++ src/RvtIO/Parsing/GridAxisReader.cs | 4 +- src/RvtIO/Parsing/R22Transcoder.cs | 15 +- src/RvtIO/Parsing/RebarReader.cs | 12 +- .../Revit2027ApiValues.HostQuantities.cs | 2 +- src/RvtIO/Parsing/WideBlockWalker.cs | 6 +- src/RvtIO/Parsing/WideElementRecords.cs | 121 +++++------ src/RvtIO/Parsing/WideNativeParams.cs | 4 +- src/RvtIO/Parsing/WideSolidQuantities.cs | 14 +- src/RvtIO/RvtDocument.cs | 17 +- src/RvtIO/RvtFileReader.R22Layout.cs | 4 +- src/RvtIO/RvtFileReader.cs | 101 ++++++--- tests/RvtIO.Tests/ElementCensusTests.cs | 11 +- tests/RvtIO.Tests/ElementExportIdTests.cs | 9 +- .../RvtIO.Tests/IfcExporterSkipReasonTests.cs | 2 +- tests/RvtIO.Tests/PartitionCutTests.cs | 2 +- tests/RvtIO.Tests/WideElementRecordsTests.cs | 192 ++++++++++++++++-- 35 files changed, 612 insertions(+), 190 deletions(-) create mode 100644 src/RvtIO/Parsing/ElementIdMap.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index f4762d85..9baa7bd0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,10 +6,15 @@ API between minor releases. ## [Unreleased] +### Added + +- Preserve 64-bit Revit element IDs in project reads, source-ID lookups and exports. JSON and Scene carry wide source + IDs as decimal text. + ### Fixed -- Reading an RVT whose element table contains an ID above `Int32.MaxValue` fails with `element-id-range` - and reports the offending ID before export. +- Report `element-id-range` with the offending ID if an RVT has wide element IDs and no project partition storage + to read the element records. ## [0.5.1] - 2026-11-19 diff --git a/README.md b/README.md index b72dfe15..b7c37bb9 100644 --- a/README.md +++ b/README.md @@ -215,6 +215,16 @@ The tested projects include basic and advanced architecture, structure and MEP s The stored class schema determines the decoding layout, including element row and ID widths. The saving year in `BasicFileInfo` is a fallback when the schema release cannot be recognized. Diagnostics report both years when they differ; an older saving year does not override a recognized newer schema. +For projects with wide element IDs, use `Element.ElementId` and `RvtDocument.GetElement(long)` for exact source +identity. `TypeElementId`, `HostElementId`, and `Parameter.AsElementId64()` return the exact IDs of those references. +Existing `int` members use document-local keys. `RevitFileInfo.GetSourceElementId(int)` resolves any such key. +Full JSON records the remapped keys in `SourceElementIds` and writes remapped parameter references as decimal strings. +Compact JSON keeps the exact source ID in the existing `object` string. Scene keeps local numeric links and carries wide +source IDs as text. IFC products with a Tag attribute carry the exact source ID in that attribute. + +Wide creation IDs are available as `Element.OriginalElementId`. The Revit UniqueId and IFC GUID derivation used for +32-bit original IDs is not extended to 64-bit originals without a reference from Revit. + ## Limitations - Version 0.4.0 is a preview. The API can change before 1.0. diff --git a/docs/export-report.md b/docs/export-report.md index a6b6bf8b..d1306a9a 100644 --- a/docs/export-report.md +++ b/docs/export-report.md @@ -35,7 +35,7 @@ The report lists reader limits under `limits.hit`. Reaching a recoverable limit | `elem-table-recovery-bytes` | 268435456 (256 MiB) | the platform array length | The output of the recovery of a damaged `Global/ElemTable`. The table keeps what the ordinary decoders produced. | | `elem-table-recovery-iterations` | 4096 | unbounded (each iteration moves forward in the stream) | The number of relocks the recovery of a damaged `Global/ElemTable` makes. | | `array-length` | the platform array length | cannot be raised | A stream of the compound file longer than one array. Exit code 3 whatever the options. | -| `element-id-range` | 2147483647 (`Int32.MaxValue`) | cannot be raised | An authoritative `Global/ElemTable` contains an element ID above the public range. The diagnostic includes that ID. Exit code 3 whatever the options. | +| `element-id-range` | 2147483647 (`Int32.MaxValue`) | cannot be raised | An authoritative `Global/ElemTable` contains an ID above the local key range and the read has no project partition storage to map the ID. The diagnostic includes that ID. | ## Report format diff --git a/src/RvtIO.Scene/RvtSceneReader.cs b/src/RvtIO.Scene/RvtSceneReader.cs index f2a35bfd..bea2733f 100644 --- a/src/RvtIO.Scene/RvtSceneReader.cs +++ b/src/RvtIO.Scene/RvtSceneReader.cs @@ -176,7 +176,7 @@ private static RvtSceneResult Map(RvtDocument document, MeshSet meshes, string m if (sceneElement.SourceId == null) withoutUniqueId++; if (element != null) { - if (AddPropertySet(scene, "Instance", "revit:instance", element.Parameters) is int instanceSet) + if (AddPropertySet(scene, "Instance", "revit:instance", element.Parameters, element) is int instanceSet) sceneElement.PropertySetIds.Add(instanceSet); if (document.GetTypeElement(element) is { } type) { @@ -283,9 +283,13 @@ private static string CategoryName(Element? element) => element?.CategoryId is int id && ((BuiltInCategory)id).TryGetCategoryName(out string? name) ? name : element?.Category ?? string.Empty; /// Adds the set of the parameters that have a value the file stores; null when none has. - private static int? AddPropertySet(SceneDocument scene, string name, string key, IReadOnlyList parameters) + private static int? AddPropertySet(SceneDocument scene, string name, string key, IReadOnlyList parameters, + Element? source = null) { var properties = new List(); + AddSourceId("Revit Element ID", source?.SourceElementId); + AddSourceId("Revit Type ID", source?.SourceTypeId); + AddSourceId("Revit Host ID", source?.SourceHostId); foreach (var parameter in parameters) { // An approximate or unset parameter is a reader estimate or placeholder, not a value stored in Revit. @@ -302,6 +306,12 @@ private static string CategoryName(Element? element) => int id = scene.PropertySets.Count + 1; scene.PropertySets.Add(new ScenePropertySet { Id = id, Name = name, Key = key, Properties = properties }); return id; + + void AddSourceId(string label, string? id) + { + if (id != null) + properties.Add(new SceneProperty { Name = label, Value = SceneValue.FromText(id) }); + } } /// The display string of the value as gives it, with the invariant culture; @@ -318,6 +328,7 @@ StorageType.Double when parameter.Value is double value && parameter.SpecType is // A user parameter that stores an integer is an Integer or a Yes/No, both shown by AsValueString as the number. A // built-in one may be an enumeration, which the public API cannot tell from a number, so it is left out. StorageType.Integer when parameter.Id > 0 && parameter.Value is int value => value.ToString(CultureInfo.InvariantCulture), + StorageType.ElementId => parameter.SourceElementId, // An ElementId: the public API does not give the name Revit shows for the referenced element. _ => null, }; diff --git a/src/RvtIO/Compact/CompactJsonWriter.cs b/src/RvtIO/Compact/CompactJsonWriter.cs index 591c48b6..9052879d 100644 --- a/src/RvtIO/Compact/CompactJsonWriter.cs +++ b/src/RvtIO/Compact/CompactJsonWriter.cs @@ -67,7 +67,7 @@ public void WriteNode(in CompactNode node) } _writer.WriteStartObject(); - Span id = stackalloc char[11]; + Span id = stackalloc char[20]; node.ElementId.TryFormat(id, out int idLength, default, CultureInfo.InvariantCulture); _writer.WriteString(ObjectKey, id[..idLength]); _writer.WriteString(NameKey, node.ClassName.Length == 0 ? node.ClassName : _classNamePrefix + node.ClassName); @@ -104,7 +104,7 @@ private void WritePseudoObject(string name) } /// Puts the indexes of into _order sorted by group, label and insertion index. - private int SortProperties(int elementId, IReadOnlyList properties) + private int SortProperties(long elementId, IReadOnlyList properties) { int count = properties.Count; if (count == 0) return 0; diff --git a/src/RvtIO/Compact/CompactNode.cs b/src/RvtIO/Compact/CompactNode.cs index 13ee2eea..d6706f8b 100644 --- a/src/RvtIO/Compact/CompactNode.cs +++ b/src/RvtIO/Compact/CompactNode.cs @@ -9,7 +9,7 @@ namespace RvtIO.Compact; /// Name of the second of the two preceding objects. /// Insertion-ordered properties; the writer sorts them. internal readonly record struct CompactNode( - int ElementId, + long ElementId, string ClassName, string UniqueId, string? CategoryLabel, diff --git a/src/RvtIO/Compact/CompactNodeBuilder.cs b/src/RvtIO/Compact/CompactNodeBuilder.cs index cfe4890d..2f2dd8ef 100644 --- a/src/RvtIO/Compact/CompactNodeBuilder.cs +++ b/src/RvtIO/Compact/CompactNodeBuilder.cs @@ -61,7 +61,19 @@ public CompactNode Build(Element element, IReadOnlyList propert string why = _identity.FamilyName(element).Unknown ?? _identity.CategoryLabel(element).Unknown ?? "undecided"; _unknownPseudo[why] = _unknownPseudo.GetValueOrDefault(why) + 1; } - return new CompactNode(element.Id, className ?? "", element.UniqueId ?? "", pseudo.CategoryLabel, pseudo.FamilyName, properties); + if (element.NativeTypeId != null || element.NativeHostId != null + || element.Parameters.Any(parameter => parameter.NativeElementId != null)) + { + var exactIds = new List(properties); + const string group = "Revit Element IDs"; + if (element.SourceTypeId is string typeId) exactIds.Add(new(group, "Type", typeId)); + if (element.SourceHostId is string hostId) exactIds.Add(new(group, "Host", hostId)); + foreach (var parameter in element.Parameters.DistinctBy(parameter => parameter.Id)) + if (parameter.SourceElementId is string reference) + exactIds.Add(new(group, parameter.Id.ToString(System.Globalization.CultureInfo.InvariantCulture), reference)); + properties = exactIds; + } + return new CompactNode(element.ElementId, className ?? "", element.UniqueId ?? "", pseudo.CategoryLabel, pseudo.FamilyName, properties); } /// The class name for the property rules (): the same as . diff --git a/src/RvtIO/Ifc/IfcExporter.cs b/src/RvtIO/Ifc/IfcExporter.cs index 6d3fcbe4..001814c7 100644 --- a/src/RvtIO/Ifc/IfcExporter.cs +++ b/src/RvtIO/Ifc/IfcExporter.cs @@ -427,6 +427,7 @@ private void ExportDocument(RevitFileInfo info, TextWriter output) if (LengthUnit is { } explicitUnit && !Enum.IsDefined(explicitUnit)) throw new ArgumentOutOfRangeException(nameof(LengthUnit), explicitUnit, "Unsupported IFC length unit family."); var w = new StepWriter(); + Dictionary? sourceProductTags = null; // Without an explicit LengthUnit choice, the legacy profile writes millimetres whatever the // document says and the current profile follows the length unit of the project. _unitFamily = LengthUnit ?? (CurrentProfile ? IfcLengthUnitChoice.Family(info.SerializedLengthUnit) : IfcUnitFamily.Millimetre); @@ -4661,7 +4662,7 @@ fallbackSourceOwnerTagId is null string productGlobalId = (ExportIdProductClasses.Contains(ifcType) ? ResolveExactElementGlobalId(elem, _usedExportIds, handleBased: CurrentProfile) : null) - ?? IfcGuid.FromElementId(elem.Id); + ?? IfcGuid.FromElementId(elem.ElementId); string elemArgs = ifcType switch { "IFCWALLSTANDARDCASE" or "IFCWALL" => @@ -4705,6 +4706,8 @@ fallbackSourceOwnerTagId is null }; int elemEntityId = w.Add(ifcType, elemArgs); + if (elem.NativeId is long sourceId && ExportsIfcTagAttribute(ifcType)) + (sourceProductTags ??= [])[elemEntityId] = (elem.Id, sourceId); exportedIfcElements[elem.Id] = (elemEntityId, elemPlacementId, ifcType); exportedGlobalIds[elem.Id] = productGlobalId; if (rampPartBodies != null) @@ -6765,6 +6768,18 @@ void AddWallConnection(int relating, int related, string relatingType, string re } if (CurrentProfile) ApplyCurrentOpeningOrder(w, openingOrderKeys); w.RewriteArguments(IfcLengthUnit.Converter(_unitFamily, CurrentProfile)); + if (sourceProductTags != null) + { + for (int i = 0; i < w.EntityCount; i++) + { + var (id, type, args) = w.EntityAt(i); + if (!sourceProductTags.TryGetValue(id, out var tag) || !ExportsIfcTagAttribute(type)) continue; + var attributes = SplitStepArguments(args); + if (attributes.Length <= 7 || attributes[7] != S(tag.Key.ToString())) continue; + attributes[7] = S(tag.SourceId.ToString(System.Globalization.CultureInfo.InvariantCulture)); + w.ReplaceArgs(i, string.Join(",", attributes)); + } + } w.WriteTo(output, headerFileName, "IFC2X3", desc, appName, headerOrganization, Timestamp); ExportedProducts = exportedCount; diff --git a/src/RvtIO/Ifc/IfcGuid.cs b/src/RvtIO/Ifc/IfcGuid.cs index 3d561c2c..9fb312db 100644 --- a/src/RvtIO/Ifc/IfcGuid.cs +++ b/src/RvtIO/Ifc/IfcGuid.cs @@ -90,8 +90,12 @@ public static string ToIfcGuid(Guid guid) /// Generate a deterministic IFC GUID from element ID and a namespace string. // The default namespace seed is fixed: it keeps the generated GUIDs stable across releases. public static string FromElementId(int elemId, string ns = "RevitReader") + => FromElementId((long)elemId, ns); + + /// Generate a deterministic fallback IFC GUID from the complete source element ID. + public static string FromElementId(long elemId, string ns = "RevitReader") { - var bytes = Encoding.UTF8.GetBytes($"{ns}:{elemId}"); + var bytes = Encoding.UTF8.GetBytes(FormattableString.Invariant($"{ns}:{elemId}")); var hash = MD5.HashData(bytes); hash[6] = (byte)((hash[6] & 0x0F) | 0x30); hash[8] = (byte)((hash[8] & 0x3F) | 0x80); diff --git a/src/RvtIO/Internal/ParsingState.cs b/src/RvtIO/Internal/ParsingState.cs index 567ba35b..a6ef9a3d 100644 --- a/src/RvtIO/Internal/ParsingState.cs +++ b/src/RvtIO/Internal/ParsingState.cs @@ -20,6 +20,7 @@ internal class ParsingState public Dictionary> OwnCurrentWallFaceGroups { get; } = new(); /// Element-table membership. Values are zero: ElemRec has no type/class column. public Dictionary ElemTable { get; set; } = new(); + internal ElementIdMap? ElementIds { get; set; } /// Per-element workset ids from ElemTable offset-20 (workshared files only). public Dictionary ElemWorksets { get; set; } = new(); diff --git a/src/RvtIO/Model/Element.cs b/src/RvtIO/Model/Element.cs index dbac10f9..8d8d17ff 100644 --- a/src/RvtIO/Model/Element.cs +++ b/src/RvtIO/Model/Element.cs @@ -17,9 +17,47 @@ public class Element /// A copy that shares all members with this element; the caller replaces what it changes. internal Element ShallowCopy() => (Element)MemberwiseClone(); - /// The element id. + /// The document-local element key used by the existing 32-bit APIs. Use + /// for the ID as stored in the RVT. public int Id { get; set; } + /// The exact Revit element ID. + [JsonIgnore] + public long ElementId => NativeId ?? Id; + + /// The source ID as decimal text when it differs from the local key. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public string? SourceElementId => NativeId?.ToString(System.Globalization.CultureInfo.InvariantCulture); + + /// The exact type element ID, or the native unresolved sentinel. + [JsonIgnore] + public long TypeElementId => NativeTypeId ?? TypeId; + + /// The source type ID as decimal text when it differs from the local key. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public string? SourceTypeId => NativeTypeId?.ToString(System.Globalization.CultureInfo.InvariantCulture); + + /// The exact host element ID when a host was resolved. + [JsonIgnore] + public long? HostElementId => NativeHostId ?? HostId; + + /// The source host ID as decimal text when it differs from the local key. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public string? SourceHostId => NativeHostId?.ToString(System.Globalization.CultureInfo.InvariantCulture); + + internal long? NativeId { get; set; } + internal long? NativeTypeId { get; set; } + internal long? NativeHostId { get; set; } + + /// The element ID recorded in the creation history, when available. + [JsonIgnore] + public long? OriginalElementId { get; internal set; } + + /// The full creation ID as decimal text when it exceeds the supported UniqueId derivation range. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public string? SourceOriginalElementId => OriginalElementId is > uint.MaxValue + ? OriginalElementId.Value.ToString(System.Globalization.CultureInfo.InvariantCulture) : null; + /// Resolved type element id; nonpositive when unresolved. public int TypeId { get; set; } diff --git a/src/RvtIO/Model/Parameter.cs b/src/RvtIO/Model/Parameter.cs index 3c76cd41..e54226ca 100644 --- a/src/RvtIO/Model/Parameter.cs +++ b/src/RvtIO/Model/Parameter.cs @@ -286,13 +286,23 @@ public int AsInteger() return Value?.ToString(); } - /// Get the value as ElementId (int). Returns -1 (InvalidElementId) if not an ElementId parameter. + /// Returns the legacy document-local element key. Use for the source ID. public int AsElementId() { if (Value is int i) return i; return -1; } + /// The exact element reference, or -1 if the parameter holds no element ID. + public long AsElementId64() => + StorageType == StorageType.ElementId && Value is int key ? NativeElementId ?? key : -1; + + /// The source reference as decimal text when it differs from the local key. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public string? SourceElementId => NativeElementId?.ToString(CultureInfo.InvariantCulture); + + internal long? NativeElementId { get; set; } + /// /// Get a formatted display string for the value. /// Uses ForgeTypeId spec registry for precise unit conversion when available, @@ -322,7 +332,7 @@ public int AsElementId() { return catName; } - return elemId.ToString(CultureInfo.InvariantCulture); + return AsElementId64().ToString(CultureInfo.InvariantCulture); } if (Value is double d) { diff --git a/src/RvtIO/Model/ParameterListConverter.cs b/src/RvtIO/Model/ParameterListConverter.cs index aee5304c..4ba42d84 100644 --- a/src/RvtIO/Model/ParameterListConverter.cs +++ b/src/RvtIO/Model/ParameterListConverter.cs @@ -28,7 +28,10 @@ public override void Write(Utf8JsonWriter writer, List value, JsonSer // rare duplicate id does not produce an invalid repeated JSON property. if (!seen.Add(p.Id)) continue; writer.WritePropertyName(p.Id.ToString(System.Globalization.CultureInfo.InvariantCulture)); - JsonSerializer.Serialize(writer, p.Value, options); + if (p.SourceElementId is string sourceId) + writer.WriteStringValue(sourceId); + else + JsonSerializer.Serialize(writer, p.Value, options); } writer.WriteEndObject(); } diff --git a/src/RvtIO/Model/RevitFileInfo.cs b/src/RvtIO/Model/RevitFileInfo.cs index 1c7a2cd1..240f8a7b 100644 --- a/src/RvtIO/Model/RevitFileInfo.cs +++ b/src/RvtIO/Model/RevitFileInfo.cs @@ -29,6 +29,34 @@ public partial class RevitFileInfo /// All elements of the file. public List Elements { get; set; } = new(); + internal Parsing.ElementIdMap? ElementIds { get; set; } + + /// Resolves any document-local element key to its original signed 64-bit ID. + public long GetSourceElementId(int key) => ElementIds?.SourceId(key) ?? key; + + /// Exact decimal source IDs for keys remapped while reading the model. + [System.Text.Json.Serialization.JsonIgnore(Condition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull)] + public IReadOnlyDictionary? SourceElementIds => ElementIds?.SourceIdsAsText(); + + internal void AttachSourceElementIds() + { + if (ElementIds is not { } ids) return; + long? WhenRemapped(int key) + { + long sourceId = ids.SourceId(key); + return key == sourceId ? null : sourceId; + } + foreach (var element in Elements) + { + element.NativeId = WhenRemapped(element.Id); + element.NativeTypeId = WhenRemapped(element.TypeId); + element.NativeHostId = element.HostId is int host ? WhenRemapped(host) : null; + foreach (var parameter in element.Parameters) + if (parameter.StorageType == StorageType.ElementId && parameter.Value is int key) + parameter.NativeElementId = WhenRemapped(key); + } + } + /// The whole ElemTable was decoded and verified, so a parsed record without a row is a /// record the exporter never iterates (a deleted or embedded element), not an element lost to a damaged stream. [System.Text.Json.Serialization.JsonIgnore] diff --git a/src/RvtIO/Parsing/ElemTableReader.cs b/src/RvtIO/Parsing/ElemTableReader.cs index 61a57d19..4bad7711 100644 --- a/src/RvtIO/Parsing/ElemTableReader.cs +++ b/src/RvtIO/Parsing/ElemTableReader.cs @@ -43,10 +43,17 @@ public static Dictionary Read(RootStorage root, public static Dictionary Read(RootStorage root, out Dictionary worksets, out Dictionary creationDates, out bool exact, (int MaxBytes, int MaxIterations)? limits = null, RvtReadDiagnostics? diagnostics = null) + => Read(root, out worksets, out creationDates, out exact, out _, allowWideIds: false, limits, diagnostics); + + internal static Dictionary Read(RootStorage root, + out Dictionary worksets, out Dictionary creationDates, out bool exact, + out ElementIdMap? ids, bool allowWideIds, + (int MaxBytes, int MaxIterations)? limits = null, RvtReadDiagnostics? diagnostics = null) { worksets = new(); creationDates = new(); exact = false; + ids = null; var result = new Dictionary(); try { @@ -63,32 +70,27 @@ public static Dictionary Read(RootStorage root, var formats = FormatsSchema.TryRead(root); bool shipped = exactTable.Length >= 2 && BitConverter.ToUInt16(exactTable, 0) == ElementExportIds.ElemTableClassId && SchemaRelease.AllowsShipped(formats?.Release ?? SchemaRelease.Of(root, null), 2022); - if (exactTable.Length >= 2 && !shipped - && formats is { } schema && ElemTableLayout.TryParse(exactTable, schema) is { } rows) - { - foreach (var row in rows) - { - // Id 0 is a real row (ProjectPhase / DimensionStyle) in ElemTable across wide and 32-bit schemas. - if (row.Id > int.MaxValue) ThrowUnsupportedId(row.Id); - result[(uint)row.Id] = 0; - creationDates[(uint)row.Id] = row.CreationDate; - if (row.PartitionId >= 0) worksets[(uint)row.Id] = (uint)row.PartitionId; - } - exact = result.Count > 0; - return result; - } - if (exactTable.Length >= 2 && !shipped - && FileSchema.Read(root) is { } wideSchema - && WideElementRecords.ParseElemTable(exactTable, wideSchema) is { } wide) + if (exactTable.Length >= 2 && !shipped) { - if (wide.UnsupportedId is long idOutsideRange) ThrowUnsupportedId(idOutsideRange); - foreach (var (id, history) in wide.Histories) + var rows = formats == null ? null : ElemTableLayout.TryParse(exactTable, formats); + if (rows == null && FileSchema.Read(root) is { } fileSchema) + rows = WideElementRecords.ParseElemTable(exactTable, fileSchema); + if (rows != null) { - result[id] = 0; // ElemRec holds history and ownership, not a class id. - creationDates[id] = history.CreationDate; + if (allowWideIds && rows.Any(row => row.Id > int.MaxValue || row.OwningId is < int.MinValue or > int.MaxValue)) + ids = new ElementIdMap(rows); + foreach (var row in rows) + { + // Id 0 is a real row (ProjectPhase / DimensionStyle) in ElemTable across wide and 32-bit schemas. + if (row.Id > int.MaxValue && ids == null) ThrowUnsupportedId(row.Id); + uint key = ids == null ? (uint)row.Id : (uint)ids.Key(row.Id); + result[key] = 0; + creationDates[key] = row.CreationDate; + if (row.PartitionId >= 0) worksets[key] = (uint)row.PartitionId; + } + exact = result.Count > 0; + return result; } - exact = result.Count > 0; - return result; } // The release in force has a layout other than the one the bytes have: no row is guessed. if (formats != null && ElemTableLayout.DisagreesWithRelease(formats)) return result; diff --git a/src/RvtIO/Parsing/ElementBuilder.cs b/src/RvtIO/Parsing/ElementBuilder.cs index debf936b..4e7ae204 100644 --- a/src/RvtIO/Parsing/ElementBuilder.cs +++ b/src/RvtIO/Parsing/ElementBuilder.cs @@ -4971,13 +4971,17 @@ internal static (int Elements, int ReplacedUniqueIds) ApplyExportIds( // Id 0 is a valid ElemTable row (ProjectPhase / DimensionStyle) across wide and native R22 tables. if (element.Id < 0 || state.ElemRecHistories is not { } histories - || !histories.TryGetValue((uint)element.Id, out var history) - || ElementExportIds.EpisodeGuid(history, state.HistoryEpisodeGuids, state.EpisodeTableX) - is not Guid episode) + || !histories.TryGetValue((uint)element.Id, out var history)) continue; - element.SerializedExportId = ElementExportIds.ExportId(episode, history.OriginalElementId); - element.SerializedHandleExportId = ElementExportIds.ExportId(episode, (uint)element.Id); - string uniqueId = ElementExportIds.UniqueId(episode, history.OriginalElementId); + element.OriginalElementId = history.OriginalElementId; + if (history.OriginalElementId is < 0 or > uint.MaxValue + || ElementExportIds.EpisodeGuid(history, state.HistoryEpisodeGuids, state.EpisodeTableX) is not Guid episode) + continue; + uint originalId = (uint)history.OriginalElementId; + element.SerializedExportId = ElementExportIds.ExportId(episode, originalId); + if (element.ElementId is >= 0 and <= uint.MaxValue) + element.SerializedHandleExportId = ElementExportIds.ExportId(episode, (uint)element.ElementId); + string uniqueId = ElementExportIds.UniqueId(episode, originalId); if (element.UniqueId != null && element.UniqueId != uniqueId) replaced++; element.UniqueId = uniqueId; applied++; diff --git a/src/RvtIO/Parsing/ElementExportIds.cs b/src/RvtIO/Parsing/ElementExportIds.cs index 89cc63d5..195dbb26 100644 --- a/src/RvtIO/Parsing/ElementExportIds.cs +++ b/src/RvtIO/Parsing/ElementExportIds.cs @@ -4,7 +4,7 @@ namespace RvtIO.Parsing; /// History of one element as stored in its ElemRec record: the id the element was created with and /// the episode it was created in (a reverse index into the episode list). /// -internal readonly record struct ElemRecHistory(uint OriginalElementId, int CreationDate); +internal readonly record struct ElemRecHistory(long OriginalElementId, int CreationDate); /// Element UniqueId and export id from the document's own tables. internal static class ElementExportIds diff --git a/src/RvtIO/Parsing/ElementHeaderCategory.cs b/src/RvtIO/Parsing/ElementHeaderCategory.cs index 07ae181b..8df77f1e 100644 --- a/src/RvtIO/Parsing/ElementHeaderCategory.cs +++ b/src/RvtIO/Parsing/ElementHeaderCategory.cs @@ -135,7 +135,8 @@ public static void Record(ParsingState state, byte[] buffer, int recordStart, ui /// Adds the outline verdict of one more record of an element: the first verdict stands, a verdict that /// differs from it (or an unknown one) turns the element unknown, and unknown stays unknown. /// - internal static void Merge(Dictionary boxes, uint elementId, ElementHeaderBox? box) + internal static void Merge(Dictionary boxes, TId elementId, ElementHeaderBox? box) + where TId : notnull { if (!boxes.TryGetValue(elementId, out ElementHeaderBox? previousBox)) boxes[elementId] = box; else if (!SameBox(previousBox, box)) boxes[elementId] = null; diff --git a/src/RvtIO/Parsing/ElementIdMap.cs b/src/RvtIO/Parsing/ElementIdMap.cs new file mode 100644 index 00000000..2d74650b --- /dev/null +++ b/src/RvtIO/Parsing/ElementIdMap.cs @@ -0,0 +1,50 @@ +namespace RvtIO.Parsing; + +/// Document-local keys for the geometry readers whose records use signed 32-bit IDs. +internal sealed class ElementIdMap +{ + private readonly HashSet _occupied = []; + private readonly Dictionary _keys = []; + private readonly Dictionary _sourceIds = []; + private int _nextKey = int.MaxValue; + + internal ElementIdMap(IReadOnlyList rows) + { + foreach (var row in rows) + if (row.Id <= int.MaxValue) _occupied.Add((int)row.Id); + foreach (var row in rows) + if (row.OwningId is > 0 and <= int.MaxValue) _occupied.Add((int)row.OwningId); + foreach (var row in rows) + if (row.Id > int.MaxValue) Key(row.Id); + } + + internal long SourceId(int key) => _sourceIds.TryGetValue(key, out long id) ? id : key; + + internal IReadOnlyDictionary? SourceIdsAsText() => _sourceIds.Count == 0 ? null + : _sourceIds.ToDictionary(pair => pair.Key, pair => pair.Value.ToString(System.Globalization.CultureInfo.InvariantCulture)); + + internal bool TryGetKey(long sourceId, out int key) + { + if (_keys.TryGetValue(sourceId, out key)) return true; + if (sourceId is < int.MinValue or > int.MaxValue) return false; + key = (int)sourceId; + return !_sourceIds.ContainsKey(key); + } + + internal int Key(long sourceId) + { + if (sourceId is >= int.MinValue and <= 0) return (int)sourceId; + if (_keys.TryGetValue(sourceId, out int key)) return key; + if (sourceId <= int.MaxValue && sourceId > 0 && !_sourceIds.ContainsKey((int)sourceId)) + { + _occupied.Add((int)sourceId); + return (int)sourceId; + } + while (_nextKey > 0 && !_occupied.Add(_nextKey)) _nextKey--; + if (_nextKey == 0) throw new InvalidOperationException("The document has exhausted the local element key range."); + key = _nextKey--; + _keys.Add(sourceId, key); + _sourceIds.Add(key, sourceId); + return key; + } +} diff --git a/src/RvtIO/Parsing/GridAxisReader.cs b/src/RvtIO/Parsing/GridAxisReader.cs index 387d37f3..21ff8429 100644 --- a/src/RvtIO/Parsing/GridAxisReader.cs +++ b/src/RvtIO/Parsing/GridAxisReader.cs @@ -13,7 +13,7 @@ internal sealed class GridAxisReader private readonly Dictionary _segments = []; private readonly Dictionary _chains = []; - internal GridAxisReader(SchemaDocument schema, IReadOnlyDictionary entities) + internal GridAxisReader(SchemaDocument schema, IReadOnlyDictionary entities, ElementIdMap? ids = null) { _walker = new(schema, static (type, field) => type.Name switch { @@ -25,7 +25,7 @@ internal GridAxisReader(SchemaDocument schema, IReadOnlyDictionary type.Name + "." + field.Name, "Plane" or "CylSurf" => type.Name + "." + field.Name, _ => null, - }, [Pair], captureRootPointers: true); + }, [Pair], captureRootPointers: true, ids: ids); _walker.UseEntitySchemas(entities, passUnknown: true); } diff --git a/src/RvtIO/Parsing/R22Transcoder.cs b/src/RvtIO/Parsing/R22Transcoder.cs index 9b93c86c..ea65d1e4 100644 --- a/src/RvtIO/Parsing/R22Transcoder.cs +++ b/src/RvtIO/Parsing/R22Transcoder.cs @@ -29,13 +29,14 @@ private sealed class Fail(string message) : Exception(message); private readonly Dictionary _tagMap = new(); private readonly int _sourceWidth; private readonly int _sourceIdentifier; + private readonly ElementIdMap? _ids; private readonly Dictionary _plans = new(); /// Source fields in serialization order, the target class of the same name and the target field positions by (declaring class, field). private sealed record Plan((SchemaClass Declaring, SchemaField Field)[] Source, (SchemaClass Declaring, SchemaField Field)[] Target, int[] TargetIndex, bool[] TargetPresent, bool Reordered, bool[] Narrow); - internal R22Transcoder(SchemaDocument source, SchemaDocument target, int sourceIdWidth) + internal R22Transcoder(SchemaDocument source, SchemaDocument target, int sourceIdWidth, ElementIdMap? ids = null) { _source = source.Classes.GroupBy(c => c.Id).ToDictionary(g => g.Key, g => g.First()); _target = target.Classes.GroupBy(c => c.Id).ToDictionary(g => g.Key, g => g.First()); @@ -44,6 +45,7 @@ internal R22Transcoder(SchemaDocument source, SchemaDocument target, int sourceI foreach (var c in source.Classes) if (_targetByName.TryGetValue(c.Name, out int id)) _tagMap[c.Id] = id; _sourceWidth = sourceIdWidth; + _ids = ids; _sourceIdentifier = source.Classes.FirstOrDefault(c => c.Name == "ElementId")?.Id ?? -1; } @@ -146,7 +148,8 @@ bool HasRecordlessSectionAhead(int at) var (data, start, _) = source.Bytes(item); long at = flushed + output.Length; WriteBlock(data, start, output, stats, root: item.Channel == 102); - items.Add(new(item.Channel, item.Owner, at, (int)(flushed + output.Length - at))); + ulong owner = _ids == null ? item.Owner : unchecked((uint)_ids.Key(unchecked((long)item.Owner))); + items.Add(new(item.Channel, owner, at, (int)(flushed + output.Length - at))); if (output.Length >= 1 << 20) { flushed += output.Length; segments.Add(output.ToArray()); output.SetLength(0); } } if (output.Length > 0) segments.Add(output.ToArray()); @@ -185,7 +188,9 @@ private static bool TryBlock(byte[] b, int p, int w, out int length) private void WriteId(byte[] b, int p, MemoryStream output) { Span id = stackalloc byte[4]; - BinaryPrimitives.WriteUInt32LittleEndian(id, BitConverter.ToUInt32(b, p)); + uint key = _ids != null && _sourceWidth == 8 + ? unchecked((uint)_ids.Key(BitConverter.ToInt64(b, p))) : BitConverter.ToUInt32(b, p); + BinaryPrimitives.WriteUInt32LittleEndian(id, key); output.Write(id); } @@ -573,8 +578,8 @@ private void ReadReference(Context c, SchemaField f, int depth) if (_sourceWidth == 8 && !c.Cutting) { long id = BitConverter.ToInt64(c.D, p); - if (id < int.MinValue || id > int.MaxValue) throw new Fail("id beyond 32 bits"); - c.Edits.Add(new(p, p + 8, BitConverter.GetBytes((int)id))); + if (_ids == null && (id < int.MinValue || id > int.MaxValue)) throw new Fail("id beyond 32 bits"); + c.Edits.Add(new(p, p + 8, BitConverter.GetBytes(_ids?.Key(id) ?? (int)id))); } return; } diff --git a/src/RvtIO/Parsing/RebarReader.cs b/src/RvtIO/Parsing/RebarReader.cs index ee238979..a6efc92f 100644 --- a/src/RvtIO/Parsing/RebarReader.cs +++ b/src/RvtIO/Parsing/RebarReader.cs @@ -124,7 +124,7 @@ internal static bool HeldLayout(FileSchema schema) => internal static ReinforcementData Read( IReadOnlyList> streams, FileSchema schema, IReadOnlySet wanted, IReadOnlyDictionary? entitySchemas = null, bool passUnknownEntities = false, - IReadOnlyList? framed = null) + IReadOnlyList? framed = null, ElementIdMap? ids = null) { var result = new Dictionary(); var joists = new Dictionary(); @@ -144,7 +144,7 @@ internal static ReinforcementData Read( var joist = schema.ByName("JoistSystem")?.Id; var joistType = schema.ByName("JoistSystemAttr")?.Id; if (rebar == null || system == null || inSystem == null || barType == null || settings == null || shape == null || joist == null || joistType == null) return empty; - var walker = new WideBlockWalker(schema.Document, Key, []); + var walker = new WideBlockWalker(schema.Document, Key, [], ids: ids); if (entitySchemas != null) walker.UseEntitySchemas(entitySchemas, passUnknownEntities); var layers = new Dictionary>(); var members = new Dictionary(); @@ -221,7 +221,7 @@ internal static ReinforcementData Read( foreach (var ((layer, index), bar) in ReadHeld(walk.Captures)) held.TryAdd((id, layer, index), bar); } else if (ReadMember(walker, walk, byQueue) is { } member) members.TryAdd(id, member); - }, framed); + }, framed, ids); RebarBars? Solve(PendingBar bar) => diameters.TryGetValue(bar.BarTypeId, out var barDiameters) && barKinds.TryGetValue(bar.BarTypeId, out var kind) && shapeDefinitions.TryGetValue(bar.ShapeId, out var definition) ? SolveShapeDriven(bar, definition, hookKinds, kind, barDiameters.Model) : null; @@ -229,7 +229,7 @@ internal static ReinforcementData Read( if (Solve(bar) is { } solved) result.TryAdd(id, solved); // the items of a container that can be solved; their bar types come with the pass, like those of the other bars. They are in the // coordinates of the host instance, so a container whose host has no frame is not written. - var hostFrames = ReadHostFrames(walker, streams, framed, schema, containers.Values.Select(c => (uint)c.HostId).ToHashSet()); + var hostFrames = ReadHostFrames(walker, streams, framed, schema, containers.Values.Select(c => (uint)c.HostId).ToHashSet(), ids); foreach (var (id, (typeId, hostId, inAssembly, items)) in containers) { if (!hostFrames.TryGetValue((uint)hostId, out var hostFrame)) continue; @@ -301,7 +301,7 @@ private static (int TypeId, int HostId, bool InAssembly, List Items) /// each of the FamilyInstance elements (FamilyInstance.m_instOrigin, m_RefDir and m_zAxis); a host that is no /// FamilyInstance or whose values are not a frame has none. private static Dictionary ReadHostFrames(WideBlockWalker walker, IReadOnlyList> streams, - IReadOnlyList? framed, FileSchema schema, IReadOnlySet hosts) + IReadOnlyList? framed, FileSchema schema, IReadOnlySet hosts, ElementIdMap? ids) { var frames = new Dictionary(); if (hosts.Count == 0) return frames; @@ -322,7 +322,7 @@ private static Dictionary ReadHostFrames(WideBlockWalker walker, if (Math.Abs(Dot(x, x) - 1) > 1e-9 || Math.Abs(Dot(z, z) - 1) > 1e-9 || Math.Abs(Dot(x, z)) > 1e-9) return; double[] y = [z[1] * x[2] - z[2] * x[1], z[2] * x[0] - z[0] * x[2], z[0] * x[1] - z[1] * x[0]]; frames.TryAdd(id, [x[0], y[0], z[0], x[1], y[1], z[1], x[2], y[2], z[2], origin[0], origin[1], origin[2]]); - }, framed); + }, framed, ids); return frames; } diff --git a/src/RvtIO/Parsing/Revit2027ApiValues.HostQuantities.cs b/src/RvtIO/Parsing/Revit2027ApiValues.HostQuantities.cs index 55337be7..9f61bf39 100644 --- a/src/RvtIO/Parsing/Revit2027ApiValues.HostQuantities.cs +++ b/src/RvtIO/Parsing/Revit2027ApiValues.HostQuantities.cs @@ -35,7 +35,7 @@ BuiltInCategory.OST_GenericModel or BuiltInCategory.OST_PlumbingFixtures or Buil bool volumeMissing = (volumeLevel.HasValue || rawVolume) && !HasValue(element, BuiltInParameter.HOST_VOLUME_COMPUTED); if ((!areaMissing && !volumeMissing) || ExactRoot(state, element.Id) is not { } root) continue; - geometry ??= new WideSolidQuantities(schema, frames); + geometry ??= new WideSolidQuantities(schema, frames, state.ElementIds); bool curtainDoor = false; if (wallArea && areaMissing) { diff --git a/src/RvtIO/Parsing/WideBlockWalker.cs b/src/RvtIO/Parsing/WideBlockWalker.cs index 54ae16a9..e1715c10 100644 --- a/src/RvtIO/Parsing/WideBlockWalker.cs +++ b/src/RvtIO/Parsing/WideBlockWalker.cs @@ -103,11 +103,12 @@ private sealed class Fail(string message) : Exception(message); /// The capture key of a scalar field (null: not captured); a fixed array adds "@index". /// Classes whose objects are returned as . internal WideBlockWalker(SchemaDocument schema, Func keyOf, IEnumerable recordClassNames, - bool captureRootPointers = false) + bool captureRootPointers = false, ElementIdMap? ids = null) { _classes = schema.Classes.GroupBy(c => c.Id).ToDictionary(g => g.Key, g => g.First()); _keyOf = keyOf; _captureRootPointers = captureRootPointers; + _ids = ids; var names = recordClassNames.ToHashSet(StringComparer.Ordinal); _recordClasses = _classes.Values.Where(c => names.Contains(c.Name)).Select(c => c.Id).ToHashSet(); int max = _classes.Keys.Max(); @@ -134,6 +135,8 @@ internal void UseEntitySchemas(IReadOnlyDictionary schemas /// The class of a queue entry; the values of an extensible storage entity (a negative entry) are an ESBlob. internal SchemaClass? Class(int id) => id < 0 ? _entityBlob : _classes.GetValueOrDefault(id); + private readonly ElementIdMap? _ids; + private (SchemaClass Declaring, SchemaField Field)[] Chain(int classId) => _chains.GetOrAdd(classId, id => { var order = new List(); @@ -525,6 +528,7 @@ private void ReadReference(Context c, SchemaClass declaring, SchemaField f, stri // ElementId: Identifier.m_id (4 bytes) or Identifier.m_id64 (8 bytes) int p = Take(c, _idWidth); long id = _idWidth == 8 ? BitConverter.ToInt64(c.D, p) : BitConverter.ToInt32(c.D, p); + if (_ids != null) id = _ids.Key(id); if (key != null) walk.Captures.Add(new(key, CaptureKind.Integer, id, 0, null, c.AtRoot && depth == 0, c.QueueIndex, declaring.Name, f.Name)); if (record != null) record[f.Name] = id; return; diff --git a/src/RvtIO/Parsing/WideElementRecords.cs b/src/RvtIO/Parsing/WideElementRecords.cs index c929c8ce..54ea0612 100644 --- a/src/RvtIO/Parsing/WideElementRecords.cs +++ b/src/RvtIO/Parsing/WideElementRecords.cs @@ -25,22 +25,13 @@ namespace RvtIO.Parsing; /// internal static class WideElementRecords { - internal sealed record Result( - Dictionary Histories, - Dictionary OwningElementIds, - long? UnsupportedId); - /// Byte width of the element id of this schema (ElemRec.m_id): 4 up to Revit 2023, 8 from Revit 2024; null otherwise. internal static int? IdWidth(FileSchema schema) => schema.ByName("ElemRec") is { } rec && FileSchema.SerializedFields(rec).FirstOrDefault(f => f.Name == "m_id") is { } id && schema.FieldSize(id) is (4 or 8) and int width && (SchemaRelease.IdWidth(schema.Release) is not int expected || expected == width) ? width : null; - private static ulong ReadId(byte[] data, int at, int width) - => width == 8 ? BitConverter.ToUInt64(data, at) : BitConverter.ToUInt32(data, at); - - /// Element id to ElemRec history and owner from a decoded Global/ElemTable stream, or null when the - /// schema does not declare the 64-bit ElemRec layout or the stream does not match it. - internal static Result? ParseElemTable(byte[] data, FileSchema schema) + /// Reads the schema-declared rows without applying the public model's ID range. + internal static List? ParseElemTable(byte[] data, FileSchema schema) { var table = schema.ByName("ElemTable"); var rec = schema.ByName("ElemRec"); @@ -58,39 +49,33 @@ private static ulong ReadId(byte[] data, int at, int width) || schema.FixedSize(rec.Id) is not int length || IdWidth(schema) is not int width || schema.FieldSize(recFields.First(f => f.Name == "m_OwningElementId")) != width - || schema.FieldSize(historyFields[0]) != width || schema.FieldSize(historyFields[1]) != 4 + || schema.FieldSize(recFields.First(f => f.Name == "m_partitionId")) != 4 + || schema.FieldSize(historyFields[0]) != width || schema.FieldSize(historyFields[1]) != 4 || schema.FieldSize(historyFields[2]) != 4 || schema.OffsetOf(rec.Id, "m_history") is not int historyAt || schema.OffsetOf(history.Id, "m_creationDate") is not int creationAt + || schema.OffsetOf(history.Id, "m_lastModificationDate") is not int modificationAt || schema.OffsetOf(rec.Id, "m_id") is not int idAt || schema.OffsetOf(rec.Id, "m_OwningElementId") is not int ownerAt - || data.Length < 6 || BitConverter.ToUInt16(data, 0) != table.Id) + || schema.OffsetOf(rec.Id, "m_partitionId") is not int partitionAt + || data.Length < ElemTableLayout.HeaderLength || BitConverter.ToUInt16(data, 0) != table.Id) return null; uint count = BitConverter.ToUInt32(data, 2); - if (6 + (long)count * length > data.Length) return null; + if (ElemTableLayout.HeaderLength + (long)count * length > data.Length) return null; - var histories = new Dictionary((int)count); - var owners = new Dictionary((int)count); + var rows = new List((int)count); long previous = -1; - long? unsupportedId = null; for (int i = 0; i < count; i++) { - int at = 6 + i * length; + int at = ElemTableLayout.HeaderLength + i * length; long id = width == 8 ? BitConverter.ToInt64(data, at + idAt) : BitConverter.ToUInt32(data, at + idAt); if (id <= previous) return null; previous = id; - if (id > int.MaxValue) - { - unsupportedId ??= id; - continue; - } - ulong original = ReadId(data, at + historyAt, width); - if (original > uint.MaxValue) continue; - histories[(uint)id] = new ElemRecHistory( - (uint)original, BitConverter.ToInt32(data, at + historyAt + creationAt)); + long original = width == 8 ? BitConverter.ToInt64(data, at + historyAt) : BitConverter.ToUInt32(data, at + historyAt); long owner = width == 8 ? BitConverter.ToInt64(data, at + ownerAt) : BitConverter.ToInt32(data, at + ownerAt); - if (owner >= int.MinValue && owner <= int.MaxValue) owners[(uint)id] = (int)owner; + rows.Add(new ElemTableLayout.Row(id, original, BitConverter.ToInt32(data, at + historyAt + creationAt), + BitConverter.ToInt32(data, at + partitionAt), owner, BitConverter.ToInt32(data, at + historyAt + modificationAt))); } - return new Result(histories, owners, unsupportedId); + return rows; } /// Header category and root class of the elements of the partition streams. @@ -98,19 +83,19 @@ internal sealed class Index { /// ElementHeader.m_categroryId per element id; the value is null when the id's records disagree or the /// value does not fit 32 bits. Ids without a record are absent. - internal Dictionary HeaderCategories { get; } = new(); + internal Dictionary HeaderCategories { get; } = new(); /// ElementHeader.m_designOptionId per element id, with the same agreement rule as . - internal Dictionary HeaderDesignOptions { get; } = new(); + internal Dictionary HeaderDesignOptions { get; } = new(); /// The outline the ElementHeader stores per element id (see ): a verdict when the /// records of the id agree it is there or agree there is none, null when they disagree or the structure was not read. Ids of a file whose /// schema does not have the header layout the reader relies on are absent. - internal Dictionary HeaderBoundingBoxes { get; } = new(); + internal Dictionary HeaderBoundingBoxes { get; } = new(); /// Class id (of the file's own schema) of the Element-derived block of the id; absent when the id has no /// such block or its blocks disagree. - internal Dictionary RootClasses { get; } = new(); + internal Dictionary RootClasses { get; } = new(); internal int Records { get; set; } internal int Blocks { get; set; } @@ -123,14 +108,17 @@ internal sealed class Index /// families are not read. Null when the schema does not declare the expected ElementHeader shape. internal static Index? BuildIndex( IReadOnlyList> streams, FileSchema schema, IReadOnlySet wanted, - Action? onRootBlock = null, IReadOnlyList? framed = null) - => BuildIndexWithPartitions(streams, schema, wanted, - onRootBlock == null ? null : (id, buf, off, size, cls, _) => onRootBlock(id, buf, off, size, cls), framed); + Action? onRootBlock = null, IReadOnlyList? framed = null, + ElementIdMap? ids = null) + => BuildIndexWithPartitions(streams, schema, + id => ids == null ? id is >= 0 and <= uint.MaxValue && wanted.Contains((uint)id) + : ids.TryGetKey(id, out int key) && wanted.Contains((uint)key), + onRootBlock == null ? null : (id, buf, off, size, cls, _) => onRootBlock(ids == null ? (uint)id : (uint)ids.Key(id), buf, off, size, cls), framed); - /// Same as , passing the framed partition number (or null when unframed) to . + /// Indexes serialized element IDs. The root callback also receives the framed partition number when available. internal static Index? BuildIndexWithPartitions( - IReadOnlyList> streams, FileSchema schema, IReadOnlySet wanted, - Action? onRootBlock, IReadOnlyList? framed = null) + IReadOnlyList> streams, FileSchema schema, Func wanted, + Action? onRootBlock, IReadOnlyList? framed = null) { if (framed != null && framed.Count != streams.Count) throw new ArgumentException("one framing entry per stream", nameof(framed)); var header = schema.ByName("ElementHeader"); @@ -153,9 +141,9 @@ internal sealed class Index foreach (int id in schema.Classes.Keys) known[id] = true; var index = new Index(); - var conflictCategory = new HashSet(); - var conflictDesignOption = new HashSet(); - var conflictClass = new HashSet(); + var conflictCategory = new HashSet(); + var conflictDesignOption = new HashSet(); + var conflictClass = new HashSet(); for (int s = 0; s < streams.Count; s++) { var frame = framed?[s] is { } f && f.IdWidth == width ? f : null; @@ -166,34 +154,35 @@ internal sealed class Index var buf = new byte[total]; int off = 0; foreach (var c in chunks) { Buffer.BlockCopy(c, 0, buf, off, c.Length); off += c.Length; } - var recordIds = new HashSet(); - var blockClasses = new Dictionary(); // -1: the stream holds blocks of two classes for the id - var rootBlocks = onRootBlock == null ? null : new List<(uint Id, int Offset, int Size, int Class)>(); - void Header(int p, int size, uint id) + var recordIds = new HashSet(); + var blockClasses = new Dictionary(); // -1: the stream holds blocks of two classes for the id + var rootBlocks = onRootBlock == null ? null : new List<(long Id, int Offset, int Size, int Class)>(); + void Header(int p, int size, long id) { index.Records++; - if (!wanted.Contains(id)) return; + if (!wanted(id)) return; recordIds.Add(id); RecordCategory(buf, p + width - 8, size, categoryWidth, entry, id, index, conflictCategory, conflictDesignOption, outlineTags); } - void Block(int p, int size, uint id, int cls) + void Block(int p, int size, long id, int cls) { index.Blocks++; - if (!isElement[cls] || !wanted.Contains(id)) return; + if (!isElement[cls] || !wanted(id)) return; blockClasses[id] = blockClasses.TryGetValue(id, out int prior) && prior != cls ? -1 : cls; rootBlocks?.Add((id, p + width + 8, size, cls)); } - if (frame == null) Walk(buf, header.Id, width, known, Header, Block); + if (frame == null) Walk(buf, header.Id, width, known, wanted, Header, Block); else foreach (var item in frame.Items) { - // an id the 32-bit element table cannot hold is skipped, as the scan skips it - if (item.Owner > uint.MaxValue) continue; + if (item.Owner > long.MaxValue) continue; + long owner = (long)item.Owner; + if (owner > uint.MaxValue && !wanted(owner)) continue; int p = (int)item.Offset; if (item.Channel == 101 && item.Length >= width + 16 && BitConverter.ToUInt16(buf, p + width + 4) == header.Id) - Header(p, item.Length - width - 8, (uint)item.Owner); + Header(p, item.Length - width - 8, owner); else if (item.Channel == 102 && item.Length >= width + 20 && BitConverter.ToUInt16(buf, p + width + 8) is var cls && cls < known.Length && known[cls]) - Block(p, item.Length - width - 12, (uint)item.Owner, cls); + Block(p, item.Length - width - 12, owner, cls); } // payload (class id first) of every Element-derived block whose stream holds the header record of its id if (rootBlocks != null) @@ -207,21 +196,22 @@ void Block(int p, int size, uint id, int cls) else index.RootClasses[id] = cls; } } - foreach (uint id in conflictCategory) index.HeaderCategories[id] = null; - foreach (uint id in conflictDesignOption) index.HeaderDesignOptions[id] = null; - foreach (uint id in conflictClass) index.RootClasses.Remove(id); + foreach (long id in conflictCategory) index.HeaderCategories[id] = null; + foreach (long id in conflictDesignOption) index.HeaderDesignOptions[id] = null; + foreach (long id in conflictClass) index.RootClasses.Remove(id); return index; } /// The position-by-position scan: every candidate whose length echo holds is a header record or a block (item start, size, id). - private static void Walk(byte[] b, int headerId, int w, bool[] known, Action header, Action block) + private static void Walk(byte[] b, int headerId, int w, bool[] known, Func wanted, + Action header, Action block) { int n = b.Length; int p = 0; while (p + w + 12 <= n) { - uint id = BitConverter.ToUInt32(b, p); - if (w == 8 && BitConverter.ToUInt32(b, p + 4) != 0) { p++; continue; } + long id = w == 8 ? BitConverter.ToInt64(b, p) : BitConverter.ToUInt32(b, p); + if (id < 0 || id > uint.MaxValue && !wanted(id)) { p++; continue; } uint size = BitConverter.ToUInt32(b, p + w); if (BitConverter.ToUInt16(b, p + w + 4) == headerId && size >= 8 && size < 4_000_000 @@ -266,8 +256,8 @@ private static (int Outline, int Parents)? OutlineTags(FileSchema schema, FileSc return schema.ByName("Outline") is { } outline && schema.ByName("ElementParents") is { } parents ? (outline.Id, parents.Id) : null; } - private static void RecordCategory(byte[] b, int p, int size, int categoryWidth, int entry, uint id, Index index, HashSet conflict, - HashSet conflictDesignOption, (int Outline, int Parents)? outlineTags) + private static void RecordCategory(byte[] b, int p, int size, int categoryWidth, int entry, long id, Index index, HashSet conflict, + HashSet conflictDesignOption, (int Outline, int Parents)? outlineTags) { // payload starts at p + 12 with the class id; m_regenHistory: u32 count + count * entry; then m_categroryId (8 bytes) uint count = BitConverter.ToUInt32(b, p + 14); @@ -282,12 +272,9 @@ private static void RecordCategory(byte[] b, int p, int size, int categoryWidth, else index.HeaderCategories[id] = value; // m_familyId, m_ownerViewId, m_designOptionId follow the category and have its width (ids) long optionAt = categoryAt + 3L * categoryWidth; - int? option = null; + long? option = null; if (optionAt + categoryWidth <= p + 12L + size) - { - long raw = categoryWidth == 8 ? BitConverter.ToInt64(b, (int)optionAt) : BitConverter.ToInt32(b, (int)optionAt); - if (raw >= int.MinValue && raw <= int.MaxValue) option = (int)raw; - } + option = categoryWidth == 8 ? BitConverter.ToInt64(b, (int)optionAt) : BitConverter.ToInt32(b, (int)optionAt); if (index.HeaderDesignOptions.TryGetValue(id, out var priorOption)) { if (priorOption != option) conflictDesignOption.Add(id); } else index.HeaderDesignOptions[id] = option; if (outlineTags is var (outlineTag, parentsTag)) diff --git a/src/RvtIO/Parsing/WideNativeParams.cs b/src/RvtIO/Parsing/WideNativeParams.cs index 456390d7..40db7c70 100644 --- a/src/RvtIO/Parsing/WideNativeParams.cs +++ b/src/RvtIO/Parsing/WideNativeParams.cs @@ -75,7 +75,7 @@ internal sealed partial class WideNativeParams private readonly HashSet _storeIds; private readonly int _namedParam; - internal WideNativeParams(SchemaDocument schema) + internal WideNativeParams(SchemaDocument schema, ElementIdMap? ids = null) { _schema = schema; _r22 = TfBlockDeserializer.Schemas; @@ -93,7 +93,7 @@ internal WideNativeParams(SchemaDocument schema) _walker = new WideBlockWalker(schema, KeyOf, ["ParamValueDouble", "ParamValueInt", "ParamValueAString", "ParamValueElementId", "NamedParam", "ForgeTypeId", "FormatOptions", "AUnits", "CompoundStructureLayer", "Connector", "ConnectorId", "SegmentConnectorCalculation", "MEPFamilyConnectorCalculationHvac", - "MEPFamilyConnectorCalculationPiping", "MEPFamilyConnectorCalculationElectrical"]); + "MEPFamilyConnectorCalculationPiping", "MEPFamilyConnectorCalculationElectrical"], ids: ids); } /// The class number of the Revit 2022 table for a class of the file, 0 when that class has none. diff --git a/src/RvtIO/Parsing/WideSolidQuantities.cs b/src/RvtIO/Parsing/WideSolidQuantities.cs index db79e188..95b27656 100644 --- a/src/RvtIO/Parsing/WideSolidQuantities.cs +++ b/src/RvtIO/Parsing/WideSolidQuantities.cs @@ -28,17 +28,23 @@ internal readonly record struct Solid(double Volume, double Surface, double? Lar private readonly Dictionary _massAreas = []; private readonly HashSet<(long X, long Y, long Z)> _splitVertices = []; - internal WideSolidQuantities(FileSchema schema, IReadOnlyList frames) + internal WideSolidQuantities(FileSchema schema, IReadOnlyList frames, ElementIdMap? ids = null) { - _geometryLayout = new(schema.Document, GeometrySchema.Value, 8); + _geometryLayout = new(schema.Document, GeometrySchema.Value, 8, ids); var ambiguous = new HashSet(); foreach (var frame in frames) { if (frame?.IdWidth != 8) continue; foreach (var item in frame.Items) { - if (item.Channel != 103 || item.Owner is 0 or > int.MaxValue) continue; - int id = (int)item.Owner; + if (item.Channel != 103 || item.Owner is 0 or > long.MaxValue) continue; + int id; + if (ids == null) + { + if (item.Owner > int.MaxValue) continue; + id = (int)item.Owner; + } + else if (!ids.TryGetKey((long)item.Owner, out id)) continue; if (!_records.TryAdd(id, (frame, item))) ambiguous.Add(id); } } diff --git a/src/RvtIO/RvtDocument.cs b/src/RvtIO/RvtDocument.cs index f45f535f..b580e8ba 100644 --- a/src/RvtIO/RvtDocument.cs +++ b/src/RvtIO/RvtDocument.cs @@ -12,6 +12,7 @@ public class RvtDocument private readonly RevitFileInfo _info; private readonly string? _sourcePath; private readonly Dictionary _elemById; + private readonly Dictionary? _elementsBySourceId; private readonly Dictionary? _elemByUniqueId; private readonly HashSet _typeElementIds; @@ -86,7 +87,11 @@ private RvtDocument(RevitFileInfo info, string? sourcePath = null) _elemById = new Dictionary(info.Elements.Count); foreach (var e in info.Elements) + { _elemById.TryAdd(e.Id, e); + if (e.NativeId is long sourceId) + (_elementsBySourceId ??= []).TryAdd(sourceId, e); + } // Build type element ID set: elements referenced via ELEM_TYPE_PARAM by other elements _typeElementIds = new HashSet(); @@ -104,6 +109,7 @@ private RvtDocument(RevitFileInfo info, string? sourcePath = null) } SynthesizeMissingParams(); + info.AttachSourceElementIds(); Parameter.ResolveZeroElementIds(_info); ResolveElementNames(); @@ -364,13 +370,22 @@ public RvtWriteResult SaveAs(string outputPath) } - /// Get element by ID. Returns null if not found. + /// Finds an element by its document-local key. Use the long overload for a source ID. public Element? GetElement(int elementId) { _elemById.TryGetValue(elementId, out var elem); return elem; } + /// Finds an element by the exact source ID stored in the RVT. + public Element? GetElement(long elementId) + { + if (_elementsBySourceId?.TryGetValue(elementId, out var element) == true) return element; + if (elementId is < int.MinValue or > int.MaxValue) return null; + element = GetElement((int)elementId); + return element?.ElementId == elementId ? element : null; + } + /// Get element by UniqueId string. Returns null if not found. public Element? GetElement(string uniqueId) { diff --git a/src/RvtIO/RvtFileReader.R22Layout.cs b/src/RvtIO/RvtFileReader.R22Layout.cs index 5b2aa43a..c255a5fa 100644 --- a/src/RvtIO/RvtFileReader.R22Layout.cs +++ b/src/RvtIO/RvtFileReader.R22Layout.cs @@ -11,7 +11,7 @@ public partial class RvtFileReader /// a framing or with another id width). Null when the file's schema table does not parse a second time or its id width is not 4 or 8 bytes. private static (List Chunks, int PartitionChunkCount, List Framed)? RewriteToR22Layout(RootStorage root, FileSchema schema, List chunks, IReadOnlyList> partitionStreams, - IReadOnlyList framedStreams, TextWriter? diag) + IReadOnlyList framedStreams, TextWriter? diag, ElementIdMap? ids) { if (WideElementRecords.IdWidth(schema) is not int width || PagedGzipStream.Read(root, "Formats", "Latest") is not { } schemaBytes) @@ -21,7 +21,7 @@ private static (List Chunks, int PartitionChunkCount, List(chunks.Count); foreach (var stream in partitionStreams) { diff --git a/src/RvtIO/RvtFileReader.cs b/src/RvtIO/RvtFileReader.cs index 65090198..3d9a8671 100644 --- a/src/RvtIO/RvtFileReader.cs +++ b/src/RvtIO/RvtFileReader.cs @@ -33,8 +33,8 @@ public RvtFileReader(RvtReaderOptions? options = null) /// Read and parse a Revit file, returning structured element data. /// The file cannot be read: missing, empty, not a compound file, cut or damaged. - /// A stream is longer than one array can hold, or the element table - /// contains an ID above . + /// A stream is longer than one array can hold, or a file with no project + /// partitions contains a source element ID above the range of document-local keys. public RevitFileInfo Read(string rvtPath) { RvtContainerCheck.Verify(rvtPath); @@ -45,7 +45,8 @@ public RevitFileInfo Read(string rvtPath) using var root = RootStorage.OpenRead(rvtPath); - var elemTable = ElemTableReader.Read(root, out var elemWorksets, out _, out bool elemTableIsExact, + var elemTable = ElemTableReader.Read(root, out var elemWorksets, out _, out bool elemTableIsExact, out var ids, + allowWideIds: root.TryOpenStorage("Partitions", out _), ElemTableRecover.Limits(_options.RaiseLimits), _options.Diagnostics); diag?.WriteLine($"ElemTable: {elemTable.Count} elements"); @@ -82,7 +83,7 @@ public RevitFileInfo Read(string rvtPath) if (globalChunks.Count > 0) chunks.AddRange(globalChunks); // Episode GUID table: nested stream Global/History (there is no top-level "History" storage). - var (elemRecHistories, elemRecOwners, wideSchema) = ReadElemRecs(root); + var (elemRecHistories, elemRecOwners, wideSchema) = ReadElemRecs(root, ids); LogRelease(root, fileMetadata, wideSchema, diag); var episodeTable = ReadEpisodeTable(root, diag, wideSchema); if (wideSchema != null && _options.R22Layout && _options.PreserveWideLayout) @@ -90,7 +91,7 @@ public RevitFileInfo Read(string rvtPath) var (wideInfo, wideState) = ParseModel(root, chunks, framedStreams, partitionStreams.Sum(s => s.Count), r22View: false, partitionStreams, framedStreams, wideSchema, elemTable, elemWorksets, fileMetadata, projectInfo, transmissionData, episodeTable, elemRecHistories, elemRecOwners, tfSchemas, ownPartitionWallParts, - staleCopiesRemoved, incrementRoutedPartitions, elemTableIsExact, previewBase64, previewMime, diag, LogPhase); + staleCopiesRemoved, incrementRoutedPartitions, elemTableIsExact, previewBase64, previewMime, diag, LogPhase, ids); WideModel = wideInfo; WideState = wideState; } @@ -99,7 +100,7 @@ public RevitFileInfo Read(string rvtPath) IReadOnlyList readFrames = framedStreams; int partitionChunkCount = partitionStreams.Sum(s => s.Count); if (wideSchema != null && _options.R22Layout - && RewriteToR22Layout(root, wideSchema, chunks, partitionStreams, framedStreams, diag) is { } r22) + && RewriteToR22Layout(root, wideSchema, chunks, partitionStreams, framedStreams, diag, ids) is { } r22) { (chunks, partitionChunkCount, var r22Frames) = r22; readFrames = r22Frames; @@ -111,7 +112,7 @@ public RevitFileInfo Read(string rvtPath) var (rvtInfo, state) = ParseModel(root, chunks, readFrames, partitionChunkCount, r22View, partitionStreams, framedStreams, wideSchema, elemTable, elemWorksets, fileMetadata, projectInfo, transmissionData, episodeTable, elemRecHistories, elemRecOwners, tfSchemas, ownPartitionWallParts, - staleCopiesRemoved, incrementRoutedPartitions, elemTableIsExact, previewBase64, previewMime, diag, LogPhase); + staleCopiesRemoved, incrementRoutedPartitions, elemTableIsExact, previewBase64, previewMime, diag, LogPhase, ids); LastParsingState = state; return rvtInfo; } @@ -141,12 +142,20 @@ public RevitFileInfo Read(string rvtPath) string? previewBase64, string? previewMime, TextWriter? diag, - Action LogPhase) + Action LogPhase, + ElementIdMap? ids) { + if (ids != null && !r22View) + { + // The native index reads these partitions. A legacy scan could attach a wide owner's low bits to another element. + chunks = chunks.Skip(partitionChunkCount).ToList(); + partitionChunkCount = 0; + } var state = new ParsingState { SeparateFacesWithDistinctOpenings = _options.SeparateFacesWithDistinctOpenings, ElemTable = elemTable, + ElementIds = ids, ElemWorksets = elemWorksets, AllKnownIds = new HashSet(elemTable.Keys), Chunks = chunks, @@ -162,7 +171,7 @@ public RevitFileInfo Read(string rvtPath) R22View = r22View, StaleCopiesRemoved = staleCopiesRemoved, FramedPartitions = readFrames, - IncrementRoutedPartitions = incrementRoutedPartitions, + IncrementRoutedPartitions = LocalPartitionRoutes(incrementRoutedPartitions, ids), PartitionChunkCount = partitionChunkCount, }; ReadWideElementIndex(root, state, partitionStreams, framedStreams, wideSchema, diag); @@ -826,6 +835,8 @@ public RevitFileInfo Read(string rvtPath) ?? (lengthOptions == null ? null : ProjectLengthUnits.StoredLengthUnit(lengthOptions.Value, out lengthUnitIssue)); if (rvtInfo.SerializedLengthUnit == null) rvtInfo.SerializedLengthUnitIssue = state.WideLengthUnitIssue ?? lengthUnitIssue; + rvtInfo.ElementIds = ids; + rvtInfo.AttachSourceElementIds(); var (exportIds, replacedUniqueIds) = ElementBuilder.ApplyExportIds(rvtInfo.Elements, state); diag?.WriteLine($"Element export ids: episodes={state.HistoryEpisodeGuids.Count}/{state.EpisodeTableX?.ToString() ?? "?"}, " + $"records={state.ElemRecHistories?.Count.ToString() ?? "unavailable"}, elements={exportIds}, " @@ -901,7 +912,8 @@ internal static void MergeElemScanStringsInChunkOrder( using var root = RootStorage.OpenRead(rvtPath); - var elemTable = ElemTableReader.Read(root, out var elemWorksets, out _, out bool elemTableIsExact, + var elemTable = ElemTableReader.Read(root, out var elemWorksets, out _, out bool elemTableIsExact, out var ids, + allowWideIds: root.TryOpenStorage("Partitions", out _), ElemTableRecover.Limits(_options.RaiseLimits), _options.Diagnostics); var fileMetadata = BasicFileInfoReader.Read(root); var projectInfo = ProjectInfoReader.Read(root); @@ -912,23 +924,29 @@ internal static void MergeElemScanStringsInChunkOrder( var chunks = DecompressPartitions(root, diag, out var ownPartitionWallParts, out var partitionStreams, out var framedStreams, out bool staleCopiesRemoved, out var incrementRoutedPartitions); // Episode GUID table: nested stream Global/History (see Read() above). - var (elemRecHistories, elemRecOwners, wideSchema) = ReadElemRecs(root); + var (elemRecHistories, elemRecOwners, wideSchema) = ReadElemRecs(root, ids); var episodeTable = ReadEpisodeTable(root, diag, wideSchema); bool r22View = false; IReadOnlyList readFrames = framedStreams; int partitionChunkCount = partitionStreams.Sum(s => s.Count); if (wideSchema != null && _options.R22Layout - && RewriteToR22Layout(root, wideSchema, chunks, partitionStreams, framedStreams, diag) is { } r22) + && RewriteToR22Layout(root, wideSchema, chunks, partitionStreams, framedStreams, diag, ids) is { } r22) { (chunks, partitionChunkCount, var r22Frames) = r22; readFrames = r22Frames; r22View = true; } + if (ids != null && !r22View) + { + chunks = chunks.Skip(partitionChunkCount).ToList(); + partitionChunkCount = 0; + } var state = new ParsingState { SeparateFacesWithDistinctOpenings = _options.SeparateFacesWithDistinctOpenings, ElemTable = elemTable, + ElementIds = ids, ElemWorksets = elemWorksets, AllKnownIds = new HashSet(elemTable.Keys), Chunks = chunks, @@ -942,7 +960,7 @@ internal static void MergeElemScanStringsInChunkOrder( R22View = r22View, StaleCopiesRemoved = staleCopiesRemoved, FramedPartitions = readFrames, - IncrementRoutedPartitions = incrementRoutedPartitions, + IncrementRoutedPartitions = LocalPartitionRoutes(incrementRoutedPartitions, ids), PartitionChunkCount = partitionChunkCount, }; ReadWideElementIndex(root, state, partitionStreams, framedStreams, wideSchema, diag); @@ -1000,25 +1018,44 @@ private static void LogRelease(RootStorage root, Dictionary file /// Element table records of the file: the Revit 2022 layout (shipped schema tables) or, when that does not /// apply, the 64-bit layout declared by the file's own schema, in which case the schema is returned too. private static (Dictionary? Histories, Dictionary? Owners, FileSchema? WideSchema) - ReadElemRecs(RootStorage root) + ReadElemRecs(RootStorage root, ElementIdMap? ids) { if (PagedGzipStream.Read(root, "Global", "ElemTable") is not { } bytes) return (null, null, null); var schema = FileSchema.Read(root); // the layout shipped for Revit 2022 applies to a file whose release in force (SchemaRelease.Of) is 2022 or unknown if (SchemaRelease.AllowsShipped(schema?.Release ?? SchemaRelease.Of(root, null), 2022) && ElementExportIds.ParseElemTable(bytes, out var owners) is { } histories) return (histories, owners, null); - if (schema != null && WideElementRecords.ParseElemTable(bytes, schema) is { } wide) - return (wide.Histories, wide.OwningElementIds, schema); + if (schema != null && WideElementRecords.ParseElemTable(bytes, schema) is { } rows) + { + var wideHistories = new Dictionary(rows.Count); + var wideOwners = new Dictionary(rows.Count); + foreach (var row in rows) + { + if (ids == null && row.Id > int.MaxValue) continue; + uint id = ids == null ? (uint)row.Id : (uint)ids.Key(row.Id); + wideHistories[id] = new ElemRecHistory(row.OriginalId, row.CreationDate); + if (ids != null) + wideOwners[id] = ids.Key(row.OwningId); + else if (row.OwningId is >= int.MinValue and <= int.MaxValue) + wideOwners[id] = (int)row.OwningId; + } + return (wideHistories, wideOwners, schema); + } return (null, null, null); } + private static IReadOnlyDictionary? LocalPartitionRoutes(IReadOnlyDictionary? routes, ElementIdMap? ids) + => routes == null || ids == null ? routes + : routes.Where(route => route.Key <= long.MaxValue) + .ToDictionary(route => (ulong)ids.Key((long)route.Key), route => route.Value); + /// The bars of the reinforcement elements and the beam systems (), by the file's own class schema in every layout. private static void ReadRebarBars(RootStorage root, ParsingState state, IReadOnlyList> partitionStreams, IReadOnlyList framedStreams, FileSchema? wideSchema) { if ((wideSchema ?? FileSchema.Read(root)) is not { } schema) return; var reinforcement = RebarReader.Read(partitionStreams, schema, state.AllKnownIds, EntitySchemaReader.Read(root, schema.Document), passUnknownEntities: true, - framed: framedStreams); + framed: framedStreams, ids: state.ElementIds); foreach (var (id, bars) in reinforcement.Bars) state.RebarBars[id] = bars; foreach (var (id, joist) in reinforcement.Joists) state.JoistSystems[id] = joist; } @@ -1029,6 +1066,7 @@ private static void ReadWideElementIndex(RootStorage root, ParsingState state, { if (schema == null) return; state.WideSchema = schema; + var ids = state.ElementIds; // the field walk of the root blocks (schema by class and field name); a file whose schema table does not parse a second time has none WideNativeParams? fields = null; GridAxisReader? gridReader = null; @@ -1037,11 +1075,11 @@ private static void ReadWideElementIndex(RootStorage root, ParsingState state, { try { - fields = new WideNativeParams(schemaDocument = TfSchemaReader.Parse(schemaBytes)); + fields = new WideNativeParams(schemaDocument = TfSchemaReader.Parse(schemaBytes), ids); // the values of an extensible storage entity are read by its schema, so the objects behind them are read in place var entitySchemas = EntitySchemaReader.Read(root, schemaDocument); fields.Walker.UseEntitySchemas(entitySchemas, passUnknown: true); - gridReader = new GridAxisReader(schemaDocument, entitySchemas); + gridReader = new GridAxisReader(schemaDocument, entitySchemas, ids); } catch (FormatException) { diag?.WriteLine("Wide element records: Formats/Latest does not parse for the field walk"); } } @@ -1049,9 +1087,14 @@ private static void ReadWideElementIndex(RootStorage root, ParsingState state, var gridBlocks = new Dictionary(); var drivers = new Dictionary>(); var wallShim = new Dictionary(); - var index = WideElementRecords.BuildIndexWithPartitions(partitionStreams, schema, state.AllKnownIds, - fields == null ? null : (id, data, offset, size, cls, partition) => - { + uint Key(long sourceId) => ids == null ? (uint)sourceId : (uint)ids.Key(sourceId); + long SourceId(uint key) => ids == null ? key : ids.SourceId((int)key); + var index = WideElementRecords.BuildIndexWithPartitions(partitionStreams, schema, + id => ids == null ? id is >= 0 and <= uint.MaxValue && state.AllKnownIds.Contains((uint)id) + : ids.TryGetKey(id, out int key) && state.AllKnownIds.Contains((uint)key), + fields == null ? null : (sourceId, data, offset, size, cls, partition) => + { + uint id = Key(sourceId); if (!walks.TryGetValue(id, out var list)) walks[id] = list = []; list.Add((fields.Walker.Run(data, offset, size, cls), cls, partition)); if (list.Count == 1 && gridReader?.IsGrid(cls) == true) @@ -1069,17 +1112,19 @@ private static void ReadWideElementIndex(RootStorage root, ParsingState state, diag?.WriteLine("Wide element records: the file's schema does not declare the expected ElementHeader"); return; } - foreach (var (id, category) in index.HeaderCategories) state.HeaderCategories[id] = category; - foreach (var (id, option) in index.HeaderDesignOptions) state.HeaderDesignOptions[id] = option; - foreach (var (id, box) in index.HeaderBoundingBoxes) state.HeaderBoundingBoxes[id] = box; - foreach (var (id, classId) in index.RootClasses) state.NativeRootClassNames[id] = schema.Get(classId)!.Name; + foreach (var (id, category) in index.HeaderCategories) state.HeaderCategories[Key(id)] = category; + foreach (var (id, option) in index.HeaderDesignOptions) + state.HeaderDesignOptions[Key(id)] = option is long value && ids != null ? ids.Key(value) + : option is >= int.MinValue and <= int.MaxValue ? (int)option : null; + foreach (var (id, box) in index.HeaderBoundingBoxes) state.HeaderBoundingBoxes[Key(id)] = box; + foreach (var (id, classId) in index.RootClasses) state.NativeRootClassNames[Key(id)] = schema.Get(classId)!.Name; int walked = 0, exact = 0; var walkFailures = new Dictionary(); if (fields != null) foreach (var (id, list) in walks) { if (list.Count > 1 - && index.RootClasses.TryGetValue(id, out int multiRootClass) + && index.RootClasses.TryGetValue(SourceId(id), out int multiRootClass) && state.IncrementRoutedPartitions != null && state.IncrementRoutedPartitions.TryGetValue(id, out int routedPartition) && list.Where(w => w.Partition == routedPartition).ToList() is [{ } routed] @@ -1091,7 +1136,7 @@ private static void ReadWideElementIndex(RootStorage root, ParsingState state, continue; } // a copy of the element in two streams is decoded only when it is one record - if (list.Count != 1 || !index.RootClasses.TryGetValue(id, out int rootClass) || list[0].Class != rootClass) continue; + if (list.Count != 1 || !index.RootClasses.TryGetValue(SourceId(id), out int rootClass) || list[0].Class != rootClass) continue; if (gridBlocks.TryGetValue(id, out var grid)) gridReader!.Read(id, grid.Data, grid.Offset, grid.Size, rootClass); if (drivers.TryGetValue(id, out var exactDrivers) && exactDrivers.Count > 0) state.ExactCurveDrivers[id] = exactDrivers; diff --git a/tests/RvtIO.Tests/ElementCensusTests.cs b/tests/RvtIO.Tests/ElementCensusTests.cs index 6cffc69f..26fa6866 100644 --- a/tests/RvtIO.Tests/ElementCensusTests.cs +++ b/tests/RvtIO.Tests/ElementCensusTests.cs @@ -39,7 +39,7 @@ private static SchemaDocument Table() private sealed record Block(bool Keyed, (uint Owner, string Class)[] Elements, bool Tagless = false); /// One record: its owner, its body and the value in front of the size on channels 102 and 103. - internal sealed record Rec(uint Owner, byte[] Body, uint Extra = 77); + internal sealed record Rec(ulong Owner, byte[] Body, uint Extra = 77); // the body of a record is the 2-byte class tag and one more byte, or, in a tagless block, one byte only on channel 102 private static byte[] Partition(params Block[] blocks) => Partition(Id, [.. blocks.Select(block => (block.Keyed, Enumerable.Range(101, 3) @@ -49,6 +49,9 @@ private static byte[] Partition(params Block[] blocks) => Partition(Id, [.. bloc /// The partition stream of the blocks, each given as the records of its channels 101, 102 and 103; /// gives the class id of a framing class. internal static byte[] Partition(Func id, params (bool Keyed, Rec[][] Channels)[] blocks) + => Partition(id, 4, blocks); + + internal static byte[] Partition(Func id, int idWidth, params (bool Keyed, Rec[][] Channels)[] blocks) { using var stream = new MemoryStream(); using var writer = new BinaryWriter(stream); @@ -59,7 +62,8 @@ internal static byte[] Partition(Func id, params (bool Keyed, Re writer.Write(id("ContentMarker")); writer.Write(keyed ? uint.MaxValue : 0u); if (keyed) writer.Write(id("ContentKey")); - writer.Write((uint)channels[0].Count(r => r.Owner != uint.MaxValue)); + ulong separator = idWidth == 4 ? uint.MaxValue : ulong.MaxValue; + writer.Write((uint)channels[0].Count(r => r.Owner != separator)); if (keyed) writer.Write([(byte)index, .. new byte[15]]); for (uint channel = 101; channel <= 103; channel++) { @@ -68,7 +72,8 @@ internal static byte[] Partition(Func id, params (bool Keyed, Re using var item = new BinaryWriter(items); foreach (var record in records) { - item.Write(record.Owner); + if (idWidth == 8) item.Write(record.Owner); + else item.Write(checked((uint)record.Owner)); if (channel != 101) item.Write(record.Extra); item.Write((uint)record.Body.Length); item.Write(record.Body); diff --git a/tests/RvtIO.Tests/ElementExportIdTests.cs b/tests/RvtIO.Tests/ElementExportIdTests.cs index a2ba0aa9..eaccd063 100644 --- a/tests/RvtIO.Tests/ElementExportIdTests.cs +++ b/tests/RvtIO.Tests/ElementExportIdTests.cs @@ -90,19 +90,21 @@ public void BuildUniqueId_TakesTheEpisodeAnExternalDumpGivesTheElement() public void ApplyExportIds_GivesTheUniqueIdOfTheElementHistoryAndNoneWithout() { var episodes = new[] { Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid() }; + const long wideOriginal = 0x1_0000_0005L; var state = new ParsingState { HistoryEpisodeGuids = episodes.Select(g => g.ToString("D")).ToList(), EpisodeTableX = 3, // 5: created in the last episode; 6: renumbered from 4 in the first; 9: a creation date beyond the list. - ElemRecHistories = new() { [5] = new(5, 0), [6] = new(4, 2), [9] = new(9, 3) }, + ElemRecHistories = new() { [5] = new(5, 0), [6] = new(4, 2), [9] = new(9, 3), [13] = new(wideOriginal, 0) }, }; var created = new Element { Id = 5 }; var renumbered = new Element { Id = 6 }; var outsideList = new Element { Id = 9 }; var withoutRow = new Element { Id = 12 }; + var wide = new Element { Id = 13 }; - var (applied, replaced) = ElementBuilder.ApplyExportIds([created, renumbered, outsideList, withoutRow], state); + var (applied, replaced) = ElementBuilder.ApplyExportIds([created, renumbered, outsideList, withoutRow, wide], state); Assert.Equal((2, 0), (applied, replaced)); Assert.Equal($"{episodes[2]:D}-00000005", created.UniqueId); @@ -113,6 +115,9 @@ public void ApplyExportIds_GivesTheUniqueIdOfTheElementHistoryAndNoneWithout() Assert.Null(outsideList.SerializedExportId); Assert.Null(withoutRow.UniqueId); Assert.Null(withoutRow.SerializedExportId); + Assert.Equal(wideOriginal, wide.OriginalElementId); + Assert.Null(wide.UniqueId); + Assert.Null(wide.SerializedExportId); } [Fact] diff --git a/tests/RvtIO.Tests/IfcExporterSkipReasonTests.cs b/tests/RvtIO.Tests/IfcExporterSkipReasonTests.cs index 1c9445fa..0a2a4519 100644 --- a/tests/RvtIO.Tests/IfcExporterSkipReasonTests.cs +++ b/tests/RvtIO.Tests/IfcExporterSkipReasonTests.cs @@ -9,7 +9,7 @@ namespace RvtIO.Tests; /// the elements of the file. public class IfcExporterSkipReasonTests { - private static GeometryData Box(double x0, double x1, double y0, double y1, double z0, double z1) + internal static GeometryData Box(double x0, double x1, double y0, double y1, double z0, double z1) { double[][] p = [ diff --git a/tests/RvtIO.Tests/PartitionCutTests.cs b/tests/RvtIO.Tests/PartitionCutTests.cs index 55e75585..e682d208 100644 --- a/tests/RvtIO.Tests/PartitionCutTests.cs +++ b/tests/RvtIO.Tests/PartitionCutTests.cs @@ -90,7 +90,7 @@ private static byte[] Records(uint channel, params ElementCensusTests.Rec[] reco using var item = new BinaryWriter(items); foreach (var record in records) { - item.Write(record.Owner); + item.Write(checked((uint)record.Owner)); if (channel != 101) item.Write(record.Extra); item.Write((uint)record.Body.Length); item.Write(record.Body); diff --git a/tests/RvtIO.Tests/WideElementRecordsTests.cs b/tests/RvtIO.Tests/WideElementRecordsTests.cs index aaef5bb2..347c502b 100644 --- a/tests/RvtIO.Tests/WideElementRecordsTests.cs +++ b/tests/RvtIO.Tests/WideElementRecordsTests.cs @@ -53,7 +53,7 @@ public byte[] ToArray() private sealed record Ids(int Identifier, int ElementId, int ElemRec, int ElemTable, int Header, int Element, int Wall, int Other, int Level); - private static (byte[] Stream, Ids Ids) BuildSchema(string originalClassName = "OriginalElementId") + private static (byte[] Stream, Ids Ids) BuildSchema(string originalClassName = "OriginalElementId", bool model = false) { var w = new SchemaWriter(); int identifier = w.Add("Identifier", 0, Scalar("m_id64", 11)); @@ -71,10 +71,17 @@ private static (byte[] Stream, Ids Ids) BuildSchema(string originalClassName = " int pair = w.Add("std::pair< ElementRegenerationInfo, EpisodeId >", 0, Ref("first", info), Ref("second", episode)); int regen = w.Add("ElementRegenHistory", 0, Array("m_historyMap", pair)); int header = w.Add("ElementHeader", 0, Ref("m_regenHistory", regen), Ref("m_categroryId", elementId)); - int element = w.Add("Element", 0); + int element = model ? w.Add("Element", 0, Ref("m_id", elementId)) : w.Add("Element", 0); int wall = w.Add("Wall", element); int other = w.Add("Other", 0); int level = w.Add("Level", wall); + if (model) + { + w.Add("FamilyInstance", element, Ref("m_masterSymbolId", elementId), Ref("m_hostId", elementId)); + w.Add("FamilySymbol", element); + foreach (var marker in new[] { "ContentMarker", "ContentKey", "SegmentMarker", "SegmentCheckback", "SignatureMarker" }) + w.Add(marker, 0); + } return (w.ToArray(), new Ids(identifier, elementId, rec, table, header, element, wall, other, level)); } @@ -135,11 +142,9 @@ public void ParseElemTable_ReadsOriginalIdCreationEpisodeAndOwnerOfEveryRow() var table = WideElementRecords.ParseElemTable( ElemTable(ids, (5, 7, 5, -1), (20, 3, 21, 5), (30, 0, 31, 0x1_0000_0000)), schema); Assert.NotNull(table); - Assert.Equal(new ElemRecHistory(5, 7), table.Histories[5]); - Assert.Equal(new ElemRecHistory(20, 3), table.Histories[21]); // the key is m_id, UniqueId uses the original id - Assert.Equal(-1, table.OwningElementIds[5]); - Assert.Equal(5, table.OwningElementIds[21]); - Assert.False(table.OwningElementIds.ContainsKey(31)); // an owner beyond 32 bits is not represented + Assert.Equal(new ElemTableLayout.Row(5, 5, 7, 0, -1, 0), table[0]); + Assert.Equal(new ElemTableLayout.Row(21, 20, 3, 0, 5, 0), table[1]); + Assert.Equal(new ElemTableLayout.Row(31, 30, 0, 0, 0x1_0000_0000, 0), table[2]); } [Fact] @@ -169,21 +174,22 @@ public void ParseElemTable_ReadsTheFourByteIdLayoutOfRevit2023() s.Write(new byte[24]); var wide = WideElementRecords.ParseElemTable(s.ToArray(), schema); Assert.NotNull(wide); - Assert.Equal(new ElemRecHistory(5, 7), wide.Histories[5]); - Assert.Equal(new ElemRecHistory(20, 3), wide.Histories[21]); - Assert.Equal(-1, wide.OwningElementIds[5]); - Assert.Equal(5, wide.OwningElementIds[21]); + Assert.Equal(new ElemTableLayout.Row(5, 5, 7, 9, -1, 0), wide[0]); + Assert.Equal(new ElemTableLayout.Row(21, 20, 3, 9, 5, 0), wide[1]); } [Fact] - public void ParseElemTable_KeepsIdZeroReportsTheFirstIdOutsideTheModelRangeAndRejectsBrokenTables() + public void ParseElemTable_PreservesWideIdsWithTheSameLowBitsAndRejectsBrokenTables() { var (stream, ids) = BuildSchema(); var schema = FileSchema.Parse(stream)!; + const long first = 0x1_0000_0009L, second = 0x20_0001_0000_0009L; var wide = WideElementRecords.ParseElemTable( - ElemTable(ids, (0, 0, 0, -1), (5, 0, int.MaxValue, -1), (9, 0, 0x1_0000_0009UL, -1)), schema)!; - Assert.Equal([0u, int.MaxValue], wide.Histories.Keys.ToArray()); // id 0 is a real row (ProjectPhase / DimensionStyle) - Assert.Equal(4294967305L, wide.UnsupportedId); + ElemTable(ids, (0, 0, 0, -1), (second, 3, 9, first), (first, 4, first, second), (5, 6, second, 0)), schema)!; + Assert.Equal([0L, 9L, first, second], wide.Select(row => row.Id)); + Assert.Equal(new ElemTableLayout.Row(9, second, 3, 0, first, 0), wide[1]); + Assert.Equal(new ElemTableLayout.Row(first, first, 4, 0, second, 0), wide[2]); + Assert.Equal(new ElemTableLayout.Row(second, 5, 6, 0, 0, 0), wide[3]); var good = ElemTable(ids, (5, 0, 5, -1), (6, 0, 6, -1)); Assert.Null(WideElementRecords.ParseElemTable(ElemTable(ids, (6, 0, 6, -1), (5, 0, 5, -1)), schema)); // not increasing Assert.Null(WideElementRecords.ParseElemTable(good[..^30], schema)); // truncated @@ -213,6 +219,112 @@ public void ElementTableFallbackRejectsAnIdOutsideInt32() finally { File.Delete(path); } } + [Fact] + public void ElementTableFallbackKeepsTheRowWhenOnlyTheOriginalIdIsWide() + { + var (stream, ids) = BuildSchema("StoredOriginalId"); + byte[] table = ElemTable(ids, (0, 0, 0, -1), (0x20_0001_0000_0009UL, 4, 9, -1)); + string path = TestFiles.Scratch($"wide-original-id-{Guid.NewGuid():N}.rvt"); + try + { + CoverageCensusTests.WriteFile(path, + ("Formats/Latest", RvtIO.Writing.PageCodec.EncodePadded(RvtIO.Writing.GzipMember.Write(stream))), + ("Global/ElemTable", RvtIO.Writing.PageCodec.EncodePadded(RvtIO.Writing.GzipMember.Write(table)))); + using var root = OpenMcdf.RootStorage.OpenRead(path); + var membership = ElemTableReader.Read(root, out _, out var dates, out bool exact); + Assert.True(exact); + Assert.Equal([0u, 9u], membership.Keys.Order()); + Assert.Equal(4, dates[9]); + } + finally { File.Delete(path); } + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void WideProjectRetainsExactElementTypeAndHostIds(bool r22Layout) + { + const long instanceId = 2147483648L, hostId = 0x1_0000_0009L, typeId = 0x20_0000_0000_0009L; + var (schemaBytes, ids) = BuildSchema(model: true); + var schema = FileSchema.Parse(schemaBytes)!; + ushort Tag(string name) => (ushort)schema.ByName(name)!.Id; + var idsAndCategories = new (long Id, long Category)[] { (9, -2000011), (int.MaxValue, -2000011), + (instanceId, -2000151), (hostId, -2000011), (typeId, -2000151) }; + var headers = idsAndCategories.Select(row => new ElementCensusTests.Rec((ulong)row.Id, + [.. BitConverter.GetBytes(Tag("ElementHeader")), .. BitConverter.GetBytes(0u), .. BitConverter.GetBytes(row.Category)])).ToArray(); + var part = ElementCensusTests.Partition(Tag, 8, (false, [headers, [ + Body(9, "Wall"), Body(int.MaxValue, "Wall"), Body(instanceId, "FamilyInstance", typeId, hostId), + Body(hostId, "Wall"), Body(typeId, "FamilySymbol")], []])); + string path = TestFiles.Scratch($"wide-references-{Guid.NewGuid():N}.rvt"); + try + { + CoverageCensusTests.WriteFile(path, + ("BasicFileInfo", RvtWriterTests.BuildBasicFileInfoBytes(2027)), + ("Formats/Latest", Paged(schemaBytes)), + ("Global/ElemTable", Paged(ElemTable(ids, (9, 0, 9, -1), (int.MaxValue, 0, int.MaxValue, -1), + (instanceId, 0, instanceId, hostId), (hostId, 0, hostId, -1), (typeId, 0, typeId, -1)))), + ("Partitions/0", part)); + var doc = RvtDocument.Open(path, new RvtReaderOptions { R22Layout = r22Layout }); + var instance = Assert.IsType(doc.GetElement(instanceId)); + Assert.Equal(instanceId, instance.ElementId); + Assert.Equal(typeId, instance.TypeElementId); + Assert.Equal(hostId, instance.HostElementId); + Assert.Equal(typeId, doc.GetTypeElement(instance)!.ElementId); + Assert.Equal(hostId, doc.GetElement(instance.HostElementId!.Value)!.ElementId); + Assert.Equal("Wall", doc.GetElement(9L)!.RootClassName); + Assert.Equal("FamilySymbol", doc.GetElement(typeId)!.RootClassName); + Assert.Equal(typeId, doc.GetElement(typeId)!.OriginalElementId); + Assert.Null(doc.GetElement(typeId)!.UniqueId); + Assert.Equal(int.MaxValue, doc.GetElement((long)int.MaxValue)!.Id); + var hostParameter = Assert.Single(instance.Parameters, parameter => parameter.Id == -1002108); + Assert.Equal(hostId, hostParameter.AsElementId64()); + Assert.Equal(hostId.ToString(System.Globalization.CultureInfo.InvariantCulture), hostParameter.AsValueString()); + + using var full = System.Text.Json.JsonDocument.Parse(System.Text.Json.JsonSerializer.Serialize(doc.RawData, + new System.Text.Json.JsonSerializerOptions { Converters = { new RvtIO.Model.ParameterListConverter() } })); + Assert.Equal("9007199254741001", full.RootElement.GetProperty("SourceElementIds") + .GetProperty(instance.TypeId.ToString(System.Globalization.CultureInfo.InvariantCulture)).GetString()); + var jsonInstance = Assert.Single(full.RootElement.GetProperty("Elements").EnumerateArray(), + row => row.TryGetProperty("SourceElementId", out var id) && id.GetString() == "2147483648"); + Assert.Equal("9007199254741001", jsonInstance.GetProperty("SourceTypeId").GetString()); + Assert.Equal("4294967305", jsonInstance.GetProperty("SourceHostId").GetString()); + Assert.Equal("4294967305", jsonInstance.GetProperty("Parameters").GetProperty("-1002108").GetString()); + using var compact = new MemoryStream(); + RvtIO.Compact.CompactJsonExporter.Export(doc.RawData, compact); + using var compactJson = System.Text.Json.JsonDocument.Parse(compact.ToArray()); + var compactRows = compactJson.RootElement.GetProperty("data").GetProperty("collection").EnumerateArray().ToList(); + Assert.Contains(compactRows, row => row.TryGetProperty("object", out var id) && id.GetString() == "9007199254741001"); + var compactInstance = Assert.Single(compactRows, row => row.TryGetProperty("object", out var id) && id.GetString() == "2147483648"); + Assert.Contains("4294967305", compactInstance.GetRawText()); + Assert.Contains("9007199254741001", compactInstance.GetRawText()); + + // These records carry links rather than a BRep. Supply a test body to exercise the geometry exporters. + instance.Geometry = IfcExporterSkipReasonTests.Box(0, 10, 0, 10, 0, 10); + instance.BoundingBox = instance.Geometry.BoundingBox; + instance.SerializedCreatedPhaseId = 9; + instance.Parameters.RemoveAll(parameter => parameter.Id == -1012100); + instance.Parameters.Add(new RvtIO.Model.Parameter { Id = -1012100, Value = 9, StorageType = RvtIO.Model.StorageType.ElementId }); + var scene = RvtIO.Scene.RvtSceneReader.Read(doc, new RvtIO.Scene.RvtSceneOptions { ModelKey = "wide.rvt" }).Document; + scene = IOScene.SceneJson.Read(IOScene.SceneJson.Write(scene)); + var sceneElement = Assert.Single(scene.Elements, element => element.Id == instance.Id); + Assert.Contains(scene.Instances, placement => placement.ElementId == sceneElement.Id); + Assert.Contains(scene.PropertySets.SelectMany(set => set.Properties), property => + property.Name == "Revit Type ID" && property.Value.Text == "9007199254741001"); + + using var ifc = new StringWriter(); + new RvtIO.Ifc.IfcExporter().Export(doc.RawData, ifc); + string fallbackGuid = RvtIO.Ifc.IfcGuid.FromElementId(instanceId); + Assert.Contains(ifc.ToString().Split('\n'), line => line.StartsWith('#') + && line.Contains($"IFCBUILDINGELEMENTPROXY('{fallbackGuid}'", StringComparison.Ordinal) + && line.Contains("'2147483648'", StringComparison.Ordinal)); + } + finally { File.Delete(path); } + + ElementCensusTests.Rec Body(long owner, string name, params long[] references) => new((ulong)owner, + [.. BitConverter.GetBytes(Tag(name)), .. BitConverter.GetBytes(owner), .. references.SelectMany(BitConverter.GetBytes)]); + static byte[] Paged(byte[] bytes) => RvtIO.Writing.PageCodec.EncodePadded(RvtIO.Writing.GzipMember.Write(bytes)); + } + [Theory] [InlineData("Rebar", "RebarBarType", 7)] [InlineData("RebarInSystem", "RebarBarType", 7)] @@ -301,6 +413,33 @@ public void BuildIndex_ReadsHeaderCategoryAndTheElementDerivedBlockClass() Assert.Equal(4, index.Records); } + [Theory] + [InlineData(false)] + [InlineData(true)] + public void BuildIndex_KeepsDistinctWideOwnersAndTheirRootBlocks(bool framed) + { + var (stream, ids) = BuildSchema(); + var schema = FileSchema.Parse(stream)!; + const long wideId = 9007199254741001L; + byte[] narrowHeader = Record(ids, 9, [], -2000011); + byte[] narrowBlock = Block(9, ids.Wall); + byte[] wideHeader = Record(ids, wideId, [], -2000240); + byte[] wideBlock = Block(wideId, ids.Level); + byte[] data = Join(narrowHeader, narrowBlock, wideHeader, wideBlock); + int wideAt = narrowHeader.Length + narrowBlock.Length; + var frame = new PartitionFraming.Framed([data], + [new(101, 9, 0, narrowHeader.Length), new(102, 9, narrowHeader.Length, narrowBlock.Length), + new(101, wideId, wideAt, wideHeader.Length), new(102, wideId, wideAt + wideHeader.Length, wideBlock.Length)], 8); + var roots = new List(); + var index = WideElementRecords.BuildIndexWithPartitions([[data]], schema, id => id is 9 or wideId, + (id, _, _, _, _, _) => roots.Add(id), framed ? [frame] : null)!; + Assert.Equal([9L, wideId], roots); + Assert.Equal(ids.Wall, index.RootClasses[9]); + Assert.Equal(ids.Level, index.RootClasses[wideId]); + Assert.Equal(-2000011, index.HeaderCategories[9]); + Assert.Equal(-2000240, index.HeaderCategories[wideId]); + } + [Fact] public void BuildIndex_ReadsTheRecordAndBlockOfIdZeroAndIgnoresAZeroRun() { @@ -316,7 +455,7 @@ public void BuildIndex_ReadsTheRecordAndBlockOfIdZeroAndIgnoresAZeroRun() Assert.Equal(ids.Level, index.RootClasses[0]); Assert.Equal(-1, index.HeaderCategories[1]); Assert.Equal(2, index.Records); - Assert.DoesNotContain(2u, index.HeaderCategories.Keys); + Assert.DoesNotContain(2L, index.HeaderCategories.Keys); var without = WideElementRecords.BuildIndex([[data]], schema, new HashSet { 1 })!; Assert.False(without.HeaderCategories.ContainsKey(0)); // only wanted ids are collected } @@ -403,7 +542,8 @@ private static (byte[] Stream, OutlineIds Ids) BuildOutlineSchema(bool withParen /// A header record of the 64-bit layout whose outline is (none when null), tagged with the classes /// of the schema it is written for. - private static byte[] OutlineRecord(OutlineIds ids, ulong id, double[]? box, int regenEntries = 0, int? outlineTag = null) + private static byte[] OutlineRecord(OutlineIds ids, ulong id, double[]? box, int regenEntries = 0, int? outlineTag = null, + long designOption = -1) { var p = new MemoryStream(); p.Write(BitConverter.GetBytes((ushort)ids.Header)); @@ -415,7 +555,11 @@ private static byte[] OutlineRecord(OutlineIds ids, ulong id, double[]? box, int p.Write(new byte[22 - 8]); } p.Write(BitConverter.GetBytes(-2000011L)); // m_categroryId - for (int i = 0; i < 5; i++) p.Write(BitConverter.GetBytes(-1L)); + p.Write(BitConverter.GetBytes(-1L)); // m_familyId + p.Write(BitConverter.GetBytes(-1L)); // m_ownerViewId + p.Write(BitConverter.GetBytes(designOption)); + p.Write(BitConverter.GetBytes(-1L)); // m_unplacedOwnerId + p.Write(BitConverter.GetBytes(-1L)); // m_miscId p.Write(BitConverter.GetBytes(0xFFFF8000u)); // m_viewRules p.Write(BitConverter.GetBytes(0x000109B8u)); // m_abFlags4Bytes p.Write(BitConverter.GetBytes((ushort)0x0725)); // m_classDef @@ -473,6 +617,18 @@ public void BuildIndex_DropsAnOutlineTheCopiesOfAnIdDisagreeOn() Assert.False(index.HeaderBoundingBoxes[12]!.Present); } + [Fact] + public void BuildIndex_KeepsTheDesignOptionIdAtItsSerializedWidth() + { + var (stream, ids) = BuildOutlineSchema(); + var schema = FileSchema.Parse(stream)!; + const long optionId = 0x20_0000_0000_0009L; + byte[] record = OutlineRecord(ids, 10, box: null, designOption: optionId); + var index = WideElementRecords.BuildIndex([[record]], schema, new HashSet { 10 })!; + Assert.Equal(optionId, index.HeaderDesignOptions[10]); + Assert.Equal(-2000011, index.HeaderCategories[10]); + } + [Fact] public void BuildIndex_ReadsNoOutlineWhereTheSchemaDoesNotHaveTheHeaderLayout() { From dbaf49f7abb31bc51af0b1c045f8cd10bf86d47f Mon Sep 17 00:00:00 2001 From: mahach666 <79989386+mahach666@users.noreply.github.com> Date: Thu, 19 Nov 2026 17:31:37 +0300 Subject: [PATCH 033/259] Pass the portable publish property intact --- tools/pack-release.ps1 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/pack-release.ps1 b/tools/pack-release.ps1 index c09335a1..5ebb8ae9 100644 --- a/tools/pack-release.ps1 +++ b/tools/pack-release.ps1 @@ -109,7 +109,7 @@ New-Zip $cli10Stage (Join-Path $Output "RvtIO-Cli-$version-net10.0.zip") foreach ($framework in 'net8.0', 'net10.0') { Write-Host "Publishing RvtIO.Nwc ($framework)..." $nwcStage = Join-Path $stage "nwc-$framework" - Invoke-DotNet publish (Join-Path $root 'tools\RvtIO.Nwc\RvtIO.Nwc.csproj') -c Release -f $framework --self-contained false -p:UseAppHost=false -o $nwcStage + Invoke-DotNet publish (Join-Path $root 'tools\RvtIO.Nwc\RvtIO.Nwc.csproj') -c Release -f $framework --self-contained false '-p:UseAppHost=false' -o $nwcStage Invoke-DotNet (Join-Path $nwcStage 'RvtIO.Nwc.dll') --help Copy-Item (Join-Path $root 'docs\rvt-to-nwc.md') (Join-Path $nwcStage 'README.md') Copy-Item (Join-Path $root 'LICENSE'), (Join-Path $root 'THIRD-PARTY-NOTICES.md') $nwcStage From 2ff97e0bbff6d206bdacb3535386c7160cf5799b Mon Sep 17 00:00:00 2001 From: mahach666 <79989386+mahach666@users.noreply.github.com> Date: Thu, 19 Nov 2026 18:32:20 +0300 Subject: [PATCH 034/259] Use NwcIO 0.15.1 in RvtIO.Nwc --- CHANGELOG.md | 7 +++++++ Directory.Build.props | 2 +- Directory.Packages.props | 2 +- THIRD-PARTY-NOTICES.md | 2 +- 4 files changed, 10 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ac9f1bb2..2a4fc260 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,6 +16,13 @@ API between minor releases. - Report `element-id-range` with the offending ID if an RVT has wide element IDs and no project partition storage to read the element records. +## [0.6.1] - 2026-11-19 + +### Changed + +- The ready-to-run `RvtIO.Nwc` archives bundle NwcIO 0.15.1, which reads the alternate Revit element ID flags + and shared fragment poses described in [NwcIO #261](https://github.com/IOExtend/NwcIO/issues/261). + ## [0.6.0] - 2026-11-19 ### Added diff --git a/Directory.Build.props b/Directory.Build.props index 07a97ec3..ed8a4871 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -6,7 +6,7 @@ enable true true - 0.6.0 + 0.6.1 true true snupkg diff --git a/Directory.Packages.props b/Directory.Packages.props index dedc7313..6a7f3ca6 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -17,7 +17,7 @@ - + diff --git a/THIRD-PARTY-NOTICES.md b/THIRD-PARTY-NOTICES.md index 82e38dba..e8b8100e 100644 --- a/THIRD-PARTY-NOTICES.md +++ b/THIRD-PARTY-NOTICES.md @@ -7,7 +7,7 @@ RvtIO uses the following components. | [OpenMcdf](https://github.com/ironfede/openmcdf) 3.4.0 | reads the compound file container of Revit files | MPL-2.0 | | [SharpZipLib](https://github.com/icsharpcode/SharpZipLib) 1.4.2 | stream decompression | MIT | | [IOScene](https://github.com/IOExtend/IOScene) | scene contract used by RvtIO.Scene and RvtIO.Nwc | MIT, copyright (c) 2026 mahach666 | -| [NwcIO](https://github.com/IOExtend/NwcIO) 0.15.0 | NWC writer bundled with RvtIO.Nwc | MIT, copyright (c) 2026 mahach666 | +| [NwcIO](https://github.com/IOExtend/NwcIO) 0.15.1 | NWC writer bundled with RvtIO.Nwc | MIT, copyright (c) 2026 mahach666 | | .NET runtime libraries (DeflateManaged sources, `src/RvtIO/DeflateManaged`) | managed inflate implementation adapted for tolerant decoding | MIT, copyright (c) .NET Foundation and Contributors | Development and build-time packages (xunit, Microsoft.NET.Test.Sdk, Microsoft.SourceLink.GitHub) are not part of the From da4428daac243a841e78c43cfc4b7a1682fb11a1 Mon Sep 17 00:00:00 2001 From: mie <79989386+mahach666@users.noreply.github.com> Date: Thu, 19 Nov 2026 18:48:47 +0300 Subject: [PATCH 035/259] Match Revit export identity for 64-bit element IDs --- docs/scene.md | 2 +- src/RvtIO.Scene/RvtSceneReader.cs | 11 +++--- src/RvtIO/Compact/CompactIfcParameters.cs | 12 +++---- src/RvtIO/Model/Element.cs | 4 +-- src/RvtIO/Parsing/ElementBuilder.cs | 8 ++--- src/RvtIO/Parsing/ElementExportIds.cs | 27 +++++++------- tests/RvtIO.Tests/ApiTests.cs | 2 +- .../RvtIO.Tests/CompactIfcParametersTests.cs | 1 + tests/RvtIO.Tests/ElementExportIdTests.cs | 36 +++++++++++++++---- tests/RvtIO.Tests/RvtSceneReaderTests.cs | 15 +++++--- 10 files changed, 74 insertions(+), 44 deletions(-) diff --git a/docs/scene.md b/docs/scene.md index 1a268cb3..183e177f 100644 --- a/docs/scene.md +++ b/docs/scene.md @@ -59,7 +59,7 @@ rvtio project.rvt --ifc project.ifc --compact-json project.compact.json --scene | `SceneElement.LevelId` | The building-storey assignment from `RvtDocument.GetBuildingStoreyCatalog()`, using the current IFC rules for stored level references and geometry fallback. Assignments to the building itself leave this field empty. The scene assigns a storey to each drawable element independently of IFC product aggregation. | | `SceneElement` | One per drawable element of `ElementMeshes.Extract` (the elements the IFC export would consider products, see the remarks of `ElementMeshes`). `Id` is the element id. | | `SourceId` | The Revit `UniqueId`. This derivation does not change; a golden test pins it on a fixture file. | -| `IfcGuid` | The GlobalId Revit's IFC export gives the element: the value of its built-in IfcGUID parameter (`IFC_GUID`, matched by id as RvtIO's IFC export matches it) when it is a valid 22-character GlobalId; else the export id of the `UniqueId` (the episode GUID with its last 32 bits XORed with the element id the `UniqueId` ends with) in the IFC base-64 form. It depends on the element only, never on export order or options. This derivation does not change; the golden test pins it. | +| `IfcGuid` | The GlobalId Revit's IFC export gives the element. A valid built-in IfcGUID parameter (`IFC_GUID`) takes precedence. Otherwise the episode GUID has its last 64 bits XORed with the original element ID from the `UniqueId` suffix, then is encoded as a 22-character IFC GlobalId. | | `Name`, `Category`, `TypeName` | `Element.Name`; the English name of the built-in category (else `Element.Category`); the name of the type element. | | `SceneGeometry`, `SceneInstance` | A symbol placed whole is one geometry per mesh in the frame of its family, and each placement is one instance per mesh with the placement's transform. A mirrored placement keeps its transform as it is: the winding of the triangles is not changed. A mesh of an element's own is a geometry used once, with vertices relative to the lowest corner of the element's meshes, which is the translation of its instances. All lengths are feet x 0.3048, in the internal coordinates of the document, Z up. | | `SceneMaterial` | One per material element that a mesh uses: its name and its colour (`MATERIAL_PARAM_COLOR`, alpha from `MATERIAL_PARAM_TRANSPARENCY`), else a neutral grey. | diff --git a/src/RvtIO.Scene/RvtSceneReader.cs b/src/RvtIO.Scene/RvtSceneReader.cs index bea2733f..ebe87180 100644 --- a/src/RvtIO.Scene/RvtSceneReader.cs +++ b/src/RvtIO.Scene/RvtSceneReader.cs @@ -344,19 +344,20 @@ StorageType.Double when parameter.Value is double value && parameter.SpecType is private const string IfcGuidAlphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_$"; /// The IFC GlobalId Revit's IFC export gives the element: the value of its built-in IfcGUID parameter (IFC_GUID) - /// when it is a valid GlobalId, else the export id of its UniqueId (the episode GUID with its last 32 bits XORed with the + /// when it is a valid GlobalId, else the export id of its UniqueId (the episode GUID with its last 64 bits XORed with the /// element id the UniqueId ends with) in the IFC base-64 form; null without either. private static string? IfcGuidOf(Element element) { if (element.Parameters.Where(parameter => parameter.Id == (int)BuiltInParameter.IFC_GUID) .Select(parameter => parameter.Value as string).FirstOrDefault(IsIfcGuid) is { } stored) return stored; - // A UniqueId is the episode GUID, '-' and the original element id as eight hex digits. - if (element.UniqueId is not { Length: 45 } uniqueId || uniqueId[36] != '-' + // The original element id has a minimum width of eight hex digits. + if (element.UniqueId is not { Length: >= 45 and <= 53 } uniqueId || uniqueId[36] != '-' || !Guid.TryParseExact(uniqueId.AsSpan(0, 36), "D", out var episode) - || !uint.TryParse(uniqueId.AsSpan(37), NumberStyles.AllowHexSpecifier, CultureInfo.InvariantCulture, out uint originalId)) + || !long.TryParse(uniqueId.AsSpan(37), NumberStyles.AllowHexSpecifier, CultureInfo.InvariantCulture, out long originalId) + || originalId < 0) return null; - UInt128 bits = BinaryPrimitives.ReadUInt128BigEndian(episode.ToByteArray(bigEndian: true)) ^ originalId; + UInt128 bits = BinaryPrimitives.ReadUInt128BigEndian(episode.ToByteArray(bigEndian: true)) ^ (ulong)originalId; var text = new char[22]; for (int index = 21; index >= 0; index--, bits >>= 6) text[index] = IfcGuidAlphabet[(int)(bits & 63)]; return new string(text); diff --git a/src/RvtIO/Compact/CompactIfcParameters.cs b/src/RvtIO/Compact/CompactIfcParameters.cs index 4804897a..dd437acc 100644 --- a/src/RvtIO/Compact/CompactIfcParameters.cs +++ b/src/RvtIO/Compact/CompactIfcParameters.cs @@ -212,15 +212,15 @@ internal static bool ListsOperation(string recordClass, int? category, Form form form == Form.Type && recordClass == "FamilySymbol" && category is (int)BuiltInCategory.OST_Doors or (int)BuiltInCategory.OST_Windows; - /// IfcGUID of a Revit UniqueId ("{episode GUID}-{original id:x8}"): the IFC base-64 of the episode GUID with its - /// last 32 bits XORed with the id. Null when the text is not a UniqueId. + /// IfcGUID of a Revit UniqueId: the IFC base-64 of the episode GUID with its + /// last 64 bits XORed with the original id. Null when the text is not a UniqueId. internal static string? IfcGuidOf(string? uniqueId) { - if (uniqueId is not { Length: 45 } || uniqueId[36] != '-' + if (uniqueId is not { Length: >= 45 and <= 53 } || uniqueId[36] != '-' || !Guid.TryParseExact(uniqueId.AsSpan(0, 36), "D", out Guid episode) - || !uint.TryParse(uniqueId.AsSpan(37), System.Globalization.NumberStyles.AllowHexSpecifier, - System.Globalization.CultureInfo.InvariantCulture, out uint id)) return null; - return IfcGuid.ToIfcGuid(ElementExportIds.ExportId(episode, id)); + || !long.TryParse(uniqueId.AsSpan(37), System.Globalization.NumberStyles.AllowHexSpecifier, + System.Globalization.CultureInfo.InvariantCulture, out long id) || id < 0) return null; + return IfcGuid.ToIfcGuid(ElementExportIds.ExportId(episode, (ulong)id)); } internal static IReadOnlyList Properties( diff --git a/src/RvtIO/Model/Element.cs b/src/RvtIO/Model/Element.cs index 8d8d17ff..5503bcfc 100644 --- a/src/RvtIO/Model/Element.cs +++ b/src/RvtIO/Model/Element.cs @@ -973,8 +973,8 @@ internal bool RootClassIs(string className) => NativeRootClassName != null internal double[]? DecodedBox => BoundingBoxIsHeaderOutline ? Geometry?.BoundingBox : BoundingBox; /// - /// Revit UniqueId: "{episode GUID}-{original element id:x8}", the GUID of the episode that created the element and - /// the id it was created with, both read from the element's history in the document's element table. Null when the + /// Revit UniqueId: the creation episode GUID followed by the original element ID in hexadecimal (at least eight + /// digits). Both are read from the element's history in the document's element table. Null when the /// file holds no history for the element (for example an element found only in a stream), since its UniqueId cannot /// be known then. /// diff --git a/src/RvtIO/Parsing/ElementBuilder.cs b/src/RvtIO/Parsing/ElementBuilder.cs index 4e7ae204..6d86f40e 100644 --- a/src/RvtIO/Parsing/ElementBuilder.cs +++ b/src/RvtIO/Parsing/ElementBuilder.cs @@ -4974,13 +4974,13 @@ internal static (int Elements, int ReplacedUniqueIds) ApplyExportIds( || !histories.TryGetValue((uint)element.Id, out var history)) continue; element.OriginalElementId = history.OriginalElementId; - if (history.OriginalElementId is < 0 or > uint.MaxValue + if (history.OriginalElementId < 0 || ElementExportIds.EpisodeGuid(history, state.HistoryEpisodeGuids, state.EpisodeTableX) is not Guid episode) continue; - uint originalId = (uint)history.OriginalElementId; + ulong originalId = (ulong)history.OriginalElementId; element.SerializedExportId = ElementExportIds.ExportId(episode, originalId); - if (element.ElementId is >= 0 and <= uint.MaxValue) - element.SerializedHandleExportId = ElementExportIds.ExportId(episode, (uint)element.ElementId); + if (element.ElementId >= 0) + element.SerializedHandleExportId = ElementExportIds.ExportId(episode, (ulong)element.ElementId); string uniqueId = ElementExportIds.UniqueId(episode, originalId); if (element.UniqueId != null && element.UniqueId != uniqueId) replaced++; element.UniqueId = uniqueId; diff --git a/src/RvtIO/Parsing/ElementExportIds.cs b/src/RvtIO/Parsing/ElementExportIds.cs index 195dbb26..720a7903 100644 --- a/src/RvtIO/Parsing/ElementExportIds.cs +++ b/src/RvtIO/Parsing/ElementExportIds.cs @@ -1,3 +1,5 @@ +using System.Buffers.Binary; + namespace RvtIO.Parsing; /// @@ -86,32 +88,29 @@ private static bool SchemaDeclaresElemRecLayout() } /// Revit UniqueId: the episode GUID and the original element id. - internal static string UniqueId(Guid episode, uint originalElementId) => + internal static string UniqueId(Guid episode, ulong originalElementId) => $"{episode:D}-{originalElementId:x8}"; /// - /// The export-id rule: the episode GUID with its last 32 bits XORed with the - /// original element id. + /// The export-id rule: the episode GUID with the original element id XORed into its last 64 bits. /// - internal static Guid ExportId(Guid episode, uint originalElementId) => - XorBigEndian(episode, 12, originalElementId); + internal static Guid ExportId(Guid episode, ulong originalElementId) => + XorTail(episode, originalElementId); /// /// ExporterIFCUtils.CreateSubElementGUID: the export id with the index XORed into bits /// 32-63. /// internal static Guid SubElementId(Guid exportId, int index) => - XorBigEndian(exportId, 8, unchecked((uint)index)); + XorTail(exportId, (ulong)unchecked((uint)index) << 32); - // Bytes 8-15 of Guid.ToByteArray are stored in text order (big-endian), so the last 32 bits of - // the GUID are bytes 12-15 and the 32 bits before them are bytes 8-11. - private static Guid XorBigEndian(Guid guid, int offset, uint value) + // The last eight GUID bytes are stored in text order. + private static Guid XorTail(Guid guid, ulong value) { - byte[] bytes = guid.ToByteArray(); - bytes[offset] ^= (byte)(value >> 24); - bytes[offset + 1] ^= (byte)(value >> 16); - bytes[offset + 2] ^= (byte)(value >> 8); - bytes[offset + 3] ^= (byte)value; + Span bytes = stackalloc byte[16]; + guid.TryWriteBytes(bytes); + var tail = bytes[8..]; + BinaryPrimitives.WriteUInt64BigEndian(tail, BinaryPrimitives.ReadUInt64BigEndian(tail) ^ value); return new Guid(bytes); } } diff --git a/tests/RvtIO.Tests/ApiTests.cs b/tests/RvtIO.Tests/ApiTests.cs index da6f96ff..cca03e15 100644 --- a/tests/RvtIO.Tests/ApiTests.cs +++ b/tests/RvtIO.Tests/ApiTests.cs @@ -667,7 +667,7 @@ public void EveryUniqueIdIsTheOneOfTheElementHistory() Assert.Null(element.SerializedExportId); return; } - Assert.Equal(Parsing.ElementExportIds.ExportId(Guid.Parse(uniqueId[..36]), Convert.ToUInt32(uniqueId[37..], 16)), + Assert.Equal(Parsing.ElementExportIds.ExportId(Guid.Parse(uniqueId[..36]), Convert.ToUInt64(uniqueId[37..], 16)), element.SerializedExportId); }); } diff --git a/tests/RvtIO.Tests/CompactIfcParametersTests.cs b/tests/RvtIO.Tests/CompactIfcParametersTests.cs index 771cf039..1612e450 100644 --- a/tests/RvtIO.Tests/CompactIfcParametersTests.cs +++ b/tests/RvtIO.Tests/CompactIfcParametersTests.cs @@ -22,6 +22,7 @@ private static string Text(IEnumerable properties) => [InlineData("1551350c-45e5-41b8-bdf1-bcfa6794dc6a-000b0dce", "0LKJKCHUL1kBtnlFfddz6a")] // sample project A wall 6900242 was renumbered: its UniqueId keeps the original id 6879768 (0x0068fa18). [InlineData("6a7c3860-b4f0-401b-a699-81014e2efddb-0068fa18", "1gV3XWjF106wQPWG5EHWV3")] + [InlineData("95db5b0a-a7bf-4747-af03-b1f5fe59fca1-1000f4241", "2LsriAfxz7Hwy3iVJ_LhxW")] public void IfcGuid_IsTheIfcBase64OfTheEpisodeGuidXoredWithTheId(string uniqueId, string expected) => Assert.Equal(expected, CompactIfcParameters.IfcGuidOf(uniqueId)); diff --git a/tests/RvtIO.Tests/ElementExportIdTests.cs b/tests/RvtIO.Tests/ElementExportIdTests.cs index eaccd063..71b13074 100644 --- a/tests/RvtIO.Tests/ElementExportIdTests.cs +++ b/tests/RvtIO.Tests/ElementExportIdTests.cs @@ -90,21 +90,20 @@ public void BuildUniqueId_TakesTheEpisodeAnExternalDumpGivesTheElement() public void ApplyExportIds_GivesTheUniqueIdOfTheElementHistoryAndNoneWithout() { var episodes = new[] { Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid() }; - const long wideOriginal = 0x1_0000_0005L; var state = new ParsingState { HistoryEpisodeGuids = episodes.Select(g => g.ToString("D")).ToList(), EpisodeTableX = 3, // 5: created in the last episode; 6: renumbered from 4 in the first; 9: a creation date beyond the list. - ElemRecHistories = new() { [5] = new(5, 0), [6] = new(4, 2), [9] = new(9, 3), [13] = new(wideOriginal, 0) }, + ElemRecHistories = new() { [5] = new(5, 0), [6] = new(4, 2), [9] = new(9, 3), [13] = new(-1, 0) }, }; var created = new Element { Id = 5 }; var renumbered = new Element { Id = 6 }; var outsideList = new Element { Id = 9 }; var withoutRow = new Element { Id = 12 }; - var wide = new Element { Id = 13 }; + var invalidOriginal = new Element { Id = 13 }; - var (applied, replaced) = ElementBuilder.ApplyExportIds([created, renumbered, outsideList, withoutRow, wide], state); + var (applied, replaced) = ElementBuilder.ApplyExportIds([created, renumbered, outsideList, withoutRow, invalidOriginal], state); Assert.Equal((2, 0), (applied, replaced)); Assert.Equal($"{episodes[2]:D}-00000005", created.UniqueId); @@ -115,9 +114,32 @@ public void ApplyExportIds_GivesTheUniqueIdOfTheElementHistoryAndNoneWithout() Assert.Null(outsideList.SerializedExportId); Assert.Null(withoutRow.UniqueId); Assert.Null(withoutRow.SerializedExportId); - Assert.Equal(wideOriginal, wide.OriginalElementId); - Assert.Null(wide.UniqueId); - Assert.Null(wide.SerializedExportId); + Assert.Equal(-1L, invalidOriginal.OriginalElementId); + Assert.Null(invalidOriginal.UniqueId); + Assert.Null(invalidOriginal.SerializedExportId); + } + + [Fact] + public void ApplyExportIds_MatchesRevit2027ForAWallAboveUInt32() + { + // A generated two-wall model reopened in Revit 2027.2 and exported to IFC2x3. + const long elementId = 4_295_967_297; + const int key = int.MaxValue; + var state = new ParsingState + { + HistoryEpisodeGuids = ["95db5b0a-a7bf-4747-af03-b1f5fe59fca1"], + EpisodeTableX = 1, + ElemRecHistories = new() { [key] = new(elementId, 0) }, + }; + var wall = new Element { Id = key, NativeId = elementId }; + + Assert.Equal((1, 0), ElementBuilder.ApplyExportIds([wall], state)); + + Assert.Equal(elementId, wall.OriginalElementId); + Assert.Equal("95db5b0a-a7bf-4747-af03-b1f5fe59fca1-1000f4241", wall.UniqueId); + Assert.Equal(Guid.Parse("95db5b0a-a7bf-4747-af03-b1f4fe56bee0"), wall.SerializedExportId); + Assert.Equal(wall.SerializedExportId, wall.SerializedHandleExportId); + Assert.Equal("2LsriAfxz7Hwy3iVJ_LhxW", IfcExporter.ResolveExactElementGlobalId(wall, new HashSet())); } [Fact] diff --git a/tests/RvtIO.Tests/RvtSceneReaderTests.cs b/tests/RvtIO.Tests/RvtSceneReaderTests.cs index 96d1e705..951c7da3 100644 --- a/tests/RvtIO.Tests/RvtSceneReaderTests.cs +++ b/tests/RvtIO.Tests/RvtSceneReaderTests.cs @@ -437,12 +437,19 @@ public void YesNoOfAUserParameterIsTheNumberTheApiShows() Assert.Empty(document.Validate()); } + [Theory] + [InlineData(263584, "d45b1816-cbcc-4dc6-b0bb-007467f3c600-000405a0", "3KMnWMoynDnh2x07HdzyEW")] + [InlineData(4295967297L, "95db5b0a-a7bf-4747-af03-b1f5fe59fca1-1000f4241", "2LsriAfxz7Hwy3iVJ_LhxW")] + public void IfcGuidIsTheExportIdOfTheUniqueId(long id, string uniqueId, string expectedGuid) + { + var element = MapOne(new Element { Id = 1, NativeId = id, UniqueId = uniqueId }).Elements[0]; + Assert.Equal(uniqueId, element.SourceId); + Assert.Equal(expectedGuid, element.IfcGuid); + } + [Fact] - public void IfcGuidIsTheExportIdOfTheUniqueId() + public void MissingOrMalformedUniqueIdHasNoIfcGuid() { - // The UniqueId and GlobalId of an element of a fixture file, as Revit 2022 exported it to IFC. - var element = MapOne(new Element { Id = 263584, UniqueId = "d45b1816-cbcc-4dc6-b0bb-007467f3c600-000405a0" }).Elements[0]; - Assert.Equal("3KMnWMoynDnh2x07HdzyEW", element.IfcGuid); Assert.Null(MapOne(new Element { Id = 1, UniqueId = "d45b1816-cbcc-4dc6-b0bb-007467f3c600-0405a0" }).Elements[0].IfcGuid); Assert.Null(MapOne(new Element { Id = 1 }).Elements[0].IfcGuid); } From 0484df38d8241b73b61bb9922d68167857ca9a99 Mon Sep 17 00:00:00 2001 From: mie <79989386+mahach666@users.noreply.github.com> Date: Thu, 19 Nov 2026 20:06:25 +0300 Subject: [PATCH 036/259] Read nested Extensible Storage in projects and loaded families --- docs/public-api.md | 11 ++ src/RvtIO/Model/Element.cs | 4 + src/RvtIO/Model/ExtensibleStorageEntity.cs | 7 ++ src/RvtIO/Model/RevitFileInfo.cs | 4 + src/RvtIO/Parsing/ElementBuilder.cs | 1 + src/RvtIO/Parsing/EntitySchemaReader.cs | 31 +++-- src/RvtIO/Parsing/ExtensibleStorageReader.cs | 110 ++++++++++++++++++ src/RvtIO/Parsing/PartitionFraming.cs | 5 + src/RvtIO/Parsing/TfBlockDeserializer.cs | 1 + .../Parsing/WideBlockWalker.EntityValues.cs | 75 ++++++++++++ src/RvtIO/Parsing/WideBlockWalker.cs | 65 ++++++++--- src/RvtIO/RvtFileReader.cs | 34 ++++-- tests/RvtIO.Tests/PartitionCutTests.cs | 17 +++ .../RvtIO.Tests/WideBlockWalkerEntityTests.cs | 97 +++++++++++++++ 14 files changed, 431 insertions(+), 31 deletions(-) create mode 100644 src/RvtIO/Model/ExtensibleStorageEntity.cs create mode 100644 src/RvtIO/Parsing/ExtensibleStorageReader.cs create mode 100644 src/RvtIO/Parsing/WideBlockWalker.EntityValues.cs diff --git a/docs/public-api.md b/docs/public-api.md index 45085f91..f410f3e0 100644 --- a/docs/public-api.md +++ b/docs/public-api.md @@ -37,6 +37,17 @@ data cannot be recovered, the numeric property is omitted. This does not change An unavailable format does not mean zero or an unset value: a stored zero is formatted normally when its format is known, while a known unset bound user parameter is written as an empty string. A missing family value record is omitted. +`Element.ExtensibleStorage` gives the public Extensible Storage entities decoded from the element's own cell, including +files with 32-bit element IDs. Full JSON includes the same data. Each entity has a schema GUID, a schema name and a field dictionary. +Values can include nested entities, arrays, or maps represented as lists of key/value pairs. Integers outside the exact +JavaScript integer range are decimal strings. An entity is omitted if any of its values cannot be recovered completely. +The field dictionary is separate from Revit's normal parameter list. + +`RevitFileInfo.EmbeddedFamilyExtensibleStorage` lists the same data for elements in loaded family documents. +Each entry identifies its owner by the saved content-key GUID and the exact decimal element ID in that block. +Element ID fields inside an entity use the IDs saved in that document. Opening an RFA directly exposes its own data through +`Element.ExtensibleStorage`. + `Element.BoundingBox` is the axis-aligned outline stored in the element header, as the Revit API bounding box (null for elements with no stored outline, such as grids and levels). The tight box of the decoded geometry is `Element.Geometry.BoundingBox`; before 0.3.0 `Element.BoundingBox` held that decoded value, which also changes the result of `FilteredElementCollector.WhereBoundingBoxIsNotNull`. `Element.ViewportViewId` and `Element.ViewportOffset` are the view a viewport displays and the offset of that view diff --git a/src/RvtIO/Model/Element.cs b/src/RvtIO/Model/Element.cs index 5503bcfc..d9cdfed3 100644 --- a/src/RvtIO/Model/Element.cs +++ b/src/RvtIO/Model/Element.cs @@ -980,6 +980,10 @@ internal bool RootClassIs(string className) => NativeRootClassName != null /// public string? UniqueId { get; set; } + /// Fully decoded public Extensible Storage entities owned by this element, when available. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public IReadOnlyList? ExtensibleStorage { get; internal set; } + /// Family/type name resolved from FamId or ELEM_TYPE_PARAM reference. public string? FamilyName { get; set; } diff --git a/src/RvtIO/Model/ExtensibleStorageEntity.cs b/src/RvtIO/Model/ExtensibleStorageEntity.cs new file mode 100644 index 00000000..421ae3b6 --- /dev/null +++ b/src/RvtIO/Model/ExtensibleStorageEntity.cs @@ -0,0 +1,7 @@ +namespace RvtIO.Model; + +/// A public Extensible Storage entity and its saved field values. +public sealed record ExtensibleStorageEntity(Guid SchemaId, string SchemaName, IReadOnlyDictionary Fields); + +/// Public entities of an element in a loaded family's saved document, identified by content key and saved element ID. +public sealed record EmbeddedFamilyElementStorage(Guid ContentKey, string ElementId, IReadOnlyList ExtensibleStorage); diff --git a/src/RvtIO/Model/RevitFileInfo.cs b/src/RvtIO/Model/RevitFileInfo.cs index 240f8a7b..a2e1d512 100644 --- a/src/RvtIO/Model/RevitFileInfo.cs +++ b/src/RvtIO/Model/RevitFileInfo.cs @@ -29,6 +29,10 @@ public partial class RevitFileInfo /// All elements of the file. public List Elements { get; set; } = new(); + /// Public Extensible Storage on elements of loaded family documents, outside the main element collection. + [System.Text.Json.Serialization.JsonIgnore(Condition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull)] + public IReadOnlyList? EmbeddedFamilyExtensibleStorage { get; internal set; } + internal Parsing.ElementIdMap? ElementIds { get; set; } /// Resolves any document-local element key to its original signed 64-bit ID. diff --git a/src/RvtIO/Parsing/ElementBuilder.cs b/src/RvtIO/Parsing/ElementBuilder.cs index 6d86f40e..071b2abf 100644 --- a/src/RvtIO/Parsing/ElementBuilder.cs +++ b/src/RvtIO/Parsing/ElementBuilder.cs @@ -3214,6 +3214,7 @@ internal static void ApplyNativeParams(RevitFileInfo info, ParsingState? state) e.NativeCellListTag = np.Fields.TryGetValue("37:m_cellList", out int cellListTag) ? cellListTag : null; e.NativeCellClasses = np.CellClasses?.ToArray(); e.NativeTailWalkComplete = np.TailWalkComplete; + e.ExtensibleStorage = np.ExtensibleStorage; if (np.NamedParams.Count > 0) e.NativeNamedParameters = np.NamedParams.Where(named => named.ParamId < 0).Select(named => (named.ParamId, named.Instance)).ToArray(); // the two element-base keys are only kept for family instances (they exist in every diff --git a/src/RvtIO/Parsing/EntitySchemaReader.cs b/src/RvtIO/Parsing/EntitySchemaReader.cs index c11c5228..8ed882ec 100644 --- a/src/RvtIO/Parsing/EntitySchemaReader.cs +++ b/src/RvtIO/Parsing/EntitySchemaReader.cs @@ -16,8 +16,8 @@ internal static class EntitySchemaReader /// Per schema GUID the fields of an entity as fields of the class schema, in the order an entity stores them; null for a /// schema with a field whose type is not read or whose entry indexes are not 0 to n-1. Empty when Global/Latest is missing, does not decode or is not walked without an /// error: no schema is known then, and a walk that is given the empty set stops at every entity that has values. - internal static Dictionary Read(RootStorage root, SchemaDocument schema) => - PagedGzipStream.Read(root, "Global", "Latest") is { } latest && Read(latest, schema) is { } schemas ? schemas : []; + internal static Dictionary Read(RootStorage root, SchemaDocument schema, Dictionary? publicNames = null) => + PagedGzipStream.Read(root, "Global", "Latest") is { } latest && Read(latest, schema, publicNames) is { } schemas ? schemas : []; /// The entity schemas of each loaded family document, by the key of its content block (, the /// same text): an entity in a family block names a schema of its own document, which Global/Latest need not hold. Global/ContentDocuments @@ -26,29 +26,38 @@ internal static class EntitySchemaReader /// ADocument, and the length again; a ContentMarker with the handle 0, its count and a length of 0 ends it at its last byte. Each /// ADocument is read like Global/Latest; a document whose ADocument is not walked without an error has no schemas. Empty when the /// stream is missing, does not decode or does not end so. - internal static Dictionary> ReadContentDocuments(RootStorage root, SchemaDocument schema) + internal static Dictionary> ReadContentDocuments(RootStorage root, SchemaDocument schema, + IReadOnlySet? wantedKeys = null, Dictionary>? publicNames = null) { var documents = new Dictionary>(StringComparer.Ordinal); if (PagedGzipStream.Read(root, "Global", "ContentDocuments") is not { } data || schema.Classes.FirstOrDefault(c => c.Name == "ContentMarker") is not { } marker || schema.Classes.FirstOrDefault(c => c.Name == "ContentKey") is not { } key) return documents; var span = data.AsSpan(); + var seen = new HashSet(StringComparer.Ordinal); for (int at = 0; ;) { if (at + 6 > span.Length || BinaryPrimitives.ReadUInt16LittleEndian(span[at..]) != marker.Id) return []; uint handle = BinaryPrimitives.ReadUInt32LittleEndian(span[(at + 2)..]); - if (handle == 0) return at + 14 == span.Length && BinaryPrimitives.ReadUInt32LittleEndian(span[(at + 10)..]) == 0 ? documents : []; + if (handle == 0) + return at + 14 == span.Length && BinaryPrimitives.ReadUInt32LittleEndian(span[(at + 10)..]) == 0 ? documents : []; if (handle != uint.MaxValue || at + 32 > span.Length || BinaryPrimitives.ReadUInt16LittleEndian(span[(at + 6)..]) != key.Id) return []; string name = Convert.ToHexString(span.Slice(at + 12, 16)); int length = BinaryPrimitives.ReadInt32LittleEndian(span[(at + 28)..]); if (length < 0 || length > span.Length - at - 36 || BinaryPrimitives.ReadInt32LittleEndian(span[(at + 32 + length)..]) != length) return []; - if (!documents.TryAdd(name, Read(span.Slice(at + 32, length).ToArray(), schema) ?? [])) return []; + if (!seen.Add(name)) return []; + if (wantedKeys == null || wantedKeys.Contains(name)) + { + var names = publicNames == null ? null : new Dictionary(); + documents.Add(name, Read(span.Slice(at + 32, length).ToArray(), schema, names) ?? []); + if (names is { Count: > 0 }) publicNames!.Add(name, names); + } at += 36 + length; } } /// The same of a decoded Global/Latest; null when it is not an ADocument or its walk does not end without an error. - internal static Dictionary? Read(byte[] latest, SchemaDocument schema) + internal static Dictionary? Read(byte[] latest, SchemaDocument schema, Dictionary? publicNames = null) { if (latest.Length < 2) return null; // the step budget of the record walks of the census: a walk that is out of step can meet a large count of items without bytes @@ -73,8 +82,14 @@ internal static class EntitySchemaReader } // an entity stores its fields in the order of ESField.m_entryIndex, which is not the order the schema lists them in if (values.GetValueOrDefault("m_guid") is Guid guid) - schemas.TryAdd(guid, fields.Any(f => f.Field == null) || !Numbered(fields.Select(f => f.Index)) ? null - : [.. fields.OrderBy(f => f.Index).Select(f => f.Field!)]); + { + SchemaField[]? layout = fields.Any(f => f.Field == null) || !Numbered(fields.Select(f => f.Index)) ? null + : [.. fields.OrderBy(f => f.Index).Select(f => f.Field!)]; + if (!schemas.TryAdd(guid, layout)) publicNames?.Remove(guid); + else if (layout != null && values.GetValueOrDefault("m_readAccessLevel") is 1L + && values.GetValueOrDefault("m_schemaName") is string name) + publicNames?.Add(guid, name); + } fields.Clear(); } return schemas; diff --git a/src/RvtIO/Parsing/ExtensibleStorageReader.cs b/src/RvtIO/Parsing/ExtensibleStorageReader.cs new file mode 100644 index 00000000..c0c4321c --- /dev/null +++ b/src/RvtIO/Parsing/ExtensibleStorageReader.cs @@ -0,0 +1,110 @@ +using System.Globalization; +using ICSharpCode.SharpZipLib.Checksum; +using OpenMcdf; +using RvtIO.Model; + +namespace RvtIO.Parsing; + +/// Reads public entities from legacy project records and embedded family records in their saved document scope. +internal static class ExtensibleStorageReader +{ + internal static void Apply(RootStorage root, RevitFileInfo info, IReadOnlyList framed) + { + // An unframed partition may contain a second copy of an owner or family block. + if (framed.Count == 0 || framed.Any(frame => frame == null)) return; + var parts = framed.Cast().ToArray(); + bool legacy = parts[0].IdWidth == 4 && info.ElemTableIsExact; + var candidates = parts.SelectMany(part => part.FamilyEntityCandidates.Select(item => (Part: part, Record: item))).ToArray(); + if ((!legacy && candidates.Length == 0) || TfSchemaReader.Read(root) is not { } schema + || schema.Classes.FirstOrDefault(c => c.Name == "ESEntityCell") is not { } cell) return; + + var projectNames = new Dictionary(); + var project = EntitySchemaReader.Read(root, schema, projectNames); + var walker = new WideBlockWalker(schema, (declaring, field) => + declaring.Name == "Element" && field.Name == "m_id" ? field.Name : null, []); + if (legacy && projectNames.Count != 0) + { + walker.UseEntitySchemas(project, publicEntityNames: projectNames); + ApplyLegacyProject(info, parts, walker, BitConverter.GetBytes((ushort)cell.Id)); + } + + if (candidates.Length == 0) return; + var uniqueKeys = parts.Where(part => part.FamilyKeys != null).SelectMany(part => part.FamilyKeys!) + .GroupBy(key => key, StringComparer.Ordinal).Where(group => group.Count() == 1) + .Select(group => group.Key).ToHashSet(StringComparer.Ordinal); + uniqueKeys.IntersectWith(candidates.Select(candidate => candidate.Record.ContentKey)); + var names = new Dictionary>(StringComparer.Ordinal); + var families = uniqueKeys.Count != 0 && SchemaRelease.FromSchema(new FormatsSchema(schema)) is not >= 2025 + ? EntitySchemaReader.ReadContentDocuments(root, schema, uniqueKeys, names) : []; + var embedded = new List(); + foreach (var block in candidates.GroupBy(candidate => candidate.Record.ContentKey, StringComparer.Ordinal)) + { + if (!uniqueKeys.Contains(block.Key) || projectNames.Count == 0 && !names.ContainsKey(block.Key)) continue; + ConfigureFamily(walker, project, projectNames, families.GetValueOrDefault(block.Key), names.GetValueOrDefault(block.Key)); + var key = new Guid(Convert.FromHexString(block.Key)); + foreach (var owner in block.GroupBy(candidate => candidate.Record.Item.Owner)) + { + if (owner.Take(2).ToArray() is not [var candidate]) continue; + if (ReadOwner(walker, candidate.Part, candidate.Record.Item, []) is { } entities) + embedded.Add(new(key, owner.Key.ToString(CultureInfo.InvariantCulture), entities)); + } + } + if (embedded.Count > 0) info.EmbeddedFamilyExtensibleStorage = embedded; + } + + internal static void ConfigureFamily(WideBlockWalker walker, Dictionary project, + Dictionary projectNames, Dictionary? family, Dictionary? familyNames) + { + if (family is not { Count: > 0 }) + { + walker.UseEntitySchemas(project, publicEntityNames: projectNames); + return; + } + + var layouts = new Dictionary(project); + var names = new Dictionary(projectNames); + foreach (var (guid, fields) in family) + { + layouts[guid] = fields; + names.Remove(guid); + if (familyNames?.TryGetValue(guid, out var name) == true) names.Add(guid, name); + } + walker.UseEntitySchemas(layouts, publicEntityNames: names); + } + + private static void ApplyLegacyProject(RevitFileInfo info, PartitionFraming.Framed[] parts, WideBlockWalker walker, byte[] cellTag) + { + var recovered = new Dictionary>(); + foreach (var part in parts) + foreach (var item in part.Items) + if (item.Channel == 102 && ReadOwner(walker, part, item, cellTag) is { } entities) + recovered.TryAdd(item.Owner, entities); + if (recovered.Count == 0) return; + + // The framing index has already dropped any copies resolved by the increment table. + var owners = parts.SelectMany(part => part.Items).Where(item => item.Channel == 102 && recovered.ContainsKey(item.Owner)) + .GroupBy(item => item.Owner).Where(group => group.Count() == 1).Select(group => group.Key).ToHashSet(); + foreach (var element in info.Elements) + if (owners.Contains((ulong)element.ElementId) && recovered.TryGetValue((ulong)element.ElementId, out var entities)) + element.ExtensibleStorage = entities; + } + + private static IReadOnlyList? ReadOwner(WideBlockWalker walker, PartitionFraming.Framed part, + PartitionFraming.ProjectItem item, ReadOnlySpan requiredCellTag) + { + int length = item.Length - part.IdWidth - 12; + if (length < 2 || item.Owner > long.MaxValue) return null; + var (data, start, _) = part.Bytes(item); + int offset = start + part.IdWidth + 8; + if (!requiredCellTag.IsEmpty && data.AsSpan(offset, length).IndexOf(requiredCellTag) < 0) return null; + int tag = BitConverter.ToUInt16(data, offset); + if (!walker.IsA(tag, "Element")) return null; + walker.StepBudget = 16L * length + 65536; + var walk = walker.Run(data, offset, length, tag); + if (walk.OwnPublicEntities() is not { } entities + || !walk.Captures.Any(c => c.AtRoot && c.Key == "m_id" && c.Integer == (long)item.Owner)) return null; + var checksum = new Adler32(); + checksum.Update(new ArraySegment(data, offset, length)); + return (uint)checksum.Value == BitConverter.ToUInt32(data, start + part.IdWidth) ? entities : null; + } +} diff --git a/src/RvtIO/Parsing/PartitionFraming.cs b/src/RvtIO/Parsing/PartitionFraming.cs index 3a01bb8c..64359929 100644 --- a/src/RvtIO/Parsing/PartitionFraming.cs +++ b/src/RvtIO/Parsing/PartitionFraming.cs @@ -35,11 +35,16 @@ internal static class PartitionFraming /// for bytes in the stream's inflated output. internal readonly record struct ProjectItem(int Channel, ulong Owner, long Offset, int Length); + internal readonly record struct FamilyItem(string ContentKey, ProjectItem Item); + /// A partition stream read by its framing: the output of every segment in file order, and the records of the project's own block /// (the null-key map) in file order, without the chain terminators. The records of the keyed blocks (loaded family documents) are not listed. /// is the byte width of the owner the walk read; is the partition stream number when known. internal sealed record Framed(IReadOnlyList Segments, List Items, int IdWidth, int? Partition = null) { + internal IReadOnlyList FamilyEntityCandidates { get; init; } = []; + internal IReadOnlySet? FamilyKeys { get; init; } + private long[]? starts; /// Where the bytes of the item are: in its segment when it lies in one, else in a copy (an item can run into the next segment diff --git a/src/RvtIO/Parsing/TfBlockDeserializer.cs b/src/RvtIO/Parsing/TfBlockDeserializer.cs index 4f52f083..d318e7f2 100644 --- a/src/RvtIO/Parsing/TfBlockDeserializer.cs +++ b/src/RvtIO/Parsing/TfBlockDeserializer.cs @@ -40,6 +40,7 @@ internal sealed class NativeParams public HashSet? RoofExtrusionFaceTags { get; set; } /// The deferred walk consumed every queued object of the record (so the NamedParams and cells are complete). public bool TailWalkComplete { get; set; } + public IReadOnlyList? ExtensibleStorage { get; set; } public List<(int ParamId, double Value)> Doubles { get; } = new(); public List<(int ParamId, int Value)> Ints { get; } = new(); public List<(int ParamId, string Value)> Strings { get; } = new(); diff --git a/src/RvtIO/Parsing/WideBlockWalker.EntityValues.cs b/src/RvtIO/Parsing/WideBlockWalker.EntityValues.cs new file mode 100644 index 00000000..0ed04367 --- /dev/null +++ b/src/RvtIO/Parsing/WideBlockWalker.EntityValues.cs @@ -0,0 +1,75 @@ +using System.Globalization; +using RvtIO.Model; + +namespace RvtIO.Parsing; + +internal sealed partial class WideBlockWalker +{ + private static readonly object UnavailableEntityValue = new(); + private IReadOnlyDictionary? _publicEntityNames; + + internal sealed class EntityFields : Dictionary { } + + internal sealed partial class Walk + { + internal Dictionary? EntityPayloads; + internal Dictionary? EntityCells; + internal int OwnCellList = -1; + + internal IReadOnlyList? OwnPublicEntities() + { + if (!Exact || OwnCellList < 0 || EntityCells == null) return null; + var entities = new Dictionary(); + var duplicates = new HashSet(); + for (int i = QueueCountAtStart[OwnCellList]; i < QueueEnd[OwnCellList]; i++) + { + if (EntityCells.GetValueOrDefault(i) is not List entries) continue; + foreach (var entry in entries) + { + if (entry is not KeyValuePair { Key: Guid id, Value: ExtensibleStorageEntity entity } + || id != entity.SchemaId || !IsComplete(entity, 0)) continue; + if (!entities.TryAdd(id, entity)) duplicates.Add(id); + } + } + foreach (Guid id in duplicates) entities.Remove(id); + return entities.Count == 0 ? null : entities.Values.ToArray(); + } + } + + private void ReadEntityArray(Context c, SchemaClass declaring, SchemaField field, int depth, EntityFields values, int count) + { + var items = new List(); + var item = new EntityFields(); + for (int index = 0; index < count; index++) + { + item.Clear(); + Scalar(c, declaring, field, null, depth, item, null); + items.Add(item.TryGetValue(field.Name, out var value) ? value : UnavailableEntityValue); + } + values[field.Name] = items; + } + + private static object? EntityInlineValue(string className, EntityFields values) => className switch + { + "ESEntity" when values.TryGetValue("m_blob", out var entity) => entity, + "AStringWrapper" when values.GetValueOrDefault("m_str") is string text => text, + "GUIDvalue" when values.GetValueOrDefault("m_guid") is Guid guid => guid, + "XYZ" when values.GetValueOrDefault("m_xyz") is List { Count: 3 } xyz => xyz, + _ when className.StartsWith("std::pair< ", StringComparison.Ordinal) + && values.TryGetValue("first", out var first) && values.TryGetValue("second", out var second) + => new KeyValuePair(first, second), + _ => UnavailableEntityValue, + }; + + private static object ExactEntityInteger(long value) => + value is < -9_007_199_254_740_991L or > 9_007_199_254_740_991L ? value.ToString(CultureInfo.InvariantCulture) : value; + + private static bool IsComplete(object? value, int depth) => depth <= 32 && value switch + { + ExtensibleStorageEntity entity => entity.Fields.Values.All(v => IsComplete(v, depth + 1)), + List items => items.All(v => IsComplete(v, depth + 1)), + KeyValuePair entry => IsComplete(entry.Key, depth + 1) && IsComplete(entry.Value, depth + 1), + double real => double.IsFinite(real), + _ => !ReferenceEquals(value, UnavailableEntityValue), + }; +} diff --git a/src/RvtIO/Parsing/WideBlockWalker.cs b/src/RvtIO/Parsing/WideBlockWalker.cs index e1715c10..da42d2d9 100644 --- a/src/RvtIO/Parsing/WideBlockWalker.cs +++ b/src/RvtIO/Parsing/WideBlockWalker.cs @@ -21,14 +21,14 @@ namespace RvtIO.Parsing; /// the file when those are given (); without them the entity is passed and the objects that lie /// behind its values are read out of place. /// -internal sealed class WideBlockWalker +internal sealed partial class WideBlockWalker { internal readonly record struct Capture(string Key, CaptureKind Kind, long Integer, double Real, string? Text, bool AtRoot, int QueueIndex, string DeclaringClass, string Field); internal enum CaptureKind { Integer, Real, Text, PointerClass } - internal sealed class Walk + internal sealed partial class Walk { public bool RootRead; public bool Exact; @@ -125,9 +125,11 @@ internal WideBlockWalker(SchemaDocument schema, Func /// An entity whose schema is not given or not read is passed as without the schemas (the readers behind the /// output); otherwise it stops the walk (the census). - internal void UseEntitySchemas(IReadOnlyDictionary schemas, bool passUnknown = false) + internal void UseEntitySchemas(IReadOnlyDictionary schemas, bool passUnknown = false, + IReadOnlyDictionary? publicEntityNames = null) { _passUnknownEntities = passUnknown; + _publicEntityNames = publicEntityNames; _entityLayouts = [.. schemas.Values]; _entityLayoutOf = schemas.Keys.Select((guid, index) => (guid, index)).ToDictionary(pair => pair.guid, pair => pair.index); } @@ -292,29 +294,40 @@ private static int Take(Context c, int n) private static uint U32(Context c) => BitConverter.ToUInt32(c.D, Take(c, 4)); - private void ReadObject(Context c, int classId, int depth) + private void ReadObject(Context c, int classId, int depth, EntityFields? entityFields = null) { if (depth > 40) throw new Fail("depth"); if (++c.Steps > StepBudget) throw new Fail("step budget"); if (classId < 0) { ReadEntityPayload(c, classId, depth); return; } - Dictionary? record = _recordClasses.Contains(classId) ? new() : null; + bool entityCell = _publicEntityNames is { Count: > 0 } && depth == 1 && _classes[classId].Name == "ESEntityCell"; + Dictionary? record = entityCell ? new EntityFields() : entityFields; + if (record == null && _recordClasses.Contains(classId)) record = new(); if (record != null && c.AtRoot) record[RootFieldKey] = c.RootField; foreach (var (declaring, field) in Chain(classId)) ReadField(c, declaring, field, depth, record); - if (record != null) c.Walk.Records.Add((classId, c.QueueIndex, record)); + if (entityCell) + (c.Walk.EntityCells ??= [])[c.QueueIndex] = record!.GetValueOrDefault("m_entityMap"); + else if (record != null && entityFields == null) + c.Walk.Records.Add((classId, c.QueueIndex, record)); } // The values of an extensible storage entity are the fields of its schema, which the class schema does not hold: each one stored // like a class field of the same type, in the order of ESField.m_entryIndex. private void ReadEntityPayload(Context c, int queued, int depth) { - foreach (var field in _entityLayouts[-1 - queued]!) ReadField(c, _entityBlob, field, depth, null); + EntityFields? values = c.Walk.EntityPayloads?.GetValueOrDefault(c.QueueIndex); + foreach (var field in _entityLayouts[-1 - queued]!) + { + ReadField(c, _entityBlob, field, depth, values); + values?.TryAdd(field.Name, UnavailableEntityValue); + } } // ESEntity.m_blob is an owned pointer whose class tag is not written: a handle of 0 is no entity and nothing follows; behind // 0xFFFFFFFF the 16-byte GUID of the entity's schema stands where the class tag would, and the values are queued like any owned object. // False when the entity is to be passed as without the schemas: nothing is read then. - private bool QueueEntityPayload(Context c, uint handle) + private bool QueueEntityPayload(Context c, uint handle, EntityFields? values) { + if (values != null) values["m_blob"] = handle == 0 ? null : UnavailableEntityValue; if (handle == 0) return true; if (_passUnknownEntities && !(handle == 0xFFFFFFFF && c.Pos + 16 <= c.End && _entityLayoutOf!.TryGetValue(new Guid(c.D.AsSpan(c.Pos, 16)), out int known) && _entityLayouts[known] != null)) return false; @@ -323,6 +336,12 @@ private bool QueueEntityPayload(Context c, uint handle) if (!_entityLayoutOf!.TryGetValue(guid, out int layout)) throw new Fail("entity schema not stored"); if (_entityLayouts[layout] == null) throw new Fail("entity field type"); if (c.Walk.Queue.Count >= 1_000_000) throw new Fail("queue"); + if (values != null && _publicEntityNames?.TryGetValue(guid, out string? name) == true) + { + var fields = new EntityFields(); + (c.Walk.EntityPayloads ??= [])[c.Walk.Queue.Count] = fields; + values["m_blob"] = new Model.ExtensibleStorageEntity(guid, name, fields); + } c.Walk.Queue.Add(-1 - layout); if (c.Walk.EmptyEntityAt < 0) c.Walk.EmptyEntityAt = c.QueueIndex; return true; @@ -342,6 +361,7 @@ private void ReadField(Context c, SchemaClass declaring, SchemaField f, int dept if (hi == 1) { int n = f.Fixed ?? 0; + if (record is EntityFields fixedValues) { ReadEntityArray(c, declaring, f, depth, fixedValues, n); return; } for (int i = 0; i < n; i++) Scalar(c, declaring, f, key == null ? null : key + "@" + i, depth, record, null); return; } @@ -350,6 +370,7 @@ private void ReadField(Context c, SchemaClass declaring, SchemaField f, int dept uint n = U32(c); if (n == 0xFFFFFFFF) n = 0; if (n > 5_000_000) throw new Fail("count " + n + " at " + declaring.Name + "." + f.Name); + if (record is EntityFields countedValues) { ReadEntityArray(c, declaring, f, depth, countedValues, (int)n); return; } if (key != null) c.Walk.Captures.Add(new(key + "#", CaptureKind.Integer, n, 0, null, c.AtRoot && depth == 0, c.QueueIndex, declaring.Name, f.Name)); // The host type of an empty array is zero (the Revit 2022 walk keeps that zero as the first entry) if (key != null && n == 0 && declaring.Name == "Family" && f.Name == "m_refTypeIds") @@ -388,7 +409,10 @@ void Note(CaptureKind kind, long i, double d, string? s) { int p = Take(c, 1); Note(CaptureKind.Integer, c.D[p], 0, null); - if (record != null) record[f.Name] = (long)c.D[p]; + if (record != null) + record[f.Name] = record is EntityFields && f.Type == 1 + ? c.D[p] switch { 0 => false, 1 => true, _ => UnavailableEntityValue } + : (long)c.D[p]; return; } case 3: @@ -445,7 +469,7 @@ void Note(CaptureKind kind, long i, double d, string? s) int p = Take(c, 8); long v = BitConverter.ToInt64(c.D, p); Note(CaptureKind.Integer, v, 0, null); - if (record != null) record[f.Name] = v; + if (record != null) record[f.Name] = record is EntityFields ? ExactEntityInteger(v) : v; return; } case 8: @@ -460,7 +484,8 @@ void Note(CaptureKind kind, long i, double d, string? s) return; } case 9: - Take(c, 16); + int guidAt = Take(c, 16); + if (record is EntityFields) record[f.Name] = new Guid(c.D.AsSpan(guidAt, 16)); return; case 13: { @@ -493,7 +518,7 @@ private void ReadReference(Context c, SchemaClass declaring, SchemaField f, stri { uint handle = U32(c); int tag = 0; - if (_entityLayoutOf != null && declaring.Name == "ESEntity" && f.Name == "m_blob" && QueueEntityPayload(c, handle)) return; + if (_entityLayoutOf != null && declaring.Name == "ESEntity" && f.Name == "m_blob" && QueueEntityPayload(c, handle, record as EntityFields)) return; // Without the entity schemas: an extensible storage entity whose schema GUID behind the handle repeats the pair key in // front of it is passed, and nothing is queued for its values. if (handle == 0xFFFFFFFF && declaring.Name == "ESEntity" && f.Name == "m_blob" && c.Pos >= 20 && c.Pos + 16 <= c.End @@ -502,7 +527,7 @@ private void ReadReference(Context c, SchemaClass declaring, SchemaField f, stri Take(c, 16); if (c.Walk.EmptyEntityAt < 0) c.Walk.EmptyEntityAt = c.QueueIndex; if (key != null) walk.Captures.Add(new(key, CaptureKind.PointerClass, -1, 0, null, c.AtRoot && depth == 0, c.QueueIndex, declaring.Name, f.Name)); - if (record != null) record[f.Name] = 0L; + if (record != null && record is not EntityFields) record[f.Name] = 0L; return; } if (handle != 0) @@ -514,11 +539,14 @@ private void ReadReference(Context c, SchemaClass declaring, SchemaField f, stri if (walk.Queue.Count >= 1_000_000) throw new Fail("queue"); if (_captureRootPointers && c.AtRoot && depth == 0 && key != null) (walk.RootPointers ??= new())[key] = walk.Queue.Count; + if (_publicEntityNames is { Count: > 0 } && c.AtRoot && depth == 0 && declaring.Name == "Element" + && f.Name == "m_cellList" && _classes[tag].Name == "CellList") + walk.OwnCellList = walk.Queue.Count; walk.Queue.Add(tag); } } if (key != null) walk.Captures.Add(new(key, CaptureKind.PointerClass, handle == 0 ? 0 : tag == 0 ? -1 : tag, 0, null, c.AtRoot && depth == 0, c.QueueIndex, declaring.Name, f.Name)); - if (record != null) record[f.Name] = (long)tag; + if (record != null) record[f.Name] = record is EntityFields ? UnavailableEntityValue : (long)tag; return; } if (f.Ref is int reference) @@ -528,6 +556,7 @@ private void ReadReference(Context c, SchemaClass declaring, SchemaField f, stri // ElementId: Identifier.m_id (4 bytes) or Identifier.m_id64 (8 bytes) int p = Take(c, _idWidth); long id = _idWidth == 8 ? BitConverter.ToInt64(c.D, p) : BitConverter.ToInt32(c.D, p); + if (record is EntityFields) { record[f.Name] = ExactEntityInteger(id); return; } if (_ids != null) id = _ids.Key(id); if (key != null) walk.Captures.Add(new(key, CaptureKind.Integer, id, 0, null, c.AtRoot && depth == 0, c.QueueIndex, declaring.Name, f.Name)); if (record != null) record[f.Name] = id; @@ -537,7 +566,13 @@ private void ReadReference(Context c, SchemaClass declaring, SchemaField f, stri int structAt = c.Pos; // a stop behind this structure belongs to the field that holds it, not to the last field of the structure var (outerClass, outerField) = (c.Declaring, c.Field); - ReadObject(c, reference, depth + 1); + if (record is EntityFields) + { + var values = new EntityFields(); + ReadObject(c, reference, depth + 1, values); + record[f.Name] = EntityInlineValue(_classes[reference].Name, values); + } + else ReadObject(c, reference, depth + 1); c.Declaring = outerClass; c.Field = outerField; // the GUID of an entity schema is kept as its value in the record of the schema diff --git a/src/RvtIO/RvtFileReader.cs b/src/RvtIO/RvtFileReader.cs index 3d9a8671..b3c0c219 100644 --- a/src/RvtIO/RvtFileReader.cs +++ b/src/RvtIO/RvtFileReader.cs @@ -65,7 +65,7 @@ public RevitFileInfo Read(string rvtPath) Dictionary? tfSchemas = null; LogPhase("Decompressing partitions..."); - var chunks = DecompressPartitions(root, diag, out var ownPartitionWallParts, out var partitionStreams, out var framedStreams, out bool staleCopiesRemoved, out var incrementRoutedPartitions); + var chunks = DecompressPartitions(root, diag, out var ownPartitionWallParts, out var partitionStreams, out var framedStreams, out bool staleCopiesRemoved, out var incrementRoutedPartitions, collectFamilyStorage: true); var fmtChunks = DecompressStorage(root, "Formats", diag); if (fmtChunks.Count > 0) { @@ -113,6 +113,7 @@ public RevitFileInfo Read(string rvtPath) r22View, partitionStreams, framedStreams, wideSchema, elemTable, elemWorksets, fileMetadata, projectInfo, transmissionData, episodeTable, elemRecHistories, elemRecOwners, tfSchemas, ownPartitionWallParts, staleCopiesRemoved, incrementRoutedPartitions, elemTableIsExact, previewBase64, previewMime, diag, LogPhase, ids); + ExtensibleStorageReader.Apply(root, rvtInfo, framedStreams); LastParsingState = state; return rvtInfo; } @@ -1077,8 +1078,9 @@ private static void ReadWideElementIndex(RootStorage root, ParsingState state, { fields = new WideNativeParams(schemaDocument = TfSchemaReader.Parse(schemaBytes), ids); // the values of an extensible storage entity are read by its schema, so the objects behind them are read in place - var entitySchemas = EntitySchemaReader.Read(root, schemaDocument); - fields.Walker.UseEntitySchemas(entitySchemas, passUnknown: true); + var publicEntityNames = new Dictionary(); + var entitySchemas = EntitySchemaReader.Read(root, schemaDocument, publicEntityNames); + fields.Walker.UseEntitySchemas(entitySchemas, passUnknown: true, publicEntityNames: publicEntityNames); gridReader = new GridAxisReader(schemaDocument, entitySchemas, ids); } catch (FormatException) { diag?.WriteLine("Wide element records: Formats/Latest does not parse for the field walk"); } @@ -1142,6 +1144,8 @@ private static void ReadWideElementIndex(RootStorage root, ParsingState state, if (drivers.TryGetValue(id, out var exactDrivers) && exactDrivers.Count > 0) state.ExactCurveDrivers[id] = exactDrivers; var np = fields.Build(list[0].Walk, rootClass); if (np == null) continue; + if (np.Fields.TryGetValue("m_id", out int entityOwner) && entityOwner == (int)id) + np.ExtensibleStorage = list[0].Walk.OwnPublicEntities(); if (fields.LevelElevation(list[0].Walk, rootClass) is double levelElevation) { np.Fields["__isLevel"] = 1; @@ -1293,7 +1297,7 @@ void Fail(string reason) private List DecompressPartitions(RootStorage root, TextWriter? diag, out Dictionary? ownPartitionWallParts, out List> partitionStreams, out List framedStreams, - out bool staleCopiesRemoved, out IReadOnlyDictionary? incrementRoutedPartitions) + out bool staleCopiesRemoved, out IReadOnlyDictionary? incrementRoutedPartitions, bool collectFamilyStorage = false) { staleCopiesRemoved = false; var partStor = root.OpenStorage("Partitions"); @@ -1313,10 +1317,14 @@ private List DecompressPartitions(RootStorage root, TextWriter? diag, : null; incrementRoutedPartitions = routing?.Current; // the exact framing of the partition streams (PartitionFraming), when the class table names its marker classes and the id width is known - var framing = FormatsSchema.TryRead(root) is { } formats && PartitionFraming.TagsOf(formats) is { } framingTags + var formats = FormatsSchema.TryRead(root); + var framing = formats != null && PartitionFraming.TagsOf(formats) is { } framingTags && SchemaRelease.IdWidth(SchemaRelease.Effective(SchemaRelease.Saved(BasicFileInfoReader.Read(root).GetValueOrDefault("RevitVersion")), SchemaRelease.FromSchema(formats))) is int framingIdWidth ? (Tags: framingTags, IdWidth: framingIdWidth) : ((PartitionFraming.Tags Tags, int IdWidth)?)null; + ushort? entityCellTag = collectFamilyStorage && framing != null && formats?.IdOf("ESEntityCell") is > 0 and <= ushort.MaxValue and int cell + ? (ushort)cell : null; + foreach (var partEntry in partEntries) { diag?.WriteLine($"Partitions stream: '{partEntry.Name}' ({partEntry.Length:N0} bytes)"); @@ -1336,7 +1344,7 @@ private List DecompressPartitions(RootStorage root, TextWriter? diag, diag?.WriteLine($" Own partition wall parts: {ownPartitionWallParts?.Count.ToString() ?? "unavailable"} ({failure ?? "exact"})"); } - var chunks = CutPartition(raw, framing, decompressor, out var stats, out string? framingFailure, out var framed); + var chunks = CutPartition(raw, framing, decompressor, out var stats, out string? framingFailure, out var framed, entityCellTag); int? partitionNumber = int.TryParse(partEntry.Name, out int parsedPartition) ? parsedPartition : null; if (framed != null && partitionNumber is int partNum) framed = framed with { Partition = partNum }; @@ -1372,20 +1380,30 @@ private List DecompressPartitions(RootStorage root, TextWriter? diag, /// gzip member checked by its CRC and length, and null; otherwise the members a search for gzip headers /// finds, with the recovery of damaged ones (), and the reason the framing does not hold. internal static List CutPartition(byte[] raw, (PartitionFraming.Tags Tags, int IdWidth)? framing, ChunkDecompressor decompressor, - out (int Members, int Decoded, int Failed, int Recovered, int Unverified) stats, out string? framingFailure, out PartitionFraming.Framed? framed) + out (int Members, int Decoded, int Failed, int Recovered, int Unverified) stats, out string? framingFailure, out PartitionFraming.Framed? framed, + ushort? familyEntityCellTag = null) { var segments = new List(); var items = new List(); + var familyItems = new List(); + var familyKeys = familyEntityCellTag.HasValue ? new HashSet(StringComparer.Ordinal) : null; + byte[]? cellTagBytes = familyEntityCellTag is ushort tag ? BitConverter.GetBytes(tag) : null; framed = null; framingFailure = "the class table names no framing classes or the id width is not known"; if (framing is var (tags, idWidth) && PartitionFraming.Walk(raw, tags, idWidth, r => { if (r.Block == 0 && r.Owner != (idWidth == 8 ? ulong.MaxValue : uint.MaxValue)) items.Add(new(r.Channel, r.Owner, r.Offset, r.Item.Length)); + else if (familyKeys != null && r.Key.Length != 0 && r.Channel == 102) + { + familyKeys.Add(r.Key); + if (r.Body.Span.IndexOf(cellTagBytes!) >= 0) + familyItems.Add(new(r.Key, new(r.Channel, r.Owner, r.Offset, r.Item.Length))); + } }, out framingFailure, out _, null, segments)) { stats = (segments.Count, segments.Count, 0, 0, 0); - framed = new PartitionFraming.Framed(segments, items, idWidth); + framed = new PartitionFraming.Framed(segments, items, idWidth) { FamilyEntityCandidates = familyItems, FamilyKeys = familyKeys }; return segments; } var chunks = decompressor.DecompressAll(raw); diff --git a/tests/RvtIO.Tests/PartitionCutTests.cs b/tests/RvtIO.Tests/PartitionCutTests.cs index e682d208..6154e47a 100644 --- a/tests/RvtIO.Tests/PartitionCutTests.cs +++ b/tests/RvtIO.Tests/PartitionCutTests.cs @@ -52,6 +52,23 @@ public void AStreamWhoseFramingDoesNotHold_IsSearchedForGzipMembers() Assert.Equal("the class table names no framing classes or the id width is not known", failure); } + [Fact] + public void FamilyStorageCandidatesKeepTheirContentKeyAndStayOutOfProjectRecords() + { + byte[] raw = TwoBlocks(); + RvtFileReader.CutPartition(raw, Framing, new ChunkDecompressor(), out _, out _, out var framed, Id("Plain")); + var candidate = Assert.Single(framed!.FamilyEntityCandidates); + Assert.Equal(Assert.Single(framed.FamilyKeys!), candidate.ContentKey); + Assert.Equal((102, 2ul), (candidate.Item.Channel, candidate.Item.Owner)); + Assert.All(framed.Items, item => Assert.Equal(1ul, item.Owner)); + var (bytes, start, _) = framed.Bytes(candidate.Item); + Assert.Equal(Id("Plain"), BitConverter.ToUInt16(bytes, start + 12)); + + raw[^10] ^= 0xFF; + RvtFileReader.CutPartition(raw, Framing, new ChunkDecompressor(), out _, out _, out var rejected, Id("Plain")); + Assert.Null(rejected); + } + [Fact] public void TheSegmentsOfAChain_AreTheOutputOfEachOfItsMembers() { diff --git a/tests/RvtIO.Tests/WideBlockWalkerEntityTests.cs b/tests/RvtIO.Tests/WideBlockWalkerEntityTests.cs index c58bde24..0c066f19 100644 --- a/tests/RvtIO.Tests/WideBlockWalkerEntityTests.cs +++ b/tests/RvtIO.Tests/WideBlockWalkerEntityTests.cs @@ -1,4 +1,5 @@ using System.Text; +using RvtIO.Model; using RvtIO.Parsing; using Xunit; @@ -172,6 +173,102 @@ public void ProductionFieldReaderPreservesANameQueuedAfterANestedEntity() Assert.False(reader.Walker.Run(block[..^1], 0, block.Length - 1, HostId).Exact); } + [Theory] + [InlineData(true, true)] + [InlineData(true, false)] + [InlineData(false, true)] + [InlineData(false, false)] + public void OwnPublicEntitiesKeepNestedArraysMapsAndWideValues(bool wideIds, bool publicChild) + { + const int cellList = 20, textEntityPair = 21; + var schema = Schema(wideIds); + schema.Classes[schema.Classes.FindIndex(c => c.Id == HostId)] = new(HostId, "Element", 0, 1, + [Field("m_cellList", 14, 1)], []); + schema.Classes.Add(new(cellList, "CellList", 0, 1, [Field("m_cells", 14, 0x51)], [])); + schema.Classes.Add(new(textEntityPair, "std::pair< AString, ESEntity >", 0, 1, + [Field("first", 8, 0x60), Field("second", 14, 0, EntityId)], [])); + (string Name, string Type, int Container, int Index)[] parent = + [("Child", "ESEntity", 0, 0), ("Children", "ESEntity", 1, 1), ("ByName", "std::pair< AString, ESEntity >", 2, 2)]; + (string Name, string Type, int Container, int Index)[] child = + [("Label", "TCHAR", 0, 0), ("Sequence", "int64_t", 0, 1), ("Flag", "bool", 0, 2), ("Reference", "ElementId", 0, 3)]; + var layouts = EntitySchemaReader.Read(Latest(false, (SchemaA, parent), (SchemaB, child)), schema)!; + var publicNames = new Dictionary { [SchemaA] = "Parent" }; + if (publicChild) publicNames.Add(SchemaB, "Child"); + var walker = new WideBlockWalker(schema, (_, _) => null, []); + walker.UseEntitySchemas(layouts, publicEntityNames: publicNames); + var block = Block(HostId, w => + { + void Entity(Guid id) { w.Write(uint.MaxValue); w.Write(id.ToByteArray()); } + w.Write(uint.MaxValue); w.Write((ushort)cellList); + w.Write(1u); w.Write(uint.MaxValue); w.Write((ushort)CellId); + w.Write(1u); w.Write(SchemaA.ToByteArray()); Entity(SchemaA); + Entity(SchemaB); + w.Write(1u); Entity(SchemaB); + w.Write(1u); Text(w, "key"); Entity(SchemaB); + foreach (var label in new[] { "direct", "array", "map" }) + { + Text(w, label); w.Write(9_007_199_254_740_993L); w.Write(true); + if (wideIds) w.Write(4_294_967_297L); + else w.Write(47); + } + }); + + var walk = walker.Run(block, 0, block.Length, HostId); + Assert.True(walk.Exact, walk.Error); + Assert.Null(walker.Run(block, 0, block.Length - 1, HostId).OwnPublicEntities()); + if (!publicChild) { Assert.Null(walk.OwnPublicEntities()); return; } + + var entity = Assert.Single(walk.OwnPublicEntities()!); + Assert.Equal(SchemaA, entity.SchemaId); + Assert.Equal("Parent", entity.SchemaName); + var direct = Assert.IsType(entity.Fields["Child"]); + Assert.Equal("direct", direct.Fields["Label"]); + Assert.Equal("9007199254740993", direct.Fields["Sequence"]); + Assert.Equal(true, direct.Fields["Flag"]); + Assert.Equal(wideIds ? 4_294_967_297L : 47L, direct.Fields["Reference"]); + var arrayChild = Assert.IsType(Assert.Single(Assert.IsType>(entity.Fields["Children"]))); + Assert.Equal("array", arrayChild.Fields["Label"]); + var entry = Assert.IsType>(Assert.Single(Assert.IsType>(entity.Fields["ByName"]))); + Assert.Equal("key", entry.Key); + Assert.Equal("map", Assert.IsType(entry.Value).Fields["Label"]); + } + + [Fact] + public void FamilySchemaDoesNotBorrowPublicAccessFromTheProjectOrAnotherFamily() + { + var schema = Schema(wideIds: false); + const int cellList = 20; + schema.Classes[schema.Classes.FindIndex(c => c.Id == HostId)] = new(HostId, "Element", 0, 1, + [Field("m_cellList", 14, 1)], []); + schema.Classes.Add(new(cellList, "CellList", 0, 1, [Field("m_cells", 14, 0x51)], [])); + var project = EntitySchemaReader.Read(Latest(false, (SchemaA, [("ProjectValue", "int", 0, 0)])), schema)!; + var local = EntitySchemaReader.Read(Latest(false, (SchemaA, [("FamilyValue", "int", 0, 0)])), schema)!; + var projectNames = new Dictionary { [SchemaA] = "Project" }; + var block = Block(HostId, w => + { + w.Write(uint.MaxValue); w.Write((ushort)cellList); + w.Write(1u); w.Write(uint.MaxValue); w.Write((ushort)CellId); + w.Write(1u); w.Write(SchemaA.ToByteArray()); w.Write(uint.MaxValue); w.Write(SchemaA.ToByteArray()); + w.Write(71); + }); + var walker = new WideBlockWalker(schema, (_, _) => null, []); + + ExtensibleStorageReader.ConfigureFamily(walker, project, projectNames, local, null); + var restricted = walker.Run(block, 0, block.Length, HostId); + Assert.True(restricted.Exact); + Assert.Null(restricted.OwnPublicEntities()); + + ExtensibleStorageReader.ConfigureFamily(walker, project, projectNames, local, new() { [SchemaA] = "Family" }); + var family = Assert.Single(walker.Run(block, 0, block.Length, HostId).OwnPublicEntities()!); + Assert.Equal("Family", family.SchemaName); + Assert.Equal(71L, family.Fields["FamilyValue"]); + + ExtensibleStorageReader.ConfigureFamily(walker, project, projectNames, null, null); + var host = Assert.Single(walker.Run(block, 0, block.Length, HostId).OwnPublicEntities()!); + Assert.Equal("Project", host.SchemaName); + Assert.Equal(71L, host.Fields["ProjectValue"]); + } + [Fact] public void Walk_AnEntityWithTheHandle0_HasNoValues_AndQueuesNothing() { From fe8713e074ec308d4987fcf8616618b1fe70f892 Mon Sep 17 00:00:00 2001 From: mie <79989386+mahach666@users.noreply.github.com> Date: Thu, 19 Nov 2026 21:11:53 +0300 Subject: [PATCH 037/259] Preserve reinforcement and model lines in native NWC export --- CHANGELOG.md | 2 + src/RvtIO.Scene/RvtSceneOptions.cs | 3 + src/RvtIO.Scene/RvtSceneReader.cs | 20 +++- src/RvtIO/Ifc/IfcExporter.cs | 2 +- src/RvtIO/Meshes/ElementMeshOptions.cs | 3 + src/RvtIO/Meshes/ElementMeshes.cs | 39 +++++- src/RvtIO/Meshes/MeshSet.cs | 3 + src/RvtIO/Meshes/ReinforcementMeshes.cs | 112 ++++++++++++++++++ src/RvtIO/Parsing/ElementBuilder.cs | 2 +- src/RvtIO/Parsing/RebarReader.ShapeDriven.cs | 7 +- src/RvtIO/Parsing/RebarReader.cs | 71 +++++++---- src/RvtIO/Parsing/Revit2027ApiValues.cs | 2 +- .../NwcSupplementalGeometryTests.cs | 68 +++++++++++ tests/RvtIO.Tests/RebarReaderTests.cs | 49 +++++++- tools/RvtIO.Nwc/NwcExport.cs | 12 +- tools/RvtIO.Nwc/Program.cs | 6 +- 16 files changed, 355 insertions(+), 46 deletions(-) create mode 100644 src/RvtIO/Meshes/ReinforcementMeshes.cs create mode 100644 tests/RvtIO.Tests/NwcSupplementalGeometryTests.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index 2a4fc260..2b950642 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,8 @@ API between minor releases. ## [Unreleased] +- The native RVT-to-NWC exporter keeps straight model and separation lines as NWC line segments. It also meshes cached reinforcement paths with the model's bar placements, including per-bar caches of free-form reinforcement. + ### Added - Preserve 64-bit Revit element IDs in project reads, source-ID lookups and exports. JSON and Scene carry wide source diff --git a/src/RvtIO.Scene/RvtSceneOptions.cs b/src/RvtIO.Scene/RvtSceneOptions.cs index c3f9210a..24f74650 100644 --- a/src/RvtIO.Scene/RvtSceneOptions.cs +++ b/src/RvtIO.Scene/RvtSceneOptions.cs @@ -7,4 +7,7 @@ public sealed class RvtSceneOptions /// element outside the scene, so it must stay the same for every conversion of one file. Null takes the file name without its /// directory (with the extension) when a path is read; a document passed as it is has no file name and needs this key. public string? ModelKey { get; set; } + + /// Includes straight model lines and reinforcement described by its centre lines. + public bool IncludeModelLinesAndReinforcement { get; set; } } diff --git a/src/RvtIO.Scene/RvtSceneReader.cs b/src/RvtIO.Scene/RvtSceneReader.cs index ebe87180..4ab8b628 100644 --- a/src/RvtIO.Scene/RvtSceneReader.cs +++ b/src/RvtIO.Scene/RvtSceneReader.cs @@ -58,7 +58,7 @@ public static RvtSceneResult Read(string path, RvtSceneOptions? options = null) SeparateFacesWithDistinctOpenings = true, Diagnostics = readDiagnostics, }); - return Map(document, ElementMeshes.Extract(document), key, ReadDiagnostics(readDiagnostics)); + return Map(document, ElementMeshes.Extract(document, MeshOptions(options)), key, ReadDiagnostics(readDiagnostics)); } /// The scene diagnostics of a read: read-cut for each stream a reader limit cut, then for each stream read, in @@ -98,7 +98,7 @@ internal static IEnumerable ReadDiagnostics(RvtReadDiagnostics public static RvtSceneResult Read(RvtDocument document, RvtSceneOptions? options) { ArgumentNullException.ThrowIfNull(document); - return Map(document, ElementMeshes.Extract(document), RequiredKey(options)); + return Map(document, ElementMeshes.Extract(document, MeshOptions(options)), RequiredKey(options)); } /// Turns an opened document into a scene with meshes the caller extracted from it, for example with @@ -117,6 +117,9 @@ public static RvtSceneResult Read(RvtDocument document, MeshSet meshes, RvtScene return Map(document, meshes, RequiredKey(options)); } + private static ElementMeshOptions? MeshOptions(RvtSceneOptions? options) => + options?.IncludeModelLinesAndReinforcement == true ? new() { IncludeModelLinesAndReinforcement = true } : null; + private static string RequiredKey(RvtSceneOptions? options) => options?.ModelKey is { Length: > 0 } key ? key : throw new ArgumentException("A document has no file name: give the model key in RvtSceneOptions.ModelKey.", nameof(options)); @@ -169,7 +172,7 @@ private static RvtSceneResult Map(RvtDocument document, MeshSet meshes, string m SourceId = element?.UniqueId, IfcGuid = element != null ? IfcGuidOf(element) : null, Kind = SceneNodeKind.Element, - Name = element?.Name ?? string.Empty, + Name = mesh.Line != null && string.IsNullOrWhiteSpace(element?.Name) ? "Model Lines" : element?.Name ?? string.Empty, Category = CategoryName(element), TypeName = element != null ? document.GetTypeElement(element)?.Name ?? string.Empty : string.Empty, }; @@ -188,6 +191,17 @@ private static RvtSceneResult Map(RvtDocument document, MeshSet meshes, string m scene.Elements.Add(sceneElement); int instancesBefore = scene.Instances.Count; + if (mesh.Line is { } line) + { + var start = Vector(line.Start) * MetresPerFoot; + var end = Vector(line.End) * MetresPerFoot; + int geometryId = scene.Geometries.Count + 1; + scene.Geometries.Add(new SceneGeometry + { + Id = geometryId, Topology = SceneTopology.Lines, Vertices = [Vector3d.Zero, end - start], Indices = [0, 1], + }); + scene.Instances.Add(new SceneInstance { ElementId = mesh.ElementId, GeometryId = geometryId, Transform = Transform3d.Translate(start) }); + } foreach (var placement in mesh.Placements) { placements++; diff --git a/src/RvtIO/Ifc/IfcExporter.cs b/src/RvtIO/Ifc/IfcExporter.cs index 001814c7..7a77c185 100644 --- a/src/RvtIO/Ifc/IfcExporter.cs +++ b/src/RvtIO/Ifc/IfcExporter.cs @@ -1715,7 +1715,7 @@ bool HasCompetingExactHostedWriterAuthority( if (CurrentProfile && elem.SerializedFamilyId is > 0) { Skip(elem, "owned-by-family-nonspatial"); continue; } // Reinforcement bars are written whole (placement, swept discs, Pset) and contained by // the storey of their lowest point - if (CurrentProfile && elem.RebarBars != null) + if (CurrentProfile && elem.RebarBars is { IsFreeForm: false }) { if (!WriteRebarProduct(w, elem, elemById, ownerHistId, axisId, bldgLocalPlacementId, bodySubCtxId, propertySingleValueIds, int.TryParse(info.Metadata?.RevitVersion, out int revitRelease) && revitRelease >= 2026, storeyIds, storeyResolver, storeyContents)) diff --git a/src/RvtIO/Meshes/ElementMeshOptions.cs b/src/RvtIO/Meshes/ElementMeshOptions.cs index d4f90ad2..2013bdc4 100644 --- a/src/RvtIO/Meshes/ElementMeshOptions.cs +++ b/src/RvtIO/Meshes/ElementMeshOptions.cs @@ -6,4 +6,7 @@ public sealed class ElementMeshOptions /// Returns an element that is exactly its symbols placed as of shared symbol meshes /// (true, the default). False gives every element its own triangles and leaves empty. public bool UseSymbolPlacements { get; set; } = true; + + /// Includes decoded straight model lines and meshes of reinforcement described by its centre lines. + public bool IncludeModelLinesAndReinforcement { get; set; } } diff --git a/src/RvtIO/Meshes/ElementMeshes.cs b/src/RvtIO/Meshes/ElementMeshes.cs index 023cd026..f0de7671 100644 --- a/src/RvtIO/Meshes/ElementMeshes.cs +++ b/src/RvtIO/Meshes/ElementMeshes.cs @@ -1,3 +1,4 @@ +using RvtIO.BuiltIns; using RvtIO.Geometry.Meshing; using RvtIO.Model; using RvtIO.Parsing; @@ -43,7 +44,7 @@ public static MeshSet Extract(RvtDocument document, ElementMeshOptions? options ArgumentNullException.ThrowIfNull(document); options ??= new ElementMeshOptions(); var info = document.RawData; - var drawable = DrawableElements(info); + var drawable = DrawableElements(info, options.IncludeModelLinesAndReinforcement); var drawableIds = drawable.Select(item => item.Element.Id).ToHashSet(); var symbolCache = new Dictionary(); var placedSymbols = new Dictionary>(); @@ -109,7 +110,16 @@ int MaterialOf(GeoFace face) { if (body == null) { - elements.Add(new ElementMesh { ElementId = element.Id, Coverage = MeshCoverage.Undecoded }); + var line = options.IncludeModelLinesAndReinforcement ? ModelLine(element) : null; + var rebar = options.IncludeModelLinesAndReinforcement && element.RebarBars is { } bars ? ReinforcementMeshes.Build(bars) : null; + elements.Add(new ElementMesh + { + ElementId = element.Id, + Line = line, + Meshes = rebar == null ? [] : [rebar], + Coverage = line != null || rebar != null ? MeshCoverage.Complete + : info.WideLayoutNotRewritten ? MeshCoverage.Undecoded : MeshCoverage.NoGeometry, + }); continue; } if (options.UseSymbolPlacements && ReferenceEquals(body, element.Geometry) && PlacementsOf(body) is var (placements, failedInSymbols, untriangulatedInSymbols, symbolGhosts)) @@ -159,7 +169,7 @@ private static bool DropsUntakenNodes(IReadOnlyList faces, bool hasGhos /// The drawable elements (see ) in document order, each with the geometry that is its body: /// the geometry of its computed symbol for a void helper that has one, its own geometry otherwise (null in a document whose /// geometry was not decoded). - internal static List<(Element Element, GeometryData? Body)> DrawableElements(RevitFileInfo info) + internal static List<(Element Element, GeometryData? Body)> DrawableElements(RevitFileInfo info, bool includeModelLinesAndReinforcement = false) { var designOptions = DesignOptions.Of(info.Elements); var phaseFilter = ProductRules.BuildExportPhaseFilter(info, exportPhaseId: null, lastPhaseByDefault: true); @@ -169,20 +179,22 @@ private static bool DropsUntakenNodes(IReadOnlyList faces, bool hasGhos var drawable = new List<(Element, GeometryData?)>(); foreach (var element in info.Elements) { + bool modelLine = includeModelLinesAndReinforcement && ModelLine(element) != null; + bool rebar = includeModelLinesAndReinforcement && element.RebarBars is { Bars.Count: > 0 } or { Items.Count: > 0 }; if (element.IsBlockOnly || element.IsGroupTemplate || designOptions.InNonPrimaryOption(element) == true || phaseFilter?.Excludes(element) == true || element.CategoryId == RevealsCategoryId || ProductRules.IsWallRectangularOpening(element) || ProductRules.IsValidatedStackedWallContainer(element, elementsById) || info.ElemTableIsExact && element.IsDiscovered || element.SerializedFamilyId is > 0 - || ProductRules.IsNonPhysicalCategory(element.Category)) + || (!modelLine && ProductRules.IsNonPhysicalCategory(element.Category))) continue; bool namesPhase = ProductRules.HasProjectPhaseReference(element) || ProductRules.IsTransformOnlyFamily(element); - if (!namesPhase && (typeElementIds.Contains(element.Id) || element.CategoryId != WallsCategoryId)) continue; + if (!namesPhase && !modelLine && !rebar && (typeElementIds.Contains(element.Id) || element.CategoryId != WallsCategoryId)) continue; GeometryData? body = element.Geometry; if (element.SerializedComputedSymbolGeometry is { } computed) body = computed; else if (ProductRules.HasOnlyUnfilledFaces(element)) continue; - if (body != null || info.WideLayoutNotRewritten && element.BoundingBox != null) drawable.Add((element, body)); + if (body != null || modelLine || rebar || info.WideLayoutNotRewritten && element.BoundingBox != null) drawable.Add((element, body)); } // A stair places its runs and landings, a model group its members: those are drawn as elements of their own. var ids = drawable.Select(item => item.Item1.Id).ToHashSet(); @@ -190,6 +202,21 @@ private static bool DropsUntakenNodes(IReadOnlyList faces, bool hasGhos || !mapped.All(instance => ids.Contains(instance.SymbolId))).ToList(); } + private static (MeshVector Start, MeshVector End)? ModelLine(Element element) + { + if (element.CategoryId is not ((int)BuiltInCategory.OST_Lines or (int)BuiltInCategory.OST_RoomSeparationLines + or (int)BuiltInCategory.OST_MEPSpaceSeparationLines) || element.OwnerViewId != null + || !element.RootClassIs("CurveElem") + || !element.Parameters.Any(p => p.Id == (int)BuiltInParameter.CURVE_IS_DETAIL && p.Value is 0) + || element.Location is not { CurveType: "Line" } line + || line.StartPoint is not [var x0, var y0, var z0] || line.EndPoint is not [var x1, var y1, var z1]) + return null; + var start = new Pt3(x0, y0, z0); + var end = new Pt3(x1, y1, z1); + return start.IsFinite && end.IsFinite && (end - start).Norm is > 0 and < double.PositiveInfinity + ? (new(x0, y0, z0), new(x1, y1, z1)) : null; + } + /// The triangles of , one mesh per material in the order the materials first appear, and the /// number of faces that could not be triangulated. The faces of untaken Geometry nodes (a negative node id) are left out when /// a face of a taken node is there, unless the geometry has ghost nodes (). diff --git a/src/RvtIO/Meshes/MeshSet.cs b/src/RvtIO/Meshes/MeshSet.cs index 7cf83c74..e49378d7 100644 --- a/src/RvtIO/Meshes/MeshSet.cs +++ b/src/RvtIO/Meshes/MeshSet.cs @@ -30,6 +30,9 @@ public sealed class ElementMesh /// is given only when the element's geometry is exactly its symbols placed rigidly; any other element has its own triangles. public IReadOnlyList Placements { get; init; } = []; + /// The endpoints of a straight model line in document coordinates (feet), if present. + public (MeshVector Start, MeshVector End)? Line { get; init; } + /// How completely and represent the element. public MeshCoverage Coverage { get; init; } diff --git a/src/RvtIO/Meshes/ReinforcementMeshes.cs b/src/RvtIO/Meshes/ReinforcementMeshes.cs new file mode 100644 index 00000000..93e4fe70 --- /dev/null +++ b/src/RvtIO/Meshes/ReinforcementMeshes.cs @@ -0,0 +1,112 @@ +using RvtIO.Geometry.Meshing; +using RvtIO.Parsing; + +namespace RvtIO.Meshes; + +internal static class ReinforcementMeshes +{ + private const int Sides = 24; + private const double ChordToleranceFeet = 0.0005; + private const double JoinToleranceFeet = 1e-6; + + internal static TriangleMesh? Build(RebarBars element) + { + var mesh = new ElementMeshes.MeshBuilder(0); + foreach (var item in element.Items ?? [element]) + { + double radius = item.ModelDiameter / 2; + if (!double.IsFinite(radius) || radius <= 0) return null; + foreach (var path in item.ModelPaths ?? item.Bars) + if (!AppendBar(mesh, path, radius)) return null; + } + return mesh.Indices.Count > 0 ? mesh.ToMesh() : null; + } + + private static bool AppendBar(ElementMeshes.MeshBuilder mesh, IReadOnlyList path, double radius) + { + int firstRing = mesh.VertexCount; + Pt3 firstPoint = default, firstTangent = default, point = default, tangent = default, normal = default; + foreach (var piece in path) + { + double sweep = piece.End - piece.Start; + if (!double.IsFinite(sweep) || sweep == 0 || piece.Origin.Length != 3 || piece.Axis.Length != 3 + || (piece.IsArc && (piece.Axis2.Length != 3 || !double.IsFinite(piece.Radius) + || piece.Radius <= 0 || Math.Abs(sweep) > 2 * Math.PI + 1e-9))) + return false; + var origin = Pt3.From(piece.Origin); + var x = Pt3.From(piece.Axis); + var y = piece.IsArc ? Pt3.From(piece.Axis2) : default; + double maxStep = piece.IsArc + ? Math.Min(Math.PI / 12, 2 * Math.Acos(Math.Max(0, 1 - ChordToleranceFeet / (piece.Radius + radius)))) + : Math.Abs(sweep); + double steps = Math.Ceiling(Math.Abs(sweep) / maxStep); + if (!(steps is >= 1 and <= 4096)) return false; + + for (int i = 0; i <= (int)steps; i++) + { + double t = piece.Start + sweep * i / steps; + double cos = Math.Cos(t), sin = Math.Sin(t); + var center = piece.IsArc ? origin + piece.Radius * (cos * x + sin * y) : origin + t * x; + var direction = Math.Sign(sweep) * (piece.IsArc ? -sin * x + cos * y : x); + double length = direction.Norm; + if (!center.IsFinite || !double.IsFinite(length) || length <= 0) return false; + direction /= length; + + int ring = mesh.VertexCount; + if (ring == firstRing) + { + firstPoint = center; + firstTangent = direction; + var seed = Math.Abs(direction.Z) < 0.9 ? new Pt3(0, 0, 1) : new Pt3(1, 0, 0); + normal = Pt3.Cross(seed, direction); + } + else if (i == 0) + { + // Adjacent analytic pieces share the end ring. + if ((point - center).Norm > JoinToleranceFeet || tangent.Dot(direction) < 0.999) + return false; + continue; + } + normal -= normal.Dot(direction) * direction; + double normalLength = normal.Norm; + if (!(normalLength > 0)) return false; + normal /= normalLength; + var binormal = Pt3.Cross(direction, normal); + + for (int side = 0; side < Sides; side++) + { + double angle = 2 * Math.PI * side / Sides; + var outward = Math.Cos(angle) * normal + Math.Sin(angle) * binormal; + var vertex = center + radius * outward; + if (!vertex.IsFinite) return false; + mesh.AddVertex(vertex.ToArray(), outward.X, outward.Y, outward.Z); + if (ring == firstRing) continue; + int previous = ring - Sides; + int next = (side + 1) % Sides; + mesh.AddTriangle(previous + side, previous + next, ring + side); + mesh.AddTriangle(previous + next, ring + next, ring + side); + } + point = center; + tangent = direction; + } + } + + if (mesh.VertexCount - firstRing < 2 * Sides) return false; + int lastRing = mesh.VertexCount - Sides; + AddCap(firstRing, firstPoint, -1 * firstTangent, reverse: true); + AddCap(lastRing, point, tangent, reverse: false); + return true; + + void AddCap(int ring, Pt3 center, Pt3 outward, bool reverse) + { + int hub = mesh.VertexCount; + mesh.AddVertex(center.ToArray(), outward.X, outward.Y, outward.Z); + for (int side = 0; side < Sides; side++) + { + int a = ring + side, b = ring + (side + 1) % Sides; + if (reverse) mesh.AddTriangle(hub, b, a); + else mesh.AddTriangle(hub, a, b); + } + } + } +} diff --git a/src/RvtIO/Parsing/ElementBuilder.cs b/src/RvtIO/Parsing/ElementBuilder.cs index 071b2abf..f530c677 100644 --- a/src/RvtIO/Parsing/ElementBuilder.cs +++ b/src/RvtIO/Parsing/ElementBuilder.cs @@ -1190,7 +1190,7 @@ public static void BuildElemTableElement( // heuristics. The element is what the file's own tables and the schema-driven block // walk give: the header category is exact. if (elem.NativeRootClassName is "Rebar" or "RebarInSystem" - && elem.RebarBars is { BarTypeId: > 0 } bars + && elem.RebarBars is { BarTypeId: > 0, IsFreeForm: false } bars && state.NativeRootClassNames.GetValueOrDefault((uint)bars.BarTypeId) == "RebarBarType") elem.TypeId = bars.BarTypeId; if (wideHeaderCategory is int resolvedHeader) diff --git a/src/RvtIO/Parsing/RebarReader.ShapeDriven.cs b/src/RvtIO/Parsing/RebarReader.ShapeDriven.cs index b5575ffa..dddf19f9 100644 --- a/src/RvtIO/Parsing/RebarReader.ShapeDriven.cs +++ b/src/RvtIO/Parsing/RebarReader.ShapeDriven.cs @@ -296,12 +296,15 @@ private static bool ConstraintsValid(WideBlockWalker walker, WideBlockWalker.Wal if (pieces == null) return null; var first = pieces.Select(piece => piece.Moved(bar.Frame)).ToList(); var bars = new List>(); + List>? modelPaths = bar.Held ? null : []; for (int i = 0; i < bar.Positions.Count; i++) { if (bar.Included.Count != 0 && bar.Included[i] == 0) continue; - bars.Add(first.Select(s => bar.Held ? s.Moved(bar.Positions[i]) : s.Moved(bar.Positions[i]).Moved(bar.Positions[i])).ToList()); + var placed = first.Select(s => s.Moved(bar.Positions[i])).ToList(); + modelPaths?.Add(placed); + bars.Add(bar.Held ? placed : placed.Select(s => s.Moved(bar.Positions[i])).ToList()); } return new RebarBars(bar.BarTypeId, 0, bar.BarLength, bars, ShapeName: bar.ShapeId.ToString(CultureInfo.InvariantCulture), - InAssembly: bar.InAssembly, ShapeId: bar.ShapeId); + InAssembly: bar.InAssembly, ShapeId: bar.ShapeId, ModelPaths: modelPaths); } } diff --git a/src/RvtIO/Parsing/RebarReader.cs b/src/RvtIO/Parsing/RebarReader.cs index a6efc92f..1a1918c9 100644 --- a/src/RvtIO/Parsing/RebarReader.cs +++ b/src/RvtIO/Parsing/RebarReader.cs @@ -46,10 +46,12 @@ private static double[] Point(double[] t, double[] p) /// is true for a bar that is a member of an assembly (AssemblyGroupMembership cell). /// A RebarContainer holds no bars of its own: are its items (one bar each, is the index of the item /// in the container) and is the name of the container type. -/// is true for a RebarInSystem that is the one RebarInSystem of its system. +/// is true for a RebarInSystem that is the one RebarInSystem of its system. +/// gives the bar paths with Revit model placement when it differs from the IFC exporter convention. internal sealed record RebarBars(int BarTypeId, int SystemId, double? BarLength, IReadOnlyList> Bars, double NominalDiameter = 0, double ModelDiameter = 0, string? BarTypeName = null, double LengthRoundingMillimetres = 0, string? ShapeName = null, - bool InAssembly = false, IReadOnlyList? Items = null, int ItemIndex = -1, bool OnlyBarOfSystem = false, int ShapeId = 0); + bool InAssembly = false, IReadOnlyList? Items = null, int ItemIndex = -1, bool OnlyBarOfSystem = false, int ShapeId = 0, bool IsFreeForm = false, + IReadOnlyList>? ModelPaths = null); /// A beam system (JoistSystem): its type (JoistSystemAttr, from SymbolInfo.m_name) and the beams it holds /// (HeldBeam.m_existingBeamId, in stored order, deleted ones left out). @@ -240,7 +242,8 @@ internal static ReinforcementData Read( { ItemIndex = index, InAssembly = inAssembly, ShapeName = null, NominalDiameter = itemDiameters.Nominal, ModelDiameter = itemDiameters.Model, BarTypeName = itemDiameters.Name, LengthRoundingMillimetres = rounding, - Bars = solvedItem.Bars.Select(bar => (IReadOnlyList)bar.Select(piece => piece.Moved(hostFrame)).ToList()).ToList(), + Bars = MovePaths(solvedItem.Bars, hostFrame), + ModelPaths = solvedItem.ModelPaths is { } modelPaths ? MovePaths(modelPaths, hostFrame) : null, }); if (solvedItems.Count > 0 && containerNames.TryGetValue(typeId, out var typeName)) result.TryAdd(id, new RebarBars(-1, 0, null, [], BarTypeName: typeName, Items: solvedItems, InAssembly: inAssembly)); @@ -279,6 +282,9 @@ internal static ReinforcementData Read( return empty; } + private static IReadOnlyList> MovePaths(IReadOnlyList> paths, double[] frame) => + paths.Select(path => (IReadOnlyList)path.Select(piece => piece.Moved(frame)).ToList()).ToList(); + /// A RebarContainer: its type and the shape driven bar of each of its RebarContainerItem objects (the walk of the root queues them in /// the order of the items); null when an item cannot be read. private static (int TypeId, int HostId, bool InAssembly, List Items)? ReadContainer( @@ -511,8 +517,9 @@ private static List WithCuts(WideBlockWalker walker, WideBlockWalker.Walk private static RebarBars? ReadRebar(WideBlockWalker walker, WideBlockWalker.Walk walk, Dictionary> byQueue) { - int instance = walk.Queue.FindIndex(c => walker.Class(c)?.Name == "RebarInstance"); + int instance = walk.Queue.FindIndex(c => walker.Class(c)?.Name is "RebarInstance" or "RebarInstFreeForm"); if (instance < 0 || !byQueue.TryGetValue(instance, out var caps)) return null; + bool freeForm = walker.Class(walk.Queue[instance])?.Name == "RebarInstFreeForm"; // the lists of the cache are two counts, then the OneBarCenterlineCurves objects of the first and of the second list int cache = Children(walk, instance).FirstOrDefault(q => walker.Class(walk.Queue[q])?.Name == "RebarInstCache", -1); if (cache < 0 || !byQueue.TryGetValue(cache, out var cacheCaps)) return null; @@ -524,33 +531,53 @@ private static List WithCuts(WideBlockWalker walker, WideBlockWalker.Walk // the list of bars without self intersection is the one exported var oneBar = firstCount > 0 ? lists[0] : secondCount > 0 ? lists[(int)firstCount] : -1; if (oneBar < 0) return null; - var first = new List(); - foreach (int q in Children(walk, oneBar)) - { - var segment = Curve(walker, walk, byQueue, q); - if (segment == null) return null; - first.Add(segment); - } - if (first.Count == 0) return null; - - var trfs = Transforms(caps); - if (!trfs.TryGetValue(Positions, out var positions) || positions.Count == 0) return null; - int count = positions.Count; var flags = IncludedFlags(caps); var bars = new List>(); - for (int i = 0; i < count; i++) + List>? modelPaths = null; + if (freeForm) + { + // The free-form cache stores one already positioned path for each bar. + long count = Integer(caps, "RebarInstBase.m_numberOfBarPositions") ?? -1; + if ((firstCount > 0 ? firstCount : secondCount) != count || (flags.Count != 0 && flags.Count != count)) + return null; + for (int i = 0; i < count; i++) + { + if (flags.Count != 0 && flags[i] == 0) continue; + if (ReadPath(lists[i]) is not { } path) return null; + bars.Add(path); + } + } + else { - if (flags.Count == count && flags[i] == 0) continue; - // The exported geometry moves the first bar by the position transform twice (a stored spacing of 400 mm is written as 800 mm); - // a pure translation is then 2 * the stored offset - bars.Add(first.Select(s => s.Moved(positions[i]).Moved(positions[i])).ToList()); + if (ReadPath(oneBar) is not { } first) return null; + if (!Transforms(caps).TryGetValue(Positions, out var positions) || positions.Count == 0) return null; + modelPaths = new(); + for (int i = 0; i < positions.Count; i++) + { + if (flags.Count == positions.Count && flags[i] == 0) continue; + var placed = first.Select(s => s.Moved(positions[i])).ToList(); + modelPaths.Add(placed); + // The IFC compatibility path applies the position transform twice. + bars.Add(placed.Select(s => s.Moved(positions[i])).ToList()); + } } double? length = caps.FirstOrDefault(c => c.Key == "RebarInstBase.m_barLength" && c.Kind == WideBlockWalker.CaptureKind.Real) is { } l ? l.Real : null; // the shape id travels in ShapeName until the shapes are read long shape = Integer(caps, "RebarInstBase.m_shapeId") ?? 0; return new RebarBars((int)(Integer(caps, "RebarInstBase.m_barTypeId") ?? -1), 0, length, bars, ShapeName: shape.ToString(CultureInfo.InvariantCulture), InAssembly: InAssembly(walker, walk, byQueue), - ShapeId: shape is > 0 and <= int.MaxValue ? (int)shape : 0); + ShapeId: shape is > 0 and <= int.MaxValue ? (int)shape : 0, IsFreeForm: freeForm, ModelPaths: modelPaths); + + IReadOnlyList? ReadPath(int bar) + { + var path = new List(); + foreach (int q in Children(walk, bar)) + { + if (Curve(walker, walk, byQueue, q) is not { } segment) return null; + path.Add(segment); + } + return path.Count > 0 ? path : null; + } } /// The queue indexes the queued object appended while it was read. diff --git a/src/RvtIO/Parsing/Revit2027ApiValues.cs b/src/RvtIO/Parsing/Revit2027ApiValues.cs index 1dded6d6..8b4931c9 100644 --- a/src/RvtIO/Parsing/Revit2027ApiValues.cs +++ b/src/RvtIO/Parsing/Revit2027ApiValues.cs @@ -108,7 +108,7 @@ internal static void Apply(RevitFileInfo info, ParsingState state, IReadOnlyDict parameter.HasNoRevitValue = true; } break; - case "Rebar" or "RebarInSystem" when element.RebarBars is { Bars.Count: > 0 } bar: + case "Rebar" or "RebarInSystem" when element.RebarBars is { Bars.Count: > 0, IsFreeForm: false } bar: if (RootIs(state, bar.BarTypeId, "RebarBarType")) SetTypeParameters(element, bar.BarTypeId); SetParameter(element, BuiltInParameter.REBAR_ELEM_QUANTITY_OF_BARS, StorageType.Integer, bar.Bars.Count); diff --git a/tests/RvtIO.Tests/NwcSupplementalGeometryTests.cs b/tests/RvtIO.Tests/NwcSupplementalGeometryTests.cs new file mode 100644 index 00000000..12462aaf --- /dev/null +++ b/tests/RvtIO.Tests/NwcSupplementalGeometryTests.cs @@ -0,0 +1,68 @@ +using IOScene; +using RvtIO.BuiltIns; +using RvtIO.Meshes; +using RvtIO.Model; +using RvtIO.Parsing; +using RvtIO.Scene; +using Xunit; + +namespace RvtIO.Tests; + +public class NwcSupplementalGeometryTests +{ + [Fact] + public void NativeSceneIncludesModelLineAndReinforcementButSkipsDetailAndSketchCurves() + { + var modelLine = Line(1, BuiltInCategory.OST_MEPSpaceSeparationLines, detail: false); + var detail = Line(2, BuiltInCategory.OST_Lines, detail: true); + var sketch = Line(3, BuiltInCategory.OST_SketchLines, detail: false); + var bar = RebarReaderTests.Bar(4, systemId: 0); + var document = RvtDocument.FromInfo(new RevitFileInfo { Elements = [modelLine, detail, sketch, bar] }); + + Assert.Empty(RvtSceneReader.Read(document, new() { ModelKey = "model" }).Document.Elements); + var scene = RvtSceneReader.Read(document, new() { ModelKey = "model", IncludeModelLinesAndReinforcement = true }); + + Assert.Equal(new long[] { 1, 4 }, scene.Document.Elements.Select(item => item.Id)); + Assert.Equal(2, scene.ElementsWithGeometry); + var linePlacement = Assert.Single(scene.Document.Instances, item => item.ElementId == 1); + var geometry = Assert.Single(scene.Document.Geometries, item => item.Id == linePlacement.GeometryId); + Assert.Equal(SceneTopology.Lines, geometry.Topology); + var translation = linePlacement.Transform!.Value.Translation; + Assert.Equal(0.3048, translation.X, 12); + Assert.Equal(0.6096, translation.Y, 12); + Assert.Equal(0.9144, translation.Z, 12); + Assert.Collection(geometry.Vertices, point => Assert.Equal(Vector3d.Zero, point), point => Assert.Equal(0.6096, point.X, 12)); + var native = Nwc.NwcExport.Build(scene.Document, "model.rvt", 0, DateTime.UnixEpoch, native: true); + Assert.Equal(new[] { 0, 1 }, Assert.Single(native.Meshes, m => m.LineIndices.Count > 0).LineIndices); + Assert.NotEmpty(Assert.Single(native.Meshes, m => m.TriangleCount > 0).Indices); + } + + [Fact] + public void SweepKeepsTheStoredRadiusAndExtentsOfAStraightBar() + { + var segment = new RebarSegment(false, [4, 5, 6], [0, 0, 1], [], 0, 0, 10); + var mesh = ReinforcementMeshes.Build(new RebarBars(1, 0, 10, [[segment]], ModelDiameter: 0.5)); + Assert.NotNull(mesh); + + var points = mesh.Positions.Chunk(3).ToArray(); + Assert.Equal(3.75, points.Min(p => p[0]), 12); + Assert.Equal(4.25, points.Max(p => p[0]), 12); + Assert.Equal(4.75, points.Min(p => p[1]), 12); + Assert.Equal(5.25, points.Max(p => p[1]), 12); + Assert.Equal(6, points.Min(p => p[2]), 12); + Assert.Equal(16, points.Max(p => p[2]), 12); + Assert.All(mesh.Indices, i => Assert.InRange(i, 0, points.Length - 1)); + } + + private static Element Line(int id, BuiltInCategory category, bool detail) => new() + { + Id = id, + NativeRootClassName = "CurveElem", + NativeRootClassChain = ["CurveElem"], + CategoryId = (int)category, + Category = category.ToString(), + SerializedOwnerDbViewId = detail ? 99 : -1, + Parameters = [new() { Id = (int)BuiltInParameter.CURVE_IS_DETAIL, StorageType = StorageType.Integer, Value = detail ? 1 : 0 }], + Location = new() { StartPoint = [1, 2, 3], EndPoint = [3, 2, 3], Length = 2 }, + }; +} diff --git a/tests/RvtIO.Tests/RebarReaderTests.cs b/tests/RvtIO.Tests/RebarReaderTests.cs index 9f3cae08..70635444 100644 --- a/tests/RvtIO.Tests/RebarReaderTests.cs +++ b/tests/RvtIO.Tests/RebarReaderTests.cs @@ -17,7 +17,7 @@ public class RebarReaderTests private static SchemaField Field(string name, byte type, byte mods = 0, int? reference = null, int? fixedCount = null, List? args = null) => new(name, type, mods, 0, fixedCount, reference, null, args); - private static SchemaDocument Schema() => new() + private static SchemaDocument Schema(bool freeForm = false) => new() { Classes = [ @@ -33,8 +33,9 @@ private static SchemaField Field(string name, byte type, byte mods = 0, int? ref [Field("m_noSelfIntersectingCenterlineCurves", 14, 81), Field("m_selfIntersectingCenterlineCurves", 14, 81)], []), new(InstBase, "RebarInstBase", 0, 1, [Field("m_barPositionsRelativeToFirstBarArr", 14, 80, Trf), Field("m_oCacheData", 14, 1), Field("m_includedBars", 1, 80), - Field("m_barTypeId", 14, 0, ElementId), Field("m_barLength", 7)], []), - new(Instance, "RebarInstance", InstBase, 1, [], []), + Field("m_barTypeId", 14, 0, ElementId), Field("m_barLength", 7), + .. (freeForm ? new[] { Field("m_numberOfBarPositions", 4) } : [])], []), + new(Instance, freeForm ? "RebarInstFreeForm" : "RebarInstance", InstBase, 1, [], []), new(Element, "Element", 0, 1, [Field("m_id", 14, 0, ElementId)], []), new(Rebar, "Rebar", Element, 1, [Field("m_oInstance", 14, 1)], []), ], @@ -118,6 +119,7 @@ public void ReadRebar_MovesTheCachedBarByEveryPositionTwiceAndKeepsTheLengthAndT Assert.Equal(0, bars.Bars[0][0].Origin[0]); // The current profile applies the position transform twice: the second position (offset 1) lies 2 feet from the first Assert.Equal(2, bars.Bars[1][0].Origin[0]); + Assert.Equal(1, bars.ModelPaths![1][0].Origin[0]); Assert.Equal(4, bars.Bars[1][1].Origin[0]); Assert.True(bars.Bars[0][1].IsArc); Assert.Equal(0.5, bars.Bars[0][1].Radius); @@ -134,6 +136,47 @@ public void ReadRebar_LeavesOutABarThatIsNotIncluded() } + [Theory] + [InlineData(false)] + [InlineData(true)] + public void ReadFreeFormRebarKeepsTheCachedPathOfEachIncludedPosition(bool secondIncluded) + { + var schema = Schema(freeForm: true); + using var stream = new MemoryStream(); + using var writer = new BinaryWriter(stream, Encoding.Unicode); + writer.Write((ushort)Rebar); + writer.Write(55L); + Pointer(writer, Instance); + writer.Write(2u); + Transform(writer, 0); + Transform(writer, 100); + Pointer(writer, Cache); + writer.Write(2u); + writer.Write((byte)1); + writer.Write((byte)(secondIncluded ? 1 : 0)); + writer.Write(9L); + writer.Write(3.5); + writer.Write(2); + writer.Write(2u); + Pointer(writer, OneBar); + Pointer(writer, OneBar); + writer.Write(0u); + writer.Write(1u); + Pointer(writer, GLine); + writer.Write(1u); + Pointer(writer, GLine); + foreach (double value in new[] { 0.0, 2, 1, 0, 0, 1, 0, 0, 0, 2, 7, 0, 0, 1, 0, 0 }) + writer.Write(value); + var data = stream.ToArray(); + var walker = new WideBlockWalker(schema, RebarReader.Key, []); + var walk = walker.Run(data, 0, data.Length, Rebar); + Assert.True(walk.Exact, walk.Error); + var bars = RebarReader.ReadRebar(walker, walk); + Assert.NotNull(bars); + Assert.True(bars.IsFreeForm); + Assert.Equal(secondIncluded ? new[] { 1.0, 7.0 } : new[] { 1.0 }, bars.Bars.Select(path => path[0].Origin[0])); + } + private static string Export(params Element[] elements) { var info = new RevitFileInfo(); diff --git a/tools/RvtIO.Nwc/NwcExport.cs b/tools/RvtIO.Nwc/NwcExport.cs index b208444a..e637834a 100644 --- a/tools/RvtIO.Nwc/NwcExport.cs +++ b/tools/RvtIO.Nwc/NwcExport.cs @@ -18,7 +18,7 @@ internal static NwcDocument Build(SceneDocument scene, string sourceName, long s if (scene.Validate().FirstOrDefault(d => d.Severity == SceneSeverity.Error) is { } error) throw new InvalidDataException(error.Message); if (scene.Instances.Count == 0) - throw new InvalidDataException("The model has no triangle geometry to export."); + throw new InvalidDataException(native ? "The model has no triangle or line geometry to export." : "The model has no triangle geometry to export."); var root = new NwcNode { Id = 0, Name = sourceName, Class = "Model" }; int nextNodeId = 1; @@ -71,8 +71,9 @@ internal static NwcDocument Build(SceneDocument scene, string sourceName, long s foreach (var instance in scene.Instances) { var geometry = geometries[instance.GeometryId]; - if (geometry.Topology != SceneTopology.Triangles || geometry.Vertices.Count < 3) - throw new InvalidDataException($"Geometry {geometry.Id} is not a triangle mesh."); + bool lines = native && geometry.Topology == SceneTopology.Lines; + if (lines ? geometry.Vertices.Count < 2 : geometry.Topology != SceneTopology.Triangles || geometry.Vertices.Count < 3) + throw new InvalidDataException($"Geometry {geometry.Id} does not have a supported topology."); var transform = instance.Transform ?? Transform3d.Identity; var linear = new Transform3d(transform.XAxis, transform.YAxis, transform.ZAxis, SceneVector.Zero); @@ -80,7 +81,7 @@ internal static NwcDocument Build(SceneDocument scene, string sourceName, long s var indices = geometry.Indices.Count == 0 ? Enumerable.Range(0, vertices.Length).ToArray() : geometry.Indices.ToArray(); - if (SceneVector.Dot(transform.XAxis, SceneVector.Cross(transform.YAxis, transform.ZAxis)) < 0) + if (!lines && SceneVector.Dot(transform.XAxis, SceneVector.Cross(transform.YAxis, transform.ZAxis)) < 0) { for (int i = 0; i < indices.Length; i += 3) (indices[i + 1], indices[i + 2]) = (indices[i + 2], indices[i + 1]); @@ -100,7 +101,8 @@ internal static NwcDocument Build(SceneDocument scene, string sourceName, long s Id = meshId, Name = string.Create(CultureInfo.InvariantCulture, $"{node.Name} [RVT {instance.ElementId}]"), Vertices = vertices, - Indices = indices, + Indices = lines ? [] : indices, + LineIndices = lines ? indices : [], Node = native ? node : null, Material = instance.MaterialId is int materialId ? materials?.GetValueOrDefault(materialId) : null, // The read-back tree also looks for transforms by node ID. diff --git a/tools/RvtIO.Nwc/Program.cs b/tools/RvtIO.Nwc/Program.cs index a3882f0d..bf684ace 100644 --- a/tools/RvtIO.Nwc/Program.cs +++ b/tools/RvtIO.Nwc/Program.cs @@ -47,7 +47,7 @@ public static int Main(string[] args) var source = new FileInfo(input); long length = source.Length; - var scene = RvtSceneReader.Read(input); + var scene = RvtSceneReader.Read(input, native ? new RvtSceneOptions { IncludeModelLinesAndReinforcement = true } : null); foreach (var diagnostic in scene.Diagnostics.Where(d => d.Severity != SceneSeverity.Info)) Console.Error.WriteLine($"RVT {diagnostic.Severity} [{diagnostic.Code}]: {diagnostic.Message}"); if (scene.Diagnostics.Any(d => d.Severity == SceneSeverity.Error)) @@ -55,7 +55,9 @@ public static int Main(string[] args) var cache = NwcExport.Build(scene.Document, source.Name, length, source.LastWriteTimeUtc, native); NwcExport.Save(cache, output, native); - Console.Out.WriteLine($"Exported {cache.Meshes.Count} triangle meshes to '{output}'."); + int lines = cache.Meshes.Count(mesh => mesh.LineIndices.Count != 0); + string lineCount = lines > 0 ? $" and {lines} line meshes" : ""; + Console.Out.WriteLine($"Exported {cache.Meshes.Count - lines} triangle meshes{lineCount} to '{output}'."); return 0; } catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException or From 2a29a0281a7453cefa9df26af5f578dc740e65bd Mon Sep 17 00:00:00 2001 From: mie <79989386+mahach666@users.noreply.github.com> Date: Thu, 19 Nov 2026 21:16:47 +0300 Subject: [PATCH 038/259] Use NwcIO 0.16.0 for model lines --- Directory.Packages.props | 2 +- docs/public-api.md | 4 ++-- docs/scene.md | 2 ++ 3 files changed, 5 insertions(+), 3 deletions(-) diff --git a/Directory.Packages.props b/Directory.Packages.props index 6a7f3ca6..daaeb8b4 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -17,7 +17,7 @@ - + diff --git a/docs/public-api.md b/docs/public-api.md index f410f3e0..4a9078aa 100644 --- a/docs/public-api.md +++ b/docs/public-api.md @@ -164,9 +164,9 @@ another character is refused. With it, every text is written with the embedded f | Type | Use | |---|---| | `ElementMeshes` | `Extract(document, options)` returns the triangle meshes of the drawable model elements of an opened `RvtDocument`, from the geometry the document already holds (the file is not read again). Coordinates are in feet, in the coordinates of the document (Revit internal coordinates, Z up). | -| `ElementMeshOptions` | `UseSymbolPlacements` (default true): an element that is exactly its family symbols placed rigidly is returned as placements of shared symbol meshes; false gives every element its own triangles. | +| `ElementMeshOptions` | `UseSymbolPlacements` (default true): an element that is exactly its family symbols placed rigidly is returned as placements of shared symbol meshes; false gives every element its own triangles. `IncludeModelLinesAndReinforcement` (default false) adds straight model lines and triangulated reinforcement where decoded bar paths supply the geometry. | | `MeshSet` | `Elements` (one `ElementMesh` per drawable element, in document order), `Symbols` (symbol element id to its triangle meshes in the frame of the family, only for placed symbols) and `GeometryUndecoded` (a file of a release other than Revit 2022, read by its own class schema, opened without `RvtReaderOptions.R22Layout`: its elements are listed as `Undecoded`). | -| `ElementMesh` | `ElementId`, `Meshes` (the element's own triangles, one mesh per material), `Placements`, `Coverage` and `UntriangulatedFaces`. | +| `ElementMesh` | `ElementId`, `Meshes` (the element's own triangles, one mesh per material), `Placements`, `Coverage`, `UntriangulatedFaces` and optional `Line` endpoints in feet. | | `TriangleMesh` | `Positions` (x, y, z per vertex), `Indices` (three per triangle, counter-clockwise around the normals), `Normals` (one unit normal per vertex, flat per face: vertices are not shared between faces) and `MaterialId` (the material element id, 0 for none). | | `SymbolPlacement`, `MeshTransform`, `MeshVector` | A symbol id with its transform. `MeshTransform` maps a family point p to `Origin + BasisX * p.X + BasisY * p.Y + BasisZ * p.Z`; the basis vectors are the columns of the row-major 3x3 matrix of `GeoInstance.Transform` (`BasisX = (t[0], t[3], t[6])`, `Origin = (t[9], t[10], t[11])`, see `FromRowMajor`). A negative `Determinant` is a mirror image. | | `MeshCoverage` | `Complete`, `Partial` (some faces did not triangulate, a placed symbol or a symbol nested in one has no geometry, or a Geometry node that Revit exports has no decoded polygon), `BoxSubstitute` (a symbol placed at a rescaled placement was replaced by its box), `NoGeometry` (a geometry record with nothing to draw) and `Undecoded`. | diff --git a/docs/scene.md b/docs/scene.md index 183e177f..d8c99ed7 100644 --- a/docs/scene.md +++ b/docs/scene.md @@ -30,6 +30,8 @@ Only `Read(path)` reports the diagnostics of the read (`read-cut`, `failed-membe `unverified-members`), as only it opens the file; if you open the document yourself, read them from the `RvtReaderOptions.Diagnostics` you opened it with. +Set `RvtSceneOptions.IncludeModelLinesAndReinforcement` to include straight model lines as line primitives and reinforcement with decoded bar paths as triangles. The native RVT-to-NWC tool enables this option. + `RvtSceneResult` holds the `Document`, the `Diagnostics` and counts: elements, elements with geometry, elements by coverage, geometries, instances and symbol placements. From 5383f4a364d62cfc94612413c879380593e2aebc Mon Sep 17 00:00:00 2001 From: Mahach <79989386+mahach666@users.noreply.github.com> Date: Fri, 20 Nov 2026 01:37:35 +0300 Subject: [PATCH 039/259] Preserve room and annotation data after current-copy resolution --- CHANGELOG.md | 5 +++ src/RvtIO/Ifc/IfcExporter.cs | 15 ++++--- src/RvtIO/Parsing/ElementBuilder.cs | 5 ++- src/RvtIO/RvtFileReader.cs | 39 +++++++++++++++++-- .../RvtIO.Tests/DerivedInstanceParamsTests.cs | 11 ++++++ .../IfcExporterSpacesCurrentTests.cs | 22 +++++++++++ tests/RvtIO.Tests/OwnElementClassTests.cs | 36 +++++++++++++++++ .../RvtIO.Tests/RoomNameSerializationTests.cs | 21 ++++++++++ 8 files changed, 144 insertions(+), 10 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2b950642..27e92db7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,11 @@ API between minor releases. ### Fixed +- Read the selected project-room record by its stored boundaries when current-copy resolution leaves it outside the + sequential scan. The current IFC profile also exports placed rooms with an explicitly empty number. +- Recover text note and linear dimension types from their unique project records when the sequential scan misses them. +- Keep room separation lines from inheriting a type from another line referenced by the current copy. + - Report `element-id-range` with the offending ID if an RVT has wide element IDs and no project partition storage to read the element records. diff --git a/src/RvtIO/Ifc/IfcExporter.cs b/src/RvtIO/Ifc/IfcExporter.cs index 7a77c185..679e3e4e 100644 --- a/src/RvtIO/Ifc/IfcExporter.cs +++ b/src/RvtIO/Ifc/IfcExporter.cs @@ -68146,12 +68146,17 @@ private Dictionary WriteSpaces( storeyId = storeyBelowId; else continue; - string? number = RoomStringParam(elem, RoomNumberParam); + string? number = elem.Parameters.FirstOrDefault(p => p.Id == RoomNumberParam)?.Value as string; // A 64-bit-id file keeps the name of a room only as its ROOM_NAME parameter (no scanned // fallback name). string? longName = elem.Name ?? (_geometryUndecoded ? RoomStringParam(elem, RoomNameParam) : null); - if (string.IsNullOrEmpty(number) || string.IsNullOrEmpty(longName)) + if (number == null || string.IsNullOrEmpty(longName)) continue; + // Revit exports a placed room whose number was explicitly cleared using its name and element ID. + bool emptyNumber = number.Length == 0; + if (emptyNumber && (!CurrentProfile || elem.CategoryId != RoomCategoryId || elem.SerializedRoomIsLocationless != false)) + continue; + string spaceName = emptyNumber ? $"{longName}:{elem.ElementId.ToString(CultureInfo.InvariantCulture)}" : number; int storeyPlacementId = storeyPlacements[storeyId]; int originPointId = w.Add("IFCCARTESIANPOINT", StepWriter.List(D(0), D(0), D(0))); @@ -68227,7 +68232,7 @@ private Dictionary WriteSpaces( // exporter's IfcElevationWithFlooring is not read). string description = CurrentProfile && RoomStringParam(elem, SpaceCommentsParamId) is { } comments ? S(comments) : "$"; int spaceEntityId = w.Add("IFCSPACE", - $"{S(spaceGuid)},{R(ownerHistId)},{S(number)},{description},{(CurrentProfile ? "''" : "$")},{R(placementId)}," + $"{S(spaceGuid)},{R(ownerHistId)},{S(spaceName)},{description},{(CurrentProfile ? "''" : "$")},{R(placementId)}," + $"{(shapeId > 0 ? R(shapeId) : "$")},{S(longName)},.ELEMENT.,.INTERNAL.,{(CurrentProfile ? "0." : "$")}"); spaceEntityIdByRoomId[elem.Id] = spaceEntityId; if (writtenBoundary != null) _spaceBodyGeometry[spaceEntityId] = writtenBoundary; @@ -68238,7 +68243,7 @@ private Dictionary WriteSpaces( schemeSpaces.Add(spaceEntityId); } - string referenceText = $"{longName} {number}"; + string referenceText = emptyNumber ? longName : $"{longName} {number}"; int referenceValueId = GetOrAddPropertySingleValue( w, propertySingleValueIds, "Reference", $"IFCIDENTIFIER({S(referenceText)})"); var commonValueIds = new List { referenceValueId }; @@ -68253,7 +68258,7 @@ private Dictionary WriteSpaces( $"{S(IfcGuid.FromName($"space-common-rel:{elem.Id}"))},{R(ownerHistId)},$,$," + $"{StepWriter.List(R(spaceEntityId))},{R(psetId)}"); - string typeName = $"{longName} {number}:{elem.Id}"; + string typeName = $"{referenceText}:{elem.Id}"; string? exactSpaceTypeGuid = ResolveExactElementGlobalId( elem, _usedExportIds, InstanceAsTypeSubElementIndex, CurrentProfile); string spaceTypeGuid = exactSpaceTypeGuid ?? IfcGuid.FromName($"space-type:{elem.Id}"); diff --git a/src/RvtIO/Parsing/ElementBuilder.cs b/src/RvtIO/Parsing/ElementBuilder.cs index f530c677..1cdc8479 100644 --- a/src/RvtIO/Parsing/ElementBuilder.cs +++ b/src/RvtIO/Parsing/ElementBuilder.cs @@ -5980,8 +5980,9 @@ public static void PostProcess(RevitFileInfo rvtInfo, ParsingState? state = null && (paramTarget.CategoryId == e.CategoryId || !e.CategoryId.HasValue)) { resolved = v; break; } } - // Fallback: pick a same-category element from References - if (resolved == null && e.References != null && e.CategoryId.HasValue) + // Room separation lines reference other boundaries, but have no Revit type. + if (resolved == null && e.References != null && e.CategoryId.HasValue + && e.CategoryId != (int)BuiltIns.BuiltInCategory.OST_RoomSeparationLines) { foreach (var refId in e.References) { diff --git a/src/RvtIO/RvtFileReader.cs b/src/RvtIO/RvtFileReader.cs index b3c0c219..31d178bc 100644 --- a/src/RvtIO/RvtFileReader.cs +++ b/src/RvtIO/RvtFileReader.cs @@ -2347,7 +2347,8 @@ internal static void AddDriveCurveFromRewrittenBlock(TfBlockDeserializer.NativeP /// element in its current copy, instead of every block the stream walk meets: the walk also meets the copies of an id in the documents /// of loaded families and byte runs inside other items, and each one counted as a second root of the element. The location line of a /// wall () is read from its root record once every root is counted. - internal static void RecordFramedRoots(ParsingState state) + internal static void RecordFramedRoots(ParsingState state, + List<(byte[] Data, int Start, uint Size, ushort Class, uint Owner)>? annotationRoots = null) { var roots = new List<(byte[] Data, int Start, uint Size, ushort Class, uint Owner, int? Partition)>(); foreach (var frame in state.FramedPartitions!) @@ -2370,6 +2371,22 @@ internal static void RecordFramedRoots(ParsingState state) foreach (var (data, start, size, classId, owner, partition) in roots) { StairComponentSource.Record(state, data, start, size, classId, owner); + if (classId is 2335 or 3971) // LinearDimString and TextNote + annotationRoots?.Add((data, start, size, classId, owner)); + if (classId == 3471) + { + RecordRoomNameSource(state, data, start, size, classId, owner); + if (state.StaleCopiesRemoved && partition is int partWithRoom + && state.IncrementRoutedPartitions?.TryGetValue(owner, out int currentRoomPartition) == true + && partWithRoom == currentRoomPartition + && !state.NativeParamsFromRootClass.Contains(owner) + && TfBlockDeserializer.ExtractParams(data, start, size, classId) is { Count: > 0 } roomParams + && roomParams.Fields.TryGetValue("m_id", out int roomId) && (uint)roomId == owner) + { + state.NativeParams[owner] = roomParams; + state.NativeParamsFromRootClass.Add(owner); + } + } if (state.WideSchema == null && classId == 187 && (state.IncrementRoutedPartitions == null || partition is not int part @@ -2418,7 +2435,9 @@ internal static void RunTfStreamWalk(ParsingState state) var walkGReps = new List<(byte[] Segment, int Start, uint Size, uint Eid)>(); // the roots the class and stair sources count: the records of the project's block when every stream is read by its framing bool framedRoots = state.ReadsFramedRecords; - if (framedRoots) RecordFramedRoots(state); + List<(byte[] Data, int Start, uint Size, ushort Class, uint Owner)>? annotationRoots = + framedRoots && state.StaleCopiesRemoved ? [] : null; + if (framedRoots) RecordFramedRoots(state, annotationRoots); TfStreamWalker.Walk(state.Chunks, state.AllKnownIds, (seg, bs, ds, cls, eid) => { uint fullClassIdx = BitConverter.ToUInt32(seg, bs + 12); @@ -2459,7 +2478,7 @@ internal static void RunTfStreamWalk(ParsingState state) RecordCurtainFamilyHost(state, seg, bs, ds, cls, eid); if (cls is 3681 or 3742) RecordStairRootSource(state, seg, bs, (uint)ds, cls, eid); - if (cls == 3471) + if (!framedRoots && cls == 3471) RecordRoomNameSource(state, seg, bs, ds, cls, eid); if (cls == 2306) RecordRoomPlanSource(state, seg, bs, ds, cls, eid); @@ -2580,6 +2599,20 @@ internal static void RunTfStreamWalk(ParsingState state) // AnalyticalNodeOwners, registry category assignment. }, (seg, recordStart, eid) => ElementHeaderCategory.Record(state, seg, recordStart, eid)); + // Pruning can leave a valid annotation root where the sequential scan cannot anchor. + if (annotationRoots != null) + foreach (var (data, start, size, classId, owner) in annotationRoots) + { + if (state.NativeParamsFromRootClass.Contains(owner) + || !state.WalkedElementClassRoots.TryGetValue(owner, out var root) + || root.BlockCount != 1 || root.ClassId != classId + || TfBlockDeserializer.ExtractParams(data, start, size, classId) is not { } parameters + || NativeTypePointers.Of(classId, parameters) is not int typeId || !state.AllKnownIds.Contains((uint)typeId)) + continue; + state.NativeParams[owner] = parameters; + state.NativeParamsFromRootClass.Add(owner); + } + ApplyFirstDecodableGReps(state, walkGReps); // Second pass: geometry blocks the anchored walk missed. Family symbols live in diff --git a/tests/RvtIO.Tests/DerivedInstanceParamsTests.cs b/tests/RvtIO.Tests/DerivedInstanceParamsTests.cs index a38ed4c2..705a052d 100644 --- a/tests/RvtIO.Tests/DerivedInstanceParamsTests.cs +++ b/tests/RvtIO.Tests/DerivedInstanceParamsTests.cs @@ -7,6 +7,17 @@ namespace RvtIO.Tests; public class DerivedInstanceParamsTests { + [Fact] + public void RoomSeparationLineDoesNotUseItsNeighborAsAType() + { + var line = new Element { Id = 1, CategoryId = -2000066, TypeId = -1, References = [2] }; + var neighbor = new Element { Id = 2, CategoryId = -2000066, TypeId = -1 }; + + ElementBuilder.PostProcess(new RevitFileInfo { Elements = [line, neighbor] }); + + Assert.Equal(-1L, line.TypeElementId); + } + private static Parameter P(int id, StorageType storage, object value) => BipHelpers.MakeBipParam(id, id.ToString(), storage, value); private static object? Value(Element e, int id) => e.Parameters.FirstOrDefault(p => p.Id == id)?.Value; diff --git a/tests/RvtIO.Tests/IfcExporterSpacesCurrentTests.cs b/tests/RvtIO.Tests/IfcExporterSpacesCurrentTests.cs index 947098a3..7aaab29f 100644 --- a/tests/RvtIO.Tests/IfcExporterSpacesCurrentTests.cs +++ b/tests/RvtIO.Tests/IfcExporterSpacesCurrentTests.cs @@ -44,6 +44,28 @@ public void SpaceWithoutComments_HasAnEmptyDescription() Assert.Equal("''", Args(ifc, Ids(ifc, "IFCSPACE").Single(), "IFCSPACE")[3]); } + [Fact] + public void PlacedRoomWithAnExplicitlyEmptyNumber_UsesItsNameAndSourceId() + { + var placed = Room(100, "Vestibule", ""); + placed.SerializedRoomIsLocationless = false; + placed.NativeId = (long)int.MaxValue + 1; + var missing = Room(200, "Missing", ""); + missing.SerializedRoomIsLocationless = false; + missing.Parameters.RemoveAll(p => p.Id == -1006901); + var unverified = Room(300, "Unverified", ""); + var unplaced = Room(400, "Unplaced", ""); + unplaced.SerializedRoomIsLocationless = true; + var info = new RevitFileInfo { Elements = [Level(900), placed, missing, unverified, unplaced] }; + + string ifc = Export(info); + + Assert.Equal("'Vestibule:2147483648'", Args(ifc, Ids(ifc, "IFCSPACE").Single(), "IFCSPACE")[2]); + Assert.Single(Ids(ifc, "IFCSPACETYPE")); + Assert.Equal("'Vestibule:100'", Args(ifc, Ids(ifc, "IFCSPACETYPE").Single(), "IFCSPACETYPE")[2]); + Assert.Empty(Ids(Export(info, new IfcExporter { Profile = IfcProfile.Legacy }), "IFCSPACE")); + } + [Fact] public void Spaces_ShareTheContainmentOfTheirStorey_InFrontOfItsProducts() { diff --git a/tests/RvtIO.Tests/OwnElementClassTests.cs b/tests/RvtIO.Tests/OwnElementClassTests.cs index 0afcd5c8..c93fea8b 100644 --- a/tests/RvtIO.Tests/OwnElementClassTests.cs +++ b/tests/RvtIO.Tests/OwnElementClassTests.cs @@ -271,6 +271,42 @@ public void TheClassOfAnElementHeldOnce_DoesNotDependOnTheRemovalOfOtherCopies() Assert.Equal(new StairComponentSource.ElementClassRoot(1, 361), resolved.WalkedElementClassRoots[290112]); } + [Theory] + [InlineData(false)] + [InlineData(true)] + public void TextNoteType_UsesAnUnambiguousFramedRootWhenTheScanCannotAnchor(bool duplicate) + { + const ushort textNote = 3971; + const int style = 456; + byte[] prefix = Frame(textNote)[..^4]; + using var stream = new MemoryStream(); + using var writer = new BinaryWriter(stream); + writer.Write(prefix); + writer.Write(new byte[3 * sizeof(uint) + 13 * sizeof(double)]); // text fragments, optional pointers, and dimensions + writer.Write(style); + writer.Write(new byte[4 * sizeof(uint) + 3 + sizeof(uint)]); // flags, attachment, leaders, and extension points + var size = (uint)stream.Length - 12; + writer.Write(size); + byte[] block = stream.ToArray(); + BitConverter.GetBytes(size).CopyTo(block, 8); + + byte[] chunk = [.. block, .. new byte[16]]; + var frame = new PartitionFraming.Framed([chunk], [new(102, 123, 0, block.Length)], 4, 2); + var state = new ParsingState + { + AllKnownIds = [123, style], + ElemRecOwningElementIds = new Dictionary { [123] = -1 }, + Chunks = [chunk], + FramedPartitions = duplicate ? [frame, frame with { Partition = 3 }] : [frame], + StaleCopiesRemoved = true, + }; + + RvtFileReader.RunTfStreamWalk(state); + + if (duplicate) Assert.False(state.NativeParams.ContainsKey(123)); + else Assert.Equal(style, NativeTypePointers.Of(textNote, state.NativeParams[123])); + } + private static uint Size(byte[] bytes) => BitConverter.ToUInt32(bytes, 8); private static void Reject(byte[] bytes, ushort cls) diff --git a/tests/RvtIO.Tests/RoomNameSerializationTests.cs b/tests/RvtIO.Tests/RoomNameSerializationTests.cs index 47b997d2..8cf16cc9 100644 --- a/tests/RvtIO.Tests/RoomNameSerializationTests.cs +++ b/tests/RvtIO.Tests/RoomNameSerializationTests.cs @@ -64,6 +64,27 @@ public void Metadata_ReadsTheLocationlessFlagOfAPlacedOrUnplacedRoom(bool locati Assert.False(state.ExactRoomLocationless.ContainsKey(100)); } + [Fact] + public void CurrentRoom_UsesItsFramedRootWhenTheStreamScanCannotAnchor() + { + byte[] room = Block(circuit: 49); + byte[] chunk = [.. room, .. new byte[16]]; + var state = new ParsingState + { + AllKnownIds = [100], + Chunks = [chunk], + FramedPartitions = [new PartitionFraming.Framed([chunk], [new(102, 100, 0, room.Length)], 4, 2)], + IncrementRoutedPartitions = new Dictionary { [100] = 2 }, + StaleCopiesRemoved = true, + }; + + RvtFileReader.RunTfStreamWalk(state); + + Assert.Equal((1, "Room's own name, №2"), state.RoomNameSource[100]); + Assert.Equal(49, state.ExactRoomCircuitIds[100]); + Assert.Contains((-1006901, "1.20"), state.NativeParams[100].Strings); + } + [Fact] public void Metadata_ReadsTheCachedCircuitIdOfTheRoom() { From 3f9a0eaf28ff1e96294a66744a8b1450e5556d4e Mon Sep 17 00:00:00 2001 From: mie <79989386+mahach666@users.noreply.github.com> Date: Fri, 20 Nov 2026 01:38:05 +0300 Subject: [PATCH 040/259] Prepare RvtIO 0.6.2 release --- CHANGELOG.md | 10 +++++++++- Directory.Build.props | 2 +- docs/rvt-to-nwc.md | 4 ++-- 3 files changed, 12 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2b950642..0b5d594b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,12 +6,20 @@ API between minor releases. ## [Unreleased] -- The native RVT-to-NWC exporter keeps straight model and separation lines as NWC line segments. It also meshes cached reinforcement paths with the model's bar placements, including per-bar caches of free-form reinforcement. +## [0.6.2] - 2026-11-20 ### Added +- The native RVT-to-NWC exporter keeps straight model and separation lines as NWC line segments. It meshes + reinforcement from decoded bar paths with the model's placements, including per-bar caches of free-form reinforcement. - Preserve 64-bit Revit element IDs in project reads, source-ID lookups and exports. JSON and Scene carry wide source IDs as decimal text. +- Read nested Extensible Storage entities in project elements and loaded family documents, including files with + 32-bit element IDs. Full JSON includes the recovered entities. + +### Changed + +- The ready-to-run `RvtIO.Nwc` archives for .NET 8 and .NET 10 bundle NwcIO 0.16.0 for native line output. ### Fixed diff --git a/Directory.Build.props b/Directory.Build.props index ed8a4871..3a2519bd 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -6,7 +6,7 @@ enable true true - 0.6.1 + 0.6.2 true true snupkg diff --git a/docs/rvt-to-nwc.md b/docs/rvt-to-nwc.md index 1db2f203..658e0429 100644 --- a/docs/rvt-to-nwc.md +++ b/docs/rvt-to-nwc.md @@ -10,8 +10,8 @@ Install the .NET runtime that matches the archive and run the command from the e dotnet RvtIO.Nwc.dll model.rvt model.nwc --native ``` -This mode writes placed triangle geometry, face normals, diffuse colours, the element tree, IFC GlobalIds -and Revit property display text. The cache uses feet internally. It opens in NwcIO and was validated in +This mode writes placed triangles, straight model and separation lines, face normals, diffuse colours, the element tree, +IFC GlobalIds and Revit property display text. It also writes reinforcement meshes from decoded bar paths. The cache uses feet internally. It opens in NwcIO and was validated in Navisworks Manage 2027. Export uses managed .NET code on Windows and Linux. ## Autodesk Navisworks From dea481943573b2649e577b4f112bbb1ff6365321 Mon Sep 17 00:00:00 2001 From: mie <79989386+mahach666@users.noreply.github.com> Date: Fri, 20 Nov 2026 03:02:33 +0300 Subject: [PATCH 041/259] Preserve stair containers in native NWC exports --- src/RvtIO.Scene/RvtSceneReader.cs | 9 ++++ src/RvtIO/Meshes/ElementMeshes.cs | 18 +++++++- src/RvtIO/Meshes/MeshSet.cs | 3 ++ .../NwcSupplementalGeometryTests.cs | 41 +++++++++++++++++++ tools/RvtIO.Nwc/NwcExport.cs | 9 ++++ 5 files changed, 79 insertions(+), 1 deletion(-) diff --git a/src/RvtIO.Scene/RvtSceneReader.cs b/src/RvtIO.Scene/RvtSceneReader.cs index 4ab8b628..db812fbc 100644 --- a/src/RvtIO.Scene/RvtSceneReader.cs +++ b/src/RvtIO.Scene/RvtSceneReader.cs @@ -225,6 +225,15 @@ private static RvtSceneResult Map(RvtDocument document, MeshSet meshes, string m coverage[mesh.Coverage] = coverage.GetValueOrDefault(mesh.Coverage) + 1; if (CoverageDiagnostic(mesh, sceneElement.SourceId) is { } diagnostic) report.Add(diagnostic); } + Dictionary? sceneElements = null; + foreach (var mesh in meshes.Elements) + { + if (mesh.ComponentIds.Count == 0) continue; + sceneElements ??= scene.Elements.ToDictionary(element => element.Id); + foreach (int component in mesh.ComponentIds) + if (sceneElements.TryGetValue(component, out var element)) + element.ParentId = mesh.ElementId; + } if (withoutUniqueId > 0) report.Add(new(SceneSeverity.Warning, "no-source-id", $"{withoutUniqueId} elements have no Revit UniqueId: their SourceId is empty and they cannot be identified outside this scene.")); diff --git a/src/RvtIO/Meshes/ElementMeshes.cs b/src/RvtIO/Meshes/ElementMeshes.cs index f0de7671..ce4de3de 100644 --- a/src/RvtIO/Meshes/ElementMeshes.cs +++ b/src/RvtIO/Meshes/ElementMeshes.cs @@ -108,6 +108,16 @@ int MaterialOf(GeoFace face) var elements = new List(); foreach (var (element, body) in drawable) { + if (options.IncludeModelLinesAndReinforcement && IsStairContainer(element, body, drawableIds)) + { + elements.Add(new ElementMesh + { + ElementId = element.Id, + ComponentIds = body!.ExactMappedInstances!.Select(instance => instance.SymbolId).Distinct().ToArray(), + Coverage = MeshCoverage.Complete, + }); + continue; + } if (body == null) { var line = options.IncludeModelLinesAndReinforcement ? ModelLine(element) : null; @@ -199,9 +209,15 @@ private static bool DropsUntakenNodes(IReadOnlyList faces, bool hasGhos // A stair places its runs and landings, a model group its members: those are drawn as elements of their own. var ids = drawable.Select(item => item.Item1.Id).ToHashSet(); return drawable.Where(item => item.Item2?.ExactMappedInstances is not { Count: > 0 } mapped - || !mapped.All(instance => ids.Contains(instance.SymbolId))).ToList(); + || !mapped.All(instance => ids.Contains(instance.SymbolId)) + || includeModelLinesAndReinforcement && IsStairContainer(item.Item1, item.Item2, ids)).ToList(); } + private static bool IsStairContainer(Element element, GeometryData? body, HashSet drawableIds) => + element.CategoryId == (int)BuiltInCategory.OST_Stairs && element.RootClassIs("StairsElement") + && body?.ExactMappedInstances is { Count: > 0 } mapped + && mapped.All(instance => instance.SymbolId != element.Id && drawableIds.Contains(instance.SymbolId)); + private static (MeshVector Start, MeshVector End)? ModelLine(Element element) { if (element.CategoryId is not ((int)BuiltInCategory.OST_Lines or (int)BuiltInCategory.OST_RoomSeparationLines diff --git a/src/RvtIO/Meshes/MeshSet.cs b/src/RvtIO/Meshes/MeshSet.cs index e49378d7..c8abdca6 100644 --- a/src/RvtIO/Meshes/MeshSet.cs +++ b/src/RvtIO/Meshes/MeshSet.cs @@ -30,6 +30,9 @@ public sealed class ElementMesh /// is given only when the element's geometry is exactly its symbols placed rigidly; any other element has its own triangles. public IReadOnlyList Placements { get; init; } = []; + /// Drawable component IDs that make up all the geometry of this container. + public IReadOnlyList ComponentIds { get; init; } = []; + /// The endpoints of a straight model line in document coordinates (feet), if present. public (MeshVector Start, MeshVector End)? Line { get; init; } diff --git a/tests/RvtIO.Tests/NwcSupplementalGeometryTests.cs b/tests/RvtIO.Tests/NwcSupplementalGeometryTests.cs index 12462aaf..9042997b 100644 --- a/tests/RvtIO.Tests/NwcSupplementalGeometryTests.cs +++ b/tests/RvtIO.Tests/NwcSupplementalGeometryTests.cs @@ -37,6 +37,47 @@ public void NativeSceneIncludesModelLineAndReinforcementButSkipsDetailAndSketchC Assert.NotEmpty(Assert.Single(native.Meshes, m => m.TriangleCount > 0).Indices); } + [Fact] + public void NativeExportKeepsTheStairIdAboveItsAlreadyDrawnComponents() + { + var triangle = new GeoFace + { + OuterVertices = [[0, 0, 0], [1, 0, 0], [1, 1, 0]], + Normal = [0, 0, 1], + GeometryNode = 1, + }; + var run = Product(1, BuiltInCategory.OST_StairsRuns, "StairsRun", new() { Faces = [triangle] }); + var stair = Product(2, BuiltInCategory.OST_Stairs, "StairsElement", new() + { + Faces = [triangle], + ExactMappedInstances = [new() { SymbolId = run.Id, Transform = [1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0] }], + }); + var document = RvtDocument.FromInfo(new RevitFileInfo { Elements = [run, stair] }); + + Assert.Equal(run.Id, Assert.Single(RvtSceneReader.Read(document, new() { ModelKey = "model" }).Document.Elements).Id); + var scene = RvtSceneReader.Read(document, new() { ModelKey = "model", IncludeModelLinesAndReinforcement = true }).Document; + Assert.Equal(stair.Id, scene.Elements.Single(e => e.Id == run.Id).ParentId); + Assert.Single(scene.Instances); + var native = Nwc.NwcExport.Build(scene, "model.rvt", 0, DateTime.UnixEpoch, native: true); + var parent = Assert.Single(native.RootNode!.Children); + var child = Assert.Single(parent.Children); + Assert.Contains(parent.Properties, property => property.Name == "Element ID" && property.Value == "2"); + Assert.Contains(child.Properties, property => property.Name == "Element ID" && property.Value == "1"); + Assert.Same(child, Assert.Single(native.Meshes).Node); + + static Element Product(int id, BuiltInCategory category, string className, GeometryData geometry) => new() + { + Id = id, + CategoryId = (int)category, + Category = category.ToString(), + NativeRootClassName = className, + NativeRootClassChain = [className], + Geometry = geometry, + SerializedCreatedPhaseId = 3, + Parameters = [new() { Id = -1012100, Value = 3 }], + }; + } + [Fact] public void SweepKeepsTheStoredRadiusAndExtentsOfAStraightBar() { diff --git a/tools/RvtIO.Nwc/NwcExport.cs b/tools/RvtIO.Nwc/NwcExport.cs index e637834a..226fad19 100644 --- a/tools/RvtIO.Nwc/NwcExport.cs +++ b/tools/RvtIO.Nwc/NwcExport.cs @@ -57,6 +57,15 @@ internal static NwcDocument Build(SceneDocument scene, string sourceName, long s AddText(node, $"Revit {set.Name} Property", property.Name, property.Value.Text); } } + if (native) + foreach (var element in scene.Elements) + if (element.ParentId is long parentId) + { + var node = nodes[element.Id]; + node.Parent!.Children.Remove(node); + node.Parent = nodes[parentId]; + node.Parent.Children.Add(node); + } var geometries = scene.Geometries.ToDictionary(geometry => geometry.Id); var materials = native From 428dac6e425b190a63928abffc465891dd293d28 Mon Sep 17 00:00:00 2001 From: mie <79989386+mahach666@users.noreply.github.com> Date: Fri, 20 Nov 2026 03:30:47 +0300 Subject: [PATCH 042/259] Export native circular Revit model lines to NWC --- src/RvtIO.Scene/RvtSceneReader.cs | 19 +++++- src/RvtIO/Internal/ParsingState.cs | 2 +- src/RvtIO/Meshes/ElementMeshes.cs | 24 +++++-- src/RvtIO/Meshes/MeshSet.cs | 3 + src/RvtIO/Model/Element.cs | 3 + src/RvtIO/Model/GridAxis.cs | 8 ++- src/RvtIO/Parsing/ElementBuilder.cs | 1 + src/RvtIO/Parsing/TfBlockDeserializer.cs | 63 +++++++++++++++++-- .../NwcSupplementalGeometryTests.cs | 41 ++++++++++++ 9 files changed, 149 insertions(+), 15 deletions(-) diff --git a/src/RvtIO.Scene/RvtSceneReader.cs b/src/RvtIO.Scene/RvtSceneReader.cs index db812fbc..3dd6b29e 100644 --- a/src/RvtIO.Scene/RvtSceneReader.cs +++ b/src/RvtIO.Scene/RvtSceneReader.cs @@ -172,7 +172,7 @@ private static RvtSceneResult Map(RvtDocument document, MeshSet meshes, string m SourceId = element?.UniqueId, IfcGuid = element != null ? IfcGuidOf(element) : null, Kind = SceneNodeKind.Element, - Name = mesh.Line != null && string.IsNullOrWhiteSpace(element?.Name) ? "Model Lines" : element?.Name ?? string.Empty, + Name = (mesh.Line != null || mesh.Arc != null) && string.IsNullOrWhiteSpace(element?.Name) ? "Model Lines" : element?.Name ?? string.Empty, Category = CategoryName(element), TypeName = element != null ? document.GetTypeElement(element)?.Name ?? string.Empty : string.Empty, }; @@ -202,6 +202,23 @@ private static RvtSceneResult Map(RvtDocument document, MeshSet meshes, string m }); scene.Instances.Add(new SceneInstance { ElementId = mesh.ElementId, GeometryId = geometryId, Transform = Transform3d.Translate(start) }); } + if (mesh.Arc is { } arc) + { + var start = Vector(arc[0]) * MetresPerFoot; + var vertices = arc.Select(point => Vector(point) * MetresPerFoot - start).ToArray(); + int[] indices = new int[2 * (vertices.Length - 1)]; + for (int i = 0; i < vertices.Length - 1; i++) + { + indices[2 * i] = i; + indices[2 * i + 1] = i + 1; + } + int geometryId = scene.Geometries.Count + 1; + scene.Geometries.Add(new SceneGeometry + { + Id = geometryId, Topology = SceneTopology.Lines, Vertices = vertices, Indices = indices, + }); + scene.Instances.Add(new SceneInstance { ElementId = mesh.ElementId, GeometryId = geometryId, Transform = Transform3d.Translate(start) }); + } foreach (var placement in mesh.Placements) { placements++; diff --git a/src/RvtIO/Internal/ParsingState.cs b/src/RvtIO/Internal/ParsingState.cs index a6ef9a3d..580d358e 100644 --- a/src/RvtIO/Internal/ParsingState.cs +++ b/src/RvtIO/Internal/ParsingState.cs @@ -405,7 +405,7 @@ public TfBlockDeserializer.UnitsElemOptions? OwnDocumentUnitOptions /// Curve line style + length from the full CurveElem schema walk (handles /// detail arcs the GInfoBlob pattern scan can't reach). - public Dictionary CurveGeometry { get; set; } = new(); + public Dictionary CurveGeometry { get; set; } = new(); /// Native parameter stores per element, deserialized from the Element base /// class m_pParamValueSet* containers (schema-driven). diff --git a/src/RvtIO/Meshes/ElementMeshes.cs b/src/RvtIO/Meshes/ElementMeshes.cs index ce4de3de..f9f9f86d 100644 --- a/src/RvtIO/Meshes/ElementMeshes.cs +++ b/src/RvtIO/Meshes/ElementMeshes.cs @@ -36,6 +36,7 @@ public static class ElementMeshes private const int RevealsCategoryId = -2000182; private const int WallsCategoryId = -2000011; private const double RigidTolerance = 1e-6; + private const double ArcChordErrorFeet = 0.001 / 0.3048; /// The meshes of the drawable elements of . /// is null. @@ -120,14 +121,18 @@ int MaterialOf(GeoFace face) } if (body == null) { - var line = options.IncludeModelLinesAndReinforcement ? ModelLine(element) : null; + var curve = options.IncludeModelLinesAndReinforcement ? ModelCurve(element) : null; + var line = ModelLine(curve); + var arc = curve is { CurveType: "Arc" } && GridAxis.Tessellate([curve], ArcChordErrorFeet) is { } samples + ? samples.Select(p => new MeshVector(p[0], p[1], p[2])).ToArray() : null; var rebar = options.IncludeModelLinesAndReinforcement && element.RebarBars is { } bars ? ReinforcementMeshes.Build(bars) : null; elements.Add(new ElementMesh { ElementId = element.Id, Line = line, + Arc = arc, Meshes = rebar == null ? [] : [rebar], - Coverage = line != null || rebar != null ? MeshCoverage.Complete + Coverage = line != null || arc != null || rebar != null ? MeshCoverage.Complete : info.WideLayoutNotRewritten ? MeshCoverage.Undecoded : MeshCoverage.NoGeometry, }); continue; @@ -189,7 +194,8 @@ private static bool DropsUntakenNodes(IReadOnlyList faces, bool hasGhos var drawable = new List<(Element, GeometryData?)>(); foreach (var element in info.Elements) { - bool modelLine = includeModelLinesAndReinforcement && ModelLine(element) != null; + var curve = includeModelLinesAndReinforcement ? ModelCurve(element) : null; + bool modelLine = curve?.CurveType == "Arc" || ModelLine(curve) != null; bool rebar = includeModelLinesAndReinforcement && element.RebarBars is { Bars.Count: > 0 } or { Items.Count: > 0 }; if (element.IsBlockOnly || element.IsGroupTemplate || designOptions.InNonPrimaryOption(element) == true || phaseFilter?.Excludes(element) == true @@ -218,13 +224,19 @@ private static bool IsStairContainer(Element element, GeometryData? body, HashSe && body?.ExactMappedInstances is { Count: > 0 } mapped && mapped.All(instance => instance.SymbolId != element.Id && drawableIds.Contains(instance.SymbolId)); - private static (MeshVector Start, MeshVector End)? ModelLine(Element element) + private static LocationCurve? ModelCurve(Element element) { if (element.CategoryId is not ((int)BuiltInCategory.OST_Lines or (int)BuiltInCategory.OST_RoomSeparationLines or (int)BuiltInCategory.OST_MEPSpaceSeparationLines) || element.OwnerViewId != null || !element.RootClassIs("CurveElem") - || !element.Parameters.Any(p => p.Id == (int)BuiltInParameter.CURVE_IS_DETAIL && p.Value is 0) - || element.Location is not { CurveType: "Line" } line + || !element.Parameters.Any(p => p.Id == (int)BuiltInParameter.CURVE_IS_DETAIL && p.Value is 0)) + return null; + return element.NativeModelArc ?? (element.Location is { CurveType: "Line" } line ? line : null); + } + + private static (MeshVector Start, MeshVector End)? ModelLine(LocationCurve? curve) + { + if (curve is not { CurveType: "Line" } line || line.StartPoint is not [var x0, var y0, var z0] || line.EndPoint is not [var x1, var y1, var z1]) return null; var start = new Pt3(x0, y0, z0); diff --git a/src/RvtIO/Meshes/MeshSet.cs b/src/RvtIO/Meshes/MeshSet.cs index c8abdca6..eb3b745a 100644 --- a/src/RvtIO/Meshes/MeshSet.cs +++ b/src/RvtIO/Meshes/MeshSet.cs @@ -36,6 +36,9 @@ public sealed class ElementMesh /// The endpoints of a straight model line in document coordinates (feet), if present. public (MeshVector Start, MeshVector End)? Line { get; init; } + /// The points of a tessellated model arc in document coordinates (feet), if present. + public IReadOnlyList? Arc { get; init; } + /// How completely and represent the element. public MeshCoverage Coverage { get; init; } diff --git a/src/RvtIO/Model/Element.cs b/src/RvtIO/Model/Element.cs index d9cdfed3..d9272094 100644 --- a/src/RvtIO/Model/Element.cs +++ b/src/RvtIO/Model/Element.cs @@ -83,6 +83,9 @@ public class Element [JsonIgnore] internal (double StartZ, double EndZ)? CurveDriverLineZ { get; set; } + /// The circular drive curve owned by this curve element, in internal coordinates. + internal LocationCurve? NativeModelArc { get; set; } + /// Unit direction of the straight drive curve (CurveDriver.m_pCrv GLine dirVec); absent for an arc driver. [JsonIgnore] internal (double X, double Y, double Z)? CurveDriverLineDirection { get; set; } diff --git a/src/RvtIO/Model/GridAxis.cs b/src/RvtIO/Model/GridAxis.cs index 41ab8b23..a430c2bd 100644 --- a/src/RvtIO/Model/GridAxis.cs +++ b/src/RvtIO/Model/GridAxis.cs @@ -19,13 +19,15 @@ internal GridAxis(int id, string name, LocationCurve[] segments) /// Samples the axis as an ordered polyline in feet, with the requested maximum arc-to-chord error. /// Returns null if the tolerance would require more than 65,536 vertices or the curve is incomplete. - public List? Tessellate(double maxErrorFeet) + public List? Tessellate(double maxErrorFeet) => Tessellate(Segments, maxErrorFeet); + + internal static List? Tessellate(IReadOnlyList segments, double maxErrorFeet) { if (!double.IsFinite(maxErrorFeet) || maxErrorFeet <= 0) throw new ArgumentOutOfRangeException(nameof(maxErrorFeet)); const int MaxVertices = 65_536; - var points = new List { Segments[0].StartPoint }; - foreach (var curve in Segments) + var points = new List { segments[0].StartPoint }; + foreach (var curve in segments) { if (curve.CurveType == "Arc") { diff --git a/src/RvtIO/Parsing/ElementBuilder.cs b/src/RvtIO/Parsing/ElementBuilder.cs index 1cdc8479..74d9a5fe 100644 --- a/src/RvtIO/Parsing/ElementBuilder.cs +++ b/src/RvtIO/Parsing/ElementBuilder.cs @@ -1317,6 +1317,7 @@ private static void AttachSketchCurve(Element elem, uint id, ParsingState state) { if (elem.Location == null && state.SketchCurves.TryGetValue(id, out var lc)) elem.Location = lc; + elem.NativeModelArc ??= state.CurveGeometry.GetValueOrDefault(id).Arc; } /// diff --git a/src/RvtIO/Parsing/TfBlockDeserializer.cs b/src/RvtIO/Parsing/TfBlockDeserializer.cs index d318e7f2..b22f2271 100644 --- a/src/RvtIO/Parsing/TfBlockDeserializer.cs +++ b/src/RvtIO/Parsing/TfBlockDeserializer.cs @@ -3867,7 +3867,7 @@ bool TryOrientation(bool reverseFirst, out List ordered) /// return the curve's line style (BUILDING_CURVE_GSTYLE) and length (CURVE_ELEM_LENGTH). /// Detail arcs store geometry as deferred GArc/GLine/GEllipse objects the pattern scan /// couldn't reach; the full schema walk with rules R1-R7 recovers them. - public static (int GStyle, double Length)? ExtractCurveGeometry(byte[] d, int blockStart, uint dataSize) + public static (int GStyle, double Length, Model.LocationCurve? Arc)? ExtractCurveGeometry(byte[] d, int blockStart, uint dataSize) { var fields = SerializationFields(0x346); if (fields == null) return null; @@ -3878,9 +3878,17 @@ public static (int GStyle, double Length)? ExtractCurveGeometry(byte[] d, int bl var cur = new Cursor { D = d, Pos = payloadStart, End = payloadEnd - 4, Curves = new() }; var queue = new List<(ushort Cls, uint Id)>(); + int driver = -1, driveArc = -1; + Model.LocationCurve? arc = null; try { - foreach (var f in fields) ReadField(cur, f, queue, 0, null); + foreach (var f in fields) + { + int before = queue.Count; + ReadField(cur, f, queue, 0, null); + if (f.Declaring == 838 && f.Name == "m_pCurveDriver" && queue.Count == before + 1 && queue[before].Cls == 929) + driver = before; + } // Process the FULL deferred queue (not just param stores), capturing each // GArc/GLine/GEllipse object's geometry. for (int i = 0; i < queue.Count; i++) @@ -3900,7 +3908,24 @@ public static (int GStyle, double Length)? ExtractCurveGeometry(byte[] d, int bl if (qf == null) throw Fail; bool isCurve = cls is 0x7B6 or 0x7DA or 0x6C8; if (isCurve) { cur.Ep0 = cur.Ep1 = cur.Radius = cur.XLen = cur.YLen = 0; } - foreach (var sf in qf) ReadField(cur, sf, queue, 1, null); + double[]? center = null, x = null, y = null; + foreach (var sf in qf) + { + int before = queue.Count, pos = cur.Pos; + ReadField(cur, sf, queue, 1, null); + if (i == driver && sf.Declaring == 87 && sf.Name == "m_pCrv" && queue.Count == before + 1 && queue[before].Cls == 1974) + driveArc = before; + if (i != driveArc || sf.Declaring != 1974 || cur.Pos - pos != 24) continue; + double[] Vector() => [BitConverter.ToDouble(d, pos), BitConverter.ToDouble(d, pos + 8), BitConverter.ToDouble(d, pos + 16)]; + switch (sf.Name) + { + case "m_center": center = Vector(); break; + case "m_xVec": x = Vector(); break; + case "m_yVec": y = Vector(); break; + } + } + if (i == driveArc && center != null && x != null && y != null) + arc = CreateCurveElementArc(center, x, y, cur.Radius, cur.Ep0, cur.Ep1); if (isCurve) cur.Curves!.Add((cls, cur.Ep0, cur.Ep1, cur.Radius, cur.XLen, cur.YLen)); } @@ -3944,7 +3969,37 @@ public static (int GStyle, double Length)? ExtractCurveGeometry(byte[] d, int bl int gs = cur.GStyle == int.MinValue ? -1 : cur.GStyle; if (gs < 0 && length == null) return null; - return (gs, length ?? 0); + return (gs, length ?? 0, arc); + } + + private static Model.LocationCurve? CreateCurveElementArc(double[] center, double[] x, double[] y, double radius, double start, double end) + { + if (!center.Concat(x).Concat(y).All(double.IsFinite) || !(radius > 0 && double.IsFinite(radius)) + || !double.IsFinite(start) || !double.IsFinite(end)) return null; + const double tolerance = 1e-8; + static double Dot(double[] a, double[] b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; + if (Math.Abs(Dot(x, x) - 1) > tolerance || Math.Abs(Dot(y, y) - 1) > tolerance || Math.Abs(Dot(x, y)) > tolerance) + return null; + if (Math.Abs(end - start) < 1e-12) end = start + 2 * Math.PI; + double sweep = Math.Abs(end - start); + double length = sweep * radius; + if (!(sweep > 0 && sweep <= 2 * Math.PI + tolerance && double.IsFinite(length))) return null; + var first = Model.GridAxis.PointOnArc(center, radius, x, y, start); + var last = Model.GridAxis.PointOnArc(center, radius, x, y, end); + if (!first.Concat(last).All(double.IsFinite)) return null; + return new Model.LocationCurve + { + CurveType = "Arc", + StartPoint = first, + EndPoint = last, + Length = length, + ArcCenter = center, + ArcRadius = radius, + ArcXDirection = x, + ArcYDirection = y, + ArcStartParameter = start, + ArcEndParameter = end, + }; } /// Decode the two coordinate representations stored by a BasePoint block. diff --git a/tests/RvtIO.Tests/NwcSupplementalGeometryTests.cs b/tests/RvtIO.Tests/NwcSupplementalGeometryTests.cs index 9042997b..5a00bbfa 100644 --- a/tests/RvtIO.Tests/NwcSupplementalGeometryTests.cs +++ b/tests/RvtIO.Tests/NwcSupplementalGeometryTests.cs @@ -78,6 +78,47 @@ public void NativeExportKeepsTheStairIdAboveItsAlreadyDrawnComponents() }; } + [Fact] + public void NativeModelArcKeepsItsPlaneAndTessellatesTheCircularPath() + { + var arc = Line(1, BuiltInCategory.OST_Lines, detail: false); + arc.Location = null; + arc.NativeModelArc = new() + { + CurveType = "Arc", + ArcCenter = [3, 5, 7], + ArcRadius = 2, + ArcXDirection = [0, 1, 0], + ArcYDirection = [0, 0, 1], + ArcStartParameter = 0, + ArcEndParameter = Math.PI / 2, + StartPoint = [3, 7, 7], + EndPoint = [3, 5, 9], + Length = Math.PI, + }; + var document = RvtDocument.FromInfo(new RevitFileInfo { Elements = [arc] }); + Assert.Empty(RvtSceneReader.Read(document, new() { ModelKey = "model" }).Document.Elements); + var scene = RvtSceneReader.Read(document, new() { ModelKey = "model", IncludeModelLinesAndReinforcement = true }).Document; + var instance = Assert.Single(scene.Instances); + var geometry = Assert.Single(scene.Geometries); + Assert.Equal(SceneTopology.Lines, geometry.Topology); + Assert.True(geometry.Vertices.Count > 2); + var points = geometry.Vertices.Select(point => instance.Transform!.Value.Apply(point)).ToArray(); + Assert.Equal(new Vector3d(3 * 0.3048, 7 * 0.3048, 7 * 0.3048), points[0]); + Assert.Equal(new Vector3d(3 * 0.3048, 5 * 0.3048, 9 * 0.3048), points[^1]); + Assert.All(points, point => Assert.Equal(3 * 0.3048, point.X, 12)); + for (int i = 0; i < points.Length - 1; i++) + { + Assert.Equal(i, geometry.Indices[2 * i]); + Assert.Equal(i + 1, geometry.Indices[2 * i + 1]); + var midpoint = (points[i] + points[i + 1]) * 0.5; + double radius = Math.Sqrt(Math.Pow(midpoint.Y - 5 * 0.3048, 2) + Math.Pow(midpoint.Z - 7 * 0.3048, 2)); + Assert.InRange(2 * 0.3048 - radius, 0, 0.001); + } + var native = Nwc.NwcExport.Build(scene, "model.rvt", 0, DateTime.UnixEpoch, native: true); + Assert.Equal(geometry.Indices, Assert.Single(native.Meshes).LineIndices); + } + [Fact] public void SweepKeepsTheStoredRadiusAndExtentsOfAStraightBar() { From 58020211fc60012310c3cd4a5f8efae1a3f82b14 Mon Sep 17 00:00:00 2001 From: mie <79989386+mahach666@users.noreply.github.com> Date: Fri, 20 Nov 2026 03:36:32 +0300 Subject: [PATCH 043/259] Keep native NWC selection geometry for area reinforcement --- src/RvtIO.Scene/RvtSceneReader.cs | 12 ++++++ src/RvtIO/Meshes/ElementMeshes.cs | 39 +++++++++++++++++-- src/RvtIO/Meshes/MeshSet.cs | 3 ++ .../NwcSupplementalGeometryTests.cs | 29 ++++++++++++++ 4 files changed, 79 insertions(+), 4 deletions(-) diff --git a/src/RvtIO.Scene/RvtSceneReader.cs b/src/RvtIO.Scene/RvtSceneReader.cs index 3dd6b29e..a8cea305 100644 --- a/src/RvtIO.Scene/RvtSceneReader.cs +++ b/src/RvtIO.Scene/RvtSceneReader.cs @@ -219,6 +219,18 @@ private static RvtSceneResult Map(RvtDocument document, MeshSet meshes, string m }); scene.Instances.Add(new SceneInstance { ElementId = mesh.ElementId, GeometryId = geometryId, Transform = Transform3d.Translate(start) }); } + if (mesh.LinePairs is { } pairs) + { + var origin = Vector(pairs[0]) * MetresPerFoot; + int geometryId = scene.Geometries.Count + 1; + scene.Geometries.Add(new SceneGeometry + { + Id = geometryId, Topology = SceneTopology.Lines, + Vertices = pairs.Select(point => Vector(point) * MetresPerFoot - origin).ToArray(), + Indices = Enumerable.Range(0, pairs.Count).ToArray(), + }); + scene.Instances.Add(new SceneInstance { ElementId = mesh.ElementId, GeometryId = geometryId, Transform = Transform3d.Translate(origin) }); + } foreach (var placement in mesh.Placements) { placements++; diff --git a/src/RvtIO/Meshes/ElementMeshes.cs b/src/RvtIO/Meshes/ElementMeshes.cs index f9f9f86d..f9e650ed 100644 --- a/src/RvtIO/Meshes/ElementMeshes.cs +++ b/src/RvtIO/Meshes/ElementMeshes.cs @@ -125,14 +125,17 @@ int MaterialOf(GeoFace face) var line = ModelLine(curve); var arc = curve is { CurveType: "Arc" } && GridAxis.Tessellate([curve], ArcChordErrorFeet) is { } samples ? samples.Select(p => new MeshVector(p[0], p[1], p[2])).ToArray() : null; + var linePairs = options.IncludeModelLinesAndReinforcement && AreaReinforcementBounds(element) is { } bounds + ? BoxEdges(bounds) : null; var rebar = options.IncludeModelLinesAndReinforcement && element.RebarBars is { } bars ? ReinforcementMeshes.Build(bars) : null; elements.Add(new ElementMesh { ElementId = element.Id, Line = line, Arc = arc, + LinePairs = linePairs, Meshes = rebar == null ? [] : [rebar], - Coverage = line != null || arc != null || rebar != null ? MeshCoverage.Complete + Coverage = line != null || arc != null || linePairs != null || rebar != null ? MeshCoverage.Complete : info.WideLayoutNotRewritten ? MeshCoverage.Undecoded : MeshCoverage.NoGeometry, }); continue; @@ -196,6 +199,7 @@ private static bool DropsUntakenNodes(IReadOnlyList faces, bool hasGhos { var curve = includeModelLinesAndReinforcement ? ModelCurve(element) : null; bool modelLine = curve?.CurveType == "Arc" || ModelLine(curve) != null; + bool areaReinforcement = includeModelLinesAndReinforcement && AreaReinforcementBounds(element) != null; bool rebar = includeModelLinesAndReinforcement && element.RebarBars is { Bars.Count: > 0 } or { Items.Count: > 0 }; if (element.IsBlockOnly || element.IsGroupTemplate || designOptions.InNonPrimaryOption(element) == true || phaseFilter?.Excludes(element) == true @@ -203,14 +207,16 @@ private static bool DropsUntakenNodes(IReadOnlyList faces, bool hasGhos || ProductRules.IsValidatedStackedWallContainer(element, elementsById) || info.ElemTableIsExact && element.IsDiscovered || element.SerializedFamilyId is > 0 - || (!modelLine && ProductRules.IsNonPhysicalCategory(element.Category))) + || (!modelLine && !areaReinforcement && ProductRules.IsNonPhysicalCategory(element.Category))) continue; bool namesPhase = ProductRules.HasProjectPhaseReference(element) || ProductRules.IsTransformOnlyFamily(element); - if (!namesPhase && !modelLine && !rebar && (typeElementIds.Contains(element.Id) || element.CategoryId != WallsCategoryId)) continue; + if (!namesPhase && !modelLine && !rebar && !areaReinforcement + && (typeElementIds.Contains(element.Id) || element.CategoryId != WallsCategoryId)) continue; GeometryData? body = element.Geometry; if (element.SerializedComputedSymbolGeometry is { } computed) body = computed; else if (ProductRules.HasOnlyUnfilledFaces(element)) continue; - if (body != null || modelLine || rebar || info.WideLayoutNotRewritten && element.BoundingBox != null) drawable.Add((element, body)); + if (body != null || modelLine || rebar || areaReinforcement || info.WideLayoutNotRewritten && element.BoundingBox != null) + drawable.Add((element, body)); } // A stair places its runs and landings, a model group its members: those are drawn as elements of their own. var ids = drawable.Select(item => item.Item1.Id).ToHashSet(); @@ -234,6 +240,31 @@ private static bool IsStairContainer(Element element, GeometryData? body, HashSe return element.NativeModelArc ?? (element.Location is { CurveType: "Line" } line ? line : null); } + private static double[]? AreaReinforcementBounds(Element element) => + element.CategoryId == (int)BuiltInCategory.OST_AreaRein && element.RootClassIs("RebarSystem") + && element.BoundingBox is [var x0, var y0, var z0, var x1, var y1, var z1] bounds + && bounds.All(double.IsFinite) && x0 < x1 && y0 < y1 && z0 < z1 + ? bounds : null; + + private static MeshVector[] BoxEdges(double[] bounds) + { + // An area's exported selection graphics are the twelve edges of its stored model bounds. + var endpoints = new MeshVector[24]; + int at = 0; + for (int corner = 0; corner < 8; corner++) + for (int axis = 0; axis < 3; axis++) + { + int bit = 1 << axis; + if ((corner & bit) != 0) continue; + endpoints[at++] = Vertex(corner); + endpoints[at++] = Vertex(corner | bit); + } + return endpoints; + + MeshVector Vertex(int corner) => new(bounds[(corner & 1) == 0 ? 0 : 3], + bounds[(corner & 2) == 0 ? 1 : 4], bounds[(corner & 4) == 0 ? 2 : 5]); + } + private static (MeshVector Start, MeshVector End)? ModelLine(LocationCurve? curve) { if (curve is not { CurveType: "Line" } line diff --git a/src/RvtIO/Meshes/MeshSet.cs b/src/RvtIO/Meshes/MeshSet.cs index eb3b745a..ac40c3df 100644 --- a/src/RvtIO/Meshes/MeshSet.cs +++ b/src/RvtIO/Meshes/MeshSet.cs @@ -39,6 +39,9 @@ public sealed class ElementMesh /// The points of a tessellated model arc in document coordinates (feet), if present. public IReadOnlyList? Arc { get; init; } + /// Independent line segments listed as consecutive endpoint pairs, in document feet. + public IReadOnlyList? LinePairs { get; init; } + /// How completely and represent the element. public MeshCoverage Coverage { get; init; } diff --git a/tests/RvtIO.Tests/NwcSupplementalGeometryTests.cs b/tests/RvtIO.Tests/NwcSupplementalGeometryTests.cs index 5a00bbfa..bdc95f2d 100644 --- a/tests/RvtIO.Tests/NwcSupplementalGeometryTests.cs +++ b/tests/RvtIO.Tests/NwcSupplementalGeometryTests.cs @@ -119,6 +119,35 @@ public void NativeModelArcKeepsItsPlaneAndTessellatesTheCircularPath() Assert.Equal(geometry.Indices, Assert.Single(native.Meshes).LineIndices); } + [Fact] + public void NativeAreaReinforcementKeepsTheTwelveEdgesOfItsStoredBounds() + { + var area = new Element + { + Id = 1, + CategoryId = (int)BuiltInCategory.OST_AreaRein, + Category = nameof(BuiltInCategory.OST_AreaRein), + NativeRootClassName = "RebarSystem", + NativeRootClassChain = ["RebarSystem"], + BoundingBox = [1, 2, 3, 4, 5, 6], + }; + var document = RvtDocument.FromInfo(new RevitFileInfo { Elements = [area] }); + Assert.Empty(RvtSceneReader.Read(document, new() { ModelKey = "model" }).Document.Elements); + + var scene = RvtSceneReader.Read(document, new() { ModelKey = "model", IncludeModelLinesAndReinforcement = true }).Document; + Assert.Equal(area.Id, Assert.Single(scene.Elements).Id); + var instance = Assert.Single(scene.Instances); + var geometry = Assert.Single(scene.Geometries); + Assert.Equal(SceneTopology.Lines, geometry.Topology); + Assert.Equal(24, geometry.Indices.Count); + var points = geometry.Vertices.Select(point => instance.Transform!.Value.Apply(point)).ToArray(); + Assert.Equal(8, points.Distinct().Count()); + Assert.Equal(new Vector3d(1 * 0.3048, 2 * 0.3048, 3 * 0.3048), points[0]); + Assert.Equal(6 * 0.3048, points.Max(p => p.Z), 12); + foreach (var pair in points.Chunk(2)) + Assert.Equal(2, new[] { pair[0].X == pair[1].X, pair[0].Y == pair[1].Y, pair[0].Z == pair[1].Z }.Count(same => same)); + } + [Fact] public void SweepKeepsTheStoredRadiusAndExtentsOfAStraightBar() { From 142581be939a1b669d257326080be53957213cb3 Mon Sep 17 00:00:00 2001 From: mie <79989386+mahach666@users.noreply.github.com> Date: Fri, 20 Nov 2026 03:56:27 +0300 Subject: [PATCH 044/259] Export Revit grid and level reference geometry as hidden NWC nodes --- Directory.Packages.props | 2 +- src/RvtIO.Scene/RvtSceneOptions.cs | 3 ++ src/RvtIO.Scene/RvtSceneReader.cs | 9 +++- src/RvtIO.Scene/RvtSceneResult.cs | 3 ++ src/RvtIO/Internal/ParsingState.cs | 1 + src/RvtIO/Meshes/ElementMeshOptions.cs | 3 ++ src/RvtIO/Meshes/ElementMeshes.cs | 44 +++++++++++++++++++ src/RvtIO/Meshes/MeshSet.cs | 3 ++ src/RvtIO/Model/Element.cs | 3 ++ src/RvtIO/Parsing/ElementBuilder.cs | 1 + src/RvtIO/Parsing/TfBlockDeserializer.cs | 12 ++--- src/RvtIO/RvtFileReader.cs | 8 ++-- .../NwcSupplementalGeometryTests.cs | 26 +++++++++++ tools/RvtIO.Nwc/NwcExport.cs | 4 +- tools/RvtIO.Nwc/Program.cs | 8 +++- 15 files changed, 116 insertions(+), 14 deletions(-) diff --git a/Directory.Packages.props b/Directory.Packages.props index daaeb8b4..bdf30cbf 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -17,7 +17,7 @@ - + diff --git a/src/RvtIO.Scene/RvtSceneOptions.cs b/src/RvtIO.Scene/RvtSceneOptions.cs index 24f74650..9ad5ad87 100644 --- a/src/RvtIO.Scene/RvtSceneOptions.cs +++ b/src/RvtIO.Scene/RvtSceneOptions.cs @@ -10,4 +10,7 @@ public sealed class RvtSceneOptions /// Includes straight model lines and reinforcement described by its centre lines. public bool IncludeModelLinesAndReinforcement { get; set; } + + /// Includes reference geometry for project grids and levels. + public bool IncludeDatumGeometry { get; set; } } diff --git a/src/RvtIO.Scene/RvtSceneReader.cs b/src/RvtIO.Scene/RvtSceneReader.cs index a8cea305..ef07ca20 100644 --- a/src/RvtIO.Scene/RvtSceneReader.cs +++ b/src/RvtIO.Scene/RvtSceneReader.cs @@ -118,7 +118,11 @@ public static RvtSceneResult Read(RvtDocument document, MeshSet meshes, RvtScene } private static ElementMeshOptions? MeshOptions(RvtSceneOptions? options) => - options?.IncludeModelLinesAndReinforcement == true ? new() { IncludeModelLinesAndReinforcement = true } : null; + options is null ? null : new() + { + IncludeModelLinesAndReinforcement = options.IncludeModelLinesAndReinforcement, + IncludeDatumGeometry = options.IncludeDatumGeometry, + }; private static string RequiredKey(RvtSceneOptions? options) => options?.ModelKey is { Length: > 0 } key ? key : throw new ArgumentException("A document has no file name: give the model key in RvtSceneOptions.ModelKey.", nameof(options)); @@ -168,7 +172,7 @@ private static RvtSceneResult Map(RvtDocument document, MeshSet meshes, string m { Id = mesh.ElementId, ModelId = ModelId, - LevelId = storeys.GetStoreyId(mesh.ElementId), + LevelId = mesh.IsDatum ? null : storeys.GetStoreyId(mesh.ElementId), SourceId = element?.UniqueId, IfcGuid = element != null ? IfcGuidOf(element) : null, Kind = SceneNodeKind.Element, @@ -273,6 +277,7 @@ private static RvtSceneResult Map(RvtDocument document, MeshSet meshes, string m Diagnostics = report, ElementCount = scene.Elements.Count, ElementsWithGeometry = withGeometry, + HiddenDatumIds = meshes.Elements.Where(mesh => mesh.IsDatum).Select(mesh => (long)mesh.ElementId).ToArray(), Coverage = coverage, GeometryCount = scene.Geometries.Count, InstanceCount = scene.Instances.Count, diff --git a/src/RvtIO.Scene/RvtSceneResult.cs b/src/RvtIO.Scene/RvtSceneResult.cs index a45e4578..9aacba17 100644 --- a/src/RvtIO.Scene/RvtSceneResult.cs +++ b/src/RvtIO.Scene/RvtSceneResult.cs @@ -20,6 +20,9 @@ public sealed class RvtSceneResult /// The number of elements that have at least one instance. public int ElementsWithGeometry { get; init; } + /// Revit datum IDs whose reference geometry is hidden by default in native export. + public IReadOnlyList HiddenDatumIds { get; init; } = []; + /// The number of elements by the coverage of their meshes; a coverage that no element has is not listed. public IReadOnlyDictionary Coverage { get; init; } = new Dictionary(); diff --git a/src/RvtIO/Internal/ParsingState.cs b/src/RvtIO/Internal/ParsingState.cs index 580d358e..484ca0de 100644 --- a/src/RvtIO/Internal/ParsingState.cs +++ b/src/RvtIO/Internal/ParsingState.cs @@ -390,6 +390,7 @@ public TfBlockDeserializer.UnitsElemOptions? OwnDocumentUnitOptions /// the serialized datum text, free end, bubble end and cut vector. The element-level /// name remains authoritative for the grid mark because datum text may name its head type. public Dictionary GridDatums { get; } = new(); + public Dictionary LevelPlanes { get; } = new(); public (List Paths, HashSet Members)? GridAxes { get; set; } /// Line-style element id for 0x0346 curves whose GStyleElemId was a real id diff --git a/src/RvtIO/Meshes/ElementMeshOptions.cs b/src/RvtIO/Meshes/ElementMeshOptions.cs index 2013bdc4..8bdf99e4 100644 --- a/src/RvtIO/Meshes/ElementMeshOptions.cs +++ b/src/RvtIO/Meshes/ElementMeshOptions.cs @@ -9,4 +9,7 @@ public sealed class ElementMeshOptions /// Includes decoded straight model lines and meshes of reinforcement described by its centre lines. public bool IncludeModelLinesAndReinforcement { get; set; } + + /// Includes the finite reference lines of grids and levels for native cache export. + public bool IncludeDatumGeometry { get; set; } } diff --git a/src/RvtIO/Meshes/ElementMeshes.cs b/src/RvtIO/Meshes/ElementMeshes.cs index f9e650ed..963e98dd 100644 --- a/src/RvtIO/Meshes/ElementMeshes.cs +++ b/src/RvtIO/Meshes/ElementMeshes.cs @@ -1,5 +1,6 @@ using RvtIO.BuiltIns; using RvtIO.Geometry.Meshing; +using RvtIO.Internal; using RvtIO.Model; using RvtIO.Parsing; @@ -166,9 +167,52 @@ int MaterialOf(GeoFace face) UntriangulatedFaces = failed, }); } + if (options.IncludeDatumGeometry) + { + var existing = elements.Select(element => element.ElementId).ToHashSet(); + double lowestLevel = info.Elements.Where(element => BuildingStoreyResolver.IsProjectLevel(element) && element.LevelPlane != null) + .Select(element => element.LevelPlane!.Origin[2]).Where(double.IsFinite).DefaultIfEmpty(double.NaN).Min(); + foreach (var element in info.Elements) + if (!existing.Contains(element.Id) && DatumLinePairs(element, lowestLevel) is { } linePairs) + { + elements.Add(new ElementMesh + { + ElementId = element.Id, LinePairs = linePairs, IsDatum = true, Coverage = MeshCoverage.Complete, + }); + } + } return new MeshSet { Elements = elements, Symbols = placedSymbols, GeometryUndecoded = info.WideLayoutNotRewritten }; } + private static MeshVector[]? DatumLinePairs(Element element, double lowestLevel) + { + var plane = element.CategoryId switch + { + (int)BuiltInCategory.OST_Levels when BuildingStoreyResolver.IsProjectLevel(element) => element.LevelPlane, + (int)BuiltInCategory.OST_Grids => element.GridPlane, + _ => null, + }; + if (plane?.Envelope is not [var u0, var v0, var u1, var v1] + || plane.Origin.Length != 3 || plane.XVector.Length != 3 || plane.YVector.Length != 3 + || !plane.Envelope.Concat(plane.Origin).Concat(plane.XVector).Concat(plane.YVector).All(double.IsFinite) + || !(u1 > u0 && v1 > v0)) return null; + + MeshVector Point(double u, double v) => new( + plane.Origin[0] + u * plane.XVector[0] + v * plane.YVector[0], + plane.Origin[1] + u * plane.XVector[1] + v * plane.YVector[1], + plane.Origin[2] + u * plane.XVector[2] + v * plane.YVector[2]); + + if (element.CategoryId == (int)BuiltInCategory.OST_Grids) + { + double bottom = plane.YVector[2] >= 0 ? v0 : v1; + if (double.IsFinite(lowestLevel) && plane.YVector[2] != 0) + bottom = Math.Clamp((lowestLevel - plane.Origin[2]) / plane.YVector[2], v0, v1); + return [Point(u0, bottom), Point(u1, bottom)]; + } + var corner = Point(u0, v1); + return [Point(u0, v0), corner, corner, Point(u1, v1)]; + } + // A ghost node is a Geometry node Revit exports that has no polygon here (display surfaces, or a duplicate of another node). private static MeshCoverage CoverageOf(bool drawn, GeometryData geometry, int failed, bool symbolGhosts) => !drawn ? MeshCoverage.NoGeometry diff --git a/src/RvtIO/Meshes/MeshSet.cs b/src/RvtIO/Meshes/MeshSet.cs index ac40c3df..991c7691 100644 --- a/src/RvtIO/Meshes/MeshSet.cs +++ b/src/RvtIO/Meshes/MeshSet.cs @@ -42,6 +42,9 @@ public sealed class ElementMesh /// Independent line segments listed as consecutive endpoint pairs, in document feet. public IReadOnlyList? LinePairs { get; init; } + /// Whether the line pairs are datum references that are hidden by default. + public bool IsDatum { get; init; } + /// How completely and represent the element. public MeshCoverage Coverage { get; init; } diff --git a/src/RvtIO/Model/Element.cs b/src/RvtIO/Model/Element.cs index d9272094..975aa377 100644 --- a/src/RvtIO/Model/Element.cs +++ b/src/RvtIO/Model/Element.cs @@ -1055,6 +1055,9 @@ internal bool RootClassIs(string className) => NativeRootClassName != null [JsonIgnore] internal GridPlaneData? GridPlane { get; set; } + [JsonIgnore] + internal GridPlaneData? LevelPlane { get; set; } + /// CompoundStructure layers (wall/floor/ceiling types). Each layer has thickness, function, material. public List? Layers { get; set; } diff --git a/src/RvtIO/Parsing/ElementBuilder.cs b/src/RvtIO/Parsing/ElementBuilder.cs index 74d9a5fe..241b3d9a 100644 --- a/src/RvtIO/Parsing/ElementBuilder.cs +++ b/src/RvtIO/Parsing/ElementBuilder.cs @@ -3600,6 +3600,7 @@ void ApplyType(int typeId) if (np.Fields.ContainsKey("__isLevel")) { e.IsNativeLevel = true; + e.LevelPlane = state.LevelPlanes.GetValueOrDefault((uint)e.Id); if (np.DoubleFields.TryGetValue("__levelElevation", out double levelElevation) && double.IsFinite(levelElevation)) Apply(-1007102, StorageType.Double, levelElevation, force: true); diff --git a/src/RvtIO/Parsing/TfBlockDeserializer.cs b/src/RvtIO/Parsing/TfBlockDeserializer.cs index b22f2271..3a90f02b 100644 --- a/src/RvtIO/Parsing/TfBlockDeserializer.cs +++ b/src/RvtIO/Parsing/TfBlockDeserializer.cs @@ -4146,17 +4146,19 @@ double[] PointAt(double parameter) => origin.ToArray(), yVector.ToArray()); } - /// Decode the exact Level elevation from its authored datum Plane origin. - public static double? ExtractLevelElevation(byte[] d, int blockStart, uint dataSize, + /// Decode a Level's authored finite datum plane. + public static Model.GridPlaneData? ExtractLevelPlane(byte[] d, int blockStart, uint dataSize, ushort classId) { if (classId != 2299) return null; var surface = ExtractDatumPlaneSurface(d, blockStart, dataSize, classId); - if (surface == null) return null; - double elevation = surface.Value.Origin[2]; - return double.IsFinite(elevation) ? elevation : null; + return surface is { } plane ? new(plane.Envelope, plane.Origin, plane.XVector, plane.YVector) : null; } + public static double? ExtractLevelElevation(byte[] d, int blockStart, uint dataSize, ushort classId) => + ExtractLevelPlane(d, blockStart, dataSize, classId) is { } plane && double.IsFinite(plane.Origin[2]) + ? plane.Origin[2] : null; + private static (double[] Envelope, double[] Origin, double[] XVector, double[] YVector)? ExtractDatumPlaneSurface(byte[] d, int blockStart, uint dataSize, ushort classId) { diff --git a/src/RvtIO/RvtFileReader.cs b/src/RvtIO/RvtFileReader.cs index 31d178bc..5902d81c 100644 --- a/src/RvtIO/RvtFileReader.cs +++ b/src/RvtIO/RvtFileReader.cs @@ -2523,9 +2523,11 @@ internal static void RunTfStreamWalk(ParsingState state) seg, bs, (uint)ds, cls); if (!string.IsNullOrWhiteSpace(levelName)) np.StringFields["m_text"] = levelName; - if (TfBlockDeserializer.ExtractLevelElevation( - seg, bs, (uint)ds, cls) is double levelElevation) - np.DoubleFields["__levelElevation"] = levelElevation; + if (TfBlockDeserializer.ExtractLevelPlane(seg, bs, (uint)ds, cls) is { } plane) + { + state.LevelPlanes[eid] = plane; + if (double.IsFinite(plane.Origin[2])) np.DoubleFields["__levelElevation"] = plane.Origin[2]; + } } if (np is { Count: > 0 }) state.NativeParams[eid] = np; if (cls == 0x083C diff --git a/tests/RvtIO.Tests/NwcSupplementalGeometryTests.cs b/tests/RvtIO.Tests/NwcSupplementalGeometryTests.cs index bdc95f2d..7cec11ad 100644 --- a/tests/RvtIO.Tests/NwcSupplementalGeometryTests.cs +++ b/tests/RvtIO.Tests/NwcSupplementalGeometryTests.cs @@ -148,6 +148,32 @@ public void NativeAreaReinforcementKeepsTheTwelveEdgesOfItsStoredBounds() Assert.Equal(2, new[] { pair[0].X == pair[1].X, pair[0].Y == pair[1].Y, pair[0].Z == pair[1].Z }.Count(same => same)); } + [Fact] + public void NativeDatumsKeepTheirIdsAndHiddenReferenceGeometry() + { + var level = new Element + { + Id = 1, Name = "Level", CategoryId = (int)BuiltInCategory.OST_Levels, + IsNativeLevel = true, SerializedFamilyId = -1, SerializedUnplacedOwnerId = -1, SerializedOwnerDbViewId = -1, + LevelPlane = new([0, 1, 4, 5], [0, 0, 2], [1, 0, 0], [0, 1, 0]), + }; + var grid = new Element + { + Id = 2, Name = "Grid", CategoryId = (int)BuiltInCategory.OST_Grids, + GridPlane = new([1, 0, 6, 10], [0, 0, 0], [1, 0, 0], [0, 0, 1]), + }; + var document = RvtDocument.FromInfo(new RevitFileInfo { Elements = [level, grid] }); + Assert.Empty(RvtSceneReader.Read(document, new() { ModelKey = "model" }).Document.Elements); + var scene = RvtSceneReader.Read(document, new() { ModelKey = "model", IncludeDatumGeometry = true }); + Assert.Equal([1L, 2L], scene.HiddenDatumIds); + var native = Nwc.NwcExport.Build(scene.Document, "model.rvt", 0, DateTime.UnixEpoch, native: true, scene.HiddenDatumIds.ToHashSet()); + Assert.All(native.Meshes, mesh => Assert.True(mesh.Node!.IsHidden)); + Assert.Equal(4, native.Meshes.Single(mesh => mesh.Node!.Name == "Level").LineIndices.Count); + var gridMesh = native.Meshes.Single(mesh => mesh.Node!.Name == "Grid"); + Assert.Equal(2, gridMesh.LineIndices.Count); + Assert.All(gridMesh.GetWorldVertices(), point => Assert.Equal(2 * 0.3048, point.Z, 12)); + } + [Fact] public void SweepKeepsTheStoredRadiusAndExtentsOfAStraightBar() { diff --git a/tools/RvtIO.Nwc/NwcExport.cs b/tools/RvtIO.Nwc/NwcExport.cs index 226fad19..4bfc4e50 100644 --- a/tools/RvtIO.Nwc/NwcExport.cs +++ b/tools/RvtIO.Nwc/NwcExport.cs @@ -13,7 +13,8 @@ internal static class NwcExport // The optional metadata is written by NwcIO 0.14 and interpreted by the linked-cache reader. private const string MetreCacheOption = "IOExtend.NwcWriter.Scene/1"; private const string LinkClass = "IOExtend.NwcWriter.Link"; - internal static NwcDocument Build(SceneDocument scene, string sourceName, long sourceLength, DateTime timestamp, bool native = false) + internal static NwcDocument Build(SceneDocument scene, string sourceName, long sourceLength, DateTime timestamp, + bool native = false, IReadOnlySet? hiddenDatumIds = null) { if (scene.Validate().FirstOrDefault(d => d.Severity == SceneSeverity.Error) is { } error) throw new InvalidDataException(error.Message); @@ -44,6 +45,7 @@ internal static NwcDocument Build(SceneDocument scene, string sourceName, long s { node.Class = "LcRevitElement"; node.IfcGlobalId = element.IfcGuid; + node.IsHidden = hiddenDatumIds?.Contains(element.Id) == true; } AddText(node, "Revit", "Element ID", id); AddText(node, "Revit", "UniqueId", element.SourceId); diff --git a/tools/RvtIO.Nwc/Program.cs b/tools/RvtIO.Nwc/Program.cs index bf684ace..f4792360 100644 --- a/tools/RvtIO.Nwc/Program.cs +++ b/tools/RvtIO.Nwc/Program.cs @@ -47,13 +47,17 @@ public static int Main(string[] args) var source = new FileInfo(input); long length = source.Length; - var scene = RvtSceneReader.Read(input, native ? new RvtSceneOptions { IncludeModelLinesAndReinforcement = true } : null); + var scene = RvtSceneReader.Read(input, native ? new RvtSceneOptions + { + IncludeModelLinesAndReinforcement = true, + IncludeDatumGeometry = true, + } : null); foreach (var diagnostic in scene.Diagnostics.Where(d => d.Severity != SceneSeverity.Info)) Console.Error.WriteLine($"RVT {diagnostic.Severity} [{diagnostic.Code}]: {diagnostic.Message}"); if (scene.Diagnostics.Any(d => d.Severity == SceneSeverity.Error)) return 2; - var cache = NwcExport.Build(scene.Document, source.Name, length, source.LastWriteTimeUtc, native); + var cache = NwcExport.Build(scene.Document, source.Name, length, source.LastWriteTimeUtc, native, scene.HiddenDatumIds.ToHashSet()); NwcExport.Save(cache, output, native); int lines = cache.Meshes.Count(mesh => mesh.LineIndices.Count != 0); string lineCount = lines > 0 ? $" and {lines} line meshes" : ""; From e618d530fc4d3419dfeee05c9e7e79e223ac929a Mon Sep 17 00:00:00 2001 From: mie <79989386+mahach666@users.noreply.github.com> Date: Fri, 20 Nov 2026 04:03:30 +0300 Subject: [PATCH 045/259] Use reinforcement sketch planes and host outlines for NWC --- src/RvtIO/Internal/ParsingState.cs | 1 + src/RvtIO/Meshes/ElementMeshes.cs | 70 +++++++++++++++---- src/RvtIO/Model/Element.cs | 3 + src/RvtIO/Parsing/ElementBuilder.cs | 1 + src/RvtIO/Parsing/RebarReader.cs | 49 +++++++++++-- src/RvtIO/RvtFileReader.cs | 1 + .../NwcSupplementalGeometryTests.cs | 22 ++++-- 7 files changed, 123 insertions(+), 24 deletions(-) diff --git a/src/RvtIO/Internal/ParsingState.cs b/src/RvtIO/Internal/ParsingState.cs index 580d358e..595627cf 100644 --- a/src/RvtIO/Internal/ParsingState.cs +++ b/src/RvtIO/Internal/ParsingState.cs @@ -390,6 +390,7 @@ public TfBlockDeserializer.UnitsElemOptions? OwnDocumentUnitOptions /// the serialized datum text, free end, bubble end and cut vector. The element-level /// name remains authoritative for the grid mark because datum text may name its head type. public Dictionary GridDatums { get; } = new(); + public Dictionary AreaReinforcementPlanes { get; } = new(); public (List Paths, HashSet Members)? GridAxes { get; set; } /// Line-style element id for 0x0346 curves whose GStyleElemId was a real id diff --git a/src/RvtIO/Meshes/ElementMeshes.cs b/src/RvtIO/Meshes/ElementMeshes.cs index f9e650ed..6ba398fc 100644 --- a/src/RvtIO/Meshes/ElementMeshes.cs +++ b/src/RvtIO/Meshes/ElementMeshes.cs @@ -126,7 +126,8 @@ int MaterialOf(GeoFace face) var arc = curve is { CurveType: "Arc" } && GridAxis.Tessellate([curve], ArcChordErrorFeet) is { } samples ? samples.Select(p => new MeshVector(p[0], p[1], p[2])).ToArray() : null; var linePairs = options.IncludeModelLinesAndReinforcement && AreaReinforcementBounds(element) is { } bounds - ? BoxEdges(bounds) : null; + && element.SerializedHostId is int hostId && document.GetElement(hostId)?.Geometry is { } host + ? AreaReinforcementOutline(element.AreaReinforcementPlane!, host, bounds) : null; var rebar = options.IncludeModelLinesAndReinforcement && element.RebarBars is { } bars ? ReinforcementMeshes.Build(bars) : null; elements.Add(new ElementMesh { @@ -242,27 +243,68 @@ private static bool IsStairContainer(Element element, GeometryData? body, HashSe private static double[]? AreaReinforcementBounds(Element element) => element.CategoryId == (int)BuiltInCategory.OST_AreaRein && element.RootClassIs("RebarSystem") + && element.AreaReinforcementPlane != null && element.SerializedHostId is > 0 && element.BoundingBox is [var x0, var y0, var z0, var x1, var y1, var z1] bounds && bounds.All(double.IsFinite) && x0 < x1 && y0 < y1 && z0 < z1 ? bounds : null; - private static MeshVector[] BoxEdges(double[] bounds) + private static MeshVector[]? AreaReinforcementOutline(AreaSketchPlane plane, GeometryData host, double[] bounds) { - // An area's exported selection graphics are the twelve edges of its stored model bounds. - var endpoints = new MeshVector[24]; - int at = 0; - for (int corner = 0; corner < 8; corner++) - for (int axis = 0; axis < 3; axis++) + const double tolerance = 1e-5; // Feet. The source envelope and face coordinates can round independently. + var direction = Pt3.Cross(Pt3.From(plane.XAxis), Pt3.From(plane.YAxis)); + double length = direction.Norm; + if (!(length > 0 && double.IsFinite(length))) return null; + var normal = direction / length; + var origin = Pt3.From(plane.Origin); + var faces = host.Faces.Where(face => face.OuterVertices is { Count: >= 3 } loop && + loop.All(point => point.Length == 3 && Math.Abs(normal.Dot(Pt3.From(point) - origin)) <= tolerance)) + .Take(2).ToArray(); + if (faces.Length != 1) return null; + + // The host face supplies the outline. The area's own bounds locate its two parallel copies. + var points = faces[0].OuterVertices!.Select(Pt3.From).ToArray(); + double[] axis = normal.ToArray(); + int dominant = Math.Abs(axis[0]) >= Math.Abs(axis[1]) ? 0 : 1; + if (Math.Abs(axis[2]) > Math.Abs(axis[dominant])) dominant = 2; + var profileBounds = Bounds(points); + double first = (bounds[dominant] - profileBounds[dominant]) / axis[dominant]; + double second = (bounds[dominant + 3] - profileBounds[dominant + 3]) / axis[dominant]; + if (!double.IsFinite(first) || !double.IsFinite(second) || Math.Abs(first - second) <= tolerance) return null; + var front = points.Select(point => point + normal * first).ToArray(); + var back = points.Select(point => point + normal * second).ToArray(); + if (Bounds(front.Concat(back)).Zip(bounds).Any(pair => Math.Abs(pair.First - pair.Second) > tolerance)) + return null; + var pairs = new List(4 * points.Length); + AddOutline(front); + AddOutline(back); + return pairs.ToArray(); + + void AddOutline(Pt3[] loop) + { + for (int i = 0; i < loop.Length; i++) { - int bit = 1 << axis; - if ((corner & bit) != 0) continue; - endpoints[at++] = Vertex(corner); - endpoints[at++] = Vertex(corner | bit); + var a = loop[i]; + var b = loop[(i + 1) % loop.Length]; + pairs.Add(new(a.X, a.Y, a.Z)); + pairs.Add(new(b.X, b.Y, b.Z)); } - return endpoints; + } - MeshVector Vertex(int corner) => new(bounds[(corner & 1) == 0 ? 0 : 3], - bounds[(corner & 2) == 0 ? 1 : 4], bounds[(corner & 4) == 0 ? 2 : 5]); + static double[] Bounds(IEnumerable source) + { + var bounds = new double[] { double.PositiveInfinity, double.PositiveInfinity, double.PositiveInfinity, + double.NegativeInfinity, double.NegativeInfinity, double.NegativeInfinity }; + foreach (var point in source) + { + bounds[0] = Math.Min(bounds[0], point.X); + bounds[1] = Math.Min(bounds[1], point.Y); + bounds[2] = Math.Min(bounds[2], point.Z); + bounds[3] = Math.Max(bounds[3], point.X); + bounds[4] = Math.Max(bounds[4], point.Y); + bounds[5] = Math.Max(bounds[5], point.Z); + } + return bounds; + } } private static (MeshVector Start, MeshVector End)? ModelLine(LocationCurve? curve) diff --git a/src/RvtIO/Model/Element.cs b/src/RvtIO/Model/Element.cs index d9272094..38b167ba 100644 --- a/src/RvtIO/Model/Element.cs +++ b/src/RvtIO/Model/Element.cs @@ -447,6 +447,9 @@ public class Element [JsonIgnore] internal Parsing.RebarBars? RebarBars { get; set; } + [JsonIgnore] + internal Parsing.AreaSketchPlane? AreaReinforcementPlane { get; set; } + /// The type and the beams of a beam system (JoistSystem), null for every other element. [JsonIgnore] internal Parsing.JoistSystemData? JoistSystem { get; set; } diff --git a/src/RvtIO/Parsing/ElementBuilder.cs b/src/RvtIO/Parsing/ElementBuilder.cs index 74d9a5fe..35c69acf 100644 --- a/src/RvtIO/Parsing/ElementBuilder.cs +++ b/src/RvtIO/Parsing/ElementBuilder.cs @@ -1171,6 +1171,7 @@ public static void BuildElemTableElement( elem.NativeHeaderDesignOptionId = state.HeaderDesignOptions.GetValueOrDefault(elemId); elem.NativeRootClassName = state.NativeRootClassNames.GetValueOrDefault(elemId); elem.RebarBars = state.RebarBars.GetValueOrDefault(elemId); + elem.AreaReinforcementPlane = state.AreaReinforcementPlanes.GetValueOrDefault(elemId); elem.JoistSystem = state.JoistSystems.GetValueOrDefault(elemId); if (elem.NativeRootClassName is { } rootName) elem.NativeRootClassChain = state.WideSchema?.ChainOf(rootName); if (state.WideSchema is { } wideSchema && wideSchema.ByName("Symbol") is { } symbolClass diff --git a/src/RvtIO/Parsing/RebarReader.cs b/src/RvtIO/Parsing/RebarReader.cs index 1a1918c9..1722c40e 100644 --- a/src/RvtIO/Parsing/RebarReader.cs +++ b/src/RvtIO/Parsing/RebarReader.cs @@ -58,7 +58,10 @@ internal sealed record RebarBars(int BarTypeId, int SystemId, double? BarLength, internal sealed record JoistSystemData(int TypeId, string? TypeName, IReadOnlyList BeamIds); /// The reinforcement and the beam systems of a file by element id. -internal sealed record ReinforcementData(Dictionary Bars, Dictionary Joists); +internal sealed record AreaSketchPlane(double[] Origin, double[] XAxis, double[] YAxis); + +internal sealed record ReinforcementData(Dictionary Bars, Dictionary Joists, + Dictionary AreaPlanes); /// /// Centre lines of the reinforcement of a Revit file, read with the schema-driven field walk (, classes and @@ -101,6 +104,9 @@ internal static partial class RebarReader "HookLengthSettings" => field.Name is "m_hookLength" or "m_offsetLength" or "m_tangentLength", "RebarSystemLayer" => field.Name is "m_barType" or "m_active" or "m_uncutCurves" or "m_individualLineTrf" or "m_uncutRebarInstances" or "m_includedUncutBars", + "RebarSystemBase" => field.Name == "m_sketchId", + "Sketch" => field.Name is "m_absorbedCurves" or "m_pPlane", + "Plane" => field.Name is "m_origin" or "m_xVec" or "m_yVec", "RebarInSystem" => field.Name == "m_systemId", "RebarContainer" => field.Name is "m_rebarContainerTypeId" or "m_hostId", "FamilyInstance" => field.Name is "m_instOrigin" or "m_RefDir" or "m_zAxis", @@ -115,7 +121,8 @@ internal static partial class RebarReader }; if (!wanted || field.Type == 9) return null; string key = name + "." + field.Name; - return field.Name is "m_includedBars" or "m_includedUncutBars" or "m_doubles" ? WideBlockWalker.AllItemsKeyPrefix + key : key; + return field.Name is "m_includedBars" or "m_includedUncutBars" or "m_doubles" or "m_absorbedCurves" + ? WideBlockWalker.AllItemsKeyPrefix + key : key; } /// True for the schema of Revit 2020 and 2021, whose RebarSystemLayer has no m_uncutCurves: the bars of a system are the held @@ -132,7 +139,8 @@ internal static ReinforcementData Read( var joists = new Dictionary(); var joistTypeNames = new Dictionary(); var shapeNames = new Dictionary(); - var empty = new ReinforcementData(result, joists); + var areaPlanes = new Dictionary(); + var empty = new ReinforcementData(result, joists, areaPlanes); var rebar = schema.ByName("Rebar")?.Id; var system = schema.ByName("RebarSystem")?.Id; var inSystem = schema.ByName("RebarInSystem")?.Id; @@ -146,7 +154,7 @@ internal static ReinforcementData Read( var joist = schema.ByName("JoistSystem")?.Id; var joistType = schema.ByName("JoistSystemAttr")?.Id; if (rebar == null || system == null || inSystem == null || barType == null || settings == null || shape == null || joist == null || joistType == null) return empty; - var walker = new WideBlockWalker(schema.Document, Key, [], ids: ids); + var walker = new WideBlockWalker(schema.Document, Key, [], captureRootPointers: true, ids: ids); if (entitySchemas != null) walker.UseEntitySchemas(entitySchemas, passUnknownEntities); var layers = new Dictionary>(); var members = new Dictionary(); @@ -158,6 +166,7 @@ internal static ReinforcementData Read( var containers = new Dictionary Items)>(); var containerNames = new Dictionary(); var held = new Dictionary<(uint System, int Layer, int Index), PendingBar>(); + var areaSketches = new Dictionary(); bool heldLayout = HeldLayout(schema); double rounding = 0; WideElementRecords.BuildIndex(streams, schema, wanted, (id, data, offset, size, cls) => @@ -165,6 +174,9 @@ internal static ReinforcementData Read( if (cls != rebar && cls != system && cls != inSystem && cls != barType && cls != settings && cls != shape && cls != joist && cls != joistType && cls != hookType && cls != container && cls != containerType) return; var walk = walker.Run(data, offset, size, cls, cls == shape ? (w, first) => ConstraintsValid(walker, w, first) : null); + if (cls == system && walk.RootRead && + walk.Captures.FirstOrDefault(capture => capture.AtRoot && capture.Key == "RebarSystemBase.m_sketchId").Integer is > 0 and <= int.MaxValue and long sketch) + areaSketches.TryAdd(id, (uint)sketch); // The bar of a Rebar that stopped behind an extensible storage entity is its RebarInstance, read before the entity payloads. if (cls == rebar && walk.BeforeEntityBlobs() is { } beforeBlobs) { @@ -224,6 +236,35 @@ internal static ReinforcementData Read( } else if (ReadMember(walker, walk, byQueue) is { } member) members.TryAdd(id, member); }, framed, ids); + if (areaSketches.Count > 0) + { + const string curvesKey = WideBlockWalker.AllItemsKeyPrefix + "Sketch.m_absorbedCurves"; + var planes = new Dictionary(); + WideElementRecords.BuildIndex(streams, schema, areaSketches.Values.ToHashSet(), (id, data, offset, size, cls) => + { + if (!walker.IsA(cls, "Sketch")) return; + var walk = walker.Run(data, offset, size, cls); + // A sketch with a single direction line takes its reinforcement boundary from the host face. + if (!walk.RootRead || walk.Captures.FirstOrDefault(c => c.AtRoot && c.Key == curvesKey + "#").Integer != 1 + || walk.Captures.FirstOrDefault(c => c.AtRoot && c.Key == curvesKey + "@0") is not + { Kind: WideBlockWalker.CaptureKind.PointerClass, Integer: >= 0 and <= int.MaxValue } direction + || walker.Class((int)direction.Integer)?.Name != "GLine" + || walk.RootPointers?.TryGetValue("Sketch.m_pPlane", out int plane) != true + || plane >= walk.QueueEnd.Count || walker.Class(walk.Queue[plane])?.Name != "Plane") + return; + + double[]? Vector(string field) + { + var values = walk.Captures.Where(c => c.QueueIndex == plane && c.Kind == WideBlockWalker.CaptureKind.Real + && c.Field == field).Select(c => c.Real).ToArray(); + return values.Length == 3 && values.All(double.IsFinite) ? values : null; + } + if (Vector("m_origin") is { } origin && Vector("m_xVec") is { } x && Vector("m_yVec") is { } y) + planes.TryAdd(id, new(origin, x, y)); + }, framed, ids); + foreach (var (id, sketch) in areaSketches) + if (planes.TryGetValue(sketch, out var plane)) areaPlanes.Add(id, plane); + } RebarBars? Solve(PendingBar bar) => diameters.TryGetValue(bar.BarTypeId, out var barDiameters) && barKinds.TryGetValue(bar.BarTypeId, out var kind) && shapeDefinitions.TryGetValue(bar.ShapeId, out var definition) ? SolveShapeDriven(bar, definition, hookKinds, kind, barDiameters.Model) : null; diff --git a/src/RvtIO/RvtFileReader.cs b/src/RvtIO/RvtFileReader.cs index 31d178bc..0875c956 100644 --- a/src/RvtIO/RvtFileReader.cs +++ b/src/RvtIO/RvtFileReader.cs @@ -1058,6 +1058,7 @@ private static void ReadRebarBars(RootStorage root, ParsingState state, var reinforcement = RebarReader.Read(partitionStreams, schema, state.AllKnownIds, EntitySchemaReader.Read(root, schema.Document), passUnknownEntities: true, framed: framedStreams, ids: state.ElementIds); foreach (var (id, bars) in reinforcement.Bars) state.RebarBars[id] = bars; + foreach (var (id, plane) in reinforcement.AreaPlanes) state.AreaReinforcementPlanes[id] = plane; foreach (var (id, joist) in reinforcement.Joists) state.JoistSystems[id] = joist; } diff --git a/tests/RvtIO.Tests/NwcSupplementalGeometryTests.cs b/tests/RvtIO.Tests/NwcSupplementalGeometryTests.cs index bdc95f2d..657d7e11 100644 --- a/tests/RvtIO.Tests/NwcSupplementalGeometryTests.cs +++ b/tests/RvtIO.Tests/NwcSupplementalGeometryTests.cs @@ -120,8 +120,16 @@ public void NativeModelArcKeepsItsPlaneAndTessellatesTheCircularPath() } [Fact] - public void NativeAreaReinforcementKeepsTheTwelveEdgesOfItsStoredBounds() + public void NativeAreaReinforcementKeepsBothCopiesOfTheHostOutline() { + var host = new Element + { + Id = 2, + Geometry = new() + { + Faces = [new() { OuterVertices = [[1, 2, 3], [4, 2, 3], [1, 5, 3]], Normal = [0, 0, 1] }], + }, + }; var area = new Element { Id = 1, @@ -129,9 +137,11 @@ public void NativeAreaReinforcementKeepsTheTwelveEdgesOfItsStoredBounds() Category = nameof(BuiltInCategory.OST_AreaRein), NativeRootClassName = "RebarSystem", NativeRootClassChain = ["RebarSystem"], + SerializedHostId = host.Id, + AreaReinforcementPlane = new([1, 2, 3], [1, 0, 0], [0, 1, 0]), BoundingBox = [1, 2, 3, 4, 5, 6], }; - var document = RvtDocument.FromInfo(new RevitFileInfo { Elements = [area] }); + var document = RvtDocument.FromInfo(new RevitFileInfo { Elements = [area, host] }); Assert.Empty(RvtSceneReader.Read(document, new() { ModelKey = "model" }).Document.Elements); var scene = RvtSceneReader.Read(document, new() { ModelKey = "model", IncludeModelLinesAndReinforcement = true }).Document; @@ -139,13 +149,13 @@ public void NativeAreaReinforcementKeepsTheTwelveEdgesOfItsStoredBounds() var instance = Assert.Single(scene.Instances); var geometry = Assert.Single(scene.Geometries); Assert.Equal(SceneTopology.Lines, geometry.Topology); - Assert.Equal(24, geometry.Indices.Count); + Assert.Equal(12, geometry.Indices.Count); var points = geometry.Vertices.Select(point => instance.Transform!.Value.Apply(point)).ToArray(); - Assert.Equal(8, points.Distinct().Count()); + Assert.Equal(6, points.Distinct().Count()); Assert.Equal(new Vector3d(1 * 0.3048, 2 * 0.3048, 3 * 0.3048), points[0]); Assert.Equal(6 * 0.3048, points.Max(p => p.Z), 12); - foreach (var pair in points.Chunk(2)) - Assert.Equal(2, new[] { pair[0].X == pair[1].X, pair[0].Y == pair[1].Y, pair[0].Z == pair[1].Z }.Count(same => same)); + Assert.All(points.Chunk(2), pair => Assert.Equal(pair[0].Z, pair[1].Z)); + Assert.Equal(2, points.Chunk(2).Count(pair => pair[0].X != pair[1].X && pair[0].Y != pair[1].Y)); } [Fact] From b86134504140253683b36188af5f8c707beb15c9 Mon Sep 17 00:00:00 2001 From: mie Date: Fri, 20 Nov 2026 04:13:12 +0300 Subject: [PATCH 046/259] Match Autodesk level outlines in project coordinates --- src/RvtIO/Meshes/ElementMeshes.cs | 9 +++++++-- tests/RvtIO.Tests/NwcSupplementalGeometryTests.cs | 9 +++++++-- 2 files changed, 14 insertions(+), 4 deletions(-) diff --git a/src/RvtIO/Meshes/ElementMeshes.cs b/src/RvtIO/Meshes/ElementMeshes.cs index 07523b6c..b4c9aab4 100644 --- a/src/RvtIO/Meshes/ElementMeshes.cs +++ b/src/RvtIO/Meshes/ElementMeshes.cs @@ -210,8 +210,13 @@ int MaterialOf(GeoFace face) bottom = Math.Clamp((lowestLevel - plane.Origin[2]) / plane.YVector[2], v0, v1); return [Point(u0, bottom), Point(u1, bottom)]; } - var corner = Point(u0, v1); - return [Point(u0, v0), corner, corner, Point(u1, v1)]; + // Level outlines follow the west and north bounds in project coordinates. + MeshVector[] corners = [Point(u0, v0), Point(u0, v1), Point(u1, v0), Point(u1, v1)]; + double west = corners.Min(point => point.X); + double north = corners.Max(point => point.Y); + double z = plane.Origin[2]; + MeshVector corner = new(west, north, z); + return [new(west, corners.Min(point => point.Y), z), corner, corner, new(corners.Max(point => point.X), north, z)]; } // A ghost node is a Geometry node Revit exports that has no polygon here (display surfaces, or a duplicate of another node). diff --git a/tests/RvtIO.Tests/NwcSupplementalGeometryTests.cs b/tests/RvtIO.Tests/NwcSupplementalGeometryTests.cs index a388eb9e..54b0dd5b 100644 --- a/tests/RvtIO.Tests/NwcSupplementalGeometryTests.cs +++ b/tests/RvtIO.Tests/NwcSupplementalGeometryTests.cs @@ -165,7 +165,7 @@ public void NativeDatumsKeepTheirIdsAndHiddenReferenceGeometry() { Id = 1, Name = "Level", CategoryId = (int)BuiltInCategory.OST_Levels, IsNativeLevel = true, SerializedFamilyId = -1, SerializedUnplacedOwnerId = -1, SerializedOwnerDbViewId = -1, - LevelPlane = new([0, 1, 4, 5], [0, 0, 2], [1, 0, 0], [0, 1, 0]), + LevelPlane = new([1, -4, 5, 0], [0, 0, 2], [0, 1, 0], [-1, 0, 0]), }; var grid = new Element { @@ -178,7 +178,12 @@ public void NativeDatumsKeepTheirIdsAndHiddenReferenceGeometry() Assert.Equal([1L, 2L], scene.HiddenDatumIds); var native = Nwc.NwcExport.Build(scene.Document, "model.rvt", 0, DateTime.UnixEpoch, native: true, scene.HiddenDatumIds.ToHashSet()); Assert.All(native.Meshes, mesh => Assert.True(mesh.Node!.IsHidden)); - Assert.Equal(4, native.Meshes.Single(mesh => mesh.Node!.Name == "Level").LineIndices.Count); + var levelMesh = native.Meshes.Single(mesh => mesh.Node!.Name == "Level"); + var levelPoints = levelMesh.GetWorldVertices().ToArray(); + Assert.Equal(new NwcIO.Model.Vector3d(0, 0.3048, 2 * 0.3048), levelPoints[levelMesh.LineIndices[0]]); + Assert.Equal(new NwcIO.Model.Vector3d(0, 5 * 0.3048, 2 * 0.3048), levelPoints[levelMesh.LineIndices[1]]); + Assert.Equal(levelPoints[levelMesh.LineIndices[1]], levelPoints[levelMesh.LineIndices[2]]); + Assert.Equal(new NwcIO.Model.Vector3d(4 * 0.3048, 5 * 0.3048, 2 * 0.3048), levelPoints[levelMesh.LineIndices[3]]); var gridMesh = native.Meshes.Single(mesh => mesh.Node!.Name == "Grid"); Assert.Equal(2, gridMesh.LineIndices.Count); Assert.All(gridMesh.GetWorldVertices(), point => Assert.Equal(2 * 0.3048, point.Z, 12)); From 34cf77a742aac426e88c3576604b4f04f5efc1ea Mon Sep 17 00:00:00 2001 From: mie Date: Fri, 20 Nov 2026 04:31:11 +0300 Subject: [PATCH 047/259] Pin published NwcIO 0.17.0 for native export --- Directory.Packages.props | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Directory.Packages.props b/Directory.Packages.props index daaeb8b4..bdf30cbf 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -17,7 +17,7 @@ - + From eed537da1f8bb687d67b1c2018bf0e0c384c68a1 Mon Sep 17 00:00:00 2001 From: mahach666 <79989386+mahach666@users.noreply.github.com> Date: Fri, 20 Nov 2026 05:00:58 +0300 Subject: [PATCH 048/259] Recover current wall types and verified host quantities Refs #192 --- src/RvtIO/Geometry/BrepMeasures.cs | 25 ++++++- .../Ifc/IfcExporter.QuantitiesCurrent.cs | 20 +++++- src/RvtIO/Parsing/ElementBuilder.cs | 24 +++++-- src/RvtIO/RvtFileReader.cs | 26 ++++--- .../IfcExporterBaseQuantitiesCurrentTests.cs | 70 +++++++++++++++++++ tests/RvtIO.Tests/SystemTypeIdentityTests.cs | 32 +++++++++ 6 files changed, 181 insertions(+), 16 deletions(-) diff --git a/src/RvtIO/Geometry/BrepMeasures.cs b/src/RvtIO/Geometry/BrepMeasures.cs index 53b21a0c..14941062 100644 --- a/src/RvtIO/Geometry/BrepMeasures.cs +++ b/src/RvtIO/Geometry/BrepMeasures.cs @@ -125,12 +125,31 @@ internal static List ShellsOfCurrent(GeometryData? geometry, return result; } + /// Measures a single planar extrusion whose closed faces and stored node volume agree. + internal static (ShellPrism Prism, double Volume)? MeasuredPlanarPrism(GeometryData? geometry, bool wallSides = false) + { + if (geometry is not { UntriangulatedFaces: 0, BrepSolids: [{ IsClosed: true } solid], + NodeMeasures: [{ Node: > 0, Volume: > 0 } measure] } + || !double.IsFinite(measure.Volume) + || solid.FaceIndices.Count != geometry.Faces.Count + || geometry.Faces.Any(face => face.CurvedSurface || face.GeometryNode != measure.Node) + || !FacetedShell.TryOrientExactFacetedShell(geometry.Faces, solid.FaceIndices, out var faces, triangulateNonPlanarFaces: false)) + return null; + var shell = new ShellInfo(faces, Closed: true, measure.Volume, measure.Area); + if (FindPrismCurrent(shell, verticalOnly: !wallSides, wallSides: wallSides) is not { ProfileArea: > 0 } prism + || !(Math.Abs(prism.ProfileArea * prism.Depth - measure.Volume) <= measure.Volume * 1e-6)) + return null; + return (prism, measure.Volume); + } + /// The prism of a shell: two planar faces of equal net area (within 1e-4 ft2) facing each other on /// different planes, with every other face parallel to their common normal. Null for any other shape, a curved face /// included. /// With the vertical cylinders that tessellate the arcs of the outline are allowed as sides and left /// out of the search (the perimeters stay those of the chords), and a shell with any other curved face is no prism. - internal static ShellPrism? FindPrismCurrent(ShellInfo shell, bool verticalOnly = false, bool arcSides = false) + /// For a straight wall, the largest pair of vertical end faces bounds its thickness. + internal static ShellPrism? FindPrismCurrent(ShellInfo shell, bool verticalOnly = false, bool arcSides = false, + bool wallSides = false) { var faces = shell.Faces; if (faces.Count < 4) return null; @@ -160,7 +179,7 @@ internal static List ShellsOfCurrent(GeometryData? geometry, var b = normals[j]; if (a[0] * b[0] + a[1] * b[1] + a[2] * b[2] > -1 + 1e-9 || Math.Abs(areas[i] - areas[j]) > 1e-4) continue; bool vertical = Math.Abs(a[2]) > 1 - 1e-9; - if (verticalOnly && !vertical) continue; + if (verticalOnly && !vertical || wallSides && Math.Abs(a[2]) > 1e-9) continue; bool others = true; for (int k = 0; k < count && others; k++) if (k != i && k != j) @@ -170,7 +189,7 @@ internal static List ShellsOfCurrent(GeometryData? geometry, var pj = faces[j].OuterVertices![0]; double depth = Math.Abs((pj[0] - pi[0]) * a[0] + (pj[1] - pi[1]) * a[1] + (pj[2] - pi[2]) * a[2]); // A box is a prism along each of its three axes; its long axis is the one a bar is extruded along. - if (depth < 1e-9 || best is { } known && known.Depth >= depth) continue; + if (depth < 1e-9 || best is { } known && (wallSides ? known.ProfileArea >= areas[i] : known.Depth >= depth)) continue; var outer = faces[i].OuterVertices!; var lower = vertical && MeanHeightCurrent(faces[j]) < MeanHeightCurrent(faces[i]) ? faces[j] : faces[i]; var measured = lower.FirstSourceLoop ?? lower.OuterVertices!; diff --git a/src/RvtIO/Ifc/IfcExporter.QuantitiesCurrent.cs b/src/RvtIO/Ifc/IfcExporter.QuantitiesCurrent.cs index 9f92fc4b..41f1f6c4 100644 --- a/src/RvtIO/Ifc/IfcExporter.QuantitiesCurrent.cs +++ b/src/RvtIO/Ifc/IfcExporter.QuantitiesCurrent.cs @@ -835,7 +835,7 @@ internal int ApplyCurrentBaseQuantities( private List QuantitiesOfProductCurrent(QuantityContextCurrent context, int productId, string type, string args) { var none = new List(); - if (type is not ("IFCOPENINGELEMENT" or "IFCDOOR" or "IFCWINDOW" or "IFCWALLSTANDARDCASE" or "IFCMEMBER" or "IFCPLATE" + if (type is not ("IFCOPENINGELEMENT" or "IFCDOOR" or "IFCWINDOW" or "IFCWALL" or "IFCWALLSTANDARDCASE" or "IFCMEMBER" or "IFCPLATE" or "IFCSLAB" or "IFCCOVERING" or "IFCCOLUMN" or "IFCBEAM" or "IFCSTAIRFLIGHT" or "IFCSPACE" or "IFCRAILING")) return none; string[] arguments = SplitStepArguments(args); @@ -849,6 +849,8 @@ private List QuantitiesOfProductCurrent(QuantityContextCurrent co return ReadBodyExtrusionCurrent(context.W, context.IndexById, arguments[6]) is { } opening ? FillerOpeningQuantitiesCurrent(context, productId, OpeningQuantitiesCurrent(context, productId, arguments, opening)) : none; + case "IFCWALL": + return element == null ? none : FacetedWallQuantitiesCurrent(element, context.Elements); case "IFCWALLSTANDARDCASE": return element != null && ReadBodyExtrusionCurrent(context.W, context.IndexById, arguments[6]) is { } wall ? WallQuantitiesCurrent(wall, element, context) : none; @@ -1046,6 +1048,22 @@ private static void AddIfPositive(List list, QuantityKind kind, s if (value is > 1e-12) list.Add(new(kind, name, value.Value)); } + private static List FacetedWallQuantitiesCurrent(Element wall, IReadOnlyDictionary elements) + { + var result = new List(); + if (wall is not { CategoryId: -2000011, RootClassName: "SWall", SerializedSystemTypeId: > 0 and int typeId } + || !elements.TryGetValue(typeId, out var type) || type.SerializedSystemTypeClassId != 512 + || wall.CuttingElementIds is { Count: > 0 } + || MeasuredPlanarPrism(wall.Geometry, wallSides: true) is not { } measured) return result; + // A closed body establishes volume. For the legacy layout, admit its side as the area + // only when the extrusion follows the stored thickness of the wall type. + if (wall.NativeRootClassName == null && TryGetSerializedWallWidthFeet(wall, out double width) + && Math.Abs(width - measured.Prism.Depth) <= 1e-6) + AddIfPositive(result, QuantityKind.Area, "NetSideArea", measured.Prism.ProfileArea * SquareFeetToSquareMetres); + AddIfPositive(result, QuantityKind.Volume, "NetVolume", measured.Volume * CubicFeetToCubicMetres); + return result; + } + /// Quantities for a wall written as an extrusion: Height is the extrusion depth, /// Length and Width the profile sides, GrossFootprintArea its area; the side area is the largest vertical face of the /// wall solids (the net and the gross side area agree), GrossVolume is Width times it, NetVolume the solid volume. diff --git a/src/RvtIO/Parsing/ElementBuilder.cs b/src/RvtIO/Parsing/ElementBuilder.cs index 1cdc8479..2cde93e4 100644 --- a/src/RvtIO/Parsing/ElementBuilder.cs +++ b/src/RvtIO/Parsing/ElementBuilder.cs @@ -1,4 +1,5 @@ using System.Runtime.CompilerServices; +using RvtIO.Geometry; using RvtIO.Internal; using RvtIO.Lookup; using RvtIO.Model; @@ -964,12 +965,15 @@ private static void RemoveInteriorLayerFaces(List faces) if (drop[i]) faces.RemoveAt(i); } - public static void AddComputedBipsFromGeometry(Element elem, GRepData grep) + public static void AddComputedBipsFromGeometry(Element elem, GRepData grep, ParsingState state) { if (grep.Faces.Count == 0) return; // Face-derived quantities hold only for slab-like categories (floors/ceilings/roofs/foundations). bool slabLike = elem.CategoryId is -2000032 or -2000038 or -2000035 or -2001300; if (!slabLike) return; + if (elem.CategoryId == -2000032 && state.SystemOccurrenceTypeIds.GetValueOrDefault((uint)elem.Id) + is { BlockCount: 1, ClassId: 1913, TypeId: > 0 }) + ApplyCutFloorQuantities(elem); var existingBips = new HashSet(elem.Parameters.Select(p => p.Id)); GRepFace? primaryFace = null; @@ -1270,7 +1274,7 @@ public static void BuildElemTableElement( AttachFamilyCutGeometry(elem, elemId, state); if (grepDataForElem != null) - AddComputedBipsFromGeometry(elem, grepDataForElem); + AddComputedBipsFromGeometry(elem, grepDataForElem, state); AddBboxDimensionsIfMissing(elem, state); BuildLocationCurve(elem, elemId, state); @@ -4318,7 +4322,7 @@ public static void BuildDiscoveredElement(uint eid, ParsingState state, RevitFil AttachFamilyCutGeometry(elem, eid, state); if (grepData != null) - AddComputedBipsFromGeometry(elem, grepData); + AddComputedBipsFromGeometry(elem, grepData, state); AddBboxDimensionsIfMissing(elem, state); BuildLocationCurve(elem, eid, state); @@ -4352,7 +4356,7 @@ public static void BuildBlockOnlyElement(uint bid, ParsingState state, RevitFile AttachFamilyCutGeometry(elem, bid, state); if (grepData != null) - AddComputedBipsFromGeometry(elem, grepData); + AddComputedBipsFromGeometry(elem, grepData, state); AddBboxDimensionsIfMissing(elem, state); AttachDimension(elem, bid, state); @@ -6931,6 +6935,18 @@ private static void ComputeSketchQuantities(RevitFileInfo info, ParsingState? st } } + internal static void ApplyCutFloorQuantities(Element floor) + { + if (floor.CutOutSteps?.Any(step => step.Cutout) != true + || BrepMeasures.MeasuredPlanarPrism(floor.Geometry) is not ({ InnerPerimeter: > 0 } prism, var volume)) return; + + // The closed body includes the inserted opening that the host sketch omits. + if (floor.Parameters.All(p => p.Id != -1012805)) + floor.Parameters.Add(BipHelpers.MakeBipParam(-1012805, "HOST_AREA_COMPUTED", StorageType.Double, prism.ProfileArea)); + if (floor.Parameters.All(p => p.Id != -1012806)) + floor.Parameters.Add(BipHelpers.MakeBipParam(-1012806, "HOST_VOLUME_COMPUTED", StorageType.Double, volume)); + } + private static readonly HashSet EditedByUserCats = new() { -2000171, -2009645, -2000011, -2000170, -2000151, -2000321, -2000014, -2000576, diff --git a/src/RvtIO/RvtFileReader.cs b/src/RvtIO/RvtFileReader.cs index 31d178bc..746399cd 100644 --- a/src/RvtIO/RvtFileReader.cs +++ b/src/RvtIO/RvtFileReader.cs @@ -2348,7 +2348,7 @@ internal static void AddDriveCurveFromRewrittenBlock(TfBlockDeserializer.NativeP /// of loaded families and byte runs inside other items, and each one counted as a second root of the element. The location line of a /// wall () is read from its root record once every root is counted. internal static void RecordFramedRoots(ParsingState state, - List<(byte[] Data, int Start, uint Size, ushort Class, uint Owner)>? annotationRoots = null) + List<(byte[] Data, int Start, uint Size, ushort Class, uint Owner)>? unanchoredTypeRoots = null) { var roots = new List<(byte[] Data, int Start, uint Size, ushort Class, uint Owner, int? Partition)>(); foreach (var frame in state.FramedPartitions!) @@ -2371,8 +2371,11 @@ internal static void RecordFramedRoots(ParsingState state, foreach (var (data, start, size, classId, owner, partition) in roots) { StairComponentSource.Record(state, data, start, size, classId, owner); - if (classId is 2335 or 3971) // LinearDimString and TextNote - annotationRoots?.Add((data, start, size, classId, owner)); + if (classId is 2335 or 3971 + || classId == 3524 && partition is int partWithWall + && state.IncrementRoutedPartitions?.TryGetValue(owner, out int currentWallPartition) == true + && partWithWall == currentWallPartition) + unanchoredTypeRoots?.Add((data, start, size, classId, owner)); if (classId == 3471) { RecordRoomNameSource(state, data, start, size, classId, owner); @@ -2435,9 +2438,9 @@ internal static void RunTfStreamWalk(ParsingState state) var walkGReps = new List<(byte[] Segment, int Start, uint Size, uint Eid)>(); // the roots the class and stair sources count: the records of the project's block when every stream is read by its framing bool framedRoots = state.ReadsFramedRecords; - List<(byte[] Data, int Start, uint Size, ushort Class, uint Owner)>? annotationRoots = + List<(byte[] Data, int Start, uint Size, ushort Class, uint Owner)>? unanchoredTypeRoots = framedRoots && state.StaleCopiesRemoved ? [] : null; - if (framedRoots) RecordFramedRoots(state, annotationRoots); + if (framedRoots) RecordFramedRoots(state, unanchoredTypeRoots); TfStreamWalker.Walk(state.Chunks, state.AllKnownIds, (seg, bs, ds, cls, eid) => { uint fullClassIdx = BitConverter.ToUInt32(seg, bs + 12); @@ -2599,9 +2602,9 @@ internal static void RunTfStreamWalk(ParsingState state) // AnalyticalNodeOwners, registry category assignment. }, (seg, recordStart, eid) => ElementHeaderCategory.Record(state, seg, recordStart, eid)); - // Pruning can leave a valid annotation root where the sequential scan cannot anchor. - if (annotationRoots != null) - foreach (var (data, start, size, classId, owner) in annotationRoots) + // Pruning can leave an element's own record where the sequential scan cannot anchor. + if (unanchoredTypeRoots != null) + foreach (var (data, start, size, classId, owner) in unanchoredTypeRoots) { if (state.NativeParamsFromRootClass.Contains(owner) || !state.WalkedElementClassRoots.TryGetValue(owner, out var root) @@ -2609,6 +2612,13 @@ internal static void RunTfStreamWalk(ParsingState state) || TfBlockDeserializer.ExtractParams(data, start, size, classId) is not { } parameters || NativeTypePointers.Of(classId, parameters) is not int typeId || !state.AllKnownIds.Contains((uint)typeId)) continue; + if (classId == 3524) + { + if (TfBlockDeserializer.ExtractSystemOccurrenceTypeId(data, start, size, classId) != typeId + || state.SystemTypeRoots.GetValueOrDefault((uint)typeId) is not { BlockCount: 1, ClassId: 512 }) + continue; + state.SystemOccurrenceTypeIds[owner] = (1, classId, typeId); + } state.NativeParams[owner] = parameters; state.NativeParamsFromRootClass.Add(owner); } diff --git a/tests/RvtIO.Tests/IfcExporterBaseQuantitiesCurrentTests.cs b/tests/RvtIO.Tests/IfcExporterBaseQuantitiesCurrentTests.cs index b5450319..a1079897 100644 --- a/tests/RvtIO.Tests/IfcExporterBaseQuantitiesCurrentTests.cs +++ b/tests/RvtIO.Tests/IfcExporterBaseQuantitiesCurrentTests.cs @@ -51,6 +51,76 @@ private static GeoFace Face(params double[][] ring) private static BrepMeasures.ShellInfo SoleShell(GeometryData geometry) => Assert.Single(BrepMeasures.ShellsOfCurrent(geometry)); + [Theory] + [InlineData(true, true)] + [InlineData(false, true)] + [InlineData(true, false)] + public void FloorQuantities_UseTheMeasuredClosedBodyWithItsThroughOpening(bool hasCutStep, bool validMeasure) + { + var geometry = Box(4, 4, 1); + var opening = Box(1, 1, 1); + foreach (var face in opening.Faces) + { + foreach (var corner in face.OuterVertices!) + { + corner[0]++; + corner[1]++; + } + face.OuterVertices!.Reverse(); + } + geometry.Faces[0].InnerVertices = [opening.Faces[0].OuterVertices!]; + geometry.Faces[1].InnerVertices = [opening.Faces[1].OuterVertices!]; + geometry.Faces.AddRange(opening.Faces.Skip(2)); + geometry.BrepSolids![0].FaceIndices.AddRange(Enumerable.Range(6, 4)); + foreach (var face in geometry.Faces) face.GeometryNode = 1; + geometry.NodeMeasures = [new(1, 50, validMeasure ? 15 : 16)]; + var floor = new Element + { + CategoryId = -2000032, NativeRootClassName = "Floor", SerializedSystemTypeId = 20, Geometry = geometry, + CutOutSteps = [(4137, 30, hasCutStep)], + }; + + ElementBuilder.ApplyCutFloorQuantities(floor); + ElementBuilder.ApplyCutFloorQuantities(floor); + + if (hasCutStep && validMeasure) + { + Assert.Equal(new[] { 15d, 15d }, floor.Parameters.Select(p => Assert.IsType(p.Value))); + Assert.Equal(new[] { -1012805, -1012806 }, floor.Parameters.Select(p => p.Id)); + } + else Assert.Empty(floor.Parameters); + } + + [Theory] + [InlineData(true, 12, 1, false, true, true)] + [InlineData(true, 12, 2, false, true, false)] + [InlineData(true, 12, 1, true, true, false)] + [InlineData(false, 12, 1, false, false, false)] + [InlineData(true, 99, 1, false, false, false)] + public void FacetedBasicWall_ExportsOnlyTheSupportedMeasuredQuantities( + bool closed, double volume, double typeWidth, bool wide, bool writesVolume, bool writesArea) + { + var geometry = Box(6, 1, 2); + geometry.BrepSolids![0].IsClosed = closed; + foreach (var face in geometry.Faces) face.GeometryNode = 1; + geometry.NodeMeasures = [new(1, 40, volume)]; + var wall = new Element + { + Id = 10, CategoryId = -2000011, NativeRootClassName = wide ? "SWall" : null, SerializedOwnElementClassId = 3524, + SerializedSystemTypeId = 20, ValidatedWallTypeThicknessFeet = typeWidth, Geometry = geometry, + }; + var type = new Element { Id = 20, CategoryId = -2000011, SerializedSystemTypeClassId = 512 }; + var w = new StepWriter(); + int owner = w.Add("IFCOWNERHISTORY", "$,$,$,.ADDED.,$,$,$,0"); + int wallProduct = AddProduct(w, "IFCWALL", "1ZGD7y6S5209$mGLi_sPlj", owner, placement: 0); + + Assert.Equal(writesVolume ? 1 : 0, Apply(w, owner, new() { [10] = wall, [20] = type }, new() { [wallProduct] = 10 })); + if (writesArea) AssertQuantities(Quantities(w, "IFCQUANTITYAREA"), ("NetSideArea", 12 * SquareFeet)); + else Assert.Empty(Quantities(w, "IFCQUANTITYAREA")); + if (writesVolume) AssertQuantities(Quantities(w, "IFCQUANTITYVOLUME"), ("NetVolume", 12 * CubicFeet)); + else Assert.Empty(Quantities(w, "IFCQUANTITYVOLUME")); + } + [Fact] public void Shells_Box_HaveTheVolumeAndTheSurfaceOfTheBox() { diff --git a/tests/RvtIO.Tests/SystemTypeIdentityTests.cs b/tests/RvtIO.Tests/SystemTypeIdentityTests.cs index 995ff355..8ff77c95 100644 --- a/tests/RvtIO.Tests/SystemTypeIdentityTests.cs +++ b/tests/RvtIO.Tests/SystemTypeIdentityTests.cs @@ -47,6 +47,37 @@ public void WideFile_RecordsAnOccurrenceOnce_WhenItsTranscodedCopyIsSeenAgain() Assert.Equal((1, (ushort)3524, (int?)500), state.SystemOccurrenceTypeIds[100]); } + [Theory] + [InlineData(2, 512, false, true)] + [InlineData(3, 512, false, false)] + [InlineData(2, 2559, false, false)] + [InlineData(2, 512, true, false)] + public void RoutedBasicWall_RecoversItsOwnTypedRootBeyondTheSequentialScan( + int route, ushort typeClass, bool duplicate, bool recovered) + { + byte[] block = Block(3524); + var frame = new PartitionFraming.Framed([block], [new(102, 100, 0, block.Length)], 4, 2); + var state = new ParsingState + { + AllKnownIds = [100, 500], + ElemRecOwningElementIds = new() { [100] = -1 }, + FramedPartitions = duplicate ? [frame, frame with { Partition = 3 }] : [frame], + IncrementRoutedPartitions = new Dictionary { [100] = route }, + StaleCopiesRemoved = true, + }; + state.SystemTypeRoots[500] = (1, typeClass, null); + + RvtFileReader.RunTfStreamWalk(state); + + Assert.Equal(recovered, state.NativeParamsFromRootClass.Contains(100)); + if (recovered) + { + Assert.Equal(500, NativeTypePointers.Of(3524, state.NativeParams[100])); + Assert.Equal((1, (ushort)3524, (int?)500), state.SystemOccurrenceTypeIds[100]); + } + else Assert.False(state.SystemOccurrenceTypeIds.ContainsKey(100)); + } + [Fact] public void BoundsAreValidated_AndOtherHostRootsCannotBorrowTheField() { @@ -240,6 +271,7 @@ private static byte[] Block(ushort cls, string? mutation = null) writer.Write(100); writer.Write(0u); writer.Write(0u); writer.Write(cls); foreach (var field in TfBlockDeserializer.SerializationFields(cls)!) { + if (field.Declaring == 37 && field.Name == "m_docAccess") { writer.Write(1u); continue; } if (field.Declaring == 37 && field.Name == "m_id") { writer.Write(100); continue; } if (field.Name is "m_WallAttributesId" or "m_floorAttributesId" or "m_ceilingAttributesId") { From 6228497159fa0d06d6612f3828a13ec607a912ef Mon Sep 17 00:00:00 2001 From: mie Date: Fri, 20 Nov 2026 05:40:46 +0300 Subject: [PATCH 049/259] Prepare RvtIO 0.6.3 release --- CHANGELOG.md | 23 ++++++++++++++++++----- Directory.Build.props | 2 +- docs/rvt-to-nwc.md | 8 +++++--- 3 files changed, 24 insertions(+), 9 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f67627d5..d8ec7fe7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,24 @@ API between minor releases. ## [Unreleased] +## [0.6.3] - 2026-11-20 + +### Fixed + +- Native NWC export preserves stair containers and their component IDs, circular model lines, and area + reinforcement outlines (#282, #283, #284). +- Native NWC export includes authored grid lines and level outlines and keeps them hidden when the file + opens in Navisworks (#285). + +- Read the selected project-room record by its stored boundaries when current-copy resolution leaves it outside the + sequential scan. The current IFC profile also exports placed rooms with an explicitly empty number. +- Recover text note and linear dimension types from their unique project records when the sequential scan misses them. +- Keep room separation lines from inheriting a type from another line referenced by the current copy. + +### Changed + +- Both ready-to-run `RvtIO.Nwc` archives bundle NwcIO 0.17.0 for native visibility. + ## [0.6.2] - 2026-11-20 ### Added @@ -23,11 +41,6 @@ API between minor releases. ### Fixed -- Read the selected project-room record by its stored boundaries when current-copy resolution leaves it outside the - sequential scan. The current IFC profile also exports placed rooms with an explicitly empty number. -- Recover text note and linear dimension types from their unique project records when the sequential scan misses them. -- Keep room separation lines from inheriting a type from another line referenced by the current copy. - - Report `element-id-range` with the offending ID if an RVT has wide element IDs and no project partition storage to read the element records. diff --git a/Directory.Build.props b/Directory.Build.props index 3a2519bd..84979a3a 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -6,7 +6,7 @@ enable true true - 0.6.2 + 0.6.3 true true snupkg diff --git a/docs/rvt-to-nwc.md b/docs/rvt-to-nwc.md index 658e0429..75b55f17 100644 --- a/docs/rvt-to-nwc.md +++ b/docs/rvt-to-nwc.md @@ -10,9 +10,11 @@ Install the .NET runtime that matches the archive and run the command from the e dotnet RvtIO.Nwc.dll model.rvt model.nwc --native ``` -This mode writes placed triangles, straight model and separation lines, face normals, diffuse colours, the element tree, -IFC GlobalIds and Revit property display text. It also writes reinforcement meshes from decoded bar paths. The cache uses feet internally. It opens in NwcIO and was validated in -Navisworks Manage 2027. Export uses managed .NET code on Windows and Linux. +Native export writes placed triangles, straight and circular model lines, separation lines, reinforcement meshes +and area reinforcement outlines. It preserves the selection tree, including stair components, along with face +normals, diffuse colours, IFC GlobalIds and Revit property display text. Exported grid lines and level outlines +are hidden when the file opens. The cache uses feet internally and opens in NwcIO and Navisworks Manage 2027. +Export uses managed .NET code on Windows and Linux. ## Autodesk Navisworks From ac54f6281ddb12b41312ad86fa5c99f367217a79 Mon Sep 17 00:00:00 2001 From: Mahach <79989386+mahach666@users.noreply.github.com> Date: Sat, 21 Nov 2026 13:44:47 +0300 Subject: [PATCH 050/259] Recover remaining current-copy types and host quantities --- src/RvtIO/Geometry/BrepMeasures.cs | 22 ++++-- src/RvtIO/Geometry/FacetedShell.cs | 7 ++ .../Ifc/IfcExporter.QuantitiesCurrent.cs | 21 +++++- .../IfcExporter.QuantityGeometryCurrent.cs | 28 ++++++++ src/RvtIO/Internal/ParsingState.cs | 3 + src/RvtIO/Parsing/ElementBuilder.cs | 23 ++++++- src/RvtIO/Parsing/NativeTypePointers.cs | 1 + src/RvtIO/RvtFileReader.cs | 40 ++++++++++- .../FamilySymbolReferenceSourceTests.cs | 39 ++++++++++- .../IfcExporterBaseQuantitiesCurrentTests.cs | 69 +++++++++++++++++++ tests/RvtIO.Tests/NativeTypePointersTests.cs | 1 + tests/RvtIO.Tests/OwnElementClassTests.cs | 47 +++++++++++++ tests/RvtIO.Tests/SystemTypeIdentityTests.cs | 8 ++- 13 files changed, 290 insertions(+), 19 deletions(-) diff --git a/src/RvtIO/Geometry/BrepMeasures.cs b/src/RvtIO/Geometry/BrepMeasures.cs index 14941062..398c3c2f 100644 --- a/src/RvtIO/Geometry/BrepMeasures.cs +++ b/src/RvtIO/Geometry/BrepMeasures.cs @@ -125,21 +125,29 @@ internal static List ShellsOfCurrent(GeometryData? geometry, return result; } - /// Measures a single planar extrusion whose closed faces and stored node volume agree. - internal static (ShellPrism Prism, double Volume)? MeasuredPlanarPrism(GeometryData? geometry, bool wallSides = false) + /// Orients the complete planar shell of a single solid with a stored measure. + internal static ShellInfo? MeasuredPlanarShell(GeometryData? geometry, out double geometricVolume) { + geometricVolume = 0; if (geometry is not { UntriangulatedFaces: 0, BrepSolids: [{ IsClosed: true } solid], NodeMeasures: [{ Node: > 0, Volume: > 0 } measure] } || !double.IsFinite(measure.Volume) || solid.FaceIndices.Count != geometry.Faces.Count || geometry.Faces.Any(face => face.CurvedSurface || face.GeometryNode != measure.Node) - || !FacetedShell.TryOrientExactFacetedShell(geometry.Faces, solid.FaceIndices, out var faces, triangulateNonPlanarFaces: false)) + || !FacetedShell.TryOrientExactFacetedShell(geometry.Faces, solid.FaceIndices, + out var faces, out geometricVolume, triangulateNonPlanarFaces: false)) return null; - var shell = new ShellInfo(faces, Closed: true, measure.Volume, measure.Area); - if (FindPrismCurrent(shell, verticalOnly: !wallSides, wallSides: wallSides) is not { ProfileArea: > 0 } prism - || !(Math.Abs(prism.ProfileArea * prism.Depth - measure.Volume) <= measure.Volume * 1e-6)) + return new ShellInfo(faces, Closed: true, measure.Volume, measure.Area); + } + + /// Measures a single planar extrusion whose closed faces and stored node volume agree. + internal static (ShellPrism Prism, double Volume)? MeasuredPlanarPrism(GeometryData? geometry, bool wallSides = false) + { + if (MeasuredPlanarShell(geometry, out _) is not { } shell + || FindPrismCurrent(shell, verticalOnly: !wallSides, wallSides: wallSides) is not { ProfileArea: > 0 } prism + || !(Math.Abs(prism.ProfileArea * prism.Depth - shell.Volume) <= shell.Volume * 1e-6)) return null; - return (prism, measure.Volume); + return (prism, shell.Volume); } /// The prism of a shell: two planar faces of equal net area (within 1e-4 ft2) facing each other on diff --git a/src/RvtIO/Geometry/FacetedShell.cs b/src/RvtIO/Geometry/FacetedShell.cs index df98c046..69f277ca 100644 --- a/src/RvtIO/Geometry/FacetedShell.cs +++ b/src/RvtIO/Geometry/FacetedShell.cs @@ -61,9 +61,15 @@ internal static bool FaceCollapsesAtIfcPrecision(GeoFace face) /// internal static bool TryOrientExactFacetedShell(IReadOnlyList faces, IReadOnlyCollection faceIndices, out List orientedFaces, + bool triangulateNonPlanarFaces, HashSet<(long X, long Y, long Z)>? splitVertices = null) => + TryOrientExactFacetedShell(faces, faceIndices, out orientedFaces, out _, triangulateNonPlanarFaces, splitVertices); + + internal static bool TryOrientExactFacetedShell(IReadOnlyList faces, + IReadOnlyCollection faceIndices, out List orientedFaces, out double volume, bool triangulateNonPlanarFaces, HashSet<(long X, long Y, long Z)>? splitVertices = null) { orientedFaces = []; + volume = 0; var indices = faceIndices.Distinct().Order().ToList(); if (indices.Count < 4 || indices.Any(index => (uint)index >= faces.Count)) return false; @@ -175,6 +181,7 @@ internal static bool TryOrientExactFacetedShell(IReadOnlyList faces, if (signedVolume < 0) foreach (var face in orientedFaces) ReverseFace(face, detachVertices: true); + volume = Math.Abs(signedVolume); if (!triangulateNonPlanarFaces) return true; var triangulatedFaces = TriangulateNonPlanarFacetedFaces(orientedFaces); diff --git a/src/RvtIO/Ifc/IfcExporter.QuantitiesCurrent.cs b/src/RvtIO/Ifc/IfcExporter.QuantitiesCurrent.cs index 41f1f6c4..736ee8f7 100644 --- a/src/RvtIO/Ifc/IfcExporter.QuantitiesCurrent.cs +++ b/src/RvtIO/Ifc/IfcExporter.QuantitiesCurrent.cs @@ -1052,9 +1052,24 @@ private static List FacetedWallQuantitiesCurrent(Element wall, IR { var result = new List(); if (wall is not { CategoryId: -2000011, RootClassName: "SWall", SerializedSystemTypeId: > 0 and int typeId } - || !elements.TryGetValue(typeId, out var type) || type.SerializedSystemTypeClassId != 512 - || wall.CuttingElementIds is { Count: > 0 } - || MeasuredPlanarPrism(wall.Geometry, wallSides: true) is not { } measured) return result; + || !elements.TryGetValue(typeId, out var type) || type.SerializedSystemTypeClassId != 512) return result; + if (wall.CuttingElementIds is { Count: > 0 } cutters) + { + if (wall.CutOutSteps is not { Count: > 0 } steps + || steps.Any(step => step.Cutout && step.ClassId != 4137) + || !steps.Where(step => step.Cutout).Select(step => step.ElementId).ToHashSet().SetEquals(cutters) + || !TryGetSerializedWallWidthFeet(wall, out double cutWallWidth) + || MeasuredPlanarShell(wall.Geometry, out double geometricVolume) is not { } shell) return result; + // Through-cuts need not be perpendicular to the wall sides. + double area = LargestVerticalFaceAreaCurrent([shell]); + if (!(Math.Abs(area * cutWallWidth - shell.Volume) <= shell.Volume * 1e-6) + && (!(Math.Abs(geometricVolume - shell.Volume) <= shell.Volume * 1e-6) + || !HasOpposedWallSidePlanes(shell, area, cutWallWidth))) return result; + AddIfPositive(result, QuantityKind.Area, "NetSideArea", area * SquareFeetToSquareMetres); + AddIfPositive(result, QuantityKind.Volume, "NetVolume", shell.Volume * CubicFeetToCubicMetres); + return result; + } + if (MeasuredPlanarPrism(wall.Geometry, wallSides: true) is not { } measured) return result; // A closed body establishes volume. For the legacy layout, admit its side as the area // only when the extrusion follows the stored thickness of the wall type. if (wall.NativeRootClassName == null && TryGetSerializedWallWidthFeet(wall, out double width) diff --git a/src/RvtIO/Ifc/IfcExporter.QuantityGeometryCurrent.cs b/src/RvtIO/Ifc/IfcExporter.QuantityGeometryCurrent.cs index 41f33fda..574f0631 100644 --- a/src/RvtIO/Ifc/IfcExporter.QuantityGeometryCurrent.cs +++ b/src/RvtIO/Ifc/IfcExporter.QuantityGeometryCurrent.cs @@ -34,6 +34,34 @@ internal static double LargestVerticalFaceAreaCurrent(IEnumerable she shells.Sum(shell => FaceAreasCurrent(shell.Faces.Where(face => !face.CurvedSurface && FaceUnitNormal(face) is { } n && Math.Abs(n[2]) < 1e-9)) .DefaultIfEmpty(0).Max()); + private static bool HasOpposedWallSidePlanes(ShellInfo shell, double sideArea, double width) + { + const double planeTolerance = 1e-6; + foreach (var side in shell.Faces) + { + if (NetFaceArea(side) != sideArea + || FaceUnitNormal(side) is not { } normal || Math.Abs(normal[2]) >= 1e-9) continue; + var point = side.OuterVertices![0]; + double Offset(double[] v) => (v[0] - point[0]) * normal[0] + + (v[1] - point[1]) * normal[1] + (v[2] - point[2]) * normal[2]; + foreach (var other in shell.Faces) + { + if (FaceUnitNormal(other) is not { } n + || normal[0] * n[0] + normal[1] * n[1] + normal[2] * n[2] > -1 + 1e-9) continue; + double offset = Offset(other.OuterVertices![0]); + if (Math.Abs(offset + width) <= planeTolerance + && NetFaceArea(other) is { } oppositeArea + && Math.Abs((sideArea + oppositeArea) * width / 2 - shell.Volume) <= shell.Volume * 1e-6 + && shell.Faces.All(face => face.OuterVertices!.All(vertex => + { + double distance = Offset(vertex); + return distance >= offset - planeTolerance && distance <= planeTolerance; + }))) return true; + } + } + return false; + } + /// An exact end face: a planar face that carries the area of the Revit face (). private static bool IsExactCap(GeoFace face) => face.PlaneSurface && face.QuadratureArea != null && face.OuterVertices is { Count: >= 3 }; diff --git a/src/RvtIO/Internal/ParsingState.cs b/src/RvtIO/Internal/ParsingState.cs index 2e83cfb2..c03c2917 100644 --- a/src/RvtIO/Internal/ParsingState.cs +++ b/src/RvtIO/Internal/ParsingState.cs @@ -91,6 +91,9 @@ public TfBlockDeserializer.UnitsElemOptions? OwnDocumentUnitOptions /// a null value marks an id whose records disagree or whose header could not be read. public Dictionary HeaderCategories { get; } = new(); + // Categories proved by the current project's own framed header and a compatible root. + internal Dictionary CurrentFramedCategories { get; } = new(); + /// ElementHeader.m_designOptionId per element id (files with 64-bit ids; null: the records of the id disagree). public Dictionary HeaderDesignOptions { get; } = new(); diff --git a/src/RvtIO/Parsing/ElementBuilder.cs b/src/RvtIO/Parsing/ElementBuilder.cs index 3f88173d..40859c49 100644 --- a/src/RvtIO/Parsing/ElementBuilder.cs +++ b/src/RvtIO/Parsing/ElementBuilder.cs @@ -6833,7 +6833,8 @@ private static void FixCategoryFromClassIdx(RevitFileInfo info, ParsingState? st { if (e.Id < 0) continue; int cat; - if (useHeader && e.NativeHeaderCategoryId is int header && header != -1) cat = header; + if (state.CurrentFramedCategories.GetValueOrDefault((uint)e.Id) is int current) cat = current; + else if (useHeader && e.NativeHeaderCategoryId is int header && header != -1) cat = header; else if (!state.ElemClassIdx.TryGetValue((uint)e.Id, out var cls) || !TfClassRegistry.HighPurityClassCategory.TryGetValue(cls, out cat)) continue; if (e.CategoryId == cat && (e.Id != 0 || e.Parameters.Any(p => p.Id == -1140362))) continue; @@ -6893,7 +6894,14 @@ private static void ComputeSketchQuantities(RevitFileInfo info, ParsingState? st if (sk == null && e.References != null) foreach (var r in e.References) if (byId.TryGetValue(r, out var re) && re.SketchLoops != null) { sk = re.SketchLoops; break; } - if (sk == null || sk.Count == 0) continue; + if (sk == null || sk.Count == 0) + { + if (state is { StaleCopiesRemoved: true } + && e.References?.Any(r => r > 0 + && state.WalkedElementClassRoots.GetValueOrDefault((uint)r) is { BlockCount: 1, ClassId: 4065 }) == true) + ApplyUnsketchedFloorArea(e); + continue; + } double outerA = 0, sumA = 0, outerP = 0; foreach (var loop in sk) @@ -6938,6 +6946,17 @@ private static void ComputeSketchQuantities(RevitFileInfo info, ParsingState? st } } + internal static void ApplyUnsketchedFloorArea(Element floor) + { + if (floor is not { CategoryId: -2000032, RootClassName: "Floor", SerializedSystemTypeId: > 0 } + || floor.CuttingElementIds is { Count: > 0 } + || floor.CutOutSteps?.Any(step => step.Cutout) == true + || floor.Parameters.Any(p => p.Id == -1012805) + || BrepMeasures.MeasuredPlanarPrism(floor.Geometry) is not ({ InnerPerimeter: 0 } prism, _)) return; + + floor.Parameters.Add(BipHelpers.MakeBipParam(-1012805, "HOST_AREA_COMPUTED", StorageType.Double, prism.ProfileArea)); + } + internal static void ApplyCutFloorQuantities(Element floor) { if (floor.CutOutSteps?.Any(step => step.Cutout) != true diff --git a/src/RvtIO/Parsing/NativeTypePointers.cs b/src/RvtIO/Parsing/NativeTypePointers.cs index 2802e238..ee5c36f7 100644 --- a/src/RvtIO/Parsing/NativeTypePointers.cs +++ b/src/RvtIO/Parsing/NativeTypePointers.cs @@ -24,6 +24,7 @@ internal static class NativeTypePointers [993] = "108:m_dbViewTypeId", [995] = "108:m_dbViewTypeId", [1004] = "108:m_dbViewTypeId", + [1005] = "108:m_dbViewTypeId", [1011] = "108:m_dbViewTypeId", [1016] = "108:m_dbViewTypeId", [1322] = "422:m_groupId", diff --git a/src/RvtIO/RvtFileReader.cs b/src/RvtIO/RvtFileReader.cs index 94e6baf4..5cc77310 100644 --- a/src/RvtIO/RvtFileReader.cs +++ b/src/RvtIO/RvtFileReader.cs @@ -2373,9 +2373,9 @@ internal static void RecordFramedRoots(ParsingState state, { StairComponentSource.Record(state, data, start, size, classId, owner); if (classId is 2335 or 3971 - || classId == 3524 && partition is int partWithWall - && state.IncrementRoutedPartitions?.TryGetValue(owner, out int currentWallPartition) == true - && partWithWall == currentWallPartition) + || classId is 1005 or 3524 && partition is int partWithType + && (state.IncrementRoutedPartitions?.TryGetValue(owner, out int currentTypePartition) != true + || partWithType == currentTypePartition)) unanchoredTypeRoots?.Add((data, start, size, classId, owner)); if (classId == 3471) { @@ -2400,6 +2400,33 @@ internal static void RecordFramedRoots(ParsingState state, } foreach (var (data, start, size, classId, owner, _) in roots) if (classId is 3524 or 361) RecordWallLocationLine(state, data, start, size, classId, owner); + + if (!state.StaleCopiesRemoved) return; + foreach (var frame in state.FramedPartitions) + foreach (var record in frame!.Items) + { + if (record.Channel != 101 || record.Owner > uint.MaxValue) continue; + uint owner = (uint)record.Owner; + if (state.WalkedElementClassRoots.GetValueOrDefault(owner) is not { BlockCount: 1, ClassId: 1794 or 3061 } own + || state.IncrementRoutedPartitions?.TryGetValue(owner, out int currentPartition) == true + && frame.Partition != currentPartition) + continue; + var (data, start, _) = frame.Bytes(record); + int? category = ElementHeaderCategory.Read(data, start); + // These categories are carried by the header of the occurrence, independently of the type. + if (!(own.ClassId == 1794 && category is -2000150 or -2002000 + || own.ClassId == 3061 && category == -2003101)) + category = null; + if (!state.CurrentFramedCategories.TryAdd(owner, category) + && state.CurrentFramedCategories[owner] != category) + state.CurrentFramedCategories[owner] = null; + } + if (unanchoredTypeRoots != null) + foreach (var (data, start, size, classId, owner, partition) in roots) + if (classId == 1794 && state.CurrentFramedCategories.GetValueOrDefault(owner) == -2000150 + && (state.IncrementRoutedPartitions?.TryGetValue(owner, out int currentPartition) != true + || partition == currentPartition)) + unanchoredTypeRoots.Add((data, start, size, classId, owner)); } /// Hands the channel-102 and 103 records of the project's own block (the root objects and the @@ -2622,6 +2649,13 @@ internal static void RunTfStreamWalk(ParsingState state) continue; state.SystemOccurrenceTypeIds[owner] = (1, classId, typeId); } + if (classId == 1005 + && state.WalkedElementClassRoots.GetValueOrDefault((uint)typeId) is not { BlockCount: 1, ClassId: 1020 }) + continue; + if (classId == 1794 + && (TfBlockDeserializer.ExtractFamilyInstanceSymbolId(data, start, size, classId) != typeId + || state.WalkedElementClassRoots.GetValueOrDefault((uint)typeId) is not { BlockCount: 1, ClassId: 1829 })) + continue; state.NativeParams[owner] = parameters; state.NativeParamsFromRootClass.Add(owner); } diff --git a/tests/RvtIO.Tests/FamilySymbolReferenceSourceTests.cs b/tests/RvtIO.Tests/FamilySymbolReferenceSourceTests.cs index 35c624da..0bf31509 100644 --- a/tests/RvtIO.Tests/FamilySymbolReferenceSourceTests.cs +++ b/tests/RvtIO.Tests/FamilySymbolReferenceSourceTests.cs @@ -8,6 +8,42 @@ namespace RvtIO.Tests; public class FamilySymbolReferenceSourceTests { + [Theory] + [InlineData(-2000150, true, false, true)] + [InlineData(-2000150, false, false, false)] + [InlineData(-2000150, true, true, false)] + [InlineData(-2002000, true, false, false)] + public void CurrentFramedAnnotationUsesItsOwnUnambiguousSymbol( + int category, bool hasSymbol, bool duplicate, bool recovered) + { + var header = new byte[22]; + BitConverter.GetBytes(100u).CopyTo(header, 0); + BitConverter.GetBytes(10u).CopyTo(header, 4); + BitConverter.GetBytes((ushort)0x053C).CopyTo(header, 8); + BitConverter.GetBytes(category).CopyTo(header, 14); + BitConverter.GetBytes(10u).CopyTo(header, 18); + byte[] root = Block(1794, project: true), symbol = Block(1829, project: true); + var instance = new PartitionFraming.Framed([[.. header, .. root]], + [new(101, 100, 0, header.Length), new(102, 100, header.Length, root.Length)], 4, 2); + var frames = new List { instance }; + if (hasSymbol) frames.Add(new([symbol], [new(102, 500, 0, symbol.Length)], 4, 1)); + if (duplicate) frames.Add(instance with { Partition = 3 }); + var state = new ParsingState + { + AllKnownIds = [100, 500], + ElemRecOwningElementIds = new() { [100] = -1, [500] = -1 }, + FramedPartitions = frames, + StaleCopiesRemoved = true, + }; + var annotation = new Element { Id = 100, TypeId = 123, CategoryId = category }; + + RvtFileReader.RunTfStreamWalk(state); + ElementBuilder.ApplyNativeParams(new RevitFileInfo { Elements = [annotation] }, state); + + Assert.Equal(recovered, state.NativeParamsFromRootClass.Contains(100)); + Assert.Equal(recovered ? 500 : 123, annotation.TypeId); + } + [Fact] public void DoorNameAfterCanonicalizationUsesTheOwnSymbolNameRatherThanAnEarlierTypeGuess() { @@ -233,7 +269,7 @@ private static ParsingState State() private static void Record(ParsingState state, byte[] block) => RvtFileReader.RecordFamilySymbolReferenceSource( state, block, 0, Size(block), BitConverter.ToUInt16(block,12), BitConverter.ToUInt32(block,0)); - private static byte[] Block(ushort cls, string? mutation = null) + private static byte[] Block(ushort cls, string? mutation = null, bool project = false) { using var stream = new MemoryStream(); using var writer = new BinaryWriter(stream); int owner = cls == 1794 ? 100 : 500; @@ -242,6 +278,7 @@ private static byte[] Block(ushort cls, string? mutation = null) foreach (var field in TfBlockDeserializer.SerializationFields(cls)!) { if (field.Declaring == 37 && field.Name == "m_id") { writer.Write(owner); continue; } + if (project && field.Declaring == 37 && field.Name == "m_docAccess") { writer.Write(1u); continue; } if (mutation == "truncated_root" && field.Name == (cls == 1794 ? "m_masterSymbolId" : "m_subInstData")) break; if (field.Declaring == 1794 && field.Name == "m_masterSymbolId") { writer.Write(mutation switch { "zero_type" => 0, "negative_type" => -1, "self_type" => owner, _ => 500 }); continue; } diff --git a/tests/RvtIO.Tests/IfcExporterBaseQuantitiesCurrentTests.cs b/tests/RvtIO.Tests/IfcExporterBaseQuantitiesCurrentTests.cs index a1079897..d8b79316 100644 --- a/tests/RvtIO.Tests/IfcExporterBaseQuantitiesCurrentTests.cs +++ b/tests/RvtIO.Tests/IfcExporterBaseQuantitiesCurrentTests.cs @@ -91,6 +91,36 @@ public void FloorQuantities_UseTheMeasuredClosedBodyWithItsThroughOpening(bool h else Assert.Empty(floor.Parameters); } + [Theory] + [InlineData(true, 12, false, true)] + [InlineData(false, 12, false, false)] + [InlineData(true, 40, false, false)] + [InlineData(true, 12, true, false)] + public void FloorAreaWithoutASketch_RequiresAMeasuredClosedPrismWithoutCutters( + bool closed, double measuredVolume, bool cut, bool recover) + { + var geometry = Box(4, 3, 1); + geometry.BrepSolids![0].IsClosed = closed; + foreach (var face in geometry.Faces) face.GeometryNode = 1; + geometry.NodeMeasures = [new(1, 38, measuredVolume)]; + var floor = new Element + { + CategoryId = -2000032, NativeRootClassName = "Floor", SerializedSystemTypeId = 20, Geometry = geometry, + CuttingElementIds = cut ? [30] : [], + }; + + ElementBuilder.ApplyUnsketchedFloorArea(floor); + ElementBuilder.ApplyUnsketchedFloorArea(floor); + + if (recover) + { + var parameter = Assert.Single(floor.Parameters); + Assert.Equal(-1012805, parameter.Id); + Assert.Equal(12, Assert.IsType(parameter.Value)); + } + else Assert.Empty(floor.Parameters); + } + [Theory] [InlineData(true, 12, 1, false, true, true)] [InlineData(true, 12, 2, false, true, false)] @@ -121,6 +151,45 @@ public void FacetedBasicWall_ExportsOnlyTheSupportedMeasuredQuantities( else Assert.Empty(Quantities(w, "IFCQUANTITYVOLUME")); } + [Theory] + [InlineData(4137, 30, 12, false, 1, true)] + [InlineData(4137, 31, 12, false, 1, false)] + [InlineData(977, 30, 12, false, 1, false)] + [InlineData(4137, 30, 99, false, 1, false)] + [InlineData(4137, 30, 12.3, true, 1, true)] + [InlineData(4137, 30, 12.5, true, 1, false)] + [InlineData(4137, 30, 12.3, true, 2, false)] + public void FacetedCutWall_RequiresTheRecordedCutsAndMatchingVolume( + ushort cutterClass, int cutterId, double volume, bool slopedCut, double typeWidth, bool writesQuantities) + { + var geometry = Box(6, 1, 2); + foreach (var face in geometry.Faces) + { + face.GeometryNode = 1; + if (!slopedCut) continue; + foreach (var vertex in face.OuterVertices!) + if (vertex[1] == 1 && vertex[2] == 2) vertex[2] = 2.1; + } + geometry.NodeMeasures = [new(1, 40, volume)]; + var wall = new Element + { + Id = 10, CategoryId = -2000011, SerializedOwnElementClassId = 3524, SerializedSystemTypeId = 20, + ValidatedWallTypeThicknessFeet = typeWidth, Geometry = geometry, + CuttingElementIds = [30], CutOutSteps = [(cutterClass, cutterId, true)], + }; + var type = new Element { Id = 20, CategoryId = -2000011, SerializedSystemTypeClassId = 512 }; + var w = new StepWriter(); + int owner = w.Add("IFCOWNERHISTORY", "$,$,$,.ADDED.,$,$,$,0"); + int wallProduct = AddProduct(w, "IFCWALL", "1ZGD7y6S5209$mGLi_sPlj", owner, placement: 0); + + Assert.Equal(writesQuantities ? 1 : 0, Apply(w, owner, new() { [10] = wall, [20] = type }, new() { [wallProduct] = 10 })); + if (writesQuantities) + { + AssertQuantities(Quantities(w, "IFCQUANTITYAREA"), ("NetSideArea", (slopedCut ? 12.6 : 12) * SquareFeet)); + AssertQuantities(Quantities(w, "IFCQUANTITYVOLUME"), ("NetVolume", volume * CubicFeet)); + } + } + [Fact] public void Shells_Box_HaveTheVolumeAndTheSurfaceOfTheBox() { diff --git a/tests/RvtIO.Tests/NativeTypePointersTests.cs b/tests/RvtIO.Tests/NativeTypePointersTests.cs index fe308b41..11535a87 100644 --- a/tests/RvtIO.Tests/NativeTypePointersTests.cs +++ b/tests/RvtIO.Tests/NativeTypePointersTests.cs @@ -19,6 +19,7 @@ private static TfBlockDeserializer.NativeParams With(string key, int value) [InlineData(3475, "3475:m_symbolId")] // room tag [InlineData(527, "527:m_symbolId")] // independent tag [InlineData(804, "804:m_typeId")] // continuous footing + [InlineData(1005, "108:m_dbViewTypeId")] // plan view [InlineData(3111, "3111:m_stairsAttrId")] // stairs in the wide schema [InlineData(3989, "823:m_typeId")] // continuous rail type public void TypeIdIsTheFieldOfTheRootClass(ushort rootClass, string key) diff --git a/tests/RvtIO.Tests/OwnElementClassTests.cs b/tests/RvtIO.Tests/OwnElementClassTests.cs index c93fea8b..3b7c8ea0 100644 --- a/tests/RvtIO.Tests/OwnElementClassTests.cs +++ b/tests/RvtIO.Tests/OwnElementClassTests.cs @@ -1,4 +1,5 @@ using RvtIO.Internal; +using RvtIO.Model; using RvtIO.Parsing; using Xunit; @@ -307,6 +308,52 @@ public void TextNoteType_UsesAnUnambiguousFramedRootWhenTheScanCannotAnchor(bool else Assert.Equal(style, NativeTypePointers.Of(textNote, state.NativeParams[123])); } + [Theory] + [InlineData(1794, -2002000, true, false)] + [InlineData(1794, -2000150, true, false)] + [InlineData(3061, -2003101, true, false)] + [InlineData(1794, -2003101, false, false)] + [InlineData(1794, -2000150, false, true)] + public void CategoryComesFromTheCompatibleCurrentProjectHeader( + ushort rootClass, int category, bool accepted, bool conflictingHeader) + { + byte[] root = Frame(rootClass); + byte[] Header(int value) + { + var header = new byte[22]; + BitConverter.GetBytes(123u).CopyTo(header, 0); + BitConverter.GetBytes(10u).CopyTo(header, 4); + BitConverter.GetBytes((ushort)0x053C).CopyTo(header, 8); + BitConverter.GetBytes(value).CopyTo(header, 14); + BitConverter.GetBytes(10u).CopyTo(header, 18); + return header; + } + + byte[] header = Header(category); + var frame = new PartitionFraming.Framed([[.. header, .. root]], + [new(101, 123, 0, header.Length), new(102, 123, header.Length, root.Length)], 4, 2); + byte[] other = Header(-2000700); + var conflict = new PartitionFraming.Framed([other], [new(101, 123, 0, other.Length)], 4, 3); + var state = new ParsingState + { + AllKnownIds = [123], + ElemRecOwningElementIds = new() { [123] = -1 }, + FramedPartitions = conflictingHeader ? [frame, conflict] : [frame], + StaleCopiesRemoved = true, + }; + var element = new Element { Id = 123 }; + + RvtFileReader.RunTfStreamWalk(state); + ElementBuilder.PostProcess(new RevitFileInfo { Elements = [element] }, state); + + Assert.Equal(accepted ? (int?)category : null, state.CurrentFramedCategories.GetValueOrDefault(123u)); + if (accepted) + { + Assert.Equal(category, element.CategoryId); + Assert.Equal(category, element.Parameters.Single(p => p.Id == -1140362).Value); + } + } + private static uint Size(byte[] bytes) => BitConverter.ToUInt32(bytes, 8); private static void Reject(byte[] bytes, ushort cls) diff --git a/tests/RvtIO.Tests/SystemTypeIdentityTests.cs b/tests/RvtIO.Tests/SystemTypeIdentityTests.cs index 8ff77c95..b0b68839 100644 --- a/tests/RvtIO.Tests/SystemTypeIdentityTests.cs +++ b/tests/RvtIO.Tests/SystemTypeIdentityTests.cs @@ -52,8 +52,10 @@ public void WideFile_RecordsAnOccurrenceOnce_WhenItsTranscodedCopyIsSeenAgain() [InlineData(3, 512, false, false)] [InlineData(2, 2559, false, false)] [InlineData(2, 512, true, false)] - public void RoutedBasicWall_RecoversItsOwnTypedRootBeyondTheSequentialScan( - int route, ushort typeClass, bool duplicate, bool recovered) + [InlineData(null, 512, false, true)] + [InlineData(null, 512, true, false)] + public void UniqueCurrentBasicWall_RecoversItsOwnTypedRootBeyondTheSequentialScan( + int? route, ushort typeClass, bool duplicate, bool recovered) { byte[] block = Block(3524); var frame = new PartitionFraming.Framed([block], [new(102, 100, 0, block.Length)], 4, 2); @@ -62,7 +64,7 @@ public void RoutedBasicWall_RecoversItsOwnTypedRootBeyondTheSequentialScan( AllKnownIds = [100, 500], ElemRecOwningElementIds = new() { [100] = -1 }, FramedPartitions = duplicate ? [frame, frame with { Partition = 3 }] : [frame], - IncrementRoutedPartitions = new Dictionary { [100] = route }, + IncrementRoutedPartitions = route is int partition ? new Dictionary { [100] = partition } : null, StaleCopiesRemoved = true, }; state.SystemTypeRoots[500] = (1, typeClass, null); From 25a3e93bf3226b26daeea646a009a6ea69cae85d Mon Sep 17 00:00:00 2001 From: mahach666 <79989386+mahach666@users.noreply.github.com> Date: Sat, 21 Nov 2026 14:36:38 +0300 Subject: [PATCH 051/259] Export Site families as IFC building element proxies --- CHANGELOG.md | 1 + src/RvtIO/Ifc/IfcExporter.cs | 3 +- ...rterGeometrylessProductSuppressionTests.cs | 11 +++---- .../IfcExporterSiteLocationTests.cs | 33 +++++++++++++++++++ 4 files changed, 40 insertions(+), 8 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d8ec7fe7..fd3648c3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -241,6 +241,7 @@ The text of a sheet prints too: a text note's RTF string (class 0x0F83 block) is ### Fixed +- IFC2X3 export writes Site-category family instances as `IfcBuildingElementProxy` with their existing `GlobalId`. Exportable topography still supplies the project `IfcSite`. Refs #234. - Printing: `rvtio print` refuses an output path that is the input file by file identity (`ExportReport.SameFile`), so a hard link, symbolic link or junction to the model is no longer truncated when the PDF is written; the PDF is written to a temporary file beside the target and moved over it, so a failed write leaves the target as it was. A regression test creates a hard link and checks that the model keeps its bytes. - Printing: a view the layout reduces to fit its place no longer claims its nominal scale. The title of a reduced plan, elevation or section, the scale row of the title block and the plan page title name the scale the geometry is printed at (a 100 ft wall at 1:100 reduced onto A4 prints at about 1:117 and says so); a drawing the layout moves or reduces is also kept inside the page frame and clear of the title block strip, annotations included. The title block strip is drawn over the drawings, so no line runs under it. - Parsing: the RTF reader decodes the standard `ansicpg` code page word (`ansicp` stays an alias), keeps each code page run apart so the bytes of two pages are not decoded together, and handles `\uNNNN` escapes with their `\ucN` fallback count (including `\uc0` and the group scope of `\ucN`), so a Unicode character is not decoded again with the code page bytes. diff --git a/src/RvtIO/Ifc/IfcExporter.cs b/src/RvtIO/Ifc/IfcExporter.cs index 679e3e4e..56d00373 100644 --- a/src/RvtIO/Ifc/IfcExporter.cs +++ b/src/RvtIO/Ifc/IfcExporter.cs @@ -64047,7 +64047,6 @@ private static void ExportWallCommonPropertySet( $"{S(IfcGuid.FromName($"wall-common-rel:{elem.Id}"))},{R(ownerHistId)},$,$,{StepWriter.List(R(elemEntityId))},{R(psetId)}"); } - /// IFCSITE here is a site-category family instance, not the project's site. private static readonly HashSet ExportIdProductClasses = new(StringComparer.Ordinal) { "IFCWALL", "IFCWALLSTANDARDCASE", "IFCCURTAINWALL", "IFCSLAB", "IFCROOF", "IFCFOOTING", @@ -68516,7 +68515,7 @@ private static double ConvexIntersectionAreaOf((double X, double Y)[] subject, ( -2001160 => "IFCFLOWTERMINAL", // OST_PlumbingFixtures 1333/1333 -2001120 => "IFCFLOWTERMINAL", // OST_LightingFixtures -2001040 => "IFCBUILDINGELEMENTPROXY", // OST_ElectricalEquipment - -2001260 => "IFCSITE", // OST_Site family instances + -2001260 => "IFCBUILDINGELEMENTPROXY", // OST_Site family instances -2001340 => "IFCSITE", // OST_Topography (surface model) -2001360 => "IFCBUILDINGELEMENTPROXY", // OST_Planting / RPC -2001263 => "IFCSLAB", // OST_BuildingPad diff --git a/tests/RvtIO.Tests/IfcExporterGeometrylessProductSuppressionTests.cs b/tests/RvtIO.Tests/IfcExporterGeometrylessProductSuppressionTests.cs index 15d16360..18312306 100644 --- a/tests/RvtIO.Tests/IfcExporterGeometrylessProductSuppressionTests.cs +++ b/tests/RvtIO.Tests/IfcExporterGeometrylessProductSuppressionTests.cs @@ -153,7 +153,7 @@ public void Predicate_ExemptsAggregateParentsOfEveryElementClass(string ifcType) } [Fact] - public void RepresentationlessSiteProduct_IsNotSuppressed() + public void RepresentationlessSiteFamily_IsSuppressed() { var info = new RevitFileInfo(); info.Elements.Add(SiteInstance(id: 330, typeId: 331)); @@ -165,10 +165,9 @@ public void RepresentationlessSiteProduct_IsNotSuppressed() new IfcExporter(diagnostics).Export(info, path); string ifc = File.ReadAllText(path); - // Two IFCSITE entities: the spatial container written for every file, plus this - // representation-less site product from the element loop. - Assert.Equal(2, Regex.Matches(ifc, @"#\d+=IFCSITE\(").Count); - Assert.Contains("IFC geometry-less element products suppressed: 0", diagnostics.ToString()); + Assert.Single(Regex.Matches(ifc, @"#\d+=IFCSITE\(")); + Assert.DoesNotContain("=IFCBUILDINGELEMENTPROXY(", ifc); + Assert.Contains("IFC geometry-less element products suppressed: 1 - IFCBUILDINGELEMENTPROXY=1", diagnostics.ToString()); } finally { Cleanup(path); } } @@ -899,7 +898,7 @@ private static Element SiteInstance(int id, int typeId) => Id = id, TypeId = typeId, IsDiscovered = true, - CategoryId = -2001260, // OST_Site family instances -> IFCSITE + CategoryId = -2001260, // OST_Site Category = "OST_Site", Name = "SiteType", FamilyName = "SiteFamily", diff --git a/tests/RvtIO.Tests/IfcExporterSiteLocationTests.cs b/tests/RvtIO.Tests/IfcExporterSiteLocationTests.cs index af760d08..f0bfb046 100644 --- a/tests/RvtIO.Tests/IfcExporterSiteLocationTests.cs +++ b/tests/RvtIO.Tests/IfcExporterSiteLocationTests.cs @@ -1,4 +1,5 @@ using System.Text.RegularExpressions; +using RvtIO.BuiltIns; using RvtIO.Ifc; using RvtIO.Model; using Xunit; @@ -45,6 +46,38 @@ private static (string Origin, string AxisArgs, string RefDirection) SitePlaceme private static string SiteArgs(string ifc) => Regex.Match(ifc, @"#\d+=IFCSITE\((.*?)\);").Groups[1].Value; + [SkippableFact] + public void Export_TopographyIsTheProjectSiteAndSiteFamilyKeepsItsGlobalIdAsProxy() + { + var info = new RvtFileReader().Read(TestFiles.Find("Test_2022.rvt")); + var family = info.Elements.OrderBy(element => element.Id).First(element => + element.CategoryId == (int)BuiltInCategory.OST_Site && element.RootClassName == "FamilyInstance" + && !element.IsDiscovered && !element.IsBlockOnly && element.Geometry?.Faces.Count > 0); + string globalId = IfcGuid.ToIfcGuid(Assert.IsType(family.SerializedExportId)); + + using var output = new StringWriter(); + new IfcExporter { Profile = IfcProfile.Current }.Export(info, output); + var entities = Entities(output.ToString()); + + var proxy = Assert.Single(entities, entity => entity.Value.Args.StartsWith($"'{globalId}',", StringComparison.Ordinal)); + Assert.Equal("IFCBUILDINGELEMENTPROXY", proxy.Value.Type); + string[] proxyArgs = IfcExporter.SplitStepArguments(proxy.Value.Args); + Assert.Equal("IFCPRODUCTDEFINITIONSHAPE", entities[Ref(proxyArgs[6])].Type); + Assert.Contains(entities.Values, entity => entity.Type == "IFCRELCONTAINEDINSPATIALSTRUCTURE" + && IfcExporter.SplitStepArguments(entity.Args) is var containment + && IfcExporter.SplitStepArguments(containment[4][1..^1]).Contains($"#{proxy.Key}") + && entities[Ref(containment[5])].Type == "IFCBUILDINGSTOREY"); + + var site = Assert.Single(entities, entity => entity.Value.Type == "IFCSITE"); + string[] siteArgs = IfcExporter.SplitStepArguments(site.Value.Args); + Assert.Contains(info.Elements, element => element.CategoryId == (int)BuiltInCategory.OST_Topography + && siteArgs[2].EndsWith($":{element.Id}'", StringComparison.Ordinal)); + Assert.Equal("IFCPRODUCTDEFINITIONSHAPE", entities[Ref(siteArgs[6])].Type); + int projectId = Assert.Single(entities, entity => entity.Value.Type == "IFCPROJECT").Key; + Assert.Contains(entities.Values, entity => entity.Type == "IFCRELAGGREGATES" + && entity.Args.EndsWith($",#{projectId},(#{site.Key})", StringComparison.Ordinal)); + } + private static readonly double[] CcTransform = [1.0, 0, 0, 0, 1.0, 0, 0, 0, 1.0, 343696.5743381642, 283643.7554585116, 11.975065616797893]; From c594a380c9b46497c4c8e768365fcc1d0a9c0959 Mon Sep 17 00:00:00 2001 From: mie <79989386+mahach666@users.noreply.github.com> Date: Sat, 21 Nov 2026 16:10:55 +0300 Subject: [PATCH 052/259] Recover stored schedule type IDs --- src/RvtIO/Parsing/TfBlockDeserializer.cs | 11 ++ src/RvtIO/RvtFileReader.cs | 50 ++++++- .../ScheduleTypeSerializationTests.cs | 127 ++++++++++++++++++ 3 files changed, 183 insertions(+), 5 deletions(-) create mode 100644 tests/RvtIO.Tests/ScheduleTypeSerializationTests.cs diff --git a/src/RvtIO/Parsing/TfBlockDeserializer.cs b/src/RvtIO/Parsing/TfBlockDeserializer.cs index 3a90f02b..e88343d6 100644 --- a/src/RvtIO/Parsing/TfBlockDeserializer.cs +++ b/src/RvtIO/Parsing/TfBlockDeserializer.cs @@ -4819,6 +4819,17 @@ private static bool TryFieldOverride(Cursor c, TfField f, List<(ushort, uint)> q { switch (f.Declaring, f.Name) { + // The R22 table omits the item type: a color and an ElementId, both four bytes. + case (1013, "m_colorToCategoryIdMap") when c.RootClassId == 1012 + && f is { Type: 14, Mods: 80, Ref: null, Cnt: null }: + { + uint count = ReadU32(c); + if (count == uint.MaxValue) return true; + long bytes = count * 8L; + if (bytes > c.End - c.Pos) throw Fail; + c.Pos += (int)bytes; + return true; + } // A mullion's nominal axis belongs to the first reference of its own symbol, not its trimmed solid. case (1829, "m_refs") when IsSubclassOf(c.RootClassId, 1829) && f.Type == 14 && f.Mods == 81 && ReferenceEquals(queue, c.RootQueue): diff --git a/src/RvtIO/RvtFileReader.cs b/src/RvtIO/RvtFileReader.cs index 5cc77310..0328ee48 100644 --- a/src/RvtIO/RvtFileReader.cs +++ b/src/RvtIO/RvtFileReader.cs @@ -2372,10 +2372,11 @@ internal static void RecordFramedRoots(ParsingState state, foreach (var (data, start, size, classId, owner, partition) in roots) { StairComponentSource.Record(state, data, start, size, classId, owner); - if (classId is 2335 or 3971 + if (classId == 1012 && state.WideSchema == null + || state.StaleCopiesRemoved && (classId is 2335 or 3971 || classId is 1005 or 3524 && partition is int partWithType && (state.IncrementRoutedPartitions?.TryGetValue(owner, out int currentTypePartition) != true - || partWithType == currentTypePartition)) + || partWithType == currentTypePartition))) unanchoredTypeRoots?.Add((data, start, size, classId, owner)); if (classId == 3471) { @@ -2450,6 +2451,42 @@ internal static void ParseFramedBlocks(ParsingState state, bool collectBlockOnly pending.RemoveRange(queued, pending.Count - queued); } } + private static void RecoverFramedScheduleTypes(ParsingState state, + List<(byte[] Data, int Start, uint Size, ushort Class, uint Owner)> roots) + { + const string typeField = "m_dbViewTypeId"; + foreach (var schedule in roots.Where(root => root.Class == 1012).GroupBy(root => root.Owner)) + { + uint owner = schedule.Key; + state.NativeParams.TryGetValue(owner, out var native); + if (state.ElemClassIdx.GetValueOrDefault(owner) != 1012 + || (native?.Fields.GetValueOrDefault(typeField) ?? 0) > 0 + || state.WalkedElementClassRoots.GetValueOrDefault(owner)?.BlockCount != schedule.Count()) + continue; + + // Without pruning, the remaining project copies must agree on the stored reference. + int typeId = 0; + foreach (var (data, start, size, classId, _) in schedule) + { + if (!TfBlockDeserializer.TryExtractOwnElementClass(data, start, size, classId, out int ownId) + || ownId != owner + || TfBlockDeserializer.ExtractParams(data, start, size, classId) is not { } fields + || !fields.Fields.TryGetValue(typeField, out int value) || value <= 0 + || typeId != 0 && typeId != value) + { + typeId = 0; + break; + } + typeId = value; + } + if (typeId <= 0 + || state.WalkedElementClassRoots.GetValueOrDefault((uint)typeId) is not { BlockCount: 1, ClassId: 1020 }) + continue; + if (native == null) state.NativeParams.Add(owner, native = new()); + native.Fields[typeField] = typeId; + } + } + /// Continuous-stream anchored block walk (see TfStreamWalker): native param /// stores + full-coverage re-run of block-driven signals (curve owners, node owners, /// registry categories, sketch/detail curves). @@ -2467,7 +2504,7 @@ internal static void RunTfStreamWalk(ParsingState state) // the roots the class and stair sources count: the records of the project's block when every stream is read by its framing bool framedRoots = state.ReadsFramedRecords; List<(byte[] Data, int Start, uint Size, ushort Class, uint Owner)>? unanchoredTypeRoots = - framedRoots && state.StaleCopiesRemoved ? [] : null; + framedRoots ? [] : null; if (framedRoots) RecordFramedRoots(state, unanchoredTypeRoots); TfStreamWalker.Walk(state.Chunks, state.AllKnownIds, (seg, bs, ds, cls, eid) => { @@ -2632,11 +2669,13 @@ internal static void RunTfStreamWalk(ParsingState state) // AnalyticalNodeOwners, registry category assignment. }, (seg, recordStart, eid) => ElementHeaderCategory.Record(state, seg, recordStart, eid)); - // Pruning can leave an element's own record where the sequential scan cannot anchor. if (unanchoredTypeRoots != null) + { + RecoverFramedScheduleTypes(state, unanchoredTypeRoots); + // Pruning can leave an element's own record where the sequential scan cannot anchor. foreach (var (data, start, size, classId, owner) in unanchoredTypeRoots) { - if (state.NativeParamsFromRootClass.Contains(owner) + if (classId == 1012 || state.NativeParamsFromRootClass.Contains(owner) || !state.WalkedElementClassRoots.TryGetValue(owner, out var root) || root.BlockCount != 1 || root.ClassId != classId || TfBlockDeserializer.ExtractParams(data, start, size, classId) is not { } parameters @@ -2659,6 +2698,7 @@ internal static void RunTfStreamWalk(ParsingState state) state.NativeParams[owner] = parameters; state.NativeParamsFromRootClass.Add(owner); } + } ApplyFirstDecodableGReps(state, walkGReps); diff --git a/tests/RvtIO.Tests/ScheduleTypeSerializationTests.cs b/tests/RvtIO.Tests/ScheduleTypeSerializationTests.cs new file mode 100644 index 00000000..71ab1cba --- /dev/null +++ b/tests/RvtIO.Tests/ScheduleTypeSerializationTests.cs @@ -0,0 +1,127 @@ +using RvtIO.Internal; +using RvtIO.Model; +using RvtIO.Parsing; +using Xunit; + +namespace RvtIO.Tests; + +public class ScheduleTypeSerializationTests +{ + private const ushort ScheduleClass = 1012; + private const int Owner = 100; + private const int StoredType = 200; + private const int Viewer = 300; + private const int Template = 400; + + [Theory] + [InlineData(0u, StoredType, StoredType)] + [InlineData(2u, StoredType, StoredType)] + [InlineData(uint.MaxValue, StoredType, StoredType)] + [InlineData(2u, -1, Viewer)] + public void UsesStoredViewTypeThroughTheScheduleColorMap(uint colors, int storedType, int expected) + { + byte[] block = Schedule(colors, storedType); + var parameters = Read(block); + Assert.NotNull(parameters); + Assert.Equal(storedType, parameters.Fields["m_dbViewTypeId"]); + + var state = new ParsingState(); + state.NativeParams[Owner] = parameters; + state.ElemClassIdx[Owner] = ScheduleClass; + var schedule = new Element { Id = Owner, TypeId = Viewer, CategoryId = -2000573 }; + var info = new RevitFileInfo(); + info.Elements.Add(schedule); + + ElementBuilder.ApplyNativeParams(info, state); + + Assert.Equal((long)expected, schedule.TypeElementId); + } + + [Fact] + public void RejectsAColorMapThatExtendsPastTheBlock() + => Assert.Null(Read(Schedule(uint.MaxValue - 1, StoredType))); + + [Theory] + [InlineData(StoredType, 1020, StoredType)] + [InlineData(Template, 1020, Viewer)] + [InlineData(StoredType, ScheduleClass, Viewer)] + public void TypesFromFramedCopiesRequireAgreementAndAnOwnViewType( + int otherCopyType, ushort targetClass, int expected) + { + byte[] current = Schedule(2, StoredType); + byte[] otherCopy = Schedule(2, otherCopyType); + byte[] target = Block(StoredType, targetClass, 0, -1); + var state = new ParsingState + { + AllKnownIds = [Owner, StoredType], + ElemRecOwningElementIds = new() { [Owner] = -1, [StoredType] = -1 }, + FramedPartitions = + [ + new([current], [new(102, Owner, 0, current.Length)], 4, 1), + new([otherCopy], [new(102, Owner, 0, otherCopy.Length)], 4, 2), + new([target], [new(102, StoredType, 0, target.Length)], 4, 2), + ], + }; + var schedule = new Element { Id = Owner, TypeId = Viewer, CategoryId = -2000573 }; + RvtFileReader.RunTfStreamWalk(state); + ElementBuilder.ApplyNativeParams(new RevitFileInfo { Elements = [schedule] }, state); + + Assert.Equal((long)expected, schedule.TypeElementId); + } + + private static TfBlockDeserializer.NativeParams? Read(byte[] block) + => TfBlockDeserializer.ExtractParams(block, 0, BitConverter.ToUInt32(block, 8), ScheduleClass); + + private static byte[] Schedule(uint colors, int storedType) + => Block(Owner, ScheduleClass, colors, storedType); + + private static byte[] Block(int owner, ushort classId, uint colors, int storedType) + { + using var stream = new MemoryStream(); + using var writer = new BinaryWriter(stream); + writer.Write(owner); + writer.Write(0u); + writer.Write(0u); + writer.Write(classId); + foreach (var field in TfBlockDeserializer.SerializationFields(classId)!) + { + switch (field.Name) + { + case "m_docAccess": writer.Write(1u); break; + case "m_id": writer.Write(owner); break; + case "m_dbViewTypeId": writer.Write(storedType); break; + case "m_viewerId": writer.Write(Viewer); break; + case "m_viewTemplateId": writer.Write(Template); break; + case "m_colorToCategoryIdMap": + writer.Write(colors); + if (colors == 2) + { + writer.Write(0x004080C0u); + writer.Write(700); + writer.Write(0x005090D0u); + writer.Write(701); + } + break; + case "m_fontIds": + writer.Write(1u); + writer.Write(500); + break; + default: + int bytes = field.Type switch + { + 1 => 1, + 7 => 8, + 4 or 8 or 14 => 4, + _ => throw new InvalidOperationException(field.Name) + }; + writer.Write(new byte[bytes * (field.Cnt ?? 1)]); + break; + } + } + uint size = checked((uint)stream.Length - 12); + writer.Write(size); + stream.Position = 8; + writer.Write(size); + return stream.ToArray(); + } +} From 2a0a01799d278c15e90b8a21a3bee8d23e852cfa Mon Sep 17 00:00:00 2001 From: mie <79989386+mahach666@users.noreply.github.com> Date: Sat, 21 Nov 2026 20:24:54 +0300 Subject: [PATCH 053/259] Recover type IDs from framed project records --- src/RvtIO/Parsing/FramedElementTypes.cs | 216 +++++++++++++++++++ src/RvtIO/RvtFileReader.cs | 7 + tests/RvtIO.Tests/FramedElementTypesTests.cs | 211 ++++++++++++++++++ 3 files changed, 434 insertions(+) create mode 100644 src/RvtIO/Parsing/FramedElementTypes.cs create mode 100644 tests/RvtIO.Tests/FramedElementTypesTests.cs diff --git a/src/RvtIO/Parsing/FramedElementTypes.cs b/src/RvtIO/Parsing/FramedElementTypes.cs new file mode 100644 index 00000000..accc0335 --- /dev/null +++ b/src/RvtIO/Parsing/FramedElementTypes.cs @@ -0,0 +1,216 @@ +using System.Buffers.Binary; +using RvtIO.BuiltIns; +using RvtIO.Internal; +using RvtIO.Model; + +namespace RvtIO.Parsing; + +/// Type links backed by complete project records in the file's own schema. +internal sealed class FramedElementTypes +{ + private const string OwnerField = "Element.m_id"; + private const string ViewerView = "Viewer.m_dbViewId"; + private const string ViewType = "DBView.m_dbViewTypeId"; + private const string ViewMarker = "DBView.m_viewerId"; + private const string ReferenceViewer = "Viewer.m_bIsViewerReference"; + private const string ArrowList = WideBlockWalker.AllItemsKeyPrefix + "InteriorElev.m_arrowIds"; + private const string MarkerParent = "InteriorElevArrow.m_parentId"; + private const string MarkerType = "InteriorElev.m_symbolId"; + private const string StairOwner = "StairsRunAndLanding.m_stairsId"; + private const string StairType = "StairsElement.m_typeId"; + private const string RunType = "StairsType.m_runTypeId"; + private const string LandingType = "StairsType.m_landingTypeId"; + private const string FabricType = "FabricSheet.m_sheetTypeId"; + private const string RailType = "ContinuousRail.m_typeId"; + private const string ActualSpanSymbol = "SpanDirectionSymbol.m_actualSymbolId"; + private const string TagSymbol = "IndependentTag.m_symbolId"; + private const string MasterSymbol = "FamilyInstance.m_masterSymbolId"; + + private static readonly HashSet CapturedFields = + [ + OwnerField, ViewerView, ViewType, ViewMarker, ReferenceViewer, MarkerParent, MarkerType, StairOwner, + StairType, RunType, LandingType, FabricType, RailType, ActualSpanSymbol, TagSymbol, MasterSymbol, + ]; + private static readonly HashSet Classes = + [ + "Viewer3d", "DBView3d", "DBViewType", "DBViewSection", "InteriorElevArrow", "InteriorElev", + "FabricSheet", "FabricSheetType", "StairsRun", "StairsLanding", "StairsElement", "StairsType", + "StairsRunType", "StairsLandingType", "HandRail", "TopRail", "HandRailType", "TopRailType", + "SpanDirectionSymbol", "FamilyInstance", "FamilySymbol", + ]; + + private readonly record struct Source(PartitionFraming.Framed Frame, PartitionFraming.ProjectItem Item, SchemaClass Class); + + private sealed record Root(string Kind, IReadOnlyList> Copies) + { + internal long? Field(string name) + => Copies[0].TryGetValue(name, out long value) + && Copies.All(copy => copy.GetValueOrDefault(name, long.MinValue) == value) ? value : null; + + internal bool ContainsArrow(long arrow) => Copies.All(copy => + copy.TryGetValue(ArrowList + "#", out long count) + && copy.Where(field => field.Key.StartsWith(ArrowList + "@", StringComparison.Ordinal)) + .Count(field => field.Value == arrow) == 1 + && copy.Count(field => field.Key.StartsWith(ArrowList + "@", StringComparison.Ordinal)) == count); + } + + private readonly WideBlockWalker _walker; + private readonly Dictionary> _sources = new(); + private readonly Dictionary _roots = new(); + + private FramedElementTypes(SchemaDocument schema, IReadOnlyDictionary entities) + { + _walker = new WideBlockWalker(schema, (declaring, field) => + { + string key = declaring.Name + "." + field.Name; + return key == "InteriorElev.m_arrowIds" ? ArrowList : CapturedFields.Contains(key) ? key : null; + }, []); + _walker.UseEntitySchemas(entities, passUnknown: true); + } + + internal static int Apply(SchemaDocument schema, IReadOnlyDictionary entities, + IReadOnlyList frames, ParsingState state, IReadOnlyList elements) + { + if (frames.Count == 0 || frames.Any(frame => frame == null)) return 0; + var reader = new FramedElementTypes(schema, entities); + var ids = state.ElementIds; + long SourceId(int key) => ids?.SourceId(key) ?? key; + bool LocalId(long sourceId, out int key) + { + key = 0; + return sourceId > 0 && (ids != null ? ids.TryGetKey(sourceId, out key) + : sourceId <= int.MaxValue && (key = (int)sourceId) > 0); + } + + var details = elements.Where(element => element.CategoryId == (int)BuiltInCategory.OST_DetailComponents) + .Select(element => SourceId(element.Id)).ToHashSet(); + foreach (var frame in frames.Cast()) + foreach (var item in frame.Items) + { + int headerSize = frame.IdWidth + 8; + if (item.Channel != 102 || item.Length < headerSize + 6 || item.Owner > long.MaxValue + || !LocalId((long)item.Owner, out int key) || !state.ElemTable.ContainsKey((uint)key)) continue; + var (header, start, _) = frame.Bytes(item with { Length = headerSize + 2 }); + int tag = BinaryPrimitives.ReadUInt16LittleEndian(header.AsSpan(start + headerSize, 2)); + if (reader._walker.Class(tag) is not { } kind || !Classes.Contains(kind.Name) + || kind.Name == "FamilyInstance" && (!details.Contains((long)item.Owner) + || state.IncrementRoutedPartitions?.ContainsKey((uint)key) == true)) continue; + if (!reader._sources.TryGetValue((long)item.Owner, out var copies)) + reader._sources.Add((long)item.Owner, copies = []); + copies.Add(new(frame, item, kind)); + } + + // A second record of an unsupported class still makes the owner's type ambiguous. + var recordCounts = new Dictionary(); + foreach (var frame in frames.Cast()) + foreach (var item in frame.Items) + if (item.Channel == 102 && item.Owner <= long.MaxValue && reader._sources.ContainsKey((long)item.Owner)) + recordCounts[(long)item.Owner] = recordCounts.GetValueOrDefault((long)item.Owner) + 1; + foreach (var (owner, count) in recordCounts) + if (reader._sources[owner].Count != count) reader._sources.Remove(owner); + + int changed = 0; + foreach (var element in elements) + { + long owner = SourceId(element.Id); + if (!reader._sources.TryGetValue(owner, out var copies)) continue; + long? type = copies[0].Class.Name switch + { + "Viewer3d" => reader.ViewerType(owner), + "DBViewSection" => reader.ElevationType(owner), + "InteriorElevArrow" => reader.ElevationArrowType(owner), + "StairsRun" => reader.StairPartType(owner, "StairsRun", RunType), + "StairsLanding" => reader.StairPartType(owner, "StairsLanding", LandingType), + "FabricSheet" => reader.DirectType(owner, "FabricSheet", FabricType, "FabricSheetType"), + "HandRail" => reader.DirectType(owner, "HandRail", RailType, "HandRailType"), + "TopRail" => reader.DirectType(owner, "TopRail", RailType, "TopRailType"), + "SpanDirectionSymbol" => reader.SpanType(owner), + "FamilyInstance" when copies.Count == 1 => reader.DirectType(owner, "FamilyInstance", MasterSymbol, "FamilySymbol"), + _ => null, + }; + if (type is not long sourceType || sourceType == owner || !LocalId(sourceType, out int typeKey) + || element.TypeId == typeKey) continue; + element.TypeId = typeKey; + changed++; + } + return changed; + } + + private Root? GetRoot(long? id, string kind) + { + if (id is not > 0) return null; + long owner = id.Value; + if (!_roots.TryGetValue(owner, out var root)) _roots[owner] = root = ReadRoot(owner); + return root?.Kind == kind ? root : null; + } + + private Root? ReadRoot(long owner) + { + if (!_sources.TryGetValue(owner, out var copies)) return null; + var fields = new List>(copies.Count); + var kind = copies[0].Class; + foreach (var (frame, item, cls) in copies) + { + if (cls.Id != kind.Id) return null; + var (data, start, _) = frame.Bytes(item); + int size = item.Length - frame.IdWidth - 12; + _walker.StepBudget = 16L * size + 65536; + var walk = _walker.Run(data, start + frame.IdWidth + 8, size, cls.Id); + if (!walk.Exact) return null; + var values = new Dictionary(); + foreach (var capture in walk.Captures) + if (capture.AtRoot && capture.Kind == WideBlockWalker.CaptureKind.Integer + && !values.TryAdd(capture.Key, capture.Integer)) return null; + if (!values.TryGetValue(OwnerField, out long decodedOwner) || decodedOwner != owner) return null; + fields.Add(values); + } + return new(kind.Name, fields); + } + + private long? ViewerType(long viewer) + { + var view = GetRoot(GetRoot(viewer, "Viewer3d")?.Field(ViewerView), "DBView3d"); + return view?.Field(ViewMarker) == viewer ? VerifyType(view.Field(ViewType), "DBViewType") : null; + } + + private long? ElevationType(long? viewId) + { + var view = GetRoot(viewId, "DBViewSection"); + if (view?.Field(ViewType) != -1 || view.Field(ViewMarker) is not long arrowId) return null; + var arrow = GetRoot(arrowId, "InteriorElevArrow"); + return arrow?.Field(ViewerView) == viewId && arrow?.Field(ReferenceViewer) == 0 + ? ParentMarkerType(arrowId, arrow) : null; + } + + private long? ElevationArrowType(long arrowId) + { + var arrow = GetRoot(arrowId, "InteriorElevArrow"); + if (arrow?.Field(ViewerView) is not long viewId || ElevationType(viewId) is not long type) return null; + return GetRoot(viewId, "DBViewSection")?.Field(ViewMarker) == arrowId + || arrow.Field(ReferenceViewer) == 1 && ParentMarkerType(arrowId, arrow) == type ? type : null; + } + + private long? ParentMarkerType(long arrowId, Root arrow) + { + var marker = GetRoot(arrow.Field(MarkerParent), "InteriorElev"); + return marker?.ContainsArrow(arrowId) == true ? VerifyType(marker.Field(MarkerType), "DBViewType") : null; + } + + private long? StairPartType(long part, string kind, string field) + { + var stair = GetRoot(GetRoot(part, kind)?.Field(StairOwner), "StairsElement"); + return VerifyType(GetRoot(stair?.Field(StairType), "StairsType")?.Field(field), kind + "Type"); + } + + private long? DirectType(long id, string kind, string field, string target) + => VerifyType(GetRoot(id, kind)?.Field(field), target); + + private long? SpanType(long id) + { + var root = GetRoot(id, "SpanDirectionSymbol"); + return root?.Field(ActualSpanSymbol) is long symbol && root.Field(TagSymbol) == symbol + ? VerifyType(symbol, "FamilySymbol") : null; + } + + private long? VerifyType(long? id, string kind) => GetRoot(id, kind) == null ? null : id; +} diff --git a/src/RvtIO/RvtFileReader.cs b/src/RvtIO/RvtFileReader.cs index 0328ee48..3c648cfc 100644 --- a/src/RvtIO/RvtFileReader.cs +++ b/src/RvtIO/RvtFileReader.cs @@ -836,6 +836,13 @@ public RevitFileInfo Read(string rvtPath) ?? (lengthOptions == null ? null : ProjectLengthUnits.StoredLengthUnit(lengthOptions.Value, out lengthUnitIssue)); if (rvtInfo.SerializedLengthUnit == null) rvtInfo.SerializedLengthUnitIssue = state.WideLengthUnitIssue ?? lengthUnitIssue; + if ((wideSchema?.Release != 2027 || r22View) + && (wideSchema?.Document ?? TfSchemaReader.Read(root)) is { } typeSchema) + { + int typeLinks = FramedElementTypes.Apply(typeSchema, EntitySchemaReader.Read(root, typeSchema), + framedStreams, state, rvtInfo.Elements); + diag?.WriteLine($"Framed type references: {typeLinks} corrected"); + } rvtInfo.ElementIds = ids; rvtInfo.AttachSourceElementIds(); var (exportIds, replacedUniqueIds) = ElementBuilder.ApplyExportIds(rvtInfo.Elements, state); diff --git a/tests/RvtIO.Tests/FramedElementTypesTests.cs b/tests/RvtIO.Tests/FramedElementTypesTests.cs new file mode 100644 index 00000000..5c65353a --- /dev/null +++ b/tests/RvtIO.Tests/FramedElementTypesTests.cs @@ -0,0 +1,211 @@ +using RvtIO.BuiltIns; +using RvtIO.Internal; +using RvtIO.Model; +using RvtIO.Parsing; +using Xunit; + +namespace RvtIO.Tests; + +public class FramedElementTypesTests +{ + [Theory] + [InlineData(4, true)] + [InlineData(8, true)] + [InlineData(4, false)] + public void AViewerNeedsTheBacklinkToItsOwnView(int width, bool reciprocal) + { + var fixture = new Fixture(width); + long type = width == 8 ? (long)int.MaxValue + 20 : 30; + fixture.Add("Viewer3d", 10, w => { fixture.Id(w, 20); w.Write(false); }); + fixture.Add("DBView3d", 20, w => { fixture.Id(w, type); fixture.Id(w, reciprocal ? 10 : 11); }); + fixture.Add("DBViewType", type); + + Assert.Equal(reciprocal ? type : 99, fixture.TypeOf(10)); + } + + [Theory] + [InlineData(true, true, 70)] + [InlineData(true, false, 99)] + [InlineData(false, true, 99)] + public void AReferencedElevationArrowNeedsAgreementBetweenBothMarkers( + bool containsArrow, bool sameType, long referenceType) + { + var fixture = new Fixture(); + fixture.Add("DBViewSection", 10, w => { fixture.Id(w, -1); fixture.Id(w, 20); }); + fixture.Add("InteriorElevArrow", 20, w => { fixture.Id(w, 10); w.Write(false); fixture.Id(w, 30); }); + fixture.Add("InteriorElev", 30, w => { fixture.Id(w, 70); w.Write(1u); fixture.Id(w, 20); }); + fixture.Add("InteriorElevArrow", 40, w => { fixture.Id(w, 10); w.Write(true); fixture.Id(w, 50); }); + fixture.Add("InteriorElev", 50, w => + { + fixture.Id(w, sameType ? 70 : 71); + w.Write(1u); + fixture.Id(w, containsArrow ? 40 : 41); + }); + fixture.Add("DBViewType", 70); + fixture.Add("DBViewType", 71); + + Assert.Equal(70, fixture.TypeOf(10)); + Assert.Equal(70, fixture.TypeOf(20)); + Assert.Equal(referenceType, fixture.TypeOf(40)); + } + + [Theory] + [InlineData("StairsRun", 40)] + [InlineData("StairsLanding", 50)] + public void StairPartsTakeTheirTypeFromTheOwningStairType(string kind, long expected) + { + var fixture = new Fixture(); + fixture.Add(kind, 10, w => fixture.Id(w, 20)); + fixture.Add("StairsElement", 20, w => fixture.Id(w, 30)); + fixture.Add("StairsType", 30, w => { fixture.Id(w, 40); fixture.Id(w, 50); }); + fixture.Add("StairsRunType", 40); + fixture.Add("StairsLandingType", 50); + + Assert.Equal(expected, fixture.TypeOf(10)); + } + + [Theory] + [InlineData("FabricSheet", "FabricSheetType")] + [InlineData("HandRail", "HandRailType")] + [InlineData("TopRail", "TopRailType")] + public void DirectLinksValidateTheDestinationClass(string kind, string target) + { + var fixture = new Fixture(); + fixture.Add(kind, 10, w => fixture.Id(w, 20)); + fixture.Add(kind, 11, w => fixture.Id(w, 21)); + fixture.Add(target, 20); + fixture.Add("DBViewType", 21); + + Assert.Equal(20, fixture.TypeOf(10)); + Assert.Equal(99, fixture.TypeOf(11)); + } + + [Theory] + [InlineData(20, 20)] + [InlineData(21, 99)] + public void ASpanTagNeedsBothStoredSymbolFieldsToAgree(int actual, long expected) + { + var fixture = new Fixture(); + fixture.Add("SpanDirectionSymbol", 10, w => { fixture.Id(w, 20); fixture.Id(w, actual); }); + fixture.Add("FamilySymbol", 20); + fixture.Add("FamilySymbol", 21); + + Assert.Equal(expected, fixture.TypeOf(10)); + } + + [Theory] + [InlineData(false, false, BuiltInCategory.OST_DetailComponents, 20)] + [InlineData(true, false, BuiltInCategory.OST_DetailComponents, 99)] + [InlineData(false, true, BuiltInCategory.OST_DetailComponents, 99)] + [InlineData(false, false, BuiltInCategory.OST_Doors, 99)] + public void ADetailComponentMustHaveOneUnroutedOwnRecord( + bool duplicate, bool wasRouted, BuiltInCategory category, long expected) + { + var fixture = new Fixture(); + fixture.Add("FamilyInstance", 10, w => fixture.Id(w, 20)); + if (duplicate) fixture.Add("FamilyInstance", 10, w => fixture.Id(w, 20)); + fixture.Add("FamilySymbol", 20); + + Assert.Equal(expected, fixture.TypeOf(10, category, wasRouted)); + } + + [Fact] + public void OtherOrInvalidProjectRecordsPreventTypeRecovery() + { + var fixture = new Fixture(); + fixture.Add("FabricSheet", 10, w => fixture.Id(w, 20)); + fixture.Add("Other", 10); + fixture.Add("FabricSheet", 11, w => fixture.Id(w, 20), storedOwner: 18); + fixture.Add("FabricSheet", 12, w => { fixture.Id(w, 20); w.Write((byte)0); }); + fixture.Add("FabricSheetType", 20); + + Assert.All(new[] { 10, 11, 12 }, id => Assert.Equal(99, fixture.TypeOf(id))); + } + + private sealed class Fixture + { + private readonly SchemaDocument _schema = new(); + private readonly List _frames = []; + private readonly HashSet _ids = []; + private readonly int _width; + + internal Fixture(int width = 4) + { + _width = width; + int identifier = Class("Identifier", 0, new SchemaField("m_id", (byte)(width == 8 ? 11 : 4), 0, 0, null, null, null, null)); + int elementId = Class("ElementId", 0, new SchemaField("m_id", 14, 0, 0, null, identifier, null, null)); + SchemaField Ref(string field, byte mods = 0) => new(field, 14, mods, 0, null, elementId, null, null); + int element = Class("Element", 0, Ref("m_id")); + int view = Class("DBView", element, Ref("m_dbViewTypeId"), Ref("m_viewerId")); + int viewer = Class("Viewer", element, Ref("m_dbViewId"), new SchemaField("m_bIsViewerReference", 1, 0, 0, null, null, null, null)); + Class("Viewer3d", viewer); + Class("DBView3d", view); + Class("DBViewSection", view); + Class("DBViewType", element); + Class("InteriorElevArrow", viewer, Ref("m_parentId")); + Class("InteriorElev", element, Ref("m_symbolId"), Ref("m_arrowIds", 0x50)); + int stairPart = Class("StairsRunAndLanding", element, Ref("m_stairsId")); + Class("StairsRun", stairPart); + Class("StairsLanding", stairPart); + Class("StairsElement", element, Ref("m_typeId")); + Class("StairsType", element, Ref("m_runTypeId"), Ref("m_landingTypeId")); + Class("StairsRunType", element); + Class("StairsLandingType", element); + Class("FabricSheet", element, Ref("m_sheetTypeId")); + Class("FabricSheetType", element); + int rail = Class("ContinuousRail", element, Ref("m_typeId")); + foreach (string kind in new[] { "HandRail", "TopRail" }) + { + Class(kind, rail); + Class(kind + "Type", element); + } + int tag = Class("IndependentTag", element, Ref("m_symbolId")); + Class("SpanDirectionSymbol", tag, Ref("m_actualSymbolId")); + Class("FamilyInstance", element, Ref("m_masterSymbolId")); + Class("FamilySymbol", element); + Class("Other", element); + } + + private int Class(string name, int baseId, params SchemaField[] fields) + { + int id = 12 + _schema.Classes.Count; + _schema.Classes.Add(new(id, name, baseId, 1, [.. fields], [])); + return id; + } + + internal void Id(BinaryWriter writer, long id) + { + if (_width == 4) writer.Write(checked((int)id)); + else writer.Write(id); + } + + internal void Add(string kind, long owner, Action? payload = null, long? storedOwner = null) + { + using var stream = new MemoryStream(); + using var writer = new BinaryWriter(stream); + Id(writer, owner); + writer.Write(0u); + writer.Write(0u); + writer.Write((ushort)_schema.Classes.Single(cls => cls.Name == kind).Id); + Id(writer, storedOwner ?? owner); + payload?.Invoke(writer); + uint size = checked((uint)stream.Length - (uint)_width - 8); + writer.Write(size); + stream.Position = _width + 4; + writer.Write(size); + byte[] bytes = stream.ToArray(); + _frames.Add(new([bytes], [new(102, (ulong)owner, 0, bytes.Length)], _width)); + _ids.Add(owner); + } + + internal long TypeOf(int owner, BuiltInCategory category = BuiltInCategory.INVALID, bool wasRouted = false) + { + var ids = new ElementIdMap(_ids.Select(id => new ElemTableLayout.Row(id, id, 0, 0, 0)).ToArray()); + var state = new ParsingState { ElementIds = ids, ElemTable = _ids.ToDictionary(id => (uint)ids.Key(id), _ => 0u) }; + if (wasRouted) state.IncrementRoutedPartitions = new Dictionary { [(uint)owner] = 1 }; + var element = new Element { Id = owner, TypeId = 99, CategoryId = (int)category }; + FramedElementTypes.Apply(_schema, new Dictionary(), _frames, state, [element]); + return ids.SourceId(element.TypeId); + } + } +} From 7776fc038c5573b0e2f01d2756e7aa66decaed9a Mon Sep 17 00:00:00 2001 From: mie <79989386+mahach666@users.noreply.github.com> Date: Sat, 21 Nov 2026 23:01:34 +0300 Subject: [PATCH 054/259] Recover remaining historical RVT type IDs --- src/RvtIO/Parsing/FramedElementTypes.cs | 106 ++++++++++++-- src/RvtIO/RvtFileReader.cs | 35 +++-- tests/RvtIO.Tests/FramedElementTypesTests.cs | 138 +++++++++++++++++-- 3 files changed, 246 insertions(+), 33 deletions(-) diff --git a/src/RvtIO/Parsing/FramedElementTypes.cs b/src/RvtIO/Parsing/FramedElementTypes.cs index accc0335..859cbfe3 100644 --- a/src/RvtIO/Parsing/FramedElementTypes.cs +++ b/src/RvtIO/Parsing/FramedElementTypes.cs @@ -25,23 +25,39 @@ internal sealed class FramedElementTypes private const string ActualSpanSymbol = "SpanDirectionSymbol.m_actualSymbolId"; private const string TagSymbol = "IndependentTag.m_symbolId"; private const string MasterSymbol = "FamilyInstance.m_masterSymbolId"; + private const string SupportHost = "StairsSupport.m_hostCompId"; + private const string SupportOverridden = "StairsSupport.m_isTypeOverridden"; + private const string LeftSupport = "StairsType.m_leftSideSupportTypeId"; + private const string RightSupport = "StairsType.m_rightSideSupportTypeId"; + private const string LeftSupportStyle = "StairsType.m_leftSupportStyle"; + private const string RightSupportStyle = "StairsType.m_rightSupportStyle"; + private const string IntermediateSupport = "StairsType.m_hasIntermediateSupport"; + private const string GridChainType = "GridChain.m_typeId"; + private const string RebarContainerType = "RebarContainer.m_rebarContainerTypeId"; + private const string RebarInstance = "Rebar.m_oInstance"; + private const string RebarType = "RebarInstBase.m_barTypeId"; + private const string SoffitType = "Ceiling.m_ceilingAttributesId"; + private const string RampType = "Ramp.m_rampAttrId"; private static readonly HashSet CapturedFields = [ OwnerField, ViewerView, ViewType, ViewMarker, ReferenceViewer, MarkerParent, MarkerType, StairOwner, StairType, RunType, LandingType, FabricType, RailType, ActualSpanSymbol, TagSymbol, MasterSymbol, + SupportHost, SupportOverridden, LeftSupport, RightSupport, LeftSupportStyle, RightSupportStyle, IntermediateSupport, + GridChainType, RebarContainerType, RebarInstance, RebarType, SoffitType, RampType, ]; private static readonly HashSet Classes = [ "Viewer3d", "DBView3d", "DBViewType", "DBViewSection", "InteriorElevArrow", "InteriorElev", "FabricSheet", "FabricSheetType", "StairsRun", "StairsLanding", "StairsElement", "StairsType", "StairsRunType", "StairsLandingType", "HandRail", "TopRail", "HandRailType", "TopRailType", - "SpanDirectionSymbol", "FamilyInstance", "FamilySymbol", + "SpanDirectionSymbol", "FamilyInstance", "StairsSupport", "StairsSupportType", "GridChain", "GridAttributes", + "RebarContainer", "RebarContainerType", "Rebar", "RebarBarType", "RoofSoffit", "RoofSoffitType", "Ramp", "RampAttributes", ]; private readonly record struct Source(PartitionFraming.Framed Frame, PartitionFraming.ProjectItem Item, SchemaClass Class); - private sealed record Root(string Kind, IReadOnlyList> Copies) + private sealed record Root(SchemaClass Class, IReadOnlyList> Copies) { internal long? Field(string name) => Copies[0].TryGetValue(name, out long value) @@ -55,6 +71,7 @@ internal bool ContainsArrow(long arrow) => Copies.All(copy => } private readonly WideBlockWalker _walker; + private readonly HashSet _classes; private readonly Dictionary> _sources = new(); private readonly Dictionary _roots = new(); @@ -64,12 +81,33 @@ private FramedElementTypes(SchemaDocument schema, IReadOnlyDictionary Classes.Contains(cls.Name) || _walker.IsA(cls.Id, "FamilySymbol")) + .Select(cls => cls.Id).ToHashSet(); + } + + internal static Dictionary? TypePartitionsWithoutRoutedCopy( + IReadOnlyDictionary> holdersByOwner, IReadOnlyList rows, + DocumentIncrementTable.Table increments, IReadOnlyDictionary routed) + { + if (increments.Permutation.Count != 0) return null; + var partitions = new Dictionary(); + foreach (var row in rows) + { + ulong owner = (ulong)row.Id; + if (!holdersByOwner.TryGetValue(owner, out var holders) || holders.Count < 2 || routed.ContainsKey(owner) + || row.LastModificationDate is not int episode || DocumentIncrementTable.Route(increments, episode) is not int partition + || holders.Contains(partition)) continue; + int latest = holders.Max(); + if ((uint)latest < (uint)increments.Increments.Count) partitions.Add(owner, latest); + } + return partitions; } internal static int Apply(SchemaDocument schema, IReadOnlyDictionary entities, - IReadOnlyList frames, ParsingState state, IReadOnlyList elements) + IReadOnlyList frames, ParsingState state, IReadOnlyList elements, + IReadOnlyDictionary? unroutedTypePartitions = null) { if (frames.Count == 0 || frames.Any(frame => frame == null)) return 0; var reader = new FramedElementTypes(schema, entities); @@ -92,8 +130,9 @@ bool LocalId(long sourceId, out int key) || !LocalId((long)item.Owner, out int key) || !state.ElemTable.ContainsKey((uint)key)) continue; var (header, start, _) = frame.Bytes(item with { Length = headerSize + 2 }); int tag = BinaryPrimitives.ReadUInt16LittleEndian(header.AsSpan(start + headerSize, 2)); - if (reader._walker.Class(tag) is not { } kind || !Classes.Contains(kind.Name) + if (!reader._classes.Contains(tag) || reader._walker.Class(tag) is not { } kind || kind.Name == "FamilyInstance" && (!details.Contains((long)item.Owner) + && unroutedTypePartitions?.ContainsKey(item.Owner) != true || state.IncrementRoutedPartitions?.ContainsKey((uint)key) == true)) continue; if (!reader._sources.TryGetValue((long)item.Owner, out var copies)) reader._sources.Add((long)item.Owner, copies = []); @@ -121,11 +160,21 @@ bool LocalId(long sourceId, out int key) "InteriorElevArrow" => reader.ElevationArrowType(owner), "StairsRun" => reader.StairPartType(owner, "StairsRun", RunType), "StairsLanding" => reader.StairPartType(owner, "StairsLanding", LandingType), + "StairsSupport" when state.ElemRecOwningElementIds?.TryGetValue((uint)element.Id, out int stairKey) == true + => reader.StairSupportType(owner, SourceId(stairKey)), "FabricSheet" => reader.DirectType(owner, "FabricSheet", FabricType, "FabricSheetType"), "HandRail" => reader.DirectType(owner, "HandRail", RailType, "HandRailType"), "TopRail" => reader.DirectType(owner, "TopRail", RailType, "TopRailType"), "SpanDirectionSymbol" => reader.SpanType(owner), - "FamilyInstance" when copies.Count == 1 => reader.DirectType(owner, "FamilyInstance", MasterSymbol, "FamilySymbol"), + "GridChain" => reader.DirectType(owner, "GridChain", GridChainType, "GridAttributes"), + "RebarContainer" => reader.DirectType(owner, "RebarContainer", RebarContainerType, "RebarContainerType"), + "Rebar" => reader.DirectType(owner, "Rebar", RebarType, "RebarBarType"), + "RoofSoffit" => reader.DirectType(owner, "RoofSoffit", SoffitType, "RoofSoffitType"), + "Ramp" => reader.DirectType(owner, "Ramp", RampType, "RampAttributes"), + "FamilyInstance" when copies.Count == 1 && details.Contains(owner) + => reader.DirectType(owner, "FamilyInstance", MasterSymbol, "FamilySymbol"), + "FamilyInstance" when unroutedTypePartitions?.TryGetValue((ulong)owner, out int partition) == true + => reader.UnroutedFamilyType(owner, copies, partition), _ => null, }; if (type is not long sourceType || sourceType == owner || !LocalId(sourceType, out int typeKey) @@ -136,14 +185,17 @@ bool LocalId(long sourceId, out int key) return changed; } - private Root? GetRoot(long? id, string kind) + private Root? GetRoot(long? id) { if (id is not > 0) return null; long owner = id.Value; if (!_roots.TryGetValue(owner, out var root)) _roots[owner] = root = ReadRoot(owner); - return root?.Kind == kind ? root : null; + return root; } + private Root? GetRoot(long? id, string kind) + => GetRoot(id) is { } root && root.Class.Name == kind ? root : null; + private Root? ReadRoot(long owner) { if (!_sources.TryGetValue(owner, out var copies)) return null; @@ -157,14 +209,17 @@ bool LocalId(long sourceId, out int key) _walker.StepBudget = 16L * size + 65536; var walk = _walker.Run(data, start + frame.IdWidth + 8, size, cls.Id); if (!walk.Exact) return null; + int rebarInstance = kind.Name == "Rebar" && walk.RootPointers?.TryGetValue(RebarInstance, out int queued) == true + && _walker.IsA(walk.Queue[queued], "RebarInstBase") ? queued : -1; var values = new Dictionary(); foreach (var capture in walk.Captures) - if (capture.AtRoot && capture.Kind == WideBlockWalker.CaptureKind.Integer + if (capture.Kind == WideBlockWalker.CaptureKind.Integer + && (capture.Key == RebarType ? rebarInstance >= 0 && capture.QueueIndex == rebarInstance : capture.AtRoot) && !values.TryAdd(capture.Key, capture.Integer)) return null; if (!values.TryGetValue(OwnerField, out long decodedOwner) || decodedOwner != owner) return null; fields.Add(values); } - return new(kind.Name, fields); + return new(kind, fields); } private long? ViewerType(long viewer) @@ -202,6 +257,37 @@ bool LocalId(long sourceId, out int key) return VerifyType(GetRoot(stair?.Field(StairType), "StairsType")?.Field(field), kind + "Type"); } + private long? StairSupportType(long supportId, long stairId) + { + var support = GetRoot(supportId, "StairsSupport"); + if (support?.Field(SupportOverridden) != 0) return null; + var host = GetRoot(support.Field(SupportHost)); + if (host?.Class.Name is not ("StairsRun" or "StairsLanding") || host.Field(StairOwner) != stairId) return null; + var stairType = GetRoot(GetRoot(stairId, "StairsElement")?.Field(StairType), "StairsType"); + // The confirmed side-support layout uses style 1 and has no intermediate support. + if (stairType?.Field(IntermediateSupport) != 0 + || stairType.Field(LeftSupportStyle) != 1 || stairType.Field(RightSupportStyle) != 1 + || stairType.Field(LeftSupport) is not long left || stairType.Field(RightSupport) != left) return null; + return VerifyType(left, "StairsSupportType"); + } + + private long? UnroutedFamilyType(long owner, List copies, int partition) + { + if (copies.Count < 2 || GetRoot(owner, "FamilyInstance") is not { } root) return null; + int latest = -1; + var holders = new HashSet(); + for (int i = 0; i < copies.Count; i++) + { + if (copies[i].Frame.Partition is not int holder || !holders.Add(holder) + || root.Copies[i].GetValueOrDefault(MasterSymbol) <= 0) return null; + if (holder == partition) latest = i; + } + if (latest < 0 || holders.Max() != partition || root.Field(MasterSymbol) != null) return null; + // The increment named by ElemTable lost its record. Use the last holder just for the symbol link. + long symbol = root.Copies[latest][MasterSymbol]; + return GetRoot(symbol) is { } target && _walker.IsA(target.Class.Id, "FamilySymbol") ? symbol : null; + } + private long? DirectType(long id, string kind, string field, string target) => VerifyType(GetRoot(id, kind)?.Field(field), target); diff --git a/src/RvtIO/RvtFileReader.cs b/src/RvtIO/RvtFileReader.cs index 3c648cfc..e67db24d 100644 --- a/src/RvtIO/RvtFileReader.cs +++ b/src/RvtIO/RvtFileReader.cs @@ -65,7 +65,7 @@ public RevitFileInfo Read(string rvtPath) Dictionary? tfSchemas = null; LogPhase("Decompressing partitions..."); - var chunks = DecompressPartitions(root, diag, out var ownPartitionWallParts, out var partitionStreams, out var framedStreams, out bool staleCopiesRemoved, out var incrementRoutedPartitions, collectFamilyStorage: true); + var chunks = DecompressPartitions(root, diag, out var ownPartitionWallParts, out var partitionStreams, out var framedStreams, out bool staleCopiesRemoved, out var routing, collectFamilyStorage: true); var fmtChunks = DecompressStorage(root, "Formats", diag); if (fmtChunks.Count > 0) { @@ -91,7 +91,7 @@ public RevitFileInfo Read(string rvtPath) var (wideInfo, wideState) = ParseModel(root, chunks, framedStreams, partitionStreams.Sum(s => s.Count), r22View: false, partitionStreams, framedStreams, wideSchema, elemTable, elemWorksets, fileMetadata, projectInfo, transmissionData, episodeTable, elemRecHistories, elemRecOwners, tfSchemas, ownPartitionWallParts, - staleCopiesRemoved, incrementRoutedPartitions, elemTableIsExact, previewBase64, previewMime, diag, LogPhase, ids); + staleCopiesRemoved, routing, elemTableIsExact, previewBase64, previewMime, diag, LogPhase, ids); WideModel = wideInfo; WideState = wideState; } @@ -112,7 +112,7 @@ public RevitFileInfo Read(string rvtPath) var (rvtInfo, state) = ParseModel(root, chunks, readFrames, partitionChunkCount, r22View, partitionStreams, framedStreams, wideSchema, elemTable, elemWorksets, fileMetadata, projectInfo, transmissionData, episodeTable, elemRecHistories, elemRecOwners, tfSchemas, ownPartitionWallParts, - staleCopiesRemoved, incrementRoutedPartitions, elemTableIsExact, previewBase64, previewMime, diag, LogPhase, ids); + staleCopiesRemoved, routing, elemTableIsExact, previewBase64, previewMime, diag, LogPhase, ids); ExtensibleStorageReader.Apply(root, rvtInfo, framedStreams); LastParsingState = state; return rvtInfo; @@ -138,7 +138,7 @@ public RevitFileInfo Read(string rvtPath) Dictionary? tfSchemas, Dictionary? ownPartitionWallParts, bool staleCopiesRemoved, - IReadOnlyDictionary? incrementRoutedPartitions, + (IReadOnlyDictionary? Current, IReadOnlyDictionary? UnroutedTypePartitions) routing, bool elemTableIsExact, string? previewBase64, string? previewMime, @@ -172,7 +172,7 @@ public RevitFileInfo Read(string rvtPath) R22View = r22View, StaleCopiesRemoved = staleCopiesRemoved, FramedPartitions = readFrames, - IncrementRoutedPartitions = LocalPartitionRoutes(incrementRoutedPartitions, ids), + IncrementRoutedPartitions = LocalPartitionRoutes(routing.Current, ids), PartitionChunkCount = partitionChunkCount, }; ReadWideElementIndex(root, state, partitionStreams, framedStreams, wideSchema, diag); @@ -840,7 +840,7 @@ public RevitFileInfo Read(string rvtPath) && (wideSchema?.Document ?? TfSchemaReader.Read(root)) is { } typeSchema) { int typeLinks = FramedElementTypes.Apply(typeSchema, EntitySchemaReader.Read(root, typeSchema), - framedStreams, state, rvtInfo.Elements); + framedStreams, state, rvtInfo.Elements, routing.UnroutedTypePartitions); diag?.WriteLine($"Framed type references: {typeLinks} corrected"); } rvtInfo.ElementIds = ids; @@ -929,7 +929,7 @@ internal static void MergeElemScanStringsInChunkOrder( var (previewBase64, previewMime) = PreviewImageReader.Read(root); LogPhase("Decompressing partitions..."); - var chunks = DecompressPartitions(root, diag, out var ownPartitionWallParts, out var partitionStreams, out var framedStreams, out bool staleCopiesRemoved, out var incrementRoutedPartitions); + var chunks = DecompressPartitions(root, diag, out var ownPartitionWallParts, out var partitionStreams, out var framedStreams, out bool staleCopiesRemoved, out var routing); // Episode GUID table: nested stream Global/History (see Read() above). var (elemRecHistories, elemRecOwners, wideSchema) = ReadElemRecs(root, ids); @@ -968,7 +968,7 @@ internal static void MergeElemScanStringsInChunkOrder( R22View = r22View, StaleCopiesRemoved = staleCopiesRemoved, FramedPartitions = readFrames, - IncrementRoutedPartitions = LocalPartitionRoutes(incrementRoutedPartitions, ids), + IncrementRoutedPartitions = LocalPartitionRoutes(routing.Current, ids), PartitionChunkCount = partitionChunkCount, }; ReadWideElementIndex(root, state, partitionStreams, framedStreams, wideSchema, diag); @@ -1305,7 +1305,9 @@ void Fail(string reason) private List DecompressPartitions(RootStorage root, TextWriter? diag, out Dictionary? ownPartitionWallParts, out List> partitionStreams, out List framedStreams, - out bool staleCopiesRemoved, out IReadOnlyDictionary? incrementRoutedPartitions, bool collectFamilyStorage = false) + out bool staleCopiesRemoved, + out (IReadOnlyDictionary? Current, IReadOnlyDictionary? UnroutedTypePartitions) routes, + bool collectFamilyStorage = false) { staleCopiesRemoved = false; var partStor = root.OpenStorage("Partitions"); @@ -1321,9 +1323,10 @@ private List DecompressPartitions(RootStorage root, TextWriter? diag, framedStreams = []; ownPartitionWallParts = null; var routing = partEntries.Count > 1 - ? PlanRecordRouting(root, partStor, partEntries.Select(e => e.Name).ToList(), _options.ResolveCurrentCopies ? diag : null) + ? PlanRecordRouting(root, partStor, partEntries.Select(e => e.Name).ToList(), _options.ResolveCurrentCopies ? diag : null, + recoverTypeIds: collectFamilyStorage) : null; - incrementRoutedPartitions = routing?.Current; + routes = (routing?.Current, routing?.UnroutedTypePartitions); // the exact framing of the partition streams (PartitionFraming), when the class table names its marker classes and the id width is known var formats = FormatsSchema.TryRead(root); var framing = formats != null && PartitionFraming.TagsOf(formats) is { } framingTags @@ -1419,11 +1422,13 @@ internal static List CutPartition(byte[] raw, (PartitionFraming.Tags Tag return chunks; } - private sealed record RoutingPlan(RecordRouting.Census Census, Dictionary Current); + private sealed record RoutingPlan(RecordRouting.Census Census, Dictionary Current, + IReadOnlyDictionary? UnroutedTypePartitions); /// The current copy of every element that several partition streams hold (), or null with the /// reason in the diagnostics when the framing, the element table or the increment table does not decode. - private static RoutingPlan? PlanRecordRouting(RootStorage root, Storage partStor, IReadOnlyList names, TextWriter? diag) + private static RoutingPlan? PlanRecordRouting(RootStorage root, Storage partStor, IReadOnlyList names, TextWriter? diag, + bool recoverTypeIds) { var schema = FormatsSchema.TryRead(root); var census = RecordRouting.Begin(schema, out var failure); @@ -1444,7 +1449,9 @@ private sealed record RoutingPlan(RecordRouting.Census Census, Dictionary fixture.Id(w, 20)); fixture.Add("StairsElement", 20, w => fixture.Id(w, 30)); - fixture.Add("StairsType", 30, w => { fixture.Id(w, 40); fixture.Id(w, 50); }); + fixture.Add("StairsType", 30, w => fixture.StairsType(w, 40, 50)); fixture.Add("StairsRunType", 40); fixture.Add("StairsLandingType", 50); Assert.Equal(expected, fixture.TypeOf(10)); } + [Theory] + [InlineData("StairsRun", 20, false, false, 40, 40)] + [InlineData("StairsLanding", 20, false, false, 40, 40)] + [InlineData("StairsRun", 21, false, false, 40, 99)] + [InlineData("StairsRun", 20, true, false, 40, 99)] + [InlineData("StairsRun", 20, false, true, 40, 99)] + [InlineData("StairsRun", 20, false, false, 41, 99)] + public void AStairSupportNeedsMatchingSideTypesOnItsOwningStair( + string hostKind, int hostStair, bool overridden, bool intermediate, int right, long expected) + { + var fixture = new Fixture(); + fixture.Add("StairsSupport", 10, w => { fixture.Id(w, 11); w.Write(overridden); }); + fixture.Add(hostKind, 11, w => fixture.Id(w, hostStair)); + fixture.Add("StairsElement", 20, w => fixture.Id(w, 30)); + fixture.Add("StairsType", 30, w => fixture.StairsType(w, -1, -1, 40, right, intermediate)); + fixture.Add("StairsSupportType", 40); + + Assert.Equal(expected, fixture.TypeOf(10, stairOwner: 20)); + } + [Theory] [InlineData("FabricSheet", "FabricSheetType")] [InlineData("HandRail", "HandRailType")] [InlineData("TopRail", "TopRailType")] + [InlineData("GridChain", "GridAttributes")] + [InlineData("RebarContainer", "RebarContainerType")] + [InlineData("RoofSoffit", "RoofSoffitType")] + [InlineData("Ramp", "RampAttributes")] public void DirectLinksValidateTheDestinationClass(string kind, string target) { var fixture = new Fixture(); @@ -80,6 +104,25 @@ public void DirectLinksValidateTheDestinationClass(string kind, string target) Assert.Equal(99, fixture.TypeOf(11)); } + [Theory] + [InlineData(true, 20)] + [InlineData(false, 99)] + public void RebarTypeComesFromItsOwnInstancePointer(bool hasInstance, long expected) + { + var fixture = new Fixture(); + fixture.Add("Rebar", 10, w => + { + fixture.Pointer(w, "RebarInstance"); + fixture.Pointer(w, hasInstance ? "RebarInstance" : null); + fixture.Id(w, 21); + if (hasInstance) fixture.Id(w, 20); + }); + fixture.Add("RebarBarType", 20); + fixture.Add("RebarBarType", 21); + + Assert.Equal(expected, fixture.TypeOf(10)); + } + [Theory] [InlineData(20, 20)] [InlineData(21, 99)] @@ -109,6 +152,44 @@ public void ADetailComponentMustHaveOneUnroutedOwnRecord( Assert.Equal(expected, fixture.TypeOf(10, category, wasRouted)); } + [Theory] + [InlineData(4, 1, false, false, false, true)] + [InlineData(8, 1, false, false, false, true)] + [InlineData(4, 0, false, false, false, false)] + [InlineData(4, 1, true, false, false, false)] + [InlineData(4, 1, false, true, false, false)] + [InlineData(4, 1, false, false, true, false)] + public void AnUnroutedFamilyRecoversOnlyTypeIdFromTheLatestHolder( + int width, int routedIncrement, bool permutation, bool wrongType, bool ambiguous, bool corrected) + { + var fixture = new Fixture(width); + long latest = width == 8 ? (long)int.MaxValue + 50 : 21; + fixture.Add("FamilyInstance", 10, w => fixture.Id(w, latest), partition: 2); + fixture.Add("FamilyInstance", 10, w => fixture.Id(w, 20), partition: 0); + if (ambiguous) fixture.Add("FamilyInstance", 10, w => fixture.Id(w, 20), partition: 2); + fixture.Add("FamilySymbol", 20); + fixture.Add(wrongType ? "Other" : "SysPanelFamSym", latest); + + var rows = new[] { new ElemTableLayout.Row(10, 10, 0, 0, -1, routedIncrement) }; + var increments = Enumerable.Range(0, 3) + .Select(i => new DocumentIncrementTable.Increment(i, 1, 1, [])).ToArray(); + var table = new DocumentIncrementTable.Table(increments, increments, permutation ? [(1, 2)] : []); + var typePartitions = FramedElementTypes.TypePartitionsWithoutRoutedCopy( + new Dictionary> { [10] = [0, 2] }, rows, table, new Dictionary()); + var element = new Element + { + Id = 10, TypeId = 20, Name = "Earlier name", HostId = 32, + Parameters = [new Parameter { Definition = new Definition { Name = "ELEM_TYPE_PARAM" }, Value = 20 }], + }; + var parameters = element.Parameters; + + Assert.Equal(corrected ? latest : 20, fixture.Apply(element, typePartitions: typePartitions)); + Assert.Equal("Earlier name", element.Name); + Assert.Equal(32, element.HostId); + Assert.Equal(20, element.FamilyTypeId); + Assert.Same(parameters, element.Parameters); + } + [Fact] public void OtherOrInvalidProjectRecordsPreventTypeRecovery() { @@ -135,6 +216,9 @@ internal Fixture(int width = 4) int identifier = Class("Identifier", 0, new SchemaField("m_id", (byte)(width == 8 ? 11 : 4), 0, 0, null, null, null, null)); int elementId = Class("ElementId", 0, new SchemaField("m_id", 14, 0, 0, null, identifier, null, null)); SchemaField Ref(string field, byte mods = 0) => new(field, 14, mods, 0, null, elementId, null, null); + SchemaField Int(string field) => new(field, 4, 0, 0, null, null, null, null); + SchemaField Bool(string field) => new(field, 1, 0, 0, null, null, null, null); + SchemaField Owned(string field) => new(field, 14, 1, 0, null, null, null, null); int element = Class("Element", 0, Ref("m_id")); int view = Class("DBView", element, Ref("m_dbViewTypeId"), Ref("m_viewerId")); int viewer = Class("Viewer", element, Ref("m_dbViewId"), new SchemaField("m_bIsViewerReference", 1, 0, 0, null, null, null, null)); @@ -148,9 +232,12 @@ internal Fixture(int width = 4) Class("StairsRun", stairPart); Class("StairsLanding", stairPart); Class("StairsElement", element, Ref("m_typeId")); - Class("StairsType", element, Ref("m_runTypeId"), Ref("m_landingTypeId")); + Class("StairsType", element, Ref("m_runTypeId"), Ref("m_landingTypeId"), Ref("m_leftSideSupportTypeId"), + Ref("m_rightSideSupportTypeId"), Int("m_leftSupportStyle"), Int("m_rightSupportStyle"), Bool("m_hasIntermediateSupport")); Class("StairsRunType", element); Class("StairsLandingType", element); + Class("StairsSupport", element, Ref("m_hostCompId"), Bool("m_isTypeOverridden")); + Class("StairsSupportType", element); Class("FabricSheet", element, Ref("m_sheetTypeId")); Class("FabricSheetType", element); int rail = Class("ContinuousRail", element, Ref("m_typeId")); @@ -162,7 +249,18 @@ internal Fixture(int width = 4) int tag = Class("IndependentTag", element, Ref("m_symbolId")); Class("SpanDirectionSymbol", tag, Ref("m_actualSymbolId")); Class("FamilyInstance", element, Ref("m_masterSymbolId")); - Class("FamilySymbol", element); + Class("SysPanelFamSym", Class("FamilySymbol", element)); + Class("GridChain", element, Ref("m_typeId")); + Class("GridAttributes", element); + Class("RebarContainer", element, Ref("m_rebarContainerTypeId")); + Class("RebarContainerType", element); + Class("Rebar", element, Owned("m_other"), Owned("m_oInstance")); + Class("RebarInstance", Class("RebarInstBase", 0, Ref("m_barTypeId"))); + Class("RebarBarType", element); + Class("RoofSoffit", Class("Ceiling", element, Ref("m_ceilingAttributesId"))); + Class("RoofSoffitType", element); + Class("Ramp", element, Ref("m_rampAttrId")); + Class("RampAttributes", element); Class("Other", element); } @@ -179,7 +277,25 @@ internal void Id(BinaryWriter writer, long id) else writer.Write(id); } - internal void Add(string kind, long owner, Action? payload = null, long? storedOwner = null) + internal void StairsType(BinaryWriter writer, long run, long landing, long left = -1, long right = -1, bool intermediate = false) + { + Id(writer, run); + Id(writer, landing); + Id(writer, left); + Id(writer, right); + writer.Write(1); + writer.Write(1); + writer.Write(intermediate); + } + + internal void Pointer(BinaryWriter writer, string? kind) + { + writer.Write(kind == null ? 0u : uint.MaxValue); + if (kind != null) writer.Write((ushort)_schema.Classes.Single(cls => cls.Name == kind).Id); + } + + internal void Add(string kind, long owner, Action? payload = null, long? storedOwner = null, + int? partition = null) { using var stream = new MemoryStream(); using var writer = new BinaryWriter(stream); @@ -194,17 +310,21 @@ internal void Add(string kind, long owner, Action? payload = null, stream.Position = _width + 4; writer.Write(size); byte[] bytes = stream.ToArray(); - _frames.Add(new([bytes], [new(102, (ulong)owner, 0, bytes.Length)], _width)); + _frames.Add(new([bytes], [new(102, (ulong)owner, 0, bytes.Length)], _width, partition)); _ids.Add(owner); } - internal long TypeOf(int owner, BuiltInCategory category = BuiltInCategory.INVALID, bool wasRouted = false) + internal long TypeOf(int owner, BuiltInCategory category = BuiltInCategory.INVALID, bool wasRouted = false, int? stairOwner = null) + => Apply(new Element { Id = owner, TypeId = 99, CategoryId = (int)category }, wasRouted, stairOwner); + + internal long Apply(Element element, bool wasRouted = false, int? stairOwner = null, + IReadOnlyDictionary? typePartitions = null) { var ids = new ElementIdMap(_ids.Select(id => new ElemTableLayout.Row(id, id, 0, 0, 0)).ToArray()); var state = new ParsingState { ElementIds = ids, ElemTable = _ids.ToDictionary(id => (uint)ids.Key(id), _ => 0u) }; - if (wasRouted) state.IncrementRoutedPartitions = new Dictionary { [(uint)owner] = 1 }; - var element = new Element { Id = owner, TypeId = 99, CategoryId = (int)category }; - FramedElementTypes.Apply(_schema, new Dictionary(), _frames, state, [element]); + if (wasRouted) state.IncrementRoutedPartitions = new Dictionary { [(uint)element.Id] = 1 }; + if (stairOwner is int stair) state.ElemRecOwningElementIds = new Dictionary { [(uint)element.Id] = stair }; + FramedElementTypes.Apply(_schema, new Dictionary(), _frames, state, [element], typePartitions); return ids.SourceId(element.TypeId); } } From b29a45a56130533623b7bd7a9ee9e54a48e2f6b0 Mon Sep 17 00:00:00 2001 From: mie <79989386+mahach666@users.noreply.github.com> Date: Sun, 22 Nov 2026 02:23:52 +0300 Subject: [PATCH 055/259] Recover unanchored type IDs when keeping copies --- src/RvtIO/Parsing/FramedElementTypes.cs | 25 ++++++++-- src/RvtIO/RvtFileReader.cs | 3 +- tests/RvtIO.Tests/FramedElementTypesTests.cs | 48 +++++++++++++++++++- 3 files changed, 68 insertions(+), 8 deletions(-) diff --git a/src/RvtIO/Parsing/FramedElementTypes.cs b/src/RvtIO/Parsing/FramedElementTypes.cs index 859cbfe3..30e1ccf1 100644 --- a/src/RvtIO/Parsing/FramedElementTypes.cs +++ b/src/RvtIO/Parsing/FramedElementTypes.cs @@ -39,6 +39,13 @@ internal sealed class FramedElementTypes private const string SoffitType = "Ceiling.m_ceilingAttributesId"; private const string RampType = "Ramp.m_rampAttrId"; + private static readonly Dictionary UnanchoredTypes = new() + { + ["LinearDimString"] = ("Dimension.m_styleSymbolId", "DimensionStyle"), + ["TextNote"] = ("TextElement.m_attrId", "TextNoteAttributes"), + ["SWall"] = ("VWall.m_WallAttributesId", "BasicWallType"), + }; + private static readonly HashSet CapturedFields = [ OwnerField, ViewerView, ViewType, ViewMarker, ReferenceViewer, MarkerParent, MarkerType, StairOwner, @@ -75,15 +82,19 @@ internal bool ContainsArrow(long arrow) => Copies.All(copy => private readonly Dictionary> _sources = new(); private readonly Dictionary _roots = new(); - private FramedElementTypes(SchemaDocument schema, IReadOnlyDictionary entities) + private FramedElementTypes(SchemaDocument schema, IReadOnlyDictionary entities, bool recoverUnanchoredTypes) { + var extraFields = recoverUnanchoredTypes ? UnanchoredTypes.Values.Select(link => link.Field).ToHashSet() : null; _walker = new WideBlockWalker(schema, (declaring, field) => { string key = declaring.Name + "." + field.Name; - return key == "InteriorElev.m_arrowIds" ? ArrowList : CapturedFields.Contains(key) ? key : null; + return key == "InteriorElev.m_arrowIds" ? ArrowList + : CapturedFields.Contains(key) || extraFields?.Contains(key) == true ? key : null; }, [], captureRootPointers: true); _walker.UseEntitySchemas(entities, passUnknown: true); - _classes = schema.Classes.Where(cls => Classes.Contains(cls.Name) || _walker.IsA(cls.Id, "FamilySymbol")) + var extraTargets = recoverUnanchoredTypes ? UnanchoredTypes.Values.Select(link => link.Target).ToHashSet() : null; + _classes = schema.Classes.Where(cls => Classes.Contains(cls.Name) || _walker.IsA(cls.Id, "FamilySymbol") + || recoverUnanchoredTypes && (UnanchoredTypes.ContainsKey(cls.Name) || extraTargets!.Contains(cls.Name))) .Select(cls => cls.Id).ToHashSet(); } @@ -107,10 +118,10 @@ private FramedElementTypes(SchemaDocument schema, IReadOnlyDictionary entities, IReadOnlyList frames, ParsingState state, IReadOnlyList elements, - IReadOnlyDictionary? unroutedTypePartitions = null) + IReadOnlyDictionary? unroutedTypePartitions = null, bool recoverUnanchoredTypes = false) { if (frames.Count == 0 || frames.Any(frame => frame == null)) return 0; - var reader = new FramedElementTypes(schema, entities); + var reader = new FramedElementTypes(schema, entities, recoverUnanchoredTypes); var ids = state.ElementIds; long SourceId(int key) => ids?.SourceId(key) ?? key; bool LocalId(long sourceId, out int key) @@ -131,6 +142,7 @@ bool LocalId(long sourceId, out int key) var (header, start, _) = frame.Bytes(item with { Length = headerSize + 2 }); int tag = BinaryPrimitives.ReadUInt16LittleEndian(header.AsSpan(start + headerSize, 2)); if (!reader._classes.Contains(tag) || reader._walker.Class(tag) is not { } kind + || UnanchoredTypes.ContainsKey(kind.Name) && state.NativeParamsFromRootClass.Contains((uint)key) || kind.Name == "FamilyInstance" && (!details.Contains((long)item.Owner) && unroutedTypePartitions?.ContainsKey(item.Owner) != true || state.IncrementRoutedPartitions?.ContainsKey((uint)key) == true)) continue; @@ -175,6 +187,9 @@ bool LocalId(long sourceId, out int key) => reader.DirectType(owner, "FamilyInstance", MasterSymbol, "FamilySymbol"), "FamilyInstance" when unroutedTypePartitions?.TryGetValue((ulong)owner, out int partition) == true => reader.UnroutedFamilyType(owner, copies, partition), + // A single exact record can supply the type even when the stream walk never anchored on it. + var kind when copies.Count == 1 && UnanchoredTypes.TryGetValue(kind, out var link) + => reader.DirectType(owner, kind, link.Field, link.Target), _ => null, }; if (type is not long sourceType || sourceType == owner || !LocalId(sourceType, out int typeKey) diff --git a/src/RvtIO/RvtFileReader.cs b/src/RvtIO/RvtFileReader.cs index e67db24d..c0acf23e 100644 --- a/src/RvtIO/RvtFileReader.cs +++ b/src/RvtIO/RvtFileReader.cs @@ -840,7 +840,8 @@ public RevitFileInfo Read(string rvtPath) && (wideSchema?.Document ?? TfSchemaReader.Read(root)) is { } typeSchema) { int typeLinks = FramedElementTypes.Apply(typeSchema, EntitySchemaReader.Read(root, typeSchema), - framedStreams, state, rvtInfo.Elements, routing.UnroutedTypePartitions); + framedStreams, state, rvtInfo.Elements, routing.UnroutedTypePartitions, + recoverUnanchoredTypes: !_options.ResolveCurrentCopies); diag?.WriteLine($"Framed type references: {typeLinks} corrected"); } rvtInfo.ElementIds = ids; diff --git a/tests/RvtIO.Tests/FramedElementTypesTests.cs b/tests/RvtIO.Tests/FramedElementTypesTests.cs index 62af4265..7acad1a3 100644 --- a/tests/RvtIO.Tests/FramedElementTypesTests.cs +++ b/tests/RvtIO.Tests/FramedElementTypesTests.cs @@ -203,6 +203,43 @@ public void OtherOrInvalidProjectRecordsPreventTypeRecovery() Assert.All(new[] { 10, 11, 12 }, id => Assert.Equal(99, fixture.TypeOf(id))); } + [Theory] + [InlineData("LinearDimString", "DimensionStyle", -1)] + [InlineData("TextNote", "TextNoteAttributes", -1)] + [InlineData("SWall", "BasicWallType", 30)] + public void KeepCopiesRestoresOnlyTypeIdFromASingleUnanchoredRecord(string kind, string target, int oldType) + { + var fixture = new Fixture(); + fixture.Add(kind, 10, w => fixture.Id(w, 20), partition: 1); + fixture.Add(target, 20, partition: 0); + var element = new Element { Id = 10, TypeId = oldType, Name = "Stored name", HostId = 45 }; + element.Parameters.Add(new Parameter { Value = "Stored parameter" }); + + Assert.Equal(20, fixture.Apply(element, recoverUnanchoredTypes: true)); + Assert.Equal("Stored name", element.Name); + Assert.Equal(45, element.HostId); + Assert.Equal("Stored parameter", Assert.Single(element.Parameters).Value); + } + + [Theory] + [InlineData(false, false, false, false)] + [InlineData(true, true, false, false)] + [InlineData(true, false, true, false)] + [InlineData(true, false, false, true)] + public void UnanchoredWallRequiresKeepModeAnUnambiguousRootAndARealType( + bool keepCopies, bool anchored, bool otherCopy, bool wrongTarget) + { + var fixture = new Fixture(); + fixture.Add("SWall", 10, w => fixture.Id(w, 20), partition: 1); + if (otherCopy) fixture.Add("SWall", 10, w => fixture.Id(w, 30), partition: 0); + if (wrongTarget) fixture.Add("SWall", 20, w => fixture.Id(w, 30)); + else fixture.Add("BasicWallType", 20); + fixture.Add("BasicWallType", 30); + + var element = new Element { Id = 10, TypeId = 30 }; + Assert.Equal(30, fixture.Apply(element, recoverUnanchoredTypes: keepCopies, anchored: anchored)); + } + private sealed class Fixture { private readonly SchemaDocument _schema = new(); @@ -261,6 +298,12 @@ internal Fixture(int width = 4) Class("RoofSoffitType", element); Class("Ramp", element, Ref("m_rampAttrId")); Class("RampAttributes", element); + Class("LinearDimString", Class("Dimension", element, Ref("m_styleSymbolId"))); + Class("DimensionStyle", element); + Class("TextNote", Class("TextElement", element, Ref("m_attrId"))); + Class("TextNoteAttributes", element); + Class("SWall", Class("VWall", element, Ref("m_WallAttributesId"))); + Class("BasicWallType", element); Class("Other", element); } @@ -318,13 +361,14 @@ internal long TypeOf(int owner, BuiltInCategory category = BuiltInCategory.INVAL => Apply(new Element { Id = owner, TypeId = 99, CategoryId = (int)category }, wasRouted, stairOwner); internal long Apply(Element element, bool wasRouted = false, int? stairOwner = null, - IReadOnlyDictionary? typePartitions = null) + IReadOnlyDictionary? typePartitions = null, bool recoverUnanchoredTypes = false, bool anchored = false) { var ids = new ElementIdMap(_ids.Select(id => new ElemTableLayout.Row(id, id, 0, 0, 0)).ToArray()); var state = new ParsingState { ElementIds = ids, ElemTable = _ids.ToDictionary(id => (uint)ids.Key(id), _ => 0u) }; if (wasRouted) state.IncrementRoutedPartitions = new Dictionary { [(uint)element.Id] = 1 }; if (stairOwner is int stair) state.ElemRecOwningElementIds = new Dictionary { [(uint)element.Id] = stair }; - FramedElementTypes.Apply(_schema, new Dictionary(), _frames, state, [element], typePartitions); + if (anchored) state.NativeParamsFromRootClass.Add((uint)element.Id); + FramedElementTypes.Apply(_schema, new Dictionary(), _frames, state, [element], typePartitions, recoverUnanchoredTypes); return ids.SourceId(element.TypeId); } } From a270ac2f39060f54c3e41a928b34490be842b84f Mon Sep 17 00:00:00 2001 From: mie <79989386+mahach666@users.noreply.github.com> Date: Sun, 22 Nov 2026 02:25:24 +0300 Subject: [PATCH 056/259] Avoid overflow in trimmed-face ear clipping --- CHANGELOG.md | 4 ++++ src/RvtIO/Parsing/GRepParserV2.cs | 4 ++-- tests/RvtIO.Tests/GRepParserV2Tests.cs | 15 +++++++++++++++ 3 files changed, 21 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index fd3648c3..5775540e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,10 @@ API between minor releases. ## [Unreleased] +### Fixed + +- Avoid overflow when triangulating trimmed faces with 46,341 or more vertices after bridging. + ## [0.6.3] - 2026-11-20 ### Fixed diff --git a/src/RvtIO/Parsing/GRepParserV2.cs b/src/RvtIO/Parsing/GRepParserV2.cs index a4be085b..a580d5df 100644 --- a/src/RvtIO/Parsing/GRepParserV2.cs +++ b/src/RvtIO/Parsing/GRepParserV2.cs @@ -4990,8 +4990,8 @@ bool IsEar(int index) (previous[1] + current[1] + next[1]) / 3 }; return InsideRegion(centroid); } - int guard = polygon.Count * polygon.Count; - while (count > 3 && guard-- > 0) + // Each iteration removes one vertex or returns; the trim budget limits the search for ears. + while (count > 3) { int ear; while ((ear = NextCandidate()) >= 0 && !IsEar(ear)) { } diff --git a/tests/RvtIO.Tests/GRepParserV2Tests.cs b/tests/RvtIO.Tests/GRepParserV2Tests.cs index 4298f6dc..f6675564 100644 --- a/tests/RvtIO.Tests/GRepParserV2Tests.cs +++ b/tests/RvtIO.Tests/GRepParserV2Tests.cs @@ -547,6 +547,21 @@ public async Task TrimTriangulation_TriangulatesManyFinelySampledHolesInNearLine Assert.All(rings.SelectMany(ring => ring), point => Assert.Contains((point[0], point[1]), vertices)); } + [Fact] + public void TrimTriangulation_ClipsARingWhoseVertexCountSquaredExceedsInt32() + { + // The parabola and its closing chord form a convex ring with no collinear vertices to simplify. + const int count = 46_341; + var ring = Enumerable.Range(0, count).Select(index => new[] { (double)index, (double)index * index }).ToList(); + + var polygons = GRepParserV2.TriangulateTrimRegions([ring], out bool outOfBudget); + + Assert.False(outOfBudget); + Assert.NotNull(polygons); + Assert.Equal(count - 2, polygons.Count); + Assert.Equal(PolygonArea(ring), polygons.Sum(PolygonArea)); + } + [Fact] public void TrimTriangulation_TellsARunOutBudgetApartFromLoopsThatDoNotTriangulate() { From 26147536955f29d02b884afe5b10f1374f064860 Mon Sep 17 00:00:00 2001 From: mie <79989386+mahach666@users.noreply.github.com> Date: Sun, 22 Nov 2026 04:23:36 +0300 Subject: [PATCH 057/259] Support centimetres and inches in IFC exports --- CHANGELOG.md | 5 + README.md | 8 +- docs/public-api.md | 8 +- src/RvtIO.Cli/IfcLengthUnitOption.cs | 15 +- src/RvtIO.Cli/Program.cs | 4 +- src/RvtIO/Ifc/IfcExporter.HeaderCurrent.cs | 62 ++++---- src/RvtIO/Ifc/IfcExporter.Rebar.cs | 4 +- src/RvtIO/Ifc/IfcExporter.cs | 41 ++--- src/RvtIO/Ifc/IfcLengthUnit.cs | 14 +- src/RvtIO/Ifc/IfcLengthUnitChoice.cs | 6 +- tests/RvtIO.Tests/IfcLengthUnitTests.cs | 177 +++++++++++++++++---- 11 files changed, 254 insertions(+), 90 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5775540e..4cfbbca8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,11 @@ API between minor releases. ## [Unreleased] +### Added + +- IFC export supports explicit centimetres (`cm`) and inches (`in`) in the CLI and API, with the corresponding square + and cubic units in both profiles. Default IFC output and JSON units are unchanged. + ### Fixed - Avoid overflow when triangulating trimmed faces with 46,341 or more vertices after bridging. diff --git a/README.md b/README.md index 90aaf864..55d644aa 100644 --- a/README.md +++ b/README.md @@ -108,15 +108,15 @@ rvtio project.rvt project.ifc --ifc-phase all An element is left out of the IFC when it is demolished in the export phase or an earlier one, or created in a later one. Without the option the current profile exports the last project phase and the legacy profile every phase; `all` keeps every element and room, and an id selects that phase (it must occur in the project's phase order, or the tool exits with code 1). Rooms follow the export phase unless `--ifc-room-phase` names another one. The compact and full JSON are not filtered. In the library the same choices are `IfcExporter.ExportPhaseId` and `IfcExporter.ExportAllPhases`. -The IFC declares the length unit of the project and writes every length in it: millimetres, metres (also for the "metres and centimetres" format) or feet (also for feet and fractional inches and for US survey feet). A project in any other unit, such as centimetres or inches, and a project whose length unit cannot be read are written in millimetres; the diagnostics name the stored unit or the reason. Without an explicit choice, the legacy profile always writes millimetres. To choose the IFC length unit explicitly (`mm`, `m` or `ft`; `IfcExporter.LengthUnit` in the library): +By default the current IFC profile maps the project length format to millimetres, metres (also for "metres and centimetres") or feet (also for feet and fractional inches and for US survey feet). Other or unreadable project length formats fall back to millimetres; diagnostics name the stored format or the reason. The legacy profile defaults to millimetres. Use `--ifc-length-unit` (`IfcExporter.LengthUnit` in the library) to select `mm`, `cm`, `m`, `in` or `ft` explicitly: ```sh rvtio project.rvt project.ifc --ifc-length-unit m -rvtio project.rvt project.ifc --ifc-length-unit ft -rvtio project.rvt project.ifc --ifc-length-unit mm +rvtio project.rvt project.ifc --ifc-length-unit cm +rvtio project.rvt project.ifc --ifc-length-unit in ``` -All IFC coordinates, areas, volumes and base quantities are scaled to the chosen unit; unknown unit names exit with code 1. Compact JSON keeps the formatted display units of the project and full JSON keeps Revit's internal units (feet, square feet, cubic feet, radians). +IFC coordinates, geometry and quantities use the declared units: `cm` selects cm/cm²/cm³, `in` selects in/in²/in³, and `ft` selects ft/ft²/ft³. The existing `mm` and `m` families both keep square and cubic metres. Unknown unit names exit with code 1. The IFC choice does not affect JSON, including multi-output exports. Compact JSON uses the project's display formatting; full JSON keeps Revit's internal units (feet, square feet, cubic feet, radians). The Width and Height quantities of the opening of a door or window are those of the door or window as Revit has them: for a door 0.8 wide and 2.1 high the opening gets Width 0.8 (along the wall) and Height 2.1 (vertical), and the Depth is the thickness of the wall, in a wall of any direction. The Width and Height are the instance values, else the type values; a side the door or window holds no value for is measured from the opening, vertical for Height and along the wall for Width. Where the cut loop of the door or window is decoded, the opening is measured by that loop, as Revit cuts it, which can be larger than the nominal size (a door 0.9 by 2.1 with a frame cut of 1.0 by 2.2 gets Width 1.0 and Height 2.2); the nominal size stays only where the cut loop is not decoded. This applies to openings in straight walls. Unfilled openings in straight walls are measured from their final extrusion in the same wall frame: Width along the wall, Height vertical and Depth across it. The openings of curved walls and curtain walls and openings of other fillers are measured as before. Releases before this one named the sides of the cut loop by the frame they are measured in, which gave the same door Height 0.8 and Width 2.1. To write those values, restore the earlier reading: diff --git a/docs/public-api.md b/docs/public-api.md index 4a9078aa..4ff74c96 100644 --- a/docs/public-api.md +++ b/docs/public-api.md @@ -109,10 +109,16 @@ extension and label helpers carry the ids and names stored in the file format. |---|---| | `IfcExporter` | Writes IFC from a `RevitFileInfo` (`Export`). Properties: `Profile`, `BaseQuantities`, `OpeningQuantitiesSwapped` (true writes the legacy Width and Height of door and window openings; default false), `OpeningQuantitiesInHostAxes` (the opposite of it, kept for compatibility), `ExportPhaseId`, `ExportAllPhases`, `RoomExportPhaseId`, `ExportRoomsOfAllPhases`, `RevitParameterGroups`, `LengthUnit`, `Timestamp`, `SkipLog`, `ExportedProducts`, `ExportedElementQualities`, `DiagnosticOutput`. | | `IfcProfile` | `Legacy` or `Current` (the default) output profile. | -| `IfcUnitFamily` | The length unit family an IFC export declares (`Millimetre`, `Metre` or `Foot`), chosen explicitly via `IfcExporter.LengthUnit` or derived in the current profile from the length format of the project (`Metre` for metres and for metres and centimetres, `Foot` for feet, feet and fractional inches and US survey feet, `Millimetre` for millimetres, for every other format and for an unreadable one; the legacy profile defaults to millimetres). | +| `IfcUnitFamily` | Set `IfcExporter.LengthUnit` to `Millimetre`, `Centimetre`, `Metre`, `Inch` or `Foot`. `Centimetre` and `Inch` declare the corresponding square and cubic units and are explicit overrides only. Without an override, the current profile maps the stored project format to millimetres, metres or feet as before; the legacy profile defaults to millimetres. | | `CompactJsonExporter` | `Export(rvtPath, outputPath, readerOptions, options)` reads a file and writes the compact JSON. | | `CompactJsonExportOptions` | `JsonClassNamePrefix`: text put in front of every class name in the `name` field. | +**Compact JSON unit policy.** `IfcExporter.LengthUnit` and `--ifc-length-unit` never affect JSON. Any future compact JSON +override must be a separate opt-in setting. Convert only values with a resolved length, area or volume specification +from their raw stored value and identify the resulting unit; do not parse or relabel the project's formatted strings. +Values with unknown specs or no stored value keep their existing behavior. Other specs and full JSON are out of scope. +No compact JSON override is implemented. + ## Sheets and viewports | Type | Use | diff --git a/src/RvtIO.Cli/IfcLengthUnitOption.cs b/src/RvtIO.Cli/IfcLengthUnitOption.cs index 8127ccad..9a095884 100644 --- a/src/RvtIO.Cli/IfcLengthUnitOption.cs +++ b/src/RvtIO.Cli/IfcLengthUnitOption.cs @@ -1,13 +1,14 @@ namespace RvtIO.Cli; -/// The --ifc-length-unit <mm|m|ft> option: overrides the length unit family declared in the IFC file and scales all +/// The --ifc-length-unit <mm|cm|m|in|ft> option: overrides the length unit family declared in the IFC file and scales all /// written lengths, areas and volumes to match (). internal static class IfcLengthUnitOption { public const string Name = "--ifc-length-unit"; + private const string InvalidUnit = Name + " requires one supported IFC length unit: mm, cm, m, in or ft."; /// Reads --ifc-length-unit from . Without the option is null. - /// Accepts mm/millimetre/millimeter, m/metre/meter, and ft/foot/feet + /// Accepts mm, cm, m, in, ft and their spelled-out names /// (case-insensitive, singular or plural). Returns false with set when the option has no value, is given /// twice or names an unsupported unit. public static bool TryParse(string[] args, out RvtIO.Ifc.IfcUnitFamily? unit, out string? error) @@ -20,14 +21,14 @@ public static bool TryParse(string[] args, out RvtIO.Ifc.IfcUnitFamily? unit, ou if (args[i] != Name) continue; if (seen || i + 1 >= args.Length || args[i + 1].StartsWith("--", StringComparison.Ordinal)) { - error = $"{Name} requires one supported IFC length unit: mm (millimetre), m (metre) or ft (foot)."; + error = InvalidUnit; unit = null; return false; } seen = true; if (!TryParseValue(args[++i], out var parsed)) { - error = $"{Name} requires one supported IFC length unit: mm (millimetre), m (metre) or ft (foot)."; + error = InvalidUnit; unit = null; return false; } @@ -43,12 +44,18 @@ private static bool TryParseValue(string raw, out RvtIO.Ifc.IfcUnitFamily unit) case "mm" or "millimetre" or "millimeter" or "millimetres" or "millimeters": unit = RvtIO.Ifc.IfcUnitFamily.Millimetre; return true; + case "cm" or "centimetre" or "centimeter" or "centimetres" or "centimeters": + unit = RvtIO.Ifc.IfcUnitFamily.Centimetre; + return true; case "m" or "metre" or "meter" or "metres" or "meters": unit = RvtIO.Ifc.IfcUnitFamily.Metre; return true; case "ft" or "foot" or "feet": unit = RvtIO.Ifc.IfcUnitFamily.Foot; return true; + case "in" or "inch" or "inches": + unit = RvtIO.Ifc.IfcUnitFamily.Inch; + return true; default: unit = default; return false; diff --git a/src/RvtIO.Cli/Program.cs b/src/RvtIO.Cli/Program.cs index 1a83eaf2..b51d9c81 100644 --- a/src/RvtIO.Cli/Program.cs +++ b/src/RvtIO.Cli/Program.cs @@ -35,8 +35,8 @@ to write several formats from a single file read. Diagnostics go to standard err --ifc-room-phase says otherwise, rooms of other phases are left out. Default: the last phase for the current profile, every phase for the legacy profile (IFC only) --ifc-room-phase rooms to export: the last phase, every phase or one native phase id (IFC only) - --ifc-length-unit length unit family written to the IFC file: mm (millimetre), m (metre) or ft (foot); default: the - unit stored in the project for the current profile, mm for the legacy profile (IFC only) + --ifc-length-unit length unit family written to the IFC file: millimetres, centimetres, metres, inches or feet. + Without an override, the existing project-unit mapping applies (legacy: mm; IFC only). --ifc-timestamp UTC timestamp for the STEP FILE_NAME header (ISO-8601 or Unix epoch seconds; IFC only) --revit-localization deprecated, ignored: the system family names are built in --r22-layout read the Revit 2022 layout for a JSON export too (an IFC export does it by default) diff --git a/src/RvtIO/Ifc/IfcExporter.HeaderCurrent.cs b/src/RvtIO/Ifc/IfcExporter.HeaderCurrent.cs index 5c8aca09..7555e45d 100644 --- a/src/RvtIO/Ifc/IfcExporter.HeaderCurrent.cs +++ b/src/RvtIO/Ifc/IfcExporter.HeaderCurrent.cs @@ -22,49 +22,53 @@ private static int AddConversionBasedUnit( return w.Add("IFCCONVERSIONBASEDUNIT", $"{R(dimensionsId)},.{unitType}UNIT.,'{name}',{R(measureWithUnitId)}"); } - private static int AddFootLengthUnit(StepWriter w, int metreUnitId) => - AddConversionBasedUnit(w, "1,0,0,0,0,0,0", "LENGTH", "FOOT", "IFCLENGTHMEASURE", - StepWriter.Real(IfcLengthUnit.MetresPerFoot, "G17"), metreUnitId); + private static int AddProjectLengthUnit(StepWriter w, int siLength, IfcUnitFamily family) => family switch + { + IfcUnitFamily.Foot => AddConversionBasedUnit(w, "1,0,0,0,0,0,0", "LENGTH", "FOOT", "IFCLENGTHMEASURE", + StepWriter.Real(IfcLengthUnit.MetresPerFoot, "G17"), siLength), + IfcUnitFamily.Inch => AddConversionBasedUnit(w, "1,0,0,0,0,0,0", "LENGTH", "INCH", "IFCLENGTHMEASURE", + StepWriter.Real(IfcLengthUnit.MetresPerInch, "G17"), siLength), + _ => siLength, + }; - private static int AddSquareFootUnit(StepWriter w) => - AddConversionBasedUnit(w, "2,0,0,0,0,0,0", "AREA", "SQUARE FOOT", "IFCAREAMEASURE", - StepWriter.Real(IfcLengthUnit.SquareMetresPerSquareFoot, "G17"), - w.Add("IFCSIUNIT", "*,.AREAUNIT.,$,.SQUARE_METRE.")); + private static int AddProjectAreaUnit(StepWriter w, IfcUnitFamily family) => family switch + { + IfcUnitFamily.Foot => AddConversionBasedUnit(w, "2,0,0,0,0,0,0", "AREA", "SQUARE FOOT", "IFCAREAMEASURE", + StepWriter.Real(IfcLengthUnit.SquareMetresPerSquareFoot, "G17"), w.Add("IFCSIUNIT", "*,.AREAUNIT.,$,.SQUARE_METRE.")), + IfcUnitFamily.Inch => AddConversionBasedUnit(w, "2,0,0,0,0,0,0", "AREA", "SQUARE INCH", "IFCAREAMEASURE", + StepWriter.Real(IfcLengthUnit.SquareMetresPerSquareInch, "G17"), w.Add("IFCSIUNIT", "*,.AREAUNIT.,$,.SQUARE_METRE.")), + IfcUnitFamily.Centimetre => w.Add("IFCSIUNIT", "*,.AREAUNIT.,.CENTI.,.SQUARE_METRE."), + _ => w.Add("IFCSIUNIT", "*,.AREAUNIT.,$,.SQUARE_METRE."), + }; - private static int AddCubicFootUnit(StepWriter w) => - AddConversionBasedUnit(w, "3,0,0,0,0,0,0", "VOLUME", "CUBIC FOOT", "IFCVOLUMEMEASURE", - StepWriter.Real(IfcLengthUnit.CubicMetresPerCubicFoot, "G17"), - w.Add("IFCSIUNIT", "*,.VOLUMEUNIT.,$,.CUBIC_METRE.")); + private static int AddProjectVolumeUnit(StepWriter w, IfcUnitFamily family) => family switch + { + IfcUnitFamily.Foot => AddConversionBasedUnit(w, "3,0,0,0,0,0,0", "VOLUME", "CUBIC FOOT", "IFCVOLUMEMEASURE", + StepWriter.Real(IfcLengthUnit.CubicMetresPerCubicFoot, "G17"), w.Add("IFCSIUNIT", "*,.VOLUMEUNIT.,$,.CUBIC_METRE.")), + IfcUnitFamily.Inch => AddConversionBasedUnit(w, "3,0,0,0,0,0,0", "VOLUME", "CUBIC INCH", "IFCVOLUMEMEASURE", + StepWriter.Real(IfcLengthUnit.CubicMetresPerCubicInch, "G17"), w.Add("IFCSIUNIT", "*,.VOLUMEUNIT.,$,.CUBIC_METRE.")), + IfcUnitFamily.Centimetre => w.Add("IFCSIUNIT", "*,.VOLUMEUNIT.,.CENTI.,.CUBIC_METRE."), + _ => w.Add("IFCSIUNIT", "*,.VOLUMEUNIT.,$,.CUBIC_METRE."), + }; private static int AddDegreeUnit(StepWriter w) => AddConversionBasedUnit(w, "0,0,0,0,0,0,0", "PLANEANGLE", "DEGREE", "IFCPLANEANGLEMEASURE", DegreeInRadiansCurrent, w.Add("IFCSIUNIT", "*,.PLANEANGLEUNIT.,$,.RADIAN.")); /// A unit is created when the first measure of its kind is made; the created ones are assigned, in creation order, - /// in IfcProject.UnitsInContext at the end of the export. The project units are millimetre, degree, square metre and - /// cubic metre; the selected unit of a spec that has an SI unit of its own is written as IfcSIUnit (area, volume), + /// in IfcProject.UnitsInContext at the end of the export. The default project units are millimetre, degree, square metre + /// and cubic metre. Metric units are written as IfcSIUnit, imperial units as IfcConversionBasedUnit, and /// the degree as IfcConversionBasedUnit of the radian with the factor . /// All four are always present, so they are written up front; the assignment lists the defaults until the final order is known. internal static UnitAssignmentCurrent CreateUnitAssignmentCurrent(StepWriter w, int lengthUnitId, IfcUnitFamily family = IfcUnitFamily.Millimetre) { - if (family == IfcUnitFamily.Foot) - { - // A project in feet: length, area and volume are conversion-based foot units referencing named - // SI base units (.METRE., .SQUARE_METRE., .CUBIC_METRE.) via IfcMeasureWithUnit factors. - int footLength = AddFootLengthUnit(w, lengthUnitId); - int degreeFoot = AddDegreeUnit(w); - int squareFoot = AddSquareFootUnit(w); - int cubicFoot = AddCubicFootUnit(w); - int footIndex = w.EntityCount; - int footAssignment = w.Add("IFCUNITASSIGNMENT", StepWriter.List(R(footLength), R(degreeFoot), R(squareFoot), R(cubicFoot))); - return new UnitAssignmentCurrent(footLength, degreeFoot, squareFoot, cubicFoot, footIndex, footAssignment); - } + int length = AddProjectLengthUnit(w, lengthUnitId, family); int degree = AddDegreeUnit(w); - int area = w.Add("IFCSIUNIT", "*,.AREAUNIT.,$,.SQUARE_METRE."); - int volume = w.Add("IFCSIUNIT", "*,.VOLUMEUNIT.,$,.CUBIC_METRE."); + int area = AddProjectAreaUnit(w, family); + int volume = AddProjectVolumeUnit(w, family); int index = w.EntityCount; - int assignment = w.Add("IFCUNITASSIGNMENT", StepWriter.List(R(lengthUnitId), R(degree), R(area), R(volume))); - return new UnitAssignmentCurrent(lengthUnitId, degree, area, volume, index, assignment); + int assignment = w.Add("IFCUNITASSIGNMENT", StepWriter.List(R(length), R(degree), R(area), R(volume))); + return new UnitAssignmentCurrent(length, degree, area, volume, index, assignment); } /// Completes the unit assignment from the finished property values: the thermal transmittance unit diff --git a/src/RvtIO/Ifc/IfcExporter.Rebar.cs b/src/RvtIO/Ifc/IfcExporter.Rebar.cs index 66e1691c..b59b9546 100644 --- a/src/RvtIO/Ifc/IfcExporter.Rebar.cs +++ b/src/RvtIO/Ifc/IfcExporter.Rebar.cs @@ -23,6 +23,8 @@ public partial class IfcExporter { IfcUnitFamily.Foot => 1, IfcUnitFamily.Metre => FeetToMetres, + IfcUnitFamily.Centimetre => FeetToMillimetres / 10, + IfcUnitFamily.Inch => 12, _ => FeetToMillimetres, }; @@ -183,7 +185,7 @@ private int WriteSweptDisk(StepWriter w, IReadOnlyList pieces, dou string Direction(double[] v) => R(w.Add("IFCDIRECTION", StepWriter.List(D(v[0]), D(v[1]), D(v[2])))); var curves = new List(); lengthFt = 0; - // the end parameter of the directrix is the sum of the parameter extents of its pieces: millimetres of a line, degrees of an arc + // The end parameter adds line lengths in file units and arc extents in degrees. double endParameter = 0; foreach (var piece in pieces) { diff --git a/src/RvtIO/Ifc/IfcExporter.cs b/src/RvtIO/Ifc/IfcExporter.cs index 56d00373..f2a8d64c 100644 --- a/src/RvtIO/Ifc/IfcExporter.cs +++ b/src/RvtIO/Ifc/IfcExporter.cs @@ -291,9 +291,9 @@ private void ValidateRoomExportPhase(RevitFileInfo info) /// UTC timestamp written into the STEP FILE_NAME header (yyyy-MM-ddTHH:mm:ss). Null (the default) uses the current UTC time. public DateTimeOffset? Timestamp { get; init; } - /// The length unit family written to the IFC file (, - /// or ). Null (the default) uses the length format stored in the project for - /// and millimetres for . + /// The length unit family written to the IFC file. Null keeps the stored-unit mapping in + /// and millimetres in . + /// Centimetres and inches are only selected explicitly. public IfcUnitFamily? LengthUnit { get; init; } /// Products written by the last export, as counted in the "IFC export:" diagnostic line. @@ -448,9 +448,13 @@ private void ExportDocument(RevitFileInfo info, TextWriter output) int poaId = w.Add("IFCPERSONANDORGANIZATION", $"{R(personId)},{R(owningOrgId)},$"); int ownerHistId = w.Add("IFCOWNERHISTORY", $"{R(poaId)},{R(appId)},$,.NOCHANGE.,$,$,$,0"); - // ---- Units (metric: millimetres/metres, square metres, cubic metres; or conversion-based feet). - int lengthUnitId = w.Add("IFCSIUNIT", _unitFamily == IfcUnitFamily.Millimetre - ? "*,.LENGTHUNIT.,.MILLI.,.METRE." : "*,.LENGTHUNIT.,$,.METRE."); + // Metric lengths use SI prefixes; conversion-based lengths reference the unprefixed metre. + int lengthUnitId = w.Add("IFCSIUNIT", _unitFamily switch + { + IfcUnitFamily.Millimetre => "*,.LENGTHUNIT.,.MILLI.,.METRE.", + IfcUnitFamily.Centimetre => "*,.LENGTHUNIT.,.CENTI.,.METRE.", + _ => "*,.LENGTHUNIT.,$,.METRE.", + }); UnitAssignmentCurrent? unitsCurrent = null; int unitsId; if (CurrentProfile) @@ -458,21 +462,13 @@ private void ExportDocument(RevitFileInfo info, TextWriter output) unitsCurrent = CreateUnitAssignmentCurrent(w, lengthUnitId, _unitFamily); unitsId = unitsCurrent.AssignmentId; } - else if (_unitFamily == IfcUnitFamily.Foot) + else { - int footLengthId = AddFootLengthUnit(w, lengthUnitId); - int areaUnitId = AddSquareFootUnit(w); - int volumeUnitId = AddCubicFootUnit(w); + lengthUnitId = AddProjectLengthUnit(w, lengthUnitId, _unitFamily); + int areaUnitId = AddProjectAreaUnit(w, _unitFamily); + int volumeUnitId = AddProjectVolumeUnit(w, _unitFamily); int angleUnitId = w.Add("IFCSIUNIT", "*,.PLANEANGLEUNIT.,$,.RADIAN."); int timeUnitId = w.Add("IFCSIUNIT", "*,.TIMEUNIT.,$,.SECOND."); - unitsId = w.Add("IFCUNITASSIGNMENT", StepWriter.List(R(footLengthId), R(areaUnitId), R(volumeUnitId), R(angleUnitId), R(timeUnitId))); - } - else - { - int areaUnitId = w.Add("IFCSIUNIT", $"*,.AREAUNIT.,$,.SQUARE_METRE."); - int volumeUnitId = w.Add("IFCSIUNIT", $"*,.VOLUMEUNIT.,$,.CUBIC_METRE."); - int angleUnitId = w.Add("IFCSIUNIT", $"*,.PLANEANGLEUNIT.,$,.RADIAN."); - int timeUnitId = w.Add("IFCSIUNIT", $"*,.TIMEUNIT.,$,.SECOND."); unitsId = w.Add("IFCUNITASSIGNMENT", StepWriter.List(R(lengthUnitId), R(areaUnitId), R(volumeUnitId), R(angleUnitId), R(timeUnitId))); } @@ -482,8 +478,15 @@ private void ExportDocument(RevitFileInfo info, TextWriter output) // so TrueNorth is always the y axis: (cos(pi/2), sin(pi/2)) //. int trueNorthId = CurrentProfile ? w.Add("IFCDIRECTION", StepWriter.List(D(Math.Cos(Math.PI / 2)), "1.")) : 0; + double precision = _unitFamily switch + { + IfcUnitFamily.Millimetre => CurrentProfile ? 0.1 : 0.01, + IfcUnitFamily.Centimetre => CurrentProfile ? 0.01 : 0.001, + IfcUnitFamily.Inch => (CurrentProfile ? 0.0001 : 0.00001) / IfcLengthUnit.MetresPerInch, + _ => CurrentProfile ? 0.0001 : 0.00001, + }; int contextId = w.Add("IFCGEOMETRICREPRESENTATIONCONTEXT", - $"{(CurrentProfile ? "''" : "$")},{S("Model")},3,{D(CurrentProfile ? (_unitFamily == IfcUnitFamily.Millimetre ? 0.1 : 0.0001) : (_unitFamily == IfcUnitFamily.Millimetre ? 0.01 : 0.00001))},{R(axisId)},{(CurrentProfile ? R(trueNorthId) : "$")}"); + $"{(CurrentProfile ? "''" : "$")},{S("Model")},3,{D(precision)},{R(axisId)},{(CurrentProfile ? R(trueNorthId) : "$")}"); // The current profile writes the four sub-contexts of CoordinationView 2.0 // (createContextInformation), each named by its identifier with type "Model" and no target // scale; Box and FootPrint are used by the grids and bounding boxes. diff --git a/src/RvtIO/Ifc/IfcLengthUnit.cs b/src/RvtIO/Ifc/IfcLengthUnit.cs index 32d24974..e6fbfa2e 100644 --- a/src/RvtIO/Ifc/IfcLengthUnit.cs +++ b/src/RvtIO/Ifc/IfcLengthUnit.cs @@ -61,14 +61,16 @@ internal static string ToMillimetres(string type, string args, bool exactQuantit /// The conversion of the finished entity list for a unit family. Millimetre is /// (what every file wrote before the family existed); Metre keeps the metres of the table and moves the - /// millimetre-written attributes; Foot divides every length, area and volume by its factor, which is what the Revit - /// internal unit is, so those files are printed in the values of the document itself. + /// millimetre-written attributes; the other families convert lengths, areas and volumes to their corresponding units. internal static Func Converter(IfcUnitFamily family, bool exactQuantities = false) => family == IfcUnitFamily.Millimetre ? (type, args) => ToMillimetres(type, args, exactQuantities) : (type, args) => ToFamily(type, args, family, exactQuantities); internal const double MetresPerFoot = 0.3048; internal const double SquareMetresPerSquareFoot = MetresPerFoot * MetresPerFoot; internal const double CubicMetresPerCubicFoot = MetresPerFoot * MetresPerFoot * MetresPerFoot; + internal const double MetresPerInch = 0.0254; + internal const double SquareMetresPerSquareInch = MetresPerInch * MetresPerInch; + internal const double CubicMetresPerCubicInch = MetresPerInch * MetresPerInch * MetresPerInch; /// Attributes written in millimetres at their source (the overall size of a door or window, the nominal diameter /// and the length of a bar, the radius of a swept disk). @@ -101,6 +103,14 @@ private enum SourceUnit { Metre, Millimetre, SquareMetre, CubicMetre } (SourceUnit.Millimetre, IfcUnitFamily.Metre) => 1000, (SourceUnit.SquareMetre, IfcUnitFamily.Foot) => SquareMetresPerSquareFoot, (SourceUnit.CubicMetre, IfcUnitFamily.Foot) => CubicMetresPerCubicFoot, + (SourceUnit.Metre, IfcUnitFamily.Centimetre) => 0.01, + (SourceUnit.Millimetre, IfcUnitFamily.Centimetre) => 10, + (SourceUnit.SquareMetre, IfcUnitFamily.Centimetre) => 0.0001, + (SourceUnit.CubicMetre, IfcUnitFamily.Centimetre) => 0.000001, + (SourceUnit.Metre, IfcUnitFamily.Inch) => MetresPerInch, + (SourceUnit.Millimetre, IfcUnitFamily.Inch) => 25.4, + (SourceUnit.SquareMetre, IfcUnitFamily.Inch) => SquareMetresPerSquareInch, + (SourceUnit.CubicMetre, IfcUnitFamily.Inch) => CubicMetresPerCubicInch, _ => 1, }; diff --git a/src/RvtIO/Ifc/IfcLengthUnitChoice.cs b/src/RvtIO/Ifc/IfcLengthUnitChoice.cs index 2936930d..868beb08 100644 --- a/src/RvtIO/Ifc/IfcLengthUnitChoice.cs +++ b/src/RvtIO/Ifc/IfcLengthUnitChoice.cs @@ -11,6 +11,10 @@ public enum IfcUnitFamily Metre, /// Lengths are written in feet. Foot, + /// Lengths are written in centimetres. This family is opt-in. + Centimetre, + /// Lengths are written in inches. This family is opt-in. + Inch, } internal static class IfcLengthUnitChoice @@ -19,7 +23,7 @@ internal static class IfcLengthUnitChoice /// The family the stored unit is written in, as Revit's own IFC export declares it: feet, feet-and-fractional-inches /// and US survey feet as FOOT, meters and meters-and-centimeters as METRE, millimeters as MILLI METRE. Null for every - /// other unit (centimeters and inches among them, which have no family here) and for an unreadable option. + /// other unit (including centimetres and inches, which require an explicit override) and for an unreadable option. internal static IfcUnitFamily? OwnFamily(string? storedLengthUnit) => storedLengthUnit == null ? null : UnitSchemaEvaluator.DisplayNameKey(storedLengthUnit) switch diff --git a/tests/RvtIO.Tests/IfcLengthUnitTests.cs b/tests/RvtIO.Tests/IfcLengthUnitTests.cs index 49290e9a..dcd39a61 100644 --- a/tests/RvtIO.Tests/IfcLengthUnitTests.cs +++ b/tests/RvtIO.Tests/IfcLengthUnitTests.cs @@ -134,6 +134,32 @@ public void Metre_KeepsMetresAndMovesMillimetreAttributes() Assert.Equal("'P','',IFCLENGTHMEASURE(0.0254),$", IfcLengthUnit.ToFamily("IFCPROPERTYSINGLEVALUE", "'P','',IFCLENGTHMEASURE(25.4),$", IfcUnitFamily.Metre)); } + [Theory] + [InlineData(IfcUnitFamily.Centimetre, 0.01, 0.0001, 0.000001)] + [InlineData(IfcUnitFamily.Inch, 0.0254, 0.00064516, 0.000016387064)] + public void ExplicitUnits_ScaleMillimetreDoorSizesAndTypedProperties( + IfcUnitFamily family, double lengthFactor, double areaFactor, double volumeFactor) + { + string door = IfcLengthUnit.ToFamily("IFCDOOR", "#1,#2,'Door','','',#3,#4,'5',2000.,800.", family); + var sizes = IfcLengthUnit.SplitTopLevel(door); + Assert.Equal(2.0, double.Parse(sizes[8], CultureInfo.InvariantCulture) * lengthFactor, 12); + Assert.Equal(0.8, double.Parse(sizes[9], CultureInfo.InvariantCulture) * lengthFactor, 12); + + foreach (var (measure, source, factor, expected) in new[] + { + ("IFCLENGTHMEASURE", "25.4", lengthFactor, 0.0254), + ("IFCAREAMEASURE", "2.5", areaFactor, 2.5), + ("IFCVOLUMEMEASURE", "1.25", volumeFactor, 1.25), + }) + { + string args = IfcLengthUnit.ToFamily("IFCPROPERTYSINGLEVALUE", $"'P',$,{measure}({source}),$", family); + string nominal = IfcLengthUnit.SplitTopLevel(args)[2]; + Assert.StartsWith(measure + "(", nominal); + Assert.Equal(expected, double.Parse(nominal.AsSpan(measure.Length + 1, nominal.Length - measure.Length - 2), + CultureInfo.InvariantCulture) * factor, 12); + } + } + [Fact] public void FootUnitAssignment_NamesTheFootAndTheSquareAndCubicFoot() { @@ -233,6 +259,10 @@ public void IfcLengthUnitOption_WithoutOption_ReturnsNull() [InlineData("millimeter", IfcUnitFamily.Millimetre)] [InlineData("millimetres", IfcUnitFamily.Millimetre)] [InlineData("millimeters", IfcUnitFamily.Millimetre)] + [InlineData("cm", IfcUnitFamily.Centimetre)] + [InlineData("CM", IfcUnitFamily.Centimetre)] + [InlineData("centimetre", IfcUnitFamily.Centimetre)] + [InlineData("centimeters", IfcUnitFamily.Centimetre)] [InlineData("m", IfcUnitFamily.Metre)] [InlineData("metre", IfcUnitFamily.Metre)] [InlineData("meter", IfcUnitFamily.Metre)] @@ -242,6 +272,10 @@ public void IfcLengthUnitOption_WithoutOption_ReturnsNull() [InlineData("FT", IfcUnitFamily.Foot)] [InlineData("foot", IfcUnitFamily.Foot)] [InlineData("feet", IfcUnitFamily.Foot)] + [InlineData("in", IfcUnitFamily.Inch)] + [InlineData("IN", IfcUnitFamily.Inch)] + [InlineData("inch", IfcUnitFamily.Inch)] + [InlineData("inches", IfcUnitFamily.Inch)] public void IfcLengthUnitOption_SupportedSpellings_MapToExpectedFamily(string raw, IfcUnitFamily expected) { Assert.True(RvtIO.Cli.IfcLengthUnitOption.TryParse(["project.rvt", "project.ifc", "--ifc-length-unit", raw], out var unit, out string? error)); @@ -253,10 +287,6 @@ public static IEnumerable InvalidLengthUnitArguments() { yield return [new[] { "project.rvt", "project.ifc", "--ifc-length-unit" }]; yield return [new[] { "project.rvt", "project.ifc", "--ifc-length-unit", "--ifc-revit-parameters" }]; - yield return [new[] { "project.rvt", "project.ifc", "--ifc-length-unit", "cm" }]; - yield return [new[] { "project.rvt", "project.ifc", "--ifc-length-unit", "centimetre" }]; - yield return [new[] { "project.rvt", "project.ifc", "--ifc-length-unit", "in" }]; - yield return [new[] { "project.rvt", "project.ifc", "--ifc-length-unit", "inch" }]; yield return [new[] { "project.rvt", "project.ifc", "--ifc-length-unit", "km" }]; yield return [new[] { "project.rvt", "project.ifc", "--ifc-length-unit", "m", "--ifc-length-unit", "ft" }]; } @@ -290,6 +320,8 @@ public void Export_WithInvalidEnumValue_ThrowsArgumentOutOfRangeException(IfcPro [InlineData(IfcProfile.Current, "autodesk.unit.unit:millimeters-1.0.1", IfcUnitFamily.Millimetre)] [InlineData(IfcProfile.Current, "autodesk.unit.unit:meters-1.0.0", IfcUnitFamily.Metre)] [InlineData(IfcProfile.Current, "autodesk.unit.unit:feet-1.0.1", IfcUnitFamily.Foot)] + [InlineData(IfcProfile.Current, "autodesk.unit.unit:centimeters-1.0.1", IfcUnitFamily.Millimetre)] + [InlineData(IfcProfile.Current, "autodesk.unit.unit:inches-1.0.1", IfcUnitFamily.Millimetre)] [InlineData(IfcProfile.Legacy, "autodesk.unit.unit:meters-1.0.0", IfcUnitFamily.Millimetre)] public void Export_WithoutExplicitSetting_MatchesMatchingExplicitFamilyByteForByte( IfcProfile profile, string storedUnit, IfcUnitFamily matchingFamily) @@ -326,14 +358,14 @@ public void Export_WithoutExplicitSetting_MatchesMatchingExplicitFamilyByteForBy [Theory] [InlineData(IfcProfile.Current)] [InlineData(IfcProfile.Legacy)] - public void Export_AcrossMillimetreMetreAndFoot_DeclaresMatchingUnitsAndPreservesPhysicalGeometryAndQuantities(IfcProfile profile) + public void Export_AcrossUnitFamilies_DeclaresMatchingUnitsAndPreservesPhysicalGeometryAndQuantities(IfcProfile profile) { string dir = Path.Combine(Path.GetTempPath(), $"rvtio-unit-equiv-{Guid.NewGuid():N}"); Directory.CreateDirectory(dir); try { var outputs = new Dictionary(); - foreach (var family in new[] { IfcUnitFamily.Millimetre, IfcUnitFamily.Metre, IfcUnitFamily.Foot }) + foreach (var family in Enum.GetValues()) { string path = Path.Combine(dir, $"{family}.ifc"); var diag = new StringWriter(); @@ -365,13 +397,22 @@ public void Export_AcrossMillimetreMetreAndFoot_DeclaresMatchingUnitsAndPreserve Assert.Contains("=IFCSIUNIT(*,.AREAUNIT.,$,.SQUARE_METRE.);", outputs[IfcUnitFamily.Foot]); Assert.Contains("=IFCSIUNIT(*,.VOLUMEUNIT.,$,.CUBIC_METRE.);", outputs[IfcUnitFamily.Foot]); - foreach (var family in new[] { IfcUnitFamily.Millimetre, IfcUnitFamily.Metre, IfcUnitFamily.Foot }) - AssertValidIfcUnitGraph(outputs[family]); + string cm = outputs[IfcUnitFamily.Centimetre]; + Assert.Contains("=IFCSIUNIT(*,.LENGTHUNIT.,.CENTI.,.METRE.);", cm); + Assert.Contains("=IFCSIUNIT(*,.AREAUNIT.,.CENTI.,.SQUARE_METRE.);", cm); + Assert.Contains("=IFCSIUNIT(*,.VOLUMEUNIT.,.CENTI.,.CUBIC_METRE.);", cm); + string inch = outputs[IfcUnitFamily.Inch]; + Assert.Contains(",'INCH',", inch); + Assert.Contains(",'SQUARE INCH',", inch); + Assert.Contains(",'CUBIC INCH',", inch); + AssertConversionFactor(inch, "IFCLENGTHMEASURE", 0.0254); + AssertConversionFactor(inch, "IFCAREAMEASURE", 0.00064516); + AssertConversionFactor(inch, "IFCVOLUMEMEASURE", 0.000016387064); + + foreach (string ifc in outputs.Values) + AssertValidIfcUnitGraph(ifc); var mmMetrics = ExtractPhysicalMetricsInSi(outputs[IfcUnitFamily.Millimetre], IfcUnitFamily.Millimetre); - var mMetrics = ExtractPhysicalMetricsInSi(outputs[IfcUnitFamily.Metre], IfcUnitFamily.Metre); - var ftMetrics = ExtractPhysicalMetricsInSi(outputs[IfcUnitFamily.Foot], IfcUnitFamily.Foot); - Assert.NotEmpty(mmMetrics.Points); Assert.NotEmpty(mmMetrics.StoreyElevations); if (profile == IfcProfile.Current) @@ -381,20 +422,55 @@ public void Export_AcrossMillimetreMetreAndFoot_DeclaresMatchingUnitsAndPreserve Assert.NotEmpty(mmMetrics.Volumes); } - AssertListsClose(mmMetrics.StoreyElevations, mMetrics.StoreyElevations, 1e-9); - AssertListsClose(mmMetrics.StoreyElevations, ftMetrics.StoreyElevations, 1e-9); - AssertPointListsClose(mmMetrics.Points, mMetrics.Points, 1e-9); - AssertPointListsClose(mmMetrics.Points, ftMetrics.Points, 1e-9); - AssertListsClose(mmMetrics.Lengths, mMetrics.Lengths, 1e-9); - AssertListsClose(mmMetrics.Lengths, ftMetrics.Lengths, 1e-9); - AssertListsClose(mmMetrics.Areas, mMetrics.Areas, 1e-9); - AssertListsClose(mmMetrics.Areas, ftMetrics.Areas, 1e-9); - AssertListsClose(mmMetrics.Volumes, mMetrics.Volumes, 1e-9); - AssertListsClose(mmMetrics.Volumes, ftMetrics.Volumes, 1e-9); + foreach (var family in Enum.GetValues().Where(family => family != IfcUnitFamily.Millimetre)) + { + var metrics = ExtractPhysicalMetricsInSi(outputs[family], family); + AssertListsClose(mmMetrics.StoreyElevations, metrics.StoreyElevations, 1e-9); + AssertPointListsClose(mmMetrics.Points, metrics.Points, 1e-9); + AssertListsClose(mmMetrics.Depths, metrics.Depths, 1e-9); + AssertListsClose(mmMetrics.Lengths, metrics.Lengths, 1e-9); + AssertListsClose(mmMetrics.Areas, metrics.Areas, 1e-9); + AssertListsClose(mmMetrics.Volumes, metrics.Volumes, 1e-9); + if (family is IfcUnitFamily.Centimetre or IfcUnitFamily.Inch) + { + double precision = profile == IfcProfile.Current ? 0.0001 : 0.00001; + Assert.Equal(precision, metrics.Precision, 13); + } + } } finally { Directory.Delete(dir, recursive: true); } } + private static void AssertConversionFactor(string ifc, string measure, double expected) + { + var match = Assert.Single(Regex.Matches(ifc, $@"=IFCMEASUREWITHUNIT\({measure}\(([^)]+)\),")); + Assert.Equal(expected, double.Parse(match.Groups[1].Value, CultureInfo.InvariantCulture), 15); + } + + [Theory] + [InlineData(IfcUnitFamily.Centimetre, 0.01, 30.48)] + [InlineData(IfcUnitFamily.Inch, 0.0254, 12.0)] + public void Export_ScalesRebarRadiusAndLineParameterButKeepsTheArcAngle( + IfcUnitFamily family, double metresPerUnit, double lineParameter) + { + var info = new RevitFileInfo(); + info.Elements.Add(RebarReaderTests.Bar(500, 0)); + string path = Path.Combine(Path.GetTempPath(), $"rvtio-unit-rebar-{Guid.NewGuid():N}.ifc"); + try + { + new IfcExporter { LengthUnit = family }.Export(info, path); + string ifc = File.ReadAllText(path); + var disks = Regex.Matches(ifc, @"=IFCSWEPTDISKSOLID\(#\d+,([^,]+),\$,0\.,([^)]+)\);"); + Assert.Equal(2, disks.Count); + foreach (Match disk in disks) + { + Assert.Equal(0.004, double.Parse(disk.Groups[1].Value, CultureInfo.InvariantCulture) * metresPerUnit, 12); + Assert.Equal(lineParameter + 90, double.Parse(disk.Groups[2].Value, CultureInfo.InvariantCulture), 12); + } + } + finally { if (File.Exists(path)) File.Delete(path); } + } + [Fact] public void CliExport_WithIfcLengthUnit_WritesChosenUnitAndRejectsUnknownUnitsOrJsonOutput() { @@ -405,7 +481,7 @@ public void CliExport_WithIfcLengthUnit_WritesChosenUnitAndRejectsUnknownUnitsOr string rvt = Path.Combine(dir, "synthetic.rvt"); IfcDeterminismTests.WriteSyntheticRvt(rvt); - var (badExit, badErr) = RunCli(rvt, Path.Combine(dir, "bad.ifc"), "--ifc-length-unit", "cm"); + var (badExit, badErr) = RunCli(rvt, Path.Combine(dir, "bad.ifc"), "--ifc-length-unit", "km"); Assert.Equal(RvtExitCodes.Usage, badExit); Assert.Contains("--ifc-length-unit", badErr); Assert.False(File.Exists(Path.Combine(dir, "bad.ifc"))); @@ -418,13 +494,45 @@ public void CliExport_WithIfcLengthUnit_WritesChosenUnitAndRejectsUnknownUnitsOr string mmPath = Path.Combine(dir, "mm.ifc"); string mPath = Path.Combine(dir, "m.ifc"); string ftPath = Path.Combine(dir, "ft.ifc"); + string cmPath = Path.Combine(dir, "cm.ifc"); + string inPath = Path.Combine(dir, "in.ifc"); Assert.Equal(RvtExitCodes.Success, RunCli(rvt, mmPath, "--ifc-length-unit", "mm").ExitCode); Assert.Equal(RvtExitCodes.Success, RunCli(rvt, mPath, "--ifc-length-unit", "m").ExitCode); Assert.Equal(RvtExitCodes.Success, RunCli(rvt, ftPath, "--ifc-length-unit", "ft").ExitCode); + Assert.Equal(RvtExitCodes.Success, RunCli(rvt, cmPath, "--ifc-length-unit", "cm").ExitCode); + Assert.Equal(RvtExitCodes.Success, RunCli(rvt, inPath, "--ifc-length-unit", "in").ExitCode); Assert.Contains("=IFCSIUNIT(*,.LENGTHUNIT.,.MILLI.,.METRE.);", File.ReadAllText(mmPath)); Assert.Contains("=IFCSIUNIT(*,.LENGTHUNIT.,$,.METRE.);", File.ReadAllText(mPath)); Assert.Contains("'FOOT'", File.ReadAllText(ftPath)); + Assert.Contains("=IFCSIUNIT(*,.LENGTHUNIT.,.CENTI.,.METRE.);", File.ReadAllText(cmPath)); + Assert.Contains("'INCH'", File.ReadAllText(inPath)); + } + finally { Directory.Delete(dir, recursive: true); } + } + + [Theory] + [InlineData("cm")] + [InlineData("in")] + public void CliExport_WithIfcLengthUnit_LeavesBothJsonOutputsUnchanged(string unit) + { + string dir = Path.Combine(Path.GetTempPath(), $"rvtio-cli-unit-json-{Guid.NewGuid():N}"); + Directory.CreateDirectory(dir); + try + { + string rvt = Path.Combine(dir, "synthetic.rvt"); + IfcDeterminismTests.WriteSyntheticRvt(rvt); + string ifc = Path.Combine(dir, "model.ifc"); + string compact = Path.Combine(dir, "compact.json"); + string full = Path.Combine(dir, "full.json"); + string[] args = [rvt, "--ifc", ifc, "--compact-json", compact, "--full-json", full]; + Assert.Equal(RvtExitCodes.Success, RunCli(args).ExitCode); + byte[] compactDefault = File.ReadAllBytes(compact), fullDefault = File.ReadAllBytes(full); + + Assert.Equal(RvtExitCodes.Success, RunCli([.. args, "--ifc-length-unit", unit]).ExitCode); + + Assert.Equal(compactDefault, File.ReadAllBytes(compact)); + Assert.Equal(fullDefault, File.ReadAllBytes(full)); } finally { Directory.Delete(dir, recursive: true); } } @@ -433,9 +541,13 @@ public void CliExport_WithIfcLengthUnit_WritesChosenUnitAndRejectsUnknownUnitsOr [InlineData(IfcProfile.Current, IfcUnitFamily.Millimetre)] [InlineData(IfcProfile.Current, IfcUnitFamily.Metre)] [InlineData(IfcProfile.Current, IfcUnitFamily.Foot)] + [InlineData(IfcProfile.Current, IfcUnitFamily.Centimetre)] + [InlineData(IfcProfile.Current, IfcUnitFamily.Inch)] [InlineData(IfcProfile.Legacy, IfcUnitFamily.Millimetre)] [InlineData(IfcProfile.Legacy, IfcUnitFamily.Metre)] [InlineData(IfcProfile.Legacy, IfcUnitFamily.Foot)] + [InlineData(IfcProfile.Legacy, IfcUnitFamily.Centimetre)] + [InlineData(IfcProfile.Legacy, IfcUnitFamily.Inch)] public void Export_EmptyAndPopulatedModels_EmitSchemaValidUnitGraphAcrossProfilesAndFamilies( IfcProfile profile, IfcUnitFamily family) { @@ -467,7 +579,7 @@ public void Export_EmptyAndPopulatedModels_EmitSchemaValidUnitGraphAcrossProfile Assert.Contains(".WATT.", populatedIfc); } - if (family == IfcUnitFamily.Foot) + if (family is IfcUnitFamily.Foot or IfcUnitFamily.Inch) { foreach (string ifc in new[] { emptyIfc, populatedIfc }) { @@ -897,7 +1009,8 @@ private static RevitFileInfo BuildSampleModel(string storedUnit) } private sealed record PhysicalMetrics( - List Points, List StoreyElevations, List Lengths, List Areas, List Volumes); + List Points, List StoreyElevations, List Depths, List Lengths, + List Areas, List Volumes, double Precision); private static PhysicalMetrics ExtractPhysicalMetricsInSi(string ifc, IfcUnitFamily family) { @@ -906,16 +1019,20 @@ private static PhysicalMetrics ExtractPhysicalMetricsInSi(string ifc, IfcUnitFam IfcUnitFamily.Millimetre => 0.001, IfcUnitFamily.Metre => 1.0, IfcUnitFamily.Foot => IfcLengthUnit.MetresPerFoot, + IfcUnitFamily.Centimetre => 0.01, + IfcUnitFamily.Inch => 0.0254, _ => throw new ArgumentOutOfRangeException(nameof(family)), }; - double areaToSqMetres = family == IfcUnitFamily.Foot ? IfcLengthUnit.SquareMetresPerSquareFoot : 1.0; - double volumeToCuMetres = family == IfcUnitFamily.Foot ? IfcLengthUnit.CubicMetresPerCubicFoot : 1.0; + double areaToSqMetres = family is IfcUnitFamily.Millimetre or IfcUnitFamily.Metre ? 1.0 : lengthToMetres * lengthToMetres; + double volumeToCuMetres = family is IfcUnitFamily.Millimetre or IfcUnitFamily.Metre ? 1.0 : areaToSqMetres * lengthToMetres; var points = new List(); var elevations = new List(); + var depths = new List(); var lengths = new List(); var areas = new List(); var volumes = new List(); + double precision = 0; foreach (string rawLine in ifc.Split('\n')) { @@ -937,6 +1054,12 @@ private static PhysicalMetrics ExtractPhysicalMetricsInSi(string ifc, IfcUnitFam elevations.Add(elev * lengthToMetres); break; } + case "IFCGEOMETRICREPRESENTATIONCONTEXT": + precision = double.Parse(IfcExporter.SplitStepArguments(args)[3], CultureInfo.InvariantCulture) * lengthToMetres; + break; + case "IFCEXTRUDEDAREASOLID": + depths.Add(double.Parse(IfcExporter.SplitStepArguments(args)[3], CultureInfo.InvariantCulture) * lengthToMetres); + break; case "IFCQUANTITYLENGTH": lengths.Add(double.Parse(args[(args.LastIndexOf(',') + 1)..], System.Globalization.CultureInfo.InvariantCulture) * lengthToMetres); break; @@ -948,7 +1071,7 @@ private static PhysicalMetrics ExtractPhysicalMetricsInSi(string ifc, IfcUnitFam break; } } - return new PhysicalMetrics(points, elevations, lengths, areas, volumes); + return new PhysicalMetrics(points, elevations, depths, lengths, areas, volumes, precision); } private static void AssertListsClose(List expected, List actual, double relativeTolerance) From 7821caf5d78996f45d9eddcf85705287e5b2bc8c Mon Sep 17 00:00:00 2001 From: mahach666 <79989386+mahach666@users.noreply.github.com> Date: Mon, 23 Nov 2026 04:44:45 +0300 Subject: [PATCH 058/259] Use saved section planes in model units when printing PDFs --- CHANGELOG.md | 1 + src/RvtIO/Print/ElevationPrinter.cs | 4 +++- tests/RvtIO.Tests/ViewPlaneTests.cs | 30 +++++++++++++++++------------ 3 files changed, 22 insertions(+), 13 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5775540e..06d4e822 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,7 @@ API between minor releases. ### Fixed - Avoid overflow when triangulating trimmed faces with 46,341 or more vertices after bridging. +- Use the saved section plane in model millimetres to clip PDF geometry and place detail windows. ## [0.6.3] - 2026-11-20 diff --git a/src/RvtIO/Print/ElevationPrinter.cs b/src/RvtIO/Print/ElevationPrinter.cs index 3cfce504..b4114fd3 100644 --- a/src/RvtIO/Print/ElevationPrinter.cs +++ b/src/RvtIO/Print/ElevationPrinter.cs @@ -105,7 +105,9 @@ internal sealed record ElevationContent( ViewVerticalDirection: { Length: 3 } vert, ViewHorizontalDirection: { Length: 3 } horiz }) { (H, V, D) = (horiz, vert, dir); - planeOrigin = origin; + // Face vertices and the detail window use model millimetres. + planeOrigin = [origin[0] * FeetToMillimetres, origin[1] * FeetToMillimetres, + origin[2] * FeetToMillimetres]; // A section is cut at its plane: only what stands behind it is drawn. cut = direction == "section"; } diff --git a/tests/RvtIO.Tests/ViewPlaneTests.cs b/tests/RvtIO.Tests/ViewPlaneTests.cs index 3ba39cb9..f66aecd0 100644 --- a/tests/RvtIO.Tests/ViewPlaneTests.cs +++ b/tests/RvtIO.Tests/ViewPlaneTests.cs @@ -49,14 +49,14 @@ public void CollectViewPlanes_ReadsThePlaneOfTheViewBlock() Assert.Equal([0, -1, 0], plane.Horiz); } - private static Element SectionView(int id) + private static Element SectionView(int id, double[] origin) { return new Element { Id = id, CategoryId = (int)BuiltInCategory.OST_Views, NativeRootClassName = "DBViewSection", - ViewOrigin = [0, 0, 0], + ViewOrigin = origin, ViewDirection = [1, 0, 0], ViewVerticalDirection = [0, 0, 1], ViewHorizontalDirection = [0, -1, 0], @@ -81,22 +81,28 @@ private static Element WallWithFace(int id, double x) }; } - [Fact] - public void Collect_SectionIsCutAtItsPlane() + [Theory] + [InlineData(0, false)] + [InlineData(12.5, false)] + [InlineData(-7.75, false)] + [InlineData(12.5, true)] + public void Collect_SectionUsesTheSavedPlaneInModelUnits(double cutX, bool windowed) { - // The plane is at x = 0 looking along +x: the wall at x = -2 stands between the viewer and the plane and is cut - // away; the wall at x = 2 stands behind it and is drawn. + var view = SectionView(900, [cutX, 2, 1.5]); var document = RvtDocument.FromInfo(new RevitFileInfo { - Elements = { SectionView(900), WallWithFace(100, -2), WallWithFace(200, 2) }, + Elements = { view, WallWithFace(100, cutX - 2), WallWithFace(200, cutX + 2) }, }); - var content = ElevationPrinter.Collect(document, "section", planeView: document.GetElement(900)); + var content = ElevationPrinter.Collect(document, "section", planeView: view, + window: windowed ? (4 * FeetToMillimetres, 3 * FeetToMillimetres) : null); Assert.NotNull(content); - Assert.Single(content!.Faces); - // The wall at x = 2 ft is drawn; it spans y from 0 to 4 ft, and the horizontal axis is -y. - Assert.Equal(-4 * FeetToMillimetres, content!.MinX, 3); - Assert.Equal(0, content.MaxX, 3); + var face = Assert.Single(content!.Faces); + Assert.Equal((cutX + 2) * FeetToMillimetres, face.Depth, 3); + Assert.Equal(-4 * FeetToMillimetres, face.Points.Min(point => point.X), 3); + Assert.Equal(0, face.Points.Max(point => point.X), 3); + Assert.Equal(0, face.Points.Min(point => point.Y), 3); + Assert.Equal(3 * FeetToMillimetres, face.Points.Max(point => point.Y), 3); } } From bbc7b5528e90ca02dd44a1b09816c468042bbab9 Mon Sep 17 00:00:00 2001 From: mahach666 <79989386+mahach666@users.noreply.github.com> Date: Mon, 23 Nov 2026 04:46:20 +0300 Subject: [PATCH 059/259] Add offline parameter editing for Revit projects and families --- CHANGELOG.md | 4 + README.md | 2 +- docs/public-api.md | 2 +- docs/writing.md | 698 +++- src/RvtIO.Cli/Program.cs | 9 + src/RvtIO.Cli/SetParameterCommand.cs | 107 + src/RvtIO/Parsing/PagedGzipStream.cs | 20 +- src/RvtIO/Parsing/WideBlockWalker.cs | 43 +- src/RvtIO/Writing/FamilyFormulaPropagation.cs | 182 + src/RvtIO/Writing/FormulaParameterStorage.cs | 74 + src/RvtIO/Writing/GlobalParameterWriter.cs | 344 ++ src/RvtIO/Writing/ImportedImageReference.cs | 47 + src/RvtIO/Writing/LinkedImageReference.cs | 73 + .../Writing/LoadedFamilyParameterWriter.cs | 718 ++++ .../Writing/ParameterFormulaEvaluator.cs | 379 +++ src/RvtIO/Writing/ParameterMeasurement.cs | 165 + src/RvtIO/Writing/ParameterWriter.cs | 698 ++++ src/RvtIO/Writing/ProjectFamilyReference.cs | 240 ++ src/RvtIO/Writing/RvtWriter.cs | 155 +- .../StandaloneFamilyParameterWriter.cs | 828 +++++ src/RvtIO/Writing/UserParameterWriter.cs | 276 ++ tests/RvtIO.Tests/PagedGzipStreamTests.cs | 14 + tests/RvtIO.Tests/SetParameterTests.cs | 2971 +++++++++++++++++ .../StandaloneFamilyParameterTests.cs | 837 +++++ tests/RvtIO.Tests/WideBlockWalkerTests.cs | 3 + 25 files changed, 8857 insertions(+), 32 deletions(-) create mode 100644 src/RvtIO.Cli/SetParameterCommand.cs create mode 100644 src/RvtIO/Writing/FamilyFormulaPropagation.cs create mode 100644 src/RvtIO/Writing/FormulaParameterStorage.cs create mode 100644 src/RvtIO/Writing/GlobalParameterWriter.cs create mode 100644 src/RvtIO/Writing/ImportedImageReference.cs create mode 100644 src/RvtIO/Writing/LinkedImageReference.cs create mode 100644 src/RvtIO/Writing/LoadedFamilyParameterWriter.cs create mode 100644 src/RvtIO/Writing/ParameterFormulaEvaluator.cs create mode 100644 src/RvtIO/Writing/ParameterMeasurement.cs create mode 100644 src/RvtIO/Writing/ParameterWriter.cs create mode 100644 src/RvtIO/Writing/ProjectFamilyReference.cs create mode 100644 src/RvtIO/Writing/StandaloneFamilyParameterWriter.cs create mode 100644 src/RvtIO/Writing/UserParameterWriter.cs create mode 100644 tests/RvtIO.Tests/SetParameterTests.cs create mode 100644 tests/RvtIO.Tests/StandaloneFamilyParameterTests.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index 5775540e..578a579b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,10 @@ API between minor releases. ## [Unreleased] +### Added + +- Edit verified project and family parameters in local Revit 2020–2027 files without Revit. The API and CLI support single assignments and atomic batches, including supported clears, measured values, references, and verified family and global formulas. See the [writing guide](docs/writing.md). + ### Fixed - Avoid overflow when triangulating trimmed faces with 46,341 or more vertices after bridging. diff --git a/README.md b/README.md index 90aaf864..54c9218c 100644 --- a/README.md +++ b/README.md @@ -231,7 +231,7 @@ Wide creation IDs are available as `Element.OriginalElementId`. The Revit Unique - Version 0.4.0 is a preview. The API can change before 1.0. - Geometry coverage is partial for some element kinds. - Revit 2027 support is partial. -- There is no support for writing or modifying Revit files. +- Parameter editing supports single assignments and atomic batches of verified assignments and clears in local Revit 2020–2027 projects and standalone families. See the [writing guide](docs/writing.md). - IFC output is limited to IFC2X3 coordination view. - Output was compared with an independent reference exporter on the tested samples. Byte equality with Revit's own IFC export is not claimed. diff --git a/docs/public-api.md b/docs/public-api.md index 4a9078aa..4985abe5 100644 --- a/docs/public-api.md +++ b/docs/public-api.md @@ -187,7 +187,7 @@ elements that the IFC leaves out. Curved surfaces are the dense polygons the rea | Type | Use | |---|---| -| `RvtWriter` | Inspects the write-capability matrix (`InspectCapabilities`), writes lossless copies (`SaveAs`), and persists targeted stream and partition-record edits (`Rewrite`) for local `2020` to `2027` `.rvt` and `.rfa` files; see [writing and save-as](writing.md). | +| `RvtWriter` | Inspects write capabilities (`InspectCapabilities`), writes lossless copies (`SaveAs`), and persists targeted stream and partition-record edits (`Rewrite`). For supported parameters in local Revit 2020–2027 files it provides single assignments (`SetParameter`, `SetFamilyParameter`) and atomic batches (`SetParameters`, `SetFamilyParameters`). See [writing and save-as](writing.md) for edit records, `long` IDs and supported clears. | | `RvtWriteCapabilities`, `RvtOperationSupport`, `RvtFileKind`, `RvtWriteOperation` | Capability classification by file kind (`Project`, `Family`), release (`2020` to `2027`), element ID width (`4` or `8` bytes), worksharing/cloud flags, and operation (`SaveAs`, `PagedStreamRewrite`, `PartitionRecordRewrite`). | | `RvtWriteRequest`, `RvtPagedStreamEdit`, `RvtPartitionRecordEdit`, `RvtWriteResult` | Edit specifications for `Formats/Latest`, `Global/*`, and `Partitions/` records, and the verified write summary. | | `RvtWriteRefusedException` | Thrown with a stable `Kind` code when a file state or edit request is outside the supported write scope. | diff --git a/docs/writing.md b/docs/writing.md index dc12a948..4129d0ca 100644 --- a/docs/writing.md +++ b/docs/writing.md @@ -20,6 +20,693 @@ rvtio save-as project.rvt --check rvtio save-as project.rvt project.copy.rvt --report save-as.report.json ``` +## Editing a parameter + +`SetParameter` writes a new RVT without Revit installed. Pass the owning element ID, the parameter identifier, and the replacement value. + +```csharp +using RvtIO; +using RvtIO.BuiltIns; + +RvtWriter.SetParameter("project.rvt", "project.edited.rvt", 12345, BuiltInParameter.CLIENT_NAME, "Example Client"); +RvtWriter.SetParameter("project.rvt", "wall.edited.rvt", 42000, 43000, "Inspected"); +``` + +```sh +rvtio set-parameter project.rvt project.edited.rvt 12345 CLIENT_NAME "Example Client" +rvtio set-parameter project.rvt wall.edited.rvt 42000 43000 "Inspected" +``` + +The command accepts a built-in name or a signed 64-bit numeric ID. Use the positive definition element ID from the same project +for a project, shared, or loaded-family parameter. The scope is local, non-workshared Revit 2020–2027 projects with exactly one +readable project record for the element and a verified source for the parameter value. + +| Owner | Supported parameters | +| --- | --- | +| Project Information (`ProjectInfo`) | `CLIENT_NAME`, `PROJECT_ADDRESS`, `PROJECT_ISSUE_DATE`, `PROJECT_NAME`, `PROJECT_NUMBER`, `PROJECT_STATUS`. The matching system field in the English `ProjectInformation` XML must agree with the stored value. Both are updated together. | +| Straight wall or top-level loaded family instance | `ALL_MODEL_MARK` (Mark). The writer verifies the main-model owner and the element's text store. | +| Straight wall or top-level loaded Generic Model, Door, Window, or Furniture instance | `ALL_MODEL_INSTANCE_COMMENTS` (Comments). | +| Straight wall, room, or top-level loaded Generic Model, Door, Window, or Furniture instance | `ALL_MODEL_IMAGE` (Image). | +| Basic wall type | `ALL_MODEL_TYPE_IMAGE` (Type Image). | +| Basic wall type, primary or directly linked derived family symbol | `ALL_MODEL_TYPE_MARK` (Type Mark). Pass the ID of the type or symbol whose value you want to write. | +| Basic wall type or verified loaded family type | `ALL_MODEL_TYPE_COMMENTS`, `ALL_MODEL_DESCRIPTION`, `ALL_MODEL_MANUFACTURER`, `ALL_MODEL_MODEL`, `ALL_MODEL_URL`, and `ALL_MODEL_COST`. Cost takes a finite invariant number with no currency symbol. | +| Basic wall type or primary Door symbol without derived copies | `FIRE_RATING` (also named `DOOR_FIRE_RATING`, the same parameter ID). | +| Straight wall (`SWall`), basic wall type (`BasicWallType`), room (`RoomElem`) | Project and shared parameters of supported types with a verified definition and a matching instance or type binding. | +| Straight wall, basic wall type, room, or loaded family instance or type | **Family Type** parameters supplied by a verified project binding. Assign a matching nested type reference, a verified material ID, or `"-1"`. Shared definitions also accept the verified local element and active primary type references described below. A shared definition with `HideWhenNoValue` supports clearing. | +| Top-level loaded family instance (`FamilyInstance`) or primary family type (`FamilySymbol`) | Family and family-shared parameters of supported types. The loaded family must mark the parameter as independent of geometry. | +| Top-level loaded family instance or primary loaded family type | Family and family-shared **Family Type** parameters with a verified geometry-independent declaration. Assign a matching local nested type reference, a verified local material ID, or the explicit value `"-1"`. Primary type assignments also update verified derived copies. | +| Top-level loaded family instance (`FamilyInstance`) | Writable shared and non-shared parameters supplied by a verified project instance binding. Pass the instance's ID to assign or replace its own value. | +| Primary or directly linked derived family symbol (`FamilySymbol`) | Writable shared and non-shared parameters supplied by a verified project type binding. Pass the symbol's element ID to assign or replace its own value. | +| Global parameter (`GlobalParameter`) | Text, Integer, Yes/No, Number, Length, Area, Volume, Angle, Currency, Mass, Force, Mass Density, Speed, Slope, and Time, including inputs to verified formulas. Currency globals can update verified built-in Cost and shared Currency associations on walls, basic wall types, rooms, and loaded family elements. Use the global parameter's element ID for both `elementId` and `parameterId` in single edits and batches. | + +For project and shared parameters, the writer checks the definition's read-only flag and verifies the category binding in the main model. +Revit API editability governs shared parameters that the UI displays as read-only. The writer can also assign the first +value of a supported parameter on a straight wall, a basic wall type, or a room. First assignment of a wall comment requires +a wall in the main model. First assignment of project-bound text on walls and rooms requires a non-empty value. +The supported built-in Comments and text identity fields, and project-bound text on loaded family elements, accept an +empty string even on first assignment. +Ordinary element edits also work in projects with global parameters. RvtIO checks project associations by the +parameter ID on the element. A supported parameter can be assigned or cleared when another parameter on that +element has an association. The associated parameter is read-only. Group membership and unverified association +layouts still cause refusal. [Autodesk Revit API guide to parameter associations](https://help.autodesk.com/cloudhelp/2025/ENU/Revit-API/files/Revit_API_Developers_Guide/Basic_Interaction_with_Revit_Elements/Parameters/Revit_API_Revit_API_Developers_Guide_Basic_Interaction_with_Revit_Elements_Parameters_Parameter_html.html) + +For a **Family Type** parameter declared in a loaded family, the writer assigns a first value or replaces the current value +on the selected type or instance. An instance can receive its first local value while its type retains the inherited +default. A primary type assignment updates directly linked derived copies when their existing value agrees with +the primary value. Revit can report success for a direct assignment to a family-declared parameter on a derived +symbol while keeping its inherited value. RvtIO refuses that direct edit. Use the element ID of a verified +`NestedFamilyTypeReference` in the parameter's category or of a local material. An already active primary +`FamilySymbol` in the parameter's category can also be a target. RvtIO checks that the target belongs to a +different family in the main model. It follows registered family and type IDs in family maps and saved parameter +values, including edits already staged in the batch. The writer refuses unverified dependencies. For a family-declared, +geometry-independent parameter on an active primary type, the target can directly nest that shared type. The +container must map both the referring family and its type, and any private nested type references in the map +must resolve to records owned by that family. A dependency path back to the referring family remains outside +the supported instance edits. Use the explicit string `"-1"` to assign Revit's invalid element ID. +[Autodesk Family.GetFamilyTypeParameterValues reference](https://help.autodesk.com/cloudhelp/2026/ENU/Revit-API-MainReference/files/html/a9c8ff23-17ec-1b87-e58a-4be589217766.htm) + +For a **Family Type** parameter supplied by a shared project binding, a verified active primary +`FamilySymbol` can also come from a different category. This applies on supported loaded family types and +instances, straight walls, basic wall types, and rooms. The value is stored on the addressed element. On a +loaded family type or instance, the target can be its own primary type, another primary type of the same family, +or a family type that nests the referring family. The same binding also accepts a verified local basic `WallType`, +`RebarCoverType`, `Level`, loadable `Family`, or top-level `FamilyInstance`. RvtIO checks the +target ID, class, and main-model header. A `NestedFamilyTypeReference` must still match the parameter category. +Assigning `"-1"` leaves a stored value. Clearing removes the assigned value and requires a shared project binding +with `HideWhenNoValue`. + +Global parameter edits require an explicit value. The writer checks the full project element table and stored +formula, dimension, and element property references before changing a global value. Use the normal numeric and +unit formats below. A writable Currency global takes a finite invariant number with no currency symbol, +for example `1234.56789` or `-58.625`. The writer refuses differences for which Revit can retain the previous +number under its comparison tolerance. Use an empty string to assign empty Text, or `0` to assign an unchecked Yes/No value. +If a global value controls a verified project-bound user parameter, RvtIO updates both values in the same batch. +The controlled property must have matching storage and units, and its saved value must match the previous global +value. This applies to project properties controlled directly by the edited global and to properties controlled by +the result of a recalculated global formula. The element parameter remains read-only through a direct assignment. +[Autodesk GlobalParameter.SetValue reference](https://help.autodesk.com/cloudhelp/2026/ENU/Revit-API-MainReference/files/html/df012c22-6e65-8de5-1057-f15660d02288.htm) +The same write path supports verified parameters declared by a loaded family when the family marks the parameter +as independent of geometry. An instance association updates the local value and its dependent formulas. A type +association updates the primary symbol and recalculates affected instance results, including on placements with +derived symbols. Derived symbol records retain their saved values in this case. +A Text global can also update Type Comments, Description, Manufacturer, and Model on a primary Generic Model, +Door, Window, or Furniture type, and Fire Rating on a primary Door type. A Currency global can update the +type's Cost. The writer verifies the existing value in the typed element store +or named family store. A Generic Model global updates the primary or directly derived symbols to which it is +associated. Starting with the 2022 format, a Text global can also update Comments on a main-model wall +or a top-level Generic Model instance. These edits require an existing association and use the global parameter's +ID for both edit IDs. +Verified formulas support parentheses, negation, addition, subtraction, multiplication, and division with +compatible units. They also support `=`, `>`, `<`, `and`, `or`, `not`, and `if` with numeric, Yes/No, or Text +branches as permitted by the formula type. Only the selected branch of `if` is evaluated. In `and` and `or`, +the writer evaluates the second operand only when the first operand does not determine the answer. Unitless formulas +support `round`, `roundup`, and `rounddown`. Integer results use Revit's nearest-integer rounding, with exact +halves rounded toward the greater integer. Recalculation uses the stored integer result in downstream formulas. +Global formulas treat Currency and Number as scalar numbers. Results retain their original parameter type for +associations. Revit accepted `CurrencyInput + 2` in the tested formulas and rejected +`CurrencyInput + 2 $`. +Mass, Force, Mass Density, Speed, Slope, and Time also support verified formula dependencies and existing global +associations. Formulas can scale the quantity and add a compatible measured constant. Revit evaluates Slope as +a ratio in formulas. For example, a formula that adds 2 percentage points stores the constant as the number `0.02`. +An association still requires the Slope parameter type on both ends. +[Autodesk global parameter association reference](https://help.autodesk.com/cloudhelp/2026/ENU/Revit-API-MainReference/files/html/796f3d95-956e-a2a9-7f8e-e8efd2a0eea0.htm) +Mathematical functions include `abs`, `sqrt`, `exp`, `log`, `ln`, `sin`, `cos`, `tan`, `asin`, `acos`, `atan`, +and `pi()`. Square roots support scalars and areas. Trigonometric functions accept angles in radians internally, +and the inverse functions return angles. Powers (`^`) support scalar bases with scalar exponents, length squared +or cubed, and the square root of an area. +The writer checks the current stored results and updates every affected value in the same batch. For verified +cases where Revit accepts a new input and retains a formula's previous result, RvtIO preserves that result's bytes. +These include division by a zero or almost-zero denominator, negative square roots, logarithms below the +verified positive threshold, inverse sine or cosine outside their domain, tangent at a verified pole, +exponential results above a magnitude of `1e30`, and powers that underflow to zero. Other formulas referencing +the affected parameter use its stored value until it can be recalculated. Unverified mathematical inputs, +ambiguous changes or comparisons, and rounding near tolerance boundaries still cause refusal. Global values +that also control dimensions or other unverified dependents still cause refusal. + +For a parameter declared in the loaded family, pass the instance ID to update an override or create one from a verified +inherited value. Pass the primary type ID to update that type and its verified derived copies together. Assigning a +verified input on the primary type also recalculates dependent formula values in the type, its derived copies, and +the affected stored values on top-level instances. Each instance uses its own stored overrides as formula inputs. +Assigning a stored input on a top-level instance recalculates that instance's stored formula results using its +effective symbol and local values. Every updated value must be classified by the family as independent of geometry. +On a primary loaded type, RvtIO also supports direct assignments to numeric results of verified linear formulas +with one writable type input. It solves for the input and recalculates the affected values. With an integer input, +an exact half rounds toward positive infinity, so assigning `99` to the result of `input * 2` can store input `50` +and result `100`. If the requested result already matches, the input stays at its current value. Inverses that +change a real input require exact scaling. Reporting parameters and unverified expressions, scopes, or associations +still cause refusal. + +Revit 2025 exposes the tested loaded type formulas for Boolean identity, Boolean negation, a numeric conditional +controlled by a Boolean parameter, and text identity as read-only. Revit 2027 also refused the tested numeric +formula with two independent inputs. +For a parameter supplied only by a project binding, the assignment edits the addressed symbol or instance's +typed value. The writer verifies that the loaded family does not also declare the same parameter. +The supported built-in Comments and identity fields also edit the addressed element's own value. An assignment to a +primary symbol through the verified project value store preserves local values of its derived symbols. +Door, Window, and Furniture identity fields support primary symbols without derived copies. The writer follows the +storage Revit uses for the parameter, either a value in the project store or an existing value imported from the +family. Editing an imported Generic Model identity field on the primary symbol also updates its verified derived +copies when they match the previous primary value. Generic Model identity fields in the project store can be +edited on the primary or a directly linked derived symbol by its own ID. + +Supported types are Text, Integer, Yes/No, Number, Length, Area, Volume, Angle, and Material. Use `0` or `1` for Yes/No. +Integers respect the stored definition bounds. For Number, pass a finite invariant decimal without a unit. For measurements, +pass a finite invariant decimal followed by a space and the unit. Length accepts `mm`, `cm`, `m`, `in`, and `ft`. Area accepts +`m2` and `ft2`. Volume accepts `m3` and `ft3`. Angles accept `deg` and `rad`. The corresponding `²`, `³`, and `°` symbols also work. +Assignments also accept Mass in `kg`, Force in `kN`, Mass Density in `kg/m3` or `kg/m³`, +Speed in `m/s`, Slope in `%`, and Time in `s`. In a value such as `16.5 %`, the space separates the value +from the unit. RvtIO converts the quantity to Revit's internal units before writing. +[Autodesk Revit API unit system](https://help.autodesk.com/cloudhelp/2024/ENU/Revit-API/files/Revit_API_Developers_Guide/Introduction/Application_and_Document/Revit_API_Revit_API_Developers_Guide_Introduction_Application_and_Document_Units_html.html) +Shared project-bound Currency values on walls, basic wall types, rooms, top-level loaded family instances, and +primary and directly linked derived symbols use a finite invariant number with no currency symbol. An explicit zero +gives the parameter a value. Clearing requires `HideWhenNoValue`. The writer refuses changes that Revit may +suppress within its numeric comparison tolerance. [Autodesk shared parameter guide](https://help.autodesk.com/cloudhelp/2026/ENU/Revit-API/files/Revit_API_Developers_Guide/Basic_Interaction_with_Revit_Elements/Parameters/Revit_API_Revit_API_Developers_Guide_Basic_Interaction_with_Revit_Elements_Parameters_Shared_Parameters_html.html) +Family-declared Currency values on loaded primary types and top-level instances use the same numeric input. +The writer checks the effective value, including an inherited instance default, against Revit's comparison tolerance. +It recalculates verified dependent results and supports a calculated Currency type value when its formula has +one verified Currency input with exact scaling. An existing Currency global association uses the same +family dependency checks. +When Revit keeps an instance's calculated Currency value within its relative comparison tolerance, the writer preserves +that saved value for a result with no downstream formulas. A subsequent input change can recalculate the result from +the retained value. +On loaded families, the writer recalculates verified Mass, Force, Mass Density, Speed, Slope, and Time results after +editing a type value or a top-level instance input. It also supports assignment to a primary type's calculated +value when Revit permits solving the exact scaling of one input of the same type. +For Material, pass the positive ID of an existing material in the source file. A non-shared project Material +parameter on a loaded family type also accepts `-1` to explicitly assign `By Category` through the same operation +as `Parameter.Set(ElementId.InvalidElementId)`. + +For a supported project Image or Type Image built-in, pass the positive ID of a verified imported or locally +linked image in the project. Revit also persists a verified project level ID in these fields as an element +reference. An explicit `-1` assigns None and leaves a stored value. Linked images require the verified absolute +or relative local resource layout introduced for image links in Revit 2021. [Autodesk linking documentation](https://help.autodesk.com/cloudhelp/2021/ENU/Revit-HaveYouTried/files/GUID-52C359EE-4FBC-400F-9216-73CB0F578CBA.htm) + +When writing to another directory, RvtIO checks the saved path of root project image links. It refuses a write +if a relative image path would resolve to a different file, or if the link's path layout cannot be verified. + +```sh +rvtio set-parameter project.rvt project.edited.rvt 42000 43000 "300 mm" +rvtio set-parameter project.rvt with-material.rvt 42000 43001 44000 +rvtio set-parameter project.rvt with-global-value.rvt 45000 45000 "3.625 ft" +rvtio set-family-parameter cabinet.rfa cabinet.edited.rfa "Standard" 12345 "0.25 m²" +``` + +`HOST_AREA_COMPUTED` fails with `read-only-parameter`. Unsupported edits fail without creating an output. +An identical value produces a lossless copy. The input and existing destination files are preserved. + +The command uses exit code 0 for success, 1 for invalid arguments, 2 for input or I/O errors, and 5 for a refused edit. +Low-level `Rewrite` accepts raw stream or record payloads and does not perform parameter editability checks. + +## Editing a standalone family + +`SetFamilyParameter` saves a new local Revit 2020–2027 `.rfa` without Revit installed. Pass the exact family type name, +the replacement value, and either the positive definition ID from the same family or the signed ID of a supported built-in. +The command also accepts the built-in name. + +```sh +rvtio set-family-parameter door.rfa door.edited.rfa "900 x 2100" 12345 "Acoustic seal" +rvtio set-family-parameter fixture.rfa fixture.edited.rfa "Standard" ALL_MODEL_TYPE_COMMENTS "Inspection required" +rvtio set-family-parameter fixture.rfa fixture.elevated.rfa "Standard" FAMILY_FREEINST_DEFAULT_ELEVATION "300 mm" +``` + +```csharp +RvtWriter.SetFamilyParameter("door.rfa", "door.edited.rfa", "900 x 2100", 12345, "Acoustic seal"); +``` + +Standalone families use the same input formats as projects. Existing family and shared parameters can supply type values +or instance defaults. The writer checks each active record for dependencies and refuses +read-only definitions, reporting parameters, direct writes to formula results, element associations, and +families with unverified dimension constraints or protection. +Mass, Force, Mass Density, Speed, Slope, and Time assignments update the matching type's `PartAtom` +entry when its stored display format can be verified. The same checks apply to values calculated by verified formulas. +Currency values take a finite invariant number with no currency symbol. Changes that Revit may suppress within +its numeric comparison tolerance are refused. Formulas use the unrounded stored value. With the verified two-decimal +currency format, `PartAtom` stores the rounded display value and its currency unit. Amounts rounded to zero use `0.00`. +Native checks covered first assignments, replacements, and ordered batches on active and inactive types and on +instance defaults. The 24 family-parameter files and 24 shared-parameter files matched `FamilyManager.Set` after +Save As and reopening without Audit in Revit 2020–2025 and 2027. The 2026-format files passed after upgrade in +Revit 2027. Eighty-eight invalid batches left the source bytes intact and created no output. +[Autodesk FamilyManager.Set reference](https://help.autodesk.com/cloudhelp/2026/ENU/Revit-API-MainReference/files/html/7fc40346-6188-66ff-4c00-bd4360e70c6f.htm) + +An assignment to a verified formula input recalculates the selected type's dependent results in the same batch. This +also applies to formulas for instance defaults stored on that type. The writer checks saved results against the +formula, verifies that no affected parameter drives geometry or an association, and updates the corresponding +`PartAtom` values. It refuses results it cannot compute or store exactly. The verified cases include arithmetic +chains, measured values, Yes/No conditions, and text results. + +The writer updates the selected type and its current-value copy if it is the active type. It also updates matching `PartAtom` +metadata and adds the missing entry when filling an empty, visible user text parameter. User and shared parameters must +have a stored row for the selected type. The source, any existing destination, and the active type selection are preserved. +For measured type parameters, a matching `PartAtom` entry requires a verified decimal display format. For materials, +`PartAtom` uses the name of the material read from the same document. + +**Family Type** parameters in standalone families accept the element ID of a verified local nested type. +Family and shared definitions support first assignment and replacement on both type values and instance defaults. For a +shared definition, the metadata entry is identified by its GUID. Use the explicit string +`"-1"` to assign Revit's invalid element ID. Revit also stores an ID for a nested type in another category or +for a local material passed to this setter, and RvtIO supports those verified cases. The writer keeps the active +type's copy in sync and updates the visible type entry in `PartAtom` when the reference resolves to a nested type. +Revit omits that entry for `-1` and for material IDs. A new entry requires a verified metadata category label. +Missing element IDs are rejected. [Autodesk FamilyManager.Set reference](https://help.autodesk.com/cloudhelp/2026/ENU/Revit-API-MainReference/files/html/5004314a-c77f-e469-1e03-395f5e17de5a.htm) + +The built-in type fields `ALL_MODEL_TYPE_COMMENTS`, `ALL_MODEL_DESCRIPTION`, `ALL_MODEL_MANUFACTURER`, +`ALL_MODEL_MODEL`, `ALL_MODEL_URL`, and `ALL_MODEL_COST` support first assignment and replacement in Generic Model, +Door, Window, and Furniture families. Doors also support `FIRE_RATING` (also named `DOOR_FIRE_RATING`). +Door identity writes accept the verified layout for dimension constraints independent of the edited parameter. The writer checks parameter +references from dimension labels, constraint expressions, family formulas, and element associations. + +On first assignment the other named types receive the Revit default, empty text or zero. If a door or window +also contains an unnamed type, Revit copies each assigned identity value to it. The command targets the named +type. Assign an empty string to write empty built-in text. Cost takes a finite invariant number and requires +the default two-decimal currency format with `$` in the family metadata. + +In Generic Model families, `FAMILY_FREEINST_DEFAULT_ELEVATION` takes a length with an explicit unit. The type table must contain the parameter +and the family must use a verified decimal length format for the matching `PartAtom` value. +`ALL_MODEL_TYPE_IMAGE` takes the positive ID of a verified raster image already imported into the same family. +An explicit `-1` sets it to None. On first assignment the other types receive None, and the imported image data is preserved. +Revit accepts imported images in family documents. [Autodesk ImageTypeOptions reference](https://help.autodesk.com/cloudhelp/2026/ENU/Revit-API-MainReference/files/html/47f3832b-9cf5-4628-214d-7e7e7d705393.htm) + +A visible non-shared custom type parameter of data type **Image** also accepts the positive ID of a verified raster +image imported into the same family. RvtIO replaces the selected type's saved reference and the image name in its +`PartAtom` entry. On the active type it updates the current-value copy too. Assign `"-1"` explicitly to select None. + +The command uses the same exit codes as `set-parameter`. + +## Applying a parameter batch + +`SetParameters` edits one local RVT and `SetFamilyParameters` edits one local RFA. Each takes a non-empty list and +applies it in order. Repeated edits to the same parameter see the previous value in the batch. The writer publishes +the new file only after every operation and the final container pass validation. A refused edit leaves the source +untouched and produces no destination file. + +```csharp +RvtWriter.SetParameters("project.rvt", "project.edited.rvt", +[ + new RvtParameterEdit(42000, 43000, "Inspected"), + new RvtParameterEdit(42000, 43001, null), +]); + +RvtWriter.SetFamilyParameters("door.rfa", "door.edited.rfa", +[ + new RvtFamilyParameterEdit("900 x 2100", 12345, null), + new RvtFamilyParameterEdit("900 x 2100", 12346, "300 mm"), +]); +``` + +```sh +rvtio edit-parameters project.rvt project.edited.rvt project-edits.json +rvtio edit-parameters door.rfa door.edited.rfa family-edits.json +``` + +Each manifest is a JSON array. An RVT entry has `elementId`, numeric `parameterId`, and `value`. +An RFA entry has `typeName`, signed numeric `parameterId`, and `value`. +For example, an RVT assignment is `{"elementId":42000,"parameterId":43000,"value":"Inspected"}`. +An RFA reset is `{"typeName":"900 x 2100","parameterId":12345,"value":null}`. + +Pass a string to assign a value using the same formats and write checks as single edits. To clear or reset, +pass an explicit JSON or C# `null`. + +| File | Effect of `null` | +| --- | --- | +| RVT | Removes the stored value of a writable, supported shared parameter with `HideWhenNoValue` and a matching project binding. This corresponds to Revit API `Parameter.ClearValue()`. Supported owners include straight walls, basic wall types, rooms, top-level loaded family instances, and primary and directly linked derived symbols of loaded families. | +| RFA | Resets supported user and shared text parameters to empty text and material parameters to `By Category`. This corresponds to `FamilyManager.Set(parameter, "")` or `FamilyManager.Set(parameter, ElementId.InvalidElementId)`. Built-ins and numeric values require an explicit assignment. | + +An empty string in an RVT is a text assignment where supported. It is distinct from clearing the value. +Revit's `ClearValue()` returns false for values declared inside a loaded family, even when the shared definition +has `HideWhenNoValue` and the same definition is also bound in the project. The batch rejects those clears, +along with built-ins, non-shared parameters, and shared parameters with the flag disabled. +For a loaded type with derived symbols, use the element ID of the symbol whose value you want to clear. +Revit clears the primary value and each local derived value independently. Include one edit per symbol to clear both +the primary value and local copies in the same batch. The writer verifies the direct links and the local parameter stores. +An assignment to a primary or derived symbol also uses its own ID and edits its local value. +The batch command uses the same exit codes as `set-parameter`. + +The batch round-trip checks used Revit 2020, 2022 and 2027. The API values in the edited RVT and RFA matched the +Revit-authored reference files both at the initial open and after SaveAs and reopen, with Audit disabled. + +For shared project instance bindings on loaded families, these checks covered first assignment, replacement, and +first empty text. They included Text, Integer, Yes/No, Number, Length, and Material with both settings of +`HideWhenNoValue`. This scenario still lacks direct checks in Revit 2021, 2023, 2024, 2025, and 2026. + +The Mark and Type Mark checks in the same three Revit releases covered first assignment, replacement, and empty +text, including a separate Type Mark assignment to a derived symbol. Direct checks for these assignments are pending +in Revit 2021, 2023, 2024, 2025, and 2026. + +The Comments and type identity checks compared first assignment, replacement, and empty text against values +written by the Revit API in Revit 2020–2025 and 2027. Each check opened the edited RVT without Audit and read +the values again after SaveAs and reopening without Audit. The cases included basic wall types, straight walls, +and instances and symbols of a loaded Generic Model family. The same releases also verified first assignment and +replacement on a derived symbol and checked the values of the other symbols. Revit 2027 upgraded and verified +the same cases in controlled 2026-format files. Direct checks in Revit 2026 are pending. + +Revit 2020–2025 and 2027 verified 15 Comments assignments each on hosted Door and Window instances and +unhosted Furniture instances. First assignment, replacement, and empty text matched the API-authored files, +including `HasValue`, symbol and host IDs, and instance locations, after SaveAs and reopening without Audit. +Revit 2027 verified the 2026-format fixtures after upgrading them. + +The standalone Generic Model built-in checks covered first assignment and replacement in the active type and +another type, empty strings, and the default values that Revit records for the other types. Revit 2020–2025 and +2027 opened, saved, and reopened the edited RFA files without Audit. All values and `HasValue` flags matched +the files written by `FamilyManager.Set`. Revit 2027 also verified the 2026-format fixtures after upgrading +them. Direct verification in Revit 2026 is pending. + +Revit 2020–2025 and 2027 verified first assignment and replacement of Default Elevation and Type Image in the +active and inactive types, and resetting a recorded image to None. The edited values, the active type, and +`HasValue` matched the API-authored references after open, SaveAs, and reopen without Audit. Revit 2022 and +2027 also checked setting an unassigned image to None. Revit 2027 verified the cases in the 2026 format after +upgrading the files. Direct verification in Revit 2026 is pending. + +Project Image and Type Image checks covered first assignment, replacement, and explicit None on straight +walls, rooms, top-level Generic Model instances, and basic wall types. Revit 2020–2025 and 2027 verified the +image IDs and `HasValue` after resaving and reopening without Audit. Revit 2027 also verified the 2026-format +files after upgrade. The measured wall and room geometry matched the native results. Batches with a missing +image ID, a `null` clear, or a Type Image edit on the tested read-only loaded type preserved the original bytes +and created no output in every format. + +The same four assignment cases were verified on top-level Door, Window, and Furniture instances. Revit +2020–2025 and 2027 opened, resaved, and reopened the files without Audit. Revit 2027 verified the 2026 format +after upgrade. All 48 assignments per format matched the native image IDs, `HasValue`, instance hosts, and +bounds. The tested loaded family types reported Type Image as read-only throughout these checks. + +The project Image checks also covered first assignment and replacement with local absolute image links, +local relative image links, and level references. Revit 2021–2025 and 2027 verified 24 assignments per +release on straight walls, rooms, top-level Generic Model instances, and basic wall types. The files opened, +resaved, and reopened without Audit. Revit 2027 also verified the 2026-format files after upgrade. +Revit 2020 verified the eight level assignments. Revit 2021 introduced +image links. The linked images reloaded successfully in the applicable releases. Batches with missing IDs +left their source bytes intact and created no output file. Relocation that changed a relative image's target +was also refused. Revit 2025 verified the copy between sibling folders that resolved the same relative +image path to the same file, including reloading both relative and absolute links after resaving. + +For non-shared custom type Image parameters in standalone Generic Model families, Revit verified the first local +image, replacement, and explicit None in both the active type and another type. Revit 2020–2025 and 2027 opened, +resaved, and reopened the results without Audit. Revit 2027 verified the 2026-format files after upgrade. The API +returned the expected image IDs, `HasValue`, and active type. The image names in `PartAtom` matched the native +results. A batch containing a missing image ID or a `null` clear left the source bytes intact and created no output +file in every format. + +Standalone Door, Window, and Furniture identity assignments were verified in Revit 2020–2025 and 2027 after opening, +saving, and reopening without Audit. The checks covered first assignment, replacement, and empty values, +and compared formula values, dimensions, the active type, and the unnamed type against native files. +Revit 2022 and 2027 also checked assignments while the unnamed type was active. Revit 2027 verified both +cases in files upgraded from the 2026 format. Direct verification in Revit 2026 is pending. + +For loaded types in RVT, Revit 2020–2025 and 2027 verified 220 assignments each on Door, Window, Furniture, +and Generic Model symbols. The tests covered first assignment, replacement, and empty values in the applicable +project and imported family stores. Values, `HasValue`, and sibling types matched the API-authored files after +SaveAs and reopening without Audit. Revit 2027 also verified the 2026-format cases after upgrading the files. + +For imported Generic Model identity fields with derived symbol copies, the values and instance geometry matched +the API-authored files after SaveAs and reopening without Audit. Revit 2020, 2022, and 2027 checked all six +Generic Model type identity fields. Revit 2025 checked Type Comments and Cost. Revit 2027 also verified all six +fields after upgrading fixtures from the 2026 format. Direct `Set` calls on the derived copies reported success. +Revit saved the previous values in these fixtures. Use the primary type ID for imported identity edits. +Direct verification in Revit 2021, 2023, 2024, and 2026 is pending for this scenario. + +Independent global values matched native first assignments and replacements after opening, SaveAs, and +reopening without Audit in Revit 2020–2025 and 2027. The checks covered Text, Integer, Yes/No, Number, Length, +Area, Volume, and Angle, and compared the source and result of an unrelated formula. Revit 2027 also verified +the 2026-format fixtures after upgrading them. In Revit 2027, another fixture preserved an unrelated wall association through the same +round-trip and verified whole-batch refusal when an edit targeted the global value driving that wall. + +Independent Currency checks covered the first assignment, a negative replacement, and both edits in an +ordered batch. The 24 edited files matched the API after Save As and reopening without Audit in Revit 2020–2025 +and 2027, including 2026-format files upgraded in Revit 2027. Seven batches per format refused an invalid value, +a clear, or an ambiguous numeric change. The source bytes were preserved and no output was produced. +Two additional Revit 2025 files retained Currency changes just outside the comparison tolerance after reopening. + +Currency formula checks compared first assignments, replacements, and ordered batches in 24 files. The fixtures +covered arithmetic, a comparison, a conditional branch, Currency and Number results, and a formula-driven +Currency result associated with a Generic Model type's built-in Cost. Revit 2020–2025 and 2027 retained all values +and the Cost association after Save As and reopening without Audit. The 2026-format files passed after upgrade +in Revit 2027. Forty batches that included a direct assignment to a calculated value or controlled Cost, +an ambiguous numeric change, or a Currency clear were refused with the source bytes intact and no output. + +Ordinary element writes alongside global associations matched 168 Revit API assignments and clears across the +eight formats. The checks covered walls, a wall type, a loaded family instance, and a loaded family type, including +editing one parameter while preserving an association on another parameter of the same element. Revit 2020–2025 +and 2027 opened, saved, and reopened the files with Audit disabled. Revit 2027 upgraded and verified the +2026-format files. In every format, batches targeting a controlled wall, instance, or type parameter left the +source bytes intact and created no output. A mixed batch with a global formula input and an independent wall +comment matched Revit 2021 in either edit order. + +Global assignments that update project properties matched 136 Revit API assignments and 224 linked property +updates across the eight formats. The checks covered all eight supported global data types on wall properties, +one global text value shared by multiple walls, a wall type and a loaded family instance, and a recalculated +integer formula driving a property. Empty text stayed present after the assignment. Revit 2020–2025 and 2027 +opened, saved, and reopened the files with Audit disabled. Revit 2027 upgraded and verified the 2026-format files. +Four invalid batches per format left the source bytes intact and created no output. + +Shared Currency checks covered first assignment, replacement, clearing, and ordered batches on walls and basic wall +types, including an explicit first zero and updates through an existing global association. The 56 edited files matched +the API values, presence flags, and associations after Save As and reopening without Audit in Revit 2020–2025 and 2027. +Revit 2027 also verified files upgraded from the 2026 format. Forty invalid batches preserved the source bytes and +created no output. +Three further Revit 2025 files verified first assignments of tiny nonzero values and updates from a recalculated +Currency global formula after Save As and reopening without Audit. + +Shared Currency checks also covered project bindings on rooms, top-level loaded family instances, and primary and +directly linked derived family symbols. The matrix used shared definitions with both settings of `HideWhenNoValue`, +including a first value of zero, replacement, clearing hidden values, ordered batches, and updates through an +existing global association. For 49 edited files, the affected element records matched native writes in +Revit 2020–2025 and 2027. Revit 2027 verified the seven 2026-format files after upgrade. All 56 projects matched the +expected API values, presence flags, associations, room area, and instance bounds after Save As and reopening +without Audit. Thirty-two refused batches preserved the source bytes and created no output. + +Independent Mass, Force, Mass Density, Speed, Slope, and Time checks covered 64 files. Project fixtures included +shared values on walls and wall types, family-defined values on loaded primary types and top-level instances, +and independent global parameters. Standalone family fixtures covered custom and shared type values and instance +defaults. First assignments, negative replacements, and ordered batches matched the Revit API. Project-bound +values with `HideWhenNoValue` also matched after clearing. For 56 files, affected records matched native writes +in Revit 2020–2025 and 2027. Revit 2027 verified eight 2026-format files after upgrade. API values and family +`PartAtom` entries matched after Save As and reopening without Audit. Fifty-six refused batches preserved the +source bytes and created no output. Three additional Revit 2025 family files matched stored values and +`PartAtom` at a negative value that rounds to zero and at positive and negative decimal rounding midpoints +after Save As and reopening without Audit. + +Formula checks for the same six specs covered 80 projects and standalone families. They compared first assignments, +replacements, ordered batches, an exact loaded type inverse, and updates through existing global associations to +project-bound and family-declared values. The fixtures used scaling, sums of compatible parameters, and measured +constants. For 70 files, the affected records matched Revit 2020–2025 and 2027. Revit 2027 verified ten files after +upgrading them from the 2026 format. All files matched the API values and, for families, their `PartAtom` entries +after Save As and reopening without Audit. Fifty-six refused batches preserved the source bytes and created no output. + +Global assignments to loaded family parameters matched 240 Revit API assignments across the eight formats. +The fixtures included shared family definitions, empty text, unitless and measured values, links to recalculated +global formula results, and type inputs consumed by formulas on multiple placements with separate local inputs. +The affected placements retained their values after SaveAs and reopening without Audit in Revit 2020–2025 and +2027. Revit 2027 upgraded and verified the 2026-format files. In each format, batches with a geometry-driving +global, a formula-driven global, or a direct write to an associated instance or type parameter were refused +without changing the source or creating an output. + +Global Text assignments to built-in properties matched 48 Revit API assignments and 132 linked property +updates across the eight formats. The fixtures covered the first nonempty value, replacement, and explicit +empty text. Revit 2020–2025 and 2027 verified the values and association IDs after SaveAs and reopening +without Audit. The same checks covered 16 Currency assignments that updated Cost on Generic Model types. +Revit 2027 upgraded the controlled 2026-format fixtures. Seventy-six batches containing a direct write to an +associated property, an unverified geometry-driving global, or an invalid Currency value preserved the source +bytes and created no output. + +The Door, Window, and Furniture type fixtures matched 96 global assignments and 768 linked built-in writes +against Revit. They covered first nonempty values, replacements, empty text and zero Cost in both the typed +and named stores. The Generic Model fixtures with derived symbol copies matched 144 more global assignments +and 480 linked built-in writes. They covered a primary symbol, a derived symbol, and both symbols linked to +the same global. Unassociated symbol records matched the source byte for byte. Revit 2020–2025 and 2027 read +the values and association IDs before and after SaveAs with Audit disabled. Revit 2027 upgraded the +2026-format fixtures. All 88 rejected batches preserved the source bytes and left no output. + +Non-shared project parameter checks matched 264 direct assignments and 48 global assignments that updated +72 linked values. The Generic Model fixtures covered Text and Length on top-level instances and Text and +Material on primary and directly derived symbols. They included first assignment, replacement, explicit +empty text, zero Length and Material set to `By Category`. Revit 2020–2025 and 2027 checked the values +after opening, SaveAs and reopening without Audit, with the 2026-format fixtures upgraded in Revit 2027. +The 48 refused batches preserved the source bytes and created no output. + +Global formula checks in Revit 2020–2025 and 2027 compared 12 input changes and 24 recalculated values per +release, including chained formulas and mixed length, area, angle, and scalar operations. Both opening and +reopening after SaveAs used Audit disabled. Revit 2027 also verified the 2026-format fixtures after upgrading +them. Additional volume calculations and constants with length and angle units passed the same round-trip in +Revit 2020 and 2027. Those additional fixtures still lack direct checks in Revit 2021–2026. + +The conditional and integer formula fixtures checked 12 input assignments and 38 formula results per +format against the Revit API after opening, SaveAs, and reopening with Audit disabled. The checks ran +directly in Revit 2020–2025 and 2027. For the 2026 format, Revit 2027 upgraded and verified the files. +Four negative batches per format preserved the source bytes and left no output file. Revit 2027 also +verified separate changes to the results of `and` and `or`, and preserved the selected `if` result while +the inactive branch had a zero divisor, after SaveAs and reopening without Audit. + +The mathematical function fixtures compared 12 input assignments and 38 formula result values per format +against Revit API assignments. Revit 2020–2025 and 2027 opened, saved, and reopened edited files with Audit +disabled. Revit 2027 also verified upgraded 2026-format fixtures. Three batches per format refused unverified +formula domains in that verification run. Subsequent coverage verified the retained results for those domains. + +The retained-result fixtures compared 32 assignments and 57 formula result values per format against the +Revit API, including changes between inputs that retain results and inputs that resume recalculation. Revit +2020–2025 and 2027 opened, saved, and reopened the files with Audit disabled. Revit 2027 verified upgraded +2026-format fixtures and five additional results for Boolean formulas with unavailable operands in both +positions. For each format, a batch containing an allowed input edit and an attempted write to a calculated +result left the source bytes intact and created no output file. + +Standalone family formula checks compared 20 input assignments and 28 formula result values per format +against the Revit API. The selected type's values and matching `PartAtom` entries agreed with native files, +including type parameters and instance defaults. Revit 2020–2025 and 2027 opened, saved, and reopened the +files with Audit disabled. Revit 2027 upgraded and verified the 2026-format files. A mixed batch that tried +to assign a formula result preserved the source bytes and left no output file in each format. + +Loaded family type formula checks compared 194 input assignments against Revit API assignments across the +eight formats. They included formulas on primary types and derived symbols, stored results on top-level +instances, and recalculation using local instance inputs. Revit 2020–2025 and 2027 opened, saved, and reopened +the files with Audit disabled. Revit 2027 upgraded and verified the 2026-format files. A mixed batch with an +invalid value left the source bytes intact and created no output file in each format. + +Loaded family instance formula checks compared 24 integer input assignments across the eight formats. The fixtures +covered assigning an input that matched the type default before the edit, replacing a local input, and setting it back +to the default. Only the selected instance record changed, and its stored input and formula result matched +the Revit API. Revit 2020–2025 and 2027 opened, saved, and reopened the files with Audit disabled. Revit 2027 +upgraded and verified the 2026-format files. In each format, a batch with invalid input or a direct write to +the read-only instance formula result left the source bytes intact and created no output file. + +Loaded family Currency checks covered 65 edited project files. The fixtures exercised first assignment and +replacement for shared and non-shared parameters, ordered batches, an exact type formula inverse, existing +global associations, and an instance formula that retains its saved result within Revit's comparison tolerance. +For 57 files, the affected element records matched native writes in Revit 2020–2025 and 2027. Revit 2027 +verified the eight 2026-format files after upgrade. All 65 files retained the expected API values after +Save As and reopening without Audit. Forty refused batches preserved the source bytes and created no output. +In Revit 2025, `Parameter.ClearValue()` returned `false` for a family-declared shared Currency parameter +with `HideWhenNoValue` on a primary type and on a placed instance. Both existing values remained after +saving and reopening without Audit. [Autodesk shared parameter documentation](https://help.autodesk.com/cloudhelp/2026/ENU/Revit-API/files/Revit_API_Developers_Guide/Basic_Interaction_with_Revit_Elements/Parameters/Revit_API_Revit_API_Developers_Guide_Basic_Interaction_with_Revit_Elements_Parameters_Shared_Parameters_html.html) + +Direct writes to loaded type formula results were checked against 118 Revit API assignments across the eight +formats. The checks covered integer rounding and exact real scaling, dependent formulas, derived symbols, and +stored instance results. Revit 2020–2025 and 2027 opened, saved, and reopened the files with Audit disabled. +Revit 2027 upgraded and verified the 2026-format files. Mixed batches containing an invalid or unsupported +inverse left the source bytes intact and created no output file. + +Standalone non-shared Family Type assignments were checked in all eight file formats. The checks covered +first assignment from `-1`, replacement, explicit `-1`, another category's nested type, and a local material. +Revit 2020–2025 and 2027 opened, saved, and reopened the files with Audit disabled. The API values and +`PartAtom` entries agreed after saving. Revit 2027 upgraded and verified the 2026-format files. Native Revit +2026 verification is pending. In every format, batches with a missing reference or a null clearing request +left the source bytes intact and created no output file. + +Shared Family Type assignments were also checked in all eight formats. For each format, the API comparison +covered first assignment, replacement, explicit `-1`, and reassignment to type values and instance defaults +on both active and inactive types. The checks compared the shared GUIDs and `PartAtom` values after opening, +saving, and reopening without Audit in Revit 2020–2025 and 2027. Revit 2027 verified the converted 2026-format +fixtures after upgrading them. Native Revit 2026 verification is pending. + +Project Family Type checks compared 16 assignments per format on primary types and top-level instances. They +covered family and shared definitions, first assignment, replacement, material IDs, and explicit `-1`. Revit +2020–2025 and 2027 opened, saved, and reopened the results without Audit. Revit 2027 verified the 2026-format +fixtures after upgrading them. Revit 2025 also verified a first local instance value over an inherited default. +In each format, batches with a missing ID, a family symbol the writer could not verify as a safe reference, +or a null clearing request left the source bytes intact and created no output file. + +Shared project bindings for Family Type were checked with 40 assignments and five clears per format. The +fixtures covered loaded family types and instances, basic wall types, straight walls, and rooms. They verified +first assignment, replacement, material IDs, explicit `-1`, and clearing a shared value with `HideWhenNoValue`. +Revit 2020–2025 and 2027 opened, saved, and reopened the files without Audit. Revit 2027 verified the 2026 +file format after upgrade. Revit 2025 separately verified first assignment, replacement, and clearing of +project-bound material references on a primary symbol and its two derived symbols. The tested dimensions +of the placed instances stayed the same. In each format, rejected batches preserved the source bytes and left no output. + +Family-declared references on primary types with directly linked derived copies were checked in all eight +file formats. First assignment, replacement and explicit `-1` on the primary type, plus local assignment +and reset on a placed instance, matched the API. Revit 2020–2025 and 2027 opened, saved, and reopened the +results without Audit. Revit 2027 verified the 2026 format after upgrade. The instance dimensions stayed +the same. The corresponding shared family definitions were checked in Revit 2020, 2025 and 2027 and with +the 2026 format after upgrade in Revit 2027. Direct checks of shared definitions in Revit 2021–2024 and +2026 are pending. Across the tested releases, direct calls on the derived symbols returned success but +the inherited value persisted. A batch containing such a direct edit left the source bytes intact and +created no output file. + +Ordinary active primary family types used as reference targets were checked in all eight project formats. +Each check compared first assignment and replacement on primary types and top-level instances, for both a family +declaration and a shared project binding. It also checked inherited copies on derived types, explicit `-1`, and +clearing the shared bindings. Revit 2020–2025 and 2027 opened, saved, and reopened the files with Audit disabled. +Revit 2027 upgraded and verified the 2026-format files. The API returned the expected values and the measured +instance geometry stayed the same. Batches containing a missing target left the source bytes intact and created +no output file. + +For targets that contain another shared family, first assignment and replacement matched the native API on +primary types and instances, for family-declared and shared project parameters. Revit 2020–2025 and 2027 saved +and reopened the files without Audit. Revit 2027 verified the 2026-format files after upgrade. Revit 2025 +separately verified a target whose dependency was stored as a project parameter value. Both verification sets +checked the API values and measured instance geometry. Direct verification of the stored-parameter dependency +variant in other releases is pending. + +The direct shared nesting case was checked with first assignments and replacements of the independent +family-declared type parameter. Revit 2020–2025 and 2027 confirmed the API values and instance geometry after +opening, saving, and reopening with Audit disabled. Revit 2027 also checked the 2026-format files after upgrade. +Each batch containing the corresponding instance assignment was refused, leaving the source bytes intact and +creating no output file. In Revit 2025, a separate case started with a private nested type value and a derived +placement. Replacing that value changed the same primary and derived type records as Revit. The saved reference +and the instance geometry matched the API after reopening without Audit. Direct checks of the derived-placement +variant in other releases are pending. + +Shared project bindings were also checked with a target type from a different category. First assignment and +replacement matched the API on loaded family types and instances, basic wall types, straight walls, and rooms, +with and without `HideWhenNoValue`. Revit 2020–2025 and 2027 saved and reopened the results without Audit. +Revit 2027 verified the 2026-format files after upgrade. The tested wall location, bounds, and room measurements +matched the native results. A batch containing a missing target was rejected in every format without changing its +source or creating an output file. + +Revit 2025 also verified first assignment and replacement of local shared project values on two derived +symbols using active primary symbols as targets. The primary symbol retained its existing value. Both local +values persisted after saving and reopening without Audit. Direct checks of this variant in other releases are pending. + +For shared project bindings on a loaded family type and instance, Revit accepted an active target type that +contained the referring family, the referring primary type itself, and another primary type of the same family. +First assignment and replacement matched the native values and measured instance geometry after opening, saving, +and reopening without Audit in Revit 2020–2025 and 2027. Revit 2027 verified the 2026-format files after upgrade. +In every format a mixed batch with a missing target preserved the original bytes and created no output file. +Revit 2025 also confirmed references to a family type containing a shared nested family on loaded family types +and instances, basic wall types, straight walls, and rooms, with and without `HideWhenNoValue`. The values and +measured wall and room geometry matched after resaving and reopening without Audit. Direct checks of this +additional variant in other releases are pending. + +For references to a basic wall type, rebar cover type, level, loadable family, or top-level family instance, the +matrix checks first assignment and replacement on a shared project-bound type parameter and a shared +project-bound instance parameter. Revit 2020–2025 and 2027 saved and reopened the results without Audit. +Revit 2027 also checked the 2026-format files after upgrading them. The API returned the expected target IDs +and classes, the measured instance geometry matched, and the checked files opened without warnings. Batches +containing a missing target preserved their source bytes and created no output file in every format. +[Autodesk Parameter.Set(ElementId) reference](https://help.autodesk.com/cloudhelp/2026/ENU/Revit-API-MainReference/files/html/992097b4-0477-249f-581d-7903dfafd66d.htm) + +The same five targets were also verified on loaded family types and instances, basic wall types, straight walls, +and rooms, with and without `HideWhenNoValue`. The matrix compared 100 first assignments and replacements per +format, including values read before and after resaving the offline results. Revit 2020–2025 and 2027 opened +and reopened them without Audit. Revit 2027 verified the 2026-format files after upgrade. Wall and room geometry +matched the native controls. Mixed batches with a missing target preserved the source and created no output file. + +The single-assignment round-trip checks open edited projects and families with Audit disabled, read values through the Revit API, +then save and reopen in Revit. These checks ran in Revit 2020–2025 and 2027. For the 2026 format, Revit 2027 upgraded and verified a project +sample from Autodesk and controlled project and family fixtures converted to the 2026 format. + +## Remaining parameter coverage + +| Case | Current boundary | +| --- | --- | +| Read-only values | Revit API rejects assignments to parameters such as computed wall area. RvtIO also rejects these assignments. | +| Wall Unconnected Height | The Revit API permits some assignments on unconnected walls. The writer requires further coverage of the affected wall, opening, and geometry records. | +| Clearing an RVT value | Revit API `ClearValue()` requires a shared definition with `HideWhenNoValue`. RvtIO also checks the binding and stored value layout. | +| Additional writable RVT built-ins and element classes | The RVT parameter writer supports the combinations in the table above. Type identity assignments on Door, Window, and Furniture types with derived symbol copies still require coverage. | +| Additional built-ins in standalone families | The verified Generic Model, Door, Window, and Furniture fields are listed above. Other built-ins, other family categories, and selecting an unnamed family type still require coverage. | +| User Currency parameters in standalone families | RvtIO supports verified type values, instance defaults, and formula dependencies. Additional Currency display formats still require coverage. | +| Family-declared Currency parameters in projects | RvtIO supports the verified primary type and top-level instance assignments, exact type formula inverses, and existing global associations described above. Other formula paths and geometry dependencies still require coverage. | +| Project-bound Currency parameters | RvtIO supports verified shared values on walls, basic wall types, rooms, and loaded family types and instances. Non-shared bindings and other owner classes still require coverage. | +| Additional measurable specs and units | RvtIO supports the input units listed above, including Mass, Force, Mass Density, Speed, Slope, and Time. The formula and association coverage for those six specs is described above. Additional relationships between dimensions, further measurable specs, and additional display formats still require coverage. | +| Invalid standalone image references | Revit 2022 and 2027 rejected a missing element ID and an existing family element that was outside the image class. RvtIO requires a local imported image with a verified raster record, or the explicit None value. | +| Standalone instance and shared Image definitions | The Revit API prohibits creating instance Image parameters. Revit 2025 also rejected the tested attempt to create a shared type definition. RvtIO supports the non-shared type scope described above. [Autodesk FamilyManager.AddParameter reference](https://help.autodesk.com/cloudhelp/2026/ENU/Revit-API-MainReference/files/html/3ac89d60-4b71-694f-002f-125d2e6565fc.htm) | +| Linked images in standalone families | Revit 2025 rejected `ImageTypeSource.Link` when creating an image in a family document. The verified standalone Image path uses imported images. [Autodesk ImageType.Create reference](https://help.autodesk.com/cloudhelp/2026/ENU/Revit-API-MainReference/files/html/31bb13e3-e8f5-cb66-18d0-619578d56cde.htm) | +| Project Image targets and loaded family types | Revit exposes Type Image as read-only on the tested loaded family types. A missing ID was accepted during the Revit 2025 transaction and read back as `-1` on reopen. RvtIO refuses missing IDs and unverified target or external resource layouts. [Autodesk ImageTypeOptions reference](https://help.autodesk.com/cloudhelp/2026/ENU/Revit-API-MainReference/files/html/7dda4131-548f-7c39-4dcd-ba9b85846018.htm) | +| Additional parameter types and references | RvtIO supports the verified material, standalone family type image, and Family Type assignments described above. Revit 2025 accepted an ordinary top-level symbol even when the API candidate list omitted it. Revit activated inactive targets in both family-declared and project-bound tests. RvtIO still needs coverage for that regeneration, dependencies represented by unresolved `NestedFamilyTypeReference` proxies, and other combinations of categories and parameter definitions. In the shared nesting test, Revit committed the independent type assignment and rolled back the corresponding instance assignment after `Parameter.Set` returned true. RvtIO supports the described type scope. A return path without the verified direct nesting remains outside that scope. After a test assignment of a missing ID, the API read back the previous value on reopen. [Autodesk NestedFamilyTypeReference reference](https://help.autodesk.com/cloudhelp/2026/ENU/Revit-API-MainReference/files/html/ff71e3b0-4300-7d04-1356-a045b9a90407.htm) | +| Driven global parameters | Revit API rejects direct assignments to global parameters driven by a formula or reporting dimension. [Autodesk GlobalParameter.SetValue reference](https://help.autodesk.com/cloudhelp/2026/ENU/Revit-API-MainReference/files/html/df012c22-6e65-8de5-1057-f15660d02288.htm) | +| Global parameters with dependents | Revit API can assign a global value that drives a formula, dimension, or element property. RvtIO recalculates verified formulas and updates verified project-bound or geometry-independent loaded family parameters and the built-in properties described above. Dimension recalculation, family geometry updates, and other unverified formula or association layouts still require coverage. | +| Global associations on built-in fields | Revit 2020 and 2021 refused the tested wall and family instance Comments associations. Revit 2022–2025 and 2027 accepted them. The tested wall Mark, BasicWallType Type Comments, Manufacturer, and Model, and type URL on Generic Model, Door, Window, and Furniture could not be associated in the tested releases. Derived Door, Window, and Furniture symbol associations and other family categories still require coverage. | +| Family formulas | RvtIO can recalculate verified dependencies of inputs in standalone families and on primary types and top-level instances of loaded families. `FamilyManager.Set` rejects direct writes to formula results in standalone families. RvtIO supports the loaded type inverses described above. Nonlinear inverses, real-valued inverses that depend on the starting value, unverified instance storage, and geometry-driving formulas still require coverage. [Autodesk FamilyManager.Set reference](https://help.autodesk.com/cloudhelp/2026/ENU/Revit-API-MainReference/files/html/428551ba-9037-2e23-7f18-8747624d0ff2.htm) | +| Geometry, formulas, groups, and other dependencies | The writer refuses unverified family geometry dependencies, formulas and associations, and unverified project model contexts. These checks are RvtIO write restrictions. | + ## Write-capability matrix Every write call inspects the source file first and checks the requested operation against the capability matrix: @@ -79,7 +766,7 @@ When rewriting data, `RvtWriter` enforces the following invariants: | `cloud-model` | `BasicFileInfo` marks a single-user or workshared cloud model (`IsSingleUserCloudModel: True` or cloud central path). | | `workshared-model` | `BasicFileInfo` reports worksharing enabled. | | `missing-metadata` | `BasicFileInfo` is missing, unreadable, or lacks a recognised `Worksharing`, `IsSingleUserCloudModel`, or saving-release field, or, when relocating a file with `RvtLinkSymbol` records, `TransmissionData` is missing or lists no external reference with a saved path and path type for one of them. | -| `relative-reference-relocation` | Saving to a different directory would change the resolved target of a relative external file reference (path type `Relative` or `Relative to Central Model`, as Revit writes it, or no path type with a relative path), a reference has a path type other than these, `Absolute`, `Server`, `Content` and `Library`, or the file holds an unverified `PointCloudType` path. | +| `relative-reference-relocation` | Saving to a different directory would change the resolved target of a relative external file reference (including local image links), a reference has an unrecognised path type, or a point cloud or image link has an unverified external path. | | `unreadable-transmission-data` | `TransmissionData` cannot be parsed cleanly when saving to a different directory. | | `corrupt-page-parity` | A `Formats/*`, `Global/*`, or `Partitions/*` stream fails Hamming page parity verification. | | `missing-schema` | `Formats/Latest` is missing, unreadable, or cannot be parsed. | @@ -98,3 +785,12 @@ When rewriting data, `RvtWriter` enforces the following invariants: | `missing-partition` | A `RvtPartitionRecordEdit` names a `Partitions/` stream that does not exist in the source container. | | `missing-record` | A `RvtPartitionRecordEdit` names a `(Block, Channel, OwnerId)` record that does not exist in the target partition. | | `invalid-record-target` | A `RvtPartitionRecordEdit` uses an invalid partition number, block index, channel, `-1` terminator owner, 32-bit overflow owner, or body shorter than 2 bytes. | +| `read-only-parameter` | Revit exposes the computed parameter as read-only, or the stored project or shared definition marks the parameter read-only. | +| `unsupported-parameter` | Writing this built-in parameter, definition class, or data type has not been verified. | +| `unsupported-parameter-file` | The source is outside the verified parameter editing file scope, or the paths lack the extension required by the operation (`.rvt` for project edits and `.rfa` for family edits). | +| `unsupported-parameter-owner` | The element class is outside the verified scope for this parameter. | +| `invalid-parameter-value` | The value is invalid for the supported text representation, integer bounds, or numeric type. | +| `missing-element` | The element ID is absent from the source element table. | +| `missing-parameter-definition` | The positive parameter definition ID is absent from the source element table. | +| `missing-family-type` | The standalone family type name has no unique match. | +| `unverified-parameter-storage` | The writer cannot confirm the element's record, stored value, editability conditions, or mirrored project metadata. | diff --git a/src/RvtIO.Cli/Program.cs b/src/RvtIO.Cli/Program.cs index 1a83eaf2..11df80de 100644 --- a/src/RvtIO.Cli/Program.cs +++ b/src/RvtIO.Cli/Program.cs @@ -88,6 +88,12 @@ Developer options (measurement and comparison dumps, not a stable interface): save-as [] [--check] [--report ] (first argument) inspect the write-capability matrix (--check) or write a verified lossless copy of a local 2020-2027 project or family; exit code 5 when refused by the matrix + set-parameter + replace a supported parameter in a local Revit 2020-2027 project + set-family-parameter + replace a supported parameter on a type in a local Revit 2020-2027 family + edit-parameters + apply an ordered batch of supported parameter assignments and clears atomically coverage [--report ] [--top ] (first argument) count the records of the partition streams that the class schema of the file walks to their last byte, per channel and class; writes nothing but the report @@ -155,6 +161,9 @@ internal static int Main(string[] args) if (args[0].StartsWith("--schema-")) return RvtIO.Parsing.TfSchemaTools.Run(args, Console.Out, Console.Error); if (args[0] == "downgrade") return RvtIO.Cli.DowngradeCommand.Run(args[1..], Console.Out, Console.Error); if (args[0] == "save-as") return RvtIO.Cli.SaveAsCommand.Run(args[1..], Console.Out, Console.Error); + if (args[0] == "set-parameter") return RvtIO.Cli.SetParameterCommand.Run(args[1..], Console.Out, Console.Error); + if (args[0] == "set-family-parameter") return RvtIO.Cli.SetParameterCommand.Run(args[1..], Console.Out, Console.Error, familyFile: true); + if (args[0] == "edit-parameters") return RvtIO.Cli.SetParameterCommand.RunBatch(args[1..], Console.Out, Console.Error); if (args[0] == "coverage") return RvtIO.Cli.CoverageCommand.Run(args[1..], Console.Out, Console.Error); if (args[0] == "sheets") return RvtIO.Cli.SheetsCommand.Run(args[1..], Console.Out, Console.Error); if (args[0] == "print") return RvtIO.Cli.PrintCommand.Run(args[1..], Console.Out, Console.Error); diff --git a/src/RvtIO.Cli/SetParameterCommand.cs b/src/RvtIO.Cli/SetParameterCommand.cs new file mode 100644 index 00000000..8436b267 --- /dev/null +++ b/src/RvtIO.Cli/SetParameterCommand.cs @@ -0,0 +1,107 @@ +using System.Globalization; +using System.Text.Json; +using RvtIO.BuiltIns; + +namespace RvtIO.Cli; + +internal static class SetParameterCommand +{ + internal static int Run(string[] args, TextWriter output, TextWriter error, bool familyFile = false) + { + long elementId = 0; + long parameterId = 0; + if (args.Length != 5 || args.Take(3).Any(string.IsNullOrWhiteSpace) || !TryParseParameter(args[3], out parameterId) + || (!familyFile && (!long.TryParse(args[2], NumberStyles.None, CultureInfo.InvariantCulture, out elementId) || elementId <= 0))) + { + error.WriteLine(familyFile + ? "Usage: rvtio set-family-parameter " + : "Usage: rvtio set-parameter "); + return RvtExitCodes.Usage; + } + + return Write(() => familyFile ? RvtWriter.SetFamilyParameter(args[0], args[1], args[2], parameterId, args[4]) + : RvtWriter.SetParameter(args[0], args[1], elementId, parameterId, args[4]), output, error); + } + + internal static int RunBatch(string[] args, TextWriter output, TextWriter error) + { + if (args.Length != 3 || args.Any(string.IsNullOrWhiteSpace)) + { + error.WriteLine("Usage: rvtio edit-parameters "); + return RvtExitCodes.Usage; + } + + return Write(() => + { + using var file = File.OpenRead(args[2]); + using var json = JsonDocument.Parse(file); + if (json.RootElement.ValueKind != JsonValueKind.Array || json.RootElement.GetArrayLength() == 0) + throw new JsonException("Expected a non-empty array of edits."); + bool family = Path.GetExtension(args[0]).Equals(".rfa", StringComparison.OrdinalIgnoreCase); + var projectEdits = new List(); + var familyEdits = new List(); + foreach (var entry in json.RootElement.EnumerateArray()) + { + int index = (family ? familyEdits.Count : projectEdits.Count) + 1; + if (entry.ValueKind != JsonValueKind.Object || entry.EnumerateObject().Count() != 3 + || !entry.TryGetProperty("parameterId", out var parameter) || parameter.ValueKind != JsonValueKind.Number + || !parameter.TryGetInt64(out long id) || id == 0 + || !entry.TryGetProperty("value", out var value) || value.ValueKind is not (JsonValueKind.String or JsonValueKind.Null)) + throw new JsonException($"Edit {index} must have a target, an integer parameterId, and a string or null value."); + if (family) + { + if (!entry.TryGetProperty("typeName", out var type) || type.ValueKind != JsonValueKind.String + || string.IsNullOrWhiteSpace(type.GetString())) + throw new JsonException($"Edit {index} requires a family typeName."); + familyEdits.Add(new(type.GetString()!, id, value.GetString())); + } + else + { + if (!entry.TryGetProperty("elementId", out var element) || element.ValueKind != JsonValueKind.Number + || !element.TryGetInt64(out long elementId) || elementId <= 0) + throw new JsonException($"Edit {index} requires a positive integer elementId."); + projectEdits.Add(new(elementId, id, value.GetString())); + } + } + return family ? RvtWriter.SetFamilyParameters(args[0], args[1], familyEdits) + : RvtWriter.SetParameters(args[0], args[1], projectEdits); + }, output, error); + } + + private static int Write(Func save, TextWriter output, TextWriter error) + { + try + { + var result = save(); + output.WriteLine(result.ReplacedStreamCount == 0 + ? $"Saved: {Path.GetFileName(result.OutputPath)} (value already matched)" + : $"Saved: {Path.GetFileName(result.OutputPath)}"); + return RvtExitCodes.Success; + } + catch (JsonException ex) + { + error.WriteLine($"error: {ex.Message}"); + return RvtExitCodes.Usage; + } + catch (RvtWriteRefusedException ex) + { + error.WriteLine($"error [{ex.Kind}]: {ex.Message}"); + return SaveAsCommand.Refused; + } + catch (Exception ex) when (ex is RvtInputException or RvtLimitException or IOException or UnauthorizedAccessException or ArgumentException) + { + error.WriteLine($"error: {ex.Message}"); + return RvtExitCodes.InputError; + } + } + + private static bool TryParseParameter(string text, out long id) + { + if (long.TryParse(text, NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out id)) + return id != 0; + if (!Enum.IsDefined(typeof(BuiltInParameter), text) || !Enum.TryParse(text, out var parameter)) + return false; + id = (int)parameter; + return true; + } +} diff --git a/src/RvtIO/Parsing/PagedGzipStream.cs b/src/RvtIO/Parsing/PagedGzipStream.cs index b6bfc2bb..4b871148 100644 --- a/src/RvtIO/Parsing/PagedGzipStream.cs +++ b/src/RvtIO/Parsing/PagedGzipStream.cs @@ -15,6 +15,7 @@ namespace RvtIO.Parsing; /// the segments start at stream offsets 64,896 + k * 65,249. Each one begins with a zero byte /// followed by a byte whose low nibble is zero, like the removable segments of partition pages /// (). A short stream has no segment and is decoded unchanged. +/// A terminal page can use all the lanes of a full page with data bits in the segment marker. /// The result is accepted only when the CRC-32 and length of the gzip trailer that follows the /// deflate data match, so a wrong page rule yields no data rather than wrong data. /// @@ -57,9 +58,8 @@ internal static class PagedGzipStream /// not match its own CRC-32 and length. internal static byte[]? Decompress(byte[] raw) { - // The last page of a stream may end before its segment position (the member is complete and only padding - // follows, measured on Global/ElemTable of rmebasic21): the strict removal fails there, the tail-tolerant one - // keeps the padding as trailing bytes. The gzip CRC-32 and length below still prove the result. + // A terminal page can put padding at the expected segment marker. The gzip CRC-32 and + // length still prove the member is complete when the tail-tolerant removal is used. byte[]? body = RemoveSegments(raw) ?? RemoveSegments(raw, tolerateTail: true); if (body == null) return null; int start = IsGzipHeader(body, 0) ? 0 : IsGzipHeader(body, PrefixLength) ? PrefixLength : -1; @@ -134,8 +134,9 @@ private static bool IsGzipHeader(byte[] data, int offset) => && data[offset] == 0x1F && data[offset + 1] == 0x8B && data[offset + 2] == 0x08; /// The stream without its page segments, or null when a segment position does - /// not hold a segment (wrong tag, or the stream ends inside one). With the first - /// position after the first segment that holds none ends the removal and the rest of the stream is kept unchanged. + /// not hold a segment (wrong tag, or the stream ends inside one). With , + /// an exact-length terminal page can be trimmed at the segment position without a segment marker. + /// After a verified segment, any shorter tail without a segment is kept unchanged. internal static byte[]? RemoveSegments(byte[] raw, bool tolerateTail = false) { var body = new MemoryStream(raw.Length); @@ -143,9 +144,14 @@ private static bool IsGzipHeader(byte[] data, int offset) => for (long segment = PageDataLength; segment < raw.Length; segment += PageStride) { int start = (int)segment; - if (start + SegmentLength > raw.Length - || raw[start] != 0 || (raw[start + 1] & 0x0F) != 0) + int remaining = raw.Length - start; + if (remaining < SegmentLength || raw[start] != 0 || (raw[start + 1] & 0x0F) != 0) { + if (tolerateTail && remaining == SegmentLength) + { + body.Write(raw, source, start - source); + return body.ToArray(); + } if (!tolerateTail || source == 0) return null; // the first boundary of a multi-page stream always holds a segment break; } diff --git a/src/RvtIO/Parsing/WideBlockWalker.cs b/src/RvtIO/Parsing/WideBlockWalker.cs index da42d2d9..d574728a 100644 --- a/src/RvtIO/Parsing/WideBlockWalker.cs +++ b/src/RvtIO/Parsing/WideBlockWalker.cs @@ -24,7 +24,8 @@ namespace RvtIO.Parsing; internal sealed partial class WideBlockWalker { internal readonly record struct Capture(string Key, CaptureKind Kind, long Integer, double Real, string? Text, bool AtRoot, int QueueIndex, - string DeclaringClass, string Field); + string DeclaringClass, string Field, int ValueOffset = -1, int QueuePosition = -1); + internal enum CaptureKind { Integer, Real, Text, PointerClass } @@ -169,7 +170,7 @@ internal bool IsA(int classId, string baseName) /// behind it can be read, inside the payload, from exactly one start position and (walk, index of the first /// object read again) accepts what was read there (RebarShape: the constraints of the edges lie behind the ESEntityCell of the shape; /// their values tell a real start from a misaligned one). - internal Walk Run(byte[] data, int offset, int size, int classId, Func? tailValid = null) + internal Walk Run(byte[] data, int offset, int size, int classId, Func? tailValid = null, bool rootOnly = false) { var walk = new Walk(); var ctx = new Context(data, offset + 2, offset + size, walk); @@ -178,9 +179,12 @@ internal Walk Run(byte[] data, int offset, int size, int classId, Func 5_000_000) throw new Fail("count " + n + " at " + declaring.Name + "." + f.Name); if (record is EntityFields countedValues) { ReadEntityArray(c, declaring, f, depth, countedValues, (int)n); return; } - if (key != null) c.Walk.Captures.Add(new(key + "#", CaptureKind.Integer, n, 0, null, c.AtRoot && depth == 0, c.QueueIndex, declaring.Name, f.Name)); + if (key != null) c.Walk.Captures.Add(new(key + "#", CaptureKind.Integer, n, 0, null, c.AtRoot && depth == 0, c.QueueIndex, declaring.Name, f.Name, countAt)); // The host type of an empty array is zero (the Revit 2022 walk keeps that zero as the first entry) if (key != null && n == 0 && declaring.Name == "Family" && f.Name == "m_refTypeIds") c.Walk.Captures.Add(new(key + "@0", CaptureKind.Integer, 0, 0, null, c.AtRoot && depth == 0, c.QueueIndex, declaring.Name, f.Name)); @@ -399,16 +404,16 @@ private void Scalar(Context c, SchemaClass declaring, SchemaField f, string? key { var walk = c.Walk; if (++c.Steps > StepBudget) throw new Fail("step budget"); - void Note(CaptureKind kind, long i, double d, string? s) + void Note(CaptureKind kind, long i, double d, string? s, int valueOffset = -1) { - if (key != null) walk.Captures.Add(new(key, kind, i, d, s, c.AtRoot && depth == 0, c.QueueIndex, declaring.Name, f.Name)); + if (key != null) walk.Captures.Add(new(key, kind, i, d, s, c.AtRoot && depth == 0, c.QueueIndex, declaring.Name, f.Name, valueOffset)); } switch (f.Type) { case 1: case 2: { int p = Take(c, 1); - Note(CaptureKind.Integer, c.D[p], 0, null); + Note(CaptureKind.Integer, c.D[p], 0, null, p); if (record != null) record[f.Name] = record is EntityFields && f.Type == 1 ? c.D[p] switch { 0 => false, 1 => true, _ => UnavailableEntityValue } @@ -427,7 +432,7 @@ void Note(CaptureKind kind, long i, double d, string? s) { int p = Take(c, 4); int v = BitConverter.ToInt32(c.D, p); - Note(CaptureKind.Integer, v, 0, null); + Note(CaptureKind.Integer, v, 0, null, p); if (record != null) record[f.Name] = (long)v; return; } @@ -451,7 +456,7 @@ void Note(CaptureKind kind, long i, double d, string? s) { int p = Take(c, 8); double v = BitConverter.ToDouble(c.D, p); - Note(CaptureKind.Real, 0, v, null); + Note(CaptureKind.Real, 0, v, null, p); if (record != null) record[f.Name] = v; return; } @@ -479,7 +484,7 @@ void Note(CaptureKind kind, long i, double d, string? s) if (2L * len > c.End - c.Pos) throw new Fail("end of payload"); int p = Take(c, 2 * (int)len); string s = Encoding.Unicode.GetString(c.D, p, 2 * (int)len); - Note(CaptureKind.Text, 0, 0, s); + Note(CaptureKind.Text, 0, 0, s, p - sizeof(uint)); if (record != null) record[f.Name] = s; return; } @@ -509,13 +514,15 @@ private void ReadReference(Context c, SchemaClass declaring, SchemaField f, stri int lo = f.Mods & 15; if (lo == 3) { + int offset = c.Pos; uint back = U32(c); - if (key != null) walk.Captures.Add(new(key, CaptureKind.Integer, back, 0, null, c.AtRoot && depth == 0, c.QueueIndex, declaring.Name, f.Name)); + if (key != null) walk.Captures.Add(new(key, CaptureKind.Integer, back, 0, null, c.AtRoot && depth == 0, c.QueueIndex, declaring.Name, f.Name, offset)); if (record != null) record[f.Name] = (long)back; return; } if (lo is 1 or 2 or 4) { + int handleAt = c.Pos, queuePosition = walk.Queue.Count; uint handle = U32(c); int tag = 0; if (_entityLayoutOf != null && declaring.Name == "ESEntity" && f.Name == "m_blob" && QueueEntityPayload(c, handle, record as EntityFields)) return; @@ -545,7 +552,8 @@ private void ReadReference(Context c, SchemaClass declaring, SchemaField f, stri walk.Queue.Add(tag); } } - if (key != null) walk.Captures.Add(new(key, CaptureKind.PointerClass, handle == 0 ? 0 : tag == 0 ? -1 : tag, 0, null, c.AtRoot && depth == 0, c.QueueIndex, declaring.Name, f.Name)); + if (key != null) walk.Captures.Add(new(key, CaptureKind.PointerClass, handle == 0 ? 0 : tag == 0 ? -1 : tag, 0, null, + c.AtRoot && depth == 0, c.QueueIndex, declaring.Name, f.Name, handleAt, queuePosition)); if (record != null) record[f.Name] = record is EntityFields ? UnavailableEntityValue : (long)tag; return; } @@ -558,7 +566,7 @@ private void ReadReference(Context c, SchemaClass declaring, SchemaField f, stri long id = _idWidth == 8 ? BitConverter.ToInt64(c.D, p) : BitConverter.ToInt32(c.D, p); if (record is EntityFields) { record[f.Name] = ExactEntityInteger(id); return; } if (_ids != null) id = _ids.Key(id); - if (key != null) walk.Captures.Add(new(key, CaptureKind.Integer, id, 0, null, c.AtRoot && depth == 0, c.QueueIndex, declaring.Name, f.Name)); + if (key != null) walk.Captures.Add(new(key, CaptureKind.Integer, id, 0, null, c.AtRoot && depth == 0, c.QueueIndex, declaring.Name, f.Name, p)); if (record != null) record[f.Name] = id; return; } @@ -586,6 +594,11 @@ private void ReadReference(Context c, SchemaClass declaring, SchemaField f, stri if (key != null && _classes[reference].Name == "ForgeTypeId" && walk.Records is [.., (var recordClass, _, var forge)] && recordClass == reference && forge.GetValueOrDefault("m_typeId") is string forgeText) walk.Captures.Add(new(key, CaptureKind.Text, 0, 0, forgeText, c.AtRoot && depth == 0, c.QueueIndex, declaring.Name, f.Name)); + if (key != null && c.Pos - structAt == 16 + && _classes[reference] is { Name: "ExternalParamKey", Fields: [{ Name: "m_guidValue", Type: 14, Mods: 0, Ref: int guidClass }] } + && Class(guidClass) is { Name: "GUIDvalue", Fields: [{ Name: "m_guid", Type: 9, Mods: 0 }] }) + walk.Captures.Add(new(key, CaptureKind.Text, 0, 0, new Guid(c.D.AsSpan(structAt, 16)).ToString(), c.AtRoot && depth == 0, + c.QueueIndex, declaring.Name, f.Name)); return; } { diff --git a/src/RvtIO/Writing/FamilyFormulaPropagation.cs b/src/RvtIO/Writing/FamilyFormulaPropagation.cs new file mode 100644 index 00000000..2543bbd6 --- /dev/null +++ b/src/RvtIO/Writing/FamilyFormulaPropagation.cs @@ -0,0 +1,182 @@ +using RvtIO.BuiltIns; +using RvtIO.Model; +using RvtIO.Parsing; +using static RvtIO.Writing.LoadedFamilyParameterWriter; +using static RvtIO.Writing.ParameterWriter; +using FormulaValue = RvtIO.Writing.ParameterFormulaEvaluator.Value; + +namespace RvtIO.Writing; + +internal static class FamilyFormulaPropagation +{ + private const string FormulaReference = "formula-reference"; + internal sealed record Result(long Id, FormulaParameterStorage Format, byte[] Replacement); + internal sealed record InstanceValues(byte[] Body, FamilyStore Store); + private readonly record struct Change(FormulaValue Before, FormulaValue After); + + internal static Dictionary> Dependencies(WideBlockWalker.Walk family, FamilyStore store) + { + var dependents = new Dictionary>(); + IndexDependencies(family, store, References(family), [], dependents); + return dependents; + } + + internal static List Recalculate(WideBlockWalker walker, WideBlockWalker.Walk family, byte[] body, + IEnumerable stores, FamilyStore selected, FamilyStore? activeMirror, + long inputId, byte[] inputValue, int idWidth, Func canRecalculate, + Func formatOf, Func?>? declaredUses = null, + InstanceValues? instance = null) + { + var references = References(family); + if (!references.Any(group => group.Any(c => c.Integer == inputId)) && declaredUses?.Invoke(inputId) is null) + return []; + + var formulaSlots = new HashSet(); + var dependents = new Dictionary>(); + var mirrorDependents = new Dictionary>(); + foreach (var store in stores) + IndexDependencies(family, store, references, formulaSlots, + store == selected ? dependents : store == activeMirror ? mirrorDependents : null); + + var affected = new HashSet { inputId }; + var remaining = new Queue(); + remaining.Enqueue(inputId); + while (remaining.TryDequeue(out long id)) + { + if (!canRecalculate(id)) + throw Unverified("A parameter in the family formula chain also drives geometry or another element."); + var uses = dependents.GetValueOrDefault(id); + if (activeMirror is not null && !SameUses(uses, mirrorDependents.GetValueOrDefault(id))) + throw Unverified("The active type and current family formula dependencies disagree."); + if (declaredUses is not null && !SameUses(uses, declaredUses(id))) + throw Unverified("The loaded type and family formula dependencies disagree."); + if (uses is null) + continue; + foreach (long dependent in uses) + if (affected.Add(dependent)) + remaining.Enqueue(dependent); + } + if (references.Any(group => !formulaSlots.Contains(group.Key) && group.Any(c => affected.Contains(c.Integer)))) + throw Unverified("A parameter in the family formula chain is referenced outside the family type values."); + if (affected.Count == 1) + return []; + + bool editsInstanceInput = instance is not null && FindFormulaRow(selected, inputId).Instance == 1; + var result = new List(); + var resolved = new Dictionary(); + var evaluating = new HashSet(); + foreach (long id in affected) + Resolve(id, ParameterFormulaEvaluator.MaxDepth); + return result; + + Change Resolve(long id, int depth) + { + if (resolved.TryGetValue(id, out var change)) + return change; + if (depth <= 0 || !evaluating.Add(id)) + throw Unverified("The family formula dependency chain cannot be resolved."); + + var row = FindFormulaRow(selected, id); + var format = formatOf(id); + NamedValue? instanceRow = instance is not null && row.Instance == 1 + ? FindRow(instance.Store, id, 0, required: affected.Contains(id)) + : null; + var location = Location(instanceRow ?? row, format.Storage, idWidth); + var stored = (instanceRow is null ? body : instance!.Body).AsSpan(location.Offset, location.Length); + var oldValue = format.Decode(stored); + NamedValue? mirror = activeMirror is null ? null : FindFormulaRow(activeMirror, id); + if (mirror is not null) + { + var copy = Location(mirror, format.Storage, idWidth); + if (copy.Offset == location.Offset || !stored.SequenceEqual(body.AsSpan(copy.Offset, copy.Length)) || + mirror.Instance != row.Instance || mirror.Fields[1].Integer != row.Fields[1].Integer) + throw Unverified("The active type and current family formula values disagree."); + } + + if (id == inputId) + { + change = new(oldValue, format.Decode(inputValue)); + if (format.Storage == StorageType.Double) + ParameterFormulaEvaluator.VerifyStableChange(change.Before.Number, change.After.Number); + } + else if (affected.Contains(id)) + { + // A retained intermediate result would need separate verification of downstream evaluation. + bool retainNearValue = editsInstanceInput && instanceRow is not null && format.Unit == UnitType.UT_Currency && + !dependents.ContainsKey(id); + var replacement = Evaluate(row, format, depth, stored, retainNearValue); + if (mirror is not null && !replacement.AsSpan().SequenceEqual(Evaluate(mirror, format, depth, stored, retainNearValue))) + throw Unverified("The two active family formula copies produced different values."); + change = new(oldValue, format.Decode(replacement)); + if (format.Storage == StorageType.Double) + ParameterFormulaEvaluator.VerifyStableChange(change.Before.Number, change.After.Number); + if (instance is null || instanceRow is not null) + result.Add(new(id, format, replacement)); + } + else + { + change = new(oldValue, oldValue); + } + + evaluating.Remove(id); + resolved.Add(id, change); + return change; + } + + byte[] Evaluate(NamedValue row, FormulaParameterStorage format, int depth, ReadOnlySpan stored, bool retainNearValue) + { + var expression = row.Fields[1]; + double savedNumber = retainNearValue ? format.Decode(stored).Number : 0; + if (ParameterFormulaEvaluator.Evaluate(walker, family, expression, depth, (id, remaining) => Resolve(id, remaining).Before) + is not { } before || (!stored.SequenceEqual(format.Encode(before)) && !ShouldRetain(before))) + throw Unverified("A family formula does not reproduce its stored value exactly."); + if (ParameterFormulaEvaluator.Evaluate(walker, family, expression, depth, (id, remaining) => Resolve(id, remaining).After) + is not { } after) + throw new RvtWriteRefusedException("invalid-parameter-value", "The family formula did not produce a value for this input."); + byte[] replacement = format.Encode(after); + return ShouldRetain(after) ? stored.ToArray() : replacement; + + bool ShouldRetain(FormulaValue calculated) => retainNearValue && + ParameterFormulaEvaluator.IsWithinVerifiedRelativeTolerance(savedNumber, calculated.Number); + } + } + + private static bool SameUses(HashSet? actual, IReadOnlySet? expected) + => actual is null ? expected is null : expected is not null && actual.SetEquals(expected); + + private static ILookup References(WideBlockWalker.Walk family) + => family.Captures.Where(c => c.Key == FormulaReference && c.Integer > 0).ToLookup(c => c.QueueIndex); + + private static void IndexDependencies(WideBlockWalker.Walk family, FamilyStore store, + ILookup references, HashSet owned, + Dictionary>? dependents) + { + foreach (var row in store.Rows.Where(r => r.Fields[1].Integer != 0)) + { + var pending = new Queue(); + pending.Enqueue(ParameterFormulaEvaluator.ChildSlot(row.Fields[1], family)); + while (pending.TryDequeue(out int slot)) + { + if (!owned.Add(slot)) + throw Unverified("The family formula objects do not have unique ownership."); + if (dependents is not null) + foreach (var reference in references[slot]) + { + if (!dependents.TryGetValue(reference.Integer, out var uses)) + dependents.Add(reference.Integer, uses = []); + uses.Add(row.Id); + } + for (int child = family.QueueCountAtStart[slot]; child < family.QueueEnd[slot]; child++) + pending.Enqueue(child); + } + } + } + + internal static NamedValue FindFormulaRow(FamilyStore store, long id) + { + if (store.Rows.Where(row => row.Id == id).ToArray() is not [var item] || + item.Instance is not (0 or 1) || item.Fields[7].Integer != 0) + throw Unverified("A formula parameter has no unique stored value or is reporting."); + return item; + } +} diff --git a/src/RvtIO/Writing/FormulaParameterStorage.cs b/src/RvtIO/Writing/FormulaParameterStorage.cs new file mode 100644 index 00000000..ce9b44c6 --- /dev/null +++ b/src/RvtIO/Writing/FormulaParameterStorage.cs @@ -0,0 +1,74 @@ +using System.Buffers.Binary; +using System.Text; +using RvtIO.BuiltIns; +using RvtIO.Model; +using RvtIO.Parsing; +using static RvtIO.Writing.UserParameterWriter; +using FormulaValue = RvtIO.Writing.ParameterFormulaEvaluator.Value; +using ValueKind = RvtIO.Writing.ParameterFormulaEvaluator.ValueKind; + +namespace RvtIO.Writing; + +internal readonly record struct FormulaParameterStorage(StorageType Storage, UnitType Unit, ValueKind Kind, + int Min = int.MinValue, int Max = int.MaxValue) +{ + // Revit uses scalar numbers for Currency and Slope in formulas and keeps their specs for associations. + internal UnitType FormulaUnit => Unit is UnitType.UT_Currency or UnitType.UT_Slope ? UnitType.UT_Number : Unit; + + internal static FormulaParameterStorage Read(WideBlockWalker walker, WideBlockWalker.Walk walk, int slot, + bool includeCurrency = false) + { + if (walk.EmptyEntityAt >= 0) + throw ParameterWriter.Unverified("A formula parameter contains unverified stored data."); + return walker.Class(walk.Queue[slot])?.Name switch + { + "ParamDefValue" when Integer(walk, "ParamDefValue.m_restriction", slot) == 1 && + Integer(walk, "ParamDefValue.m_boundless", slot) == 0 && + ParameterMeasurement.Spec(walk, slot, includeCurrency: includeCurrency, includeAdditional: true) is UnitType unit + => new(StorageType.Double, unit, ValueKind.Number), + "ParamDefInt" when Integer(walk, "ParamDefInt.m_lowBound", slot) is >= int.MinValue and <= int.MaxValue and long low && + Integer(walk, "ParamDefInt.m_upBound", slot) is >= int.MinValue and <= int.MaxValue and long high && low <= high + => new(StorageType.Integer, UnitType.UT_Number, ValueKind.Number, (int)low, (int)high), + "ParamDefYesNo" => new(StorageType.Integer, UnitType.UT_Number, ValueKind.Boolean, 0, 1), + "ParamDefString" => new(StorageType.String, UnitType.UT_Number, ValueKind.Text), + _ => throw ParameterWriter.Unverified("A referenced parameter does not have a verified formula type."), + }; + } + + internal FormulaValue Decode(ReadOnlySpan bytes) + { + if (Storage == StorageType.Double) + { + double value = BinaryPrimitives.ReadDoubleLittleEndian(bytes); + if (!double.IsFinite(value)) + throw ParameterWriter.Unverified("A stored formula number is not finite."); + return new(value, FormulaUnit); + } + if (Storage == StorageType.String) + return FormulaValue.String(Encoding.Unicode.GetString(bytes[sizeof(uint)..])); + int number = BinaryPrimitives.ReadInt32LittleEndian(bytes); + if (number < Min || number > Max) + throw ParameterWriter.Unverified("A stored integer is outside the verified bounds for its formula type."); + return new(number, Unit, Kind); + } + + internal byte[] Encode(FormulaValue value) + { + if (value.Kind != Kind || value.Unit != FormulaUnit) + throw ParameterWriter.Unverified("A formula result has incompatible storage or units."); + if (Storage == StorageType.Double) + return ParameterWriter.EncodeDouble(value.Number); + if (Storage == StorageType.String) + { + string text = value.Text ?? throw ParameterWriter.Unverified("The text formula does not have a verified value."); + ParameterWriter.ValidateText(text); + return ParameterWriter.EncodeText(text); + } + double number = ParameterFormulaEvaluator.Round(value.Number); + if (number < Min || number > Max) + throw new RvtWriteRefusedException("invalid-parameter-value", "A recalculated integer exceeds its definition bounds."); + byte[] bytes = new byte[sizeof(int)]; + BinaryPrimitives.WriteInt32LittleEndian(bytes, (int)number); + return bytes; + } +} diff --git a/src/RvtIO/Writing/GlobalParameterWriter.cs b/src/RvtIO/Writing/GlobalParameterWriter.cs new file mode 100644 index 00000000..aa9d40e9 --- /dev/null +++ b/src/RvtIO/Writing/GlobalParameterWriter.cs @@ -0,0 +1,344 @@ +using System.Buffers.Binary; +using OpenMcdf; +using RvtIO.BuiltIns; +using RvtIO.Model; +using RvtIO.Parsing; +using static RvtIO.Writing.UserParameterWriter; +using FormulaValue = RvtIO.Writing.ParameterFormulaEvaluator.Value; + +namespace RvtIO.Writing; + +internal static class GlobalParameterWriter +{ + private const string Dependency = "global-parameter-dependency"; + private const string AssociatedParameters = "project-global-associations"; + private static readonly string[] AssociationFields = ["m_famParamId", "m_elemPropId", "m_geomTag", "m_bIsSymbol"]; + + internal sealed record GlobalRecord(int Partition, int ClassId, byte[] Body); + internal sealed record ProjectDependencies( + Dictionary Globals, Dictionary> Formulas, + Dictionary> Properties, HashSet OtherConsumers); + internal readonly record struct PropertyTarget(long ElementId, long ParameterId); + internal readonly record struct PropertyValue(long GlobalId, FormulaParameterStorage Format, byte[] Previous, byte[] Replacement) + { + internal void VerifyFormat(FormulaParameterStorage target) + { + if (target.Storage != Format.Storage || target.Unit != Format.Unit || target.Kind != Format.Kind) + throw ParameterWriter.Unverified("The controlled property and global parameter have different types."); + _ = target.Decode(Replacement); + } + } + private readonly record struct Association(long GlobalId, long ParameterId, int GlobalOffset, bool Ordinary); + private readonly record struct FormulaChange(FormulaValue Before, FormulaValue After); + + internal static string? CaptureKey(SchemaClass declaring, SchemaField field) => (declaring.Name, field.Name) switch + { + ("ParamIdPair", "m_famParamId") or ("DimSegInfo" or "ParamExprEntry", "m_paramId") => Dependency, + ("ParametrizedElemParamsCellBase", "m_paramDrivenData") => AssociatedParameters, + ("ParamIdPair", "m_elemPropId" or "m_geomTag" or "m_bIsSymbol") => field.Name, + ("ParamElemGlobal", "m_constraintId" or "m_propertyId" or "m_reporting" or "m_oExpression") or + ("ParamStorage", "m_dbl" or "m_elemId" or "m_int" or "m_storageType") or ("AStringWrapper", "m_str") + => declaring.Name + "." + field.Name, + _ => ParameterFormulaEvaluator.CaptureKey(declaring, field), + }; + + internal static void VerifyElementParameter(WideBlockWalker walker, WideBlockWalker.Walk walk, int idWidth, + IReadOnlySet elementIds, IReadOnlySet globals, long parameterId, long? controllingGlobal = null) + { + if (!walk.Exact || (globals.Count != 0 && walk.EmptyEntityAt >= 0)) + throw ParameterWriter.Unverified("The element's parameter associations could not be read exactly."); + var slots = walk.Queue.Select((tag, index) => (tag, index)) + .Where(item => walker.IsA(item.tag, "ParametrizedElemParamsCellBase")).ToArray(); + Association[] rows = slots.Length == 0 ? [] : slots is [var slot] && + walker.Class(slot.tag)?.Name == "ProjectParametrizedElemParamsCell" && walk.EmptyEntityAt < 0 + ? ReadAssociations(walk, slot.index, idWidth, elementIds, globals) + : throw ParameterWriter.Unverified("The element has an unsupported parameter association."); + if (rows.Any(row => !row.Ordinary)) + throw ParameterWriter.Unverified("The element has an unverified global parameter association."); + var association = rows.SingleOrDefault(row => row.ParameterId == parameterId); + if (controllingGlobal is long global && association.GlobalId != global) + throw ParameterWriter.Unverified("The element parameter is not associated with the expected global parameter."); + if (controllingGlobal is null && association.GlobalId > 0) + throw new RvtWriteRefusedException("read-only-parameter", "A global parameter controls this element parameter."); + } + + private static Association[] ReadAssociations(WideBlockWalker.Walk walk, int slot, int idWidth, + IReadOnlySet elementIds, IReadOnlySet globals) + { + var fields = walk.Captures.Where(c => c.QueueIndex == slot).ToArray(); + var rows = fields.Where(c => c.DeclaringClass == "ParamIdPair").ToArray(); + if (fields.Where(c => c.Key == AssociatedParameters + "#").ToArray() is not + [{ Kind: WideBlockWalker.CaptureKind.Integer, ValueOffset: >= 0 } count] || rows.Length != count.Integer * AssociationFields.Length) + throw ParameterWriter.Unverified("The element's global parameter association list could not be read exactly."); + + var seen = new HashSet(); + var duplicates = new HashSet(); + var associations = new List(); + int offset = count.ValueOffset + sizeof(uint); + foreach (var row in rows.Chunk(AssociationFields.Length)) + { + var global = row[0]; + var property = row[1]; + if (!row.Select(c => c.Field).SequenceEqual(AssociationFields) || row.Any(c => c.Kind != WideBlockWalker.CaptureKind.Integer) || + global.ValueOffset != offset || property.ValueOffset != offset + idWidth || + row[2].ValueOffset != offset + 2 * idWidth || row[3].ValueOffset != offset + 2 * idWidth + sizeof(int) || + global.Integer <= 0 || !globals.Contains(global.Integer) || + property.Integer is 0 or -1 or < int.MinValue || (property.Integer > 0 && !elementIds.Contains(property.Integer))) + throw ParameterWriter.Unverified("The element has an unverified global parameter association."); + if (!seen.Add(property.Integer)) + duplicates.Add(property.Integer); + associations.Add(new(global.Integer, property.Integer, global.ValueOffset, row[2].Integer == -1 && row[3].Integer == 0)); + offset += 2 * idWidth + sizeof(int) + sizeof(byte); + } + return associations.Select(row => duplicates.Contains(row.ParameterId) ? row with { Ordinary = false } : row).ToArray(); + } + + internal static ParameterWriter.PlanResult? Plan( + RootStorage root, PartitionFraming.Tags tags, int idWidth, WideBlockWalker walker, IReadOnlySet elementIds, IReadOnlySet globals, + ParameterWriter.Edit edit, ParameterWriter.Pending pending, int partition, byte[] body, int classId) + { + if (edit.Value is null) + throw new RvtWriteRefusedException("unsupported-parameter-clear", "Global parameters require an explicit value."); + + var (walk, slot) = ReadDefinition(walker, body, edit); + if (walk.EmptyEntityAt >= 0 || Integer(walk, "ParamElemGlobal.m_reporting") is not (0 or 1) || + Integer(walk, "ParamElemGlobal.m_oExpression") is not (>= 0 and long expression)) + throw ParameterWriter.Unverified("The global parameter's formula and reporting state could not be verified."); + if (expression != 0 || Integer(walk, "ParamElemGlobal.m_reporting") == 1) + throw new RvtWriteRefusedException("read-only-parameter", "A formula or reporting dimension drives this global parameter."); + VerifyUnlinked(walk); + + // Supported edits change values only. The same dependency census applies to every global assignment in the batch. + var dependencies = pending.GlobalParameterDependencies ??= ReadDependencies(root, tags, idWidth, walker, elementIds, globals, pending); + if (dependencies.OtherConsumers.Contains(edit.ParameterId)) + throw ParameterWriter.Unverified("A dimension or element property depends on this global parameter."); + + bool currency = IsCurrency(walker, walk, slot); + var (storage, replacement, quantity) = currency + ? (StorageType.Double, ParameterWriter.EncodeCost(edit.Value), (UnitType?)UnitType.UT_Currency) + : Encode(walker, walk, slot, edit, idWidth, material: null); + var result = new List(); + var properties = new List<(PropertyTarget Target, PropertyValue Value)>(); + var location = ValueLocation(walk, storage, idWidth); + WriteValue(result, edit.ElementId, partition, body, classId, walker, storage, replacement, idWidth, location); + bool recalculates = dependencies.Formulas.ContainsKey(edit.ParameterId); + if (currency || ParameterMeasurement.IsAdditionalSpec(quantity) || recalculates || dependencies.Properties.ContainsKey(edit.ParameterId)) + { + var type = FormulaParameterStorage.Read(walker, walk, slot, includeCurrency: true); + var previous = body.AsSpan(location.Offset, location.Length); + var input = new FormulaChange(type.Decode(previous), type.Decode(replacement)); + if (type.Storage == StorageType.Double) + ParameterFormulaEvaluator.VerifyStableChange(input.Before.Number, input.After.Number); + CollectProperties(properties, dependencies, new(edit.ParameterId, type, previous.ToArray(), replacement)); + if (recalculates) + Recalculate(result, properties, dependencies, pending, walker, edit.ParameterId, input, idWidth); + if (properties.Count != 0) + { + // Several globals can update different properties on the same record in this assignment. + var staged = new ParameterWriter.Pending(); + foreach (var (key, record) in pending.Records) + staged.Records.Add(key, record); + foreach (var (target, value) in properties) + { + var plan = ParameterWriter.Plan(root, tags, idWidth, new(target.ElementId, target.ParameterId, null), staged, value); + staged.Apply(plan); + if (plan is not null) + result.AddRange(plan.Records); + } + } + } + return result.Count == 0 ? null : new ParameterWriter.PlanResult(result, null); + } + + private static bool IsCurrency(WideBlockWalker walker, WideBlockWalker.Walk walk, int slot) + => walker.Class(walk.Queue[slot])?.Name == "ParamDefValue" + && Integer(walk, "ParamDefValue.m_restriction", slot) == 1 + && Integer(walk, "ParamDefValue.m_boundless", slot) == 0 + && ParameterMeasurement.Spec(walk, slot, includeCurrency: true) == UnitType.UT_Currency; + + private static void CollectProperties(List<(PropertyTarget Target, PropertyValue Value)> properties, + ProjectDependencies dependencies, PropertyValue value) + { + if (dependencies.Properties.TryGetValue(value.GlobalId, out var targets)) + foreach (var target in targets) + { + if (value.Format.Unit == UnitType.UT_Currency && target.ParameterId < 0 && target.ParameterId != (int)BuiltInParameter.ALL_MODEL_COST) + throw ParameterWriter.Unverified("The Currency global parameter controls an unverified built-in property."); + properties.Add((target, value)); + } + } + + private static void Recalculate(List result, + List<(PropertyTarget Target, PropertyValue Value)> properties, ProjectDependencies dependencies, ParameterWriter.Pending pending, + WideBlockWalker walker, long inputId, FormulaChange input, int idWidth) + { + var affected = new HashSet { inputId }; + var remaining = new Queue(); + remaining.Enqueue(inputId); + while (remaining.TryDequeue(out long next)) + { + if (dependencies.OtherConsumers.Contains(next)) + throw ParameterWriter.Unverified("A dimension or element property depends on a value in the global formula chain."); + if (!dependencies.Formulas.TryGetValue(next, out var consumers)) + continue; + foreach (long consumer in consumers) + if (affected.Add(consumer)) + remaining.Enqueue(consumer); + } + + var calculated = new Dictionary { [inputId] = input }; + var evaluating = new HashSet(); + foreach (long parameter in affected) + Resolve(parameter, ParameterFormulaEvaluator.MaxDepth); + + FormulaChange Resolve(long id, int depth) + { + if (calculated.TryGetValue(id, out var value)) + return value; + if (depth <= 0 || !evaluating.Add(id) || !dependencies.Globals.TryGetValue(id, out var record)) + throw ParameterWriter.Unverified("A global formula reference is missing or its dependency chain cannot be resolved."); + + var key = (record.Partition, 0, 102, (ulong)id); + byte[] body = pending.Records.TryGetValue(key, out var prior) ? prior.Body.ToArray() : record.Body; + var (walk, slot) = ReadDefinition(walker, body, new ParameterWriter.Edit(id, id, null)); + var type = FormulaParameterStorage.Read(walker, walk, slot, includeCurrency: true); + var (offset, length) = ValueLocation(walk, type.Storage, idWidth); + var stored = body.AsSpan(offset, length); + var oldValue = type.Decode(stored); + value = new(oldValue, oldValue); + if (affected.Contains(id)) + { + VerifyUnlinked(walk); + if (Integer(walk, "ParamElemGlobal.m_reporting") != 0) + throw ParameterWriter.Unverified("A reporting global parameter occurs in the formula chain."); + if (walk.Captures.Where(c => c.AtRoot && c.Key == "ParamElemGlobal.m_oExpression").ToArray() is not [var expression]) + throw ParameterWriter.Unverified("The global formula root could not be verified."); + var before = ParameterFormulaEvaluator.Evaluate(walker, walk, expression, depth, (reference, budget) => Resolve(reference, budget).Before); + if (before is { } calculatedBefore && !stored.SequenceEqual(type.Encode(calculatedBefore))) + throw ParameterWriter.Unverified("A dependent global formula does not reproduce its stored value exactly."); + var after = ParameterFormulaEvaluator.Evaluate(walker, walk, expression, depth, (reference, budget) => Resolve(reference, budget).After); + if (after is { } calculatedAfter) + { + byte[] replacement = type.Encode(calculatedAfter); + value = new(oldValue, type.Decode(replacement)); + if (type.Storage == StorageType.Double) + ParameterFormulaEvaluator.VerifyStableChange(value.Before.Number, value.After.Number); + WriteValue(result, id, record.Partition, body, record.ClassId, walker, type.Storage, replacement, idWidth, (offset, length)); + CollectProperties(properties, dependencies, new(id, type, stored.ToArray(), replacement)); + } + } + evaluating.Remove(id); + calculated.Add(id, value); + return value; + } + } + + private static void VerifyUnlinked(WideBlockWalker.Walk walk) + { + if (Integer(walk, "ParamElemGlobal.m_constraintId") != -1 || Integer(walk, "ParamElemGlobal.m_propertyId") != -1) + throw ParameterWriter.Unverified("The global parameter has a dimension or property link that is outside the verified write scope."); + } + + private static void WriteValue(List result, long id, int partition, byte[] body, int classId, + WideBlockWalker walker, StorageType storage, byte[] replacement, int idWidth, (int Offset, int Length) location) + { + var (offset, length) = location; + if (body.AsSpan(offset, length).SequenceEqual(replacement)) + return; + + byte[] updated = ParameterWriter.ReplaceValue(body, offset, length, replacement); + var verified = walker.Run(updated, 0, updated.Length, classId); + if (!verified.Exact || verified.EmptyEntityAt >= 0 || ValueLocation(verified, storage, idWidth) != (offset, replacement.Length) || + !updated.AsSpan(offset, replacement.Length).SequenceEqual(replacement)) + throw ParameterWriter.Unverified("The updated global parameter could not be read back."); + result.Add(new(partition, 102, (ulong)id, updated)); + } + + private static (int Offset, int Length) ValueLocation(WideBlockWalker.Walk walk, StorageType storage, int idWidth) + { + int reporting = Field("ParamElemGlobal.m_reporting", WideBlockWalker.CaptureKind.Integer).ValueOffset; + var number = Field("ParamStorage.m_dbl", WideBlockWalker.CaptureKind.Real); + var reference = Field("ParamStorage.m_elemId", WideBlockWalker.CaptureKind.Integer); + var integer = Field("ParamStorage.m_int", WideBlockWalker.CaptureKind.Integer); + var type = Field("ParamStorage.m_storageType", WideBlockWalker.CaptureKind.Integer); + int expression = Field("ParamElemGlobal.m_oExpression", WideBlockWalker.CaptureKind.PointerClass).ValueOffset; + if (walk.Captures.Where(c => c.QueueIndex == -1 && c.Key == "AStringWrapper.m_str" && c.ValueOffset == reporting + 1).ToArray() + is not [{ Kind: WideBlockWalker.CaptureKind.Text, Text: not null } text] || + reference.Integer != -1 || type.Integer != (int)storage || + !double.IsFinite(number.Real) || (storage != StorageType.Double && number.Real != 0) || + (storage != StorageType.Integer && integer.Integer != 0) || (storage != StorageType.String && text.Text.Length != 0)) + throw ParameterWriter.Unverified("The global parameter does not have the verified typed value layout."); + + int textLength = checked(sizeof(uint) + sizeof(char) * text.Text.Length); + if (text.ValueOffset + textLength != number.ValueOffset || number.ValueOffset + sizeof(double) != reference.ValueOffset || + reference.ValueOffset + idWidth != integer.ValueOffset || integer.ValueOffset + sizeof(int) != type.ValueOffset || + type.ValueOffset + sizeof(int) != expression) + throw ParameterWriter.Unverified("The global parameter's inline value could not be located exactly."); + + return storage switch + { + StorageType.String => (text.ValueOffset, textLength), + StorageType.Integer => (integer.ValueOffset, sizeof(int)), + StorageType.Double => (number.ValueOffset, sizeof(double)), + _ => throw ParameterWriter.Unverified("The global parameter's storage type is outside the verified scope."), + }; + + WideBlockWalker.Capture Field(string key, WideBlockWalker.CaptureKind kind) => + walk.Captures.Where(c => c.QueueIndex == -1 && c.Key == key).ToArray() is [{ ValueOffset: >= 0 } field] && field.Kind == kind + ? field : throw ParameterWriter.Unverified("The global parameter's value fields could not be located exactly."); + } + + private static ProjectDependencies ReadDependencies( + RootStorage root, PartitionFraming.Tags tags, int idWidth, WideBlockWalker walker, IReadOnlySet elementIds, IReadOnlySet globalIds, + ParameterWriter.Pending pending) + { + var globals = new Dictionary(); + var formulas = new Dictionary>(); + var properties = new Dictionary>(); + var otherConsumers = new HashSet(); + var seen = new HashSet(); + ParameterWriter.ScanPartitions(root, tags, idWidth, (partition, record) => + { + long id = (long)record.Owner; + if (record.Block != 0 || record.Channel != 102 || !elementIds.Contains(id)) + return; + if (!seen.Add(id) || record.Body.Length < 2) + throw ParameterWriter.Unverified("A project element has an ambiguous global parameter dependency record."); + + byte[] data = record.Body.ToArray(); + int classId = BinaryPrimitives.ReadUInt16LittleEndian(data); + var walk = walker.Run(data, 0, data.Length, classId); + if (!walk.Exact || walk.EmptyEntityAt >= 0 || Integer(walk, "m_id") != id) + throw ParameterWriter.Unverified("A project element could not be read exactly for global parameter dependencies."); + bool global = walker.Class(classId)?.Name == "ParamElemGlobal"; + if (global) + globals.Add(id, new(partition, classId, data)); + var claimed = new HashSet(); + var slots = walk.Queue.Select((tag, index) => (tag, index)) + .Where(item => walker.IsA(item.tag, "ParametrizedElemParamsCellBase")).ToArray(); + if (slots is [var slot] && walker.Class(slot.tag)?.Name == "ProjectParametrizedElemParamsCell") + foreach (var association in ReadAssociations(walk, slot.index, idWidth, elementIds, globalIds)) + if (association.Ordinary && (association.ParameterId > 0 || ParameterWriter.IsSupportedBuiltInGlobalProperty(association.ParameterId))) + { + if (!properties.TryGetValue(association.GlobalId, out var targets)) + properties.Add(association.GlobalId, targets = []); + targets.Add(new(id, association.ParameterId)); + claimed.Add(association.GlobalOffset); + } + foreach (var field in walk.Captures.Where(c => c.Integer > 0 && c.Key is Dependency or "formula-reference")) + { + if (global && field.Key == "formula-reference") + { + if (!formulas.TryGetValue(field.Integer, out var consumers)) + formulas.Add(field.Integer, consumers = []); + consumers.Add(id); + } + else if (field.Key != Dependency || !claimed.Contains(field.ValueOffset)) + otherConsumers.Add(field.Integer); + } + }, pending); + if (!seen.SetEquals(elementIds)) + throw ParameterWriter.Unverified("The project element records are incomplete for global parameter dependency checks."); + return new(globals, formulas, properties, otherConsumers); + } +} diff --git a/src/RvtIO/Writing/ImportedImageReference.cs b/src/RvtIO/Writing/ImportedImageReference.cs new file mode 100644 index 00000000..ff28445e --- /dev/null +++ b/src/RvtIO/Writing/ImportedImageReference.cs @@ -0,0 +1,47 @@ +using RvtIO.Parsing; +using static RvtIO.Writing.UserParameterWriter; + +namespace RvtIO.Writing; + +internal static class ImportedImageReference +{ + internal const string NoneName = ""; + + internal static string? CaptureKey(SchemaClass declaring, SchemaField field) => (declaring.Name, field.Name) switch + { + ("ImageSymbol", "m_idImageHolder" or "m_flags" or "m_viewId" or "m_ownerSymbolId" or "m_widthInPixels" or "m_heightInPixels") or + ("ImageHolder", "m_pRasterImage" or "m_idImageSymbol" or "m_flags") or + ("ARasterImage", "m_compressedImage" or "m_width" or "m_height") or + ("Symbol", "m_symbolInfo") or ("SymbolInfo", "m_name") => declaring.Name + "." + field.Name, + _ => null, + }; + + internal static long ReadId(string value) => value == "-1" ? -1 : ReferenceId(value) + ?? throw new RvtWriteRefusedException("invalid-parameter-value", "Expected a positive element ID or -1 for no image."); + + internal static string? ReadName(WideBlockWalker walker, IReadOnlyDictionary images, long id) + { + if (id == -1) + return NoneName; + if (images.GetValueOrDefault(id) is not { Exact: true, EmptyEntityAt: < 0 } symbol || Integer(symbol, "m_id") != id + || Integer(symbol, "ImageSymbol.m_idImageHolder") is not (> 0 and long holderId) + || Integer(symbol, "ImageSymbol.m_flags") != 0 || Integer(symbol, "ImageSymbol.m_viewId") != -1 + || Integer(symbol, "ImageSymbol.m_ownerSymbolId") != -1 + || Integer(symbol, "ImageSymbol.m_widthInPixels") is not (> 0 and long width) + || Integer(symbol, "ImageSymbol.m_heightInPixels") is not (> 0 and long height) + || images.GetValueOrDefault(holderId) is not { Exact: true, EmptyEntityAt: < 0 } holder || Integer(holder, "m_id") != holderId + || Integer(holder, "ImageHolder.m_idImageSymbol") != id || Integer(holder, "ImageHolder.m_flags") != 0 + || PointerSlot(walker, holder, "ImageHolder.m_pRasterImage", "ARasterImage") is not int raster + || Integer(holder, "ARasterImage.m_width", raster) != width || Integer(holder, "ARasterImage.m_height", raster) != height + || Integer(holder, "ARasterImage.m_compressedImage#", raster) is not > 0 + || PointerSlot(walker, symbol, "Symbol.m_symbolInfo", "SymbolInfo") is not int info) + return null; + return symbol.Captures.Where(c => c.QueueIndex == info && c.Key == "SymbolInfo.m_name").ToArray() + is [{ Text: { Length: > 0 } name }] ? name : null; + } + + internal static int? PointerSlot(WideBlockWalker walker, WideBlockWalker.Walk walk, string field, string type) => + walk.Captures.Where(c => c.AtRoot && c.Key == field && c.Kind == WideBlockWalker.CaptureKind.PointerClass).ToArray() + is [{ Integer: > 0 and long tag, QueuePosition: >= 0 and int slot }] + && slot < walk.Queue.Count && walk.Queue[slot] == tag && walker.Class((int)tag)?.Name == type ? slot : null; +} diff --git a/src/RvtIO/Writing/LinkedImageReference.cs b/src/RvtIO/Writing/LinkedImageReference.cs new file mode 100644 index 00000000..fa1a72eb --- /dev/null +++ b/src/RvtIO/Writing/LinkedImageReference.cs @@ -0,0 +1,73 @@ +using RvtIO.Parsing; +using static RvtIO.Writing.UserParameterWriter; + +namespace RvtIO.Writing; + +internal static class LinkedImageReference +{ + internal sealed record Location(string Path, string PathType); + + private const string TextPair = "std::pair< AString, AString >"; + private const string ResourceCell = "ExternalResourceReferenceCell"; + + internal static string? CaptureKey(SchemaClass declaring, SchemaField field) => (declaring.Name, field.Name) switch + { + (ResourceCell, "m_externalResourceReferences" or "m_externalResourceReferencesExpanded") or + ("ExternalRefIdMap", "m_refs") or ("ExternalResourceRef", "m_referenceInformation") or + (TextPair, "first" or "second") => WideBlockWalker.AllItemsKeyPrefix + declaring.Name + "." + field.Name, + _ => null, + }; + + internal static bool IsVerifiedTarget(WideBlockWalker walker, IReadOnlyDictionary images, long id) + { + return images.GetValueOrDefault(id) is { } symbol && Integer(symbol, "m_id") == id + && Integer(symbol, "ImageSymbol.m_viewId") == -1 && Integer(symbol, "ImageSymbol.m_ownerSymbolId") == -1 + && Integer(symbol, "ImageSymbol.m_idImageHolder") is > 0 and long holderId + && images.GetValueOrDefault(holderId) is { Exact: true, EmptyEntityAt: < 0 } holder + && Integer(holder, "m_id") == holderId && Integer(holder, "ImageHolder.m_idImageSymbol") == id + && Integer(holder, "ImageHolder.m_flags") == 1 && Integer(holder, "ImageHolder.m_pRasterImage") == 0 + && ReadLocation(walker, symbol) is not null; + } + + internal static Location? ReadLocation(WideBlockWalker walker, WideBlockWalker.Walk symbol) + { + if (!symbol.Exact || symbol.EmptyEntityAt >= 0 || Integer(symbol, "ImageSymbol.m_flags") != 4 + || symbol.Queue.Select((tag, index) => (tag, index)).Where(x => walker.Class(x.tag)?.Name == ResourceCell) + .ToArray() is not [{ index: var slot }]) + return null; + + const string prefix = WideBlockWalker.AllItemsKeyPrefix; + var maps = (Integer(symbol, prefix + ResourceCell + ".m_externalResourceReferences#", slot), + Integer(symbol, prefix + ResourceCell + ".m_externalResourceReferencesExpanded#", slot), + Integer(symbol, prefix + "ExternalRefIdMap.m_refs#", slot)); + if (maps is not ((1, null, null) or (0, 1, 1)) + || Integer(symbol, prefix + "ExternalResourceRef.m_referenceInformation#", slot) is not (> 0 and long count)) + return null; + + var fields = symbol.Captures.Where(x => x.QueueIndex == slot && x.DeclaringClass == TextPair).ToArray(); + if (fields.Length % 2 != 0 || fields.Length / 2 != count) + return null; + + var entries = new Dictionary(StringComparer.Ordinal); + for (int i = 0; i < fields.Length; i += 2) + { + if (fields[i] is not { Field: "first", Text: { Length: > 0 } key } + || fields[i + 1] is not { Field: "second", Text: { } value } || !entries.TryAdd(key, value)) + return null; + } + if (!entries.TryGetValue("Path", out string? path) || string.IsNullOrWhiteSpace(path) || path.Contains('\0') + || !entries.TryGetValue("PathType", out string? pathType)) + return null; + return pathType switch + { + "Absolute" when IsAbsoluteFilePath(path) => new(path, pathType), + "Relative" or "Relative to Central Model" when !Path.IsPathRooted(path) + && !path.StartsWith('\\') && !path.StartsWith('/') && !path.Contains(':') => new(path, pathType), + _ => null, + }; + } + + private static bool IsAbsoluteFilePath(string path) => Path.IsPathFullyQualified(path) + || path.StartsWith("\\\\", StringComparison.Ordinal) + || path.Length >= 3 && char.IsAsciiLetter(path[0]) && path[1] == ':' && path[2] is '\\' or '/'; +} diff --git a/src/RvtIO/Writing/LoadedFamilyParameterWriter.cs b/src/RvtIO/Writing/LoadedFamilyParameterWriter.cs new file mode 100644 index 00000000..2ce3d54e --- /dev/null +++ b/src/RvtIO/Writing/LoadedFamilyParameterWriter.cs @@ -0,0 +1,718 @@ +using System.Buffers.Binary; +using OpenMcdf; +using RvtIO.BuiltIns; +using RvtIO.Model; +using RvtIO.Parsing; +using static RvtIO.Writing.UserParameterWriter; + +namespace RvtIO.Writing; + +internal static class LoadedFamilyParameterWriter +{ + private const string TrivialIds = WideBlockWalker.AllItemsKeyPrefix + "trivial"; + private static readonly string[] NamedFields = + ["m_str", "m_oExpression", "m_value", "m_elemId", "m_paramId", "m_int", "m_instance", "m_reporting"]; + private sealed record ProjectRecord(int Partition, long Id, byte[] Body, int ClassId, WideBlockWalker.Walk Walk); + private sealed record FormulaSymbol(ProjectRecord Record, FamilyStore Values); + private sealed record ValueEdit(long Id, StorageType Storage, byte[] Bytes, int Mode); + internal sealed record NamedValue(WideBlockWalker.Capture[] Fields) + { + internal long Id => Fields[4].Integer; + internal long Instance => Fields[6].Integer; + internal bool IsDriven => Fields[1].Integer != 0 || Fields[7].Integer != 0; + internal WideBlockWalker.Capture Value(StorageType storage) => Fields[storage switch + { + StorageType.String => 0, + StorageType.Double => 2, + StorageType.ElementId => 3, + _ => 5, + }]; + } + internal sealed record FamilyStore(int CountOffset, NamedValue[] Rows); + + internal static string? CaptureKey(SchemaClass declaring, SchemaField field) => (declaring.Name, field.Name) switch + { + ("FamilyBase", "m_trivialParamIds") => TrivialIds, + ("FamilyBase", "m_familyParams" or "m_inPlace" or "m_categoryId" or "m_name") or + ("FamilyInstance", "m_pInstParams" or "m_masterSymbolId" or "m_superInstanceId") or + ("FamilySymbol", "m_pParams" or "m_familyId" or "m_masterId" or "m_ownerInstanceId") or + ("FamilyParams", "m_params") or + ("ParamElemFamily", "m_instanceParam") or + ("InstInfoBase", "m_symbolId") => declaring.Name + "." + field.Name, + ("ParameterExpression" or "CalculatedParameterExpression" or "FormulaTokenParameter", "m_paramId") => "formula-reference", + ("NamedParam", _) when NamedFields.Contains(field.Name) => field.Name, + _ => null, + }; + + internal static ParameterWriter.PlanResult? Plan( + RootStorage root, PartitionFraming.Tags tags, int idWidth, WideBlockWalker walker, IReadOnlySet elementIds, + IReadOnlySet globals, int? category, + byte[]? definition, ParameterWriter.Edit edit, long? material, WideBlockWalker.Walk? reference, ProjectFamilyReference? projectReference, + int partition, byte[] body, WideBlockWalker.Walk walk, + ParameterWriter.Pending pending, bool instance, GlobalParameterWriter.PropertyValue? driven = null) + { + if (definition is not { Length: >= 2 }) + throw ParameterWriter.Unverified("The family parameter definition record was not found."); + string? definitionClass = walker.Class(BinaryPrimitives.ReadUInt16LittleEndian(definition))?.Name; + if (definitionClass is not ("ParamElemFamily" or "ParamElemExternal")) + throw new RvtWriteRefusedException("unsupported-parameter", "The definition is outside the loaded family parameter scope."); + var (def, slot) = ReadDefinition(walker, definition, edit); + int mode = instance ? 1 : 0; + if ((definitionClass == "ParamElemFamily" && Integer(def, "ParamElemFamily.m_instanceParam") != mode) + || (definitionClass == "ParamElemExternal" && Integer(def, WideBlockWalker.AllItemsKeyPrefix + "bindings#") != 0)) + throw ParameterWriter.Unverified("The definition belongs to a different parameter scope."); + bool familyTypeReference = walker.Class(def.Queue[slot])?.Name == "ParamDefFamType"; + (StorageType Storage, byte[] Replacement, UnitType? Quantity)? encoded = driven is { } property + ? PrepareDriven(property) + : familyTypeReference ? null : Encode(walker, def, slot, edit, idWidth, material, includeCurrency: true); + if (!instance && Integer(walk, "FamilySymbol.m_masterId") != -1) + throw ParameterWriter.Unverified("The family element's master and effective symbols could not be verified."); + var (familyWalk, display, symbols, masterIds) = ReadOwnership(root, tags, idWidth, walker, elementIds, + category, edit.ElementId, walk, pending, instance); + var owner = new ProjectRecord(partition, edit.ElementId, body, BinaryPrimitives.ReadUInt16LittleEndian(body), walk); + var declaration = ReadStore(walker, familyWalk, "FamilyBase.m_familyParams"); + var declared = FamilyFormulaPropagation.FindFormulaRow(declaration, edit.ParameterId); + bool inverse = !instance && declared.Fields[1].Integer != 0; + if (inverse && driven is not null) + throw ParameterWriter.Unverified("A global parameter cannot update a calculated family property directly."); + if (!inverse) + _ = FindRow(declaration, edit.ParameterId, mode); + var trivial = familyWalk.Captures.Where(c => c.AtRoot && + c.Key.StartsWith(TrivialIds + "@", StringComparison.Ordinal)).ToArray(); + if (Integer(familyWalk, TrivialIds + "#") != trivial.Length + || trivial.Count(c => c.Integer == edit.ParameterId) != 1) + throw ParameterWriter.Unverified("The family does not classify this parameter as independent of geometry."); + + if (familyTypeReference) + { + if (Integer(display.Walk, "FamilySymbol.m_ownerInstanceId") != -1) + throw ParameterWriter.Unverified("The effective family symbol is outside the verified family type reference scope."); + bool independentType = !instance && definitionClass == "ParamElemFamily" && !inverse + && !UsesFormula(familyWalk) && !UsesFormula(walk); + VerifyFamilyReferenceOwner(familyWalk, reference, projectReference, edit, independentType); + } + var (storage, replacement, quantity) = encoded ?? EncodeFamilyTypeReference(def, slot, edit, idWidth, material, reference, projectReference); + var records = new List(); + string pointer = instance ? "FamilyInstance.m_pInstParams" : "FamilySymbol.m_pParams"; + // Revit writes the instance flag on the family declaration, but clears it in the instance override store. + var store = ReadStore(walker, walk, pointer); + var storedRow = inverse ? null : FindRow(store, edit.ParameterId, 0, required: !instance || driven is not null); + if (driven is { } expected) + { + var saved = Location(storedRow!, storage, idWidth); + if (!body.AsSpan(saved.Offset, saved.Length).SequenceEqual(expected.Previous)) + throw ParameterWriter.Unverified("The controlled family property disagrees with the saved global value."); + VerifySeparateNamedValue(walk, edit.ParameterId); + } + var displayWalk = instance ? walker.Run(display.Body, 0, display.Body.Length, display.ClassId) : walk; + if (!inverse && (quantity == UnitType.UT_Currency || ParameterMeasurement.IsAdditionalSpec(quantity))) + { + var effectiveRow = storedRow ?? FindRow(ReadStore(walker, displayWalk, "FamilySymbol.m_pParams"), edit.ParameterId, 1)!; + var effectiveBody = storedRow is null ? display.Body : body; + var effectiveValue = Location(effectiveRow, storage, idWidth); + ParameterFormulaEvaluator.VerifyStableChange(BinaryPrimitives.ReadDoubleLittleEndian(effectiveBody.AsSpan(effectiveValue.Offset)), + BinaryPrimitives.ReadDoubleLittleEndian(replacement)); + } + if (familyTypeReference) + { + VerifySeparateNamedValue(walk, edit.ParameterId); + if (displayWalk != walk) + VerifySeparateNamedValue(displayWalk, edit.ParameterId); + } + if (instance) + { + GlobalParameterWriter.VerifyElementParameter(walker, displayWalk, idWidth, elementIds, globals, edit.ParameterId); + CheckFormulaDependencies(walk, edit.ParameterId); + } + if (inverse || UsesFormula(familyWalk) || UsesFormula(displayWalk)) + return PlanFormula(); + if (storedRow is null) + { + var inherited = FindRow(ReadStore(walker, displayWalk, "FamilySymbol.m_pParams"), edit.ParameterId, 1)!; + var inheritedValue = Location(inherited, storage, idWidth); + if (display.Body.AsSpan(inheritedValue.Offset, inheritedValue.Length).SequenceEqual(replacement)) + return null; + + // An undriven NamedParam has no deferred payload. Its first and last fields delimit the inline row. + int rowStart = inherited.Fields[0].ValueOffset; + int rowEnd = inherited.Fields[7].ValueOffset + 1; + int flag = inherited.Fields[6].ValueOffset; + if (rowStart < 0 || flag < rowStart || flag >= rowEnd || inheritedValue.Offset + inheritedValue.Length > flag) + throw ParameterWriter.Unverified("The inherited parameter does not have a verified inline layout."); + byte[] row = display.Body[rowStart..rowEnd]; + row[flag - rowStart] = 0; + row = ParameterWriter.ReplaceValue(row, inheritedValue.Offset - rowStart, inheritedValue.Length, replacement); + byte[] updated = InsertNamedParam(body, store, row); + VerifyUpdated(updated, owner.ClassId); + return new ParameterWriter.PlanResult([new(partition, 102, (ulong)edit.ElementId, updated)], null); + } + var original = Location(storedRow, storage, idWidth); + ReadOnlySpan originalBytes = body.AsSpan(original.Offset, original.Length); + AddReplacement(owner, original); + if (!instance) + { + long? familyId = Integer(familyWalk, "m_id"); + foreach (var (id, symbol) in symbols) + { + if (id == edit.ElementId) + continue; + if (symbol is null || masterIds.Contains(id) || Integer(symbol.Walk, "FamilySymbol.m_familyId") != familyId + || (familyTypeReference && Integer(symbol.Walk, "FamilySymbol.m_ownerInstanceId") != -1)) + throw ParameterWriter.Unverified("A derived family symbol could not be verified."); + var full = walker.Run(symbol.Body, 0, symbol.Body.Length, symbol.ClassId); + GlobalParameterWriter.VerifyElementParameter(walker, full, idWidth, elementIds, globals, edit.ParameterId); + if (driven is not null || familyTypeReference) + VerifySeparateNamedValue(full, edit.ParameterId); + CheckFormulaDependencies(full, edit.ParameterId); + if (driven is not null) + continue; + var stored = Location(FindRow(ReadStore(walker, full, pointer), edit.ParameterId, 0)!, storage, idWidth); + if (!symbol.Body.AsSpan(stored.Offset, stored.Length).SequenceEqual(originalBytes)) + throw ParameterWriter.Unverified("The parameter value of a derived symbol disagrees with its master."); + AddReplacement(symbol, stored); + } + } + return records.Count == 0 ? null : new ParameterWriter.PlanResult(records, null); + + (StorageType Storage, byte[] Replacement, UnitType? Quantity) PrepareDriven(GlobalParameterWriter.PropertyValue value) + { + var format = FormulaParameterStorage.Read(walker, def, slot, includeCurrency: true); + value.VerifyFormat(format); + return (format.Storage, value.Replacement, format.Unit); + } + + static void VerifySeparateNamedValue(WideBlockWalker.Walk record, long id) + { + if (record.Captures.Any(field => field.Field == "m_paramId" && field.Integer == id && + field.DeclaringClass.StartsWith("ParamValue", StringComparison.Ordinal))) + throw ParameterWriter.Unverified("The named family property has a competing typed store."); + } + + void AddReplacement(ProjectRecord record, (int Offset, int Length) value) + { + if (record.Body.AsSpan(value.Offset, value.Length).SequenceEqual(replacement)) + return; + byte[] updated = ParameterWriter.ReplaceValue(record.Body, value.Offset, value.Length, replacement); + VerifyUpdated(updated, record.ClassId); + records.Add(new(record.Partition, 102, (ulong)record.Id, updated)); + } + + void VerifyUpdated(byte[] updated, int classId) + { + var readBack = Location(FindRow(ReadStore(walker, walker.Run(updated, 0, updated.Length, classId), pointer), + edit.ParameterId, 0)!, storage, idWidth); + if (!updated.AsSpan(readBack.Offset, readBack.Length).SequenceEqual(replacement)) + throw ParameterWriter.Unverified("The updated family parameter could not be read back."); + } + + bool UsesFormula(WideBlockWalker.Walk value) => + value.Captures.Any(c => c.Key == "formula-reference" && c.Integer == edit.ParameterId); + + ParameterWriter.PlanResult? PlanFormula() + { + var familyId = Integer(familyWalk, "m_id"); + var declaredDependencies = FamilyFormulaPropagation.Dependencies(familyWalk, declaration); + if (!inverse && UsesFormula(familyWalk) && !declaredDependencies.ContainsKey(edit.ParameterId)) + throw ParameterWriter.Unverified("The loaded family formula input is referenced outside its declared formulas."); + var independent = trivial.Select(c => c.Integer).ToHashSet(); + var ids = declaration.Rows.Where(row => row.Id > 0).Select(row => row.Id).ToHashSet(); + var definitions = new Dictionary(); + ParameterWriter.ScanPartitions(root, tags, idWidth, (number, record) => + { + if (record.Block == 0 && record.Channel == 102 && ids.Contains((long)record.Owner) && + !definitions.TryAdd((long)record.Owner, record.Body.ToArray())) + throw ParameterWriter.Unverified("A formula parameter has more than one project definition."); + }, pending); + var formats = new Dictionary(); + var input = new ValueEdit(edit.ParameterId, storage, replacement, mode); + ParameterFormulaEvaluator.Linear? equation = null; + if (inverse) + { + equation = ReadEquation(familyWalk, declaration); + if (ReadEquation(walk, store) != equation) + throw ParameterWriter.Unverified("The loaded type formula disagrees with its family declaration."); + var resultFormat = ReadFormat(edit.ParameterId); + var requested = resultFormat.Decode(replacement); + var formula = equation.Value; + var inputFormat = ReadFormat(formula.InputId); + if (formula.Scale == 0 || requested.Kind != ParameterFormulaEvaluator.ValueKind.Number || requested.Unit != formula.Offset.Unit) + throw ParameterWriter.Unverified("The requested formula result does not have a verified inverse."); + _ = FindRow(declaration, formula.InputId, 0); + var outputLocation = Location(FamilyFormulaPropagation.FindFormulaRow(store, edit.ParameterId), resultFormat.Storage, idWidth); + var inputLocation = Location(FindRow(store, formula.InputId, 0)!, inputFormat.Storage, idWidth); + bool unchangedResult = body.AsSpan(outputLocation.Offset, outputLocation.Length).SequenceEqual(replacement); + double solved = unchangedResult ? inputFormat.Decode(body.AsSpan(inputLocation.Offset, inputLocation.Length)).Number + : (requested.Number - formula.Offset.Number) / formula.Scale; + if (inputFormat.Storage == StorageType.Double && (!formula.ExactScaling || inputFormat.Unit != resultFormat.Unit || + solved == 0 && requested.Number != 0 || double.IsSubnormal(solved) || double.IsSubnormal(requested.Number))) + throw ParameterWriter.Unverified("The real-valued inverse does not have verified exact scaling."); + if (!double.IsFinite(solved)) + throw new RvtWriteRefusedException("invalid-parameter-value", "The formula inverse does not produce a finite input."); + var encoded = inputFormat.Encode(new(solved, inputFormat.FormulaUnit)); + input = new(formula.InputId, inputFormat.Storage, encoded, 0); + } + if (instance) + { + VerifyFormulaRecord(walk, edit.ElementId); + VerifyFormulaRecord(displayWalk, display.Id); + if (Integer(displayWalk, "FamilySymbol.m_ownerInstanceId") is not long displayOwner || + displayOwner != -1 && displayOwner != edit.ElementId) + throw ParameterWriter.Unverified("The effective formula symbol belongs to another instance."); + var symbolRows = ReadStore(walker, displayWalk, "FamilySymbol.m_pParams"); + _ = FindRow(symbolRows, edit.ParameterId, 1); + var source = new FormulaSymbol(display with { Walk = displayWalk }, symbolRows); + var updates = Recalculate(source, new(body, store)); + foreach (var update in updates) + CheckFormulaDependencies(walk, update.Id); + updates.Add(new(edit.ParameterId, storage, replacement, 1)); + WriteFormulaValues(owner, pointer, store, updates.Select(update => update with { Mode = 0 })); + return records.Count == 0 ? null : new ParameterWriter.PlanResult(records, null); + } + + var sources = new Dictionary(); + var seenInstances = new HashSet(); + bool hasInstanceResults = false; + var original = Location(FindRow(store, input.Id, 0)!, input.Storage, idWidth); + + foreach (var (id, record) in symbols) + { + if (record is null || id != edit.ElementId && (masterIds.Contains(id) || + Integer(record.Walk, "FamilySymbol.m_familyId") != familyId || + Integer(record.Walk, "FamilySymbol.m_ownerInstanceId") != -1)) + throw ParameterWriter.Unverified("A derived formula symbol could not be verified."); + // Global edits write the associated primary type, even when placements use derived copies. + if (driven is not null && id != edit.ElementId) + continue; + var full = id == edit.ElementId ? walk : walker.Run(record.Body, 0, record.Body.Length, record.ClassId); + VerifyFormulaRecord(full, id); + var rows = id == edit.ElementId ? store : ReadStore(walker, full, pointer); + if (equation is not null && id != edit.ElementId && ReadEquation(full, rows) != equation) + throw ParameterWriter.Unverified("A derived symbol has a different formula inverse from its master."); + var before = Location(FindRow(rows, input.Id, 0)!, input.Storage, idWidth); + if (!record.Body.AsSpan(before.Offset, before.Length).SequenceEqual(body.AsSpan(original.Offset, original.Length))) + throw ParameterWriter.Unverified("The derived formula input disagrees with its master."); + + var source = new FormulaSymbol(record with { Walk = full }, rows); + sources.Add(id, source); + var results = Recalculate(source); + if (inverse && !results.Any(result => result.Id == edit.ParameterId && + (input.Storage == StorageType.Integer || result.Bytes.AsSpan().SequenceEqual(replacement)))) + throw ParameterWriter.Unverified("The verified forward calculation does not reproduce the formula inverse."); + hasInstanceResults |= results.Any(result => result.Mode == 1); + results.Add(input); + WriteFormulaValues(source.Record, pointer, rows, results); + } + + if (hasInstanceResults) + ParameterWriter.ScanPartitions(root, tags, idWidth, ReadInstance, pending); + return records.Count == 0 ? null : new ParameterWriter.PlanResult(records, null); + + ParameterFormulaEvaluator.Linear ReadEquation(WideBlockWalker.Walk record, FamilyStore rows) + { + var linear = Resolve(edit.ParameterId, ParameterFormulaEvaluator.MaxDepth); + if (linear.InputId <= 0) + throw ParameterWriter.Unverified("The loaded type formula does not have one writable input."); + return linear; + + ParameterFormulaEvaluator.Linear Resolve(long id, int depth) + { + var row = FamilyFormulaPropagation.FindFormulaRow(rows, id); + var format = ReadFormat(id); + if (row.Instance != 0 || format.Kind != ParameterFormulaEvaluator.ValueKind.Number || !independent.Contains(id)) + throw ParameterWriter.Unverified("The formula inverse contains an unverified type parameter."); + if (row.Fields[1].Integer == 0) + return ParameterFormulaEvaluator.Linear.Input(id, format.FormulaUnit); + var value = ParameterFormulaEvaluator.ReadLinear(walker, record, row.Fields[1], depth, Resolve); + if (value.Offset.Unit != format.FormulaUnit) + throw ParameterWriter.Unverified("A formula inverse has incompatible units."); + if (id != edit.ParameterId && format.Storage == StorageType.Integer && + (value.InputId <= 0 || ReadFormat(value.InputId).Storage != StorageType.Integer || + value.Scale != Math.Truncate(value.Scale) || value.Offset.Number != Math.Truncate(value.Offset.Number))) + throw ParameterWriter.Unverified("A formula inverse would have to reverse an intermediate rounding step."); + return value; + } + } + + void ReadInstance(int number, PartitionFraming.Record record) + { + if (record.Block != 0 || record.Channel != 102 || record.Body.Length < 2 || !elementIds.Contains((long)record.Owner)) + return; + int id = BinaryPrimitives.ReadUInt16LittleEndian(record.Body.Span); + if (walker.Class(id)?.Name != "FamilyInstance") + return; + var data = record.Body.ToArray(); + var header = walker.Run(data, 0, data.Length, id, rootOnly: true); + if (!header.RootRead || Integer(header, "FamilyInstance.m_masterSymbolId") is not long master) + throw ParameterWriter.Unverified("A family instance's master symbol link could not be verified."); + if (master != edit.ElementId) + return; + if (!seenInstances.Add(record.Owner)) + throw ParameterWriter.Unverified("A dependent family instance has more than one project record."); + var full = walker.Run(data, 0, data.Length, id); + VerifyFormulaRecord(full, (long)record.Owner); + long effective = InstanceSymbol(walker, full); + if (Integer(full, "FamilyInstance.m_superInstanceId") != -1 || !symbols.ContainsKey(effective) || + !sources.TryGetValue(driven is null ? effective : edit.ElementId, out var source)) + throw ParameterWriter.Unverified("A dependent family instance is nested or has an unverified effective type."); + const string instancePointer = "FamilyInstance.m_pInstParams"; + var rows = ReadStore(walker, full, instancePointer); + var results = Recalculate(source, new(data, rows)); + WriteFormulaValues(new(number, (long)record.Owner, data, id, full), instancePointer, rows, + results.Select(result => result with { Mode = 0 })); + } + + List Recalculate(FormulaSymbol source, FamilyFormulaPropagation.InstanceValues? values = null) + { + return FamilyFormulaPropagation.Recalculate(walker, source.Record.Walk, source.Record.Body, [source.Values], + source.Values, null, input.Id, input.Bytes, idWidth, + id => independent.Contains(id) && (!instance || FamilyFormulaPropagation.FindFormulaRow(declaration, id).Instance == 1), ReadSymbolFormat, + id => declaredDependencies.GetValueOrDefault(id), values) + .Select(result => new ValueEdit(result.Id, result.Format.Storage, result.Replacement, + (int)FamilyFormulaPropagation.FindFormulaRow(source.Values, result.Id).Instance)).ToList(); + + FormulaParameterStorage ReadSymbolFormat(long id) + { + if (FamilyFormulaPropagation.FindFormulaRow(source.Values, id).Instance != + FamilyFormulaPropagation.FindFormulaRow(declaration, id).Instance) + throw ParameterWriter.Unverified("A loaded formula value's scope disagrees with its family declaration."); + return ReadFormat(id); + } + } + + FormulaParameterStorage ReadFormat(long id) + { + if (formats.TryGetValue(id, out var format)) + return format; + if (!definitions.TryGetValue(id, out var data) || data.Length < sizeof(ushort)) + throw ParameterWriter.Unverified("A loaded formula parameter definition was not found."); + var type = walker.Class(BinaryPrimitives.ReadUInt16LittleEndian(data))?.Name; + if (type is not ("ParamElemFamily" or "ParamElemExternal")) + throw ParameterWriter.Unverified("A formula references a parameter outside the loaded family definition."); + var (decoded, index) = ReadDefinition(walker, data, new ParameterWriter.Edit(edit.ElementId, id, null)); + long mode = FamilyFormulaPropagation.FindFormulaRow(declaration, id).Instance; + if (type == "ParamElemFamily" ? Integer(decoded, "ParamElemFamily.m_instanceParam") != mode : + Integer(decoded, WideBlockWalker.AllItemsKeyPrefix + "bindings#") != 0) + throw ParameterWriter.Unverified("A loaded formula parameter's definition disagrees with its family declaration."); + format = FormulaParameterStorage.Read(walker, decoded, index, includeCurrency: true); + formats.Add(id, format); + return format; + } + + void WriteFormulaValues(ProjectRecord target, string storePointer, FamilyStore rows, IEnumerable updates) + { + var locations = updates.Select(update => (Update: update, Location: Location(Row(rows, update), update.Storage, idWidth))) + .OrderByDescending(item => item.Location.Offset).ToArray(); + byte[] data = target.Body; + foreach (var (update, location) in locations) + { + long? controlling = target.Id == edit.ElementId && update.Id == edit.ParameterId ? driven?.GlobalId : null; + GlobalParameterWriter.VerifyElementParameter(walker, target.Walk, idWidth, elementIds, globals, update.Id, controlling); + if (driven is not null) + VerifySeparateNamedValue(target.Walk, update.Id); + if (!target.Body.AsSpan(location.Offset, location.Length).SequenceEqual(update.Bytes)) + data = ParameterWriter.ReplaceValue(data, location.Offset, location.Length, update.Bytes); + } + if (ReferenceEquals(data, target.Body)) + return; + var readBack = ReadStore(walker, walker.Run(data, 0, data.Length, target.ClassId), storePointer); + foreach (var (update, _) in locations) + { + var location = Location(Row(readBack, update), update.Storage, idWidth); + if (!data.AsSpan(location.Offset, location.Length).SequenceEqual(update.Bytes)) + throw ParameterWriter.Unverified("An updated loaded formula value could not be read back."); + } + records.Add(new(target.Partition, 102, (ulong)target.Id, data)); + + static NamedValue Row(FamilyStore rows, ValueEdit update) + { + var value = FamilyFormulaPropagation.FindFormulaRow(rows, update.Id); + if (value.Instance != update.Mode) + throw ParameterWriter.Unverified("A loaded formula value's instance or type scope disagrees with its definition."); + return value; + } + } + + void VerifyFormulaRecord(WideBlockWalker.Walk record, long id) + { + if (!record.Exact || record.EmptyEntityAt >= 0 || Integer(record, "m_id") != id || + record.Queue.Any(tag => walker.IsA(tag, "GroupMembership"))) + throw ParameterWriter.Unverified("A loaded formula record could not be verified or belongs to a group."); + } + } + } + + internal static bool TryPlanTypeIdentity( + RootStorage root, PartitionFraming.Tags tags, int idWidth, WideBlockWalker walker, IReadOnlySet elementIds, IReadOnlySet globals, + int? category, ParameterWriter.Edit edit, WideBlockWalker.Walk walk, StorageType storage, byte[] replacement, + ParameterWriter.Pending pending, GlobalParameterWriter.PropertyValue? driven, out ParameterWriter.PlanResult? plan) + { + plan = null; + var (family, target, symbols, masterIds) = ReadOwnership(root, tags, idWidth, walker, elementIds, category, edit.ElementId, walk, pending, instance: false); + bool derivedTarget = Integer(target.Walk, "FamilySymbol.m_masterId") is > 0; + if ((symbols.Count != 1 && category != (int)BuiltInCategory.OST_GenericModel) + || (derivedTarget && (driven is null || masterIds.Contains(target.Id))) + || family.EmptyEntityAt >= 0 || walk.EmptyEntityAt >= 0) + throw ParameterWriter.Unverified("The loaded identity field requires a verified primary symbol and supported derived copies."); + CheckFormulaDependencies(family, edit.ParameterId); + CheckFormulaDependencies(walk, edit.ParameterId); + + var declaration = FindRow(ReadStore(walker, family, "FamilyBase.m_familyParams"), edit.ParameterId, 0, required: false); + const string pointer = "FamilySymbol.m_pParams"; + var row = FindRow(ReadStore(walker, walk, pointer), edit.ParameterId, 0, required: false); + if ((declaration is null) != (row is null) + || CountLocalReferences(walk) != (row is null ? 0 : 1)) + throw ParameterWriter.Unverified("The loaded identity field has an ambiguous parameter store."); + if (row is null) + { + if (symbols.Count != 1) + throw ParameterWriter.Unverified("The loaded identity field has no verified family value to mirror."); + return false; + } + + if (!HasIdentityStorage(declaration!) || !HasIdentityStorage(row) || ParameterWriter.FindValue(walker, walk, edit, storage) is not null) + throw ParameterWriter.Unverified("The loaded identity field has an unverified value or competing typed store."); + + var records = new List(); + var original = Location(row, storage, idWidth); + var originalValue = target.Body.AsSpan(original.Offset, original.Length); + if (driven is { } expected && !originalValue.SequenceEqual(expected.Previous)) + throw ParameterWriter.Unverified("The controlled family identity value disagrees with the saved global value."); + ReplaceNamedValue(target, original); + foreach (var (id, symbol) in symbols) + { + if (derivedTarget || id == target.Id) + continue; + if (symbol is null || masterIds.Contains(id) + || Integer(symbol.Walk, "FamilySymbol.m_familyId") != Integer(family, "m_id") + || Integer(symbol.Walk, "FamilySymbol.m_ownerInstanceId") != -1) + throw ParameterWriter.Unverified("A derived family symbol could not be verified for the identity edit."); + var full = walker.Run(symbol.Body, 0, symbol.Body.Length, symbol.ClassId); + if (driven is null) + GlobalParameterWriter.VerifyElementParameter(walker, full, idWidth, elementIds, globals, edit.ParameterId); + CheckFormulaDependencies(full, edit.ParameterId); + var copy = FindRow(ReadStore(walker, full, pointer), edit.ParameterId, 0)!; + var position = Location(copy, storage, idWidth); + if (full.EmptyEntityAt >= 0 || CountLocalReferences(full) != 1 || !HasIdentityStorage(copy) + || ParameterWriter.FindValue(walker, full, edit, storage) is not null + || full.Queue.Any(tag => walker.IsA(tag, "GroupMembership"))) + throw ParameterWriter.Unverified("A stored identity copy has an unverified layout."); + if (driven is not null) + continue; + if (!symbol.Body.AsSpan(position.Offset, position.Length).SequenceEqual(originalValue)) + throw ParameterWriter.Unverified("A stored identity copy cannot be verified against its primary symbol."); + ReplaceNamedValue(symbol, position); + } + if (records.Count != 0) + plan = new ParameterWriter.PlanResult(records, null); + return true; + + void ReplaceNamedValue(ProjectRecord owner, (int Offset, int Length) location) + { + if (owner.Body.AsSpan(location.Offset, location.Length).SequenceEqual(replacement)) + return; + byte[] updated = ParameterWriter.ReplaceValue(owner.Body, location.Offset, location.Length, replacement); + var verified = walker.Run(updated, 0, updated.Length, owner.ClassId); + var readBack = Location(FindRow(ReadStore(walker, verified, pointer), edit.ParameterId, 0)!, storage, idWidth); + if (readBack.Length != replacement.Length || CountLocalReferences(verified) != 1 + || !updated.AsSpan(readBack.Offset, readBack.Length).SequenceEqual(replacement)) + throw ParameterWriter.Unverified("The loaded identity value could not be read back."); + records.Add(new(owner.Partition, 102, (ulong)owner.Id, updated)); + } + + int CountLocalReferences(WideBlockWalker.Walk owner) => owner.Captures.Count(c => c.Field == "m_paramId" + && c.Integer == edit.ParameterId && !c.DeclaringClass.StartsWith("ParamValue", StringComparison.Ordinal)); + + bool HasIdentityStorage(NamedValue value) => value.Fields[3].Integer == -1 && value.Fields[5].Integer == 0 + && (storage == StorageType.String ? value.Fields[2].Real == 0 : value.Fields[0].Text == ""); + } + + internal static void VerifyLocalValueEdit( + RootStorage root, PartitionFraming.Tags tags, int idWidth, WideBlockWalker walker, IReadOnlySet elementIds, + int? category, ParameterWriter.Edit edit, WideBlockWalker.Walk walk, StorageType storage, WideBlockWalker.Walk? reference, + ProjectFamilyReference? projectReference, ParameterWriter.Pending pending, bool instance) + { + var (family, display, symbols, masterIds) = ReadOwnership(root, tags, idWidth, walker, elementIds, category, edit.ElementId, walk, pending, instance); + if (family.EmptyEntityAt >= 0) + throw ParameterWriter.Unverified("The loaded family declarations could not be read exactly."); + if (storage == StorageType.ElementId) + VerifyFamilyReferenceOwner(family, reference, projectReference, edit); + if (ReadStore(walker, family, "FamilyBase.m_familyParams").Rows.Any(row => row.Id == edit.ParameterId)) + { + if (!edit.UserDefined) + throw ParameterWriter.Unverified("The built-in parameter also has a value in the family store."); + throw new RvtWriteRefusedException(edit.Value is null ? "unsupported-parameter-clear" : "unsupported-parameter", + "This edit requires a parameter value separate from the loaded family declaration."); + } + if (instance) + { + VerifyStore(walk); + return; + } + + // Revit edits the addressed symbol's own value in the element store. + long masterId = Integer(display.Walk, "FamilySymbol.m_masterId") is > 0 and long master ? master : display.Id; + long? familyId = Integer(family, "m_id"); + foreach (var (id, symbol) in symbols) + { + bool primary = id == masterId; + if (primary && id != edit.ElementId) + continue; + if (symbol is null || (!primary && (masterIds.Contains(id) || Integer(symbol.Walk, "FamilySymbol.m_familyId") != familyId + || Integer(symbol.Walk, "FamilySymbol.m_ownerInstanceId") != -1))) + throw ParameterWriter.Unverified("A derived family symbol could not be verified for editing."); + var symbolWalk = id == edit.ElementId ? walk : walker.Run(symbol.Body, 0, symbol.Body.Length, symbol.ClassId); + VerifyStore(symbolWalk); + _ = ParameterWriter.FindValue(walker, symbolWalk, edit, storage); + } + + void VerifyStore(WideBlockWalker.Walk owner) + { + if (!owner.Exact || owner.EmptyEntityAt >= 0 + || owner.Captures.Any(c => c.Field == "m_paramId" && c.Integer == edit.ParameterId + && !c.DeclaringClass.StartsWith("ParamValue", StringComparison.Ordinal))) + throw ParameterWriter.Unverified("A family element has an unverified parameter store."); + } + } + + private static (WideBlockWalker.Walk Family, ProjectRecord Display, Dictionary Symbols, HashSet MasterIds) + ReadOwnership(RootStorage root, PartitionFraming.Tags tags, int idWidth, WideBlockWalker walker, IReadOnlySet elementIds, + int? category, long elementId, WideBlockWalker.Walk walk, ParameterWriter.Pending pending, bool instance) + { + if (category is not < -1 || (instance && Integer(walk, "FamilyInstance.m_superInstanceId") != -1)) + throw ParameterWriter.Unverified("A main-model, top-level family element could not be verified."); + + long masterId = instance ? Integer(walk, "FamilyInstance.m_masterSymbolId") ?? -1 + : Integer(walk, "FamilySymbol.m_masterId") switch { -1 => elementId, > 0 and long linked => linked, _ => -1 }; + long displayId = instance ? InstanceSymbol(walker, walk) : elementId; + if (masterId <= 0 || displayId <= 0 || !elementIds.Contains(masterId) || !elementIds.Contains(displayId) + || (!instance && Integer(walk, "FamilySymbol.m_ownerInstanceId") != -1)) + throw ParameterWriter.Unverified("The family element's master and effective symbols could not be verified."); + + var families = new Dictionary(); + var symbols = new Dictionary(); + var masterIds = new HashSet(); + ParameterWriter.ScanPartitions(root, tags, idWidth, (number, record) => + { + if (record.Block != 0 || record.Channel != 102 || record.Body.Length < 2 || !elementIds.Contains((long)record.Owner)) + return; + int cls = BinaryPrimitives.ReadUInt16LittleEndian(record.Body.Span); + string? name = walker.Class(cls)?.Name; + long id = (long)record.Owner; + if (name == "Family") + { + if (!families.TryAdd(id, record.Body.ToArray())) + families[id] = null; + return; + } + if (name != "FamilySymbol" || (instance && id != masterId && id != displayId)) + return; + byte[] data = record.Body.ToArray(); + var symbol = walker.Run(data, 0, data.Length, cls, rootOnly: true); + if (!symbol.RootRead || Integer(symbol, "m_id") != id + || Integer(symbol, "FamilySymbol.m_masterId") is not long master) + throw ParameterWriter.Unverified("A family symbol's master link could not be read exactly."); + if (master > 0) + masterIds.Add(master); + if (id == masterId || id == displayId || master == masterId) + { + if (!symbols.TryAdd(id, new(number, id, data, cls, symbol))) + symbols[id] = null; + } + }, pending); + if (!symbols.TryGetValue(masterId, out var masterSymbol) || masterSymbol is null + || Integer(masterSymbol.Walk, "FamilySymbol.m_masterId") != -1 + || Integer(masterSymbol.Walk, "FamilySymbol.m_ownerInstanceId") != -1 + || Integer(masterSymbol.Walk, "FamilySymbol.m_familyId") is not long familyId + || !families.TryGetValue(familyId, out var family) || family is null + || !symbols.TryGetValue(displayId, out var display) || display is null + || Integer(display.Walk, "FamilySymbol.m_familyId") != familyId + || (displayId != masterId && Integer(display.Walk, "FamilySymbol.m_masterId") != masterId)) + throw ParameterWriter.Unverified("The active family and its symbols could not be identified uniquely."); + + var familyWalk = walker.Run(family, 0, family.Length, BinaryPrimitives.ReadUInt16LittleEndian(family)); + if (!familyWalk.Exact || Integer(familyWalk, "m_id") != familyId || Integer(familyWalk, "FamilyBase.m_inPlace") != 0 + || Integer(familyWalk, "FamilyBase.m_categoryId") != category) + throw ParameterWriter.Unverified("The loaded family's ownership or category could not be verified."); + return (familyWalk, display, symbols, masterIds); + } + + private static long InstanceSymbol(WideBlockWalker walker, WideBlockWalker.Walk walk) + { + var instanceInfo = walk.Captures.Where(c => c.Key == "InstInfoBase.m_symbolId" && c.QueueIndex >= 0 + && walker.IsA(walk.Queue[c.QueueIndex], "InstanceInfo")).ToArray(); + return instanceInfo is [var value] ? value.Integer : -1; + } + + internal static void CheckFormulaDependencies(WideBlockWalker.Walk walk, long parameterId) + { + if (walk.Captures.Any(c => c.Key == "formula-reference" && c.Integer == parameterId)) + throw ParameterWriter.Unverified("The parameter is used by a saved family formula."); + } + + internal static FamilyStore ReadStore(WideBlockWalker walker, WideBlockWalker.Walk walk, string pointer) + { + if (!walk.Exact || Integer(walk, pointer) is not long tag + || walker.Class((int)tag)?.Name != "FamilyParams" + || walk.Queue.Select((cls, index) => (cls, index)).Where(p => p.cls == tag).ToArray() is not [{ index: var slot }]) + throw ParameterWriter.Unverified("The element's own FamilyParams store could not be read exactly."); + return ReadStore(walk.Captures.Where(c => c.QueueIndex == slot)); + } + + internal static FamilyStore ReadStore(IEnumerable captures) + { + var items = captures.ToArray(); + if (items.Where(c => c.Key == "FamilyParams.m_params#").ToArray() is not [{ ValueOffset: >= 0 } count]) + throw ParameterWriter.Unverified("The FamilyParams array count could not be read exactly."); + var fields = items.Where(c => c.DeclaringClass == "NamedParam").ToArray(); + if (fields.Length != count.Integer * NamedFields.Length) + throw ParameterWriter.Unverified("The NamedParam records could not be identified exactly."); + var rows = fields.Chunk(NamedFields.Length).ToArray(); + if (rows.Any(group => !group.Select(c => c.Field).SequenceEqual(NamedFields))) + throw ParameterWriter.Unverified("The NamedParam layout could not be verified."); + return new FamilyStore(count.ValueOffset, rows.Select(row => new NamedValue(row)).ToArray()); + } + + internal static byte[] InsertNamedParam(byte[] body, FamilyStore store, ReadOnlySpan row) + { + int minimum = store.CountOffset + sizeof(uint); + int insertion = store.Rows.Length == 0 ? minimum : store.Rows[^1].Fields[7].ValueOffset + 1; + if (insertion < minimum || insertion > body.Length + || BinaryPrimitives.ReadUInt32LittleEndian(body.AsSpan(store.CountOffset)) != store.Rows.Length) + throw ParameterWriter.Unverified("The family parameter array does not have a verified inline layout."); + byte[] updated = ParameterWriter.ReplaceValue(body, insertion, 0, row); + BinaryPrimitives.WriteInt32LittleEndian(updated.AsSpan(store.CountOffset), checked(store.Rows.Length + 1)); + return updated; + } + + internal static NamedValue? FindRow(FamilyStore store, long parameterId, int mode, bool required = true) + { + var matches = store.Rows.Where(row => row.Id == parameterId).ToArray(); + if (matches.Length == 0 && !required) + return null; + if (matches.Length == 0) + throw ParameterWriter.Unverified("The element has no unique locally stored family parameter value."); + if (matches is not [var named] || named.Instance != mode) + throw ParameterWriter.Unverified("The stored family parameter does not match its instance or type scope."); + if (named.IsDriven) + throw ParameterWriter.Unverified("The family parameter has a saved expression or is reporting."); + return named; + } + + internal static (int Offset, int Length) Location(NamedValue row, StorageType storage, int idWidth) + { + var value = row.Value(storage); + int length = storage switch + { + StorageType.String when value.Kind == WideBlockWalker.CaptureKind.Text && value.Text is not null + => sizeof(uint) + sizeof(char) * value.Text.Length, + StorageType.Integer when value.Kind == WideBlockWalker.CaptureKind.Integer => sizeof(int), + StorageType.Double when value.Kind == WideBlockWalker.CaptureKind.Real => sizeof(double), + StorageType.ElementId when value.Kind == WideBlockWalker.CaptureKind.Integer + && row.Fields[4].ValueOffset - value.ValueOffset == idWidth => idWidth, + _ => 0, + }; + if (value.ValueOffset < 0 || length == 0) + throw ParameterWriter.Unverified("The family parameter value does not match its definition."); + return (value.ValueOffset, length); + } +} diff --git a/src/RvtIO/Writing/ParameterFormulaEvaluator.cs b/src/RvtIO/Writing/ParameterFormulaEvaluator.cs new file mode 100644 index 00000000..4a11ec3a --- /dev/null +++ b/src/RvtIO/Writing/ParameterFormulaEvaluator.cs @@ -0,0 +1,379 @@ +using RvtIO.BuiltIns; +using RvtIO.Parsing; + +namespace RvtIO.Writing; + +internal static class ParameterFormulaEvaluator +{ + // The same bounded recursion covers both expression nodes and references to other global parameters. + internal const int MaxDepth = 40; + private const double ComparisonTolerance = 1e-9; + // Revit retains the current result when an exponentiation would exceed this magnitude. + private const double MaximumExponentialResult = 1e30; + // Revit's pi() is stored with this precision, including when it is multiplied by another parameter. + private const double RevitPi = 3.14159265358979; + private const string Arguments = WideBlockWalker.AllItemsKeyPrefix + "FunctionExpression.m_subexpressions"; + internal enum ValueKind { Number, Boolean, Text } + internal readonly record struct Value(double Number, UnitType Unit = UnitType.UT_Number, ValueKind Kind = ValueKind.Number, + string? Text = null) + { + internal static Value Boolean(bool value) => new(value ? 1 : 0, Kind: ValueKind.Boolean); + internal static Value String(string value) => new(0, Kind: ValueKind.Text, Text: value); + } + internal readonly record struct Linear(long InputId, double Scale, Value Offset, bool ExactScaling) + { + internal static Linear Input(long id, UnitType unit) => new(id, 1, new(0, unit), true); + } + + private enum BinaryOperator { Add = 1, Subtract = 2, Multiply = 3, Divide = 4, RaiseToPower = 5, Equal = 6, Greater = 7, Less = 8 } + private enum Function : long + { + Sin = 1, Cos = 2, Tan = 3, Asin = 4, Acos = 5, Atan = 6, Exp = 7, Log = 8, Sqrt = 9, + If = 10, Or = 11, And = 12, Not = 13, Abs = 14, Pi = 16, Round = 18, RoundUp = 19, RoundDown = 20, Ln = 22, + } + + internal static string? CaptureKey(SchemaClass declaring, SchemaField field) => (declaring.Name, field.Name) switch + { + ("BinaryOperatorExpression", "m_binaryOperator" or "m_pLeftSubexpression" or "m_pRightSubexpression") or + ("UnaryOperatorExpression", "m_unaryOperator" or "m_pSubexpression") or + ("ParenExpression", "m_pSubexpression") or ("NumberConstantExpression", "m_value" or "m_unitType" or "m_specTypeId") or + ("StringConstantExpression", "m_value") or ("FunctionExpression", "m_function") + => declaring.Name + "." + field.Name, + ("FunctionExpression", "m_subexpressions") => Arguments, + _ => null, + }; + + // A null result means the current inputs make Revit keep the formula's stored value. + internal static Value? Evaluate(WideBlockWalker walker, WideBlockWalker.Walk walk, WideBlockWalker.Capture expression, + int depth, Func resolve) + { + return Visit(ChildSlot(expression, walk), depth); + + Value? Visit(int slot, int remaining) + { + if (remaining <= 0) + throw ParameterWriter.Unverified("The formula dependency depth exceeds the verified limit."); + + switch (walker.Class(walk.Queue[slot])?.Name) + { + case "ParameterExpression": + long id = Field(slot, "formula-reference", WideBlockWalker.CaptureKind.Integer).Integer; + return resolve(id, remaining - 1); + case "NumberConstantExpression": + return ReadNumber(walk, slot); + case "StringConstantExpression": + string text = Field(slot, "StringConstantExpression.m_value", WideBlockWalker.CaptureKind.Text).Text ?? throw Unsupported(); + return Value.String(text); + case "ParenExpression": + return Visit(Child(slot, "ParenExpression.m_pSubexpression"), remaining - 1); + case "UnaryOperatorExpression": + if (Field(slot, "UnaryOperatorExpression.m_unaryOperator", WideBlockWalker.CaptureKind.Integer).Integer != 1) + throw Unsupported(); + if (Visit(Child(slot, "UnaryOperatorExpression.m_pSubexpression"), remaining - 1) is not { } operand) + return null; + if (operand.Kind != ValueKind.Number) + throw Unsupported(); + return operand with { Number = -operand.Number }; + case "BinaryOperatorExpression": + long operation = Field(slot, "BinaryOperatorExpression.m_binaryOperator", WideBlockWalker.CaptureKind.Integer).Integer; + if (operation is < 1 or > 8) + throw Unsupported(); + var left = Visit(Child(slot, "BinaryOperatorExpression.m_pLeftSubexpression"), remaining - 1); + var right = Visit(Child(slot, "BinaryOperatorExpression.m_pRightSubexpression"), remaining - 1); + return left is { } lhs && right is { } rhs ? Calculate((BinaryOperator)operation, lhs, rhs) : null; + case "FunctionExpression": + return EvaluateFunction(slot, remaining); + default: + throw Unsupported(); + } + } + + Value? EvaluateFunction(int slot, int remaining) + { + var function = (Function)Field(slot, "FunctionExpression.m_function", WideBlockWalker.CaptureKind.Integer).Integer; + int arity = function switch + { + Function.Pi => 0, + Function.If => 3, + Function.And or Function.Or => 2, + Function.Sin or Function.Cos or Function.Tan or Function.Asin or Function.Acos or Function.Atan or + Function.Exp or Function.Log or Function.Ln or Function.Sqrt or Function.Abs or Function.Not or + Function.Round or Function.RoundUp or Function.RoundDown => 1, + _ => throw Unsupported(), + }; + if (Field(slot, Arguments + "#", WideBlockWalker.CaptureKind.Integer).Integer != arity) + throw Unsupported(); + if (function == Function.Pi) + return new(RevitPi); + int[] children = Enumerable.Range(0, arity).Select(i => Child(slot, Arguments + "@" + i)).ToArray(); + Value? Argument(int index) => Visit(children[index], remaining - 1); + + if (Argument(0) is not { } argument) + return null; + return function switch + { + Function.If => Argument(AsBoolean(argument) ? 1 : 2), + Function.And when !AsBoolean(argument) => Value.Boolean(false), + Function.Or when AsBoolean(argument) => Value.Boolean(true), + Function.And or Function.Or => Argument(1) is { } right ? Value.Boolean(AsBoolean(right)) : null, + Function.Not => Value.Boolean(!AsBoolean(argument)), + _ when argument.Kind == ValueKind.Number => CalculateFunction(function, argument), + _ => throw Unsupported(), + }; + } + + int Child(int parent, string key) => ChildSlot(Field(parent, key, WideBlockWalker.CaptureKind.PointerClass), walk); + + WideBlockWalker.Capture Field(int slot, string key, WideBlockWalker.CaptureKind kind) => + ReadField(walk, slot, key, kind); + } + + internal static Linear ReadLinear(WideBlockWalker walker, WideBlockWalker.Walk walk, WideBlockWalker.Capture expression, + int depth, Func resolve) + { + return Visit(ChildSlot(expression, walk), depth); + + Linear Visit(int slot, int remaining) + { + if (remaining <= 0) + throw Unsupported(); + switch (walker.Class(walk.Queue[slot])?.Name) + { + case "ParameterExpression": + return resolve(ReadField(walk, slot, "formula-reference", WideBlockWalker.CaptureKind.Integer).Integer, + remaining - 1); + case "NumberConstantExpression": + return new(0, 0, ReadNumber(walk, slot), true); + case "ParenExpression": + return Visit(Child(slot, "ParenExpression.m_pSubexpression"), remaining - 1); + case "UnaryOperatorExpression" when + ReadField(walk, slot, "UnaryOperatorExpression.m_unaryOperator", WideBlockWalker.CaptureKind.Integer).Integer == 1: + var operand = Visit(Child(slot, "UnaryOperatorExpression.m_pSubexpression"), remaining - 1); + return operand with { Scale = -operand.Scale, Offset = operand.Offset with { Number = -operand.Offset.Number } }; + case "BinaryOperatorExpression": + var operation = (BinaryOperator)ReadField(walk, slot, "BinaryOperatorExpression.m_binaryOperator", + WideBlockWalker.CaptureKind.Integer).Integer; + var left = Visit(Child(slot, "BinaryOperatorExpression.m_pLeftSubexpression"), remaining - 1); + var right = Visit(Child(slot, "BinaryOperatorExpression.m_pRightSubexpression"), remaining - 1); + if (operation is < BinaryOperator.Add or > BinaryOperator.Divide || + right.InputId != 0 && (left.InputId != 0 || operation == BinaryOperator.Divide)) + throw Unsupported(); + + var offset = Calculate(operation, left.Offset, right.Offset) ?? throw Unsupported(); + if (left.InputId == 0 && right.InputId == 0) + return new(0, 0, offset, true); + + var (variable, constant) = left.InputId != 0 ? (left, right) : (right, left); + double factor = constant.Offset.Number; + double scale = operation switch + { + BinaryOperator.Add => variable.Scale, + BinaryOperator.Subtract => left.InputId != 0 ? variable.Scale : -variable.Scale, + BinaryOperator.Multiply => variable.Scale * factor, + BinaryOperator.Divide => variable.Scale / factor, + _ => throw Unsupported(), + }; + if (!ExactBinaryCoefficient(scale) || !ExactBinaryCoefficient(offset.Number)) + throw Unsupported(); + bool exactScaling = variable.ExactScaling && (operation is BinaryOperator.Multiply or BinaryOperator.Divide + ? Math.ScaleB(1, Math.ILogB(Math.Abs(factor))) == Math.Abs(factor) : factor == 0); + return new(variable.InputId, scale, offset, exactScaling); + default: + throw Unsupported(); + } + } + + int Child(int parent, string key) => ChildSlot(ReadField(walk, parent, key, WideBlockWalker.CaptureKind.PointerClass), walk); + + // This range keeps affine evaluations on 32-bit integer inputs exact in the binary mantissa. + static bool ExactBinaryCoefficient(double value) + { + double scaled = Math.ScaleB(value, 12); + return Math.Abs(value) <= 256 && scaled == Math.Truncate(scaled); + } + } + + private static Value ReadNumber(WideBlockWalker.Walk walk, int slot) + { + double number = ReadField(walk, slot, "NumberConstantExpression.m_value", WideBlockWalker.CaptureKind.Real).Real; + if (!double.IsFinite(number) || + ParameterMeasurement.Spec(walk, slot, "NumberConstantExpression", includeAdditional: true) is not { } unit) + throw Unsupported(); + return new(number, unit); + } + + private static WideBlockWalker.Capture ReadField(WideBlockWalker.Walk walk, int slot, string key, + WideBlockWalker.CaptureKind kind) => walk.Captures.Where(c => c.QueueIndex == slot && c.Key == key).ToArray() + is [var field] && field.Kind == kind ? field : throw Unsupported(); + + internal static int ChildSlot(WideBlockWalker.Capture pointer, WideBlockWalker.Walk walk) + { + int child = pointer.QueuePosition; + if (pointer.Kind != WideBlockWalker.CaptureKind.PointerClass || child < 0 || child <= pointer.QueueIndex || + child >= walk.Queue.Count || pointer.Integer <= 0 || walk.Queue[child] != pointer.Integer) + throw Unsupported(); + return child; + } + + private static bool AsBoolean(Value value) => value.Kind == ValueKind.Boolean ? value.Number != 0 : throw Unsupported(); + + private static Value? CalculateFunction(Function function, Value argument) + { + double number = argument.Number; + Value? result = (function, argument.Unit) switch + { + (Function.Abs, _) => argument with { Number = Math.Abs(number) }, + (Function.Sqrt, UnitType.UT_Number) when number >= 0 => new(Math.Sqrt(number)), + (Function.Sqrt, UnitType.UT_Area) when number >= 0 => new(Math.Sqrt(number), UnitType.UT_Length), + (Function.Exp, UnitType.UT_Number) => ExponentialResult(Math.Exp(number), UnitType.UT_Number), + (Function.Log, UnitType.UT_Number) when number >= ComparisonTolerance => new(Math.Log10(number)), + (Function.Ln, UnitType.UT_Number) when number >= ComparisonTolerance => new(Math.Log(number)), + (Function.Sin, UnitType.UT_Angle) => new(Math.Sin(number)), + (Function.Cos, UnitType.UT_Angle) => new(Math.Cos(number)), + (Function.Tan, UnitType.UT_Angle) when Math.Abs(Math.Cos(number)) > ComparisonTolerance => new(Math.Tan(number)), + (Function.Asin, UnitType.UT_Number) when Math.Abs(number) <= 1 => new(Math.Asin(number), UnitType.UT_Angle), + (Function.Acos, UnitType.UT_Number) when Math.Abs(number) <= 1 => new(Math.Acos(number), UnitType.UT_Angle), + (Function.Atan, UnitType.UT_Number) => new(Math.Atan(number), UnitType.UT_Angle), + (Function.Round, UnitType.UT_Number) => new(Round(number)), + (Function.RoundUp, UnitType.UT_Number) => new(RoundDirected(number, up: true)), + (Function.RoundDown, UnitType.UT_Number) => new(RoundDirected(number, up: false)), + (Function.Sqrt, UnitType.UT_Number or UnitType.UT_Area) or + (Function.Log or Function.Ln or Function.Asin or Function.Acos, UnitType.UT_Number) or + (Function.Tan, UnitType.UT_Angle) => null, + _ => throw Unsupported(), + }; + return result is { } calculated ? Finite(calculated) : null; + } + + internal static double Round(double value) + { + double floor = Math.Floor(value); + if (value == floor) + return value; + VerifyStableChange(value, floor + 0.5); + return Math.Floor(value + 0.5); + } + + private static double RoundDirected(double value, bool up) + { + VerifyStableChange(value, Math.Round(value)); + return up ? Math.Ceiling(value) : Math.Floor(value); + } + + private static Value? Calculate(BinaryOperator operation, Value left, Value right) + { + if (left.Kind != ValueKind.Number || right.Kind != ValueKind.Number) + throw Unsupported(); + if (operation is BinaryOperator.Equal or BinaryOperator.Greater or BinaryOperator.Less) + { + if (left.Unit != right.Unit) + throw Unsupported(); + if (left.Number != right.Number) + VerifyStableChange(left.Number, right.Number); + return Value.Boolean(operation switch + { + BinaryOperator.Equal => left.Number == right.Number, + BinaryOperator.Greater => left.Number > right.Number, + _ => left.Number < right.Number, + }); + } + + UnitType? unit = operation switch + { + BinaryOperator.Add or BinaryOperator.Subtract when left.Unit == right.Unit => left.Unit, + BinaryOperator.Multiply when left.Unit == UnitType.UT_Number => right.Unit, + BinaryOperator.Multiply or BinaryOperator.Divide when right.Unit == UnitType.UT_Number => left.Unit, + BinaryOperator.Divide when left.Unit == right.Unit => UnitType.UT_Number, + BinaryOperator.Multiply => LinearUnit(Power(left.Unit) + Power(right.Unit)), + BinaryOperator.Divide => LinearUnit(Power(left.Unit) - Power(right.Unit)), + BinaryOperator.RaiseToPower when right.Unit == UnitType.UT_Number => (left.Unit, right.Number) switch + { + (UnitType.UT_Number, _) => UnitType.UT_Number, + (UnitType.UT_Length, 2) => UnitType.UT_Area, + (UnitType.UT_Length, 3) => UnitType.UT_Volume, + (UnitType.UT_Area, 0.5) => UnitType.UT_Length, + _ => null, + }, + _ => null, + }; + if (unit is null) + throw Unsupported(); + + if (operation == BinaryOperator.Divide && Math.Abs(right.Number) <= ComparisonTolerance) + return null; + if (operation == BinaryOperator.RaiseToPower) + return RaiseToPower(left.Number, right.Number, unit.Value); + return Finite(new(CalculateNumber(operation, left.Number, right.Number), unit.Value)); + } + + private static Value Finite(Value value) + { + if (!double.IsFinite(value.Number)) + throw new RvtWriteRefusedException("invalid-parameter-value", "The global assignment does not produce finite formula values."); + return value; + } + + internal static void VerifyStableChange(double before, double after) + { + if (BitConverter.DoubleToInt64Bits(before) == BitConverter.DoubleToInt64Bits(after)) + return; + + // Revit can suppress changes within its relative comparison tolerance, even after recomputing the expression. + double magnitude = Math.Abs(before) + Math.Abs(after); + if (!double.IsFinite(magnitude) || magnitude <= ComparisonTolerance || + Math.Abs(after - before) <= Math.BitIncrement(magnitude * ComparisonTolerance)) + throw ParameterWriter.Unverified("The numeric change cannot be verified against Revit's comparison tolerance."); + } + + internal static bool IsWithinVerifiedRelativeTolerance(double before, double after) + { + double magnitude = Math.Abs(before) + Math.Abs(after); + // Leave the values at the floating-point cutoff to the normal stability check. + return double.IsFinite(magnitude) && magnitude > ComparisonTolerance && + Math.Abs(after - before) < Math.BitDecrement(magnitude * ComparisonTolerance); + } + + private static int? Power(UnitType unit) => unit switch + { + UnitType.UT_Length => 1, + UnitType.UT_Area => 2, + UnitType.UT_Volume => 3, + _ => null, + }; + + private static UnitType? LinearUnit(int? power) => power switch + { + 1 => UnitType.UT_Length, + 2 => UnitType.UT_Area, + 3 => UnitType.UT_Volume, + _ => null, + }; + + private static double CalculateNumber(BinaryOperator operation, double left, double right) => operation switch + { + BinaryOperator.Add => left + right, + BinaryOperator.Subtract => left - right, + BinaryOperator.Multiply => left * right, + BinaryOperator.Divide => left / right, + _ => throw Unsupported(), + }; + + private static Value? RaiseToPower(double number, double exponent, UnitType unit) + { + if (number == 0 && exponent > 0) + return new(0, unit); + if (Math.Abs(number) <= ComparisonTolerance) + throw Unsupported(); + + double value = Math.Pow(number, exponent); + if (double.IsNaN(value)) + throw Unsupported(); + return value == 0 ? null : ExponentialResult(value, unit); + } + + private static Value? ExponentialResult(double value, UnitType unit) + => Math.Abs(value) <= MaximumExponentialResult ? new(value, unit) : null; + + private static RvtWriteRefusedException Unsupported() => + ParameterWriter.Unverified("A dependent formula has an expression or units outside the verified write scope."); +} diff --git a/src/RvtIO/Writing/ParameterMeasurement.cs b/src/RvtIO/Writing/ParameterMeasurement.cs new file mode 100644 index 00000000..832870fa --- /dev/null +++ b/src/RvtIO/Writing/ParameterMeasurement.cs @@ -0,0 +1,165 @@ +using System.Globalization; +using RvtIO.BuiltIns; +using RvtIO.Parsing; + +namespace RvtIO.Writing; + +internal static class ParameterMeasurement +{ + private const double MetresPerFoot = 0.3048; + private const string SpecPrefix = "autodesk.spec.aec:"; + private const string UnitPrefix = "autodesk.unit.unit:"; + internal const string LegacyFormats = WideBlockWalker.AllItemsKeyPrefix + "legacy-unit-options"; + private sealed record Unit(UnitType Spec, string Input, string Forge, DisplayUnitType? Legacy, string Atom, double ToInternal); + private sealed record MeasurableSpec(UnitType Unit, string Forge, string Atom); + + private static readonly MeasurableSpec[] AdditionalSpecs = + [ + new(UnitType.UT_Mass, "autodesk.spec.aec.structural:mass", "Mass"), + new(UnitType.UT_Force, "autodesk.spec.aec.structural:force", "Force"), + new(UnitType.UT_MassDensity, SpecPrefix + "massDensity", "Mass Density"), + new(UnitType.UT_Speed, SpecPrefix + "speed", "Speed"), + new(UnitType.UT_Slope, SpecPrefix + "slope", "Slope"), + new(UnitType.UT_TimeInterval, SpecPrefix + "time", "Time"), + ]; + + private static readonly Unit[] Units = + [ + new(UnitType.UT_Length, "mm", "millimeters", DisplayUnitType.DUT_MILLIMETERS, "mm", 0.001 / MetresPerFoot), + new(UnitType.UT_Length, "cm", "centimeters", DisplayUnitType.DUT_CENTIMETERS, "cm", 0.01 / MetresPerFoot), + new(UnitType.UT_Length, "m", "meters", DisplayUnitType.DUT_METERS, "m", 1 / MetresPerFoot), + new(UnitType.UT_Length, "ft", "feet", DisplayUnitType.DUT_DECIMAL_FEET, "ft", 1), + new(UnitType.UT_Length, "in", "inches", DisplayUnitType.DUT_DECIMAL_INCHES, "in", 1.0 / 12), + new(UnitType.UT_Area, "m2", "squareMeters", DisplayUnitType.DUT_SQUARE_METERS, "m²", 1 / (MetresPerFoot * MetresPerFoot)), + new(UnitType.UT_Area, "ft2", "squareFeet", DisplayUnitType.DUT_SQUARE_FEET, "ft²", 1), + new(UnitType.UT_Volume, "m3", "cubicMeters", DisplayUnitType.DUT_CUBIC_METERS, "m³", 1 / (MetresPerFoot * MetresPerFoot * MetresPerFoot)), + new(UnitType.UT_Volume, "ft3", "cubicFeet", DisplayUnitType.DUT_CUBIC_FEET, "ft³", 1), + new(UnitType.UT_Angle, "deg", "degrees", DisplayUnitType.DUT_DECIMAL_DEGREES, "°", Math.PI / 180), + new(UnitType.UT_Angle, "rad", "radians", null, "rad", 1), + new(UnitType.UT_Currency, "", "currency", DisplayUnitType.DUT_CURRENCY, "$", 1), + new(UnitType.UT_Mass, "kg", "kilograms", DisplayUnitType.DUT_KILOGRAMS_MASS, "kg", 1), + new(UnitType.UT_Force, "kN", "kilonewtons", DisplayUnitType.DUT_KILONEWTONS, "kN", 1000 / MetresPerFoot), + new(UnitType.UT_MassDensity, "kg/m3", "kilogramsPerCubicMeter", DisplayUnitType.DUT_KILOGRAMS_PER_CUBIC_METER, + "kg/m³", MetresPerFoot * MetresPerFoot * MetresPerFoot), + new(UnitType.UT_Speed, "m/s", "metersPerSecond", DisplayUnitType.DUT_METERS_PER_SECOND, "m/s", 1 / MetresPerFoot), + new(UnitType.UT_Slope, "%", "percentage", DisplayUnitType.DUT_PERCENTAGE, "%", 0.01), + new(UnitType.UT_TimeInterval, "s", "seconds", DisplayUnitType.DUT_SECONDS, "s", 1), + ]; + + internal static bool IsAdditionalSpec(UnitType? unit) => unit is { } value && AdditionalSpecs.Any(spec => spec.Unit == value); + + internal static UnitType? Spec(WideBlockWalker.Walk definition, int slot, string declaringClass = "ParamDefValue", + bool includeCurrency = false, bool includeAdditional = false) + { + var fields = definition.Captures.Where(c => c.QueueIndex == slot && c.DeclaringClass == declaringClass + && c.Field is "m_unitType" or "m_specTypeId").ToArray(); + return fields switch + { + [{ Field: "m_unitType", Kind: WideBlockWalker.CaptureKind.Integer, Integer: >= 0 and <= 4 and long legacy }] => (UnitType)legacy, + [{ Field: "m_unitType", Kind: WideBlockWalker.CaptureKind.Integer, Integer: (int)UnitType.UT_Currency }] when includeCurrency + => UnitType.UT_Currency, + [{ Field: "m_unitType", Kind: WideBlockWalker.CaptureKind.Integer, Integer: >= 0 and <= int.MaxValue and long legacy }] + when includeAdditional && IsAdditionalSpec((UnitType)legacy) => (UnitType)legacy, + [{ Field: "m_specTypeId", Text: string forge }] => UnitSchemaEvaluator.DisplayNameKey(forge) switch + { + SpecPrefix + "length" => UnitType.UT_Length, + SpecPrefix + "area" => UnitType.UT_Area, + SpecPrefix + "volume" => UnitType.UT_Volume, + SpecPrefix + "angle" => UnitType.UT_Angle, + SpecPrefix + "number" => UnitType.UT_Number, + "autodesk.spec.measurable:currency" when includeCurrency => UnitType.UT_Currency, + string name when includeAdditional => AdditionalSpecs.SingleOrDefault(spec => spec.Forge == name)?.Unit, + _ => null, + }, + _ => null, + }; + } + + internal static double? Parse(UnitType spec, string input) + { + var text = input.AsSpan().Trim(); + if (spec is UnitType.UT_Number or UnitType.UT_Currency) + return ReadNumber(text); + int separator = text.LastIndexOfAny(' ', '\t'); + if (separator < 0 || ReadNumber(text[..separator]) is not double number) + return null; + string suffix = text[(separator + 1)..].ToString().Replace('²', '2').Replace('³', '3').Replace("°", "deg", StringComparison.Ordinal); + var unit = Units.SingleOrDefault(unit => unit.Spec == spec && unit.Input == suffix); + if (unit is null) + return null; + double value = number * unit.ToInternal; + return double.IsFinite(value) ? value : null; + } + + private static double? ReadNumber(ReadOnlySpan text) => + double.TryParse(text, NumberStyles.Float, CultureInfo.InvariantCulture, out double value) && double.IsFinite(value) ? value : null; + + internal readonly record struct DisplayValue(string Type, string Unit, string Symbol, double Before, string After) + { + internal bool Matches(string text) => text.EndsWith(Symbol, StringComparison.Ordinal) + && ReadNumber(text.AsSpan(0, text.Length - Symbol.Length)) == Before; + } + + internal static DisplayValue? Display(UnitType spec, WideBlockWalker walker, WideBlockWalker.Walk units, double before, double after) + { + var records = units.Records.Select(r => (Class: walker.Class(r.ClassId)!.Name, r.Values)).ToArray(); + if (records.Where(r => r.Class == "AUnits").ToArray() is not [var aUnits] + || aUnits.Values.GetValueOrDefault("m_decimalSymbol") is not 0L) + return null; + Unit? unit; + double accuracy; + string symbol; + var additional = AdditionalSpecs.SingleOrDefault(entry => entry.Unit == spec); + if (WideDocument.UnitOptions(records) is { } modern) + { + string specName = additional?.Forge ?? (spec == UnitType.UT_Currency ? "autodesk.spec.measurable:currency" + : SpecPrefix + spec.ToString()[3..].ToLowerInvariant()); + if (modern.Options.Where(o => UnitSchemaEvaluator.DisplayNameKey(o.Spec) == specName).ToArray() is not [var option] + || option.UseDefault != 0 || option.RoundingMethod != 0 || option.UseGrouping != 0 || option.UsePlusPrefix != 0) + return null; + if ((spec == UnitType.UT_Currency || additional is not null) && + (option.SuppressLeadingZeros != 0 || option.SuppressTrailingZeros != 0)) + return null; + unit = Units.SingleOrDefault(u => u.Spec == spec && UnitPrefix + u.Forge == UnitSchemaEvaluator.DisplayNameKey(option.Unit)); + accuracy = option.Accuracy; + symbol = UnitSchemaEvaluator.DisplayNameKey(option.Symbol); + } + else + { + if (records.Any(r => r.Class == "ForgeTypeId") + || units.Captures.Where(c => c.Key == LegacyFormats + "@" + ((int)spec).ToString(CultureInfo.InvariantCulture)).ToArray() + is not [{ Kind: WideBlockWalker.CaptureKind.PointerClass, Integer: > 0 and long tag, QueuePosition: >= 0 } pointer] + || units.Records.Where(r => r.QueueIndex == pointer.QueuePosition && r.ClassId == tag && walker.Class(r.ClassId)?.Name == "FormatOptions") + .ToArray() is not [{ Values: var option }]) + return null; + if (option.GetValueOrDefault("m_accuracy") is not double precision || option.GetValueOrDefault("m_displayUnits") is not long display + || option.GetValueOrDefault("m_unitSymbol") is not long legacySymbol + || new[] { "m_bUseDefault", "m_roundingMethod", "m_bUseGrouping", "m_bUsePlusPrefix" }.Any(f => option.GetValueOrDefault(f) is not 0L)) + return null; + if ((spec == UnitType.UT_Currency || additional is not null) && new[] { "m_bSuppressLeadingZeros", "m_bSuppressTrailingZeros" } + .Any(f => option.GetValueOrDefault(f) is not 0L)) + return null; + unit = Units.SingleOrDefault(u => u.Spec == spec && u.Legacy == (DisplayUnitType)display); + accuracy = precision; + symbol = legacySymbol switch { 0 => "", (int)UnitSymbolType.UST_DEGREE_SYMBOL => "autodesk.unit.symbol:degree", _ => "unsupported" }; + } + if (unit is null || (symbol != "" && (unit.Input != "deg" || symbol != "autodesk.unit.symbol:degree"))) + return null; + if (spec == UnitType.UT_Currency && accuracy != 0.01) + return null; + int digits = 0; + while (digits <= 8 && accuracy != Math.Pow(10, -digits)) + digits++; + if (digits > 8) + return null; + string suffix = symbol == "" ? "" : "°"; + double Round(double number) => Math.Round(number / unit.ToInternal, digits, MidpointRounding.AwayFromZero); + double oldValue = Round(before), newValue = Round(after); + if (!double.IsFinite(oldValue) || !double.IsFinite(newValue)) + return null; + if (spec == UnitType.UT_Currency && newValue == 0) + newValue = 0; // Revit writes 0.00 for amounts rounded to zero on either side. + return new(additional?.Atom ?? spec.ToString()[3..], unit.Atom, suffix, oldValue, + newValue.ToString($"F{digits}", CultureInfo.InvariantCulture) + suffix); + } +} diff --git a/src/RvtIO/Writing/ParameterWriter.cs b/src/RvtIO/Writing/ParameterWriter.cs new file mode 100644 index 00000000..ceec4c9d --- /dev/null +++ b/src/RvtIO/Writing/ParameterWriter.cs @@ -0,0 +1,698 @@ +using System.Buffers.Binary; +using System.Globalization; +using System.IO.Compression; +using System.Text; +using System.Xml; +using System.Xml.Linq; +using OpenMcdf; +using RvtIO.BuiltIns; +using RvtIO.Model; +using RvtIO.Parsing; + +namespace RvtIO.Writing; + +internal static class ParameterWriter +{ + internal sealed record Edit(long ElementId, long ParameterId, string? Value) + { + internal BuiltInParameter Parameter => (BuiltInParameter)ParameterId; + internal bool UserDefined => ParameterId > 0; + } + internal sealed record PlanResult(IReadOnlyList Records, (string Path, byte[] Bytes)? Metadata); + + internal sealed class Pending + { + internal readonly Dictionary<(int Partition, int Block, int Channel, ulong Owner), RvtPartitionRecordEdit> Records = new(); + internal readonly Dictionary Metadata = new(StringComparer.OrdinalIgnoreCase); + internal GlobalParameterWriter.ProjectDependencies? GlobalParameterDependencies; + + internal void Apply(PlanResult? plan) + { + if (plan is null) + return; + foreach (var edit in plan.Records) + Records[(edit.PartitionNumber, edit.Block, edit.Channel, edit.OwnerId)] = edit; + if (plan.Metadata is { } metadata) + Metadata[metadata.Path] = metadata.Bytes; + } + + internal Stream? OpenMetadata(RootStorage root, string path) => + Metadata.TryGetValue(path, out byte[]? bytes) ? new MemoryStream(bytes, writable: false) + : root.TryOpenStream(path, out var source) ? source : null; + } + + // These ProjectInfo fields are writable in Revit and have a second representation in the ProjectInformation stream. + private static readonly Dictionary Fields = new() + { + [BuiltInParameter.CLIENT_NAME] = "Client_Name", + [BuiltInParameter.PROJECT_ADDRESS] = "Project_Address", + [BuiltInParameter.PROJECT_ISSUE_DATE] = "Project_Issue_Date", + [BuiltInParameter.PROJECT_NAME] = "Project_Name", + [BuiltInParameter.PROJECT_NUMBER] = "Project_Number", + [BuiltInParameter.PROJECT_STATUS] = "Project_Status", + }; + + private static bool IsTypeIdentity(BuiltInParameter parameter) => parameter is BuiltInParameter.ALL_MODEL_TYPE_MARK + or BuiltInParameter.ALL_MODEL_TYPE_COMMENTS or BuiltInParameter.ALL_MODEL_DESCRIPTION + or BuiltInParameter.ALL_MODEL_MANUFACTURER or BuiltInParameter.ALL_MODEL_MODEL + or BuiltInParameter.ALL_MODEL_URL or BuiltInParameter.FIRE_RATING or BuiltInParameter.ALL_MODEL_COST; + + private static bool IsImage(BuiltInParameter parameter) => parameter is BuiltInParameter.ALL_MODEL_IMAGE + or BuiltInParameter.ALL_MODEL_TYPE_IMAGE; + + internal static bool IsSupportedBuiltInGlobalProperty(long id) => id is + (int)BuiltInParameter.ALL_MODEL_INSTANCE_COMMENTS or (int)BuiltInParameter.ALL_MODEL_TYPE_COMMENTS + or (int)BuiltInParameter.ALL_MODEL_DESCRIPTION or (int)BuiltInParameter.ALL_MODEL_MANUFACTURER + or (int)BuiltInParameter.ALL_MODEL_MODEL or (int)BuiltInParameter.ALL_MODEL_COST + or (int)BuiltInParameter.FIRE_RATING; + + internal static void Validate(long parameterId, string? value) + { + if (parameterId < int.MinValue) + throw new RvtWriteRefusedException("unsupported-parameter", $"Writing parameter {parameterId} has not been verified."); + var parameter = (BuiltInParameter)parameterId; + if (parameterId == (int)BuiltInParameter.HOST_AREA_COMPUTED) + throw new RvtWriteRefusedException("read-only-parameter", "Revit computes HOST_AREA_COMPUTED and exposes it as read-only."); + if (parameterId <= 0 && parameter is not (BuiltInParameter.ALL_MODEL_INSTANCE_COMMENTS or BuiltInParameter.ALL_MODEL_MARK) + && !IsTypeIdentity(parameter) && !IsImage(parameter) + && !Fields.ContainsKey(parameter)) + throw new RvtWriteRefusedException("unsupported-parameter", $"Writing {parameter} has not been verified."); + if (value is null) + { + if (parameterId <= 0) + throw new RvtWriteRefusedException("unsupported-parameter-clear", "Revit ClearValue requires a shared parameter with HideWhenNoValue."); + return; + } + ValidateText(value); + } + + internal static void ValidateText(string value) + { + try { XmlConvert.VerifyXmlChars(value); } + catch (XmlException ex) + { + throw new RvtWriteRefusedException("invalid-parameter-value", "The text contains a character that the supported parameter values cannot represent.", ex); + } + } + + internal static PlanResult? Plan(RootStorage root, PartitionFraming.Tags tags, int idWidth, Edit edit, Pending pending, + GlobalParameterWriter.PropertyValue? driven = null) + { + if (driven is not null && (edit.ElementId == edit.ParameterId + || (!edit.UserDefined && !IsSupportedBuiltInGlobalProperty(edit.ParameterId)))) + throw Unverified("The global parameter does not control a verified project property."); + bool clearing = edit.Value is null && driven is null; + bool comments = !edit.UserDefined && edit.Parameter == BuiltInParameter.ALL_MODEL_INSTANCE_COMMENTS; + bool mark = !edit.UserDefined && edit.Parameter is BuiltInParameter.ALL_MODEL_MARK or BuiltInParameter.ALL_MODEL_TYPE_MARK; + bool typeIdentity = !edit.UserDefined && IsTypeIdentity(edit.Parameter); + bool image = !edit.UserDefined && IsImage(edit.Parameter); + bool projectInfo = !edit.UserDefined && !comments && !mark && !typeIdentity && !image; + bool possibleGlobalEdit = edit.UserDefined && edit.ElementId == edit.ParameterId; + if (TfSchemaReader.Read(root) is not { } schema) + throw Unverified("The source schema could not be read exactly."); + + var formats = new FormatsSchema(schema); + if (ElemTableLayout.IdWidth(formats) != idWidth || PagedGzipStream.Read(root, "Global", "ElemTable") is not { } table + || ElemTableLayout.TryParse(table, formats) is not { } elements) + throw Unverified("Global/ElemTable could not be read exactly."); + var elementIds = elements.Select(row => row.Id).ToHashSet(); + if (!elementIds.Contains(edit.ElementId)) + throw new RvtWriteRefusedException("missing-element", $"Element {edit.ElementId} was not found in the element table."); + if (edit.UserDefined && !elementIds.Contains(edit.ParameterId)) + throw new RvtWriteRefusedException("missing-parameter-definition", $"Parameter definition {edit.ParameterId} was not found in the element table."); + + var walker = new WideBlockWalker(schema, (c, f) => (c.Name, f.Name) switch + { + ("Element", "m_id" or "m_pParamValueSetAString") => f.Name, + ("FamilySymbol", "m_active") when edit.UserDefined => "FamilySymbol.m_active", + ("ElementHeader", "m_categroryId" or "m_designOptionId") => f.Name, + ("ParamValueDouble" or "ParamValueInt" or "ParamValueAString" or "ParamValueElementId", "m_paramId") => f.Name, + ("ParamValueAString", "m_value") => f.Name, + ("Element", "m_pParamValueSetDouble") or ("ParamValueDouble", "m_value") + when edit.ParameterId == (int)BuiltInParameter.ALL_MODEL_COST => f.Name, + _ => (edit.UserDefined || image ? UserParameterWriter.CaptureKey(c, f) : null) + ?? (image ? ImportedImageReference.CaptureKey(c, f) ?? LinkedImageReference.CaptureKey(c, f) : null) + ?? (!projectInfo ? LoadedFamilyParameterWriter.CaptureKey(c, f) : null) + ?? (edit.UserDefined ? ParameterFormulaEvaluator.CaptureKey(c, f) : null) + ?? GlobalParameterWriter.CaptureKey(c, f), + }, edit.UserDefined ? ["ForgeTypeId"] : []); + var bindings = new Dictionary(); + long imageId = image ? ImportedImageReference.ReadId(edit.Value!) : -1; + var imageRecords = imageId > 0 ? new Dictionary() : null; + var seenImageRecords = imageRecords is not null ? new HashSet() : null; + bool imageTargetsLevel = false; + long? referenceId = edit.UserDefined ? UserParameterWriter.ReferenceId(edit.Value) : imageId > 0 ? imageId : null; + byte[]? reference = null; + bool sawReference = false; + bool sawReferenceHeader = false; + bool mainModelReference = false; + ulong terminator = idWidth == 8 ? ulong.MaxValue : uint.MaxValue; + byte[]? definition = null; + byte[]? body = null; + int? category = null; + bool sawHeader = false; + int partition = -1; + var globals = new HashSet(); + ScanPartitions(root, tags, idWidth, (number, record) => + { + if (record.Block != 0 || record.Owner == terminator) + return; + if (!projectInfo && record.Channel == 101) + { + if (referenceId is long targetId && record.Owner == (ulong)targetId) + { + mainModelReference = !sawReferenceHeader && ReadMainModelHeader(record) is not null; + sawReferenceHeader = true; + } + if (record.Owner != (ulong)edit.ElementId) + return; + if (sawHeader) + { + if (edit.UserDefined) + throw Unverified($"Element {edit.ElementId} has more than one project header."); + category = null; + return; + } + sawHeader = true; + if (ReadMainModelHeader(record) is { } fields + && UserParameterWriter.Integer(fields, "m_categroryId") is >= int.MinValue and <= int.MaxValue and long id) + category = (int)id; + } + if (record.Channel != 102) + return; + if (!projectInfo && record.Body.Length >= 2 + && walker.Class(BinaryPrimitives.ReadUInt16LittleEndian(record.Body.Span))?.Name == "ParamElemGlobal" + && (!elementIds.Contains((long)record.Owner) || !globals.Add((long)record.Owner))) + throw Unverified("A global parameter does not have a unique project record."); + if (imageRecords is not null && elementIds.Contains((long)record.Owner)) + { + long id = (long)record.Owner; + int tag = record.Body.Length >= 2 ? BinaryPrimitives.ReadUInt16LittleEndian(record.Body.Span) : -1; + string? name = walker.Class(tag)?.Name; + if (!seenImageRecords!.Add(id)) + imageRecords[id] = null; + else if (name == "ImageHolder" || id == imageId && (name is "ImageSymbol" or "Level")) + { + imageRecords.Add(id, walker.Run(record.Body.ToArray(), 0, record.Body.Length, tag)); + imageTargetsLevel |= name == "Level"; + } + } + if (edit.UserDefined) + { + if (referenceId is long target && record.Owner == (ulong)target && elementIds.Contains(target)) + { + string? referenceClass = record.Body.Length >= 2 + ? walker.Class(BinaryPrimitives.ReadUInt16LittleEndian(record.Body.Span))?.Name : null; + reference = !sawReference && (referenceClass is "MaterialElem" or "NestedFamSymRefElem" or "FamilySymbol" + || IsProjectElementReferenceClass(referenceClass)) + ? record.Body.ToArray() : null; + sawReference = true; + } + if (record.Owner == (ulong)edit.ParameterId) + { + if (definition is not null) + throw Unverified($"Parameter definition {edit.ParameterId} has more than one project record."); + definition = record.Body.ToArray(); + } + if (record.Body.Length >= 2 && elementIds.Contains((long)record.Owner) + && walker.Class(BinaryPrimitives.ReadUInt16LittleEndian(record.Body.Span))?.Name == "ParamBinding" + && !bindings.TryAdd((long)record.Owner, record.Body.ToArray())) + bindings[(long)record.Owner] = null; + } + if (record.Owner != (ulong)edit.ElementId) + return; + if (body is not null) + throw Unverified($"Element {edit.ElementId} has more than one project record."); + body = record.Body.ToArray(); + partition = number; + }, pending); + + WideBlockWalker.Walk? ReadMainModelHeader(PartitionFraming.Record record) + { + int tag = record.Body.Length >= 2 ? BinaryPrimitives.ReadUInt16LittleEndian(record.Body.Span) : -1; + if (walker.Class(tag)?.Name != "ElementHeader") + return null; + var fields = walker.Run(record.Body.ToArray(), 0, record.Body.Length, tag, rootOnly: true); + return fields.RootRead && UserParameterWriter.Integer(fields, "m_designOptionId") == -1 ? fields : null; + } + + if (body is null) + throw Unverified($"No project record was found for element {edit.ElementId}."); + int classId = body.Length < 2 ? -1 : BinaryPrimitives.ReadUInt16LittleEndian(body); + string? ownerClass = walker.Class(classId)?.Name; + if (ownerClass == "ParamElemGlobal") + { + if (!possibleGlobalEdit) + throw new RvtWriteRefusedException("unsupported-parameter-owner", "Use the global parameter's element ID for both IDs."); + return GlobalParameterWriter.Plan(root, tags, idWidth, walker, elementIds, globals, edit, pending, partition, body, classId); + } + bool loadedFamily = ownerClass is "FamilyInstance" or "FamilySymbol"; + bool doorWindowFurniture = category is (int)BuiltInCategory.OST_Doors or (int)BuiltInCategory.OST_Windows or (int)BuiltInCategory.OST_Furniture; + bool loadedCategoryIdentity = typeIdentity && !mark && ownerClass == "FamilySymbol" + && doorWindowFurniture; + bool loadedCategoryInstance = (comments || image) && ownerClass == "FamilyInstance" && doorWindowFurniture; + if (!edit.UserDefined && !(edit.Parameter switch + { + BuiltInParameter.ALL_MODEL_MARK => ownerClass is "SWall" or "FamilyInstance", + BuiltInParameter.ALL_MODEL_TYPE_MARK => ownerClass is "BasicWallType" or "FamilySymbol", + BuiltInParameter.ALL_MODEL_INSTANCE_COMMENTS => ownerClass is "SWall" or "FamilyInstance", + BuiltInParameter.ALL_MODEL_IMAGE => ownerClass is "SWall" or "RoomElem" or "FamilyInstance", + BuiltInParameter.ALL_MODEL_TYPE_IMAGE => ownerClass == "BasicWallType", + BuiltInParameter.FIRE_RATING => ownerClass == "BasicWallType" + || (ownerClass == "FamilySymbol" && category == (int)BuiltInCategory.OST_Doors), + _ when typeIdentity => ownerClass is "BasicWallType" or "FamilySymbol", + _ => ownerClass == "ProjectInfo", + })) + throw new RvtWriteRefusedException("unsupported-parameter-owner", $"{edit.Parameter} cannot be written on this element class."); + if ((mark || typeIdentity || image) && (ownerClass is "SWall" or "BasicWallType") && category != (int)BuiltInCategory.OST_Walls) + throw Unverified("The wall's category or design option could not be verified for writing."); + if (image && ownerClass == "RoomElem" && category != (int)BuiltInCategory.OST_Rooms) + throw Unverified("The room's category or design option could not be verified for writing."); + if (!edit.UserDefined && !mark && loadedFamily && !loadedCategoryIdentity && !loadedCategoryInstance + && category != (int)BuiltInCategory.OST_GenericModel) + throw Unverified("The built-in parameter's availability and writability have not been verified for this family category."); + var walk = walker.Run(body, 0, body.Length, classId); + if (!walk.Exact || !walk.Captures.Any(c => c.AtRoot && c.DeclaringClass == "Element" && c.Field == "m_id" && c.Integer == edit.ElementId)) + throw Unverified("The element record could not be read exactly."); + if (driven is not null && !edit.UserDefined) + { + long? master = UserParameterWriter.Integer(walk, "FamilySymbol.m_masterId"); + bool supportedOwner = comments + ? SchemaRelease.FromSchema(formats) is >= 2022 && (ownerClass == "SWall" && category == (int)BuiltInCategory.OST_Walls + || ownerClass == "FamilyInstance" && category == (int)BuiltInCategory.OST_GenericModel) + : ownerClass == "FamilySymbol" && (master == -1 && doorWindowFurniture + || category == (int)BuiltInCategory.OST_GenericModel && master is -1 or > 0); + if (!supportedOwner) + throw Unverified("This built-in global association has not been verified for the element class, category, and release."); + } + if (!projectInfo) + { + if (walk.Queue.Any(tag => walker.IsA(tag, "GroupMembership"))) + throw Unverified("The element has a group membership that has not been verified for writing."); + GlobalParameterWriter.VerifyElementParameter(walker, walk, idWidth, elementIds, globals, edit.ParameterId, driven?.GlobalId); + } + + int targetTag = reference is null ? -1 : BinaryPrimitives.ReadUInt16LittleEndian(reference); + string? targetClass = walker.Class(targetTag)?.Name; + var target = reference is null ? null : walker.Run(reference, 0, reference.Length, targetTag); + long? material = target is not null && referenceId is long materialId + && UserParameterWriter.MaterialName(walker, target, materialId) is not null + ? materialId : null; + long? localElementReference = mainModelReference && IsProjectElementReferenceClass(targetClass) + && target is { Exact: true, EmptyEntityAt: < 0 } && UserParameterWriter.Integer(target, "m_id") == referenceId + && (targetClass != "Family" || UserParameterWriter.Integer(target, "FamilyBase.m_inPlace") == 0) + && (targetClass != "FamilyInstance" || UserParameterWriter.Integer(target, "FamilyInstance.m_superInstanceId") == -1) + ? referenceId : null; + bool hasProjectBinding = edit.UserDefined && UserParameterWriter.HasProjectBinding(walker, definition); + bool sharedProjectReference = false; + ProjectFamilyReference? projectReference = null; + if (ownerClass is ("FamilySymbol" or "FamilyInstance" or "SWall" or "BasicWallType" or "RoomElem") + && targetClass == "FamilySymbol" + && UserParameterWriter.IsFamilyTypeDefinition(walker, definition)) + { + string? definitionClass = walker.Class(BinaryPrimitives.ReadUInt16LittleEndian(definition!))?.Name; + sharedProjectReference = driven is null && hasProjectBinding && definitionClass == "ParamElemExternal"; + if (sharedProjectReference) + _ = UserParameterWriter.ReadBoundDefinition(walker, ownerClass, category, definition, bindings, edit, clearing: false); + else + _ = UserParameterWriter.ReadDefinition(walker, definition!, edit); + if (target is not { Exact: true, EmptyEntityAt: < 0 } || referenceId is not long id + || UserParameterWriter.Integer(target, "m_id") != id + || UserParameterWriter.Integer(target, "FamilySymbol.m_masterId") != -1 + || UserParameterWriter.Integer(target, "FamilySymbol.m_ownerInstanceId") != -1 + || UserParameterWriter.Integer(target, "FamilySymbol.m_familyId") is not (> 0 and long familyId)) + throw Unverified("The reference does not identify a primary project family type."); + if (UserParameterWriter.Integer(target, "FamilySymbol.m_active") != 1) + throw Unverified("Assigning this reference requires activating and regenerating the target family type."); + long? referringType = driven is null && ownerClass == "FamilySymbol" + && definitionClass == "ParamElemFamily" + && UserParameterWriter.Integer(walk, "FamilySymbol.m_masterId") == -1 + && UserParameterWriter.Integer(walk, "FamilySymbol.m_ownerInstanceId") == -1 + && UserParameterWriter.Integer(walk, "FamilySymbol.m_active") == 1 ? edit.ElementId : null; + projectReference = ProjectFamilyReference.Read(root, tags, idWidth, schema, elementIds, id, familyId, pending, + referringType, inspectDependencies: !sharedProjectReference); + } + bool projectBoundAssignment = edit.UserDefined && loadedFamily && !clearing + && (ownerClass == "FamilySymbol" && UserParameterWriter.Integer(walk, "FamilySymbol.m_masterId") is > 0 + || hasProjectBinding); + if (edit.UserDefined && loadedFamily && !clearing && !projectBoundAssignment) + return LoadedFamilyParameterWriter.Plan(root, tags, idWidth, walker, elementIds, globals, category, definition, edit, material, + target, projectReference, partition, body, walk, pending, ownerClass == "FamilyInstance", driven); + + if (imageRecords is not null && (!mainModelReference || !IsVerifiedImageTarget(imageRecords))) + throw new RvtWriteRefusedException("invalid-parameter-value", "The image ID does not identify a verified local image or level in this project."); + var (storage, replacement, quantity) = driven is { } property ? PrepareDriven(property) : edit.UserDefined + ? UserParameterWriter.Prepare(walker, ownerClass, category, definition, bindings, edit, idWidth, material, target, + projectReference, localElementReference) + : edit.Parameter switch + { + BuiltInParameter.ALL_MODEL_COST => (StorageType.Double, EncodeCost(edit.Value!), (UnitType?)null), + _ when image => (StorageType.ElementId, UserParameterWriter.EncodeElementId(imageId, idWidth), null), + _ => (StorageType.String, EncodeText(edit.Value!), null), + }; + bool genericNamedIdentity = typeIdentity && !mark && ownerClass == "FamilySymbol" && category == (int)BuiltInCategory.OST_GenericModel + && walk.Captures.Any(c => c.DeclaringClass == "NamedParam" && c.Field == "m_paramId" && c.Integer == edit.ParameterId); + bool checkTypeIdentity = loadedCategoryIdentity || genericNamedIdentity; + if (checkTypeIdentity && LoadedFamilyParameterWriter.TryPlanTypeIdentity(root, tags, idWidth, walker, elementIds, globals, category, + edit, walk, storage, replacement, pending, driven, out var identityPlan)) + return identityPlan; + if (loadedFamily && !checkTypeIdentity) + LoadedFamilyParameterWriter.VerifyLocalValueEdit(root, tags, idWidth, walker, elementIds, category, edit, walk, storage, + target, sharedProjectReference ? null : projectReference, pending, ownerClass == "FamilyInstance"); + var original = FindValue(walker, walk, edit, storage); + if (clearing) + { + if (walk.EmptyEntityAt >= 0) + throw Unverified("The parameter store could not be read exactly for clearing."); + if (original is not { } row) + return null; + byte[] cleared = RemoveValue(walk, body, idWidth, storage, row); + var clearedWalk = walker.Run(cleared, 0, cleared.Length, classId); + if (clearedWalk.EmptyEntityAt >= 0 || FindValue(walker, clearedWalk, edit, storage) is not null) + throw Unverified("The cleared parameter store could not be read back exactly."); + return new PlanResult([new RvtPartitionRecordEdit(partition, 102, (ulong)edit.ElementId, cleared)], null); + } + byte[]? xml = null; + byte[] updated; + if (original?.Value is { } stored) + { + if (projectInfo) + xml = EditProjectInformation(root, pending, Fields[edit.Parameter], stored.Text!, edit.Value!); + int length = storage == StorageType.String ? sizeof(uint) + sizeof(char) * stored.Text!.Length : replacement.Length; + if (driven is { } expected && !body.AsSpan(stored.ValueOffset, length).SequenceEqual(expected.Previous)) + throw Unverified("The controlled property disagrees with the saved global value."); + if (quantity == UnitType.UT_Currency || ParameterMeasurement.IsAdditionalSpec(quantity)) + ParameterFormulaEvaluator.VerifyStableChange(stored.Real, BinaryPrimitives.ReadDoubleLittleEndian(replacement)); + if (body.AsSpan(stored.ValueOffset, length).SequenceEqual(replacement)) + return null; + updated = ReplaceValue(body, stored.ValueOffset, length, replacement); + } + else + { + if (driven is not null) + throw Unverified("The controlled property has no verified saved value."); + if (walk.EmptyEntityAt >= 0 || projectInfo || (comments && ownerClass == "SWall" && category != (int)BuiltInCategory.OST_Walls)) + throw Unverified("The first value requires a verified main-model element and parameter store."); + if (storage == StorageType.String && edit.Value!.Length == 0 && edit.UserDefined && !projectBoundAssignment) + throw new RvtWriteRefusedException("invalid-parameter-value", "The first text value must be non-empty."); + updated = InsertValue(formats, walker, walk, body, idWidth, edit, storage, replacement); + } + + var verified = walker.Run(updated, 0, updated.Length, classId); + if (FindValue(walker, verified, edit, storage)?.Value is not { } readBack + || (original?.Value is { } previous && readBack.ValueOffset != previous.ValueOffset) + || readBack.ValueOffset > updated.Length - replacement.Length + || !updated.AsSpan(readBack.ValueOffset, replacement.Length).SequenceEqual(replacement)) + throw Unverified("The updated parameter could not be read back."); + return new PlanResult([new RvtPartitionRecordEdit(partition, 102, (ulong)edit.ElementId, updated)], + xml is null ? null : ("ProjectInformation", xml)); + + bool IsVerifiedImageTarget(IReadOnlyDictionary records) => imageTargetsLevel + ? records.GetValueOrDefault(imageId) is { Exact: true, EmptyEntityAt: < 0 } level + && UserParameterWriter.Integer(level, "m_id") == imageId + : ImportedImageReference.ReadName(walker, records, imageId) is not null + || LinkedImageReference.IsVerifiedTarget(walker, records, imageId); + + (StorageType Storage, byte[] Replacement, UnitType? Quantity) PrepareDriven(GlobalParameterWriter.PropertyValue value) + { + if (!edit.UserDefined) + { + var format = edit.Parameter == BuiltInParameter.ALL_MODEL_COST + ? new FormulaParameterStorage(StorageType.Double, UnitType.UT_Currency, ParameterFormulaEvaluator.ValueKind.Number) + : new FormulaParameterStorage(StorageType.String, UnitType.UT_Number, ParameterFormulaEvaluator.ValueKind.Text); + value.VerifyFormat(format); + return (format.Storage, value.Replacement, null); + } + var (definitionWalk, slot) = UserParameterWriter.ReadBoundDefinition(walker, ownerClass, category, definition, bindings, + edit, clearing: false); + string? definitionClass = walker.Class(BinaryPrimitives.ReadUInt16LittleEndian(definition))?.Name; + var target = FormulaParameterStorage.Read(walker, definitionWalk, slot, + includeCurrency: definitionClass == "ParamElemExternal"); + value.VerifyFormat(target); + return (target.Storage, value.Replacement, target.Unit); + } + } + + internal static byte[] ReplaceValue(byte[] body, int start, int length, ReadOnlySpan replacement) + { + byte[] updated = new byte[checked(body.Length - length + replacement.Length)]; + body.AsSpan(0, start).CopyTo(updated); + replacement.CopyTo(updated.AsSpan(start)); + body.AsSpan(start + length).CopyTo(updated.AsSpan(start + replacement.Length)); + return updated; + } + + private static bool IsProjectElementReferenceClass(string? name) => name is + "BasicWallType" or "CoverType" or "Level" or "Family" or "FamilyInstance"; + + internal static void ScanPartitions(RootStorage root, PartitionFraming.Tags tags, int idWidth, + Action visit, Pending pending) + { + var partitions = root.OpenStorage("Partitions"); + foreach (var entry in partitions.EnumerateEntries()) + { + if (entry.Type != EntryType.Stream || !int.TryParse(entry.Name, NumberStyles.None, CultureInfo.InvariantCulture, out int number)) + continue; + using var stream = partitions.OpenStream(entry.Name); + var raw = new byte[stream.Length]; + stream.ReadExactly(raw); + if (!PartitionFraming.Walk(raw, tags, idWidth, record => + { + if (pending.Records.TryGetValue((number, record.Block, record.Channel, record.Owner), out var edit)) + record = record with { Body = edit.Body }; + visit(number, record); + }, out string? failure, out _)) + throw Unverified($"Partition {entry.Name} could not be read exactly ({failure})."); + } + } + + internal static byte[] EncodeText(string value) + { + byte[] result = new byte[checked(sizeof(uint) + Encoding.Unicode.GetByteCount(value))]; + BinaryPrimitives.WriteInt32LittleEndian(result, value.Length); + Encoding.Unicode.GetBytes(value, result.AsSpan(sizeof(uint))); + return result; + } + + internal static byte[] EncodeCost(string value) + { + if (ParameterMeasurement.Parse(UnitType.UT_Number, value) is not double cost) + throw new RvtWriteRefusedException("invalid-parameter-value", "Currency and Cost require a finite invariant number."); + return EncodeDouble(cost); + } + + internal static byte[] EncodeDouble(double value) + { + var result = new byte[sizeof(double)]; + BinaryPrimitives.WriteDoubleLittleEndian(result, value); + return result; + } + + private static string ValueSuffix(StorageType storage) => storage switch + { + StorageType.String => "AString", + StorageType.Integer => "Int", + StorageType.ElementId => "ElementId", + _ => "Double", + }; + + private static string ValueClass(StorageType storage) => "ParamValue" + ValueSuffix(storage); + private static string StoreClass(StorageType storage) => "ParamValueSet" + ValueSuffix(storage); + + private static WideBlockWalker.Capture StorePointer(WideBlockWalker.Walk walk, StorageType storage) + { + string field = "m_p" + StoreClass(storage); + if (!walk.Exact || walk.Captures.Where(c => c.AtRoot && c.DeclaringClass == "Element" && c.Field == field + && c.Kind == WideBlockWalker.CaptureKind.PointerClass).ToArray() is not [var store]) + throw Unverified("The root parameter store could not be read exactly."); + return store; + } + + private static SchemaField[] StoreRow(WideBlockWalker walker, int tag, StorageType storage) + { + if (walker.Class(tag) is not { Base: 0 } store || store.Name != StoreClass(storage) + || store.Fields.Where(f => f.Stored).ToArray() is not [{ Name: "m_paramSet", Type: 14, Mods: 0x50, Ref: int rowTag }] + || walker.Class(rowTag) is not { Base: 0 } row || row.Name != ValueClass(storage)) + throw Unverified("The parameter store layout could not be verified."); + var fields = row.Fields.Where(f => f.Stored).ToArray(); + if (fields is not ([{ Name: "m_paramId" }, { Name: "m_value" }] + or [{ Name: "m_value" }, { Name: "m_paramId" }])) + throw Unverified("The parameter row layout could not be verified."); + return fields; + } + + internal static (WideBlockWalker.Capture Id, WideBlockWalker.Capture Value)? FindValue( + WideBlockWalker walker, WideBlockWalker.Walk walk, Edit edit, StorageType storage) + { + var store = StorePointer(walk, storage); + string valueClass = ValueClass(storage); + var matches = walk.Captures + .Select((capture, index) => (capture, index)) + .Where(p => p.capture.DeclaringClass.StartsWith("ParamValue", StringComparison.Ordinal) + && p.capture.Field == "m_paramId" && p.capture.Integer == edit.ParameterId) + .ToArray(); + if (matches.Length == 0) + return null; + if (matches is not [{ capture: { QueueIndex: >= 0 } id, index: var index }] + || id.DeclaringClass != valueClass + || id.QueueIndex != StoreSlot(walk, store)) + throw Unverified($"No unique stored value was found for parameter {edit.ParameterId}."); + var row = StoreRow(walker, (int)store.Integer, storage); + bool idFirst = row[0].Name == "m_paramId"; + if (storage == StorageType.ElementId && (!idFirst || !IsElementId(walker, row[1]))) + throw Unverified("The reference parameter's stored ID layout could not be verified."); + int valueIndex = index + (idFirst ? 1 : -1); + if ((uint)valueIndex >= walk.Captures.Count + || walk.Captures[valueIndex] is not { Field: "m_value", ValueOffset: >= 0 } value + || value.DeclaringClass != valueClass || value.QueueIndex != id.QueueIndex + || value.Kind != (storage == StorageType.String ? WideBlockWalker.CaptureKind.Text + : storage == StorageType.Double ? WideBlockWalker.CaptureKind.Real : WideBlockWalker.CaptureKind.Integer)) + throw Unverified($"The stored value for parameter {edit.ParameterId} does not match its definition."); + return (id, value); + } + + private static byte[] RemoveValue(WideBlockWalker.Walk walk, byte[] body, int idWidth, StorageType storage, + (WideBlockWalker.Capture Id, WideBlockWalker.Capture Value) row) + { + int valueLength = storage switch + { + StorageType.String => checked(sizeof(uint) + sizeof(char) * row.Value.Text!.Length), + StorageType.Integer => sizeof(int), + StorageType.Double => sizeof(double), + _ => idWidth, + }; + int slot = row.Id.QueueIndex; + int countAt = walk.QueueStart[slot]; + int storeEnd = slot + 1 == walk.Queue.Count ? body.Length : walk.QueueStart[slot + 1]; + int start = Math.Min(row.Id.ValueOffset, row.Value.ValueOffset); + int end = Math.Max(row.Id.ValueOffset + idWidth, row.Value.ValueOffset + valueLength); + int count = walk.Captures.Count(c => c.QueueIndex == slot && c.DeclaringClass == ValueClass(storage) && c.Field == "m_paramId"); + if (start < countAt + sizeof(uint) || end > storeEnd || end - start != idWidth + valueLength + || count == 0 || BinaryPrimitives.ReadUInt32LittleEndian(body.AsSpan(countAt)) != count) + throw Unverified("The parameter row could not be located exactly for clearing."); + byte[] updated = ReplaceValue(body, start, end - start, []); + BinaryPrimitives.WriteUInt32LittleEndian(updated.AsSpan(countAt), (uint)count - 1); + return updated; + } + + private static byte[] InsertValue(FormatsSchema schema, WideBlockWalker walker, WideBlockWalker.Walk walk, + byte[] body, int idWidth, Edit edit, StorageType storage, byte[] replacement) + { + var store = StorePointer(walk, storage); + if (schema.IdOf(StoreClass(storage)) is not int tag || store.Integer != tag && store.Integer != 0) + throw Unverified("The parameter store class could not be verified."); + var fields = StoreRow(walker, tag, storage); + bool idFirst = fields[0].Name == "m_paramId"; + var idField = fields[idFirst ? 0 : 1]; + var valueField = fields[idFirst ? 1 : 0]; + if (!(IsElementId(walker, idField) || idField is { Type: 4, Mods: 0 } && idWidth == 4) + || (storage switch + { + StorageType.String => !idFirst || valueField is not { Type: 8, Mods: 0 or 0x60 }, + StorageType.Integer => !idFirst || valueField is not { Type: 4, Mods: 0 }, + StorageType.ElementId => !idFirst || !IsElementId(walker, valueField), + _ => valueField is not { Type: 7, Mods: 0 }, + })) + throw Unverified("The parameter row encoding could not be verified."); + + byte[] row = new byte[checked(idWidth + replacement.Length)]; + var idBytes = row.AsSpan(idFirst ? 0 : replacement.Length, idWidth); + if (idWidth == 8) + BinaryPrimitives.WriteInt64LittleEndian(idBytes, edit.ParameterId); + else + BinaryPrimitives.WriteInt32LittleEndian(idBytes, checked((int)edit.ParameterId)); + replacement.CopyTo(row.AsSpan(idFirst ? idWidth : 0)); + + if (store.Integer == 0) + { + if (store.ValueOffset < 0 || (uint)store.QueuePosition > walk.Queue.Count + || BinaryPrimitives.ReadUInt32LittleEndian(body.AsSpan(store.ValueOffset)) != 0) + throw Unverified("The empty parameter-store pointer could not be verified."); + byte[] payload = new byte[checked(sizeof(uint) + row.Length)]; + BinaryPrimitives.WriteUInt32LittleEndian(payload, 1); + row.CopyTo(payload.AsSpan(sizeof(uint))); + int start = store.QueuePosition == walk.Queue.Count ? body.Length : walk.QueueStart[store.QueuePosition]; + Span pointer = stackalloc byte[sizeof(uint) + sizeof(ushort)]; + BinaryPrimitives.WriteUInt32LittleEndian(pointer, uint.MaxValue); + BinaryPrimitives.WriteUInt16LittleEndian(pointer[sizeof(uint)..], checked((ushort)tag)); + return ReplaceValue(ReplaceValue(body, start, 0, payload), store.ValueOffset, sizeof(uint), pointer); + } + + int slot = StoreSlot(walk, store); + var ids = walk.Captures.Where(c => c.QueueIndex == slot && c.DeclaringClass == ValueClass(storage) && c.Field == "m_paramId").ToArray(); + int countAt = walk.QueueStart[slot]; + int endAt = slot + 1 == walk.Queue.Count ? body.Length : walk.QueueStart[slot + 1]; + if (BinaryPrimitives.ReadUInt32LittleEndian(body.AsSpan(countAt)) != ids.Length + || ids.Any(c => c.ValueOffset < countAt + sizeof(uint) || c.ValueOffset >= endAt) + || ids.Zip(ids.Skip(1)).Any(pair => pair.First.Integer >= pair.Second.Integer)) + throw Unverified("The existing parameter rows are not uniquely sorted by ID."); + int next = Array.FindIndex(ids, id => id.Integer > edit.ParameterId); + int insertAt = next < 0 ? endAt : ids[next].ValueOffset - (idFirst ? 0 : sizeof(double)); + byte[] updated = ReplaceValue(body, insertAt, 0, row); + BinaryPrimitives.WriteUInt32LittleEndian(updated.AsSpan(countAt), (uint)ids.Length + 1); + return updated; + } + + private static bool IsElementId(WideBlockWalker walker, SchemaField field) => + field is { Type: 14, Mods: 0, Ref: int tag } && walker.Class(tag)?.Name == "ElementId"; + + private static int StoreSlot(WideBlockWalker.Walk walk, WideBlockWalker.Capture pointer) + { + int slot = pointer.QueuePosition; + if (slot < 0) + { + slot = walk.Queue.IndexOf((int)pointer.Integer); + if (slot != walk.Queue.LastIndexOf((int)pointer.Integer)) + slot = -1; + } + if (pointer.Integer <= 0 || (uint)slot >= walk.Queue.Count || walk.Queue[slot] != pointer.Integer) + throw Unverified("The root parameter store is ambiguous."); + return slot; + } + + private static byte[]? EditProjectInformation(RootStorage root, Pending pending, string field, string oldValue, string newValue) + { + if (pending.OpenMetadata(root, "ProjectInformation") is not { } source) + throw Unverified("The ProjectInformation stream is missing."); + using (source) + { + try + { + using var zip = new ZipArchive(source, ZipArchiveMode.Read, leaveOpen: true); + if (zip.Entries.Count != 1 || !zip.Entries[0].Name.EndsWith(".project.xml", StringComparison.Ordinal)) + throw Unverified("The ProjectInformation archive layout is unsupported."); + var entry = zip.Entries[0]; + using var xml = XmlReader.Create(entry.Open(), new XmlReaderSettings { CloseInput = true, MaxCharactersInDocument = 16 * 1024 * 1024 }); + var doc = XDocument.Load(xml, LoadOptions.PreserveWhitespace); + XNamespace atom = "http://www.w3.org/2005/Atom"; + XNamespace partAtom = "urn:schemas-autodesk-com:partatom"; + var values = doc.Elements(atom + "entry").Elements(partAtom + "features").Elements(partAtom + "feature") + .Elements(partAtom + "group").Elements(atom + field).Where(e => (string?)e.Attribute("type") == "system").ToArray(); + if (values is not [var target] || target.HasElements || NormalizeXmlText(target.Value) != NormalizeXmlText(oldValue)) + throw Unverified($"The stored parameter and its ProjectInformation XML field '{field}' do not match."); + if (oldValue == newValue) + return null; + + target.Value = newValue; + using var buffer = new MemoryStream(); + using (var output = new ZipArchive(buffer, ZipArchiveMode.Create, leaveOpen: true)) + { + var outputEntry = output.CreateEntry(entry.FullName); + outputEntry.LastWriteTime = entry.LastWriteTime; + using var destination = outputEntry.Open(); + using var writer = XmlWriter.Create(destination, new XmlWriterSettings { NewLineHandling = NewLineHandling.Entitize }); + doc.Save(writer); + } + return buffer.ToArray(); + } + catch (Exception ex) when (ex is InvalidDataException or XmlException) + { + throw new RvtWriteRefusedException("unverified-parameter-storage", "The ProjectInformation stream could not be decoded.", ex); + } + } + } + + private static string NormalizeXmlText(string value) => value.Replace("\r\n", "\n", StringComparison.Ordinal).Replace('\r', '\n'); + + internal static RvtWriteRefusedException Unverified(string message) => new("unverified-parameter-storage", message); +} diff --git a/src/RvtIO/Writing/ProjectFamilyReference.cs b/src/RvtIO/Writing/ProjectFamilyReference.cs new file mode 100644 index 00000000..eef06c26 --- /dev/null +++ b/src/RvtIO/Writing/ProjectFamilyReference.cs @@ -0,0 +1,240 @@ +using System.Buffers.Binary; +using OpenMcdf; +using RvtIO.Parsing; +using static RvtIO.Writing.UserParameterWriter; + +namespace RvtIO.Writing; + +internal sealed record ProjectFamilyReference(long FamilyId, long Category, IReadOnlySet Dependencies, long? SharedNestedOwner) +{ + private const string ExternalIds = "FamilyDocument.m_big2SmallMap2"; + private const string OwnedIds = "ElementIdIndexPairSet.m_data"; + + internal static ProjectFamilyReference Read(RootStorage root, PartitionFraming.Tags tags, int idWidth, + SchemaDocument schema, IReadOnlySet elementIds, long id, long familyId, ParameterWriter.Pending pending, + long? referringType = null, bool inspectDependencies = true) + { + var walker = new WideBlockWalker(schema, (c, f) => (c.Name, f.Name) switch + { + ("Element", "m_id") or ("ElementHeader", "m_designOptionId" or "m_categroryId") => f.Name, + ("FamilyBase", "m_oFamDoc" or "m_familyIds" or "m_bShared") or ("FamilyDocument", "m_big2SmallMap2") or + ("ElementIdIndexPairSet", "m_data") or ("std::pair< ElementId, ForeignElemRef >", "first") or + ("ElementIdPlusIndex", "m_elementId") => c.Name + "." + f.Name, + _ => LoadedFamilyParameterWriter.CaptureKey(c, f) ?? CaptureKey(c, f), + }, ["ForgeTypeId"]); + var classes = new Dictionary(); + var familyRecords = new Dictionary(); + var nestedTypeRecords = new Dictionary(); + var familySymbols = new Dictionary>(); + var symbolFamilies = new Dictionary(); + var dependencies = new HashSet(); + var familiesToRead = new Queue(); + var mappedProxies = new HashSet(); + HashSet? ownedProxies = null; + long? sharedNestedOwner = null; + long? category = null; + bool sawHeader = false; + + ParameterWriter.ScanPartitions(root, tags, idWidth, (_, record) => + { + long owner = (long)record.Owner; + if (record.Block != 0 || !elementIds.Contains(owner)) + return; + int tag = Tag(record); + if (record.Channel == 101 && owner == id) + { + if (sawHeader || walker.Class(tag)?.Name != "ElementHeader") + throw UnverifiedTarget(); + sawHeader = true; + var header = Walk(record, tag, rootOnly: true); + if (!header.RootRead || Integer(header, "m_designOptionId") != -1) + throw UnverifiedTarget(); + category = Integer(header, "m_categroryId"); + } + if (record.Channel != 102 || (!inspectDependencies && owner != id && owner != familyId)) + return; + string? name = walker.Class(tag)?.Name; + if (!classes.TryAdd(owner, name)) + classes[owner] = null; + if (name == "Family" && classes[owner] is not null) + familyRecords.Add(owner, record.Body.ToArray()); + if (referringType is not null && name == "NestedFamSymRefElem" && classes[owner] is not null) + nestedTypeRecords.Add(owner, record.Body.ToArray()); + if (!walker.IsA(tag, "FamilySymbol")) + return; + var symbol = Walk(record, tag, rootOnly: true); + if (!symbol.RootRead || Integer(symbol, "m_id") != owner + || Integer(symbol, "FamilySymbol.m_familyId") is not (> 0 and long owningFamily)) + throw UnverifiedTarget(); + if (!familySymbols.TryGetValue(owningFamily, out var symbols)) + familySymbols.Add(owningFamily, symbols = []); + symbols.Add(owner); + symbolFamilies.TryAdd(owner, owningFamily); + }, pending); + + if (classes.GetValueOrDefault(id) != "FamilySymbol" || symbolFamilies.GetValueOrDefault(id) != familyId + || category is not (< -1 and long targetCategory)) + throw UnverifiedTarget(); + + // A verified shared project binding stores the ID on the element, outside the family declaration. + if (!inspectDependencies) + { + _ = ReadFamily(familyId); + return new(familyId, targetCategory, dependencies, null); + } + + EnqueueFamily(familyId); + while (familiesToRead.Count != 0) + { + // Following mapped families first keeps their parameter stores in the same partition scan. + var symbolsToRead = new HashSet(); + while (familiesToRead.TryDequeue(out long dependency)) + { + var (family, symbols) = ReadFamily(dependency); + var external = ReadMappedReferences(family, "FamilyBase.m_oFamDoc", "FamilyDocument", ExternalIds, "std::pair< ElementId, ForeignElemRef >.first"); + var owned = ReadMappedReferences(family, "FamilyBase.m_familyIds", "ElementIdIndexPairSet", OwnedIds, "ElementIdPlusIndex.m_elementId"); + if (dependency == familyId && referringType is long type && classes.GetValueOrDefault(type) == "FamilySymbol" + && symbolFamilies.TryGetValue(type, out long owner) && owner != familyId && external.Contains(owner) && external.Contains(type)) + sharedNestedOwner = owner; + if (dependency == sharedNestedOwner) + { + if (Integer(family, "FamilyBase.m_bShared") != 1) + throw UnverifiedTarget(); + // The container also maps the shared nested family's own private type proxies. + ownedProxies = owned.Where(reference => external.Contains(reference) && classes.GetValueOrDefault(reference) == "NestedFamSymRefElem") + .ToHashSet(); + } + foreach (long reference in external) + { + if (sharedNestedOwner is not null && (dependency == familyId || dependency == sharedNestedOwner) + && classes.GetValueOrDefault(reference) == "NestedFamSymRefElem") + mappedProxies.Add(reference); + else + FollowReference(reference); + } + foreach (long reference in owned) + if (dependency != sharedNestedOwner || ownedProxies?.Contains(reference) != true) + FollowReference(reference); + AddValueReferences(family, dependency, dependency); + symbolsToRead.UnionWith(symbols); + } + + ParameterWriter.ScanPartitions(root, tags, idWidth, (_, record) => + { + long owner = (long)record.Owner; + if (record.Block != 0 || record.Channel != 102 || !elementIds.Contains(owner)) + return; + int tag = Tag(record); + if (symbolsToRead.Contains(owner)) + { + AddValueReferences(Walk(record, tag), owner, symbolFamilies[owner]); + return; + } + if (!walker.IsA(tag, "FamilyInstance")) + return; + var instance = Walk(record, tag, rootOnly: true); + if (!instance.RootRead || Integer(instance, "m_id") != owner + || Integer(instance, "FamilyInstance.m_masterSymbolId") is not long master) + throw UnverifiedTarget(); + if (symbolsToRead.Contains(master)) + { + if (classes.GetValueOrDefault(owner) is null) + throw UnverifiedTarget(); + AddValueReferences(Walk(record, tag), owner, symbolFamilies[master]); + } + }, pending); + } + if (sharedNestedOwner is not null && (ownedProxies is null || !mappedProxies.IsSubsetOf(ownedProxies) + || mappedProxies.Any(proxy => !VerifyNestedProxy(proxy)))) + throw UnverifiedTarget(); + dependencies.Remove(familyId); + return new(familyId, targetCategory, dependencies, sharedNestedOwner); + + static int Tag(PartitionFraming.Record record) => record.Body.Length >= 2 + ? BinaryPrimitives.ReadUInt16LittleEndian(record.Body.Span) : -1; + + WideBlockWalker.Walk Walk(PartitionFraming.Record record, int tag, bool rootOnly = false) + { + byte[] bytes = record.Body.ToArray(); + return walker.Run(bytes, 0, bytes.Length, tag, rootOnly: rootOnly); + } + + (WideBlockWalker.Walk Walk, List Symbols) ReadFamily(long owner) + { + if (classes.GetValueOrDefault(owner) != "Family" || !familyRecords.TryGetValue(owner, out byte[]? bytes) + || !familySymbols.TryGetValue(owner, out var symbols) + || symbols.Any(symbol => classes.GetValueOrDefault(symbol) is null)) + throw UnverifiedTarget(); + var family = walker.Run(bytes, 0, bytes.Length, BinaryPrimitives.ReadUInt16LittleEndian(bytes)); + if (!family.Exact || family.EmptyEntityAt >= 0 || Integer(family, "m_id") != owner + || Integer(family, "FamilyBase.m_inPlace") != 0 || Integer(family, "FamilyBase.m_categoryId") is not (< -1 and long familyCategory) + || (owner == familyId && familyCategory != targetCategory)) + throw UnverifiedTarget(); + return (family, symbols); + } + + void EnqueueFamily(long family) + { + if (dependencies.Add(family)) + familiesToRead.Enqueue(family); + } + + void FollowReference(long reference) + { + string? name = classes.GetValueOrDefault(reference); + if (name is "CategoryElem" or "GStyleElem" or "FontElem" or "LeaderStyle" or "DimensionStyle" + or "TextNoteAttributes" or "TagNoteAttributes" or "MaterialElem" or "CoverType" or "ParamElemFamily" or "ParamElemExternal") + return; + if (name == "Family") + EnqueueFamily(reference); + else if (name is not null && symbolFamilies.TryGetValue(reference, out long owningFamily)) + EnqueueFamily(owningFamily); + else + throw UnverifiedTarget(); + } + + void AddValueReferences(WideBlockWalker.Walk walk, long owner, long owningFamily) + { + if (!walk.Exact || walk.EmptyEntityAt >= 0 || Integer(walk, "m_id") != owner) + throw UnverifiedTarget(); + foreach (var capture in walk.Captures.Where(c => (c.DeclaringClass, c.Field) is + ("NamedParam", "m_elemId") or ("ParamValueElementId", "m_value"))) + { + if (capture.Kind != WideBlockWalker.CaptureKind.Integer) + throw UnverifiedTarget(); + if (capture.Integer > 0 && (owningFamily != sharedNestedOwner || ownedProxies?.Contains(capture.Integer) != true)) + FollowReference(capture.Integer); + } + } + + HashSet ReadMappedReferences(WideBlockWalker.Walk walk, string pointer, string targetClass, string array, string field) + { + if (walk.Captures.Where(c => c.AtRoot && c.Key == pointer).ToArray() is not + [{ Kind: WideBlockWalker.CaptureKind.PointerClass, Integer: > 0 and var tag, QueuePosition: >= 0 and var slot }] + || slot >= walk.Queue.Count || walk.Queue[slot] != tag + || walker.Class(walk.Queue[slot])?.Name != targetClass) + throw UnverifiedTarget(); + var entries = walk.Captures.Where(c => c.QueueIndex == slot && c.Key == field).ToArray(); + var ids = entries.Select(c => c.Integer).ToHashSet(); + if (Integer(walk, array + "#", slot) != entries.Length + || entries.Any(c => c.Kind != WideBlockWalker.CaptureKind.Integer || c.Integer <= 0) + || ids.Count != entries.Length) + throw UnverifiedTarget(); + return ids; + } + + bool VerifyNestedProxy(long reference) + { + if (!nestedTypeRecords.TryGetValue(reference, out byte[]? record)) + return false; + var proxy = walker.Run(record, 0, record.Length, BinaryPrimitives.ReadUInt16LittleEndian(record)); + return proxy is { Exact: true, EmptyEntityAt: < 0 } && Integer(proxy, "m_id") == reference + && Integer(proxy, "NestedFamSymRefElem.m_categoryId") is < -1 + && RootName(proxy, "NestedFamSymRefElem.m_famName") is not null + && RootName(proxy, "NestedFamSymRefElem.m_symName") is not null; + } + } + + private static RvtWriteRefusedException UnverifiedTarget() => + ParameterWriter.Unverified("The project family type target or its family dependencies could not be verified."); +} diff --git a/src/RvtIO/Writing/RvtWriter.cs b/src/RvtIO/Writing/RvtWriter.cs index c65cd30b..d6df8f9f 100644 --- a/src/RvtIO/Writing/RvtWriter.cs +++ b/src/RvtIO/Writing/RvtWriter.cs @@ -4,6 +4,7 @@ using System.Xml; using ICSharpCode.SharpZipLib.Checksum; using OpenMcdf; +using RvtIO.BuiltIns; using RvtIO.Internal; using RvtIO.Parsing; using RvtIO.Writing; @@ -110,6 +111,12 @@ public sealed record RvtPartitionRecordEdit( ReadOnlyMemory Body, int Block = 0); +/// An RVT parameter assignment. A null value clears a supported shared parameter with HideWhenNoValue. +public sealed record RvtParameterEdit(long ElementId, long ParameterId, string? Value); + +/// An RFA parameter assignment. A null value resets supported text to empty or material to By Category. +public sealed record RvtFamilyParameterEdit(string FamilyTypeName, long ParameterId, string? Value); + /// Set of stream and partition record edits to persist atomically into a new Revit container. public sealed class RvtWriteRequest { @@ -138,7 +145,7 @@ public sealed class RvtWriteResult /// Number of container streams replaced during the write (0 for an unchanged ). public required int ReplacedStreamCount { get; init; } - /// Number of partition records rewritten across all Partitions/<n> streams. + /// Number of partition records replaced across all Partitions/<n> streams. public required int RewrittenRecordCount { get; init; } } @@ -180,6 +187,83 @@ public static RvtWriteCapabilities InspectCapabilities(string sourcePath) public static RvtWriteResult SaveAs(string sourcePath, string outputPath) => Rewrite(sourcePath, outputPath, new RvtWriteRequest()); + /// Writes a new local RVT with one verified writable built-in parameter set. + /// The source and any existing output are preserved. See the writing guide for supported parameters and releases. + /// The parameter, element or source layout is outside the verified scope. + public static RvtWriteResult SetParameter(string sourcePath, string outputPath, long elementId, BuiltInParameter parameter, string value) + => SetParameter(sourcePath, outputPath, elementId, (int)parameter, value); + + /// Writes a new local RVT with one verified writable parameter replaced. A positive + /// identifies a parameter definition in the source project. Numeric values use invariant format. + /// The parameter, element, value or source layout is outside the verified scope. + public static RvtWriteResult SetParameter(string sourcePath, string outputPath, long elementId, int parameterId, string value) + => SetParameter(sourcePath, outputPath, elementId, (long)parameterId, value); + + /// + public static RvtWriteResult SetParameter(string sourcePath, string outputPath, long elementId, long parameterId, string value) + { + ArgumentNullException.ThrowIfNull(value); + return SetParameters(sourcePath, outputPath, [new(elementId, parameterId, value)]); + } + + /// Applies an ordered batch of RVT parameter edits. The output is published only if every edit succeeds. + public static RvtWriteResult SetParameters(string sourcePath, string outputPath, IReadOnlyList edits) + { + ArgumentNullException.ThrowIfNull(sourcePath); + ArgumentNullException.ThrowIfNull(outputPath); + ArgumentNullException.ThrowIfNull(edits); + if (!string.Equals(Path.GetExtension(sourcePath), ".rvt", StringComparison.OrdinalIgnoreCase) + || !string.Equals(Path.GetExtension(outputPath), ".rvt", StringComparison.OrdinalIgnoreCase)) + throw new RvtWriteRefusedException("unsupported-parameter-file", "Parameter edits require a source and output with the .rvt extension."); + if (edits.Count == 0) + throw new ArgumentException("At least one parameter edit is required.", nameof(edits)); + + var batch = edits.Select(edit => + { + ArgumentNullException.ThrowIfNull(edit); + ParameterWriter.Validate(edit.ParameterId, edit.Value); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(edit.ElementId); + return new ParameterWriter.Edit(edit.ElementId, edit.ParameterId, edit.Value); + }).ToArray(); + return RewriteCore(sourcePath, outputPath, new RvtWriteRequest(), parameterEdits: batch); + } + + /// Writes a new local RFA with a verified writable parameter set on the named family type. + /// Use the source family's parameter definition ID or a supported built-in ID. Numeric values use invariant format. + /// The family, type, parameter or value is outside the verified scope. + public static RvtWriteResult SetFamilyParameter(string sourcePath, string outputPath, string familyTypeName, int parameterId, string value) + => SetFamilyParameter(sourcePath, outputPath, familyTypeName, (long)parameterId, value); + + /// + public static RvtWriteResult SetFamilyParameter(string sourcePath, string outputPath, string familyTypeName, long parameterId, string value) + { + ArgumentNullException.ThrowIfNull(value); + return SetFamilyParameters(sourcePath, outputPath, [new(familyTypeName, parameterId, value)]); + } + + /// Applies an ordered batch of RFA parameter edits. The output is published only if every edit succeeds. + public static RvtWriteResult SetFamilyParameters(string sourcePath, string outputPath, IReadOnlyList edits) + { + ArgumentNullException.ThrowIfNull(sourcePath); + ArgumentNullException.ThrowIfNull(outputPath); + ArgumentNullException.ThrowIfNull(edits); + if (!Path.GetExtension(sourcePath).Equals(".rfa", StringComparison.OrdinalIgnoreCase) + || !Path.GetExtension(outputPath).Equals(".rfa", StringComparison.OrdinalIgnoreCase)) + throw new RvtWriteRefusedException("unsupported-parameter-file", "Family parameter edits require a source and output with the .rfa extension."); + if (edits.Count == 0) + throw new ArgumentException("At least one parameter edit is required.", nameof(edits)); + + var batch = edits.Select(edit => + { + ArgumentNullException.ThrowIfNull(edit); + ArgumentException.ThrowIfNullOrWhiteSpace(edit.FamilyTypeName); + ArgumentOutOfRangeException.ThrowIfZero(edit.ParameterId); + StandaloneFamilyParameterWriter.Validate(edit.ParameterId, edit.Value); + return new StandaloneFamilyParameterWriter.Edit(edit.FamilyTypeName, edit.ParameterId, edit.Value); + }).ToArray(); + return RewriteCore(sourcePath, outputPath, new RvtWriteRequest(), familyEdits: batch); + } + /// Writes from with the requested paged-stream and partition-record /// edits applied, preserving every other stream, block, channel, and record byte-for-byte. /// , , or is null. @@ -189,6 +273,10 @@ public static RvtWriteResult SaveAs(string sourcePath, string outputPath) => /// A stream exceeds the maximum single-array byte length. /// The source file state or edit request is outside the supported scope. public static RvtWriteResult Rewrite(string sourcePath, string outputPath, RvtWriteRequest request) + => RewriteCore(sourcePath, outputPath, request); + + private static RvtWriteResult RewriteCore(string sourcePath, string outputPath, RvtWriteRequest request, + ParameterWriter.Edit[]? parameterEdits = null, StandaloneFamilyParameterWriter.Edit[]? familyEdits = null) { ArgumentNullException.ThrowIfNull(sourcePath); ArgumentNullException.ThrowIfNull(outputPath); @@ -204,13 +292,22 @@ public static RvtWriteResult Rewrite(string sourcePath, string outputPath, RvtWr Dictionary? replacements = null; RvtWriteCapabilities capabilities; - using (var sourceFile = new FileStream(sourcePath, FileMode.Open, FileAccess.Read, FileShare.Read)) + using var sourceFile = new FileStream(fullSource, FileMode.Open, FileAccess.Read, FileShare.Read); using (var root = RootStorage.Open(sourceFile, StorageModeFlags.LeaveOpen)) { - var inspection = InspectRoot(root, sourcePath); + var inspection = InspectRoot(root, sourcePath, inspectImageLinks: + !SameDirectory(Path.GetDirectoryName(fullSource)!, Path.GetDirectoryName(fullOutput)!)); capabilities = inspection.Capabilities; RequireSupported(capabilities, RvtWriteOperation.SaveAs); + bool editParameters = parameterEdits is not null || familyEdits is not null; + if (editParameters) + { + RequireSupported(capabilities, RvtWriteOperation.PartitionRecordRewrite); + var requiredKind = familyEdits is null ? RvtFileKind.Project : RvtFileKind.Family; + if (capabilities.FileKind != requiredKind) + throw new RvtWriteRefusedException("unsupported-parameter-file", $"This edit requires a local Revit {requiredKind.ToString().ToLowerInvariant()}."); + } if (request.PagedStreamEdits.Count > 0) RequireSupported(capabilities, RvtWriteOperation.PagedStreamRewrite); if (request.PartitionRecordEdits.Count > 0) @@ -218,8 +315,21 @@ public static RvtWriteResult Rewrite(string sourcePath, string outputPath, RvtWr ValidateExternalReferenceRelocation(root, inspection, fullSource, fullOutput); + var pending = new ParameterWriter.Pending(); + if (editParameters) + { + var tags = inspection.FramingTags!.Value; + int idWidth = capabilities.ElementIdWidth!.Value; + foreach (var edit in parameterEdits ?? []) + pending.Apply(ParameterWriter.Plan(root, tags, idWidth, edit, pending)); + foreach (var edit in familyEdits ?? []) + pending.Apply(StandaloneFamilyParameterWriter.Plan(root, tags, idWidth, edit, pending)); + request = new RvtWriteRequest { PartitionRecordEdits = pending.Records.Values.ToArray() }; + } if (request.PagedStreamEdits.Count > 0 || request.PartitionRecordEdits.Count > 0) replacements = BuildReplacements(root, inspection, request); + foreach (var (path, bytes) in pending.Metadata) + (replacements ??= new(StringComparer.OrdinalIgnoreCase)).Add(inspection.CanonicalStreamPaths[path], bytes); } string outputKindHint = KindFromPath(fullOutput) is not RvtFileKind.Unknown ? fullOutput : sourcePath; @@ -228,7 +338,7 @@ public static RvtWriteResult Rewrite(string sourcePath, string outputPath, RvtWr : temporaryPath => VerifyOutputEligibility(temporaryPath, outputKindHint, capabilities, request); var containerResult = ContainerRewriter.Rewrite( - sourcePath, + fullSource, fullOutput, replacements ?? NoStreamReplacements, verifyEditedOutput); @@ -249,7 +359,8 @@ private sealed record Inspection( PartitionFraming.Tags? FramingTags, IReadOnlyDictionary CanonicalStreamPaths, IReadOnlySet PartitionRevitLinkIds, - bool HasPartitionPointClouds); + bool HasPartitionPointClouds, + IReadOnlyList<(ulong Id, LinkedImageReference.Location? Location)> ImageLinks); private static RvtWriteCapabilities InspectContainer(string containerPath, string? pathHint = null) { @@ -299,7 +410,7 @@ private static void RequireSupported(RvtWriteCapabilities capabilities, RvtWrite throw new RvtWriteRefusedException(support.RefusalCode!, support.Reason!); } - private static Inspection InspectRoot(RootStorage root, string sourcePath) + private static Inspection InspectRoot(RootStorage root, string sourcePath, bool inspectImageLinks = false) { bool hasBasicFileInfo = false; Dictionary bfi; @@ -371,6 +482,24 @@ private static Inspection InspectRoot(RootStorage root, string sourcePath) PartitionFraming.Tags? framingTags = formatsSchema is null ? null : PartitionFraming.TagsOf(formatsSchema); ushort? rvtLinkClassTag = FindClassTag(schemaDoc, "RvtLinkSymbol"); ushort? pointCloudClassTag = FindClassTag(schemaDoc, "PointCloudType"); + var imageLinks = new List<(ulong Id, LinkedImageReference.Location? Location)>(); + Action? inspectImage = null; + if (inspectImageLinks && schemaDoc is not null && FindClassTag(schemaDoc, "ImageSymbol") is ushort imageTag) + { + var walker = new WideBlockWalker(schemaDoc, (declaring, field) => + ImportedImageReference.CaptureKey(declaring, field) ?? LinkedImageReference.CaptureKey(declaring, field), []); + inspectImage = record => + { + if (BinaryPrimitives.ReadUInt16LittleEndian(record.Body.Span) != imageTag) + return; + byte[] body = record.Body.ToArray(); + var image = walker.Run(body, 0, body.Length, imageTag, rootOnly: true); + if (image.RootRead && UserParameterWriter.Integer(image, "ImageSymbol.m_flags") == 0) + return; + image = walker.Run(body, 0, body.Length, imageTag); + imageLinks.Add((record.Owner, LinkedImageReference.ReadLocation(walker, image))); + }; + } (string Code, string Reason)? baseFailure = EvaluateBaseEligibility( fileKind, @@ -406,6 +535,7 @@ private static Inspection InspectRoot(RootStorage root, string sourcePath) idWidth, rvtLinkClassTag, pointCloudClassTag, + inspectImage, out partitionRevitLinkIds, out hasPartitionPointClouds); } @@ -436,7 +566,8 @@ private static Inspection InspectRoot(RootStorage root, string sourcePath) framingTags, canonicalPaths, partitionRevitLinkIds, - hasPartitionPointClouds); + hasPartitionPointClouds, + imageLinks); } private static ushort? FindClassTag(SchemaDocument? schemaDoc, string className) @@ -517,6 +648,7 @@ private static RvtOperationSupport EvaluatePartitionEligibility( int? idWidth, ushort? rvtLinkClassTag, ushort? pointCloudClassTag, + Action? inspectImage, out IReadOnlySet partitionRevitLinkIds, out bool hasPartitionPointClouds) { @@ -549,6 +681,7 @@ private static RvtOperationSupport EvaluatePartitionEligibility( ushort classTag = BinaryPrimitives.ReadUInt16LittleEndian(record.Body.Span); if (rvtLinkClassTag == classTag) revitLinkIds.Add(record.Owner); if (pointCloudClassTag == classTag) sawPointCloud = true; + inspectImage?.Invoke(record); } if (record.Channel == 101) return; adler.Reset(); @@ -607,6 +740,14 @@ private static void ValidateExternalReferenceRelocation( "Saving to a different directory cannot verify external file paths of PointCloudType records, which are not listed in TransmissionData."); } + foreach (var (id, location) in inspection.ImageLinks) + { + if (location is null) + throw new RvtWriteRefusedException("relative-reference-relocation", $"The external path of image {id} could not be verified."); + CheckRelativeReferenceTarget(location.Path, location.PathType, null, id.ToString(CultureInfo.InvariantCulture), + sourceDir, outputDir, sameDirectory); + } + if (!inspection.CanonicalStreamPaths.TryGetValue("TransmissionData", out string? tdPath)) { if (inspection.PartitionRevitLinkIds.Count > 0 && !sameDirectory) diff --git a/src/RvtIO/Writing/StandaloneFamilyParameterWriter.cs b/src/RvtIO/Writing/StandaloneFamilyParameterWriter.cs new file mode 100644 index 00000000..8c78d6ce --- /dev/null +++ b/src/RvtIO/Writing/StandaloneFamilyParameterWriter.cs @@ -0,0 +1,828 @@ +using System.Buffers.Binary; +using System.Globalization; +using System.Xml; +using System.Xml.Linq; +using OpenMcdf; +using RvtIO.BuiltIns; +using RvtIO.Model; +using RvtIO.Parsing; +using static RvtIO.Writing.ImportedImageReference; +using static RvtIO.Writing.LoadedFamilyParameterWriter; +using static RvtIO.Writing.ParameterWriter; +using static RvtIO.Writing.UserParameterWriter; + +namespace RvtIO.Writing; + +internal static class StandaloneFamilyParameterWriter +{ + internal sealed record Edit(string TypeName, long ParameterId, string? Value); + private sealed record FamilyType(string Name, FamilyStore Values); + private sealed record FamilyDefinition(WideBlockWalker.Walk Walk, int Slot, int Mode, Guid? SharedGuid); + private sealed record BuiltInField(string Name, string Type, string? DisplayName = null, UnitType? Quantity = null) + { + internal StorageType Storage => Quantity.HasValue ? StorageType.Double : Type == "Image" ? StorageType.ElementId : StorageType.String; + internal bool IsIdentity => Storage == StorageType.String || Quantity == UnitType.UT_Currency; + } + private static readonly Dictionary BuiltInFields = new() + { + [(int)BuiltInParameter.ALL_MODEL_TYPE_COMMENTS] = new("Type_Comments", "Text", "Type Comments"), + [(int)BuiltInParameter.ALL_MODEL_DESCRIPTION] = new("Description", "Text"), + [(int)BuiltInParameter.ALL_MODEL_MANUFACTURER] = new("Manufacturer", "Text"), + [(int)BuiltInParameter.ALL_MODEL_MODEL] = new("Model", "Text"), + [(int)BuiltInParameter.ALL_MODEL_URL] = new("URL", "URL"), + [(int)BuiltInParameter.ALL_MODEL_COST] = new("Cost", "Currency", Quantity: UnitType.UT_Currency), + [(int)BuiltInParameter.FIRE_RATING] = new("Fire_Rating", "Text", "Fire Rating"), + [(int)BuiltInParameter.FAMILY_FREEINST_DEFAULT_ELEVATION] = new("Default_Elevation", "Length", "Default Elevation", UnitType.UT_Length), + [(int)BuiltInParameter.ALL_MODEL_TYPE_IMAGE] = new("Type_Image", "Image", "Type Image"), + }; + private static readonly XNamespace Atom = "http://www.w3.org/2005/Atom"; + private static readonly XNamespace PartAtom = "urn:schemas-autodesk-com:partatom"; + private static readonly string[] ConstraintFields = + ["m_paramExprs", "m_drivenDimSegs", "m_additionalParamExprs", "m_dimSegDataMap"]; + + internal static void Validate(long parameterId, string? value) + { + if (parameterId < 0) + { + if (!BuiltInFields.ContainsKey(parameterId)) + throw new RvtWriteRefusedException("unsupported-parameter", "This built-in family parameter has not been verified for writing."); + if (value is null) + throw new RvtWriteRefusedException("unsupported-parameter-clear", "Built-in family parameters require an explicit assignment."); + ValidateText(value); + return; + } + ParameterWriter.Validate(parameterId, value); + } + + private static string? CaptureKey(SchemaClass declaring, SchemaField field) => (declaring.Name, field.Name) switch + { + ("AUnits", "m_formatOptionsArr") => ParameterMeasurement.LegacyFormats, + ("ADocument", "m_ownerFamilyId" or "m_ownerFamilyContainingGroupId") or + ("FamilyBase", "m_pFamilyTypes" or "m_bHasLabeledDimensions" or "m_contentProtected" or "m_name") or + ("Family", "m_oFamDimConstrMgr") or + ("FamilyTypeTable", "m_idx" or "m_pairs") or + ("FamilyTypePair", "name") or + ("ParamIdPair", "m_famParamId") or + ("DimSegInfo" or "ParamExprEntry", "m_paramId") or + ("ParamExpr", "m_entries") or + ("ParamDef", "m_caption" or "m_typeId" or "m_userVisible") or + ("ParamDefFamType", "m_categoryId") or + ("ParamElemExternal", "m_externalParamKey") => declaring.Name + "." + field.Name, + ("FamDimConstrMgrImpl", _) when ConstraintFields.Contains(field.Name) => declaring.Name + "." + field.Name, + ("Element", "m_id") => field.Name, + _ => ImportedImageReference.CaptureKey(declaring, field) ?? UserParameterWriter.CaptureKey(declaring, field) + ?? LoadedFamilyParameterWriter.CaptureKey(declaring, field) + ?? ParameterFormulaEvaluator.CaptureKey(declaring, field), + }; + + internal static PlanResult? Plan(RootStorage root, PartitionFraming.Tags tags, int idWidth, Edit edit, Pending pending) + { + BuiltInField? builtIn = BuiltInFields.GetValueOrDefault(edit.ParameterId); + if (TfSchemaReader.Read(root) is not { } schema) + throw Unverified("The family schema could not be read exactly."); + var formats = new FormatsSchema(schema); + var walker = new WideBlockWalker(schema, CaptureKey, ["ForgeTypeId", "FormatOptions", "AUnits"]); + if (PagedGzipStream.Read(root, "Global", "Latest") is not { Length: >= 2 } latest + || BinaryPrimitives.ReadUInt16LittleEndian(latest) != formats.IdOf("ADocument")) + throw Unverified("The family document header could not be located."); + var header = walker.Run(latest, 0, latest.Length, BinaryPrimitives.ReadUInt16LittleEndian(latest), rootOnly: true); + if (!header.RootRead || Integer(header, "ADocument.m_ownerFamilyId") is not long familyId || familyId <= 0 + || Integer(header, "ADocument.m_ownerFamilyContainingGroupId") != -1) + throw Unverified("The family document's owner could not be verified."); + + if (ElemTableLayout.IdWidth(formats) != idWidth || PagedGzipStream.Read(root, "Global", "ElemTable") is not { } table + || ElemTableLayout.TryParse(table, formats) is not { } elements) + throw Unverified("Global/ElemTable could not be read exactly."); + var active = elements.Select(row => (ulong)row.Id).ToHashSet(); + if (!active.Contains((ulong)familyId)) + throw Unverified("The document's owner family is absent from the element table."); + int definitionIndex = elements.FindIndex(element => element.Id == edit.ParameterId); + if (builtIn is null && definitionIndex < 0) + throw new RvtWriteRefusedException("missing-parameter-definition", $"Parameter definition {edit.ParameterId} is absent from the family."); + + var seen = new HashSet(); + var materials = new Dictionary(); + var images = new Dictionary(); + var nestedTypes = new Dictionary(); + var nestedFamilies = new Dictionary(); + var units = new Dictionary(); + var definitions = new Dictionary(); + var externalReferences = new HashSet(); + byte[]? body = null; + WideBlockWalker.Walk? family = null; + int partition = -1, familyClass = -1; + ScanPartitions(root, tags, idWidth, (number, record) => + { + if (record.Block != 0 || record.Channel != 102 || !active.Contains(record.Owner)) + return; + if (!seen.Add(record.Owner) || record.Body.Length < 2) + throw Unverified($"Family element {record.Owner} has an ambiguous record."); + int cls = BinaryPrimitives.ReadUInt16LittleEndian(record.Body.Span); + byte[] data = record.Body.ToArray(); + var walk = walker.Run(data, 0, data.Length, cls); + if (!walk.Exact || walk.EmptyEntityAt >= 0 || Integer(walk, "m_id") != (long)record.Owner) + throw Unverified($"Family element {record.Owner} could not be read exactly for dependency checks."); + string? className = walker.Class(cls)?.Name; + if (className == "MaterialElem" && MaterialName(walker, walk, (long)record.Owner) is { } name) + materials.Add((long)record.Owner, name); + if ((builtIn is null || builtIn.Storage == StorageType.ElementId) && className is ("ImageSymbol" or "ImageHolder")) + images.Add((long)record.Owner, walk); + if (className == "UnitsElem") + units.Add(record.Owner, walk); + bool owner = record.Owner == (ulong)familyId; + if (!owner && builtIn is null && className == "Family") + nestedFamilies.Add((long)record.Owner, walk); + if (builtIn is null && className == "FamilySymbol") + nestedTypes.Add((long)record.Owner, walk); + if (walker.IsA(cls, "ParamElemGlobal")) + throw Unverified("The parameter may participate in a global, element, or dimension association."); + foreach (var capture in walk.Captures) + if (capture.Key is "ParamIdPair.m_famParamId" or "DimSegInfo.m_paramId" or "ParamExprEntry.m_paramId" || + !owner && capture.Key == "formula-reference") + externalReferences.Add(capture.Integer); + if (builtIn is not null) + CheckFormulaDependencies(walk, edit.ParameterId); + if (owner) + { + if (className != "Family") + throw Unverified("The owner element is outside the verified family scope."); + (body, family, partition, familyClass) = (data, walk, number, cls); + } + if (className is "ParamElemFamily" or "ParamElemExternal") + definitions.Add((long)record.Owner, data); + }, pending); + if (!seen.SetEquals(active) || family is null || body is null) + throw Unverified("The family element records are incomplete."); + if (externalReferences.Contains(edit.ParameterId)) + throw Unverified("The parameter is used by an external formula or may participate in an element or dimension association."); + long? category = Integer(family, "FamilyBase.m_categoryId"); + bool independentOfDoorConstraints = builtIn?.IsIdentity == true && category == (int)BuiltInCategory.OST_Doors; + if (Integer(family, "FamilyBase.m_contentProtected") != 0 || Integer(family, "FamilyBase.m_bHasLabeledDimensions") != 0 + || Integer(family, "Family.m_oFamDimConstrMgr") is not long manager + || family.Queue.Select((tag, index) => (tag, index)).Where(p => p.tag == manager).ToArray() is not [{ index: var constraintSlot }] + || ConstraintFields.Any(name => Integer(family, "FamDimConstrMgrImpl." + name + "#", constraintSlot) is not (>= 0 and long count) + || (!independentOfDoorConstraints && count != 0)) + || (independentOfDoorConstraints && !HasExactConstraintReferences(family, constraintSlot))) + throw Unverified("The family has protection or dimension constraints outside the verified write scope."); + + if (builtIn is not null) + return PlanBuiltIn(builtIn, family, body); + + var (types, current) = ReadTypes(walker, family); + var selected = FindType(types, edit.TypeName); + var rootStore = ReadStore(walker, family, "FamilyBase.m_familyParams"); + if (rootStore.Rows.Where(r => r.Id == edit.ParameterId).ToArray() is [var requested] && requested.Fields[1].Integer != 0) + throw new RvtWriteRefusedException("read-only-parameter", "A formula drives the family parameter."); + var parsed = new Dictionary(); + var input = Definition(edit.ParameterId); + var valueEdit = new ParameterWriter.Edit(familyId, edit.ParameterId, edit.Value); + string? definitionClass = walker.Class(input.Walk.Queue[input.Slot])?.Name; + bool familyTypeReference = definitionClass == "ParamDefFamType"; + bool imageReference = definitionClass == "ParamDefImageSymbolBrowseEdit"; + long? reference = ReferenceId(edit.Value); + long? material = reference.HasValue && materials.ContainsKey(reference.Value) ? reference : null; + string? nestedReferenceName = null; + string? imageReferenceName = null; + (StorageType storage, byte[] replacement, UnitType? quantity) = + familyTypeReference ? EncodeFamilyTypeReference() : + imageReference ? EncodeImageReference() : + Encode(walker, input.Walk, input.Slot, valueEdit, idWidth, material, familyReset: true, includeCurrency: true); + var calculated = FamilyFormulaPropagation.Recalculate(walker, family, body, types.Select(type => type.Values).Append(rootStore), + selected.Values, selected == current ? rootStore : null, edit.ParameterId, replacement, idWidth, id => !externalReferences.Contains(id), + id => + { + var definition = Definition(id); + return FormulaParameterStorage.Read(walker, definition.Walk, definition.Slot, includeCurrency: true); + }); + + var metadata = ReadPartAtom(root, pending); + var part = FindPart(metadata, edit.TypeName); + bool metadataChanged = false; + var locations = new List<(int Offset, int Length, byte[] Replacement)>(); + var staged = new List<(long Id, StorageType Storage, byte[] Replacement)>(); + Stage(edit.ParameterId, storage, replacement, quantity, edit.Value, computed: false); + foreach (var result in calculated) + { + var format = result.Format; + Stage(result.Id, format.Storage, result.Replacement, + format.Storage == StorageType.Double ? format.Unit : null, + format.Storage == StorageType.String ? format.Decode(result.Replacement).Text : null, computed: true); + } + + byte[]? atom = metadataChanged ? SerializePartAtom(metadata) : null; + if (locations.Count == 0) + return atom is null ? null : new PlanResult([], ("PartAtom", atom)); + + byte[] updated = body; + foreach (var location in locations.OrderByDescending(location => location.Offset)) + updated = ReplaceValue(updated, location.Offset, location.Length, location.Replacement); + var verified = walker.Run(updated, 0, updated.Length, familyClass); + var (checkedTypes, checkedCurrent) = ReadTypes(walker, verified); + if (checkedCurrent.Name != current.Name || checkedTypes.Where(type => type.Name == edit.TypeName).ToArray() is not [var checkedType]) + throw Unverified("The edited record changed the current type or lost the requested type."); + Verify(checkedType.Values); + if (checkedType == checkedCurrent) + Verify(ReadStore(walker, verified, "FamilyBase.m_familyParams")); + + return new PlanResult([new RvtPartitionRecordEdit(partition, 102, (ulong)familyId, updated)], + atom is null ? null : ("PartAtom", atom)); + + void Verify(FamilyStore store) + { + foreach (var item in staged) + { + var row = FamilyFormulaPropagation.FindFormulaRow(store, item.Id); + var location = Location(row, item.Storage, idWidth); + if (row.Instance != Definition(item.Id).Mode || + !updated.AsSpan(location.Offset, location.Length).SequenceEqual(item.Replacement)) + throw Unverified("The updated family type value could not be read back."); + } + } + + FamilyDefinition Definition(long id) + { + if (parsed.TryGetValue(id, out var saved)) + return saved; + if (!definitions.TryGetValue(id, out var data)) + throw new RvtWriteRefusedException("unsupported-parameter", "The parameter must have a family or shared definition."); + if (rootStore.Rows.Where(row => row.Id == id).ToArray() is not [{ Instance: 0 or 1 } declaration]) + throw Unverified("The parameter is not declared by the owner family."); + int mode = (int)declaration.Instance; + var (def, slot) = ReadDefinition(walker, data, new ParameterWriter.Edit(familyId, id, null)); + bool shared = walker.Class(BinaryPrimitives.ReadUInt16LittleEndian(data))?.Name == "ParamElemExternal"; + if (shared ? Integer(def, WideBlockWalker.AllItemsKeyPrefix + "bindings#") != 0 : + Integer(def, "ParamElemFamily.m_instanceParam") != mode) + throw Unverified("The parameter definition does not match the family declaration."); + Guid? guid = shared + ? ReadSharedGuid(root, schema, elements[elements.FindIndex(element => element.Id == id)], def, slot) + : null; + var definition = new FamilyDefinition(def, slot, mode, guid); + parsed.Add(id, definition); + return definition; + } + + (StorageType, byte[], UnitType?) EncodeFamilyTypeReference() + { + if (Integer(input.Walk, "ParamDefFamType.m_categoryId", input.Slot) is not < 0) + throw Unverified("The family type parameter definition is outside the verified layout."); + if (edit.Value is null) + throw new RvtWriteRefusedException("unsupported-parameter-clear", "Family type references require an explicit assignment."); + if (edit.Value == "-1") + reference = -1; + if (reference is not long target || target != -1 && !nestedTypes.ContainsKey(target) && !materials.ContainsKey(target)) + throw new RvtWriteRefusedException("invalid-parameter-value", + "Expected -1 or the ID of an existing nested family type or material in the family file."); + nestedReferenceName = ReferencePartAtomName(target); + return (StorageType.ElementId, EncodeElementId(target, idWidth), null); + } + + (StorageType, byte[], UnitType?) EncodeImageReference() + { + if (input.SharedGuid is not null || input.Mode != 0 || Integer(input.Walk, "ParamDef.m_userVisible", input.Slot) != 1) + throw Unverified("The image parameter is outside the verified custom type scope."); + if (edit.Value is null) + throw new RvtWriteRefusedException("unsupported-parameter-clear", "Image references require an explicit assignment."); + var (id, name) = ReadImageAssignment(edit.Value); + imageReferenceName = name; + return (StorageType.ElementId, EncodeElementId(id, idWidth), null); + } + + (long Id, string Name) ReadImageAssignment(string value) + { + long id = ReadId(value); + string name = ReadName(walker, images, id) + ?? throw new RvtWriteRefusedException("invalid-parameter-value", "The image ID does not identify a verified image imported into this family."); + ValidateText(name); + return (id, name); + } + + string? ReferencePartAtomName(long target) + { + if (target == -1 || materials.ContainsKey(target)) + return null; + if (!nestedTypes.TryGetValue(target, out var symbol) || Integer(symbol, "FamilySymbol.m_masterId") != -1 + || Integer(symbol, "FamilySymbol.m_ownerInstanceId") != -1 + || Integer(symbol, "FamilySymbol.m_familyId") is not long ownerId + || !nestedFamilies.TryGetValue(ownerId, out var owner) || Integer(owner, "FamilyBase.m_inPlace") != 0 + || PointerSlot(walker, symbol, "Symbol.m_symbolInfo", "SymbolInfo") is not int info + || symbol.Captures.Where(c => c.QueueIndex == info && c.Key == "SymbolInfo.m_name").ToArray() + is not [{ Text: { Length: > 0 } typeName }] + || owner.Captures.Where(c => c.AtRoot && c.Key == "FamilyBase.m_name").ToArray() + is not [{ Text: { Length: > 0 } familyName }]) + throw Unverified("The nested family type reference or its name could not be verified."); + return familyName + " : " + typeName; + } + + void Stage(long id, StorageType storage, byte[] replacement, UnitType? quantity, string? text, bool computed) + { + var definition = Definition(id); + var row = ReadRow(selected.Values); + var value = Location(row, storage, idWidth); + var old = body.AsSpan(value.Offset, value.Length); + if (!computed && (quantity == UnitType.UT_Currency || ParameterMeasurement.IsAdditionalSpec(quantity))) + ParameterFormulaEvaluator.VerifyStableChange(BinaryPrimitives.ReadDoubleLittleEndian(old), + BinaryPrimitives.ReadDoubleLittleEndian(replacement)); + if (selected == current) + { + var copy = Location(ReadRow(rootStore), storage, idWidth); + if (copy.Offset == value.Offset || !body.AsSpan(copy.Offset, copy.Length).SequenceEqual(old)) + throw Unverified("The active type and the current family parameter value disagree."); + if (!old.SequenceEqual(replacement)) + locations.Add((copy.Offset, copy.Length, replacement)); + } + if (!old.SequenceEqual(replacement)) + locations.Add((value.Offset, value.Length, replacement)); + staged.Add((id, storage, replacement)); + + var original = row.Value(storage); + if (familyTypeReference && !computed) + { + metadataChanged |= UpdateFamilyTypePartAtom(metadata, part, definition, category, + ReferencePartAtomName(original.Integer), nestedReferenceName); + return; + } + ParameterMeasurement.DisplayValue? display = definition.Mode == 0 && quantity is UnitType measured && measured != UnitType.UT_Number + && WideDocument.Read(latest, schema) is { } document && units.TryGetValue(document.UnitsElemId, out var displayUnits) + ? ParameterMeasurement.Display(measured, walker, displayUnits, original.Real, BinaryPrimitives.ReadDoubleLittleEndian(replacement)) + : null; + (string? Type, string? Before, string? After) referenceNames = default; + if (storage == StorageType.ElementId) + { + referenceNames = imageReference && !computed + ? ("Image", ReadName(walker, images, original.Integer) + ?? throw Unverified("The stored image does not identify a verified image imported into this family."), imageReferenceName) + : ("Material", original.Integer == -1 ? "" : materials.GetValueOrDefault(original.Integer), + edit.Value is null ? "" : materials.GetValueOrDefault(material!.Value)); + } + metadataChanged |= UpdatePartAtom(part, definition.Walk, definition.Slot, definition.SharedGuid, definition.Mode, + storage, original, replacement, text, display, referenceNames); + + NamedValue ReadRow(FamilyStore store) + { + var row = computed ? FamilyFormulaPropagation.FindFormulaRow(store, id) : FindRow(store, id, definition.Mode)!; + if (row.Instance != definition.Mode) + throw Unverified("The family formula result has a different instance or type scope."); + return row; + } + } + + PlanResult? PlanBuiltIn(BuiltInField field, WideBlockWalker.Walk owner, byte[] data) + { + bool supportedCategory = edit.ParameterId == (int)BuiltInParameter.FIRE_RATING + ? category == (int)BuiltInCategory.OST_Doors + : category == (int)BuiltInCategory.OST_GenericModel || (field.IsIdentity + && category is ((int)BuiltInCategory.OST_Doors or (int)BuiltInCategory.OST_Windows or (int)BuiltInCategory.OST_Furniture)); + if (!supportedCategory || Integer(owner, "FamilyBase.m_inPlace") != 0) + throw Unverified("This built-in field has not been verified for the family category."); + + var (allTypes, activeType) = ReadTypes(walker, owner); + var target = FindType(allTypes, edit.TypeName); + // Revit also copies the last assigned identity value to the unnamed door or window type. + var unnamedType = field.IsIdentity && category is ((int)BuiltInCategory.OST_Doors or (int)BuiltInCategory.OST_Windows) + ? allTypes.SingleOrDefault(type => type.Name == " ") : null; + var currentValues = ReadStore(walker, owner, "FamilyBase.m_familyParams"); + var activeCopy = FindRow(currentValues, edit.ParameterId, 0, required: false); + var rows = allTypes.ToDictionary(t => t, t => FindRow(t.Values, edit.ParameterId, 0, required: false)); + bool first = activeCopy is null; + if ((first && field.Quantity == UnitType.UT_Length) || rows.Values.Any(row => (row is null) != first)) + throw Unverified("The built-in parameter's family value stores could not be verified."); + + var storageType = field.Storage; + if (!first) + { + if (rows.Values.Append(activeCopy).Any(row => row is null || row.Fields[5].Integer != 0 + || (storageType != StorageType.ElementId && row.Fields[3].Integer != -1) + || (storageType != StorageType.Double && row.Fields[2].Real != 0) + || (storageType != StorageType.String && row.Fields[0].Text != ""))) + throw Unverified("The built-in family parameter has an unverified value layout."); + var copy = Location(activeCopy!, storageType, idWidth); + var saved = Location(rows[activeType]!, storageType, idWidth); + if (copy.Offset == saved.Offset || !data.AsSpan(copy.Offset, copy.Length).SequenceEqual(data.AsSpan(saved.Offset, saved.Length))) + throw Unverified("The active type and the current family parameter value disagree."); + } + + var old = rows[target]?.Value(storageType); + string newText = edit.Value!; + byte[] encoded; + if (storageType == StorageType.ElementId) + { + var (imageId, name) = ReadImageAssignment(newText); + newText = name; + encoded = EncodeElementId(imageId, idWidth); + } + else if (field.Quantity == UnitType.UT_Length) + { + if (ParameterMeasurement.Parse(UnitType.UT_Length, newText) is not double value) + throw new RvtWriteRefusedException("invalid-parameter-value", "Default Elevation requires a finite length with a unit, such as 300 mm."); + encoded = EncodeDouble(value); + } + else + encoded = storageType == StorageType.Double ? EncodeCost(newText) : EncodeText(newText); + var format = field.Quantity is UnitType quantity && WideDocument.Read(latest, schema) is { } document + && units.TryGetValue(document.UnitsElemId, out var displayUnits) + ? ParameterMeasurement.Display(quantity, walker, displayUnits, old?.Real ?? 0, + BinaryPrimitives.ReadDoubleLittleEndian(encoded)) + : null; + if (storageType == StorageType.Double && format is null) + throw Unverified("The family display format for this built-in parameter could not be verified."); + + string? oldText = storageType == StorageType.ElementId && old is { } storedImage + ? ReadName(walker, images, storedImage.Integer) + ?? throw Unverified("The family references an image whose imported value could not be verified.") + : old?.Text; + var (defaultBytes, defaultText) = storageType switch + { + StorageType.ElementId => (EncodeElementId(-1, idWidth), NoneName), + StorageType.Double => (new byte[sizeof(double)], "0.00"), + _ => (new byte[sizeof(uint)], ""), + }; + byte[]? partAtom = EditBuiltInPartAtom(root, pending, field, allTypes, target, unnamedType, first, oldText, newText, defaultText, format); + byte[] revised = data; + if (first) + { + VerifyNamedParamLayout(formats, walker); + byte[] defaultRow = EncodeNamedParam(edit.ParameterId, storageType, idWidth, defaultBytes); + byte[] assignedRow = EncodeNamedParam(edit.ParameterId, storageType, idWidth, encoded); + var stores = allTypes.Select(t => (Store: t.Values, Assigned: Updates(t))) + .Append((Store: currentValues, Assigned: Updates(activeType))); + foreach (var (store, assigned) in stores.OrderByDescending(s => s.Store.CountOffset)) + revised = InsertNamedParam(revised, store, assigned ? assignedRow : defaultRow); + } + else + { + var locationsToEdit = allTypes.Where(Updates).Select(t => Location(rows[t]!, storageType, idWidth)).ToList(); + if (Updates(activeType)) + locationsToEdit.Add(Location(activeCopy!, storageType, idWidth)); + foreach (var location in locationsToEdit.OrderByDescending(l => l.Offset)) + if (!revised.AsSpan(location.Offset, location.Length).SequenceEqual(encoded)) + revised = ReplaceValue(revised, location.Offset, location.Length, encoded); + } + + var readBack = walker.Run(revised, 0, revised.Length, familyClass); + var (verifiedTypes, verifiedCurrent) = ReadTypes(walker, readBack); + if (verifiedCurrent.Name != activeType.Name || !verifiedTypes.Select(t => t.Name).SequenceEqual(allTypes.Select(t => t.Name))) + throw Unverified("The edited family record changed the type table."); + foreach (var type in verifiedTypes.Where(t => first || Updates(t))) + VerifyValue(type.Values, Updates(type)); + if (first || Updates(activeType)) + VerifyValue(ReadStore(walker, readBack, "FamilyBase.m_familyParams"), Updates(activeType)); + + return ReferenceEquals(data, revised) && partAtom is null ? null + : new PlanResult(ReferenceEquals(data, revised) ? [] : [new(partition, 102, (ulong)familyId, revised)], + partAtom is null ? null : ("PartAtom", partAtom)); + + bool Updates(FamilyType type) => type.Name == target.Name || type.Name == unnamedType?.Name; + + void VerifyValue(FamilyStore store, bool assigned) + { + var location = Location(FindRow(store, edit.ParameterId, 0)!, storageType, idWidth); + var bytes = revised.AsSpan(location.Offset, location.Length); + if (!bytes.SequenceEqual(assigned ? encoded : defaultBytes)) + throw Unverified("The built-in family parameter could not be read back."); + } + } + } + + private static FamilyType FindType(FamilyType[] types, string name) => + types.SingleOrDefault(t => t.Name == name) + ?? throw new RvtWriteRefusedException("missing-family-type", $"The family has no unique type named '{name}'."); + + private static bool HasExactConstraintReferences(WideBlockWalker.Walk family, int slot) + { + long? expressionCount = Integer(family, "FamDimConstrMgrImpl.m_paramExprs#", slot) + + Integer(family, "FamDimConstrMgrImpl.m_additionalParamExprs#", slot); + var counts = family.Captures.Where(c => c.QueueIndex == slot && c.Key == "ParamExpr.m_entries#").ToArray(); + return expressionCount == counts.Length && counts.Sum(c => c.Integer) == family.Captures.Count(c => + c.QueueIndex == slot && c.Key == "ParamExprEntry.m_paramId" && c.Kind == WideBlockWalker.CaptureKind.Integer); + } + + private static void VerifyNamedParamLayout(FormatsSchema formats, WideBlockWalker walker) + { + if (formats.IdOf("NamedParam") is not int tag || walker.Class(tag) is not { Base: 0 } row + || row.Fields.Where(f => f.Stored).ToArray() is not + [ + { Name: "m_str", Type: 8, Mods: 0 or 0x60 }, + { Name: "m_oExpression", Type: 14, Mods: 1 }, + { Name: "m_value", Type: 7, Mods: 0 }, + { Name: "m_elemId", Type: 14, Mods: 0, Ref: int idTag }, + { Name: "m_paramId", Type: 14, Mods: 0, Ref: int paramTag }, + { Name: "m_int", Type: 4, Mods: 0 }, + { Name: "m_instance", Type: 1, Mods: 0 }, + { Name: "m_reporting", Type: 1, Mods: 0 }, + ] || idTag != paramTag || walker.Class(idTag)?.Name != "ElementId") + throw Unverified("The built-in family parameter row layout could not be verified."); + } + + private static byte[] EncodeNamedParam(long id, StorageType storage, int idWidth, byte[] value) + { + using var output = new MemoryStream(); + using var writer = new BinaryWriter(output); + if (storage == StorageType.String) + writer.Write(value); + else + writer.Write(0u); + writer.Write(0u); + if (storage == StorageType.Double) + writer.Write(value); + else + writer.Write(0d); + writer.Write(storage == StorageType.ElementId ? value : EncodeElementId(-1, idWidth)); + writer.Write(EncodeElementId(id, idWidth)); + writer.Write(0); + writer.Write(false); + writer.Write(false); + return output.ToArray(); + } + + private static (FamilyType[] Types, FamilyType Current) ReadTypes(WideBlockWalker walker, WideBlockWalker.Walk family) + { + if (!family.Exact || Integer(family, "FamilyBase.m_pFamilyTypes") is not long tag + || walker.Class((int)tag)?.Name != "FamilyTypeTable" + || family.Queue.Select((cls, index) => (cls, index)).Where(p => p.cls == tag).ToArray() is not [{ index: var slot }]) + throw Unverified("The family type table could not be read exactly."); + var fields = family.Captures.Where(c => c.QueueIndex == slot).ToArray(); + var names = fields.Select((capture, index) => (capture, index)).Where(p => p.capture.Key == "FamilyTypePair.name").ToArray(); + if (Integer(family, "FamilyTypeTable.m_pairs#", slot) != names.Length + || Integer(family, "FamilyTypeTable.m_idx", slot) is not long current || current < 0 || current >= names.Length + || names.Any(p => p.capture.Text is null) + || names.Select(p => p.capture.Text).Distinct(StringComparer.Ordinal).Count() != names.Length) + throw Unverified("The family type names or current type could not be verified."); + var types = new FamilyType[names.Length]; + for (int i = 0; i < types.Length; i++) + { + int end = i + 1 == types.Length ? fields.Length : names[i + 1].index; + types[i] = new FamilyType(names[i].capture.Text!, ReadStore(fields[(names[i].index + 1)..end])); + } + return (types, types[current]); + } + + private static byte[]? EditBuiltInPartAtom(RootStorage root, Pending pending, BuiltInField field, FamilyType[] types, FamilyType selected, + FamilyType? unnamedType, bool first, string? before, string text, string defaultText, ParameterMeasurement.DisplayValue? display) + { + var document = ReadPartAtom(root, pending); + if (unnamedType is not null && TypeParts(document).Any(part => (string?)part.Element(Atom + "title") == unnamedType.Name)) + throw Unverified("The unnamed family type has an unverified PartAtom entry."); + bool changed = false; + foreach (var type in types.Where(t => t == selected || (first && t != unnamedType))) + { + var part = FindPart(document, type.Name); + var matches = part.Elements(Atom + field.Name).Where(node => (string?)node.Attribute("type") == "system").ToArray(); + if (matches.Length > 1) + throw Unverified("The built-in family metadata entry is ambiguous."); + var entry = matches.SingleOrDefault(); + bool expected = !first && (display is not null || !string.IsNullOrEmpty(before)); + if (expected != (entry is not null) + || (entry is not null && (entry.HasElements || (string?)entry.Attribute("typeOfParameter") != field.Type + || (string?)entry.Attribute("displayName") != field.DisplayName || (string?)entry.Attribute("units") != display?.Unit + || !(display?.Matches(entry.Value) ?? entry.Value == before)))) + throw Unverified("The stored built-in value and family metadata disagree."); + + string after = type == selected ? display?.After ?? text : defaultText; + if (entry is null) + { + if (after.Length == 0) + continue; + entry = new XElement(Atom + field.Name); + if (field.DisplayName is not null) + entry.SetAttributeValue("displayName", field.DisplayName); + entry.SetAttributeValue("type", "system"); + entry.SetAttributeValue("typeOfParameter", field.Type); + if (display is { } units) + entry.SetAttributeValue("units", units.Unit); + entry.Value = after; + part.Add(entry); + } + else if (after.Length == 0) + entry.Remove(); + else if (entry.Value != after) + entry.Value = after; + else + continue; + changed = true; + } + return changed ? SerializePartAtom(document) : null; + } + + private static XElement FindPart(XDocument document, string typeName) + { + var parts = TypeParts(document) + .Where(part => (string?)part.Element(Atom + "title") == typeName).ToArray(); + return parts is [var part] ? part : throw Unverified("The family metadata does not identify the requested type uniquely."); + } + + private static IEnumerable TypeParts(XDocument document) => + document.Elements(Atom + "entry").Elements(PartAtom + "family").Elements(PartAtom + "part"); + + private static XDocument ReadPartAtom(RootStorage root, Pending pending) + { + using var stream = pending.OpenMetadata(root, "PartAtom") + ?? throw Unverified("The family metadata stream is missing."); + try + { + using var input = XmlReader.Create(stream, new XmlReaderSettings { MaxCharactersInDocument = 16 * 1024 * 1024 }); + return XDocument.Load(input, LoadOptions.PreserveWhitespace); + } + catch (XmlException ex) + { + throw new RvtWriteRefusedException("unverified-parameter-storage", "The family metadata stream could not be decoded.", ex); + } + } + + private static bool UpdateFamilyTypePartAtom(XDocument metadata, XElement part, FamilyDefinition definition, + long? ownerCategory, string? before, string? after) + { + if (definition.Walk.Captures.Where(c => c.QueueIndex == definition.Slot && c.Key == "ParamDef.m_caption").ToArray() + is not [{ Text: { Length: > 0 } caption }] + || Integer(definition.Walk, "ParamDef.m_userVisible", definition.Slot) is not long visible || visible is not (0 or 1)) + throw Unverified("The family type parameter name or visibility could not be verified."); + + var matches = Entries(part).ToArray(); + if (definition.Mode != 0 || visible == 0) + { + if (matches.Length > 0) + throw Unverified("The family type parameter has an unexpected metadata entry."); + return false; + } + + const string prefix = "Family type: "; + var labels = TypeParts(metadata).SelectMany(Entries).Select(e => (string?)e.Attribute("typeOfParameter")) + .Distinct(StringComparer.Ordinal).ToArray(); + string? type = labels is [{ } label] && label.StartsWith(prefix, StringComparison.Ordinal) && label.Length > prefix.Length + ? label : null; + if (labels.Length > 0 && type is null) + throw Unverified("The family type parameter metadata uses an unverified category label."); + + if (before is not null) + { + if (matches is not [var target] || target.HasElements || target.Attribute("units") is not null || target.Value != before) + throw Unverified("The stored family type reference and family metadata disagree."); + if (before == after) + return false; + if (after is null) + target.Remove(); + else + target.Value = after; + return true; + } + + if (matches.Length > 0) + throw Unverified("The unset family type reference has an unexpected metadata entry."); + if (after is null) + return false; + if (type is null && ownerCategory is >= int.MinValue and < 0 + && ((BuiltInCategory)ownerCategory.Value).TryGetCategoryName(out var ownerLabel) + && metadata.Root?.Elements(Atom + "category").Where(e => (string?)e.Element(Atom + "scheme") == "adsk:revit:grouping") + .Select(e => (string?)e.Element(Atom + "term")).ToArray() is [var grouping] && grouping == ownerLabel + && Integer(definition.Walk, "ParamDefFamType.m_categoryId", definition.Slot) is >= int.MinValue and < 0 and long targetCategory + && ((BuiltInCategory)targetCategory).TryGetCategoryName(out var targetLabel)) + type = prefix + targetLabel; + if (type is null) + throw Unverified("The family type parameter metadata category label could not be verified."); + + part.Add(CreatePartAtomEntry(caption, definition.SharedGuid, type, after)); + return true; + + IEnumerable Entries(XElement entry) => entry.Elements().Where(node => + MatchesPartAtomParameter(node, caption, definition.SharedGuid)); + } + + private static bool UpdatePartAtom( + XElement part, WideBlockWalker.Walk definition, int slot, Guid? sharedGuid, int mode, + StorageType storage, WideBlockWalker.Capture original, byte[] replacement, string? text, + ParameterMeasurement.DisplayValue? display, (string? Type, string? Before, string? After) reference) + { + if (definition.Captures.Where(c => c.QueueIndex == slot && c.Key == "ParamDef.m_caption").ToArray() + is not [{ Text: { Length: > 0 } caption }]) + throw Unverified("The parameter name could not be verified."); + var matches = part.Elements().Where(node => MatchesPartAtomParameter(node, caption, sharedGuid)).ToArray(); + if (matches.Length == 0) + { + if (reference.Type == "Image") + throw Unverified("The custom image has no verified family metadata entry."); + if (mode != 0 || storage != StorageType.String || original.Text != "" || string.IsNullOrEmpty(text) + || Integer(definition, "ParamDef.m_userVisible", slot) != 1) + return false; + + part.Add(CreatePartAtomEntry(caption, sharedGuid, "Text", text)); + return true; + } + if (mode != 0 || matches is not [var target] || target.HasElements || (string?)target.Attribute("units") != display?.Unit) + throw Unverified("The parameter's family metadata is outside the verified layout."); + + string before = target.Value; + string after; + bool matchesValue; + switch (storage, (string?)target.Attribute("typeOfParameter")) + { + case (StorageType.String, "Text"): + matchesValue = before == original.Text; + after = text ?? ""; + break; + case (StorageType.Integer, "Integer"): + matchesValue = int.TryParse(before, NumberStyles.Integer, CultureInfo.InvariantCulture, out int integer) && integer == original.Integer; + after = BinaryPrimitives.ReadInt32LittleEndian(replacement).ToString(CultureInfo.InvariantCulture); + break; + case (StorageType.Integer, "Yes/No"): + matchesValue = before is "Yes" or "No" && (before == "Yes" ? 1 : 0) == original.Integer; + after = BinaryPrimitives.ReadInt32LittleEndian(replacement) == 0 ? "No" : "Yes"; + break; + case (StorageType.Double, "Number") when display is null: + matchesValue = double.TryParse(before, NumberStyles.Float, CultureInfo.InvariantCulture, out double number) && number == original.Real; + after = BinaryPrimitives.ReadDoubleLittleEndian(replacement).ToString("R", CultureInfo.InvariantCulture); + break; + case (StorageType.Double, string type) when display is { } formatted && type == formatted.Type: + matchesValue = formatted.Matches(before); + after = formatted.After; + break; + case (StorageType.ElementId, string type) when reference.Type == type && reference.After is not null: + matchesValue = before == reference.Before; + after = reference.After; + break; + default: + throw Unverified("The parameter's family metadata uses an unverified value format."); + } + if (!matchesValue) + throw Unverified("The stored parameter value and family metadata disagree."); + if (storage == StorageType.String && after.Length == 0) + target.Remove(); + else + { + if (after == before) + return false; + target.Value = after; + } + return true; + } + + private static bool MatchesPartAtomParameter(XElement entry, string caption, Guid? sharedGuid) => + sharedGuid is Guid guid + ? (string?)entry.Attribute("type") == "shared" && Guid.TryParse((string?)entry.Attribute("id"), out var id) && id == guid + : (string?)entry.Attribute("type") == "custom" && (string?)entry.Attribute("displayName") == caption; + + private static XElement CreatePartAtomEntry(string caption, Guid? sharedGuid, string type, string value) + { + var entry = new XElement(Atom + PartAtomParameterName(caption), new XAttribute("displayName", caption), + new XAttribute("type", sharedGuid.HasValue ? "shared" : "custom")); + if (sharedGuid is Guid guid) + entry.Add(new XAttribute("id", guid)); + entry.Add(new XAttribute("typeOfParameter", type), value); + return entry; + } + + private static string PartAtomParameterName(string caption) + { + string name = new(caption.Select(c => char.IsLetterOrDigit(c) || c is '_' or '.' ? c : '_').ToArray()); + return name[0] != '_' && !char.IsLetter(name[0]) ? "_" + name : name; + } + + private const string LocalSharedPrefix = "revit.local.shared:"; + + private static Guid ReadSharedGuid(RootStorage root, SchemaDocument schema, ElemTableLayout.Row parameter, + WideBlockWalker.Walk definition, int slot) + { + var key = definition.Captures.Where(c => c.AtRoot && c.Key == "ParamElemExternal.m_externalParamKey").ToArray(); + var forge = definition.Captures.Where(c => c.QueueIndex == slot && c.Key == "ParamDef.m_typeId").ToArray(); + string? typeId = forge is [{ Text: var text }] ? text : null; + Guid? forgeGuid = SharedTypeGuid(typeId); + if (key is [{ Text: var guidText }] && Guid.TryParse(guidText, out Guid guid) && guid != Guid.Empty) + { + if (forge.Length != 0 && forgeGuid != guid && !MatchesLocalSharedElement(root, schema, parameter, typeId)) + throw Unverified("The shared family parameter GUID and Forge type ID disagree."); + return guid; + } + if (key.Length == 0 && forgeGuid is Guid known && known != Guid.Empty) + return known; + throw Unverified("The shared family parameter GUID could not be verified."); + } + + private static Guid? SharedTypeGuid(string? typeId) + { + if (typeId?.StartsWith(LocalSharedPrefix, StringComparison.Ordinal) != true) + return BipHelpers.ParseGuidFromForgeId(typeId); + var value = typeId.AsSpan(LocalSharedPrefix.Length); + return value.Length == 38 && (value[32..].SequenceEqual("-1.0.0") || value[32..].SequenceEqual("-2.0.0")) + && Guid.TryParseExact(value[..32], "N", out Guid guid) ? guid : null; + } + + private static bool MatchesLocalSharedElement(RootStorage root, SchemaDocument schema, ElemTableLayout.Row parameter, string? typeId) + { + // Revit 2023 uses the definition element's compact UniqueId here, while PartAtom still uses its shared GUID. + if (typeId?.StartsWith(LocalSharedPrefix, StringComparison.Ordinal) != true + || typeId.Length != LocalSharedPrefix.Length + 46 || !typeId.EndsWith("-1.0.0", StringComparison.Ordinal) + || parameter.OriginalId is < 0 or > uint.MaxValue + || PagedGzipStream.Read(root, "Global", "History") is not { } history) + return false; + var episodes = RvtFileReader.ParseEpisodeGuids([history], null, new FileSchema(schema)); + var original = new ElemRecHistory((uint)parameter.OriginalId, parameter.CreationDate); + return ElementExportIds.EpisodeGuid(original, episodes.Guids, episodes.X) is Guid episode + && typeId.AsSpan(LocalSharedPrefix.Length, 40).Equals($"{episode:N}{original.OriginalElementId:x8}", StringComparison.OrdinalIgnoreCase); + } + + private static byte[] SerializePartAtom(XDocument document) + { + using var buffer = new MemoryStream(); + using (var output = XmlWriter.Create(buffer, new XmlWriterSettings { NewLineHandling = NewLineHandling.Entitize })) + document.Save(output); + return buffer.ToArray(); + } +} diff --git a/src/RvtIO/Writing/UserParameterWriter.cs b/src/RvtIO/Writing/UserParameterWriter.cs new file mode 100644 index 00000000..c2a6817d --- /dev/null +++ b/src/RvtIO/Writing/UserParameterWriter.cs @@ -0,0 +1,276 @@ +using System.Buffers.Binary; +using System.Globalization; +using RvtIO.BuiltIns; +using RvtIO.Model; +using RvtIO.Parsing; + +namespace RvtIO.Writing; + +internal static class UserParameterWriter +{ + internal static string? CaptureKey(SchemaClass declaring, SchemaField field) => (declaring.Name, field.Name) switch + { + ("Element", "m_pParamValueSetInt" or "m_pParamValueSetDouble" or "m_pParamValueSetElementId") => field.Name, + ("ParamValueInt" or "ParamValueDouble" or "ParamValueElementId", "m_value") => field.Name, + ("ParamElemProject" or "ParamElemExternal", "m_bindingIds") => WideBlockWalker.AllItemsKeyPrefix + "bindings", + ("ParamElemExternal", "m_hideWhenNoValue") or + ("ParamElem", "m_pParamDef") or + ("ParamDef", "m_paramElemId" or "m_readOnly") or + ("ParamDefValue", "m_specTypeId" or "m_unitType" or "m_restriction" or "m_boundless") or + ("ParamDefInt", "m_lowBound" or "m_upBound") or + ("ParamDefFamType", "m_categoryId") or + ("NestedFamSymRefElem", "m_famName" or "m_symName" or "m_categoryId") or + ("ParamDefMaterialBrowse", "m_unassignedString" or "m_extraButtonFlag" or "m_includeParams") or + ("MaterialElem", "m_pMaterial") or ("Material", "m_name") or + ("ParamBinding", "m_paramId" or "m_categoryId" or "m_elemOrSymbol") => declaring.Name + "." + field.Name, + _ => null, + }; + + internal static bool HasProjectBinding(WideBlockWalker walker, byte[]? definition) + { + if (definition is not { Length: >= 2 }) + return false; + int tag = BinaryPrimitives.ReadUInt16LittleEndian(definition); + return walker.Class(tag)?.Name is "ParamElemExternal" or "ParamElemProject" + && walker.Run(definition, 0, definition.Length, tag, rootOnly: true) is { RootRead: true } root + && Integer(root, WideBlockWalker.AllItemsKeyPrefix + "bindings#") is > 0; + } + + internal static bool IsFamilyTypeDefinition(WideBlockWalker walker, byte[]? definition) + { + if (definition is not { Length: >= 2 }) + return false; + int tag = BinaryPrimitives.ReadUInt16LittleEndian(definition); + var root = walker.Run(definition, 0, definition.Length, tag, rootOnly: true); + return root.RootRead && Integer(root, "ParamElem.m_pParamDef") is (> 0 and long kind) + && walker.Class((int)kind)?.Name == "ParamDefFamType"; + } + + internal static (StorageType Storage, byte[] Replacement, UnitType? Quantity) Prepare( + WideBlockWalker walker, string? ownerClass, int? category, byte[]? definition, + IReadOnlyDictionary bindings, ParameterWriter.Edit edit, int idWidth, long? material, + WideBlockWalker.Walk? reference, ProjectFamilyReference? projectReference, long? localElementReference) + { + var (def, slot) = ReadBoundDefinition(walker, ownerClass, category, definition, bindings, edit, edit.Value is null); + string? definitionClass = walker.Class(BinaryPrimitives.ReadUInt16LittleEndian(definition))?.Name; + if (walker.Class(def.Queue[slot])?.Name == "ParamDefFamType") + { + return EncodeFamilyTypeReference(def, slot, edit, idWidth, material, reference, projectReference, + definitionClass == "ParamElemExternal", localElementReference); + } + if (ownerClass == "FamilySymbol" && edit.Value == "-1" + && definitionClass == "ParamElemProject") + material = -1; + return Encode(walker, def, slot, edit, idWidth, material, includeCurrency: definitionClass == "ParamElemExternal"); + } + + internal static (WideBlockWalker.Walk Walk, int Slot) ReadBoundDefinition( + WideBlockWalker walker, string? ownerClass, int? category, byte[]? definition, + IReadOnlyDictionary bindings, ParameterWriter.Edit edit, bool clearing) + { + bool loadedFamily = ownerClass is "FamilyInstance" or "FamilySymbol"; + (int? expectedCategory, int bindingKind) = ownerClass switch + { + "SWall" => ((int)BuiltInCategory.OST_Walls, 1), + "BasicWallType" => ((int)BuiltInCategory.OST_Walls, 2), + "RoomElem" => ((int)BuiltInCategory.OST_Rooms, 1), + "FamilyInstance" => (category, 1), + "FamilySymbol" => (category, 2), + _ => throw new RvtWriteRefusedException("unsupported-parameter-owner", "Writing user parameters on this element class has not been verified."), + }; + if (category is not < -1 || category != expectedCategory) + throw ParameterWriter.Unverified("The element's category or design option could not be verified for writing."); + + if (definition is not { Length: >= 2 }) + throw ParameterWriter.Unverified("The parameter definition record was not found."); + int definitionId = BinaryPrimitives.ReadUInt16LittleEndian(definition); + string? definitionClass = walker.Class(definitionId)?.Name; + string refusal = clearing ? "unsupported-parameter-clear" : "unsupported-parameter"; + if (loadedFamily && definitionClass != "ParamElemExternal" && (clearing || definitionClass != "ParamElemProject")) + throw new RvtWriteRefusedException(refusal, clearing + ? "Clearing requires a shared parameter bound in the project." + : "This edit requires a parameter bound in the project."); + if (definitionClass is not ("ParamElemExternal" or "ParamElemProject")) + throw new RvtWriteRefusedException("unsupported-parameter", "The parameter must have a project or shared definition bound in this project."); + + var (def, slot) = ReadDefinition(walker, definition, edit); + + if (clearing && (definitionClass != "ParamElemExternal" || Integer(def, "ParamElemExternal.m_hideWhenNoValue") != 1)) + throw new RvtWriteRefusedException(refusal, "This edit requires a shared parameter with HideWhenNoValue."); + if (loadedFamily && Integer(def, WideBlockWalker.AllItemsKeyPrefix + "bindings#") == 0) + throw new RvtWriteRefusedException(refusal, "This edit requires a project-bound parameter declared outside the loaded family."); + + var bindingIds = def.Captures.Where(c => c.AtRoot && c.Key.StartsWith(WideBlockWalker.AllItemsKeyPrefix + "bindings@", StringComparison.Ordinal)) + .Select(c => c.Integer).ToArray(); + if (bindingIds.Length == 0 || Integer(def, WideBlockWalker.AllItemsKeyPrefix + "bindings#") != bindingIds.Length + || bindingIds.Distinct().Count() != bindingIds.Length) + throw ParameterWriter.Unverified("The parameter has no verified category bindings."); + int matches = 0; + foreach (long id in bindingIds) + { + if (!bindings.TryGetValue(id, out byte[]? binding) || binding is null) + throw ParameterWriter.Unverified("A declared parameter binding could not be found exactly."); + var resolved = walker.Run(binding, 0, binding.Length, BinaryPrimitives.ReadUInt16LittleEndian(binding)); + if (!resolved.Exact || Integer(resolved, "m_id") != id || Integer(resolved, "ParamBinding.m_paramId") != edit.ParameterId + || Integer(resolved, "ParamBinding.m_categoryId") is not long boundCategory + || Integer(resolved, "ParamBinding.m_elemOrSymbol") is not (1 or 2)) + throw ParameterWriter.Unverified("A declared parameter binding could not be read exactly."); + if (boundCategory == category) + { + if (Integer(resolved, "ParamBinding.m_elemOrSymbol") != bindingKind) + throw ParameterWriter.Unverified("The parameter binding targets a different instance or type."); + matches++; + } + } + if (matches != 1) + throw ParameterWriter.Unverified("The category has no unique applicable parameter binding."); + + return (def, slot); + } + + internal static (WideBlockWalker.Walk Walk, int Slot) ReadDefinition( + WideBlockWalker walker, byte[] definition, ParameterWriter.Edit edit) + { + var def = walker.Run(definition, 0, definition.Length, BinaryPrimitives.ReadUInt16LittleEndian(definition)); + if (!def.Exact || Integer(def, "m_id") != edit.ParameterId + || Integer(def, "ParamElem.m_pParamDef") is not long paramDefClass + || def.Queue.Select((tag, index) => (tag, index)).Where(p => p.tag == paramDefClass).ToArray() is not [{ index: var slot }] + || Integer(def, "ParamDef.m_paramElemId", slot) != edit.ParameterId + || Integer(def, "ParamDef.m_readOnly", slot) is not long readOnly) + throw ParameterWriter.Unverified("The parameter definition could not be read exactly."); + if (readOnly != 0) + throw new RvtWriteRefusedException("read-only-parameter", $"Parameter {edit.ParameterId} is marked read-only in its definition."); + return (def, slot); + } + + internal static (StorageType Storage, byte[] Replacement, UnitType? Quantity) Encode( + WideBlockWalker walker, WideBlockWalker.Walk def, int slot, ParameterWriter.Edit edit, int idWidth, long? material, + bool familyReset = false, bool includeCurrency = false) + { + string? defClassName = walker.Class(def.Queue[slot])?.Name; + if (defClassName == "ParamDefString") + return (StorageType.String, edit.Value is null && !familyReset ? [] : ParameterWriter.EncodeText(edit.Value ?? ""), null); + if (defClassName is "ParamDefInt" or "ParamDefYesNo") + { + long? min = defClassName == "ParamDefYesNo" ? 0 : Integer(def, "ParamDefInt.m_lowBound", slot); + long? max = defClassName == "ParamDefYesNo" ? 1 : Integer(def, "ParamDefInt.m_upBound", slot); + if (min is null || max is null || min > max) + throw ParameterWriter.Unverified("The integer parameter's bounds could not be read exactly."); + if (edit.Value is null) + { + if (familyReset) throw UnsupportedFamilyReset(); + return (StorageType.Integer, [], null); + } + if (!int.TryParse(edit.Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out int value) || value < min || value > max) + throw InvalidValue(edit, $"An integer between {min} and {max} is required."); + byte[] bytes = new byte[sizeof(int)]; + BinaryPrimitives.WriteInt32LittleEndian(bytes, value); + return (StorageType.Integer, bytes, null); + } + if (defClassName == "ParamDefValue" && Integer(def, "ParamDefValue.m_restriction", slot) == 1 + && Integer(def, "ParamDefValue.m_boundless", slot) == 0 + && ParameterMeasurement.Spec(def, slot, includeCurrency: includeCurrency, includeAdditional: true) is UnitType quantity) + { + if (edit.Value is null) + { + if (familyReset) throw UnsupportedFamilyReset(); + return (StorageType.Double, [], quantity); + } + if (ParameterMeasurement.Parse(quantity, edit.Value) is not double value) + throw InvalidValue(edit, quantity is UnitType.UT_Number or UnitType.UT_Currency ? "A finite number in invariant format is required." + : "A finite number and a matching unit are required, separated by a space."); + return (StorageType.Double, ParameterWriter.EncodeDouble(value), quantity); + } + if (defClassName == "ParamDefMaterialBrowse" && Integer(def, "ParamDefMaterialBrowse.m_unassignedString", slot) == 0 + && Integer(def, "ParamDefMaterialBrowse.m_extraButtonFlag", slot) == -1 + && Integer(def, "ParamDefMaterialBrowse.m_includeParams", slot) == 0) + { + if (edit.Value is null && !familyReset) + return (StorageType.ElementId, [], null); + if (edit.Value is null) + material = -1; + if (material is not long id) + throw InvalidValue(edit, "Expected the positive ID of an existing material in the source file."); + return (StorageType.ElementId, EncodeElementId(id, idWidth), null); + } + throw new RvtWriteRefusedException("unsupported-parameter", $"The data type of parameter {edit.ParameterId} has not been verified for writing."); + } + + private static RvtWriteRefusedException UnsupportedFamilyReset() => + new("unsupported-parameter-clear", "Family parameters can be reset to empty text or By Category for materials. Numeric values require an explicit assignment."); + + internal static long? ReferenceId(string? value) => + long.TryParse(value, NumberStyles.None, CultureInfo.InvariantCulture, out long id) && id > 0 ? id : null; + + internal static (StorageType, byte[], UnitType?) EncodeFamilyTypeReference(WideBlockWalker.Walk definition, int slot, + ParameterWriter.Edit edit, int idWidth, long? material, WideBlockWalker.Walk? reference, ProjectFamilyReference? projectReference, + bool sharedProjectBinding = false, long? localElementReference = null) + { + if (Integer(definition, "ParamDefFamType.m_categoryId", slot) is not (< 0 and long referenceCategory)) + throw ParameterWriter.Unverified("The family type reference category could not be verified."); + if (edit.Value is null) + return (StorageType.ElementId, [], null); + long? target = edit.Value == "-1" ? -1 : ReferenceId(edit.Value); + if (target is not long id) + throw InvalidValue(edit, "Expected -1 or a project element ID."); + bool verifiedProjectType = projectReference is not null && (sharedProjectBinding || projectReference.Category == referenceCategory); + if (id != -1 && id != material && !verifiedProjectType && !(sharedProjectBinding && id == localElementReference) + && (reference is not { Exact: true, EmptyEntityAt: < 0 } + || Integer(reference, "m_id") != id + || Integer(reference, "NestedFamSymRefElem.m_categoryId") != referenceCategory + || RootName(reference, "NestedFamSymRefElem.m_symName") is null + || RootName(reference, "NestedFamSymRefElem.m_famName") is null)) + throw InvalidValue(edit, sharedProjectBinding ? "Expected a verified local element or nested family type reference." + : "Expected a verified material or family type reference in the parameter's category."); + return (StorageType.ElementId, EncodeElementId(id, idWidth), null); + } + + internal static void VerifyFamilyReferenceOwner(WideBlockWalker.Walk family, WideBlockWalker.Walk? reference, + ProjectFamilyReference? projectReference, ParameterWriter.Edit edit, bool independentType = false) + { + if (projectReference is not null) + { + if (Integer(family, "m_id") is not long owner) + throw ParameterWriter.Unverified("The referring family could not be identified."); + if (owner == projectReference.FamilyId) + throw InvalidValue(edit, "The referenced type belongs to the family being edited."); + if (projectReference.Dependencies.Contains(owner) && (!independentType || projectReference.SharedNestedOwner != owner)) + throw ParameterWriter.Unverified("The referenced type has a dependency on the family being edited."); + } + if (reference is not null && RootName(reference, "NestedFamSymRefElem.m_famName") is string targetFamily + && (RootName(family, "FamilyBase.m_name") is not string ownerFamily + || targetFamily.Equals(ownerFamily, StringComparison.OrdinalIgnoreCase))) + throw InvalidValue(edit, "The nested type does not identify a different family from the owner."); + } + + internal static string? RootName(WideBlockWalker.Walk record, string key) => + record.Captures.Where(field => field.AtRoot && field.Key == key).ToArray() is [{ Text: { Length: > 0 } name }] + && !string.IsNullOrWhiteSpace(name) ? name : null; + + internal static byte[] EncodeElementId(long id, int idWidth) + { + var bytes = new byte[idWidth]; + if (idWidth == sizeof(long)) + BinaryPrimitives.WriteInt64LittleEndian(bytes, id); + else + BinaryPrimitives.WriteInt32LittleEndian(bytes, checked((int)id)); + return bytes; + } + + internal static string? MaterialName(WideBlockWalker walker, WideBlockWalker.Walk walk, long id) + { + if (!walk.Exact || walk.EmptyEntityAt >= 0 || Integer(walk, "m_id") != id + || Integer(walk, "MaterialElem.m_pMaterial") is not long tag || walker.Class((int)tag)?.Name != "Material" + || walk.Queue.Select((cls, index) => (cls, index)).Where(p => p.cls == tag).ToArray() is not [{ index: var slot }]) + return null; + return walk.Captures.Where(c => c.QueueIndex == slot && c.Key == "Material.m_name").ToArray() + is [{ Text: { Length: > 0 } name }] ? name : null; + } + + internal static long? Integer(WideBlockWalker.Walk walk, string key, int queueIndex = -1) + => walk.Captures.Where(c => c.QueueIndex == queueIndex && c.Key == key).ToArray() is [var value] + && value.Kind is WideBlockWalker.CaptureKind.Integer or WideBlockWalker.CaptureKind.PointerClass ? value.Integer : null; + + private static RvtWriteRefusedException InvalidValue(ParameterWriter.Edit edit, string message) + => new("invalid-parameter-value", $"Parameter {edit.ParameterId}: {message}"); +} diff --git a/tests/RvtIO.Tests/PagedGzipStreamTests.cs b/tests/RvtIO.Tests/PagedGzipStreamTests.cs index c3999db2..d29d5c8a 100644 --- a/tests/RvtIO.Tests/PagedGzipStreamTests.cs +++ b/tests/RvtIO.Tests/PagedGzipStreamTests.cs @@ -43,6 +43,20 @@ public void MemberEndingBeforeTheNextSegmentPosition_DecodesWithPaddingOverThatP Assert.Equal(payload, PagedGzipStream.Decompress(raw)); } + [Fact] + public void MemberEndingBeforeTheMarkerOfAnExactLengthTerminalPageRequiresAValidTrailer() + { + byte[] payload = Payload(64_000); + byte[] member = Member(payload); + var raw = new byte[PagedGzipStream.PageStride]; + member.CopyTo(raw, PagedGzipStream.PrefixLength); + raw[PagedGzipStream.PageDataLength] = 0x83; + Assert.Equal(payload, PagedGzipStream.Decompress(raw)); + + raw[PagedGzipStream.PrefixLength + member.Length - 1] ^= 1; + Assert.Null(PagedGzipStream.Decompress(raw)); + } + [Fact] public void StreamWithoutItsFirstSegment_IsRejectedByTheMemberCrc() { diff --git a/tests/RvtIO.Tests/SetParameterTests.cs b/tests/RvtIO.Tests/SetParameterTests.cs new file mode 100644 index 00000000..0c996c16 --- /dev/null +++ b/tests/RvtIO.Tests/SetParameterTests.cs @@ -0,0 +1,2971 @@ +using System.Buffers.Binary; +using System.Globalization; +using System.IO.Compression; +using System.Security.Cryptography; +using System.Text; +using System.Xml.Linq; +using OpenMcdf; +using RvtIO.BuiltIns; +using RvtIO.Cli; +using RvtIO.Parsing; +using RvtIO.Writing; +using Xunit; +using Back = RvtIO.Tests.SchemaStreamEditorTests.Back; +using Fld = RvtIO.Tests.SchemaStreamEditorTests.Fld; +using NoRef = RvtIO.Tests.SchemaStreamEditorTests.NoRef; + +namespace RvtIO.Tests; + +public sealed class SetParameterTests : IDisposable +{ + private const int ProjectId = 70; + private const int DefinitionId = 71; + private const int BindingId = 72; + private static PartitionFraming.Tags Tags(int release) => release switch + { + 2020 => new(779, 778, 780, 781, 782), + 2021 => new(801, 800, 802, 803, 804), + _ => new(817, 816, 818, 819, 820), + }; + private readonly string _folder = Directory.CreateTempSubdirectory("rvtio-parameter-").FullName; + private string Output => Path.Combine(_folder, "output.rvt"); + + public void Dispose() => Directory.Delete(_folder, recursive: true); + + [Theory] + [InlineData("A different & longer name \U0001F642\r\nSecond line")] + [InlineData("")] + [InlineData("Owner")] + public void WritesIdenticalTextToTheRecordAndMetadata(string value) + { + string source = CreateSource(); + byte[] sourceHash = SHA256.HashData(File.ReadAllBytes(source)); + RvtWriteResult result = RvtWriter.SetParameter(source, Output, ProjectId, BuiltInParameter.CLIENT_NAME, value); + Assert.Equal(value == "Owner" ? 0 : 2, result.ReplacedStreamCount); + Assert.Equal(sourceHash, SHA256.HashData(File.ReadAllBytes(source))); + + using var root = RootStorage.OpenRead(Output); + using var info = root.OpenStream("ProjectInformation"); + using var archive = new ZipArchive(info); + using var xml = Assert.Single(archive.Entries).Open(); + var fields = XDocument.Load(xml).Descendants().ToArray(); + Assert.Equal(value, Assert.Single(fields, f => f.Name.LocalName == "Client_Name").Value); + Assert.Equal("Owner", Assert.Single(fields, f => f.Name.LocalName == "Project_Name").Value); + + Assert.Equal(Body(value), ReadBody(root)); + } + + [Fact] + public void BatchAppliesRepeatedEditsToTheSameRecordAndMetadataInOrder() + { + string source = CreateSource(); + var result = RvtWriter.SetParameters(source, Output, + [new(ProjectId, (int)BuiltInParameter.CLIENT_NAME, "First"), + new(ProjectId, (int)BuiltInParameter.CLIENT_NAME, "Last")]); + Assert.Equal(1, result.RewrittenRecordCount); + Assert.Equal(2, result.ReplacedStreamCount); + using var root = RootStorage.OpenRead(Output); + using var info = root.OpenStream("ProjectInformation"); + using var archive = new ZipArchive(info); + using var xml = Assert.Single(archive.Entries).Open(); + Assert.Equal("Last", Assert.Single(XDocument.Load(xml).Descendants(), e => e.Name.LocalName == "Client_Name").Value); + Assert.Equal(Body("Last"), ReadBody(root)); + } + + [Theory] + [InlineData(Kind.Text, "Первое значение", "", false)] + [InlineData(Kind.Integer, "17", "-9", false)] + [InlineData(Kind.YesNo, "1", "0", false)] + [InlineData(Kind.Number, "7.625", "11.125", false)] + [InlineData(Kind.Number, "1234.56789", "-58.625", true)] + public void AssignsAndReplacesAnIndependentGlobalParameter(Kind kind, string first, string last, bool currency) + { + var parameter = new GlobalFixture(kind, Currency: currency); + string source = CreateSource(globalParameter: parameter); + byte[] hash = SHA256.HashData(File.ReadAllBytes(source)); + var result = RvtWriter.SetParameters(source, Output, [new(DefinitionId, DefinitionId, first), new(DefinitionId, DefinitionId, last)]); + Assert.Equal(1, result.RewrittenRecordCount); + Assert.Equal(hash, SHA256.HashData(File.ReadAllBytes(source))); + using var root = RootStorage.OpenRead(Output); + Assert.Equal(GlobalBody(parameter, last), ReadBody(root, DefinitionId)); + } + + [Fact] + public void AssignsAnIndependentGlobalForceUsingKilonewtons() + { + var parameter = new GlobalFixture(Kind.Number, SpecId: "autodesk.spec.aec.structural:force-2.0.0"); + string source = CreateSource(globalParameter: parameter); + RvtWriter.SetParameter(source, Output, DefinitionId, DefinitionId, "13.5 kN"); + using var root = RootStorage.OpenRead(Output); + Assert.Equal(GlobalBody(parameter, "44291.33858267716"), ReadBody(root, DefinitionId)); + } + + [Theory] + [InlineData("NaN", "invalid-parameter-value")] + [InlineData("1e309", "invalid-parameter-value")] + [InlineData("42 $", "invalid-parameter-value")] + [InlineData("17.25000000001", "unverified-parameter-storage")] + [InlineData(null, "unsupported-parameter-clear")] + public void RefusesInvalidIndependentCurrencyValuesAfterStagingAnAssignment(string? value, string code) + { + string source = CreateSource(globalParameter: new(Kind.Number, Currency: true)); + byte[] hash = SHA256.HashData(File.ReadAllBytes(source)); + var error = Assert.Throws(() => RvtWriter.SetParameters(source, Output, + [new(DefinitionId, DefinitionId, "17.25"), new(DefinitionId, DefinitionId, value)])); + Assert.Equal(code, error.Kind); + Assert.False(File.Exists(Output)); + Assert.Equal(hash, SHA256.HashData(File.ReadAllBytes(source))); + } + + [Theory] + [InlineData("1e-300", "0")] + [InlineData("1.7976931348623157e308", "-1.7976931348623157e308")] + public void RefusesIndependentCurrencyChangesThatRevitMaySuppress(string initial, string value) + { + string source = CreateSource(globalParameter: new(Kind.Number, InitialValue: initial, Currency: true)); + byte[] hash = SHA256.HashData(File.ReadAllBytes(source)); + var error = Assert.Throws(() => RvtWriter.SetParameters(source, Output, + [new(ProjectId, (int)BuiltInParameter.CLIENT_NAME, "Staged"), new(DefinitionId, DefinitionId, value)])); + Assert.Equal("unverified-parameter-storage", error.Kind); + Assert.False(File.Exists(Output)); + Assert.Equal(hash, SHA256.HashData(File.ReadAllBytes(source))); + } + + [Theory] + [InlineData("formula", "1", "read-only-parameter")] + [InlineData("reporting", "1", "read-only-parameter")] + [InlineData("consumer", "1", "unverified-parameter-storage")] + [InlineData("", null, "unsupported-parameter-clear")] + [InlineData("", "2", "invalid-parameter-value")] + public void RefusesTheWholeBatchForAnInvalidGlobalAssignment(string control, string? value, string code) + { + var parameter = new GlobalFixture(Kind.YesNo, Formula: control == "formula", Reporting: control == "reporting", + Consumer: control == "consumer"); + string source = CreateSource(globalParameter: parameter); + byte[] hash = SHA256.HashData(File.ReadAllBytes(source)); + var error = Assert.Throws(() => RvtWriter.SetParameters(source, Output, + [new(ProjectId, (int)BuiltInParameter.CLIENT_NAME, "Staged"), new(DefinitionId, DefinitionId, value)])); + Assert.Equal(code, error.Kind); + Assert.False(File.Exists(Output)); + Assert.Equal(hash, SHA256.HashData(File.ReadAllBytes(source))); + } + + [Theory] + [InlineData(false, false)] + [InlineData(true, true)] + [InlineData(false, true)] + public void RecalculatesGlobalFormulaChainsUsingTheCurrentBatchValues(bool currencyInput, bool currencyResult) + { + var number = new GlobalFixture(Kind.Number); + var input = number with { Currency = currencyInput }; + var graph = new GlobalFormulaFixture(CurrencyResult: currencyResult); + string source = CreateSource(globalParameter: input, globalFormulas: graph); + var write = RvtWriter.SetParameters(source, Output, [new(DefinitionId, DefinitionId, "3"), new(DefinitionId, DefinitionId, "5")]); + Assert.Equal(3, write.RewrittenRecordCount); + using var root = RootStorage.OpenRead(Output); + Assert.Equal(GlobalBody(input, "5"), ReadBody(root, DefinitionId)); + Assert.Equal(GlobalBody(number with { Currency = currencyResult }, "10", BindingId, new(3, DefinitionId, 2)), + ReadBody(root, BindingId)); + Assert.Equal(GlobalBody(number, "11", GlobalFormulaResultId, new(1, BindingId, 1)), ReadBody(root, GlobalFormulaResultId)); + } + + [Theory] + [InlineData("autodesk.spec.aec.structural:mass-2.0.0", "autodesk.spec.aec.structural:mass-2.0.0", "5 kg", "5", "7", "8")] + [InlineData("autodesk.spec.aec:slope-2.0.0", "autodesk.spec.aec:number-2.0.0", "5 %", "0.05", "2.05", "3.05")] + public void RecalculatesAFormulaChainWithMeasuredValues(string spec, string constantSpec, string requested, string input, + string result, string downstream) + { + var value = new GlobalFixture(Kind.Number, SpecId: spec); + string source = CreateSource(globalParameter: value, + globalFormulas: new(Operation: 1, SpecId: spec, ConstantSpecId: constantSpec)); + var write = RvtWriter.SetParameter(source, Output, DefinitionId, DefinitionId, requested); + Assert.Equal(3, write.RewrittenRecordCount); + + using var root = RootStorage.OpenRead(Output); + Assert.Equal(GlobalBody(value, input), ReadBody(root, DefinitionId)); + Assert.Equal(GlobalBody(value, result, BindingId, new(1, DefinitionId, 2, SpecId: constantSpec)), + ReadBody(root, BindingId)); + Assert.Equal(GlobalBody(value, downstream, GlobalFormulaResultId, new(1, BindingId, 1, SpecId: constantSpec)), + ReadBody(root, GlobalFormulaResultId)); + } + + [Theory] + [InlineData(false, "read-only-parameter")] + [InlineData(true, "unverified-parameter-storage")] + public void RejectsBatchesWithAWritableCurrencyInputAndAnInvalidFormulaEdit(bool stale, string code) + { + string source = CreateSource(globalParameter: new(Kind.Number, Currency: true), + globalFormulas: new(Stale: stale, CurrencyResult: true)); + byte[] hash = SHA256.HashData(File.ReadAllBytes(source)); + var error = Assert.Throws(() => RvtWriter.SetParameters(source, Output, + [new(DefinitionId, DefinitionId, "5"), new(BindingId, BindingId, "7")])); + Assert.Equal(code, error.Kind); + Assert.False(File.Exists(Output)); + Assert.Equal(hash, SHA256.HashData(File.ReadAllBytes(source))); + } + + [Fact] + public void GlobalFormulaChainUsesTheRoundedIntegerResult() + { + var number = new GlobalFixture(Kind.Number); + var integer = new GlobalFixture(Kind.Integer); + string source = CreateSource(globalParameter: number, globalFormulas: new(IntegerResult: true)); + var write = RvtWriter.SetParameter(source, Output, DefinitionId, DefinitionId, "-2"); + Assert.Equal(3, write.RewrittenRecordCount); + using var root = RootStorage.OpenRead(Output); + Assert.Equal(GlobalBody(integer, "-2", BindingId, new(3, DefinitionId, 1.25)), ReadBody(root, BindingId)); + Assert.Equal(GlobalBody(number, "-1", GlobalFormulaResultId, new(1, BindingId, 1)), ReadBody(root, GlobalFormulaResultId)); + } + + [Fact] + public void GlobalIfFormulaUsesTheChangedYesNoValue() + { + var integer = new GlobalFixture(Kind.Integer); + string source = CreateSource(globalParameter: new(Kind.YesNo), globalFormulas: new(Conditional: true)); + var write = RvtWriter.SetParameter(source, Output, DefinitionId, DefinitionId, "0"); + Assert.Equal(3, write.RewrittenRecordCount); + using var root = RootStorage.OpenRead(Output); + Assert.Equal(GlobalBody(integer, "3", BindingId, conditional: true), ReadBody(root, BindingId)); + Assert.Equal(GlobalBody(new(Kind.Number), "4", GlobalFormulaResultId, new(1, BindingId, 1)), ReadBody(root, GlobalFormulaResultId)); + } + + [Fact] + public void RecalculatesASquareRootAndItsDependent() + { + var number = new GlobalFixture(Kind.Number); + string source = CreateSource(globalParameter: number, globalFormulas: new(Function: 9)); + var write = RvtWriter.SetParameter(source, Output, DefinitionId, DefinitionId, "9"); + Assert.Equal(3, write.RewrittenRecordCount); + using var root = RootStorage.OpenRead(Output); + Assert.Equal(GlobalBody(number, "3", BindingId, function: 9), ReadBody(root, BindingId)); + Assert.Equal(GlobalBody(number, "4", GlobalFormulaResultId, new(1, BindingId, 1)), ReadBody(root, GlobalFormulaResultId)); + } + + [Theory] + [InlineData(3, 9, "-1", "9", 3)] + [InlineData(3, 7, "70", "0", 1)] + [InlineData(5, 0, "1e16", "3", 9)] + [InlineData(4, 0, "0", "3", 4)] + [InlineData(4, 0, "1e-9", "3", 4)] + public void PreservesTheStoredFormulaValueAndResumesCalculation(int operation, int function, string value, + string recoveredInput, double recoveredResult) + { + var number = new GlobalFixture(Kind.Number); + string source = CreateSource(globalParameter: number, globalFormulas: new(Operation: operation, Function: function)); + byte[] cached; + byte[] dependent; + using (var original = RootStorage.OpenRead(source)) + { + cached = ReadBody(original, BindingId); + dependent = ReadBody(original, GlobalFormulaResultId); + } + + var retained = RvtWriter.SetParameter(source, Output, DefinitionId, DefinitionId, value); + Assert.Equal(1, retained.RewrittenRecordCount); + using (var written = RootStorage.OpenRead(Output)) + { + Assert.Equal(GlobalBody(number, value), ReadBody(written, DefinitionId)); + Assert.Equal(cached, ReadBody(written, BindingId)); + Assert.Equal(dependent, ReadBody(written, GlobalFormulaResultId)); + } + + string recoveredPath = Path.Combine(_folder, "recovered.rvt"); + var recovered = RvtWriter.SetParameter(Output, recoveredPath, DefinitionId, DefinitionId, recoveredInput); + Assert.Equal(3, recovered.RewrittenRecordCount); + using var root = RootStorage.OpenRead(recoveredPath); + GlobalBinary? binary = function == 0 + ? new(operation, DefinitionId, operation == 4 ? 12 : 2, ConstantFirst: operation == 4) : null; + Assert.Equal(GlobalBody(number, recoveredResult.ToString(CultureInfo.InvariantCulture), BindingId, binary, function: function), + ReadBody(root, BindingId)); + Assert.Equal(GlobalBody(number, (recoveredResult + 1).ToString(CultureInfo.InvariantCulture), GlobalFormulaResultId, + new(1, BindingId, 1)), ReadBody(root, GlobalFormulaResultId)); + } + + [Fact] + public void RejectsABatchThatTriesToEditARetainedFormulaResult() + { + string source = CreateSource(globalParameter: new(Kind.Number), globalFormulas: new(Function: 9)); + byte[] hash = SHA256.HashData(File.ReadAllBytes(source)); + var error = Assert.Throws(() => RvtWriter.SetParameters(source, Output, + [new(DefinitionId, DefinitionId, "-1"), new(BindingId, BindingId, "5")])); + Assert.Equal("read-only-parameter", error.Kind); + Assert.False(File.Exists(Output)); + Assert.Equal(hash, SHA256.HashData(File.ReadAllBytes(source))); + } + + [Theory] + [InlineData(9, false, false, "3", "unverified-parameter-storage")] + [InlineData(3, true, false, "3", "unverified-parameter-storage")] + [InlineData(3, false, true, "3", "unverified-parameter-storage")] + [InlineData(3, false, false, "2.000000001", "unverified-parameter-storage")] + [InlineData(5, false, false, "1e-12", "unverified-parameter-storage")] + public void RefusesTheWholeBatchWhenAGlobalFormulaCannotBeRecalculated(int operation, bool stale, bool consumer, + string value, string code) + { + var graph = new GlobalFormulaFixture(operation, stale, consumer); + string source = CreateSource(globalParameter: new(Kind.Number), globalFormulas: graph); + byte[] hash = SHA256.HashData(File.ReadAllBytes(source)); + var error = Assert.Throws(() => RvtWriter.SetParameters(source, Output, + [new(ProjectId, (int)BuiltInParameter.CLIENT_NAME, "Staged"), new(DefinitionId, DefinitionId, value)])); + Assert.Equal(code, error.Kind); + Assert.False(File.Exists(Output)); + Assert.Equal(hash, SHA256.HashData(File.ReadAllBytes(source))); + } + + [Theory] + [InlineData(Kind.Text, "Restored text")] + [InlineData(Kind.Integer, "42")] + [InlineData(Kind.YesNo, "0")] + [InlineData(Kind.Number, "8.625")] + [InlineData(Kind.Number, "-8.625", true)] + [InlineData(Kind.Material, "81")] + public void BatchClearsSharedValueAndCanAssignItAgain(Kind kind, string newValue, bool currency = false) + { + var parameter = new UserParameter(kind, true, HideWhenNoValue: true, Currency: currency); + string source = CreateSource(wall: true, user: parameter); + var result = RvtWriter.SetParameters(source, Output, + [new(ProjectId, DefinitionId, null), new(ProjectId, DefinitionId, null)]); + Assert.Equal(1, result.RewrittenRecordCount); + using (var cleared = RootStorage.OpenRead(Output)) + Assert.Equal(UserBody(parameter, cleared: true), ReadBody(cleared)); + + string restored = Path.Combine(_folder, "restored.rvt"); + RvtWriter.SetParameters(source, restored, + [new(ProjectId, DefinitionId, null), new(ProjectId, DefinitionId, newValue)]); + using var root = RootStorage.OpenRead(restored); + Assert.Equal(UserBody(parameter, newValue), ReadBody(root)); + } + + [Theory] + [InlineData(false, false, "unsupported-parameter-clear")] + [InlineData(true, false, "unsupported-parameter-clear")] + [InlineData(true, true, "missing-element")] + public void BatchRefusalLeavesNoOutputAndPreservesTheInput(bool shared, bool hide, string code) + { + string source = CreateSource(wall: true, user: new(Kind.Text, shared, HideWhenNoValue: hide)); + byte[] hash = SHA256.HashData(File.ReadAllBytes(source)); + var error = Assert.Throws(() => RvtWriter.SetParameters(source, Output, + [new(ProjectId, DefinitionId, "Staged"), new(hide ? 999 : ProjectId, DefinitionId, null)])); + Assert.Equal(code, error.Kind); + Assert.False(File.Exists(Output)); + Assert.Equal(hash, SHA256.HashData(File.ReadAllBytes(source))); + } + + private static byte[] ReadBody(RootStorage root, ulong elementId = ProjectId, int release = 2022) + { + using var stream = root.OpenStorage("Partitions").OpenStream("0"); + byte[] raw = new byte[stream.Length]; + stream.ReadExactly(raw); + var records = new List(); + Assert.True(PartitionFraming.Walk(raw, Tags(release), 4, record => + { + if (record.Block != 0 || record.Channel != 102 || record.Owner != elementId) + return; + records.Add(record.Body.ToArray()); + }, out var failure, out _), failure); + return Assert.Single(records); + } + + [Theory] + [InlineData(BuiltInParameter.HOST_AREA_COMPUTED, "read-only-parameter")] + [InlineData(BuiltInParameter.ALL_MODEL_TYPE_NAME, "unsupported-parameter")] + public void CliRefusesUnverifiedParameters(BuiltInParameter parameter, string errorCode) + { + using var error = new StringWriter(); + int exit = SetParameterCommand.Run([CreateSource(), Output, "70", parameter.ToString(), "123"], TextWriter.Null, error); + Assert.Equal(SaveAsCommand.Refused, exit); + Assert.Contains(errorCode, error.ToString()); + Assert.False(File.Exists(Output)); + } + + [Fact] + public void RefusesANegativeIdOutsideTheBuiltInRange() + { + long id = (int)BuiltInParameter.CLIENT_NAME - (1L << 32); + var error = Assert.Throws(() => RvtWriter.SetParameter(CreateSource(), Output, ProjectId, id, "New")); + Assert.Equal("unsupported-parameter", error.Kind); + Assert.False(File.Exists(Output)); + } + + [Theory] + [InlineData(71, "Owner", false, "missing-element")] + [InlineData(ProjectId, "stale", false, "unverified-parameter-storage")] + [InlineData(ProjectId, "Owner", true, "unverified-parameter-storage")] + public void RefusesAmbiguousStorage(int id, string xmlValue, bool duplicate, string errorCode) + { + var exception = Assert.Throws(() => + RvtWriter.SetParameter(CreateSource(xmlValue, duplicate), Output, id, BuiltInParameter.CLIENT_NAME, "New")); + Assert.Equal(errorCode, exception.Kind); + Assert.False(File.Exists(Output)); + } + + [Theory] + [InlineData(false, false, null)] + [InlineData(true, false, "group membership")] + [InlineData(false, true, "global parameter")] + public void WritesWallCommentsOnlyWithoutUnverifiedDependencies(bool grouped, bool global, string? reason) + { + string source = CreateSource(wall: true, grouped: grouped, global: global); + if (reason is null) + { + var result = RvtWriter.SetParameter(source, Output, ProjectId, BuiltInParameter.ALL_MODEL_INSTANCE_COMMENTS, "New"); + Assert.Equal(1, result.ReplacedStreamCount); + Assert.Equal(1, result.RewrittenRecordCount); + return; + } + + var refused = Assert.Throws(() => + RvtWriter.SetParameter(source, Output, ProjectId, BuiltInParameter.ALL_MODEL_INSTANCE_COMMENTS, "New")); + Assert.Equal("unverified-parameter-storage", refused.Kind); + Assert.Contains(reason, refused.Message); + Assert.False(File.Exists(Output)); + } + + [Fact] + public void WritesAnUnassociatedParameterOnAWallWithAGlobalAssociation() + { + var association = new ProjectAssociation(BuiltInParameter.WALL_BASE_OFFSET); + string source = CreateSource(wall: true, globalParameter: new(Kind.Number), association: association); + var result = RvtWriter.SetParameter(source, Output, ProjectId, BuiltInParameter.ALL_MODEL_INSTANCE_COMMENTS, "New"); + + Assert.Equal(1, result.RewrittenRecordCount); + using var root = RootStorage.OpenRead(Output); + using var original = RootStorage.OpenRead(source); + Assert.Equal(Body("New", wall: true, association: association), ReadBody(root)); + Assert.Equal(ReadBody(original, DefinitionId), ReadBody(root, DefinitionId)); + } + + [Fact] + public void RefusesTheEntireBatchWhenOneRequestedParameterIsGloballyDriven() + { + const BuiltInParameter property = BuiltInParameter.ALL_MODEL_MARK; + var association = new ProjectAssociation(property); + string source = CreateSource(wall: true, globalParameter: new(Kind.Text), association: association); + var before = SHA256.HashData(File.ReadAllBytes(source)); + var refused = Assert.Throws(() => RvtWriter.SetParameters(source, Output, + [new(ProjectId, (int)BuiltInParameter.ALL_MODEL_INSTANCE_COMMENTS, "Staged"), new(ProjectId, (int)property, "Rejected")])); + + Assert.Equal("read-only-parameter", refused.Kind); + Assert.False(File.Exists(Output)); + Assert.Equal(before, SHA256.HashData(File.ReadAllBytes(source))); + } + + [Fact] + public void RefusesAnOrdinaryWriteWhenTheElementHasAnUnverifiedAssociationLayout() + { + var association = new ProjectAssociation(BuiltInParameter.WALL_BASE_OFFSET, Malformed: true); + string source = CreateSource(wall: true, globalParameter: new(Kind.Number), association: association); + var before = SHA256.HashData(File.ReadAllBytes(source)); + var refused = Assert.Throws(() => + RvtWriter.SetParameter(source, Output, ProjectId, BuiltInParameter.ALL_MODEL_INSTANCE_COMMENTS, "Rejected")); + + Assert.Equal("unverified-parameter-storage", refused.Kind); + Assert.False(File.Exists(Output)); + Assert.Equal(before, SHA256.HashData(File.ReadAllBytes(source))); + } + + [Theory] + [InlineData("Replacement")] + [InlineData("")] + public void WritesAGlobalValueAndItsControlledProjectPropertyInOrder(string finalValue) + { + var association = new ProjectAssociation((BuiltInParameter)DefinitionId, GlobalId: PropertyGlobalId); + var user = new UserParameter(Kind.Text, Shared: true); + var global = new GlobalFixture(Kind.Text, InitialValue: "Old"); + string source = CreateSource(wall: true, user: user, globalParameter: global, association: association); + var result = RvtWriter.SetParameters(source, Output, + [new(PropertyGlobalId, PropertyGlobalId, "Intermediate"), new(PropertyGlobalId, PropertyGlobalId, finalValue)]); + + Assert.Equal(2, result.RewrittenRecordCount); + using var output = RootStorage.OpenRead(Output); + Assert.Equal(UserBody(user, finalValue, association: association), ReadBody(output)); + Assert.Equal(GlobalBody(global, finalValue, PropertyGlobalId), ReadBody(output, PropertyGlobalId)); + } + + [Theory] + [InlineData("", "First")] + [InlineData("Old", "Replacement")] + [InlineData("Old", "")] + public void WritesAGlobalTextValueAndItsControlledWallComments(string initial, string value) + { + var association = new ProjectAssociation(BuiltInParameter.ALL_MODEL_INSTANCE_COMMENTS); + var global = new GlobalFixture(Kind.Text, InitialValue: initial); + string source = CreateSource(xmlValue: initial, wall: true, globalParameter: global, association: association); + var result = RvtWriter.SetParameters(source, Output, + [new(DefinitionId, DefinitionId, "Intermediate"), new(DefinitionId, DefinitionId, value)]); + + Assert.Equal(2, result.RewrittenRecordCount); + using var output = RootStorage.OpenRead(Output); + Assert.Equal(Body(value, wall: true, association: association), ReadBody(output)); + Assert.Equal(GlobalBody(global, value), ReadBody(output, DefinitionId)); + } + + [Theory] + [InlineData(BuiltInParameter.ALL_MODEL_INSTANCE_COMMENTS, Kind.Text, "Different", "unverified-parameter-storage")] + [InlineData(BuiltInParameter.ALL_MODEL_INSTANCE_COMMENTS, Kind.Number, "0", "unverified-parameter-storage")] + [InlineData(BuiltInParameter.ALL_MODEL_TYPE_COMMENTS, Kind.Text, "Owner", "unsupported-parameter-owner")] + [InlineData(BuiltInParameter.ALL_MODEL_MARK, Kind.Text, "Owner", "unverified-parameter-storage")] + [InlineData(BuiltInParameter.ALL_MODEL_URL, Kind.Text, "Owner", "unverified-parameter-storage")] + public void RefusesAnUnverifiedBuiltInAssociation(BuiltInParameter parameter, Kind kind, string initial, string error) + { + var association = new ProjectAssociation(parameter); + string source = CreateSource(wall: true, globalParameter: new(kind, InitialValue: initial), association: association); + var before = SHA256.HashData(File.ReadAllBytes(source)); + var refused = Assert.Throws(() => RvtWriter.SetParameter(source, Output, + DefinitionId, DefinitionId, kind == Kind.Text ? "New" : "2")); + + Assert.Equal(error, refused.Kind); + Assert.False(File.Exists(Output)); + Assert.Equal(before, SHA256.HashData(File.ReadAllBytes(source))); + } + + [Theory] + [InlineData(2020)] + [InlineData(2021)] + public void RefusesAGlobalAssociationToInstanceCommentsInOlderFormats(int release) + { + var association = new ProjectAssociation(BuiltInParameter.ALL_MODEL_INSTANCE_COMMENTS); + string source = CreateSource(wall: true, release: release, globalParameter: new(Kind.Text, InitialValue: "Owner"), association: association); + var before = SHA256.HashData(File.ReadAllBytes(source)); + var refused = Assert.Throws(() => RvtWriter.SetParameter(source, Output, DefinitionId, DefinitionId, "New")); + + Assert.Equal("unverified-parameter-storage", refused.Kind); + Assert.False(File.Exists(Output)); + Assert.Equal(before, SHA256.HashData(File.ReadAllBytes(source))); + } + + [Theory] + [InlineData(BuiltInCategory.OST_GenericModel)] + [InlineData(BuiltInCategory.OST_Doors)] + [InlineData(BuiltInCategory.OST_Windows)] + [InlineData(BuiltInCategory.OST_Furniture)] + public void WritesAGlobalCurrencyValueAndItsControlledFamilyCost(BuiltInCategory category) + { + var global = new GlobalFixture(Kind.Number, Currency: true, InitialValue: "17.25"); + var association = new ProjectAssociation(BuiltInParameter.ALL_MODEL_COST, GlobalId: PropertyGlobalId); + var family = new FamilyFixture(Category: category, OnlyPrimary: true, TypedCost: 17.25); + string source = CreateSource(family: family, globalParameter: global, association: association); + var result = RvtWriter.SetParameters(source, Output, + [new(PropertyGlobalId, PropertyGlobalId, "0"), new(PropertyGlobalId, PropertyGlobalId, "58.625")]); + + Assert.Equal(2, result.RewrittenRecordCount); + using var output = RootStorage.OpenRead(Output); + Assert.Equal(SymbolBody(ProjectId, -1, "Old", association: association, associationSlot: true, typedCost: 58.625), ReadBody(output)); + Assert.Equal(GlobalBody(global, "58.625", PropertyGlobalId), ReadBody(output, PropertyGlobalId)); + } + + [Theory] + [InlineData(BuiltInCategory.OST_Doors, BuiltInParameter.FIRE_RATING, "60 min", "90 min")] + [InlineData(BuiltInCategory.OST_Windows, BuiltInParameter.ALL_MODEL_MANUFACTURER, "", "New manufacturer")] + [InlineData(BuiltInCategory.OST_Furniture, BuiltInParameter.ALL_MODEL_MODEL, "Old model", "")] + [InlineData(BuiltInCategory.OST_Furniture, BuiltInParameter.ALL_MODEL_COST, "17.25", "58.625")] + public void WritesAnIdentityValueInTheNamedFamilyStoreThroughAGlobal( + BuiltInCategory category, BuiltInParameter parameter, string initial, string replacement) + { + bool cost = parameter == BuiltInParameter.ALL_MODEL_COST; + var global = new GlobalFixture(cost ? Kind.Number : Kind.Text, InitialValue: initial, Currency: cost); + var association = new ProjectAssociation(parameter, GlobalId: PropertyGlobalId); + var identity = new StoredIdentity(parameter, initial); + var family = new FamilyFixture(Category: category, OnlyPrimary: true, Identity: identity); + string source = CreateSource(family: family, globalParameter: global, association: association); + var result = RvtWriter.SetParameter(source, Output, PropertyGlobalId, PropertyGlobalId, replacement); + + Assert.Equal(2, result.RewrittenRecordCount); + using var output = RootStorage.OpenRead(Output); + using var original = RootStorage.OpenRead(source); + Assert.Equal(SymbolBody(ProjectId, -1, "Old", identity: identity with { Value = replacement }, + association: association, associationSlot: true), ReadBody(output)); + Assert.Equal(ReadBody(original, FamilyId), ReadBody(output, FamilyId)); + Assert.Equal(GlobalBody(global, replacement, PropertyGlobalId), ReadBody(output, PropertyGlobalId)); + } + + [Theory] + [InlineData(false, "Different")] + [InlineData(true, "Stored")] + public void RefusesAStaleOrAmbiguousIdentityValueControlledByAGlobal(bool competingTypedCopy, string initial) + { + const BuiltInParameter parameter = BuiltInParameter.ALL_MODEL_TYPE_COMMENTS; + var identity = new StoredIdentity(parameter, "Stored", competingTypedCopy); + var family = new FamilyFixture(Category: BuiltInCategory.OST_Furniture, OnlyPrimary: true, Identity: identity); + var association = new ProjectAssociation(parameter, GlobalId: PropertyGlobalId); + string source = CreateSource(family: family, globalParameter: new(Kind.Text, InitialValue: initial), association: association); + var before = SHA256.HashData(File.ReadAllBytes(source)); + var refused = Assert.Throws(() => + RvtWriter.SetParameter(source, Output, PropertyGlobalId, PropertyGlobalId, "Replacement")); + + Assert.Equal("unverified-parameter-storage", refused.Kind); + Assert.False(File.Exists(Output)); + Assert.Equal(before, SHA256.HashData(File.ReadAllBytes(source))); + } + + [Theory] + [InlineData(false, false)] + [InlineData(true, false)] + [InlineData(false, true)] + public void AGlobalIdentityAssignmentChangesOnlyTheAssociatedSymbols(bool derived, bool both) + { + const BuiltInParameter parameter = BuiltInParameter.ALL_MODEL_TYPE_COMMENTS; + var identity = new StoredIdentity(parameter, "Stored"); + var association = new ProjectAssociation(parameter, GlobalId: PropertyGlobalId, Derived: derived, PrimaryAndDerived: both); + var family = new FamilyFixture(Category: BuiltInCategory.OST_GenericModel, Identity: identity, DerivedType: derived || both); + string source = CreateSource(family: family, globalParameter: new(Kind.Text, InitialValue: identity.Value), association: association); + var result = RvtWriter.SetParameter(source, Output, PropertyGlobalId, PropertyGlobalId, "New"); + + Assert.Equal(both ? 3 : 2, result.RewrittenRecordCount); + using var output = RootStorage.OpenRead(Output); + using var original = RootStorage.OpenRead(source); + int unchanged = derived ? ProjectId : DerivedId; + int target = derived ? DerivedId : ProjectId; + if (both) + Assert.Equal(SymbolBody(DerivedId, ProjectId, "Old", identity: identity with { Value = "New" }, + association: association, associationSlot: true), ReadBody(output, DerivedId)); + else + Assert.Equal(ReadBody(original, (ulong)unchanged), ReadBody(output, (ulong)unchanged)); + Assert.Equal(SymbolBody(target, derived ? ProjectId : -1, "Old", identity: identity with { Value = "New" }, + association: association, associationSlot: true), ReadBody(output, (ulong)target)); + } + + [Theory] + [InlineData(false, "unverified-parameter-storage")] + [InlineData(true, "read-only-parameter")] + public void RefusesUnsafeGlobalCostBatches(bool currency, string error) + { + var global = new GlobalFixture(Kind.Number, Currency: currency, InitialValue: "17.25"); + var association = new ProjectAssociation(BuiltInParameter.ALL_MODEL_COST, GlobalId: PropertyGlobalId); + var family = new FamilyFixture(Category: BuiltInCategory.OST_GenericModel, OnlyPrimary: true, TypedCost: 17.25); + string source = CreateSource(family: family, globalParameter: global, association: association); + var before = SHA256.HashData(File.ReadAllBytes(source)); + var refused = Assert.Throws(() => RvtWriter.SetParameters(source, Output, + [new(PropertyGlobalId, PropertyGlobalId, "58.625"), new(ProjectId, (int)BuiltInParameter.ALL_MODEL_COST, "12")])); + + Assert.Equal(error, refused.Kind); + Assert.False(File.Exists(Output)); + Assert.Equal(before, SHA256.HashData(File.ReadAllBytes(source))); + } + + [Fact] + public void RefusesAGlobalWriteWhenTheControlledPropertyDisagreesWithTheSavedValue() + { + var association = new ProjectAssociation((BuiltInParameter)DefinitionId, GlobalId: PropertyGlobalId); + var global = new GlobalFixture(Kind.Text, InitialValue: "Different"); + string source = CreateSource(wall: true, user: new(Kind.Text, Shared: true), globalParameter: global, association: association); + var before = SHA256.HashData(File.ReadAllBytes(source)); + var refused = Assert.Throws(() => RvtWriter.SetParameter(source, Output, PropertyGlobalId, PropertyGlobalId, "New")); + + Assert.Equal("unverified-parameter-storage", refused.Kind); + Assert.Contains("controlled property disagrees", refused.Message); + Assert.False(File.Exists(Output)); + Assert.Equal(before, SHA256.HashData(File.ReadAllBytes(source))); + } + + [Theory] + [InlineData(OwnerKind.Wall, 1)] + [InlineData(OwnerKind.WallType, 2)] + [InlineData(OwnerKind.Room, 1)] + public void AGlobalCurrencyValueUpdatesAVerifiedSharedProjectParameter(OwnerKind owner, int binding) + { + var parameter = new UserParameter(Kind.Number, true, Binding: binding, Owner: owner, Currency: true); + var association = new ProjectAssociation((BuiltInParameter)DefinitionId, GlobalId: PropertyGlobalId); + var global = new GlobalFixture(Kind.Number, InitialValue: "1.5", Currency: true); + string source = CreateSource(wall: true, user: parameter, globalParameter: global, association: association); + var result = RvtWriter.SetParameters(source, Output, + [new(PropertyGlobalId, PropertyGlobalId, "-82.625"), new(PropertyGlobalId, PropertyGlobalId, "14.25")]); + + Assert.Equal(2, result.RewrittenRecordCount); + using var output = RootStorage.OpenRead(Output); + Assert.Equal(UserBody(parameter, "14.25", association: association), ReadBody(output)); + Assert.Equal(GlobalBody(global, "14.25", PropertyGlobalId), ReadBody(output, PropertyGlobalId)); + } + + [Fact] + public void RefusesACurrencyAssociationToANumberDefinition() + { + var association = new ProjectAssociation((BuiltInParameter)DefinitionId, GlobalId: PropertyGlobalId); + string source = CreateSource(wall: true, user: new(Kind.Number, true), association: association, + globalParameter: new(Kind.Number, InitialValue: "1.5", Currency: true)); + var error = Assert.Throws(() => RvtWriter.SetParameter(source, Output, + PropertyGlobalId, PropertyGlobalId, "14.25")); + Assert.Equal("unverified-parameter-storage", error.Kind); + Assert.False(File.Exists(Output)); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public void ASlopeGlobalRequiresMatchingStorageOnItsAssociatedParameter(bool matchingSpec) + { + const string slope = "autodesk.spec.aec:slope-2.0.0"; + var parameter = new UserParameter(Kind.Number, true, + DefinitionSpec: matchingSpec ? (UnitType.UT_Slope, slope) : null); + var association = new ProjectAssociation((BuiltInParameter)DefinitionId, GlobalId: PropertyGlobalId); + var global = new GlobalFixture(Kind.Number, InitialValue: "1.5", SpecId: slope); + string source = CreateSource(wall: true, user: parameter, association: association, globalParameter: global); + if (!matchingSpec) + { + byte[] before = File.ReadAllBytes(source); + var error = Assert.Throws(() => RvtWriter.SetParameters(source, Output, + [new(ProjectId, (int)BuiltInParameter.ALL_MODEL_INSTANCE_COMMENTS, "Staged"), new(PropertyGlobalId, PropertyGlobalId, "25 %")])); + Assert.Equal("unverified-parameter-storage", error.Kind); + Assert.Contains("different types", error.Message); + Assert.False(File.Exists(Output)); + Assert.Equal(before, File.ReadAllBytes(source)); + return; + } + + RvtWriter.SetParameter(source, Output, PropertyGlobalId, PropertyGlobalId, "25 %"); + using var root = RootStorage.OpenRead(Output); + Assert.Equal(UserBody(parameter, "0.25", association: association), ReadBody(root)); + Assert.Equal(GlobalBody(global, "0.25", PropertyGlobalId), ReadBody(root, PropertyGlobalId)); + } + + [Fact] + public void AGlobalFamilyInstanceInputRecalculatesItsLocalResult() + { + var association = new ProjectAssociation((BuiltInParameter)DefinitionId, GlobalId: PropertyGlobalId); + var global = new GlobalFixture(Kind.Text, InitialValue: "Old"); + string source = CreateSource(family: new FamilyFixture(Instance: true, Formula: true), globalParameter: global, association: association); + var result = RvtWriter.SetParameter(source, Output, PropertyGlobalId, PropertyGlobalId, "New"); + + Assert.Equal(2, result.RewrittenRecordCount); + using var output = RootStorage.OpenRead(Output); + using var original = RootStorage.OpenRead(source); + Assert.Equal(InstanceBody("New", formulaResult: "New", association: association), ReadBody(output)); + Assert.Equal(ReadBody(original, MasterId), ReadBody(output, MasterId)); + Assert.Equal(ReadBody(original, DerivedId), ReadBody(output, DerivedId)); + } + + [Fact] + public void AGlobalFamilyTypeInputRecalculatesThePrimaryTypeWithoutRewritingDerivedCopies() + { + var association = new ProjectAssociation((BuiltInParameter)DefinitionId, GlobalId: PropertyGlobalId); + var global = new GlobalFixture(Kind.Text, InitialValue: "Old"); + string source = CreateSource(family: new FamilyFixture(Formula: true), globalParameter: global, association: association); + var result = RvtWriter.SetParameter(source, Output, PropertyGlobalId, PropertyGlobalId, "New"); + + Assert.Equal(2, result.RewrittenRecordCount); + using var output = RootStorage.OpenRead(Output); + using var original = RootStorage.OpenRead(source); + Assert.Equal(SymbolBody(ProjectId, -1, "New", formula: true, association: association, associationSlot: true), ReadBody(output)); + Assert.Equal(ReadBody(original, DerivedId), ReadBody(output, DerivedId)); + } + + [Fact] + public void RefusesAGlobalWriteWhenTheControlledFamilyCacheIsStale() + { + var association = new ProjectAssociation((BuiltInParameter)DefinitionId, GlobalId: PropertyGlobalId); + string source = CreateSource(family: new FamilyFixture(Instance: true, Formula: true), + globalParameter: new(Kind.Text, InitialValue: "Stale"), association: association); + var before = SHA256.HashData(File.ReadAllBytes(source)); + var refused = Assert.Throws(() => + RvtWriter.SetParameter(source, Output, PropertyGlobalId, PropertyGlobalId, "New")); + + Assert.Equal("unverified-parameter-storage", refused.Kind); + Assert.Contains("controlled family property disagrees", refused.Message); + Assert.False(File.Exists(Output)); + Assert.Equal(before, SHA256.HashData(File.ReadAllBytes(source))); + } + + [Theory] + [InlineData(BuiltInParameter.ALL_MODEL_MARK, null, "First")] + [InlineData(BuiltInParameter.ALL_MODEL_MARK, "Old", "")] + [InlineData(BuiltInParameter.ALL_MODEL_TYPE_MARK, null, "")] + [InlineData(BuiltInParameter.ALL_MODEL_TYPE_MARK, "Old", "Replacement")] + [InlineData(BuiltInParameter.ALL_MODEL_INSTANCE_COMMENTS, null, "")] + [InlineData(BuiltInParameter.ALL_MODEL_TYPE_COMMENTS, null, "")] + [InlineData(BuiltInParameter.ALL_MODEL_DESCRIPTION, "Existing", "Description")] + [InlineData(BuiltInParameter.ALL_MODEL_MANUFACTURER, null, "Manufacturer")] + [InlineData(BuiltInParameter.ALL_MODEL_MODEL, "Existing", "Model")] + [InlineData(BuiltInParameter.ALL_MODEL_URL, null, "https://example.invalid/")] + [InlineData(BuiltInParameter.FIRE_RATING, "1 h", "2 h")] + [InlineData(BuiltInParameter.ALL_MODEL_COST, null, "58.625")] + [InlineData(BuiltInParameter.ALL_MODEL_COST, "17.25", "58.625")] + public void WritesBuiltInIdentityParameters(BuiltInParameter parameter, string? before, string value) + { + string source = CreateSource(builtIn: parameter, builtInValue: before); + var result = RvtWriter.SetParameters(source, Output, [new(ProjectId, (int)parameter, value)]); + Assert.Equal(1, result.RewrittenRecordCount); + using var root = RootStorage.OpenRead(Output); + Assert.Equal(BuiltInBody(parameter, value), ReadBody(root)); + } + + [Fact] + public void RejectsAWholeMarkBatchForAnInapplicableOwner() + { + string source = CreateSource(builtIn: BuiltInParameter.ALL_MODEL_MARK); + byte[] original = SHA256.HashData(File.ReadAllBytes(source)); + var refused = Assert.Throws(() => RvtWriter.SetParameters(source, Output, + [new(ProjectId, (int)BuiltInParameter.ALL_MODEL_MARK, "First"), + new(ProjectId, (int)BuiltInParameter.ALL_MODEL_TYPE_MARK, "Wrong owner")])); + Assert.Equal("unsupported-parameter-owner", refused.Kind); + Assert.False(File.Exists(Output)); + Assert.Equal(original, SHA256.HashData(File.ReadAllBytes(source))); + } + + [Theory] + [InlineData("12.75 ft", "unsupported-parameter")] + [InlineData(null, "unsupported-parameter")] + public void RefusesAWholeBatchWhenWallHeightCannotBeWritten(string? height, string errorCode) + { + string source = CreateSource(builtIn: BuiltInParameter.ALL_MODEL_MARK); + byte[] original = SHA256.HashData(File.ReadAllBytes(source)); + var refused = Assert.Throws(() => RvtWriter.SetParameters(source, Output, + [new(ProjectId, (int)BuiltInParameter.ALL_MODEL_MARK, "New mark"), + new(ProjectId, (int)BuiltInParameter.WALL_USER_HEIGHT_PARAM, height)])); + Assert.Equal(errorCode, refused.Kind); + Assert.False(File.Exists(Output)); + Assert.Equal(original, SHA256.HashData(File.ReadAllBytes(source))); + } + + [Theory] + [InlineData("NaN")] + [InlineData("1,250")] + [InlineData("100 USD")] + public void RejectsAWholeBatchForInvalidCost(string cost) + { + string source = CreateSource(builtIn: BuiltInParameter.ALL_MODEL_COST); + byte[] original = SHA256.HashData(File.ReadAllBytes(source)); + var refused = Assert.Throws(() => RvtWriter.SetParameters(source, Output, + [new(ProjectId, (int)BuiltInParameter.ALL_MODEL_TYPE_COMMENTS, "Staged"), + new(ProjectId, (int)BuiltInParameter.ALL_MODEL_COST, cost)])); + Assert.Equal("invalid-parameter-value", refused.Kind); + Assert.False(File.Exists(Output)); + Assert.Equal(original, SHA256.HashData(File.ReadAllBytes(source))); + } + + [Theory] + [InlineData(true, BuiltInParameter.ALL_MODEL_INSTANCE_COMMENTS)] + [InlineData(false, BuiltInParameter.ALL_MODEL_TYPE_COMMENTS)] + public void RefusesBuiltInIdentityOnAnUnverifiedFamilyCategory(bool instance, BuiltInParameter parameter) + { + string source = CreateSource(family: new(Instance: instance, Category: BuiltInCategory.OST_PlumbingFixtures)); + var refused = Assert.Throws(() => + RvtWriter.SetParameter(source, Output, ProjectId, parameter, "Comment")); + Assert.Equal("unverified-parameter-storage", refused.Kind); + Assert.False(File.Exists(Output)); + } + + [Theory] + [InlineData(BuiltInCategory.OST_Doors, null, "Первый комментарий")] + [InlineData(BuiltInCategory.OST_Windows, "Existing", "Replacement")] + [InlineData(BuiltInCategory.OST_Furniture, null, "")] + public void WritesInstanceCommentsOnVerifiedFamilyCategories(BuiltInCategory category, string? before, string value) + { + string source = CreateSource(family: new(Instance: true, Category: category, InstanceComment: before)); + var result = RvtWriter.SetParameter(source, Output, ProjectId, BuiltInParameter.ALL_MODEL_INSTANCE_COMMENTS, value); + Assert.Equal(1, result.RewrittenRecordCount); + + using var root = RootStorage.OpenRead(Output); + Assert.Equal(InstanceBody("Old", BindStore.Value, value, (int)BuiltInParameter.ALL_MODEL_INSTANCE_COMMENTS), ReadBody(root)); + } + + [Theory] + [InlineData(Kind.Text, "Text with new length & unicode ✓", false)] + [InlineData(Kind.Text, "Old", true)] + [InlineData(Kind.Integer, "-17", true)] + [InlineData(Kind.YesNo, "0", true)] + [InlineData(Kind.Number, "-2.25", true)] + [InlineData(Kind.Number, "-2.25", true, 2020)] + [InlineData(Kind.Number, "-2.25", true, 2021)] + public void WritesUserParameterByDefinitionId(Kind kind, string value, bool shared, int release = 2022) + { + var parameter = new UserParameter(kind, shared); + string source = CreateSource(wall: true, user: parameter, release: release); + using var error = new StringWriter(); + int exit = SetParameterCommand.Run([source, Output, "70", "71", value], TextWriter.Null, error); + Assert.True(exit == RvtExitCodes.Success, error.ToString()); + using var root = RootStorage.OpenRead(Output); + Assert.Equal(UserBody(parameter, value), ReadBody(root, release: release)); + } + + [Theory] + [InlineData(2020)] + [InlineData(2021)] + public void RequiresAMatchingUnitForMeasurements(int release) + { + string source = CreateSource(wall: true, user: new(Kind.Number, true, Measured: true), release: release); + var error = Assert.Throws(() => RvtWriter.SetParameter(source, Output, ProjectId, DefinitionId, "2 m2")); + Assert.Equal("invalid-parameter-value", error.Kind); + Assert.False(File.Exists(Output)); + } + + [Theory] + [InlineData(2020)] + [InlineData(2021)] + [InlineData(2022)] + public void ConvertsAnExplicitLengthToInternalFeet(int release) + { + var parameter = new UserParameter(Kind.Number, true, Measured: true); + string source = CreateSource(wall: true, user: parameter, release: release); + RvtWriter.SetParameter(source, Output, ProjectId, DefinitionId, "609.6 mm"); + using var root = RootStorage.OpenRead(Output); + Assert.Equal(UserBody(parameter, "2"), ReadBody(root, release: release)); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void SetsAMaterialInTheRootReferenceStore(bool first) + { + var parameter = new UserParameter(Kind.Material, true, Store: first ? StoreState.NullPointer : StoreState.Value); + string source = CreateSource(wall: true, user: parameter); + RvtWriter.SetParameter(source, Output, ProjectId, DefinitionId, TargetMaterialId.ToString(CultureInfo.InvariantCulture)); + using var root = RootStorage.OpenRead(Output); + Assert.Equal(UserBody(parameter, TargetMaterialId.ToString(CultureInfo.InvariantCulture)), ReadBody(root)); + } + + [Theory] + [InlineData("70")] + [InlineData("999")] + [InlineData("-1")] + public void RefusesReferencesToAnythingOtherThanAnExistingMaterial(string target) + { + string source = CreateSource(wall: true, user: new(Kind.Material, true)); + var error = Assert.Throws(() => RvtWriter.SetParameter(source, Output, ProjectId, DefinitionId, target)); + Assert.Equal("invalid-parameter-value", error.Kind); + Assert.False(File.Exists(Output)); + } + + [Fact] + public void WritesTheRightNumberWhenTheSchemaStoresTheIdFirst() + { + var parameter = new UserParameter(Kind.Number, true, IdFirst: true); + string source = CreateSource(wall: true, user: parameter); + RvtWriter.SetParameter(source, Output, ProjectId, DefinitionId, "8.625"); + using var root = RootStorage.OpenRead(Output); + Assert.Equal(UserBody(parameter, "8.625"), ReadBody(root)); + } + + [Theory] + [InlineData(Kind.Text, "First text ✓", false, false)] + [InlineData(Kind.Integer, "-17", false, false)] + [InlineData(Kind.YesNo, "1", true, false)] + [InlineData(Kind.Number, "8.625", true, false)] + [InlineData(Kind.Number, "8.625", true, true)] + public void AssignsFirstValueWithOrWithoutAnExistingStore(Kind kind, string value, bool populated, bool idFirst) + { + var parameter = new UserParameter(kind, true, IdFirst: idFirst, Store: populated ? StoreState.Neighbour : StoreState.NullPointer); + string source = CreateSource(wall: true, user: parameter); + var result = RvtWriter.SetParameter(source, Output, ProjectId, DefinitionId, value); + Assert.Equal(1, result.RewrittenRecordCount); + using var root = RootStorage.OpenRead(Output); + Assert.Equal(UserBody(parameter, value), ReadBody(root)); + } + + [Theory] + [InlineData(2020, OwnerKind.Wall, 1, "0")] + [InlineData(2022, OwnerKind.WallType, 2, "1e-300")] + [InlineData(2022, OwnerKind.Room, 1, "0")] + public void AssignsAnExplicitFirstCurrencyValue(int release, OwnerKind owner, int binding, string value) + { + var parameter = new UserParameter(Kind.Number, true, Binding: binding, Store: StoreState.NullPointer, + Owner: owner, Currency: true); + string source = CreateSource(wall: true, user: parameter, release: release); + RvtWriter.SetParameter(source, Output, ProjectId, DefinitionId, value); + using var output = RootStorage.OpenRead(Output); + Assert.Equal(UserBody(parameter, value), ReadBody(output, release: release)); + } + + [Theory] + [InlineData(2020, UnitType.UT_Force, "autodesk.spec.aec.structural:force-2.0.0", "13.5 kN", "44291.33858267716")] + [InlineData(2022, UnitType.UT_Mass, "autodesk.spec.aec.structural:mass-2.0.0", "12.5 kg", "12.5")] + [InlineData(2022, UnitType.UT_MassDensity, "autodesk.spec.aec:massDensity-2.0.0", "14.5 kg/m³", "0.4105942755840001")] + [InlineData(2022, UnitType.UT_Speed, "autodesk.spec.aec:speed-2.0.0", "15.5 m/s", "50.85301837270341")] + [InlineData(2020, UnitType.UT_Slope, "autodesk.spec.aec:slope-2.0.0", "16.5 %", "0.165")] + [InlineData(2020, UnitType.UT_TimeInterval, "autodesk.spec.aec:time-2.0.0", "17.5 s", "17.5")] + public void ConvertsAndReplacesAnEngineeringMeasurement(int release, UnitType legacy, string forge, string input, string internalValue) + { + var parameter = new UserParameter(Kind.Number, true, Store: StoreState.NullPointer, DefinitionSpec: (legacy, forge)); + string source = CreateSource(wall: true, user: parameter, release: release); + RvtWriter.SetParameters(source, Output, [new(ProjectId, DefinitionId, input), new(ProjectId, DefinitionId, "-" + input)]); + using var root = RootStorage.OpenRead(Output); + Assert.Equal(UserBody(parameter, "-" + internalValue), ReadBody(root, release: release)); + } + + [Theory] + [InlineData("12.5 kN", "invalid-parameter-value")] + [InlineData("12.50000000001 kg", "unverified-parameter-storage")] + public void RefusesTheBatchWhenAnEngineeringMeasurementIsInvalidOrAmbiguous(string value, string kind) + { + var parameter = new UserParameter(Kind.Number, true, + DefinitionSpec: (UnitType.UT_Mass, "autodesk.spec.aec.structural:mass-2.0.0")); + string source = CreateSource(wall: true, user: parameter); + byte[] before = File.ReadAllBytes(source); + var error = Assert.Throws(() => RvtWriter.SetParameters(source, Output, + [new(ProjectId, DefinitionId, "12.5 kg"), new(ProjectId, DefinitionId, value)])); + Assert.Equal(kind, error.Kind); + Assert.False(File.Exists(Output)); + Assert.Equal(before, File.ReadAllBytes(source)); + } + + [Theory] + [InlineData(OwnerKind.Wall, "17.25000000001", "unverified-parameter-storage")] + [InlineData(OwnerKind.Wall, "42 $", "invalid-parameter-value")] + [InlineData(OwnerKind.Wall, null, "unsupported-parameter-clear")] + [InlineData(OwnerKind.Room, "17.25000000001", "unverified-parameter-storage")] + [InlineData(OwnerKind.Room, "42 $", "invalid-parameter-value")] + [InlineData(OwnerKind.Room, null, "unsupported-parameter-clear")] + public void RefusesInvalidCurrencyBatchesWithoutChangingTheProject(OwnerKind owner, string? value, string kind) + { + string source = CreateSource(wall: true, user: new(Kind.Number, true, Owner: owner, Currency: true)); + byte[] hash = SHA256.HashData(File.ReadAllBytes(source)); + var error = Assert.Throws(() => RvtWriter.SetParameters(source, Output, + [new(ProjectId, DefinitionId, "17.25"), new(ProjectId, DefinitionId, value)])); + Assert.Equal(kind, error.Kind); + Assert.False(File.Exists(Output)); + Assert.Equal(hash, SHA256.HashData(File.ReadAllBytes(source))); + } + + [Theory] + [InlineData(OwnerKind.WallType, 2, true)] + [InlineData(OwnerKind.Room, 1, true)] + [InlineData(OwnerKind.WallType, 1, false)] + [InlineData(OwnerKind.Room, 2, false)] + public void FirstValueRequiresTheRightBindingForTheOwner(OwnerKind owner, int binding, bool writable) + { + var parameter = new UserParameter(Kind.Text, false, Binding: binding, Store: StoreState.NullPointer, Owner: owner); + string source = CreateSource(wall: true, user: parameter); + if (!writable) + { + var error = Assert.Throws(() => RvtWriter.SetParameter(source, Output, ProjectId, DefinitionId, "First")); + Assert.Contains("different instance or type", error.Message); + Assert.False(File.Exists(Output)); + return; + } + + RvtWriter.SetParameter(source, Output, ProjectId, DefinitionId, "First"); + using var root = RootStorage.OpenRead(Output); + Assert.Equal(UserBody(parameter, "First"), ReadBody(root)); + } + + [Theory] + [InlineData(false, "", false, "invalid-parameter-value")] + [InlineData(true, "New", false, "read-only-parameter")] + [InlineData(false, "New", true, "unverified-parameter-storage")] + public void RefusesUnsafeFirstAssignments(bool readOnly, string value, bool unsorted, string code) + { + var parameter = new UserParameter(Kind.Text, true, ReadOnly: readOnly, + Store: unsorted ? StoreState.Unsorted : StoreState.NullPointer); + string source = CreateSource(wall: true, user: parameter); + var error = Assert.Throws(() => RvtWriter.SetParameter(source, Output, ProjectId, DefinitionId, value)); + Assert.Equal(code, error.Kind); + Assert.False(File.Exists(Output)); + } + + [Theory] + [InlineData(Kind.Text, "New", true, 1, false, false, "read-only-parameter")] + [InlineData(Kind.Text, "New", false, 2, false, false, "unverified-parameter-storage")] + [InlineData(Kind.Text, "New", false, 1, true, false, "unverified-parameter-storage")] + [InlineData(Kind.Text, "New", false, 1, false, true, "unverified-parameter-storage")] + [InlineData(Kind.Integer, "101", false, 1, false, false, "invalid-parameter-value")] + [InlineData(Kind.YesNo, "2", false, 1, false, false, "invalid-parameter-value")] + [InlineData(Kind.Number, "NaN", false, 1, false, false, "invalid-parameter-value")] + public void RefusesUnsafeUserParameterEdits(Kind kind, string value, bool readOnly, int binding, bool grouped, bool global, string code) + { + string source = CreateSource(wall: true, grouped: grouped, global: global, user: new UserParameter(kind, true, readOnly, binding)); + var refused = Assert.Throws(() => RvtWriter.SetParameter(source, Output, ProjectId, DefinitionId, value)); + Assert.Equal(code, refused.Kind); + Assert.False(File.Exists(Output)); + } + + public enum Kind { Text, Integer, YesNo, Number, Material, FamilyType } + public enum OwnerKind : ushort { Wall = 22, WallType = 50, Room = 51 } + private enum StoreState { Value, NullPointer, Neighbour, Unsorted } + private sealed record UserParameter(Kind Kind, bool Shared, bool ReadOnly = false, int Binding = 1, bool Measured = false, + bool IdFirst = false, StoreState Store = StoreState.Value, OwnerKind Owner = OwnerKind.Wall, bool HideWhenNoValue = false, + bool Currency = false, (UnitType Legacy, string Forge)? DefinitionSpec = null); + private sealed record ProjectImage(OwnerKind Owner, int? Stored = null, bool BrokenHolder = false, int DesignOption = -1, + string? LinkedPath = null, string PathType = "Relative to Central Model"); + private sealed record GlobalFixture(Kind Kind, bool Formula = false, bool Reporting = false, bool Consumer = false, string? InitialValue = null, + bool Currency = false, string? SpecId = null); + private sealed record ProjectAssociation(BuiltInParameter Property, bool Malformed = false, int GlobalId = DefinitionId, + bool Derived = false, bool PrimaryAndDerived = false); + private sealed record GlobalFormulaFixture(int Operation = 3, bool Stale = false, bool Consumer = false, + bool IntegerResult = false, bool Conditional = false, int Function = 0, bool CurrencyResult = false, + string? SpecId = null, string? ConstantSpecId = null); + private sealed record GlobalBinary(int Operation, int Parameter, double Constant, bool ConstantFirst = false, string? SpecId = null); + private const int GlobalFormulaResultId = 73; + private const int GlobalFormulaConsumerId = 74; + private const int PropertyGlobalId = 79; + private sealed record FamilyFixture(bool Instance = false, bool Inherited = false, bool Trivial = true, bool Diverged = false, + bool Reporting = false, bool ProjectBound = false, bool SameDefinition = false, bool DerivedType = false, bool DerivedBoundCopy = false, + bool BoundReadOnly = false, bool HideWhenNoValue = true, bool BoundValue = true, BuiltInCategory Category = BuiltInCategory.OST_Doors, + bool OnlyPrimary = false, StoredIdentity? Identity = null, string? InstanceComment = null, + bool Formula = false, bool FormulaTrivial = true, string? InstanceFormulaCache = null, NumericFamilyFormula? NumericFormula = null, + double? TypedCost = null, bool SharedBinding = true, NestedReference? Reference = null, OrdinaryTarget? ProjectTarget = null, + bool BoundFamilyType = false); + private sealed record NestedReference(int Value = -1, string TargetFamily = "Nested", BuiltInCategory TargetCategory = BuiltInCategory.OST_GenericModel, + bool ReadOnly = false); + private sealed record OrdinaryTarget(int MappedId = TargetMaterialId, int SavedReference = -1, + BuiltInCategory Category = BuiltInCategory.OST_GenericModel, bool Active = true, bool DependentSymbol = false, + int? LinkedFamilyMap = null, bool ContainsOwner = false, bool OwnerHasProxy = true); + private sealed record NumericFamilyFormula(int Input = 8, int Operation = 3, double? CurrencyInput = null); + private sealed record StoredIdentity(BuiltInParameter Parameter, string Value, bool CompetingTypedCopy = false); + private const int FamilyId = 73, MasterId = 74, DerivedId = 75; + private const int BoundParameterId = 76; + private const int FamilyFormulaResultId = 77; + private const int OriginalMaterialId = 80, TargetMaterialId = 81; + private const int NestedTypeId = 82; + private const int ProjectTargetFamilyId = 83, ProjectTargetSymbolId = 84, DependentTargetSymbolId = 85; + private const int LinkedFamilyId = 86, LinkedSymbolId = 87; + private const int TargetLevelId = 88; + private const int ImageId = 89, RasterHolderId = 90; + + [Theory] + [InlineData(OwnerKind.Wall, null, ImageId)] + [InlineData(OwnerKind.WallType, -1, ImageId)] + [InlineData(OwnerKind.Room, ImageId, -1)] + [InlineData(OwnerKind.Room, null, -1)] + public void WritesTheBuiltInProjectImage(OwnerKind owner, int? stored, int value) + { + var image = new ProjectImage(owner, stored); + string source = CreateSource(image: image); + RvtWriter.SetParameter(source, Output, ProjectId, ImageParameter(owner), value.ToString(CultureInfo.InvariantCulture)); + using var root = RootStorage.OpenRead(Output); + Assert.Equal(ProjectImageBody(image with { Stored = value }), ReadBody(root)); + } + + [Fact] + public void WritesALevelIdInTheBuiltInProjectImage() + { + var image = new ProjectImage(OwnerKind.Room, Stored: ImageId); + string source = CreateSource(targetLevelDesignOption: -1, image: image); + RvtWriter.SetParameter(source, Output, ProjectId, ImageParameter(image.Owner), TargetLevelId.ToString(CultureInfo.InvariantCulture)); + using var root = RootStorage.OpenRead(Output); + Assert.Equal(ProjectImageBody(image with { Stored = TargetLevelId }), ReadBody(root)); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void WritesALinkedImageWhenItsPathKeepsTheSameTarget(bool absolute) + { + string imagePath = absolute ? Path.Combine(_folder, "picture.png") : "picture.png"; + var image = new ProjectImage(OwnerKind.Wall, LinkedPath: imagePath, PathType: absolute ? "Absolute" : "Relative to Central Model"); + string source = CreateSource(image: image); + string output = absolute ? Path.Combine(Directory.CreateDirectory(Path.Combine(_folder, "moved")).FullName, "output.rvt") : Output; + RvtWriter.SetParameter(source, output, ProjectId, ImageParameter(image.Owner), ImageId.ToString(CultureInfo.InvariantCulture)); + using var root = RootStorage.OpenRead(output); + Assert.Equal(ProjectImageBody(image with { Stored = ImageId }), ReadBody(root)); + } + + [Fact] + public void RefusesToRelocateAProjectWhenAnImagePathWouldResolveDifferently() + { + string source = CreateSource(image: new(OwnerKind.Wall, LinkedPath: "picture.png")); + string output = Path.Combine(Directory.CreateDirectory(Path.Combine(_folder, "moved")).FullName, "output.rvt"); + byte[] hash = SHA256.HashData(File.ReadAllBytes(source)); + var refused = Assert.Throws(() => RvtWriter.SetParameters(source, output, + [new(ProjectId, (int)BuiltInParameter.ALL_MODEL_MARK, "Staged"), new(ProjectId, (int)BuiltInParameter.ALL_MODEL_IMAGE, "-1")])); + Assert.Equal("relative-reference-relocation", refused.Kind); + Assert.False(File.Exists(output)); + Assert.Equal(hash, SHA256.HashData(File.ReadAllBytes(source))); + } + + [Theory] + [InlineData("89", true, -1, "invalid-parameter-value")] + [InlineData("89", false, 91, "invalid-parameter-value")] + [InlineData(null, false, -1, "unsupported-parameter-clear")] + public void AnInvalidProjectImageRejectsTheEntireBatch(string? value, bool brokenHolder, int designOption, string expectedKind) + { + string source = CreateSource(image: new(OwnerKind.Wall, BrokenHolder: brokenHolder, DesignOption: designOption)); + byte[] hash = SHA256.HashData(File.ReadAllBytes(source)); + var refused = Assert.Throws(() => RvtWriter.SetParameters(source, Output, + [new(ProjectId, (int)BuiltInParameter.ALL_MODEL_MARK, "Staged"), new(ProjectId, (int)BuiltInParameter.ALL_MODEL_IMAGE, value)])); + Assert.Equal(expectedKind, refused.Kind); + Assert.False(File.Exists(Output)); + Assert.Equal(hash, SHA256.HashData(File.ReadAllBytes(source))); + } + + [Fact] + public void RefusesToWriteTypeImageOnALoadedFamilySymbol() + { + string source = CreateSource(family: new(OnlyPrimary: true, Category: BuiltInCategory.OST_GenericModel)); + var refused = Assert.Throws(() => + RvtWriter.SetParameter(source, Output, ProjectId, BuiltInParameter.ALL_MODEL_TYPE_IMAGE, "-1")); + Assert.Equal("unsupported-parameter-owner", refused.Kind); + Assert.False(File.Exists(Output)); + } + + [Theory] + [InlineData(OwnerKind.Wall, 1, false, NestedTypeId)] + [InlineData(OwnerKind.WallType, 2, true, TargetMaterialId)] + [InlineData(OwnerKind.Room, 1, true, -1)] + public void WritesAProjectBoundFamilyTypeReference(OwnerKind owner, int binding, bool hasValue, int target) + { + var parameter = new UserParameter(Kind.FamilyType, Shared: true, Binding: binding, + Store: hasValue ? StoreState.Value : StoreState.NullPointer, Owner: owner); + string source = CreateSource(user: parameter); + string value = target.ToString(CultureInfo.InvariantCulture); + RvtWriter.SetParameter(source, Output, ProjectId, DefinitionId, value); + using var root = RootStorage.OpenRead(Output); + Assert.Equal(UserBody(parameter, value), ReadBody(root)); + } + + [Theory] + [InlineData(OwnerKind.Wall, 1, false, BuiltInCategory.OST_GenericModel)] + [InlineData(OwnerKind.WallType, 2, true, BuiltInCategory.OST_Doors)] + [InlineData(OwnerKind.Room, 1, true, BuiltInCategory.OST_Doors)] + public void WritesAnOrdinaryFamilyTypeReferenceInASharedProjectBinding(OwnerKind owner, int binding, bool hasValue, BuiltInCategory target) + { + var parameter = new UserParameter(Kind.FamilyType, Shared: true, Binding: binding, + Store: hasValue ? StoreState.Value : StoreState.NullPointer, Owner: owner); + string source = CreateSource(user: parameter, projectTarget: new(MappedId: NestedTypeId, Category: target)); + string value = ProjectTargetSymbolId.ToString(CultureInfo.InvariantCulture); + RvtWriter.SetParameter(source, Output, ProjectId, DefinitionId, value); + using var root = RootStorage.OpenRead(Output); + Assert.Equal(UserBody(parameter, value), ReadBody(root)); + } + + [Theory] + [InlineData(false, false, ProjectId)] + [InlineData(false, true, ProjectTargetSymbolId)] + [InlineData(true, false, MasterId)] + [InlineData(true, true, ProjectTargetSymbolId)] + public void WritesSharedProjectFamilyTypeReferencesOnLoadedFamilies(bool instance, bool existing, int target) + { + var family = new FamilyFixture(Instance: instance, ProjectBound: true, OnlyPrimary: true, BoundValue: existing, + Reference: new(), ProjectTarget: new(ContainsOwner: true), BoundFamilyType: true); + string source = CreateSource(family: family); + RvtWriter.SetParameter(source, Output, ProjectId, BoundParameterId, target.ToString(CultureInfo.InvariantCulture)); + using var root = RootStorage.OpenRead(Output); + Assert.Equal(instance ? InstanceBody("Old", reference: -1, primary: true, referenceStore: true, boundReference: target) + : SymbolBody(ProjectId, -1, "Old", reference: -1, active: true, referenceStore: true, boundReference: target), ReadBody(root)); + } + + [Theory] + [InlineData(OwnerKind.Wall, 1, false)] + [InlineData(OwnerKind.WallType, 2, true)] + [InlineData(OwnerKind.Room, 1, true)] + public void WritesALocalLevelInASharedProjectFamilyTypeBinding(OwnerKind owner, int binding, bool existing) + { + var parameter = new UserParameter(Kind.FamilyType, Shared: true, Binding: binding, + Store: existing ? StoreState.Value : StoreState.NullPointer, Owner: owner); + string source = CreateSource(user: parameter, targetLevelDesignOption: -1); + string value = TargetLevelId.ToString(CultureInfo.InvariantCulture); + RvtWriter.SetParameter(source, Output, ProjectId, DefinitionId, value); + using var root = RootStorage.OpenRead(Output); + Assert.Equal(UserBody(parameter, value), ReadBody(root)); + } + + [Theory] + [InlineData(true, 601)] + [InlineData(false, -1)] + public void RefusesAnUnverifiedLevelTargetForTheEntireBatch(bool shared, int targetLevelDesignOption) + { + string source = CreateSource(user: new UserParameter(Kind.FamilyType, Shared: shared), + targetLevelDesignOption: targetLevelDesignOption); + byte[] hash = SHA256.HashData(File.ReadAllBytes(source)); + var error = Assert.Throws(() => RvtWriter.SetParameters(source, Output, + [new(ProjectId, (int)BuiltInParameter.ALL_MODEL_MARK, "Staged"), + new(ProjectId, DefinitionId, TargetLevelId.ToString(CultureInfo.InvariantCulture))])); + Assert.Equal("invalid-parameter-value", error.Kind); + Assert.Equal(hash, SHA256.HashData(File.ReadAllBytes(source))); + Assert.False(File.Exists(Output)); + } + + [Fact] + public void RefusesAnInactiveTargetForASharedProjectFamilyTypeBindingAtomically() + { + string source = CreateSource(user: new UserParameter(Kind.FamilyType, Shared: true), projectTarget: new(Active: false)); + byte[] hash = SHA256.HashData(File.ReadAllBytes(source)); + var error = Assert.Throws(() => RvtWriter.SetParameters(source, Output, + [new(ProjectId, (int)BuiltInParameter.ALL_MODEL_MARK, "Staged"), + new(ProjectId, DefinitionId, ProjectTargetSymbolId.ToString(CultureInfo.InvariantCulture))])); + Assert.Equal("unverified-parameter-storage", error.Kind); + Assert.Contains("activating and regenerating", error.Message); + Assert.Equal(hash, SHA256.HashData(File.ReadAllBytes(source))); + Assert.False(File.Exists(Output)); + } + + [Fact] + public void AProjectBindingWithoutASharedDefinitionStillChecksFamilyDependencies() + { + string source = CreateSource(user: new UserParameter(Kind.FamilyType, Shared: false), projectTarget: new(MappedId: NestedTypeId)); + var error = Assert.Throws(() => RvtWriter.SetParameter(source, Output, ProjectId, DefinitionId, + ProjectTargetSymbolId.ToString(CultureInfo.InvariantCulture))); + Assert.Equal("unverified-parameter-storage", error.Kind); + Assert.False(File.Exists(Output)); + } + + [Fact] + public void ClearsAProjectBoundFamilyTypeReferenceWithHideWhenNoValue() + { + var parameter = new UserParameter(Kind.FamilyType, Shared: true, HideWhenNoValue: true); + string source = CreateSource(user: parameter); + RvtWriter.SetParameters(source, Output, [new(ProjectId, DefinitionId, null)]); + using var root = RootStorage.OpenRead(Output); + Assert.Equal(UserBody(parameter, cleared: true), ReadBody(root)); + } + + [Theory] + [InlineData("9999999", "invalid-parameter-value")] + [InlineData(null, "unsupported-parameter-clear")] + public void RefusesTheEntireBatchWhenAProjectBoundFamilyTypeEditIsInvalid(string? value, string kind) + { + string source = CreateSource(user: new UserParameter(Kind.FamilyType, Shared: true)); + byte[] hash = SHA256.HashData(File.ReadAllBytes(source)); + var error = Assert.Throws(() => RvtWriter.SetParameters(source, Output, + [new(ProjectId, (int)BuiltInParameter.ALL_MODEL_MARK, "Staged"), new(ProjectId, DefinitionId, value)])); + Assert.Equal(kind, error.Kind); + Assert.Equal(hash, SHA256.HashData(File.ReadAllBytes(source))); + Assert.False(File.Exists(Output)); + } + + [Theory] + [InlineData(-1, NestedTypeId)] + [InlineData(NestedTypeId, -1)] + [InlineData(NestedTypeId, TargetMaterialId)] + public void WritesAReferenceToThePrimaryFamilyType(int oldValue, int value) + { + string source = CreateSource(family: new FamilyFixture(OnlyPrimary: true, Reference: new(oldValue))); + RvtWriter.SetParameter(source, Output, ProjectId, DefinitionId, value.ToString(CultureInfo.InvariantCulture)); + using var root = RootStorage.OpenRead(Output); + Assert.Equal(SymbolBody(ProjectId, -1, "Old", reference: value), ReadBody(root)); + } + + [Fact] + public void WritesTheFirstLocalFamilyTypeReferenceOnAnInstance() + { + string source = CreateSource(family: new FamilyFixture(Instance: true, Inherited: true, OnlyPrimary: true, Reference: new())); + RvtWriter.SetParameter(source, Output, ProjectId, DefinitionId, NestedTypeId.ToString(CultureInfo.InvariantCulture)); + using var root = RootStorage.OpenRead(Output); + Assert.Equal(InstanceBody("", reference: NestedTypeId, primary: true), ReadBody(root)); + Assert.Equal(SymbolBody(MasterId, -1, "Old", instanceDefault: true, reference: -1), ReadBody(root, MasterId)); + } + + [Fact] + public void UpdatesTheFamilyTypeReferenceOnThePrimaryAndDerivedSymbols() + { + string source = CreateSource(family: new FamilyFixture(Reference: new())); + RvtWriter.SetParameter(source, Output, ProjectId, DefinitionId, NestedTypeId.ToString(CultureInfo.InvariantCulture)); + using var root = RootStorage.OpenRead(Output); + Assert.Equal(SymbolBody(ProjectId, -1, "Old", reference: NestedTypeId), ReadBody(root)); + Assert.Equal(SymbolBody(DerivedId, ProjectId, "Old", reference: NestedTypeId), ReadBody(root, DerivedId)); + } + + [Theory] + [InlineData(-1)] + [InlineData(NestedTypeId)] + public void WritesAnOrdinaryProjectFamilyTypeReference(int original) + { + string source = CreateSource(family: new FamilyFixture(Reference: new(original), ProjectTarget: new())); + RvtWriter.SetParameter(source, Output, ProjectId, DefinitionId, ProjectTargetSymbolId.ToString(CultureInfo.InvariantCulture)); + using var root = RootStorage.OpenRead(Output); + Assert.Equal(SymbolBody(ProjectId, -1, "Old", reference: ProjectTargetSymbolId, active: true), ReadBody(root)); + Assert.Equal(SymbolBody(DerivedId, ProjectId, "Old", reference: ProjectTargetSymbolId, active: true), ReadBody(root, DerivedId)); + } + + [Theory] + [InlineData(LinkedFamilyId, -1)] + [InlineData(LinkedSymbolId, -1)] + [InlineData(TargetMaterialId, LinkedSymbolId)] + public void WritesAProjectFamilyTypeReferenceWithAnUnrelatedDependency(int mappedId, int savedReference) + { + var target = new OrdinaryTarget(mappedId, savedReference, LinkedFamilyMap: TargetMaterialId); + string source = CreateSource(family: new FamilyFixture(Reference: new(), ProjectTarget: target)); + RvtWriter.SetParameter(source, Output, ProjectId, DefinitionId, ProjectTargetSymbolId.ToString(CultureInfo.InvariantCulture)); + using var root = RootStorage.OpenRead(Output); + Assert.Equal(SymbolBody(ProjectId, -1, "Old", reference: ProjectTargetSymbolId, active: true), ReadBody(root)); + } + + [Fact] + public void ReadsFamilyDependenciesFromRecordsAlreadyStagedInABatch() + { + var target = new OrdinaryTarget(LinkedFamilyMap: TargetMaterialId); + string source = CreateSource(family: new FamilyFixture(Reference: new(), ProjectTarget: target)); + using var root = RootStorage.OpenRead(source); + var schema = TfSchemaReader.Read(root)!; + var formats = new FormatsSchema(schema); + var table = PagedGzipStream.Read(root, "Global", "ElemTable")!; + var ids = ElemTableLayout.TryParse(table, formats)!.Select(row => row.Id).ToHashSet(); + var pending = new ParameterWriter.Pending(); + Assert.Empty(ProjectFamilyReference.Read(root, Tags(2022), sizeof(int), schema, ids, + ProjectTargetSymbolId, ProjectTargetFamilyId, pending).Dependencies); + + byte[] staged = SymbolBody(ProjectTargetSymbolId, -1, "Target", reference: LinkedSymbolId, familyId: ProjectTargetFamilyId, active: true); + pending.Apply(new ParameterWriter.PlanResult([new(0, 102, ProjectTargetSymbolId, staged)], null)); + Assert.Equal(LinkedFamilyId, Assert.Single(ProjectFamilyReference.Read(root, Tags(2022), sizeof(int), schema, ids, + ProjectTargetSymbolId, ProjectTargetFamilyId, pending).Dependencies)); + } + + [Theory] + [InlineData(FamilyId, "dependency on the family being edited")] + [InlineData(9999999, "dependencies could not be verified")] + public void RefusesTheBatchWhenAnIndirectFamilyDependencyIsUnverified(int mappedId, string message) + { + var target = new OrdinaryTarget(LinkedFamilyId, LinkedFamilyMap: mappedId); + string source = CreateSource(family: new FamilyFixture(Instance: true, ProjectBound: true, Reference: new(), ProjectTarget: target)); + byte[] hash = SHA256.HashData(File.ReadAllBytes(source)); + var error = Assert.Throws(() => RvtWriter.SetParameters(source, Output, + [new(ProjectId, BoundParameterId, "Staged"), new(ProjectId, DefinitionId, ProjectTargetSymbolId.ToString(CultureInfo.InvariantCulture))])); + Assert.Equal("unverified-parameter-storage", error.Kind); + Assert.Contains(message, error.Message); + Assert.Equal(hash, SHA256.HashData(File.ReadAllBytes(source))); + Assert.False(File.Exists(Output)); + } + + [Theory] + [InlineData(-1)] + [InlineData(TargetMaterialId)] + [InlineData(NestedTypeId)] + public void WritesAnIndependentTypeReferenceToATypeContainingTheSharedOwner(int original) + { + string source = CreateSource(family: new FamilyFixture(Reference: new(original), ProjectTarget: new(ContainsOwner: true))); + RvtWriter.SetParameter(source, Output, ProjectId, DefinitionId, ProjectTargetSymbolId.ToString(CultureInfo.InvariantCulture)); + using var root = RootStorage.OpenRead(Output); + Assert.Equal(SymbolBody(ProjectId, -1, "Old", reference: ProjectTargetSymbolId, active: true), ReadBody(root)); + Assert.Equal(SymbolBody(DerivedId, ProjectId, "Old", reference: ProjectTargetSymbolId, active: true), ReadBody(root, DerivedId)); + } + + [Theory] + [InlineData(true, true, true)] + [InlineData(false, false, true)] + [InlineData(false, true, false)] + public void RefusesAnEntireBatchForACircularReferenceOutsideTheVerifiedTypeScope(bool instance, bool ownerHasProxy, bool trivial) + { + var target = new OrdinaryTarget(ContainsOwner: true, OwnerHasProxy: ownerHasProxy); + string source = CreateSource(family: new FamilyFixture(Instance: instance, ProjectBound: true, Trivial: trivial, + Reference: new(), ProjectTarget: target)); + byte[] hash = SHA256.HashData(File.ReadAllBytes(source)); + var error = Assert.Throws(() => RvtWriter.SetParameters(source, Output, + [new(ProjectId, BoundParameterId, "Staged"), new(ProjectId, DefinitionId, ProjectTargetSymbolId.ToString(CultureInfo.InvariantCulture))])); + Assert.Equal("unverified-parameter-storage", error.Kind); + Assert.Equal(hash, SHA256.HashData(File.ReadAllBytes(source))); + Assert.False(File.Exists(Output)); + } + + [Theory] + [InlineData(FamilyId, -1, BuiltInCategory.OST_GenericModel, "unverified-parameter-storage")] + [InlineData(9999999, -1, BuiltInCategory.OST_GenericModel, "unverified-parameter-storage")] + [InlineData(TargetMaterialId, ProjectId, BuiltInCategory.OST_GenericModel, "unverified-parameter-storage")] + [InlineData(TargetMaterialId, -1, BuiltInCategory.OST_Furniture, "invalid-parameter-value")] + public void RefusesTheBatchForAnUnverifiedProjectFamilyTypeTarget(int mappedId, int savedReference, BuiltInCategory category, string kind) + { + string source = CreateSource(family: new FamilyFixture(Reference: new(), ProjectTarget: new(mappedId, savedReference, category))); + byte[] hash = SHA256.HashData(File.ReadAllBytes(source)); + var error = Assert.Throws(() => RvtWriter.SetParameters(source, Output, + [new(ProjectId, DefinitionId, NestedTypeId.ToString(CultureInfo.InvariantCulture)), + new(ProjectId, DefinitionId, ProjectTargetSymbolId.ToString(CultureInfo.InvariantCulture))])); + Assert.Equal(kind, error.Kind); + Assert.Equal(hash, SHA256.HashData(File.ReadAllBytes(source))); + Assert.False(File.Exists(Output)); + } + + [Fact] + public void RejectsAProjectFamilyTypeTargetThatNeedsActivation() + { + string source = CreateSource(family: new FamilyFixture(Reference: new(), ProjectTarget: new(Active: false))); + var error = Assert.Throws(() => RvtWriter.SetParameter(source, Output, ProjectId, DefinitionId, + ProjectTargetSymbolId.ToString(CultureInfo.InvariantCulture))); + Assert.Equal("unverified-parameter-storage", error.Kind); + Assert.Contains("activating and regenerating", error.Message); + Assert.False(File.Exists(Output)); + } + + [Fact] + public void RejectsAProjectFamilyTypeTargetWhenAnotherTypeOfItsFamilyReferencesTheOwner() + { + string source = CreateSource(family: new FamilyFixture(Reference: new(), ProjectTarget: new(DependentSymbol: true))); + var error = Assert.Throws(() => RvtWriter.SetParameter(source, Output, ProjectId, DefinitionId, + ProjectTargetSymbolId.ToString(CultureInfo.InvariantCulture))); + Assert.Equal("unverified-parameter-storage", error.Kind); + Assert.False(File.Exists(Output)); + } + + [Fact] + public void WritesTheFirstLocalReferenceForAnInstanceWithADerivedSymbol() + { + string source = CreateSource(family: new FamilyFixture(Instance: true, Inherited: true, Reference: new())); + RvtWriter.SetParameter(source, Output, ProjectId, DefinitionId, NestedTypeId.ToString(CultureInfo.InvariantCulture)); + using var root = RootStorage.OpenRead(Output); + Assert.Equal(InstanceBody("", reference: NestedTypeId), ReadBody(root)); + Assert.Equal(SymbolBody(DerivedId, MasterId, "Old", instanceDefault: true, reference: -1), ReadBody(root, DerivedId)); + } + + [Fact] + public void RefusesTheEntireFamilyTypeBatchForAnIndependentDerivedEdit() + { + string source = CreateSource(family: new FamilyFixture(DerivedType: true, Reference: new())); + byte[] hash = SHA256.HashData(File.ReadAllBytes(source)); + string value = NestedTypeId.ToString(CultureInfo.InvariantCulture); + var error = Assert.Throws(() => RvtWriter.SetParameters(source, Output, + [new(ProjectId, DefinitionId, value), new(DerivedId, DefinitionId, value)])); + Assert.Equal("unsupported-parameter", error.Kind); + Assert.Equal(hash, SHA256.HashData(File.ReadAllBytes(source))); + Assert.False(File.Exists(Output)); + } + + [Fact] + public void RefusesToOverwriteAnUnverifiedDerivedFamilyTypeReference() + { + string source = CreateSource(family: new FamilyFixture(Diverged: true, Reference: new())); + byte[] hash = SHA256.HashData(File.ReadAllBytes(source)); + string value = NestedTypeId.ToString(CultureInfo.InvariantCulture); + var error = Assert.Throws(() => RvtWriter.SetParameter(source, Output, ProjectId, DefinitionId, value)); + Assert.Equal("unverified-parameter-storage", error.Kind); + Assert.Equal(hash, SHA256.HashData(File.ReadAllBytes(source))); + Assert.False(File.Exists(Output)); + } + + [Theory] + [InlineData("9999999", "Nested", BuiltInCategory.OST_GenericModel, false, "invalid-parameter-value")] + [InlineData("82", "Host", BuiltInCategory.OST_GenericModel, false, "invalid-parameter-value")] + [InlineData("82", "Nested", BuiltInCategory.OST_Furniture, false, "invalid-parameter-value")] + [InlineData("82", "Nested", BuiltInCategory.OST_GenericModel, true, "read-only-parameter")] + [InlineData(null, "Nested", BuiltInCategory.OST_GenericModel, false, "unsupported-parameter-clear")] + public void RefusesTheEntireBatchForAnInvalidFamilyTypeReference(string? value, string nestedName, + BuiltInCategory nestedCategory, bool readOnly, string kind) + { + var comments = new StoredIdentity(BuiltInParameter.ALL_MODEL_TYPE_COMMENTS, "Original"); + string source = CreateSource(family: new FamilyFixture(OnlyPrimary: true, Identity: comments, + Reference: new(TargetFamily: nestedName, TargetCategory: nestedCategory, ReadOnly: readOnly))); + byte[] hash = SHA256.HashData(File.ReadAllBytes(source)); + var error = Assert.Throws(() => RvtWriter.SetParameters(source, Output, + [new(ProjectId, (int)comments.Parameter, "Staged"), new(ProjectId, DefinitionId, value)])); + Assert.Equal(kind, error.Kind); + Assert.Equal(hash, SHA256.HashData(File.ReadAllBytes(source))); + Assert.False(File.Exists(Output)); + } + + [Theory] + [InlineData(BuiltInCategory.OST_Doors, BuiltInParameter.FIRE_RATING, "90 min")] + [InlineData(BuiltInCategory.OST_Windows, BuiltInParameter.ALL_MODEL_TYPE_COMMENTS, "")] + [InlineData(BuiltInCategory.OST_GenericModel, BuiltInParameter.ALL_MODEL_COST, "14.125")] + public void WritesTheLocalNamedValueOfALoadedPrimaryType(BuiltInCategory category, BuiltInParameter parameter, string value) + { + var initial = new StoredIdentity(parameter, parameter == BuiltInParameter.ALL_MODEL_COST ? "17.25" : "Template"); + string source = CreateSource(family: new FamilyFixture(Category: category, OnlyPrimary: true, Identity: initial)); + var result = RvtWriter.SetParameter(source, Output, ProjectId, parameter, value); + Assert.Equal(1, result.RewrittenRecordCount); + + using var root = RootStorage.OpenRead(Output); + using var original = RootStorage.OpenRead(source); + Assert.Equal(SymbolBody(ProjectId, -1, "Old", identity: initial with { Value = value }), ReadBody(root)); + Assert.Equal(ReadBody(original, FamilyId), ReadBody(root, FamilyId)); + } + + [Fact] + public void RefusesAnEntireLoadedTypeBatchWhenTheIdentityHasTwoStores() + { + var identity = new StoredIdentity(BuiltInParameter.ALL_MODEL_TYPE_COMMENTS, "Template", CompetingTypedCopy: true); + string source = CreateSource(family: new FamilyFixture(OnlyPrimary: true, Identity: identity)); + byte[] hash = SHA256.HashData(File.ReadAllBytes(source)); + var error = Assert.Throws(() => RvtWriter.SetParameters(source, Output, + [new(ProjectId, (int)BuiltInParameter.ALL_MODEL_MODEL, "Staged"), new(ProjectId, (int)identity.Parameter, "Rejected")])); + Assert.Equal("unverified-parameter-storage", error.Kind); + Assert.Contains("competing typed store", error.Message); + Assert.False(File.Exists(Output)); + Assert.Equal(hash, SHA256.HashData(File.ReadAllBytes(source))); + } + + [Fact] + public void UpdatesAnImportedIdentityAndMirrorsTheVerifiedDerivedSymbol() + { + var identity = new StoredIdentity(BuiltInParameter.ALL_MODEL_TYPE_COMMENTS, "Template"); + string source = CreateSource(family: new FamilyFixture(Category: BuiltInCategory.OST_GenericModel, + DerivedType: true, Identity: identity)); + var result = RvtWriter.SetParameter(source, Output, ProjectId, identity.Parameter, "Updated"); + Assert.Equal(2, result.RewrittenRecordCount); + + using var root = RootStorage.OpenRead(Output); + var expected = identity with { Value = "Updated" }; + Assert.Equal(SymbolBody(ProjectId, -1, "Old", identity: expected), ReadBody(root)); + Assert.Equal(SymbolBody(DerivedId, ProjectId, "Old", identity: expected), ReadBody(root, DerivedId)); + } + + [Fact] + public void RejectsADirectNamedIdentityEditOnADerivedSymbol() + { + var identity = new StoredIdentity(BuiltInParameter.ALL_MODEL_TYPE_COMMENTS, "Template"); + string source = CreateSource(family: new FamilyFixture(Category: BuiltInCategory.OST_GenericModel, + DerivedType: true, Identity: identity)); + byte[] hash = SHA256.HashData(File.ReadAllBytes(source)); + var error = Assert.Throws(() => RvtWriter.SetParameters(source, Output, + [new(ProjectId, (int)identity.Parameter, "Staged"), new(DerivedId, (int)identity.Parameter, "Rejected")])); + Assert.Equal("unverified-parameter-storage", error.Kind); + Assert.False(File.Exists(Output)); + Assert.Equal(hash, SHA256.HashData(File.ReadAllBytes(source))); + } + + [Theory] + [InlineData(false, false, 2)] + [InlineData(true, false, 1)] + [InlineData(true, true, 1)] + public void WritesLoadedFamilyValuesAndMirrorsOnlyTheType(bool instance, bool inherited, int count) + { + string source = CreateSource(family: new FamilyFixture(instance, inherited)); + const string value = "Family text & value"; + var result = RvtWriter.SetParameter(source, Output, ProjectId, DefinitionId, value); + Assert.Equal(count, result.RewrittenRecordCount); + using var root = RootStorage.OpenRead(Output); + Assert.Equal(instance ? InstanceBody(value) : SymbolBody(ProjectId, -1, value), ReadBody(root)); + Assert.Equal(instance ? SymbolBody(DerivedId, MasterId, "Old", true) : SymbolBody(DerivedId, ProjectId, value), + ReadBody(root, DerivedId)); + } + + [Theory] + [InlineData(false, false, false, "independent of geometry")] + [InlineData(true, true, false, "disagrees with its master")] + [InlineData(true, false, true, "is reporting")] + public void RefusesLoadedFamilyValuesWithUnverifiedDependencies(bool trivial, bool diverged, bool reporting, string reason) + { + string source = CreateSource(family: new FamilyFixture(Trivial: trivial, Diverged: diverged, Reporting: reporting)); + var refused = Assert.Throws(() => RvtWriter.SetParameter(source, Output, ProjectId, DefinitionId, "New")); + Assert.Contains(reason, refused.Message); + Assert.False(File.Exists(Output)); + } + + [Fact] + public void RecalculatesAFormulaOnThePrimaryAndItsDerivedSymbol() + { + string source = CreateSource(family: new FamilyFixture(Formula: true)); + const string value = "Changed formula input"; + var result = RvtWriter.SetParameter(source, Output, ProjectId, DefinitionId, value); + Assert.Equal(2, result.RewrittenRecordCount); + using var root = RootStorage.OpenRead(Output); + Assert.Equal(SymbolBody(ProjectId, -1, value, formula: true), ReadBody(root)); + Assert.Equal(SymbolBody(DerivedId, ProjectId, value, formula: true), ReadBody(root, DerivedId)); + using var original = RootStorage.OpenRead(source); + Assert.Equal(ReadBody(original, FamilyId), ReadBody(root, FamilyId)); + } + + [Theory] + [InlineData("99", 50)] + [InlineData("-99", -49)] + public void ResolvesAFormulaResultToItsWritableInputAndMirrorsTheType(string requested, int input) + { + string source = CreateSource(family: new FamilyFixture(Formula: true, NumericFormula: new())); + var result = RvtWriter.SetParameter(source, Output, ProjectId, FamilyFormulaResultId, requested); + + Assert.Equal(2, result.RewrittenRecordCount); + using var root = RootStorage.OpenRead(Output); + using var original = RootStorage.OpenRead(source); + Assert.Equal(SymbolBody(ProjectId, -1, "Old", formula: true, numericFormula: new(input)), ReadBody(root)); + Assert.Equal(SymbolBody(DerivedId, ProjectId, "Old", formula: true, numericFormula: new(input)), ReadBody(root, DerivedId)); + Assert.Equal(ReadBody(original, FamilyId), ReadBody(root, FamilyId)); + } + + [Theory] + [InlineData("43.5", 21.75)] + [InlineData("-7.25", -3.625)] + public void ResolvesAnExactCurrencyFormulaInverse(string requested, double input) + { + var formula = new NumericFamilyFormula(CurrencyInput: 7.25); + string source = CreateSource(family: new FamilyFixture(Formula: true, NumericFormula: formula)); + var result = RvtWriter.SetParameter(source, Output, ProjectId, FamilyFormulaResultId, requested); + + Assert.Equal(2, result.RewrittenRecordCount); + using var root = RootStorage.OpenRead(Output); + var expected = formula with { CurrencyInput = input }; + Assert.Equal(SymbolBody(ProjectId, -1, "Old", formula: true, numericFormula: expected), ReadBody(root)); + Assert.Equal(SymbolBody(DerivedId, ProjectId, "Old", formula: true, numericFormula: expected), ReadBody(root, DerivedId)); + } + + [Fact] + public void RefusesAnAmbiguousReplacementOfAnIndependentLoadedCurrencyValue() + { + var formula = new NumericFamilyFormula(CurrencyInput: 7.25); + string source = CreateSource(family: new FamilyFixture(NumericFormula: formula)); + byte[] hash = SHA256.HashData(File.ReadAllBytes(source)); + var error = Assert.Throws(() => RvtWriter.SetParameters(source, Output, + [new(ProjectId, DefinitionId, "17.25"), new(ProjectId, DefinitionId, "17.25000000001")])); + Assert.Equal("unverified-parameter-storage", error.Kind); + Assert.False(File.Exists(Output)); + Assert.Equal(hash, SHA256.HashData(File.ReadAllBytes(source))); + } + + [Theory] + [InlineData(46.87500009, true)] + [InlineData(46.87499991, true)] + [InlineData(46.87500009375, false)] + [InlineData(46.87499990625, false)] + public void ClassifiesVerifiedRetainedCurrencyFormulaValues(double calculated, bool retained) + { + Assert.Equal(retained, ParameterFormulaEvaluator.IsWithinVerifiedRelativeTolerance(46.875, calculated)); + } + + [Fact] + public void AGlobalCurrencyInputRecalculatesTheLoadedTypeFormula() + { + var formula = new NumericFamilyFormula(CurrencyInput: 7.25); + var association = new ProjectAssociation((BuiltInParameter)DefinitionId, GlobalId: PropertyGlobalId); + var global = new GlobalFixture(Kind.Number, InitialValue: "7.25", Currency: true); + string source = CreateSource(family: new FamilyFixture(Formula: true, NumericFormula: formula), + globalParameter: global, association: association); + RvtWriter.SetParameter(source, Output, PropertyGlobalId, PropertyGlobalId, "17.25"); + + using var root = RootStorage.OpenRead(Output); + var expected = formula with { CurrencyInput = 17.25 }; + Assert.Equal(SymbolBody(ProjectId, -1, "Old", formula: true, numericFormula: expected, + association: association, associationSlot: true), ReadBody(root)); + Assert.Equal(GlobalBody(global, "17.25", PropertyGlobalId), ReadBody(root, PropertyGlobalId)); + } + + [Fact] + public void KeepsTheCurrentFormulaInputWhenTheRequestedResultAlreadyMatches() + { + string source = CreateSource(family: new FamilyFixture(Formula: true, NumericFormula: new(7, Operation: 4))); + var result = RvtWriter.SetParameter(source, Output, ProjectId, FamilyFormulaResultId, "4"); + + Assert.Equal(0, result.RewrittenRecordCount); + using var root = RootStorage.OpenRead(Output); + using var original = RootStorage.OpenRead(source); + Assert.Equal(ReadBody(original), ReadBody(root)); + Assert.Equal(ReadBody(original, DerivedId), ReadBody(root, DerivedId)); + } + + [Fact] + public void RefusesAnEntireBatchWhenAFormulaInverseProducesAnOutOfRangeResult() + { + string source = CreateSource(family: new FamilyFixture(Formula: true, NumericFormula: new())); + var before = SHA256.HashData(File.ReadAllBytes(source)); + var refused = Assert.Throws(() => RvtWriter.SetParameters(source, Output, + [new(ProjectId, FamilyFormulaResultId, "99"), new(ProjectId, FamilyFormulaResultId, int.MaxValue.ToString())])); + + Assert.Equal("invalid-parameter-value", refused.Kind); + Assert.False(File.Exists(Output)); + Assert.Equal(before, SHA256.HashData(File.ReadAllBytes(source))); + } + + [Fact] + public void RecalculatesAnInstanceFormulaWithoutChangingItsType() + { + string source = CreateSource(family: new FamilyFixture(Instance: true, Formula: true)); + const string value = "New local formula input"; + var result = RvtWriter.SetParameter(source, Output, ProjectId, DefinitionId, value); + + Assert.Equal(1, result.RewrittenRecordCount); + using var root = RootStorage.OpenRead(Output); + using var original = RootStorage.OpenRead(source); + Assert.Equal(InstanceBody(value, formulaResult: value), ReadBody(root)); + foreach (ulong id in new ulong[] { FamilyId, MasterId, DerivedId }) + Assert.Equal(ReadBody(original, id), ReadBody(root, id)); + } + + [Fact] + public void RefusesAnEntireBatchWhenAnInstanceFormulaResultIsEditedDirectly() + { + string source = CreateSource(family: new FamilyFixture(Instance: true, Formula: true)); + var before = SHA256.HashData(File.ReadAllBytes(source)); + var refused = Assert.Throws(() => RvtWriter.SetParameters(source, Output, + [new(ProjectId, DefinitionId, "Staged local input"), new(ProjectId, FamilyFormulaResultId, "Rejected")])); + + Assert.Contains("saved expression", refused.Message); + Assert.False(File.Exists(Output)); + Assert.Equal(before, SHA256.HashData(File.ReadAllBytes(source))); + } + + [Fact] + public void RefusesAnInstanceFormulaWhenItsStoredResultDisagreesWithTheFormula() + { + string source = CreateSource(family: new FamilyFixture(Instance: true, Formula: true, InstanceFormulaCache: "Stale")); + var before = SHA256.HashData(File.ReadAllBytes(source)); + var refused = Assert.Throws(() => RvtWriter.SetParameter(source, Output, ProjectId, DefinitionId, "New")); + + Assert.Contains("does not reproduce its stored value", refused.Message); + Assert.False(File.Exists(Output)); + Assert.Equal(before, SHA256.HashData(File.ReadAllBytes(source))); + } + + [Fact] + public void RejectsABatchWhenTheLoadedFormulaResultCanDriveGeometry() + { + string source = CreateSource(family: new FamilyFixture(Formula: true, FormulaTrivial: false)); + var before = SHA256.HashData(File.ReadAllBytes(source)); + var refused = Assert.Throws(() => RvtWriter.SetParameters(source, Output, + [new(ProjectId, DefinitionId, "Changed"), new(ProjectId, DefinitionId, "Never published")])); + Assert.Equal("unverified-parameter-storage", refused.Kind); + Assert.False(File.Exists(Output)); + Assert.Equal(before, SHA256.HashData(File.ReadAllBytes(source))); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public void ClearsOnlyTheProjectBoundValueOnALoadedFamilyElement(bool instance) + { + string source = CreateSource(family: new FamilyFixture(Instance: instance, ProjectBound: true)); + var result = RvtWriter.SetParameters(source, Output, [new(ProjectId, BoundParameterId, null), new(ProjectId, BoundParameterId, null)]); + Assert.Equal(1, result.RewrittenRecordCount); + using var root = RootStorage.OpenRead(Output); + Assert.Equal(instance ? InstanceBody("Old", BindStore.Empty) : SymbolBody(ProjectId, -1, "Old", bound: BindStore.Empty), ReadBody(root)); + } + + [Fact] + public void ClearsAProjectBoundTypeValueInheritedByADerivedSymbol() + { + string source = CreateSource(family: new FamilyFixture(ProjectBound: true, DerivedType: true)); + var result = RvtWriter.SetParameters(source, Output, [new(ProjectId, BoundParameterId, null)]); + Assert.Equal(1, result.RewrittenRecordCount); + using var root = RootStorage.OpenRead(Output); + Assert.Equal(SymbolBody(ProjectId, -1, "Old", bound: BindStore.Empty), ReadBody(root)); + Assert.Equal(SymbolBody(DerivedId, ProjectId, "Old"), ReadBody(root, DerivedId)); + } + + [Theory] + [InlineData(true, false)] + [InlineData(false, true)] + [InlineData(true, true)] + public void ClearsTheProjectBoundValuesOfOnlyTheAddressedSymbols(bool primary, bool derived) + { + string source = CreateSource(family: new FamilyFixture(ProjectBound: true, DerivedType: true, DerivedBoundCopy: true)); + var edits = new List(); + if (primary) + edits.Add(new(ProjectId, BoundParameterId, null)); + if (derived) + edits.Add(new(DerivedId, BoundParameterId, null)); + var result = RvtWriter.SetParameters(source, Output, edits); + Assert.Equal(edits.Count, result.RewrittenRecordCount); + using var root = RootStorage.OpenRead(Output); + Assert.Equal(SymbolBody(ProjectId, -1, "Old", bound: primary ? BindStore.Empty : BindStore.Value), ReadBody(root)); + Assert.Equal(SymbolBody(DerivedId, ProjectId, "Old", bound: derived ? BindStore.Empty : BindStore.Value), ReadBody(root, DerivedId)); + } + + [Theory] + [InlineData(true, false, "New local text")] + [InlineData(true, true, "Replacement text")] + [InlineData(true, false, "")] + [InlineData(false, false, "New local text")] + [InlineData(false, true, "Replacement text")] + [InlineData(false, false, "")] + public void WritesOnlyTheAddressedDerivedSymbolsProjectValue(bool hide, bool existing, string value) + { + string source = CreateSource(family: new FamilyFixture(ProjectBound: true, DerivedType: true, DerivedBoundCopy: existing, + HideWhenNoValue: hide)); + var result = RvtWriter.SetParameters(source, Output, [new(DerivedId, BoundParameterId, value)]); + Assert.Equal(1, result.RewrittenRecordCount); + using var root = RootStorage.OpenRead(Output); + Assert.Equal(SymbolBody(ProjectId, -1, "Old", bound: BindStore.Value), ReadBody(root)); + Assert.Equal(SymbolBody(DerivedId, ProjectId, "Old", bound: BindStore.Value, boundText: value), ReadBody(root, DerivedId)); + } + + [Theory] + [InlineData(false, false, true, "")] + [InlineData(true, false, false, "First value")] + [InlineData(true, true, true, "Replacement")] + [InlineData(false, true, false, "Replacement")] + public void WritesThePrimarySymbolsProjectValue(bool derived, bool existing, bool hide, string value) + { + string source = CreateSource(family: new FamilyFixture(ProjectBound: true, DerivedType: derived, DerivedBoundCopy: derived, + HideWhenNoValue: hide, BoundValue: existing)); + var result = RvtWriter.SetParameters(source, Output, [new(ProjectId, BoundParameterId, value)]); + Assert.Equal(1, result.RewrittenRecordCount); + using var root = RootStorage.OpenRead(Output); + Assert.Equal(SymbolBody(ProjectId, -1, "Old", bound: BindStore.Value, boundText: value), ReadBody(root)); + if (derived) + Assert.Equal(SymbolBody(DerivedId, ProjectId, "Old", bound: BindStore.Value), ReadBody(root, DerivedId)); + } + + [Theory] + [InlineData(false, true, "First instance value")] + [InlineData(true, false, "Replacement")] + [InlineData(false, false, "")] + public void WritesAProjectBoundValueOnALoadedInstance(bool existing, bool hide, string value) + { + string source = CreateSource(family: new FamilyFixture(Instance: true, ProjectBound: true, + HideWhenNoValue: hide, BoundValue: existing)); + var result = RvtWriter.SetParameters(source, Output, [new(ProjectId, BoundParameterId, value)]); + Assert.Equal(1, result.RewrittenRecordCount); + using var root = RootStorage.OpenRead(Output); + Assert.Equal(InstanceBody("Old", BindStore.Value, value), ReadBody(root)); + Assert.Equal(SymbolBody(DerivedId, MasterId, "Old", true), ReadBody(root, DerivedId)); + } + + [Theory] + [InlineData(true, false, "First instance text")] + [InlineData(false, false, "")] + [InlineData(false, true, "Replacement")] + public void WritesNonsharedProjectTextOnALoadedFamilyElement(bool instance, bool existing, string value) + { + var family = new FamilyFixture(Instance: instance, ProjectBound: true, BoundValue: existing, SharedBinding: false); + string source = CreateSource(family: family); + var result = RvtWriter.SetParameter(source, Output, ProjectId, BoundParameterId, value); + + Assert.Equal(1, result.RewrittenRecordCount); + using var root = RootStorage.OpenRead(Output); + Assert.Equal(instance ? InstanceBody("Old", BindStore.Value, value) + : SymbolBody(ProjectId, -1, "Old", bound: BindStore.Value, boundText: value), ReadBody(root)); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public void RefusesTheEntireBatchWhenClearingANonsharedProjectValue(bool instance) + { + string source = CreateSource(family: new FamilyFixture(Instance: instance, ProjectBound: true, SharedBinding: false)); + byte[] hash = SHA256.HashData(File.ReadAllBytes(source)); + var refused = Assert.Throws(() => RvtWriter.SetParameters(source, Output, + [new(ProjectId, BoundParameterId, "Staged"), new(ProjectId, BoundParameterId, null)])); + + Assert.Equal("unsupported-parameter-clear", refused.Kind); + Assert.False(File.Exists(Output)); + Assert.Equal(hash, SHA256.HashData(File.ReadAllBytes(source))); + } + + [Fact] + public void RejectsTheWholeBatchWhenClearingAnOrdinaryProjectBoundInstanceValue() + { + string source = CreateSource(family: new FamilyFixture(Instance: true, ProjectBound: true, HideWhenNoValue: false)); + byte[] hash = SHA256.HashData(File.ReadAllBytes(source)); + var refused = Assert.Throws(() => RvtWriter.SetParameters(source, Output, + [new(ProjectId, BoundParameterId, "Staged"), new(ProjectId, BoundParameterId, null)])); + Assert.Equal("unsupported-parameter-clear", refused.Kind); + Assert.False(File.Exists(Output)); + Assert.Equal(hash, SHA256.HashData(File.ReadAllBytes(source))); + } + + [Fact] + public void RefusesProjectBoundAssignmentWhenTheFamilyAlsoDeclaresTheDefinition() + { + string source = CreateSource(family: new FamilyFixture(SameDefinition: true)); + var refused = Assert.Throws(() => RvtWriter.SetParameters(source, Output, + [new(ProjectId, DefinitionId, "Ambiguous")])); + Assert.Equal("unsupported-parameter", refused.Kind); + Assert.False(File.Exists(Output)); + } + + [Theory] + [InlineData(true, true)] + [InlineData(true, false)] + [InlineData(false, true)] + [InlineData(false, false)] + public void RejectsTheWholeBatchWhenAProjectBoundTypeAssignmentIsReadOnly(bool derived, bool hide) + { + string source = CreateSource(family: new FamilyFixture(ProjectBound: true, DerivedType: true, + BoundReadOnly: true, HideWhenNoValue: hide)); + byte[] hash = SHA256.HashData(File.ReadAllBytes(source)); + var refused = Assert.Throws(() => RvtWriter.SetParameters(source, Output, + [new(ProjectId, DefinitionId, "Staged"), new(derived ? DerivedId : ProjectId, BoundParameterId, "Unsupported")])); + Assert.Equal("read-only-parameter", refused.Kind); + Assert.False(File.Exists(Output)); + Assert.Equal(hash, SHA256.HashData(File.ReadAllBytes(source))); + } + + [Fact] + public void RejectsTheWholeBatchWhenClearingADerivedValueWithoutHideWhenNoValue() + { + string source = CreateSource(family: new FamilyFixture(ProjectBound: true, DerivedType: true, HideWhenNoValue: false)); + byte[] hash = SHA256.HashData(File.ReadAllBytes(source)); + var refused = Assert.Throws(() => RvtWriter.SetParameters(source, Output, + [new(DerivedId, BoundParameterId, "Staged"), new(DerivedId, BoundParameterId, null)])); + Assert.Equal("unsupported-parameter-clear", refused.Kind); + Assert.False(File.Exists(Output)); + Assert.Equal(hash, SHA256.HashData(File.ReadAllBytes(source))); + } + + [Fact] + public void RejectsTheBatchWhenAClearAfterTheDerivedClearIsUnsupported() + { + string source = CreateSource(family: new FamilyFixture(ProjectBound: true, DerivedType: true, DerivedBoundCopy: true)); + byte[] hash = SHA256.HashData(File.ReadAllBytes(source)); + var refused = Assert.Throws(() => RvtWriter.SetParameters(source, Output, + [new(DerivedId, BoundParameterId, null), new(ProjectId, DefinitionId, null)])); + Assert.Equal("unsupported-parameter-clear", refused.Kind); + Assert.False(File.Exists(Output)); + Assert.Equal(hash, SHA256.HashData(File.ReadAllBytes(source))); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void RefusesClearingAValueDeclaredInTheFamily(bool sameDefinition) + { + string source = CreateSource(family: new FamilyFixture(Instance: true, ProjectBound: !sameDefinition, SameDefinition: sameDefinition)); + byte[] hash = SHA256.HashData(File.ReadAllBytes(source)); + RvtParameterEdit[] edits = sameDefinition ? [new(ProjectId, DefinitionId, null)] + : [new(ProjectId, BoundParameterId, null), new(ProjectId, DefinitionId, null)]; + var refused = Assert.Throws(() => RvtWriter.SetParameters(source, Output, edits)); + Assert.Equal("unsupported-parameter-clear", refused.Kind); + Assert.False(File.Exists(Output)); + Assert.Equal(hash, SHA256.HashData(File.ReadAllBytes(source))); + } + + private string CreateSource(string xmlValue = "Owner", bool duplicate = false, bool wall = false, bool grouped = false, bool global = false, + UserParameter? user = null, FamilyFixture? family = null, int release = 2022, + BuiltInParameter? builtIn = null, string? builtInValue = null, GlobalFixture? globalParameter = null, + GlobalFormulaFixture? globalFormulas = null, ProjectAssociation? association = null, OrdinaryTarget? projectTarget = null, + int? targetLevelDesignOption = null, ProjectImage? image = null) + { + var tags = Tags(release); + bool material = user?.Kind is Kind.Material or Kind.FamilyType || family?.BoundFamilyType == true || image is not null; + projectTarget ??= family?.ProjectTarget; + var schema = new SchemaStreamEditorTests.Writer(); + void Add(string name, params Fld[] fields) => schema.Top(new(name, new NoRef(), 1, fields, [])); + Fld Reference(string name, int id, byte mods = 0) => new(name, 14, mods, Target: new Back(id)); + Add("Identifier", new Fld("m_id", 4)); // 12 + Add("OriginalElementId", Reference("m_id", 12)); // 13 + Add("ElementId", Reference("m_id", 12)); // 14 + Add("ElemHistory", Reference("m_originalElementId", 13), new("m_creationDate", 4), new("m_lastModificationDate", 4), new("m_lastUserModificationDate", 4)); // 15 + Add("ElemRec", Reference("m_id", 14), Reference("m_history", 15), new("m_partitionId", 4), Reference("m_OwningElementId", 14)); // 16 + Add("ElemTable", Reference("m_elemArr", 16, 0x50)); // 17 + Add("ParamValueAString", new Fld("m_paramId", 4), new("m_value", 8)); // 18 + Add("ParamValueSetAString", Reference("m_paramSet", 18, 0x50)); // 19 + List elementFields = [Reference("m_id", 14), new("m_pParamValueSetAString", 14, 1), new("m_pParamValueSetInt", 14, 1), new("m_pParamValueSetDouble", 14, 1)]; + if (material) + elementFields.Add(new("m_pParamValueSetElementId", 14, 1)); + Add("Element", elementFields.ToArray()); // 20 + schema.Top(new("ProjectInfo", new Back(20), 1, [], [])); // 21 + Fld[] ownerFields = material || user is { Store: not StoreState.Value } + ? [new("m_pGroup", 14, 1), new("m_pTail", 14, 1)] : [new("m_pGroup", 14, 1)]; + if (association is not null) + ownerFields = [.. ownerFields, new("m_association", 14, 1)]; + schema.Top(new("SWall", new Back(20), 1, ownerFields, [])); // 22 + Add("GroupMembership"); // 23 + Add(globalParameter is null ? "ParamElemGlobal" : "UnrelatedRecord"); // 24 + Add("ParamDef", new Fld("m_paramElemId", 4), new("m_readOnly", 1)); // 25 + schema.Top(new("ParamDefString", new Back(25), 1, [], [])); // 26 + schema.Top(new("ParamDefInt", new Back(25), 1, [new("m_lowBound", 4), new("m_upBound", 4)], [])); // 27 + schema.Top(new("ParamDefYesNo", new Back(25), 1, [], [])); // 28 + Add("ForgeTypeId", new Fld("m_typeId", 8)); // 29 + schema.Top(new("ParamDefValue", new Back(25), 1, + [release == 2020 ? new("m_unitType", 4) : Reference("m_specTypeId", 29), new("m_restriction", 4), new("m_boundless", 1)], [])); // 30 + schema.Top(new("ParamElem", new Back(20), 1, [new("m_pParamDef", 14, 1)], [])); // 31 + schema.Top(new("ParamElemExternal", new Back(31), 1, [new("m_bindingIds", 4, 0x50), new("m_userModifiable", 1), new("m_hideWhenNoValue", 1)], [])); // 32 + schema.Top(new("ParamElemProject", new Back(31), 1, [new("m_bindingIds", 4, 0x50)], [])); // 33 + schema.Top(new("ParamBinding", new Back(20), 1, [new("m_paramId", 4), new("m_categoryId", 4), new("m_elemOrSymbol", 4)], [])); // 34 + Add("ParamValueInt", new Fld("m_paramId", 4), new("m_value", 4)); // 35 + Add("ParamValueSetInt", Reference("m_paramSet", 35, 0x50)); // 36 + Fld doubleValue = new("m_value", 7), doubleId = new("m_paramId", 4); + Add("ParamValueDouble", user?.IdFirst == true ? [doubleId, doubleValue] : [doubleValue, doubleId]); // 37 + Add("ParamValueSetDouble", Reference("m_paramSet", 37, 0x50)); // 38 + Add("NamedParam", new Fld("m_str", 8), new("m_oExpression", 14, 1), new("m_value", 7), new("m_elemId", 4), + new("m_paramId", 4), new("m_int", 4), new("m_instance", 1), new("m_reporting", 1)); // 39 + Add("FamilyParams", Reference("m_params", 39, 0x50)); // 40 + Fld[] familyFields = [new("m_familyParams", 14, 2), new("m_categoryId", 4), new("m_trivialParamIds", 4, 0x50), + new("m_inPlace", 1), new("m_name", 8)]; + if (projectTarget is not null) + familyFields = [..familyFields, new("m_oFamDoc", 14, 2), new("m_familyIds", 14, 2), new("m_bShared", 1)]; + schema.Top(new("FamilyBase", new Back(20), 1, familyFields, [])); // 41 + schema.Top(new("Family", new Back(41), 1, [], [])); // 42 + Add("InstInfoBase", new Fld("m_symbolId", 4)); // 43 + schema.Top(new("InstanceInfo", new Back(43), 1, [], [])); // 44 + Fld[] instanceFields = [new("m_pInstParams", 14, 2), new("m_pInstanceInfo", 14, 2), new("m_masterSymbolId", 4), new("m_superInstanceId", 4)]; + Fld[] symbolFields = [new("m_pParams", 14, 2), new("m_familyId", 4), new("m_masterId", 4), new("m_ownerInstanceId", 4)]; + if (projectTarget is not null) + symbolFields = [..symbolFields, new("m_active", 1)]; + if (association is not null && family is { Instance: true }) + instanceFields = [..instanceFields, new("m_association", 14, 1)]; + if (association is not null && family is { Instance: false }) + symbolFields = [..symbolFields, new("m_association", 14, 1)]; + schema.Top(new("FamilyInstance", new Back(20), 1, instanceFields, [])); // 45 + schema.Top(new("FamilySymbol", new Back(20), 1, symbolFields, [])); // 46 + schema.Top(new("ParamElemFamily", new Back(31), 1, [new("m_instanceParam", 1)], [])); // 47 + Add("ElementHeader", new Fld("m_regenHistoryCount", 4), Reference("m_categroryId", 14), + Reference("m_familyId", 14), Reference("m_ownerViewId", 14), Reference("m_designOptionId", 14)); // 48 + Add("Tail", new Fld("m_value", 4)); // 49 + schema.Top(new("BasicWallType", new Back(20), 1, ownerFields, [])); // 50 + schema.Top(new("RoomElem", new Back(20), 1, ownerFields, [])); // 51 + schema.Top(new("ParamDefMaterialBrowse", new Back(25), 1, + [new("m_unassignedString", 4), new("m_extraButtonFlag", 4), new("m_includeParams", 1)], [])); // 52 + Add("ParamValueElementId", Reference("m_paramId", 14), Reference("m_value", 14)); // 53 + Add("ParamValueSetElementId", Reference("m_paramSet", 53, 0x50)); // 54 + Add("Material", new Fld("m_name", 8)); // 55 + schema.Top(new("MaterialElem", new Back(20), 1, [new("m_pMaterial", 14, 1)], [])); // 56 + Add("AStringWrapper", new Fld("m_str", 8)); // 57 + Add("ParamStorage", Reference("m_str", 57), new("m_dbl", 7), Reference("m_elemId", 14), new("m_int", 4), new("m_storageType", 4)); // 58 + schema.Top(new(globalParameter is null ? "GlobalRecord" : "ParamElemGlobal", new Back(31), 1, + [Reference("m_constraintId", 14), Reference("m_propertyId", 14), new("m_reporting", 1), Reference("m_value", 58), new("m_oExpression", 14, 1)], [])); // 59 + if (association is null) + Add("ParamIdPair", Reference("m_famParamId", 14)); // 60 + else + Add("ParamIdPair", Reference("m_famParamId", 14), Reference("m_elemPropId", 14), new("m_geomTag", 4), new("m_bIsSymbol", 1)); + schema.Top(new("AssociatedElement", new Back(20), 1, [Reference("m_parameter", 60)], [])); // 61 + Add("FormulaTokenParameter", Reference("m_paramId", 14)); // 62 + Add("BinaryOperatorExpression", new Fld("m_binaryOperator", 4), new("m_pLeftSubexpression", 14, 1), new("m_pRightSubexpression", 14, 1)); // 63 + Add("ParameterExpression", Reference("m_paramId", 14)); // 64 + Add("NumberConstantExpression", new Fld("m_value", 7), Reference("m_specTypeId", 29)); // 65 + Add("FunctionExpression", new Fld("m_function", 4), new("m_subexpressions", 14, 0x51)); // 66 + Add("ParametrizedElemParamsCellBase", Reference("m_paramDrivenData", 60, 0x50)); // 67 + schema.Top(new("ProjectParametrizedElemParamsCell", new Back(67), 1, [], [])); // 68 + schema.Top(new("ParamDefFamType", new Back(25), 1, [new("m_categoryId", 4)], [])); // 69 + schema.Top(new("NestedFamSymRefElem", new Back(20), 1, + [new("m_famName", 8), new("m_symName", 8), new("m_categoryId", 4)], [])); // 70 + Add("ForeignElemRef", new Fld("m_id", 4)); // 71 + Add("std::pair< ElementId, ForeignElemRef >", Reference("first", 14), Reference("second", 71)); // 72 + Add("FamilyDocument", Reference("m_big2SmallMap2", 72, 0x50)); // 73 + Add("ElementIdPlusIndex", Reference("m_elementId", 14), new("m_index", 4)); // 74 + Add("ElementIdIndexPairSet", Reference("m_data", 74, 0x50)); // 75 + schema.Top(new("SpecializedFamilySymbol", new Back(46), 1, [], [])); // 76 + schema.Top(new("Level", new Back(20), 1, [], [])); // 77 + Add("SymbolInfo", new Fld("m_name", 8)); // 78 + schema.Top(new("Symbol", new Back(20), 1, [new Fld("m_symbolInfo", 14, 1)], [])); // 79 + var imageFields = new Fld[] { Reference("m_idImageHolder", 14), new("m_flags", 4), Reference("m_viewId", 14), + Reference("m_ownerSymbolId", 14), new("m_widthInPixels", 4), new("m_heightInPixels", 4) }; + if (image?.LinkedPath is not null) + imageFields = [..imageFields, new("m_externalResource", 14, 1)]; + schema.Top(new("ImageSymbol", new Back(79), 1, imageFields, [])); // 80 + Add("ARasterImage", new Fld("m_compressedImage", 2, 0x50), new("m_width", 4), new("m_height", 4)); // 81 + schema.Top(new("ImageHolder", new Back(20), 1, + [new Fld("m_pRasterImage", 14, 1), Reference("m_idImageSymbol", 14), new("m_flags", 4)], [])); // 82 + Add("std::pair< AString, AString >", new Fld("first", 8), new Fld("second", 8)); // 83 + Add("ExternalResourceRef", Reference("m_referenceInformation", 83, 0x50)); // 84 + Add("ExternalResourceReferenceCell", Reference("m_externalResourceReferences", 84, 0x50)); // 85 + for (int i = 86; i < tags.ContentKey; i++) + Add("Filler" + i); + foreach (string marker in new[] { "ContentKey", "ContentMarker", "SegmentMarker", "SegmentCheckback", "SignatureMarker" }) + Add(marker); + + string path = Path.Combine(_folder, "source.rvt"); + using var root = RootStorage.Create(path, OpenMcdf.Version.V4); + using (var basic = root.CreateStream("BasicFileInfo")) + basic.Write(RvtWriterTests.BuildBasicFileInfoBytes(release)); + using (var formats = root.CreateStorage("Formats").CreateStream("Latest")) + formats.Write(PagedStreamCodec.Encode([], schema.Build())); + using (var elemTable = root.CreateStorage("Global").CreateStream("ElemTable")) + { + int[] owners = family is { Instance: true, OnlyPrimary: true } ? [ProjectId, DefinitionId, FamilyId, MasterId] + : family is { Instance: true } ? [ProjectId, DefinitionId, FamilyId, MasterId, DerivedId] + : family is { OnlyPrimary: true } or { ProjectBound: true, DerivedType: false } ? [ProjectId, DefinitionId, FamilyId] + : family is not null ? [ProjectId, DefinitionId, FamilyId, DerivedId] + : material ? [ProjectId, DefinitionId, BindingId, OriginalMaterialId, TargetMaterialId] + : user is not null ? [ProjectId, DefinitionId, BindingId] : [ProjectId]; + if (family is { ProjectBound: true }) + owners = [..owners, BoundParameterId, BindingId]; + if (family is { SameDefinition: true }) + owners = [..owners, BindingId]; + if (family is { Formula: true }) + owners = [..owners, FamilyFormulaResultId]; + if (family?.Reference is not null) + owners = [..owners, NestedTypeId, TargetMaterialId]; + if (projectTarget is not null) + owners = [..owners, ProjectTargetFamilyId, ProjectTargetSymbolId]; + if (projectTarget is { DependentSymbol: true }) + owners = [..owners, DependentTargetSymbolId]; + if (projectTarget?.LinkedFamilyMap is not null) + owners = [..owners, LinkedFamilyId, LinkedSymbolId]; + if (user?.Kind == Kind.FamilyType) + owners = [..owners, NestedTypeId]; + if (targetLevelDesignOption is not null) + owners = [..owners, TargetLevelId]; + if (image is not null) + owners = [..owners, ImageId, RasterHolderId]; + if (globalParameter is not null) + { + int id = association?.GlobalId ?? DefinitionId; + owners = globalParameter.Consumer ? [..owners, id, BindingId] : [..owners, id]; + } + if (globalFormulas is not null) + owners = globalFormulas.Consumer ? [..owners, BindingId, GlobalFormulaResultId, GlobalFormulaConsumerId] + : [..owners, BindingId, GlobalFormulaResultId]; + Array.Sort(owners); + byte[] table = new byte[6 + owners.Length * 28]; + table[0] = 17; + table[2] = (byte)owners.Length; + for (int i = 0; i < owners.Length; i++) + BinaryPrimitives.WriteInt32LittleEndian(table.AsSpan(6 + 28 * i), owners[i]); + elemTable.Write(PagedStreamCodec.Encode(new byte[8], table)); + } + using (var partition = root.CreateStorage("Partitions").CreateStream("0")) + { + var category = (user?.Owner ?? image?.Owner) == OwnerKind.Room ? BuiltInCategory.OST_Rooms : BuiltInCategory.OST_Walls; + ushort ownerTag = user is not null ? (ushort)user.Owner : wall ? (ushort)22 : (ushort)21; + var records = new List<(ulong, ushort, byte[])> + { (ProjectId, ownerTag, user is null ? Body(wall ? xmlValue : "Owner", duplicate, wall, grouped, association)[2..] : UserBody(user, grouped: grouped, association: association)[2..]) }; + if (builtIn is BuiltInParameter builtInParameter) + { + byte[] body = BuiltInBody(builtInParameter, builtInValue); + records[0] = (ProjectId, BinaryPrimitives.ReadUInt16LittleEndian(body), body[2..]); + } + if (family is not null) + records = FamilyRecords(family, association); + if (projectTarget is not null) + AddOrdinaryTarget(records, projectTarget, material, family is { Instance: true } ? MasterId : ProjectId); + if (user is not null) + { + records.Add((DefinitionId, user.Shared ? (ushort)32 : (ushort)33, DefinitionBody(user, release))); + records.Add((BindingId, 34, Pack(writer => + { + WriteEmptyElement(writer, BindingId, material); + writer.Write(DefinitionId); + writer.Write((int)category); + writer.Write(user.Binding); + }))); + } + if (user?.Kind is Kind.Material or Kind.FamilyType) + { + foreach (int id in new[] { OriginalMaterialId, TargetMaterialId }) + records.Add(((ulong)id, 56, Pack(writer => + { + WriteEmptyElement(writer, id, material: true); + WritePointer(writer, 55); + WriteText(writer, $"Material {id}"); + }))); + } + if (user?.Kind == Kind.FamilyType) + records.Add((NestedTypeId, 70, Pack(writer => + { + WriteEmptyElement(writer, NestedTypeId, material: true); + WriteText(writer, "Nested"); + WriteText(writer, "Standard"); + writer.Write((int)BuiltInCategory.OST_GenericModel); + }))); + if (targetLevelDesignOption is not null) + records.Add((TargetLevelId, 77, Pack(writer => WriteEmptyElement(writer, TargetLevelId, material)))); + if (image is { } imageFixture) + { + bool linked = imageFixture.LinkedPath is not null; + records[0] = (ProjectId, (ushort)imageFixture.Owner, ProjectImageBody(imageFixture)[2..]); + records.Add((ImageId, 80, Pack(writer => + { + WriteEmptyElement(writer, ImageId, material: true); + WritePointer(writer, 78); + writer.Write(RasterHolderId); + writer.Write(linked ? 4 : 0); + writer.Write(-1); + writer.Write(-1); + writer.Write(2); + writer.Write(2); + if (linked) + WritePointer(writer, 85); + WriteText(writer, "Picture.png"); + if (linked) + { + writer.Write(1); + writer.Write(2); + WriteText(writer, "Path"); + WriteText(writer, imageFixture.LinkedPath!); + WriteText(writer, "PathType"); + WriteText(writer, imageFixture.PathType); + } + }))); + records.Add((RasterHolderId, 82, Pack(writer => + { + WriteEmptyElement(writer, RasterHolderId, material: true); + WritePointer(writer, linked ? 0 : 81); + writer.Write(imageFixture.BrokenHolder ? ProjectId : ImageId); + writer.Write(linked ? 1 : 0); + if (!linked) + { + writer.Write(4); + writer.Write(new byte[] { 1, 2, 3, 4 }); + writer.Write(2); + writer.Write(2); + } + }))); + } + if (global) + records.Add((ProjectId + 3, 24, [])); + if (globalParameter is not null) + { + string initial = globalParameter.InitialValue ?? (globalFormulas is null ? "0" : globalFormulas.Conditional ? "1" : "2"); + int id = association?.GlobalId ?? DefinitionId; + records.Add(((ulong)id, 59, GlobalBody(globalParameter, initial, id)[2..])); + if (globalParameter.Consumer) + records.Add((BindingId, 61, Pack(writer => + { + WriteEmptyElement(writer, BindingId); + writer.Write(DefinitionId); + }))); + } + if (globalFormulas is not null) + { + var number = new GlobalFixture(Kind.Number); + bool division = globalFormulas.Operation == 4; + bool conditional = globalFormulas.Conditional; + var first = new GlobalBinary(globalFormulas.Operation, DefinitionId, division ? 12 : globalFormulas.IntegerResult ? 1.25 : 2, + ConstantFirst: division, SpecId: globalFormulas.ConstantSpecId); + int function = globalFormulas.Function; + double cached = function switch + { + 7 => Math.Exp(2), + 9 => Math.Sqrt(2), + _ => conditional ? 2 : globalFormulas.Stale ? 13 : division ? 6 : globalFormulas.IntegerResult ? 3 : 4, + }; + var resultKind = conditional || globalFormulas.IntegerResult ? Kind.Integer : Kind.Number; + records.Add((BindingId, 59, GlobalBody(new(resultKind, Currency: globalFormulas.CurrencyResult, SpecId: globalFormulas.SpecId), + cached.ToString(CultureInfo.InvariantCulture), BindingId, + conditional || function != 0 ? null : first, conditional, function)[2..])); + double following = globalFormulas.Stale ? 5 : cached + 1; + records.Add((GlobalFormulaResultId, 59, GlobalBody(number with { SpecId = globalFormulas.SpecId }, + following.ToString(CultureInfo.InvariantCulture), GlobalFormulaResultId, + new(1, BindingId, 1, SpecId: globalFormulas.ConstantSpecId))[2..])); + if (globalFormulas.Consumer) + records.Add((GlobalFormulaConsumerId, 61, Pack(writer => + { + WriteEmptyElement(writer, GlobalFormulaConsumerId); + writer.Write(GlobalFormulaResultId); + }))); + } + var block = PartitionStreamEditorTests.MakeStandardBlock(4, keyed: false, records.ToArray()); + if (user is not null || family is not null || builtIn is not null || association is not null || image is not null) + { + byte[] header = new byte[22]; + BinaryPrimitives.WriteUInt16LittleEndian(header, 48); + BinaryPrimitives.WriteInt32LittleEndian(header.AsSpan(6), (int)(family?.Category ?? category)); + BinaryPrimitives.WriteInt32LittleEndian(header.AsSpan(18), -1); + block.Chains[0].Records[0] = new(ProjectId, header); + if (family is { DerivedType: true }) + { + var headers = block.Chains[0].Records; + int index = Array.FindIndex(headers, entry => entry.Owner == DerivedId); + headers[index] = new(DerivedId, header); + } + if (family is { Instance: true, BoundFamilyType: true }) + { + var headers = block.Chains[0].Records; + int index = Array.FindIndex(headers, entry => entry.Owner == MasterId); + headers[index] = new(MasterId, header); + } + if (projectTarget is not null) + { + byte[] targetHeader = (byte[])header.Clone(); + BinaryPrimitives.WriteInt32LittleEndian(targetHeader.AsSpan(6), (int)projectTarget.Category); + var headers = block.Chains[0].Records; + int index = Array.FindIndex(headers, entry => entry.Owner == ProjectTargetSymbolId); + headers[index] = new(ProjectTargetSymbolId, targetHeader); + } + if (targetLevelDesignOption is int designOption) + { + byte[] levelHeader = (byte[])header.Clone(); + BinaryPrimitives.WriteInt32LittleEndian(levelHeader.AsSpan(6), (int)BuiltInCategory.OST_Levels); + BinaryPrimitives.WriteInt32LittleEndian(levelHeader.AsSpan(18), designOption); + var headers = block.Chains[0].Records; + int index = Array.FindIndex(headers, entry => entry.Owner == TargetLevelId); + headers[index] = new(TargetLevelId, levelHeader); + } + if (image is not null) + { + byte[] imageHeader = (byte[])header.Clone(); + BinaryPrimitives.WriteInt32LittleEndian(imageHeader.AsSpan(6), (int)BuiltInCategory.OST_RasterImages); + BinaryPrimitives.WriteInt32LittleEndian(imageHeader.AsSpan(18), image.DesignOption); + var headers = block.Chains[0].Records; + int index = Array.FindIndex(headers, entry => entry.Owner == ImageId); + headers[index] = new(ImageId, imageHeader); + } + } + partition.Write(PartitionStreamEditorTests.BuildPartitionStream(4, tags, block)); + } + using var info = root.CreateStream("ProjectInformation"); + using var zip = new ZipArchive(info, ZipArchiveMode.Create); + using var output = zip.CreateEntry("sample.project.xml").Open(); + using var writer = new StreamWriter(output); + writer.Write($"""{xmlValue}Owner"""); + return path; + } + + private static List<(ulong, ushort, byte[])> FamilyRecords(FamilyFixture options, ProjectAssociation? association) + { + int master = options.Instance ? MasterId : ProjectId; + int numericDefinition = options.NumericFormula?.CurrencyInput is not null ? 30 : 27; + var bound = options.ProjectBound && options.BoundValue && !options.BoundFamilyType ? BindStore.Value : BindStore.None; + int? boundReference = options.BoundFamilyType && options.BoundValue ? -1 : null; + var records = new List<(ulong, ushort, byte[])> + { + (ProjectId, options.Instance ? (ushort)45 : (ushort)46, + options.Instance ? (options.InstanceComment is { } comment + ? InstanceBody(options.Inherited ? null : "Old", BindStore.Value, comment, (int)BuiltInParameter.ALL_MODEL_INSTANCE_COMMENTS) + : InstanceBody(options.Inherited ? null : "Old", bound, + formulaResult: options.Formula ? options.InstanceFormulaCache ?? "Old" : null, association: association, + reference: options.Reference?.Value, primary: options.OnlyPrimary, + referenceStore: options.BoundFamilyType, boundReference: boundReference))[2..] + : SymbolBody(ProjectId, -1, "Old", bound: bound, identity: options.Identity, + formula: options.Formula, numericFormula: options.NumericFormula, + association: association is { Derived: false } ? association : null, + associationSlot: association is not null, typedCost: options.TypedCost, reference: options.Reference?.Value, + active: options.ProjectTarget is null ? null : true, referenceStore: options.BoundFamilyType, + boundReference: boundReference)[2..]), + (DefinitionId, options.SameDefinition ? (ushort)32 : (ushort)47, Pack(writer => + { + WriteEmptyElement(writer, DefinitionId, material: options.BoundFamilyType); + WritePointer(writer, options.Reference is not null ? 69 : options.NumericFormula is null ? 26 : numericDefinition); + if (options.SameDefinition) + WriteBoundDefinition(writer, DefinitionId); + else + { + writer.Write(options.Instance); + writer.Write(DefinitionId); + writer.Write(options.Reference?.ReadOnly ?? false); + if (options.Reference is not null) + writer.Write((int)BuiltInCategory.OST_GenericModel); + if (options.NumericFormula is not null) + WriteNumericDefinition(writer); + } + })), + (FamilyId, 42, Pack(writer => + { + WriteEmptyElement(writer, FamilyId, material: options.BoundFamilyType); + WritePointer(writer, 40); + writer.Write((int)options.Category); + writer.Write((options.Trivial ? 1 : 0) + (options.Formula && options.FormulaTrivial ? 1 : 0)); + if (options.Trivial) + writer.Write(DefinitionId); + if (options.Formula && options.FormulaTrivial) + writer.Write(FamilyFormulaResultId); + writer.Write(false); + WriteText(writer, "Host"); + if (options.ProjectTarget is { } target) + { + int map = target.LinkedFamilyMap == FamilyId || target.ContainsOwner ? 73 : 0; + WritePointer(writer, map); + WritePointer(writer, map == 0 ? 0 : 75); + writer.Write(target.ContainsOwner); + } + WriteNamedStore(writer, "Old", options.Instance, options.Reporting, options.Identity, options.Formula, + numericFormula: options.NumericFormula, reference: options.Reference?.Value); + if (options.Formula) + WriteFamilyFormula(writer, options.NumericFormula); + if (options.ProjectTarget is { ContainsOwner: true } owner) + WriteFamilyMaps(writer, [NestedTypeId], owner.OwnerHasProxy ? [NestedTypeId] : []); + else if (options.ProjectTarget?.LinkedFamilyMap == FamilyId) + WriteFamilyMaps(writer, [TargetMaterialId], []); + })), + }; + if (options.Reference is { } reference) + { + records.Add((NestedTypeId, 70, Pack(writer => + { + WriteEmptyElement(writer, NestedTypeId, material: options.BoundFamilyType); + WriteText(writer, reference.TargetFamily); + WriteText(writer, "Standard"); + writer.Write((int)reference.TargetCategory); + }))); + records.Add((TargetMaterialId, 56, Pack(writer => + { + WriteEmptyElement(writer, TargetMaterialId, material: options.BoundFamilyType); + WritePointer(writer, 55); + WriteText(writer, "Finish"); + }))); + } + if (!options.OnlyPrimary && (options.Instance || !options.ProjectBound || options.DerivedType)) + records.Add((DerivedId, 46, SymbolBody(DerivedId, master, options.Diverged ? "Different" : "Old", options.Instance, + options.DerivedBoundCopy ? BindStore.Value : BindStore.None, identity: options.Identity, + formula: options.Formula, numericFormula: options.NumericFormula, + association: association is { Derived: true } or { PrimaryAndDerived: true } ? association : null, + associationSlot: association is not null && !options.Instance, + reference: options.Reference is { } nested ? options.Diverged ? OriginalMaterialId : nested.Value : null, + active: options.ProjectTarget is null ? null : true, referenceStore: options.BoundFamilyType)[2..])); + if (options.Formula) + records.Add((FamilyFormulaResultId, 47, Pack(writer => + { + WriteEmptyElement(writer, FamilyFormulaResultId); + WritePointer(writer, options.NumericFormula is null ? 26 : numericDefinition); + writer.Write(options.Instance); + writer.Write(FamilyFormulaResultId); + writer.Write(false); + if (options.NumericFormula is not null) + WriteNumericDefinition(writer); + }))); + if (options.Instance) + records.Add((MasterId, 46, SymbolBody(MasterId, -1, "Old", true, formula: options.Formula, + reference: options.Reference?.Value, active: options.ProjectTarget is null ? null : true, + referenceStore: options.BoundFamilyType)[2..])); + if (options.ProjectBound) + records.Add((BoundParameterId, options.SharedBinding ? (ushort)32 : (ushort)33, Pack(writer => + { + WriteEmptyElement(writer, BoundParameterId, material: options.BoundFamilyType); + WritePointer(writer, options.BoundFamilyType ? 69 : 26); + WriteBoundDefinition(writer, BoundParameterId, options.HideWhenNoValue, options.BoundReadOnly, options.SharedBinding); + if (options.BoundFamilyType) + writer.Write((int)BuiltInCategory.OST_GenericModel); + }))); + if (options.ProjectBound || options.SameDefinition) + records.Add((BindingId, 34, Pack(writer => + { + WriteEmptyElement(writer, BindingId, material: options.BoundFamilyType); + writer.Write(options.SameDefinition ? DefinitionId : BoundParameterId); + writer.Write((int)options.Category); + writer.Write(options.Instance ? 1 : 2); + }))); + return records; + + void WriteNumericDefinition(BinaryWriter writer) + { + if (options.NumericFormula?.CurrencyInput is not null) + { + WriteText(writer, "autodesk.spec.measurable:currency-2.0.0"); + writer.Write(1); + writer.Write(false); + } + else + { + writer.Write(int.MinValue); + writer.Write(int.MaxValue); + } + } + } + + private static void AddOrdinaryTarget(List<(ulong, ushort, byte[])> records, OrdinaryTarget target, bool referenceStore, + int referringType) + { + AddFamily(ProjectTargetFamilyId, "Target", target.ContainsOwner ? [FamilyId, referringType, NestedTypeId] : [target.MappedId]); + records.Add((ProjectTargetSymbolId, 46, SymbolBody(ProjectTargetSymbolId, -1, "Target", + reference: target.SavedReference, familyId: ProjectTargetFamilyId, active: target.Active, referenceStore: referenceStore)[2..])); + if (target.DependentSymbol) + records.Add((DependentTargetSymbolId, 76, SymbolBody(DependentTargetSymbolId, -1, "Other type", + reference: ProjectId, familyId: ProjectTargetFamilyId, active: true, referenceStore: referenceStore)[2..])); + if (target.LinkedFamilyMap is int linked) + { + AddFamily(LinkedFamilyId, "Linked", [linked]); + records.Add((LinkedSymbolId, 46, SymbolBody(LinkedSymbolId, -1, "Linked type", familyId: LinkedFamilyId, + active: true, referenceStore: referenceStore)[2..])); + } + + void AddFamily(int id, string name, int[] external) + { + records.Add(((ulong)id, 42, Pack(writer => + { + WriteEmptyElement(writer, id, material: referenceStore); + WritePointer(writer, 40); + writer.Write((int)target.Category); + writer.Write(0); + writer.Write(false); + WriteText(writer, name); + WritePointer(writer, 73); + WritePointer(writer, 75); + writer.Write(false); + writer.Write(0); + WriteFamilyMaps(writer, external, []); + }))); + } + } + + private static void WriteFamilyMaps(BinaryWriter writer, int[] external, int[] owned) + { + writer.Write(external.Length); + foreach (int id in external) + { + writer.Write(id); + writer.Write(1); + } + writer.Write(owned.Length); + for (int index = 0; index < owned.Length; index++) + { + writer.Write(owned[index]); + writer.Write(index); + } + } + + private static void WriteBoundDefinition(BinaryWriter writer, int id, bool hideWhenNoValue = true, bool readOnly = false, bool shared = true) + { + writer.Write(1); + writer.Write(BindingId); + if (shared) + { + writer.Write(true); + writer.Write(hideWhenNoValue); + } + writer.Write(id); + writer.Write(readOnly); + } + + private enum BindStore { None, Value, Empty } + + private static byte[] SymbolBody(int id, int master, string value, bool instanceDefault = false, BindStore bound = BindStore.None, + string boundText = "Bound value", StoredIdentity? identity = null, bool formula = false, + NumericFamilyFormula? numericFormula = null, ProjectAssociation? association = null, bool associationSlot = false, + double? typedCost = null, int? reference = null, int familyId = FamilyId, bool? active = null, bool referenceStore = false, + int? boundReference = null) => Pack(writer => + { + writer.Write((ushort)46); + WriteEmptyElement(writer, id, material: referenceStore, + textStore: bound != BindStore.None || identity?.CompetingTypedCopy == true, doubleStore: typedCost.HasValue, + elementIdStore: boundReference.HasValue); + WritePointer(writer, 40); + writer.Write(familyId); + writer.Write(master); + writer.Write(-1); + if (active.HasValue) + writer.Write(active.Value); + if (associationSlot) + WritePointer(writer, association is null ? 0 : 68); + WriteBoundValue(writer, bound, boundText); + if (identity is { CompetingTypedCopy: true }) + { + writer.Write(1); + writer.Write((int)identity.Parameter); + WriteText(writer, "Typed override"); + } + if (typedCost is double cost) + { + writer.Write(1); + writer.Write(cost); + writer.Write((int)BuiltInParameter.ALL_MODEL_COST); + } + WriteBoundReference(writer, boundReference); + WriteNamedStore(writer, value, instanceDefault, identity: identity, formula: formula, numericFormula: numericFormula, + reference: reference); + if (association is not null) + WriteProjectAssociation(writer, association); + if (formula) + WriteFamilyFormula(writer, numericFormula); + }); + + private static byte[] InstanceBody(string? value, BindStore bound = BindStore.None, string boundText = "Bound value", + int parameterId = BoundParameterId, string? formulaResult = null, ProjectAssociation? association = null, + int? reference = null, bool primary = false, bool referenceStore = false, int? boundReference = null) => Pack(writer => + { + writer.Write((ushort)45); + WriteEmptyElement(writer, ProjectId, material: referenceStore, textStore: bound != BindStore.None, + elementIdStore: boundReference.HasValue); + WritePointer(writer, 40); + WritePointer(writer, 44); + writer.Write(MasterId); + writer.Write(-1); + if (association is not null) + WritePointer(writer, 68); + WriteBoundValue(writer, bound, boundText, parameterId); + WriteBoundReference(writer, boundReference); + WriteNamedStore(writer, value, formulaResult: formulaResult, reference: reference); + writer.Write(primary ? MasterId : DerivedId); + if (association is not null) + WriteProjectAssociation(writer, association); + }); + + private static void WriteBoundReference(BinaryWriter writer, int? reference) + { + if (reference is not int id) + return; + writer.Write(1); + writer.Write(BoundParameterId); + writer.Write(id); + } + + private static void WriteBoundValue(BinaryWriter writer, BindStore state, string value = "Bound value", int parameterId = BoundParameterId) + { + if (state == BindStore.None) + return; + writer.Write(state == BindStore.Value ? 1 : 0); + if (state == BindStore.Value) + { + writer.Write(parameterId); + WriteText(writer, value); + } + } + + private static void WriteNamedStore(BinaryWriter writer, string? value, bool instance = false, bool reporting = false, + StoredIdentity? identity = null, bool formula = false, string? formulaResult = null, NumericFamilyFormula? numericFormula = null, + int? reference = null) + { + writer.Write((value is null ? 0 : 1) + (identity is null ? 0 : 1) + (formula || formulaResult is not null ? 1 : 0)); + if (value is not null) + WriteRow(DefinitionId, numericFormula is null && reference is null ? value : "", numericFormula?.CurrencyInput ?? 0, + instance, reporting, integer: numericFormula?.CurrencyInput is null ? numericFormula?.Input ?? 0 : 0, elementId: reference ?? -1); + if (formula && numericFormula is { CurrencyInput: double amount } currency) + WriteRow(FamilyFormulaResultId, "", currency.Operation == 3 ? 2 * amount : amount / 2d, instance, false, expression: 63); + else if (formula && numericFormula is { } numerical) + WriteRow(FamilyFormulaResultId, "", 0, instance, false, expression: 63, + integer: numerical.Operation == 3 ? 2 * numerical.Input : (int)Math.Floor(numerical.Input / 2d + 0.5)); + else if (formula) + WriteRow(FamilyFormulaResultId, value!, 0, instance, false, expression: 64); + else if (formulaResult is not null) + WriteRow(FamilyFormulaResultId, formulaResult, 0, false, false); + if (identity is not null) + { + bool cost = identity.Parameter == BuiltInParameter.ALL_MODEL_COST; + WriteRow((int)identity.Parameter, cost ? "" : identity.Value, + cost ? double.Parse(identity.Value, System.Globalization.CultureInfo.InvariantCulture) : 0, false, false); + } + + void WriteRow(int id, string text, double number, bool isInstance, bool isReporting, ushort expression = 0, int integer = 0, + int elementId = -1) + { + WriteText(writer, text); + if (expression == 0) + writer.Write(0u); + else + WritePointer(writer, expression); + writer.Write(number); writer.Write(elementId); + writer.Write(id); writer.Write(integer); writer.Write(isInstance); writer.Write(isReporting); + } + } + + private static void WriteFamilyFormula(BinaryWriter writer, NumericFamilyFormula? numericFormula) + { + if (numericFormula is not null) + { + writer.Write(numericFormula.Operation); + WritePointer(writer, 64); + WritePointer(writer, 65); + } + writer.Write(DefinitionId); + if (numericFormula is not null) + { + writer.Write(2.0); + WriteText(writer, "autodesk.spec.aec:number-2.0.0"); + } + } + + private static byte[] Body(string value, bool duplicate = false, bool wall = false, bool grouped = false, ProjectAssociation? association = null) + { + using var stream = new MemoryStream(); + using var writer = new BinaryWriter(stream); + writer.Write(wall ? (ushort)22 : (ushort)21); + writer.Write(ProjectId); + writer.Write(uint.MaxValue); + writer.Write((ushort)19); + writer.Write(0u); + writer.Write(0u); + if (wall) + { + writer.Write(grouped ? uint.MaxValue : 0); + if (grouped) + writer.Write((ushort)23); + } + if (association is not null) + WritePointer(writer, 68); + writer.Write(2); + writer.Write((int)(wall ? BuiltInParameter.ALL_MODEL_INSTANCE_COMMENTS : BuiltInParameter.CLIENT_NAME)); + writer.Write(value.Length); + writer.Write(Encoding.Unicode.GetBytes(value)); + writer.Write((int)(duplicate ? BuiltInParameter.CLIENT_NAME : BuiltInParameter.PROJECT_NAME)); + writer.Write(5); + writer.Write(Encoding.Unicode.GetBytes("Owner")); + if (association is not null) + WriteProjectAssociation(writer, association); + return stream.ToArray(); + } + + private static byte[] BuiltInBody(BuiltInParameter parameter, string? value) => Pack(writer => + { + bool instance = parameter is BuiltInParameter.ALL_MODEL_MARK or BuiltInParameter.ALL_MODEL_INSTANCE_COMMENTS; + bool cost = parameter == BuiltInParameter.ALL_MODEL_COST; + writer.Write((ushort)(instance ? OwnerKind.Wall : OwnerKind.WallType)); + writer.Write(ProjectId); + WritePointer(writer, !cost && value is not null ? 19 : 0); + WritePointer(writer, 0); + WritePointer(writer, cost && value is not null ? 38 : 0); + WritePointer(writer, 0); + if (value is not null) + { + writer.Write(1); + if (cost) + writer.Write(double.Parse(value, System.Globalization.CultureInfo.InvariantCulture)); + writer.Write((int)parameter); + if (!cost) + WriteText(writer, value); + } + }); + + private static BuiltInParameter ImageParameter(OwnerKind owner) => owner == OwnerKind.WallType + ? BuiltInParameter.ALL_MODEL_TYPE_IMAGE : BuiltInParameter.ALL_MODEL_IMAGE; + + private static byte[] ProjectImageBody(ProjectImage image) => Pack(writer => + { + writer.Write((ushort)image.Owner); + WriteEmptyElement(writer, ProjectId, material: true, elementIdStore: image.Stored.HasValue); + WritePointer(writer, 0); + WritePointer(writer, 0); + if (image.Stored is int value) + { + writer.Write(1); + writer.Write((int)ImageParameter(image.Owner)); + writer.Write(value); + } + }); + + private static byte[] UserBody(UserParameter parameter, string? value = null, bool grouped = false, bool cleared = false, + ProjectAssociation? association = null) => Pack(writer => + { + writer.Write((ushort)parameter.Owner); + writer.Write(ProjectId); + bool present = !cleared && (value is not null || parameter.Store == StoreState.Value); + bool hasTable = present || parameter.Store != StoreState.NullPointer; + bool reference = parameter.Kind is Kind.Material or Kind.FamilyType; + WritePointer(writer, hasTable && parameter.Kind == Kind.Text ? 19 : 0); + WritePointer(writer, hasTable && parameter.Kind is Kind.Integer or Kind.YesNo ? 36 : 0); + WritePointer(writer, hasTable && parameter.Kind == Kind.Number ? 38 : 0); + if (reference) + WritePointer(writer, hasTable ? 54 : 0); + WritePointer(writer, grouped ? 23 : 0); + if (reference) + WritePointer(writer, 54); + else if (parameter.Store != StoreState.Value) + WritePointer(writer, 49); + if (association is not null) + WritePointer(writer, 68); + if (hasTable) + { + int[] otherIds = parameter.Store switch + { + StoreState.Neighbour => [DefinitionId + 1], + StoreState.Unsorted => [DefinitionId + 1, DefinitionId - 1], + StoreState.Value when parameter.IdFirst => [DefinitionId - 1], + _ => [], + }; + writer.Write(otherIds.Length + (present ? 1 : 0)); + foreach (int id in otherIds.Where(id => id < DefinitionId && parameter.Store != StoreState.Unsorted)) + WriteRow(id, "42"); + if (present) + WriteRow(DefinitionId, value ?? (parameter.Kind switch + { + Kind.Text => "Old", + Kind.Number => "1.5", + Kind.Material => OriginalMaterialId.ToString(CultureInfo.InvariantCulture), + Kind.FamilyType => NestedTypeId.ToString(CultureInfo.InvariantCulture), + _ => "1", + })); + foreach (int id in otherIds.Where(id => id > DefinitionId || parameter.Store == StoreState.Unsorted)) + WriteRow(id, "42"); + } + if (reference) + { + writer.Write(1); writer.Write(-123); writer.Write(OriginalMaterialId); + } + else if (parameter.Store != StoreState.Value) + writer.Write(12345678); + if (association is not null) + WriteProjectAssociation(writer, association); + + void WriteRow(int id, string text) + { + bool valueFirst = parameter.Kind == Kind.Number && !parameter.IdFirst; + if (!valueFirst) + writer.Write(id); + if (parameter.Kind == Kind.Number) + writer.Write(double.Parse(text, CultureInfo.InvariantCulture)); + else if (parameter.Kind == Kind.Text) + WriteText(writer, text); + else + writer.Write(int.Parse(text, CultureInfo.InvariantCulture)); + if (valueFirst) + writer.Write(id); + } + }); + + private static void WriteProjectAssociation(BinaryWriter writer, ProjectAssociation association) + { + writer.Write(1); + writer.Write(association.GlobalId); + writer.Write((int)association.Property); + writer.Write(association.Malformed ? 5 : -1); + writer.Write(false); + } + + private static byte[] DefinitionBody(UserParameter parameter, int release) => Pack(writer => + { + WriteEmptyElement(writer, DefinitionId, parameter.Kind is Kind.Material or Kind.FamilyType); + WritePointer(writer, parameter.Kind switch { Kind.Text => 26, Kind.Integer => 27, Kind.YesNo => 28, Kind.Material => 52, + Kind.FamilyType => 69, _ => 30 }); + writer.Write(1); + writer.Write(BindingId); + if (parameter.Shared) + { + writer.Write(false); // Read-only in the UI. + writer.Write(parameter.HideWhenNoValue); + } + writer.Write(DefinitionId); + writer.Write(parameter.ReadOnly); + if (parameter.Kind == Kind.Material) + { + writer.Write(0); writer.Write(-1); writer.Write(false); + } + if (parameter.Kind == Kind.FamilyType) + writer.Write((int)BuiltInCategory.OST_GenericModel); + if (parameter.Kind == Kind.Integer) + { + writer.Write(-100); + writer.Write(100); + } + if (parameter.Kind == Kind.Number) + { + if (release == 2020) + writer.Write((int)(parameter.DefinitionSpec?.Legacy ?? + (parameter.Currency ? UnitType.UT_Currency : parameter.Measured ? UnitType.UT_Length : UnitType.UT_Number))); + else if (parameter.DefinitionSpec is { } spec) + WriteText(writer, spec.Forge); + else if (parameter.Currency) + WriteText(writer, "autodesk.spec.measurable:currency-2.0.0"); + else if (parameter.Measured) + WriteText(writer, "autodesk.spec.aec:length-1.0.0"); + else + WriteText(writer, release == 2021 ? "autodesk.spec.aec:number-1.0.1" : "autodesk.spec.aec:number-2.0.0"); + writer.Write(1); + writer.Write(false); + } + }); + + private static void WriteEmptyElement(BinaryWriter writer, int id, bool material = false, bool textStore = false, bool doubleStore = false, + bool elementIdStore = false) + { + writer.Write(id); + WritePointer(writer, textStore ? 19 : 0); + writer.Write(0u); + WritePointer(writer, doubleStore ? 38 : 0); + if (material) + WritePointer(writer, elementIdStore ? 54 : 0); + } + + private static byte[] GlobalBody(GlobalFixture parameter, string value = "0", int id = DefinitionId, GlobalBinary? binary = null, + bool conditional = false, int function = 0) => Pack(writer => + { + writer.Write((ushort)59); + WriteEmptyElement(writer, id); + WritePointer(writer, parameter.Kind switch { Kind.Text => 26, Kind.Integer => 27, Kind.YesNo => 28, _ => 30 }); + writer.Write(-1); + writer.Write(-1); + writer.Write(parameter.Reporting); + WriteText(writer, parameter.Kind == Kind.Text ? value : ""); + writer.Write(parameter.Kind == Kind.Number ? double.Parse(value, CultureInfo.InvariantCulture) : 0d); + writer.Write(-1); + writer.Write(parameter.Kind is Kind.Integer or Kind.YesNo ? int.Parse(value, CultureInfo.InvariantCulture) : 0); + writer.Write(parameter.Kind switch { Kind.Text => 3, Kind.Number => 2, _ => 1 }); + WritePointer(writer, conditional || function != 0 ? 66 : binary is not null ? 63 : parameter.Formula ? 62 : 0); + writer.Write(id); + writer.Write(false); + if (parameter.Kind == Kind.Integer) + { + writer.Write(-100); + writer.Write(100); + } + if (parameter.Kind == Kind.Number) + { + WriteText(writer, parameter.SpecId ?? + (parameter.Currency ? "autodesk.spec.measurable:currency-2.0.0" : "autodesk.spec.aec:number-2.0.0")); + writer.Write(1); + writer.Write(false); + } + if (parameter.Formula) + writer.Write(ProjectId); + if (binary is not null) + { + writer.Write(binary.Operation); + WritePointer(writer, binary.ConstantFirst ? 65 : 64); + WritePointer(writer, binary.ConstantFirst ? 64 : 65); + if (!binary.ConstantFirst) writer.Write(binary.Parameter); + writer.Write(binary.Constant); + WriteText(writer, binary.SpecId ?? "autodesk.spec.aec:number-2.0.0"); + if (binary.ConstantFirst) writer.Write(binary.Parameter); + } + if (conditional) + { + writer.Write(10); + writer.Write(3); + WritePointer(writer, 64); + WritePointer(writer, 65); + WritePointer(writer, 65); + writer.Write(DefinitionId); + writer.Write(1.5); + WriteText(writer, "autodesk.spec.aec:number-2.0.0"); + writer.Write(2.5); + WriteText(writer, "autodesk.spec.aec:number-2.0.0"); + } + if (function != 0) + { + writer.Write(function); + writer.Write(1); + WritePointer(writer, 64); + writer.Write(DefinitionId); + } + }); + + private static void WritePointer(BinaryWriter writer, int tag) + { + writer.Write(tag == 0 ? 0u : uint.MaxValue); + if (tag != 0) + writer.Write((ushort)tag); + } + + private static void WriteText(BinaryWriter writer, string value) + { + writer.Write(value.Length); + writer.Write(Encoding.Unicode.GetBytes(value)); + } + + private static byte[] Pack(Action write) + { + using var stream = new MemoryStream(); + using var writer = new BinaryWriter(stream); + write(writer); + return stream.ToArray(); + } +} diff --git a/tests/RvtIO.Tests/StandaloneFamilyParameterTests.cs b/tests/RvtIO.Tests/StandaloneFamilyParameterTests.cs new file mode 100644 index 00000000..bf2b53c5 --- /dev/null +++ b/tests/RvtIO.Tests/StandaloneFamilyParameterTests.cs @@ -0,0 +1,837 @@ +using System.Globalization; +using System.Security.Cryptography; +using System.Text; +using System.Xml.Linq; +using OpenMcdf; +using RvtIO.BuiltIns; +using RvtIO.Cli; +using RvtIO.Parsing; +using RvtIO.Writing; +using Xunit; +using Back = RvtIO.Tests.SchemaStreamEditorTests.Back; +using Fld = RvtIO.Tests.SchemaStreamEditorTests.Fld; +using NoRef = RvtIO.Tests.SchemaStreamEditorTests.NoRef; + +namespace RvtIO.Tests; + +public sealed class StandaloneFamilyParameterTests : IDisposable +{ + private const int OwnerId = 70, ParameterId = 71, FamilyClass = 24, OriginalParameterId = 50; + private const int ImageId = 73, ImageHolderId = 74, TypeImage = (int)BuiltInParameter.ALL_MODEL_TYPE_IMAGE; + private const int TypeComments = (int)BuiltInParameter.ALL_MODEL_TYPE_COMMENTS; + private const int FormulaResultId = 75; + private const int NestedFamilyId = 80, NestedTypeA = 81, NestedTypeB = 82; + private sealed record FamilyShape(BuiltInCategory Category, int? DimensionDriver = null, bool HasUnnamedType = false, + string? UnnamedComment = null, bool Formula = false, bool CurrencyInstance = false); + private static readonly Guid SharedGuid = new("50b3ce53-fa73-47a1-ae3e-75035a1f17dd"); + private static readonly Guid CreationEpisode = new("f569346e-bacd-43d6-a834-80eaa8fa035f"); + private static PartitionFraming.Tags Tags(int release) => release switch + { + 2020 => new(779, 778, 780, 781, 782), + 2023 => new(869, 868, 870, 871, 872), + 2024 => new(891, 890, 892, 893, 894), + 2026 => new(931, 930, 932, 933, 934), + 2027 => new(951, 950, 952, 953, 954), + _ => new(817, 816, 818, 819, 820), + }; + private static long Id(long id, bool wide) => wide ? (1L << 32) + id : id; + + private static string ImageText(int id) => id == -1 ? "" : "test-image.png"; + private readonly string _folder = Directory.CreateTempSubdirectory("rvtio-rfa-").FullName; + private string Output => Path.Combine(_folder, "edited.rfa"); + public void Dispose() => Directory.Delete(_folder, recursive: true); + + [Theory] + [InlineData("A", "Новое & longer", "Original B", "Новое & longer", "Original B")] + [InlineData("B", "New active", "New active", "Original A", "New active")] + [InlineData("A", "Original A", "Original B", "Original A", "Original B")] + [InlineData("B", "Wide ID", "Wide ID", "Original A", "Wide ID", 2024)] + [InlineData("B", "Wide ID", "Wide ID", "Original A", "Wide ID", 2026)] + [InlineData("A", "New shared value", "Original B", "New shared value", "Original B", 2020, true)] + public void WritesTheSelectedTypeItsActiveCopyAndItsPartAtom(string typeName, string input, string active, string a, string b, + int release = 2022, bool shared = false) + { + bool wide = release >= 2024; + string source = CreateSource(release: release, shared: shared); + byte[] hash = SHA256.HashData(File.ReadAllBytes(source)); + using var error = new StringWriter(); + int exit = SetParameterCommand.Run([source, Output, typeName, Id(ParameterId, wide).ToString(), input], TextWriter.Null, error, familyFile: true); + Assert.True(exit == RvtExitCodes.Success, error.ToString()); + Assert.Equal(hash, SHA256.HashData(File.ReadAllBytes(source))); + + using var root = RootStorage.OpenRead(Output); + using var atom = root.OpenStream("PartAtom"); + var values = XDocument.Load(atom).Descendants().Where(e => e.Name.LocalName == "Proof").Select(e => e.Value).ToArray(); + Assert.Equal(new[] { a, b }, values); + Assert.Equal(PartitionStreamEditorTests.TaggedBody(FamilyClass, FamilyBody(active, a, b, wide: wide)), ReadFamilyBody(root, release)); + } + + [Fact] + public void RecalculatesTheFormulaAndEditsMetadataOnlyForTheSelectedTypes() + { + var shape = new FamilyShape(BuiltInCategory.OST_GenericModel, Formula: true); + string source = CreateSource(shape: shape); + RvtWriter.SetFamilyParameters(source, Output, [new("A", ParameterId, "Changed A"), new("B", ParameterId, "Changed B")]); + using var root = RootStorage.OpenRead(Output); + Assert.Equal(PartitionStreamEditorTests.TaggedBody(FamilyClass, + FamilyBody("Changed B", "Changed A", "Changed B", shape: shape)), ReadFamilyBody(root, 2022)); + using var atom = root.OpenStream("PartAtom"); + Assert.Equal(new[] { "Changed A", "Changed B" }, XDocument.Load(atom) + .Descendants().Where(e => e.Name.LocalName == "Calculated").Select(e => e.Value)); + } + + [Theory] + [InlineData(2020)] + [InlineData(2024)] + public void WritesCurrencyDefaultsAndTheirCalculatedValuesInBatchOrder(int release) + { + var shape = new FamilyShape(BuiltInCategory.OST_GenericModel, Formula: true, CurrencyInstance: true); + string source = CreateSource(release: release, shape: shape); + bool wide = release >= 2024; + byte[] hash = SHA256.HashData(File.ReadAllBytes(source)); + long input = Id(ParameterId, wide); + RvtWriter.SetFamilyParameters(source, Output, [new("A", input, "17.125"), new("B", input, "5"), new("B", input, "-58.625")]); + + using var root = RootStorage.OpenRead(Output); + Assert.Equal(PartitionStreamEditorTests.TaggedBody(FamilyClass, + FamilyBody("-58.625", "17.125", "-58.625", wide: wide, shape: shape)), ReadFamilyBody(root, release)); + Assert.Equal(hash, SHA256.HashData(File.ReadAllBytes(source))); + } + + [Theory] + [InlineData(ParameterId, "42 $", "invalid-parameter-value")] + [InlineData(ParameterId, null, "unsupported-parameter-clear")] + [InlineData(FormulaResultId, "42", "read-only-parameter")] + public void RefusesInvalidCurrencyBatchesWithoutChangingTheSource(int id, string? value, string kind) + { + var shape = new FamilyShape(BuiltInCategory.OST_GenericModel, Formula: true, CurrencyInstance: true); + string source = CreateSource(shape: shape); + byte[] hash = SHA256.HashData(File.ReadAllBytes(source)); + var error = Assert.Throws(() => RvtWriter.SetFamilyParameters(source, Output, + [new("A", ParameterId, "17.125"), new("A", id, value)])); + Assert.Equal(kind, error.Kind); + Assert.False(File.Exists(Output)); + Assert.Equal(hash, SHA256.HashData(File.ReadAllBytes(source))); + } + + [Theory] + [InlineData("A", "17.25000000001")] + [InlineData("B", "1e-300")] + public void RefusesAmbiguousChangesToCurrencyDefaultsWithoutFormulas(string type, string value) + { + var shape = new FamilyShape(BuiltInCategory.OST_GenericModel, CurrencyInstance: true); + string source = CreateSource(shape: shape); + byte[] hash = SHA256.HashData(File.ReadAllBytes(source)); + var error = Assert.Throws(() => RvtWriter.SetFamilyParameters(source, Output, + [new("A", ParameterId, "17.25"), new(type, ParameterId, value)])); + Assert.Equal("unverified-parameter-storage", error.Kind); + Assert.False(File.Exists(Output)); + Assert.Equal(hash, SHA256.HashData(File.ReadAllBytes(source))); + } + + [Theory] + [InlineData(2020, false, "A", -1, -1, NestedTypeA, "Nested : Small")] + [InlineData(2024, false, "B", NestedTypeA, NestedTypeA, NestedTypeB, "Nested : Large")] + [InlineData(2027, false, "B", -1, NestedTypeB, -1, null)] + [InlineData(2027, true, "A", -1, NestedTypeA, NestedTypeB, null)] + [InlineData(2020, false, "A", -1, -1, NestedTypeA, "Nested : Small", true)] + [InlineData(2023, false, "B", NestedTypeA, NestedTypeA, NestedTypeB, "Nested : Large", true)] + [InlineData(2027, false, "B", -1, NestedTypeB, -1, null, true)] + [InlineData(2027, true, "A", -1, NestedTypeA, NestedTypeB, null, true)] + public void WritesNestedTypeReferencesAndTheSelectedPartAtomEntry(int release, bool instance, string type, + int oldA, int oldB, int target, string? display, bool shared = false) + { + bool wide = release >= 2024; + string source = CreateSource(release: release, shared: shared, nested: (oldA, oldB, instance)); + + RvtWriter.SetFamilyParameter(source, Output, type, Id(ParameterId, wide), + (target == -1 ? target : Id(target, wide)).ToString()); + + using var root = RootStorage.OpenRead(Output); + Assert.Equal(PartitionStreamEditorTests.TaggedBody(FamilyClass, FamilyBody("", "", "", wide: wide, + nested: (type == "A" ? target : oldA, type == "B" ? target : oldB, instance))), ReadFamilyBody(root, release)); + using var atom = root.OpenStream("PartAtom"); + var entry = XDocument.Load(atom).Descendants().Single(e => e.Name.LocalName == "part" + && e.Elements().Any(child => child.Name.LocalName == "title" && child.Value == type)) + .Elements().SingleOrDefault(e => e.Name.LocalName == "Proof"); + Assert.Equal(display, entry?.Value); + if (display is not null) + { + Assert.Equal("Family type: Generic Models", (string?)entry?.Attribute("typeOfParameter")); + Assert.Equal(shared ? "shared" : "custom", (string?)entry?.Attribute("type")); + Assert.Equal(shared ? SharedGuid.ToString() : null, (string?)entry?.Attribute("id")); + } + } + + [Theory] + [InlineData("999", false, "invalid-parameter-value")] + [InlineData(null, false, "unsupported-parameter-clear")] + [InlineData("82", true, "unverified-parameter-storage")] + public void RefusesAnEntireNestedReferenceBatchWhenAnEditFails(string? value, bool staleMetadata, string kind) + { + string source = CreateSource(nested: (NestedTypeA, NestedTypeB, false), staleMetadata: staleMetadata); + byte[] hash = SHA256.HashData(File.ReadAllBytes(source)); + var error = Assert.Throws(() => RvtWriter.SetFamilyParameters(source, Output, + [new("B", ParameterId, NestedTypeA.ToString()), new("A", ParameterId, value)])); + Assert.Equal(kind, error.Kind); + Assert.Equal(hash, SHA256.HashData(File.ReadAllBytes(source))); + Assert.False(File.Exists(Output)); + } + + [Fact] + public void RejectsASharedNestedReferenceBatchWhenThePartAtomGuidDoesNotMatch() + { + string source = CreateSource(shared: true, nested: (NestedTypeA, NestedTypeB, false), staleMetadataGuid: true); + byte[] hash = SHA256.HashData(File.ReadAllBytes(source)); + var error = Assert.Throws(() => RvtWriter.SetFamilyParameters(source, Output, + [new("B", ParameterId, NestedTypeA.ToString()), new("A", ParameterId, NestedTypeB.ToString())])); + Assert.Equal("unverified-parameter-storage", error.Kind); + Assert.Equal(hash, SHA256.HashData(File.ReadAllBytes(source))); + Assert.False(File.Exists(Output)); + } + + [Theory] + [InlineData(false, "read-only-parameter")] + [InlineData(true, "unverified-parameter-storage")] + public void RejectsABatchWithAnExplicitFormulaWriteOrAFormulaDrivenAssociation(bool association, string code) + { + var shape = new FamilyShape(BuiltInCategory.OST_GenericModel, Formula: true); + string source = CreateSource(association: association, shape: shape); + byte[] hash = SHA256.HashData(File.ReadAllBytes(source)); + var error = Assert.Throws(() => RvtWriter.SetFamilyParameters(source, Output, + [new("A", ParameterId, "Staged"), new("A", FormulaResultId, "Refused")])); + Assert.Equal(code, error.Kind); + Assert.False(File.Exists(Output)); + Assert.Equal(hash, SHA256.HashData(File.ReadAllBytes(source))); + } + + [Fact] + public void BatchClearsBothTypesAndCanRefillOne() + { + string source = CreateSource(); + string manifest = Path.Combine(_folder, "edits.json"); + File.WriteAllText(manifest, """ + [ + {"typeName":"A","parameterId":71,"value":null}, + {"typeName":"B","parameterId":71,"value":null}, + {"typeName":"A","parameterId":71,"value":"Refilled"} + ] + """); + using var error = new StringWriter(); + int exit = SetParameterCommand.RunBatch([source, Output, manifest], TextWriter.Null, error); + Assert.True(exit == RvtExitCodes.Success, error.ToString()); + using var root = RootStorage.OpenRead(Output); + using var atom = root.OpenStream("PartAtom"); + var parts = XDocument.Load(atom).Descendants(XName.Get("part", "urn:schemas-autodesk-com:partatom")).ToArray(); + Assert.Equal("Refilled", Assert.Single(parts[0].Elements(), e => (string?)e.Attribute("displayName") == "Proof").Value); + Assert.Single(parts[1].Elements()); + Assert.Equal(PartitionStreamEditorTests.TaggedBody(FamilyClass, FamilyBody("", "Refilled", "", wide: false)), ReadFamilyBody(root, 2022)); + } + + [Fact] + public void MissingTypeRefusesTheWholeFamilyBatch() + { + string source = CreateSource(); + byte[] hash = SHA256.HashData(File.ReadAllBytes(source)); + var error = Assert.Throws(() => RvtWriter.SetFamilyParameters(source, Output, + [new("B", ParameterId, null), new("Missing", ParameterId, "Never")])); + Assert.Equal("missing-family-type", error.Kind); + Assert.False(File.Exists(Output)); + Assert.Equal(hash, SHA256.HashData(File.ReadAllBytes(source))); + } + + [Fact] + public void ManifestRequiresAnExplicitValue() + { + string source = CreateSource(); + string manifest = Path.Combine(_folder, "edits.json"); + File.WriteAllText(manifest, """[{"typeName":"B","parameterId":71}]"""); + Assert.Equal(RvtExitCodes.Usage, SetParameterCommand.RunBatch([source, Output, manifest], TextWriter.Null, TextWriter.Null)); + Assert.False(File.Exists(Output)); + } + + [Theory] + [InlineData("A", 2020, "Первое")] + [InlineData("B", 2027, "")] + public void FirstBuiltInTextCreatesDefaultRowsForTheOtherTypes(string type, int release, string value) + { + string source = CreateSource(release: release); + using var errors = new StringWriter(); + int exit = SetParameterCommand.Run([source, Output, type, "ALL_MODEL_TYPE_COMMENTS", value], TextWriter.Null, errors, familyFile: true); + Assert.True(exit == RvtExitCodes.Success, errors.ToString()); + + using var root = RootStorage.OpenRead(Output); + string a = type == "A" ? value : "", b = type == "B" ? value : ""; + Assert.Equal(PartitionStreamEditorTests.TaggedBody(FamilyClass, + FamilyBody("Original B", "Original A", "Original B", wide: release >= 2024, comments: (a, b))), + ReadFamilyBody(root, release)); + using var atom = root.OpenStream("PartAtom"); + var nodes = XDocument.Load(atom).Descendants(XName.Get("Type_Comments", "http://www.w3.org/2005/Atom")).ToArray(); + if (value.Length == 0) + Assert.Empty(nodes); + else + { + var node = Assert.Single(nodes); + Assert.Equal("system", (string?)node.Attribute("type")); + Assert.Equal(value, node.Value); + } + } + + [Fact] + public void BuiltInBatchReplacesOneTypeAndWritesEmptyTextOnTheActiveType() + { + string source = CreateSource(comments: ("Old A", "Old B")); + string manifest = Path.Combine(_folder, "built-in-edits.json"); + File.WriteAllText(manifest, """ + [ + {"typeName":"B","parameterId":-1010105,"value":""}, + {"typeName":"A","parameterId":-1010105,"value":"New A"} + ] + """); + using var errors = new StringWriter(); + int exit = SetParameterCommand.RunBatch([source, Output, manifest], TextWriter.Null, errors); + Assert.True(exit == RvtExitCodes.Success, errors.ToString()); + using var root = RootStorage.OpenRead(Output); + Assert.Equal(PartitionStreamEditorTests.TaggedBody(FamilyClass, + FamilyBody("Original B", "Original A", "Original B", comments: ("New A", ""))), ReadFamilyBody(root, 2022)); + using var atom = root.OpenStream("PartAtom"); + Assert.Equal("New A", Assert.Single(XDocument.Load(atom).Descendants( + XName.Get("Type_Comments", "http://www.w3.org/2005/Atom"))).Value); + } + + [Fact] + public void BuiltInMetadataMismatchRejectsTheWholeBatch() + { + string source = CreateSource(staleMetadata: true, comments: ("Old A", "Old B")); + byte[] hash = SHA256.HashData(File.ReadAllBytes(source)); + var refused = Assert.Throws(() => RvtWriter.SetFamilyParameters(source, Output, + [new("B", TypeComments, "Staged"), new("A", TypeComments, "Invalid")])); + Assert.Equal("unverified-parameter-storage", refused.Kind); + Assert.False(File.Exists(Output)); + Assert.Equal(hash, SHA256.HashData(File.ReadAllBytes(source))); + } + + [Theory] + [InlineData(BuiltInCategory.OST_Doors, true)] + [InlineData(BuiltInCategory.OST_Windows, true)] + [InlineData(BuiltInCategory.OST_Furniture, false)] + public void WritesIdentityInSupportedCategoriesAndMirrorsTheUnnamedType(BuiltInCategory category, bool unnamed) + { + var shape = new FamilyShape(category, + category == BuiltInCategory.OST_Doors ? (int)BuiltInParameter.FAMILY_WIDTH_PARAM : null, unnamed); + string source = CreateSource(shape: shape); + RvtWriter.SetFamilyParameters(source, Output, + [new("A", TypeComments, "Initial"), new("B", TypeComments, "Other type"), new("A", TypeComments, "Changed")]); + + using var root = RootStorage.OpenRead(Output); + Assert.Equal(PartitionStreamEditorTests.TaggedBody(FamilyClass, + FamilyBody("Original B", "Original A", "Original B", comments: ("Changed", "Other type"), + shape: shape with { UnnamedComment = unnamed ? "Changed" : null })), ReadFamilyBody(root, 2022)); + using var atom = root.OpenStream("PartAtom"); + Assert.Equal(new[] { "Changed", "Other type" }, XDocument.Load(atom) + .Descendants(XName.Get("Type_Comments", "http://www.w3.org/2005/Atom")).Select(entry => entry.Value)); + } + + [Fact] + public void RefusesTheWholeBatchWhenAnIdentityParameterIsUsedByADimension() + { + string source = CreateSource(shape: new FamilyShape(BuiltInCategory.OST_Doors, TypeComments)); + byte[] hash = SHA256.HashData(File.ReadAllBytes(source)); + var refused = Assert.Throws(() => RvtWriter.SetFamilyParameters(source, Output, + [new("B", (int)BuiltInParameter.ALL_MODEL_MODEL, "Staged"), new("A", TypeComments, "Invalid")])); + Assert.Equal("unverified-parameter-storage", refused.Kind); + Assert.Contains("dimension association", refused.Message); + Assert.False(File.Exists(Output)); + Assert.Equal(hash, SHA256.HashData(File.ReadAllBytes(source))); + } + + [Theory] + [InlineData("FIRE_RATING")] + [InlineData("DOOR_FIRE_RATING")] + public void AcceptsBothNamesForDoorFireRating(string parameterName) + { + string source = CreateSource(shape: new FamilyShape(BuiltInCategory.OST_Doors)); + using var errors = new StringWriter(); + int exit = SetParameterCommand.Run([source, Output, "A", parameterName, "90 min"], TextWriter.Null, errors, familyFile: true); + Assert.True(exit == RvtExitCodes.Success, errors.ToString()); + + using var root = RootStorage.OpenRead(Output); + using var atom = root.OpenStream("PartAtom"); + Assert.Equal("90 min", Assert.Single(XDocument.Load(atom) + .Descendants(XName.Get("Fire_Rating", "http://www.w3.org/2005/Atom"))).Value); + } + + [Theory] + [InlineData(2020, "A")] + [InlineData(2027, "B")] + public void WritesImportedTypeImageAndInitializesOtherTypes(int release, string type) + { + bool wide = release >= 2024; + string source = CreateSource(release: release, importedImage: true); + RvtWriter.SetFamilyParameter(source, Output, type, TypeImage, Id(ImageId, wide).ToString()); + + using var root = RootStorage.OpenRead(Output); + var a = type == "A" ? ImageId : -1; + var b = type == "B" ? ImageId : -1; + Assert.Equal(PartitionStreamEditorTests.TaggedBody(FamilyClass, + FamilyBody("Original B", "Original A", "Original B", wide: wide, images: (a, b))), ReadFamilyBody(root, release)); + using var atom = root.OpenStream("PartAtom"); + var titles = XDocument.Load(atom).Descendants(XName.Get("Type_Image", "http://www.w3.org/2005/Atom")).Select(e => e.Value); + Assert.Equal(type == "A" ? ["test-image.png", ""] : new[] { "", "test-image.png" }, titles); + } + + [Fact] + public void ATypeImageWithoutAMatchingHolderRejectsTheWholeBatch() + { + string source = CreateSource(importedImage: true, imageHolderMismatch: true); + byte[] hash = SHA256.HashData(File.ReadAllBytes(source)); + var refused = Assert.Throws(() => RvtWriter.SetFamilyParameters(source, Output, + [new("B", TypeComments, "Staged"), new("A", TypeImage, ImageId.ToString())])); + Assert.Equal("invalid-parameter-value", refused.Kind); + Assert.False(File.Exists(Output)); + Assert.Equal(hash, SHA256.HashData(File.ReadAllBytes(source))); + } + + [Theory] + [InlineData(2020, "A", -1, ImageId)] + [InlineData(2027, "B", -1, ImageId)] + [InlineData(2027, "B", ImageId, -1)] + public void WritesCustomTypeImageAndItsMetadata(int release, string type, int before, int after) + { + bool wide = release >= 2024; + string source = CreateSource(release: release, customImage: (before, before)); + RvtWriter.SetFamilyParameter(source, Output, type, Id(ParameterId, wide), + (after == -1 ? -1 : Id(after, wide)).ToString()); + + using var root = RootStorage.OpenRead(Output); + var a = type == "A" ? after : before; + var b = type == "B" ? after : before; + Assert.Equal(PartitionStreamEditorTests.TaggedBody(FamilyClass, + FamilyBody("Original B", "Original A", "Original B", wide: wide, nested: (a, b, false))), ReadFamilyBody(root, release)); + using var atom = root.OpenStream("PartAtom"); + Assert.Equal(new[] { ImageText(a), ImageText(b) }, XDocument.Load(atom) + .Descendants(XName.Get("Proof", "http://www.w3.org/2005/Atom")).Select(entry => entry.Value)); + } + + [Theory] + [InlineData("73", false, "unverified-parameter-storage")] + [InlineData("71", true, "invalid-parameter-value")] + [InlineData(null, true, "unsupported-parameter-clear")] + public void RejectsTheWholeBatchWhenACustomTypeImageEditIsInvalid(string? value, bool validMetadata, string kind) + { + string source = CreateSource(customImage: (-1, -1), staleMetadata: !validMetadata); + byte[] hash = SHA256.HashData(File.ReadAllBytes(source)); + var refused = Assert.Throws(() => RvtWriter.SetFamilyParameters(source, Output, + [new("B", ParameterId, ImageId.ToString()), new("A", ParameterId, value)])); + Assert.Equal(kind, refused.Kind); + Assert.False(File.Exists(Output)); + Assert.Equal(hash, SHA256.HashData(File.ReadAllBytes(source))); + } + + [Theory] + [InlineData("A", 2022, false, true)] + [InlineData("B", 2020, true, true)] + [InlineData("A", 2023, true, true)] + [InlineData("B", 2027, true, true)] + [InlineData("A", 2027, true, false)] + public void FirstTextValueCreatesMetadataForTheSelectedType(string type, int release, bool shared, bool visible) + { + const string caption = "9 Русский / текст", value = "Новое & first value"; + string? forgeId = release switch + { + 2023 => $"revit.local.shared:{CreationEpisode:N}{OriginalParameterId:x8}-1.0.0", + 2027 => $"revit.local.shared:{SharedGuid:N}-2.0.0", + _ => null, + }; + string source = CreateSource(release: release, shared: shared, blankType: type, caption: caption, visible: visible, forgeId: forgeId); + var result = RvtWriter.SetFamilyParameter(source, Output, type, Id(ParameterId, release >= 2024), value); + Assert.Equal(1, result.RewrittenRecordCount); + Assert.Equal(visible ? 2 : 1, result.ReplacedStreamCount); + + using var root = RootStorage.OpenRead(Output); + using var atom = root.OpenStream("PartAtom"); + var parts = XDocument.Load(atom).Descendants(XName.Get("part", "urn:schemas-autodesk-com:partatom")).ToArray(); + var selected = Assert.Single(parts, p => p.Elements().First().Value == type); + var other = Assert.Single(parts, p => p != selected); + Assert.Equal(type == "A" ? "Original B" : "Original A", other.Elements().Last().Value); + if (visible) + { + var entry = Assert.Single(selected.Elements(), e => (string?)e.Attribute("displayName") == caption); + Assert.Equal("_9_Русский___текст", entry.Name.LocalName); + Assert.Equal(shared ? "shared" : "custom", (string?)entry.Attribute("type")); + Assert.Equal(shared ? SharedGuid.ToString() : null, (string?)entry.Attribute("id")); + Assert.Equal(value, entry.Value); + } + else + Assert.Single(selected.Elements()); + string a = type == "A" ? value : "Original A", b = type == "B" ? value : "Original B"; + Assert.Equal(PartitionStreamEditorTests.TaggedBody(FamilyClass, FamilyBody(b, a, b, wide: release >= 2024)), ReadFamilyBody(root, release)); + } + + [Fact] + public void RefusesAFirstSharedValueWhenTheGuidsDisagree() + { + string source = CreateSource(release: 2027, shared: true, blankType: "B", forgeId: $"revit.local.shared:{Guid.Empty:N}-2.0.0"); + var error = Assert.Throws(() => RvtWriter.SetFamilyParameter(source, Output, "B", Id(ParameterId, true), "First")); + Assert.Contains("GUID and Forge type ID disagree", error.Message); + Assert.False(File.Exists(Output)); + } + + [Fact] + public void RefusesAForgeIdFromADifferentElementHistory() + { + string forgeId = $"revit.local.shared:{Guid.Empty:N}{OriginalParameterId:x8}-1.0.0"; + string source = CreateSource(release: 2023, shared: true, blankType: "B", forgeId: forgeId); + var error = Assert.Throws(() => RvtWriter.SetFamilyParameter(source, Output, "B", ParameterId, "First")); + Assert.Equal("unverified-parameter-storage", error.Kind); + Assert.False(File.Exists(Output)); + } + + private static byte[] ReadFamilyBody(RootStorage root, int release) + { + bool wide = release >= 2024; + using var part = root.OpenStorage("Partitions").OpenStream("0"); + var raw = new byte[part.Length]; + part.ReadExactly(raw); + var matches = new List(); + Assert.True(PartitionFraming.Walk(raw, Tags(release), wide ? 8 : 4, r => + { + if (r.Block == 0 && r.Channel == 102 && r.Owner == (ulong)Id(OwnerId, wide)) + matches.Add(r.Body.ToArray()); + }, out var failure, out _), failure); + return Assert.Single(matches); + } + + [Theory] + [InlineData("Missing", false, false, false, false, "missing-family-type")] + [InlineData("A", true, false, false, false, "read-only-parameter")] + [InlineData("A", false, true, false, false, "unverified-parameter-storage")] + [InlineData("A", false, false, true, false, "unverified-parameter-storage")] + [InlineData("A", false, false, false, true, "unverified-parameter-storage")] + public void RefusesAmbiguousOrDrivenEdits(string type, bool readOnly, bool reporting, bool association, bool staleMetadata, string code) + { + string source = CreateSource(readOnly, reporting, association, staleMetadata); + var error = Assert.Throws(() => RvtWriter.SetFamilyParameter(source, Output, type, ParameterId, "New")); + Assert.Equal(code, error.Kind); + Assert.False(File.Exists(Output)); + } + + private string CreateSource(bool readOnly = false, bool reporting = false, bool association = false, bool staleMetadata = false, + int release = 2022, bool shared = false, string? blankType = null, string caption = "Proof", bool visible = true, + string? forgeId = null, (string A, string B)? comments = null, bool importedImage = false, bool imageHolderMismatch = false, + FamilyShape? shape = null, (int A, int B, bool Instance)? nested = null, bool staleMetadataGuid = false, + (int A, int B)? customImage = null) + { + var references = customImage is { } values ? (values.A, values.B, false) : nested; + importedImage |= customImage.HasValue; + bool currencyInstance = shape?.CurrencyInstance == true; + bool wide = release >= 2024; + int width = wide ? 8 : 4; + var tags = Tags(release); + var schema = new SchemaStreamEditorTests.Writer(); + void Add(string name, params Fld[] fields) => schema.Top(new(name, new NoRef(), 1, fields, [])); + Fld Reference(string name, int id, byte mods = 0) => new(name, 14, mods, Target: new Back(id)); + Fld PointerField(string name) => new(name, 14, 2); + Add("Identifier", new Fld(wide ? "m_id64" : "m_id", wide ? (byte)11 : (byte)4)); // 12 + Add("OriginalElementId", Reference("m_id", 12)); // 13 + Add("ElementId", Reference("m_id", 12)); // 14 + Add("ElemHistory", Reference("m_originalElementId", 13), new("m_creationDate", 4), new("m_lastModificationDate", 4), new("m_lastUserModificationDate", 4)); // 15 + Add("ElemRec", Reference("m_id", 14), Reference("m_history", 15), new("m_partitionId", 4), Reference("m_OwningElementId", 14)); // 16 + Add("ElemTable", Reference("m_elemArr", 16, 0x50)); // 17 + Add("Element", Reference("m_id", 14)); // 18 + Add("NamedParam", new Fld("m_str", 8), new("m_oExpression", 14, 1), new("m_value", 7), Reference("m_elemId", 14), + Reference("m_paramId", 14), new("m_int", 4), new("m_instance", 1), new("m_reporting", 1)); // 19 + Add("FamilyParams", Reference("m_params", 19, 0x50)); // 20 + Add("FamilyTypePair", new Fld("name", 8), Reference("params", 20)); // 21 + Add("FamilyTypeTable", new Fld("m_idx", 4), Reference("m_pairs", 21, 0x50)); // 22 + schema.Top(new("FamilyBase", new Back(18), 1, + [PointerField("m_familyParams"), PointerField("m_pFamilyTypes"), new("m_contentProtected", 1), new("m_bHasLabeledDimensions", 1), + Reference("m_categoryId", 14), new("m_inPlace", 1), new("m_name", 8)], [])); // 23 + schema.Top(new("Family", new Back(23), 1, [PointerField("m_oFamDimConstrMgr")], [])); // 24 + Add("Filler25"); // 25 + List defFields = [Reference("m_paramElemId", 14), new("m_caption", 8), new("m_readOnly", 1), new("m_userVisible", 1)]; + if (forgeId is not null) + defFields.Add(new("m_typeId", 8)); + Add("ParamDef", defFields.ToArray()); // 26 + schema.Top(new("ParamDefString", new Back(26), 1, [], [])); // 27 + schema.Top(new("ParamElem", new Back(18), 1, [PointerField("m_pParamDef")], [])); // 28 + schema.Top(new("ParamElemFamily", new Back(28), 1, [new("m_instanceParam", 1)], [])); // 29 + Add("ADocument", Reference("m_ownerFamilyId", 14), Reference("m_ownerFamilyContainingGroupId", 14)); // 30 + Add("ParamIdPair", Reference("m_famParamId", 14)); // 31 + schema.Top(new("ExtrusionElem", new Back(18), 1, [Reference("m_driver", 31)], [])); // 32 + Add("GUIDvalue", new Fld("m_guid", 9)); // 33 + Add("ExternalParamKey", Reference("m_guidValue", 33)); // 34 + schema.Top(new("ParamElemExternal", new Back(28), 1, + [Reference("m_bindingIds", 14, 0x50), Reference("m_externalParamKey", 34)], [])); // 35 + Add("DocumentHistory"); // 36 + Add("SymbolInfo", new Fld("m_name", 8)); // 37 + schema.Top(new("Symbol", new Back(18), 1, [PointerField("m_symbolInfo")], [])); // 38 + schema.Top(new("ImageSymbol", new Back(38), 1, + [Reference("m_idImageHolder", 14), new("m_flags", 4), Reference("m_viewId", 14), Reference("m_ownerSymbolId", 14), + new("m_widthInPixels", 4), new("m_heightInPixels", 4)], [])); // 39 + Add("ARasterImage", new Fld("m_compressedImage", 2, 0x50), new("m_width", 4), new("m_height", 4)); // 40 + schema.Top(new("ImageHolder", new Back(18), 1, + [new("m_pRasterImage", 14, 1), Reference("m_idImageSymbol", 14), new("m_flags", 4)], [])); // 41 + Add("ParamExprEntry", new Fld("m_coef", 7), Reference("m_paramId", 14)); // 42 + Add("ParamExpr", Reference("m_entries", 42, 0x50), new Fld("m_msgId", 4), Reference("m_elemId", 14)); // 43 + Add("ElementIdIntPair", Reference("m_elementId", 14), new Fld("m_int", 4)); // 44 + Add("std::pair< ElementIdIntPair, ParamExpr >", Reference("first", 44), Reference("second", 43)); // 45 + Add("FamDimConstrMgrImpl", Reference("m_paramExprs", 45, 0x50), new Fld("m_drivenDimSegs", 4, 0x50), + Reference("m_additionalParamExprs", 45, 0x50), new("m_dimSegDataMap", 4, 0x50)); // 46 + Add("ParameterExpression", Reference("m_paramId", 14)); // 47 + schema.Top(new("ParamDefFamType", new Back(26), 1, [Reference("m_categoryId", 14)], [])); // 48 + schema.Top(new("FamilySymbol", new Back(38), 1, [Reference("m_familyId", 14), + Reference("m_masterId", 14), Reference("m_ownerInstanceId", 14)], [])); // 49 + schema.Top(new("ParamDefImageSymbolBrowseEdit", new Back(26), 1, [], [])); // 50 + schema.Top(new("ParamDefValue", new Back(26), 1, + [release == 2020 ? new("m_unitType", 4) : new("m_specTypeId", 8), new("m_restriction", 4), new("m_boundless", 1)], [])); // 51 + for (int i = 52; i < tags.ContentKey; i++) + Add("Filler" + i); + foreach (string marker in new[] { "ContentKey", "ContentMarker", "SegmentMarker", "SegmentCheckback", "SignatureMarker" }) + Add(marker); + + var file = Path.Combine(_folder, "source.rfa"); + using var root = RootStorage.Create(file, OpenMcdf.Version.V4); + using (var basic = root.CreateStream("BasicFileInfo")) + basic.Write(RvtWriterTests.BuildBasicFileInfoBytes(release, lastSavePath: file)); + using (var formats = root.CreateStorage("Formats").CreateStream("Latest")) + formats.Write(PagedStreamCodec.Encode([], schema.Build())); + var global = root.CreateStorage("Global"); + using (var header = global.CreateStream("Latest")) + header.Write(PagedStreamCodec.Encode(new byte[8], Pack(w => { w.Write((ushort)30); WriteId(w, OwnerId, wide); WriteId(w, -1, wide); }))); + using (var table = global.CreateStream("ElemTable")) + { + var ids = new List { OwnerId, ParameterId }; + if (association) + ids.Add(72); + if (importedImage) + ids.AddRange([ImageId, ImageHolderId]); + if (shape?.Formula == true) + ids.Add(FormulaResultId); + if (nested.HasValue) + ids.AddRange([NestedFamilyId, NestedTypeA, NestedTypeB]); + byte[] bytes = Pack(w => + { + w.Write((ushort)17); w.Write(ids.Count); + foreach (int id in ids) + { + WriteId(w, id, wide); + WriteId(w, release == 2023 && id == ParameterId ? OriginalParameterId : id, wide); + w.Write(new byte[16 + width]); + } + }); + table.Write(PagedStreamCodec.Encode(new byte[8], bytes)); + } + if (release == 2023) + { + using var history = global.CreateStream("History"); + var bytes = new byte[127]; + bytes[0] = 36; bytes[2] = 1; bytes[106] = 1; + CreationEpisode.TryWriteBytes(bytes.AsSpan(110)); + history.Write(PagedStreamCodec.Encode(new byte[8], bytes)); + } + using (var part = root.CreateStorage("Partitions").CreateStream("0")) + { + string a = currencyInstance ? "0" : blankType == "A" ? "" : "Original A"; + string b = currencyInstance ? "0" : blankType == "B" ? "" : "Original B"; + var records = new List<(ulong, ushort, byte[])> + { + ((ulong)Id(OwnerId, wide), FamilyClass, FamilyBody(b, a, b, reporting, wide, comments, shape: shape, nested: references)), + ((ulong)Id(ParameterId, wide), shared ? (ushort)35 : (ushort)29, Pack(w => + { + WriteId(w, ParameterId, wide); + Pointer(w, currencyInstance ? (ushort)51 : customImage.HasValue ? (ushort)50 : nested.HasValue ? (ushort)48 : (ushort)27); + if (shared) + { + w.Write(0); w.Write(SharedGuid.ToByteArray()); + } + else + w.Write(currencyInstance || nested?.Instance == true); + WriteId(w, ParameterId, wide); Text(w, caption); w.Write(readOnly); w.Write(visible); + if (forgeId is not null) + Text(w, forgeId); + if (nested.HasValue) + WriteId(w, (int)BuiltInCategory.OST_GenericModel, wide); + if (currencyInstance) + WriteCurrencySpec(w); + })), + }; + if (nested.HasValue) + { + records.Add(((ulong)Id(NestedFamilyId, wide), FamilyClass, Pack(w => + { + WriteId(w, NestedFamilyId, wide); w.Write(0u); w.Write(0u); w.Write(false); w.Write(false); + WriteId(w, (int)BuiltInCategory.OST_GenericModel, wide); w.Write(false); Text(w, "Nested"); w.Write(0u); + }))); + foreach (int id in new[] { NestedTypeA, NestedTypeB }) + records.Add(((ulong)Id(id, wide), 49, Pack(w => + { + WriteId(w, id, wide); Pointer(w, 37); WriteId(w, NestedFamilyId, wide); + WriteId(w, -1, wide); WriteId(w, -1, wide); + Text(w, id == NestedTypeA ? "Small" : "Large"); + }))); + } + if (association) + records.Add(((ulong)Id(72, wide), 32, + Pack(w => { WriteId(w, 72, wide); WriteId(w, shape?.Formula == true ? FormulaResultId : ParameterId, wide); }))); + if (shape?.Formula == true) + records.Add(((ulong)Id(FormulaResultId, wide), 29, Pack(w => + { + WriteId(w, FormulaResultId, wide); Pointer(w, currencyInstance ? (ushort)51 : (ushort)27); w.Write(currencyInstance); + WriteId(w, FormulaResultId, wide); Text(w, "Calculated"); w.Write(false); w.Write(true); + if (currencyInstance) + WriteCurrencySpec(w); + }))); + if (importedImage) + { + records.Add(((ulong)Id(ImageId, wide), 39, Pack(w => + { + WriteId(w, ImageId, wide); Pointer(w, 37); WriteId(w, ImageHolderId, wide); + w.Write(0); WriteId(w, -1, wide); WriteId(w, -1, wide); w.Write(2); w.Write(2); + Text(w, "test-image.png"); + }))); + records.Add(((ulong)Id(ImageHolderId, wide), 41, Pack(w => + { + WriteId(w, ImageHolderId, wide); Pointer(w, 40); + WriteId(w, imageHolderMismatch ? OwnerId : ImageId, wide); w.Write(0); + w.Write(4); w.Write(new byte[] { 1, 2, 3, 4 }); w.Write(2); w.Write(2); + }))); + } + var block = PartitionStreamEditorTests.MakeStandardBlock(width, keyed: false, records.ToArray()); + part.Write(PartitionStreamEditorTests.BuildPartitionStream(width, tags, block)); + } + using var atom = root.CreateStream("PartAtom"); + XNamespace ns = "http://www.w3.org/2005/Atom", partAtom = "urn:schemas-autodesk-com:partatom"; + new XDocument(new XElement(ns + "entry", + new XElement(ns + "category", new XElement(ns + "term", "Generic Models"), new XElement(ns + "scheme", "adsk:revit:grouping")), + new XElement(partAtom + "family", + Part("A", staleMetadata ? "Stale" : "Original A"), Part("B", "Original B")))).Save(atom); + return file; + + void WriteCurrencySpec(BinaryWriter writer) + { + if (release == 2020) + writer.Write((int)UnitType.UT_Currency); + else + Text(writer, "autodesk.spec.measurable:currency-2.0.0"); + writer.Write(1); + writer.Write(false); + } + + XElement Part(string type, string value) + { + var node = new XElement(partAtom + "part", new XElement(ns + "title", type)); + int reference = type == "A" ? nested?.A ?? -1 : nested?.B ?? -1; + if (!currencyInstance && type != blankType && (nested is null || !nested.Value.Instance && reference != -1)) + { + if (nested.HasValue && !(staleMetadata && type == "A")) + value = reference == NestedTypeA ? "Nested : Small" : "Nested : Large"; + if (customImage is { } image && !(staleMetadata && type == "A")) + value = ImageText(type == "A" ? image.A : image.B); + var parameter = new XElement(ns + "Proof", new XAttribute("displayName", caption), + new XAttribute("type", shared ? "shared" : "custom"), + new XAttribute("typeOfParameter", customImage.HasValue ? "Image" : nested.HasValue ? "Family type: Generic Models" : "Text"), value); + if (shared) + parameter.SetAttributeValue("id", staleMetadataGuid && type == "A" ? CreationEpisode : SharedGuid); + node.Add(parameter); + } + string? comment = type == "A" ? comments?.A : comments?.B; + if (!string.IsNullOrEmpty(comment)) + node.Add(new XElement(ns + "Type_Comments", new XAttribute("displayName", "Type Comments"), + new XAttribute("type", "system"), new XAttribute("typeOfParameter", "Text"), + staleMetadata && type == "A" ? "Stale" : comment)); + if (shape?.Formula == true && !currencyInstance) + node.Add(new XElement(ns + "Calculated", new XAttribute("displayName", "Calculated"), + new XAttribute("type", "custom"), new XAttribute("typeOfParameter", "Text"), value)); + return node; + } + } + + private static byte[] FamilyBody(string active, string a, string b, bool reporting = false, bool wide = false, + (string A, string B)? comments = null, (int A, int B)? images = null, FamilyShape? shape = null, + (int A, int B, bool Instance)? nested = null) => Pack(w => + { + WriteId(w, OwnerId, wide); Pointer(w, 20); Pointer(w, 22); w.Write(false); w.Write(false); + WriteId(w, (int)(shape?.Category ?? BuiltInCategory.OST_GenericModel), wide); w.Write(false); Text(w, "Host"); Pointer(w, 46); + bool formula = shape?.Formula == true; + bool currencyInstance = shape?.CurrencyInstance == true; + Store(w, active, reporting, wide, comments?.B, images?.B, formula, nested?.B, nested?.Instance ?? false, currencyInstance); + if (shape?.HasUnnamedType == true) + { + w.Write(2); w.Write(3); + Text(w, " "); Store(w, "", reporting, wide, shape.UnnamedComment, null, formula); + } + else + { + w.Write(1); w.Write(2); + } + Text(w, "A"); Store(w, a, reporting, wide, comments?.A, images?.A, formula, nested?.A, nested?.Instance ?? false, currencyInstance); + Text(w, "B"); Store(w, b, reporting, wide, comments?.B, images?.B, formula, nested?.B, nested?.Instance ?? false, currencyInstance); + if (shape?.DimensionDriver is int driver) + { + w.Write(1); WriteId(w, -1, wide); w.Write(0); + w.Write(1); w.Write(1d); WriteId(w, driver, wide); w.Write(0); WriteId(w, -1, wide); + } + else + w.Write(0); + for (int field = 0; field < 3; field++) + w.Write(0); + if (formula) + for (int expression = 0; expression < (shape?.HasUnnamedType == true ? 4 : 3); expression++) + WriteId(w, ParameterId, wide); + }); + + private static void Store(BinaryWriter w, string value, bool reporting, bool wide, string? comments, int? image, bool formula, + int? nestedReference = null, bool instance = false, bool currencyInstance = false) + { + w.Write(1 + (comments is null ? 0 : 1) + (image is null ? 0 : 1) + (formula ? 1 : 0)); + double number = currencyInstance ? double.Parse(value, CultureInfo.InvariantCulture) : 0; + Row(ParameterId, nestedReference.HasValue || currencyInstance ? "" : value, reporting, nestedReference ?? -1, + isInstance: instance || currencyInstance, number: number); + if (comments is not null) + Row(TypeComments, comments, false); + if (image is int id) + Row(TypeImage, "", false, id); + if (formula) + Row(FormulaResultId, currencyInstance ? "" : value, false, expression: 47, isInstance: currencyInstance, number: number); + + void Row(int id, string text, bool isReporting, int reference = -1, ushort expression = 0, bool isInstance = false, double number = 0) + { + Text(w, text); + if (expression == 0) + w.Write(0u); + else + Pointer(w, expression); + w.Write(number); WriteId(w, reference, wide); + WriteId(w, id, wide); w.Write(0); w.Write(isInstance); w.Write(isReporting); + } + } + + private static void WriteId(BinaryWriter writer, int id, bool wide) + { + if (wide) + writer.Write(id < 0 ? id : Id(id, wide)); + else + writer.Write(id); + } + + private static void Text(BinaryWriter writer, string value) + { + writer.Write(value.Length); + writer.Write(Encoding.Unicode.GetBytes(value)); + } + + private static void Pointer(BinaryWriter writer, ushort tag) + { + writer.Write(uint.MaxValue); + writer.Write(tag); + } + + private static byte[] Pack(Action write) + { + using var stream = new MemoryStream(); + using var writer = new BinaryWriter(stream); + write(writer); + return stream.ToArray(); + } +} diff --git a/tests/RvtIO.Tests/WideBlockWalkerTests.cs b/tests/RvtIO.Tests/WideBlockWalkerTests.cs index e9d3de5a..922485a0 100644 --- a/tests/RvtIO.Tests/WideBlockWalkerTests.cs +++ b/tests/RvtIO.Tests/WideBlockWalkerTests.cs @@ -107,6 +107,9 @@ public void Walk_ConsumesAllFieldKindsToTheLastByte() Assert.Equal(StoreId, captures["Base.m_pStore"].Integer); Assert.Equal(7, captures["Derived.m_short"].Integer); Assert.Equal(42, captures["Store.m_value"].Integer); + var backReference = captures["Derived.m_back"]; + Assert.Equal(1, backReference.Integer); + Assert.Equal(1u, System.Buffers.Binary.BinaryPrimitives.ReadUInt32LittleEndian(block.AsSpan(backReference.ValueOffset))); } [Fact] From da22178750d99883d97c4a277ff664add73fee19 Mon Sep 17 00:00:00 2001 From: mie <79989386+mahach666@users.noreply.github.com> Date: Mon, 23 Nov 2026 04:51:45 +0300 Subject: [PATCH 060/259] Recover routed TypeIds when keeping historical copies Refs #192 --- src/RvtIO/Parsing/FramedElementTypes.cs | 70 ++++++++++++++++++-- tests/RvtIO.Tests/FramedElementTypesTests.cs | 56 ++++++++++++++++ 2 files changed, 121 insertions(+), 5 deletions(-) diff --git a/src/RvtIO/Parsing/FramedElementTypes.cs b/src/RvtIO/Parsing/FramedElementTypes.cs index 30e1ccf1..05dc2a0c 100644 --- a/src/RvtIO/Parsing/FramedElementTypes.cs +++ b/src/RvtIO/Parsing/FramedElementTypes.cs @@ -38,6 +38,7 @@ internal sealed class FramedElementTypes private const string RebarType = "RebarInstBase.m_barTypeId"; private const string SoffitType = "Ceiling.m_ceilingAttributesId"; private const string RampType = "Ramp.m_rampAttrId"; + private const string GroupType = "GroupMembership.m_groupId"; private static readonly Dictionary UnanchoredTypes = new() { @@ -46,6 +47,20 @@ internal sealed class FramedElementTypes ["SWall"] = ("VWall.m_WallAttributesId", "BasicWallType"), }; + private static readonly Dictionary RoutedTypes = new() + { + ["SWall"] = UnanchoredTypes["SWall"], + ["FamilyInstance"] = (MasterSymbol, "FamilySymbol"), + ["RoomTag"] = ("RoomTag.m_symbolId", "FamilySymbol"), + ["ProfileRoof"] = ("RoofBase.m_roofAttributesId", "RoofAttributes"), + ["LinearDimString"] = UnanchoredTypes["LinearDimString"], + ["Floor"] = ("Floor.m_floorAttributesId", "FloorAttributes"), + ["DBViewPlan"] = (ViewType, "DBViewType"), + ["DBViewSection"] = (ViewType, "DBViewType"), + ["BaseRailing"] = ("BaseRailing.m_stairsRailingAttrId", "StairsRailingAttr"), + ["ElementGroup"] = (GroupType, "ElementGroupType"), + }; + private static readonly HashSet CapturedFields = [ OwnerField, ViewerView, ViewType, ViewMarker, ReferenceViewer, MarkerParent, MarkerType, StairOwner, @@ -79,12 +94,15 @@ internal bool ContainsArrow(long arrow) => Copies.All(copy => private readonly WideBlockWalker _walker; private readonly HashSet _classes; + private readonly bool _readGroupMembership; private readonly Dictionary> _sources = new(); private readonly Dictionary _roots = new(); - private FramedElementTypes(SchemaDocument schema, IReadOnlyDictionary entities, bool recoverUnanchoredTypes) + private FramedElementTypes(SchemaDocument schema, IReadOnlyDictionary entities, + bool recoverUnanchoredTypes, bool recoverRoutedTypes) { var extraFields = recoverUnanchoredTypes ? UnanchoredTypes.Values.Select(link => link.Field).ToHashSet() : null; + if (recoverRoutedTypes) extraFields!.UnionWith(RoutedTypes.Values.Select(link => link.Field)); _walker = new WideBlockWalker(schema, (declaring, field) => { string key = declaring.Name + "." + field.Name; @@ -93,8 +111,16 @@ private FramedElementTypes(SchemaDocument schema, IReadOnlyDictionary link.Target).ToHashSet() : null; + if (recoverRoutedTypes) + { + extraTargets!.UnionWith(RoutedTypes.Values.Select(link => link.Target)); + extraTargets.Add("NewCurtainWallType"); + _readGroupMembership = SchemaRelease.FromEvidence( + schema.Classes.Find(cls => cls.Name == "ContentMarker")?.Id, schema.Classes.Count) == 2022; + } _classes = schema.Classes.Where(cls => Classes.Contains(cls.Name) || _walker.IsA(cls.Id, "FamilySymbol") - || recoverUnanchoredTypes && (UnanchoredTypes.ContainsKey(cls.Name) || extraTargets!.Contains(cls.Name))) + || recoverUnanchoredTypes && (UnanchoredTypes.ContainsKey(cls.Name) || extraTargets!.Contains(cls.Name)) + || recoverRoutedTypes && RoutedTypes.ContainsKey(cls.Name)) .Select(cls => cls.Id).ToHashSet(); } @@ -121,7 +147,8 @@ internal static int Apply(SchemaDocument schema, IReadOnlyDictionary? unroutedTypePartitions = null, bool recoverUnanchoredTypes = false) { if (frames.Count == 0 || frames.Any(frame => frame == null)) return 0; - var reader = new FramedElementTypes(schema, entities, recoverUnanchoredTypes); + var routes = recoverUnanchoredTypes ? state.IncrementRoutedPartitions : null; + var reader = new FramedElementTypes(schema, entities, recoverUnanchoredTypes, routes is { Count: > 0 }); var ids = state.ElementIds; long SourceId(int key) => ids?.SourceId(key) ?? key; bool LocalId(long sourceId, out int key) @@ -141,11 +168,14 @@ bool LocalId(long sourceId, out int key) || !LocalId((long)item.Owner, out int key) || !state.ElemTable.ContainsKey((uint)key)) continue; var (header, start, _) = frame.Bytes(item with { Length = headerSize + 2 }); int tag = BinaryPrimitives.ReadUInt16LittleEndian(header.AsSpan(start + headerSize, 2)); - if (!reader._classes.Contains(tag) || reader._walker.Class(tag) is not { } kind + if (!reader._classes.Contains(tag) || reader._walker.Class(tag) is not { } kind) continue; + bool routed = routes?.ContainsKey((uint)key) == true && RoutedTypes.ContainsKey(kind.Name); + if (!routed && (!Classes.Contains(kind.Name) && !UnanchoredTypes.ContainsKey(kind.Name) + && RoutedTypes.ContainsKey(kind.Name) || UnanchoredTypes.ContainsKey(kind.Name) && state.NativeParamsFromRootClass.Contains((uint)key) || kind.Name == "FamilyInstance" && (!details.Contains((long)item.Owner) && unroutedTypePartitions?.ContainsKey(item.Owner) != true - || state.IncrementRoutedPartitions?.ContainsKey((uint)key) == true)) continue; + || state.IncrementRoutedPartitions?.ContainsKey((uint)key) == true))) continue; if (!reader._sources.TryGetValue((long)item.Owner, out var copies)) reader._sources.Add((long)item.Owner, copies = []); copies.Add(new(frame, item, kind)); @@ -184,14 +214,19 @@ bool LocalId(long sourceId, out int key) "RoofSoffit" => reader.DirectType(owner, "RoofSoffit", SoffitType, "RoofSoffitType"), "Ramp" => reader.DirectType(owner, "Ramp", RampType, "RampAttributes"), "FamilyInstance" when copies.Count == 1 && details.Contains(owner) + && state.IncrementRoutedPartitions?.ContainsKey((uint)element.Id) != true => reader.DirectType(owner, "FamilyInstance", MasterSymbol, "FamilySymbol"), "FamilyInstance" when unroutedTypePartitions?.TryGetValue((ulong)owner, out int partition) == true => reader.UnroutedFamilyType(owner, copies, partition), // A single exact record can supply the type even when the stream walk never anchored on it. var kind when copies.Count == 1 && UnanchoredTypes.TryGetValue(kind, out var link) + && !state.NativeParamsFromRootClass.Contains((uint)element.Id) => reader.DirectType(owner, kind, link.Field, link.Target), _ => null, }; + if (type == null && copies.Count > 1 && element.TypeId > 0 + && routes?.TryGetValue((uint)element.Id, out int current) == true) + type = reader.RoutedType(owner, copies, current, SourceId(element.TypeId)); if (type is not long sourceType || sourceType == owner || !LocalId(sourceType, out int typeKey) || element.TypeId == typeKey) continue; element.TypeId = typeKey; @@ -232,6 +267,12 @@ bool LocalId(long sourceId, out int key) && (capture.Key == RebarType ? rebarInstance >= 0 && capture.QueueIndex == rebarInstance : capture.AtRoot) && !values.TryAdd(capture.Key, capture.Integer)) return null; if (!values.TryGetValue(OwnerField, out long decodedOwner) || decodedOwner != owner) return null; + if (_readGroupMembership && kind.Name == "ElementGroup" && cls.Id == 1322 && frame.IdWidth == 4 + && TfBlockDeserializer.ExtractParams(data, start, (uint)size, (ushort)cls.Id) is { } parameters + && NativeTypePointers.Of((ushort)cls.Id, parameters) is int groupType + && walk.Captures.Any(capture => capture.Key == GroupType && !capture.AtRoot + && capture.Kind == WideBlockWalker.CaptureKind.Integer && capture.Integer == groupType) + && !values.TryAdd(GroupType, groupType)) return null; fields.Add(values); } return new(kind, fields); @@ -303,6 +344,25 @@ bool LocalId(long sourceId, out int key) return GetRoot(symbol) is { } target && _walker.IsA(target.Class.Id, "FamilySymbol") ? symbol : null; } + private long? RoutedType(long owner, List copies, int current, long oldType) + { + string kind = copies[0].Class.Name; + if (!RoutedTypes.TryGetValue(kind, out var link) || GetRoot(owner) is not { } root) return null; + var partitions = new HashSet(); + bool retainedTypeMatches = false; + long type = 0; + for (int i = 0; i < copies.Count; i++) + { + if (copies[i].Frame.Partition is not int partition || !partitions.Add(partition) + || !root.Copies[i].TryGetValue(link.Field, out long storedType) || storedType <= 0) return null; + if (partition == current) type = storedType; + else if (storedType == oldType) retainedTypeMatches = true; + } + if (!retainedTypeMatches || type == oldType || type == owner || GetRoot(type) is not { } target) return null; + return _walker.IsA(target.Class.Id, link.Target) + || kind == "SWall" && _walker.IsA(target.Class.Id, "NewCurtainWallType") ? type : null; + } + private long? DirectType(long id, string kind, string field, string target) => VerifyType(GetRoot(id, kind)?.Field(field), target); diff --git a/tests/RvtIO.Tests/FramedElementTypesTests.cs b/tests/RvtIO.Tests/FramedElementTypesTests.cs index 7acad1a3..d5e6972a 100644 --- a/tests/RvtIO.Tests/FramedElementTypesTests.cs +++ b/tests/RvtIO.Tests/FramedElementTypesTests.cs @@ -240,6 +240,61 @@ public void UnanchoredWallRequiresKeepModeAnUnambiguousRootAndARealType( Assert.Equal(30, fixture.Apply(element, recoverUnanchoredTypes: keepCopies, anchored: anchored)); } + [Theory] + [InlineData("SWall", "BasicWallType", 20L, 4)] + [InlineData("SWall", "NewCurtainWallType", 20L, 4)] + [InlineData("FamilyInstance", "SysPanelFamSym", 2147483668L, 8)] + [InlineData("DBViewSection", "DBViewType", 20L, 4)] + public void KeepCopiesUsesTheRoutedTypeWithoutReplacingOtherFields(string kind, string target, long type, int width) + { + var fixture = new Fixture(width); + void WriteOccurrence(BinaryWriter writer, long storedType) + { + fixture.Id(writer, storedType); + if (kind == "DBViewSection") fixture.Id(writer, -1); + } + + fixture.Add(kind, 10, w => WriteOccurrence(w, 30), partition: 0); + fixture.Add(kind, 10, w => WriteOccurrence(w, type), partition: 1); + fixture.Add(target, type); + var element = new Element { Id = 10, TypeId = 30, Name = "Historical copy", HostId = 40 }; + + Assert.Equal(type, fixture.Apply(element, wasRouted: true, recoverUnanchoredTypes: true, anchored: true)); + Assert.Equal("Historical copy", element.Name); + Assert.Equal(40, element.HostId); + } + + [Theory] + [InlineData("ordinary mode")] + [InlineData("no route")] + [InlineData("missing current partition")] + [InlineData("duplicate current partition")] + [InlineData("wrong owner")] + [InlineData("different root")] + [InlineData("missing type")] + [InlineData("different target class")] + [InlineData("unsupported target copy")] + [InlineData("unrelated old type")] + public void RoutedTypeRequiresExactCopiesAStoredOldTypeAndARealTarget(string reason) + { + var fixture = new Fixture(); + fixture.Add("SWall", 10, w => fixture.Id(w, 30), partition: 0); + if (reason == "different root") fixture.Add("Other", 10, partition: 1); + else fixture.Add("SWall", 10, w => fixture.Id(w, 20), + storedOwner: reason == "wrong owner" ? 11 : null, partition: reason == "missing current partition" ? 2 : 1); + if (reason == "duplicate current partition") + fixture.Add("SWall", 10, w => fixture.Id(w, 20), partition: 1); + if (reason != "missing type") + fixture.Add(reason == "different target class" ? "Other" : "BasicWallType", 20); + if (reason == "unsupported target copy") fixture.Add("Other", 20); + fixture.Add("BasicWallType", 30); + + int oldType = reason == "unrelated old type" ? 40 : 30; + var element = new Element { Id = 10, TypeId = oldType }; + Assert.Equal(oldType, fixture.Apply(element, wasRouted: reason != "no route", + recoverUnanchoredTypes: reason != "ordinary mode", anchored: true)); + } + private sealed class Fixture { private readonly SchemaDocument _schema = new(); @@ -304,6 +359,7 @@ internal Fixture(int width = 4) Class("TextNoteAttributes", element); Class("SWall", Class("VWall", element, Ref("m_WallAttributesId"))); Class("BasicWallType", element); + Class("NewCurtainWallType", element); Class("Other", element); } From e760ffa965cb3356e578bdb89ebdad7516b1323d Mon Sep 17 00:00:00 2001 From: mahach666 <79989386+mahach666@users.noreply.github.com> Date: Mon, 23 Nov 2026 04:51:59 +0300 Subject: [PATCH 061/259] Document measured formula and association boundaries --- docs/writing.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/docs/writing.md b/docs/writing.md index 4129d0ca..713202e8 100644 --- a/docs/writing.md +++ b/docs/writing.md @@ -128,7 +128,8 @@ associations. Revit accepted `CurrencyInput + 2` in the tested formulas and reje Mass, Force, Mass Density, Speed, Slope, and Time also support verified formula dependencies and existing global associations. Formulas can scale the quantity and add a compatible measured constant. Revit evaluates Slope as a ratio in formulas. For example, a formula that adds 2 percentage points stores the constant as the number `0.02`. -An association still requires the Slope parameter type on both ends. +RvtIO currently requires matching specs for associations. Revit 2025 also saved and reopened a Slope project +parameter with a Number global association. That combination still requires RvtIO coverage. [Autodesk global parameter association reference](https://help.autodesk.com/cloudhelp/2026/ENU/Revit-API-MainReference/files/html/796f3d95-956e-a2a9-7f8e-e8efd2a0eea0.htm) Mathematical functions include `abs`, `sqrt`, `exp`, `log`, `ln`, `sin`, `cos`, `tan`, `asin`, `acos`, `atan`, and `pi()`. Square roots support scalars and areas. Trigonometric functions accept angles in radians internally, @@ -695,7 +696,7 @@ sample from Autodesk and controlled project and family fixtures converted to the | User Currency parameters in standalone families | RvtIO supports verified type values, instance defaults, and formula dependencies. Additional Currency display formats still require coverage. | | Family-declared Currency parameters in projects | RvtIO supports the verified primary type and top-level instance assignments, exact type formula inverses, and existing global associations described above. Other formula paths and geometry dependencies still require coverage. | | Project-bound Currency parameters | RvtIO supports verified shared values on walls, basic wall types, rooms, and loaded family types and instances. Non-shared bindings and other owner classes still require coverage. | -| Additional measurable specs and units | RvtIO supports the input units listed above, including Mass, Force, Mass Density, Speed, Slope, and Time. The formula and association coverage for those six specs is described above. Additional relationships between dimensions, further measurable specs, and additional display formats still require coverage. | +| Additional measurable specs and units | RvtIO supports the input units listed above, including Mass, Force, Mass Density, Speed, Slope, and Time. Revit 2025 accepted formulas multiplying Mass Density by Volume and Speed by Time. Those products, further measurable specs, and additional display formats still require coverage. | | Invalid standalone image references | Revit 2022 and 2027 rejected a missing element ID and an existing family element that was outside the image class. RvtIO requires a local imported image with a verified raster record, or the explicit None value. | | Standalone instance and shared Image definitions | The Revit API prohibits creating instance Image parameters. Revit 2025 also rejected the tested attempt to create a shared type definition. RvtIO supports the non-shared type scope described above. [Autodesk FamilyManager.AddParameter reference](https://help.autodesk.com/cloudhelp/2026/ENU/Revit-API-MainReference/files/html/3ac89d60-4b71-694f-002f-125d2e6565fc.htm) | | Linked images in standalone families | Revit 2025 rejected `ImageTypeSource.Link` when creating an image in a family document. The verified standalone Image path uses imported images. [Autodesk ImageType.Create reference](https://help.autodesk.com/cloudhelp/2026/ENU/Revit-API-MainReference/files/html/31bb13e3-e8f5-cb66-18d0-619578d56cde.htm) | @@ -704,7 +705,7 @@ sample from Autodesk and controlled project and family fixtures converted to the | Driven global parameters | Revit API rejects direct assignments to global parameters driven by a formula or reporting dimension. [Autodesk GlobalParameter.SetValue reference](https://help.autodesk.com/cloudhelp/2026/ENU/Revit-API-MainReference/files/html/df012c22-6e65-8de5-1057-f15660d02288.htm) | | Global parameters with dependents | Revit API can assign a global value that drives a formula, dimension, or element property. RvtIO recalculates verified formulas and updates verified project-bound or geometry-independent loaded family parameters and the built-in properties described above. Dimension recalculation, family geometry updates, and other unverified formula or association layouts still require coverage. | | Global associations on built-in fields | Revit 2020 and 2021 refused the tested wall and family instance Comments associations. Revit 2022–2025 and 2027 accepted them. The tested wall Mark, BasicWallType Type Comments, Manufacturer, and Model, and type URL on Generic Model, Door, Window, and Furniture could not be associated in the tested releases. Derived Door, Window, and Furniture symbol associations and other family categories still require coverage. | -| Family formulas | RvtIO can recalculate verified dependencies of inputs in standalone families and on primary types and top-level instances of loaded families. `FamilyManager.Set` rejects direct writes to formula results in standalone families. RvtIO supports the loaded type inverses described above. Nonlinear inverses, real-valued inverses that depend on the starting value, unverified instance storage, and geometry-driving formulas still require coverage. [Autodesk FamilyManager.Set reference](https://help.autodesk.com/cloudhelp/2026/ENU/Revit-API-MainReference/files/html/428551ba-9037-2e23-7f18-8747624d0ff2.htm) | +| Family formulas | RvtIO can recalculate verified dependencies of inputs in standalone families and on primary types and top-level instances of loaded families. Direct assignments to standalone formula results are refused by the writer. In Revit 2025, `FamilyManager.Set` returned without an exception on the tested Mass and Slope results and left both the inputs and results unchanged after Save As and reopening without Audit. RvtIO supports the loaded type inverses described above. Nonlinear inverses, real-valued inverses that depend on the starting value, unverified instance storage, and geometry-driving formulas still require coverage. [Autodesk FamilyManager.Set reference](https://help.autodesk.com/cloudhelp/2026/ENU/Revit-API-MainReference/files/html/7fc40346-6188-66ff-4c00-bd4360e70c6f.htm) | | Geometry, formulas, groups, and other dependencies | The writer refuses unverified family geometry dependencies, formulas and associations, and unverified project model contexts. These checks are RvtIO write restrictions. | ## Write-capability matrix From f4f7c3901e8c3e3c01e80091234e487d00e3e179 Mon Sep 17 00:00:00 2001 From: mahach666 <79989386+mahach666@users.noreply.github.com> Date: Mon, 23 Nov 2026 05:08:46 +0300 Subject: [PATCH 062/259] Support Number and Slope global parameter associations --- CHANGELOG.md | 3 + docs/writing.md | 17 +++- src/RvtIO/Writing/GlobalParameterWriter.cs | 8 +- .../Writing/LoadedFamilyParameterWriter.cs | 2 +- src/RvtIO/Writing/ParameterWriter.cs | 3 +- tests/RvtIO.Tests/SetParameterTests.cs | 83 +++++++++++++------ 6 files changed, 85 insertions(+), 31 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 578a579b..30537454 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,9 @@ API between minor releases. ### Added +- Update verified Number and Slope parameters through existing associations between the two specs, including + the release-specific rules for Number parameters bound in the project. + - Edit verified project and family parameters in local Revit 2020–2027 files without Revit. The API and CLI support single assignments and atomic batches, including supported clears, measured values, references, and verified family and global formulas. See the [writing guide](docs/writing.md). ### Fixed diff --git a/docs/writing.md b/docs/writing.md index 713202e8..685fea78 100644 --- a/docs/writing.md +++ b/docs/writing.md @@ -101,7 +101,7 @@ unit formats below. A writable Currency global takes a finite invariant number w for example `1234.56789` or `-58.625`. The writer refuses differences for which Revit can retain the previous number under its comparison tolerance. Use an empty string to assign empty Text, or `0` to assign an unchecked Yes/No value. If a global value controls a verified project-bound user parameter, RvtIO updates both values in the same batch. -The controlled property must have matching storage and units, and its saved value must match the previous global +The controlled property must have matching storage and compatible units, and its saved value must match the previous global value. This applies to project properties controlled directly by the edited global and to properties controlled by the result of a recalculated global formula. The element parameter remains read-only through a direct assignment. [Autodesk GlobalParameter.SetValue reference](https://help.autodesk.com/cloudhelp/2026/ENU/Revit-API-MainReference/files/html/df012c22-6e65-8de5-1057-f15660d02288.htm) @@ -128,8 +128,12 @@ associations. Revit accepted `CurrencyInput + 2` in the tested formulas and reje Mass, Force, Mass Density, Speed, Slope, and Time also support verified formula dependencies and existing global associations. Formulas can scale the quantity and add a compatible measured constant. Revit evaluates Slope as a ratio in formulas. For example, a formula that adds 2 percentage points stores the constant as the number `0.02`. -RvtIO currently requires matching specs for associations. Revit 2025 also saved and reopened a Slope project -parameter with a Number global association. That combination still requires RvtIO coverage. +An existing association between Number and Slope transfers the ratio directly. For example, a Number global +of `0.375` updates its associated Slope parameter to `37.5 %`. Use the global's own input format when editing +it. A Number global can update a project-bound or loaded-family Slope parameter. A Slope global can update a +Number type parameter declared in a loaded family. Using a Slope global with a shared Number parameter bound +in the project requires Revit 2022 or later. Revit 2020 and 2021 refused that project binding on the wall +instances and basic wall types tested. [Autodesk global parameter association reference](https://help.autodesk.com/cloudhelp/2026/ENU/Revit-API-MainReference/files/html/796f3d95-956e-a2a9-7f8e-e8efd2a0eea0.htm) Mathematical functions include `abs`, `sqrt`, `exp`, `log`, `ln`, `sin`, `cos`, `tan`, `asin`, `acos`, `atan`, and `pi()`. Square roots support scalars and areas. Trigonometric functions accept angles in radians internally, @@ -492,6 +496,13 @@ constants. For 70 files, the affected records matched Revit 2020–2025 and 2027 upgrading them from the 2026 format. All files matched the API values and, for families, their `PartAtom` entries after Save As and reopening without Audit. Fifty-six refused batches preserved the source bytes and created no output. +Number and Slope association checks covered first edits, replacements, and ordered batches in 24 projects. +The fixtures included direct and formula-driven associations on wall instances, basic wall types, and loaded +family elements. Revit 2020–2025 and 2027 matched the saved parameter values and dependent formulas after +Save As and reopening without Audit. In those releases the affected records in 21 files also matched native +writes byte for byte. Revit 2027 verified the three 2026-format projects after upgrade. Forty-eight refused +batches preserved the source bytes and created no output. + Global assignments to loaded family parameters matched 240 Revit API assignments across the eight formats. The fixtures included shared family definitions, empty text, unitless and measured values, links to recalculated global formula results, and type inputs consumed by formulas on multiple placements with separate local inputs. diff --git a/src/RvtIO/Writing/GlobalParameterWriter.cs b/src/RvtIO/Writing/GlobalParameterWriter.cs index aa9d40e9..b0ab296c 100644 --- a/src/RvtIO/Writing/GlobalParameterWriter.cs +++ b/src/RvtIO/Writing/GlobalParameterWriter.cs @@ -21,9 +21,13 @@ internal sealed record ProjectDependencies( internal readonly record struct PropertyTarget(long ElementId, long ParameterId); internal readonly record struct PropertyValue(long GlobalId, FormulaParameterStorage Format, byte[] Previous, byte[] Replacement) { - internal void VerifyFormat(FormulaParameterStorage target) + internal void VerifyFormat(FormulaParameterStorage target, bool allowSlopeGlobalToNumber = false) { - if (target.Storage != Format.Storage || target.Unit != Format.Unit || target.Kind != Format.Kind) + // Revit transfers the stored slope ratio directly between Slope and Number. + bool slopeNumber = (Format.Unit, target.Unit) is (UnitType.UT_Number, UnitType.UT_Slope) + || (allowSlopeGlobalToNumber && (Format.Unit, target.Unit) is (UnitType.UT_Slope, UnitType.UT_Number)); + if (target.Storage != Format.Storage || target.Kind != Format.Kind || + (target.Unit != Format.Unit && !slopeNumber)) throw ParameterWriter.Unverified("The controlled property and global parameter have different types."); _ = target.Decode(Replacement); } diff --git a/src/RvtIO/Writing/LoadedFamilyParameterWriter.cs b/src/RvtIO/Writing/LoadedFamilyParameterWriter.cs index 2ce3d54e..fe07d3aa 100644 --- a/src/RvtIO/Writing/LoadedFamilyParameterWriter.cs +++ b/src/RvtIO/Writing/LoadedFamilyParameterWriter.cs @@ -177,7 +177,7 @@ internal sealed record FamilyStore(int CountOffset, NamedValue[] Rows); (StorageType Storage, byte[] Replacement, UnitType? Quantity) PrepareDriven(GlobalParameterWriter.PropertyValue value) { var format = FormulaParameterStorage.Read(walker, def, slot, includeCurrency: true); - value.VerifyFormat(format); + value.VerifyFormat(format, allowSlopeGlobalToNumber: true); return (format.Storage, value.Replacement, format.Unit); } diff --git a/src/RvtIO/Writing/ParameterWriter.cs b/src/RvtIO/Writing/ParameterWriter.cs index ceec4c9d..032dcb86 100644 --- a/src/RvtIO/Writing/ParameterWriter.cs +++ b/src/RvtIO/Writing/ParameterWriter.cs @@ -428,7 +428,8 @@ bool IsVerifiedImageTarget(IReadOnlyDictionary reco string? definitionClass = walker.Class(BinaryPrimitives.ReadUInt16LittleEndian(definition))?.Name; var target = FormulaParameterStorage.Read(walker, definitionWalk, slot, includeCurrency: definitionClass == "ParamElemExternal"); - value.VerifyFormat(target); + // Revit 2020–2021 refuse Slope globals on Number parameters bound in the project. + value.VerifyFormat(target, allowSlopeGlobalToNumber: SchemaRelease.FromSchema(formats) is >= 2022); return (target.Storage, value.Replacement, target.Unit); } } diff --git a/tests/RvtIO.Tests/SetParameterTests.cs b/tests/RvtIO.Tests/SetParameterTests.cs index 0c996c16..c964de4f 100644 --- a/tests/RvtIO.Tests/SetParameterTests.cs +++ b/tests/RvtIO.Tests/SetParameterTests.cs @@ -690,32 +690,59 @@ public void RefusesACurrencyAssociationToANumberDefinition() } [Theory] - [InlineData(true)] - [InlineData(false)] - public void ASlopeGlobalRequiresMatchingStorageOnItsAssociatedParameter(bool matchingSpec) + [InlineData(2022, true, true)] + [InlineData(2022, true, false)] + [InlineData(2022, false, true)] + [InlineData(2021, false, true)] + [InlineData(2020, false, true)] + public void SlopeAndNumberAssociationsUseTheStoredRatio(int release, bool slopeDriver, bool slopeProperty) { const string slope = "autodesk.spec.aec:slope-2.0.0"; var parameter = new UserParameter(Kind.Number, true, - DefinitionSpec: matchingSpec ? (UnitType.UT_Slope, slope) : null); + DefinitionSpec: slopeProperty ? (UnitType.UT_Slope, slope) : null); var association = new ProjectAssociation((BuiltInParameter)DefinitionId, GlobalId: PropertyGlobalId); - var global = new GlobalFixture(Kind.Number, InitialValue: "1.5", SpecId: slope); - string source = CreateSource(wall: true, user: parameter, association: association, globalParameter: global); - if (!matchingSpec) - { - byte[] before = File.ReadAllBytes(source); - var error = Assert.Throws(() => RvtWriter.SetParameters(source, Output, - [new(ProjectId, (int)BuiltInParameter.ALL_MODEL_INSTANCE_COMMENTS, "Staged"), new(PropertyGlobalId, PropertyGlobalId, "25 %")])); - Assert.Equal("unverified-parameter-storage", error.Kind); - Assert.Contains("different types", error.Message); - Assert.False(File.Exists(Output)); - Assert.Equal(before, File.ReadAllBytes(source)); - return; - } + var global = new GlobalFixture(Kind.Number, InitialValue: "1.5", SpecId: slopeDriver ? slope : null); + string source = CreateSource(wall: true, user: parameter, association: association, globalParameter: global, release: release); - RvtWriter.SetParameter(source, Output, PropertyGlobalId, PropertyGlobalId, "25 %"); + RvtWriter.SetParameters(source, Output, + [new(PropertyGlobalId, PropertyGlobalId, slopeDriver ? "-62.5 %" : "-0.625"), + new(PropertyGlobalId, PropertyGlobalId, slopeDriver ? "25 %" : "0.25")]); using var root = RootStorage.OpenRead(Output); - Assert.Equal(UserBody(parameter, "0.25", association: association), ReadBody(root)); - Assert.Equal(GlobalBody(global, "0.25", PropertyGlobalId), ReadBody(root, PropertyGlobalId)); + Assert.Equal(UserBody(parameter, "0.25", association: association), ReadBody(root, release: release)); + Assert.Equal(GlobalBody(global, "0.25", PropertyGlobalId, release: release), ReadBody(root, PropertyGlobalId, release)); + } + + [Theory] + [InlineData(2020)] + [InlineData(2021)] + public void LegacyProjectBindingsRefuseSlopeGlobalsOnNumberParameters(int release) + { + var association = new ProjectAssociation((BuiltInParameter)DefinitionId, GlobalId: PropertyGlobalId); + string source = CreateSource(wall: true, user: new(Kind.Number, true), association: association, release: release, + globalParameter: new(Kind.Number, InitialValue: "1.5", SpecId: "autodesk.spec.aec:slope-2.0.0")); + byte[] before = File.ReadAllBytes(source); + var error = Assert.Throws(() => RvtWriter.SetParameters(source, Output, + [new(ProjectId, (int)BuiltInParameter.ALL_MODEL_INSTANCE_COMMENTS, "Staged"), new(PropertyGlobalId, PropertyGlobalId, "25 %")])); + Assert.Equal("unverified-parameter-storage", error.Kind); + Assert.Contains("different types", error.Message); + Assert.False(File.Exists(Output)); + Assert.Equal(before, File.ReadAllBytes(source)); + } + + [Fact] + public void AForceAssociationToSlopeRefusesTheEntireBatch() + { + var parameter = new UserParameter(Kind.Number, true, DefinitionSpec: (UnitType.UT_Slope, "autodesk.spec.aec:slope-2.0.0")); + var association = new ProjectAssociation((BuiltInParameter)DefinitionId, GlobalId: PropertyGlobalId); + string source = CreateSource(wall: true, user: parameter, association: association, + globalParameter: new(Kind.Number, InitialValue: "1.5", SpecId: "autodesk.spec.aec.structural:force-2.0.0")); + byte[] before = File.ReadAllBytes(source); + var error = Assert.Throws(() => RvtWriter.SetParameters(source, Output, + [new(ProjectId, (int)BuiltInParameter.ALL_MODEL_INSTANCE_COMMENTS, "Staged"), new(PropertyGlobalId, PropertyGlobalId, "25 kN")])); + Assert.Equal("unverified-parameter-storage", error.Kind); + Assert.Contains("different types", error.Message); + Assert.False(File.Exists(Output)); + Assert.Equal(before, File.ReadAllBytes(source)); } [Fact] @@ -2249,7 +2276,7 @@ private string CreateSource(string xmlValue = "Owner", bool duplicate = false, b { string initial = globalParameter.InitialValue ?? (globalFormulas is null ? "0" : globalFormulas.Conditional ? "1" : "2"); int id = association?.GlobalId ?? DefinitionId; - records.Add(((ulong)id, 59, GlobalBody(globalParameter, initial, id)[2..])); + records.Add(((ulong)id, 59, GlobalBody(globalParameter, initial, id, release: release)[2..])); if (globalParameter.Consumer) records.Add((BindingId, 61, Pack(writer => { @@ -2886,7 +2913,7 @@ private static void WriteEmptyElement(BinaryWriter writer, int id, bool material } private static byte[] GlobalBody(GlobalFixture parameter, string value = "0", int id = DefinitionId, GlobalBinary? binary = null, - bool conditional = false, int function = 0) => Pack(writer => + bool conditional = false, int function = 0, int release = 2022) => Pack(writer => { writer.Write((ushort)59); WriteEmptyElement(writer, id); @@ -2909,8 +2936,16 @@ private static byte[] GlobalBody(GlobalFixture parameter, string value = "0", in } if (parameter.Kind == Kind.Number) { - WriteText(writer, parameter.SpecId ?? - (parameter.Currency ? "autodesk.spec.measurable:currency-2.0.0" : "autodesk.spec.aec:number-2.0.0")); + if (release == 2020) + writer.Write((int)(parameter.SpecId switch + { + null => parameter.Currency ? UnitType.UT_Currency : UnitType.UT_Number, + "autodesk.spec.aec:slope-2.0.0" => UnitType.UT_Slope, + _ => throw new ArgumentException("The fixture does not supply a legacy unit for this spec.", nameof(parameter)), + })); + else + WriteText(writer, parameter.SpecId ?? + (parameter.Currency ? "autodesk.spec.measurable:currency-2.0.0" : "autodesk.spec.aec:number-2.0.0")); writer.Write(1); writer.Write(false); } From 2982704bec4cf65e9b3ac891cea7de90c8ae477f Mon Sep 17 00:00:00 2001 From: mahach666 <79989386+mahach666@users.noreply.github.com> Date: Mon, 23 Nov 2026 05:29:34 +0300 Subject: [PATCH 063/259] Recalculate formulas combining measured units --- docs/writing.md | 13 ++++- .../Writing/ParameterFormulaEvaluator.cs | 23 ++++++-- tests/RvtIO.Tests/SetParameterTests.cs | 54 +++++++++++++++++-- 3 files changed, 82 insertions(+), 8 deletions(-) diff --git a/docs/writing.md b/docs/writing.md index 685fea78..f135c86c 100644 --- a/docs/writing.md +++ b/docs/writing.md @@ -128,6 +128,10 @@ associations. Revit accepted `CurrencyInput + 2` in the tested formulas and reje Mass, Force, Mass Density, Speed, Slope, and Time also support verified formula dependencies and existing global associations. Formulas can scale the quantity and add a compatible measured constant. Revit evaluates Slope as a ratio in formulas. For example, a formula that adds 2 percentage points stores the constant as the number `0.02`. +Recalculation also supports Mass Density multiplied by Volume to give Mass, and Speed multiplied by Time to give +Length. Each product accepts either operand order. Dividing Mass or Length by one factor gives the other factor. +The same operations apply to verified family type and instance formulas in projects, and to type values and instance +defaults in standalone families. An existing association between Number and Slope transfers the ratio directly. For example, a Number global of `0.375` updates its associated Slope parameter to `37.5 %`. Use the global's own input format when editing it. A Number global can update a project-bound or loaded-family Slope parameter. A Slope global can update a @@ -503,6 +507,13 @@ Save As and reopening without Audit. In those releases the affected records in 2 writes byte for byte. Revit 2027 verified the three 2026-format projects after upgrade. Forty-eight refused batches preserved the source bytes and created no output. +Mixed-unit formula checks covered eight products and quotients in 48 edited files. The tests changed global +parameters and loaded family type and instance inputs in projects, and type values and instance defaults in +standalone families. Replacement and ordered batch results matched the Revit API after Save As and reopening +without Audit. The affected records in 42 files matched native Revit 2020–2025 and 2027 writes byte for byte. +The six 2026-format files were verified after upgrade in Revit 2027, with projects and families checked in +separate sessions. Thirty-two invalid batches preserved the source bytes and created no output. + Global assignments to loaded family parameters matched 240 Revit API assignments across the eight formats. The fixtures included shared family definitions, empty text, unitless and measured values, links to recalculated global formula results, and type inputs consumed by formulas on multiple placements with separate local inputs. @@ -707,7 +718,7 @@ sample from Autodesk and controlled project and family fixtures converted to the | User Currency parameters in standalone families | RvtIO supports verified type values, instance defaults, and formula dependencies. Additional Currency display formats still require coverage. | | Family-declared Currency parameters in projects | RvtIO supports the verified primary type and top-level instance assignments, exact type formula inverses, and existing global associations described above. Other formula paths and geometry dependencies still require coverage. | | Project-bound Currency parameters | RvtIO supports verified shared values on walls, basic wall types, rooms, and loaded family types and instances. Non-shared bindings and other owner classes still require coverage. | -| Additional measurable specs and units | RvtIO supports the input units listed above, including Mass, Force, Mass Density, Speed, Slope, and Time. Revit 2025 accepted formulas multiplying Mass Density by Volume and Speed by Time. Those products, further measurable specs, and additional display formats still require coverage. | +| Additional measurable specs and units | RvtIO supports the input units and verified formula combinations listed above. Further measurable specs, combinations, and display formats still require coverage. This includes standalone family metadata with the feet (`'`) and cubic feet (`CF`) labels observed in Revit 2025. | | Invalid standalone image references | Revit 2022 and 2027 rejected a missing element ID and an existing family element that was outside the image class. RvtIO requires a local imported image with a verified raster record, or the explicit None value. | | Standalone instance and shared Image definitions | The Revit API prohibits creating instance Image parameters. Revit 2025 also rejected the tested attempt to create a shared type definition. RvtIO supports the non-shared type scope described above. [Autodesk FamilyManager.AddParameter reference](https://help.autodesk.com/cloudhelp/2026/ENU/Revit-API-MainReference/files/html/3ac89d60-4b71-694f-002f-125d2e6565fc.htm) | | Linked images in standalone families | Revit 2025 rejected `ImageTypeSource.Link` when creating an image in a family document. The verified standalone Image path uses imported images. [Autodesk ImageType.Create reference](https://help.autodesk.com/cloudhelp/2026/ENU/Revit-API-MainReference/files/html/31bb13e3-e8f5-cb66-18d0-619578d56cde.htm) | diff --git a/src/RvtIO/Writing/ParameterFormulaEvaluator.cs b/src/RvtIO/Writing/ParameterFormulaEvaluator.cs index 4a11ec3a..c19e9a1f 100644 --- a/src/RvtIO/Writing/ParameterFormulaEvaluator.cs +++ b/src/RvtIO/Writing/ParameterFormulaEvaluator.cs @@ -80,7 +80,8 @@ private enum Function : long throw Unsupported(); var left = Visit(Child(slot, "BinaryOperatorExpression.m_pLeftSubexpression"), remaining - 1); var right = Visit(Child(slot, "BinaryOperatorExpression.m_pRightSubexpression"), remaining - 1); - return left is { } lhs && right is { } rhs ? Calculate((BinaryOperator)operation, lhs, rhs) : null; + return left is { } lhs && right is { } rhs + ? Calculate((BinaryOperator)operation, lhs, rhs, allowCompoundUnits: true) : null; case "FunctionExpression": return EvaluateFunction(slot, remaining); default: @@ -159,7 +160,8 @@ Linear Visit(int slot, int remaining) right.InputId != 0 && (left.InputId != 0 || operation == BinaryOperator.Divide)) throw Unsupported(); - var offset = Calculate(operation, left.Offset, right.Offset) ?? throw Unsupported(); + // Direct assignments to formula results have separate verification requirements. + var offset = Calculate(operation, left.Offset, right.Offset, allowCompoundUnits: false) ?? throw Unsupported(); if (left.InputId == 0 && right.InputId == 0) return new(0, 0, offset, true); @@ -260,7 +262,7 @@ private static double RoundDirected(double value, bool up) return up ? Math.Ceiling(value) : Math.Floor(value); } - private static Value? Calculate(BinaryOperator operation, Value left, Value right) + private static Value? Calculate(BinaryOperator operation, Value left, Value right, bool allowCompoundUnits) { if (left.Kind != ValueKind.Number || right.Kind != ValueKind.Number) throw Unsupported(); @@ -296,6 +298,8 @@ private static double RoundDirected(double value, bool up) }, _ => null, }; + if (unit is null && allowCompoundUnits) + unit = CompoundUnit(operation, left.Unit, right.Unit); if (unit is null) throw Unsupported(); @@ -333,6 +337,19 @@ internal static bool IsWithinVerifiedRelativeTolerance(double before, double aft Math.Abs(after - before) < Math.BitDecrement(magnitude * ComparisonTolerance); } + private static UnitType? CompoundUnit(BinaryOperator operation, UnitType left, UnitType right) => (operation, left, right) switch + { + (BinaryOperator.Multiply, UnitType.UT_MassDensity, UnitType.UT_Volume) or + (BinaryOperator.Multiply, UnitType.UT_Volume, UnitType.UT_MassDensity) => UnitType.UT_Mass, + (BinaryOperator.Multiply, UnitType.UT_Speed, UnitType.UT_TimeInterval) or + (BinaryOperator.Multiply, UnitType.UT_TimeInterval, UnitType.UT_Speed) => UnitType.UT_Length, + (BinaryOperator.Divide, UnitType.UT_Mass, UnitType.UT_Volume) => UnitType.UT_MassDensity, + (BinaryOperator.Divide, UnitType.UT_Mass, UnitType.UT_MassDensity) => UnitType.UT_Volume, + (BinaryOperator.Divide, UnitType.UT_Length, UnitType.UT_TimeInterval) => UnitType.UT_Speed, + (BinaryOperator.Divide, UnitType.UT_Length, UnitType.UT_Speed) => UnitType.UT_TimeInterval, + _ => null, + }; + private static int? Power(UnitType unit) => unit switch { UnitType.UT_Length => 1, diff --git a/tests/RvtIO.Tests/SetParameterTests.cs b/tests/RvtIO.Tests/SetParameterTests.cs index c964de4f..2d2f4d46 100644 --- a/tests/RvtIO.Tests/SetParameterTests.cs +++ b/tests/RvtIO.Tests/SetParameterTests.cs @@ -189,6 +189,52 @@ public void RecalculatesAFormulaChainWithMeasuredValues(string spec, string cons ReadBody(root, GlobalFormulaResultId)); } + [Theory] + [InlineData(3, "volume", "massDensity", "mass", "4 ft3", false)] + [InlineData(3, "volume", "massDensity", "mass", "4 ft3", true)] + [InlineData(3, "time", "speed", "length", "4 s", false)] + [InlineData(3, "time", "speed", "length", "4 s", true)] + [InlineData(4, "mass", "volume", "massDensity", "4 kg", false)] + [InlineData(4, "mass", "massDensity", "volume", "4 kg", false)] + [InlineData(4, "length", "time", "speed", "4 ft", false)] + [InlineData(4, "length", "speed", "time", "4 ft", false)] + public void RecalculatesGlobalProductsAndQuotientsWithDifferentUnits(int operation, string inputSpec, + string factorSpec, string resultSpec, string requested, bool constantFirst) + { + var input = new GlobalFixture(Kind.Number, SpecId: PhysicalSpec(inputSpec)); + var result = new GlobalFixture(Kind.Number, SpecId: PhysicalSpec(resultSpec)); + var expression = new GlobalBinary(operation, DefinitionId, 2, constantFirst, PhysicalSpec(factorSpec)); + string source = CreateSource(globalParameter: input, globalFormulas: new(SpecId: result.SpecId, + ConstantSpecId: result.SpecId, Binary: expression, Cached: operation == 3 ? 4 : 1)); + var write = RvtWriter.SetParameter(source, Output, DefinitionId, DefinitionId, requested); + Assert.Equal(3, write.RewrittenRecordCount); + + using var root = RootStorage.OpenRead(Output); + Assert.Equal(GlobalBody(input, "4"), ReadBody(root, DefinitionId)); + Assert.Equal(GlobalBody(result, operation == 3 ? "8" : "2", BindingId, expression), ReadBody(root, BindingId)); + Assert.Equal(GlobalBody(result, operation == 3 ? "9" : "3", GlobalFormulaResultId, + new(1, BindingId, 1, SpecId: result.SpecId)), ReadBody(root, GlobalFormulaResultId)); + } + + [Fact] + public void RefusesAnUnverifiedCombinationOfMeasuredUnitsAtomically() + { + var input = new GlobalFixture(Kind.Number, SpecId: PhysicalSpec("mass")); + string outputSpec = PhysicalSpec("length"); + var mixed = new GlobalBinary(3, DefinitionId, 2, SpecId: PhysicalSpec("time")); + string source = CreateSource(globalParameter: input, globalFormulas: new(SpecId: outputSpec, + ConstantSpecId: outputSpec, Binary: mixed)); + byte[] original = File.ReadAllBytes(source); + var error = Assert.Throws(() => RvtWriter.SetParameters(source, Output, + [new(ProjectId, (int)BuiltInParameter.CLIENT_NAME, "Staged"), new(DefinitionId, DefinitionId, "4 kg")])); + Assert.Equal("unverified-parameter-storage", error.Kind); + Assert.False(File.Exists(Output)); + Assert.Equal(original, File.ReadAllBytes(source)); + } + + private static string PhysicalSpec(string name) => name == "mass" ? "autodesk.spec.aec.structural:mass-2.0.0" + : "autodesk.spec.aec:" + name + "-2.0.0"; + [Theory] [InlineData(false, "read-only-parameter")] [InlineData(true, "unverified-parameter-storage")] @@ -1108,7 +1154,7 @@ private sealed record ProjectAssociation(BuiltInParameter Property, bool Malform bool Derived = false, bool PrimaryAndDerived = false); private sealed record GlobalFormulaFixture(int Operation = 3, bool Stale = false, bool Consumer = false, bool IntegerResult = false, bool Conditional = false, int Function = 0, bool CurrencyResult = false, - string? SpecId = null, string? ConstantSpecId = null); + string? SpecId = null, string? ConstantSpecId = null, GlobalBinary? Binary = null, double? Cached = null); private sealed record GlobalBinary(int Operation, int Parameter, double Constant, bool ConstantFirst = false, string? SpecId = null); private const int GlobalFormulaResultId = 73; private const int GlobalFormulaConsumerId = 74; @@ -2289,15 +2335,15 @@ private string CreateSource(string xmlValue = "Owner", bool duplicate = false, b var number = new GlobalFixture(Kind.Number); bool division = globalFormulas.Operation == 4; bool conditional = globalFormulas.Conditional; - var first = new GlobalBinary(globalFormulas.Operation, DefinitionId, division ? 12 : globalFormulas.IntegerResult ? 1.25 : 2, + var first = globalFormulas.Binary ?? new GlobalBinary(globalFormulas.Operation, DefinitionId, division ? 12 : globalFormulas.IntegerResult ? 1.25 : 2, ConstantFirst: division, SpecId: globalFormulas.ConstantSpecId); int function = globalFormulas.Function; - double cached = function switch + double cached = globalFormulas.Cached ?? (function switch { 7 => Math.Exp(2), 9 => Math.Sqrt(2), _ => conditional ? 2 : globalFormulas.Stale ? 13 : division ? 6 : globalFormulas.IntegerResult ? 3 : 4, - }; + }); var resultKind = conditional || globalFormulas.IntegerResult ? Kind.Integer : Kind.Number; records.Add((BindingId, 59, GlobalBody(new(resultKind, Currency: globalFormulas.CurrencyResult, SpecId: globalFormulas.SpecId), cached.ToString(CultureInfo.InvariantCulture), BindingId, From 2546b0dd92a2bcfebc18b33a65649be71f575b1a Mon Sep 17 00:00:00 2001 From: mahach666 <79989386+mahach666@users.noreply.github.com> Date: Mon, 23 Nov 2026 05:52:42 +0300 Subject: [PATCH 064/259] Write decimal imperial units in standalone families --- docs/writing.md | 19 +++- src/RvtIO/Writing/ParameterMeasurement.cs | 61 ++++++++---- .../StandaloneFamilyParameterWriter.cs | 8 +- .../RvtIO.Tests/ParameterMeasurementTests.cs | 96 +++++++++++++++++++ 4 files changed, 162 insertions(+), 22 deletions(-) create mode 100644 tests/RvtIO.Tests/ParameterMeasurementTests.cs diff --git a/docs/writing.md b/docs/writing.md index f135c86c..b19e4fdf 100644 --- a/docs/writing.md +++ b/docs/writing.md @@ -266,8 +266,11 @@ chains, measured values, Yes/No conditions, and text results. The writer updates the selected type and its current-value copy if it is the active type. It also updates matching `PartAtom` metadata and adds the missing entry when filling an empty, visible user text parameter. User and shared parameters must have a stored row for the selected type. The source, any existing destination, and the active type selection are preserved. -For measured type parameters, a matching `PartAtom` entry requires a verified decimal display format. For materials, -`PartAtom` uses the name of the material read from the same document. +For measured type parameters, a matching `PartAtom` entry requires a verified decimal display format. Decimal feet, +decimal inches, square feet, and cubic feet use the labels `'`, `"`, `SF`, and `CF`. RvtIO also handles the matching +format symbols when they appear in the displayed value. Use `ft`, `in`, `ft2`, and `ft3` in edit requests. +For materials, `PartAtom` uses the name of the material read from the same document. +[Autodesk Units and FormatOptions guide](https://help.autodesk.com/cloudhelp/2024/ENU/Revit-API/files/Revit_API_Developers_Guide/Introduction/Application_and_Document/Revit_API_Revit_API_Developers_Guide_Introduction_Application_and_Document_Units_html.html) **Family Type** parameters in standalone families accept the element ID of a verified local nested type. Family and shared definitions support first assignment and replacement on both type values and instance defaults. For a @@ -514,6 +517,16 @@ without Audit. The affected records in 42 files matched native Revit 2020–2025 The six 2026-format files were verified after upgrade in Revit 2027, with projects and families checked in separate sessions. Thirty-two invalid batches preserved the source bytes and created no output. +Decimal imperial formats were verified in 96 edited standalone family files. The tests covered first edits from defaults, +replacements on active and inactive types, and ordered batches. They checked user-defined Length, Area, and Volume, +dependent formula results, and Default Elevation. For 84 files, family records matched native Revit 2020–2025 +and 2027 writes byte for byte. Revit 2027 verified the twelve 2026-format files after upgrade. API values and +`PartAtom` entries matched after Save As and reopening without Audit. Ninety-eight refused batches preserved the +source bytes and created no output, including files with unrecognized unit labels or stale displayed values. +Six project files also verified assignments in inches to Length globals and loaded family type and instance parameters +in Revit 2020 and 2025. The affected records and formula results matched native writes and survived Save As and +reopening without Audit. + Global assignments to loaded family parameters matched 240 Revit API assignments across the eight formats. The fixtures included shared family definitions, empty text, unitless and measured values, links to recalculated global formula results, and type inputs consumed by formulas on multiple placements with separate local inputs. @@ -718,7 +731,7 @@ sample from Autodesk and controlled project and family fixtures converted to the | User Currency parameters in standalone families | RvtIO supports verified type values, instance defaults, and formula dependencies. Additional Currency display formats still require coverage. | | Family-declared Currency parameters in projects | RvtIO supports the verified primary type and top-level instance assignments, exact type formula inverses, and existing global associations described above. Other formula paths and geometry dependencies still require coverage. | | Project-bound Currency parameters | RvtIO supports verified shared values on walls, basic wall types, rooms, and loaded family types and instances. Non-shared bindings and other owner classes still require coverage. | -| Additional measurable specs and units | RvtIO supports the input units and verified formula combinations listed above. Further measurable specs, combinations, and display formats still require coverage. This includes standalone family metadata with the feet (`'`) and cubic feet (`CF`) labels observed in Revit 2025. | +| Additional measurable specs and units | RvtIO supports the input units, display formats, and formula combinations listed above. Further measurable specs and combinations still require coverage. Feet and fractional inches, localized decimal separators, and other display symbols in standalone family metadata also require verification. | | Invalid standalone image references | Revit 2022 and 2027 rejected a missing element ID and an existing family element that was outside the image class. RvtIO requires a local imported image with a verified raster record, or the explicit None value. | | Standalone instance and shared Image definitions | The Revit API prohibits creating instance Image parameters. Revit 2025 also rejected the tested attempt to create a shared type definition. RvtIO supports the non-shared type scope described above. [Autodesk FamilyManager.AddParameter reference](https://help.autodesk.com/cloudhelp/2026/ENU/Revit-API-MainReference/files/html/3ac89d60-4b71-694f-002f-125d2e6565fc.htm) | | Linked images in standalone families | Revit 2025 rejected `ImageTypeSource.Link` when creating an image in a family document. The verified standalone Image path uses imported images. [Autodesk ImageType.Create reference](https://help.autodesk.com/cloudhelp/2026/ENU/Revit-API-MainReference/files/html/31bb13e3-e8f5-cb66-18d0-619578d56cde.htm) | diff --git a/src/RvtIO/Writing/ParameterMeasurement.cs b/src/RvtIO/Writing/ParameterMeasurement.cs index 832870fa..63208960 100644 --- a/src/RvtIO/Writing/ParameterMeasurement.cs +++ b/src/RvtIO/Writing/ParameterMeasurement.cs @@ -7,10 +7,13 @@ namespace RvtIO.Writing; internal static class ParameterMeasurement { private const double MetresPerFoot = 0.3048; + private const double InternalFeetPerInch = 0.08333333333333334; // Revit's stored conversion differs from 1.0 / 12. private const string SpecPrefix = "autodesk.spec.aec:"; private const string UnitPrefix = "autodesk.unit.unit:"; + private const string SymbolPrefix = "autodesk.unit.symbol:"; internal const string LegacyFormats = WideBlockWalker.AllItemsKeyPrefix + "legacy-unit-options"; - private sealed record Unit(UnitType Spec, string Input, string Forge, DisplayUnitType? Legacy, string Atom, double ToInternal); + private sealed record Unit(UnitType Spec, string Input, string Forge, DisplayUnitType? Legacy, string Atom, double ToInternal, + string? AlternateAtom = null); private sealed record MeasurableSpec(UnitType Unit, string Forge, string Atom); private static readonly MeasurableSpec[] AdditionalSpecs = @@ -28,12 +31,12 @@ private sealed record MeasurableSpec(UnitType Unit, string Forge, string Atom); new(UnitType.UT_Length, "mm", "millimeters", DisplayUnitType.DUT_MILLIMETERS, "mm", 0.001 / MetresPerFoot), new(UnitType.UT_Length, "cm", "centimeters", DisplayUnitType.DUT_CENTIMETERS, "cm", 0.01 / MetresPerFoot), new(UnitType.UT_Length, "m", "meters", DisplayUnitType.DUT_METERS, "m", 1 / MetresPerFoot), - new(UnitType.UT_Length, "ft", "feet", DisplayUnitType.DUT_DECIMAL_FEET, "ft", 1), - new(UnitType.UT_Length, "in", "inches", DisplayUnitType.DUT_DECIMAL_INCHES, "in", 1.0 / 12), + new(UnitType.UT_Length, "ft", "feet", DisplayUnitType.DUT_DECIMAL_FEET, "'", 1, "ft"), + new(UnitType.UT_Length, "in", "inches", DisplayUnitType.DUT_DECIMAL_INCHES, "\"", InternalFeetPerInch, "in"), new(UnitType.UT_Area, "m2", "squareMeters", DisplayUnitType.DUT_SQUARE_METERS, "m²", 1 / (MetresPerFoot * MetresPerFoot)), - new(UnitType.UT_Area, "ft2", "squareFeet", DisplayUnitType.DUT_SQUARE_FEET, "ft²", 1), + new(UnitType.UT_Area, "ft2", "squareFeet", DisplayUnitType.DUT_SQUARE_FEET, "SF", 1, "ft²"), new(UnitType.UT_Volume, "m3", "cubicMeters", DisplayUnitType.DUT_CUBIC_METERS, "m³", 1 / (MetresPerFoot * MetresPerFoot * MetresPerFoot)), - new(UnitType.UT_Volume, "ft3", "cubicFeet", DisplayUnitType.DUT_CUBIC_FEET, "ft³", 1), + new(UnitType.UT_Volume, "ft3", "cubicFeet", DisplayUnitType.DUT_CUBIC_FEET, "CF", 1, "ft³"), new(UnitType.UT_Angle, "deg", "degrees", DisplayUnitType.DUT_DECIMAL_DEGREES, "°", Math.PI / 180), new(UnitType.UT_Angle, "rad", "radians", null, "rad", 1), new(UnitType.UT_Currency, "", "currency", DisplayUnitType.DUT_CURRENCY, "$", 1), @@ -94,8 +97,11 @@ private sealed record MeasurableSpec(UnitType Unit, string Forge, string Atom); private static double? ReadNumber(ReadOnlySpan text) => double.TryParse(text, NumberStyles.Float, CultureInfo.InvariantCulture, out double value) && double.IsFinite(value) ? value : null; - internal readonly record struct DisplayValue(string Type, string Unit, string Symbol, double Before, string After) + internal readonly record struct DisplayValue(string Type, string Unit, string Symbol, double Before, string After, + string? AlternateUnit = null) { + internal bool MatchesUnit(string? unit) => unit is not null && (unit == Unit || unit == AlternateUnit); + internal bool Matches(string text) => text.EndsWith(Symbol, StringComparison.Ordinal) && ReadNumber(text.AsSpan(0, text.Length - Symbol.Length)) == Before; } @@ -109,6 +115,8 @@ internal bool Matches(string text) => text.EndsWith(Symbol, StringComparison.Ord Unit? unit; double accuracy; string symbol; + bool suppressZeros; + bool suppressSpaces; var additional = AdditionalSpecs.SingleOrDefault(entry => entry.Unit == spec); if (WideDocument.UnitOptions(records) is { } modern) { @@ -117,12 +125,11 @@ internal bool Matches(string text) => text.EndsWith(Symbol, StringComparison.Ord if (modern.Options.Where(o => UnitSchemaEvaluator.DisplayNameKey(o.Spec) == specName).ToArray() is not [var option] || option.UseDefault != 0 || option.RoundingMethod != 0 || option.UseGrouping != 0 || option.UsePlusPrefix != 0) return null; - if ((spec == UnitType.UT_Currency || additional is not null) && - (option.SuppressLeadingZeros != 0 || option.SuppressTrailingZeros != 0)) - return null; unit = Units.SingleOrDefault(u => u.Spec == spec && UnitPrefix + u.Forge == UnitSchemaEvaluator.DisplayNameKey(option.Unit)); accuracy = option.Accuracy; symbol = UnitSchemaEvaluator.DisplayNameKey(option.Symbol); + suppressZeros = option.SuppressLeadingZeros != 0 || option.SuppressTrailingZeros != 0; + suppressSpaces = option.SuppressSpaces != 0; } else { @@ -136,14 +143,35 @@ internal bool Matches(string text) => text.EndsWith(Symbol, StringComparison.Ord || option.GetValueOrDefault("m_unitSymbol") is not long legacySymbol || new[] { "m_bUseDefault", "m_roundingMethod", "m_bUseGrouping", "m_bUsePlusPrefix" }.Any(f => option.GetValueOrDefault(f) is not 0L)) return null; - if ((spec == UnitType.UT_Currency || additional is not null) && new[] { "m_bSuppressLeadingZeros", "m_bSuppressTrailingZeros" } - .Any(f => option.GetValueOrDefault(f) is not 0L)) - return null; unit = Units.SingleOrDefault(u => u.Spec == spec && u.Legacy == (DisplayUnitType)display); accuracy = precision; - symbol = legacySymbol switch { 0 => "", (int)UnitSymbolType.UST_DEGREE_SYMBOL => "autodesk.unit.symbol:degree", _ => "unsupported" }; + symbol = legacySymbol switch + { + 0 => "", + (int)UnitSymbolType.UST_DEGREE_SYMBOL => SymbolPrefix + "degree", + (int)UnitSymbolType.UST_FOOT_SINGLE_QUOTE => SymbolPrefix + "footSingleQuote", + (int)UnitSymbolType.UST_INCH_DOUBLE_QUOTE => SymbolPrefix + "inchDoubleQuote", + (int)UnitSymbolType.UST_SF => SymbolPrefix + "sf", + (int)UnitSymbolType.UST_CF => SymbolPrefix + "cf", + _ => "unsupported", + }; + suppressZeros = option.GetValueOrDefault("m_bSuppressLeadingZeros") is not 0L || + option.GetValueOrDefault("m_bSuppressTrailingZeros") is not 0L; + suppressSpaces = option.GetValueOrDefault("m_bSuppressSpaces") is not 0L; } - if (unit is null || (symbol != "" && (unit.Input != "deg" || symbol != "autodesk.unit.symbol:degree"))) + if (unit is null || (suppressZeros && (spec == UnitType.UT_Currency || additional is not null || unit.AlternateAtom is not null))) + return null; + string? suffix = (unit.Input, symbol) switch + { + (_, "") => "", + ("deg", SymbolPrefix + "degree") => "°", + ("ft", SymbolPrefix + "footSingleQuote") => "'", + ("in", SymbolPrefix + "inchDoubleQuote") => "\"", + ("ft2", SymbolPrefix + "sf") => " SF", + ("ft3", SymbolPrefix + "cf") => " CF", + _ => null, + }; + if (suffix is null || (suppressSpaces && suffix.StartsWith(' '))) return null; if (spec == UnitType.UT_Currency && accuracy != 0.01) return null; @@ -152,14 +180,13 @@ internal bool Matches(string text) => text.EndsWith(Symbol, StringComparison.Ord digits++; if (digits > 8) return null; - string suffix = symbol == "" ? "" : "°"; double Round(double number) => Math.Round(number / unit.ToInternal, digits, MidpointRounding.AwayFromZero); double oldValue = Round(before), newValue = Round(after); if (!double.IsFinite(oldValue) || !double.IsFinite(newValue)) return null; - if (spec == UnitType.UT_Currency && newValue == 0) + if ((spec == UnitType.UT_Currency || unit.AlternateAtom is not null) && newValue == 0) newValue = 0; // Revit writes 0.00 for amounts rounded to zero on either side. return new(additional?.Atom ?? spec.ToString()[3..], unit.Atom, suffix, oldValue, - newValue.ToString($"F{digits}", CultureInfo.InvariantCulture) + suffix); + newValue.ToString($"F{digits}", CultureInfo.InvariantCulture) + suffix, symbol == "" ? unit.AlternateAtom : null); } } diff --git a/src/RvtIO/Writing/StandaloneFamilyParameterWriter.cs b/src/RvtIO/Writing/StandaloneFamilyParameterWriter.cs index 8c78d6ce..4fd05e51 100644 --- a/src/RvtIO/Writing/StandaloneFamilyParameterWriter.cs +++ b/src/RvtIO/Writing/StandaloneFamilyParameterWriter.cs @@ -571,9 +571,10 @@ private static (FamilyType[] Types, FamilyType Current) ReadTypes(WideBlockWalke throw Unverified("The built-in family metadata entry is ambiguous."); var entry = matches.SingleOrDefault(); bool expected = !first && (display is not null || !string.IsNullOrEmpty(before)); + string? unit = (string?)entry?.Attribute("units"); if (expected != (entry is not null) || (entry is not null && (entry.HasElements || (string?)entry.Attribute("typeOfParameter") != field.Type - || (string?)entry.Attribute("displayName") != field.DisplayName || (string?)entry.Attribute("units") != display?.Unit + || (string?)entry.Attribute("displayName") != field.DisplayName || !(display?.MatchesUnit(unit) ?? unit is null) || !(display?.Matches(entry.Value) ?? entry.Value == before)))) throw Unverified("The stored built-in value and family metadata disagree."); @@ -706,7 +707,10 @@ private static bool UpdatePartAtom( part.Add(CreatePartAtomEntry(caption, sharedGuid, "Text", text)); return true; } - if (mode != 0 || matches is not [var target] || target.HasElements || (string?)target.Attribute("units") != display?.Unit) + if (mode != 0 || matches is not [var target] || target.HasElements) + throw Unverified("The parameter's family metadata is outside the verified layout."); + string? unit = (string?)target.Attribute("units"); + if (!(display?.MatchesUnit(unit) ?? unit is null)) throw Unverified("The parameter's family metadata is outside the verified layout."); string before = target.Value; diff --git a/tests/RvtIO.Tests/ParameterMeasurementTests.cs b/tests/RvtIO.Tests/ParameterMeasurementTests.cs new file mode 100644 index 00000000..e15208fb --- /dev/null +++ b/tests/RvtIO.Tests/ParameterMeasurementTests.cs @@ -0,0 +1,96 @@ +using RvtIO.BuiltIns; +using RvtIO.Parsing; +using RvtIO.Writing; +using Xunit; + +namespace RvtIO.Tests; + +public sealed class ParameterMeasurementTests +{ + private const int UnitsClass = 1, FormatClass = 2, TypeIdClass = 3; + private static readonly WideBlockWalker Walker = new(new SchemaDocument + { + Classes = [new(UnitsClass, "AUnits", 0, 1, [], []), new(FormatClass, "FormatOptions", 0, 1, [], []), + new(TypeIdClass, "ForgeTypeId", 0, 1, [], [])], + }, (_, _) => null, []); + + [Theory] + [InlineData(UnitType.UT_Length, "feet", DisplayUnitType.DUT_DECIMAL_FEET, "footSingleQuote", UnitSymbolType.UST_FOOT_SINGLE_QUOTE, "'", "ft", "'")] + [InlineData(UnitType.UT_Length, "inches", DisplayUnitType.DUT_DECIMAL_INCHES, "inchDoubleQuote", UnitSymbolType.UST_INCH_DOUBLE_QUOTE, "\"", "in", "\"")] + [InlineData(UnitType.UT_Area, "squareFeet", DisplayUnitType.DUT_SQUARE_FEET, "sf", UnitSymbolType.UST_SF, "SF", "ft²", " SF")] + [InlineData(UnitType.UT_Volume, "cubicFeet", DisplayUnitType.DUT_CUBIC_FEET, "cf", UnitSymbolType.UST_CF, "CF", "ft³", " CF")] + public void FormatsDecimalImperialFamilyMetadata(UnitType spec, string unitId, DisplayUnitType legacyUnit, + string symbolId, UnitSymbolType legacySymbol, string label, string alternate, string suffix) + { + bool inches = legacyUnit == DisplayUnitType.DUT_DECIMAL_INCHES; + foreach (bool legacy in new[] { false, true }) + foreach (bool showSymbol in new[] { false, true }) + { + string expectedSuffix = showSymbol ? suffix : ""; + var units = DisplayUnits(spec, unitId, legacyUnit, showSymbol ? symbolId : "", + showSymbol ? legacySymbol : UnitSymbolType.UST_NONE, legacy); + var display = ParameterMeasurement.Display(spec, Walker, units, inches ? 0.09375000000000001 : 1.125, + inches ? -1.0416666666666668E-05 : -0.000125); + Assert.True(display.HasValue); + Assert.Equal(label, display.Value.Unit); + Assert.True(display.Value.MatchesUnit(label)); + Assert.Equal(!showSymbol, display.Value.MatchesUnit(alternate)); + Assert.False(display.Value.MatchesUnit(null)); + Assert.False(display.Value.MatchesUnit("m")); + Assert.True(display.Value.Matches("1.13" + expectedSuffix)); + Assert.Equal("0.00" + expectedSuffix, display.Value.After); + } + } + + [Theory] + [InlineData("1.125 in", 0.09375000000000001)] + [InlineData("8.5 in", 0.7083333333333334)] + [InlineData("-2.375 in", -0.19791666666666669)] + public void InchesAreConvertedToTheValueStoredByRevit(string input, double expected) => + Assert.Equal(expected, ParameterMeasurement.Parse(UnitType.UT_Length, input)); + + [Theory] + [InlineData("footSingleQuote", false, false)] + [InlineData("cf", true, false)] + [InlineData("cf", false, true)] + public void RefusesUnverifiedImperialPartAtomFormats(string symbol, bool suppressZeros, bool suppressSpaces) + { + var units = DisplayUnits(UnitType.UT_Volume, "cubicFeet", DisplayUnitType.DUT_CUBIC_FEET, symbol, + UnitSymbolType.UST_NONE, legacy: false); + var format = Assert.Single(units.Records, record => record.ClassId == FormatClass).Values; + format["m_bSuppressTrailingZeros"] = suppressZeros ? 1L : 0L; + format["m_bSuppressSpaces"] = suppressSpaces ? 1L : 0L; + Assert.Null(ParameterMeasurement.Display(UnitType.UT_Volume, Walker, units, 1, 2)); + } + + private static WideBlockWalker.Walk DisplayUnits(UnitType spec, string unitId, DisplayUnitType legacyUnit, string symbol, + UnitSymbolType legacySymbol, bool legacy) + { + var layout = new WideBlockWalker.Walk(); + var format = new Dictionary + { + ["m_accuracy"] = 0.01, ["m_roundingMethod"] = 0L, ["m_bUseDefault"] = 0L, ["m_bUseGrouping"] = 0L, + ["m_bUsePlusPrefix"] = 0L, ["m_bSuppressLeadingZeros"] = 0L, ["m_bSuppressTrailingZeros"] = 0L, ["m_bSuppressSpaces"] = 0L, + }; + if (legacy) + { + format["m_displayUnits"] = (long)legacyUnit; + format["m_unitSymbol"] = (long)legacySymbol; + layout.Captures.Add(new(ParameterMeasurement.LegacyFormats + "@" + (int)spec, WideBlockWalker.CaptureKind.PointerClass, + FormatClass, 0, null, true, 0, "AUnits", "m_formatOptionsMap", QueuePosition: 1)); + } + else + { + string name = spec.ToString()[3..].ToLowerInvariant(); + foreach (string id in new[] { $"autodesk.spec.aec:{name}-1.0.0", symbol == "" ? "" : $"autodesk.unit.symbol:{symbol}-1.0.1", + $"autodesk.unit.unit:{unitId}-1.0.1" }) + layout.Records.Add((TypeIdClass, 0, new() { ["m_typeId"] = id })); + } + layout.Records.Add((FormatClass, 1, format)); + layout.Records.Add((UnitsClass, 0, new() + { + ["m_universalUnitSystem"] = 1L, ["m_decimalSymbol"] = 0L, ["m_digitGroupingSymbol"] = 1L, ["m_digitGroupingAmount"] = 0L, + })); + return layout; + } +} From 8f793f0831b081af92ae539307b4e7acea8c3641 Mon Sep 17 00:00:00 2001 From: mahach666 <79989386+mahach666@users.noreply.github.com> Date: Mon, 23 Nov 2026 10:53:15 +0300 Subject: [PATCH 065/259] Improve Revit PDF parity across sheets and views --- CHANGELOG.md | 221 +- docs/printing.md | 553 +- src/RvtIO.Cli/PrintCommand.cs | 45 +- src/RvtIO.Cli/Program.cs | 1 + src/RvtIO/Internal/GRepData.cs | 22 + src/RvtIO/Internal/ParsingState.cs | 12 +- src/RvtIO/Model/Element.cs | 26 + src/RvtIO/Model/Geometry.cs | 9 + src/RvtIO/Model/RevitFileInfo.cs | 108 +- src/RvtIO/Model/ViewCropFrame.cs | 6 + src/RvtIO/Parsing/BlockParser.cs | 14 +- .../Parsing/ElementBuilder.OwnFamilyCutout.cs | 10 +- .../Parsing/ElementBuilder.PlanDimensions.cs | 83 + .../ElementBuilder.PlanElevationMarks.cs | 51 + src/RvtIO/Parsing/ElementBuilder.PlanNotes.cs | 56 + .../Parsing/ElementBuilder.PlanStairPaths.cs | 66 + .../Parsing/ElementBuilder.RoomColors.cs | 31 + .../Parsing/ElementBuilder.ScheduleRows.cs | 122 + .../ElementBuilder.SiteContourLabels.cs | 36 + src/RvtIO/Parsing/ElementBuilder.cs | 296 +- src/RvtIO/Parsing/GRepParserV2.cs | 435 +- src/RvtIO/Parsing/NativeFieldParameters.cs | 3 + src/RvtIO/Parsing/PartitionFraming.cs | 1 + .../Parsing/TfBlockDeserializer.BreakLine.cs | 32 + .../TfBlockDeserializer.DatumExtents.cs | 218 + .../TfBlockDeserializer.PlanDimensions.cs | 22 + .../TfBlockDeserializer.PlanFurniture.cs | 13 + .../Parsing/TfBlockDeserializer.PlanNotes.cs | 37 + .../TfBlockDeserializer.PlanRoomTags.cs | 94 + .../Parsing/TfBlockDeserializer.RoomColors.cs | 31 + .../TfBlockDeserializer.ScheduleRows.cs | 43 + .../TfBlockDeserializer.SiteContours.cs | 88 + .../TfBlockDeserializer.SiteProperty.cs | 46 + .../Parsing/TfBlockDeserializer.StairRuns.cs | 71 +- .../TfBlockDeserializer.UnitOptions.cs | 52 +- src/RvtIO/Parsing/TfBlockDeserializer.cs | 782 ++- src/RvtIO/Pdf/PdfDocument.cs | 214 +- src/RvtIO/Pdf/PdfFonts.cs | 16 +- src/RvtIO/Pdf/PdfSerializer.cs | 123 +- src/RvtIO/Pdf/PdfTrueTypeFont.cs | 5 + src/RvtIO/Pdf/WindowsArialLayout.cs | 83 + src/RvtIO/Print/CircularAnnotations.cs | 89 + src/RvtIO/Print/DetailAnnotations.cs | 297 ++ .../ElevationPrinter.AmbientOcclusion.cs | 284 ++ .../Print/ElevationPrinter.Billboards.cs | 93 + src/RvtIO/Print/ElevationPrinter.Glazing.cs | 88 + .../Print/ElevationPrinter.MeshSilhouette.cs | 82 + .../Print/ElevationPrinter.RailingTubes.cs | 238 + src/RvtIO/Print/ElevationPrinter.Shadows.cs | 608 +++ src/RvtIO/Print/ElevationPrinter.cs | 3426 ++++++++++++- src/RvtIO/Print/FillHatch.cs | 174 +- src/RvtIO/Print/LinePatterns.cs | 38 +- src/RvtIO/Print/PenWidths.cs | 25 +- src/RvtIO/Print/PlanElevationMarks.cs | 94 + src/RvtIO/Print/PlanPrinter.Columns.cs | 91 + src/RvtIO/Print/PlanPrinter.Datums.cs | 93 + src/RvtIO/Print/PlanPrinter.Dimensions.cs | 93 + src/RvtIO/Print/PlanPrinter.DoorSymbols.cs | 78 + .../Print/PlanPrinter.FixtureProfiles.cs | 244 + src/RvtIO/Print/PlanPrinter.Furniture.cs | 169 + src/RvtIO/Print/PlanPrinter.Notes.cs | 108 + src/RvtIO/Print/PlanPrinter.OpeningTags.cs | 49 + src/RvtIO/Print/PlanPrinter.RoomTags.cs | 86 + src/RvtIO/Print/PlanPrinter.SectionMarks.cs | 108 + src/RvtIO/Print/PlanPrinter.Stairs.cs | 391 ++ src/RvtIO/Print/PlanPrinter.WallCuts.cs | 150 + src/RvtIO/Print/PlanPrinter.cs | 350 +- src/RvtIO/Print/RvtRaster.cs | 63 +- src/RvtIO/Print/ShadedViewport.cs | 378 ++ .../Print/SheetComposer.ViewportTitles.cs | 57 + src/RvtIO/Print/SheetComposer.cs | 579 ++- src/RvtIO/Print/SheetPrinter.cs | 57 +- src/RvtIO/Print/SitePrinter.ContourLabels.cs | 76 + src/RvtIO/Print/SitePrinter.Equipment.cs | 87 + src/RvtIO/Print/SitePrinter.Planting.cs | 45 + src/RvtIO/Print/SitePrinter.PropertyTags.cs | 93 + src/RvtIO/Print/SitePrinter.Roof.cs | 231 + src/RvtIO/Print/SitePrinter.Shadows.cs | 164 + src/RvtIO/Print/SitePrinter.Tags.cs | 83 + src/RvtIO/Print/SitePrinter.cs | 188 +- src/RvtIO/Print/SolarStudyOverlay.cs | 363 ++ src/RvtIO/Print/ViewportShadows.cs | 143 + src/RvtIO/Print/ViewportSurfaceEdges.cs | 44 + src/RvtIO/Print/ViewportSurfacePattern.cs | 74 + .../RvtFileReader.CircularAnnotations.cs | 124 + src/RvtIO/RvtFileReader.PlanRoomTags.cs | 287 ++ src/RvtIO/RvtFileReader.cs | 54 +- tests/RvtIO.Tests/DatumExtentTests.cs | 124 + .../DeferredTailGraphicsFieldTests.cs | 21 + tests/RvtIO.Tests/DetailAnnotationsTests.cs | 152 + .../ElementBuilderGeometryTests.cs | 33 + tests/RvtIO.Tests/ElevationPrinterTests.cs | 4506 ++++++++++++++++- tests/RvtIO.Tests/FillPatternTests.cs | 73 + tests/RvtIO.Tests/PdfTrueTypeFontTests.cs | 19 + tests/RvtIO.Tests/PdfWriterTests.cs | 70 + tests/RvtIO.Tests/PlanPrinterTests.cs | 956 +++- tests/RvtIO.Tests/PlanSectionMarkTests.cs | 54 + tests/RvtIO.Tests/PrintCommandTests.cs | 12 + tests/RvtIO.Tests/ProjectLocationTests.cs | 2 + tests/RvtIO.Tests/RvtRasterTests.cs | 11 + tests/RvtIO.Tests/ScheduleTableTests.cs | 39 + tests/RvtIO.Tests/SectionMarkDedupeTests.cs | 38 + tests/RvtIO.Tests/SectionMarkViewportTests.cs | 22 +- tests/RvtIO.Tests/SheetComposerTests.cs | 553 +- tests/RvtIO.Tests/SheetTextTests.cs | 35 +- tests/RvtIO.Tests/SitePrinterTests.cs | 510 +- tests/RvtIO.Tests/SolarStudyOverlayTests.cs | 66 + tests/RvtIO.Tests/TitleBlockLinesTests.cs | 25 + tests/RvtIO.Tests/ViewCropTests.cs | 101 +- tests/RvtIO.Tests/ViewportShadowsTests.cs | 58 + 110 files changed, 21285 insertions(+), 1108 deletions(-) create mode 100644 src/RvtIO/Parsing/ElementBuilder.PlanDimensions.cs create mode 100644 src/RvtIO/Parsing/ElementBuilder.PlanElevationMarks.cs create mode 100644 src/RvtIO/Parsing/ElementBuilder.PlanNotes.cs create mode 100644 src/RvtIO/Parsing/ElementBuilder.PlanStairPaths.cs create mode 100644 src/RvtIO/Parsing/ElementBuilder.RoomColors.cs create mode 100644 src/RvtIO/Parsing/ElementBuilder.ScheduleRows.cs create mode 100644 src/RvtIO/Parsing/ElementBuilder.SiteContourLabels.cs create mode 100644 src/RvtIO/Parsing/TfBlockDeserializer.BreakLine.cs create mode 100644 src/RvtIO/Parsing/TfBlockDeserializer.DatumExtents.cs create mode 100644 src/RvtIO/Parsing/TfBlockDeserializer.PlanDimensions.cs create mode 100644 src/RvtIO/Parsing/TfBlockDeserializer.PlanFurniture.cs create mode 100644 src/RvtIO/Parsing/TfBlockDeserializer.PlanNotes.cs create mode 100644 src/RvtIO/Parsing/TfBlockDeserializer.PlanRoomTags.cs create mode 100644 src/RvtIO/Parsing/TfBlockDeserializer.RoomColors.cs create mode 100644 src/RvtIO/Parsing/TfBlockDeserializer.ScheduleRows.cs create mode 100644 src/RvtIO/Parsing/TfBlockDeserializer.SiteContours.cs create mode 100644 src/RvtIO/Parsing/TfBlockDeserializer.SiteProperty.cs create mode 100644 src/RvtIO/Pdf/WindowsArialLayout.cs create mode 100644 src/RvtIO/Print/CircularAnnotations.cs create mode 100644 src/RvtIO/Print/DetailAnnotations.cs create mode 100644 src/RvtIO/Print/ElevationPrinter.AmbientOcclusion.cs create mode 100644 src/RvtIO/Print/ElevationPrinter.Billboards.cs create mode 100644 src/RvtIO/Print/ElevationPrinter.Glazing.cs create mode 100644 src/RvtIO/Print/ElevationPrinter.MeshSilhouette.cs create mode 100644 src/RvtIO/Print/ElevationPrinter.RailingTubes.cs create mode 100644 src/RvtIO/Print/ElevationPrinter.Shadows.cs create mode 100644 src/RvtIO/Print/PlanElevationMarks.cs create mode 100644 src/RvtIO/Print/PlanPrinter.Columns.cs create mode 100644 src/RvtIO/Print/PlanPrinter.Datums.cs create mode 100644 src/RvtIO/Print/PlanPrinter.Dimensions.cs create mode 100644 src/RvtIO/Print/PlanPrinter.DoorSymbols.cs create mode 100644 src/RvtIO/Print/PlanPrinter.FixtureProfiles.cs create mode 100644 src/RvtIO/Print/PlanPrinter.Furniture.cs create mode 100644 src/RvtIO/Print/PlanPrinter.Notes.cs create mode 100644 src/RvtIO/Print/PlanPrinter.OpeningTags.cs create mode 100644 src/RvtIO/Print/PlanPrinter.RoomTags.cs create mode 100644 src/RvtIO/Print/PlanPrinter.SectionMarks.cs create mode 100644 src/RvtIO/Print/PlanPrinter.Stairs.cs create mode 100644 src/RvtIO/Print/PlanPrinter.WallCuts.cs create mode 100644 src/RvtIO/Print/ShadedViewport.cs create mode 100644 src/RvtIO/Print/SheetComposer.ViewportTitles.cs create mode 100644 src/RvtIO/Print/SitePrinter.ContourLabels.cs create mode 100644 src/RvtIO/Print/SitePrinter.Equipment.cs create mode 100644 src/RvtIO/Print/SitePrinter.Planting.cs create mode 100644 src/RvtIO/Print/SitePrinter.PropertyTags.cs create mode 100644 src/RvtIO/Print/SitePrinter.Roof.cs create mode 100644 src/RvtIO/Print/SitePrinter.Shadows.cs create mode 100644 src/RvtIO/Print/SitePrinter.Tags.cs create mode 100644 src/RvtIO/Print/SolarStudyOverlay.cs create mode 100644 src/RvtIO/Print/ViewportShadows.cs create mode 100644 src/RvtIO/Print/ViewportSurfaceEdges.cs create mode 100644 src/RvtIO/Print/ViewportSurfacePattern.cs create mode 100644 src/RvtIO/RvtFileReader.CircularAnnotations.cs create mode 100644 src/RvtIO/RvtFileReader.PlanRoomTags.cs create mode 100644 tests/RvtIO.Tests/DatumExtentTests.cs create mode 100644 tests/RvtIO.Tests/DetailAnnotationsTests.cs create mode 100644 tests/RvtIO.Tests/SolarStudyOverlayTests.cs create mode 100644 tests/RvtIO.Tests/ViewportShadowsTests.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index 7676353e..ebf5c91b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,204 @@ API between minor releases. ## [Unreleased] +### Fixed + +- Hidden-line site views print visible roof glazing inside the saved skylight openings. +- Site views keep cast shadows on their receiving roof surfaces and cast shadows from opaque skylight frames. +- Site views project visible horizontal stair treads and landings with their cast shadows. +- Site views draw visible top rail outlines and project shadows from their planar faces. +- Site views draw visible horizontal floor slabs and preserve skylight glazing over them. +- Elevations hide covered skylight frame edges when the glazing is seen edge-on. +- Elevations project shadows from opaque skylight frames onto their sloped host roofs. +- In elevations, planar opaque faces of placed structural columns cast shadows using the saved light direction. +- Overview sections trim sloping railing lines behind nearer opaque wall faces. +- Fine section callouts with ambient shadows use the saved graphics colour of supported wall finish layers. +- Visible slab sides in opaque details shade from samples outside the nearer cut caps. +- Opaque detail cuts use the projection pen on the shared boundary between touching roof and wall profiles. +- Opaque fine section details preserve the visible spans of railing posts and curtain-wall mullions behind nearer model faces. +- Elevations retain distinct railing profile edges when the same visible face separates them by more than the projection pen width. +- Fine sections mask backing geometry at closed stair cuts and correct self-shadowing on verified convex stair solids. +- Sheet schedules localize evaluated Yes/No cells for the Russian print UI culture. +- Floor-plan room tags print the square-metre symbol in Cyrillic for the Russian print UI culture. +- Floor plans place continuous section marks from their saved view-specific extents, including filled heads and tails on jogged traces. +- Cropped section details shade oblique wall faces using their view angle and preserve the transmitted tone through nearer glazing. +- Unshaded floor plans print supported wall tops below the cut with their saved outline and projection pen. +- Fixture outlines in floor plans keep closed components that reference an identical deduplicated face. +- Floor plans smooth curved fixture outlines using the native arcs of the placed horizontal faces. +- Floor plans print closed sections of placed curtain panels and mullions with their saved category cut pens. + Horizontal mullions below the cut project their saved top faces within the plan range. +- Descending sketched stairs project their attached top rails and clip nosings by the saved rail faces. +- Regular fine sections cover surfaces behind simple closed wall cuts with the wall's cut face. +- Fine sections use the saved structural floor finish on upright slab sides under ambient shading. +- Cropped construction details draw the stored layer interfaces of rectangular ceiling cuts. +- Overlapping cut contours in opaque construction details preserve their saved pen widths along each span. +- Nearer opaque faces clip round flue outlines in elevations and preserve the spans visible through decoded openings. +- Continuous drafting lines on supported fine section surfaces keep their saved positions through PDF rendering. +- Cropped opaque overview sections shade crossed planting panels from the saved solar position and ambient and sunlight intensities. +- Opaque overview sections keep intersected crossed entourage figures whole and resolve their visible panel outlines. +- Opaque overview sections print the visible outline of supported revolved assemblies behind the cut. +- Regular fine sections print the visible silhouette of placed specialty equipment built from closed revolved meshes. +- Fine model sections preserve visible door jambs at their original depths and print saved finishes on opaque doors. +- Regular fine sections shade the open areas of supported glass panes using nearby model geometry. +- Site plans print saved electrical and site equipment symbols, including photovoltaic panels and wind turbines. +- Visible site equipment with supported symbols casts shadows using the saved site lighting. +- Site plans size RPC planting marks from the saved plant height and draw the common radial profile. + +- Site plans respect the saved visibility of terrain, planting and entourage categories. +- Upper floor plans draw the descending arrow of supported sketched stairs along their saved centre paths. +- Upper hidden-line plans draw saved nosings and mask room colour across the opening of a supported sketched stair run with a view-owned path. +- Patterned overview elevations print the visible axes of verified horizontal and inclined railing tubes whose diameter is narrower than the projection pen. +- Patterned overview elevations retain visible nearer copies of stair edges when a coincident farther projection was hidden. +- In lit elevations, RPC planting inserted in front of the view plane retains its terrain shadows and is excluded from the shadow pass on visible model and planting surfaces. +- Lit elevations use the saved light to shade the visible unlit faces of crossed-plane entourage, with depth clipping against the model and planting. +- Elevations outline crossed-plane entourage display meshes without printing their triangulation diagonals. +- Soil cut shadows in cropped elevations use the foreground planting facets that face the view plane. +- Section callouts keep projected face indices paired with their depths until sloping wall edge clipping is complete. +- Opaque plans draw saved top-view region edges, masks and symbolic curves for supported plumbing and furniture families at medium detail. +- Opaque plan furniture respects saved geometry exclusions for the top view. +- Opaque plans draw visible solid outlines and top opening rims of supported multi-solid fixtures. +- Plan viewports omit projected roof-opening outlines outside their saved vertical range and for hidden inserts. +- Patterned overview elevations restore verified round flue outlines and shade them using the saved light. +- Cropped opaque section details use the projected depth of planar walls, slabs and stairs, preserve visible coincident stair edges, and retain silhouettes of placed site objects. +- Cropped section details with saved ambient shadows show the backing through supported transparent glazing. +- In cropped section details with saved ambient shadows, transparent mass surfaces preserve the backing visible through them. +- Opaque cropped section details honor the view's saved hidden categories when projecting and cutting geometry. +- Fine sections with ambient shadows apply the saved glazing tone where a pane has no opaque backing. +- Regular cropped fine sections respect saved category visibility and keep the exposed spans of sloping wall edges. +- Fine sections project verified round structural columns with their material patterns and mask their projection at closed pad cuts. +- Opaque overview sections draw verified round column silhouettes with their surface patterns and use the exact element table for placed columns and casework. +- Opaque overview sections also use the exact element table for furniture, plumbing fixtures, speciality equipment and structural foundations. Placed terrain clips projected building pads behind it. +- Opaque overview sections at fine detail draw the saved floor layers and thin drafting hatches inside supported closed cuts. +- Cropped opaque overview sections trim projected wall edges inside overlapping coplanar faces of the same wall type and material. +- Patterned elevations and overview sections draw the open edges of placed planting meshes with their category pen, clipping them behind nearer geometry and the ground cut. +- Fine sections omit internal handrail seams shared by coplanar faces, including repeated faces from embedded rail components. +- Opaque fine sections use exact ownership to omit family definition geometry and retain exposed sloping wall edges in callouts. +- Regular cropped fine sections exclude embedded family geometry when the project table is exact, clip edges behind round shafts, and mask projections behind closed floor cuts. +- Regular cropped fine sections include placed terrain and verified planar facets in ambient occlusion. +- Fine sections shade thin frames missed by the regular sampling grid and retain both edges of thin rails where visible around nearer posts. +- Elevations clip shadows on convex terrain facets against the closer terrain. +- Cropped elevations with cast terrain shadows hide supported planar faces and projection edges behind nearer placed terrain. +- Cropped overview sections hide the projected wall edges and structural foundation faces and edges behind nearer placed terrain. +- Cropped overview sections fill the placed terrain behind the section plane, including small facets between the larger polygons. +- Overview sections keep the visible stair treads and compare nearby wall depth at the projected stair and railing edges. +- Overview sections compare oblique stair risers at the projected tread position within the same native stair assembly. +- Elevations with cast terrain shadows draw the saved ground colour below the horizon and clip cut terrain at the view plane. +- Cropped elevations project foreground planting shadows onto the soil cut at the saved view plane. +- Elevations respect authored shading colours on supported grouped electrical equipment and keep its transparent covers unfilled. +- Straight section traces in plans print the supported filled head and tail, with the viewport detail and sheet numbers. +- Plans use the saved cut height, material pattern and category pen for closed column profiles. +- Elevations and sections omit discovered light-source construction faces. Regular fine sections with + saved ambient shadows shade supported opaque surfaces from nearby model geometry. +- Fine section callouts use the saved glass tint over their opaque background. +- Fine sections retain visible lighting fixture outlines and thin suspension geometry. +- Fine section ambient shadows use the saved ambient and direct light levels. Occluded sample points + contribute to the tonal gradient across the exposed parts of the same face. +- Unshaded sheet plans keep native wall ends and jambs when a closed model section preserves the saved hosted openings. +- Unshaded sheet plans retain wall mitres from closed model cuts at the saved cut height. +- Floor plan wall fills use a white base when the saved view uses unshaded hidden lines. +- Axis-aligned floor plans on sheets draw saved circular elevation markers with one attached view and its sheet reference. +- Supported level heads print names and elevations with their saved family label positions, sizes and backgrounds. +- Elevation and section levels with model extents use their saved leader positions. The East elevation + on A105 aligns straight levels with the saved head column of the jogged levels. +- Detail callout boundaries use round caps on their fitted dash segments. +- Cropped hidden-line construction sections hide internal cut edges where walls of the same material + overlap in a closed profile. +- Closed wall, floor, foundation and pad cuts in cropped hidden-line construction sections print a white + base behind their material hatches. Projected surfaces retain their view shading. +- Construction sections with a saved crop print the terrain cut and its material hatch. The ground strip + is visible at the bottom of Typ. Wall Section on A104. +- Fine sections clip door and window outlines at nearer railing faces. On A105 the visible jamb + segments in Stair Section and Main Stair Detail remain between the rails. +- Title block revision tables with supported regular Arial styles use the saved header and body text sizes + for the heading and row heights. A hidden title section preserves the visible column header and its styles. +- Sections use the cut depths and jog positions of the saved front-cut trace. On A104 the deeper span + of Building Section reveals the terrace, floor and living room. Coincident projected outlines + underneath the cut strokes are clipped to their uncovered spans. +- Cropped section details ink the original face edges while keeping the cropped polygons for fills and occlusion. +- Sections draw saved right-only level heads and leaders with the model extent at the other end. +- Elevations and sections draw visible window and door opening symbols from the saved direction filters, + including families whose opening marks apply at every detail level. +- Elevations and sections ink coincident site mesh strokes once after clipping. On A104 this removes + repeated entourage strokes from West and Building Section and restores the outline of the figure + seen from behind using its saved mesh. + +- Elevations and sections respect saved hidden element lists. Fine section projections trim edges where they + pass behind the face of a stair tread or riser. + +- Elevations and sections omit viewport annotation geometry and meshes attached to discovered material, + constraint and reference plane records. + Fine sections preserve the distinct edges of cut stairs, runs and treads. + +- Fine sections show saved glazing patterns where recovered curtain panels cover the fallback faces of an + incomplete curtain assembly. + +- Fine sections keep coincident skylight frame edges at their model depths until hidden lines are resolved. + Transparent glazing leaves the visible edges of the frame behind it. + +- Fine sections clip placed site geometry at the section plane and omit unplaced site and planting symbols. + Regular fine sections with annotation cropping disabled use the saved full envelope for default grid heads. + +- Planting on elevations with cast shadows keeps its visible silhouette and shade in front of distant model + faces. Geometry closer to the viewer masks the covered portion of the planting. + +- Title-block text uses the family's font sizes and alignment. Labels wrap at their stored widths, and the scale + field shows a shared scale or the localized "As indicated" caption for mixed scales. + +- Site viewports draw saved terrain contours, roof footprints, cast shadows from model faces for supported view lighting, and + planting tags with their saved leaders. The north marker uses its family curves and saved placement. + Sloped terrain receives shadows and casts them beyond its edge onto the authored ground plane. + Primary and secondary terrain contours use their Object Styles pens. Supported roof patterns use the + saved face placement and leave skylight openings clear. Contour labels use their stored positions and directions. + Property boundaries fit the saved dash pattern to both ends. Supported segment tags show the bearing and + distance, including chord distances on arcs. + +- Fine sections print supported projected material patterns, including the stair views' timber cladding. + The Stair Section draws the saved callout for Main Stair Detail. Round railing tubes retain their + cylindrical silhouettes in fine sections. Cropped stair details use the saved annotation crop for default + grid and level ends. Straight top rails retain their native contours in fine sections, including when + the front and back faces project to the same outline. + Fine cropped stair sections use the saved cut patterns of their wall and floor layers. + Elevations and sections draw supported roof seam grids from the saved face placement and skylight openings. + +- Supported circular generic annotations print from the saved family fill, border and text. Sheet viewports + use the separate annotation crop, including on rotated site plans. + +- Opaque hidden-line sections with both shadow modes off use white model surfaces with their existing cut pens + and material patterns. + +- Supported viewport titles use their saved annotation-family geometry, font sizes, wrapping and display settings. + The extension line uses its stored placement and length. + +- Floor-plan door and window tags use their saved view anchors, annotation-family outlines, and instance or + type marks specified by the family labels. + +- Floor-plan room tags use their saved placement, supported leaders, and annotation family labels and frames. Area labels + use the project's display units. + +- Furniture and fixtures follow the saved floor plan range, including lowered levels. Opaque hidden-line + views mask room fills with the projected face boundaries, including holes. Hidden section marks stay hidden. + +- Cropped plans print supported linear dimension chains at their saved positions, with their witnesses, ticks + and project units. Horizontal text notes use their saved frames and leader geometry. + +- Cropped plan viewports print supported grid bubbles and leaders beyond the model crop from their saved datum + settings. Plan room fills and legend swatches use solid background colours saved in the view's room-name scheme. + +- Draw title-block PNGs from their saved placements and evaluate supported itemized schedule rows from stored + instance parameters. Render merged schedule text within its band. + +- Print rendered views at their saved paper size, project authored property boundaries onto the cropped site plan, + print rooms with curved boundaries, place room legends at their saved anchors, and include the building context + inside the stair section crop. + +- Cropped construction details draw stored straight callouts, batt insulation and computed break masks. Exact + wall and slab cuts can use the drafting cut patterns of their decoded layers. + +- Printing places cropped construction details by the stored viewport offset whenever the mapped crop + intersects the sheet. Details use their active annotation crop for default datum endpoints and print the + supported level and grid heads at their saved sizes. The four construction details on the Revit sample + sheet A104 now align with the reference export. + ### Changed - The printing docs say what is still not drawn (the plane of a section, the detail views without linework, the graphic @@ -15,6 +213,9 @@ API between minor releases. ### Added +- Use `--viewport-image ID X Y WIDTH HEIGHT JPEG` when printing sheets to include native rendered graphics for a + specific viewport, including the solar study. Bounds are measured in sheet millimetres. + - CLI and API: `rvtio sheets` lists sheet parameters and filters sheets by them, ported from rvt-prt's `list --params/--where` (Unreleased after 0.1.0). `SheetRecord.Parameters` carries the text and whole-number project/shared parameters of each sheet as display strings (numbers with units stay out until their units are read); Yes/No parameters (`Appears In Sheet List` and project/shared parameters of Yes/No kind, named in `SheetRecord.YesNoParameters`) read as `Yes`/`No`. `rvtio sheets --where NAME=VALUE` (also `!=` and `~` for contains, `*`/`?` wildcards, repeatable, case-insensitive) keeps only matching sheets; on a Yes/No parameter `true/false/1/0` mean `Yes`/`No`, every other field compares literally. A misspelt name or an empty match exits with code 1. `--params` lists each kept sheet's parameters on standard error, `--csv` writes them as CSV, `--json` keeps the default JSON. New API: `SheetFilter.TryParse/Matches`, `SheetCatalog.FromFiltered`, `SheetFilter.AvailableNames`. New tests: `SheetFilterTests`. - CLI: `rvtio print --where NAME=VALUE` (also `!=` and `~`, wildcards, repeatable) prints or lists only the sheets whose parameters match, as in `rvtio sheets --where`; it needs `--sheet`, `--all-sheets` or `--list-sheets`, and with `--sheet` a sheet prints when it is one of those numbered and matches the filters. New tests: `PrintCommandTests` filter cases. @@ -272,7 +473,25 @@ The text of a sheet prints too: a text note's RTF string (class 0x0F83 block) is - Windows and doors ink through their host wall: a window sits inside its wall, whose face decodes with no opening, so the wall face up to half a metre in front of a window or door edge no longer hides it — before, the whole window vanished behind its own wall (the West elevation drew no windows at all in the sampled bay). A genuinely separate mass further in front still hides them. The sampled bay now draws the four window frames with their sashes where the reference draws them (its dashed diagonals are family symbolism with no decoded source — the types carry only degenerate points). Measured: raster line score recall 34.6% -> 35.7% (A104), 42.5% -> 42.8% (A103), 36.3% -> 36.8% (A105) with precision 56.3% -> 56.5%, 73.3% -> 73.0%, 73.5% -> 73.1%; `rvt_prt compare` recall up on A103-A105 (92.0%, 78.5%, 88.4%) with lower vector-only precision on the raster-backed pages. New test: `OccludeEdges_KeepsWindowsSetIntoTheirWall`. Full print suites 138/138 green on net8.0+net10.0. - Documented dead end: filling each subdivided layer span with its decoded cut pattern (Sand, Diagonal up 1.5 mm and the like resolve for the thin skins, while the structural core has none) added ~190 in of vector ink with zero recall gain on A104 (measured `rvt_prt` 79.1% / 64.1% -> 79.1% / 60.2% with the hatch, raster flat at 35.7% / 56.5%). The decoded patterns do not match what the reference draws inside these strips, so only the layer boundaries ink. No code ships for this; the ground hatch has no source either (the file holds no terrain mesh, the pad type has no material, no pattern is referenced by any ground element). + Documented dead end: filling each subdivided layer span with its decoded cut pattern (Sand, Diagonal up 1.5 mm and the like resolve for the thin skins, while the structural core has none) added ~190 in of vector ink with zero recall gain on A104 (measured `rvt_prt` 79.1% / 64.1% -> 79.1% / 60.2% with the hatch, raster flat at 35.7% / 56.5%). The decoded patterns do not match what the reference draws inside these strips, so only the layer boundaries ink. + +- Occlusion on elevations and sections uses the stored host wall ID for windows and doors. A deeply inset window or door stays visible through its own wall. A skylight can show through the decoded opening of its host roof face, while other faces of the roof can still hide it. Separate foreground elements use the standard depth tolerance, and faces within the insert keep their existing clearance for inset frame detail. + +- Coarse elevations and sections at 1:100 or smaller keep the shared jamb of adjacent windows on the same host. Faces that project across the jamb retain the usual occlusion rule. + +- Overview sections at 1:100 and coarser print the grade from the intersection with the decoded topography. Projected building faces and solid building-pad footprints clip out concealed spans before PDF export. + +- Overview elevations print the decoded grade at the stored view plane where it crosses a solid building pad. The pad footprint and model faces in front of the plane clip the grade line. + +- Overview elevations hatch the ground below the visible grade and building pad from the project's site cut material and poche base. Drafting grids use the view origin and the hatch is clipped to the viewport. + +- Overview sections use the same site cut material below the cut terrain and pads. Projected model faces clip the hatch strokes before PDF export. + +- Ground hatch rows join overlapping and touching terrain spans before placing the drafting dashes. + +- Elevations and sections print supported round datum heads at their saved positions. Levels use the view's stored endpoints and leaders. Grid heads use their family dimensions and authored vertical extents. + +- The model crop clips terrain and planting fills before the datum annotation strip. ## [0.4.0] - 2026-11-13 diff --git a/docs/printing.md b/docs/printing.md index 53aaccec..624ac9aa 100644 --- a/docs/printing.md +++ b/docs/printing.md @@ -47,34 +47,110 @@ left out until its renderer exists. The library API is `RvtIO.Print.PlanPrinter`: `Levels(document)` returns the printable levels, and `Render(document, levelId, scale, options)` returns a `PdfDocument` with one page. +Axis-aligned floor plans on sheets print the supported circular elevation marker with one attached view. +The marker's position and body and pointer families come from the RVT. The pointer follows the view direction, +and the labels read its detail and sheet numbers from the placed viewport. The saved crop, cut height, +coarsest scale and hidden elements determine which markers appear. +On sheets, walls in a plan with a saved unshaded hidden-line style use a white base under their outlines. +At the saved cut height, closed wall sections use the model faces and their opening loops. The cut retains +mitred ends, jambs and shared-wall joins. Saved hosted opening spans remain clear even where the model section +has a solid face above or below the opening. Such cases use the wall-axis outline with its saved gaps. +A wall below the cut and within the saved plan range uses its horizontal top face when that face covers the +wall's plan projection. The outline uses the Walls projection pen. +Opaque plans also retain the visible outlines of supported closed fixture components below the cut, even +when the same saved face belongs to more than one component. A rigid instance placement carries the +saved circular arcs into the view. Matching runs on horizontal face boundaries use the arc samples for +projection and occlusion. +Plans cut supported closed curtain panels and mullions at the saved cut height and use their category cut pens. +Horizontal mullions below the cut and within the saved plan range project their top face with the projection pen. +Curtain outlines respect the viewport crop, category visibility, and hidden components and hosts. +Plans use closed column sections at the saved cut height, with the column category's cut pen and the +material's supported drafting hatch. A matching vertical cylinder in the placed symbol supplies a +circular outline. The bounding footprint provides the fallback when the cut is unavailable. +A straight section trace in an axis-aligned plan can print the supported filled head and tail. The view +type supplies the symbols, their bounds fix the size on paper, and the placed viewport supplies +the detail and sheet numbers. + ## Images The title block family's logo is read from the file: Revit keeps the placed image files in the partition streams, so the -reader decodes the PNG it finds there (8 bits per channel, RGB, RGBA or palette) to an RGB raster and the PDF writer -embeds it as an image object with Flate compression. The logo is fitted into the logo area of the title block strip with -its aspect preserved. The API is `PdfRasterImage` and `PdfPage.DrawImage`. +reader decodes the PNG to an RGB raster and the PDF writer embeds it with Flate compression. The renderer follows the +title block symbol's GImage to its ImageSymbol and image holder, and uses the stored origin, dimensions and scale +for axis-aligned placements. The constructed title block strip keeps its existing logo fallback. ## 3D views -A 3D view placed on a sheet (a rendering that has no image, a solar analysis) prints as an isometric projection of the -model from above the south west corner, white faces with their outlines: it is the massing the view would show, not the -shaded picture Revit renders. +A regular 3D view prints as an isometric projection of the model with white faces and outlines. An analysis view +with a decoded orthographic camera and an active model section box prints the model at its saved sheet position +and scale, using the RVT material colours. The section box clips the geometry in model space. +For a multi-day study with fixed hours, the saved study settings supply the compass size, ground level, dates, +time range and active frame. The compass follows true north from the active project location. The latitude, +longitude and time zone drive the solar band and dates. Hourly studies also show the active sun and its time. +When the view enables lighting and cast shadows, opaque geometry casts shadows on model faces, terrain and the +saved ground plane at the active hour using the saved shadow intensity. The solar annotation can be hidden independently. +Graphics transparency is composited at each pixel in depth order over the lit geometry behind the panes. Surfaces +facing away from the active sun use the saved shadow strength as an approximation for their light level. +The view's surface-pattern switch controls continuous and dashed model grids anchored to their saved face placement. +The edge switch adds saved planar boundary loops. These markings follow the painted faces, so openings, foreground +geometry and the model section box hide the corresponding parts. +To include Revit's full rendered study, export and crop the viewport image above its title, then supply the image +and its sheet bounds to the composer. + +```text +rvtio print model.rvt sheets.pdf --all-sheets --viewport-image ID X Y WIDTH HEIGHT image.jpg +``` + +`ID` is the placed viewport's element id. X and Y measure from the lower-left corner of the output sheet in millimetres. +The width and height use the same units. The API is `SheetComposeOptions.ViewportImages`. The supplied image +replaces the generated model image. The analysis viewport title comes from the RVT in both cases. ## Rendering views A rendering view (a 3D view Revit rendered) prints its image: Revit stores the JPEG in the block of the image symbol's type (class 0x0890), the reader finds it among the partition streams and the PDF writer embeds it with the DCTDecode -filter without decoding the picture. A sheet places it at the offset of its viewport, keeping clear of the title block -strip. +filter without decoding the picture. On sheets, a rendering is centred at its stored viewport offset and sized by +the image symbol's paper dimensions and the placed instance's scale. The default size and title block clearance +apply when the file's dimensions are unavailable. ## Printing a site plan -A view named "Site" or "Site Plan" draws only the planting tags and the north arrow over the paper: the reference -site plan shows no building, terrain, contours, planting graphics or entourage, only the tags with their leaders -(the fall of the ground reads from its spot elevations, the planting from its schedule). Each kind of plant is -tagged the way the planting schedule tags it (T1, T2, ... with the real type marks) on a leader line from the -plant, a north arrow stands at the lower right of the site, and a planting schedule under the plan lists -every kind of plant with its count. +A view named "Site" or "Site Plan" draws the terrain, contours, building outline, plants, entourage and the +authored straight and circular property boundary segments. The segments follow the same rotated view basis and crop +as the terrain and keep their full extent when surrounding terrain is discarded. Plant tags use the schedule type +marks (T1, T2, ...). The sheet includes the north arrow and planting schedule. +Placed terrain, planting and entourage respect the site view's saved element and category visibility. + +Cropped site viewports use the saved crop for the extent of the model. They draw stored primary and secondary +contours from placed terrain surfaces with their Object Styles pens. Supported contour labels use the stored +anchor, direction, text size and project length format. Planting instances use their saved insertion points. +RPC planting with a saved model height uses a circular plan mark with a radius of 27.5% of that height. +The 16 spokes use the shared profile measured on the Revit sample export and follow the saved view basis. +Planting without RPC metadata retains the bounds-based mark. +In lit elevations the saved RPC insertion point determines whether a plant casts shadows onto visible +geometry. A point in front of the view plane keeps the terrain shadow contribution. +Supported planting tags use the family frame and label, the type mark, and the saved head and leader offsets. +Supported line-and-arc annotations such as the north marker use their family curves, pens and saved placement. +Coarse and medium site plans draw supported electrical and site equipment from saved top-view symbol curves +and masks. Masks cover terrain contours, and the saved lighting still shades the equipment. Visible site +equipment with a supported symbol can also cast shadows from its placed model faces. + +Property boundaries fit their line pattern between the segment ends, with equal terminal dashes. Supported +segment tags use the saved anchor and family label offsets. Quadrant bearings in degrees, minutes and seconds +use the active project location. The displayed distance of a curved segment is its chord length, and its label +follows the tangent at the saved anchor. Distance labels use their family's explicit unit format. + +Opaque hidden-line site views print roofs within their saved view range. The boundary and skylight openings +come from the model face loops. The view projects planar glazing of visible hosted windows and clips the +white hidden-line fill to the roof openings. Where the view shows surface patterns, continuous model grids +use the face's saved pattern placement, with the face loops clipping the ink around openings. With relative lighting and a level +ground plane enabled, the saved sun angles project the roof shadow onto that plane at the view's shadow intensity. +The site view also projects horizontal treads and landings from visible placed stairs within the saved view +range. Nearer model and terrain faces clip the projection at their local depth. The visible stair surfaces +retain their cast shadows and use the saved projection pen for their outlines. +Visible horizontal slab tops use the same depth and shadow projection. The hidden-line glazing of roof +openings masks surfaces below the panes. +Placed top rails use planar faces from the visible railing's native geometry. The projected outline joins +the top faces, and their solid faces cast shadows onto the visible model and terrain. ## Printing an elevation @@ -86,19 +162,302 @@ other edge is drawn once, and an edge whose midpoint hides behind nearer mass is collapses to one line: parallel edges within 50 mm at the same depth and of the same length (a railing family drawing one board four times, a window jamb doubled by its frame) ink once, keeping the nearest; a short edge on a long one stays, lines at different depths stay, and staggered layers stay, so distinct linework is never lost. -Windowed details skip this and keep every fine construction line. A face counts as nearer +Windowed details skip this and keep every fine construction line. Fine sections retain separated +projection edges from the same visible door frame face and add them after model-edge selection. +A face counts as nearer by its nearest corner (a wall end turned away from the view still covers what stands behind it), and a midpoint on the boundary of the nearer face counts as inside (half a millimetre): stacked wall layers and window frames project -onto the silhouette of the mass in front, and the reference draws that silhouette once. Plants, topography and +onto the silhouette of the mass in front, and the reference draws that silhouette once. A window or door edge +can show through the wall identified by the insert's stored host ID. A skylight can show through the +decoded opening of its host roof face. For the host roof, depth is measured on the face at the projected +edge midpoint, so a nearer corner elsewhere on the slope cannot hide the window frame. Other roof faces +can still hide it. Fine sections and elevations that see the skylight glazing edge-on keep coincident skylight edges +at their model depths through occlusion. +Opaque frame faces hide farther edges and transparent glazing leaves them visible. The visible edges are +then merged in projection. Other inserts use a 500 mm clearance for their own faces to keep inset frame +details visible. Faces of other elements use the standard depth tolerance. At 1:100 and coarser, adjacent windows on the same host keep +their vertical junction when the incident faces project to opposite sides of it. Actual overlapping faces +still occlude. Elevations and sections omit viewport annotation geometry and skip discovered material, +constraint and reference plane meshes before projection. Native model elements that share the material +category are retained. Fine sections preserve +the distinct edges of cut stairs, runs and treads when consolidating coincident projections. In fine sections with +surface patterns enabled, an incomplete curtain assembly clears its fallback faces only over the corresponding, +face-on rectangular glass panes with decoded model fill patterns. Other cells keep the fallback geometry. Elevations and sections use the view's saved hidden element lists +before projecting model elements, datums and break lines. Fine sections clip projections at the closed, +face-on stair surfaces at their model depths and preserve the visible portions of partially covered edges. +The model crop limits fills and occlusion. Cropped section edges retain their original face boundaries, so +the crop rectangle adds no model strokes. +Plants, topography and site surfaces are left out of the building itself: they print as light shapes without outlines behind it, the faded context the reference export shows around an elevation (their faces of a few square metres, so the ground mesh does -not bury the building). Where the viewport decoded an axis-aligned crop box, the drawing is filtered to its rectangle +not bury the building). Overview sections and regular fine sections with a usable model crop intersect the upper +terrain faces with the saved cutting plane and print the visible grade line. Projected model faces and the +footprints of solid building pads hide the grade they cover. At 1:100 and coarser, elevations print the +terrain profile at the stored view plane. The foreground portions of elements that reach the view plane +can hide this profile. Elements wholly outside the view leave the grade and hatch visible. +Closed intersections through walls, floors, foundations and pads draw their cut contours at the elevation plane +and leave their interiors clear of the soil hatch. In elevations that show surface patterns, supported drafting +grids from the cut material fill the closed profiles. Rectangular cuts through layered walls and floors use +each layer's material. The view origin anchors the patterns in paper units. +These elevations and sections hatch the ground between the profile and the stored poche base. The project +`TrueNorth` record supplies the base elevation and cut material. The material's cut pattern uses its decoded +drafting grids, anchored to the view origin. On elevations, the hatch follows the visible terrain spans and continues under the +pad at its stored elevation. In sections, the fill follows the cut terrain and pad profiles. Projected model +faces clip individual hatch strokes before PDF export. Overlapping and touching parts on the same hatch row +print as a single interval. The grade stroke is drawn over the hatch. +Where the viewport decoded an axis-aligned crop box, the drawing is filtered to its rectangle at generation time (the scorer counts vectors, not the page clip), and levels, grids and the outline follow it. The stored rectangle is origin-relative view feet (rvt-prt's viewer_frames), while the collected content runs in absolute projected millimetres, so the filter offsets it by the view origin's projection; without the offset the frame lands right but the wrong slice of the model is drawn (the stair viewport missed by 146 mm, the 1:20 detail by 365 mm). -The level lines are thin and dashed (3 mm on, 1.5 mm off on the reference). Each spans its decoded datum +Sections with an orthogonal jog in the saved front-cut polyline project each horizontal span from its +own cut plane and join the spans at the saved jog. The end planes extend to the crop beyond the plan +symbol's end marks. At a shifted cut plane, the printer clips the parts of projected strokes that +coincide with cut strokes. Levels, grids and view-owned annotations draw once across the viewport. + +For the supported round datum heads, elevations and sections use the head symbol's saved dimensions. +Level names and elevations use the label style and position saved in the head family, including opaque backgrounds. +On Windows, regular 12 pt Arial labels use device text metrics for the text box. Other supported layouts use +the embedded font's metrics. +Levels use the view's stored datum ends and leader points where supported. A right-only level override keeps +the saved model extent at the left. A level with model extents uses its saved leader elbow and anchor. +When those anchors agree for levels of the same type and projected envelope, straight levels of that type +with the same envelope use the shared head column. Grids use the saved vertical bounds or that +view's own endpoint overrides. Authored annotations can extend outside the model crop, and their dash +patterns balance the two ends. For sections with an active section annotation crop, +default datum ends are clipped using its stored paper offsets around the model crop. The supported level +heads and top grid bubbles use their saved family sizes at the resulting endpoints. +Other heads and views without usable records use the existing fallback. + +A cropped construction detail can show a child callout on the same sheet. Its child crop supplies the rounded +boundary with round-ended dashes. The saved parent-view head point places the straight leader and tag. +The viewport supplies the detail number. In the roof connection, the view-owned batt insulation supplies its +axis and width, and the computed break-line symbols supply the stretched break path and masking side. The mask clips the covered model +and insulation strokes before they reach the PDF. Perpendicular wall cuts and horizontal floor and ceiling cuts use +stored drafting patterns in the matching material bands when both sides and the exact layer stack are available. +In opaque cropped details those bands also place the layer boundaries, including layers without a cut pattern. +Where closed wall and roof cuts share a boundary with material on opposite sides, the shared span uses the projection pen. +When solid cut edges with different object-style pens overlap, the wider pen inks only the span contributed +by its source cut. The narrower edge keeps its own pen outside that span. +Sections at 1:50 or larger with a usable model crop use the same cut patterns through the regular section +projection path, including cropped stair sections. The site context in fine sections uses placed elements +and is clipped at the same section plane. +Cropped construction sections also cut and hatch the site through their saved section plane. +The printed grade stays inside the model crop. The hatch uses the site material and clips around cut foundations. +Its stroke width comes from the Topography Surface cut pen at the printed view scale. +In opaque hidden-line construction sections, closed wall, floor, foundation, pad and layered roof cut +profiles use a white base. The base covers projected surfaces and clips the spans of model edges behind the cut. +Material patterns and cut edges print above it. Faces with decoded openings preserve the projection through +the opening when the cut rings close. In aligned opaque fine sections, wall material hatches follow +those rings around junctions and openings. A perpendicular cut shows the stored roof layer boundaries +when the opposing faces match the total layer thickness. Two slopes that share a ridge join at the +intersection of their offset planes. The verified roof section supplies the white base and the bounds +of each layer's drafting cut pattern. A saved Fine view with an aligned model crop also enables these +roof layers at smaller print scales. Roof layer boundaries print after the model edges have been resolved. Valleys, nested rings and incomplete +geometry use the fallback. In aligned fine sections, a stair with one decoded face material and closed +cut profiles uses that material's drafting cut pattern. The stair body's profiles supply the hatch once +even when a modeled landing shares part of the cut. +When two walls have the same single face material, a simple closed cut of one wall clips the interior spans +of the other's cut edges. The outlines and layer lines print at their own boundaries. +In opaque cropped details, view-parallel wall faces without openings clip horizontal wall projection edges +at their actual outlines when the whole face is nearer. The remaining spans use the verified source plane +to calculate depth at the new midpoint. An overlapping wall on the same plane then keeps the shared outline visible. +Overview sections and regular fine sections with a usable model crop use white base surfaces for a saved +opaque hidden-line display. Other fine sections use white surfaces when both saved shadow modes are off. +In regular fine sections with ambient shadows, upright projected sides of structural floors use the saved +structural material's graphics colour as the base for ambient shading when the material is opaque and uses +its graphics appearance. +A regular fine section also paints a white cut face for a closed wall solid where the section plane yields +a single closed ring. The cut face covers the projected surfaces and edges behind that ring. +Section cut pens, model edges and material patterns are handled independently of the surface colour. +Fine sections with opaque hidden-line display and surface patterns enabled print supported drafting grids on the +faces that name their material. In a cropped model section, each continuous line uses the saved spacing and +view origin, and the face clips the combined vector fill. This keeps line positions independent of the PDF +reader's repeated-cell placement. Dense patterns and detail windows use a reusable PDF tile. Regular fine +sections use the saved widths for supported surface pattern pen categories at the view scale. +Nearer faces cover patterns behind them. The sample's Stair Section and Main Stair Detail use the +wood cladding's 3 mm vertical grid. The Stair Section also draws its nested Main Stair Detail callout using +the saved boundary, head and sheet reference. +Elevations and sections that show surface patterns also project a supported roof's continuous model grid +using its saved face axes and origin. Skylight holes interrupt the grid. Parallel opposite faces of a closed +roof shell use their relative plane depth to keep the interior skin behind the patterned exterior. +A curtain assembly with every native panel resolved prints the placed panels, doors and mullions. +Openings from the inner loops of walls and elevation frames apply to both fill and edge visibility. Glass faces use their +saved model pattern placement and material's dash grid, with the same instance transform as the face. +In a regular fine section with ambient shadows enabled, a pane with a decoded glass finish transmits the +gray tone of the opaque materials behind it. The pane's material transparency and the view's ambient +light intensity control the blend, which is clipped to the pane and painted in model depth order. +Open areas of the pane blend over the white background and use the same local ambient shadow sampling +as opaque faces. The printer composites visible backing surfaces over that background within the pane. +Regular cropped fine sections with the saved opaque display exclude model geometry in categories hidden in that view. +When the project element table has been read exactly, these sections leave geometry discovered outside the table out of the projection. +Opaque fine sections with an exact element table project placed family instances and skip geometry directly owned by a family definition. +Fill pattern definitions supply material graphics for faces and are excluded from the model geometry pass. +A sloping wall edge at constant view depth keeps the spans outside closer opaque planar faces in +regular sections and callouts. Visibility is resolved in model face order before painting the +fills from far to near. +Round structural column shafts wholly behind the cut use the analytic cylinder of the placed symbol when its facets match. +The silhouette carries supported drafting surface patterns. Fine sections also use the saved material colour. +Opaque overview sections with surface patterns use the same silhouette. When the project element table is exact, +these sections use placed structural columns, casework, furniture, plumbing fixtures, speciality equipment and +structural foundations. In cropped overview sections, nearer placed terrain clips projected building pad and structural foundation faces +and the projected edges of building pads, walls and structural foundations behind the cut. +The printed terrain uses the same placed facets clipped at the section plane. Small facets inside the crop +fill gaps in the background, and the cut profile and hatch still draw over the projection. +Overview sections retain coincident stair edges at their original depths until visibility is resolved. +Stair and railing projections compare their depth with the depth of a planar wall at the sampled point +on each edge. +Horizontal tread edges also use the sampled depth of oblique vertical stair faces in the same native +assembly. The serialized owner connects the parent stair with its placed runs and tread components. +Opaque overview sections draw the projected silhouette of supported placed assemblies with one native revolved +mesh and closed solids wholly behind the cutting plane. Nearer opaque faces and cut masks clip the silhouette. +Regular fine sections outline placed specialty equipment made of multiple native revolved meshes when the +decoded shells are closed and lie behind the cutting plane. Edge-on auxiliary faces are allowed. Nearer faces +clip the outline, and the individual facets of the equipment do not add seams. +At fine detail, these overview sections draw the layer boundaries and saved material cut patterns of supported +closed floor sections. Rectangular compound cuts follow the layer thicknesses from the floor type. +View-aligned wall faces at the same depth with matching type and material mask projected edges through their +interiors. The section checks the trimmed spans against closer geometry. +Nearer opaque wall faces aligned with the view also mask the covered lengths of sloping railing edges +parallel to the view plane. +Edges at constant depth behind the whole shaft are clipped at its silhouette. +Closed floor, building pad and supported stair cuts cover projected surfaces and edges behind the cut. +In fine section callouts with ambient shadows, a view-aligned wall face uses its saved graphics colour +when its opaque material matches an explicit finish layer of the wall type and render appearance is disabled. +Core materials and category defaults use the usual wall base. +In a fine section callout, the saved parent view identifies the detail. Its panes composite the +material tint over the opaque view base, with surface marks and model edges drawn above them. +Regular fine sections also approximate ambient shadows on supported planar opaque surfaces. Nearby +placed geometry reduces the ambient light at sampled points. Regular cropped sections include placed terrain +and other verified planar facets. An opaque hit inside the local sampling radius blocks its ray completely. +Ambient rays from stair surfaces enter closed convex stair solids through their verified outward-facing boundaries. +The saved ambient and direct light +levels determine how much of the surface illumination can be blocked this way. Samples behind +nearer faces contribute to interpolation on the visible part of the same surface. When the regular sample +grid misses a thin face entirely, its nearest boundaries supply the sample positions. The tone is clipped +to the surface and its openings, with hatches and edges printed above it. In opaque cropped details, +slab sides use visible samples at cut caps. The nearest visible sample supplies the texture tone behind the cap. +Cropped section details with +saved ambient shadows composite supported view-aligned glazed panels and transparent mass surfaces over +their projected backing. The surface facing the view applies the material transmission once, with its +model pattern and edges printed above it. On opaque walls in cropped details, the direct component +decreases with the angle of incidence. The ambient tone visible through nearer glazing follows the pane +boundary and its inner loops. +In opaque cropped details, planar walls, slabs and stairs occlude projected edges at +the depth of the overlap. Saved hidden categories contribute neither projected geometry nor cut outlines. +Coincident stair edges keep their individual depths until visibility is resolved. +Placed site objects print clipped silhouettes behind the model. Cropped opaque overview sections with surface +patterns, ambient shadows and a supported still solar setting shade crossed planting panels using the saved +date, location, project orientation and ambient and sunlight intensities. The diffuse tone uses either side of +each panel. Projected depth determines which parts of the panels receive the tone where they overlap. The +planting outlines print above the fills. +Discovered light-source construction faces are omitted from elevations and sections. +Fine sections retain small planar faces of placed lighting fixtures, including the facets of thin +suspensions. Coincident projections remain separate by depth until visibility is resolved. +Fully nearer solid faces without openings clip the covered spans of constant-depth fixture edges. +Elevations and sections print supported window and door opening symbols from the placed family's saved +lines. Paired direction filters select the visible side. A saved detail-level condition applies where present. +The graphics style supplies the width, colour and paper dash lengths. The symbol lines go through visibility +before they are added to the model edges. +When a saved elevation shows surface patterns, front-facing walls print supported drafting grids in paper +units from the view origin. Continuous grids leave decoded wall openings clear. Dashed grids print on +faces without openings. +Opaque hidden-line elevations with supported view-relative lighting project cast shadows from planar walls, +roofs, floors, stairs and placed railings, and from planting mesh facets, onto front-facing surfaces parallel +to the view. Opaque skylight frames cast shadows onto the sloped face of their saved host roof when that face +has decoded openings. +Placed structural columns cast shadows from their planar faces when the face material does not declare transparency. +The saved intensity controls the fill. Face openings and the visible terrain cut clip it, and model edges +and surface patterns print over it. +Patterned overview elevations draw the outline of a placed vertical cylinder, such as a flue, when its +paired native cylindrical faces match the placed facets and both rims span the projected tangents. +Wholly nearer opaque faces clip the covered lengths of the flue outline. Their decoded openings leave the +exposed edges visible. The saved light direction sets the edge of the cylinder's own shadow. Cast shadows +use the plane through the two projected tangents. +The saved view plane also clips the casters for shadows on model surfaces and plants. +The same lighting projects building and placed site mesh shadows onto sloping topography. Closer terrain facets +mask shadows on the terrain behind them. In cropped elevations, placed terrain also clips planar building faces, +their patterns and cast shadows, and the portions of projected edges known to lie behind the terrain. +A common vector fill joins the shadows across visible facets. In a cropped elevation the saved view plane also +receives shadows from planting facets in front of it that face into the view or are edge-on. The ground cut +retains those shadows under its hatch and clips them to the soil profile and the closed cut contours. +Opaque site plans with supported lighting project shadows from planar roof, wall, floor, stair, terrain and pad faces. +Opaque planar frame faces of visible hosted skylights in the saved view range also cast shadows. +The closest visible receiving surface above the authored ground plane receives the shadow, including sloping terrain. +Terrain edges also cast onto the ground plane outside the terrain mesh. The PDF joins the shadow facets in a single fill. +Roof shadows retain their receiving face and print above that face's fill and below its surface pattern. +Supported dashed drafting grids in the ground hatch use reusable PDF tiling patterns. The saved dash lengths, +row spacing, shift and origin define the tile lattice. In elevations the opaque hatched cut hides projected +faces and model edges behind the grade and pad profile. In sections that show the cut terrain, closed intersections +of walls, floors, foundations and pads mask this ground layer at the cut plane. The layer covers +projected surfaces behind the ground, so a distant wall cannot hide the grade at the cut. Model projection +edges behind the cut are clipped to the visible side of the ground. When the section shows surface patterns, +supported dashed drafting grids on wall faces use the same PDF tiles and retain the projected face outline. +In opaque hidden-line elevations with a saved gradient background, the PDF shades from the sky colour at +the model crop's top to the horizon colour at model elevation zero. Where the cropped elevation uses terrain +receivers for cast shadows, the saved ground colour fills the crop below the horizon. The saved view plane +clips the terrain surface in elevations that cut the ground. Projected terrain and model faces cover the background inside the +model crop. Elevations at 1:100 and coarser clip projected model geometry and its openings at the saved +view plane. +Elevations and building sections at 1:100 or coarser with a saved view plane draw placed planting and +entourage from their projected mesh facets. +When the view shows surface patterns, the planting pen also draws the open boundaries of triangulated +planting meshes. Shared triangle edges and edges created by the view cut stay hidden. The printed spans +are clipped behind closer planting and model faces and below the visible ground cut. +The view plane clips the mesh, the model crop clips its projection, and a joined fill retains the silhouette +through small facets without printing the internal triangle edges. +With supported cast lighting, the triangulated site meshes also receive shadows. Ray projection uses the +facets behind the saved view plane, and the closer plant facets mask coverage on plants behind them. +In those elevations, opaque model faces and site objects clip planting fills and their shadows according to +the depth at each intersection. Model face openings leave the planting behind them visible. +Placed site families retain the exterior boundaries of small mesh facets, including rotor blades. +Materialless entourage display meshes made of two perpendicular upright planes print their joined +silhouette. The printer recognizes the saved triangles, including an optional flat base. With saved +cast lighting, their visible faces use the shadow tone where the light reaches the opposite side. +Their fills and shadows are clipped behind closer geometry, including foreground planting. Other +materialless entourage meshes retain the edges of their visible triangles. At a section plane the +printer trims the original edges without adding a cut edge across a triangle. Site edges with the +same pen and projected endpoints are inked once after visibility and crop clipping. For a mesh +that lies fully behind the cut plane with only back-facing or edge-on triangles, the printer also +outlines the projected silhouette, without adding its triangulation diagonals. +In opaque vertical overview sections, a crossed entourage figure that intersects the cutting plane +prints whole. The nearer upright panel masks the farther panel where they overlap, and the figure +occludes projected model lines behind it. +Placed grouped electrical equipment in an elevation retains the visible outlines of its sloping planar +faces. The edge visibility pass measures depth at the edge and reads the nested material transparency +and the frame openings, so glazed arrays can show the geometry behind the cover. +The elevation uses the equipment material's authored shading colour when the RVT selects it instead of +the appearance asset. Transparent covers keep their edges without an opaque face fill. +Sections draw the silhouettes of supported round railing tubes from their placed cylindrical faces. +The tube profiles share the section cut, view crop and hidden-line pass used by the rest of the model. +In patterned overview elevations, verified horizontal and inclined tubes no wider than the projection pen print once along +their placed analytic axis. The view plane, nearer model faces and foreground terrain determine visibility. +The tube strokes join the drawing after projected mesh edges are resolved. +If the first projected copy of a stair edge is hidden, a coincident nearer edge can supply the visible stroke +after it passes the model and terrain visibility checks. +Fine sections trim projected door and window outlines only along the portions covered by a wholly +nearer railing face. The remaining jamb segments stay visible between the rails. +Fine model sections keep the physical depths of door edges through that visibility pass. Identical +visible spans ink once after the viewport crop. With ambient shadows enabled, doors without +transparent panels use the authored grayscale shading colour on opaque faces that select it. +Nearer railing faces and separately stored balusters clip the covered spans of projected rail edges. +In fine opaque cropped details, coincident vertical railing and curtain-wall mullion edges retain their native depths through clipping. +A nearer solid can mask the middle of a post while its upper and lower spans remain visible. +Fine sections retain separately visible edges of the same thin rail profile when consolidating +coincident strokes. +When several railing faces share a projected edge, a fine section checks their actual endpoint depths. +An edge shared by coplanar faces on both sides at every depth is an internal seam, including when the +railing and its embedded components repeat those faces. +In coarse sections and elevations with a saved view plane, coincident rail projections keep their distinct +depths until the visibility pass. Coarse elevations apply the same rule to walls, windows and doors. Nearer planting facets clip +the surviving segments. In elevations with a saved view plane, horizontal and vertical boundaries of the same visible railing +face remain distinct when their separation on the sheet exceeds the projection pen width. +For a single prismatic top rail viewed square-on, the printer checks the original face boundaries for +visibility before removing duplicate projected outlines. The view crop trims the source edges without +adding a cap where the rail crosses the crop boundary. + +Fallback level lines are thin and dashed (3 mm on, 1.5 mm off on the reference). Each spans its decoded datum envelope while the datum stays near the crop; where the datum runs far past a narrow crop (the stair at 1:50), the line is clipped to the crop plus a label-strip margin on each side, as the reference ends its lines at the markers just past the frame. Each line ends in the marker the reference export uses: @@ -123,10 +482,10 @@ annotation pen table (pen 1 is 0.1 mm at every scale on the reference), not the A detail section (1:10 to 1:50) is printed when its plane is decoded: the cut is drawn inside the view's own file crop frame (the detail's true extent: a roof detail's crop sits at roof height), clipped to it at -generation time. Without a usable crop the cut falls back to a window of about 3.0 x 2.2 metres around the -point of the plane. A detail the file parks against the border or outside the page is still printed: Revit lays -such callouts out in a bottom row above their own titles (A104's four details), so the frame is anchored on the -decoded title label instead of the file offset. A stair detail (1:20) instead takes +generation time. The stored viewport offset locates the view origin, which can lie outside the page while +its crop is on the page. The mapped crop keeps its stored position whenever it intersects the sheet. +If the whole crop falls outside the sheet, the title provides the fallback anchor. Without a usable crop +the cut falls back to a window of about 3.0 x 2.2 metres around the point of the plane. A stair detail (1:20) takes the file's own crop frame, the way the reference places it next to the stair section; it keeps its grid bubbles and the level lines whose height falls in its crop (Level 1, Ceiling, Level 2: the three bands the reference draws at the same heights; the bands run to the label margin past the crop, while the reference ends each at its own @@ -137,9 +496,9 @@ one moves to the free place of the top row. A view of the section class whose na Stair Detail") is printed as a section too. The plane of a view is looked for in every chunk of the file, and the block layout (class 0x3F8) takes precedence over the older signature, so the details are found as well as the building sections. A viewport whose view is not printed (a wall section at 1:20, a schedule) is -neither drawn nor titled, so a sheet shows only the views the printer can stand behind. A stair section (a view whose name holds "stair", 1:20 to 1:50) -projects only the stairs, their railings, supports, lines, treads and risers, so the page shows the stair rather than -the whole building; the tread/riser boards are the mass the occlusion pass needs, otherwise the stair-body projection +neither drawn nor titled, so a sheet shows only the views the printer can stand behind. A stair section with a usable +crop includes the surrounding building cut within the crop. The stair-only fallback for a small-scale stair section +applies when its crop is unavailable. The tread/riser boards are the mass the occlusion pass needs, otherwise the stair-body projection edges stay inked where the reference hides them (483 faces and 35 stair edges with them, 440 and 121 without). Measured on the Revit sample project: the South view prints the two-storey facade with its balcony rail, columns and roof on sheet A103. @@ -155,9 +514,25 @@ reference draws the sunken living room's carpet as a `Sand` hatch inside the roo the dashes to the room polygon the same way. A stair belongs to both plans of its flight: the base level draws it going up and the top level draws the flight -arriving there (`STAIRS_BASE_LEVEL_PARAM` / `STAIRS_TOP_LEVEL_PARAM`). Its plan linework is the outlines of its -horizontal faces (tread and landing tops) seen from above, so the Level 2 plan carries the tread courses the -reference shows between the stair's sides. +arriving there (`STAIRS_BASE_LEVEL_PARAM` / `STAIRS_TOP_LEVEL_PARAM`). In a hidden-line view whose cut plane +crosses a single run with decoded linear boundaries, the printer uses the saved tread fronts and side paths. +The cut line goes through the last tread at or below the view's cut elevation, using the stair type's saved +angle and symbol size. The part below the line masks the room fill in white. The part above it uses the +stairs' above-cut projection styles and leaves the room fill visible. A straight run with both side paths +fully inside the visible range below the cut uses the saved tread fronts and a white mask across the run. +For a sketched run arriving at the plan's level below its cut, a stair path owned by the view identifies +the descending projection. The saved nosings and both side paths draw the run through its opening, +including treads below the plan's ordinary bottom clip. The joined side paths mask the room colour. +The attached top rail projects through the same opening when it lies below the plan cut plane. Its saved +top faces mask the parts of each nosing they cover at that nosing's elevation. +Other views and run layouts use the horizontal faces of the treads and landings. +An owned top rail with a decoded projection follows the host stair's cut line. The printer fills its +projected faces below the cut and inks the exposed boundary with the rail's projection styles. +On an upper floor plan, the view's own `StairsPathElement` places the automatic descending arrow for a +single straight flight below the cut. For a sketched flight crossing the lower clip, the saved centre +path runs from the last physical nosing to the first nosing at or above the view's cut offset measured +from the base level. The linked arrowhead type sets the open tip for both paths. A straight vertical +descending path can display its saved horizontal Arial label and text offset. A plan also draws the elements below its level that its view range shows. `PlanViewRange2` is a nested object of the view's block (not an element record): five offsets in feet (cut plane, top clip, bottom clip, view depth and a @@ -171,7 +546,8 @@ the roof below Level 2 — reaches the Level 2 plan as the double line along the title block spans (a composed sheet keeps that paper whatever `--paper` says; the option applies to plans and views) (the extent of the title block instance's type, snapped to A4 to A0), every placed viewport draws its view at the offset the file stores for it (the viewport record also stores the reciprocal of the view scale, used when the view's own scale parameter is missing), each view is titled as Revit titles it: the circled viewport number, the view name, its scale and the extension line under the title, drawn from the viewport record's own label origin and length (m_labelOrigin, m_labelLength) in the annotation pen, and the sheet's own text notes -are written at their positions. +use the saved note frame for supported horizontal notes. The top of the frame and the font ascent give the +first baseline. The stored frame height determines the spacing of multiple lines. Measured on the Revit sample project (rac_basic_sample_project.rvt, six sheets A001 and A101 to A105): all six pages are 841 x 594 mm (A1, the size of the "A1 metric" title block), and sheet A102 draws "Level 1" at (180, 453) mm and @@ -181,6 +557,10 @@ project name and its number come from the project information element when the p them), plus: a logo area, the project area, a revision table (No. / Description / Date) and the sheet information (name, number, issue date, drawn by, checked by)). +Title-block notes use their RTF font size and stored alignment. Labels use the linked font's cap height, their +stored alignment and rotation, and the saved text width when wrapping is enabled. The scale field uses the +sheet's override when present or reports the printed scale. Sheets with multiple scales show "As indicated". + ## Printing a sheet ```sh @@ -224,12 +604,40 @@ stays empty. | Columns | the stored bounding box footprint, as a filled rectangle | | Grids | the stored location lines, clipped to the extent of the level (a grid line can run far beyond the building), drawn dashed with the file's center-segment pattern like elevation grids, with a white bubble and the grid name at both ends | | Floors | the sketch loops of the floors of the level, light under the walls | -| Rooms | the floor face of the room's decoded boundary, filled with the colour the reference plan uses for that kind of room (master bedroom blue violet, master bath magenta, bedroom cyan, linen teal, hall blue, entry hall yellow, living light green, kitchen tan, laundry brown, mech green, bath green) and tagged with the room number and the area in m² in a rounded white box at the middle of the room, as the reference plan tags it (the legend carries the names) | +| Rooms | the largest horizontal face of the room's decoded boundary, including the boundary cache for curved walls, filled with the room colour and tagged with number and area. The printer derives area from that face when the room has no area parameter | | Doors | the leaf at one jamb, perpendicular to the wall on the side the door opens into, and the quarter arc it sweeps | | Furniture | the horizontal faces of the furniture, casework, plumbing fixtures, specialty equipment, stairs and railings of the level, seen from above as light outlines (a stair names its base level, STAIRS_BASE_LEVEL_PARAM, not a level) | | Door and window marks | a door's Mark in a circle beside the opening, a window's type mark in a hexagon, each on a leader line from the opening | | Dimensions | a chain between neighbouring grid lines on all four sides of the building, with the distance in millimetres, as the reference plan dimensions it | -| Room legend | below the plan: a colour swatch and the name of every kind of room on it | +| Room legend | the stored room legend instance anchors the first swatch, and its type sets the swatch dimensions. The printer sets text spacing relative to that size. Plans without a decoded legend keep the swatches below the plan | + +Doors draw saved leaf lines and circular swing arcs using the computed family variant and its +instance placement. The plan's cut height selects the symbol's saved range. For direction-only +symbols, including doors in curtain walls, the cut must cross the placed door's vertical bounds. +Wall openings come from the family's cut loop. The swing approximation covers cut-loop openings +without a matching symbol. +Projected roof-opening outlines follow the plan's hidden-element list and saved vertical range. +The printer checks the height of the loop after applying the instance transform, so a skylight above +the range leaves the floor plan clear. + +In opaque plans, furniture silhouettes and their fills respect saved view-direction exclusions +along the family's vertical axis when the placement keeps it vertical. If the filter leaves no +projected model face, the printer keeps the model silhouette until it can read the substitute symbol. + +Plumbing fixtures represented by saved 2D family geometry draw the visible symbol lines in their +saved graphics styles, placed by the instance transform. Opaque views also draw decoded background +masks from closed face loops. Both follow the plan view range and hidden-element list. At medium +detail, supported plumbing families whose model body is excluded from the top view draw their +saved top-view regions, masking surfaces and symbolic lines, arcs and ellipses. Furniture uses +the same projection where a convex saved mask covers the model faces that remain visible from +above. + +Generic model families whose body lies below the plan cut use the projected silhouette of their +model faces, with the same visibility rules as furniture. +In an opaque plan, supported plumbing fixtures and generic families made of closed solids can also +show individual solid silhouettes and the rims of top openings. Surfaces above a line hide the +covered spans. Native surface tessellation supplies the outline when a folded polygon cannot be +triangulated in its local projection. A plan viewport whose view decoded an axis-aligned crop frame draws only that rectangle at generation time, the way elevations do (the scorer counts vectors, not the page clip): walls, furniture and opening frames outside it are dropped, their crossing edges cut without inking the crop boundary, like the reference cuts linework at the viewport frame. Grids keep running past the crop to their bubbles, as the reference draws them to the bubble row. @@ -240,52 +648,65 @@ holds no Cyrillic. Elements are selected by their level (`LEVEL_PARAM`); a wall without a location line or a column without a footprint is left out and counted by neither selection nor drawing. +Circular generic annotations with one solid filled region, a solid circular border and one horizontal text run +print on their owning sheet or viewport. Geometry, colours, pen weight, text placement and instance transforms +come from the RVT family and view. The annotation crop uses the saved paper offsets. This covers the sample's +41 help symbols, including the four on the rotated Site view. + ## What is still not drawn - **The crop region of a view**: a plan or elevation viewport whose view decoded a crop box draws the crop at the view's own scale (the frame is the crop rectangle, placed by the viewport offset); the axes the view was collected with must match the crop basis. A detail section (1:10 to 1:50) is drawn from its own file crop frame the same way, and a view without a decoded crop, with the crop region off or with a rotated basis keeps the whole-model frame. - **The four details of A104**: the "Typical Wall Roof Connection", "Typical Floor Wall Connection", "Typical Foundation Detail" and "Typ. Wall Section" viewports are placed outside the page by the file, so they are laid out in a bottom row above their own decoded title labels, the way Revit places such callouts. -- **A schedule's body rows**: the block of a schedule view stores its visible columns (the "How do I" schedule of the sample +- **Viewport titles**: supported horizontal families supply the marker curves, label anchors, font sizes and wrapping. + The viewport type controls title and extension-line visibility, and the viewport supplies the line placement. +- **Schedule evaluation**: the block of a schedule view stores its visible columns (the "How do I" schedule of the sample stores Level, Topic, What view, Reviewed?; the revision schedule No., Description, Date; the planting schedule Type Mark, Common Name, Count), its shown sections with the title height, the merged title bands and the body rows - with their stored texts, but not evaluated body cells: Revit evaluates them from the model when it draws the schedule. + with their stored texts. For itemized instance schedules with flat sorting, text, integer and Yes/No parameters, + and integer equality or inequality filters, RvtIO evaluates the body from the stored instance values. This covers + the sample's 40 rows in "How do I". Unsupported schedules retain their stored body grid. + The Russian print UI culture renders evaluated Yes/No cells as «Да» and «Нет». Text cells keep their stored values. + The title, merged instruction bands and ordinary column headings use supported saved cell styles. The styles + store cap height in logical pixels at 96 dpi. The printer uses the embedded font's cap height to convert to + half-point sizes and applies the stored horizontal and vertical alignment. + Evaluated rows use a column's horizontal alignment when all of its stored data rows agree. Every per-sheet schedule instance prints at its instance origin with its decoded columns, show flags, grid and outline pens (the negative category ids they name, resolved against the Object Styles), title bands and body grid; revision - rows come from the model revisions explicitly present on that sheet (the sample lists none, like the reference), - padded with empty rows to the decoded fixed height (ScheduleSegmentRec: 21 rows at the measured 16.30 pt pitch - on the sample) the way Revit fills the table to its height; and planting rows group the placed instances by - their resolved type (type mark with the T{n} fallback, common name from the type), with the stored leading - empty rows and a header that wraps into its columns like the reference. + rows come from the model revisions explicitly present on that sheet and pad to the fixed height stored in + ScheduleSegmentRec. For supported regular Arial revision styles, the saved header and body text cap heights + determine the row heights using the measured Revit ratio of 23/12. The heading uses its saved cell style, + including when the title section is hidden. The sample has 21 empty body rows at a 16.299 pt pitch. + Planting rows group the placed instances by their resolved type (type mark with the T{n} fallback, common + name from the type), with the stored leading empty rows and a header that wraps into its columns. - **The table grids of the title block family**: the linework, fixed texts and labels of the symbol are drawn, and the per-sheet schedule instances (revision tables, planting schedule, How-do-I table) print from their decoded view blocks; the symbol-embedded schedule template itself (the cached revision grid with GINFO_NOT_PRINTED) is left out. -- **Property and setback lines**: the site plan prints the topography, the contours, the planting and the entourage, but - the property and setback lines (OST_SitePropertyLineSegment) carry no geometry the reader decodes. -- **Images other than the logo and the renderings**: material textures and the sun-path of a solar analysis are not - pictures the writer can place; an analysis view (Solar, Lighting, Energy, Sun Path) prints no vector massing, - like the reference, which shows no such linework. -- **Annotation elements**: grid names, dimensions, room tags and the section marks are generated by the printer from - the decoded elements, not read from the file's own annotation elements; a section mark prints only where its +- **Property annotations and setbacks**: bearings, distances and setback lines remain outside the supported property graphics. +- **Analysis shading**: the generated analysis viewport uses graphics colours, graphics transparency, approximate + dome shading and shadows from opaque model geometry. The supplied rendered image preserves Revit's rendering + of appearance assets and full lighting. +- **Annotation elements**: plans print supported grids, dimensions, room tags and text notes from the owning view's + decoded annotation data. Room-tag leaders support vertical attachments to a single centred label. Room area labels + use the project area format and print the square-metre symbol as Cyrillic м² in the Russian print UI culture. + A section mark prints only where its section answers to no view or to a plan at a scale no coarser than its own (wall-section callouts and fine - details stay in their parent views, undecodable views mark nothing), only when the file gives it an extent - record (the Architectural Section has none, so it marks nothing instead of inventing a trace); a decoded - front-cut polyline draws its jogs (the Building Section turns at its jog instead of running the full frame - height) while a mark without decoded points stays a straight ray; the trace, its ticks and its bubbles ink - with the Sections projection pen (pen 1 annotates 0.1 mm on the reference, where the old hardcoded 0.22 mm - inked every trace heavy); the trace is clipped to the viewport frame at generation; the view reference - marks of a plan stay undrawn. One measured exception: the Longitudinal Section's mark is drawn 3,090 mm along - +X from its decoded front cut, because the reference places it there while the Building Section's sits exactly on - its own cut (control: both at x = 592.1 pt) and no stored field explains the difference (`m_pntForViewData` is the - first front-cut point, `m_rotOffset.x` half the cut length, the view origin 3,280 mm — 190 mm away, nine times the - measurement error). + details stay in their parent views), and a decoded front-cut polyline places the jogs. On an axis-aligned plan + with annotation cropping disabled, the plan's `ExtentElem` supplies the continuous trace's endpoints as + distances from the section's saved trace origin. The endpoints move along the first and last legs, and the + trace can extend past the model crop. A trace without supported plan extents uses the stored front cut and + clips to the model frame. A trace with no decoded points uses the available straight ray, and views without + a section extent record leave no mark. The ink uses the Sections projection pen. Supported filled heads + and tails use the section type's symbols and the placed viewport's detail and sheet numbers. + Segmented section traces and view reference marks are outside the supported subset. ## Next steps -1. Decode the crop region of a rotated view and of a crop region switched off with live bounds, and the annotation crop that keeps titles and labels outside the model crop. Decode the record that places a viewport the file puts off the page. Assign section-mark ends per viewport (the Longitudinal trace matches the reference length but sits ~88 pt left of it with Y exact and walls aligned, so the shift is trace-specific with no file rule found yet; the reference puts a numbered callout bubble "3/A103" at its start while ours centers letter bubbles on the ends; Level 2 shows only a 171 pt stub near the stair where the file extent predicts 599 pt; the short callout bubbles with sheet references). -2. Evaluate the body rows of element schedules from the model (the How-do-I reference body is computed, not stored). -3. Decode the geometry of the property lines (with their bearing/distance labels) and the spot elevations, the solar-analysis diagram of a site sheet, and the file's own tag positions with leaders. -4. Decode per-view placement of viewports and datum annotation: our stair/detail frames follow the file offset while the reference resolves overlapping viewports side by side, and the reference lines its level marks up on the crop edge and ends each line at its own marker while ours run datum spans (clipped only past a label margin). Restore the long footing/grade model edges the file's footing instances never decode into geometry. The stair railing boards the reference omits in its stair views, and the interior edges behind a section cut (A103's 207 in of extras), are **not** a hide record: `m_oHiddenElementsViewSettings` (2160), `m_pHideElementsMgr` (2163) and `m_explicitlyHiddenElements` are null/empty on every view, no `HiddenElementsViewSettings` block exists in the model (the 2160 class tags in the view bodies are null-pointer annotations, each preceded by an `FF FF FF FF` token), and the railing ids (567887, 665711, 490129, 566588) appear in no view body. Both differences are Revit's coarse-detail model representation (all views here are detail level Coarse), which the file does not store as data — a printer rule would be a guess, so neither is implemented. +1. Decode the crop region of a rotated view and of a crop region switched off with live bounds, and the annotation crop that keeps titles and labels outside the model crop. Decode the record that places a viewport the file puts off the page. Decode the view-specific section extents, including the jogged Building Section and the short Level 2 stub. +2. Extend schedule evaluation to grouping, additional filters and computed fields. +3. Decode the property lines' bearing and distance labels, setbacks, spot elevations, and the file's own tag positions with leaders. +4. Extend datum support to left and dual level heads and additional head families. Resolve overlapping stair and detail viewports from their layout records. Recover the remaining footing and grade geometry and investigate residual interior edges and stair railing pieces. 5. Widen the same printing to the releases the reader supports in its own schema. ## Comparison with the reference export @@ -304,9 +725,9 @@ those pages needs a raster-aware comparison (or a vector-only export of the refe | Sheet | Printed | Still different | |---|---|---| -| A001 Title Sheet | the title texts, the five renderings from the file, the logo, the "How do I" table with its title, long-text band, header and body grid at its instance origin, and every revision table with its header and empty body grid to its fixed height | the evaluated body text of the "How do I" table (computed by Revit, not stored) | -| A101 Site Plan | the terrain wash with its outer edge, the contour lines (every fifth one heavier), the planting symbols with their crosshairs and the entourage outlines, the building filled dark from the rooms of its level under the wall outlines, the planting tags T1... with their leaders, the north arrow, the planting schedule with Type Mark / Common Name / Count in a ruled table at its instance origin, and the Solar Analysis viewport's title line and label (the study itself is a raster, so the viewport has no vector frame; its title is sheet annotation the reference prints); the site graphics are projected on the view's own axes (the Site view's crop basis is a −37° turn: `right = (0.7986, −0.6018)`) and placed through the crop frame at the view's scale, so the plan prints turned and sized as the reference, while the planting tags and the north arrow stay upright | the property and setback lines (no decoded geometry yet), the spot elevations, the solar-analysis diagram, the file's own tag positions | -| A102 Plans | both plans with the room colours of the reference, the room fills' floor surface patterns (`Sand` in the living room, from the carpet material of the sunken floor type's top compound layer, decoded to its line families and printed as drafting-pattern dashes), furniture as the plan silhouette (the boundary of the union of its faces on a 5 mm grid, so a chair keeps its back and the gap between its legs), stairs on both plans of a flight (the tread courses of its horizontal faces: base level going up, top level arriving), the observation deck's top rails from the view range (the rails stand on the roof below Level 2; the decoded PlanViewRange2 top and bottom clips decide which are visible), door and window tags, the room legend, the room tags, the grids dashed, and the section marks of the viewports they belong to (cut to the viewport frame at generation); one dimension chain above the building, 780 mm beyond the outer wall face as the reference draws it (measured 22.1 pt at 1:100), placed from the walls the viewport actually draws so off-crop retaining walls cannot push it off the page | the view reference marks (annotation elements whose positions the reader does not decode); the Building Section trace repeats in the Level 2 plan, whose own mark the file hides elsewhere; the short per-element dimensions of the other three sides; the Level 2 chain sits 24 pt below the reference's (22 pt above its face on Level 1 but 46 pt on Level 2 - a user-placed offset with no decoded rule) | -| A103 Elevations/Sections | South elevation and the Longitudinal Section cut at its true plane (feet-to-mm), level markers, the faded site; stacked wall layers hide on the silhouette, coincident modeling inks once, coplanar triangulation diagonals not inked, crop-filtered at generation; every visible edge inks, horizontals included — the wall top, the slab and roof outlines, the sills and the ground line all print, as the reference page shows (its drawing on this sheet travels as a raster image, so the vector layer alone lacks those horizontals and must not be used as the target); a section keeps both its cut profile (the roof slab at z=6898/7178) and the projected horizontals behind the plane, and carves the cross-section out of every solid the plane passes through (wall ends, slab edges, jambs); work below the lowest decoded level prints too (the foundation walls and their hatch down to z=-6302); level lines follow their datum envelopes near the crop with a label-margin cap for narrow viewports, and the grids dash coarsely ([36 9 9 9] pt from the grid type's line pattern), as the reference does | per-view level ends and markers (not decoded) and the long footing/grade model edges (footing instances lack decoded geometry). The 207 in of 0.283 extras are the interior seen behind the cut, attributed per category on the Longitudinal Section (model inches: walls 4,290, roofs 2,303, floors 2,043, building pad 1,904, casework 1,737) — Revit's coarse-detail representation, which the file does not store (see next step 4); the pairs 3.4 pt apart are the two faces of one wall, which coarse mode draws as a single line | -| A104 Elev/Sec/Det | West elevation and the Building Section cut at its plane, the four detail sections drawn from their own file crop frames in a bottom row above their titles, each with the annotation curves the view itself owns (`OST_Lines`, `OST_InsulationLines`, `OST_SketchLines` whose `OwnerViewId` is the view; clipped to the crop so a hidden line past its edge neither prints nor stretches the frame); cut-created edges ink heavy, projection edges thin | the fine placement of the four details (laid out from the decoded title labels with a 20 mm gap while the reference varies); the remaining in-detail 2D linework, which is not stored as view-owned curves (`OST_DetailComponents` holds 264 geometry-less attribute records, and the generic `OST_Lines`/`OST_SketchLines` curves name no owner) | -| A105 Elev/Stair Sections | Stair Section cut at its true plane with restored level lines, Main Stair Detail on the file's own crop frame with grid bubbles and the three in-crop level bands at the reference heights, East elevation, hidden lines removed; a railing's continuous rails print as the long diagonals they project across the stair, as the reference page shows, and its balusters stay; the crop filter runs in the true slice (origin-relative rectangle offset by the view origin); cut edges ink with their own category's pen; treads and risers included (they are `OST_StairsTrisers` and their mass hides the stair-body projection edges the reference hides) | the fine stair-profile linework the reference draws as coarse-detail graphics (this page's drawing is raster, so the vector comparison cannot judge it) and the level-line ends at the reference's own markers (bubble positions not decoded) | \ No newline at end of file +| A001 Title Sheet | the title text in its stored frame, the five renderings at their stored sizes, the title-block logo, the "How do I" table with its saved title and instruction-band styles, inline help marker, header and 40 evaluated rows at its instance origin, and every revision table with its header and empty body grid to its fixed height | remaining font and baseline differences in schedule text | +| A101 Site Plan | saved primary and secondary terrain contours and labels, property boundaries with fitted dashes and segment tags, roof surfaces with their saved standing seams and skylight openings, cast shadows on the visible terrain and the saved ground plane for supported lighting, planting at saved instance positions, planting tags with their family frames and leaders, the native north marker, the planting schedule at its instance origin and the Solar Analysis viewport title and the model projected with its saved camera and section box, or the complete rendered study when supplied with `--viewport-image`. The site is projected onto the stored rotated view basis and clipped at its saved crop. | detailed planting symbols, other roof surface patterns, setbacks and spot elevations | +| A102 Plans | both plans with solid background room colours from each view's RVT room-name scheme, the room fills' floor surface patterns (`Sand` in the living room, from the carpet material of the sunken floor type's top compound layer, decoded to its line families and printed as drafting-pattern dashes), furniture and fixtures within the saved view range, including the sunken living room, with white hidden-line surfaces from the projected face rings and a silhouette stroke on a 5 mm grid, saved stair treads, cut marks, owned top-rail projections and supported descending paths, plus horizontal tread outlines where the saved plan shape is unavailable, the observation deck's top rails from the view range (the rails stand on the roof below Level 2; the decoded PlanViewRange2 top and bottom clips decide which are visible), horizontal local door and window tags without leaders from their saved anchors and annotation families, the room legend, horizontal local room tags with saved positions, family labels and line frames, and supported single-label leaders, dashed grid centrelines with their stored bubble visibility and leaders, and the visible section marks and the saved circular elevation markers with their sheet references; four continuous dimension chains from the saved linear dimension curves and witness points, using the project length format; seven horizontal text notes with their saved frames and curved leaders | some Level 2 grid heads are vertically offset by about 1.7 pt; other styles of view references; furniture family symbolic curves and interior edges of overlapping projected geometry; other dimension styles and rotated or rich-text note layouts are outside the supported subset | +| A103 Elevations/Sections | South elevation and the Longitudinal Section cut at its stored plane, including the six saved level heads and their leaders on the section and the faded site; stacked wall layers hide on the silhouette, coincident modeling inks once, coplanar triangulation diagonals not inked, crop-filtered at generation; every visible edge inks, horizontals included — the wall top, the slab and roof outlines, the sills and the ground line all print, as the reference page shows (its drawing on this sheet travels as a raster image, so the vector layer alone lacks those horizontals and must not be used as the target); a section keeps both its cut profile (the roof slab at z=6898/7178) and the projected horizontals behind the plane, and carves the cross-section out of every solid the plane passes through (wall ends, slab edges, jambs); work below the lowest decoded level prints too (the foundation walls and their hatch down to z=-6302); level lines follow their datum envelopes near the crop with a label-margin cap for narrow viewports, and the grids dash coarsely ([36 9 9 9] pt from the grid type's line pattern), as the reference does | remaining footing and grade edges and detail-specific representations. Some projected interior edges and site shading still differ from the reference | +| A104 Elev/Sec/Det | West and Building Section, four construction details at their stored viewport positions, level and grid heads, nested callout boundaries and sheet references, roof batt insulation with authored breaks and masks, drafting hatch in matching cut material layers | other annotation families, some cut and projected material graphics, and the remaining in-detail 2D geometry | +| A105 Elev/Stair Sections | Stair Section including the surrounding building cut at its stored plane and crop with restored level lines, Main Stair Detail on the file's own crop frame with grid bubbles and the three in-crop level bands at the reference heights, Stair Section grid heads from their full saved envelope with annotation crop disabled, East elevation, hidden lines removed; a railing's continuous rails print as the long diagonals they project across the stair, as the reference page shows, and its balusters stay; the crop filter runs in the true slice (origin-relative rectangle offset by the view origin); cut edges ink with their own category's pen; treads and risers included (they are `OST_StairsTrisers` and their mass hides the stair-body projection edges the reference hides) | the fine stair-profile linework the reference draws as coarse-detail graphics (this page's drawing is raster, so the vector comparison cannot judge it) and the level-line ends at the reference's own markers (bubble positions not decoded) | diff --git a/src/RvtIO.Cli/PrintCommand.cs b/src/RvtIO.Cli/PrintCommand.cs index 04370655..2b5ed008 100644 --- a/src/RvtIO.Cli/PrintCommand.cs +++ b/src/RvtIO.Cli/PrintCommand.cs @@ -23,6 +23,7 @@ internal static int Run(string[] args, TextWriter output, TextWriter error) var viewTexts = new List(); var sheetTexts = new List(); var whereTexts = new List(); + var imageFiles = new Dictionary(); int scale = 100; PdfPageSize? paper = null; bool listLevels = false, listViews = false, listSheets = false, allViews = false, allSheets = false; @@ -64,6 +65,16 @@ internal static int Run(string[] args, TextWriter output, TextWriter error) if (i + 1 >= args.Length) return Usage(error, "--where needs a filter: NAME=VALUE, NAME!=VALUE or NAME~TEXT."); whereTexts.Add(args[++i]); break; + case "--viewport-image": + if (i + 6 >= args.Length + || !int.TryParse(args[i + 1], NumberStyles.None, CultureInfo.InvariantCulture, out int viewportId) + || viewportId <= 0 || !Coordinate(i + 2, out double x) || !Coordinate(i + 3, out double y) + || !Coordinate(i + 4, out double width) || width <= 0 + || !Coordinate(i + 5, out double height) || height <= 0 + || !imageFiles.TryAdd(viewportId, (x, y, width, height, args[i + 6]))) + return Usage(error, "--viewport-image requires a unique viewport ID, X Y WIDTH HEIGHT in mm, and a JPEG path."); + i += 6; + break; default: if (arg.StartsWith("--where=", StringComparison.Ordinal)) { @@ -77,6 +88,8 @@ internal static int Run(string[] args, TextWriter output, TextWriter error) break; } } + bool Coordinate(int index, out double value) => + double.TryParse(args[index], NumberStyles.Float, CultureInfo.InvariantCulture, out value) && double.IsFinite(value); if (file == null) return Usage(error, "print requires the file."); var whereFilters = new List(); foreach (string text in whereTexts) @@ -88,6 +101,8 @@ internal static int Run(string[] args, TextWriter output, TextWriter error) if (whereFilters.Count > 0 && sheetTexts.Count == 0 && !allSheets && !listSheets) return Usage(error, "--where selects sheets; it needs --sheet, --all-sheets or --list-sheets."); bool listing = listLevels || listViews || listSheets; + if (imageFiles.Count > 0 && (listing || (!allSheets && sheetTexts.Count == 0) || allViews)) + return Usage(error, "--viewport-image requires --sheet or --all-sheets."); if (!listing && outputPath == null) return Usage(error, "print requires the output PDF path."); // The comparison is the file's identity, not the spelling of the paths: an output path that is a hard link, // symbolic link or junction to the input PDF would truncate the model. ExportReport.SameFile guards the other @@ -196,6 +211,24 @@ IReadOnlyList ListedComposed() => try { PdfDocument pdf; + var composeOptions = new SheetComposeOptions { PaperSize = paper }; + if (imageFiles.Count > 0) + { + var images = new Dictionary(); + foreach (var (id, input) in imageFiles) + { + if (ExportReport.SameFile(outputPath!, input.Path)) + return Usage(error, "The PDF output path is a viewport image input."); + using var stream = File.OpenRead(input.Path); + if (stream.Length is < 4 or > 64 * 1024 * 1024) + return Usage(error, $"Viewport image {id} must be a JPEG no larger than 64 MiB."); + var bytes = new byte[(int)stream.Length]; + stream.ReadExactly(bytes); + images.Add(id, new SheetViewportImage(new PdfJpegImage(bytes), + input.X, input.Y, input.Width, input.Height)); + } + composeOptions.ViewportImages = images; + } if (allSheets) { IReadOnlyList toCompose = ListedComposed(); @@ -205,7 +238,7 @@ IReadOnlyList ListedComposed() => return RvtExitCodes.DecodeError; } pdf = SheetComposer.RenderSheets(document, toCompose.Select(sheet => sheet.SheetId).ToList(), - new SheetComposeOptions { PaperSize = paper }); + composeOptions); } else if (allViews) { @@ -239,8 +272,10 @@ IReadOnlyList ListedComposed() => } var sheetIds = selection.SheetIds; var composedIds = selection.ComposedIds; + if (composeOptions.ViewportImages != null && sheetIds.Count > 0) + return Usage(error, "Viewport images require sheets with decoded viewports."); pdf = sheetIds.Count == 0 - ? SheetComposer.RenderSheets(document, composedIds, new SheetComposeOptions { PaperSize = paper }) + ? SheetComposer.RenderSheets(document, composedIds, composeOptions) : SheetPrinter.RenderSheets(document, sheetIds, new SheetPrintOptions { PaperSize = paper }); } else if (viewTexts.Count > 0) @@ -315,6 +350,10 @@ IReadOnlyList ListedComposed() => error.WriteLine($"[print] {pdf.Pages.Count} page(s), first {page.WidthMillimetres:0} x {page.HeightMillimetres:0} mm -> {outputPath}"); return RvtExitCodes.Success; } + catch (ArgumentException exception) when (imageFiles.Count > 0) + { + return Usage(error, exception.Message); + } catch (InvalidOperationException exception) { error.WriteLine(exception.Message); @@ -412,7 +451,7 @@ private static int Usage(TextWriter error, string problem) error.WriteLine(problem); error.WriteLine("Usage: rvtio print [--level ] [--view ] [--sheet ] " + "[--where FILTER] [--all-views] [--all-sheets] [--scale ] [--paper A4|A3|A2|A1|A0] " - + "[--list-levels] [--list-views] [--list-sheets]"); + + "[--viewport-image ID X Y WIDTH HEIGHT JPEG] [--list-levels] [--list-views] [--list-sheets]"); return RvtExitCodes.Usage; } } diff --git a/src/RvtIO.Cli/Program.cs b/src/RvtIO.Cli/Program.cs index 1a83eaf2..b597e326 100644 --- a/src/RvtIO.Cli/Program.cs +++ b/src/RvtIO.Cli/Program.cs @@ -66,6 +66,7 @@ Report options (read the file and print or write a report instead of exporting): write the sheet catalog (sheets, viewports, parameters, limits not decoded) as JSON print [--level ] [--view ] [--sheet ] [--where FILTER] [--scale ] [--all-views] [--all-sheets] [--paper A4|A3|A2|A1|A0] + [--viewport-image ID X Y WIDTH HEIGHT JPEG] [--list-levels] [--list-views] [--list-sheets] render the plan of one level, one or more views (plans and elevations) or all of them, or one or more sheets, to PDF diff --git a/src/RvtIO/Internal/GRepData.cs b/src/RvtIO/Internal/GRepData.cs index 73d8fe47..51a77cbd 100644 --- a/src/RvtIO/Internal/GRepData.cs +++ b/src/RvtIO/Internal/GRepData.cs @@ -1,5 +1,14 @@ namespace RvtIO.Internal; +internal sealed record DoorPlanSymbol((double Lo, double Hi)? CutRange, + IReadOnlyList Curves); + +internal sealed record StyledModelLine(double[] Start, double[] End, int StyleId); +internal sealed record PlanFixtureGraphics(List Lines, List> Masks, + PlanFixtureProjection? MediumProjection = null, PlanFixtureProjection? CoarseProjection = null); + +internal sealed record PlanFixtureProjection(List Lines, List> Masks); + internal record GRepData { public int GStyleElemId { get; set; } @@ -65,6 +74,10 @@ internal record GRepData /// symbols contain many independent mapped children; retaining only one loses solids. public List Instances { get; set; } = new(); + /// Authored projection strokes with view filters, in the representation's own frame. + public List? ViewFacingLines { get; set; } + public IReadOnlyList? DoorPlanSymbols { get; set; } + /// For a FamilySymbol complex cutter, the authored dummy-host closure plane /// in family-local coordinates. Replacing the symmetric dummy-host slab delimited by /// this plane with the real host slab preserves every authored reveal/protrusion. @@ -108,10 +121,18 @@ internal record GRepInstance public long NodeOrder { get; set; } } +internal sealed record ModelFacePattern(int PatternId, double[] Origin, double[] U, double[] V); + +internal sealed record ViewFacingLine(double[] Start, double[] End, double[] Axis, int StyleId, + (int Comparison, int Level)? DetailCondition = null); + internal record GRepFace { + public bool ExcludedFromTopPlan { get; init; } + /// GFace.m_renderStyleId: the material element of the face; absent when not read. public int? RenderStyleId { get; init; } + public ModelFacePattern? ModelPattern { get; init; } public double[] Envelope { get; set; } = Array.Empty(); public bool Orient { get; set; } @@ -160,6 +181,7 @@ internal record GRepFace /// True for a tessellated patch of a non-planar surface (cylinder, cone, revolution, ruled, Hermite). public bool CurvedSurface { get; init; } + public bool PolygonMesh { get; init; } /// The face lies on a plane surface of the file (GSurface class Plane). When every face of a closed shell lies /// on a plane, all its edges are straight lines and the shell is a polyhedron whose volume is exact. diff --git a/src/RvtIO/Internal/ParsingState.cs b/src/RvtIO/Internal/ParsingState.cs index acb03837..582dd412 100644 --- a/src/RvtIO/Internal/ParsingState.cs +++ b/src/RvtIO/Internal/ParsingState.cs @@ -157,6 +157,7 @@ public Ifc.IfcNumericUnitPlan? OwnDocumentIfcNumericUnitPlan public Dictionary> ElemBipInts { get; set; } = new(); public Dictionary ElemBaseFields { get; set; } = new(); public Dictionary GrepBlocks { get; set; } = new(); + public Dictionary PlanFixtureGraphicsBySymbol { get; } = new(); internal Dictionary RailingQuantityInputs { get; } = new(); /// While set, the symbols placed from are taken at the Coarse detail level. @@ -281,7 +282,12 @@ public Ifc.IfcNumericUnitPlan? OwnDocumentIfcNumericUnitPlan /// Material element id -> the cut and surface fill pattern ids of its Material record (-1 when the /// material has no pattern of that kind), for the blocks that decoded exactly once. - public Dictionary MaterialPatterns { get; } = new(); + public Dictionary MaterialPatterns { get; } = new(); + + public (double BaseFeet, int MaterialId)? SiteCutGraphics { get; set; } + public int SiteCutGraphicsCount { get; set; } + public (int Method, int Units)? PropertyBearingFormat { get; set; } + public int PropertyBearingFormatCount { get; set; } /// GStyleElem (class 2050) -> GStyle.m_materialElemId and the style's category; MaterialId is null when the /// block did not decode. A repeated block clears it. @@ -428,6 +434,7 @@ public Ifc.IfcNumericUnitPlan? OwnDocumentIfcNumericUnitPlan /// GeoSite (class 2071) latitude and longitude in radians by element id; the last block wins. internal Dictionary GeoSites { get; } = new(); + internal Dictionary GeoSiteTimeZones { get; } = new(); /// GeoSite (class 2071) m_placeName by element id; the last block wins. internal Dictionary GeoSitePlaceNames { get; } = new(); @@ -452,6 +459,9 @@ public Ifc.IfcNumericUnitPlan? OwnDocumentIfcNumericUnitPlan /// Null when the block did not decode; a repeated block clears it. public Dictionary LevelDatums { get; } = new(); + public Dictionary DatumExtents { get; } = new(); + public Dictionary DatumHeads { get; } = new(); + /// GridAttributes block (class 2109) -> the center-segment category id whose projection /// graphics style inks the grid's center line. Null when the block did not decode; a repeated /// block clears it. diff --git a/src/RvtIO/Model/Element.cs b/src/RvtIO/Model/Element.cs index cbf14eba..57837193 100644 --- a/src/RvtIO/Model/Element.cs +++ b/src/RvtIO/Model/Element.cs @@ -307,6 +307,26 @@ public class Element [JsonIgnore] public ViewCropFrame? ViewCrop { get; set; } + internal ViewModelBounds? OrthographicModelBounds { get; set; } + internal ViewSolarStudy? SolarStudy { get; set; } + + internal bool? ViewAnnotationCropActive { get; set; } + + // Annotation crop offsets are in paper feet, relative to the model crop. + internal (double Left, double Right, double Top, double Bottom)? ViewAnnotationCrop { get; set; } + + internal (int ParentId, double[] Head)? SectionCallout { get; set; } + + internal (double Width, double Scale, bool Mirrored)? DetailInsulation { get; set; } + internal Parsing.TfBlockDeserializer.BreakLineProfile? DetailBreak { get; set; } + internal (double Width, double Height)? ImagePaperSize { get; set; } + internal int? ImageHolderId { get; set; } + internal (double X, double Y)? RoomLegendOrigin { get; set; } + internal (double Width, double Height)? ColorLegendSwatch { get; set; } + internal (double Width, double Height)? ImageInstanceScale { get; set; } + internal IReadOnlyList<(double X, double Y)>? SitePropertyCurve { get; set; } + internal (double X, double Y)? SitePropertyArcCenter { get; set; } + /// Exact BaseRailing.m_baseRailingSymbolId stored by this occurrence. [JsonIgnore] internal int? SerializedBaseRailingSymbolId { get; set; } @@ -326,6 +346,8 @@ public class Element /// only a unique, non-inplace family with no nested instances is admitted. [JsonIgnore] internal (int SymbolId, int HostId, double[] Transform, FamilyCutLoopData Loop)? OwnSingleFamilyCutout { get; set; } + internal (IReadOnlyList Symbols, double[] Transform)? OwnDoorPlanSymbols { get; set; } + internal RvtIO.Internal.PlanFixtureGraphics? PlacedPlanFixtureGraphics { get; set; } /// Own phase-4 cutout instance IDs in source order, not inferred inverse hosts. [JsonIgnore] @@ -498,6 +520,10 @@ internal bool RootClassIs(string className) => NativeRootClassName != null [JsonIgnore] internal double? SerializedMaterialTransparency { get; set; } + /// Whether the material uses the appearance asset in place of its stored shading colour. + [JsonIgnore] + internal bool? SerializedMaterialUsesRenderAppearance { get; set; } + /// The lowest and highest elevation (feet) at which a Grid is shown in plan views /// (the V envelope of its DatumPlane surface). [JsonIgnore] diff --git a/src/RvtIO/Model/Geometry.cs b/src/RvtIO/Model/Geometry.cs index 4bf5036f..3572247e 100644 --- a/src/RvtIO/Model/Geometry.cs +++ b/src/RvtIO/Model/Geometry.cs @@ -38,6 +38,8 @@ internal bool HasCurvedFace(IReadOnlyCollection? nodes = null) => MeshNodes /// List of edges with 3D coordinates. public List? Edges { get; set; } + internal List? ViewFacingLines { get; set; } + /// Unique vertices [x, y, z] in feet, deduplicated across all faces. public List? Vertices { get; set; } @@ -116,9 +118,13 @@ public class GeoInstance /// A planar face defined by origin + two direction vectors. public class GeoFace { + // A saved direction filter excludes this face along the vertical axis of its current frame. + internal bool ExcludedFromTopPlan { get; set; } + /// GFace.m_renderStyleId: the material element id of the face (internal; not serialized). [System.Text.Json.Serialization.JsonIgnore] internal int? RenderStyleId { get; set; } + internal RvtIO.Internal.ModelFacePattern? ModelPattern { get; set; } /// Plane origin [x, y, z] in feet. public double[] Origin { get; set; } = new double[3]; @@ -172,6 +178,9 @@ public class GeoFace /// True for a tessellated patch of a non-planar surface. internal bool CurvedSurface { get; set; } + /// Triangle supplied directly by a serialized polygon mesh. + internal bool PolygonMesh { get; set; } + /// The face lies on a plane surface of the file (GRepFace.PlaneSurface); kept through placing and copying of /// the geometry. internal bool PlaneSurface { get; set; } diff --git a/src/RvtIO/Model/RevitFileInfo.cs b/src/RvtIO/Model/RevitFileInfo.cs index c6599fe8..0358879c 100644 --- a/src/RvtIO/Model/RevitFileInfo.cs +++ b/src/RvtIO/Model/RevitFileInfo.cs @@ -71,12 +71,20 @@ public class RevitFileInfo /// FamilySymbol id -> the fixed texts of a title block family symbol in symbol feet, for the /// symbols whose block decoded exactly once. [System.Text.Json.Serialization.JsonIgnore] - internal IReadOnlyDictionary>? TitleBlockTexts { get; set; } + internal IReadOnlyDictionary>? TitleBlockTexts { get; set; } - /// FamilySymbol id -> the labels of a title block family symbol in symbol feet, for the symbols + /// FamilySymbol id -> annotation labels in symbol feet, for the symbols /// whose block decoded exactly once. [System.Text.Json.Serialization.JsonIgnore] - internal IReadOnlyDictionary>? TitleBlockLabels { get; set; } + internal IReadOnlyDictionary>? TitleBlockLabels { get; set; } + internal IReadOnlyDictionary? TitleBlockCapHeightsFeet { get; set; } + internal IReadOnlySet? OpaqueSymbolLabelStyles { get; set; } + internal IReadOnlySet? RegularArialSymbolLabelStyles { get; set; } + internal IReadOnlyList? PlanElevationMarks { get; set; } + internal IReadOnlyDictionary? SectionMarkerSymbols { get; set; } + + internal sealed record PlanElevationMark(int Id, double X, double Y, int BodyId, double ArrowHalfAngle, bool Filled, + int ArrowId, int ViewId, int ArrowSymbolId, double CoarserScale); /// ScheduleInstance element id -> the DBViewSchedule it shows and its top-left origin in sheet /// feet, for the instances whose block decoded exactly once. @@ -86,7 +94,10 @@ public class RevitFileInfo /// DBViewSchedule id -> its table definition (visible columns, category, show flags, grid and /// outline line styles, title-area rows and body sections), for the views whose block decoded exactly once. [System.Text.Json.Serialization.JsonIgnore] - internal IReadOnlyDictionary Columns, int CategoryId, bool ShowTitle, bool ShowHeaders, bool ShowGridLines, bool ShowOutline, int GridStyleId, int OutlineStyleId, double TitleHeightFt, List<(double HeightFt, string Text)> TitleBands, List BodySections, double FixedHeightFt)>? ScheduleTables { get; set; } + internal IReadOnlyDictionary? ScheduleTables { get; set; } + internal IReadOnlyDictionary>>? EvaluatedScheduleRows { get; set; } + + internal readonly record struct ScheduleCellValue(string Text, bool? Boolean = null); /// Sheet element id -> the revision ids explicitly present on it, for the sheets whose block /// decoded exactly once. @@ -98,10 +109,26 @@ public class RevitFileInfo [System.Text.Json.Serialization.JsonIgnore] internal IReadOnlyDictionary? FrontCut)>? SectionViews { get; set; } + /// Project site graphics from TrueNorth: the base elevation in feet and cut material element id. + [System.Text.Json.Serialization.JsonIgnore] + internal (double BaseFeet, int MaterialId)? SiteCutGraphics { get; set; } + internal (int Method, int Units)? PropertyBearingFormat { get; set; } + internal IReadOnlyDictionary>? SiteContours { get; set; } + internal sealed record SiteContourLabel(int ElementId, int SurfaceId, double[] Position, double[] Direction, + double TextHeightFeet); + internal IReadOnlyDictionary>? SiteContourLabels { get; set; } + + [System.Text.Json.Serialization.JsonIgnore] + internal IReadOnlyDictionary? DatumExtents { get; set; } + internal IReadOnlyDictionary? SectionTraceOrigins { get; set; } + + [System.Text.Json.Serialization.JsonIgnore] + internal IReadOnlyDictionary? DatumHeads { get; set; } + /// Material element id -> its cut and surface fill pattern element ids (-1 when the material /// has no pattern of that kind), for the materials whose block decoded exactly once. [System.Text.Json.Serialization.JsonIgnore] - internal IReadOnlyDictionary? MaterialPatterns { get; set; } + internal IReadOnlyDictionary? MaterialPatterns { get; set; } /// Fill pattern element id -> its name and line families (angle, origin, shift/offset, dash list /// in the pattern's own feet), for the patterns whose block decoded exactly once. @@ -119,6 +146,75 @@ public class RevitFileInfo /// exactly once. [System.Text.Json.Serialization.JsonIgnore] internal IReadOnlyDictionary? GridCenterCategories { get; set; } + internal IReadOnlyDictionary>? ViewRoomColors { get; set; } + internal IReadOnlyDictionary>? PlanDimensions { get; set; } + + internal sealed record PlanDimension(int StyleId, double[] Origin, double[] Direction, + IReadOnlyList References, IReadOnlyList Values); + internal IReadOnlyDictionary? PlanDimensionStyles { get; set; } + + internal sealed record PlanDimensionStyle(double TextHeightFeet, int LineCategory, int TickCategory, + double LineExtensionFeet, double WitnessExtensionFeet, double WitnessGapFeet, double TextGapFeet, + double TickSizeFeet); + + internal IReadOnlyDictionary>? CircularAnnotations { get; set; } + internal sealed record CircularAnnotation(double[] Transform, CircularAnnotationStyle Style); + internal sealed record CircularAnnotationStyle( + Parsing.TfBlockDeserializer.FamilyAnnotationArc Outline, int FillColor, int BorderColor, int BorderPen, + Parsing.TfBlockDeserializer.TitleBlockText Text, string Value, double FontPoints, int TextColor, bool Bold); + + internal IReadOnlyDictionary? ViewportTitles { get; set; } + internal IReadOnlyDictionary? ViewportTitleStyles { get; set; } + internal sealed record ViewportTitle(int SymbolId, bool ShowLabel, bool ShowExtensionLine, string? CustomScale); + internal sealed record ViewportTitleStyle( + IReadOnlyList<(Parsing.TfBlockDeserializer.TitleBlockLabel Label, double FontPoints, bool Wrap)> Labels, + IReadOnlyList Lines, + IReadOnlyList Arcs); + + internal IReadOnlyDictionary>? PlanOpeningTags { get; set; } + internal IReadOnlyDictionary? PlanOpeningTagStyles { get; set; } + internal sealed record PlanOpeningTag(int ElementId, int SymbolId, double X, double Y); + internal IReadOnlyDictionary>? SitePlantingTags { get; set; } + internal IReadOnlyDictionary>? SitePropertyTags { get; set; } + internal IReadOnlyDictionary>? + SitePropertyTagStyles { get; set; } + internal IReadOnlyDictionary>? PlanOutlineAnnotations { get; set; } + internal sealed record PlanOutlineAnnotation(double[] Transform, + IReadOnlyList Lines, + IReadOnlyList Arcs); + internal sealed record SitePlantingTag(int ElementId, int SymbolId, double X, double Y, + (double X, double Y) Elbow, (double X, double Y) End); + internal sealed record PlanOpeningTagStyle( + Parsing.TfBlockDeserializer.TitleBlockLabel Label, double FontPoints, + IReadOnlyList Lines, + IReadOnlyList Arcs); + + internal IReadOnlyDictionary>? PlanRoomTags { get; set; } + internal IReadOnlyDictionary? PlanRoomTagStyles { get; set; } + internal sealed record PlanRoomTag(int RoomId, int SymbolId, double X, double Y, + (double X, double Y)? LeaderAnchor, (double X, double Y)? LeaderEnd); + internal sealed record PlanRoomTagStyle( + IReadOnlyList<(Parsing.TfBlockDeserializer.TitleBlockLabel Label, double FontPoints)> Labels, + IReadOnlyList Lines); + + internal IReadOnlyDictionary>? PlanNotes { get; set; } + internal IReadOnlyDictionary>? PlanStairPaths { get; set; } + internal sealed record PlanStairPath(int Id, int HostId, double ArrowSize, double ArrowAngle, + string? DownText, double CapHeight, double TextX, double TextY); + internal IReadOnlyDictionary>? ViewHiddenElements { get; set; } + internal IReadOnlyDictionary>? ViewHiddenCategories { get; set; } + internal IReadOnlySet? OpaquePlanViews { get; set; } + internal IReadOnlyDictionary? ViewSkyGradients { get; set; } + internal IReadOnlyDictionary? ViewGroundShadows { get; set; } + internal IReadOnlyDictionary? ViewStillSunDates { get; set; } + internal IReadOnlyDictionary? ViewAmbientLight { get; set; } + internal IReadOnlyDictionary? ViewAmbientFractions { get; set; } + internal IReadOnlySet? UnshadedHiddenLineViews { get; set; } + internal IReadOnlySet? OpaqueViewsWithSurfacePatterns { get; set; } + internal sealed record PlanNote(string Text, double FontPoints, double X, double Y, + double WidthFeet, double HeightFeet, bool Wrap, bool HasBorder, bool Opaque, double PaddingFeet, + int CategoryId, bool ArcLeaders, IReadOnlyList Leaders, + double ArrowSizeFeet, double ArrowAngle, int ElementId); /// CategoryElem id -> its name, for the category elements whose block decoded exactly once. [System.Text.Json.Serialization.JsonIgnore] internal IReadOnlyDictionary? CategoryNames { get; set; } @@ -192,6 +288,8 @@ public class RevitFileInfo /// See . public double? SiteLongitudeRadians { get; set; } + internal double? SiteTimeZoneHours { get; set; } + /// Elevation (feet) of the project base point in shared coordinates; 0 when unknown. public double SiteElevationFeet { get; set; } diff --git a/src/RvtIO/Model/ViewCropFrame.cs b/src/RvtIO/Model/ViewCropFrame.cs index ef3e8051..d21b6fc9 100644 --- a/src/RvtIO/Model/ViewCropFrame.cs +++ b/src/RvtIO/Model/ViewCropFrame.cs @@ -27,3 +27,9 @@ public sealed record ViewCropFrame( double X1, double Y1, bool Active); + +internal sealed record ViewModelBounds(double[] Origin, double[][] Axes, double[] Offsets, bool[] Active); + +internal sealed record ViewSolarStudy(double[] Outline, int SizePercent, int GroundLevelId, int AnnotationId, + uint Start, uint End, int Interval, double ActiveFrame, int ShadowIntensity = 0, + bool ShowSurfacePatterns = false, bool ShowEdges = false); diff --git a/src/RvtIO/Parsing/BlockParser.cs b/src/RvtIO/Parsing/BlockParser.cs index c96b67f7..c1d5459d 100644 --- a/src/RvtIO/Parsing/BlockParser.cs +++ b/src/RvtIO/Parsing/BlockParser.cs @@ -19,8 +19,13 @@ internal static void ApplyPendingGReps(ParsingState state, List pen { if (pending.Count == 0) return; var decoded = new Internal.GRepData?[pending.Count]; + var planFixtures = new PlanFixtureGraphics?[pending.Count]; Parallel.For(0, decoded.Length, new ParallelOptions(), index => - decoded[index] = GRepParserV2.Parse(pending[index].Chunk, pending[index].Start, pending[index].Size)); + { + var job = pending[index]; + decoded[index] = GRepParserV2.Parse(job.Chunk, job.Start, job.Size, + collectPlanFixtures: job.IsFamilyCut ? null : graphics => planFixtures[index] = graphics); + }); for (int index = 0; index < decoded.Length; index++) { var job = pending[index]; @@ -30,7 +35,12 @@ internal static void ApplyPendingGReps(ParsingState state, List pen && decoded[index] is { } familyCut && IsAuthoredFamilyComplexCutter(familyCut)) state.FamilyCutGreps[job.Eid] = familyCut; } - else ApplyGRepBlock(state, job.Eid, decoded[index]); + else + { + if (planFixtures[index] is { } graphics) + state.PlanFixtureGraphicsBySymbol.TryAdd(job.Eid, graphics); + ApplyGRepBlock(state, job.Eid, decoded[index]); + } decoded[index] = null; } } diff --git a/src/RvtIO/Parsing/ElementBuilder.OwnFamilyCutout.cs b/src/RvtIO/Parsing/ElementBuilder.OwnFamilyCutout.cs index 90263d35..00d34aa6 100644 --- a/src/RvtIO/Parsing/ElementBuilder.OwnFamilyCutout.cs +++ b/src/RvtIO/Parsing/ElementBuilder.OwnFamilyCutout.cs @@ -11,6 +11,7 @@ internal static void ApplyOwnFamilyCutoutInputs(IReadOnlyList elements, foreach (var element in elements) { element.OwnSingleFamilyCutout = null; + element.OwnDoorPlanSymbols = null; element.OwnWallCutoutInstanceIds = null; element.OwnWallCutoutSteps = null; element.OwnWallAxisLine = null; @@ -43,8 +44,13 @@ internal static void ApplyOwnFamilyCutoutInputs(IReadOnlyList elements, HostId: > 0, InsertOrientation: 0 } source } || source.HostId != element.SerializedHostId || source.SymbolId != symbolId || !IsUniqueRoot(symbolId, 1829) - || !counts.TryGetValue(symbolId, out int symbolCount) || symbolCount != 1 - || !state.OwnFamilyCutSymbols.TryGetValue((uint)symbolId, out var computed) + || !counts.TryGetValue(symbolId, out int symbolCount) || symbolCount != 1) continue; + + if (element.CategoryId == (int)RvtIO.BuiltIns.BuiltInCategory.OST_Doors + && state.GrepBlocks.GetValueOrDefault((uint)symbolId)?.DoorPlanSymbols is { Count: > 0 } planSymbols) + element.OwnDoorPlanSymbols = (planSymbols, source.Transform); + + if (!state.OwnFamilyCutSymbols.TryGetValue((uint)symbolId, out var computed) || computed is not { BlockCount: 1, Symbol: { Active: true }, Loops.Count: 1 } || !state.FamilyInstanceSymbolIds.TryGetValue((uint)element.Id, out var type) || type is not { BlockCount: 1, TypeId: > 0 } || !IsUniqueRoot(type.TypeId.Value, 1829) diff --git a/src/RvtIO/Parsing/ElementBuilder.PlanDimensions.cs b/src/RvtIO/Parsing/ElementBuilder.PlanDimensions.cs new file mode 100644 index 00000000..f4b15da7 --- /dev/null +++ b/src/RvtIO/Parsing/ElementBuilder.PlanDimensions.cs @@ -0,0 +1,83 @@ +using RvtIO.BuiltIns; +using RvtIO.Internal; +using RvtIO.Model; + +namespace RvtIO.Parsing; + +internal static partial class ElementBuilder +{ + private static void ReadPlanDimensions(RevitFileInfo info, ParsingState state) + { + var byView = new Dictionary>(); + var styles = new Dictionary(); + foreach (var (id, saved) in state.NativeParams) + { + if (saved is not { DimensionLine: { } line, DimensionReferences: { Count: >= 2 } references, + DimensionValues: { } values } + || saved.Fields.GetValueOrDefault("m_id") != (int)id + || saved.Fields.GetValueOrDefault("m_ownerDBViewId") is not > 0 + || saved.Fields.GetValueOrDefault("m_styleSymbolId") is not > 0 + || saved.Fields.GetValueOrDefault("160:m_flags") != 12 + || saved.Fields.GetValueOrDefault("160:m_useEqualityFormula") != 0 + || saved.Fields.GetValueOrDefault("160:m_showLabelGP") != 0 + || saved.Fields.GetValueOrDefault("159:m_multiReferenceAnnotationId") > 0 + || saved.CellClasses is { Count: > 0 } + || values.Count != references.Count - 1 || values.Any(value => !(value > 0 && double.IsFinite(value))) + || !line.Origin.All(value => Math.Abs(value) < 1_000_000) || !line.Direction.All(double.IsFinite) + || references.Any(point => point.Any(value => !(Math.Abs(value) < 1_000_000)))) continue; + int view = saved.Fields["m_ownerDBViewId"], style = saved.Fields["m_styleSymbolId"]; + if (!styles.ContainsKey(style)) + { + var decoded = ReadStyle(style); + if (decoded == null) continue; + styles.Add(style, decoded); + } + + if (!byView.TryGetValue(view, out var dimensions)) byView.Add(view, dimensions = new()); + dimensions.Add(new(style, line.Origin, line.Direction, references, values)); + } + info.PlanDimensions = byView; + info.PlanDimensionStyles = styles; + + RevitFileInfo.PlanDimensionStyle? ReadStyle(int id) + { + if (!state.NativeParams.TryGetValue((uint)id, out var style)) return null; + var fields = style.Fields; + int fontId = fields.GetValueOrDefault("625:m_fontId"); + int tickId = fields.GetValueOrDefault("174:m_arrowHeadStyleId"); + int category = fields.GetValueOrDefault("625:m_categoryId"); + int tickCategory = fields.GetValueOrDefault("174:m_tickCategoryId"); + // shortcut: continuous dimensions with one diagonal tick and the project length format. + if (fields.GetValueOrDefault("174:m_dimensionStyleType", -1) != 0 + || fields.GetValueOrDefault("174:m_linearDimType") != 1 + || fields.GetValueOrDefault("174:m_textAlignment") != 1 + || fields.GetValueOrDefault("174:m_textLoc", -1) != 0 + || fields.GetValueOrDefault("174:m_alternateUnits", -1) != 0 + || fields.GetValueOrDefault("174:m_dimWitnCntrlExtBelow", -1) != 0 + || fields.GetValueOrDefault("174:linearFormatUsesDefault") != 1 + || !string.IsNullOrEmpty(style.StringFields.GetValueOrDefault("174:m_prefix")) + || !string.IsNullOrEmpty(style.StringFields.GetValueOrDefault("174:m_suffix")) + || category <= 0 || tickCategory <= 0 || fontId <= 0 || tickId <= 0 + || fields.GetValueOrDefault("174:m_interiorTickMarkStyleId") != tickId + || !state.NativeParams.TryGetValue((uint)fontId, out var font) + || !state.NativeParams.TryGetValue((uint)tickId, out var tick) + || tick.Fields.GetValueOrDefault("2295:m_tickType", -1) != 0) return null; + double height = font.DoubleFields.GetValueOrDefault("1923:m_size"); + double size = PlanAnnotationDouble(tick, BuiltInParameter.ARROW_SIZE); + double extension = PlanAnnotationDouble(style, BuiltInParameter.DIM_LINE_EXTENSION); + double witness = PlanAnnotationDouble(style, BuiltInParameter.WITNS_LINE_EXTENSION); + double gap = PlanAnnotationDouble(style, BuiltInParameter.WITNS_LINE_GAP_TO_ELT); + double textGap = PlanAnnotationDouble(style, BuiltInParameter.TEXT_DIST_TO_LINE); + return height is > 0 and < 1 && size is > 0 and < 1 && extension is >= 0 and < 1 + && witness is >= 0 and < 1 && gap is >= 0 and < 1 && textGap is >= 0 and < 1 + ? new(height, category, tickCategory, extension, witness, gap, textGap, size) : null; + } + } + + private static double PlanAnnotationDouble(TfBlockDeserializer.NativeParams item, BuiltInParameter parameter) + { + foreach (var (id, value) in item.Doubles) + if (id == (int)parameter) return value; + return double.NaN; + } +} diff --git a/src/RvtIO/Parsing/ElementBuilder.PlanElevationMarks.cs b/src/RvtIO/Parsing/ElementBuilder.PlanElevationMarks.cs new file mode 100644 index 00000000..18f566ba --- /dev/null +++ b/src/RvtIO/Parsing/ElementBuilder.PlanElevationMarks.cs @@ -0,0 +1,51 @@ +using RvtIO.Internal; +using RvtIO.Model; + +namespace RvtIO.Parsing; + +internal static partial class ElementBuilder +{ + private static List ReadPlanElevationMarks(ParsingState state) + { + var result = new List(); + foreach (var (markerId, marker) in state.NativeParams) + { + if (state.ElemClassIdx.GetValueOrDefault(markerId) != 2247 + || !marker.DoubleFields.TryGetValue("2247:m_pos@0", out double x) || !double.IsFinite(x) + || !marker.DoubleFields.TryGetValue("2247:m_pos@1", out double y) || !double.IsFinite(y) + || !state.NativeParams.TryGetValue((uint)marker.Fields.GetValueOrDefault("2247:m_symbolId"), out var type) + || !state.NativeParams.TryGetValue((uint)type.Fields.GetValueOrDefault("1020:m_elevatnAttrId"), out var style) + || style.Fields.GetValueOrDefault("2251:m_shape") != 1 + || style.DoubleFields.GetValueOrDefault("2251:m_ahAngleDouble") is not (> 0 and < Math.PI / 2 and var angle) + || style.Fields.GetValueOrDefault("2251:m_elevationSymbolId") is not (> 0 and var bodyId) + || !state.NativeParams.TryGetValue((uint)bodyId, out var body)) + continue; + + // shortcut: one target view per marker, until the shared body label for multiple targets is decoded. + int arrowIndex = -1; + for (int index = 0; index < 4; index++) + { + if (marker.Fields.GetValueOrDefault($"2247:m_arrowIds@{index}") <= 0) continue; + if (arrowIndex >= 0) + { + arrowIndex = -1; + break; + } + arrowIndex = index; + } + if (arrowIndex < 0 + || marker.Fields.GetValueOrDefault($"2247:m_arrowIds@{arrowIndex}") is not (> 0 and var arrowId) + || !state.NativeParams.TryGetValue((uint)arrowId, out var arrow) + || arrow.Fields.GetValueOrDefault("2248:m_parentId") != (int)markerId + || arrow.Fields.GetValueOrDefault("621:m_dbViewId") is not (> 0 and var viewId) + || !arrow.DoubleFields.TryGetValue("2249:m_coarserScale", out double coarserScale) + || coarserScale is not (>= 0 and <= 1) + || !style.Fields.TryGetValue($"2251:m_orderedSubIndices@{arrowIndex}", out int child) + || body.Fields.GetValueOrDefault($"1829:m_subInstData@{child}") is not (> 0 and var symbolId)) + continue; + result.Add(new((int)markerId, x, y, bodyId, angle, style.Fields.GetValueOrDefault("2251:m_ahFilled") == 1, + arrowId, viewId, symbolId, coarserScale)); + } + return result; + } +} diff --git a/src/RvtIO/Parsing/ElementBuilder.PlanNotes.cs b/src/RvtIO/Parsing/ElementBuilder.PlanNotes.cs new file mode 100644 index 00000000..ddd08e0a --- /dev/null +++ b/src/RvtIO/Parsing/ElementBuilder.PlanNotes.cs @@ -0,0 +1,56 @@ +using RvtIO.BuiltIns; +using RvtIO.Internal; +using RvtIO.Model; + +namespace RvtIO.Parsing; + +internal static partial class ElementBuilder +{ + private static Dictionary> ReadPlanNotes(ParsingState state) + { + var byView = new Dictionary>(); + foreach (var (id, note) in state.NativeParams) + { + var fields = note.Fields; + var numbers = note.DoubleFields; + // shortcut: the supported left-aligned horizontal note layout. + if (note.PlanNoteText is not { Text.Length: > 0, FontSizePoints: > 0 and <= 200 } text + || fields.GetValueOrDefault("m_id") != (int)id + || fields.GetValueOrDefault("m_ownerDBViewId") is not > 0 + || fields.GetValueOrDefault("3928:m_flags") != 8768 + || numbers.GetValueOrDefault("3928:m_baseVec@0") != 1 || numbers.GetValueOrDefault("3928:m_baseVec@1") != 0 + || numbers.GetValueOrDefault("3928:m_upVec@0") != 0 || numbers.GetValueOrDefault("3928:m_upVec@1") != 1 + || fields.GetValueOrDefault("3928:m_attrId") is not > 0 + || !state.NativeParams.TryGetValue((uint)fields["3928:m_attrId"], out var style)) continue; + double x = numbers.GetValueOrDefault("3928:m_orig@0", double.NaN); + double y = numbers.GetValueOrDefault("3928:m_orig@1", double.NaN); + double width = numbers.GetValueOrDefault("3928:m_lineWidth"); + double height = numbers.GetValueOrDefault("3928:m_height"); + double padding = style.DoubleFields.GetValueOrDefault("3931:m_leaderOffsetSheet", double.NaN); + int view = fields["m_ownerDBViewId"], category = style.Fields.GetValueOrDefault("625:m_categoryId"); + if (!(Math.Abs(x) < 1_000_000 && Math.Abs(y) < 1_000_000) || !(width is > 0 and < 20) + || !(height is > 0 and < 20) || !(padding is >= 0 and < 1) || category <= 0) continue; + double arrowSize = 0, arrowAngle = 0; + var arrowId = style.ElementIds.Find(entry => entry.ParamId == (int)BuiltInParameter.LEADER_ARROWHEAD).Value; + if (arrowId > 0 && state.NativeParams.TryGetValue((uint)arrowId, out var arrow) + && arrow.Fields.GetValueOrDefault("2295:m_tickType") == 8) + { + double size = PlanAnnotationDouble(arrow, BuiltInParameter.ARROW_SIZE); + double angle = PlanAnnotationDouble(arrow, BuiltInParameter.LEADER_ARROW_WIDTH); + if (size is > 0 and < 1 && angle is > 0 and < Math.PI) + { + arrowSize = size; + arrowAngle = angle; + } + } + if (!byView.TryGetValue(view, out var notes)) byView.Add(view, notes = new()); + notes.Add(new(text.Text, text.FontSizePoints!.Value, x, y, width, height, + fields.GetValueOrDefault("3928:m_bNoWrapping") == 0, + style.Fields.GetValueOrDefault("3931:m_textBoxVisibility") == 1, + style.Fields.GetValueOrDefault("625:m_background", -1) == 0, padding, category, + fields.GetValueOrDefault("3971:m_bArcLeaders") == 1, note.PlanNoteLeaders ?? [], + arrowSize, arrowAngle, (int)id)); + } + return byView; + } +} diff --git a/src/RvtIO/Parsing/ElementBuilder.PlanStairPaths.cs b/src/RvtIO/Parsing/ElementBuilder.PlanStairPaths.cs new file mode 100644 index 00000000..a4bab94d --- /dev/null +++ b/src/RvtIO/Parsing/ElementBuilder.PlanStairPaths.cs @@ -0,0 +1,66 @@ +using RvtIO.BuiltIns; +using RvtIO.Internal; +using RvtIO.Model; + +namespace RvtIO.Parsing; + +internal static partial class ElementBuilder +{ + private static Dictionary> ReadPlanStairPaths(ParsingState state) + { + var byView = new Dictionary>(); + foreach (var (id, path) in state.NativeParams) + { + var fields = path.Fields; + // shortcut: automatic direction with an open arrow at the riser and no start extension. + if (fields.GetValueOrDefault("3702:m_stairsLinkElementId") is not (> 0 and var host) + || id > int.MaxValue || fields.GetValueOrDefault("m_id") != (int)id + || fields.GetValueOrDefault("m_ownerDBViewId") is not (> 0 and var view) + || path.DoubleFields.GetValueOrDefault("3702:m_stairsPathOffset", double.NaN) != 0 + || fields.GetValueOrDefault("3702:m_typeId") is not (> 0 and var typeId) + || !state.NativeParams.TryGetValue((uint)typeId, out var type) + || type.Fields.GetValueOrDefault("3703:m_stairsPathDirection") != 1 + || type.Fields.GetValueOrDefault("3703:m_startFromRiser") != 1 + || type.Fields.GetValueOrDefault("3703:m_endAtRiser") != 1 + || type.Fields.GetValueOrDefault("3703:m_startSymbolTypeId") != -1 + || type.Fields.GetValueOrDefault("3703:m_fullStepArrow", -1) != 0 + || type.DoubleFields.GetValueOrDefault("3703:m_startExtension", double.NaN) != 0 + || type.Fields.GetValueOrDefault("3703:m_arrowheadTypeId") is not (> 0 and var arrowId) + || !state.NativeParams.TryGetValue((uint)arrowId, out var arrow) + || arrow.Fields.GetValueOrDefault("2295:m_tickType") != 8 + || arrow.Fields.GetValueOrDefault("2295:m_arrowClosed", -1) != 0 + || arrow.Fields.GetValueOrDefault("2295:m_arrowFilled", -1) != 0) + continue; + + double size = PlanAnnotationDouble(arrow, BuiltInParameter.ARROW_SIZE); + double angle = PlanAnnotationDouble(arrow, BuiltInParameter.LEADER_ARROW_WIDTH); + if (!(size is > 0 and < 1 && angle is > 0 and < Math.PI)) continue; + string? text = null; + double cap = 0, textX = 0, textY = 0; + if (fields.GetValueOrDefault("3702:m_showDownText") == 1 + && fields.GetValueOrDefault("3702:m_textOrientation", -1) == 0 + && path.StringFields.GetValueOrDefault("3702:m_downText") is { Length: > 0 } label + && type.Fields.GetValueOrDefault("3703:m_textTypeId") is > 0 and var textId + && state.NativeParams.TryGetValue((uint)textId, out var textType) + && textType.Fields.GetValueOrDefault("625:m_fontId") is > 0 and var fontId + && textType.Fields.GetValueOrDefault("625:m_bBold", -1) == 0 + && textType.Fields.GetValueOrDefault("625:m_bItalic", -1) == 0 + && textType.Fields.GetValueOrDefault("625:m_bUnderline") == 0 + && state.NativeParams.TryGetValue((uint)fontId, out var font) + && string.Equals(font.StringFields.GetValueOrDefault("1923:m_name"), "Arial", StringComparison.OrdinalIgnoreCase) + && font.DoubleFields.GetValueOrDefault("1923:m_size") is > 0 and < 1 and var height) + { + textX = path.DoubleFields.GetValueOrDefault("3702:m_downTextOffset@0", double.NaN); + textY = path.DoubleFields.GetValueOrDefault("3702:m_downTextOffset@1", double.NaN); + if (double.IsFinite(textX) && double.IsFinite(textY)) + { + text = label; + cap = height; + } + } + if (!byView.TryGetValue(view, out var paths)) byView.Add(view, paths = []); + paths.Add(new((int)id, host, size, angle, text, cap, textX, textY)); + } + return byView; + } +} diff --git a/src/RvtIO/Parsing/ElementBuilder.RoomColors.cs b/src/RvtIO/Parsing/ElementBuilder.RoomColors.cs new file mode 100644 index 00000000..3e53bcc2 --- /dev/null +++ b/src/RvtIO/Parsing/ElementBuilder.RoomColors.cs @@ -0,0 +1,31 @@ +using RvtIO.BuiltIns; +using RvtIO.Internal; +using RvtIO.Model; + +namespace RvtIO.Parsing; + +internal static partial class ElementBuilder +{ + private static Dictionary> BuildViewRoomColors(RevitFileInfo info, + ParsingState state) + { + var result = new Dictionary>(); + if (info.FillPatterns == null) return result; + foreach (var (viewId, view) in state.NativeParams) + { + if (view.Fields.GetValueOrDefault("693:m_bBackground") != 1 + || !view.Fields.TryGetValue("693:m_roomColorScheme", out int schemeId) || schemeId <= 0 + || !state.NativeParams.TryGetValue((uint)schemeId, out var scheme) + || scheme.RoomColors is not { Count: > 0 } entries + || scheme.Fields.GetValueOrDefault("690:m_categoryId") != (int)BuiltInCategory.OST_Rooms + || scheme.Fields.GetValueOrDefault("690:m_paramId") != (int)BuiltInParameter.ROOM_NAME + || scheme.Fields.GetValueOrDefault("690:m_bByRange", -1) != 0) continue; + var colors = new Dictionary(StringComparer.Ordinal); + foreach (var entry in entries) + if (info.FillPatterns.TryGetValue(entry.PatternId, out var pattern) && pattern.Grids.Count == 0) + colors.TryAdd(entry.Name, entry.Color); + if (colors.Count > 0) result.Add((int)viewId, colors); + } + return result; + } +} diff --git a/src/RvtIO/Parsing/ElementBuilder.ScheduleRows.cs b/src/RvtIO/Parsing/ElementBuilder.ScheduleRows.cs new file mode 100644 index 00000000..53cd5abe --- /dev/null +++ b/src/RvtIO/Parsing/ElementBuilder.ScheduleRows.cs @@ -0,0 +1,122 @@ +using System.Globalization; +using RvtIO.BuiltIns; +using RvtIO.Internal; +using RvtIO.Model; + +namespace RvtIO.Parsing; + +internal static partial class ElementBuilder +{ + private static TfBlockDeserializer.ScheduleTableDef ResolveRevisionTextTypes(ParsingState state, + TfBlockDeserializer.ScheduleTableDef table) + { + if (table.CategoryId != (int)BuiltInCategory.OST_Revisions + || CapHeight(table.TextTypeIds.Header) is not double header + || CapHeight(table.TextTypeIds.Body) is not double body) return table; + return table with { RevisionCapHeightsFt = (header, body) }; + + double? CapHeight(int id) + { + if (id <= 0 || !state.NativeParams.TryGetValue((uint)id, out var type) + || type.Fields.GetValueOrDefault("625:m_bBold") != 0 + || type.Fields.GetValueOrDefault("625:m_bItalic") != 0 + || type.Fields.GetValueOrDefault("625:m_fontId") is not (> 0 and var fontId) + || !state.NativeParams.TryGetValue((uint)fontId, out var font) + || !string.Equals(font.StringFields.GetValueOrDefault("1923:m_name"), "Arial", StringComparison.OrdinalIgnoreCase)) + return null; + double height = font.DoubleFields.GetValueOrDefault("1923:m_size"); + return height is > 0 and < 1 ? height : null; + } + } + + private static Dictionary>> EvaluateScheduleRows(RevitFileInfo info, ParsingState state) + { + var result = new Dictionary>>(); + foreach (var (id, entry) in state.ScheduleTables) + { + if (entry is not { BlockCount: 1, Table: { } table } + || BuildScheduleRows(table, info.Elements, state) is not { } rows) continue; + result.Add((int)id, rows); + } + return result; + } + + private static List>? BuildScheduleRows(TfBlockDeserializer.ScheduleTableDef table, + IEnumerable elements, ParsingState state) + { + // shortcut: itemized instance rows with flat sorting and integer filters, until other schedule expression types are evaluated. + if (table.RowBindings is not { Itemized: true, Unsupported: false } binding + || table.BodySections is not [{ } section] || binding.FieldIds.Count != binding.FieldObjects.Count) + return null; + var fields = new Dictionary(); + for (int i = 0; i < binding.FieldIds.Count; i++) + { + if (!binding.Fields.TryGetValue(binding.FieldObjects[i], out var field) || field.Source != 0 + || field.Parameter <= 0 || !state.NativeParams.TryGetValue((uint)field.Parameter, out var definition) + || !definition.Fields.TryGetValue("2870:m_pParamDef.class", out int kind) + || kind is not (606 or 2756 or 2866) + || !fields.TryAdd(binding.FieldIds[i], (field.Parameter, field.Hidden, kind))) return null; + } + + var columns = binding.FieldIds.Select(id => fields[id]).Where(f => !f.Hidden).ToArray(); + if (columns.Length != table.Columns.Count) return null; + var filters = new List<(int Parameter, int Type, int Value)>(); + foreach (int index in binding.FilterObjects) + { + if (!binding.Filters.TryGetValue(index, out var filter) || filter is not { Type: 2 or 3, Storage: 1 } + || !fields.TryGetValue(filter.Field, out var field) || field.Kind is not (2756 or 2866)) return null; + filters.Add((field.Parameter, filter.Type, filter.Value)); + } + + var sorts = new List<(int Parameter, int Kind, int Order)>(); + foreach (int index in binding.SortObjects) + { + if (!binding.Sorts.TryGetValue(index, out var sort) || sort is not { GroupFlags: 0, Order: 0 or 1 } + || !fields.TryGetValue(sort.Field, out var field)) return null; + sorts.Add((field.Parameter, field.Kind, sort.Order)); + } + + var items = new List<(int Id, Dictionary Values)>(); + foreach (var element in elements) + { + if (element.CategoryId != table.CategoryId || element.RootClassName != "FamilyInstance" + || !state.NativeParams.TryGetValue((uint)element.Id, out var native) || !native.TailWalkComplete) continue; + var values = new Dictionary(); + foreach (var parameter in native.NamedParams) + values.TryAdd(parameter.ParamId, parameter); + if (!filters.All(f => values.TryGetValue(f.Parameter, out var value) + && (f.Type == 2 ? value.Int == f.Value : value.Int != f.Value))) continue; + if (columns.Any(c => !values.ContainsKey(c.Parameter)) || sorts.Any(s => !values.ContainsKey(s.Parameter))) continue; + items.Add((element.Id, values)); + } + + int spacer = binding.InitialSpacer ? 1 : 0; + if (items.Count == 0 || items.Count + spacer != section.BodyRows) return null; + items.Sort((left, right) => + { + foreach (var sort in sorts) + { + var a = left.Values[sort.Parameter]; + var b = right.Values[sort.Parameter]; + int order = sort.Kind == 606 ? string.CompareOrdinal(a.Str, b.Str) : a.Int.CompareTo(b.Int); + if (order != 0) return sort.Order == 0 ? order : -order; + } + return left.Id.CompareTo(right.Id); + }); + + var rows = new List>(); + if (spacer > 0) rows.Add(Enumerable.Repeat(new RevitFileInfo.ScheduleCellValue(""), columns.Length).ToList()); + foreach (var item in items) + rows.Add(columns.Select(column => + { + var value = item.Values[column.Parameter]; + return column.Kind switch + { + 606 => new RevitFileInfo.ScheduleCellValue(value.Str ?? ""), + 2866 => new RevitFileInfo.ScheduleCellValue("", value.Int != 0), + _ => new RevitFileInfo.ScheduleCellValue(value.Int.ToString(CultureInfo.InvariantCulture)), + }; + }).ToList()); + return rows; + } +} diff --git a/src/RvtIO/Parsing/ElementBuilder.SiteContourLabels.cs b/src/RvtIO/Parsing/ElementBuilder.SiteContourLabels.cs new file mode 100644 index 00000000..77cd51cc --- /dev/null +++ b/src/RvtIO/Parsing/ElementBuilder.SiteContourLabels.cs @@ -0,0 +1,36 @@ +using RvtIO.Internal; +using RvtIO.Model; + +namespace RvtIO.Parsing; + +internal static partial class ElementBuilder +{ + private static Dictionary> BuildSiteContourLabels(ParsingState state) + { + var labels = new Dictionary>(); + foreach (var (id, element) in state.NativeParams) + { + if (element.SiteContourLabels is not { } data + || element.Fields.GetValueOrDefault("m_id") != id + || element.Fields.GetValueOrDefault("m_ownerDBViewId") is not (> 0 and var view) + || !state.NativeParams.TryGetValue((uint)data.SurfaceId, out var surface) || surface.SiteContours == null + || element.Fields.GetValueOrDefault("m_attrId") is not (> 0 and var styleId) + || !state.NativeParams.TryGetValue((uint)styleId, out var style)) continue; + + // shortcut: plain labels using the internal elevation and project length format. + var fields = style.Fields; + if (fields.GetValueOrDefault("836:m_baseElevation", -1) != 0 + || fields.GetValueOrDefault("84:m_bUseDefault") != 1 + || fields.GetValueOrDefault("625:m_bBold") != 0 || fields.GetValueOrDefault("625:m_bItalic") != 0 + || fields.GetValueOrDefault("625:m_bUnderline") != 0 + || fields.GetValueOrDefault("625:m_fontId") is not (> 0 and var fontId) + || !state.NativeParams.TryGetValue((uint)fontId, out var font) + || font.DoubleFields.GetValueOrDefault("1923:m_size") is not (> 0 and < 1 and var size)) continue; + + if (!labels.TryGetValue(view, out var group)) labels.Add(view, group = []); + for (int i = 0; i < data.Positions.Length; i++) + group.Add(new((int)id, data.SurfaceId, data.Positions[i], data.Directions[i], size)); + } + return labels; + } +} diff --git a/src/RvtIO/Parsing/ElementBuilder.cs b/src/RvtIO/Parsing/ElementBuilder.cs index 020f11ba..d724fded 100644 --- a/src/RvtIO/Parsing/ElementBuilder.cs +++ b/src/RvtIO/Parsing/ElementBuilder.cs @@ -215,13 +215,39 @@ double[] Corner(int x, int y, int z) => TransformGeometryPoint( return geometry; } - private static double[] TransformGeometryPoint(double[] point, double[] t) => + internal static double[] TransformGeometryPoint(double[] point, double[] t) => [ t[9] + point[0] * t[0] + point[1] * t[1] + point[2] * t[2], t[10] + point[0] * t[3] + point[1] * t[4] + point[2] * t[5], t[11] + point[0] * t[6] + point[1] * t[7] + point[2] * t[8], ]; + private static void ApplyPlanFixtureGraphics(IReadOnlyList elements, ParsingState state) + { + foreach (var element in elements) + { + bool siteEquipment = element.CategoryId is (int)BuiltIns.BuiltInCategory.OST_ElectricalEquipment or (int)BuiltIns.BuiltInCategory.OST_Site; + if (!siteEquipment && element.CategoryId is not ((int)BuiltIns.BuiltInCategory.OST_PlumbingFixtures or (int)BuiltIns.BuiltInCategory.OST_Furniture) + || element.ValidatedOriginalFamilySymbolId is not int symbolId + || state.GrepBlocks.GetValueOrDefault((uint)element.Id)?.Instances is not [var placement] + || placement.SymbolElemId != symbolId + || !IsRigidPlacement(placement.Transform) || Math.Abs(placement.Transform[8] - 1) > 1e-9 + || !state.PlanFixtureGraphicsBySymbol.TryGetValue((uint)symbolId, out var source) + || element.Geometry is { Faces.Count: > 0 } && source.MediumProjection == null && (!siteEquipment || source.CoarseProjection == null)) + continue; + + double[] Place(double[] point) => TransformGeometryPoint(point, placement.Transform); + element.PlacedPlanFixtureGraphics = new( + source.Lines.Select(line => line with { Start = Place(line.Start), End = Place(line.End) }).ToList(), + source.Masks.Select(ring => ring.Select(Place).ToList()).ToList(), + PlaceProjection(source.MediumProjection), siteEquipment ? PlaceProjection(source.CoarseProjection) : null); + + PlanFixtureProjection? PlaceProjection(PlanFixtureProjection? projection) => projection == null ? null : new( + projection.Lines.Select(line => line with { Start = Place(line.Start), End = Place(line.End) }).ToList(), + projection.Masks.Select(ring => ring.Select(Place).ToList()).ToList()); + } + } + /// Set to true when this symbol or a nested one is replaced by its tight box. /// Set to true when a symbol nested in this one, at any depth, placed nothing. internal static GeometryData? BuildPlacedSymbolGeometry( @@ -402,7 +428,7 @@ internal static bool IsRigidPlacement(double[] t) /// Apply a GInstance placement (rows: basisX, basisY, basisZ, origin - 12 doubles) to a /// symbol's geometry, producing world-space faces for the instance. /// - private static GeometryData? TransformGeometry(GeometryData sym, double[] t) + internal static GeometryData? TransformGeometry(GeometryData sym, double[] t) { if (t.Length < 12) return null; double[] Map(double[] p) @@ -415,7 +441,20 @@ double[] Map(double[] p) t[11] + x * t[6] + y * t[7] + z * t[8], }; } + double[] MapAxis(double[] axis) => + [ + axis[0] * t[0] + axis[1] * t[1] + axis[2] * t[2], + axis[0] * t[3] + axis[1] * t[4] + axis[2] * t[5], + axis[0] * t[6] + axis[1] * t[7] + axis[2] * t[8], + ]; var outGeo = new GeometryData { Faces = new List() }; + bool rigid = IsRigidPlacement(t); + bool preservesVertical = rigid && Math.Abs(Math.Abs(t[8]) - 1) < 1e-9; + if (rigid && sym.ViewFacingLines is { Count: > 0 } viewLines) + outGeo.ViewFacingLines = viewLines.Select(line => line with + { + Start = Map(line.Start), End = Map(line.End), Axis = MapAxis(line.Axis), + }).ToList(); var faceMap = new Dictionary(); double minx = double.MaxValue, miny = double.MaxValue, minz = double.MaxValue; double maxx = double.MinValue, maxy = double.MinValue, maxz = double.MinValue; @@ -451,12 +490,18 @@ double[] Map(double[] p) Origin = verts[0], Area = f.Area, PlaneSurface = f.PlaneSurface, + ExcludedFromTopPlan = preservesVertical && f.ExcludedFromTopPlan, + ModelPattern = f.ModelPattern is { } pattern + ? new ModelFacePattern(pattern.PatternId, Map(pattern.Origin), MapAxis(pattern.U), MapAxis(pattern.V)) + : null, + PolygonMesh = f.PolygonMesh, NestedRenderStyleId = f.NestedRenderStyleId ?? f.RenderStyleId, GeometryNode = f.GeometryNode, NodeOrder = f.NodeOrder, GeometryStyle = f.GeometryStyle, MeshMarker = f.SourceFace != 0 ? f.SourceFace : f.MeshMarker, - QuadratureArea = IsRigidPlacement(t) ? f.QuadratureArea : null, + MeshArcs = rigid ? f.MeshArcs?.Select(arc => arc.Transformed(Map, MapAxis, 1) with { Edge = arc.Edge }).ToArray() : null, + QuadratureArea = rigid ? f.QuadratureArea : null, }); faceMap[sourceFaceIndex] = targetFaceIndex; } @@ -471,12 +516,12 @@ double[] Map(double[] p) // the Revit face meshes of the nodes are made in the frame of the symbol and placed // with the transform of the instance (a rotation or a mirror image; a scaled instance keeps // the polygons) - if (sym.MeshNodes is { Count: > 0 } && !IsRigidPlacement(t) && Environment.GetEnvironmentVariable("RVTIO_MESH_LOG") == "1") + if (sym.MeshNodes is { Count: > 0 } && !rigid && Environment.GetEnvironmentVariable("RVTIO_MESH_LOG") == "1") DiagnosticSink.WriteLine($"[meshmesh] {sym.MeshNodes.Count} nodes not placed: the transform is scaled ({string.Join(",", t.Select(v => v.ToString("G4")))})"); - if (sym.MeshNodes is { Count: > 0 } && IsRigidPlacement(t)) + if (sym.MeshNodes is { Count: > 0 } && rigid) outGeo.MeshNodes = sym.MeshNodes.Select(node => node with { Placement = node.Placement == null ? (double[])t.Clone() : ComposeTransforms(t, node.Placement) }).ToList(); // area and volume are the same in a rigidly placed frame; a scaled one has none - if (sym.NodeMeasures is { Count: > 0 } && IsRigidPlacement(t)) outGeo.NodeMeasures = sym.NodeMeasures; + if (sym.NodeMeasures is { Count: > 0 } && rigid) outGeo.NodeMeasures = sym.NodeMeasures; if (sym.BrepSolids is { Count: > 0 }) { outGeo.BrepSolids = new(); @@ -580,6 +625,7 @@ double[] Intersect(double[] a, double[] b) Solids = source.Solids, MeshNodes = source.MeshNodes, UntriangulatedFaces = source.UntriangulatedFaces, + ViewFacingLines = source.ViewFacingLines, }; var oldToNew = new Dictionary(); var clippedFaces = new HashSet(); @@ -610,6 +656,10 @@ double[] Intersect(double[] a, double[] b) ring.Select(point => (double[])point.Clone()).ToList()).ToList(), Area = face.Area, PlaneSurface = face.PlaneSurface, + MeshArcs = faceChanged ? null : face.MeshArcs, + ExcludedFromTopPlan = face.ExcludedFromTopPlan, + ModelPattern = face.ModelPattern, + PolygonMesh = face.PolygonMesh, NestedRenderStyleId = face.NestedRenderStyleId ?? face.RenderStyleId, GeometryNode = face.GeometryNode, NodeOrder = face.NodeOrder, @@ -692,6 +742,7 @@ internal static string FaceCornerKey(List cs) }).ToList(), MeshNodes = grep.MeshNodes, UntriangulatedFaces = grep.UntriangulatedFaces, + ViewFacingLines = grep.ViewFacingLines, NodeMeasures = grep.NodeMeasures, Transform = grep.Transform, Instances = grep.Instances.Count > 0 @@ -788,12 +839,15 @@ List EnvelopeToCorners(double[] env, double[] origin, double[] xv, dou QuadratureArea = fp.QuadratureArea, CurvedSurface = fp.CurvedSurface, PlaneSurface = fp.PlaneSurface, + ExcludedFromTopPlan = fp.ExcludedFromTopPlan, + PolygonMesh = fp.PolygonMesh, PlaneXAxis = fp.PlaneX, PlaneYAxis = fp.PlaneY, SourceFace = fp.SourceFace, FirstSourceLoop = fp.FirstSourceLoop, SourceLoops = fp.SourceLoops, RenderStyleId = fp.RenderStyleId, + ModelPattern = fp.ModelPattern, GeometryNode = fp.GeometryNode, NodeOrder = fp.NodeOrder, GeometryStyle = fp.GeometryStyle, @@ -830,6 +884,7 @@ List EnvelopeToCorners(double[] env, double[] origin, double[] xv, dou YVector = fp.YVector, Normal = normal, Envelope = fp.Envelope, + ExcludedFromTopPlan = fp.ExcludedFromTopPlan, RenderStyleId = fp.RenderStyleId, GeometryNode = fp.GeometryNode, NodeOrder = fp.NodeOrder, @@ -2505,6 +2560,9 @@ void Add(int id, string name, StorageType st, object val) // in ExtractMaterialAppearance. Add(-1002551, "MATERIAL_PARAM_TRANSPARENCY", StorageType.Integer, Math.Max(0, m.Transparency)); if (m.TransparencyFraction >= 0) e.SerializedMaterialTransparency = m.TransparencyFraction; + if (state.NativeParams.GetValueOrDefault(eid)?.Fields.TryGetValue("2479:m_bUseRenderAppearance", out int useRender) == true + && useRender is 0 or 1) + e.SerializedMaterialUsesRenderAppearance = useRender == 1; // Smoothness: decoded value when the integer-percent guard passed and non-zero, else // the Revit default 50 ( materials in the export are 50). Add(-1002553, "MATERIAL_PARAM_SMOOTHNESS", StorageType.Integer, m.Smoothness > 0 ? m.Smoothness : 50); @@ -2950,7 +3008,7 @@ internal static void ApplyViewCrops(RevitFileInfo info, ParsingState? state) if (state == null || state.ViewCropBlocks.Count == 0) return; var views = new Dictionary(info.Elements.Count); foreach (var e in info.Elements) views[e.Id] = e; - foreach (var (_, crop) in state.ViewCropBlocks) + foreach (var (viewerId, crop) in state.ViewCropBlocks) { // The stored viewed id is kept only when it names a real view: a wrong read offset degrades to no crop. if (!views.TryGetValue(crop.RawViewId, out var view) || view.ViewCrop != null) continue; @@ -2963,6 +3021,61 @@ internal static void ApplyViewCrops(RevitFileInfo info, ParsingState? state) crop.Origin[0], crop.Origin[1], crop.Origin[2], crop.Basis[0], crop.Basis[1], crop.Basis[2], x0, y0, x1, y1, active); + if (view.RootClassName == "DBView3d" + && state.NativeParams.TryGetValue(viewerId, out var camera) + && camera.Fields.GetValueOrDefault("621:m_projMethodType") == 1 + && camera.Fields.GetValueOrDefault("4122:m_modelClipBoxId") is > 0 and int boxId + && state.NativeParams.TryGetValue((uint)boxId, out var box) + && box.Fields.GetValueOrDefault("2505:m_viewer3dId") == viewerId) + view.OrthographicModelBounds = box.ModelClipBox; + if (view.OrthographicModelBounds != null + && state.NativeParams.TryGetValue((uint)view.Id, out var display) + && display.Fields.GetValueOrDefault("4106:m_sunAndShadowSettingsId") is > 0 and int studyId + && state.NativeParams.TryGetValue((uint)studyId, out var study) + && study.Fields.GetValueOrDefault("m_ownerDBViewId") == view.Id + && study.Fields.GetValueOrDefault("3878:m_type") == 2 + && study.Fields.GetValueOrDefault("3878:m_bGroundPlane") == 1 + && study.Fields.GetValueOrDefault("3878:m_sunriseToSunset", -1) == 0 + && study.Fields.GetValueOrDefault("3878:m_sunPathSize") is >= 100 and <= 500 and int size + && study.Fields.GetValueOrDefault("3878:m_idLevel") is > 0 and int level + && study.SunStudyOutline is { } outline) + { + int annotation = study.Fields.GetValueOrDefault("3878:m_idAnnotation"); + if (!views.TryGetValue(annotation, out var sunAnnotation) + || sunAnnotation.RootClassName != "SunAnnotationElem" || sunAnnotation.OwnerViewId != view.Id) + annotation = 0; + int shadowIntensity = display.Fields.GetValueOrDefault("4107:m_lighting") == 1 + && display.Fields.GetValueOrDefault("4110:m_castShadows") == 1 + && display.Fields.GetValueOrDefault("4106:m_shadowIntensity") is > 0 and <= 100 and int intensity + ? intensity : 0; + view.SolarStudy = new(outline, size, level, annotation, + unchecked((uint)study.Fields.GetValueOrDefault("3878:m_startDateTime")), + unchecked((uint)study.Fields.GetValueOrDefault("3878:m_endDateTime")), + study.Fields.GetValueOrDefault("3878:m_eSunStudyTimeInterval", -1), + study.DoubleFields.GetValueOrDefault("3878:m_activeFrame"), shadowIntensity, + display.Fields.GetValueOrDefault("4108:m_bShowSurfacePatterns") == 1, + display.Fields.GetValueOrDefault("4108:m_edges") == 1); + } + if (state.NativeParams.TryGetValue(viewerId, out var viewer) + && viewer.Fields.TryGetValue("621:m_bAnnotationCropActive", out int annotationActive) + && annotationActive is 0 or 1) + { + view.ViewAnnotationCropActive = annotationActive == 1; + if (annotationActive == 1 + && viewer.DoubleFields.TryGetValue("334:m_leftRightTopBottomOffsets@0", out double left) + && viewer.DoubleFields.TryGetValue("334:m_leftRightTopBottomOffsets@1", out double right) + && viewer.DoubleFields.TryGetValue("334:m_leftRightTopBottomOffsets@2", out double top) + && viewer.DoubleFields.TryGetValue("334:m_leftRightTopBottomOffsets@3", out double bottom) + && left is >= 0 and < 100 && right is >= 0 and < 100 + && top is >= 0 and < 100 && bottom is >= 0 and < 100) + view.ViewAnnotationCrop = (left, right, top, bottom); + } + if (state.SectionViews.TryGetValue(viewerId, out var section)) + { + view.ViewAnnotationCrop ??= section.Viewdata?.AnnotationCrop; + if (section.Viewdata is { CalloutHead: { } head } data) + view.SectionCallout = (data.ParentViewId, head); + } } } @@ -3193,6 +3306,36 @@ internal static void ApplyNativeParams(RevitFileInfo info, ParsingState? state) if (!state.NativeParams.TryGetValue((uint)e.Id, out var np)) continue; if (np.Fields.TryGetValue("3471:m_bIsLocationless", out int locationless)) e.SerializedRoomIsLocationless = locationless != 0; + e.DetailBreak = np.DetailBreak; + e.SitePropertyCurve = np.SitePropertyCurve; + e.SitePropertyArcCenter = np.SitePropertyArcCenter; + if (np.DoubleFields.TryGetValue("2202:m_widthInFeet", out double imageWidth) + && np.DoubleFields.TryGetValue("2202:m_heightInFeet", out double imageHeight) + && imageWidth is > 0 and < 100 && imageHeight is > 0 and < 100) + e.ImagePaperSize = (imageWidth, imageHeight); + if (np.Fields.TryGetValue("2202:m_idImageHolder", out int imageHolderId) && imageHolderId > 0) + e.ImageHolderId = imageHolderId; + if (np.DoubleFields.TryGetValue("2197:m_dWidthScale", out double imageWidthScale) + && np.DoubleFields.TryGetValue("2197:m_dHeightScale", out double imageHeightScale) + && imageWidthScale is > 0 and < 100 && imageHeightScale is > 0 and < 100) + e.ImageInstanceScale = (imageWidthScale, imageHeightScale); + if (np.Fields.TryGetValue("689:m_idSchemeCategory", out int legendCategory) + && legendCategory == (int)RvtIO.BuiltIns.BuiltInCategory.OST_Rooms + && np.DoubleFields.TryGetValue("689:m_origin@0", out double legendX) + && np.DoubleFields.TryGetValue("689:m_origin@1", out double legendY) + && double.IsFinite(legendX) && double.IsFinite(legendY)) + e.RoomLegendOrigin = (legendX, legendY); + if (np.DoubleFields.TryGetValue("697:m_swatchWidth", out double swatchWidth) + && np.DoubleFields.TryGetValue("697:m_swatchHeight", out double swatchHeight) + && swatchWidth is > 0 and < 1 && swatchHeight is > 0 and < 1) + e.ColorLegendSwatch = (swatchWidth, swatchHeight); + if (e.CategoryId == (int)RvtIO.BuiltIns.BuiltInCategory.OST_InsulationLines + && np.DoubleFields.TryGetValue("2239:m_width", out double insulationWidth) + && np.DoubleFields.TryGetValue("2239:m_scale", out double insulationScale) + && np.Fields.TryGetValue("2239:m_mirrored", out int mirrored) + && insulationWidth is > 0 and < 100 && insulationScale is > 0 and < 100 + && mirrored is 0 or 1) + e.DetailInsulation = (insulationWidth, insulationScale, mirrored == 1); if (np.StringFields.TryGetValue("388:m_areaElemName", out string? areaSchemeName) && np.StringFields.TryGetValue("388:m_areaElemDescription", out string? areaSchemeDescription)) e.SerializedAreaScheme = (areaSchemeName, areaSchemeDescription); @@ -5813,25 +5956,50 @@ public static void PostProcess(RevitFileInfo rvtInfo, ParsingState? state = null rvtInfo.TitleBlockTexts = state?.TitleBlockTexts .Where(pair => pair.Value is { BlockCount: 1, Texts: not null }) .ToDictionary(pair => (int)pair.Key, - pair => (IReadOnlyList<(double Ox, double Oy, double Height, double Width, int Flags, double Bx, double By, byte[] Rtf)>)pair.Value.Texts! - .Select(text => (text.Ox, text.Oy, text.Height, text.Width, text.Flags, text.Bx, text.By, text.Rtf)).ToList()); + pair => (IReadOnlyList)pair.Value.Texts!); rvtInfo.TitleBlockLabels = state?.TitleBlockLabels .Where(pair => pair.Value is { BlockCount: 1, Labels: not null }) .ToDictionary(pair => (int)pair.Key, - pair => (IReadOnlyList<(double Ox, double Oy, double Height, double Width, int Flags, double Bx, double By, int ParamId, string Prefix, string Suffix)>)pair.Value.Labels! - .Select(label => (label.Ox, label.Oy, label.Height, label.Width, label.Flags, label.Bx, label.By, label.ParamId, label.Prefix, label.Suffix)).ToList()); + pair => (IReadOnlyList)pair.Value.Labels!); + if (state != null && rvtInfo.TitleBlockLabels is { } titleLabels) + { + var capHeights = new Dictionary(); + var opaqueStyles = new HashSet(); + var arialStyles = new HashSet(); + foreach (int attributesId in titleLabels.Values.SelectMany(labels => labels).Select(label => label.AttrId).Distinct()) + { + if (attributesId <= 0 || !state.NativeParams.TryGetValue((uint)attributesId, out var attributes) + || attributes.Fields.GetValueOrDefault("625:m_fontId") is not (> 0 and var fontId) + || !state.NativeParams.TryGetValue((uint)fontId, out var font) + || font.DoubleFields.GetValueOrDefault("1923:m_size") is not (> 0 and < 1 and var height)) + continue; + capHeights.Add(attributesId, height); + if (attributes.Fields.GetValueOrDefault("625:m_background", -1) == 0) + opaqueStyles.Add(attributesId); + if (attributes.Fields.GetValueOrDefault("625:m_bBold") == 0 + && attributes.Fields.GetValueOrDefault("625:m_bItalic") == 0 + && font.StringFields.GetValueOrDefault("1923:m_name")?.Equals("Arial", StringComparison.OrdinalIgnoreCase) == true) + arialStyles.Add(attributesId); + } + rvtInfo.TitleBlockCapHeightsFeet = capHeights; + rvtInfo.OpaqueSymbolLabelStyles = opaqueStyles; + rvtInfo.RegularArialSymbolLabelStyles = arialStyles; + rvtInfo.PlanElevationMarks = ReadPlanElevationMarks(state); + rvtInfo.SectionMarkerSymbols = state.NativeParams + .Where(pair => state.ElemClassIdx.GetValueOrDefault(pair.Key) == 3546 + && pair.Value.Fields.GetValueOrDefault("3546:m_sectionHeadFamilyTagId") > 0 + && pair.Value.Fields.GetValueOrDefault("3546:m_sectionTailFamilyTagId") > 0) + .ToDictionary(pair => (int)pair.Key, + pair => (pair.Value.Fields["3546:m_sectionHeadFamilyTagId"], + pair.Value.Fields["3546:m_sectionTailFamilyTagId"])); + } rvtInfo.ScheduleInstances = state?.ScheduleInstances .Where(pair => pair.Value is { BlockCount: 1, Placement: not null }) .ToDictionary(pair => (int)pair.Key, pair => (pair.Value.Placement!.ScheduleId, pair.Value.Placement!.Ox, pair.Value.Placement!.Oy)); rvtInfo.ScheduleTables = state?.ScheduleTables .Where(pair => pair.Value is { BlockCount: 1, Table: not null }) - .ToDictionary(pair => (int)pair.Key, - pair => (pair.Value.Table!.Columns, pair.Value.Table!.CategoryId, pair.Value.Table!.ShowTitle, - pair.Value.Table!.ShowHeaders, pair.Value.Table!.ShowGridLines, pair.Value.Table!.ShowOutline, - pair.Value.Table!.GridStyleId, pair.Value.Table!.OutlineStyleId, - pair.Value.Table!.TitleHeightFt, pair.Value.Table!.TitleBands, pair.Value.Table!.BodySections, - pair.Value.Table!.FixedHeightFt)); + .ToDictionary(pair => (int)pair.Key, pair => ResolveRevisionTextTypes(state, pair.Value.Table!)); rvtInfo.ScheduleSheetRevisions = state?.SheetRevisions .Where(pair => pair.Value is { BlockCount: 1, RevisionIds: not null }) .ToDictionary(pair => (int)pair.Key, @@ -5841,14 +6009,99 @@ public static void PostProcess(RevitFileInfo rvtInfo, ParsingState? state = null .ToDictionary(pair => (int)pair.Key, pair => (pair.Value.Viewdata!.ParentViewId, pair.Value.Viewdata!.CoarserScale, (IReadOnlyList?)pair.Value.Viewdata!.FrontCut)); + rvtInfo.SectionTraceOrigins = state?.SectionViews + .Where(pair => pair.Value is { BlockCount: 1, Viewdata.TraceOrigin: not null }) + .ToDictionary(pair => (int)pair.Key, pair => pair.Value.Viewdata!.TraceOrigin!.Value); + rvtInfo.SiteCutGraphics = state is { SiteCutGraphicsCount: 1 } ? state.SiteCutGraphics : null; + rvtInfo.PropertyBearingFormat = state is { PropertyBearingFormatCount: 1 } ? state.PropertyBearingFormat : null; + rvtInfo.DatumExtents = state?.DatumExtents + .Where(p => p.Value.BlockCount == 1).ToDictionary(p => p.Key, p => p.Value.Extents); + rvtInfo.DatumHeads = state?.DatumHeads.Where(p => p.Value != null).ToDictionary(p => p.Key, p => p.Value!); rvtInfo.MaterialPatterns = state?.MaterialPatterns .Where(pair => pair.Value is { SurfacePatternId: not -1 } or { CutPatternId: not -1 }) .ToDictionary(pair => (int)pair.Key, - pair => (pair.Value.CutPatternId, pair.Value.SurfacePatternId)); + pair => (pair.Value.CutPatternId, pair.Value.SurfacePatternId, pair.Value.SurfacePatternColor)); rvtInfo.FillPatterns = state?.FillPatterns .Where(pair => pair.Value is { Name: not null, Grids: not null }) .ToDictionary(pair => (int)pair.Key, pair => (pair.Value.Name!, (IReadOnlyList)pair.Value.Grids!)); + if (state != null) + { + rvtInfo.ViewRoomColors = BuildViewRoomColors(rvtInfo, state); + ReadPlanDimensions(rvtInfo, state); + rvtInfo.PlanNotes = ReadPlanNotes(state); + rvtInfo.PlanStairPaths = ReadPlanStairPaths(state); + rvtInfo.SiteContours = state.NativeParams.Where(entry => entry.Value.SiteContours != null) + .ToDictionary(entry => (int)entry.Key, entry => entry.Value.SiteContours!); + rvtInfo.SiteContourLabels = BuildSiteContourLabels(state); + rvtInfo.ViewHiddenElements = state.NativeParams.Where(entry => entry.Value.ViewHiddenElements != null) + .ToDictionary(entry => (int)entry.Key, entry => entry.Value.ViewHiddenElements!); + rvtInfo.ViewHiddenCategories = state.NativeParams.Where(entry => entry.Value.ViewHiddenCategories != null) + .ToDictionary(entry => (int)entry.Key, entry => entry.Value.ViewHiddenCategories!); + var opaqueViews = state.NativeParams.Where(entry => + entry.Value.Fields.GetValueOrDefault("4107:m_hlr") == 1 + && entry.Value.Fields.GetValueOrDefault("4108:m_surfaces") == 2 + && entry.Value.Fields.GetValueOrDefault("4108:m_transparency", -1) == 0) + .ToArray(); + rvtInfo.OpaquePlanViews = opaqueViews.Select(entry => (int)entry.Key).ToHashSet(); + var skyGradients = new Dictionary(); + foreach (var (view, display) in opaqueViews) + if (display.Fields.GetValueOrDefault("4103:m_type") == 257 + && display.Fields.GetValueOrDefault("4103:m_skyColor", -1) is >= 0 and <= 0xffffff and int sky + && display.Fields.GetValueOrDefault("4103:m_backgroundColor", -1) is >= 0 and <= 0xffffff and int horizon) + skyGradients.Add((int)view, (sky, horizon, + display.Fields.GetValueOrDefault("4103:m_groundColor", -1) is >= 0 and <= 0xffffff and int ground + ? ground : null)); + rvtInfo.ViewSkyGradients = skyGradients; + var groundShadows = new Dictionary(); + foreach (var (view, display) in opaqueViews) + { + if (display.Fields.GetValueOrDefault("4110:m_castShadows") != 1 + || display.Fields.GetValueOrDefault("4106:m_shadowIntensity", -1) is not (>= 0 and <= 100 and int intensity) + || display.Fields.GetValueOrDefault("4106:m_sunAndShadowSettingsId") is not (> 0 and int id) + || !state.NativeParams.TryGetValue((uint)id, out var light) + // Lighting study with an authored ground plane and light angles relative to the view. + || light.Fields.GetValueOrDefault("3878:m_type") != 3 + || light.Fields.GetValueOrDefault("3878:m_bGroundPlane") != 1 + || light.Fields.GetValueOrDefault("3878:m_bRelativeToView") != 1 + || light.Fields.GetValueOrDefault("3878:m_idLevel") is not (> 0 and int level) + || !light.DoubleFields.TryGetValue("3878:m_dAzimuth", out double azimuth) + || !(azimuth >= 0 && azimuth <= 2 * Math.PI) + || !light.DoubleFields.TryGetValue("3878:m_dAltitude", out double altitude) + || !(altitude > 0 && altitude <= Math.PI / 2)) continue; + groundShadows.Add((int)view, (azimuth, altitude, level, intensity)); + } + rvtInfo.ViewGroundShadows = groundShadows; + var stillSunDates = new Dictionary(); + foreach (var (view, display) in opaqueViews) + if (display.Fields.GetValueOrDefault("4110:m_ambientShadows") == 1 + && display.Fields.GetValueOrDefault("4110:m_castShadows", -1) == 0 + && display.Fields.GetValueOrDefault("4106:m_sunAndShadowSettingsId") is > 0 and int id + && state.NativeParams.TryGetValue((uint)id, out var light) + && light.Fields.GetValueOrDefault("3878:m_type", -1) == 0 + && light.Fields.TryGetValue("3878:m_startDateTime", out int time)) + stillSunDates.Add((int)view, unchecked((uint)time)); + rvtInfo.ViewStillSunDates = stillSunDates; + rvtInfo.ViewAmbientLight = opaqueViews.Where(entry => + entry.Value.Fields.GetValueOrDefault("4110:m_ambientShadows") == 1 + && entry.Value.Fields.GetValueOrDefault("4106:m_ambientLightIntensity", -1) is >= 0 and <= 100) + .ToDictionary(entry => (int)entry.Key, + entry => entry.Value.Fields["4106:m_ambientLightIntensity"] / 100.0); + rvtInfo.ViewAmbientFractions = opaqueViews.Where(entry => + entry.Value.Fields.GetValueOrDefault("4110:m_ambientShadows") == 1 + && entry.Value.Fields.GetValueOrDefault("4106:m_ambientLightIntensity", -1) is > 0 and <= 100 + && entry.Value.Fields.GetValueOrDefault("4106:m_sunlightIntensity", -1) is >= 0 and <= 100) + .ToDictionary(entry => (int)entry.Key, + entry => (double)entry.Value.Fields["4106:m_ambientLightIntensity"] + / (entry.Value.Fields["4106:m_ambientLightIntensity"] + entry.Value.Fields["4106:m_sunlightIntensity"])); + rvtInfo.OpaqueViewsWithSurfacePatterns = opaqueViews.Where(entry => + entry.Value.Fields.GetValueOrDefault("4108:m_bShowSurfacePatterns", -1) == 1) + .Select(entry => (int)entry.Key).ToHashSet(); + rvtInfo.UnshadedHiddenLineViews = opaqueViews.Where(entry => + entry.Value.Fields.GetValueOrDefault("4110:m_ambientShadows", -1) == 0 + && entry.Value.Fields.GetValueOrDefault("4110:m_castShadows", -1) == 0) + .Select(entry => (int)entry.Key).ToHashSet(); + } rvtInfo.PlanViewRanges = state?.PlanViewRanges .Where(pair => pair.Value is { Offsets: not null, LevelIds: not null }) .ToDictionary(pair => (int)pair.Key, @@ -6551,6 +6804,7 @@ void ReportDistinctMissing(string label, Dictionary counts) ApplySerializedSystemTypeIdentity(rvtInfo.Elements, state); ApplyValidatedOriginalFamilySymbols(rvtInfo.Elements, state); ApplyOwnFamilyCutoutInputs(rvtInfo.Elements, state); + ApplyPlanFixtureGraphics(rvtInfo.Elements, state); ApplySolidTrimmedAxis(rvtInfo.Elements); ApplyValidatedCeilingCanonicalTypes(rvtInfo.Elements, state); ApplySerializedStairData( @@ -6636,6 +6890,7 @@ void ReportDistinctMissing(string label, Dictionary counts) ApplyColumnAttachments(rvtInfo); ApplyMovesWithGrids(rvtInfo); ApplyEditedByCategoryRules(rvtInfo, state); + if (state != null) rvtInfo.EvaluatedScheduleRows = EvaluateScheduleRows(rvtInfo, state); ApplyCapturedCurveStyles(rvtInfo, state); // Reference precedence needs the final decoded instance/type parameter sets. if (state != null) @@ -6759,6 +7014,8 @@ private static void AppendGeometry(GeometryData target, GeometryData source, lon int faceOffset = target.Faces.Count; int edgeOffset = target.Edges?.Count ?? 0; target.UntriangulatedFaces += source.UntriangulatedFaces; + if (source.ViewFacingLines is { Count: > 0 } viewLines) + (target.ViewFacingLines ??= []).AddRange(viewLines); // Geometry node ids are unique within one GeometryData: the appended nodes follow the // existing ones. (a negative id marks a node that Revit does not take, see // GRepParserV2). @@ -6810,6 +7067,9 @@ face.AnalyticCylinderReferenceDirection is null QuadratureArea = face.QuadratureArea, CurvedSurface = face.CurvedSurface, PlaneSurface = face.PlaneSurface, + ExcludedFromTopPlan = face.ExcludedFromTopPlan, + ModelPattern = face.ModelPattern, + PolygonMesh = face.PolygonMesh, PlaneXAxis = face.PlaneXAxis, PlaneYAxis = face.PlaneYAxis, SourceFace = face.SourceFace, diff --git a/src/RvtIO/Parsing/GRepParserV2.cs b/src/RvtIO/Parsing/GRepParserV2.cs index a90f342b..61514f07 100644 --- a/src/RvtIO/Parsing/GRepParserV2.cs +++ b/src/RvtIO/Parsing/GRepParserV2.cs @@ -40,6 +40,8 @@ private sealed class DecodeStop : Exception { } private sealed record InstanceRec( int SymbolElemId, double[] Transform, int OwnerQueueIndex); + internal sealed record SheetImagePlacement(int SymbolId, double X, double Y, double ScaleX, double ScaleY); + private sealed class Cur { public byte[] D = []; @@ -50,6 +52,7 @@ private sealed class Cur public bool NativeWallBody; public bool IncludeNonVisible; public bool SawDetailCondition; // a node was judged below a detail-level condition + public List? SheetImages; public int BlockStart, BlockEnd; // this block's payload bounds (plane scan) public int LastEdgeEnd; // pos after the last decoded Edge public List<(ushort Cls, int V)> Queue = new(); @@ -58,6 +61,7 @@ private sealed class Cur public int FaceCount; // faces seen (schema-walked) public List FaceOrder = new(); // face handle (queue v) in processing order public Dictionary FaceRenderStyle = new(); // GFace.m_renderStyleId (the face material) by face handle + public Dictionary? FacePatternPlacers; public Dictionary FaceFlagsV9 = new(); // GFace.m_faceFlags_v9 by face handle public List SurfClasses = new(); // surface classId per face, in queue order public List Edges = new(); @@ -107,7 +111,7 @@ private sealed class Cur public Dictionary HarvestSurf = new(); // Exact deferred-pointer graph. QueueLinks is also needed by production geometry ownership; - // QueueChildren retains only m_oConditions outside targeted diagnostics. + // QueueChildren keeps condition links and direct root-filter contents outside diagnostics. public int CurrentObjectHandle; public ushort CurrentObjectClass; public int CurrentQueueIndex = -1; @@ -118,6 +122,9 @@ private sealed class Cur public Dictionary>> QueueDoubles = new(); public Dictionary>> QueueBytes = new(); public Dictionary ObjectGInfo = new(); + public List<(int Index, int Tag, int StyleId, ArcRec Line)>? ViewLineCandidates; + public List<(int Filter, uint Handle, uint Flags, bool Filled, int StyleId)>? PlanCurveCandidates; + public List<(int FaceIndex, uint Handle)>? PlanMaskCandidates; public EdgeRec? CapEdge; // non-null while walking an Edge public bool ExactPlanarSpaceBoundary; @@ -790,9 +797,10 @@ static double Distance(double[] a, double[] b) => Math.Sqrt((a[0] - b[0]) * (a[0 /// holds detail-level alternatives that differ (). /// /// Use native Low edge sampling only after confirming a unique own wall root and GRep. - public static GRepData? Parse(byte[] d, int blockStart, uint dataSize, bool nativeWallBody = false) + public static GRepData? Parse(byte[] d, int blockStart, uint dataSize, bool nativeWallBody = false, + Action? collectPlanFixtures = null) { - var fine = ParseCore(d, blockStart, dataSize, nativeWallBody); + var fine = ParseCore(d, blockStart, dataSize, nativeWallBody, collectPlanFixtures: collectPlanFixtures); if (fine is not { HasDetailLevelAlternatives: true }) return fine; try { @@ -828,7 +836,18 @@ internal static bool IsSameDetailLevelGeometry(GRepData fine, GRepData coarse) = && fine.Instances.Zip(coarse.Instances).All(pair => pair.First.SymbolElemId == pair.Second.SymbolElemId && pair.First.Transform.SequenceEqual(pair.Second.Transform)); - private static GRepData? ParseCore(byte[] d, int blockStart, uint dataSize, bool nativeWallBody, bool includeNonVisible = false) + internal static IReadOnlyList ReadSheetImages(byte[] block) + { + if (block.Length < 20) return []; + uint size = BitConverter.ToUInt32(block, 8); + if (size != block.Length - 16 || BitConverter.ToUInt32(block, block.Length - 4) != size) return []; + var images = new List(); + ParseCore(block, 0, size, false, sheetImages: images); + return images; + } + + private static GRepData? ParseCore(byte[] d, int blockStart, uint dataSize, bool nativeWallBody, bool includeNonVisible = false, + List? sheetImages = null, Action? collectPlanFixtures = null) { int payloadStart = blockStart + 14; int payloadEnd = (int)Math.Min((long)blockStart + 16 + dataSize, d.Length); @@ -851,6 +870,7 @@ internal static bool IsSameDetailLevelGeometry(GRepData fine, GRepData coarse) = RootClass = classId, CurrentObjectHandle = elementId, CurrentObjectClass = classId, + SheetImages = sheetImages, }; if (targeted) { @@ -858,17 +878,22 @@ internal static bool IsSameDetailLevelGeometry(GRepData fine, GRepData coarse) = Array.Copy(d, blockStart, raw, 0, raw.Length); File.WriteAllBytes(Path.Combine(Path.GetTempPath(), $"grep_schema_{elementId}.bin"), raw); } + int resyncs = 0; try { foreach (var f in rootFields) ReadField(c, f, 0); if (dbg) DiagnosticSink.WriteLine($" V2 eid={elementId} root bbox=[{string.Join(',', c.RootBoundingBox ?? [])}] tight=[{string.Join(',', c.RootTightBoundingBox ?? [])}]"); - int resyncs = 0; for (int qi = 0; qi < c.Queue.Count; qi++) { int itemStart = c.Pos; if (targeted) c.DebugItemStarts.Add(itemStart); - try { WalkQueueItem(c, qi); } + try + { + WalkQueueItem(c, qi); + if (resyncs == 0 && c.Queue[qi].Cls == 2014) + CaptureFacePattern(c, qi, itemStart); + } catch (DecodeStop) { if (dbg) @@ -895,6 +920,7 @@ internal static bool IsSameDetailLevelGeometry(GRepData fine, GRepData coarse) = } catch (DecodeStop) { if (dbg) DiagnosticSink.WriteLine($" V2 stop at pos={c.Pos}/{c.End} faces={c.FaceCount} edges={c.Edges.Count} queue={c.Queue.Count}"); } catch (Exception ex) { if (dbg) DiagnosticSink.WriteLine($" V2 exc {ex.GetType().Name}: {ex.Message} at pos={c.Pos} faces={c.FaceCount} edges={c.Edges.Count}"); } + if (sheetImages != null && c.Pos != c.End) sheetImages.Clear(); // Grammar-first harvest of a large unwalked tail: post-gap objects belong to queue entries // whose parents were never walked (never enqueued) - the queue can't reach them, but the @@ -1001,9 +1027,17 @@ string Number(double value) => value.ToString("G17", } } } + if (collectPlanFixtures != null && c.Pos == c.End && resyncs == 0 + && ReadPlanFixtureGraphics(c) is { } planGraphics) + collectPlanFixtures(planGraphics); var built = BuildGeometry(c); if (built != null) { + if (c.Pos == c.End) + { + built.ViewFacingLines = ReadViewFacingLines(c); + if (resyncs == 0) built.DoorPlanSymbols = ReadDoorPlanSymbols(c); + } built.QueueClassCounts = c.Queue.GroupBy(item => item.Cls).ToDictionary(group => group.Key, group => group.Count()); built.HasDetailLevelAlternatives = c.SawDetailCondition; built.RootBoundingBox = ValidBox(c.RootBoundingBox) ? c.RootBoundingBox : null; @@ -1241,6 +1275,74 @@ bool TryReadCount(out uint count) return true; } + private static void ReadSheetImage(Cur c) + { + // ImageInfoScaled starts with the base/up vectors and the inline Trf basis and origin. + ReadOnlySpan basis = [1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1]; + if (!c.CanRead(168)) return; + int start = c.Pos; + for (int i = 0; i < basis.Length; i++) + if (BitConverter.ToDouble(c.D, start + 8 * i) != basis[i]) return; + double x = BitConverter.ToDouble(c.D, start + 120); + double y = BitConverter.ToDouble(c.D, start + 128); + double z = BitConverter.ToDouble(c.D, start + 136); + int symbol = BitConverter.ToInt32(c.D, start + 144); + double sx = BitConverter.ToDouble(c.D, start + 152); + double sy = BitConverter.ToDouble(c.D, start + 160); + if (symbol > 0 && z == 0 && Math.Abs(x) < 100 && Math.Abs(y) < 100 + && sx is > 0 and < 100 && sy is > 0 and < 100) + c.SheetImages!.Add(new SheetImagePlacement(symbol, x, y, sx, sy)); + } + + private static void CaptureFacePattern(Cur c, int qi, int start) + { + if (c.QueueLinks[qi] is not (>= 0 and var parent, "m_pGFilling") + || c.Queue[parent] is not (1589, var face)) return; + if (c.RootClass == 2007 && !c.IncludeNonVisible && c.Pos - start == 94) + { + var fill = c.D.AsSpan(start, 94); + // A blank pattern with the saved background-color token forms the mask of a 2D symbol. + if (BitConverter.ToInt32(fill[16..]) == face && BitConverter.ToUInt32(fill[78..]) == 0 + && BitConverter.ToInt32(fill[82..]) == -1 && BitConverter.ToUInt32(fill[86..]) == 0x01000000u + && BitConverter.ToInt32(fill[90..]) == 34) + (c.PlanMaskCandidates ??= []).Add((parent, (uint)face)); + return; + } + if (c.Pos - start != 96) return; + + // GFilling: GInfo, face back-reference, FillPatternPlacer, FillPatternData pointer, id, color, flags. + var data = c.D.AsSpan(start, 96); + if (BitConverter.ToInt32(data[16..]) != face + || BitConverter.ToUInt32(data[78..]) != uint.MaxValue || BitConverter.ToUInt16(data[82..]) != 1850 + || BitConverter.ToUInt32(data[88..]) != 0 || BitConverter.ToInt32(data[92..]) != 9) + return; + int id = BitConverter.ToInt32(data[84..]); + // shortcut: support black model placers with unit scales, extend when other layouts are verified. + if (id <= 0 || BitConverter.ToDouble(data[20..]) != 1 || BitConverter.ToDouble(data[60..]) != 1 + || BitConverter.ToDouble(data[68..]) != 1 || data[76] != 0 || data[77] != 0) return; + double u = BitConverter.ToDouble(data[28..]), v = BitConverter.ToDouble(data[36..]); + double du = BitConverter.ToDouble(data[44..]), dv = BitConverter.ToDouble(data[52..]); + if (!IsFinite(u) || !IsFinite(v) || !IsFinite(du) || !IsFinite(dv) + || Math.Abs(du * du + dv * dv - 1) > 1e-9) return; + (c.FacePatternPlacers ??= new())[(uint)face] = (id, u, v, du, dv); + } + + private static ModelFacePattern? PlacedFacePattern(Cur c, uint face) + { + if (c.FacePatternPlacers?.TryGetValue(face, out var placer) != true + || !c.DirectSurfaceByFace.TryGetValue(face, out var surface) || surface.Kind != SurfKind.Plane + || World(ToPlane(surface), placer.U, placer.V) is not { } origin) return null; + + var u = new double[3]; + var v = new double[3]; + for (int axis = 0; axis < 3; axis++) + { + u[axis] = placer.Du * surface.X[axis] + placer.Dv * surface.Y[axis]; + v[axis] = -placer.Dv * surface.X[axis] + placer.Du * surface.Y[axis]; + } + return new ModelFacePattern(placer.Id, origin, u, v); + } + private static void WalkQueueItem(Cur c, int qi) { var (cls, v) = c.Queue[qi]; @@ -1249,6 +1351,9 @@ private static void WalkQueueItem(Cur c, int qi) c.CurrentObjectClass = cls; var qf = TfBlockDeserializer.SerializationFields(cls); if (qf == null) throw Stop; + if (cls == 2197 && c.SheetImages != null && c.QueueLinks[qi] is (int parent, "m_imageInfo") + && parent >= 0 && c.Queue[parent].Cls == 2022) + ReadSheetImage(c); // Blob-headed items: refresh the class's tag base (tag = base + ordinal). if (qf.Count > 0 && qf[0].Name == "m_GInfo" && c.CanRead(16)) { @@ -1426,6 +1531,7 @@ double[] ReadParameters() ar.Y[k] = BitConverter.ToDouble(c.D, c.Pos + 56 + 8 * k); ar.C[k] = BitConverter.ToDouble(c.D, c.Pos + 88 + 8 * k); } + CapturePlanCutCurve(c, qi, (uint)v, c.D[c.Pos + 112] != 0); c.Take(113); if (IsFinite(ar.R) && IsFinite(ar.C[0]) && Math.Abs(ar.R) > 1e-9 && Math.Abs(ar.R) < 1e5) c.Curves[(uint)v] = ar; @@ -1448,6 +1554,7 @@ double[] ReadParameters() ellipse.X[k] = BitConverter.ToDouble(c.D, c.Pos + 56 + 8 * k); ellipse.Y[k] = BitConverter.ToDouble(c.D, c.Pos + 80 + 8 * k); } + CapturePlanCutCurve(c, qi, (uint)v, false); c.Take(120); if (IsFinite(ellipse.R) && IsFinite(ellipse.RY) && Math.Abs(ellipse.R) > 1e-9 && Math.Abs(ellipse.R) < 1e5 @@ -1480,6 +1587,16 @@ double[] ReadParameters() ln.C[k] = BitConverter.ToDouble(c.D, c.Pos + 32 + 8 * k); ln.X[k] = BitConverter.ToDouble(c.D, c.Pos + 56 + 8 * k); } + if (c.RootClass == 2007 && !c.IncludeNonVisible + && c.QueueLinks[qi] is (>= 0 and int parentIndex, "m_subNodes") + && c.Queue[parentIndex].Cls == 2015 && c.QueueLinks[parentIndex].ParentQueueIndex < 0) + { + int style = BitConverter.ToInt32(c.D, c.Pos + 8); + uint flags = BitConverter.ToUInt32(c.D, c.Pos + 12); + if (style > 0 && !IsHiddenInstanceVariant(flags) && IsPhysicalBodySurface(flags)) + (c.ViewLineCandidates ??= []).Add((qi, BitConverter.ToInt32(c.D, c.Pos), style, ln)); + } + CapturePlanCutCurve(c, qi, (uint)v, false); c.Take(80); if (IsFinite(ln.C[0]) && IsFinite(ln.X[0])) c.Curves[(uint)v] = ln; @@ -1807,6 +1924,292 @@ internal static bool ShouldAttachSymbolGeometry(ushort ownerClass) /// internal static bool IsHiddenInstanceVariant(uint nodeFlags) => (nodeFlags & 0xE0u) == 0xE0u; + private static void CapturePlanCutCurve(Cur c, int index, uint handle, bool filled) + { + if (c.RootClass != 2007 || c.IncludeNonVisible + || c.QueueLinks[index] is not (>= 0 and int filter, "m_subNodes") + || c.Queue[filter].Cls != 2015 || c.QueueLinks[filter] != (-1, "m_subNodes")) + return; + int style = BitConverter.ToInt32(c.D, c.Pos + 4) == 0 ? BitConverter.ToInt32(c.D, c.Pos + 8) : -1; + (c.PlanCurveCandidates ??= []).Add((filter, handle, BitConverter.ToUInt32(c.D, c.Pos + 12), filled, style)); + } + + private static List? ReadDoorPlanSymbols(Cur c) + { + if (c.PlanCurveCandidates == null) return null; + var symbols = new List(); + foreach (var group in c.PlanCurveCandidates.GroupBy(candidate => candidate.Filter)) + { + var conditions = c.QueueChildren.GetValueOrDefault(group.Key)?.Where(index => + c.QueueLinks[index].Field == "m_oConditions").ToArray(); + if (conditions is not [int condition] || c.Queue[condition].Cls is not (1995 or 1996) + || !IsTopPlanCondition(c, condition, out var values)) + continue; + (double Lo, double Hi)? cutRange = null; + if (c.Queue[condition].Cls == 1995) + { + if (values.GetValueOrDefault("m_rangeLo") is not [double lo] + || values.GetValueOrDefault("m_rangeHi") is not [double hi] + || !IsFinite(lo) || !IsFinite(hi) || hi <= lo) + continue; + cutRange = (lo, hi); + } + // shortcut: require a complete set of direct line and circular-arc children. + if (c.QueueChildren[group.Key].Count != group.Count() + 1 + || !c.ObjectGInfo.TryGetValue(c.Queue[group.Key].V, out var filterInfo) + || (filterInfo.Flags & 0x20u) != 0) + continue; + var curves = new List(); + foreach (var item in group) + { + if (item.Filled || (item.Flags & 0x20u) != 0 + || !c.Curves.TryGetValue(item.Handle, out var curve) || curve.RY != 0 || !IsPlanCutCurve(curve)) + break; + curves.Add(curve); + } + if (curves.Count == group.Count() && curves.Any(curve => curve.R > 0) + && curves.Any(curve => curve.R == 0)) + symbols.Add(new(cutRange, curves)); + } + return symbols.Count == 0 ? null : symbols; + } + + private static bool IsTopPlanCondition(Cur c, int condition, + [System.Diagnostics.CodeAnalysis.NotNullWhen(true)] out Dictionary>? values) + { + values = c.QueueDoubles.GetValueOrDefault(condition); + return c.QueueInts.GetValueOrDefault(condition)?.GetValueOrDefault("m_comp") == 6 + && c.QueueBytes.GetValueOrDefault(condition)?.GetValueOrDefault("m_negateDirCondition") is [0] + && values?.GetValueOrDefault("m_dir") is [0, 0, 1]; + } + + private static bool ExcludesTopPlan(Cur c, int node) + { + while (node >= 0 && node < c.QueueLinks.Count && c.QueueLinks[node] is (>= 0 and int parent, "m_subNodes")) + { + if (c.Queue[parent].Cls == 2015 + && c.QueueChildren.TryGetValue(parent, out var children) + && children.Any(child => c.QueueLinks[child].Field == "m_oConditions" + && c.Queue[child].Cls == 1996 + && c.QueueInts.GetValueOrDefault(child)?.GetValueOrDefault("m_comp") == 8 + && c.QueueBytes.GetValueOrDefault(child)?.GetValueOrDefault("m_negateDirCondition") is [1] + && c.QueueDoubles.GetValueOrDefault(child)?.GetValueOrDefault("m_dir") is [var x, var y, var z] + && Math.Abs(x) < 1e-9 && Math.Abs(y) < 1e-9 && Math.Abs(Math.Abs(z) - 1) < 1e-9)) + return true; + node = parent; + } + return false; + } + + private static PlanFixtureGraphics? ReadPlanFixtureGraphics(Cur c) + { + var lines = new List(); + foreach (var group in (c.PlanCurveCandidates ?? []).GroupBy(candidate => candidate.Filter)) + { + // The unconditional line branch is complete, including any tagged non-printing lines. + if (c.QueueChildren[group.Key].Count != group.Count() + || !c.ObjectGInfo.TryGetValue(c.Queue[group.Key].V, out var filterInfo) + || (filterInfo.Flags & 0x20u) != 0 + || c.QueueChildren[group.Key].Any(index => c.QueueLinks[index].Field != "m_subNodes" || c.Queue[index].Cls != 1736)) + continue; + var visible = group.Where(item => (item.Flags & 0x20u) == 0).ToArray(); + var strokes = new List(); + foreach (var item in visible) + { + if (item.StyleId <= 0 || !c.Curves.TryGetValue(item.Handle, out var curve) + || !IsPlanCutCurve(curve)) break; + var start = Enumerable.Range(0, 3).Select(i => curve.C[i] + curve.T0 * curve.X[i]).ToArray(); + var end = Enumerable.Range(0, 3).Select(i => curve.C[i] + curve.T1 * curve.X[i]).ToArray(); + if (!start.All(IsFinite) || !end.All(IsFinite) || start.SequenceEqual(end)) break; + strokes.Add(new(start, end, item.StyleId)); + } + if (strokes.Count == visible.Length) lines.AddRange(strokes); + } + var mediumProjection = ReadTopFixtureProjection(c, 2); + var coarseProjection = ReadTopFixtureProjection(c, 1); + return lines.Count == 0 && mediumProjection == null && coarseProjection == null ? null + : new(lines, lines.Count == 0 ? [] : ReadPlanFixtureMasks(c), mediumProjection, coarseProjection); + } + + private static PlanFixtureProjection? ReadTopFixtureProjection(Cur c, int detailLevel) + { + if (c.PlanMaskCandidates == null && c.PlanCurveCandidates == null) return null; + var lines = new List(); + var masks = new List>(); + var curvesByFilter = (c.PlanCurveCandidates ?? []).ToLookup(candidate => candidate.Filter); + Dictionary>? loopsByFace = null; + Dictionary? edges = null; + foreach (var (filter, children) in c.QueueChildren) + { + if (c.Queue[filter].Cls != 2015 || c.QueueLinks[filter] != (-1, "m_subNodes") + || !c.ObjectGInfo.TryGetValue(c.Queue[filter].V, out var filterInfo) + || (filterInfo.Flags & 0x20u) != 0) + continue; + var conditions = children.Where(index => c.QueueLinks[index].Field == "m_oConditions").ToArray(); + if (!conditions.Any(index => c.Queue[index].Cls == 1996 && IsTopPlanCondition(c, index, out _))) + continue; + if (conditions.Length > 2) return null; + if (conditions.Length == 2) + { + var detailConditions = conditions.Where(index => c.Queue[index].Cls == 1999).ToArray(); + if (detailConditions is not [int detail] + || c.QueueInts.GetValueOrDefault(detail) is not { } values + || values.GetValueOrDefault("m_param") != 3 + || !values.TryGetValue("m_comp", out int comparison) || comparison is < -1 or > 5 + || values.GetValueOrDefault("m_value") is not (>= 1 and <= 3 and var level)) + return null; + if (!CompareSerializedInteger(detailLevel, comparison, level)) continue; + } + + var drawable = children.Where(index => c.QueueLinks[index].Field == "m_subNodes").ToArray(); + var geometries = drawable.Where(index => c.Queue[index].Cls == 2092).ToArray(); + if (drawable.Length != geometries.Length + curvesByFilter[filter].Count()) return null; + foreach (int geometry in geometries) + { + if (!c.ObjectGInfo.TryGetValue(c.Queue[geometry].V, out var geometryInfo) + || (geometryInfo.Flags & 0x20u) != 0 + || c.PlanMaskCandidates?.Where(candidate => c.QueueLinks[candidate.FaceIndex] == (geometry, "m_pFaces")) + .ToArray() is not [var candidate] + || !c.ObjectGInfo.TryGetValue((int)candidate.Handle, out var faceInfo) + || (faceInfo.Flags & (DisplaySurfaceBit | 0x20u)) != DisplaySurfaceBit + || !c.DirectSurfaceByFace.TryGetValue(candidate.Handle, out var surface) || surface.Kind != SurfKind.Plane + || Math.Abs(surface.X[2]) > 1e-9 || Math.Abs(surface.Y[2]) > 1e-9 + || !(loopsByFace ??= CompleteFaceLoops(c)).TryGetValue(candidate.Handle, out var loops)) + return null; + var segments = new List<(double[] A, double[] B)>(); + var loopEdges = new HashSet(); + if (TryOrderLoopRings(c, candidate.Handle, loops, edges ??= EdgesByHandle(c), ToPlane(surface), segments, loopEdges) is not { } rings) + return null; + if (rings is [var mask]) masks.Add(mask); + + var styles = loopEdges.Select(edge => c.ObjectGInfo.GetValueOrDefault((int)edge)).ToArray(); + if (styles.Any(style => (style.Flags & 0x20u) == 0)) + { + if (styles.Select(style => style.Category).Distinct().ToArray() is not [> 0 and int styleId] + || styles.Any(style => (style.Flags & 0x20u) != 0)) + return null; + lines.AddRange(segments.Select(segment => new StyledModelLine(segment.A, segment.B, styleId))); + } + } + + foreach (var item in curvesByFilter[filter]) + { + if ((item.Flags & 0x20u) != 0) continue; + if (item.Filled || item.StyleId <= 0 || !c.Curves.TryGetValue(item.Handle, out var curve) + || !IsPlanCutCurve(curve) || (curve.RY != 0 && (!IsFinite(curve.RY) || curve.RY < 0))) + return null; + var parameters = curve.R == 0 ? [curve.T0, curve.T1] + : RefineAngularSamples([curve.T0, curve.T1], Math.Max(curve.R, curve.RY)); + var start = curve.Eval(parameters[0]); + if (!start.All(IsFinite)) return null; + foreach (double parameter in parameters.Skip(1)) + { + var end = curve.Eval(parameter); + if (!end.All(IsFinite)) return null; + if (!start.SequenceEqual(end)) lines.Add(new(start, end, item.StyleId)); + start = end; + } + } + } + return lines.Count == 0 ? null : new(lines, masks); + } + + private static List> ReadPlanFixtureMasks(Cur c) + { + var masks = new List>(); + if (c.PlanMaskCandidates == null) return masks; + var loopsByFace = CompleteFaceLoops(c); + var edges = EdgesByHandle(c); + foreach (var (faceIndex, face) in c.PlanMaskCandidates) + { + if (c.QueueLinks[faceIndex] is not (>= 0 and int geometry, "m_pFaces") + || c.Queue[geometry].Cls != 2092 + || !c.ObjectGInfo.TryGetValue(c.Queue[geometry].V, out var geometryInfo) + || (geometryInfo.Flags & 0x20u) != 0 + || c.QueueLinks[geometry] is not (>= 0 and int filter, "m_subNodes") + || c.Queue[filter].Cls != 2015 || c.QueueLinks[filter] != (-1, "m_subNodes") + || !c.ObjectGInfo.TryGetValue(c.Queue[filter].V, out var filterInfo) || (filterInfo.Flags & 0x20u) != 0 + || c.QueueChildren.GetValueOrDefault(filter)?.Where(i => c.QueueLinks[i].Field == "m_oConditions").ToArray() + is not [int condition] || c.Queue[condition].Cls != 1996 || !IsTopPlanCondition(c, condition, out _) + || !c.DirectSurfaceByFace.TryGetValue(face, out var surface) || surface.Kind != SurfKind.Plane + || Math.Abs(surface.X[2]) > 1e-9 || Math.Abs(surface.Y[2]) > 1e-9 + || loopsByFace.GetValueOrDefault(face) is not { Count: 1 } loops + || TryOrderLoopRings(c, face, loops, edges, ToPlane(surface), [], []) is not [var ring]) + continue; + masks.Add(ring); + } + return masks; + } + + private static bool IsPlanCutCurve(ArcRec curve) + { + if (!IsFinite(curve.T0) || !IsFinite(curve.T1) || curve.T1 <= curve.T0 + || !curve.C.All(IsFinite) || !curve.X.All(IsFinite) || Math.Abs(curve.X[2]) > 1e-9) + return false; + if (curve.R == 0) return curve.X[0] != 0 || curve.X[1] != 0; + return curve.R > 0 && curve.T1 - curve.T0 <= Math.Tau + 1e-9 + && curve.Y.All(IsFinite) && Math.Abs(curve.Y[2]) <= 1e-9 + && Math.Abs(curve.X[0] * curve.X[0] + curve.X[1] * curve.X[1] - 1) <= 1e-9 + && Math.Abs(curve.Y[0] * curve.Y[0] + curve.Y[1] * curve.Y[1] - 1) <= 1e-9 + && Math.Abs(curve.X[0] * curve.Y[0] + curve.X[1] * curve.Y[1]) <= 1e-9; + } + + private static List? ReadViewFacingLines(Cur c) + { + if (c.ViewLineCandidates == null) return null; + // shortcut: require matching opposite elevation filters until asymmetric direction modes are decoded. + var alternatives = new List<(int Tag, int Side, ViewFacingLine Line)>(); + foreach (var (index, tag, style, curve) in c.ViewLineCandidates) + { + int filter = c.QueueLinks[index].ParentQueueIndex; + var conditions = c.QueueChildren.GetValueOrDefault(filter)?.Where(i => + i < c.QueueLinks.Count && c.QueueLinks[i].Field == "m_oConditions").ToArray(); + if (conditions is not ({ Length: 1 } or { Length: 2 })) continue; + int direction = conditions.FirstOrDefault(i => c.Queue[i].Cls == 1996, -1); + if (direction < 0) continue; + int side = c.QueueInts.GetValueOrDefault(direction)?.GetValueOrDefault("m_comp") ?? 0; + if (side is not (6 or 7) + || c.QueueBytes.GetValueOrDefault(direction)?.GetValueOrDefault("m_negateDirCondition") is not [0] + || c.QueueDoubles.GetValueOrDefault(direction)?.GetValueOrDefault("m_dir") is not { Count: 3 } axis + || Normalize(axis.ToArray()) is not { } unitAxis) continue; + (int Comparison, int Level)? detailCondition = null; + if (conditions.Length == 2) + { + int detail = conditions.FirstOrDefault(i => c.Queue[i].Cls == 1999, -1); + if (detail < 0 || c.QueueInts.GetValueOrDefault(detail) is not { } level + || level.GetValueOrDefault("m_param") != 3 + || !level.TryGetValue("m_comp", out int comparison) || comparison is < -1 or > 5 + || !level.TryGetValue("m_value", out int detailLevel) || detailLevel is < 1 or > 3) continue; + detailCondition = (comparison, detailLevel); + } + var start = Enumerable.Range(0, 3).Select(i => curve.C[i] + curve.T0 * curve.X[i]).ToArray(); + var end = Enumerable.Range(0, 3).Select(i => curve.C[i] + curve.T1 * curve.X[i]).ToArray(); + if (!start.All(IsFinite) || !end.All(IsFinite) || start.SequenceEqual(end)) continue; + alternatives.Add((tag, side, new(start, end, unitAxis, style, detailCondition))); + } + var result = new List(); + foreach (var group in alternatives.GroupBy(item => (item.Tag, item.Line.StyleId))) + { + if (group.OrderBy(item => item.Side).ToArray() is not [{ Side: 6, Line: var a }, { Side: 7, Line: var b }]) continue; + if (a.DetailCondition != b.DetailCondition || !a.Axis.SequenceEqual(b.Axis) + || !SameProjection(a.Start, b.Start, a.Axis, out double startSpacing) + || !SameProjection(a.End, b.End, a.Axis, out double endSpacing) + || Math.Abs(startSpacing - endSpacing) > 1e-9) continue; + var reverse = a.Axis.Select(value => -value).ToArray(); + result.Add(a with { Axis = startSpacing >= 0 ? reverse : a.Axis }); + result.Add(b with { Axis = startSpacing >= 0 ? a.Axis : reverse }); + } + return result.Count == 0 ? null : result; + + static bool SameProjection(double[] a, double[] b, double[] axis, out double spacing) + { + double x = a[0] - b[0], y = a[1] - b[1], z = a[2] - b[2]; + spacing = x * axis[0] + y * axis[1] + z * axis[2]; + return Math.Abs(x - spacing * axis[0]) <= 1e-9 && Math.Abs(y - spacing * axis[1]) <= 1e-9 + && Math.Abs(z - spacing * axis[2]) <= 1e-9; + } + } + /// /// Plausibility gate for the 3x3 part of a serialized GInstance placement (InstanceInfo.m_Trf), /// which also rejects a misparsed record. @@ -2214,7 +2617,8 @@ private static void ReadScalar(Cur c, TfBlockDeserializer.TfField f, int depth) case 0x04: { int value = c.U32(); - bool captureModelCondition = c.CurrentObjectClass is 1999 or 2002; + bool captureModelCondition = c.CurrentObjectClass is 1999 or 2002 + || c.RootClass == 2007 && (c.CurrentObjectClass is 1995 or 1996) && f.Name == "m_comp"; if (c.CurrentQueueIndex >= 0 && ((c.Debug && c.CurrentObjectClass is >= 1992 and <= 2015) || captureModelCondition)) @@ -2229,7 +2633,11 @@ private static void ReadScalar(Cur c, TfBlockDeserializer.TfField f, int depth) case 0x07: { double value = c.F64(); - if (c.Debug && c.CurrentQueueIndex >= 0 && c.CurrentObjectClass is >= 1992 and <= 2003) + if (c.CurrentQueueIndex >= 0 && (c.Debug && c.CurrentObjectClass is >= 1992 and <= 2003 + || c.RootClass == 2007 && c.CurrentObjectClass == 1995 + && f.Name is "m_dir" or "m_rangeLo" or "m_rangeHi" + || c.CurrentObjectClass == 1996 && f.Name == "m_dir" + && c.QueueInts.GetValueOrDefault(c.CurrentQueueIndex)?.GetValueOrDefault("m_comp") is 6 or 7 or 8)) { if (!c.QueueDoubles.TryGetValue(c.CurrentQueueIndex, out var values)) c.QueueDoubles[c.CurrentQueueIndex] = values = new(); @@ -2314,7 +2722,9 @@ private static void Enqueue(Cur c, ushort cls, int handle, string field) int childIndex = c.Queue.Count; c.Queue.Add((cls, handle)); c.QueueLinks.Add((c.CurrentQueueIndex, field)); - if (c.CurrentQueueIndex >= 0 && (c.Debug || field == "m_oConditions")) + if (c.CurrentQueueIndex >= 0 && (c.Debug || field == "m_oConditions" + || c.RootClass == 2007 && !c.IncludeNonVisible && field == "m_subNodes" + && c.CurrentObjectClass == 2015 && c.QueueLinks[c.CurrentQueueIndex] == (-1, "m_subNodes"))) { if (!c.QueueChildren.TryGetValue(c.CurrentQueueIndex, out var children)) c.QueueChildren[c.CurrentQueueIndex] = children = new(); @@ -2750,6 +3160,10 @@ void AddFractions(double start, double end, // and a node it does not take is marked with a negative id (the faces stay in the geometry // for every other consumer): see ResolveGeometryNodes. var geometryNodeByFace = ResolveGeometryNodes(c.Queue, c.QueueLinks, c.ObjectGInfo, c.IncludeNonVisible); + var excludedFromTopPlan = c.RootClass == 2007 && c.Pos == c.End + ? geometryNodeByFace.Values.Select(owner => owner.Node).Where(node => node != 0) + .Distinct().Where(node => ExcludesTopPlan(c, Math.Abs(node) - 1)).ToHashSet() + : []; foreach (uint handle in inactiveBodyFaceHandles) { if (!c.DirectSurfaceByFace.TryGetValue(handle, out var surface) || surface.Kind == SurfKind.Unknown @@ -2830,9 +3244,11 @@ void AddFace(uint handle, GRepFace face) face = boundedFace with { SourceFace = handle, GeometryNode = faceNode, + ExcludedFromTopPlan = excludedFromTopPlan.Contains(faceNode), NodeOrder = faceNode != 0 ? nodeOrders.GetValueOrDefault(Math.Abs(faceNode) - 1) : 0, GeometryStyle = faceStyle, GInfoFlags = c.ObjectGInfo.TryGetValue((int)handle, out var faceGInfo) ? faceGInfo.Flags : null, + ModelPattern = PlacedFacePattern(c, handle), MeshEdgeBounds = meshEdgeBounds.GetValueOrDefault(handle), // (the circular Edges of the loops the face was built from; the others are // leftovers of an earlier state of the join) @@ -3801,6 +4217,7 @@ private static int AppendPolyMeshes(GRepData target, Cur c) Origin = vertices[0], XVector = normal, RenderStyleId = meshMaterial, + PolygonMesh = true, }); AddEdge(a, b); AddEdge(b, d); diff --git a/src/RvtIO/Parsing/NativeFieldParameters.cs b/src/RvtIO/Parsing/NativeFieldParameters.cs index 05962e36..5d2154a5 100644 --- a/src/RvtIO/Parsing/NativeFieldParameters.cs +++ b/src/RvtIO/Parsing/NativeFieldParameters.cs @@ -369,7 +369,10 @@ internal static class NativeFieldParameters new(-1006630, StorageType.Integer, "3703:m_showArrowheadToCutMark", ["3703"], null), // Show Arrowhead to Cut Mark new(-1006625, StorageType.Double, "3703:m_distanceToCutMark", ["3703"], null), // Distance to Cut Mark new(-1006623, StorageType.ElementId, "3703:m_arrowheadTypeId", ["3703"], null), // Arrowhead Type + new(-1006621, StorageType.Double, "974:m_cutMarkSymbolSize", ["974"], null), // Cut Mark Symbol Size new(-1006620, StorageType.Integer, "974:m_cutLineType", ["974"], null), // Cut Line Type + new(-1006619, StorageType.Double, "974:m_rotationAngle", ["974"], null), // Cut Line Angle + new(-1006618, StorageType.Double, "974:m_extensionDistanceToBoundary", ["974"], null), // Cut Line Extension new(-1006616, StorageType.Integer, "974:m_cutMarkSymbol", ["974"], null), // Cut Mark Symbol new(-1006525, StorageType.String, "174:m_prefix", ["174/-2000150", "174/None"], null), // Dimension Prefix new(-1006523, StorageType.Integer, "174:m_interiorTickMarkDisplay", ["174/-2000150", "174/None"], null), // Interior Tick Mark Display diff --git a/src/RvtIO/Parsing/PartitionFraming.cs b/src/RvtIO/Parsing/PartitionFraming.cs index 3a01bb8c..820c9df5 100644 --- a/src/RvtIO/Parsing/PartitionFraming.cs +++ b/src/RvtIO/Parsing/PartitionFraming.cs @@ -41,6 +41,7 @@ internal static class PartitionFraming internal sealed record Framed(IReadOnlyList Segments, List Items, int IdWidth, int? Partition = null) { private long[]? starts; + internal List<(string Key, ProjectItem Item)>? FamilyAnnotationItems { get; init; } /// Where the bytes of the item are: in its segment when it lies in one, else in a copy (an item can run into the next segment /// of its chain); Copied tells which. diff --git a/src/RvtIO/Parsing/TfBlockDeserializer.BreakLine.cs b/src/RvtIO/Parsing/TfBlockDeserializer.BreakLine.cs new file mode 100644 index 00000000..ef7228d4 --- /dev/null +++ b/src/RvtIO/Parsing/TfBlockDeserializer.BreakLine.cs @@ -0,0 +1,32 @@ +namespace RvtIO.Parsing; + +internal static partial class TfBlockDeserializer +{ + private const int BreakReferenceCount = 20; + + internal sealed record BreakLineProfile(IReadOnlyList<(double X, double Y)> Line, double MaskY); + + // The computed M_Break Line symbol's reference faces carry the stretched extents and the + // reference planes for the six vertices. The profile is used only for that family. + internal static BreakLineProfile? ReadBreakReferencePlanes(ReadOnlySpan data) + { + const int planeSize = 105; + if (data.Length < BreakReferenceCount * planeSize) return null; + Span x = stackalloc double[BreakReferenceCount]; + Span y = stackalloc double[BreakReferenceCount]; + for (int i = 0; i < BreakReferenceCount; i++) + { + var plane = data.Slice(i * planeSize, planeSize); + if (plane[32] != 1) return null; + x[i] = BitConverter.ToDouble(plane[33..]); + y[i] = BitConverter.ToDouble(plane[41..]); + if (!(Math.Abs(x[i]) < 1000 && Math.Abs(y[i]) < 1000 + && Math.Abs(BitConverter.ToDouble(plane[49..])) < 1e-7)) return null; + } + if (!(x[0] < x[14] && x[14] < x[19] && x[19] < 0 + && 0 < x[18] && x[18] < x[15] && x[15] < x[2])) return null; + if (!(Math.Abs(y[9]) < 1e-7 && Math.Abs(y[16] + y[17]) < 1e-7 + && Math.Abs(y[16]) > 1e-7 && Math.Abs(y[13]) > Math.Abs(y[16]))) return null; + return new([(x[0], 0), (x[14], 0), (x[19], y[16]), (x[18], y[17]), (x[15], 0), (x[2], 0)], y[13]); + } +} diff --git a/src/RvtIO/Parsing/TfBlockDeserializer.DatumExtents.cs b/src/RvtIO/Parsing/TfBlockDeserializer.DatumExtents.cs new file mode 100644 index 00000000..17e574ea --- /dev/null +++ b/src/RvtIO/Parsing/TfBlockDeserializer.DatumExtents.cs @@ -0,0 +1,218 @@ +namespace RvtIO.Parsing; + +internal static partial class TfBlockDeserializer +{ + internal sealed record DatumLeader(double[] End, double[] Elbow, double[] Anchor); + internal sealed record DatumExtent(double FreeEnd, double BubbleEnd, byte Overrides, DatumLeader? BubbleLeader, + double? FreeEnd3d = null, double? BubbleEnd3d = null, DatumLeader? FreeEndLeader = null); + internal sealed record ViewDatumExtents(int ViewId, double[] Normal, Dictionary Datums, + IReadOnlyDictionary? Sections = null); + internal sealed record SectionTraceExtent(double Start, double End, int SegmentCount); + internal sealed record DatumHead(int SymbolId, int GridBubblePosition, double? EndSegmentLength = null, + bool? BubbleAtEnd1 = null, bool? BubbleAtEnd2 = null); + + internal static DatumHead? ExtractDatumHead(byte[] data, int start, uint size, ushort classId) + { + if (classId is not (2109 or 2301) || start < 0 || size > int.MaxValue + || (long)start + 16 + size > data.Length || size < 6 + || BitConverter.ToUInt32(data, start + 8) != size + || BitConverter.ToUInt16(data, start + 12) != classId) return null; + int end = start + 12 + (int)size; + if (BitConverter.ToUInt32(data, end) != size) return null; + var fields = SerializationFields(classId); + if (fields == null || !HasExactSchemaField(fields, classId, "m_familyTagId", 14, 0, 20)) return null; + var cursor = new Cursor { D = data, Pos = start + 14, End = end, RootClassId = classId }; + var queue = new List<(ushort Cls, uint Id)>(); + int owner = -1, symbol = -1, position = -1; + double? endLength = null; + bool? end1 = null, end2 = null; + try + { + foreach (var field in fields) + { + if (field is { Declaring: 37, Name: "m_id", Type: 14, Mods: 0, Ref: 20 }) owner = ReadI32(cursor); + else if (field.Declaring == classId && field is { Name: "m_familyTagId", Type: 14, Mods: 0, Ref: 20 }) + symbol = ReadI32(cursor); + else if (field is { Declaring: 2109, Name: "m_bubbleLocInElev", Type: 4, Mods: 0 }) + position = ReadI32(cursor); + else if (field is { Declaring: 2109, Name: "m_endSegmentsLength", Type: 7, Mods: 0 }) + endLength = ReadF64(cursor); + else if (field is { Declaring: 2109, Name: "m_bubbleAtEnd1" or "m_bubbleAtEnd2", Type: 1, Mods: 0 }) + { + if (!TryReadFlag(cursor, field, out bool visible)) throw Fail; + if (field.Name == "m_bubbleAtEnd1") end1 = visible; + else end2 = visible; + } + else ReadField(cursor, field, queue, 0, null); + } + } + catch (DecodeFail) { return null; } + return owner > 0 && (uint)owner == BitConverter.ToUInt32(data, start) && symbol > 0 + ? new DatumHead(symbol, position, endLength, end1, end2) : null; + } + + internal static ViewDatumExtents? ExtractViewDatumExtents(byte[] data, int start, uint size, ushort classId) + { + const ushort extentElement = 1471, datumRecord = 1054, leaderRecord = 622, sectionRecord = 886; + if (classId != extentElement || start < 0 || size > int.MaxValue + || (long)start + 16 + size > data.Length || size < 6 + || BitConverter.ToUInt32(data, start + 8) != size + || BitConverter.ToUInt16(data, start + 12) != classId) return null; + int end = start + 12 + (int)size; + if (BitConverter.ToUInt32(data, end) != size) return null; + + var fields = SerializationFields(classId); + if (fields == null || !HasExactSchemaField(fields, extentElement, "m_idExtents", 14, 80, null) + || !HasExactSchemaField(fields, extentElement, "m_dbViewId", 14, 0, 20) + || !HasExactSchemaField(fields, 37, "m_id", 14, 0, 20)) return null; + var cursor = new Cursor { D = data, Pos = start + 14, End = end, RootClassId = classId }; + var queue = new List<(ushort Cls, uint Id)>(); + var datumIndices = new Dictionary(); + var sectionIndices = new Dictionary(); + var sections = new Dictionary(); + var leaders = new Dictionary(); + var records = new Dictionary(); + double[]? normal = null; + int viewId = -1, owner = -1; + try + { + foreach (var field in fields) + { + if (field is { Declaring: 37, Name: "m_id" }) owner = ReadI32(cursor); + else if (field is { Declaring: extentElement, Name: "m_dbViewId" }) viewId = ReadI32(cursor); + else if (field is { Declaring: extentElement, Name: "m_dbViewNorm", Type: 7, Mods: 16, Cnt: 3 }) + normal = ReadPoint(); + else if (field is { Declaring: extentElement, Name: "m_idExtents" }) + { + uint count = ReadU32(cursor); + if (count > 10_000) return null; + for (int i = 0; i < count; i++) + { + int datumId = ReadI32(cursor); + int index = queue.Count; + ReadPoly(cursor, queue); + if (queue.Count != index + 1) continue; + if (queue[index].Cls == datumRecord) datumIndices.Add(index, datumId); + if (queue[index].Cls == sectionRecord) sectionIndices.Add(index, datumId); + } + } + else ReadField(cursor, field, queue, 0, null); + } + if (owner <= 0 || (uint)owner != BitConverter.ToUInt32(data, start) + || viewId <= 0 || normal == null || !normal.All(double.IsFinite) + || (datumIndices.Count == 0 && sectionIndices.Count == 0)) return null; + + for (int i = 0; i < queue.Count; i++) + { + if (datumIndices.TryGetValue(i, out int id)) + { + double free = double.NaN, bubble = double.NaN; + double? free3d = null, bubble3d = null; + byte overrides = 0; + int recordViewId = -1; + bool supported = true; + foreach (var field in SerializationFields(datumRecord) ?? throw Fail) + { + if (field is { Name: "m_freeEnd", Type: 7, Mods: 0 }) free = ReadF64(cursor); + else if (field is { Name: "m_bubbleEnd", Type: 7, Mods: 0 }) bubble = ReadF64(cursor); + else if (field is { Name: "m_freeEnd3d", Type: 7, Mods: 0 }) free3d = ReadF64(cursor); + else if (field is { Name: "m_bubbleEnd3d", Type: 7, Mods: 0 }) bubble3d = ReadF64(cursor); + else if (field is { Name: "m_dbViewId", Type: 14, Mods: 0, Ref: 20 }) recordViewId = ReadI32(cursor); + else if (field is { Name: "m_endBubbleOverrides", Type: 2, Mods: 0 }) + { + if (!cursor.Take(1)) throw Fail; + overrides = data[cursor.Pos - 1]; + } + else if (field is { Name: "m_pLeader" or "m_pFreeEndLeader" }) + { + int index = queue.Count; + uint pointer = ReadPoly(cursor, queue); + if (pointer == 0) continue; + if (queue.Count == index + 1 && queue[index].Cls == leaderRecord) + leaders.Add(index, (id, field.Name == "m_pFreeEndLeader")); + else supported = false; + } + else ReadField(cursor, field, queue, 1, null); + } + if (supported && id > 0 && (recordViewId == -1 || recordViewId == viewId) + && double.IsFinite(free) && double.IsFinite(bubble) + && !records.TryAdd(id, new DatumExtent(free, bubble, overrides, null, free3d, bubble3d))) return null; + } + else if (leaders.TryGetValue(i, out var ownership)) + { + double[]? tip = null, elbow = null, anchor = null; + foreach (var field in SerializationFields(leaderRecord) ?? throw Fail) + { + if (field is { Name: "m_end", Type: 7, Mods: 16, Cnt: 3 }) tip = ReadPoint(); + else if (field is { Name: "m_elbow", Type: 7, Mods: 16, Cnt: 3 }) elbow = ReadPoint(); + else if (field is { Name: "m_anchor", Type: 7, Mods: 16, Cnt: 3 }) anchor = ReadPoint(); + else ReadField(cursor, field, queue, 1, null); + } + if (tip == null || elbow == null || anchor == null + || !tip.All(double.IsFinite) || !elbow.All(double.IsFinite) || !anchor.All(double.IsFinite)) return null; + if (records.TryGetValue(ownership.DatumId, out var record)) + { + var leader = new DatumLeader(tip, elbow, anchor); + records[ownership.DatumId] = ownership.FreeEnd + ? record with { FreeEndLeader = leader } : record with { BubbleLeader = leader }; + } + } + else if (queue[i].Cls == sectionRecord) + { + uint segments = 0; + bool continuous = true, hideLine = true; + double startExtent = double.NaN, endExtent = double.NaN; + double startUncropped = double.NaN, endUncropped = double.NaN; + int head = 0, tail = 0; + foreach (var field in SerializationFields(sectionRecord) ?? throw Fail) + { + if (field is { Name: "m_endVisLengths", Type: 13, Mods: 80 }) + { + segments = ReadU32(cursor); + if (segments == uint.MaxValue) segments = 0; + if (segments > 10_000) throw Fail; + for (int segment = 0; segment < segments; segment++) + { + double first = ReadF64(cursor), last = ReadF64(cursor); + continuous &= first == -1 && last == -1; + } + } + else if (field is { Name: "m_horzExtents", Type: 7, Mods: 16, Cnt: 2 }) + { + startUncropped = ReadF64(cursor); + endUncropped = ReadF64(cursor); + } + else if (field is { Name: "m_croppedHorzExtents", Type: 7, Mods: 16, Cnt: 2 }) + { + startExtent = ReadF64(cursor); + endExtent = ReadF64(cursor); + } + else if (field is { Name: "m_end1Mark", Type: 4, Mods: 0 }) head = ReadI32(cursor); + else if (field is { Name: "m_end2Mark", Type: 4, Mods: 0 }) tail = ReadI32(cursor); + else if (field is { Name: "m_hideLine", Type: 1, Mods: 0 }) + { + if (!TryReadFlag(cursor, field, out hideLine)) throw Fail; + } + else ReadField(cursor, field, queue, 1, null); + } + // A straight trace can supply only the first cropped endpoint. Use its saved uncut + // end when the second cropped coordinate is zero and the two start coordinates agree. + if (segments == 1 && startExtent == startUncropped && endExtent == 0 && startExtent >= endExtent) + endExtent = endUncropped; + // Continuous traces with the head on the first leg and the tail on the last. + if (sectionIndices.TryGetValue(i, out int sectionId) && sectionId > 0 + && continuous && !hideLine && head == 1 && tail == 2 && segments > 0 + && double.IsFinite(startExtent) && double.IsFinite(endExtent) && startExtent < endExtent + && !sections.TryAdd(sectionId, new SectionTraceExtent(startExtent, endExtent, (int)segments))) + return null; + } + else SkipQueuedObjects(cursor, queue, i + 1, i); + } + } + catch (DecodeFail) { return null; } + return cursor.Pos == end && (records.Count > 0 || sections.Count > 0) + ? new ViewDatumExtents(viewId, normal, records, sections) : null; + + double[] ReadPoint() => [ReadF64(cursor), ReadF64(cursor), ReadF64(cursor)]; + } +} diff --git a/src/RvtIO/Parsing/TfBlockDeserializer.PlanDimensions.cs b/src/RvtIO/Parsing/TfBlockDeserializer.PlanDimensions.cs new file mode 100644 index 00000000..46fad3f8 --- /dev/null +++ b/src/RvtIO/Parsing/TfBlockDeserializer.PlanDimensions.cs @@ -0,0 +1,22 @@ +namespace RvtIO.Parsing; + +internal static partial class TfBlockDeserializer +{ + private static double[] ReadStoredPoint(Cursor cursor) => [ReadF64(cursor), ReadF64(cursor), ReadF64(cursor)]; + + private static (double[] Origin, double[] Direction)? ReadDimensionLine(Cursor cursor, + IReadOnlyList fields, List<(ushort, uint)> queue) + { + double[]? origin = null, direction = null; + foreach (var field in fields) + { + if (field is { Declaring: 1736, Name: "m_origin", Type: 7, Mods: 16, Cnt: 3 }) + origin = ReadStoredPoint(cursor); + else if (field is { Declaring: 1736, Name: "m_dirVec", Type: 7, Mods: 16, Cnt: 3 }) + direction = ReadStoredPoint(cursor); + else + ReadField(cursor, field, queue, 1, null); + } + return origin != null && direction != null ? (origin, direction) : null; + } +} diff --git a/src/RvtIO/Parsing/TfBlockDeserializer.PlanFurniture.cs b/src/RvtIO/Parsing/TfBlockDeserializer.PlanFurniture.cs new file mode 100644 index 00000000..91667c2c --- /dev/null +++ b/src/RvtIO/Parsing/TfBlockDeserializer.PlanFurniture.cs @@ -0,0 +1,13 @@ +namespace RvtIO.Parsing; + +internal static partial class TfBlockDeserializer +{ + private static HashSet ReadViewIdSet(Cursor cursor) + { + int count = ReadI32(cursor); + if (count is < -1 or > 1_000_000 || count * 4L > cursor.End - cursor.Pos) throw Fail; + var hidden = new HashSet(); + for (int i = 0; i < count; i++) hidden.Add(ReadI32(cursor)); + return hidden; + } +} diff --git a/src/RvtIO/Parsing/TfBlockDeserializer.PlanNotes.cs b/src/RvtIO/Parsing/TfBlockDeserializer.PlanNotes.cs new file mode 100644 index 00000000..0527280a --- /dev/null +++ b/src/RvtIO/Parsing/TfBlockDeserializer.PlanNotes.cs @@ -0,0 +1,37 @@ +namespace RvtIO.Parsing; + +internal static partial class TfBlockDeserializer +{ + internal sealed record PlanNoteLeader(double[] End, double[] Elbow, double[] Anchor); + + private static (string Text, double? FontSizePoints)? ReadPlanNoteRtf(Cursor cursor, + IReadOnlyList fields) + { + if (fields is not [{ Declaring: 3487, Name: "m_arrRtfStream", Type: 2, Mods: 80 }]) throw Fail; + int count = ReadI32(cursor); + if (count is -1 or 0) return null; + int start = cursor.Pos; + if (count is < 0 or > 1_048_576 || !cursor.Take(count)) throw Fail; + return RtfText.Parse(cursor.D, start, cursor.Pos); + } + + private static PlanNoteLeader? ReadPlanNoteLeader(Cursor cursor, IReadOnlyList fields, + List<(ushort, uint)> queue) + { + double[]? end = null, elbow = null, anchor = null; + int type = -1; + foreach (var field in fields) + { + if (field is { Declaring: 622, Name: "m_end", Type: 7, Mods: 16, Cnt: 3 }) end = ReadStoredPoint(cursor); + else if (field is { Declaring: 622, Name: "m_elbow", Type: 7, Mods: 16, Cnt: 3 }) elbow = ReadStoredPoint(cursor); + else if (field is { Declaring: 622, Name: "m_anchor", Type: 7, Mods: 16, Cnt: 3 }) anchor = ReadStoredPoint(cursor); + else if (field is { Declaring: 622, Name: "m_type", Type: 4, Mods: 0 }) type = ReadI32(cursor); + else ReadField(cursor, field, queue, 1, null); + } + return type == 1 && end != null && elbow != null && anchor != null + && ValidPoint(end) && ValidPoint(elbow) && ValidPoint(anchor) + ? new(end, elbow, anchor) : null; + + static bool ValidPoint(double[] point) => point.All(value => Math.Abs(value) < 1_000_000); + } +} diff --git a/src/RvtIO/Parsing/TfBlockDeserializer.PlanRoomTags.cs b/src/RvtIO/Parsing/TfBlockDeserializer.PlanRoomTags.cs new file mode 100644 index 00000000..710cb759 --- /dev/null +++ b/src/RvtIO/Parsing/TfBlockDeserializer.PlanRoomTags.cs @@ -0,0 +1,94 @@ +namespace RvtIO.Parsing; + +internal static partial class TfBlockDeserializer +{ + internal sealed record FamilyAnnotationArc(double X, double Y, double Radius, double Start, double End, int StyleId); + + internal static (TitleBlockLine? Line, FamilyAnnotationArc? Arc, bool TypeDependent, int SketchId)? + ReadFamilyAnnotationCurve(byte[] data, int start, uint size) + { + var fields = SerializationFields(838); + if (fields == null || size < 6 || start < 0 || (long)start + size + 16 > data.Length + || BitConverter.ToUInt16(data, start + 12) != 838 + || BitConverter.ToUInt32(data, start + 12 + (int)size) != size) return null; + var queue = new List<(ushort Cls, uint Id)>(); + var cursor = new Cursor + { + D = data, Pos = start + 14, End = start + 12 + (int)size, RootClassId = 838, TailWalk = true, RootQueue = queue + }; + int driver = -1, curve = -1, sketch = -1; + try + { + foreach (var field in fields) + { + int next = queue.Count; + ReadField(cursor, field, queue, 0, null); + if (field is { Declaring: 838, Name: "m_pCurveDriver", Type: 14, Mods: 2 } + && queue.Count == next + 1 && queue[next].Cls == 929) + driver = next; + } + if (driver < 0) return null; + for (int i = 0; i < queue.Count; i++) + { + if (i == curve) + { + bool typeDependent = queue.Any(entry => entry.Cls == 1806); + if (queue[i].Cls == 1974) + return ReadFamilyAnnotationArc(cursor) is { } arc ? (null, arc, typeDependent, sketch) : null; + if (!TryReadGLine(cursor, queue, i, out var line) || (line.Flags & 0x20) != 0) return null; + double x0 = line.Ox + line.T0 * line.Dx, y0 = line.Oy + line.T0 * line.Dy; + double x1 = line.Ox + line.T1 * line.Dx, y1 = line.Oy + line.T1 * line.Dy; + if (x0 == x1 && y0 == y1 + || !(Math.Abs(line.Oz + line.T0 * line.Dz) < 1e-8 + && Math.Abs(line.Oz + line.T1 * line.Dz) < 1e-8)) return null; + return Math.Abs(x0) < 1 && Math.Abs(x1) < 1 && Math.Abs(y0) < 1 && Math.Abs(y1) < 1 + ? (new(x0, y0, x1, y1, line.CategoryId), null, typeDependent, sketch) : null; + } + cursor.TailClassId = queue[i].Cls; + foreach (var field in SerializationFields(queue[i].Cls) ?? throw Fail) + { + int next = queue.Count; + if (queue[i].Cls == 3606 && field is { Declaring: 422, Name: "m_groupId", Type: 14, Mods: 0, Ref: 20 }) + sketch = ReadI32(cursor); + else ReadField(cursor, field, queue, 1, null); + if (i == driver && field is { Declaring: 87, Name: "m_pCrv" } + && queue.Count == next + 1 && queue[next].Cls is 1736 or 1974) + curve = next; + } + } + } + catch (DecodeFail) { return null; } + return null; + } + + private static FamilyAnnotationArc? ReadFamilyAnnotationArc(Cursor cursor) + { + if (SerializationFields(1974) is not { Count: 7 } fields + || fields[0] is not { Declaring: 1246, Name: "m_GInfo", Type: 14, Mods: 0 } + || fields[1] is not { Declaring: 1737, Name: "m_endParams", Type: 7, Mods: 16, Cnt: 2 } + || fields[2] is not { Declaring: 1974, Name: "m_xVec", Type: 7, Mods: 16, Cnt: 3 } + || fields[3] is not { Declaring: 1974, Name: "m_yVec", Type: 7, Mods: 16, Cnt: 3 } + || fields[4] is not { Declaring: 1974, Name: "m_radius", Type: 7, Mods: 0 } + || fields[5] is not { Declaring: 1974, Name: "m_center", Type: 7, Mods: 16, Cnt: 3 } + || fields[6] is not { Declaring: 1974, Name: "m_bFilled", Type: 1, Mods: 0 } + || !cursor.Take(8)) return null; + int styleId = ReadI32(cursor); + uint flags = ReadU32(cursor); + double start = ReadF64(cursor), end = ReadF64(cursor); + double xx = ReadF64(cursor), xy = ReadF64(cursor), xz = ReadF64(cursor); + double yx = ReadF64(cursor), yy = ReadF64(cursor), yz = ReadF64(cursor); + double radius = ReadF64(cursor); + double x = ReadF64(cursor), y = ReadF64(cursor), z = ReadF64(cursor); + if (!cursor.Take(1) || cursor.D[cursor.Pos - 1] != 0 || (flags & 0x20) != 0 + || !(radius is > 0 and < 1) || !(Math.Abs(x) < 1 && Math.Abs(y) < 1) + || z != 0 || xz != 0 || yz != 0 + || !(Math.Abs(xx * xx + xy * xy - 1) < 1e-8 && Math.Abs(yx * yx + yy * yy - 1) < 1e-8 + && Math.Abs(xx * yx + xy * yy) < 1e-8) + || !double.IsFinite(start) || !double.IsFinite(end) || !(end - start is >= 0 and <= 2 * Math.PI + 1e-8)) + return null; + if (start == end) end = start + 2 * Math.PI; + double angle = Math.Atan2(xy, xx), sign = Math.Sign(xx * yy - xy * yx); + return new(x, y, radius, (angle + sign * start) * (180 / Math.PI), + (angle + sign * end) * (180 / Math.PI), styleId); + } +} diff --git a/src/RvtIO/Parsing/TfBlockDeserializer.RoomColors.cs b/src/RvtIO/Parsing/TfBlockDeserializer.RoomColors.cs new file mode 100644 index 00000000..f5f7c84e --- /dev/null +++ b/src/RvtIO/Parsing/TfBlockDeserializer.RoomColors.cs @@ -0,0 +1,31 @@ +namespace RvtIO.Parsing; + +internal static partial class TfBlockDeserializer +{ + internal sealed record RoomColorEntry(string Name, uint Color, int PatternId); + + private static List ReadRoomColorEntries(Cursor cursor) + { + uint count = ReadU32(cursor); + var colors = new List(); + if (count == uint.MaxValue) return colors; + if (count > 10_000) throw Fail; + for (uint i = 0; i < count; i++) + { + ReadString(cursor); // Caption is independent of the value used to select a room. + string name = ReadString(cursor); + ReadF64(cursor); + ReadI32(cursor); // ElementId and integer storage slots. + ReadI32(cursor); + int storage = ReadI32(cursor); + uint color = ReadU32(cursor); + int pattern = ReadI32(cursor); + if (!cursor.Take(6)) throw Fail; + var flags = cursor.D.AsSpan(cursor.Pos - 6, 6); + if (storage == 3 && name.Length > 0 && color <= 0xFFFFFF + && flags[0] == 0 && flags[3] == 0 && flags[5] == 0) + colors.Add(new RoomColorEntry(name, color, pattern)); + } + return colors; + } +} diff --git a/src/RvtIO/Parsing/TfBlockDeserializer.ScheduleRows.cs b/src/RvtIO/Parsing/TfBlockDeserializer.ScheduleRows.cs new file mode 100644 index 00000000..2ef9df73 --- /dev/null +++ b/src/RvtIO/Parsing/TfBlockDeserializer.ScheduleRows.cs @@ -0,0 +1,43 @@ +namespace RvtIO.Parsing; + +internal static partial class TfBlockDeserializer +{ + internal sealed class ScheduleRowBindings + { + public readonly Dictionary Fields = new(); + public readonly Dictionary Sorts = new(); + public readonly Dictionary Filters = new(); + public List FieldIds = new(), FieldObjects = new(), SortObjects = new(), FilterObjects = new(); + public bool Itemized, InitialSpacer, Unsupported; + } + + private static bool ReadScheduleBindingField(ScheduleRowBindings bindings, Cursor cur, TfField field, List<(ushort, uint)> queue) + { + switch (field.Name) + { + case "m_pFields": bindings.FieldObjects = Pointers(); return true; + case "m_sortFieldArr": bindings.SortObjects = Pointers(); return true; + case "m_filterArr": bindings.FilterObjects = Pointers(); return true; + case "m_fieldIds": + uint count = ReadU32(cur); + if (count != uint.MaxValue) + { + if (count > 100_000) throw Fail; + for (uint i = 0; i < count; i++) bindings.FieldIds.Add(ReadI32(cur)); + } + return true; + case "m_bInstanceSchedule": bindings.Itemized = Flag(); return true; + case "m_showInitialSpacer": bindings.InitialSpacer = Flag(); return true; + case "m_bRefTable" or "m_bMaterialSchedule" or "m_bFilterBySheet" or "m_bIncludeLinkedFiles" + or "m_showGrandTotal" or "m_isEmbedded": + bindings.Unsupported |= Flag(); + return true; + default: return false; + } + + List Pointers() => TryReadPtrArray(cur, queue, field with { Mods = 1 }, out var indices, out _) + ? indices : throw Fail; + + bool Flag() => TryReadFlag(cur, field, out bool value) ? value : throw Fail; + } +} diff --git a/src/RvtIO/Parsing/TfBlockDeserializer.SiteContours.cs b/src/RvtIO/Parsing/TfBlockDeserializer.SiteContours.cs new file mode 100644 index 00000000..e7a3ee93 --- /dev/null +++ b/src/RvtIO/Parsing/TfBlockDeserializer.SiteContours.cs @@ -0,0 +1,88 @@ +namespace RvtIO.Parsing; + +internal static partial class TfBlockDeserializer +{ + internal sealed record SiteContour(double Elevation, bool Primary, List> Lines); + internal sealed record SiteContourLabelData(int SurfaceId, double[][] Positions, double[][] Directions); + + private static SiteContourLabelData? ReadSiteContourLabels(Cursor cursor, List fields, + List<(ushort, uint)> queue) + { + if (fields is not + [{ Name: "m_oAssocPropData" }, { Name: "m_textPos", Type: 13, Mods: 80 }, + { Name: "m_textDir", Type: 13, Mods: 80 }, { Name: "m_textDirPerp", Type: 13, Mods: 80 }, + { Name: "m_surfId", Type: 14, Mods: 0, Ref: 20 }, { Name: "m_curveStatus", Type: 4, Mods: 0 }, + { Name: "m_makePrimaryOnly", Type: 1, Mods: 0 }]) throw Fail; + + ReadField(cursor, fields[0], queue, 1, null); + var positions = Points(); + var directions = Points(); + var perpendiculars = Points(); + int surface = ReadI32(cursor), status = ReadI32(cursor); + if (!cursor.Take(1)) throw Fail; + return status == 0 && surface > 0 && positions.Length == directions.Length + && positions.Length == perpendiculars.Length ? new(surface, positions, directions) : null; + + double[][] Points() + { + uint count = ReadU32(cursor); + if (count == uint.MaxValue) return []; + if (count > 100_000 || count > (cursor.End - cursor.Pos) / 24) throw Fail; + var points = new double[count][]; + for (int i = 0; i < points.Length; i++) + { + points[i] = [ReadF64(cursor), ReadF64(cursor), ReadF64(cursor)]; + if (points[i].Any(value => !(Math.Abs(value) < 1_000_000))) throw Fail; + } + return points; + } + } + + private static List ReadSiteContours(Cursor cursor) + { + // ContourManager owns an inline map of elevations to polyline wrappers and facet indices. + if (SerializationFields(845) is not + [{ Name: "first", Type: 7, Mods: 0 }, { Name: "second", Type: 14, Mods: 0 }] + || SerializationFields(846) is not + [{ Name: "m_arr", Type: 14, Mods: 80 }, { Name: "m_facets", Type: 4, Mods: 80 }, + { Name: "m_isPrimary", Type: 1, Mods: 0 }] + || SerializationFields(847) is not [{ Name: "m_arr", Type: 13, Mods: 80 }]) + throw Fail; + uint count = Count(cursor, 10_000); + var result = new List((int)count); + for (uint i = 0; i < count; i++) + { + double level = ReadF64(cursor); + if (!double.IsFinite(level)) throw Fail; + uint lines = Count(cursor, 100_000); + var curves = new List>((int)lines); + for (uint j = 0; j < lines; j++) + { + uint points = Count(cursor, 100_000); + if (points > (cursor.End - cursor.Pos) / 24) throw Fail; + var vertices = new List<(double X, double Y)>((int)points); + for (uint k = 0; k < points; k++) + { + double x = ReadF64(cursor), y = ReadF64(cursor), z = ReadF64(cursor); + if (!(Math.Abs(x) < 1_000_000 && Math.Abs(y) < 1_000_000 && Math.Abs(z - level) < 1e-6)) + throw Fail; + vertices.Add((x, y)); + } + if (vertices.Count > 1) curves.Add(vertices); + } + uint facets = Count(cursor, 1_000_000); + if (!cursor.Take((int)facets * 4) || cursor.Pos == cursor.End) throw Fail; + byte primary = cursor.D[cursor.Pos++]; + if (primary > 1) throw Fail; + result.Add(new(level, primary == 1, curves)); + } + return result; + + static uint Count(Cursor cursor, uint limit) + { + uint count = ReadU32(cursor); + if (count == uint.MaxValue) return 0; + return count <= limit ? count : throw Fail; + } + } +} diff --git a/src/RvtIO/Parsing/TfBlockDeserializer.SiteProperty.cs b/src/RvtIO/Parsing/TfBlockDeserializer.SiteProperty.cs new file mode 100644 index 00000000..4ac62ed2 --- /dev/null +++ b/src/RvtIO/Parsing/TfBlockDeserializer.SiteProperty.cs @@ -0,0 +1,46 @@ +namespace RvtIO.Parsing; + +internal static partial class TfBlockDeserializer +{ + private static List<(double X, double Y)> ReadSitePropertyCurve(Cursor cur, ushort classId, + out (double X, double Y)? arcCenter) + { + arcCenter = null; + if (!cur.Take(16)) throw Fail; // Inline GInfo in the property segment's own curve. + double start = ReadF64(cur), end = ReadF64(cur); + if (!double.IsFinite(start) || !double.IsFinite(end) || start == end) throw Fail; + if (classId == 1736) + { + var origin = ReadPoint(); + var direction = ReadPoint(); + return [PointAt(start), PointAt(end)]; + + (double X, double Y) PointAt(double t) => (origin.X + t * direction.X, origin.Y + t * direction.Y); + } + + var xAxis = ReadPoint(); + var yAxis = ReadPoint(); + double radius = ReadF64(cur); + var center = ReadPoint(); + double sweep = end - start; + if (!cur.Take(1) || !(radius is > 0 and < 1_000_000) || Math.Abs(sweep) > 2 * Math.PI + 1e-7) + throw Fail; + if (xAxis.Z == 0 && yAxis.Z == 0) arcCenter = (center.X, center.Y); + int segments = (int)Math.Ceiling(Math.Abs(sweep) * 60 / Math.PI); + var points = new List<(double X, double Y)>(segments + 1); + for (int i = 0; i <= segments; i++) + { + double t = start + sweep * i / segments; + double cos = radius * Math.Cos(t), sin = radius * Math.Sin(t); + points.Add((center.X + cos * xAxis.X + sin * yAxis.X, center.Y + cos * xAxis.Y + sin * yAxis.Y)); + } + return points; + + (double X, double Y, double Z) ReadPoint() + { + double x = ReadF64(cur), y = ReadF64(cur), z = ReadF64(cur); + if (!(Math.Abs(x) < 1_000_000 && Math.Abs(y) < 1_000_000 && Math.Abs(z) < 1_000_000)) throw Fail; + return (x, y, z); + } + } +} diff --git a/src/RvtIO/Parsing/TfBlockDeserializer.StairRuns.cs b/src/RvtIO/Parsing/TfBlockDeserializer.StairRuns.cs index cba92601..fee46f6c 100644 --- a/src/RvtIO/Parsing/TfBlockDeserializer.StairRuns.cs +++ b/src/RvtIO/Parsing/TfBlockDeserializer.StairRuns.cs @@ -9,7 +9,10 @@ internal enum StairRunStyle { Sketched = 2, Straight = 3, Spiral = 4 } internal sealed record StairRunNumbers(double BottomElevation, double TopElevation, double ActualRunWidth, int BaseRiserIndex, int TopRiserIndex, int BeginWithRiser = -1, int EndWithRiser = -1); internal sealed record StairRunInput(int OwnerId, int StairsId, StairRunStyle Style, - StairPathDirection[] Directions, StairRunNumbers? Numbers = null); + StairPathDirection[] Directions, StairRunNumbers? Numbers = null, StairPlanInput? Plan = null); + internal readonly record struct StairPlanLine(double X1, double Y1, double X2, double Y2, double Elevation); + internal sealed record StairPlanInput(StairPlanLine[] Treads, StairPlanLine[] Left, StairPlanLine[] Right, + StairPlanLine[] Center); /// Own R22 StairsRun graph, exact FIFO and footer. getRunType checks the own CellList run cell; /// getStairsPath2D uses m_oRefCurvesArr[0], not the cell's base lines. Only Straight/Sketched runs and @@ -20,13 +23,15 @@ internal sealed record StairRunInput(int OwnerId, int StairsId, StairRunStyle St var cursor = new Cursor { D = data, Pos = start + 14, End = checked((int)((long)start + 12 + size)), RootClassId = classId }; var queue = new List<(ushort Cls, uint Id)>(); int cellList = -1, cachedLoop = -1, cell = -1, stairId = 0; - int[]? cachedCurves = null; + int[]? cachedCurves = null, outlineLoops = null; + int firstTread = -1, pastLastTread = -1; + var planLoops = new Dictionary(); double bottom = double.NaN, top = double.NaN, width = double.NaN; int baseIndex = int.MinValue, topIndex = int.MinValue; int beginRiser = -1, endRiser = -1; var directions = new Dictionary(); - var finiteOrigins = new HashSet(); - var boundedLines = new HashSet(); + var origins = new Dictionary(); + var bounds = new Dictionary(); try { foreach (var field in SerializationFields(classId) ?? throw Fail) @@ -79,7 +84,15 @@ internal sealed record StairRunInput(int OwnerId, int StairsId, StairRunStyle St || BitConverter.ToUInt16(data, position + 8) != 938 || queue.Count <= before || queue[before].Cls != 938) throw Fail; cachedLoop = before; + // The two projected open side paths follow the ten path/riser reference groups. + if (BitConverter.ToUInt32(data, position) == 12 && queue.Count - before == 12 + && queue.Skip(before).All(item => item.Cls == 938)) + outlineLoops = [before + 10, before + 11]; } + if (field is { Declaring: 3708, Name: "m_orderedNosingFront", Type: 14, Mods: 81, Ref: null } + && queue.Count > before && BitConverter.ToUInt32(data, position) == queue.Count - before + && queue.Skip(before).All(item => item.Cls == 938)) + (firstTread, pastLastTread) = (before, queue.Count); if (queue.Count > 100_000) throw Fail; } if (cellList < 0 || cachedLoop < 0 || stairId <= 0 || stairId == owner) throw Fail; @@ -140,6 +153,12 @@ internal sealed record StairRunInput(int OwnerId, int StairsId, StairRunStyle St cachedCurves = Enumerable.Range(before, queue.Count - before).ToArray(); if (cachedCurves.Any(i => queue[i].Cls is not (1736 or 1974))) throw Fail; } + if (sourceField is { Declaring: 938, Name: "m_curves", Type: 14, Mods: 81, Ref: null } + && (index == cachedLoop || outlineLoops?.Contains(index) == true + || index >= firstTread && index < pastLastTread) + && queue.Count > before && BitConverter.ToUInt32(data, position) == queue.Count - before + && queue.Skip(before).All(item => item.Cls == 1736)) + planLoops.Add(index, Enumerable.Range(before, queue.Count - before).ToArray()); if (cls == 1736 && sourceField is { Declaring: 1736, Name: "m_dirVec", Type: 7, Mods: 16, Cnt: 3 }) { var direction = new StairPathDirection(BitConverter.ToDouble(data, position), @@ -148,28 +167,64 @@ internal sealed record StairRunInput(int OwnerId, int StairsId, StairRunStyle St } if (cls == 1736 && sourceField is { Declaring: 1736, Name: "m_origin", Type: 7, Mods: 16, Cnt: 3 } && Enumerable.Range(0, 3).All(i => double.IsFinite(BitConverter.ToDouble(data, position + i * 8)))) - finiteOrigins.Add(index); + origins.Add(index, new(BitConverter.ToDouble(data, position), + BitConverter.ToDouble(data, position + 8), BitConverter.ToDouble(data, position + 16))); if (cls == 1736 && sourceField is { Declaring: 1737, Name: "m_endParams", Type: 7, Mods: 16, Cnt: 2 }) { double first = BitConverter.ToDouble(data, position), last = BitConverter.ToDouble(data, position + 8); - if (double.IsFinite(first) && double.IsFinite(last) && first < last) boundedLines.Add(index); + if (double.IsFinite(first) && double.IsFinite(last) && first < last) bounds.Add(index, (first, last)); } } } // A spiral run has arcs for a base line and no direction and stops the walk early; every other style needs bounded horizontal lines and the exact footer. bool spiral = cell >= 0 && queue[cell].Cls == 3723; if (cell < 0 || cachedCurves == null || !spiral && cursor.Pos != cursor.End - || !spiral && cachedCurves.Any(i => !directions.ContainsKey(i) || !finiteOrigins.Contains(i) || !boundedLines.Contains(i))) throw Fail; + || !spiral && cachedCurves.Any(i => !directions.ContainsKey(i) || !origins.ContainsKey(i) || !bounds.ContainsKey(i))) throw Fail; StairPathDirection[] path = spiral ? [] : cachedCurves.Select(i => directions[i]).ToArray(); if (path.Any(direction => !double.IsFinite(direction.X) || !double.IsFinite(direction.Y) || direction.Z != 0 || direction.X == 0 && direction.Y == 0)) throw Fail; var numbers = double.IsFinite(bottom) && double.IsFinite(top) && double.IsFinite(width) && baseIndex != int.MinValue && topIndex != int.MinValue ? new StairRunNumbers(bottom, top, width, baseIndex, topIndex, beginRiser, endRiser) : null; + StairPlanInput? plan = null; + if (!spiral && outlineLoops is [int left, int right] && pastLastTread - firstTread > 1 + && ReadPlanLines([left]) is { } leftSide && ReadPlanLines([right]) is { } rightSide) + { + int[] treadLoops = Enumerable.Range(firstTread, pastLastTread - firstTread).ToArray(); + if (treadLoops.All(loop => planLoops.TryGetValue(loop, out var lines) && lines.Length == 1) + && ReadPlanLines(treadLoops) is { } treads) + plan = new(treads, leftSide, rightSide, ReadPlanLines([cachedLoop]) ?? []); + } return new(owner, stairId, queue[cell].Cls switch { 3725 => StairRunStyle.Straight, 3723 => StairRunStyle.Spiral, _ => StairRunStyle.Sketched }, - path, numbers); + path, numbers, plan); } catch (DecodeFail) { return null; } catch (OverflowException) { return null; } + + StairPlanLine[]? ReadPlanLines(int[] loops) + { + var lines = new List(); + foreach (int loop in loops) + { + if (!planLoops.TryGetValue(loop, out var indices)) return null; + foreach (int index in indices) + { + if (ReadPlanLine(index) is not { } line) return null; + lines.Add(line); + } + } + return lines.ToArray(); + } + + StairPlanLine? ReadPlanLine(int index) + { + if (!origins.TryGetValue(index, out var p) || !directions.TryGetValue(index, out var v) + || v.Z != 0 || !bounds.TryGetValue(index, out var t)) return null; + var line = new StairPlanLine(p.X + t.First * v.X, p.Y + t.First * v.Y, + p.X + t.Last * v.X, p.Y + t.Last * v.Y, p.Z); + return double.IsFinite(line.X1) && double.IsFinite(line.Y1) + && double.IsFinite(line.X2) && double.IsFinite(line.Y2) + && (line.X1 != line.X2 || line.Y1 != line.Y2) ? line : null; + } } } diff --git a/src/RvtIO/Parsing/TfBlockDeserializer.UnitOptions.cs b/src/RvtIO/Parsing/TfBlockDeserializer.UnitOptions.cs index f3314180..6694f934 100644 --- a/src/RvtIO/Parsing/TfBlockDeserializer.UnitOptions.cs +++ b/src/RvtIO/Parsing/TfBlockDeserializer.UnitOptions.cs @@ -74,29 +74,12 @@ internal static bool TryReadUnitOptions(byte[] data, int start, int end, out int if (count > 100_000 || count * 30L + 16 > end - position) return false; var options = new UnitFormatOption[(int)count]; var specs = new HashSet(StringComparer.Ordinal); - bool ReadId(out string value) - { - value = ""; - if (position > end - 4) return false; - uint length = BitConverter.ToUInt32(data, position); position += 4; - if (length > 10_000 || length * 2L > end - position) return false; - try { value = UnitIdUtf16.GetString(data, position, (int)length * 2); } - catch (DecoderFallbackException) { return false; } - position += (int)length * 2; - return true; - } for (int index = 0; index < options.Length; index++) { - if (!ReadId(out string spec) || !ReadId(out string symbol) || !ReadId(out string unit) - || !specs.Add(spec) || position > end - 18) return false; - double accuracy = BitConverter.ToDouble(data, position); - if (!double.IsFinite(accuracy) || accuracy < 0) return false; - for (int flag = 12; flag < 18; flag++) - if (data[position + flag] > 1) return false; - options[index] = new(spec, symbol, unit, accuracy, BitConverter.ToInt32(data, position + 8), - data[position + 12], data[position + 13], data[position + 14], - data[position + 15], data[position + 16], data[position + 17]); - position += 18; + if (!ReadUnitId(data, ref position, end, out string spec) + || !specs.Add(spec) + || ReadUnitFormatOption(data, ref position, end, spec) is not { } option) return false; + options[index] = option; } if (position > end - 16) return false; units = new(options, BitConverter.ToInt32(data, position), BitConverter.ToInt32(data, position + 4), @@ -105,6 +88,33 @@ bool ReadId(out string value) return true; } + private static bool ReadUnitId(byte[] data, ref int position, int end, out string value) + { + value = ""; + if (position > end - 4) return false; + uint length = BitConverter.ToUInt32(data, position); position += 4; + if (length > 10_000 || length * 2L > end - position) return false; + try { value = UnitIdUtf16.GetString(data, position, (int)length * 2); } + catch (DecoderFallbackException) { return false; } + position += (int)length * 2; + return true; + } + + private static UnitFormatOption? ReadUnitFormatOption(byte[] data, ref int position, int end, string spec) + { + if (!ReadUnitId(data, ref position, end, out string symbol) + || !ReadUnitId(data, ref position, end, out string unit) || position > end - 18) return null; + double accuracy = BitConverter.ToDouble(data, position); + if (!double.IsFinite(accuracy) || accuracy < 0) return null; + for (int flag = 12; flag < 18; flag++) + if (data[position + flag] > 1) return null; + var option = new UnitFormatOption(spec, symbol, unit, accuracy, BitConverter.ToInt32(data, position + 8), + data[position + 12], data[position + 13], data[position + 14], + data[position + 15], data[position + 16], data[position + 17]); + position += 18; + return option; + } + private static bool UnitOptionSchemasMatch() { if (!Schemas.TryGetValue(4029, out var element) || element.Name != "UnitsElem" || element.Base != 37 diff --git a/src/RvtIO/Parsing/TfBlockDeserializer.cs b/src/RvtIO/Parsing/TfBlockDeserializer.cs index f8c58955..b186c33c 100644 --- a/src/RvtIO/Parsing/TfBlockDeserializer.cs +++ b/src/RvtIO/Parsing/TfBlockDeserializer.cs @@ -1,4 +1,5 @@ using System.Text.Json; +using RvtIO.BuiltIns; using RvtIO.Internal; using RvtIO.Model; @@ -37,6 +38,21 @@ internal sealed class NativeParams public bool RootParameterStoresComplete { get; set; } /// Class tags of the cells of the element's CellList, when the deferred walk reached that object. public List? CellClasses { get; set; } + internal BreakLineProfile? DetailBreak { get; set; } + internal IReadOnlyList<(double X, double Y)>? SitePropertyCurve { get; set; } + internal (double X, double Y)? SitePropertyArcCenter { get; set; } + internal List? RoomColors { get; set; } + internal List? DimensionReferences { get; set; } + internal List? DimensionValues { get; set; } + internal (double[] Origin, double[] Direction)? DimensionLine { get; set; } + internal (string Text, double? FontSizePoints)? PlanNoteText { get; set; } + internal List? PlanNoteLeaders { get; set; } + internal HashSet? ViewHiddenElements { get; set; } + internal HashSet? ViewHiddenCategories { get; set; } + internal ViewModelBounds? ModelClipBox { get; set; } + internal double[]? SunStudyOutline { get; set; } + internal List? SiteContours { get; set; } + internal SiteContourLabelData? SiteContourLabels { get; set; } /// The deferred walk consumed every queued object of the record (so the NamedParams and cells are complete). public bool TailWalkComplete { get; set; } public List<(int ParamId, double Value)> Doubles { get; } = new(); @@ -58,7 +74,7 @@ internal sealed class NativeParams public double[]? PlanViewRangeOffsets { get; set; } public int[]? PlanViewRangeLevelIds { get; set; } public int Count => Doubles.Count + Ints.Count + Strings.Count + ElementIds.Count - + Fields.Count + DoubleFields.Count + StringFields.Count; + + Fields.Count + DoubleFields.Count + StringFields.Count + (SitePropertyCurve == null ? 0 : 1); } /// One NamedParam of FamilyParams.m_params. Which of Value/ElemId/Int/Str is meaningful depends on the @@ -230,6 +246,7 @@ private static void DiagNoteQueued(List<(ushort, uint)> queue) "602:m_idSystemCategory", "602:m_iEndReference", "602:m_idLevelStart", "602:m_pCurveDriver", "602:m_pConnectorManager", "527:m_leader", "527:m_leaderEndCondition", "527:m_tagRelOffsetCondition", "527:m_isRelPosValid", "527:m_hideTagIn3DView", "527:m_oTagOrientationCell", "527:m_symbolId", "527:m_taggedEntitiesCell", "527:m_multiReferenceAnnotationId", + "3936:m_isStraightLeader", "3936:m_needReconcile", "1990:m_dbViewId", "1990:m_dbDrawingId", "1990:m_viewportOrientation", "1990:m_clipping", "1990:m_detailNumber", ]; @@ -303,6 +320,49 @@ private static void DiagNoteQueued(List<(ushort, uint)> queue) "37:m_cellList", // HVAC zones: the default zone flag of a ZoneElement and the zone of a space (RoomElem). "4215:m_bDefault", "3471:m_zoneElementId", + "2239:m_width", "2239:m_scale", "2239:m_mirrored", + "2202:m_widthInFeet", "2202:m_heightInFeet", "2197:m_dWidthScale", "2197:m_dHeightScale", + "2202:m_idImageHolder", + "689:m_origin@0", "689:m_origin@1", "689:m_idSchemeCategory", + "697:m_swatchWidth", "697:m_swatchHeight", + "690:m_categoryId", "690:m_paramId", "690:m_bByRange", "693:m_bBackground", + "174:m_tickCategoryId", "174:m_dimensionStyleType", "174:m_linearDimType", + "174:m_textAlignment", "174:m_textLoc", "174:m_alternateUnits", "174:m_dimWitnCntrlExtBelow", + "174:m_arrowHeadStyleId", "174:m_interiorTickMarkStyleId", "174:m_prefix", "174:m_suffix", + "2295:m_tickType", "625:m_fontId", "625:m_categoryId", "1923:m_size", "1923:m_name", "84:m_bUseDefault", + "3702:m_stairsPathOffset", "3703:m_startFromRiser", "3703:m_endAtRiser", "3703:m_startSymbolTypeId", + "160:m_flags", "160:m_useEqualityFormula", "160:m_showLabelGP", "159:m_multiReferenceAnnotationId", + "3928:m_orig@0", "3928:m_orig@1", "3928:m_baseVec@0", "3928:m_baseVec@1", + "3928:m_upVec@0", "3928:m_upVec@1", "3928:m_flags", "3928:m_attrId", "3928:m_height", + "3928:m_lineWidth", "3928:m_bNoWrapping", "3931:m_leaderOffsetSheet", "3931:m_textBoxVisibility", + "625:m_background", "3971:m_bArcLeaders", + "625:m_bBold", "625:m_bItalic", "625:m_bUnderline", + "836:m_baseElevation", + "1861:m_sketchId", "1860:m_bMasking", "1862:m_fillPatternElemId", "1862:m_backgroundPatternElemId", + "621:m_bAnnotationCropActive", "334:m_leftRightTopBottomOffsets@0", "334:m_leftRightTopBottomOffsets@1", + "334:m_leftRightTopBottomOffsets@2", "334:m_leftRightTopBottomOffsets@3", + "2247:m_pos@0", "2247:m_pos@1", "2247:m_symbolId", "2248:m_parentId", + "621:m_dbViewId", "621:m_projMethodType", "4122:m_modelClipBoxId", "2505:m_viewer3dId", + "2249:m_coarserScale", "1020:m_elevatnAttrId", + "2251:m_elevationSymbolId", "2251:m_shape", "2251:m_ahAngleDouble", "2251:m_ahFilled", + "1763:first", "1724:m_masterSymId", + "4108:m_surfaces", "4108:m_transparency", "4108:m_edges", "4108:m_bShowSurfacePatterns", + "4107:m_hlr", "4107:m_lighting", + "4103:m_type", "4103:m_backgroundColor", "4103:m_skyColor", "4103:m_groundColor", + "4110:m_ambientShadows", "4110:m_castShadows", "4106:m_ambientLightIntensity", + "4106:m_sunlightIntensity", "4106:m_shadowIntensity", "4106:m_sunAndShadowSettingsId", + "3878:m_dAzimuth", "3878:m_dAltitude", "3878:m_type", "3878:m_idLevel", + "3878:m_bGroundPlane", "3878:m_bRelativeToView", + "3878:m_idAnnotation", "3878:m_sunPathSize", "3878:m_startDateTime", "3878:m_endDateTime", + "3878:m_activeFrame", "3878:m_eSunStudyTimeInterval", "3878:m_sunriseToSunset", + "108:m_bCustomScaleName", "108:m_strCustomScaleName", + "3475:m_symbolId", "3475:m_bLeader", "3475:m_bLeaderIsStraight", + "3475:m_leaderAnchor@0", "3475:m_leaderAnchor@1", + "3475:m_tagOffset@0", "3475:m_tagOffset@1", + "3934:m_headLocation@0", "3934:m_headLocation@1", "3934:m_rotationAngle", + "3934:m_orientation", "3934:m_isSpatialElementTag", + "2479:m_bUseRenderAppearance", + "3546:m_sectionHeadFamilyTagId", "3546:m_sectionTailFamilyTagId", .. RoomRuleFieldKeys, .. ListFactFieldKeys, ]; @@ -388,7 +448,7 @@ private static void MergeKeyed(NativeParams from, NativeParams into) { "m_scale", "m_topRailHeight", // GeoSite (project location symbol): latitude / longitude in radians. - "m_dLatitude", "m_dLongitude", + "m_dLatitude", "m_dLongitude", "m_dTimeZone", }; /// String schema fields captured into StringFields. @@ -592,6 +652,11 @@ private sealed class DecodeFail : Exception { } var queue = new List<(ushort Cls, uint Id)>(); cur.RootQueue = queue; var res = new NativeParams(); + int breakFaces = -1, breakPlanes = -1; + int propertyCurve = -1, dimensionLine = -1, linearFormat = -1; + int noteRtf = -1, noteLeaderStart = -1, noteLeaderEnd = -1; + int viewHiddenElements = -1, viewHiddenCategories = -1, viewDisplay = -1, planRange = -1; + int contourLabels = -1; if (CaptureAllFields) { diagRootQueue = queue; @@ -599,7 +664,61 @@ private sealed class DecodeFail : Exception { } } try { - foreach (var f in fields) ReadField(cur, f, queue, 0, res); + foreach (var f in fields) + { + int next = queue.Count; + if (classId is 986 or 1005 or 1016 + && f is { Declaring: 108, Name: "m_explicitlyHiddenElements", Type: 14, Mods: 80, Ref: 20 }) + res.ViewHiddenElements = ReadViewIdSet(cur); + else + ReadField(cur, f, queue, 0, res); + if (classId == 1829 && f is { Declaring: 1829, Name: "m_refFaces", Type: 14, Mods: 81 } + && queue.Count - next == BreakReferenceCount + && queue.Skip(next).All(entry => entry.Cls == 1589)) + breakFaces = next; + if (classId == 3070 && f is { Declaring: 3070, Name: "m_curve", Type: 14, Mods: 1 } + && queue.Count == next + 1 && queue[next].Cls is 1736 or 1974) + propertyCurve = next; + if (classId == 837 && f is { Declaring: 838, Name: "m_data" } + && next < queue.Count && queue[next].Cls == 840) + contourLabels = next; + if (classId == 2335 && f is { Declaring: 158, Name: "m_pDimLine", Type: 14, Mods: 2 } + && queue.Count == next + 1 && queue[next].Cls == 1736) + dimensionLine = next; + if (classId == 174 && f is { Declaring: 174, Name: "m_oLinFormatOptions", Type: 14, Mods: 2 } + && queue.Count == next + 1 && queue[next].Cls == 84) + linearFormat = next; + if (classId is 3971 or 3927 && f is { Declaring: 3928, Name: "m_oSavedRtfData", Type: 14, Mods: 1 } + && queue.Count == next + 1 && queue[next].Cls == 3487) + noteRtf = next; + if (classId == 3971 && f is { Declaring: 3971, Name: "m_leaders", Type: 14, Mods: 81 } + && queue.Count > next && queue.Skip(next).All(entry => entry.Cls == 622)) + { + noteLeaderStart = next; + noteLeaderEnd = queue.Count; + } + if (classId is 986 or 1005 or 1016 && queue.Count == next + 1) + { + if (f is { Declaring: 108, Name: "m_oHiddenElementsViewSettings" } + && queue[next].Cls == 2160) + viewHiddenElements = next; + if (f is { Declaring: 108, Name: "m_pViewDisplayMgr" } && queue[next].Cls == 4107) + viewDisplay = next; + if (f is { Declaring: 1005, Name: "m_pPlanViewRange2", Type: 14, Mods: 2 } + && queue[next].Cls == 2974) + planRange = next; + } + if (classId is 986 or 1005 or 1016 + && f is { Declaring: 108, Name: "m_oaDrawFilters", Type: 14, Mods: 81 }) + { + for (int i = next; i < queue.Count; i++) + if (queue[i].Cls == 2190) + { + viewHiddenCategories = i; + break; + } + } + } } catch (DecodeFail) { @@ -673,7 +792,71 @@ private sealed class DecodeFail : Exception { } walked?.Append(queue[qi].Cls).Append("<").Append(origin).Append("@").Append(cur.Pos).Append(qf == null ? "!," : ","); if (walked != null && WalkHexClasses.Contains(queue[qi].Cls)) walked.Append("[").Append(Convert.ToHexString(cur.D, cur.Pos, Math.Min(800, cur.End - cur.Pos))).Append("]"); if (qf == null) break; - if (queue[qi].Cls == 2974) + if (qi == breakPlanes) + res.DetailBreak = ReadBreakReferencePlanes(cur.D.AsSpan(cur.Pos, cur.End - cur.Pos)); + if (qi == propertyCurve) + { + res.SitePropertyCurve = ReadSitePropertyCurve(cur, queue[qi].Cls, out var center); + res.SitePropertyArcCenter = center; + continue; + } + if (qi == contourLabels) + { + res.SiteContourLabels = ReadSiteContourLabels(cur, qf, queue); + continue; + } + if (qi == viewDisplay) + { + if (!TryReadViewDisplayMgr(cur, queue, out _, tail)) throw Fail; + continue; + } + if (qi == viewHiddenElements) + { + foreach (var field in qf) + { + if (field is { Declaring: 2160, Name: "m_hiddenElements", Type: 14, Mods: 80, Ref: 20 }) + (res.ViewHiddenElements ??= []).UnionWith(ReadViewIdSet(cur)); + else + ReadField(cur, field, queue, 1, null); + } + continue; + } + if (qi == viewHiddenCategories) + { + foreach (var field in qf) + { + if (field is { Declaring: 2190, Name: "m_categoryIds", Type: 14, Mods: 80, Ref: 20 }) + res.ViewHiddenCategories = ReadViewIdSet(cur); + else + ReadField(cur, field, queue, 1, null); + } + continue; + } + if (qi == noteRtf) + { + res.PlanNoteText = ReadPlanNoteRtf(cur, qf); + continue; + } + if (qi >= noteLeaderStart && qi < noteLeaderEnd) + { + if (ReadPlanNoteLeader(cur, qf, queue) is { } leader) + (res.PlanNoteLeaders ??= new()).Add(leader); + continue; + } + if (qi == dimensionLine) + { + res.DimensionLine = ReadDimensionLine(cur, qf, queue); + continue; + } + if (qi == linearFormat) + { + var format = new NativeParams(); + foreach (var field in qf) ReadField(cur, field, queue, 1, format); + if (format.Fields.TryGetValue("84:m_bUseDefault", out int useDefault)) + res.Fields["174:linearFormatUsesDefault"] = useDefault; + continue; + } + if (qi == planRange) { // PlanViewRange2: two five-element arrays of the view's own block. Keeping its // offsets and level ids lets a plan decide which elements below the level it shows. @@ -694,8 +877,8 @@ private sealed class DecodeFail : Exception { } } if (offsetCount == 5 && levelCount == 5) { - tail.PlanViewRangeOffsets = offsets; - tail.PlanViewRangeLevelIds = levelIds; + res.PlanViewRangeOffsets = offsets; + res.PlanViewRangeLevelIds = levelIds; } continue; } @@ -731,7 +914,18 @@ private sealed class DecodeFail : Exception { } bool driveSpline = qi == cur.CurveDriverCurveQueueIndex && queue[qi].Cls == 2020; if (driveSpline) cur.HermiteNodes = new List(); int cellsBefore = queue[qi].Cls == 653 ? queue.Count : -1; + int nextObject = queue.Count; foreach (var sf in qf) { lastField = FieldKey(sf) + "/" + sf.Type + "/" + sf.Mods + "/" + sf.Ref; ReadField(cur, sf, queue, 1, tail); } + if (breakFaces >= 0 && qi >= breakFaces && qi < breakFaces + BreakReferenceCount) + { + if (queue.Count != nextObject + 1 || queue[nextObject].Cls != 522 + || (qi != breakFaces && nextObject != breakPlanes + qi - breakFaces)) + { + breakFaces = -1; + breakPlanes = -1; + } + else if (qi == breakFaces) breakPlanes = nextObject; + } if (cellsBefore >= 0 && ReferenceEquals(queue, cur.RootQueue)) tail.CellClasses = queue.Skip(cellsBefore).Select(entry => (int)entry.Item1).ToList(); KeepAnyAttachTop(tail, queue[qi].Cls, attachedTopBefore); @@ -778,6 +972,7 @@ private sealed class DecodeFail : Exception { } if (walked != null) tail.StringFields["walk:"] = walked.ToString() + " queue=" + queue.Count + " rest=" + (cur.End - cur.Pos); res.TailWalkComplete = tailDone; MergeKeyed(tail, res); + res.SiteContours = tail.SiteContours; res.NamedParams.AddRange(tail.NamedParams); if (tail.CellClasses != null) res.CellClasses = tail.CellClasses; } @@ -3426,20 +3621,63 @@ private sealed class StepLayoutSearch catch (DecodeFail) { return null; } } + internal static (double BaseFeet, int MaterialId)? ExtractSiteCutGraphics( + byte[] data, int start, uint size, ushort classId, out (int Method, int Units)? bearing) + { + bearing = null; + const ushort trueNorth = 4007; + if (classId != trueNorth || !HasExactOwnElementRoot(data, start, size, classId)) return null; + var fields = SerializationFields(classId)!; + if (!HasExactSchemaField(fields, 37, "m_famId", 14, 0, 20) + || !HasExactSchemaField(fields, trueNorth, "m_pocheDepth", 7, 0, null) + || !HasExactSchemaField(fields, trueNorth, "m_siteCutMaterialId", 14, 0, 20)) return null; + + var cursor = new Cursor { D = data, Pos = start + 14, End = start + 12 + (int)size }; + var queue = new List<(ushort Cls, uint Id)>(); + double baseFeet = double.NaN; + int materialId = -1, method = -1, units = -1; + try + { + foreach (var field in fields) + { + if (field is { Declaring: 37, Name: "m_famId" }) + { + // Embedded families have their own TrueNorth settings. + if (ReadI32(cursor) != -1) return null; + } + else if (field is { Declaring: trueNorth, Name: "m_pocheDepth" }) + baseFeet = ReadF64(cursor); + else if (field is { Declaring: trueNorth, Name: "m_siteCutMaterialId" }) + materialId = ReadI32(cursor); + else if (field is { Declaring: trueNorth, Name: "m_propertyBearingMethod", Type: 4, Mods: 0 }) + method = ReadI32(cursor); + else if (field is { Declaring: trueNorth, Name: "m_propertyBearingUnits", Type: 4, Mods: 0 }) + units = ReadI32(cursor); + else + ReadField(cursor, field, queue, 0, null); + } + } + catch (DecodeFail) { return null; } + if (method >= 0 && units >= 0) bearing = (method, units); + return double.IsFinite(baseFeet) && materialId > 0 ? (baseFeet, materialId) : null; + } + /// One line family of a fill pattern: its angle (radians), origin, shift (along the line) and /// offset (between lines) in the pattern's own feet, and its repeating dash list (dash, gap, ...; a zero /// dash is a dot). internal sealed record PatternGrid(double Angle, double OriginX, double OriginY, double Shift, double Offset, - double[] Segments); + double[] Segments, int Target = -1, int Orientation = -1); /// Reads a material's cut and surface fill patterns: the MaterialElem root (class 2486) owns one /// deferred Material (class 2479) through m_pMaterial, whose m_cutPatternId and m_surfacePatternId name the /// pattern elements. Both ids are -1 when the material has no pattern of that kind. False when anything /// fails to decode. internal static bool TryExtractMaterialPatterns( - byte[] d, int blockStart, uint dataSize, ushort classId, out int cutPatternId, out int surfacePatternId) + byte[] d, int blockStart, uint dataSize, ushort classId, out int cutPatternId, out int surfacePatternId, + out int? surfacePatternColor) { cutPatternId = surfacePatternId = -1; + surfacePatternColor = null; if (classId != 2486 || blockStart < 0 || dataSize > int.MaxValue @@ -3494,6 +3732,11 @@ internal static bool TryExtractMaterialPatterns( if (field is { Declaring: 2479, Name: "m_surfacePatternId", Type: 14, Mods: 0, Ref: 20 }) { surfacePatternId = ReadI32(cur); + continue; + } + if (field is { Declaring: 2479, Name: "m_surfacePatternColor", Type: 5, Mods: 0 }) + { + surfacePatternColor = ReadI32(cur); return true; } ReadField(cur, field, queue, 1, null); @@ -3520,9 +3763,9 @@ private static void SkipMaterialPathMap(Cursor cur) /// Walks the deferred objects queued before , so the cursor reaches the /// object whose fields the caller wants to read next. Parameter-set stores are read as their own records. - private static void SkipQueuedObjects(Cursor cur, List<(ushort Cls, uint Id)> queue, int stopIndex) + private static void SkipQueuedObjects(Cursor cur, List<(ushort Cls, uint Id)> queue, int stopIndex, int startIndex = 0) { - for (int queueIndex = 0; queueIndex < stopIndex; queueIndex++) + for (int queueIndex = startIndex; queueIndex < stopIndex; queueIndex++) { ushort queuedClass = queue[queueIndex].Cls; if (ParamSetTags.TryGetValue(queuedClass, out var parameterStore)) @@ -3590,14 +3833,16 @@ internal static bool TryExtractFillPattern( if (patternIndex < 0 || !ownOwnerRead) return false; SkipQueuedObjects(cur, queue, patternIndex); - int gridCount = 0; + int gridCount = -1, target = -1, orientation = -1; foreach (var field in patternFields) { if (field is { Declaring: 1849, Name: "m_gridsArr", Type: 14, Mods: 81 }) { - int before = queue.Count; + int start = cur.Pos, before = queue.Count; ReadField(cur, field, queue, 1, null); gridCount = queue.Count - before; + if (cur.Pos - start < 4 || BitConverter.ToUInt32(d, start) != (uint)gridCount) + return false; } else if (field is { Declaring: 1849, Name: "m_name", Type: 8, Mods: 96 }) name = ReadString(cur); @@ -3605,10 +3850,14 @@ internal static bool TryExtractFillPattern( ReadF64(cur); else if (field is { Declaring: 1849, Name: "m_windowSize", Type: 7, Mods: 0 }) ReadF64(cur); + else if (field is { Declaring: 1849, Name: "m_fpTarget", Type: 4, Mods: 0 }) + target = ReadI32(cur); + else if (field is { Declaring: 1849, Name: "m_fpOrientation", Type: 4, Mods: 0 }) + orientation = ReadI32(cur); else ReadField(cur, field, queue, 1, null); } - if (gridCount <= 0) return false; + if (gridCount < 0) return false; // The queued children are read in the stream order the pointers were seen: a CellList may have // queued a PatternHelper before the grids, so skip every non-FillGrid object up to the last grid. @@ -3652,7 +3901,7 @@ internal static bool TryExtractFillPattern( else ReadField(cur, field, queue, 1, null); } - result.Add(new PatternGrid(angle, ox, oy, shift, offset, segments)); + result.Add(new PatternGrid(angle, ox, oy, shift, offset, segments, target, orientation)); } if (result.Count != gridCount) return false; grids = result; @@ -4011,7 +4260,10 @@ internal sealed record TitleBlockText(double Ox, double Oy, double Oz, double Hx /// A label of a title block family symbol, in symbol feet: the anchor, the box, the flags, the base /// direction and the parameter it prints (a BuiltInParameter id) with its prefix, suffix and sample text. internal sealed record TitleBlockLabel(double Ox, double Oy, double Oz, double Hx, double Hy, double Bx, double By, - double Height, double Width, int AttrId, int Flags, int ParamId, string Prefix, string Suffix); + double Height, double Width, int AttrId, int Flags, int ParamId, string Prefix, string Suffix, + UnitFormatOption? SingleParameterFormat = null, bool Wrap = false); + + private sealed record TagLabelParameter(int ParamId, string Prefix, string Suffix, UnitFormatOption? Format); /// A schedule instance placed on a sheet: the DBViewSchedule it shows and its top-left origin in /// sheet feet. @@ -4074,7 +4326,13 @@ internal static bool TryExtractSheetRevisions( /// A body section of a schedule table: its stored header texts (one per visible column, /// empty when the file stores none), the count of leading all-empty body rows and the total body row count. - internal sealed record ScheduleBodySection(List Header, int LeadingEmpty, int BodyRows); + internal sealed record ScheduleBodySection(List Header, int LeadingEmpty, int BodyRows) + { + internal IReadOnlyList? HeaderStyles { get; init; } + internal IReadOnlyList? BodyAlignment { get; init; } + } + internal readonly record struct ScheduleTextStyle(double CapHeightPixels, int HorizontalAlignment, + int VerticalAlignment, string? FontName = null, int Flags = 0); /// A schedule definition decoded from its DBViewSchedule block: the visible columns (heading and width /// in feet, in order), the category id, the show flags, the title height and merged bands of the first shown @@ -4082,21 +4340,30 @@ internal sealed record ScheduleBodySection(List Header, int LeadingEmpty internal sealed record ScheduleTableDef(List<(string Heading, double WidthFt)> Columns, int CategoryId, bool ShowTitle, bool ShowHeaders, bool ShowGridLines, bool ShowOutline, int GridStyleId, int OutlineStyleId, - double TitleHeightFt, List<(double HeightFt, string Text)> TitleBands, List BodySections, - double FixedHeightFt); + double TitleHeightFt, List<(double HeightFt, string Text, ScheduleTextStyle Style)> TitleBands, + List BodySections, + double FixedHeightFt) + { + internal ScheduleRowBindings? RowBindings { get; init; } + internal ScheduleTextStyle TitleStyle { get; init; } + internal (int Header, int Body) TextTypeIds { get; init; } + internal (double Header, double Body)? RevisionCapHeightsFt { get; init; } + } /// A section annotation (class 3545) boiled down to what places its mark on a plan: the parent view /// (a section/elevation view for a callout, -1 for a top-level section), the coarsest scale it shows at, /// and the front-cut polyline in model feet (null when undecodable; the trace the reference draws). - internal sealed record SectionViewdata(int ParentViewId, double CoarserScale, List? FrontCut); + internal sealed record SectionViewdata(int ParentViewId, double CoarserScale, List? FrontCut, + (double Left, double Right, double Top, double Bottom)? AnnotationCrop = null, + double[]? CalloutHead = null, + (double X, double Y)? TraceOrigin = null); internal static bool TryExtractSectionViewdata( byte[] d, int blockStart, uint dataSize, ushort classId, out SectionViewdata viewdata) => TryExtractSectionViewdata(d, blockStart, dataSize, classId, out viewdata, out _); - /// Reads a section annotation (class 3545): the parent view id and the coarsest scale. Stops before - /// the front-cut polyline (a composite the generic walk cannot stride); every earlier field walks generically. - /// False when anything fails to decode. + /// Reads a section annotation (class 3545): the parent view, coarsest scale and, when available, + /// the front cut and annotation crop offsets. False when the parent or scale cannot be read. internal static bool TryExtractSectionViewdata( byte[] d, int blockStart, uint dataSize, ushort classId, out SectionViewdata viewdata, out string failure) { @@ -4130,6 +4397,9 @@ internal static bool TryExtractSectionViewdata( int parentViewId = 0; double coarserScale = 0; bool parentRead = false, coarserRead = false; + (double X, double Y)? traceOrigin = null; + int annotationCropIndex = -1; + bool annotationCropActive = false; foreach (var field in fields) { if (field is { Declaring: 2249, Name: "m_frontCut" }) break; @@ -4141,6 +4411,12 @@ internal static bool TryExtractSectionViewdata( parentViewId = ReadI32(cur); parentRead = true; } + else if (field is { Declaring: 2249, Name: "m_pntForViewData", Type: 7, Mods: 16, Cnt: 3 }) + { + double x = ReadF64(cur), y = ReadF64(cur); + ReadF64(cur); + if (double.IsFinite(x) && double.IsFinite(y)) traceOrigin = (x, y); + } else if (field is { Declaring: 2249, Name: "m_coarserScale" }) { if (field is not { Type: 7, Mods: 0 }) { failure = "coarser-type"; return false; } @@ -4155,11 +4431,17 @@ internal static bool TryExtractSectionViewdata( for (int i = 0; i < 3; i++) ReadF64(cur); if (!cur.Take(72 + 48 + 6 + 1)) throw Fail; } - else if (field.Name == "m_viewerFlags" && field.Type == 3) + else if (field is { Declaring: 621, Name: "m_pAnnotationCropOffsets", Type: 14, Mods: 2 }) { - // A two-byte flags field where the generic single-byte scalar stride would misalign - // the four one-byte flags and the view-layout pointer after it. - if (!cur.Take(2)) throw Fail; + int index = queue.Count; + ReadPtr(cur, queue); + if (queue.Count == index + 1 && queue[index].Cls == 334) + annotationCropIndex = index; + } + else if (field is { Declaring: 621, Name: "m_bAnnotationCropActive", Type: 1, Mods: 0 }) + { + if (!cur.Take(1)) throw Fail; + annotationCropActive = cur.D[cur.Pos - 1] == 1; } else ReadField(cur, field, queue, 0, null); } @@ -4175,7 +4457,12 @@ internal static bool TryExtractSectionViewdata( // The loop stopped at the front-cut polyline: a count-prefixed array of XYZ points in model // feet. A failure here never loses the parent/scale facts above; the mark just falls back // to its straight-line trace. - viewdata = new(parentViewId, coarserScale, TryReadFrontCut(cur)); + var frontCut = TryReadFrontCut(cur); + double[]? calloutHead = null; + var annotationCrop = frontCut != null + ? ReadSectionDecorations(cur, queue, annotationCropActive ? annotationCropIndex : -1, + fields, parentViewId, out calloutHead) : null; + viewdata = new(parentViewId, coarserScale, frontCut, annotationCrop, calloutHead, traceOrigin); return true; } catch (DecodeFail) { failure = $"decodefail pos={cur.Pos}"; return false; } @@ -4190,8 +4477,11 @@ internal static bool TryExtractSectionViewdata( { if (cur.Pos + 4 > cur.End || cur.Pos < 0) return null; uint n = BitConverter.ToUInt32(cur.D, cur.Pos); - if (n == 0xFFFFFFFF) return new List(); - if (n == 0) return new List(); + if (n is 0 or uint.MaxValue) + { + cur.Pos += 4; + return []; + } if (n > 10000 || cur.Pos + 4L + n * 24 > cur.End) return null; cur.Pos += 4; var points = new List((int)n); @@ -4213,6 +4503,53 @@ internal static bool TryExtractSectionViewdata( } } + private static (double Left, double Right, double Top, double Bottom)? ReadSectionDecorations( + Cursor cur, List<(ushort Cls, uint Id)> queue, int index, IReadOnlyList fields, + int parentViewId, out double[]? calloutHead) + { + calloutHead = null; + if (!HasExactSchemaField(fields, 2249, "m_pCreationViewData", 14, 1, null) + || !HasExactSchemaField(fields, 2249, "m_viewDataMapForCallout", 14, 80, null)) return null; + try + { + ReadPtr(cur, queue); + uint count = ReadU32(cur); + if (count == uint.MaxValue) count = 0; + if (count > 10000) return null; + // The map serializes an ElementId followed by an inline CalloutGraphicsViewData. + bool foundParent = false; + double[]? point = null; + for (uint i = 0; i < count; i++) + { + int owner = ReadI32(cur); + int start = cur.Pos; + ReadInlineStruct(cur, 626, queue, 0); + if (owner != parentViewId || owner <= 0) continue; + if (foundParent) return null; + foundParent = true; + // A straight leader uses its head point at the rim of the tag. + if (cur.Pos - start == 153 && cur.D[cur.Pos - 1] == 1 + && SerializationFields(626) is + [{ Name: "m_headPoint", Type: 7, Mods: 16, Cnt: 3 }, _, _]) + { + var head = new[] { BitConverter.ToDouble(cur.D, start), BitConverter.ToDouble(cur.D, start + 8), + BitConverter.ToDouble(cur.D, start + 16) }; + if (head.All(value => Math.Abs(value) < 1_000_000)) point = head; + } + } + calloutHead = point; + if (index < 0 || SerializationFields(334) is not + [{ Name: "m_leftRightTopBottomOffsets", Type: 7, Mods: 16, Cnt: 4 }]) return null; + for (int i = 0; i < index; i++) + ReadInlineStruct(cur, queue[i].Cls, queue, 0); + double left = ReadF64(cur), right = ReadF64(cur), top = ReadF64(cur), bottom = ReadF64(cur); + return Valid(left) && Valid(right) && Valid(top) && Valid(bottom) ? (left, right, top, bottom) : null; + } + catch (DecodeFail) { return null; } + + static bool Valid(double value) => value is >= 0 and < 100; + } + /// Reads a schedule instance (class 3532): the DBViewSchedule it shows and its top-left origin in /// sheet feet. False when anything fails to decode. internal static bool TryExtractScheduleInstance( @@ -4337,13 +4674,18 @@ internal static bool TryExtractScheduleTable( cur.RootQueue = queue; try { + int headerTextTypeId = -1, bodyTextTypeId = -1; try { foreach (var field in fields) { try { - ReadField(cur, field, queue, 0, null); + if (field is { Declaring: 1012, Name: "m_headerTextTypeId", Type: 14, Mods: 0, Ref: 20 }) + headerTextTypeId = ReadI32(cur); + else if (field is { Declaring: 1012, Name: "m_bodyTextTypeId", Type: 14, Mods: 0, Ref: 20 }) + bodyTextTypeId = ReadI32(cur); + else ReadField(cur, field, queue, 0, null); } catch (DecodeFail) { @@ -4366,7 +4708,9 @@ internal static bool TryExtractScheduleTable( var sectionInfos = new List<(int Index, List RowQis, List CellQis, bool Hide)>(); var rowHeights = new Dictionary(); var rowCellQis = new Dictionary>(); - var cellInfos = new Dictionary(); + var cellInfos = new Dictionary(); + var cellStyles = new Dictionary(); + var rowBindings = new ScheduleRowBindings(); double fixedHeightFt = 0; for (int qi = 0; qi < queue.Count; qi++) { @@ -4397,17 +4741,33 @@ internal static bool TryExtractScheduleTable( } if (queuedClass == 3528) { - if (!TryReadScheduleField(cur, queue, out var heading, out var widthFt, out var hidden, out string fieldFailure)) + if (!TryReadScheduleField(cur, queue, out var heading, out var widthFt, out var hidden, + out int parameterId, out int source, out string fieldFailure)) { failure = $"field qi={qi} pos={cur.Pos} {fieldFailure}"; return false; } if (!hidden) columns.Add((heading, widthFt)); + rowBindings.Fields[qi] = (parameterId, hidden, source); + continue; + } + if (queuedClass == 3542) + { + rowBindings.Sorts[qi] = (ReadI32(cur), ReadI32(cur), ReadI32(cur)); + continue; + } + if (queuedClass == 3530) + { + int fieldId = ReadI32(cur), type = ReadI32(cur); + ReadString(cur); // ParamStorage's string slot. + ReadF64(cur); + ReadI32(cur); + rowBindings.Filters[qi] = (fieldId, type, ReadI32(cur), ReadI32(cur)); continue; } if (queuedClass == 3535) { - if (!TryReadScheduleSchemaFlags(cur, queue, out int category, out bool title, out bool headers, out bool grid, out bool outline, out int gridStyle, out int outlineStyle, out string schemaFailure)) + if (!TryReadScheduleSchemaFlags(cur, queue, rowBindings, out int category, out bool title, out bool headers, out bool grid, out bool outline, out int gridStyle, out int outlineStyle, out string schemaFailure)) { failure = $"schema qi={qi} pos={cur.Pos} {schemaFailure}"; return false; @@ -4463,12 +4823,35 @@ internal static bool TryExtractScheduleTable( } if (queuedClass == 3921) { - if (!TryReadScheduleCell(cur, queue, out string cellText, out int cellType, out int coverBottom, out int coverRight, out string cellFailure)) + if (!TryReadScheduleCell(cur, queue, out string cellText, out int cellType, + out int coverBottom, out int coverRight, out int style, out string cellFailure)) { failure = $"tablecell qi={qi} pos={cur.Pos} {cellFailure}"; return false; } - cellInfos[qi] = (cellText, cellType, coverBottom, coverRight); + cellInfos[qi] = (cellText, cellType, coverBottom, coverRight, style); + continue; + } + if (queuedClass == 3922) + { + double size = 0; + int horizontal = -1, vertical = -1, flags = 0; + string? fontName = null; + foreach (var styleField in SerializationFields(queuedClass) ?? throw Fail) + { + if (styleField is { Declaring: 3922, Name: "m_textSize", Type: 7, Mods: 0 }) + size = ReadF64(cur); + else if (styleField is { Declaring: 3922, Name: "m_fontName", Type: 8, Mods: 96 }) + fontName = ReadString(cur); + else if (styleField is { Declaring: 3922, Name: "m_flag", Type: 4, Mods: 0 }) + flags = ReadI32(cur); + else if (styleField is { Declaring: 3922, Name: "m_horizontalAlignment", Type: 5, Mods: 0 }) + horizontal = ReadI32(cur); + else if (styleField is { Declaring: 3922, Name: "m_verticalAlignment", Type: 5, Mods: 0 }) + vertical = ReadI32(cur); + else ReadField(cur, styleField, queue, 1, null); + } + if (size is > 0 and <= 256) cellStyles[qi] = new(size, horizontal, vertical, fontName, flags); continue; } if (queuedClass == 3539) @@ -4524,10 +4907,11 @@ internal static bool TryExtractScheduleTable( failure = $"empty schema={schemaRead} cols={columns.Count} queue={queue.Count}"; return false; } - AssembleScheduleTitleBody(sectionInfos, rowHeights, rowCellQis, cellInfos, - out double titleHeightFt, out List<(double HeightFt, string Text)> titleBands, out List bodySections); + AssembleScheduleTitleBody(sectionInfos, rowHeights, rowCellQis, cellInfos, cellStyles, + out double titleHeightFt, out var titleStyle, out var titleBands, out var bodySections); table = new ScheduleTableDef(columns, categoryId, showTitle, showHeaders, showGridLines, showOutline, - gridStyleId, outlineStyleId, titleHeightFt, titleBands, bodySections, fixedHeightFt); + gridStyleId, outlineStyleId, titleHeightFt, titleBands, bodySections, fixedHeightFt) + { RowBindings = rowBindings, TitleStyle = titleStyle, TextTypeIds = (headerTextTypeId, bodyTextTypeId) }; return true; } catch (DecodeFail) @@ -4545,45 +4929,60 @@ private static void AssembleScheduleTitleBody( List<(int Index, List RowQis, List CellQis, bool Hide)> sectionInfos, Dictionary rowHeights, Dictionary> rowCellQis, - Dictionary cellInfos, - out double titleHeightFt, out List<(double HeightFt, string Text)> titleBands, out List bodySections) + Dictionary cellInfos, + Dictionary cellStyles, + out double titleHeightFt, out ScheduleTextStyle titleStyle, + out List<(double HeightFt, string Text, ScheduleTextStyle Style)> titleBands, out List bodySections) { titleHeightFt = 0; + titleStyle = default; titleBands = new(); bodySections = new(); var shown = sectionInfos.Where(section => !section.Hide).OrderBy(section => section.Index).ToList(); if (shown.Count == 0) return; - var first = shown[0]; + // A hidden title section still owns index zero. The first visible section can be the column header. + var first = shown[0].Index == 0 ? shown[0] : (Index: 0, RowQis: new List(), CellQis: new List(), Hide: true); + if (first.CellQis.Count > 0 && rowCellQis.GetValueOrDefault(first.CellQis[0]) is { Count: > 0 } titleCells + && cellInfos.TryGetValue(titleCells[0], out var titleCell)) + titleStyle = cellStyles.GetValueOrDefault(titleCell.Style); if (first.RowQis.Count > 0 && rowHeights.TryGetValue(first.RowQis[0], out double titleHeight) && titleHeight > 0 && titleHeight <= 10) titleHeightFt = titleHeight; // Later rows of the first section form merged bands: a band extends while its last row's cells // carry a bottom cover into the next row (the How-do-I long-text band spans two stored rows). - var bands = new List<(double HeightFt, string Text)>(); + var bands = new List<(double HeightFt, string Text, ScheduleTextStyle Style)>(); var bandRows = new List(); string bandText = ""; double bandHeight = 0; + ScheduleTextStyle bandStyle = default; for (int i = 1; i < first.RowQis.Count; i++) { int rowQi = first.RowQis[i]; double height = rowHeights.TryGetValue(rowQi, out double h) ? h : 0; - string text = FirstCellText(first, i, rowCellQis, cellInfos); + int cellGroup = first.CellQis[i]; + var cell = rowCellQis.GetValueOrDefault(cellGroup)? + .Select(qi => cellInfos.GetValueOrDefault(qi)).FirstOrDefault(item => !string.IsNullOrEmpty(item.Text)); bool extends = bandRows.Count > 0 && BandExtends(bandRows[^1], first, rowCellQis, cellInfos); if (!extends && bandRows.Count > 0 && bandHeight > 0 && bandHeight <= 20) { - bands.Add((bandHeight, bandText)); + bands.Add((bandHeight, bandText, bandStyle)); bandRows.Clear(); bandText = ""; bandHeight = 0; + bandStyle = default; } bandRows.Add(rowQi); if (height > 0 && height <= 10) bandHeight += height; - if (bandText.Length == 0 && text.Length > 0) bandText = text; + if (bandText.Length == 0 && cell is { Text.Length: > 0 } cellWithText) + { + bandText = cellWithText.Text; + bandStyle = cellStyles.GetValueOrDefault(cellWithText.Style); + } } if (bandRows.Count > 0 && bandHeight > 0 && bandHeight <= 20) - bands.Add((bandHeight, bandText)); + bands.Add((bandHeight, bandText, bandStyle)); titleBands = bands; - foreach (var section in shown.Skip(1)) + foreach (var section in shown.Where(section => section.Index != 0)) { var header = SectionRowTexts(section, 0, rowCellQis, cellInfos); int bodyRows = Math.Max(0, section.RowQis.Count - 1); @@ -4595,13 +4994,35 @@ private static void AssembleScheduleTitleBody( if (SectionRowTexts(section, i, rowCellQis, cellInfos).Any(text => text.Length > 0)) break; leadingEmpty++; } - bodySections.Add(new ScheduleBodySection(header, leadingEmpty, bodyRows)); + ScheduleTextStyle[]? StylesAt(int row) => rowCellQis.TryGetValue(section.CellQis[row], out var cells) + ? cells.Select(cellQi => cellInfos.TryGetValue(cellQi, out var cell) + ? cellStyles.GetValueOrDefault(cell.Style) : default).ToArray() + : null; + var headerStyles = section.CellQis.Count > 0 ? StylesAt(0) : null; + int[]? bodyAlignment = null; + // Evaluated rows can be reordered, so carry an alignment only when all stored data rows agree. + for (int row = 1 + leadingEmpty; row < section.CellQis.Count; row++) + { + if (StylesAt(row) is not { Length: > 0 } styles || styles.Length != header.Count) + { + bodyAlignment = null; + break; + } + if (bodyAlignment == null) + bodyAlignment = styles.Select(style => style.CapHeightPixels > 0 ? style.HorizontalAlignment : -1).ToArray(); + else + for (int col = 0; col < styles.Length; col++) + if (styles[col].CapHeightPixels <= 0 || styles[col].HorizontalAlignment != bodyAlignment[col]) + bodyAlignment[col] = -1; + } + bodySections.Add(new ScheduleBodySection(header, leadingEmpty, bodyRows) + { HeaderStyles = headerStyles, BodyAlignment = bodyAlignment }); } } private static List SectionRowTexts((int Index, List RowQis, List CellQis, bool Hide) section, int rowPos, Dictionary> rowCellQis, - Dictionary cellInfos) + Dictionary cellInfos) { var texts = new List(); if (rowPos < 0 || rowPos >= section.CellQis.Count) return texts; @@ -4617,18 +5038,9 @@ private static List SectionRowTexts((int Index, List RowQis, List RowQis, List CellQis, bool Hide) section, int rowPos, - Dictionary> rowCellQis, - Dictionary cellInfos) - { - foreach (string text in SectionRowTexts(section, rowPos, rowCellQis, cellInfos)) - if (text.Length > 0) return text; - return ""; - } - private static bool BandExtends(int rowQi, (int Index, List RowQis, List CellQis, bool Hide) section, Dictionary> rowCellQis, - Dictionary cellInfos) + Dictionary cellInfos) { int pos = section.RowQis.IndexOf(rowQi); if (pos < 0 || pos >= section.CellQis.Count) return false; @@ -4638,11 +5050,12 @@ private static bool BandExtends(int rowQi, (int Index, List RowQis, List queue, - out string heading, out double widthFt, out bool hidden, out string failure) + out string heading, out double widthFt, out bool hidden, out int parameterId, out int source, out string failure) { heading = ""; widthFt = 0; hidden = false; + parameterId = source = 0; failure = "ok"; var fieldFields = SerializationFields(3528); if (fieldFields == null) { failure = "no-schema-3528"; return false; } @@ -4669,6 +5082,8 @@ private static bool TryReadScheduleField(Cursor cur, List<(ushort, uint)> queue, cur.Pos++; hiddenRead = true; } + else if (field is { Declaring: 3528, Name: "m_paramElemId" }) parameterId = ReadI32(cur); + else if (field is { Declaring: 3528, Name: "m_sourceType" }) source = ReadI32(cur); else ReadField(cur, field, queue, 1, null); } if (!headRead || !widthRead || !hiddenRead) { failure = "missing-schedule-field"; return false; } @@ -4676,7 +5091,7 @@ private static bool TryReadScheduleField(Cursor cur, List<(ushort, uint)> queue, return true; } - private static bool TryReadScheduleSchemaFlags(Cursor cur, List<(ushort, uint)> queue, + private static bool TryReadScheduleSchemaFlags(Cursor cur, List<(ushort, uint)> queue, ScheduleRowBindings bindings, out int categoryId, out bool showTitle, out bool showHeaders, out bool showGridLines, out bool showOutline, out int gridStyleId, out int outlineStyleId, out string failure) { @@ -4690,6 +5105,7 @@ private static bool TryReadScheduleSchemaFlags(Cursor cur, List<(ushort, uint)> foreach (var field in schemaFields) { if (field.Declaring != 3535) { ReadField(cur, field, queue, 1, null); continue; } + if (ReadScheduleBindingField(bindings, cur, field, queue)) continue; if (field is { Name: "m_categoryId" }) { if (field is not { Type: 14, Mods: 0, Ref: 20 }) { failure = "category-type"; return false; } @@ -4850,17 +5266,24 @@ private static bool TryReadScheduleRowCells(Cursor cur, List<(ushort, uint)> que } private static bool TryReadScheduleCell(Cursor cur, List<(ushort, uint)> queue, - out string text, out int cellType, out int coverBottom, out int coverRight, out string failure) + out string text, out int cellType, out int coverBottom, out int coverRight, out int style, out string failure) { text = ""; cellType = coverBottom = coverRight = 0; + style = -1; failure = "ok"; var fields = SerializationFields(3921); if (fields == null) { failure = "no-schema-3921"; return false; } bool textRead = false, typeRead = false, bottomRead = false, rightRead = false; foreach (var field in fields) { - if (field is { Declaring: 3921, Name: "m_text" }) + if (field is { Declaring: 3921, Name: "m_oTableCellStyle" }) + { + int before = queue.Count; + ReadField(cur, field, queue, 1, null); + if (queue.Count == before + 1 && queue[before].Item1 == 3922) style = before; + } + else if (field is { Declaring: 3921, Name: "m_text" }) { if (field is not { Type: 8, Mods: 96 }) { failure = "text-type"; return false; } text = ReadString(cur); @@ -4895,14 +5318,19 @@ private static bool TryReadScheduleCell(Cursor cur, List<(ushort, uint)> queue, /// (the file's own schema names their classes; the shipped schema leaves them unreferenced, so the generic /// walk would read them as polymorphic handles and misalign). The two raytrace settings stay queued owned /// pointers. False when anything fails to decode. - private static bool TryReadViewDisplayMgr(Cursor cur, List<(ushort, uint)> queue, out string failure) + private static bool TryReadViewDisplayMgr(Cursor cur, List<(ushort, uint)> queue, out string failure, + NativeParams? capture = null) { failure = "ok"; var fields = SerializationFields(4107); if (fields == null) { failure = "no-schema-4107"; return false; } foreach (var field in fields) { - if (field.Declaring != 4107 || field is not { Type: 14, Mods: 0 }) { ReadField(cur, field, queue, 1, null); continue; } + if (field.Declaring != 4107 || field is not { Type: 14, Mods: 0 }) + { + ReadField(cur, field, queue, 1, capture); + continue; + } int inlineClass = field.Name switch { "m_background" => 4103, @@ -4915,7 +5343,7 @@ private static bool TryReadViewDisplayMgr(Cursor cur, List<(ushort, uint)> queue _ => 0, }; if (inlineClass == 0) ReadField(cur, field, queue, 1, null); - else ReadInlineStruct(cur, inlineClass, queue, 1); + else ReadInlineStruct(cur, inlineClass, queue, 1, inlineClass is 4103 or 4106 or 4108 or 4110 ? capture : null); } return true; } @@ -5003,7 +5431,7 @@ internal static bool TryExtractTitleBlockSymbol( // TextNoteData queues its RtfData; TagNoteData carries its parameter formatting inline. var geoms = new List<(double T0, double T1, double Ox, double Oy, double Oz, double Dx, double Dy, double Dz, int Tag, int Control, int CategoryId, uint Flags)>(); var rawTexts = new List<(double Ox, double Oy, double Oz, double Hx, double Hy, double Bx, double By, double Height, double Width, int AttrId, int Flags, int RtfQi)>(); - var rawLabels = new List<(double Ox, double Oy, double Oz, double Hx, double Hy, double Bx, double By, double Height, double Width, int AttrId, int Flags, List<(int ParamId, string Prefix, string Suffix, string Sample)> Params)>(); + var rawLabels = new List<(double Ox, double Oy, double Oz, double Hx, double Hy, double Bx, double By, double Height, double Width, int AttrId, int Flags, bool Wrap, List Params)>(); var rtfBlobs = new Dictionary(); for (int qi = 0; qi < queue.Count; qi++) { @@ -5133,7 +5561,8 @@ internal static bool TryExtractTitleBlockSymbol( } if (paramId == 0) continue; labels.Add(new TitleBlockLabel(raw.Ox, raw.Oy, raw.Oz, raw.Hx, raw.Hy, raw.Bx, raw.By, - raw.Height, raw.Width, raw.AttrId, raw.Flags, paramId, prefix, suffix)); + raw.Height, raw.Width, raw.AttrId, raw.Flags, paramId, prefix, suffix, + raw.Params.Count == 1 ? raw.Params[0].Format : null, raw.Wrap)); } failure = $"ok glines={geoms.Count} kept={lines.Count} texts={texts.Count} labels={labels.Count} queue={queue.Count}"; return true; @@ -5228,10 +5657,11 @@ private static bool TryReadGLine(Cursor cur, List<(ushort Cls, uint Id)> queue, private static bool TryReadTextDataBase(Cursor cur, List<(ushort Cls, uint Id)> queue, out double ox, out double oy, out double oz, out double hx, out double hy, out double bx, out double by, out double height, out double width, - out int attrId, out int flags, out string failure) + out int attrId, out int flags, out bool wrap, out string failure) { ox = oy = oz = hx = hy = bx = by = height = width = 0; attrId = flags = 0; + wrap = false; failure = "ok"; var baseFields = SerializationFields(3933); if (baseFields == null) @@ -5277,6 +5707,11 @@ private static bool TryReadTextDataBase(Cursor cur, List<(ushort Cls, uint Id)> if (field is not { Type: 4, Mods: 0 }) { failure = "flags-type"; return false; } flags = ReadI32(cur); f = true; } + else if (field is { Declaring: 3933, Name: "m_bNoWrapping", Type: 1, Mods: 0 }) + { + if (!cur.Take(1)) throw Fail; + wrap = cur.D[cur.Pos - 1] == 0; + } else ReadField(cur, field, queue, 1, null); } if (!o || !u || !b || !h || !w || !a || !f) { failure = "missing-base"; return false; } @@ -5290,7 +5725,7 @@ private static bool TryReadTextNoteData(Cursor cur, List<(ushort Cls, uint Id)> failure = "ok"; if (!TryReadTextDataBase(cur, queue, out double ox, out double oy, out double oz, out double hx, out double hy, out double bx, out double by, out double height, out double width, - out int attrId, out int flags, out string baseFailure)) + out int attrId, out int flags, out _, out string baseFailure)) { failure = baseFailure; return false; @@ -5329,20 +5764,20 @@ private static bool TryReadTextNoteData(Cursor cur, List<(ushort Cls, uint Id)> } private static bool TryReadTagNoteData(Cursor cur, List<(ushort Cls, uint Id)> queue, - out (double Ox, double Oy, double Oz, double Hx, double Hy, double Bx, double By, double Height, double Width, int AttrId, int Flags, List<(int ParamId, string Prefix, string Suffix, string Sample)> Params) label, out string failure) + out (double Ox, double Oy, double Oz, double Hx, double Hy, double Bx, double By, double Height, double Width, int AttrId, int Flags, bool Wrap, List Params) label, out string failure) { label = default; failure = "ok"; if (!TryReadTextDataBase(cur, queue, out double ox, out double oy, out double oz, out double hx, out double hy, out double bx, out double by, out double height, out double width, - out int attrId, out int flags, out string baseFailure)) + out int attrId, out int flags, out bool wrap, out string baseFailure)) { failure = baseFailure; return false; } var tagFields = SerializationFields(3932); if (tagFields == null) { failure = "no-schema-3932"; return false; } - var collected = new List<(int ParamId, string Prefix, string Suffix, string Sample)>(); + var collected = new List(); bool arrRead = false; foreach (var field in tagFields) { @@ -5364,26 +5799,27 @@ private static bool TryReadTagNoteData(Cursor cur, List<(ushort Cls, uint Id)> q failure = $"parr[{i}] {paramFailure}"; return false; } - collected.Add(param); + collected.Add(param!); } arrRead = true; } else ReadField(cur, field, queue, 1, null); } if (!arrRead) { failure = "missing-parr"; return false; } - label = (ox, oy, oz, hx, hy, bx, by, height, width, attrId, flags, collected); + label = (ox, oy, oz, hx, hy, bx, by, height, width, attrId, flags, wrap, collected); return true; } private static bool TryReadTagParam(Cursor cur, List<(ushort Cls, uint Id)> queue, - out (int ParamId, string Prefix, string Suffix, string Sample) param, out string failure) + out TagLabelParameter? param, out string failure) { param = default; failure = "ok"; var paramFields = SerializationFields(3929); if (paramFields == null) { failure = "no-schema-3929"; return false; } int paramId = 0; - string prefix = "", sample = "", suffix = ""; + string prefix = "", suffix = ""; + int formatStart = -1, formatEnd = -1; bool idRead = false, preRead = false, samRead = false, sufRead = false; foreach (var field in paramFields) { @@ -5398,16 +5834,30 @@ private static bool TryReadTagParam(Cursor cur, List<(ushort Cls, uint Id)> queu } else if (field is { Declaring: 3929, Name: "m_sampleText" }) { - sample = ReadString(cur); samRead = true; + ReadString(cur); samRead = true; } else if (field is { Declaring: 3929, Name: "m_suffix" }) { suffix = ReadString(cur); sufRead = true; } + else if (field is { Declaring: 3929, Name: "m_formatOptions", Type: 14, Mods: 0, Ref: 84 }) + { + formatStart = cur.Pos; + ReadField(cur, field, queue, 1, null); + formatEnd = cur.Pos; + } else ReadField(cur, field, queue, 1, null); } if (!idRead || !preRead || !samRead || !sufRead) { failure = "missing-param"; return false; } - param = (paramId, prefix, suffix, sample); + UnitFormatOption? format = null; + if (formatStart >= 0 && (BuiltInParameter)paramId is BuiltInParameter.PROPERTY_SEGMENT_N_S + or BuiltInParameter.PROPERTY_SEGMENT_BEARING or BuiltInParameter.PROPERTY_SEGMENT_E_W + or BuiltInParameter.PROPERTY_SEGMENT_DISTANCE) + { + format = ReadUnitFormatOption(cur.D, ref formatStart, formatEnd, ""); + if (formatStart != formatEnd) format = null; + } + param = new(paramId, prefix, suffix, format); return true; } @@ -6636,6 +7086,26 @@ private static void ReadField(Cursor c, TfField f, List<(ushort, uint)> queue, i if (hi == 5) { uint n = ReadU32(c); + if (capture != null && n == 4 + && f is { Declaring: 2247, Name: "m_arrowIds", Type: 14, Mods: 80, Ref: 20 } + or { Declaring: 2251, Name: "m_orderedSubIndices", Type: 4, Mods: 80 }) + { + for (int i = 0; i < 4; i++) capture.Fields[$"{FieldKey(f)}@{i}"] = ReadI32(c); + return; + } + if (capture != null && n == 4 && c.RootClassId == 1829 + && f is { Declaring: 1829, Name: "m_subInstData", Type: 14, Mods: 80, Ref: 1763 }) + { + for (int i = 0; i < 4; i++) + { + var item = new NativeParams(); + ReadInlineStruct(c, 1763, queue, depth, item); + if (item.Fields.TryGetValue("1763:first", out int index) + && item.Fields.TryGetValue("1724:m_masterSymId", out int symbol)) + capture.Fields.TryAdd($"1829:m_subInstData@{index}", symbol); + } + return; + } if (capture != null && c.RootClassId == 1772 && f is { Declaring: 1772, Name: "m_refTypeIds", Type: 4, Mods: 80, Ref: null, Cnt: null }) { @@ -6880,11 +7350,31 @@ private static bool TryFieldOverride(Cursor c, TfField f, List<(ushort, uint)> q { switch (f.Declaring, f.Name) { + case (690, "m_colorFillArr") when f is { Type: 14, Mods: 80, Ref: 687 } && capture != null: + capture.RoomColors = ReadRoomColorEntries(c); + return true; + case (693, "m_categoryToSchema") when f is { Type: 14, Mods: 80, Ref: 24 } && capture != null: + { + uint count = ReadU32(c); + if (count == uint.MaxValue) return true; + if (count > 10_000) throw Fail; + for (uint i = 0; i < count; i++) + { + int category = ReadI32(c), scheme = ReadI32(c); + if (category == -2000160) + capture.Fields["693:m_roomColorScheme"] = scheme; + } + return true; + } // An attribute symbol's line-and-text attributes are an inline LineAndTextAttr struct (font id, // category id, background, bold/italic/underline flags: 15 bytes), not the polymorphic pointer // the typeless field would read (which drifts every later field of a GridAttributes root). case (624, "m_lineAndTextAttr") when f.Type == 14 && f.Mods == 0 && f.Ref == null: - if (!c.Take(15)) throw Fail; + if (c.RootClassId is 3972 or 1862 or 836 or 3930) ReadInlineStruct(c, 625, queue, depth, capture); + else if (!c.Take(15)) throw Fail; + return true; + case (838, "m_data") when c.RootClassId == 837 && f is { Type: 14, Mods: 0, Ref: null }: + ReadInlineStruct(c, 839, queue, depth, capture); return true; // A mullion's nominal axis belongs to the first reference of its own symbol, not its trimmed solid. case (1829, "m_refs") when IsSubclassOf(c.RootClassId, 1829) && f.Type == 14 && f.Mods == 81 @@ -6926,6 +7416,27 @@ private static bool TryFieldOverride(Cursor c, TfField f, List<(ushort, uint)> q case (2008, "m_bBox" or "m_tightbBox") when f.Type == 13 && f.Mods == 16 && f.Cnt == 2: if (!c.Take(48)) throw Fail; return true; + // The viewer flags occupy two bytes before the annotation crop switch. + case (621, "m_viewerFlags") when f is { Type: 3, Mods: 0 }: + if (!c.Take(2)) throw Fail; + return true; + case (554, "m_boundedSpace") when c.RootClassId == 2505 + && f is { Type: 14, Mods: 0, Ref: 553 } && capture != null: + { + double[] Point() => [ReadF64(c), ReadF64(c), ReadF64(c)]; + double[] origin = Point(); + double[][] axes = [Point(), Point(), Point()]; + var offsets = new double[6]; + for (int i = 0; i < offsets.Length; i++) offsets[i] = ReadF64(c); + if (!c.Take(7)) throw Fail; + var flags = c.D.AsSpan(c.Pos - 7, 7); + if (flags[6] == 1 && flags[..6].IndexOfAnyExcept((byte)0, (byte)1) < 0 + && origin.All(double.IsFinite) && axes.All(axis => axis.All(double.IsFinite)) + && offsets.All(double.IsFinite) + && offsets[0] >= offsets[1] && offsets[2] >= offsets[3] && offsets[4] >= offsets[5]) + capture.ModelClipBox = new(origin, axes, offsets, flags[..6].ToArray().Select(flag => flag == 1).ToArray()); + return true; + } // BoundedSpace (553) composites are wider than Cnt x 8 per element: the basis is 3 x XYZ (72 bytes), // the bound offsets 3 pairs of doubles (48 bytes) and the active flags 3 pairs of booleans (6 bytes). // The generic stride under-reads them and misaligns every following field of a viewer root. @@ -6988,7 +7499,8 @@ private static bool TryFieldOverride(Cursor c, TfField f, List<(ushort, uint)> q } // SpatialElementCalculationPointRegenData.m_position is an XYZ struct (three doubles); read here so that they are // kept under the key of the field (the key of the struct's own field, "171:m_xyz", is not a captured one). - case (3639, "m_position") when f.Type == 14 && f.Mods == 0 && f.Ref == 171 && capture != null: + case (3639, "m_position") or (3702, "m_downTextOffset") + when f.Type == 14 && f.Mods == 0 && f.Ref == 171 && capture != null: { if (SerializationFields(171) is not [{ Name: "m_xyz", Type: 7, Mods: 16, Cnt: 3 }]) throw Fail; for (int i = 0; i < 3; i++) capture.DoubleFields[FieldKey(f) + "@" + i] = ReadF64(c); @@ -7017,6 +7529,57 @@ private static bool TryFieldOverride(Cursor c, TfField f, List<(ushort, uint)> q if (!c.Take((int)count * 8)) throw Fail; return true; } + case (527, "m_taggedEntitiesCell") when f is { Type: 14, Mods: 0, Ref: null }: + { + if (SerializationFields(528) is not { Count: 1 } entries + || entries[0] is not { Declaring: 528, Name: "m_taggedEntities", Type: 14, Mods: 81, Ref: 528 } + || c.End - c.Pos < 4) throw Fail; + bool single = BitConverter.ToUInt32(c.D, c.Pos) == 1; + int first = queue.Count; + ReadField(c, entries[0], queue, depth + 1, null); + if (capture != null && single && queue.Count == first + 1 && queue[first].Item1 == 3935) + capture.Fields["527:singleTaggedElement"] = 1; + return true; + } + case (844, "m_contourCache") when c.RootClassId == 3595 + && f is { Type: 14, Mods: 80, Ref: null }: + { + var contours = ReadSiteContours(c); + if (capture != null) capture.SiteContours = contours; + return true; + } + case (3936, "m_elbowOffset" or "m_endOffset") when c.RootClassId == 527 + && f is { Type: 14, Mods: 0, Ref: 171 } && capture != null: + capture.DoubleFields[$"3936:{f.Name}@0"] = ReadF64(c); + capture.DoubleFields[$"3936:{f.Name}@1"] = ReadF64(c); + ReadF64(c); + return true; + case (3935, "m_taggedId") when c.RootClassId == 527 && f is { Type: 14, Mods: 0, Ref: 180 } + && capture != null: + capture.Fields["3935:elementOrLinkId"] = ReadI32(c); + capture.Fields["3935:linkedElementId"] = ReadI32(c); + return true; + case (3475, "m_taggedRoomElemId") when f is { Type: 14, Mods: 0, Ref: 180 } && capture != null: + capture.Fields["3475:roomOrLinkId"] = ReadI32(c); + capture.Fields["3475:linkedRoomId"] = ReadI32(c); + return true; + case (1740, "m_contentDocGUID") when f is { Type: 14, Mods: 0, Ref: 30 } + && c.RootClassId == 1772 && capture != null: + if (!c.Take(16)) throw Fail; + capture.StringFields["1740:contentDoc"] = Convert.ToHexString(c.D.AsSpan(c.Pos - 16, 16)); + return true; + case (1807, "m_paramDrivenData") when f is { Type: 14, Mods: 80, Ref: null, Cnt: null }: + ReadInlineContainer(c, 1808, queue, depth); + return true; + case (3927, "m_paramDataFormattingArr") when f is { Type: 14, Mods: 80, Ref: null }: + ReadInlineContainer(c, 3929, queue, depth); + return true; + case (3702, "m_stairsLinkElementId") when f is { Type: 14, Mods: 0, Ref: 180 } && c.TailWalk: + { + int host = ReadI32(c), link = ReadI32(c); + if (capture != null && host > 0 && link == -1) capture.Fields[FieldKey(f)] = host; + return true; + } // The r22 schema's self-reference is not a recursive inline object: // RoomBoundingItem stores (host/link instance ElementId, linked ElementId). // Keep this 4-byte leaf local to exact RoomElem name extraction and the ExtractParams walk @@ -7405,6 +7968,15 @@ private static bool TryFieldOverride(Cursor c, TfField f, List<(ushort, uint)> q case (716, "m_offsetGeomMap"): ReadInlineContainer(c, 717, queue, depth, capture); return true; + case (3878, "m_outline") when c.RootClassId == 3878 + && f is { Type: 14, Mods: 0, Ref: 297 } && capture != null: + { + var bounds = new double[6]; + for (int i = 0; i < bounds.Length; i++) bounds[i] = ReadF64(c); + if (bounds.All(double.IsFinite) && bounds[0] <= bounds[3] && bounds[1] <= bounds[4] + && bounds[2] <= bounds[5]) capture.SunStudyOutline = bounds; + return true; + } // Outline.m_minmax is a fixed array of two XYZ POD values. case (297, "m_minmax"): if (!c.Take(2 * 3 * 8)) throw Fail; @@ -7447,14 +8019,48 @@ private static bool TryFieldOverride(Cursor c, TfField f, List<(ushort, uint)> q ReadField(c, record, queue, depth + 1, null); return true; } + case (174, "m_equalityFormattingArr") when f is { Type: 14, Mods: 80, Ref: null }: + ReadInlineContainer(c, 175, queue, depth); + return true; + case (175, "m_formatOptions") when f is { Type: 14, Mods: 0, Ref: 175 }: + ReadInlineStruct(c, 84, queue, depth); + return true; + case (160, "m_refPnts") when c.RootClassId == 2335 && capture != null + && f is { Type: 13, Mods: 80, Cnt: null }: + { + int count = ReadI32(c); + if (count is < -1 or > 100_000) throw Fail; + if (count >= 0) capture.Fields["m_refPnts#"] = count; + if (count is < 2 or > 128) + { + if (!c.Take(Math.Max(0, count) * 24)) throw Fail; + return true; + } + capture.DimensionReferences = new List(count); + for (int i = 0; i < count; i++) capture.DimensionReferences.Add(ReadStoredPoint(c)); + return true; + } case (0xA0, "m_ArrSegInfo"): // D1: [count] x inline DimSegInfo + if (c.RootClassId == 2335 && capture?.DimensionReferences != null) + capture.DimensionValues = new List(); ReadInlineContainer(c, 0xA1, queue, depth, capture); return true; case (0xA0, "m_ArrEqualityFormulaInfo_DimEqSegInfoArr"): // D3: inline DimEqSegInfoArr ReadInlineStruct(c, 0xA5, queue, depth); return true; case (0x9F, "m_witnessRefs"): // D4 - ReadInlineContainer(c, 0xA7, queue, depth); + ReadInlineContainer(c, 0xA7, queue, depth, capture?.DimensionValues != null ? capture : null); + return true; + case (161, "m_offset") when capture?.DimensionValues != null && f is { Type: 7, Mods: 16, Cnt: 2 }: + { + double x = ReadF64(c), y = ReadF64(c); + if (x != 0 || y != 0) capture.DimensionValues = null; + return true; + } + case (167, "m_modified" or "m_useDistToDimLn") when capture?.DimensionValues != null + && f is { Type: 1, Mods: 0 }: + if (!c.Take(1)) throw Fail; + if (c.D[c.Pos - 1] != 0) capture.DimensionValues = null; return true; case (0x162, "m_witnessRefs"): // D4 (radial chain) ReadInlineContainer(c, 0x163, queue, depth); @@ -7483,7 +8089,16 @@ private static bool TryFieldOverride(Cursor c, TfField f, List<(ushort, uint)> q queue.Add((tag, 0xFFFFFFFF)); } else if (hdr > 1000) throw Fail; + int first = c.Pos, queued = queue.Count; for (int i = 0; i < 3; i++) ReadInlineStruct(c, 0xA3, queue, depth); + if (capture?.DimensionValues is { } values) + { + // Each value owns its text overrides and format state. Only plain measured labels are supported. + if (hdr != 0xFFFFFFFF && queued == queue.Count) + values.Add(BitConverter.ToDouble(c.D, first)); + else + capture.DimensionValues = null; + } return true; } case (0xA1, "m_id"): // D6: plain i32 (may be -1) @@ -7499,6 +8114,9 @@ private static bool TryFieldOverride(Cursor c, TfField f, List<(ushort, uint)> q return true; // CurveElem / arc geometry (rules R1-R7) + case (838, "m_referenceType") when c.RootClassId == 837: + if (!c.Take(4)) throw Fail; + return true; case (0x346, "m_referenceType"): // R1: field i32 + a hidden extra i32 if (!c.Take(8)) throw Fail; return true; diff --git a/src/RvtIO/Pdf/PdfDocument.cs b/src/RvtIO/Pdf/PdfDocument.cs index f1fdc371..03647107 100644 --- a/src/RvtIO/Pdf/PdfDocument.cs +++ b/src/RvtIO/Pdf/PdfDocument.cs @@ -115,6 +115,9 @@ internal static (int Width, int Height, int Components) ReadHeader(byte[] jpeg) /// An RGB raster image of the document, 8 bits per channel, written with Flate compression. public sealed class PdfRasterImage : IPdfImage { + internal bool Interpolate { get; init; } + internal bool TransparentWhite { get; init; } + /// Width in pixels. public int Width { get; } @@ -161,6 +164,9 @@ public readonly record struct PdfColor(double R, double G, double B) B + (1 - B) * amount); } +internal sealed record PdfLinePattern(double Spacing, double Angle, double X, double Y, double Width, + double Shift = 0, double[]? Segments = null); + /// Horizontal placement of a text anchor. public enum PdfTextAlignment { @@ -193,6 +199,12 @@ public sealed class PdfDocument /// The characters drawn with , which the font's width array and ToUnicode map hold. internal HashSet UsedCharacters { get; } = new(); + internal PdfTrueTypeFont? BoldFont { get; set; } + internal HashSet UsedBoldCharacters { get; } = new(); + + internal List LinePatterns { get; } = new(); + internal List<(double BottomY, double TopY, PdfColor Bottom, PdfColor Top)> VerticalGradients { get; } = new(); + /// The pages, in the order they were added. public IReadOnlyList Pages => _pages; @@ -275,6 +287,19 @@ internal PdfPage(PdfPageSize size, PdfDocument document) public void DrawLine(double x1, double y1, double x2, double y2, double widthMillimetres = 0.25, double gray = 0) { Stroke(widthMillimetres, gray); + AppendLine(x1, y1, x2, y2); + } + + internal void DrawLine(double x1, double y1, double x2, double y2, double widthMillimetres, PdfColor color) + { + Stroke(widthMillimetres, 0); + _content.Append(Number(color.R)).Append(' ').Append(Number(color.G)).Append(' ') + .Append(Number(color.B)).Append(" RG\n"); + AppendLine(x1, y1, x2, y2); + } + + private void AppendLine(double x1, double y1, double x2, double y2) + { _content.Append(Number(Points(x1))).Append(' ').Append(Number(Points(y1))).Append(" m ") .Append(Number(Points(x2))).Append(' ').Append(Number(Points(y2))).Append(" l S\n"); } @@ -294,13 +319,31 @@ public void DrawArc(double centerX, double centerY, double radius, double startD if (endDegrees < startDegrees) (startDegrees, endDegrees) = (endDegrees, startDegrees); double span = endDegrees - startDegrees; if (span <= 0) return; + Stroke(widthMillimetres, gray); + AppendArc(centerX, centerY, radius, startDegrees, span); + _content.Append("S\n"); + } + + internal void DrawFilledCircle(double centerX, double centerY, double radius, double widthMillimetres, + PdfColor fill, PdfColor outline) + { + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(radius); + Stroke(widthMillimetres, 0); + _content.Append(Number(outline.R)).Append(' ').Append(Number(outline.G)).Append(' ') + .Append(Number(outline.B)).Append(" RG\n"); + FillColor(fill); + AppendArc(centerX, centerY, radius, 0, 360); + _content.Append("h B\n"); + } + + private void AppendArc(double centerX, double centerY, double radius, double startDegrees, double span) + { double sweep = span * Math.PI / 180; int segments = Math.Max(1, (int)Math.Ceiling(sweep / (Math.PI / 2))); double step = sweep / segments; double handle = 4.0 / 3.0 * Math.Tan(step / 4); double angle = startDegrees * Math.PI / 180; double x0 = centerX + radius * Math.Cos(angle), y0 = centerY + radius * Math.Sin(angle); - Stroke(widthMillimetres, gray); _content.Append(Number(Points(x0))).Append(' ').Append(Number(Points(y0))).Append(" m "); for (int i = 0; i < segments; i++) { @@ -315,7 +358,6 @@ public void DrawArc(double centerX, double centerY, double radius, double startD .Append(Number(Points(x3))).Append(' ').Append(Number(Points(y3))).Append(" c "); angle = next; } - _content.Append("S\n"); } /// Draws a polyline through the points, optionally closed, either stroked or filled. @@ -351,6 +393,159 @@ public void DrawPolyline(IReadOnlyList<(double X, double Y)> points, double widt _content.Append(stroke && fillColor != null ? "B\n" : stroke ? "S\n" : "f\n"); } + internal HashSet LinePatternIndices { get; } = []; + internal HashSet VerticalGradientIndices { get; } = []; + + internal void FillVerticalGradient(double x, double y, double width, double height, + PdfColor bottom, PdfColor top) + { + if (!(width > 0 && height > 0)) return; + var gradient = (Points(y), Points(y + height), bottom, top); + int index = _document.VerticalGradients.IndexOf(gradient); + if (index < 0) + { + index = _document.VerticalGradients.Count; + _document.VerticalGradients.Add(gradient); + } + VerticalGradientIndices.Add(index); + BeginClip(x, y, width, height); + _content.Append("/Sh").Append(index).Append(" sh\n"); + EndClip(); + } + + internal void DrawRoundDashedPolyline(IReadOnlyList<(double X, double Y)> points, double width, double[] dashes) + { + _content.Append("q 1 J 1 j\n"); + SetDashPoints(dashes); + DrawPolyline(points, width); + _content.Append("Q\n"); + } + + internal void FillWithParallelLines(IReadOnlyList<(double X, double Y)> polygon, double spacing, + double angle, double anchorX, double anchorY, double width) + => FillWithParallelLines([polygon], spacing, angle, anchorX, anchorY, width); + + internal void FillWithParallelLines(IReadOnlyList> rings, double spacing, + double angle, double anchorX, double anchorY, double width) + => FillWithLinePattern(rings, new PdfLinePattern(spacing, angle, anchorX, anchorY, width)); + + internal void FillWithClippedParallelLines(IReadOnlyList> rings, + double spacing, double angle, double anchorX, double anchorY, double width) + { + if (rings.Count == 0 || rings[0].Count < 3 || !(spacing > width && width > 0) + || !double.IsFinite(spacing) || !double.IsFinite(angle) + || !double.IsFinite(anchorX) || !double.IsFinite(anchorY)) return; + + double sin = Math.Sin(angle), cos = Math.Cos(angle); + double minAcross = double.PositiveInfinity, maxAcross = double.NegativeInfinity; + double minAlong = double.PositiveInfinity, maxAlong = double.NegativeInfinity; + foreach (var ring in rings) + foreach (var (x, y) in ring) + { + double across = x * sin - y * cos, along = x * cos + y * sin; + minAcross = Math.Min(minAcross, across); + maxAcross = Math.Max(maxAcross, across); + minAlong = Math.Min(minAlong, along); + maxAlong = Math.Max(maxAlong, along); + } + if (!(maxAcross > minAcross && maxAlong > minAlong)) return; + + double half = width / 2; + double phase = (anchorX * sin - anchorY * cos) % spacing; + double first = phase + Math.Ceiling((minAcross - half - phase) / spacing) * spacing; + double last = maxAcross + half; + double count = 1 + Math.Floor((last - first) / spacing); + if (!(count > 0)) return; + // Keep tiling for very dense patterns to bound the size of the filled path. + if (count > 4096) + { + FillWithParallelLines(rings, spacing, angle, anchorX, anchorY, width); + return; + } + + BeginPolygonClip(rings, evenOdd: false); + FillPolygonUnion(Strips((int)count), 0); + EndClip(); + + IEnumerable> Strips(int stripCount) + { + for (int i = 0; i < stripCount; i++) + { + double across = first + i * spacing; + yield return [InPage(across - half, minAlong), InPage(across + half, minAlong), + InPage(across + half, maxAlong), InPage(across - half, maxAlong)]; + } + } + + (double X, double Y) InPage(double across, double along) => + (across * sin + along * cos, along * sin - across * cos); + } + + internal void FillWithLinePattern(IReadOnlyList> rings, PdfLinePattern pattern) + { + var (spacing, angle, anchorX, anchorY, width, _, _) = pattern; + if (rings.Count == 0 || rings[0].Count < 3 || !(spacing > width && width > 0) + || !double.IsFinite(spacing) || !double.IsFinite(angle) + || !double.IsFinite(anchorX) || !double.IsFinite(anchorY)) return; + int index = _document.LinePatterns.IndexOf(pattern); + if (index < 0) + { + index = _document.LinePatterns.Count; + _document.LinePatterns.Add(pattern); + } + LinePatternIndices.Add(index); + _content.Append("q /Pattern cs /P").Append(index).Append(" scn\n"); + AppendFillRings(rings); + _content.Append("f Q\n"); + } + + // Outer rings share one orientation and holes use the opposite orientation; nonzero winding unions overlaps. + internal List FillOpacities { get; } = []; + + internal void FillPolygonUnion(IEnumerable> rings, double gray, + double opacity = 1) + { + if (opacity <= 0) return; + if (opacity < 1) + { + int index = FillOpacities.IndexOf(opacity); + if (index < 0) + { + index = FillOpacities.Count; + FillOpacities.Add(opacity); + } + _content.Append("q /Gs").Append(index).Append(" gs\n"); + } + Fill(gray); + AppendFillRings(rings); + _content.Append(opacity < 1 ? "f\nQ\n" : "f\n"); + } + + private void AppendFillRings(IEnumerable> rings) + { + foreach (var ring in rings) + { + if (ring.Count < 3) continue; + for (int i = 0; i < ring.Count; i++) + _content.Append(Number(Points(ring[i].X))).Append(' ').Append(Number(Points(ring[i].Y))) + .Append(i == 0 ? " m " : " l "); + _content.Append("h "); + } + } + + internal void BeginPolygonClip(IEnumerable> rings, bool evenOdd = true) + { + _content.Append("q "); + AppendFillRings(rings); + _content.Append(evenOdd ? "W* n\n" : "W n\n"); + } + + internal void IntersectPolygonClip(IEnumerable> rings) + { + AppendFillRings(rings); + _content.Append("W* n\n"); + } + /// Starts a clipping region: everything drawn until is cut to the rectangle. /// Left edge, millimetres. /// Bottom edge, millimetres. @@ -451,21 +646,28 @@ public void DrawRectangle(double x, double y, double width, double height, doubl /// No font is set and the text holds a character outside printable ASCII. public void DrawText(string text, double x, double y, double heightMillimetres = 3, PdfTextAlignment alignment = PdfTextAlignment.Left, double gray = 0) + => DrawStyledText(text, x, y, heightMillimetres, alignment, gray, useBold: false); + + internal void DrawStyledText(string text, double x, double y, double heightMillimetres, + PdfTextAlignment alignment, double gray, bool useBold, PdfColor? ink = null) { if (string.IsNullOrEmpty(text)) return; ArgumentOutOfRangeException.ThrowIfNegativeOrZero(heightMillimetres); double fontPoints = heightMillimetres * 72.0 / 25.4; // Text is painted with the non-stroking colour, so set the fill (not the stroke) colour: after a white-filled // bubble or floor the fill could still be white and the text would disappear. - Fill(gray); - if (_document.Font is { } font) + if (ink is { } color) FillColor(color); + else Fill(gray); + var bold = useBold ? _document.BoldFont : null; + if ((bold ?? _document.Font) is { } font) { + var used = bold != null ? _document.UsedBoldCharacters : _document.UsedCharacters; var encoded = new StringBuilder(text.Length * 4); double width = 0; foreach (char character in text) { int glyph = font.GlyphOf(character); - _document.UsedCharacters.Add(character); + used.Add(character); width += font.AdvanceOf(glyph) / (double)font.UnitsPerEm * heightMillimetres; encoded.Append(glyph.ToString("X4", CultureInfo.InvariantCulture)); } @@ -475,7 +677,7 @@ public void DrawText(string text, double x, double y, double heightMillimetres = PdfTextAlignment.Right => x - width, _ => x, }; - _content.Append("BT /F2 ").Append(Number(fontPoints)).Append(" Tf ") + _content.Append(bold != null ? "BT /F3 " : "BT /F2 ").Append(Number(fontPoints)).Append(" Tf ") .Append(Number(Points(anchor))).Append(' ').Append(Number(Points(y))).Append(" Td <") .Append(encoded).Append("> Tj ET\n"); return; diff --git a/src/RvtIO/Pdf/PdfFonts.cs b/src/RvtIO/Pdf/PdfFonts.cs index c0592f57..b5084140 100644 --- a/src/RvtIO/Pdf/PdfFonts.cs +++ b/src/RvtIO/Pdf/PdfFonts.cs @@ -19,10 +19,22 @@ public static class PdfFonts /// Loads the first font file of that exists and parses. /// The file that was used, or null when none exists. /// The font, or null when no candidate is a TrueType font this reader supports. - public static PdfTrueTypeFont? TryFind(out string? path) + public static PdfTrueTypeFont? TryFind(out string? path) => TryFind(Candidates, out path); + + internal static PdfTrueTypeFont? TryFindBold() => TryFind( + [ + "/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf", + "/usr/share/fonts/TTF/DejaVuSans-Bold.ttf", + "/System/Library/Fonts/Supplemental/Arial Bold.ttf", + @"C:\Windows\Fonts\arialbd.ttf", + @"C:\Windows\Fonts\segoeuib.ttf", + @"C:\Windows\Fonts\tahomabd.ttf" + ], out _); + + private static PdfTrueTypeFont? TryFind(IReadOnlyList candidates, out string? path) { path = null; - foreach (string candidate in Candidates) + foreach (string candidate in candidates) { if (!File.Exists(candidate)) continue; try diff --git a/src/RvtIO/Pdf/PdfSerializer.cs b/src/RvtIO/Pdf/PdfSerializer.cs index 093ce426..4b32f01c 100644 --- a/src/RvtIO/Pdf/PdfSerializer.cs +++ b/src/RvtIO/Pdf/PdfSerializer.cs @@ -14,10 +14,6 @@ internal static class PdfSerializer private const int PagesId = 2; private const int HelveticaId = 3; private const int Type0Id = 4; - private const int CidFontId = 5; - private const int DescriptorId = 6; - private const int FontFileId = 7; - private const int ToUnicodeId = 8; private const int FirstPageWithFont = 9; private const int FirstPageWithoutFont = 4; @@ -26,9 +22,15 @@ internal static void Write(Stream stream, PdfDocument document) IReadOnlyList pages = document.Pages; PdfTrueTypeFont? font = document.Font; int firstPage = font != null ? FirstPageWithFont : FirstPageWithoutFont; + var bold = document.UsedBoldCharacters.Count > 0 ? document.BoldFont : null; + int boldId = firstPage; + if (bold != null) firstPage += 5; int PageId(int index) => firstPage + index * 2; int ContentId(int index) => firstPage + index * 2 + 1; int ImageId(int index) => firstPage + pages.Count * 2 + index; + int PatternId(int index) => ImageId(document.Images.Count) + index; + int GradientId(int index) => PatternId(document.LinePatterns.Count) + index; + int outlinesId = GradientId(document.VerticalGradients.Count); var offsets = new List(); long position = 0; @@ -56,7 +58,6 @@ void BeginObject(int id) outlines.Add((i, title)); if (outlines.Count > 0) { - int outlinesId = firstPage + pages.Count * 2 + document.Images.Count; Raw($"<< /Type /Catalog /Pages {PagesId} 0 R /Outlines {outlinesId} 0 R /PageMode /UseOutlines >>\n"); } else @@ -75,47 +76,47 @@ void BeginObject(int id) Raw("<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>\n"); EndObject(); - if (font != null) + void WriteFont(PdfTrueTypeFont font, HashSet characters, int id) { double scale = 1000.0 / font.UnitsPerEm; - BeginObject(Type0Id); + BeginObject(id); Raw($"<< /Type /Font /Subtype /Type0 /BaseFont /{font.Name} /Encoding /Identity-H " - + $"/DescendantFonts [ {CidFontId} 0 R ] /ToUnicode {ToUnicodeId} 0 R >>\n"); + + $"/DescendantFonts [ {(id + 1)} 0 R ] /ToUnicode {(id + 4)} 0 R >>\n"); EndObject(); var widths = new StringBuilder(); var used = new SortedSet(); - foreach (char character in document.UsedCharacters) used.Add(font.GlyphOf(character)); + foreach (char character in characters) used.Add(font.GlyphOf(character)); foreach (int glyph in used) { widths.Append(glyph).Append(" [ ") .Append(Number(font.AdvanceOf(glyph) * scale)).Append(" ] "); } - BeginObject(CidFontId); + BeginObject((id + 1)); Raw($"<< /Type /Font /Subtype /CIDFontType2 /BaseFont /{font.Name} " + "/CIDSystemInfo << /Registry (Adobe) /Ordering (Identity) /Supplement 0 >> " - + $"/FontDescriptor {DescriptorId} 0 R /CIDToGIDMap /Identity /DW 1000 /W [ {widths.ToString().TrimEnd()} ] >>\n"); + + $"/FontDescriptor {(id + 2)} 0 R /CIDToGIDMap /Identity /DW 1000 /W [ {widths.ToString().TrimEnd()} ] >>\n"); EndObject(); - BeginObject(DescriptorId); + BeginObject((id + 2)); Raw($"<< /Type /FontDescriptor /FontName /{font.Name} /Flags 32 " + $"/FontBBox [ {Number(font.XMin * scale)} {Number(font.YMin * scale)} " + $"{Number(font.XMax * scale)} {Number(font.YMax * scale)} ] /ItalicAngle 0 " + $"/Ascent {Number(font.Ascent * scale)} /Descent {Number(font.Descent * scale)} " - + $"/CapHeight {Number(font.Ascent * 0.7 * scale)} /StemV 80 /FontFile2 {FontFileId} 0 R >>\n"); + + $"/CapHeight {Number(font.Ascent * 0.7 * scale)} /StemV 80 /FontFile2 {(id + 3)} 0 R >>\n"); EndObject(); byte[] file = font.File_; byte[] fontPayload = document.Compress ? Zlib(file) : file; - BeginObject(FontFileId); + BeginObject((id + 3)); Raw($"<< /Length {fontPayload.Length} /Length1 {file.Length}" + (document.Compress ? " /Filter /FlateDecode" : string.Empty) + " >>\nstream\n"); WriteBytes(fontPayload); Raw("\nendstream\n"); EndObject(); - BeginObject(ToUnicodeId); - string cmap = ToUnicode(document, font); + BeginObject((id + 4)); + string cmap = ToUnicode(characters, font); byte[] cmapBytes = Encoding.ASCII.GetBytes(cmap); byte[] cmapPayload = document.Compress ? Zlib(cmapBytes) : cmapBytes; Raw($"<< /Length {cmapPayload.Length}" @@ -125,17 +126,30 @@ void BeginObject(int id) EndObject(); } + if (font != null) WriteFont(font, document.UsedCharacters, Type0Id); + if (bold != null) WriteFont(bold, document.UsedBoldCharacters, boldId); + for (int i = 0; i < pages.Count; i++) { PdfPage page = pages[i]; var (width, height) = page.Size.InPoints; string fonts = font != null ? $"/F1 {HelveticaId} 0 R /F2 {Type0Id} 0 R" : $"/F1 {HelveticaId} 0 R"; + if (bold != null) fonts += $" /F3 {boldId} 0 R"; var xobjects = new StringBuilder(); for (int k = 0; k < page.Images.Count; k++) xobjects.Append($"/Im{k} {ImageId(document.ImageIndex(page.Images[k]))} 0 R "); - string resources = xobjects.Length == 0 - ? $"/Resources << /Font << {fonts} >> >>" - : $"/Resources << /Font << {fonts} >> /XObject << {xobjects.ToString().TrimEnd()} >> >>"; + string resources = $"/Resources << /Font << {fonts} >>"; + if (xobjects.Length > 0) resources += $" /XObject << {xobjects.ToString().TrimEnd()} >>"; + if (page.LinePatternIndices.Count > 0) + resources += $" /Pattern << {string.Join(" ", page.LinePatternIndices.Order() + .Select(index => $"/P{index} {PatternId(index)} 0 R"))} >>"; + if (page.VerticalGradientIndices.Count > 0) + resources += $" /Shading << {string.Join(" ", page.VerticalGradientIndices.Order() + .Select(index => $"/Sh{index} {GradientId(index)} 0 R"))} >>"; + if (page.FillOpacities.Count > 0) + resources += $" /ExtGState << {string.Join(" ", page.FillOpacities.Select((opacity, index) => + $"/Gs{index} << /Type /ExtGState /ca {Number(opacity)} >>"))} >>"; + resources += " >>"; BeginObject(PageId(i)); Raw($"<< /Type /Page /Parent {PagesId} 0 R /MediaBox [0 0 {Number(width)} {Number(height)}] " + resources + $" /Contents {ContentId(i)} 0 R >>\n"); @@ -162,17 +176,80 @@ void BeginObject(int id) BeginObject(ImageId(k)); Raw($"<< /Type /XObject /Subtype /Image /Width {image.Width} /Height {image.Height} " + $"/ColorSpace {image.ColorSpace} /BitsPerComponent 8" + filter + + (image is PdfRasterImage { Interpolate: true } ? " /Interpolate true" : string.Empty) + + (image is PdfRasterImage { TransparentWhite: true } ? " /Mask [255 255 255 255 255 255]" : string.Empty) + $" /Length {pixels.Length} >>\nstream\n"); WriteBytes(pixels); Raw("\nendstream\n"); EndObject(); } - // The document outline, after the images: one bookmark per titled page, in page order, each pointing + const double pointsPerMillimetre = 72.0 / 25.4; + double span = pages.Select(p => p.Size.InPoints.Width + p.Size.InPoints.Height).DefaultIfEmpty().Max(); + for (int k = 0; k < document.LinePatterns.Count; k++) + { + var (spacing, angle, x, y, width, shift, segments) = document.LinePatterns[k]; + double step = spacing * pointsPerMillimetre; + double inkWidth = width * pointsPerMillimetre; + double sin = Math.Sin(angle), cos = Math.Cos(angle); + if (segments != null) + { + double period = segments.Sum() * pointsPerMillimetre; + double skew = Math.IEEERemainder(shift * pointsPerMillimetre, period) / step; + double half = inkWidth / 2, pad = Math.Abs(skew) * half; + static string Exact(double value) => value.ToString("0.#########", CultureInfo.InvariantCulture); + string dashedMatrix = $"{Exact(cos)} {Exact(sin)} {Exact(-sin + cos * skew)} {Exact(cos + sin * skew)} " + + $"{Exact(x * pointsPerMillimetre)} {Exact(y * pointsPerMillimetre)}"; + var tile = new StringBuilder("0 g\n"); + double start = 0; + for (int i = 0; i < segments.Length; i++) + { + double end = start + segments[i] * pointsPerMillimetre; + if (i % 2 == 0 && end > start) + { + double slant = skew * half; + tile.Append($"{Exact(start + slant)} {Exact(-half)} m {Exact(end + slant)} {Exact(-half)} l " + + $"{Exact(end - slant)} {Exact(half)} l {Exact(start - slant)} {Exact(half)} l h "); + } + start = end; + } + tile.Append("f\n"); + BeginObject(PatternId(k)); + Raw($"<< /Type /Pattern /PatternType 1 /PaintType 1 /TilingType 2 " + + $"/BBox [{Exact(-pad)} {Exact(-step / 2)} {Exact(period + pad)} {Exact(step / 2)}] " + + $"/XStep {Exact(period)} /YStep {Exact(step)} /Matrix [{dashedMatrix}] /Resources << >> /Length {tile.Length} >>\nstream\n"); + Raw(tile.ToString()); + Raw("endstream\n"); + EndObject(); + continue; + } + double normalOffset = ((x * sin - y * cos) * pointsPerMillimetre) % step - step / 2; + string matrix = $"{Number(sin)} {Number(-cos)} {Number(cos)} {Number(sin)} " + + $"{Number(sin * normalOffset)} {Number(-cos * normalOffset)}"; + // One tile spans the page along the line, so the print has no seams between line ends. + string ink = $"0 g {Number((step - inkWidth) / 2)} {Number(-span)} {Number(inkWidth)} {Number(2 * span)} re f\n"; + BeginObject(PatternId(k)); + Raw($"<< /Type /Pattern /PatternType 1 /PaintType 1 /TilingType 2 /BBox [0 {Number(-span)} {Number(step)} {Number(span)}] " + + $"/XStep {Number(step)} /YStep {Number(2 * span)} /Matrix [{matrix}] /Resources << >> /Length {ink.Length} >>\nstream\n"); + Raw(ink); + Raw("endstream\n"); + EndObject(); + } + + for (int k = 0; k < document.VerticalGradients.Count; k++) + { + var (bottomY, topY, bottom, top) = document.VerticalGradients[k]; + string Rgb(PdfColor color) => $"{Number(color.R)} {Number(color.G)} {Number(color.B)}"; + BeginObject(GradientId(k)); + Raw($"<< /ShadingType 2 /ColorSpace /DeviceRGB /Coords [0 {Number(bottomY)} 0 {Number(topY)}] " + + $"/Function << /FunctionType 2 /Domain [0 1] /C0 [{Rgb(bottom)}] /C1 [{Rgb(top)}] /N 1 >> >>\n"); + EndObject(); + } + + // The document outline, after the resources: one bookmark per titled page, in page order, each pointing // at its page. Untitled documents write no outline, as before. if (outlines.Count > 0) { - int outlinesId = firstPage + pages.Count * 2 + document.Images.Count; int firstItem = outlinesId + 1; BeginObject(outlinesId); Raw($"<< /Type /Outlines /First {firstItem} 0 R /Last {firstItem + outlines.Count - 1} 0 R " @@ -227,10 +304,10 @@ private static byte[] Zlib(byte[] data) return output.ToArray(); } - private static string ToUnicode(PdfDocument document, PdfTrueTypeFont font) + private static string ToUnicode(HashSet characters, PdfTrueTypeFont font) { var byGlyph = new SortedDictionary(); - foreach (char character in document.UsedCharacters) + foreach (char character in characters) byGlyph.TryAdd(font.GlyphOf(character), character); var text = new StringBuilder(); text.Append("/CIDInit /ProcSet findresource begin\n12 dict begin\nbegincmap\n") diff --git a/src/RvtIO/Pdf/PdfTrueTypeFont.cs b/src/RvtIO/Pdf/PdfTrueTypeFont.cs index f67a5e3b..bfb8c528 100644 --- a/src/RvtIO/Pdf/PdfTrueTypeFont.cs +++ b/src/RvtIO/Pdf/PdfTrueTypeFont.cs @@ -53,6 +53,10 @@ public PdfTrueTypeFont(byte[] file, string name) XMax = BinaryPrimitives.ReadInt16BigEndian(file.AsSpan(head.Offset + 40)); YMax = BinaryPrimitives.ReadInt16BigEndian(file.AsSpan(head.Offset + 42)); + if (tables.TryGetValue("OS/2", out var os2) && os2.Length >= 90 + && os2.Offset >= 0 && os2.Offset <= file.Length - 90 + && BinaryPrimitives.ReadUInt16BigEndian(file.AsSpan(os2.Offset)) >= 2) + CapHeight = BinaryPrimitives.ReadInt16BigEndian(file.AsSpan(os2.Offset + 88)); Ascent = BinaryPrimitives.ReadInt16BigEndian(file.AsSpan(hhea.Offset + 4)); Descent = BinaryPrimitives.ReadInt16BigEndian(file.AsSpan(hhea.Offset + 6)); int metrics = BinaryPrimitives.ReadUInt16BigEndian(file.AsSpan(hhea.Offset + 34)); @@ -87,6 +91,7 @@ public PdfTrueTypeFont(byte[] file, string name) internal int XMax { get; } internal int YMax { get; } internal int Ascent { get; } + internal int CapHeight { get; } internal int Descent { get; } /// The font file, embedded whole. diff --git a/src/RvtIO/Pdf/WindowsArialLayout.cs b/src/RvtIO/Pdf/WindowsArialLayout.cs new file mode 100644 index 00000000..f23e2710 --- /dev/null +++ b/src/RvtIO/Pdf/WindowsArialLayout.cs @@ -0,0 +1,83 @@ +using System.Runtime.InteropServices; +using System.Text; + +namespace RvtIO.Pdf; + +internal static class WindowsArialLayout +{ + private const double MillimetresPerPixel = 25.4 / 384; + + internal static bool TryMeasure(string text, double sizeMm, out double width, out double ascent) + { + width = ascent = 0; + // shortcut: the verified 12 pt Arial layout uses a 64-pixel em, extend when other sizes are verified. + if (!OperatingSystem.IsWindows() || Math.Abs(sizeMm - 64 * MillimetresPerPixel) > 1e-6) + return false; + nint dc = CreateCompatibleDC(0); + if (dc == 0) return false; + nint font = CreateFontW(-64, 0, 0, 0, 400, 0, 0, 0, 1, 0, 0, 0, 0, "Arial"); + nint previous = 0; + try + { + if (font == 0) return false; + previous = SelectObject(dc, font); + var face = new StringBuilder(32); + if (previous == 0 || previous == -1 || GetTextFaceW(dc, face.Capacity, face) == 0 + || !string.Equals(face.ToString(), "Arial", StringComparison.OrdinalIgnoreCase) + || !GetTextExtentPoint32W(dc, text, text.Length, out var size) + || !GetTextMetricsW(dc, out var metrics)) + return false; + width = size.Width * MillimetresPerPixel; + ascent = metrics.Ascent * MillimetresPerPixel; + return width > 0 && ascent > 0; + } + finally + { + if (previous != 0 && previous != -1) SelectObject(dc, previous); + if (font != 0) DeleteObject(font); + DeleteDC(dc); + } + } + + [StructLayout(LayoutKind.Sequential)] + private struct TextSize + { + public int Width; + public int Height; + } + + [StructLayout(LayoutKind.Explicit, Size = 60)] + private struct TextMetrics + { + [FieldOffset(4)] + public int Ascent; + } + + [DllImport("gdi32.dll", ExactSpelling = true)] + private static extern nint CreateCompatibleDC(nint device); + + [DllImport("gdi32.dll", ExactSpelling = true, CharSet = CharSet.Unicode)] + private static extern nint CreateFontW(int height, int width, int escapement, int orientation, int weight, + uint italic, uint underline, uint strikeout, uint charSet, uint outputPrecision, uint clipPrecision, + uint quality, uint pitchAndFamily, string face); + + [DllImport("gdi32.dll", ExactSpelling = true)] + private static extern nint SelectObject(nint device, nint obj); + + [DllImport("gdi32.dll", ExactSpelling = true, CharSet = CharSet.Unicode)] + private static extern int GetTextFaceW(nint device, int count, StringBuilder face); + + [DllImport("gdi32.dll", ExactSpelling = true, CharSet = CharSet.Unicode)] + [return: MarshalAs(UnmanagedType.Bool)] + private static extern bool GetTextExtentPoint32W(nint device, string text, int count, out TextSize size); + + [DllImport("gdi32.dll", ExactSpelling = true)] + [return: MarshalAs(UnmanagedType.Bool)] + private static extern bool GetTextMetricsW(nint device, out TextMetrics metrics); + + [DllImport("gdi32.dll", ExactSpelling = true)] + private static extern int DeleteObject(nint obj); + + [DllImport("gdi32.dll", ExactSpelling = true)] + private static extern int DeleteDC(nint device); +} diff --git a/src/RvtIO/Print/CircularAnnotations.cs b/src/RvtIO/Print/CircularAnnotations.cs new file mode 100644 index 00000000..3c30431f --- /dev/null +++ b/src/RvtIO/Print/CircularAnnotations.cs @@ -0,0 +1,89 @@ +using RvtIO.Model; +using RvtIO.Pdf; + +namespace RvtIO.Print; + +internal static class CircularAnnotations +{ + private const double FeetToMillimetres = 304.8; + private const double PointsToMillimetres = 25.4 / 72; + + internal sealed record Placement(double X, double Y, double Factor, RevitFileInfo.CircularAnnotationStyle Style); + + internal static IReadOnlyList Project(RvtDocument? document, int? viewId, + double[]? right = null, double[]? up = null) + { + if (viewId is not int view || document?.RawData.CircularAnnotations?.GetValueOrDefault(view) is not { } source) + return []; + var result = new List(); + foreach (var (t, style) in source) + if (ProjectTransform(t, right, up) is { } projected) + result.Add(new(projected.X, projected.Y, projected.Factor, style)); + return result; + } + + internal static (double X, double Y, double Factor)? ProjectTransform(double[] t, double[]? right, double[]? up) + { + double scale = Dot(t[0], t[3], t[6], right, t[0]); + double other = Dot(t[1], t[4], t[7], up, t[4]); + if (!(scale is > 0 and <= 100_000) || Math.Abs(scale - other) > scale * 1e-8 + || Math.Abs(Dot(t[0], t[3], t[6], up, t[3])) > scale * 1e-8 + || Math.Abs(Dot(t[1], t[4], t[7], right, t[1])) > scale * 1e-8) return null; + return (Dot(t[9], t[10], t[11], right, t[9]) * FeetToMillimetres, + Dot(t[9], t[10], t[11], up, t[10]) * FeetToMillimetres, scale); + + static double Dot(double x, double y, double z, double[]? axis, double fallback) => + axis == null ? fallback : x * axis[0] + y * axis[1] + z * axis[2]; + } + + internal static void DrawViewport(PdfPage page, RvtDocument document, Element? view, + IReadOnlyList items, double scale, double originX, double originY, + double minX, double minY, ViewCropFrame? crop) + { + if (items.Count == 0) return; + + double ToX(double x) => originX + (x - minX) / scale; + double ToY(double y) => originY + (y - minY) / scale; + + bool clip = crop != null && view?.ViewAnnotationCropActive != false; + if (clip) + { + var (x0, y0, x1, y1) = SheetComposer.CropContentRect(crop!); + var (left, right, top, bottom) = view?.ViewAnnotationCrop ?? (0, 0, 0, 0); + double x = ToX(x0) - left * FeetToMillimetres; + double y = ToY(y0) - bottom * FeetToMillimetres; + page.BeginClip(x, y, ToX(x1) + right * FeetToMillimetres - x, + ToY(y1) + top * FeetToMillimetres - y); + } + Draw(page, document, items, scale, ToX, ToY); + if (clip) page.EndClip(); + } + + internal static void Draw(PdfPage page, RvtDocument? document, IReadOnlyList items, double scale, + Func toX, Func toY) + { + if (document == null || items.Count == 0) return; + var regular = page.Owner.Font; + if (regular != null && items.Any(item => item.Style.Bold)) page.Owner.BoldFont ??= PdfFonts.TryFindBold(); + foreach (var (originX, originY, factor, style) in items) + { + double unit = FeetToMillimetres * factor / scale; + double x = toX(originX), y = toY(originY); + double pen = PenWidths.TryAnnotationWidth(document, style.BorderPen, out double width) ? width : 0.1; + var circle = style.Outline; + page.DrawFilledCircle(x + circle.X * unit, y + circle.Y * unit, circle.Radius * unit, pen, + Rgb(style.FillColor), Rgb(style.BorderColor)); + if (regular == null) continue; + var text = style.Text; + var font = style.Bold ? page.Owner.BoldFont ?? regular : regular; + var alignment = (text.Flags & 0x80) != 0 ? PdfTextAlignment.Center + : (text.Flags & 0x100) != 0 ? PdfTextAlignment.Right : PdfTextAlignment.Left; + double size = style.FontPoints * PointsToMillimetres * factor / scale; + double baseline = y + text.Oy * unit - size * font.Ascent / font.UnitsPerEm; + page.DrawStyledText(style.Value, x + text.Ox * unit, baseline, size, alignment, 0, style.Bold, Rgb(style.TextColor)); + } + + static PdfColor Rgb(int color) => new((color & 255) / 255d, ((color >> 8) & 255) / 255d, + ((color >> 16) & 255) / 255d); + } +} diff --git a/src/RvtIO/Print/DetailAnnotations.cs b/src/RvtIO/Print/DetailAnnotations.cs new file mode 100644 index 00000000..947fd5cc --- /dev/null +++ b/src/RvtIO/Print/DetailAnnotations.cs @@ -0,0 +1,297 @@ +using RvtIO.BuiltIns; +using RvtIO.Model; +using RvtIO.Parsing; +using RvtIO.Pdf; + +namespace RvtIO.Print; + +internal static class DetailAnnotations +{ + private const double FeetToMillimetres = 304.8; + private const double PointsToMillimetres = 25.4 / 72; + + internal sealed record BreakLine(List<(double X, double Y)> Line, List<(double X, double Y)> Mask); + internal sealed record LayerHatch(List<(double X, double Y)> Polygon, + IReadOnlyList Grids, double AnchorX, double AnchorY, double? PenWidth = null); + internal sealed record LayerBoundary((double X, double Y) Start, (double X, double Y) End, int CategoryId); + + internal static void AddClosedHostCutHatches(List output, RvtDocument document, Element host, + List<(double X, double Y)> ring, double[] right, double[] up, double[] viewOrigin, + List? boundaries = null, double? penWidth = null) + { + if (document.GetElement(host.TypeId)?.SerializedHostTypeLayers is [{ RawMaterialId: > 0 } layer]) + { + AddMaterialCutHatch(output, document, layer.RawMaterialId, ring, right, up, viewOrigin, penWidth); + return; + } + // shortcut: split rectangular cuts until the layer bands can be clipped to a nonrectangular ring. + if (ring.Count != 4) return; + var cuts = ring.Select((a, i) => (X1: a.X, Y1: a.Y, X2: ring[(i + 1) % ring.Count].X, + Y2: ring[(i + 1) % ring.Count].Y)).ToArray(); + if (cuts.Any(c => Math.Abs(c.X1 - c.X2) > 1e-5 && Math.Abs(c.Y1 - c.Y2) > 1e-5)) return; + AddLayerHatches(output, document, host, cuts, right, up, viewOrigin, boundaries, penWidth: penWidth); + } + + internal static void AddMaterialCutHatch(List output, RvtDocument document, int materialId, + List<(double X, double Y)> ring, double[] right, double[] up, double[] viewOrigin, double? penWidth = null) + { + if (CutGrids(document, materialId) is { } grids) + output.Add(new(ring, grids, Project(viewOrigin, right), Project(viewOrigin, up), penWidth)); + } + + internal static void AddLayerHatches(List output, RvtDocument document, Element host, + IEnumerable<(double X1, double Y1, double X2, double Y2)> cuts, + double[] right, double[] up, double[] viewOrigin, List? boundaries = null, + List>? wallSections = null, double? penWidth = null) + { + bool horizontalHost = host.CategoryId is (int)BuiltInCategory.OST_Floors or (int)BuiltInCategory.OST_Ceilings; + if (Math.Abs(up[2] - 1) > 1e-6 + || document.GetElement(host.TypeId)?.SerializedHostTypeLayers is not { Length: > 1 } layers) return; + bool exteriorAtLow = false; + if (!horizontalHost) + { + if (host.CategoryId != (int)BuiltInCategory.OST_Walls + || host.Location is not { CurveType: "Line", Direction: { Length: 3 } axis } + || host.SerializedWallFlipped is not bool flipped + || Math.Abs(axis[0] * right[0] + axis[1] * right[1]) > 1e-6) return; + double normal = (-axis[1] * right[0] + axis[0] * right[1]) * (flipped ? -1 : 1); + if (!(Math.Abs(normal) > 0.999)) return; + exteriorAtLow = normal < 0; + } + else + { + cuts = cuts.Select(c => (c.Y1, c.X1, c.Y2, c.X2)); + } + + var widths = layers.Select(l => BitConverter.Int64BitsToDouble(l.LayerWidthBits) * FeetToMillimetres).ToArray(); + if (widths.Any(w => !(w is >= 0 and < 10000))) return; + var sides = cuts.Where(c => Math.Abs(c.X1 - c.X2) < 0.01 && Math.Abs(c.Y1 - c.Y2) > 0.1) + .Select(c => (X: c.X1, Bottom: Math.Min(c.Y1, c.Y2), Top: Math.Max(c.Y1, c.Y2))).ToArray(); + if (sides.Length < 2) return; + double left = sides.Min(c => c.X), rightmost = sides.Max(c => c.X); + if (Math.Abs(rightmost - left - widths.Sum()) > 0.1) return; + double start = exteriorAtLow ? left : rightmost; + double direction = exteriorAtLow ? 1 : -1; + double anchorX = Project(viewOrigin, right), anchorY = Project(viewOrigin, up); + for (int i = 0; i < layers.Length; i++) + { + double end = start + direction * widths[i]; + if (end != start) + { + var grids = CutGrids(document, layers[i].RawMaterialId); + var layerLines = end > left + 0.01 && end < rightmost - 0.01 ? boundaries : null; + if (wallSections != null) + { + double bandLeft = Math.Min(start, end), bandRight = Math.Max(start, end); + foreach (var section in wallSections) + { + if (grids != null) + { + var band = ElevationPrinter.ClipToWindow(section, bandLeft, bandRight, + double.NegativeInfinity, double.PositiveInfinity); + if (band.Count >= 3 && Math.Abs(PlanPrinter.SignedArea(band)) > 1e-6) + output.Add(new(band, grids, anchorX, anchorY, penWidth)); + } + if (layerLines != null) + { + var ring = section.Select(point => new[] { point.X, point.Y, 0d }).ToList(); + foreach (var (a, b) in ElevationPrinter.CutChords(ring, [end, 0, 0], [1, 0, 0])) + layerLines.Add(new((end, a[1]), (end, b[1]), host.CategoryId!.Value)); + } + } + } + else if (grids != null || layerLines != null) + foreach (var a in sides.Where(c => Math.Abs(c.X - left) < 0.01)) + foreach (var b in sides.Where(c => Math.Abs(c.X - rightmost) < 0.01)) + { + double low = Math.Max(a.Bottom, b.Bottom), high = Math.Min(a.Top, b.Top); + if (high <= low) continue; + if (grids != null) + output.Add(new([Point(start, low), Point(end, low), Point(end, high), Point(start, high)], + grids, anchorX, anchorY, penWidth)); + layerLines?.Add(new(Point(end, low), Point(end, high), host.CategoryId!.Value)); + } + } + start = end; + } + + (double X, double Y) Point(double across, double along) => + horizontalHost ? (along, across) : (across, along); + } + + internal static IReadOnlyList? CutGrids(RvtDocument document, int materialId) + { + if (document.RawData.MaterialPatterns?.TryGetValue(materialId, out var material) != true + || document.RawData.FillPatterns?.TryGetValue(material.CutPatternId, out var pattern) != true + || pattern.Grids.Count == 0 || !pattern.Grids.All(grid => + grid.Target == 0 && double.IsFinite(grid.Angle) && double.IsFinite(grid.Offset) + && Math.Abs(grid.Offset) > 0.0001 && double.IsFinite(grid.OriginX) && double.IsFinite(grid.OriginY) + && double.IsFinite(grid.Shift) && grid.Segments.All(length => length is >= 0 and < 100) + && (grid.Segments.Length == 0 || grid.Segments.Sum() > 0.0001))) return null; + return pattern.Grids; + } + + internal static List BreakLines(RvtDocument document, int viewId, double[] right, double[] up) + { + var result = new List(); + var hidden = document.RawData.ViewHiddenElements?.GetValueOrDefault(viewId); + foreach (var element in document.Elements) + { + if (element.OwnerViewId != viewId || hidden?.Contains(element.Id) == true + || element.FamilyName != "M_Break Line" + || element.Transform is not { Origin.Length: 3, BasisX.Length: 3, BasisY.Length: 3 } transform + || document.GetElement(transform.SymbolId)?.DetailBreak is not { } profile) continue; + var line = profile.Line.Select(p => ToView(p.X, p.Y)).ToList(); + var mask = new List<(double X, double Y)>(line) + { + ToView(profile.Line[^1].X, profile.MaskY), ToView(profile.Line[0].X, profile.MaskY) + }; + result.Add(new(line, mask)); + + (double X, double Y) ToView(double x, double y) + { + double[] world = new double[3]; + for (int k = 0; k < world.Length; k++) + world[k] = transform.Origin[k] + x * transform.BasisX[k] + y * transform.BasisY[k]; + return (Project(world, right), Project(world, up)); + } + } + return result; + } + + internal static IEnumerable BattInsulation( + double ax, double ay, double bx, double by, double width, bool mirrored) + { + double dx = bx - ax, dy = by - ay; + double length = Math.Sqrt(dx * dx + dy * dy); + double radius = width / 6; + double steps = length / radius; + if (!(steps is > 0 and <= 4096)) yield break; + dx /= length; + dy /= length; + for (int i = -1; i < steps; i++) + { + double side = (i % 2 == 0) == mirrored ? 1 : -1; + for (int k = 0; k < 8; k++) + { + double a = Math.PI * k / 8, b = Math.PI * (k + 1) / 8; + if (Stroke(i + 1 - Math.Cos(a), side * (2 + Math.Sin(a)), + i + 1 - Math.Cos(b), side * (2 + Math.Sin(b))) is { } arc) yield return arc; + } + for (int k = 0; k < 6; k++) + { + double a = k / 6.0, b = (k + 1) / 6.0; + if (Stroke(i + Smooth(a), side * (2 - 4 * a), + i + Smooth(b), side * (2 - 4 * b)) is { } bridge) yield return bridge; + } + } + + static double Smooth(double t) => t * t * (3 - 2 * t); + ElevationPrinter.CollectedEdge? Stroke(double x1, double y1, double x2, double y2) + { + if (x2 <= 0 || x1 >= steps) return null; + if (x1 < 0) + { + y1 += (y2 - y1) * (-x1 / (x2 - x1)); + x1 = 0; + } + if (x2 > steps) + { + y2 = y1 + (y2 - y1) * ((steps - x1) / (x2 - x1)); + x2 = steps; + } + return new(ax + radius * (x1 * dx - y1 * dy), ay + radius * (x1 * dy + y1 * dx), + ax + radius * (x2 * dx - y2 * dy), ay + radius * (x2 * dy + y2 * dx), + 0, 0, -1, -1, 0, 0, 0, 0); + } + } + + internal static void DrawCallouts(PdfPage page, RvtDocument document, Element sheet, Element parent, + ViewCropFrame parentCrop, double scale, double originX, double originY) + { + var (x0, y0, x1, y1) = SheetComposer.CropContentRect(parentCrop); + var annotationCrop = parent.ViewAnnotationCrop; + double boundaryPen = Pen(BuiltInCategory.OST_CalloutBoundary, 0.7); + double leaderPen = Pen(BuiltInCategory.OST_CalloutLeaderLine, 0.1); + double headPen = Pen(BuiltInCategory.OST_CalloutHeads, 0.1); + LinePatterns.TryGetDashes(document, (int)BuiltInCategory.OST_CalloutBoundary, out var points); + double[] pattern = points.Select(value => value * PointsToMillimetres).ToArray(); + string number = sheet.LookupParameter(BuiltInParameter.SHEET_NUMBER)?.Value as string ?? ""; + foreach (var viewport in document.Elements) + { + if (viewport.OwnerViewId != sheet.Id || viewport.ViewportViewId is not int viewId + || document.GetElement(viewId) is not { SectionCallout: { } callout, ViewCrop: { Active: true } crop } child + || callout.ParentId != parent.Id || !SameAxis(crop.Right, parentCrop.Right) || !SameAxis(crop.Up, parentCrop.Up)) + continue; + if (document.GetElement(child.TypeId)?.LookupParameter(BuiltInParameter.CALLOUT_TAG)?.Value is not int tagId + || document.GetElement(tagId) is not { } tag + || tag.LookupParameter(BuiltInParameter.CALLOUT_CORNER_SHEET_RADIUS)?.Value is not double cornerFeet + || cornerFeet is <= 0 or > 1 + || tag.LookupParameter(BuiltInParameter.CALLOUT_ATTR_HEAD_TAG)?.Value is not int headId + || document.GetElement(headId) is not { FamilyName: "M_Callout Head", BoundingBox: { Length: 6 } box }) + continue; + double headRadius = (box[3] - box[0]) * FeetToMillimetres / 2; + if (!(headRadius is > 0 and <= 100) || Math.Abs(box[3] - box[0] - box[4] + box[1]) > 1e-6) + continue; + var (left, bottom, right, top) = SheetComposer.CropContentRect(crop); + if (right <= left || top <= bottom || right < x0 || top < y0 || left > x1 || bottom > y1) continue; + left = ToX(left); right = ToX(right); bottom = ToY(bottom); top = ToY(top); + double r = Math.Min(cornerFeet * FeetToMillimetres, Math.Min(right - left, top - bottom) / 2); + double hx = ToX(Project(callout.Head, parentCrop.Right)), hy = ToY(Project(callout.Head, parentCrop.Up)); + double qx = Math.Min(Math.Max(hx, left + r), right - r); + double qy = Math.Min(Math.Max(hy, bottom + r), top - r); + double dx = hx - qx, dy = hy - qy; + double length = Math.Sqrt(dx * dx + dy * dy); + if (!(length > r)) continue; + dx /= length; + dy /= length; + double cx = hx + dx * headRadius, cy = hy + dy * headRadius; + if (annotationCrop is { } pad + && (Math.Min(left, cx - headRadius) < ToX(x0) - pad.Left * FeetToMillimetres + || Math.Max(right, cx + headRadius) > ToX(x1) + pad.Right * FeetToMillimetres + || Math.Min(bottom, cy - headRadius) < ToY(y0) - pad.Bottom * FeetToMillimetres + || Math.Max(top, cy + headRadius) > ToY(y1) + pad.Top * FeetToMillimetres)) continue; + + ElevationPrinter.DrawDatumDashes(page, left + r, bottom, right - r, bottom, pattern, boundaryPen, roundCaps: true); + ElevationPrinter.DrawDatumDashes(page, left + r, top, right - r, top, pattern, boundaryPen, roundCaps: true); + ElevationPrinter.DrawDatumDashes(page, left, bottom + r, left, top - r, pattern, boundaryPen, roundCaps: true); + ElevationPrinter.DrawDatumDashes(page, right, bottom + r, right, top - r, pattern, boundaryPen, roundCaps: true); + Arc(right - r, top - r, 0); + Arc(left + r, top - r, 90); + Arc(left + r, bottom + r, 180); + Arc(right - r, bottom + r, 270); + page.DrawLine(qx + dx * r, qy + dy * r, hx, hy, leaderPen); + page.DrawPolyline(Circle(cx, cy, headRadius, 0, 360, 24), headPen, true, 1); + page.DrawLine(cx - headRadius, cy, cx + headRadius, cy, headPen); + string detail = viewport.LookupParameter(BuiltInParameter.VIEWPORT_DETAIL_NUMBER)?.Value as string ?? ""; + page.DrawText(detail, cx, cy + 1, 12 * PointsToMillimetres, PdfTextAlignment.Center); + page.DrawText(number, cx, cy - 4, 8 * PointsToMillimetres, PdfTextAlignment.Center); + + void Arc(double x, double y, int angle) => + page.DrawPolyline(Circle(x, y, r, angle, 90, 5), boundaryPen); + } + + double Pen(BuiltInCategory category, double fallback) => + PenWidths.TryGetPenNumber(document, (int)category, false, out int pen) + && PenWidths.TryAnnotationWidth(document, pen, out double width) ? width : fallback; + double ToX(double x) => originX + x / scale; + double ToY(double y) => originY + y / scale; + } + + private static (double X, double Y)[] Circle(double x, double y, double radius, double start, double sweep, int segments) + { + var result = new (double X, double Y)[segments + 1]; + for (int i = 0; i <= segments; i++) + { + double angle = (start + sweep * i / segments) * Math.PI / 180; + result[i] = (x + radius * Math.Cos(angle), y + radius * Math.Sin(angle)); + } + return result; + } + + private static bool SameAxis(double[] a, double[] b) => + Math.Abs(a[0] - b[0]) + Math.Abs(a[1] - b[1]) + Math.Abs(a[2] - b[2]) < 1e-6; + + private static double Project(double[] point, double[] axis) => + (point[0] * axis[0] + point[1] * axis[1] + point[2] * axis[2]) * FeetToMillimetres; +} diff --git a/src/RvtIO/Print/ElevationPrinter.AmbientOcclusion.cs b/src/RvtIO/Print/ElevationPrinter.AmbientOcclusion.cs new file mode 100644 index 00000000..729c1b2f --- /dev/null +++ b/src/RvtIO/Print/ElevationPrinter.AmbientOcclusion.cs @@ -0,0 +1,284 @@ +using System.Numerics; +using RvtIO.Pdf; +using Point = (double X, double Y); + +namespace RvtIO.Print; + +public static partial class ElevationPrinter +{ + internal sealed record AmbientPatch(PdfRasterImage Image, double X0, double Y0, double X1, double Y1, + PdfRasterImage? ThroughGlass = null, IReadOnlyList? Glass = null); + + internal sealed record AmbientGlass(List Polygon, List>? Holes, double FarDepth); + + internal sealed class AmbientOcclusion(double ambientFraction, (double X0, double Y0, double X1, double Y1) crop, + bool binaryVisibility = false) + { + private const float RayBias = 0.05f; + private const int RayCount = 24; + // shortcut: a local model-space falloff, replace it when the display kernel is available. + private const float AmbientReach = 1500; + private readonly List _occluders = []; + private readonly List<(List Polygon, List>? Holes, Vector3 Origin, Vector3 Normal, + double Gray, bool OrientDirectLight, bool IgnoreStairExitHits, bool ExcludeSamplesBehindCut)> _receivers = []; + private readonly List _glass = []; + + private readonly record struct Occluder(Vector3 Origin, Vector3 Normal, Vector3 Min, Vector3 Max, + int Axis, List Outline, List>? Holes, bool FrontFaceOnly); + private sealed record Node(Vector3 Min, Vector3 Max, int Start, int Count, Node? Left, Node? Right); + + internal void AddOccluder(List ring, Vector3 normal, List>? holes = null, + bool frontFaceOnly = false) + { + if (ring.Count < 3 || !(normal.LengthSquared() > 0.5f)) return; + Vector3 min = ring[0], max = ring[0]; + foreach (Vector3 point in ring) + { + min = Vector3.Min(min, point); + max = Vector3.Max(max, point); + } + var abs = Vector3.Abs(normal); + int axis = abs.X > abs.Y && abs.X > abs.Z ? 0 : abs.Y > abs.Z ? 1 : 2; + List Flatten(List points) => points.Select(point => Flat(point, axis)).ToList(); + var margin = new Vector3(RayBias); + _occluders.Add(new(ring[0], normal, min - margin, max + margin, axis, Flatten(ring), + holes?.Select(Flatten).ToList(), frontFaceOnly)); + } + + internal void AddReceiver(List polygon, List>? holes, Vector3 origin, Vector3 normal, + double gray = 1, bool orientDirectLight = false, bool ignoreStairExitHits = false, + bool excludeSamplesBehindCut = false) + { + if (normal.Z < -1e-5f) + _receivers.Add((polygon, holes, origin, Vector3.Normalize(normal), gray, orientDirectLight, + ignoreStairExitHits, excludeSamplesBehindCut)); + } + + internal void AddGlazing(List polygon, List>? holes, double farDepth) => + _glass.Add(new(polygon, holes, farDepth)); + + internal IReadOnlyDictionary, AmbientPatch>? Calculate( + IReadOnlyList>? cutCaps = null, double cutDepth = 0) + { + if (_receivers.Count == 0 || _occluders.Count == 0) return null; + var occluders = _occluders.ToArray(); + var tree = Build(occluders, 0, occluders.Length); + var result = new Dictionary, AmbientPatch>(); + Span rays = stackalloc Vector3[RayCount]; + const int gridSize = 3; + Span<(double X, double Y, bool OnFace)> samples = stackalloc (double, double, bool)[gridSize * gridSize]; + Span sampled = stackalloc bool[samples.Length]; + Span behindCut = stackalloc bool[samples.Length]; + foreach (var (polygon, holes, planeOrigin, normal, gray, orientDirectLight, ignoreStairExitHits, + excludeSamplesBehindCut) in _receivers) + { + sampled.Clear(); + behindCut.Clear(); + double left = Math.Max(crop.X0, polygon.Min(p => p.X)); + double right = Math.Min(crop.X1, polygon.Max(p => p.X)); + double bottom = Math.Max(crop.Y0, polygon.Min(p => p.Y)); + double top = Math.Min(crop.Y1, polygon.Max(p => p.Y)); + if (left >= right || bottom >= top) continue; + + var tangent = Vector3.Normalize(Vector3.Cross(normal, + Math.Abs(normal.Z) > 0.9f ? Vector3.UnitX : Vector3.UnitZ)); + var bitangent = Vector3.Cross(normal, tangent); + for (int k = 0; k < rays.Length; k++) + { + float radius = MathF.Sqrt((k + 0.5f) / rays.Length); + float angle = k * MathF.PI * (3 - MathF.Sqrt(5)); + rays[k] = normal * MathF.Sqrt(1 - radius * radius) + + radius * (MathF.Cos(angle) * tangent + MathF.Sin(angle) * bitangent); + } + + bool hasSurfaceSample = false; + for (int j = 0; j < gridSize; j++) + for (int i = 0; i < gridSize; i++) + { + double x = left + (right - left) * (i + 0.5) / gridSize; + double y = bottom + (top - bottom) * (j + 0.5) / gridSize; + bool onFace = PointInPolygon(x, y, polygon) + && holes?.Any(hole => PointInPolygon(x, y, hole)) != true; + hasSurfaceSample |= onFace; + samples[(gridSize - 1 - j) * gridSize + i] = (x, y, onFace); + } + + var rgb = new byte[samples.Length * 3]; + byte unshaded = (byte)Math.Round(255 * gray); + double baseLinear = gray <= 0.04045 ? gray / 12.92 : Math.Pow((gray + 0.055) / 1.055, 2.4); + float Depth(double x, double y) => planeOrigin.Z - (normal.X * ((float)x - planeOrigin.X) + + normal.Y * ((float)y - planeOrigin.Y)) / normal.Z; + double directLightLoss = orientDirectLight ? (1 - ambientFraction) * (1 - Math.Clamp(-normal.Z, 0, 1)) : 0; + List? glass = null; + if (directLightLoss > 0 && _glass.Count > 0) + { + glass = []; + foreach (var pane in _glass) + { + if (pane.Polygon.Max(p => p.X) <= left || pane.Polygon.Min(p => p.X) >= right + || pane.Polygon.Max(p => p.Y) <= bottom || pane.Polygon.Min(p => p.Y) >= top) + continue; + + // The wall depth varies across an oblique face. Only the portion behind the pane + // uses the tone for a transmitted view of the wall. + double Gap(Point point) => Depth(point.X, point.Y) - pane.FarDepth - 0.01; + List Clip(List ring) => ClipHalfPlane(ring, p => Gap(p) > 0, Gap); + var mask = Clip(pane.Polygon); + if (mask.Count >= 3) + glass.Add(pane with { Polygon = mask, Holes = pane.Holes?.Select(Clip).Where(h => h.Count >= 3).ToList() }); + } + } + byte[]? throughGlass = glass is { Count: > 0 } ? new byte[rgb.Length] : null; + if (throughGlass != null) Array.Fill(throughGlass, unshaded); + byte unoccluded = directLightLoss > 0 ? ToTone(baseLinear * (1 - directLightLoss)) : unshaded; + Array.Fill(rgb, unoccluded); + bool hasShadow = unoccluded < unshaded; + for (int i = 0; i < samples.Length; i++) + { + var (x, y, onFace) = samples[i]; + if (!onFace) + { + if (hasSurfaceSample) continue; + // A thin frame may fall between every grid point. + var boundary = holes?.Find(hole => PointInPolygon(x, y, hole)) ?? polygon; + (x, y, _) = ClosestPolygonPoint(x, y, boundary); + } + float z = Depth(x, y); + if (excludeSamplesBehindCut && z > cutDepth + RayBias + && cutCaps?.Any(cap => PointInPolygon(x, y, cap)) == true) + { + behindCut[i] = true; + continue; + } + sampled[i] = true; + var receiver = new Vector3((float)x, (float)y, z); + double blocked = 0; + foreach (var ray in rays) + { + float distance = AmbientReach; + if (!FindHit(tree, occluders, receiver + normal * RayBias, ray, ignoreStairExitHits, ref distance)) + continue; + float relativeDistance = distance / AmbientReach; + blocked += binaryVisibility ? 1 : 1 - relativeDistance * relativeDistance; + } + double ambientLoss = ambientFraction * blocked / RayCount; + byte tone = ToTone(baseLinear * (1 - ambientLoss - directLightLoss)); + int pixel = i * 3; + rgb[pixel] = rgb[pixel + 1] = rgb[pixel + 2] = tone; + if (throughGlass != null) + throughGlass[pixel] = throughGlass[pixel + 1] = throughGlass[pixel + 2] = + ToTone(baseLinear * (1 - ambientLoss)); + hasShadow |= tone < unshaded; + } + if (hasShadow) + { + // Extend valid tones across the cap in the texture so interpolation uses the visible slab. + for (int i = 0; i < behindCut.Length; i++) + { + if (!behindCut[i]) continue; + int nearest = -1; + double best = double.PositiveInfinity; + for (int j = 0; j < sampled.Length; j++) + { + if (!sampled[j]) continue; + double dx = samples[i].X - samples[j].X; + double dy = samples[i].Y - samples[j].Y; + double distance = dx * dx + dy * dy; + if (distance >= best) continue; + nearest = j; + best = distance; + } + if (nearest < 0) continue; + Array.Copy(rgb, nearest * 3, rgb, i * 3, 3); + if (throughGlass != null) + Array.Copy(throughGlass, nearest * 3, throughGlass, i * 3, 3); + } + result.Add(polygon, new(Raster(rgb), left, bottom, right, top, + throughGlass != null ? Raster(throughGlass) : null, glass)); + } + + static PdfRasterImage Raster(byte[] samples) => new(gridSize, gridSize, samples) { Interpolate = true }; + } + return result.Count > 0 ? result : null; + } + + private static byte ToTone(double linear) + { + double srgb = linear <= 0.0031308 ? 12.92 * linear : 1.055 * Math.Pow(linear, 1 / 2.4) - 0.055; + return (byte)Math.Round(255 * srgb); + } + + private static Point Flat(Vector3 p, int axis) => axis switch + { + 0 => (p.Y, p.Z), 1 => (p.X, p.Z), _ => (p.X, p.Y) + }; + + private static Node Build(Occluder[] faces, int start, int count) + { + var min = faces[start].Min; + var max = faces[start].Max; + for (int i = start + 1; i < start + count; i++) + { + min = Vector3.Min(min, faces[i].Min); + max = Vector3.Max(max, faces[i].Max); + } + if (count <= 8) return new(min, max, start, count, null, null); + var spread = max - min; + int axis = spread.X > spread.Y && spread.X > spread.Z ? 0 : spread.Y > spread.Z ? 1 : 2; + Array.Sort(faces, start, count, Comparer.Create((a, b) => + (a.Min[axis] + a.Max[axis]).CompareTo(b.Min[axis] + b.Max[axis]))); + int half = count / 2; + return new(min, max, start, 0, Build(faces, start, half), Build(faces, start + half, count - half)); + } + + private static bool FindHit(Node node, Occluder[] faces, Vector3 origin, Vector3 direction, bool ignoreStairExitHits, + ref float limit) + { + if (!HitsBounds(node.Min, node.Max, origin, direction, limit)) return false; + if (node.Left != null) + { + bool left = FindHit(node.Left, faces, origin, direction, ignoreStairExitHits, ref limit); + bool right = FindHit(node.Right!, faces, origin, direction, ignoreStairExitHits, ref limit); + return left || right; + } + bool found = false; + for (int i = node.Start; i < node.Start + node.Count; i++) + { + ref readonly var face = ref faces[i]; + float dot = Vector3.Dot(face.Normal, direction); + if (Math.Abs(dot) < 1e-6f || ignoreStairExitHits && face.FrontFaceOnly && dot > 0) continue; + float distance = Vector3.Dot(face.Normal, face.Origin - origin) / dot; + if (distance <= RayBias || distance >= limit) continue; + var point = origin + distance * direction; + if (point.X < face.Min.X || point.X > face.Max.X || point.Y < face.Min.Y || point.Y > face.Max.Y + || point.Z < face.Min.Z || point.Z > face.Max.Z) continue; + var (x, y) = Flat(point, face.Axis); + if (PointInPolygon(x, y, face.Outline) && face.Holes?.Any(hole => PointInPolygon(x, y, hole)) != true) + { + limit = distance; + found = true; + } + } + return found; + } + + private static bool HitsBounds(Vector3 min, Vector3 max, Vector3 origin, Vector3 direction, float limit) + { + float near = 0, far = limit; + for (int i = 0; i < 3; i++) + { + if (Math.Abs(direction[i]) < 1e-8f) + { + if (origin[i] < min[i] || origin[i] > max[i]) return false; + continue; + } + float a = (min[i] - origin[i]) / direction[i]; + float b = (max[i] - origin[i]) / direction[i]; + near = Math.Max(near, Math.Min(a, b)); + far = Math.Min(far, Math.Max(a, b)); + if (near > far) return false; + } + return true; + } + } +} diff --git a/src/RvtIO/Print/ElevationPrinter.Billboards.cs b/src/RvtIO/Print/ElevationPrinter.Billboards.cs new file mode 100644 index 00000000..1c0538f4 --- /dev/null +++ b/src/RvtIO/Print/ElevationPrinter.Billboards.cs @@ -0,0 +1,93 @@ +using RvtIO.BuiltIns; +using RvtIO.Model; + +namespace RvtIO.Print; + +public static partial class ElevationPrinter +{ + private readonly record struct BillboardPlane(double X, double Y, double Offset) + { + internal const double Tolerance = 0.1 / FeetToMillimetres; + + internal bool Contains(double[] point) => Math.Abs(X * point[0] + Y * point[1] - Offset) <= Tolerance; + } + + /// Recognize two perpendicular upright planes, with optional triangles at their base. + private static List? CrossedBillboardPlanes(List faces) + { + const double angleTolerance = 1e-5; + if (faces.Any(face => face.OuterVertices is not { Count: 3 } || !face.PolygonMesh + || face.RenderStyleId != null || face.NestedRenderStyleId != null)) return null; + double baseZ = faces.Min(face => face.OuterVertices!.Min(point => point[2])); + var planes = new List(2); + foreach (var face in faces) + { + var vertices = face.OuterVertices!; + if (vertices.All(point => point[2] - baseZ <= BillboardPlane.Tolerance)) continue; + var normal = face.Normal; + double length = Math.Sqrt(normal[0] * normal[0] + normal[1] * normal[1]); + if (length < angleTolerance || Math.Abs(normal[2]) > length * angleTolerance) return null; + if (planes.Any(plane => vertices.All(plane.Contains))) continue; + double x = normal[0] / length, y = normal[1] / length; + if (planes.Count == 2 || planes.Count == 1 + && Math.Abs(planes[0].X * x + planes[0].Y * y) > angleTolerance) return null; + var plane = new BillboardPlane(x, y, x * vertices[0][0] + y * vertices[0][1]); + if (!vertices.All(plane.Contains)) return null; + planes.Add(plane); + } + return planes.Count == 2 ? planes : null; + } + + private static (List> Rings, List Edges)? ProjectSectionBillboard( + List faces, List planes, double[] horizontal, double[] vertical, double[] view, + double planeDepth) + { + if (Math.Abs(vertical[2] - 1) > 1e-9 || Math.Abs(view[2]) > 1e-9) return null; + var depths = faces.SelectMany(face => face.OuterVertices!).Select(point => Project(point, view)).ToArray(); + if (depths.Min() >= planeDepth || depths.Max() <= planeDepth) return null; + + List>[] panels = [[], []]; + foreach (var face in faces) + { + var vertices = face.OuterVertices!; + var ring = vertices.Select(point => (Project(point, horizontal), Project(point, vertical))).ToList(); + double area = PlanPrinter.SignedArea(ring); + if (Math.Abs(area) < 1e-6) continue; + if (area < 0) ring.Reverse(); + int panel = planes.FindIndex(plane => vertices.All(plane.Contains)); + if (panel >= 0) panels[panel].Add(ring); + } + var rings = panels.SelectMany(panel => panel).ToList(); + if (rings.Count == 0) return null; + + const int category = (int)BuiltInCategory.OST_Entourage; + if (panels[0].Count == 0 || panels[1].Count == 0 + || planes.Any(plane => Math.Abs(ViewComponent(plane)) < 1e-9)) + return (rings, OutlineJoinedRings(rings, category, coverOppositeEdges: true).ToList()); + + var (offsetA, slopeA) = ProjectedDepth(planes[0]); + var (offsetB, slopeB) = ProjectedDepth(planes[1]); + // The upright panels exchange depth order at one horizontal coordinate in the section. + var visible = VisiblePanel(0, 1, offsetA - offsetB, slopeA - slopeB).ToList(); + visible.AddRange(VisiblePanel(1, 0, offsetB - offsetA, slopeB - slopeA)); + return (rings, visible); + + (double Offset, double Slope) ProjectedDepth(BillboardPlane plane) + { + double toward = ViewComponent(plane); + double across = plane.X * horizontal[0] + plane.Y * horizontal[1]; + return (plane.Offset * FeetToMillimetres / toward, -across / toward); + } + + double ViewComponent(BillboardPlane plane) => plane.X * view[0] + plane.Y * view[1]; + + IEnumerable VisiblePanel(int current, int other, double offset, double slope) + { + var cover = panels[other].Select(ring => ClipHalfPlane(ring, + point => offset + slope * point.X >= 0, point => offset + slope * point.X)) + .Where(ring => ring.Count >= 3 && Math.Abs(PlanPrinter.SignedArea(ring)) > 1e-6); + return VisibleTerrainEdges(OutlineJoinedRings(panels[current], category, coverOppositeEdges: true), + cover, [], coverBoundary: false, coverOppositeEdges: true); + } + } +} diff --git a/src/RvtIO/Print/ElevationPrinter.Glazing.cs b/src/RvtIO/Print/ElevationPrinter.Glazing.cs new file mode 100644 index 00000000..b832e57f --- /dev/null +++ b/src/RvtIO/Print/ElevationPrinter.Glazing.cs @@ -0,0 +1,88 @@ +using RvtIO.BuiltIns; +using RvtIO.Pdf; +using Point = (double X, double Y); + +namespace RvtIO.Print; + +public static partial class ElevationPrinter +{ + internal sealed class AmbientGlazing(double light, bool detailCallout = false) + { + private const double PlaneTolerance = 0.01; + private readonly Dictionary, Surface> _surfaces = []; + private readonly Dictionary _materials = []; + + private readonly record struct Surface(double Near, double Far, double X0, double Y0, double X1, double Y1, + double? Gray, double Transmission, bool Pane); + + internal bool HasPanes { get; private set; } + + internal void Add(RvtDocument document, List points, double near, double far, int? materialId, bool glazing) + { + double? gray = null; + double transmission = 0; + if (materialId is > 0 and int id) + { + if (!_materials.TryGetValue(id, out var appearance)) + { + var material = document.GetElement(id); + if (material is { HasShadingAppearance: true } + && material.LookupParameter(BuiltInParameter.MATERIAL_PARAM_COLOR)?.Value is int rgb + && rgb is >= 0 and <= 0xffffff) + appearance.Gray = ((rgb & 255) * 0.2126 + ((rgb >> 8) & 255) * 0.7152 + + ((rgb >> 16) & 255) * 0.0722) / 255; + appearance.Transmission = material?.SerializedMaterialTransparency ?? 0; + _materials.Add(id, appearance); + } + (gray, transmission) = appearance; + } + bool pane = glazing && gray != null && transmission is > 0 and <= 1; + HasPanes |= pane; + _surfaces.Add(points, new(near, far, points.Min(p => p.X), points.Min(p => p.Y), + points.Max(p => p.X), points.Max(p => p.Y), gray, transmission, pane)); + } + + internal bool IsPane(List points) => _surfaces.GetValueOrDefault(points).Pane; + + internal double? AmbientBackgroundGray(List points) + => !detailCallout && _surfaces.TryGetValue(points, out var pane) && pane.Pane + ? (1 - pane.Transmission) * pane.Gray!.Value + pane.Transmission * light : null; + + internal void Draw(PdfPage page, ElevationContent content, List points, + IReadOnlyList> paneRings, Func toX, Func toY, + Func, IReadOnlyList>, List>> faceRings) + { + var pane = _surfaces[points]; + double reflection = (1 - pane.Transmission) * pane.Gray!.Value; + if (detailCallout) + { + // shortcut: blend over the opaque page base, until transparent backing is decoded for callouts. + page.FillPolygonUnion(paneRings, reflection + pane.Transmission); + return; + } + page.FillPolygonUnion(paneRings, reflection + pane.Transmission * light); + page.BeginPolygonClip(paneRings); + if (content.AmbientTones?.GetValueOrDefault(points) is { } background) + { + double x = toX(background.X0), y = toY(background.Y0); + page.DrawImage(background.Image, x, y, toX(background.X1) - x, toY(background.Y1) - y); + } + foreach (var (back, _, _) in content.Faces) + { + // Only planes wholly behind the pane are repainted. The existing painter's ordering + // and inner rings keep nearer solid infill and empty openings distinct. + if (!_surfaces.TryGetValue(back, out var surface) || surface.Near < pane.Far + PlaneTolerance + || surface.Transmission > 0 || surface.X0 >= pane.X1 || surface.X1 <= pane.X0 + || surface.Y0 >= pane.Y1 || surface.Y1 <= pane.Y0) + continue; + double fill = surface.Gray is double gray ? reflection + pane.Transmission * light * gray : 1; + var projected = back.Select(point => (toX(point.X), toY(point.Y))).ToList(); + if (content.FaceOpenings?.GetValueOrDefault(back) is { } holes) + page.FillPolygonUnion(faceRings(projected, holes), fill); + else + page.DrawPolyline(projected, 0, true, fill); + } + page.EndClip(); + } + } +} diff --git a/src/RvtIO/Print/ElevationPrinter.MeshSilhouette.cs b/src/RvtIO/Print/ElevationPrinter.MeshSilhouette.cs new file mode 100644 index 00000000..35ff5124 --- /dev/null +++ b/src/RvtIO/Print/ElevationPrinter.MeshSilhouette.cs @@ -0,0 +1,82 @@ +using RvtIO.Geometry.Meshing; +using RvtIO.Model; + +namespace RvtIO.Print; + +public static partial class ElevationPrinter +{ + private static List? ProjectSectionMeshSilhouette(GeometryData geometry, + double[] horizontal, double[] vertical, double[] direction, double planeDepth, int elementId, int category, + bool multipleRevolvedNodes) + { + if (geometry is not { BrepSolids.Count: > 1, UnresolvedSymbol: false, PlacedSymbolBox: false, + PlacedSymbolClipped: false, UntriangulatedFaces: 0, MeshNodes: { Count: > 0 } nodes } + || geometry.BrepSolids.Any(solid => !solid.IsClosed) + || nodes.Any(node => node.Ghost || node.Faces.Any(face => + face.SurfaceKind is not (SurfaceKind.Plane or SurfaceKind.Cylinder or SurfaceKind.Revolved))) + || (multipleRevolvedNodes + ? nodes.Count < 2 || nodes.Any(node => !node.Faces.Any(face => face.SurfaceKind == SurfaceKind.Revolved)) + : nodes.Count != 1)) + return null; + + var revolvedMarkers = nodes.SelectMany(node => node.Faces.Where(face => face.SurfaceKind == SurfaceKind.Revolved) + .Select(face => (node.Node, (uint)face.Marker))).ToHashSet(); + if (!geometry.Faces.Any(face => !face.PlaneSurface + && revolvedMarkers.Contains((face.GeometryNode, face.MeshMarker)))) + return null; + + var assigned = geometry.BrepSolids.SelectMany(solid => solid.FaceIndices).ToHashSet(); + if ((!multipleRevolvedNodes && assigned.Count != geometry.Faces.Count) + || assigned.Any(index => (uint)index >= geometry.Faces.Count)) + return null; + + var rings = new List>(); + var depths = new List(); + for (int i = 0; i < geometry.Faces.Count; i++) + { + var face = geometry.Faces[i]; + if (face.CurvedSurface || face.InnerVertices is { Count: > 0 } || face.InnerLoops is { Count: > 0 } + || face.OuterVertices is not { Count: >= 3 } vertices + || vertices.Any(point => point.Length != 3 || !point.All(double.IsFinite))) + return null; + + var vertexDepths = vertices.Select(point => Project(point, direction)).ToArray(); + if (vertexDepths.Any(depth => depth <= planeDepth + 1e-6)) return null; + var ring = vertices.Select(point => (Project(point, horizontal), Project(point, vertical))).ToList(); + double area = PlanPrinter.SignedArea(ring); + if (Math.Abs(area) < 1e-6) continue; + // Unassigned display faces may be edge-on in this view. A visible open face uses the fallback. + if (!assigned.Contains(i)) return null; + if (area < 0) + { + ring.Reverse(); + Array.Reverse(vertexDepths); + } + rings.Add(ring); + depths.Add(vertexDepths); + } + + var strokes = new List(); + foreach (var edge in OutlineJoinedRings(rings, category, coverOppositeEdges: true, retainSource: true)) + { + var (ringIndex, first) = edge.SourceRingEdge!.Value; + var ring = rings[ringIndex]; + int second = (first + 1) % ring.Count; + var a = ring[first]; + var b = ring[second]; + double dx = b.X - a.X, dy = b.Y - a.Y; + double lengthSquared = dx * dx + dy * dy; + double DepthAt(double x, double y) => depths[ringIndex][first] + + (depths[ringIndex][second] - depths[ringIndex][first]) + * ((x - a.X) * dx + (y - a.Y) * dy) / lengthSquared; + double start = DepthAt(edge.X1, edge.Y1), end = DepthAt(edge.X2, edge.Y2); + double mid = (start + end) / 2; + strokes.Add(edge with + { + Depth = mid, MidDepth = mid, NearDepth = Math.Min(start, end), + SourceRingEdge = null, SilhouetteOwnerId = elementId, + }); + } + return strokes.Count > 0 ? strokes : null; + } +} diff --git a/src/RvtIO/Print/ElevationPrinter.RailingTubes.cs b/src/RvtIO/Print/ElevationPrinter.RailingTubes.cs new file mode 100644 index 00000000..7ffffee7 --- /dev/null +++ b/src/RvtIO/Print/ElevationPrinter.RailingTubes.cs @@ -0,0 +1,238 @@ +using RvtIO.BuiltIns; +using RvtIO.Model; +using RvtIO.Parsing; + +namespace RvtIO.Print; + +public static partial class ElevationPrinter +{ + private static IEnumerable<(GeoFace Face, bool Tube)> SectionFaces(RvtDocument document, Element element, + GeometryData geometry, bool renderTubes, double[] horizontal, double[] vertical, double[] view, double[] origin, + bool renderRoundShafts, double maxElevationTubeDiameter, List elevationTubeEdges) + { + var replaced = new HashSet(); + if (renderRoundShafts) + foreach (var (shaft, facets) in ProjectRoundShafts(document, geometry, horizontal, vertical, view, origin, + element.CategoryId == (int)BuiltInCategory.OST_StructuralColumns)) + { + replaced.UnionWith(facets); + yield return (shaft, true); + } + if ((renderTubes || maxElevationTubeDiameter > 0) && element.SerializedBaseRailingSymbolId is int id + && document.GetElement(id) is { NativeRecordClass: 492, Geometry: { } source } + && geometry.Instances?.Where(instance => instance.SymbolId == id).Take(2).ToArray() + is [{ Transform: { Length: 12 } transform }] + && ElementBuilder.IsRigidPlacement(transform)) + { + // Face handles are local to a GRep. Check the placed vertices as well as the source handle. + var placed = geometry.Faces.Where(face => face.MeshMarker != 0 && face.OuterVertices is { Count: >= 3 }) + .ToLookup(face => (face.MeshMarker, Key(face.OuterVertices![0]))); + var cylinders = source.Faces.Where(face => face.SourceFace != 0 && face.CurvedSurface + && face.AnalyticCylinderOrigin is { Length: 3 } && face.AnalyticCylinderAxis is { Length: 3 } + && face.AnalyticCylinderRadius is > 0 and < double.PositiveInfinity && face.OuterVertices is { Count: >= 3 }) + .GroupBy(face => (face.GeometryNode, Centre: Key(face.AnalyticCylinderOrigin!), + Axis: Key(face.AnalyticCylinderAxis!), face.AnalyticCylinderRadius)); + foreach (var cylinder in cylinders) + { + // shortcut: two paired analytic sides of a straight rail segment. + if (cylinder.Select(face => face.SourceFace).Distinct().Count() != 2 + || !renderTubes && 2 * cylinder.Key.AnalyticCylinderRadius > maxElevationTubeDiameter) continue; + var patches = new List(); + foreach (var face in cylinder) + { + var expected = face.OuterVertices!.Select(point => PlaceProjectionPoint(point, transform)).ToArray(); + var match = placed[(face.SourceFace, Key(expected[0]))].FirstOrDefault(candidate => + candidate.OuterVertices!.Count == expected.Length + && candidate.OuterVertices.Zip(expected).All(pair => Key(pair.First) == Key(pair.Second))); + if (match == null) break; + patches.Add(match); + } + if (patches.Count != cylinder.Count()) continue; + + if (!renderTubes) + { + var (x, y, z) = cylinder.Key.Axis; + double[] axis = + [ + x * transform[0] + y * transform[3] + z * transform[6], + x * transform[1] + y * transform[4] + z * transform[7], + x * transform[2] + y * transform[5] + z * transform[8], + ]; + if (Math.Abs(Project(axis, horizontal, 1)) <= 1e-9) continue; + var centre = cylinder.Key.Centre; + var placedCentre = PlaceProjectionPoint([centre.X, centre.Y, centre.Z], transform); + var vertices = patches.SelectMany(patch => patch.OuterVertices!); + double axisLengthSquared = Project(axis, axis, 1); + double centreAlong = Project(placedCentre, axis, 1); + double from = (vertices.Min(point => Project(point, axis, 1)) - centreAlong) / axisLengthSquared; + double to = (vertices.Max(point => Project(point, axis, 1)) - centreAlong) / axisLengthSquared; + double startDepth = Project(placedCentre, view); + double forward = Project(axis, view); + double near = Project(origin, view, 1); + if (forward > 1e-9) from = Math.Max(from, (near - startDepth) / forward); + else if (forward < -1e-9) to = Math.Min(to, (near - startDepth) / forward); + else if (startDepth < near) continue; + if (!(to > from)) continue; + // A tube narrower than its print stroke inks once along the placed analytic axis. + double At(double t, double[] direction) => Project(placedCentre, direction) + t * Project(axis, direction); + double mid = At((from + to) / 2, view); + elevationTubeEdges.Add(new(At(from, horizontal), At(from, vertical), At(to, horizontal), At(to, vertical), + mid, mid, -1, -1, 0, 0, 0, 0, false, element.CategoryId ?? 0, + Math.Min(At(from, view), At(to, view)))); + continue; + } + + var points = patches.SelectMany(patch => + ClipBehind(patch.OuterVertices!.Select(point => + point.Select(value => value * FeetToMillimetres).ToArray()).ToList(), origin, view)); + var hull = ProjectedRailHull(points, horizontal, vertical, view); + if (hull.Count < 3) continue; + replaced.UnionWith(patches); + yield return (new GeoFace + { + OuterVertices = hull.Select(point => point.Select(value => value / FeetToMillimetres).ToArray()).ToList(), + Normal = view, + }, true); + } + } + foreach (var face in geometry.Faces) + if (!replaced.Contains(face)) yield return (face, false); + + static (double X, double Y, double Z) Key(double[] point) => (point[0], point[1], point[2]); + } + + private static double[] PlaceProjectionPoint(double[] p, double[] t) => + [ + t[9] + p[0] * t[0] + p[1] * t[3] + p[2] * t[6], + t[10] + p[0] * t[1] + p[1] * t[4] + p[2] * t[7], + t[11] + p[0] * t[2] + p[1] * t[5] + p[2] * t[8], + ]; + + private static IEnumerable<(GeoFace Shaft, GeoFace[] Facets)> ProjectRoundShafts(RvtDocument document, + GeometryData geometry, double[] horizontal, double[] vertical, double[] view, double[] origin, bool column) + { + if (Math.Abs(vertical[2] - 1) > 1e-9 || origin.Length != 3 + || geometry.Instances is not [{ Transform: { Length: 12 } transform } instance] + || !ElementBuilder.IsRigidPlacement(transform) || Math.Abs(Math.Abs(transform[8]) - 1) > 1e-9 + || document.GetElement(instance.SymbolId)?.Geometry is not { BrepSolids: { } solids } symbol + || geometry.Faces.Count != symbol.Faces.Count) yield break; + + foreach (var indices in ShaftFaceIndices()) + { + var native = indices.Select(index => symbol.Faces[index]).ToArray(); + var facets = indices.Select(index => geometry.Faces[index]).ToArray(); + var sides = native.Where(face => face.AnalyticCylinderRadius > 0).ToArray(); + if (sides.Length < 2 || column && (native.Length != sides.Length + 2 + || native.Except(sides).Any(face => !face.PlaneSurface || Math.Abs(face.Normal[2]) < 1 - 1e-9)) + || sides[0] is not { AnalyticCylinderOrigin: { Length: 3 } axisOrigin, + AnalyticCylinderRadius: > 0 and < double.PositiveInfinity and double radius } + || sides.Any(face => face.AnalyticCylinderAxis is not { Length: 3 } axis || Math.Abs(Math.Abs(axis[2]) - 1) > 1e-9 + || face.AnalyticCylinderRadius != radius || face.AnalyticCylinderOrigin?.SequenceEqual(axisOrigin) != true) + || (facets[0].RenderStyleId ?? facets[0].NestedRenderStyleId) is not (> 0 and int material) + || facets.Any(face => (face.RenderStyleId ?? face.NestedRenderStyleId) != material) + || !native.Zip(facets).All(pair => pair.First.OuterVertices is { Count: >= 3 } source + && pair.Second.OuterVertices is { } placed && source.Count == placed.Count + && source.Zip(placed).All(points => PlaceProjectionPoint(points.First, transform).Zip(points.Second) + .All(coordinate => Math.Abs(coordinate.First - coordinate.Second) < 1e-6)))) continue; + + var centre = PlaceProjectionPoint(axisOrigin, transform); + if ((Project(centre, view, 1) - radius) * FeetToMillimetres <= Project(origin, view, 1)) continue; + double bottom = facets.Min(face => face.OuterVertices!.Min(point => point[2])); + double top = facets.Max(face => face.OuterVertices!.Max(point => point[2])); + if (!(top > bottom)) continue; + if (!column && (facets.Any(facet => + Math.Abs(facet.OuterVertices!.Min(p => p[2]) - bottom) > 1e-6 + || Math.Abs(facet.OuterVertices!.Max(p => p[2]) - top) > 1e-6) + || !HasTangent(-1, bottom) || !HasTangent(1, bottom) + || !HasTangent(-1, top) || !HasTangent(1, top))) continue; + // shortcut: the silhouette uses tangent depth, replace it when cylindrical depth tests are supported. + double[] Edge(double offset, double height) => + [centre[0] + horizontal[0] * offset, centre[1] + horizontal[1] * offset, height]; + yield return (new GeoFace + { + OuterVertices = [Edge(-radius, bottom), Edge(radius, bottom), Edge(radius, top), Edge(-radius, top)], + Normal = [-view[0], -view[1], -view[2]], PlaneSurface = true, RenderStyleId = material, + }, facets); + + bool HasTangent(int side, double height) + { + // A trimmed cylinder can omit a tangent. Check that its actual rims span each tangent + // at both ends before replacing the curved sides of a compound solid. + double centreX = Project(centre, horizontal, 1), centreDepth = Project(centre, view, 1); + foreach (var facet in facets) + { + var vertices = facet.OuterVertices!; + for (int i = 0; i < vertices.Count; i++) + { + var a = vertices[i]; + var b = vertices[(i + 1) % vertices.Count]; + if (Math.Abs(a[2] - height) > 1e-6 || Math.Abs(b[2] - height) > 1e-6 + || side * (Project(a, horizontal, 1) - centreX) <= 0 + || side * (Project(b, horizontal, 1) - centreX) <= 0) continue; + double da = Project(a, view, 1) - centreDepth; + double db = Project(b, view, 1) - centreDepth; + if (Math.Min(da, db) <= 1e-6 && Math.Max(da, db) >= -1e-6) return true; + } + } + return false; + } + } + + IEnumerable> ShaftFaceIndices() + { + foreach (var solid in solids.Where(solid => solid.IsClosed)) + { + if (solid.FaceIndices.Any(index => (uint)index >= symbol.Faces.Count)) continue; + if (column) + { + yield return solid.FaceIndices; + continue; + } + var cylinders = solid.FaceIndices.Where(index => symbol.Faces[index] is + { CurvedSurface: true, SourceFace: not 0, AnalyticCylinderRadius: > 0, + AnalyticCylinderOrigin: { Length: 3 }, InnerVertices: not { Count: > 0 }, InnerLoops: not { Count: > 0 } }) + .GroupBy(index => + { + var face = symbol.Faces[index]; + var axis = face.AnalyticCylinderOrigin!; + return (face.GeometryNode, axis[0], axis[1], axis[2], face.AnalyticCylinderRadius); + }); + foreach (var cylinder in cylinders) + if (cylinder.Select(index => symbol.Faces[index].SourceFace).Distinct().Count() == 2) + yield return cylinder.ToArray(); + } + } + } + + private static List ProjectedRailHull(IEnumerable vertices, double[] horizontal, + double[] vertical, double[] view) + { + var points = vertices.Select(point => (X: Dot(point, horizontal), Y: Dot(point, vertical), Point: point)) + .OrderBy(point => point.X).ThenBy(point => point.Y).ThenBy(point => Dot(point.Point, view)) + .DistinctBy(point => (point.X, point.Y)).ToArray(); + if (points.Length < 3) return []; + var hull = new List<(double X, double Y, double[] Point)>(); + AddHalf(points, 0); + hull.RemoveAt(hull.Count - 1); + AddHalf(Enumerable.Reverse(points), hull.Count); + hull.RemoveAt(hull.Count - 1); + return hull.Select(point => point.Point).ToList(); + + void AddHalf(IEnumerable<(double X, double Y, double[] Point)> sorted, int start) + { + foreach (var point in sorted) + { + while (hull.Count > start + 1) + { + var a = hull[^2]; + var b = hull[^1]; + if ((b.X - a.X) * (point.Y - a.Y) > (b.Y - a.Y) * (point.X - a.X)) break; + hull.RemoveAt(hull.Count - 1); + } + hull.Add(point); + } + } + + static double Dot(double[] a, double[] b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; + } +} diff --git a/src/RvtIO/Print/ElevationPrinter.Shadows.cs b/src/RvtIO/Print/ElevationPrinter.Shadows.cs new file mode 100644 index 00000000..96d3c1a7 --- /dev/null +++ b/src/RvtIO/Print/ElevationPrinter.Shadows.cs @@ -0,0 +1,608 @@ +namespace RvtIO.Print; + +using RvtIO.BuiltIns; +using RvtIO.Geometry.Meshing; +using RvtIO.Model; + +public static partial class ElevationPrinter +{ + internal sealed record CastShadow(double Light, List> Rings, + List> Openings); + + internal sealed record VisibleSiteFacets(IReadOnlySet> Sources, + List> Rings, List> Shade, double Light); + + internal sealed class ElevationShadows(double[] h, double[] v, double[] d, double shiftX, double shiftY, double light) + { + private const double PlaneTolerance = 0.01; // mm + private readonly List _casters = []; + private readonly List _receivers = []; + private readonly List _visibleFacets = []; + private readonly List _unlitBillboardFacets = []; + private readonly List _terrainFacets = []; + private readonly List _planting = []; + private readonly List _billboards = []; + private readonly List _modelOccluders = []; + private TerrainOcclusion? _terrain; + internal TerrainOcclusion Terrain => _terrain ??= new(h, v, d, _terrainFacets); + private sealed record ShadowCaster(List Outer, List> Holes, + (double X0, double Y0, double X1, double Y1) Bounds, double MinDepth, bool SiteOnly, bool ProjectsToSoilCut, + bool GroundOnly, int? RoofId); + private sealed record Receiver(List<(double X, double Y)> Face, GeoFace Geometry, + double A, double B, double C, double MaxDepth, bool Site, + (double X0, double Y0, double X1, double Y1) LightBounds, VisibleFacet? Facet = null, bool SoilCut = false, + bool Terrain = false, bool RoundShaft = false, int? RoofId = null); + + internal sealed record VisibleFacet(List<(double X, double Y)> Points, double Dx, double Dy, double Offset, + (double X0, double Y0, double X1, double Y1) Bounds, bool MasksModel = false) + { + internal double DepthAt((double X, double Y) p) => Dx * p.X + Dy * p.Y + Offset; + } + + internal static ElevationShadows? Create((double Azimuth, double Altitude, int GroundLevel, int Intensity)? sun, + double[] h, double[] v, double[] d) + { + // Rays are parameterized by their depth into the view, so the light must come from the front. + if (sun is not { Intensity: > 0 } settings) return null; + double azimuth = settings.Azimuth; + double altitude = settings.Altitude; + double forward = -Math.Cos(azimuth) * Math.Cos(altitude); + if (forward <= 1e-9) return null; + return new(h, v, d, Math.Sin(azimuth) * Math.Cos(altitude) / forward, + Math.Sin(altitude) / forward, 1 - settings.Intensity / 100.0); + } + + internal void AddReceiver(List<(double X, double Y)> points, GeoFace face, double depth, bool roundShaft = false) + { + if (Dot(face.Normal, d) < 0 && (face.InnerLoops is not { Count: > 0 } + || face.InnerVertices is { Count: > 0 })) + _receivers.Add(new(points, face, 0, 0, depth, depth, false, + Bounds(points.Select(p => (p.X + shiftX * depth, p.Y + shiftY * depth))), RoundShaft: roundShaft)); + } + + internal void AddRoofReceiver(List<(double X, double Y)> points, GeoFace face, List corners, int roofId) => + AddPlanarReceiver(points, face, corners, null, roofId: roofId); + + internal void AddTerrainReceiver(List<(double X, double Y)> points, GeoFace face, List corners, + bool placed = true) + { + // shortcut: preserve the existing projection for complex faces until their holes and concave outlines are tessellated. + if (!SupportsTerrainFacet(points, face)) + { + AddPlanarReceiver(points, face, corners, null); + return; + } + + var facet = CreateVisibleFacet(h, v, d, points, face, corners); + if (facet == null) return; + if (placed) facet = facet with { MasksModel = true }; + _terrainFacets.Add(facet); + AddPlanarReceiver(points, face, corners, facet, terrain: true); + } + + private static bool SupportsTerrainFacet(List<(double X, double Y)> points, GeoFace face) => + face.InnerLoops is not { Count: > 0 } && face.InnerVertices is not { Count: > 0 } + && (points.Count <= 3 || Sides(points).All(side => points.All(point => + side.X * point.X + side.Y * point.Y + side.C >= -PlaneTolerance))); + + internal List<(double X, double Y)>? AddSoilCutReceiver( + (double X0, double Y0, double X1, double Y1) crop, double depth, double baseY) + { + double bottom = Math.Max(baseY, crop.Y0); + if (!(crop.Y1 > bottom && crop.X1 > crop.X0)) return null; + List<(double X, double Y)> ring = + [(crop.X0, bottom), (crop.X1, bottom), (crop.X1, crop.Y1), (crop.X0, crop.Y1)]; + var corners = ring.Select(point => Enumerable.Range(0, 3) + .Select(axis => point.X * h[axis] + point.Y * v[axis] + depth * d[axis]).ToArray()).ToList(); + var face = new GeoFace { Normal = [-d[0], -d[1], -d[2]] }; + AddPlanarReceiver(ring, face, corners, null, soilCut: true); + return ring; + } + + internal void AddVisibleFacet(List<(double X, double Y)> points, GeoFace face, List corners, + bool planting = false, bool twoSidedBillboard = false, bool receivesShadow = true) + { + var facet = CreateVisibleFacet(h, v, d, points, face, corners); + if (facet == null) return; + _visibleFacets.Add(facet); + if (planting) _planting.Add(facet); + if (twoSidedBillboard) _billboards.Add(facet); + if (receivesShadow) AddPlanarReceiver(points, face, corners, facet, twoSidedBillboard: twoSidedBillboard); + } + + internal static VisibleFacet? CreateVisibleFacet(double[] h, double[] v, double[] d, + List<(double X, double Y)> points, GeoFace face, List corners) + { + double nz = Dot(face.Normal, d); + if (Math.Abs(nz) < 1e-9) return null; + return new(points, -Dot(face.Normal, h) / nz, -Dot(face.Normal, v) / nz, + Dot(face.Normal, corners[0]) / nz, Bounds(points)); + } + + internal static Dictionary>>? VisiblePlantTones( + List facets, Dictionary tones) + { + if (tones.Count == 0) return null; + facets.Sort((left, right) => left.Bounds.X0.CompareTo(right.Bounds.X0)); + var result = new Dictionary>>(); + foreach (var (facet, gray) in tones) + { + var visible = VisibleParts(facet, facets); + if (visible.Count == 0) continue; + if (!result.TryGetValue(gray, out var rings)) result.Add(gray, rings = []); + rings.AddRange(visible); + } + return result; + } + + internal sealed class TerrainOcclusion(double[] h, double[] v, double[] d, List? facets = null) + { + private readonly List _terrain = facets ?? []; + private readonly List _targets = []; + + internal void AddSurface(List<(double X, double Y)> points, GeoFace face, List corners) + { + if (SupportsTerrainFacet(points, face) && CreateVisibleFacet(h, v, d, points, face, corners) is { } facet) + _terrain.Add(facet with { MasksModel = true }); + } + + internal void AddTarget(List<(double X, double Y)> points, GeoFace face, List corners) + { + double origin = Dot(face.Normal, corners[0]); + if (corners.All(corner => Math.Abs(Dot(face.Normal, corner) - origin) < 1e-6) + && CreateVisibleFacet(h, v, d, points, face, corners) is { } facet) + _targets.Add(facet); + } + + internal void Sort() => _terrain.Sort((a, b) => a.Bounds.X0.CompareTo(b.Bounds.X0)); + + internal Dictionary, List>>? ClippedFaces() + { + var terrain = _terrain.Where(facet => facet.MasksModel).ToList(); + if (terrain.Count == 0) return null; + var result = new Dictionary, List>>(); + foreach (var target in _targets) + { + var visible = VisibleParts(target, terrain); + if (visible.Count != 1 || !ReferenceEquals(visible[0], target.Points)) + result.Add(target.Points, visible); + } + return result.Count > 0 ? result : null; + } + + internal List ClipEdges(List edges, bool cut, bool requireFace = true) + { + if (!_terrain.Any(facet => facet.MasksModel)) return edges; + var result = new List(edges.Count); + foreach (var edge in edges) + { + if (edge.IsCut || requireFace && edge.FaceA < 0 || edge.ViewLineStyleId != 0 || edge.NearDepth is not double depth + || cut && edge.CategoryId is not ((int)BuiltInCategory.OST_BuildingPad + or (int)BuiltInCategory.OST_Walls or (int)BuiltInCategory.OST_StructuralFoundation)) + { + result.Add(edge); + continue; + } + var bounds = (Math.Min(edge.X1, edge.X2), Math.Min(edge.Y1, edge.Y2), + Math.Max(edge.X1, edge.X2), Math.Max(edge.Y1, edge.Y2)); + // shortcut: clip only where terrain is ahead of the entire edge until edge endpoints carry depth. + var covers = TerrainCover(bounds, depth).ToList(); + if (covers.Count == 0) result.Add(edge); + else result.AddRange(VisibleTerrainEdges([edge], covers, [], coverBoundary: false)); + } + return result; + } + + private IEnumerable> TerrainCover( + (double X0, double Y0, double X1, double Y1) bounds, double depth) + { + foreach (var facet in _terrain) + { + var other = facet.Bounds; + if (other.X0 > bounds.X1) break; + if (!facet.MasksModel || other.X1 < bounds.X0 || other.Y1 < bounds.Y0 || other.Y0 > bounds.Y1) + continue; + double Difference((double X, double Y) point) => depth - facet.DepthAt(point) - PlaneTolerance; + var cover = ClipHalfPlane(facet.Points, p => Difference(p) > 0, Difference); + if (HasArea(cover)) yield return cover; + } + } + } + + internal void AddModelOccluder(List<(double X, double Y)> points, double[] normal, + double[] corner, double depth, List>? holes) => + AddOccluder(_modelOccluders, h, v, d, points, normal, corner, depth, holes); + + private static void AddOccluder(List occluders, double[] h, double[] v, double[] d, + List<(double X, double Y)> points, double[] normal, double[] corner, double depth, + List>? holes) + { + double nd = Dot(normal, d); + double dx = 0, dy = 0; + if (Math.Abs(nd) > 1e-10) + { + dx = -Dot(normal, h) / nd; + dy = -Dot(normal, v) / nd; + depth = Dot(normal, corner) / nd; + } + + if (points.Count == 3 && holes is not { Count: > 0 }) + { + occluders.Add(new(points, dx, dy, depth, Bounds(points))); + return; + } + + var vertices = points.ToList(); + var loops = new List { Enumerable.Range(0, points.Count).ToArray() }; + foreach (var hole in holes ?? []) + { + loops.Add(Enumerable.Range(vertices.Count, hole.Count).ToArray()); + vertices.AddRange(hole); + } + var outer = new bool[loops.Count]; + outer[0] = true; + foreach (var (a, b, c) in GeTess.TriangulateProfile(vertices, loops, outer)) + { + var triangle = new List<(double X, double Y)> { vertices[a], vertices[b], vertices[c] }; + occluders.Add(new(triangle, dx, dy, depth, Bounds(triangle))); + } + } + + internal sealed class PlantingOutlines(double[] h, double[] v, double[] d, double viewPlaneDepth, + ElevationShadows? shadows) + { + private readonly List _trees = []; + private readonly List _model = []; + + internal sealed class Mesh + { + internal readonly List Facets = []; + internal readonly Dictionary<((long, long, long), (long, long, long)), + (double[] A, double[] B, VisibleFacet? Source)> Edges = []; + } + + internal void AddFacet(Mesh tree, List world, List<(double X, double Y)> ring, GeoFace face, + List corners) + { + var facet = HasArea(ring) ? CreateVisibleFacet(h, v, d, ring, face, corners) : null; + if (facet != null) tree.Facets.Add(facet); + for (int i = 0; i < world.Count; i++) + { + var a = world[i]; + var b = world[(i + 1) % world.Count]; + var first = Key(a); + var second = Key(b); + var key = first.CompareTo(second) < 0 ? (first, second) : (second, first); + if (!tree.Edges.TryAdd(key, (a, b, facet))) tree.Edges[key] = default; + } + + static (long, long, long) Key(double[] point) => ((long)Math.Round(point[0] / PlaneTolerance), + (long)Math.Round(point[1] / PlaneTolerance), (long)Math.Round(point[2] / PlaneTolerance)); + } + + internal void AddTree(Mesh tree) + { + if (tree.Facets.Count > 0) _trees.Add(tree); + } + + internal void AddModelOccluder(List<(double X, double Y)> points, double[] normal, + double[] corner, double depth, List>? holes) + { + if (shadows == null) + AddOccluder(_model, h, v, d, points, normal, corner, depth, holes); + } + + internal IEnumerable Project(List> ground) + { + if (_trees.Count == 0) yield break; + var covers = (shadows?._modelOccluders ?? _model).Concat(_trees.SelectMany(tree => tree.Facets)) + .OrderBy(facet => facet.Bounds.X0).ToList(); + foreach (var (a, b, source) in _trees.SelectMany(tree => tree.Edges.Values)) + { + if (source == null) continue; + double start = Dot(a, d) - viewPlaneDepth, end = Dot(b, d) - viewPlaneDepth; + if (start < 0 && end < 0) continue; + double x0 = Dot(a, h), y0 = Dot(a, v), x1 = Dot(b, h), y1 = Dot(b, v); + if (start < 0 || end < 0) + { + double t = start / (start - end); + double x = x0 + t * (x1 - x0), y = y0 + t * (y1 - y0); + if (start < 0) (x0, y0) = (x, y); + else (x1, y1) = (x, y); + } + var edge = new CollectedEdge(x0, y0, x1, y1, 0, 0, -1, -1, 0, 0, 0, 0, + false, (int)BuiltInCategory.OST_Planting); + foreach (var span in VisibleTerrainEdges([edge], GroundAndCloser(edge, source), [], coverBoundary: false)) + yield return span; + } + + IEnumerable> GroundAndCloser(CollectedEdge edge, VisibleFacet source) + { + foreach (var ring in ground) yield return ring; + double left = Math.Min(edge.X1, edge.X2), right = Math.Max(edge.X1, edge.X2); + double low = Math.Min(edge.Y1, edge.Y2), high = Math.Max(edge.Y1, edge.Y2); + foreach (var cover in covers) + { + if (cover.Bounds.X0 > right) break; + if (ReferenceEquals(source, cover) || cover.Bounds.X1 < left + || cover.Bounds.Y0 > high || cover.Bounds.Y1 < low) continue; + double Difference((double X, double Y) point) => + source.DepthAt(point) - cover.DepthAt(point) - PlaneTolerance; + var mask = ClipHalfPlane(cover.Points, p => Difference(p) > 0, Difference); + if (HasArea(mask)) yield return mask; + } + } + } + } + + internal VisibleSiteFacets? ClipSiteFacetsToModel(Dictionary, CastShadow>? shadows) + { + if ((_planting.Count == 0 && _billboards.Count == 0) || _modelOccluders.Count == 0) return null; + _modelOccluders.Sort((a, b) => a.Bounds.X0.CompareTo(b.Bounds.X0)); + var sources = new HashSet>(); + var rings = new List>(); + var shade = new List>(); + foreach (var facet in _planting) AddVisible(facet, _modelOccluders); + if (_billboards.Count > 0) + { + var covers = _modelOccluders.Concat(_planting).OrderBy(facet => facet.Bounds.X0).ToList(); + foreach (var facet in _billboards) AddVisible(facet, covers); + } + return new(sources, rings, shade, light); + + void AddVisible(VisibleFacet facet, List covers) + { + sources.Add(facet.Points); + var visible = VisibleParts(facet, covers); + rings.AddRange(visible); + if (shadows?.GetValueOrDefault(facet.Points) is { } shadow) + shade.AddRange(visible.Count == 1 && ReferenceEquals(visible[0], facet.Points) + ? shadow.Rings : ClipRings(shadow.Rings, visible)); + } + } + + private void AddPlanarReceiver(List<(double X, double Y)> points, GeoFace face, List corners, + VisibleFacet? facet, bool soilCut = false, bool terrain = false, bool twoSidedBillboard = false, int? roofId = null) + { + double nx = Dot(face.Normal, h), ny = Dot(face.Normal, v); + double viewNormal = Dot(face.Normal, d); + double nz = viewNormal - nx * shiftX - ny * shiftY; + // A two-sided display face receives direct light only from the side visible in the view. + if (twoSidedBillboard && facet != null && (viewNormal < 0 ? nz >= -1e-9 : nz <= 1e-9)) + { + _unlitBillboardFacets.Add(facet); + return; + } + if ((facet == null || terrain) ? !(nz < -1e-9) : Math.Abs(nz) < 1e-9) return; + // In light coordinates (u, v, depth), the receiving plane has depth A*u + B*v + C. + var lightRing = corners.Select(point => LightCoordinates(point, 1)).ToList(); + _receivers.Add(new(points, face, -nx / nz, -ny / nz, Dot(face.Normal, corners[0]) / nz, + lightRing.Max(point => point[2]), !roofId.HasValue, Bounds(lightRing.Select(point => (point[0], point[1]))), + facet, soilCut, terrain, RoofId: roofId)); + } + + internal void AddCaster(GeoFace face, List corners, bool siteOnly = false, bool planting = false, + bool groundOnly = false, int? roofId = null) + { + if (face.InnerLoops is { Count: > 0 } && face.InnerVertices is not { Count: > 0 }) return; + var outer = corners.Select(point => LightCoordinates(point, 1)).ToList(); + if (outer.Any(point => !point.All(double.IsFinite))) return; + var holes = (face.InnerVertices ?? []).Select(ring => + ring.Select(point => LightCoordinates(point, FeetToMillimetres)).ToList()).ToList(); + if (holes.Any(ring => ring.Count < 3 || ring.Any(point => !point.All(double.IsFinite)))) return; + // The foreground faces of the cut's planting projection are the ones facing + // into the view. Edge-on faces can still project along the light direction. + bool projectsToSoilCut = planting && Dot(face.Normal, d) >= -1e-6; + _casters.Add(new(outer, holes, Bounds(outer.Select(point => (point[0], point[1]))), + outer.Min(point => point[2]), siteOnly, projectsToSoilCut, groundOnly, roofId)); + } + + internal Dictionary, CastShadow>? Project(double viewDepth) + { + var result = new Dictionary, CastShadow>(); + var facets = _visibleFacets.OrderBy(facet => facet.Bounds.X0).ToList(); + _terrainFacets.Sort((a, b) => a.Bounds.X0.CompareTo(b.Bounds.X0)); + var visibleCasters = new List(); + if (facets.Count > 0 || _receivers.Any(receiver => !receiver.Site)) + { + double[] near = [0, 0, viewDepth], away = [0, 0, 1]; + foreach (var caster in _casters) + { + if (caster.GroundOnly) continue; + if (caster.MinDepth >= viewDepth) { visibleCasters.Add(caster); continue; } + var outer = ClipBehind(caster.Outer, near, away); + if (outer.Count < 3) continue; + visibleCasters.Add(caster with + { + Outer = outer, + Holes = caster.Holes.Select(hole => ClipBehind(hole, near, away)).ToList(), + Bounds = Bounds(outer.Select(point => (point[0], point[1]))), + MinDepth = viewDepth, + }); + } + } + foreach (var receiver in _receivers) + { + var (face, geometry, a, b, c, maxDepth, site, lightBounds, facet, soilCut, terrain, roundShaft, roofId) = receiver; + var bounds = Bounds(face); + double[] limit = [0, 0, c - PlaneTolerance], normal = [a, b, -1]; + var rings = new List>(); + if (roundShaft && shiftX != 0) + { + // Project the point where the horizontal light ray is tangent to the cylinder. + double radius = (bounds.X1 - bounds.X0) / 2; + double terminator = bounds.X0 + radius - Math.CopySign(radius / Math.Sqrt(1 + shiftX * shiftX), shiftX); + var shade = ClipToWindow(face, shiftX > 0 ? bounds.X0 : terminator, + shiftX > 0 ? terminator : bounds.X1, bounds.Y0, bounds.Y1); + if (PlanPrinter.SignedArea(shade) < 0) shade.Reverse(); + if (HasArea(shade)) rings.Add(shade); + } + foreach (var caster in site && (facet == null || terrain) ? _casters : visibleCasters) + { + if (caster.RoofId != roofId || soilCut && !caster.ProjectsToSoilCut || caster.SiteOnly && !site + || caster.MinDepth >= maxDepth - PlaneTolerance + || caster.Bounds.X0 >= lightBounds.X1 || caster.Bounds.X1 <= lightBounds.X0 + || caster.Bounds.Y0 >= lightBounds.Y1 || caster.Bounds.Y1 <= lightBounds.Y0) continue; + if (!AddRing(caster.Outer, false)) continue; + foreach (var hole in caster.Holes) AddRing(hole, true); + } + if (rings.Count == 0) continue; + if (facet != null) + { + rings = ClipToVisibleFacet(rings, facet, terrain ? _terrainFacets : facets); + if (rings.Count == 0) continue; + } + var openings = (geometry.InnerVertices ?? []).Select(ring => ring.Select(point => + (Dot(point, h) * FeetToMillimetres, Dot(point, v) * FeetToMillimetres)).ToList()).ToList(); + result.Add(face, new CastShadow(light, rings, openings)); + + bool AddRing(List polygon, bool hole) + { + var ring = ClipBehind(polygon, limit, normal).Select(point => + { + double depth = a * point[0] + b * point[1] + c; + return (point[0] - depth * shiftX, point[1] - depth * shiftY); + }).ToList(); + ring = ClipToWindow(ring, bounds.X0, bounds.X1, bounds.Y0, bounds.Y1); + double area = PlanPrinter.SignedArea(ring); + if (Math.Abs(area) <= PlaneTolerance * PlaneTolerance) return false; + if ((area > 0) == hole) ring.Reverse(); + rings.Add(ring); + return true; + } + } + foreach (var facet in _unlitBillboardFacets) + { + var shade = VisibleParts(facet, facets); + if (shade.Count > 0) result.Add(facet.Points, new CastShadow(light, shade, [])); + } + return result.Count > 0 ? result : null; + } + + private static List> ClipToVisibleFacet(List> rings, + VisibleFacet facet, List facets) + { + return ClipRings(rings, VisibleParts(facet, facets)); + } + + internal Dictionary, List>> ClippedReceivers( + IReadOnlySet> targets, IReadOnlyList additionalCovers) + { + var visible = new Dictionary, List>>(); + if (targets.Count == 0) return visible; + var facets = _visibleFacets.Concat(additionalCovers).OrderBy(facet => facet.Bounds.X0).ToList(); + foreach (var facet in facets) + { + if (!targets.Contains(facet.Points)) continue; + var parts = VisibleParts(facet, facets); + if (parts.Count != 1 || !ReferenceEquals(parts[0], facet.Points)) + visible.Add(facet.Points, parts); + } + return visible; + } + + private static List> VisibleParts(VisibleFacet facet, + List facets) + { + List> visible = [facet.Points]; + // Intersect each covering facet with the half-plane where it is closer to the view. + foreach (var nearer in facets) + { + if (nearer.Bounds.X0 >= facet.Bounds.X1 || visible.Count == 0) break; + if (ReferenceEquals(facet, nearer) || nearer.Bounds.X1 <= facet.Bounds.X0 + || nearer.Bounds.Y0 >= facet.Bounds.Y1 || nearer.Bounds.Y1 <= facet.Bounds.Y0) continue; + double Difference((double X, double Y) point) => + facet.DepthAt(point) - nearer.DepthAt(point) - PlaneTolerance; + var cover = ClipHalfPlane(nearer.Points, point => Difference(point) > 0, Difference); + if (!HasArea(cover)) continue; + var sides = Sides(cover); + var uncovered = new List>(); + foreach (var polygon in visible) + { + if (!HasArea(ClipConvex(polygon, sides))) + { + uncovered.Add(polygon); + continue; + } + var inside = polygon; + foreach (var (x, y, c) in sides) + { + double Distance((double X, double Y) p) => x * p.X + y * p.Y + c; + var outside = ClipHalfPlane(inside, p => Distance(p) < 0, Distance); + if (HasArea(outside)) uncovered.Add(outside); + inside = ClipHalfPlane(inside, p => Distance(p) >= 0, Distance); + } + } + visible = uncovered; + } + return visible; + } + + private static List> ClipRings(List> rings, + List> visible) + { + var result = new List>(); + foreach (var polygon in visible) + { + var sides = Sides(polygon); + foreach (var ring in rings) + { + var clipped = ClipConvex(ring, sides); + if (HasArea(clipped)) result.Add(clipped); + } + } + return result; + + } + + private static bool HasArea(List<(double X, double Y)> polygon) => + Math.Abs(PlanPrinter.SignedArea(polygon)) > PlaneTolerance * PlaneTolerance; + + private static List<(double X, double Y, double C)> Sides(List<(double X, double Y)> polygon) + { + int winding = Math.Sign(PlanPrinter.SignedArea(polygon)); + var sides = new List<(double X, double Y, double C)>(polygon.Count); + for (int i = 0; i < polygon.Count; i++) + { + var a = polygon[i]; + var b = polygon[(i + 1) % polygon.Count]; + double x = winding * (a.Y - b.Y), y = winding * (b.X - a.X); + sides.Add((x, y, -x * a.X - y * a.Y)); + } + return sides; + } + + private static List<(double X, double Y)> ClipConvex(List<(double X, double Y)> polygon, + List<(double X, double Y, double C)> sides) + { + foreach (var (x, y, c) in sides) + { + double Distance((double X, double Y) p) => x * p.X + y * p.Y + c; + polygon = ClipHalfPlane(polygon, p => Distance(p) >= 0, Distance); + if (polygon.Count < 3) break; + } + return polygon; + } + + private double[] LightCoordinates(double[] point, double units) + { + double depth = Dot(point, d) * units; + return [Dot(point, h) * units + depth * shiftX, Dot(point, v) * units + depth * shiftY, depth]; + } + + private static double Dot(double[] point, double[] axis) => + point[0] * axis[0] + point[1] * axis[1] + point[2] * axis[2]; + + private static (double X0, double Y0, double X1, double Y1) Bounds(IEnumerable<(double X, double Y)> points) + { + double x0 = double.PositiveInfinity, y0 = double.PositiveInfinity; + double x1 = double.NegativeInfinity, y1 = double.NegativeInfinity; + foreach (var (x, y) in points) + { + x0 = Math.Min(x0, x); y0 = Math.Min(y0, y); + x1 = Math.Max(x1, x); y1 = Math.Max(y1, y); + } + return (x0, y0, x1, y1); + } + } +} diff --git a/src/RvtIO/Print/ElevationPrinter.cs b/src/RvtIO/Print/ElevationPrinter.cs index 41ed03f7..98914778 100644 --- a/src/RvtIO/Print/ElevationPrinter.cs +++ b/src/RvtIO/Print/ElevationPrinter.cs @@ -15,18 +15,8 @@ public sealed record ElevationView(int ViewId, string Name, string Direction, in /// A section trace on a plan: the polyline points in model millimetres and whether they are /// the file's decoded extent (bounded: drawn as-is) or a legacy straight-line mark (a ray through the /// two points, extended to the drawing bounds the way an undecodable trace was always drawn). -internal sealed record SectionMark(List<(double X, double Y)> Points, bool Bounded, string Name); - -/// Per-view corrections to a decoded section trace, in model millimetres, measured on the -/// reference export of the sample; records why they are not -/// derivable from the file. -internal static class MeasuredSectionTraceOffsets -{ - internal static readonly Dictionary ByViewName = new() - { - ["Longitudinal Section"] = (3090, 0), - }; -} +internal sealed record SectionMark(List<(double X, double Y)> Points, bool Bounded, string Name, int ViewId = 0, + bool UsesPlanExtent = false); /// /// Prints an elevation from the 3D geometry the reader decodes: every planar face of the model (walls, floors, roofs, @@ -34,7 +24,7 @@ internal static class MeasuredSectionTraceOffsets /// nearest and outlined when it faces the viewer. The view plane itself is not decoded yet, so the direction is taken /// from the view name (North, South, East, West); a section is not printed (see docs/printing.md). /// -public static class ElevationPrinter +public static partial class ElevationPrinter { private const double FeetToMillimetres = 304.8; @@ -101,9 +91,53 @@ internal sealed record ElevationContent( List<(List<(double X, double Y)> Points, double Depth, bool Outline)> Faces, List<(double Y, string Label, double X0, double X1)> Levels, List<(double X, string Name)> Grids, - List<(List<(double X, double Y)> Points, double Depth)> Context, + List<(List<(double X, double Y)> Points, double Depth, bool Terrain)> Context, List Edges, - double MinX, double MinY, double MaxX, double MaxY); + double MinX, double MinY, double MaxX, double MaxY, + TerrainHatch? GroundHatch = null, + IReadOnlyDictionary? NativeLevels = null, + IReadOnlyDictionary? NativeGrids = null, + List? Insulation = null, + IReadOnlyList? DetailBreaks = null, + IReadOnlyList? LayerHatches = null, + IReadOnlyList? AnnotationSymbols = null, + SurfaceHatches? Hatch = null, + IReadOnlyDictionary, ModelHatch>? ModelHatches = null, + IReadOnlyDictionary, CastShadow>? CastShadows = null, + (int Sky, int Horizon, int? Ground)? SkyGradient = null, + List>? SiteSilhouettes = null, + bool OpaqueSection = false, + IReadOnlyList? SiteOutlines = null, + IReadOnlyDictionary, List>>? FaceOpenings = null, + VisibleSiteFacets? ForegroundSite = null, + IReadOnlyList? SectionBands = null, + IReadOnlyList>? DetailCutFaces = null, + AmbientGlazing? Glazing = null, + IReadOnlyDictionary, AmbientPatch>? AmbientTones = null, + IReadOnlyDictionary, double?>? FaceFills = null, + IReadOnlyDictionary, (double Gray, double Opacity)>? DetailGlass = null, + IReadOnlyDictionary, List>>? TerrainClippedFaces = null, + bool KeepDoorDepths = false, + IReadOnlyList>? SectionBillboards = null, + IReadOnlyDictionary>>? PlantTones = null); + + internal sealed record SectionBand(double Left, double Right, ElevationContent Content); + + internal sealed record SurfaceHatches(double AnchorX, double AnchorY, + IReadOnlyDictionary, (Parsing.TfBlockDeserializer.PatternGrid Grid, double Width)> Faces, + IReadOnlyDictionary, IReadOnlyList> DashedFaces, + bool UseClippedLines); + + internal sealed record ModelHatch(IReadOnlyList Grids, + IReadOnlyList> Holes); + + internal sealed record TerrainHatch(double AnchorX, double AnchorY, double BaseY, + IReadOnlyList Profile, IReadOnlyList Grids, + IReadOnlyList>? SectionMasks = null, CastShadow? Shadow = null); + + internal sealed record NativeLevelLine(double Left, double HeadX, double HeadY, double LineEnd, double Radius, + (double X, double Y)? Elbow, int SymbolId = 0); + internal sealed record NativeGridLine(double Bottom, double Top, double Radius); /// Projects the model geometry on the vertical plane of a direction. Null when the model has no face. /// The categories a stair section draws: the stairs, their railings and supports. Treads and @@ -118,12 +152,74 @@ internal sealed record ElevationContent( internal static ElevationContent? Collect(RvtDocument document, string direction, bool stairsOnly = false, Element? planeView = null, (double Width, double Height)? window = null, bool isDetail = false, - (double X0, double Y0, double X1, double Y1)? cropWindow = null) + (double X0, double Y0, double X1, double Y1)? cropWindow = null, int? viewportScale = null) + { + var content = CollectPlane(document, direction, stairsOnly, planeView, window, isDetail, cropWindow, + viewportScale, planeView?.ViewOrigin); + if (direction != "section" || planeView is not + { + SectionViewerId: int viewerId, ViewOrigin: { Length: 3 } origin, + ViewDirection: { Length: 3 } look, ViewHorizontalDirection: { Length: 3 } horizontal, + ViewVerticalDirection: { Length: 3 } vertical, + } || document.RawData.SectionViews?.GetValueOrDefault(viewerId).FrontCut is not { Count: >= 4 } frontCut + || frontCut.Count % 2 != 0) return content; + + const double tolerance = 0.1; // Same model precision as the projected edges. + var points = frontCut.Select(p => (X: Project(p, horizontal), Y: Project(p, vertical), + Depth: Project(p, look))).ToArray(); + if (points[0].X > points[^1].X) Array.Reverse(points); + if (points.Any(p => Math.Abs(p.Y - points[0].Y) > tolerance)) return content; + for (int i = 0; i < points.Length; i += 2) + { + var start = points[i]; + var end = points[i + 1]; + if (end.X - start.X <= tolerance || Math.Abs(end.Depth - start.Depth) > tolerance + || i > 0 && Math.Abs(start.X - points[i - 1].X) > tolerance) return content; + } + + var bands = new List(points.Length / 2); + double originalDepth = Project(origin, look); + for (int i = 0; i < points.Length; i += 2) + { + // A section's end marks bound its plan symbol. The end planes extend to the model crop. + double left = i == 0 ? double.NegativeInfinity : points[i].X; + double right = i + 2 == points.Length ? double.PositiveInfinity : points[i + 2].X; + if (cropWindow is { } crop && (right <= crop.X0 || left >= crop.X1)) continue; + double depthShift = points[i].Depth - originalDepth; + if (Math.Abs(depthShift) <= tolerance) + { + if (cropWindow is { } detail && left <= detail.X0 && right >= detail.X1) return content; + if (content != null) bands.Add(new(left, right, content)); + continue; + } + double delta = depthShift / FeetToMillimetres; + double[] shiftedOrigin = [origin[0] + look[0] * delta, origin[1] + look[1] * delta, + origin[2] + look[2] * delta]; + var bandContent = CollectPlane(document, direction, stairsOnly, planeView, window, isDetail, cropWindow, + viewportScale, shiftedOrigin); + if (bandContent != null) + bands.Add(new(left, right, bandContent with { Edges = TrimProjectedEdgesAtCuts(bandContent.Edges).ToList() })); + } + if (bands.Count == 0) return null; + var frame = content ?? bands[0].Content; + return frame with + { + MinX = Math.Min(frame.MinX, bands.Min(band => band.Content.MinX)), + MinY = Math.Min(frame.MinY, bands.Min(band => band.Content.MinY)), + MaxX = Math.Max(frame.MaxX, bands.Max(band => band.Content.MaxX)), + MaxY = Math.Max(frame.MaxY, bands.Max(band => band.Content.MaxY)), + SectionBands = bands, + }; + } + + private static ElevationContent? CollectPlane(RvtDocument document, string direction, bool stairsOnly, + Element? planeView, (double Width, double Height)? window, bool isDetail, + (double X0, double Y0, double X1, double Y1)? cropWindow, int? viewportScale, double[]? projectionOrigin) { double[] planeOrigin = []; bool cut = false; double[] H, V, D; - if (planeView is { ViewOrigin: { Length: 3 } origin, ViewDirection: { Length: 3 } dir, + if (projectionOrigin is { Length: 3 } origin && planeView is { ViewDirection: { Length: 3 } dir, ViewVerticalDirection: { Length: 3 } vert, ViewHorizontalDirection: { Length: 3 } horiz }) { (H, V, D) = (horiz, vert, dir); @@ -169,14 +265,21 @@ internal sealed record ElevationContent( var faces = new List<(List<(double X, double Y)> Points, double Depth, bool Outline)>(); // The plants, the topography and the site surfaces print as the faded background of an elevation, behind the // building, the way the reference export fades them. - var context = new List<(List<(double X, double Y)> Points, double Depth)>(); + var context = new List<(List<(double X, double Y)> Points, double Depth, bool Terrain)>(); // The outlined faces for the shared-edge pass below, with their 3D rings for midpoint depths // and the category of the element they came from (a cut edge inks with its own category's pen). - var edgeFaces = new List<(List<(double X, double Y)> Points, List Ring, double Depth, long Nx, long Ny, long Nz, long Off, int FaceIndex, int CategoryId)>(); + var edgeFaces = new List(); // Every face for the occlusion pass below: its smallest corner depth, so an edge hidden // behind nearer mass is not inked even though the painter's fills cover it only visually. A face counts // as nearer when its nearest corner stands nearer, even a face turned away from the view. - var faceMinDepths = new List(); + var faceOccluders = new List<(double MinDepth, int ElementId, int? HostId, int CategoryId, + PlanarOcclusion? Plane)>(); + var roofInsertFaces = new HashSet(); + var stairMasks = new Dictionary>(); + var railingMaskDepths = new Dictionary(); + var topRailEdges = new List(); + var elevationTubeEdges = new List(); + var viewLines = new List(); // The chords where the cut plane slices through a face, in page coordinates: the cut profile of // solids the plane passes through. Transverse faces never outline, so the cut flag never marks their // boundary, yet the plane carves a profile out of them (a wall cross-section in a detail). Outline @@ -185,29 +288,299 @@ internal sealed record ElevationContent( // type's layer boundaries drawn between them. var rawChords = new List<(double X1, double Y1, double X2, double Y2, double Nx, double Ny, double Nz, int TypeId, int CategoryId, double Depth)>(); + var wallChordSources = new Dictionary(); + var wallCutRegions = new List<(int WallId, int MaterialId, List<(double X, double Y)> Ring)>(); + bool detailPath = window != null || isDetail || cropWindow != null; + int viewScale = planeView?.LookupParameter(BuiltInParameter.VIEW_SCALE)?.Value is int scaleValue && scaleValue > 0 + ? scaleValue : 100; + var surfacePatterns = new Dictionary, + (Parsing.TfBlockDeserializer.PatternGrid Grid, double Width)>(); + var modelHatches = new Dictionary, ModelHatch>(); + var faceFills = new Dictionary, double?>(); + var roundShaftFaces = new HashSet(); + var paintOpenings = new Dictionary, List>>(); + var dashedSurfacePatterns = new Dictionary, IReadOnlyList>(); + var shadows = !cut && !stairsOnly && planeOrigin.Length == 3 && Math.Abs(V[2] - 1) < 1e-9 + ? ElevationShadows.Create(document.RawData.ViewGroundShadows?.GetValueOrDefault(planeView!.Id), H, V, D) + : null; + var shadowTerrainCrop = shadows != null && planeView?.ViewCrop is { Active: true } terrainCrop + && SheetComposer.ViewBasisMatches(planeView, terrainCrop) ? SheetComposer.CropContentRect(terrainCrop) + : ((double X0, double Y0, double X1, double Y1)?)null; + // shortcut: keep the unlit ground backdrop white until its terrain coverage is decoded. + (int Sky, int Horizon, int? Ground)? skyGradient = !cut && !stairsOnly && planeView is { ViewCrop.Active: true } + && Math.Abs(V[2] - 1) < 1e-9 + && document.RawData.ViewSkyGradients?.TryGetValue(planeView.Id, out var sky) == true + ? (sky.Sky, sky.Horizon, shadowTerrainCrop != null ? sky.Ground : null) + : null; + bool fineSection = cut && viewScale <= 50; + bool keepDoorDepths = fineSection && !detailPath; + int? viewDetail = planeOrigin.Length == 3 + ? planeView?.LookupParameter(BuiltInParameter.VIEW_DETAIL_LEVEL)?.Value as int? : null; + bool showSurfacePatterns = planeView != null + && document.RawData.OpaqueViewsWithSurfacePatterns?.Contains(planeView.Id) == true; + // shortcut: surface hatching in fine sections, until the view's coarse surface overrides are decoded. + bool showDraftingPatterns = fineSection && showSurfacePatterns; + var datumCrop = isDetail ? cropWindow : null; + if (datumCrop == null && window == null && cut + && planeView is { ViewAnnotationCropActive: true, ViewCrop: { Active: true } viewCrop } + && SheetComposer.ViewBasisMatches(planeView, viewCrop)) + datumCrop = SheetComposer.CropContentRect(viewCrop); + (double X0, double Y0, double X1, double Y1)? sectionAnnotationCrop = null; + if (datumCrop is { } modelCrop && planeView?.ViewAnnotationCrop is { } offsets) + { + double paperToModel = FeetToMillimetres * (viewportScale ?? viewScale); + sectionAnnotationCrop = (modelCrop.X0 - offsets.Left * paperToModel, modelCrop.Y0 - offsets.Bottom * paperToModel, + modelCrop.X1 + offsets.Right * paperToModel, modelCrop.Y1 + offsets.Top * paperToModel); + } + var sectionCrop = cropWindow; + if (fineSection && window == null && sectionCrop == null && planeView?.ViewCrop is { Active: true } sectionViewCrop + && SheetComposer.ViewBasisMatches(planeView, sectionViewCrop)) + sectionCrop = SheetComposer.CropContentRect(sectionViewCrop); + bool drawTerrainCut = planeOrigin.Length == 3 && !stairsOnly && !detailPath && viewScale >= 100; + bool overviewSection = cut && drawTerrainCut; + bool drawGround = drawTerrainCut || cut && !stairsOnly && sectionCrop != null; + bool detailCallout = planeView?.SectionViewerId is int sectionViewer + && document.RawData.SectionViews?.GetValueOrDefault(sectionViewer).ParentViewId is > 0; + // The backing surfaces are available in a full section, outside the detail cut-cap pipeline. + var glazing = fineSection && !detailPath && showSurfacePatterns && planeView != null + && document.RawData.ViewAmbientLight?.TryGetValue(planeView.Id, out double ambientLight) == true + ? new AmbientGlazing(ambientLight, detailCallout) : null; + bool paintDetailCuts = cut && isDetail && cropWindow != null && planeView != null + && document.RawData.OpaquePlanViews?.Contains(planeView.Id) == true; + bool opaqueSection = cut && planeView != null && document.RawData.OpaquePlanViews?.Contains(planeView.Id) == true; + bool opaqueFineSection = opaqueSection && fineSection && sectionCrop != null; + bool regularFineSection = opaqueFineSection && !detailPath && !detailCallout; + bool regularOpaqueSection = regularFineSection || opaqueSection && drawTerrainCut && showSurfacePatterns; + var sectionTerrainCrop = opaqueSection && drawTerrainCut && showSurfacePatterns + && planeView?.ViewCrop is { Active: true } sectionTerrainViewCrop + && SheetComposer.ViewBasisMatches(planeView, sectionTerrainViewCrop) + ? SheetComposer.CropContentRect(sectionTerrainViewCrop) + : ((double X0, double Y0, double X1, double Y1)?)null; + var sectionTerrain = sectionTerrainCrop.HasValue ? new ElevationShadows.TerrainOcclusion(H, V, D) : null; + var terrainOcclusion = shadowTerrainCrop != null ? shadows!.Terrain : sectionTerrain; + var terrainFillCrop = shadowTerrainCrop ?? sectionTerrainCrop; + var ambient = opaqueFineSection && (!detailPath || paintDetailCuts) && sectionCrop is { } lightCrop + && document.RawData.ViewAmbientFractions?.TryGetValue(planeView!.Id, out double ambientFraction) == true + ? new AmbientOcclusion(ambientFraction, lightCrop, binaryVisibility: regularFineSection) : null; + var plantSun = sectionTerrainCrop.HasValue ? SolarStudyOverlay.StillSunDirection(document.RawData, planeView!.Id) : null; + double plantAmbientFraction = plantSun.HasValue + ? document.RawData.ViewAmbientFractions?.GetValueOrDefault(planeView!.Id, 1) ?? 1 : 1; + var plantFacets = new List(); + var plantTones = new Dictionary(); + var detailGlass = paintDetailCuts && ambient != null + ? new Dictionary, (double Gray, double Opacity)>() + : null; + var roofSectionCrop = opaqueFineSection || paintDetailCuts ? sectionCrop : null; + if (roofSectionCrop == null && opaqueSection && viewDetail == 3 && window == null + && planeView?.ViewCrop is { Active: true } roofViewCrop && SheetComposer.ViewBasisMatches(planeView, roofViewCrop)) + roofSectionCrop = SheetComposer.CropContentRect(roofViewCrop); + List>? modelSectionMasks = roofSectionCrop != null && !paintDetailCuts ? [] : null; + List? layerBoundaries = roofSectionCrop != null ? [] : null; + var sectionedLayerChords = new HashSet(); + bool hasSiteProjection = !stairsOnly && planeOrigin.Length == 3; + bool projectSiteMeshes = hasSiteProjection && (!cut || drawTerrainCut); + List>? siteSilhouettes = + projectSiteMeshes || hasSiteProjection && paintDetailCuts ? [] : null; + bool clipSiteContext = cut && !projectSiteMeshes; + var siteObjects = new List<(List Edges, double Near, bool WireMesh)>(); + var sectionBillboards = new List>(); + var plantMasks = new List<(List<(double X, double Y)> Points, double Far)>(); + var siteModelMasks = new List<(List<(double X, double Y)> Points, double Near, double Far)>(); + double[]? towardViewer = drawTerrainCut && !cut ? [-D[0], -D[1], -D[2]] : null; + double viewPlaneDepth = planeOrigin.Length == 3 + ? planeOrigin[0] * D[0] + planeOrigin[1] * D[1] + planeOrigin[2] * D[2] : 0; + var plantingOutlines = drawTerrainCut && showSurfacePatterns + ? new ElevationShadows.PlantingOutlines(H, V, D, viewPlaneDepth, shadows) : null; + var terrainEdges = new List(); + var terrainPads = new List<(double From, double To)>(); + var padProfile = new List(); + var terrainForeground = new List>(); + var terrainSectionMasks = new List>(); + List>? detailRoofCuts = paintDetailCuts ? [] : null; + List>? detailWallCuts = paintDetailCuts ? [] : null; + var sectionWallFaces = new Dictionary(); + var detailWallOccluders = paintDetailCuts ? new List<(List<(double X, double Y)> Points, double Depth)>() : null; + bool roundElevationShafts = !cut && drawTerrainCut && showSurfacePatterns; + var spanOccluders = fineSection || roundElevationShafts + ? new List<(List<(double X, double Y)> Points, double FarDepth)>() : null; + var spanOpenings = roundElevationShafts + ? new Dictionary, List>>() : null; + var elevationCutEdges = new List(); + var meshSilhouettes = new List(); + var meshCovers = opaqueSection && (drawTerrainCut || regularFineSection) + ? new List<(List<(double X, double Y)> Points, double FarDepth, int ElementId)>() + : null; + TerrainHatch? groundHatch = null; + List? layerHatches = sectionCrop != null && (isDetail || fineSection && window == null) + || roofSectionCrop != null && window == null || towardViewer != null && showSurfacePatterns + ? [] : null; double minX = double.MaxValue, minY = double.MaxValue, maxX = double.MinValue, maxY = double.MinValue; + double maxElevationTubeDiameter = 0; + if (!cut && drawTerrainCut && showSurfacePatterns) + { + int scale = viewportScale ?? viewScale; + double width = PenWidths.TryGetWidth(document, (int)BuiltInCategory.OST_Walls, false, scale, out double pen) + ? pen : 0.2; + maxElevationTubeDiameter = width * scale / FeetToMillimetres; + } + var hiddenElements = planeView == null ? null : document.RawData.ViewHiddenElements?.GetValueOrDefault(planeView.Id); + var hiddenCategories = regularFineSection || paintDetailCuts + ? document.RawData.ViewHiddenCategories?.GetValueOrDefault(planeView!.Id) : null; foreach (var element in document.Elements) { - if (element.CategoryId is (int)BuiltInCategory.OST_Planting or (int)BuiltInCategory.OST_Topography - or (int)BuiltInCategory.OST_Site or (int)BuiltInCategory.OST_Entourage) + if (hiddenElements?.Contains(element.Id) == true + || element.CategoryId is int category && hiddenCategories?.Contains(category) == true) continue; + if (opaqueFineSection && document.RawData.ElemTableIsExact + && element.SerializedOwningElementId is > 0 and int owner + && document.GetElement(owner)?.RootClassIs("Family") == true) continue; + if (regularFineSection && (element.NativeIsSymbol == true || element.SerializedUnplacedOwnerId is > 0 + || element.RootClassIs("FamilySymbol") || element.RootClassName == "FillPatternElem" + || document.RawData.ElemTableIsExact && element.IsDiscovered)) continue; + if (regularOpaqueSection && document.RawData.ElemTableIsExact + && element.CategoryId is ((int)BuiltInCategory.OST_Casework or (int)BuiltInCategory.OST_StructuralColumns + or (int)BuiltInCategory.OST_PlumbingFixtures or (int)BuiltInCategory.OST_Furniture + or (int)BuiltInCategory.OST_StructuralFoundation or (int)BuiltInCategory.OST_SpecialityEquipment) + && !PlacedSiteElement(element)) continue; + if (element.CategoryId == (int)BuiltInCategory.OST_Viewports) continue; + if (element.IsDiscovered && element.CategoryId is (int)BuiltInCategory.OST_Materials + or (int)BuiltInCategory.OST_Constraints or (int)BuiltInCategory.OST_CLines + or (int)BuiltInCategory.OST_LightingFixtureSource) continue; + bool siteCategory = element.CategoryId is (int)BuiltInCategory.OST_Planting + or (int)BuiltInCategory.OST_Topography or (int)BuiltInCategory.OST_Site or (int)BuiltInCategory.OST_Entourage; + bool outlineSiteObject = siteSilhouettes != null + && element.CategoryId == (int)BuiltInCategory.OST_Site + && element.RootClassIs("FamilyInstance"); + if (siteSilhouettes != null && (outlineSiteObject || projectSiteMeshes + && element.CategoryId is ((int)BuiltInCategory.OST_Planting or (int)BuiltInCategory.OST_Entourage))) + { + if (PlacedSiteElement(element) && element.Geometry is { Faces.Count: > 0 } placedGeometry) + { + int silhouetteStart = siteSilhouettes.Count; + var siteLight = outlineSiteObject ? null : shadows; + bool planting = element.CategoryId == (int)BuiltInCategory.OST_Planting; + // The RPC insertion point determines whether its proxy casts onto visible geometry. + bool groundOnly = siteLight != null && planting && Math.Abs(D[2]) < 1e-9 + && element.InstanceOriginXY is { } insertion + && (insertion.X * D[0] + insertion.Y * D[1]) * FeetToMillimetres < viewPlaneDepth + && document.GetElement(element.TypeId)?.LookupParameter(BuiltInParameter.RENDER_RPC_FILENAME) + ?.Value is string { Length: > 0 }; + var tree = planting && plantingOutlines != null && placedGeometry.Faces.All(face => + face.PolygonMesh && face.OuterVertices is { Count: 3 }) + ? new ElevationShadows.PlantingOutlines.Mesh() : null; + var wireFaces = element.CategoryId == (int)BuiltInCategory.OST_Entourage + && element.RootClassIs("FamilyInstance") + ? new List<(List Points, double Facing)>() : null; + var billboardPlanes = wireFaces != null ? CrossedBillboardPlanes(placedGeometry.Faces) : null; + bool crossedBillboard = billboardPlanes != null; + bool shadePlant = planting && plantAmbientFraction < 1 && CrossedBillboardPlanes(placedGeometry.Faces) != null; + if (billboardPlanes != null && opaqueSection && drawTerrainCut + && ProjectSectionBillboard(placedGeometry.Faces, billboardPlanes, H, V, D, viewPlaneDepth) + is { } billboard) + { + sectionBillboards.AddRange(billboard.Rings); + siteObjects.Add((billboard.Edges, viewPlaneDepth, true)); + continue; + } + double objectNear = double.PositiveInfinity; + foreach (var face in placedGeometry.Faces) + { + if (face.OuterVertices is not { Count: >= 3 } vertices) continue; + var world = vertices.Select(point => new[] { point[0] * FeetToMillimetres, + point[1] * FeetToMillimetres, point[2] * FeetToMillimetres }).ToList(); + if (wireFaces != null && face.PolygonMesh + && face.RenderStyleId == null && face.NestedRenderStyleId == null) + wireFaces.Add((world, Project(face.Normal, D, 1))); + if (face.PlaneSurface || vertices.Count == 3) + siteLight?.AddCaster(face, world, siteOnly: !planting, planting: planting, + groundOnly: groundOnly); + var visible = ClipBehind(world, planeOrigin, D); + var ring = visible.Select(point => (Project(point, H, 1), Project(point, V, 1))).ToList(); + double area = PlanPrinter.SignedArea(ring); + if (tree != null) plantingOutlines!.AddFacet(tree, world, ring, face, visible); + if (Math.Abs(area) < 1e-6) continue; + if (area < 0) ring.Reverse(); + siteSilhouettes.Add(ring); + if (plantSun is { } sun && plantAmbientFraction < 1 && vertices.Count == 3 && !face.CurvedSurface + && ElevationShadows.CreateVisibleFacet(H, V, D, ring, face, visible) is { } facet) + { + plantFacets.Add(facet); + if (shadePlant) + { + // The untextured proxy uses both sides of its saved display panels. + double incidence = Math.Abs(face.Normal[0] * sun.X + face.Normal[1] * sun.Y + face.Normal[2] * sun.Z); + double linear = Math.Min(1, plantAmbientFraction + (1 - plantAmbientFraction) * incidence); + double gray = linear <= 0.0031308 ? 12.92 * linear : 1.055 * Math.Pow(linear, 1 / 2.4) - 0.055; + plantTones.Add(facet, (byte)Math.Round(255 * gray)); + } + } + if (planting) plantMasks.Add((ring, visible.Max(point => Project(point, D, 1)))); + else if (shadows != null || plantingOutlines != null) + { + double siteDepth = visible.Average(point => Project(point, D, 1)); + shadows?.AddModelOccluder(ring, face.Normal, visible[0], siteDepth, null); + plantingOutlines?.AddModelOccluder(ring, face.Normal, visible[0], siteDepth, null); + } + if (outlineSiteObject) objectNear = Math.Min(objectNear, visible.Min(point => Project(point, D, 1))); + if (vertices.Count == 3 && !face.CurvedSurface) + siteLight?.AddVisibleFacet(ring, face, visible, planting, crossedBillboard); + } + if (tree != null) plantingOutlines!.AddTree(tree); + if (outlineSiteObject && siteSilhouettes.Count > silhouetteStart) + { + var outlines = OutlineJoinedRings(siteSilhouettes.Skip(silhouetteStart).ToList(), element.CategoryId!.Value); + siteObjects.Add((outlines.ToList(), objectNear, false)); + } + if (wireFaces is { Count: > 0 }) + { + double near = wireFaces.Min(face => face.Points.Min(point => Project(point, D, 1))); + bool cutMesh = cut && near < viewPlaneDepth; + bool wholeMesh = !cutMesh && wireFaces.Count == placedGeometry.Faces.Count; + bool outlineBillboard = wholeMesh && crossedBillboard; + const int entourageCategory = (int)BuiltInCategory.OST_Entourage; + var entourageEdges = outlineBillboard + ? OutlineJoinedRings(siteSilhouettes.Skip(silhouetteStart).ToList(), + entourageCategory, coverOppositeEdges: true) + : SiteWireEdges(wireFaces, H, V, D, viewPlaneDepth, cutMesh); + // A one-sided mesh can project a silhouette when its facets face away or are edge-on. + if (!outlineBillboard && wholeMesh && wireFaces.All(face => face.Facing >= -1e-6)) + entourageEdges = entourageEdges.Concat(OutlineJoinedRings( + siteSilhouettes.Skip(silhouetteStart).ToList(), entourageCategory)); + siteObjects.Add((entourageEdges.ToList(), Math.Max(near, viewPlaneDepth), true)); + } + } + continue; + } + if (siteCategory) { + if (clipSiteContext && !PlacedSiteElement(element)) continue; if (element.Geometry is { Faces.Count: > 0 } siteGeometry) { foreach (var siteFace in siteGeometry.Faces) { if (siteFace.OuterVertices is not { Count: >= 3 } siteVertices) continue; - var sitePoints = new List<(double X, double Y)>(siteVertices.Count); - double siteDepth = 0; - foreach (var vertex in siteVertices) + var world = siteVertices.Select(point => new[] { point[0] * FeetToMillimetres, + point[1] * FeetToMillimetres, point[2] * FeetToMillimetres }).ToList(); + bool upwardTerrain = element.CategoryId == (int)BuiltInCategory.OST_Topography + && siteFace.Normal[2] > 0; + if (drawGround && upwardTerrain) { - double x = vertex[0] * FeetToMillimetres, y = vertex[1] * FeetToMillimetres; - double z = vertex[2] * FeetToMillimetres; - sitePoints.Add((x * H[0] + y * H[1] + z * H[2], - x * V[0] + y * V[1] + z * V[2])); - siteDepth += x * D[0] + y * D[1] + z * D[2]; + foreach (var (a, b) in CutChords(world, planeOrigin, D)) + terrainEdges.Add(new CollectedEdge(Project(a, H, 1), Project(a, V, 1), + Project(b, H, 1), Project(b, V, 1), + 0, 0, -1, -1, 0, 0, 0, 0, true, (int)BuiltInCategory.OST_Topography)); } - // The mesh of the ground is tessellated into tens of thousands of triangles: only the larger - // ones shade the background, which keeps the page light. + bool planarTerrain = upwardTerrain && (siteFace.PlaneSurface || siteVertices.Count == 3); + bool placedSectionTerrain = planarTerrain && sectionTerrainCrop != null && PlacedSiteElement(element); + bool clipTerrain = placedSectionTerrain || upwardTerrain && drawTerrainCut && skyGradient?.Ground != null; + var visible = clipSiteContext || clipTerrain + ? ClipBehind(world, planeOrigin, D) : world; + if (visible.Count < 3) continue; + if (regularFineSection && planarTerrain && ambient != null + && (siteFace.InnerLoops is not { Count: > 0 } || siteFace.InnerVertices is { Count: > 0 })) + ambient.AddOccluder(visible.Select(point => AmbientVector(point, 1)).ToList(), + AmbientVector(siteFace.Normal, 1), siteFace.InnerVertices?.Select(ring => + ring.Select(point => AmbientVector(point, FeetToMillimetres)).ToList()).ToList()); + var sitePoints = visible.Select(point => (X: Project(point, H, 1), Y: Project(point, V, 1))).ToList(); double siteArea = 0; for (int i = 0; i < sitePoints.Count; i++) { @@ -215,17 +588,210 @@ internal sealed record ElevationContent( var b = sitePoints[(i + 1) % sitePoints.Count]; siteArea += a.X * b.Y - b.X * a.Y; } - if (Math.Abs(siteArea) / 2 < 500_000 || context.Count >= 3000) continue; - context.Add((sitePoints, siteDepth / siteVertices.Count)); + bool terrainFacet = placedSectionTerrain || planarTerrain && shadowTerrainCrop != null; + if (terrainFacet && terrainFillCrop is { } terrainBounds) + { + if (Math.Abs(siteArea) < 1e-6 || sitePoints.All(p => p.X < terrainBounds.X0) + || sitePoints.All(p => p.X > terrainBounds.X1) || sitePoints.All(p => p.Y < terrainBounds.Y0) + || sitePoints.All(p => p.Y > terrainBounds.Y1)) continue; + } + // Keep the size cutoff for other site context. + else if (Math.Abs(siteArea) / 2 < 500_000 || context.Count >= 3000) continue; + if (placedSectionTerrain) + sectionTerrain!.AddSurface(sitePoints, siteFace, visible); + context.Add((sitePoints, visible.Average(point => Project(point, D, 1)), + element.CategoryId == (int)BuiltInCategory.OST_Topography)); + if (planarTerrain) + shadows?.AddTerrainReceiver(sitePoints, siteFace, visible, PlacedSiteElement(element)); } } continue; } if (element.Geometry is not { Faces.Count: > 0 } geometry) continue; + List>? curtainOpenings = null; + if (element.CategoryId == (int)BuiltInCategory.OST_Walls + && element.SerializedCurtainPanelOrder is { Length: > 0 } panelOrder + && document.GetElement(element.TypeId)?.RootClassIs("NewCurtainWallType") == true) + { + var panels = panelOrder.Select(document.GetElement).OfType().Where(panel => panel is + { IsDiscovered: false, Geometry: { } panelGeometry } + && panel.SerializedHostId == element.Id && panel.NativeIsSymbol != true + && panel.SerializedUnplacedOwnerId is not > 0 + && panelGeometry.Faces.Any(face => !face.CurvedSurface && face.OuterVertices is { Count: >= 3 })).ToList(); + // A fully decoded curtain assembly prints its own panels and mullions. + if (panels.Count == panelOrder.Length) continue; + if (fineSection && showSurfacePatterns && window == null) + { + curtainOpenings = []; + foreach (var panel in panels.Distinct().Where(panel => panel.CategoryId == (int)BuiltInCategory.OST_CurtainWallPanels)) + { + var fronts = panel.Geometry!.Faces.Where(face => face.PlaneSurface && !face.CurvedSurface + && Project(face.Normal, D, 1) < -1 + 1e-9 + && face.InnerLoops is not { Count: > 0 } && face.InnerVertices is not { Count: > 0 } + && face.OuterVertices is { Count: 4 } ring + && ring.All(point => point.Length == 3 && point.All(double.IsFinite) + && Project(point, D) >= viewPlaneDepth - 1e-6) + && HasGlazingPattern(face)).Take(2).ToArray(); + if (fronts is [{ OuterVertices: { } vertices }]) + { + var opening = ProjectRing(vertices); + if (IsProjectedRectangle(opening) && !curtainOpenings.Any(other => RectanglesOverlap(opening, other))) + curtainOpenings.Add(opening); + } + } + } + } // A stair section draws the stair, not the building around it. if (stairsOnly && !StairCategories.Contains(element.CategoryId ?? -1)) continue; - foreach (var face in geometry.Faces) + int categoryId = element.CategoryId ?? 0; + bool fineEquipmentMesh = regularFineSection && categoryId == (int)BuiltInCategory.OST_SpecialityEquipment + && element.RootClassIs("FamilyInstance"); + var meshSilhouette = PlacedSiteElement(element) && (fineEquipmentMesh + || opaqueSection && drawTerrainCut && categoryId == (int)BuiltInCategory.OST_GenericModel) + ? ProjectSectionMeshSilhouette(geometry, H, V, D, viewPlaneDepth, element.Id, categoryId, + multipleRevolvedNodes: fineEquipmentMesh) + : null; + if (meshSilhouette != null) meshSilhouettes.AddRange(meshSilhouette); + bool castColumnShadow = shadows != null && categoryId == (int)BuiltInCategory.OST_StructuralColumns + && PlacedSiteElement(element); + bool shadeDoorFinish = keepDoorDepths && ambient != null && categoryId == (int)BuiltInCategory.OST_Doors + && !element.IsDiscovered && element.NativeIsSymbol != true && element.SerializedUnplacedOwnerId is not > 0 + && !geometry.Faces.Any(face => document.GetElement(face.RenderStyleId ?? face.NestedRenderStyleId ?? -1) + ?.SerializedMaterialTransparency is > 0 and <= 1); + bool physicalOccluder = ambient != null && !element.IsDiscovered && element.NativeIsSymbol != true + && element.SerializedUnplacedOwnerId is not > 0 + && categoryId != (int)BuiltInCategory.OST_LightingFixtureSource + && !(categoryId == (int)BuiltInCategory.OST_Walls + && document.GetElement(element.TypeId)?.RootClassIs("NewCurtainWallType") == true); + double? slabGray = null; + if (regularFineSection && physicalOccluder && categoryId == (int)BuiltInCategory.OST_Floors + && element.LookupParameter(BuiltInParameter.FLOOR_PARAM_IS_STRUCTURAL)?.Value is 1 + && element.LookupParameter(BuiltInParameter.STRUCTURAL_MATERIAL_PARAM)?.Value is > 0 and int slabMaterial + && document.GetElement(slabMaterial) is { HasShadingAppearance: true, + SerializedMaterialUsesRenderAppearance: false, SerializedMaterialTransparency: 0 } finish + && finish.LookupParameter(BuiltInParameter.MATERIAL_PARAM_COLOR)?.Value is int slabColor and >= 0 and <= 0xffffff) + slabGray = (0.2126 * (slabColor & 255) + 0.7152 * ((slabColor >> 8) & 255) + + 0.0722 * ((slabColor >> 16) & 255)) / 255; + var wallFaceLayers = opaqueFineSection && !detailPath && detailCallout && physicalOccluder + && categoryId == (int)BuiltInCategory.OST_Walls + ? document.GetElement(element.TypeId)?.SerializedHostTypeLayers : null; + int? wallMaterial = paintDetailCuts && categoryId == (int)BuiltInCategory.OST_Walls + && geometry.Faces[0].RenderStyleId is > 0 and int material + && geometry.Faces.All(face => face.RenderStyleId == material) ? material : null; + if (drawGround && categoryId == (int)BuiltInCategory.OST_BuildingPad) + { + foreach (var padFace in geometry.Faces) + { + // shortcut: leave pads with inner loops alone until their islands are cut as well. + if (padFace.Normal[2] <= 0 || padFace.OuterVertices is not { Count: >= 3 } padVertices + || padFace.InnerVertices is { Count: > 0 }) continue; + var ring = padVertices.Select(v => new[] + { + v[0] * FeetToMillimetres, v[1] * FeetToMillimetres, v[2] * FeetToMillimetres, + }).ToList(); + foreach (var (a, b) in CutChords(ring, planeOrigin, D)) + { + double x0 = a[0] * H[0] + a[1] * H[1] + a[2] * H[2]; + double x1 = b[0] * H[0] + b[1] * H[1] + b[2] * H[2]; + terrainPads.Add((Math.Min(x0, x1), Math.Max(x0, x1))); + padProfile.Add(new CollectedEdge(x0, a[0] * V[0] + a[1] * V[1] + a[2] * V[2], + x1, b[0] * V[0] + b[1] * V[1] + b[2] * V[2], + 0, 0, -1, -1, 0, 0, 0, 0, true, categoryId)); + } + } + } + var roofStack = roofSectionCrop != null && categoryId == (int)BuiltInCategory.OST_Roofs + ? document.GetElement(element.TypeId)?.SerializedHostTypeLayers : null; + bool layeredRoofCut = roofStack is { Length: > 1 }; + List>? wallCutRings = null; + List>? roofCutRings = null; + if ((layeredRoofCut || drawGround && categoryId is ((int)BuiltInCategory.OST_Walls or (int)BuiltInCategory.OST_Floors + or (int)BuiltInCategory.OST_BuildingPad or (int)BuiltInCategory.OST_StructuralFoundation)) + && element.BoundingBox is { Length: 6 } bounds + && Enumerable.Range(0, 3).Sum(i => bounds[D[i] < 0 ? i + 3 : i] * D[i]) * FeetToMillimetres < viewPlaneDepth + && Enumerable.Range(0, 3).Sum(i => bounds[D[i] < 0 ? i : i + 3] * D[i]) * FeetToMillimetres > viewPlaneDepth) + { + var rings = layeredRoofCut ? [] : ClosedSectionRings(geometry.Faces, planeOrigin, D, H, V).ToList(); + if (rings.Count == 0 && (layeredRoofCut || paintDetailCuts && categoryId == (int)BuiltInCategory.OST_Walls)) + rings = ClosedSectionWithOpenings(geometry.Faces, planeOrigin, D, H, V) ?? rings; + if (wallMaterial is int materialId && rings is [var wallRing]) + wallCutRegions.Add((element.Id, materialId, wallRing)); + if (rings.Count > 0) + { + if (layeredRoofCut) roofCutRings = rings; + if (paintDetailCuts && categoryId == (int)BuiltInCategory.OST_Walls && !HasNestedSectionRings(rings)) + wallCutRings = rings; + if (sectionTerrainCrop.HasValue && viewDetail == 3 && categoryId == (int)BuiltInCategory.OST_Floors + && layerHatches != null && planeView?.ViewOrigin is { Length: 3 } floorViewOrigin + && !HasNestedSectionRings(rings)) + foreach (var ring in rings) + DetailAnnotations.AddClosedHostCutHatches(layerHatches, document, element, ring, H, V, + floorViewOrigin, layerBoundaries, penWidth: 0.1); + if (regularFineSection && categoryId == (int)BuiltInCategory.OST_Walls + && geometry.BrepSolids is [{ IsClosed: true }] && rings.Count == 1 + && ClosedSectionRings(geometry.Faces, planeOrigin, D, H, V, requireClosed: true) + .ToList() is [var cap]) + modelSectionMasks?.Add(cap); + } + if (paintDetailCuts && rings.Count > 0 && !HasNestedSectionRings(rings)) + { + if (categoryId == (int)BuiltInCategory.OST_Roofs) detailRoofCuts!.AddRange(rings); + if (categoryId == (int)BuiltInCategory.OST_Walls) detailWallCuts!.AddRange(rings); + } + foreach (var ring in rings) + { + if (!layeredRoofCut || paintDetailCuts) terrainSectionMasks.Add(ring); + if (regularFineSection && categoryId is (int)BuiltInCategory.OST_BuildingPad or (int)BuiltInCategory.OST_Floors) + modelSectionMasks?.Add(ring); + if (cut) continue; + if (layerHatches != null && planeView?.ViewOrigin is { Length: 3 } cutViewOrigin) + DetailAnnotations.AddClosedHostCutHatches(layerHatches, document, element, ring, H, V, cutViewOrigin); + for (int i = 0; i < ring.Count; i++) + { + var (ax, ay) = ring[i]; + var (bx, by) = ring[(i + 1) % ring.Count]; + elevationCutEdges.Add(new(ax, ay, bx, by, viewPlaneDepth, viewPlaneDepth, + -1, -1, 0, 0, 0, 0, true, categoryId)); + } + } + } + bool isRoof = element.CategoryId == (int)BuiltInCategory.OST_Roofs; + bool fineFixture = fineSection && categoryId == (int)BuiltInCategory.OST_LightingFixtures + && !element.IsDiscovered; + bool groupedEquipment = !cut && planeOrigin.Length == 3 + && categoryId == (int)BuiltInCategory.OST_ElectricalEquipment + && element.SerializedGroupId is > 0 && !element.IsGroupTemplate && !element.IsDiscovered + && element.RootClassIs("FamilyInstance"); + bool reachesViewPlane = (towardViewer != null || groupedEquipment) && geometry.Faces.Any(face => + face.OuterVertices?.Any(vertex => Project(vertex, D) >= viewPlaneDepth) == true); + bool visibleEquipment = groupedEquipment && reachesViewPlane; + bool preciseGroupDepth = visibleEquipment || !cut && planeOrigin.Length == 3 + && categoryId == (int)BuiltInCategory.OST_IOSModelGroups; + List<(int Index, GeoFace Face)>? roofLayers = showSurfacePatterns && isRoof + && geometry.BrepSolids is [{ IsClosed: true } shell] && shell.FaceIndices.Count == geometry.Faces.Count + && geometry.Faces.Any(face => face.ModelPattern != null) ? [] : null; + // shortcut: a single prismatic top rail, until segmented native profiles are supported. + bool straightTopRail = fineSection && window == null && element.RootClassName == "TopRail" && geometry.Faces.Count == 6 + && geometry.Faces.All(face => face.PlaneSurface && face.OuterVertices is { Count: 4 } + && face.InnerVertices is not { Count: > 0 } && face.InnerLoops is not { Count: > 0 }); + int firstChord = rawChords.Count; + int firstFace = faces.Count; + bool isInsert = categoryId is (int)BuiltInCategory.OST_Windows or (int)BuiltInCategory.OST_Doors; + int? hostId = isInsert + && element.SerializedHostId is > 0 ? element.SerializedHostId : null; + int? roofHostId = hostId is int host + && document.GetElement(host)?.CategoryId == (int)BuiltInCategory.OST_Roofs ? host : null; + bool roofInsert = roofHostId.HasValue && (fineSection || !cut && HasEdgeOnRoofGlazing(geometry.Faces)); + bool projectRoundShafts = showSurfacePatterns && PlacedSiteElement(element) + && (regularOpaqueSection && categoryId == (int)BuiltInCategory.OST_StructuralColumns + || roundElevationShafts && categoryId == (int)BuiltInCategory.OST_GenericModel); + var outwardStairFaces = ambient != null && IsStairBodyCategory(categoryId) + ? OutwardConvexStairFaces(geometry) : null; + foreach (var (face, projectedSilhouette) in SectionFaces(document, element, geometry, + fineSection || cut && drawTerrainCut, H, V, D, planeOrigin, projectRoundShafts, + maxElevationTubeDiameter, elevationTubeEdges)) { + bool roundShaft = projectRoundShafts && projectedSilhouette; if (face.OuterVertices is not { Count: >= 3 } vertices) continue; if (face.CurvedSurface) continue; var corners = new List(vertices.Count); @@ -233,6 +799,32 @@ internal sealed record ElevationContent( corners.Add([vertex[0] * FeetToMillimetres, vertex[1] * FeetToMillimetres, vertex[2] * FeetToMillimetres]); double facing = Math.Abs(face.Normal[0] * D[0] + face.Normal[1] * D[1] + face.Normal[2] * D[2]); + var paneMaterial = detailGlass != null && face.PlaneSurface && facing > 1 - 1e-9 + && categoryId is ((int)BuiltInCategory.OST_CurtainWallPanels or (int)BuiltInCategory.OST_Windows + or (int)BuiltInCategory.OST_Doors or (int)BuiltInCategory.OST_Mass + or (int)BuiltInCategory.OST_MassForm) + ? document.GetElement(face.RenderStyleId ?? face.NestedRenderStyleId ?? -1) + : null; + (double Gray, double Transmission)? paneStyle = paneMaterial is { HasShadingAppearance: true, + SerializedMaterialTransparency: > 0 and <= 1 and double transmission } + && paneMaterial.LookupParameter(BuiltInParameter.MATERIAL_PARAM_COLOR)?.Value + is >= 0 and <= 0xffffff and int color + ? (((color & 255) * 0.2126 + ((color >> 8) & 255) * 0.7152 + (color >> 16) * 0.0722) / 255, transmission) + : null; + bool seeThrough = (preciseGroupDepth || groupedEquipment || roofInsert) + && (face.RenderStyleId ?? face.NestedRenderStyleId) is int faceMaterialId + && document.GetElement(faceMaterialId)?.SerializedMaterialTransparency is > 0; + if (shadows != null && face.PlaneSurface && (categoryId is ((int)BuiltInCategory.OST_Walls + or (int)BuiltInCategory.OST_Roofs or (int)BuiltInCategory.OST_Floors or (int)BuiltInCategory.OST_Stairs) + || IsRailingCategory(categoryId) && PlacedSiteElement(element) + || castColumnShadow && document.GetElement(face.RenderStyleId ?? face.NestedRenderStyleId ?? -1) + ?.SerializedMaterialTransparency is not > 0)) + shadows.AddCaster(face, corners); + if (!cut && shadows != null && roofHostId is int roof && face.PlaneSurface + && document.GetElement(face.RenderStyleId ?? face.NestedRenderStyleId ?? -1) + ?.SerializedMaterialTransparency is not > 0) + shadows.AddCaster(face, corners, roofId: roof); + if (groupedEquipment && face.PlaneSurface && !seeThrough) shadows?.AddCaster(face, corners, siteOnly: true); // The chords come from the unclipped ring: clipping moves or drops the plane crossings, and a // window-clipped polygon loses the vertex correspondence entirely. They are projected and kept // below, next to the face they were carved from. @@ -267,22 +859,47 @@ internal sealed record ElevationContent( double nl = Math.Sqrt(face.Normal[0] * face.Normal[0] + face.Normal[1] * face.Normal[1] + face.Normal[2] * face.Normal[2]); double nnx = 0, nny = 0, nnz = 0; if (nl > 1e-12) { nnx = face.Normal[0] / nl; nny = face.Normal[1] / nl; nnz = face.Normal[2] / nl; } + if (wallMaterial is int chordMaterial) + wallChordSources.Add(rawChords.Count, (element.Id, chordMaterial)); rawChords.Add((ax, ay, bx, by, nnx, nny, nnz, element.TypeId, element.CategoryId ?? 0, planeDepth)); minX = Math.Min(minX, Math.Min(ax, bx)); maxX = Math.Max(maxX, Math.Max(ax, bx)); minY = Math.Min(minY, Math.Min(ay, by)); maxY = Math.Max(maxY, Math.Max(ay, by)); } } - if (cut && planeOrigin.Length == 3) + if (towardViewer != null && reachesViewPlane && corners.Any(point => Project(point, D, 1) < viewPlaneDepth)) + { + var foreground = ClipBehind(corners, planeOrigin, towardViewer); + var mask = foreground.Select(point => (X: Project(point, H, 1), Y: Project(point, V, 1))).ToList(); + if (mask.Count >= 3 && Math.Abs(PlanPrinter.SignedArea(mask)) >= 2000) terrainForeground.Add(mask); + } + if ((cut || visibleEquipment || drawTerrainCut) && planeOrigin.Length == 3) { corners = ClipBehind(corners, planeOrigin, D); if (corners.Count < 3) continue; } + bool ambientBlocker = physicalOccluder && !roundShaft + && (face.PlaneSurface || regularFineSection && corners.All(corner => + Math.Abs(Project(corner, face.Normal, 1) - Project(corners[0], face.Normal, 1)) < 1e-6)) + && (face.InnerLoops is not { Count: > 0 } || face.InnerVertices is { Count: > 0 }) + && ((face.RenderStyleId ?? face.NestedRenderStyleId) is not (> 0 and int ambientMaterial) + || document.GetElement(ambientMaterial)?.SerializedMaterialTransparency is not > 0); + System.Numerics.Vector3 ambientNormal = default, ambientOrigin = default; + if (ambientBlocker) + { + ambientNormal = AmbientVector(face.Normal, 1); + ambientOrigin = AmbientVector(corners[0], 1); + ambient!.AddOccluder(corners.Select(point => AmbientVector(point, 1)).ToList(), ambientNormal, + face.InnerVertices?.Select(ring => ring.Select(point => AmbientVector(point, FeetToMillimetres)).ToList()).ToList(), + frontFaceOnly: outwardStairFaces?.Contains(face) == true); + } var points = new List<(double X, double Y)>(corners.Count); double depth = 0, minDepth = double.PositiveInfinity; foreach (var corner in corners) points.Add((corner[0] * H[0] + corner[1] * H[1] + corner[2] * H[2], corner[0] * V[0] + corner[1] * V[1] + corner[2] * V[2])); + var railBoundary = straightTopRail && Math.Abs(facing - 1) < 1e-9 ? points : null; + bool[]? incomingEdges = null; if (window is { } detail && cut && planeOrigin.Length == 3) { // A detail section shows the part of the cut around the point of its plane, at the height its kind @@ -306,7 +923,7 @@ internal sealed record ElevationContent( // The clip runs on the 3D ring and projects afterwards: clipping the projected points alone // broke the one-to-one correspondence with the ring, and `isCut` (which reads the ring) was // never computed, so every detail view lost its cut profile. - corners = ClipToWindow3(corners, H, V, cropRect.X0, cropRect.X1, cropRect.Y0, cropRect.Y1); + (corners, incomingEdges) = ClipToWindow3(corners, H, V, cropRect.X0, cropRect.X1, cropRect.Y0, cropRect.Y1); if (corners.Count < 3) continue; points = corners.Select(corner => ( corner[0] * H[0] + corner[1] * H[1] + corner[2] * H[2], @@ -325,32 +942,326 @@ internal sealed record ElevationContent( var b = points[(i + 1) % points.Count]; projected += a.X * b.Y - b.X * a.Y; } - if (Math.Abs(projected) / 2 < 2000) continue; + bool fineFace = visibleEquipment && face.PlaneSurface + || fineFixture && facing > 0.5 && (face.PlaneSurface + || corners.All(corner => Math.Abs(Project(corner, face.Normal, 1) + - Project(corners[0], face.Normal, 1)) < 1e-6)); + if (Math.Abs(projected) < (projectedSilhouette || fineFace ? 1e-6 : 4000)) continue; depth /= corners.Count; foreach (var (x, y) in points) { minX = Math.Min(minX, x); maxX = Math.Max(maxX, x); minY = Math.Min(minY, y); maxY = Math.Max(maxY, y); } - bool outline = facing > 0.5; + if ((roundShaft || drawTerrainCut && showSurfacePatterns && categoryId == (int)BuiltInCategory.OST_Walls) + && face.PlaneSurface && Project(face.Normal, D, 1) < 0 + && face.InnerVertices is not { Count: > 0 } && face.InnerLoops is not { Count: > 0 } + && face.RenderStyleId is int surfaceMaterialId + && document.RawData.MaterialPatterns?.TryGetValue(surfaceMaterialId, out var surfaceMaterial) == true + && surfaceMaterial.SurfacePatternColor == 0 + && document.RawData.FillPatterns?.TryGetValue(surfaceMaterial.SurfacePatternId, out var surfacePattern) == true + && surfacePattern.Grids.Count > 0 + && surfacePattern.Grids.All(grid => grid is { Target: 0, Orientation: 0, Segments.Length: > 0 })) + dashedSurfacePatterns.Add(points, surfacePattern.Grids); + bool outline = facing > 0.5 || fineFace || dashedSurfacePatterns.ContainsKey(points); + if (roundShaft) roundShaftFaces.Add(faces.Count); faces.Add((points, depth, outline)); - faceMinDepths.Add(minDepth); + double? slabSideGray = slabGray.HasValue && face.PlaneSurface && facing > 0.5 + && Math.Abs(face.Normal[2]) <= 1e-6 ? slabGray : null; + double? sideGray = slabSideGray; + if (wallFaceLayers != null && face.PlaneSurface && outline && Math.Abs(facing - 1) < 1e-9 + && face.RenderStyleId is > 0 and int wallFaceFinish + && wallFaceLayers.Any(layer => layer.RawFunction is 4 or 5 && layer.RawMaterialId == wallFaceFinish) + && document.GetElement(wallFaceFinish) is { HasShadingAppearance: true, + SerializedMaterialUsesRenderAppearance: false, SerializedMaterialTransparency: 0 } wallFinish + && wallFinish.LookupParameter(BuiltInParameter.MATERIAL_PARAM_COLOR)?.Value is int wallColour + and >= 0 and <= 0xffffff) + sideGray = (0.2126 * (wallColour & 255) + 0.7152 * ((wallColour >> 8) & 255) + + 0.0722 * ((wallColour >> 16) & 255)) / 255; + if (sideGray.HasValue) faceFills.Add(points, sideGray); + if (paneStyle is { } pane) + { + double opacity = Project(face.Normal, D, 1) < 0 ? 1 - pane.Transmission : 0; + detailGlass!.Add(points, (pane.Gray, opacity)); + } + if ((visibleEquipment || roundShaft && regularFineSection || shadeDoorFinish) && face.PlaneSurface + && document.GetElement(face.RenderStyleId ?? face.NestedRenderStyleId ?? -1) is { } faceMaterialElement) + { + // shortcut: transparent equipment covers keep their edges until their appearance is composited. + if (seeThrough) faceFills.Add(points, null); + else if (faceMaterialElement.HasShadingAppearance + && (roundShaft || faceMaterialElement.SerializedMaterialUsesRenderAppearance == false) + && (!shadeDoorFinish || faceMaterialElement.SerializedMaterialTransparency == 0) + && faceMaterialElement.LookupParameter(BuiltInParameter.MATERIAL_PARAM_COLOR)?.Value + is int colour and >= 0 and <= 0xffffff) + faceFills.Add(points, (0.2126 * (colour & 255) + 0.7152 * ((colour >> 8) & 255) + + 0.0722 * ((colour >> 16) & 255)) / 255); + } + if (fineSection && IsStairBodyCategory(categoryId) && face.PlaneSurface + && Math.Abs(facing - 1) < 1e-9 && Math.Abs(minDepth - depth) < 1e-6 + && face.InnerVertices is not { Count: > 0 } && face.InnerLoops is not { Count: > 0 }) + stairMasks.Add(faces.Count - 1, points); + if (fineSection && (IsRailingCategory(categoryId) || categoryId == (int)BuiltInCategory.OST_StairsRailingBaluster) + && face.InnerVertices is not { Count: > 0 } && face.InnerLoops is not { Count: > 0 }) + railingMaskDepths.Add(faces.Count - 1, corners.Max(point => Project(point, D, 1))); + if (siteSilhouettes != null) + siteModelMasks.Add((points, minDepth, corners.Max(point => Project(point, D, 1)))); + if (shadows != null && face.PlaneSurface && Math.Abs(facing - 1) < 1e-9) + shadows.AddReceiver(points, face, depth, roundShaft: roundShaft); + else if (!cut && shadows != null && isRoof && face.PlaneSurface + && face.Normal[2] > 1e-9 && Project(face.Normal, D, 1) < -1e-9 + && face.InnerVertices is { Count: > 0 }) + shadows.AddRoofReceiver(points, face, corners, element.Id); + if (face.PlaneSurface) roofLayers?.Add((faces.Count - 1, face)); + bool exteriorDraftingPattern = !cut && showSurfacePatterns && planeOrigin.Length == 3 + && categoryId == (int)BuiltInCategory.OST_Walls && face.PlaneSurface + && minDepth >= viewPlaneDepth - 1e-6 && Project(face.Normal, D, 1) < 0 + && (face.InnerLoops is not { Count: > 0 } || face.InnerVertices is { Count: > 0 }); + if (outline && (exteriorDraftingPattern || showDraftingPatterns + && face.InnerVertices is not { Count: > 0 } && face.InnerLoops is not { Count: > 0 }) + && face.RenderStyleId is int materialId + && document.RawData.MaterialPatterns?.TryGetValue(materialId, out var faceMaterial) == true + && faceMaterial.SurfacePatternColor == 0 + && document.RawData.FillPatterns?.TryGetValue(faceMaterial.SurfacePatternId, out var pattern) == true + && pattern.Grids is [{ Target: 0, Orientation: 0, Segments.Length: 0, Offset: > 0 } grid] + && double.IsFinite(grid.Angle) && double.IsFinite(grid.OriginX) && double.IsFinite(grid.OriginY) + && double.IsFinite(grid.Offset)) + { + int patternCategory = categoryId switch + { + (int)BuiltInCategory.OST_Walls => (int)BuiltInCategory.OST_WallsSurfacePattern, + (int)BuiltInCategory.OST_Floors => (int)BuiltInCategory.OST_FloorsSurfacePattern, + (int)BuiltInCategory.OST_Roofs => (int)BuiltInCategory.OST_RoofsSurfacePattern, + (int)BuiltInCategory.OST_Ceilings => (int)BuiltInCategory.OST_CeilingsSurfacePattern, + _ => 0, + }; + double width = fineSection && drawGround && !detailPath && patternCategory != 0 + && PenWidths.TryGetWidth(document, patternCategory, false, viewportScale ?? viewScale, out double savedWidth) + ? savedWidth : 0.1; + surfacePatterns.Add(points, (grid, width)); + } + bool glazedFace = outline && Project(face.Normal, D, 1) < 0 + && categoryId is ((int)BuiltInCategory.OST_CurtainWallPanels or + (int)BuiltInCategory.OST_Windows or (int)BuiltInCategory.OST_Doors) + && HasGlazingPattern(face); + glazing?.Add(document, points, minDepth, corners.Max(point => Project(point, D, 1)), + face.RenderStyleId ?? face.NestedRenderStyleId, glazedFace); + if (showSurfacePatterns && (isRoof || glazedFace) && window == null && planeOrigin.Length == 3 + && (face.InnerLoops is not { Count: > 0 } || face.InnerVertices is { Count: > 0 }) + && face.InnerVertices?.All(hole => hole.Count >= 3 + && hole.All(point => point.Length == 3 && point.All(double.IsFinite))) != false) + { + (double X, double Y) InView(double[] p) => (Project(p, H), Project(p, V)); + IReadOnlyList? hatchGrids = isRoof + ? FillHatch.ProjectModelGrid(document, face, InView) is { } modelGrid ? [modelGrid] : null + : FillHatch.ProjectDashedModelGrids(document, face, InView); + if (hatchGrids != null) + modelHatches.Add(points, new ModelHatch(hatchGrids, ProjectOpenings(face).ToList())); + } + bool hasPaintOpenings = face.PlaneSurface && face.InnerVertices is { Count: > 0 } + && (categoryId == (int)BuiltInCategory.OST_Walls || !cut && isInsert); + if (hasPaintOpenings) + { + var openings = ProjectOpenings(face).ToList(); + if (openings.Count > 0) paintOpenings.Add(points, openings); + } + if (curtainOpenings is { Count: > 0 } && face.PlaneSurface && Math.Abs(facing - 1) < 1e-9 + && (face.RenderStyleId ?? face.NestedRenderStyleId) is not > 0 + && face.InnerLoops is not { Count: > 0 } && face.InnerVertices is not { Count: > 0 } + && IsProjectedRectangle(points)) + { + // Clear the fallback only over the saved panes, leaving unresolved cells covered. + var openings = curtainOpenings.Where(ring => ring.All(point => + PointInPolygon(point.X, point.Y, points) || DistToPolygon(point.X, point.Y, points) < 1e-6)).ToList(); + if (openings.Count > 0) paintOpenings.Add(points, openings); + } + var faceOpenings = paintOpenings.GetValueOrDefault(points); + if (detailGlass?.GetValueOrDefault(points).Opacity is > 0) + ambient!.AddGlazing(points, faceOpenings, corners.Max(point => Project(point, D, 1))); + if (ambientBlocker && face.PlaneSurface && !glazedFace + && !(shadeDoorFinish && faceFills.ContainsKey(points))) + ambient!.AddReceiver(points, faceOpenings, ambientOrigin, ambientNormal, sideGray ?? 1, + orientDirectLight: paintDetailCuts && categoryId == (int)BuiltInCategory.OST_Walls, + ignoreStairExitHits: IsStairBodyCategory(categoryId), + excludeSamplesBehindCut: paintDetailCuts && categoryId == (int)BuiltInCategory.OST_Floors + && Math.Abs(face.Normal[2]) <= 1e-6); + else if (regularFineSection && face.PlaneSurface && ambient != null + && glazing?.AmbientBackgroundGray(points) is double glazedBackground) + ambient.AddReceiver(points, faceOpenings, AmbientVector(corners[0], 1), AmbientVector(face.Normal, 1), + glazedBackground); + shadows?.AddModelOccluder(points, face.Normal, corners[0], depth, faceOpenings); + plantingOutlines?.AddModelOccluder(points, face.Normal, corners[0], depth, faceOpenings); + if (!cut || categoryId is ((int)BuiltInCategory.OST_BuildingPad or (int)BuiltInCategory.OST_StructuralFoundation)) + terrainOcclusion?.AddTarget(points, face, corners); + faceOpenings ??= (isRoof || preciseGroupDepth) && face.InnerVertices is { Count: > 0 } holes + ? holes.Where(hole => hole.Count >= 3).Select(hole => hole.Select(p => ( + (p[0] * H[0] + p[1] * H[1] + p[2] * H[2]) * FeetToMillimetres, + (p[0] * V[0] + p[1] * V[1] + p[2] * V[2]) * FeetToMillimetres)).ToList()).ToList() + : null; + PlanarOcclusion? occludingPlane = null; + bool verifiedDetailPlane = paintDetailCuts + && (IsStairBodyCategory(categoryId) + || categoryId is ((int)BuiltInCategory.OST_Walls or (int)BuiltInCategory.OST_Floors)) + && corners.All(corner => Math.Abs(Project(corner, face.Normal, 1) + - Project(corners[0], face.Normal, 1)) < 1e-6); + bool exactStairProjectionDepth = overviewSection && face.PlaneSurface + && (IsStairBodyCategory(categoryId) || categoryId == (int)BuiltInCategory.OST_Walls); + if (isRoof || verifiedDetailPlane || exactStairProjectionDepth + || face.PlaneSurface && (preciseGroupDepth || hasPaintOpenings || faceOpenings != null || roofInsert)) + { + var normal = face.Normal; + double nd = normal[0] * D[0] + normal[1] * D[1] + normal[2] * D[2]; + if (Math.Abs(nd) > 1e-10) + { + var corner = corners[0]; + occludingPlane = new PlanarOcclusion( + -(normal[0] * H[0] + normal[1] * H[1] + normal[2] * H[2]) / nd, + -(normal[0] * V[0] + normal[1] * V[1] + normal[2] * V[2]) / nd, + (normal[0] * corner[0] + normal[1] * corner[1] + normal[2] * corner[2]) / nd, + faceOpenings, seeThrough, exactStairProjectionDepth); + } + } + faceOccluders.Add((minDepth, element.Id, hostId, categoryId, occludingPlane)); + if (meshCovers != null && face.PlaneSurface && !seeThrough && !glazedFace + && faceOpenings is not { Count: > 0 } && face.InnerLoops is not { Count: > 0 } + && face.InnerVertices is not { Count: > 0 }) + meshCovers.Add((points, corners.Max(point => Project(point, D, 1)), element.Id)); + if (spanOccluders != null && face.PlaneSurface && !element.IsDiscovered + && (face.InnerLoops is not { Count: > 0 } loops || roundElevationShafts + && Math.Max(face.InnerVertices?.Count ?? 0, faceOpenings?.Count ?? 0) >= loops.Count) + && (roundElevationShafts || face.InnerVertices is not { Count: > 0 } && faceOpenings is not { Count: > 0 }) + && ((face.RenderStyleId ?? face.NestedRenderStyleId) is not (> 0 and int spanMaskMaterial) + || document.GetElement(spanMaskMaterial)?.SerializedMaterialTransparency is not > 0)) + { + spanOccluders.Add((points, corners.Max(point => Project(point, D, 1)))); + if (spanOpenings != null) + { + var openings = faceOpenings; + if (face.InnerVertices is { Count: > 0 } inner) + openings = [.. openings ?? [], .. inner.Where(ring => ring.Count >= 3) + .Select(ring => ring.Select(p => (Project(p, H), Project(p, V))).ToList())]; + if (openings is { Count: > 0 }) spanOpenings.Add(points, openings); + } + } + if (detailWallOccluders != null && categoryId == (int)BuiltInCategory.OST_Walls && !seeThrough + && Math.Abs(depth - minDepth) < 1e-6 && faceOpenings is not { Count: > 0 } + && face.InnerLoops is not { Count: > 0 } && face.InnerVertices is not { Count: > 0 }) + detailWallOccluders.Add((points, minDepth)); if (outline) { + if (roofInsert) roofInsertFaces.Add(faces.Count - 1); + if (sectionTerrainCrop.HasValue && categoryId == (int)BuiltInCategory.OST_Walls + && element.TypeId > 0 && PlacedSiteElement(element) && face.PlaneSurface + && Math.Abs(Project(face.Normal, D, 1) + 1) < 1e-9 + && faceOpenings is not { Count: > 0 } && face.InnerLoops is not { Count: > 0 } + && face.InnerVertices is not { Count: > 0 } + && (face.RenderStyleId ?? face.NestedRenderStyleId) is > 0 and int wallFaceMaterial + && document.GetElement(wallFaceMaterial)?.SerializedMaterialTransparency is not > 0 + && corners.All(point => Math.Abs(Project(point, D, 1) - minDepth) < 1e-6)) + sectionWallFaces.Add(faces.Count - 1, (element.TypeId, wallFaceMaterial, minDepth)); // The plane of the face for edge sharing: a triangulation diagonal is the edge of two // coplanar faces, a crease or silhouette the edge of two different planes. double nx = face.Normal[0], ny = face.Normal[1], nz = face.Normal[2]; double length = Math.Sqrt(nx * nx + ny * ny + nz * nz); if (length > 1e-12) { nx /= length; ny /= length; nz /= length; } var corner = corners[0]; - edgeFaces.Add((points, corners, depth, + edgeFaces.Add(new ProjectionFace(points, corners, depth, (long)Math.Round(nx * 1000), (long)Math.Round(ny * 1000), (long)Math.Round(nz * 1000), (long)Math.Round((nx * corner[0] + ny * corner[1] + nz * corner[2]) * 2.0), - faces.Count - 1, element.CategoryId ?? 0)); + faces.Count - 1, element.CategoryId ?? 0, incomingEdges)); + if (railBoundary != null) + { + for (int i = 0; i < railBoundary.Count; i++) + { + var (x1, y1) = railBoundary[i]; + var (x2, y2) = railBoundary[(i + 1) % railBoundary.Count]; + if (sectionCrop is { } railCrop && !ClipSegment(x1, y1, x2, y2, + railCrop.X0, railCrop.Y0, railCrop.X1, railCrop.Y1, out x1, out y1, out x2, out y2)) continue; + var key = ProjectedEdgeKey(x1, y1, x2, y2); + if (key.Ax == key.Bx && key.Ay == key.By) continue; + topRailEdges.Add(new CollectedEdge(x1, y1, x2, y2, depth, depth, + faces.Count - 1, -1, 0, 0, 0, 0, false, element.CategoryId ?? 0)); + } + } + } + } + if (opaqueFineSection && !isDetail && layerHatches != null && rawChords.Count > firstChord + && categoryId == (int)BuiltInCategory.OST_Stairs && planeView?.ViewOrigin is { Length: 3 } stairViewOrigin + && (geometry.Faces[0].RenderStyleId ?? geometry.Faces[0].NestedRenderStyleId) is > 0 and int stairMaterial + && geometry.Faces.All(face => (face.RenderStyleId ?? face.NestedRenderStyleId) == stairMaterial + && !face.CurvedSurface && face.OuterVertices is { Count: >= 3 })) + { + var stairCut = ClosedSectionRings(geometry.Faces, planeOrigin, D, H, V, requireClosed: true).ToList(); + if (!HasNestedSectionRings(stairCut)) + { + if (geometry.BrepSolids is { Count: > 0 } stairSolids && stairSolids.All(solid => solid.IsClosed)) + modelSectionMasks?.AddRange(stairCut); + foreach (var ring in stairCut) + DetailAnnotations.AddMaterialCutHatch(layerHatches, document, stairMaterial, ring, H, V, stairViewOrigin); + } + } + if (roofCutRings != null && layerBoundaries != null && roofSectionCrop is { } roofCrop && roofStack != null) + { + int prior = layerBoundaries.Count; + AddRoofLayers(layerBoundaries, rawChords.Skip(firstChord), roofCutRings, roofStack, H, V, D, roofCrop, + document, !isDetail ? layerHatches : null, planeView?.ViewOrigin); + if (layerBoundaries.Count > prior) modelSectionMasks?.AddRange(roofCutRings); + } + if (layerHatches != null && (!cut || sectionCrop != null) && rawChords.Count > firstChord + && planeView?.ViewOrigin is { Length: 3 } viewOrigin) + { + if (!isDetail && opaqueFineSection && categoryId == (int)BuiltInCategory.OST_Walls) + wallCutRings = ClosedSectionWithOpenings(geometry.Faces, planeOrigin, D, H, V); + + int priorBoundaries = layerBoundaries?.Count ?? 0; + DetailAnnotations.AddLayerHatches(layerHatches, document, element, + rawChords.Skip(firstChord).Select(c => (c.X1, c.Y1, c.X2, c.Y2)), H, V, viewOrigin, + paintDetailCuts ? layerBoundaries : null, wallCutRings); + if (layerBoundaries?.Count > priorBoundaries) + for (int i = firstChord; i < rawChords.Count; i++) sectionedLayerChords.Add(i); + } + if (planeOrigin.Length == 3 && firstFace < faces.Count + && isInsert + && !element.IsDiscovered && element.NativeIsSymbol != true && !element.RootClassIs("FamilySymbol") + && element.SerializedUnplacedOwnerId is not > 0 && geometry.ViewFacingLines is { Count: > 0 } lines) + { + foreach (var line in lines) + { + if (Project(line.Axis, D, 1) < 1 - 1e-9 || line.DetailCondition is { } detail + && (viewDetail is not (>= 1 and <= 3) + || !Parsing.GRepParserV2.CompareSerializedInteger(viewDetail.Value, detail.Comparison, detail.Level))) continue; + double startDepth = Project(line.Start, D), endDepth = Project(line.End, D); + if (Math.Min(startDepth, endDepth) < viewPlaneDepth - 1e-6) continue; + double depth = (startDepth + endDepth) / 2; + viewLines.Add(new CollectedEdge(Project(line.Start, H), Project(line.Start, V), + Project(line.End, H), Project(line.End, V), depth, depth, firstFace, -1, 0, 0, 0, 0, + CategoryId: categoryId, NearDepth: Math.Min(startDepth, endDepth)) { ViewLineStyleId = line.StyleId }); } } + if (roofLayers is { Count: > 1 }) + OrderRoofLayerPaint(roofLayers); + } + if (sectionBillboards.Count > 0) + foreach (var (x, y) in sectionBillboards.SelectMany(ring => ring)) + { + minX = Math.Min(minX, x); maxX = Math.Max(maxX, x); + minY = Math.Min(minY, y); maxY = Math.Max(maxY, y); + } + if (faces.Count == 0 && rawChords.Count == 0 && sectionBillboards.Count == 0 && elevationTubeEdges.Count == 0) + { + if (towardViewer == null || siteSilhouettes is not { Count: > 0 }) return null; + foreach (var (x, y) in siteSilhouettes.SelectMany(ring => ring)) + { + minX = Math.Min(minX, x); maxX = Math.Max(maxX, x); + minY = Math.Min(minY, y); maxY = Math.Max(maxY, y); + } } - if (faces.Count == 0 && rawChords.Count == 0) return null; + if (elevationTubeEdges.Count > 0) + foreach (var edge in elevationTubeEdges) + { + minX = Math.Min(minX, Math.Min(edge.X1, edge.X2)); maxX = Math.Max(maxX, Math.Max(edge.X1, edge.X2)); + minY = Math.Min(minY, Math.Min(edge.Y1, edge.Y2)); maxY = Math.Max(maxY, Math.Max(edge.Y1, edge.Y2)); + } // The chords become inked edges on the cutting plane's own key, so the same line coming from two // solids sharing the cut surface merges into one below. var cutChords = new List(); @@ -362,36 +1273,207 @@ internal sealed record ElevationContent( pnz = (long)Math.Round(D[2] * 1000); poff = (long)Math.Round((planeOrigin[0] * D[0] + planeOrigin[1] * D[1] + planeOrigin[2] * D[2]) * 2.0); } - foreach (var chord in rawChords) - cutChords.Add(new CollectedEdge(chord.X1, chord.Y1, chord.X2, chord.Y2, - chord.Depth, chord.Depth, -1, -1, pnx, pny, pnz, poff, true, chord.CategoryId)); - // Layer boundaries subdivide the cross-section, but only in a detail at a fine scale: a 1:100 section - // draws the coarse single outline the reference draws, while a 1:50/1:20/1:10 detail draws every layer. - bool detailPath = window != null || isDetail || cropWindow != null; - int viewScale = planeView?.LookupParameter(BuiltInParameter.VIEW_SCALE)?.Value is int scaleValue && scaleValue > 0 - ? scaleValue : 100; + for (int i = 0; i < rawChords.Count; i++) + { + var chord = rawChords[i]; + var edge = new CollectedEdge(chord.X1, chord.Y1, chord.X2, chord.Y2, + chord.Depth, chord.Depth, -1, -1, pnx, pny, pnz, poff, true, chord.CategoryId); + if (wallChordSources.TryGetValue(i, out var source) && wallCutRegions.Count > 0) + { + // Only interior spans are hidden. Coincident contours and material changes still ink. + var covers = wallCutRegions.Where(region => region.WallId != source.WallId + && region.MaterialId == source.MaterialId).Select(region => region.Ring); + cutChords.AddRange(VisibleTerrainEdges([edge], covers, [], coverBoundary: false)); + } + else + { + cutChords.Add(edge); + } + } + // Layer boundaries share the exact material bands and keep any spans left by an authored cut edge. + List? roofLayerEdges = null; + if (layerBoundaries is { Count: > 0 }) + { + var sections = new List(cutChords); + foreach (var layer in layerBoundaries.Distinct()) + sections.Add(new(layer.Start.X, layer.Start.Y, layer.End.X, layer.End.Y, + viewPlaneDepth, viewPlaneDepth, -1, -1, pnx, pny, pnz, poff, false, layer.CategoryId)); + var boundaries = TrimProjectedEdgesAtCuts(sections).Where(edge => !edge.IsCut); + if (paintDetailCuts) cutChords.AddRange(boundaries); + else roofLayerEdges = boundaries.ToList(); + } if (detailPath && viewScale <= 50 && rawChords.Count > 0) - AddLayerLines(rawChords, document, cutChords, D, H, V, pnx, pny, pnz, poff); - var deduped = DedupeEdges(edgeFaces, D, cut ? planeOrigin : null); + AddLayerLines(rawChords, document, cutChords, D, H, V, pnx, pny, pnz, poff, sectionedLayerChords); + HashSet<(long Ax, long Ay, long Bx, long By)>? railSeams = fineSection ? [] : null; + // Coincident nosing edges can lie at different depths. Keep the front candidate through occlusion. + bool keepStairDepths = paintDetailCuts || overviewSection; + var deduped = DedupeEdges(edgeFaces, D, cut ? planeOrigin : null, keepComponentDepths: drawTerrainCut, + fineSection: fineSection, keepStairDepths: keepStairDepths, railSeams: railSeams, + keepDoorDepths: keepDoorDepths, keepDetailProfileDepths: paintDetailCuts); + foreach (var shaftIndex in roundShaftFaces) + { + var shaft = faces[shaftIndex]; + // Only the edges behind the full cylinder can be clipped at its whole silhouette. + double far = shaft.Depth + (shaft.Points.Max(p => p.X) - shaft.Points.Min(p => p.X)) / 2; + bool BehindShaft(CollectedEdge edge) => !edge.IsCut && edge.NearDepth is double near + && near > far + 1 && Math.Abs(near - edge.MidDepth) < 1e-6; + if (faceOccluders[shaftIndex].CategoryId == (int)BuiltInCategory.OST_GenericModel) + { + deduped = deduped.SelectMany(edge => BehindShaft(edge) + ? VisibleTerrainEdges([edge], [shaft.Points], [], coverBoundary: false) + : [edge]).ToList(); + continue; + } + var behind = deduped.Where(BehindShaft).ToList(); + deduped.RemoveAll(BehindShaft); + deduped.AddRange(VisibleTerrainEdges(behind, [shaft.Points], [], coverBoundary: false)); + } // The carved chords join the shared-edge pass late on purpose: they are already de-duplicated by // construction (one span per inside interval), and the merge below still unions the same line coming // from two solids sharing the cut surface. deduped.AddRange(cutChords); - var occluded = OccludeEdges(faces, faceMinDepths, deduped); - List edges = MergeOverlaps(occluded); + if (paintDetailCuts) + { + // Coincident constant-depth copies have the same projected endpoints. + // Keep the nearest copy before splitting it around solid covers. + var nearestProfiles = deduped.Where(IsConstantDepthDetailProfile) + .GroupBy(edge => (ProjectedEdgeKey(edge.X1, edge.Y1, edge.X2, edge.Y2), + IsMullion: edge.CategoryId == (int)BuiltInCategory.OST_CurtainWallMullions)) + .Select(group => group.MinBy(edge => edge.MidDepth)!).ToList(); + deduped.RemoveAll(IsConstantDepthDetailProfile); + deduped.AddRange(nearestProfiles); + } + if (detailWallOccluders is { Count: > 0 }) + { + // Split a horizontal wall edge at nearer opaque faces before testing the remaining midpoints. + deduped = deduped.SelectMany(edge => ClipDetailWallEdge(edge, detailWallOccluders)).ToList(); + } + var calloutWallSpans = new List(); + var clippedCalloutWalls = new HashSet<((long Ax, long Ay, long Bx, long By) Edge, double Depth)>(); + if (spanOccluders is { Count: > 0 }) + { + // A nearer face can cover the midpoint of an edge with visible spans on either side. + var projectedSpans = deduped.Where(NeedsSpanClipping).GroupBy(edge => edge.MidDepth).ToList(); + deduped.RemoveAll(NeedsSpanClipping); + foreach (var group in projectedSpans) + deduped.AddRange(VisibleTerrainEdges(group, + spanOccluders.Where(mask => mask.FarDepth < group.Key - 1).Select(mask => mask.Points), [], + openings: spanOpenings)); + if (opaqueFineSection && !regularFineSection) + foreach (var group in deduped.Where(IsSlopingWall).GroupBy(edge => edge.MidDepth)) + { + var masks = spanOccluders.Where(mask => mask.FarDepth < group.Key - 1) + .Select(mask => mask.Points).ToList(); + foreach (var edge in group) + { + var spans = VisibleTerrainEdges([edge], masks, []).ToList(); + var key = ProjectedEdgeKey(edge.X1, edge.Y1, edge.X2, edge.Y2); + if (spans is [var span] && key == ProjectedEdgeKey(span.X1, span.Y1, span.X2, span.Y2)) + continue; + clippedCalloutWalls.Add((key, edge.MidDepth)); + calloutWallSpans.AddRange(spans); + } + } + } + bool NeedsSpanClipping(CollectedEdge edge) => + !edge.IsCut && edge.NearDepth is double near && Math.Abs(near - edge.MidDepth) < 1e-6 + && (fineSection && edge.CategoryId == (int)BuiltInCategory.OST_LightingFixtures + || roundShaftFaces.Contains(edge.FaceA) || roundShaftFaces.Contains(edge.FaceB) + || regularFineSection && IsSlopingWall(edge) + || paintDetailCuts && IsVerticalDetailProfile(edge.CategoryId, edge.X1, edge.X2)); + + static bool IsConstantDepthDetailProfile(CollectedEdge edge) => + !edge.IsCut && edge.NearDepth is double near && Math.Abs(near - edge.MidDepth) < 1e-6 + && IsVerticalDetailProfile(edge.CategoryId, edge.X1, edge.X2); + + static bool IsSlopingWall(CollectedEdge edge) => + !edge.IsCut && edge.CategoryId == (int)BuiltInCategory.OST_Walls + && edge.NearDepth is double near && Math.Abs(near - edge.MidDepth) < 1e-6 + && Math.Abs(edge.X1 - edge.X2) > 1e-6 && Math.Abs(edge.Y1 - edge.Y2) > 1e-6; + + IEnumerable ClipDetailWallEdge(CollectedEdge edge, + List<(List<(double X, double Y)> Points, double Depth)> masks) + { + if (edge.IsCut || edge.CategoryId != (int)BuiltInCategory.OST_Walls + || Math.Abs(edge.Y1 - edge.Y2) >= 1e-6 || edge.NearDepth is not double depth) + return [edge]; + var plane = edge.FaceA >= 0 ? faceOccluders[edge.FaceA].Plane : null; + if (plane == null && Math.Abs(depth - edge.MidDepth) >= 1e-6) + return [edge]; + return VisibleTerrainEdges([edge], masks.Where(face => face.Depth < depth - 1).Select(face => face.Points), []) + .Select(span => plane == null ? span : span with + { + MidDepth = plane.DepthAt((span.X1 + span.X2) / 2, (span.Y1 + span.Y2) / 2), + NearDepth = Math.Min(plane.DepthAt(span.X1, span.Y1), plane.DepthAt(span.X2, span.Y2)), + }); + } + var behindRailings = new List(); + var occluded = OccludeEdges(faces, faceOccluders, deduped, !detailPath && viewScale >= 100, + stairMaskFaces: stairMasks.Count > 0 ? stairMasks : null, + railingMaskDepths: railingMaskDepths.Count > 0 ? railingMaskDepths : null, + behindRailings: behindRailings, useDetailPlaneDepth: detailWallOccluders != null, + stairAssembly: overviewSection ? StairAssembly : null); + if (keepStairDepths) + { + var stairEdges = occluded.Where(edge => IsStairBodyCategory(edge.CategoryId) && !edge.IsCut) + .GroupBy(edge => ProjectedEdgeKey(edge.X1, edge.Y1, edge.X2, edge.Y2)) + .Select(group => group.MinBy(edge => edge.MidDepth)!).ToList(); + occluded.RemoveAll(edge => IsStairBodyCategory(edge.CategoryId) && !edge.IsCut); + occluded.AddRange(stairEdges); + } + if (viewLines.Count > 0) + viewLines = OccludeEdges(faces, faceOccluders, viewLines, keepWindowJambs: false); + if (drawTerrainCut) + { + var visibleComponentEdges = occluded.Where(edge => HasCoincidentComponents(edge.CategoryId, !cut)) + .GroupBy(edge => ProjectedEdgeKey(edge.X1, edge.Y1, edge.X2, edge.Y2)) + .Select(group => group.MinBy(edge => edge.MidDepth)!).ToList(); + occluded.RemoveAll(edge => HasCoincidentComponents(edge.CategoryId, !cut)); + foreach (var group in visibleComponentEdges.GroupBy(edge => edge.NearDepth)) + occluded.AddRange(group.Key is double depth + ? VisibleTerrainEdges(group, plantMasks.Where(mask => mask.Far < depth).Select(mask => mask.Points), []) + : group); + } + if (stairMasks.Count > 0) + { + // Trim visible edges that continue behind the stair. + occluded = occluded.SelectMany(ClipAtStairs).ToList(); + } + IEnumerable ClipAtStairs(CollectedEdge edge) => + stairMasks.Count > 0 && !edge.IsCut && !IsStairBodyCategory(edge.CategoryId) && edge.NearDepth is double near + ? VisibleTerrainEdges([edge], stairMasks.Where(mask => faceOccluders[mask.Key].MinDepth < near - 1) + .Select(mask => mask.Value), []) + : new[] { edge }; + bool IsRoundElevationEdge(CollectedEdge edge) => + edge.CategoryId == (int)BuiltInCategory.OST_GenericModel + && (roundShaftFaces.Contains(edge.FaceA) || roundShaftFaces.Contains(edge.FaceB)); + var roundElevationEdges = !cut && roundShaftFaces.Count > 0 + ? occluded.Where(IsRoundElevationEdge).ToList() : null; + if (roundElevationEdges is { Count: > 0 }) occluded.RemoveAll(IsRoundElevationEdge); + int sectionPenScale = viewportScale ?? viewScale; + double wallCutWidth = PenWidths.TryGetWidth(document, (int)BuiltInCategory.OST_Walls, true, + sectionPenScale, out double wallPen) ? wallPen : 0.2; + double CutWidth(CollectedEdge edge) => + PenWidths.TryGetWidth(document, edge.CategoryId, true, sectionPenScale, out double width) + ? width : wallCutWidth; + if (detailRoofCuts is { Count: > 0 } && detailWallCuts is { Count: > 0 }) + occluded = ResolveRoofWallCutJoins(occluded, detailRoofCuts, detailWallCuts, + viewPlaneDepth, (pnx, pny, pnz, poff)); + List edges = MergeOverlaps(occluded, paintDetailCuts ? CutWidth : null); // Every visible edge inks, horizontals included: the reference prints the wall top, the slab and roof // outlines and the ground line. (An earlier rule dropped model horizontals because the reference's vector - // layer lacks them — but on A101/A103/A104/A105 the reference carries the drawing as a raster image and only + // layer lacks them — but on A101/A103/A104/A105 the reference carries the drawing as a raster image and only // the annotation as vector, so that comparison measured an export artifact.) // A detail's own annotation curves: Revit stores detail and insulation lines of a view as curve // elements that name the view as their owner (OST_Lines, OST_InsulationLines), with their points in - // model feet — they lie on the view plane and belong to no solid, so no face ever reaches them. + // model feet — they lie on the view plane and belong to no solid, so no face ever reaches them. + List? insulationLines = null; if (planeView != null) { foreach (var element in document.Elements) { - if (element.OwnerViewId != planeView.Id || element.Location is not { CurveType: "Line" } curve) - continue; + if (element.OwnerViewId != planeView.Id || hiddenElements?.Contains(element.Id) == true + || element.Location is not { CurveType: "Line" } curve) continue; if (element.CategoryId is not ((int)BuiltInCategory.OST_Lines or (int)BuiltInCategory.OST_InsulationLines or (int)BuiltInCategory.OST_SketchLines)) continue; @@ -403,6 +1485,18 @@ internal sealed record ElevationContent( double bx = (b[0] * H[0] + b[1] * H[1] + b[2] * H[2]) * FeetToMillimetres; double by = (b[0] * V[0] + b[1] * V[1] + b[2] * V[2]) * FeetToMillimetres; if (Math.Abs(bx - ax) + Math.Abs(by - ay) < 1e-6) continue; + if (isDetail && cropWindow != null && element.DetailInsulation is { } insulation + // shortcut: unit-scale batt profile; retain the curve until non-unit scaling is verified. + && Math.Abs(insulation.Scale - 1) < 1e-9) + { + var strokes = DetailAnnotations.BattInsulation(ax, ay, bx, by, + insulation.Width * FeetToMillimetres, insulation.Mirrored).ToList(); + if (strokes.Count > 0) + { + (insulationLines ??= []).AddRange(strokes); + continue; + } + } // The file keeps annotation the viewport does not show (a line drawn past the crop edge): // only the part inside the crop is printed, and it does not stretch the drawing's frame. if (cropWindow is { } curveCrop) @@ -419,7 +1513,167 @@ internal sealed record ElevationContent( } // A detail keeps its fine construction lines; anywhere else coincident modeling // (a railing family drawing the same board four times) inks once. - if (window == null && !isDetail) edges = ConsolidateCoincident(edges); + if (window == null && !isDetail) + { + double elevationRailPenWidth = 0; + if (!cut && planeOrigin.Length == 3) + { + int scale = viewportScale ?? viewScale; + double outlinePen = PenWidths.TryGetWidth(document, (int)BuiltInCategory.OST_Walls, + false, scale, out double width) ? width : DefaultOutlinePen; + elevationRailPenWidth = scale * outlinePen; + } + edges = ConsolidateCoincident(edges, keepFineSectionProfiles: fineSection, + elevationRailPenWidth: elevationRailPenWidth); + } + if (roundElevationEdges is { Count: > 0 }) + { + // Both sides of a round shaft are distinct even when they are closer than the merge tolerance. + var inked = edges.Select(edge => ProjectedEdgeKey(edge.X1, edge.Y1, edge.X2, edge.Y2)).ToHashSet(); + foreach (var edge in roundElevationEdges) + if (inked.Add(ProjectedEdgeKey(edge.X1, edge.Y1, edge.X2, edge.Y2))) edges.Add(edge); + } + if (roofInsertFaces.Count > 0) + { + // Resolve the two sides of roof inserts before reducing them to projected lines. + var roofEdges = DedupeEdges(edgeFaces.Where(face => roofInsertFaces.Contains(face.FaceIndex)).ToList(), + D, cut ? planeOrigin : null, roofInsertFaces: roofInsertFaces); + var visibleRoofEdges = OccludeEdges(faces, faceOccluders, roofEdges, false, roofInsertFaces) + .GroupBy(edge => ProjectedEdgeKey(edge.X1, edge.Y1, edge.X2, edge.Y2)) + .Select(group => group.MinBy(edge => edge.MidDepth)!).ToList(); + edges.RemoveAll(edge => roofInsertFaces.Contains(edge.FaceA)); + edges.AddRange(window == null && !isDetail ? ConsolidateCoincident(visibleRoofEdges) : visibleRoofEdges); + } + if (topRailEdges.Count > 0) + { + // Projected duplicates are resolved after visibility; a back face can share the visible face's boundary. + var inked = edges.Select(edge => ProjectedEdgeKey(edge.X1, edge.Y1, edge.X2, edge.Y2)).ToHashSet(); + var visible = OccludeEdges(faces, faceOccluders, topRailEdges, keepWindowJambs: false); + foreach (var edge in visible) + if (inked.Add(ProjectedEdgeKey(edge.X1, edge.Y1, edge.X2, edge.Y2))) edges.Add(edge); + } + if (railingMaskDepths.Count > 0) + { + // Consolidate the original strokes first so subdividing jambs cannot change which rail edges survive. + edges = edges.SelectMany(ClipAtRailings).ToList(); + var inked = edges.Select(edge => ProjectedEdgeKey(edge.X1, edge.Y1, edge.X2, edge.Y2)).ToHashSet(); + var restored = MergeOverlaps(behindRailings.SelectMany(ClipAtStairs).SelectMany(ClipAtRailings).ToList()); + // Fine railing profiles can have two visible edges just millimetres apart. + var jambs = ConsolidateCoincident(restored.FindAll(edge => !IsRailingCategory(edge.CategoryId))); + foreach (var edge in jambs.Concat(restored.Where(edge => IsRailingCategory(edge.CategoryId)))) + if (inked.Add(ProjectedEdgeKey(edge.X1, edge.Y1, edge.X2, edge.Y2))) edges.Add(edge); + } + IEnumerable ClipAtRailings(CollectedEdge edge) => + RailingClipDepth(edge) is double near + ? VisibleTerrainEdges([edge], railingMaskDepths.Where(mask => mask.Value < near + && ClipsAtBaluster(edge, faceOccluders[mask.Key].CategoryId)) + .Select(mask => faces[mask.Key].Points), [], coverBoundary: false) + : new[] { edge }; + if (meshCovers != null && meshSilhouettes.Count > 0) + { + // Replace the owning mesh's strokes after resolving the adjacent model's edge candidates. + var meshOwners = meshSilhouettes.Select(edge => edge.SilhouetteOwnerId).ToHashSet(); + edges.RemoveAll(edge => !edge.IsCut && edge.FaceA >= 0 + && meshOwners.Contains(faceOccluders[edge.FaceA].ElementId)); + var spans = new List(); + foreach (var group in meshSilhouettes.GroupBy(edge => (edge.NearDepth, edge.SilhouetteOwnerId))) + { + var covers = meshCovers.Where(face => face.ElementId != group.Key.SilhouetteOwnerId + && face.FarDepth < group.Key.NearDepth - 1).Select(face => face.Points); + if (modelSectionMasks != null) covers = covers.Concat(modelSectionMasks); + spans.AddRange(VisibleTerrainEdges(group, covers, [], coverBoundary: false)); + } + edges.AddRange(MergeOverlaps(OccludeEdges(faces, faceOccluders, spans, keepWindowJambs: false))); + } + if (terrainEdges.Count > 0) + { + var terrainMasks = !cut ? terrainForeground + : terrainSectionMasks.Count > 0 ? terrainSectionMasks : faces.Select(face => face.Points); + var terrainProfile = MergeOverlaps(terrainEdges); + var visibleGrade = VisibleTerrainEdges(terrainProfile, terrainMasks, terrainPads).ToList(); + if (cropWindow is { } gradeCrop) + { + foreach (var edge in visibleGrade) + if (ClipSegment(edge.X1, edge.Y1, edge.X2, edge.Y2, gradeCrop.X0, gradeCrop.Y0, + gradeCrop.X1, gradeCrop.Y1, out double x1, out double y1, out double x2, out double y2)) + edges.Add(edge with { X1 = x1, Y1 = y1, X2 = x2, Y2 = y2 }); + } + else + { + edges.AddRange(visibleGrade); + } + if (document.RawData.SiteCutGraphics is { } site + && document.RawData.MaterialPatterns?.TryGetValue(site.MaterialId, out var material) == true + && document.RawData.FillPatterns?.TryGetValue(material.CutPatternId, out var pattern) == true + && pattern.Grids.Count > 0) + { + var hatchProfile = cut ? VisibleTerrainEdges(terrainProfile, [], terrainPads) : visibleGrade; + // Drafting grids share the stored view origin across the profile and pad spans. + groundHatch = new TerrainHatch( + planeOrigin[0] * H[0] + planeOrigin[1] * H[1] + planeOrigin[2] * H[2], + planeOrigin[0] * V[0] + planeOrigin[1] * V[1] + planeOrigin[2] * V[2], + site.BaseFeet * FeetToMillimetres, hatchProfile.Concat(padProfile).ToList(), pattern.Grids, + terrainSectionMasks.Count > 0 ? terrainSectionMasks : null); + if ((!cut || groundHatch.SectionMasks != null) && FillHatch.DraftingTiles(pattern.Grids, 0, 0, 0.1) is { Count: > 0 }) + { + bool BehindGround(CollectedEdge edge) => + !edge.IsCut && edge.FaceA >= 0 && edge.MidDepth > viewPlaneDepth + 1; + var covers = GroundSpans(groundHatch, groundHatch.BaseY); + if (!cut) covers = covers.Concat(terrainSectionMasks); + var visible = VisibleTerrainEdges(edges.Where(BehindGround), covers, [], + coverBoundary: false).ToList(); + edges.RemoveAll(edge => BehindGround(edge)); + edges.AddRange(visible); + } + } + } + edges.AddRange(elevationCutEdges); + // Clip after merging so the selection of other coincident edges stays independent of these spans. + if (sectionWallFaces.Count > 1) + { + var wallFacesByFinish = sectionWallFaces.ToLookup(face => (face.Value.TypeId, face.Value.MaterialId)); + var trimmedSpans = new List(); + edges = edges.SelectMany(ClipWallOverlap).ToList(); + if (trimmedSpans.Count > 0) + { + var visible = OccludeEdges(faces, faceOccluders, trimmedSpans, keepWindowJambs: false); + var hidden = trimmedSpans.Except(visible).ToHashSet(); + edges.RemoveAll(hidden.Contains); + } + + IEnumerable ClipWallOverlap(CollectedEdge edge) + { + if (edge.IsCut || edge.ViewLineStyleId != 0 || edge.NearDepth is not double near + || Math.Abs(edge.MidDepth - near) >= 1e-6 + || !sectionWallFaces.TryGetValue(edge.FaceA, out var wall)) return [edge]; + + int elementId = faceOccluders[edge.FaceA].ElementId; + var covers = wallFacesByFinish[(wall.TypeId, wall.MaterialId)] + .Where(face => faceOccluders[face.Key].ElementId != elementId + && Math.Abs(face.Value.Depth - wall.Depth) < 1e-6) + .Select(face => faces[face.Key].Points).ToList(); + if (covers.Count == 0) return [edge]; + var spans = VisibleTerrainEdges([edge], covers, [], coverBoundary: false).ToList(); + if (spans is [var span] && Math.Abs(span.X2 - edge.X2) < 1e-6 && Math.Abs(span.Y2 - edge.Y2) < 1e-6 + && Math.Abs(span.X1 - edge.X1) < 1e-6 && Math.Abs(span.Y1 - edge.Y1) < 1e-6) return [edge]; + trimmedSpans.AddRange(spans); + return spans; + } + } + if (sectionWallFaces.Count > 0) + edges = edges.SelectMany(ClipSlopingRailBehindWall).ToList(); + + IEnumerable ClipSlopingRailBehindWall(CollectedEdge edge) + { + if (edge.IsCut || edge.ViewLineStyleId != 0 || !IsRailingCategory(edge.CategoryId) + || edge.NearDepth is not double near || Math.Abs(near - edge.MidDepth) >= 1e-6 + || Math.Abs(edge.X1 - edge.X2) < 1e-6 || Math.Abs(edge.Y1 - edge.Y2) < 1e-6) + return [edge]; + + var covers = sectionWallFaces.Where(face => face.Value.Depth < near - 1) + .Select(face => faces[face.Key].Points); + return VisibleTerrainEdges([edge], covers, [], coverBoundary: false); + } // The site around the building is drawn, but it does not decide the frame: the building does, with a little // air around it for the trees and the ground. Context beyond that air (a tree far down the site) is dropped, // so the drawing stays the size of the building. @@ -428,23 +1682,21 @@ internal sealed record ElevationContent( double breadth = maxX - minX, heightExtent = maxY - minY; double keepLeft = minX - breadth * 0.25, keepRight = maxX + breadth * 0.25; double keepBottom = minY - heightExtent * 0.08, keepTop = maxY + heightExtent * 0.08; - context.RemoveAll(shape => shape.Points.Any(point => point.X < keepLeft || point.X > keepRight - || point.Y < keepBottom || point.Y > keepTop)); + context.RemoveAll(shape => (!shape.Terrain || terrainFillCrop == null) && + shape.Points.Any(point => point.X < keepLeft || point.X > keepRight + || point.Y < keepBottom || point.Y > keepTop)); minX -= breadth * 0.02; maxX += breadth * 0.02; minY -= heightExtent * 0.02; maxY += heightExtent * 0.02; } - // Far to near: painter's algorithm, so a nearer wall hides the one behind it. - faces.Sort((left, right) => right.Depth.CompareTo(left.Depth)); - // The levels of the model and the grids that stand across the view are drawn dashed, as an elevation prints // them, with the level name and the grid bubble. Only the level records of the project count: the families // each carry their own reference levels (dozens sharing the category), which no project view shows. var levels = new List<(double Y, string Label, Element Plane)>(); foreach (var element in document.Elements) { - if (element.CategoryId != (int)BuiltInCategory.OST_Levels) continue; + if (element.CategoryId != (int)BuiltInCategory.OST_Levels || hiddenElements?.Contains(element.Id) == true) continue; if (element.RootClassName != "Level") continue; if (element.LookupParameter(BuiltInParameter.LEVEL_ELEV)?.Value is not double elevation) continue; levels.Add((elevation * FeetToMillimetres, element.Name ?? "", element)); @@ -454,6 +1706,12 @@ internal sealed record ElevationContent( // once, with the first name it finds. The line of a level runs to its datum envelope projected on the // view's right axis (rvt-prt datums.py); without a decoded plane it spans the content like before. var distinctLevels = new List<(double Y, string Label, double X0, double X1)>(); + var nativeLevels = new Dictionary(); + var defaultLevelHeads = new List<(double Y, int Type, double Left, double Right, double Radius, int SymbolId)>(); + var savedModelExtentHeads = new List<(int Type, double Left, double Right, double Head)>(); + var datumExtents = planeView != null ? document.RawData.DatumExtents?.GetValueOrDefault(planeView.Id) : null; + if (datumExtents != null && Math.Abs(datumExtents.Normal[0] * D[0] + datumExtents.Normal[1] * D[1] + + datumExtents.Normal[2] * D[2] - 1) > 1e-6) datumExtents = null; foreach (var level in levels) { if (distinctLevels.Count > 0 && Math.Abs(distinctLevels[^1].Y - level.Y) < 1.0) @@ -483,11 +1741,67 @@ internal sealed record ElevationContent( } } distinctLevels.Add((level.Y, level.Label, x0, x1)); + if (level.Plane.LevelPlane is not { Origin: var levelOrigin } + || document.RawData.DatumHeads?.GetValueOrDefault(level.Plane.TypeId) is not { } head + || CircleHeadRadius(document, head.SymbolId, "M_Level Head - Circle") is not double radius) continue; + var extent = datumExtents?.Datums.GetValueOrDefault(level.Plane.Id); + if (extent == null && sectionAnnotationCrop is { } annotation) + { + double left = Math.Max(x0, annotation.X0), right = Math.Min(x1, annotation.X1); + if (right > left) + nativeLevels.Add(level.Y, new NativeLevelLine(left, right, level.Y, right, radius, null, head.SymbolId)); + } + else if (extent == null && datumExtents != null) + { + defaultLevelHeads.Add((level.Y, level.Plane.TypeId, x0, x1, radius, head.SymbolId)); + } + // shortcut: support the authored right head until left and dual heads are decoded. + else if (extent is { Overrides: 0 or 0x20 or 0x30, FreeEndLeader: null } + && (extent.Overrides == 0x30 ? extent.FreeEnd : extent.FreeEnd3d) is double freeEnd + && double.IsFinite(freeEnd)) + { + double datumOrigin = Project(levelOrigin, H); + double left = datumOrigin + freeEnd * FeetToMillimetres; + // A leader remains authored when both endpoints use the model extent. + if (extent is { Overrides: 0, BubbleLeader: null }) continue; + double headX = extent.Overrides == 0 + ? Project(extent.BubbleLeader!.Anchor, H) + : datumOrigin + extent.BubbleEnd * FeetToMillimetres; + if (!(headX > left)) continue; + var line = new NativeLevelLine(left, headX, level.Y, headX, radius, null, head.SymbolId); + if (extent.BubbleLeader is { } leader) + { + double endX = Project(leader.End, H); + double endY = Project(leader.End, V); + var elbow = (X: Project(leader.Elbow, H), Y: Project(leader.Elbow, V)); + double headY = Project(leader.Anchor, V); + if (Math.Abs(endY - level.Y) > 1 || Math.Abs(Project(leader.Anchor, H) - headX) > 1 + || endX < left || elbow.X < endX || headX < elbow.X) continue; + if (Math.Abs(headY - level.Y) > 1 || Math.Abs(elbow.Y - level.Y) > 1) + line = line with { HeadY = headY, LineEnd = endX, Elbow = elbow }; + } + nativeLevels.Add(level.Y, line); + if (extent.Overrides == 0 && extent.BubbleEnd3d is double modelRight + && headX <= x1 && Math.Abs(left - x0) <= 1 + && Math.Abs(datumOrigin + modelRight * FeetToMillimetres - x1) <= 1) + savedModelExtentHeads.Add((level.Plane.TypeId, x0, x1, headX)); + } + } + foreach (var level in defaultLevelHeads) + { + // Model-extent leaders can expose the shared head column even when straight levels have no view record. + var heads = savedModelExtentHeads.Where(head => head.Type == level.Type + && Math.Abs(head.Left - level.Left) <= 1 && Math.Abs(head.Right - level.Right) <= 1) + .Select(head => head.Head).ToList(); + if (heads.Count >= 2 && heads.Max() - heads.Min() <= 1) + nativeLevels.Add(level.Y, new NativeLevelLine(level.Left, heads[0], level.Y, heads[0], + level.Radius, null, level.SymbolId)); } var grids = new List<(double X, string Name)>(); + var nativeGrids = new Dictionary(); foreach (var element in document.Elements) { - if (element.CategoryId != (int)BuiltInCategory.OST_Grids) continue; + if (element.CategoryId != (int)BuiltInCategory.OST_Grids || hiddenElements?.Contains(element.Id) == true) continue; if (element.Location is not { CurveType: "Line" } line) continue; double dx = line.EndPoint[0] - line.StartPoint[0], dy = line.EndPoint[1] - line.StartPoint[1]; double length = Math.Sqrt(dx * dx + dy * dy); @@ -495,82 +1809,353 @@ internal sealed record ElevationContent( if (Math.Abs(dx / length * H[0] + dy / length * H[1]) > 0.2) continue; double x = (line.StartPoint[0] * H[0] + line.StartPoint[1] * H[1]) * FeetToMillimetres; grids.Add((x, element.Name ?? "")); + if (planeView is { ViewOrigin.Length: 3 } && V[2] > 0.999 + && element.GridPlane is { Envelope.Length: 4 } gridPlane + && document.RawData.DatumHeads?.GetValueOrDefault(element.TypeId) is { GridBubblePosition: 2 } head + && CircleHeadRadius(document, head.SymbolId, "M_Grid Head - Circle") is double radius) + { + var extent = datumExtents?.Datums.GetValueOrDefault(element.Id); + bool authored = extent is { Overrides: 0x20 or 0x30, BubbleLeader: null, FreeEndLeader: null, + FreeEnd3d: not null, BubbleEnd3d: not null }; + bool unboundedSection = fineSection && !detailPath && !stairsOnly && sectionCrop != null + && planeView.ViewAnnotationCropActive is false && extent == null; + if (!authored && !unboundedSection && (detailPath || stairsOnly || viewScale < 100) + && (sectionAnnotationCrop == null || extent != null)) continue; + var e = gridPlane.Envelope; + double datumOrigin = Project(gridPlane.Origin, V); + double u = Project(gridPlane.XVector, V); + double v = Project(gridPlane.YVector, V); + double bottom = datumOrigin + Math.Min(u * e[0], u * e[2]) + Math.Min(v * e[1], v * e[3]); + double top = datumOrigin + Math.Max(u * e[0], u * e[2]) + Math.Max(v * e[1], v * e[3]); + if (authored) + { + // The stored 2D and 3D values share an origin, even when the detail view itself moved. + top += (extent!.BubbleEnd - extent.BubbleEnd3d!.Value) * FeetToMillimetres; + if (extent.Overrides == 0x30) + bottom += (extent.FreeEnd - extent.FreeEnd3d!.Value) * FeetToMillimetres; + } + else if (sectionAnnotationCrop is { } annotation) + { + bottom = Math.Max(bottom, annotation.Y0); + top = Math.Min(top, annotation.Y1); + } + else if (unboundedSection) + { + // The default grid envelope includes the head above the end of the line. + top -= 2 * radius * (viewportScale ?? viewScale); + } + if (double.IsFinite(bottom) && double.IsFinite(top) && top > bottom) + nativeGrids.TryAdd(x, new NativeGridLine(bottom, top, radius)); + } } grids.Sort((left, right) => left.X.CompareTo(right.X)); context.Sort((left, right) => right.Depth.CompareTo(left.Depth)); - // A detail carries no grid bubbles (none of the reference details shows one), and a windowed - // detail without a file crop carries no level lines either. But a crop-drawn detail keeps the levels - // whose height falls in its crop — the reference details draw their own level rows with markers - // (Typ. Wall Section shows all six), and DrawContent already clips rows to the crop height. + // Detail datums need authored ends or a decoded annotation crop. A detail without a model crop + // also omits the level rows because their visible height is unknown. if (window != null || isDetail) { if (cropWindow == null) distinctLevels.Clear(); - grids.Clear(); + grids.RemoveAll(grid => !nativeGrids.ContainsKey(grid.X)); } // The grid bubbles print above the frame: without grids (a windowed detail) the frame ends at the model. if (grids.Count > 0) maxY += 4500; - return new ElevationContent(faces, distinctLevels, grids, context, edges, minX, minY, maxX, maxY); - } - - /// A projected edge for inking: its ends in view millimetres, the painter's depth of its face, - /// the depth of its midpoint for occlusion, the incident faces (FaceB is -1 when single), its plane key - /// for coplanar merging, whether the section cut created it (inked with its own category's cut pen; - /// other edges use the projection pen), and the category of the face it came from. - internal sealed record CollectedEdge(double X1, double Y1, double X2, double Y2, double Depth, double MidDepth, - int FaceA, int FaceB, long Nx, long Ny, long Nz, long Off, bool IsCut = false, int CategoryId = 0); - - /// Visible edges of the projected faces: an edge shared by exactly two coplanar faces is a - /// triangulation diagonal inside a flat surface and is not inked; every other edge is drawn once, so a - /// crease shared by two faces is not inked twice. Endpoints quantize to 0.1 mm, plane normals to 0.001 - /// and plane offsets to 0.5 mm. Each edge carries its 3D midpoint depth and its incident faces. An edge - /// both of whose 3D ends lie on the cut plane (within a millimetre) is cut-created. - internal static List DedupeEdges( - List<(List<(double X, double Y)> Points, List Ring, double Depth, long Nx, long Ny, long Nz, long Off, int FaceIndex, int CategoryId)> edgeFaces, - double[] viewDir, double[]? cutOrigin = null) - { - var byEdge = new Dictionary<(long Ax, long Ay, long Bx, long By), List>(); - for (int f = 0; f < edgeFaces.Count; f++) + var detailBreaks = isDetail && cropWindow != null && planeView != null + ? DetailAnnotations.BreakLines(document, planeView.Id, H, V) : null; + var surfaceHatches = surfacePatterns.Count == 0 && dashedSurfacePatterns.Count == 0 ? null : new SurfaceHatches( + planeOrigin[0] * H[0] + planeOrigin[1] * H[1] + planeOrigin[2] * H[2], + planeOrigin[0] * V[0] + planeOrigin[1] * V[1] + planeOrigin[2] * V[2], surfacePatterns, dashedSurfacePatterns, + UseClippedLines: opaqueFineSection && !detailPath); + // shortcut: use wholly nearer masks for site meshes until their edges carry per-point depths. + foreach (var group in viewLines.GroupBy(edge => edge.NearDepth)) + edges.AddRange(VisibleTerrainEdges(group, plantMasks.Where(mask => mask.Far < group.Key).Select(mask => mask.Points), [])); + // Keep regular section layer edges out of the selection of coincident model edges. + if (roofLayerEdges != null) edges.AddRange(roofLayerEdges); + if (clippedCalloutWalls.Count > 0) { - var points = edgeFaces[f].Points; - for (int i = 0; i < points.Count; i++) + // Adding the split spans earlier can change the selection of unrelated coincident edges. + edges.RemoveAll(edge => IsSlopingWall(edge) + && clippedCalloutWalls.Contains((ProjectedEdgeKey(edge.X1, edge.Y1, edge.X2, edge.Y2), edge.MidDepth))); + var visibleSlopes = OccludeEdges(faces, faceOccluders, calloutWallSpans, keepWindowJambs: false, + useDetailPlaneDepth: detailWallOccluders != null); + edges.AddRange(MergeOverlaps(visibleSlopes.SelectMany(ClipAtStairs).SelectMany(ClipAtRailings).ToList())); + } + var cutFaces = paintDetailCuts ? terrainSectionMasks : modelSectionMasks; + if (cutFaces is { Count: > 0 }) + { + bool BehindCap(CollectedEdge edge) => + edge.FaceA >= 0 && !edge.IsCut && edge.NearDepth > viewPlaneDepth + 1; + var visible = VisibleTerrainEdges(edges.Where(BehindCap), cutFaces, [], coverBoundary: false).ToList(); + edges.RemoveAll(edge => BehindCap(edge)); + edges.AddRange(visible); + } + List<(double X, double Y)>? soilReceiver = null; + if (shadows != null && groundHatch != null && shadowTerrainCrop is { } soilBounds) + soilReceiver = shadows.AddSoilCutReceiver(soilBounds, viewPlaneDepth, groundHatch.BaseY); + var castShadows = shadows?.Project(viewPlaneDepth); + if (groundHatch != null && soilReceiver != null && castShadows?.Remove(soilReceiver, out var soilShadow) == true) + groundHatch = groundHatch with { Shadow = soilShadow }; + if (terrainOcclusion != null) + { + sectionTerrain?.Sort(); + edges = terrainOcclusion.ClipEdges(edges, cut); + } + if (!cut && drawTerrainCut && showSurfacePatterns) + { + var inked = edges.Select(edge => ProjectedEdgeKey(edge.X1, edge.Y1, edge.X2, edge.Y2)).ToHashSet(); + // A projected stair edge may have lost its nearer copy during ordinary mesh edge selection. + var missing = deduped.Where(edge => IsStairBodyCategory(edge.CategoryId) + && !inked.Contains(ProjectedEdgeKey(edge.X1, edge.Y1, edge.X2, edge.Y2))) + .GroupBy(edge => ProjectedEdgeKey(edge.X1, edge.Y1, edge.X2, edge.Y2)) + .ToDictionary(group => group.Key, group => group.Min(edge => edge.MidDepth)); + if (missing.Count > 0) { - var a = points[i]; - var b = points[(i + 1) % points.Count]; - long ax = (long)Math.Round(a.X * 10), ay = (long)Math.Round(a.Y * 10); - long bx = (long)Math.Round(b.X * 10), by = (long)Math.Round(b.Y * 10); - if (ax == bx && ay == by) continue; - var key = (ax < bx || (ax == bx && ay <= by)) ? (ax, ay, bx, by) : (bx, by, ax, ay); - if (!byEdge.TryGetValue(key, out var members)) byEdge[key] = members = new List(); - members.Add(f); + var nearer = DedupeEdges(edgeFaces.Where(face => IsStairBodyCategory(face.CategoryId)).ToList(), + D, keepStairDepths: true) + .Where(edge => missing.TryGetValue(ProjectedEdgeKey(edge.X1, edge.Y1, edge.X2, edge.Y2), + out double farDepth) && edge.MidDepth < farDepth - 1).ToList(); + var visible = OccludeEdges(faces, faceOccluders, nearer, keepWindowJambs: false); + if (terrainOcclusion != null) visible = terrainOcclusion.ClipEdges(visible, cut: false); + foreach (var edge in ConsolidateCoincident(visible)) + if (inked.Add(ProjectedEdgeKey(edge.X1, edge.Y1, edge.X2, edge.Y2))) edges.Add(edge); } } - var edges = new List(); - var seen = new HashSet<(long Ax, long Ay, long Bx, long By)>(); - for (int f = 0; f < edgeFaces.Count; f++) + if (elevationTubeEdges.Count > 0) { - var (points, ring, depth, nx, ny, nz, off, faceIndex, categoryId) = edgeFaces[f]; - // Window-clipped polygons lose the one-to-one vertex correspondence with the 3D ring; - // those small details fall back to the face-average depth. + var visible = OccludeEdges(faces, faceOccluders, elevationTubeEdges, keepWindowJambs: false); + if (terrainOcclusion != null) visible = terrainOcclusion.ClipEdges(visible, cut: false, requireFace: false); + var inked = edges.Select(edge => ProjectedEdgeKey(edge.X1, edge.Y1, edge.X2, edge.Y2)).ToHashSet(); + foreach (var edge in ConsolidateCoincident(visible)) + if (inked.Add(ProjectedEdgeKey(edge.X1, edge.Y1, edge.X2, edge.Y2))) edges.Add(edge); + } + if (sectionBillboards.Count > 0) + { + var points = sectionBillboards.SelectMany(ring => ring).ToArray(); + double left = points.Min(point => point.X), right = points.Max(point => point.X); + double bottom = points.Min(point => point.Y), top = points.Max(point => point.Y); + bool BehindBillboard(CollectedEdge edge) => edge.FaceA >= 0 && !edge.IsCut + && edge.ViewLineStyleId == 0 && edge.MidDepth >= viewPlaneDepth + && Math.Min(edge.X1, edge.X2) < right && Math.Max(edge.X1, edge.X2) > left + && Math.Min(edge.Y1, edge.Y2) < top && Math.Max(edge.Y1, edge.Y2) > bottom; + var visible = VisibleTerrainEdges(edges.Where(BehindBillboard), sectionBillboards, [], + coverBoundary: false).ToList(); + edges.RemoveAll(edge => BehindBillboard(edge)); + edges.AddRange(visible); + } + // Removing seams earlier can change which other coincident model edge is selected. + if (railSeams is { Count: > 0 }) + edges.RemoveAll(edge => !edge.IsCut && edge.ViewLineStyleId == 0 && IsRailingCategory(edge.CategoryId) + && railSeams.Contains(ProjectedEdgeKey(edge.X1, edge.Y1, edge.X2, edge.Y2))); + var siteOutlines = siteObjects.Count == 0 ? null : siteObjects.SelectMany(site => + VisibleTerrainEdges(site.Edges, plantMasks.Where(mask => mask.Far < site.Near).Select(mask => mask.Points) + .Concat(site.WireMesh + ? siteModelMasks.Where(mask => mask.Near >= viewPlaneDepth && mask.Far < site.Near) + .Select(mask => mask.Points) + : faces.Select(face => face.Points)), [])).ToList(); + if (plantingOutlines != null) + { + var ground = groundHatch != null ? GroundSpans(groundHatch, groundHatch.BaseY).ToList() : []; + var outlines = plantingOutlines.Project(ground).ToList(); + if (outlines.Count > 0) (siteOutlines ??= []).AddRange(outlines); + } + // Visibility uses face indices in collection order. Reorder the fills only for painting. + faces.Sort((left, right) => right.Depth.CompareTo(left.Depth)); + return new ElevationContent(faces, distinctLevels, grids, context, edges, minX, minY, maxX, maxY, + groundHatch, nativeLevels, nativeGrids, insulationLines, detailBreaks, layerHatches, + CircularAnnotations.Project(document, planeView?.Id, H, V), surfaceHatches, + modelHatches.Count > 0 ? modelHatches : null, castShadows, skyGradient, + siteSilhouettes is { Count: > 0 } ? siteSilhouettes : null, + opaqueSection && (drawGround && !detailPath || paintDetailCuts && ambient != null), + siteOutlines, + paintOpenings.Count > 0 ? paintOpenings : null, shadows?.ClipSiteFacetsToModel(castShadows), + DetailCutFaces: cutFaces is { Count: > 0 } ? cutFaces : null, + Glazing: glazing is { HasPanes: true } ? glazing : null, + AmbientTones: ambient?.Calculate(paintDetailCuts ? cutFaces : null, viewPlaneDepth), + FaceFills: faceFills.Count > 0 ? faceFills : null, + DetailGlass: detailGlass is { Count: > 0 } ? detailGlass : null, + TerrainClippedFaces: terrainOcclusion?.ClippedFaces(), + KeepDoorDepths: keepDoorDepths, + SectionBillboards: sectionBillboards.Count > 0 ? sectionBillboards : null, + PlantTones: ElevationShadows.VisiblePlantTones(plantFacets, plantTones)); + + System.Numerics.Vector3 AmbientVector(double[] point, double units) => + new((float)Project(point, H, units), (float)Project(point, V, units), (float)Project(point, D, units)); + + int StairAssembly(int id) => + document.GetElement(id)?.SerializedOwningElementId is > 0 and int owner + && document.GetElement(owner)?.CategoryId == (int)BuiltInCategory.OST_Stairs ? owner : id; + + static bool PlacedSiteElement(Element element) => !element.IsDiscovered + && element.SerializedUnplacedOwnerId is not > 0 && element.NativeIsSymbol != true + && !element.RootClassIs("FamilySymbol"); + + bool HasEdgeOnRoofGlazing(List geometryFaces) + { + bool hasPane = false; + foreach (var face in geometryFaces) + { + // The thickness of the pane has vertical faces even when the pane itself is seen edge-on. + if (!face.PlaneSurface || Math.Abs(face.Normal[2]) <= 1e-9 + || document.GetElement(face.RenderStyleId ?? face.NestedRenderStyleId ?? -1) + ?.SerializedMaterialTransparency is not > 0) + continue; + if (Math.Abs(Project(face.Normal, D, 1)) > 1e-9) return false; + hasPane = true; + } + return hasPane; + } + + bool HasGlazingPattern(GeoFace face) => + (face.RenderStyleId ?? face.NestedRenderStyleId) is > 0 and int material + && document.GetElement(material)?.SerializedMaterialTransparency is > 0 + && document.RawData.MaterialPatterns?.TryGetValue(material, out var pattern) == true + && pattern.SurfacePatternColor == 0 && pattern.SurfacePatternId == face.ModelPattern?.PatternId; + + static bool IsProjectedRectangle(List<(double X, double Y)> points) => + points.Count == 4 && Math.Abs(PlanPrinter.SignedArea(points)) > 1e-6 + && points.Zip(points.Skip(1).Append(points[0])).All(edge => + Math.Abs(edge.First.X - edge.Second.X) < 1e-6 || Math.Abs(edge.First.Y - edge.Second.Y) < 1e-6); + + static bool RectanglesOverlap(List<(double X, double Y)> a, List<(double X, double Y)> b) => + Math.Min(a.Max(point => point.X), b.Max(point => point.X)) + - Math.Max(a.Min(point => point.X), b.Min(point => point.X)) > 1e-6 + && Math.Min(a.Max(point => point.Y), b.Max(point => point.Y)) + - Math.Max(a.Min(point => point.Y), b.Min(point => point.Y)) > 1e-6; + + List<(double X, double Y)> ProjectRing(List vertices) + { + var ring = vertices.Select(p => p.Select(value => value * FeetToMillimetres).ToArray()).ToList(); + if (cut || drawTerrainCut) ring = ClipBehind(ring, planeOrigin, D); + var points = ring.Select(p => (X: Project(p, H, 1), Y: Project(p, V, 1))).ToList(); + return cropWindow is { } crop ? ClipToWindow(points, crop.X0, crop.X1, crop.Y0, crop.Y1) : points; + } + + IEnumerable> ProjectOpenings(GeoFace face) + { + foreach (var hole in face.InnerVertices ?? []) + { + if (hole.Count < 3 || hole.Any(point => point.Length != 3 || !point.All(double.IsFinite))) continue; + var points = ProjectRing(hole); + if (points.Count >= 3 && Math.Abs(PlanPrinter.SignedArea(points)) > 1e-6) yield return points; + } + } + + void OrderRoofLayerPaint(List<(int Index, GeoFace Face)> roofLayers) + { + foreach (var (index, exterior) in roofLayers) + { + var patterned = faces[index]; + if (!modelHatches.ContainsKey(patterned.Points) || exterior.GeometryNode == 0) continue; + double nd = Project(D, exterior.Normal, 1); + if (Math.Abs(nd) < 1e-6) continue; + double exteriorPlane = Project(exterior.OuterVertices![0], exterior.Normal); + foreach (var (otherIndex, other) in roofLayers) + { + if (other.GeometryNode != exterior.GeometryNode + || Math.Abs(other.Normal[0] + exterior.Normal[0]) + + Math.Abs(other.Normal[1] + exterior.Normal[1]) + + Math.Abs(other.Normal[2] + exterior.Normal[2]) > 1e-6) continue; + double gap = (Project(other.OuterVertices![0], exterior.Normal) - exteriorPlane) / nd; + var underside = faces[otherIndex]; + if (gap <= 1 || underside.Depth > patterned.Depth) continue; + // Different extents can reverse the mean depths of parallel skins of the same solid. + faces[otherIndex] = (underside.Points, patterned.Depth + gap, underside.Outline); + } + } + } + } + + internal static double? CircleHeadRadius(RvtDocument document, int symbolId, string familyName) + { + var family = document.GetElement(symbolId); + if (family is not { FamilyName: var name, BoundingBox: { Length: 6 } box } || name != familyName) return null; + double width = (box[3] - box[0]) * FeetToMillimetres; + double height = (box[4] - box[1]) * FeetToMillimetres; + return height > 0 && Math.Abs(width - height) < 0.01 ? height / 2 : null; + } + + /// A projected edge for inking: its ends in view millimetres, the painter's depth of its face, + /// the depth of its midpoint for occlusion, the incident faces (FaceB is -1 when single), its plane key + /// for coplanar merging, whether the section cut created it (inked with its own category's cut pen; + /// other edges use the projection pen), and the category of the face it came from. + internal sealed record CollectedEdge(double X1, double Y1, double X2, double Y2, double Depth, double MidDepth, + int FaceA, int FaceB, long Nx, long Ny, long Nz, long Off, bool IsCut = false, int CategoryId = 0, + double? NearDepth = null) + { + internal int ViewLineStyleId { get; init; } + internal (int Ring, int Segment)? SourceRingEdge { get; init; } + internal int? SilhouetteOwnerId { get; init; } + } + + internal static (long Ax, long Ay, long Bx, long By) ProjectedEdgeKey(double x1, double y1, double x2, double y2) + { + long ax = (long)Math.Round(x1 * 10), ay = (long)Math.Round(y1 * 10); + long bx = (long)Math.Round(x2 * 10), by = (long)Math.Round(y2 * 10); + return (ax < bx || (ax == bx && ay <= by)) ? (ax, ay, bx, by) : (bx, by, ax, ay); + } + + /// Visible edges of the projected faces: an edge shared by exactly two coplanar faces is a + /// triangulation diagonal inside a flat surface and is not inked; every other edge is drawn once, so a + /// crease shared by two faces is not inked twice. Endpoints quantize to 0.1 mm, plane normals to 0.001 + /// and plane offsets to 0.5 mm. Each edge carries its 3D midpoint depth and its incident faces. An edge + /// both of whose 3D ends lie on the cut plane (within a millimetre) is cut-created. + private sealed record ProjectionFace(List<(double X, double Y)> Points, List Ring, + double Depth, long Nx, long Ny, long Nz, long Off, int FaceIndex, int CategoryId, bool[]? IncomingEdges); + + private static List DedupeEdges( + List edgeFaces, + double[] viewDir, double[]? cutOrigin = null, bool keepComponentDepths = false, + IReadOnlySet? roofInsertFaces = null, bool fineSection = false, bool keepStairDepths = false, + HashSet<(long Ax, long Ay, long Bx, long By)>? railSeams = null, bool keepDoorDepths = false, + bool keepDetailProfileDepths = false) + { + var byEdge = new Dictionary<((long Ax, long Ay, long Bx, long By) Edge, long Start, long End), + List<(int Face, int Vertex)>>(); + for (int f = 0; f < edgeFaces.Count; f++) + { + var face = edgeFaces[f]; + for (int i = 0; i < face.Points.Count; i++) + { + if (face.IncomingEdges?[(i + 1) % face.Points.Count] == false) continue; + var key = EdgeKey(face.Points, face.Ring, PreserveDepth(face, i), i); + if (key.Edge.Ax == key.Edge.Bx && key.Edge.Ay == key.Edge.By) continue; + if (!byEdge.TryGetValue(key, out var members)) byEdge[key] = members = []; + members.Add((f, i)); + } + } + var edges = new List(); + var seen = new HashSet<((long Ax, long Ay, long Bx, long By) Edge, long Start, long End)>(); + for (int f = 0; f < edgeFaces.Count; f++) + { + var (points, ring, depth, nx, ny, nz, off, faceIndex, categoryId, incomingEdges) = edgeFaces[f]; + // Window-clipped polygons lose the one-to-one vertex correspondence with the 3D ring; + // those small details fall back to the face-average depth. bool hasRing = ring.Count == points.Count; for (int i = 0; i < points.Count; i++) { + int next = (i + 1) % points.Count; + if (incomingEdges?[next] == false) continue; var a = points[i]; - var b = points[(i + 1) % points.Count]; - long ax = (long)Math.Round(a.X * 10), ay = (long)Math.Round(a.Y * 10); - long bx = (long)Math.Round(b.X * 10), by = (long)Math.Round(b.Y * 10); - if (ax == bx && ay == by) continue; - var key = (ax < bx || (ax == bx && ay <= by)) ? (ax, ay, bx, by) : (bx, by, ax, ay); + var b = points[next]; + var key = EdgeKey(points, ring, PreserveDepth(edgeFaces[f], i), i); + if (key.Edge.Ax == key.Edge.Bx && key.Edge.Ay == key.Edge.By) continue; if (!seen.Add(key)) continue; var members = byEdge[key]; - int other = members.Count == 2 ? (members[0] == f ? members[1] : members[0]) : -1; + if (railSeams != null && IsRailingCategory(categoryId) && members.Count > 2 && IsProjectedRailSeam(members, a, b)) + railSeams.Add(key.Edge); + int other = members.Count == 2 ? (members[0].Face == f ? members[1].Face : members[0].Face) : -1; int otherFace = -1; if (other >= 0) { var o = edgeFaces[other]; - if (o.Nx == nx && o.Ny == ny && o.Nz == nz && o.Off == off) continue; + // Opposite sides form a seam. Same-side copies can belong to the same native face. + if (o.Nx == nx && o.Ny == ny && o.Nz == nz && o.Off == off + && (!UsesDetailProfileDepth(edgeFaces[f], i) + || ProjectedSide(a, b, points) * ProjectedSide(a, b, o.Points) == -1)) + continue; otherFace = o.FaceIndex; } double midDepth = depth; + double? nearDepth = null; bool isCut = false; if (hasRing) { @@ -578,23 +2163,107 @@ internal static List DedupeEdges( var cb = ring[(i + 1) % ring.Count]; midDepth = ((ca[0] + cb[0]) / 2) * viewDir[0] + ((ca[1] + cb[1]) / 2) * viewDir[1] + ((ca[2] + cb[2]) / 2) * viewDir[2]; - if (cutOrigin != null) - { - double da = (ca[0] - cutOrigin[0]) * viewDir[0] + (ca[1] - cutOrigin[1]) * viewDir[1] - + (ca[2] - cutOrigin[2]) * viewDir[2]; - double db = (cb[0] - cutOrigin[0]) * viewDir[0] + (cb[1] - cutOrigin[1]) * viewDir[1] - + (cb[2] - cutOrigin[2]) * viewDir[2]; - isCut = Math.Abs(da) <= 1.0 && Math.Abs(db) <= 1.0; - } + nearDepth = Math.Min(Project(ca, viewDir, 1), Project(cb, viewDir, 1)); + isCut = IsCutEdge(ca, cb); } // A horizontal face projects to a horizontal line, so it is seen edge-on and the edge along it is not // inked (the reference draws the wall top as the ends of its boards, without a line across them). // A section keeps the edges its own cut created - those are the cut profile of a horizontal slab. - edges.Add(new CollectedEdge(a.X, a.Y, b.X, b.Y, depth, midDepth, faceIndex, otherFace, nx, ny, nz, off, isCut, categoryId)); + edges.Add(new CollectedEdge(a.X, a.Y, b.X, b.Y, depth, midDepth, faceIndex, otherFace, nx, ny, nz, off, + isCut, categoryId, nearDepth)); } } edges.Sort((left, right) => right.Depth.CompareTo(left.Depth)); return edges; + + bool PreserveDepth(ProjectionFace face, int index) => roofInsertFaces?.Contains(face.FaceIndex) == true + || fineSection && face.CategoryId == (int)BuiltInCategory.OST_LightingFixtures + || keepDoorDepths && face.CategoryId == (int)BuiltInCategory.OST_Doors + || keepStairDepths && IsStairBodyCategory(face.CategoryId) + || keepComponentDepths && HasCoincidentComponents(face.CategoryId, cutOrigin == null) + || UsesDetailProfileDepth(face, index); + + bool UsesDetailProfileDepth(ProjectionFace face, int index) + { + int next = (index + 1) % face.Points.Count; + // Cut edges still share the cut-plane key and use the existing cut pens. + return keepDetailProfileDepths && face.Ring.Count == face.Points.Count + && IsVerticalDetailProfile(face.CategoryId, face.Points[index].X, face.Points[next].X) + && !IsCutEdge(face.Ring[index], face.Ring[next]); + } + + bool IsCutEdge(double[] a, double[] b) + { + if (cutOrigin == null) return false; + double da = (a[0] - cutOrigin[0]) * viewDir[0] + (a[1] - cutOrigin[1]) * viewDir[1] + + (a[2] - cutOrigin[2]) * viewDir[2]; + double db = (b[0] - cutOrigin[0]) * viewDir[0] + (b[1] - cutOrigin[1]) * viewDir[1] + + (b[2] - cutOrigin[2]) * viewDir[2]; + return Math.Abs(da) <= 1.0 && Math.Abs(db) <= 1.0; + } + + bool IsProjectedRailSeam(List<(int Face, int Vertex)> members, (double X, double Y) start, + (double X, double Y) end) => + members.All(member => IsRailingCategory(edgeFaces[member.Face].CategoryId)) + && members.GroupBy(member => + { + var face = edgeFaces[member.Face]; + return EdgeKey(face.Points, face.Ring, true, member.Vertex); + }).All(group => + { + var faces = group.Select(member => edgeFaces[member.Face]).ToArray(); + var first = faces[0]; + if (faces.Any(face => (face.Nx, face.Ny, face.Nz, face.Off) != (first.Nx, first.Ny, first.Nz, first.Off))) + return false; + // A railing and its embedded components can repeat both faces of one joint. + var sides = faces.Select(face => ProjectedSide(start, end, face.Points)).ToArray(); + return sides.Contains(-1) && sides.Contains(1); + }); + + ((long Ax, long Ay, long Bx, long By) Edge, long Start, long End) EdgeKey( + List<(double X, double Y)> points, List ring, bool preserveDepth, int index) + { + int next = (index + 1) % points.Count; + var a = points[index]; + var b = points[next]; + var edge = ProjectedEdgeKey(a.X, a.Y, b.X, b.Y); + if (!preserveDepth || ring.Count != points.Count) return (edge, 0, 0); + + // A far component can share a projection with a nearer one that covers it. + long da = (long)Math.Round(Project(ring[index], viewDir, 1) * 10); + long db = (long)Math.Round(Project(ring[next], viewDir, 1) * 10); + return edge.Ax == (long)Math.Round(a.X * 10) && edge.Ay == (long)Math.Round(a.Y * 10) + ? (edge, da, db) : (edge, db, da); + } + } + + private static bool IsRailingCategory(int categoryId) => + categoryId is (int)BuiltInCategory.OST_StairsRailing or (int)BuiltInCategory.OST_RailingTopRail; + + private static bool IsVerticalDetailProfile(int categoryId, double x1, double x2) => + Math.Abs(x1 - x2) < 1e-6 + && (IsRailingCategory(categoryId) + || categoryId is (int)BuiltInCategory.OST_StairsRailingBaluster or (int)BuiltInCategory.OST_CurtainWallMullions); + + private static bool ClipsAtBaluster(CollectedEdge edge, int maskCategory) => + maskCategory != (int)BuiltInCategory.OST_StairsRailingBaluster || IsRailingCategory(edge.CategoryId); + + private static bool HasCoincidentComponents(int categoryId, bool elevation) => + IsRailingCategory(categoryId) + || categoryId is (int)BuiltInCategory.OST_CurtainWallPanels or (int)BuiltInCategory.OST_CurtainWallMullions + || elevation && categoryId is (int)BuiltInCategory.OST_Walls + or (int)BuiltInCategory.OST_Windows or (int)BuiltInCategory.OST_Doors; + + private static double? RailingClipDepth(CollectedEdge edge) => + !edge.IsCut && edge.ViewLineStyleId == 0 + && (IsRailingCategory(edge.CategoryId) + || edge.CategoryId is ((int)BuiltInCategory.OST_Windows or (int)BuiltInCategory.OST_Doors)) + ? edge.NearDepth - 1 : null; + + private sealed record PlanarOcclusion(double Dx, double Dy, double OriginDepth, + List>? Openings, bool Transparent, bool ExactStairProjectionDepth) + { + internal double DepthAt(double x, double y) => OriginDepth + Dx * x + Dy * y; } /// Edges with their midpoint hidden behind nearer mass removed: an edge whose midpoint lies inside @@ -603,10 +2272,14 @@ internal static List DedupeEdges( /// on the boundary of the nearer face counts as inside (half a millimetre): stacked wall layers and window /// frames project their edges onto the silhouette of the mass in front, and the reference draws that /// silhouette once. - internal static List OccludeEdges( + private static List OccludeEdges( List<(List<(double X, double Y)> Points, double Depth, bool Outline)> faces, - List faceMinDepths, - List edges) + List<(double MinDepth, int ElementId, int? HostId, int CategoryId, + PlanarOcclusion? Plane)> faceOccluders, + List edges, bool keepWindowJambs, IReadOnlySet? roofInsertFaces = null, + IReadOnlyDictionary>? stairMaskFaces = null, + IReadOnlyDictionary? railingMaskDepths = null, + List? behindRailings = null, bool useDetailPlaneDepth = false, Func? stairAssembly = null) { const int Cells = 128; double minX = double.MaxValue, minY = double.MaxValue, maxX = double.MinValue, maxY = double.MinValue; @@ -642,35 +2315,109 @@ internal static List OccludeEdges( int gx = Math.Clamp((int)((mx - minX) / cellW), 0, Cells - 1); int gy = Math.Clamp((int)((my - minY) / cellH), 0, Cells - 1); bool hidden = false; + bool hiddenByRail = false; + var source = edge.FaceA >= 0 ? faceOccluders[edge.FaceA] : default; + bool isInsert = edge.CategoryId is (int)BuiltInCategory.OST_Windows or (int)BuiltInCategory.OST_Doors; + bool roofInsert = roofInsertFaces?.Contains(edge.FaceA) == true; + bool stairBody = IsStairBodyCategory(edge.CategoryId); + bool stairProjection = !edge.IsCut && (stairBody || IsRailingCategory(edge.CategoryId) + || edge.CategoryId == (int)BuiltInCategory.OST_StairsRailingBaluster); + bool horizontalTread = stairBody && !edge.IsCut && Math.Abs(edge.Y1 - edge.Y2) < 1e-6; + int assembly = horizontalTread ? stairAssembly?.Invoke(source.ElementId) ?? source.ElementId : 0; + double? stairDepth = !edge.IsCut && edge.ViewLineStyleId == 0 && !stairBody + ? edge.NearDepth : null; + double? railingDepth = railingMaskDepths != null ? RailingClipDepth(edge) : null; var candidates = grid[gy * Cells + gx]; if (candidates != null) { foreach (int f in candidates) { if (f == edge.FaceA || f == edge.FaceB) continue; - // A window or door sits inside its host wall: the wall face in front of it (up to half a - // metre, the deepest realistic inset) must not hide it, or no window would ever ink — the - // hole is not decoded in the wall face. A genuinely separate mass further in front still - // hides it. - double clearance = 1.0; - if (edge.CategoryId == (int)BuiltInCategory.OST_Windows - || edge.CategoryId == (int)BuiltInCategory.OST_Doors) - clearance = 500.0; - if (faceMinDepths[f] >= edge.MidDepth - clearance) continue; - if (PointInPolygon(mx, my, faces[f].Points) - || DistToPolygon(mx, my, faces[f].Points) <= 0.5) { hidden = true; break; } + var (coverDepth, elementId, hostId, categoryId, plane) = faceOccluders[f]; + // The projected union already resolves overlaps within this mesh. + if (edge.SilhouetteOwnerId == elementId) continue; + if (stairDepth is double near && coverDepth < near - 1 && stairMaskFaces?.ContainsKey(f) == true) + continue; // This face clips the span after midpoint occlusion. + if (plane != null && (roofInsert && elementId == source.ElementId + || source.Plane != null && source.CategoryId == (int)BuiltInCategory.OST_ElectricalEquipment + && categoryId is ((int)BuiltInCategory.OST_ElectricalEquipment or (int)BuiltInCategory.OST_IOSModelGroups))) + { + if (plane.Transparent || plane.Openings?.Any(hole => PointInPolygon(mx, my, hole)) == true) continue; + coverDepth = plane.DepthAt(mx, my); + } + if (categoryId is (int)BuiltInCategory.OST_Walls or (int)BuiltInCategory.OST_Windows + or (int)BuiltInCategory.OST_Doors && plane?.Openings is { Count: > 0 } openings) + { + if (openings.Any(hole => PointInPolygon(mx, my, hole))) continue; + coverDepth = plane.DepthAt(mx, my); + } + if (plane != null && (stairProjection && plane.ExactStairProjectionDepth + && (categoryId == (int)BuiltInCategory.OST_Walls + || assembly > 0 && Math.Abs(plane.Dx) > 1e-6 && Math.Abs(plane.Dy) < 1e-6 + && (elementId == source.ElementId || stairAssembly?.Invoke(elementId) == assembly)) + || useDetailPlaneDepth + && (IsStairBodyCategory(categoryId) + || categoryId is ((int)BuiltInCategory.OST_Walls or (int)BuiltInCategory.OST_Floors)))) + coverDepth = plane.DepthAt(mx, my); + if (elementId == source.HostId) + { + // shortcut: exempt the host wall until its openings are projected. + if (categoryId == (int)BuiltInCategory.OST_Walls || plane?.Openings?.Any(hole => PointInPolygon(mx, my, hole)) == true) continue; + if (plane != null) coverDepth = plane.DepthAt(mx, my); + } + // shortcut: keep the insert's inset detail until the occlusion pass handles glazing materials. + double clearance = !roofInsert && isInsert && elementId == source.ElementId ? 500.0 : 1.0; + if (coverDepth >= edge.MidDepth - clearance) continue; + var polygon = faces[f].Points; + if (!PointInPolygon(mx, my, polygon) && DistToPolygon(mx, my, polygon) > 0.5) continue; + // Ganged windows touch at a projected jamb, so the adjacent pane cannot hide that edge. + if (keepWindowJambs && edge.CategoryId == (int)BuiltInCategory.OST_Windows + && Math.Abs(edge.X2 - edge.X1) <= 0.1 + && categoryId == edge.CategoryId && elementId != source.ElementId + && hostId.HasValue && hostId == source.HostId + && ProjectedSide((edge.X1, edge.Y1), (edge.X2, edge.Y2), polygon) + * ProjectedSide((edge.X1, edge.Y1), (edge.X2, edge.Y2), faces[edge.FaceA].Points) == -1) + continue; + if (railingDepth is double limit && railingMaskDepths!.TryGetValue(f, out var far) + && far < limit && ClipsAtBaluster(edge, categoryId)) + { + hiddenByRail = true; + continue; + } + hidden = true; + break; } } - if (!hidden) kept.Add(edge); + if (hidden) continue; + if (hiddenByRail) behindRailings!.Add(edge); + else kept.Add(edge); } kept.Sort((left, right) => right.Depth.CompareTo(left.Depth)); return kept; } + private static int ProjectedSide((double X, double Y) start, (double X, double Y) end, + List<(double X, double Y)> polygon) + { + double dx = end.X - start.X, dy = end.Y - start.Y; + double tolerance = 0.1 * Math.Sqrt(dx * dx + dy * dy); + int side = 0; + foreach (var (x, y) in polygon) + { + double cross = dx * (y - start.Y) - dy * (x - start.X); + int vertexSide = cross > tolerance ? 1 : cross < -tolerance ? -1 : 0; + if (vertexSide == 0) continue; + if (side != 0 && side != vertexSide) return 0; + side = vertexSide; + } + return side; + } + /// Merges overlapping collinear edges on one plane into their union: stacked wall layers and /// coincident faces ink the same stretch several times, while the reference draws it once. Only true /// overlaps merge (touching ends stay separate); the plane key keeps different depths apart. - internal static List MergeOverlaps(List edges) + internal static List MergeOverlaps(List edges, + Func? cutWidth = null) { var groups = new Dictionary<(long Ang, long Off, long Nx, long Ny, long Nz, long Pln), List>(); foreach (var edge in edges) @@ -699,6 +2446,28 @@ internal static List MergeOverlaps(List edges) double hi = horizontal ? Math.Max(edge.X1, edge.X2) : Math.Max(edge.Y1, edge.Y2); spans.Add((lo, hi, edge)); } + if (cutWidth != null && list.All(edge => edge.IsCut && edge.ViewLineStyleId == 0)) + { + var cuts = spans.Select(span => (span.Lo, span.Hi, span.Edge, Width: cutWidth(span.Edge))) + .OrderByDescending(span => span.Width).ToArray(); + if (cuts[0].Width > cuts[^1].Width) + { + // A wider pen covers only the part supplied by that cut, not the whole joined edge. + var ends = cuts.SelectMany(span => new[] { span.Lo, span.Hi }).Distinct().Order().ToArray(); + int owner = -1, start = 0; + for (int i = 0; i < ends.Length; i++) + { + int next = i + 1 == ends.Length ? -1 + : Array.FindIndex(cuts, span => span.Lo <= ends[i] && span.Hi >= ends[i + 1]); + if (next == owner) continue; + if (owner >= 0) + merged.Add(WithSpan(cuts[owner].Edge, ends[start], ends[i], horizontal)); + owner = next; + start = i; + } + continue; + } + } spans.Sort((a, b) => a.Lo.CompareTo(b.Lo)); double curLo = spans[0].Lo, curHi = spans[0].Hi, curDepth = spans[0].Edge.Depth; var cur = spans[0].Edge; @@ -716,72 +2485,618 @@ internal static List MergeOverlaps(List edges) curLo = spans[i].Lo; curHi = spans[i].Hi; curDepth = spans[i].Edge.Depth; } } - merged.Add(WithSpan(cur, curLo, curHi, horizontal) with { Depth = curDepth }); + merged.Add(WithSpan(cur, curLo, curHi, horizontal) with { Depth = curDepth }); + } + merged.Sort((left, right) => right.Depth.CompareTo(left.Depth)); + return merged; + } + + /// Collapses coincident modeling drawn several times into one inked line: edges parallel within + /// 50 mm, overlapping over most of their length, at the same depth and of the same length (a railing family + /// drawing one board four times, a window jamb doubled by its frame). Only full duplicates collapse: a short + /// edge on a long one stays (a head on a wall top), lines at different depths stay (a rail in front of its + /// wall), and staggered layers stay. The nearest edge survives, the way the reference inks the visible one. + internal static List ConsolidateCoincident(List edges, + bool keepFineSectionProfiles = false, double elevationRailPenWidth = 0) + { + const double ToleranceMillimetres = 50.0; + var survivors = new List(edges.Count); + List? fineProfiles = null; + foreach (var edge in edges.OrderBy(e => e.MidDepth)) + { + double dx = edge.X2 - edge.X1, dy = edge.Y2 - edge.Y1; + double len = Math.Sqrt(dx * dx + dy * dy); + if (!(len > 1e-9)) continue; + bool horizontal = Math.Abs(dy) <= Math.Abs(dx); + double lo = horizontal ? Math.Min(edge.X1, edge.X2) : Math.Min(edge.Y1, edge.Y2); + double hi = horizontal ? Math.Max(edge.X1, edge.X2) : Math.Max(edge.Y1, edge.Y2); + bool absorbed = false; + foreach (var kept in survivors) + { + double kdx = kept.X2 - kept.X1, kdy = kept.Y2 - kept.Y1; + double klen = Math.Sqrt(kdx * kdx + kdy * kdy); + if (!(klen > 1e-9)) continue; + bool kHorizontal = Math.Abs(kdy) <= Math.Abs(kdx); + if (kHorizontal != horizontal) continue; + // Parallel within the tolerance: the perpendicular distance of both ends. + double sep = horizontal + ? Math.Max(Math.Abs(edge.Y1 - kept.Y1), Math.Abs(edge.Y2 - kept.Y2)) + : Math.Max(Math.Abs(edge.X1 - kept.X1), Math.Abs(edge.X2 - kept.X2)); + if (sep > ToleranceMillimetres) continue; + // The two sides of a cut tread or riser can be only 50 mm apart. + if (sep > 0.1 && keepFineSectionProfiles + && (edge.IsCut && IsStairBodyCategory(edge.CategoryId) || kept.IsCut && IsStairBodyCategory(kept.CategoryId))) continue; + if (Math.Abs(edge.MidDepth - kept.MidDepth) > ToleranceMillimetres) continue; + double klo = horizontal ? Math.Min(kept.X1, kept.X2) : Math.Min(kept.Y1, kept.Y2); + double khi = horizontal ? Math.Max(kept.X1, kept.X2) : Math.Max(kept.Y1, kept.Y2); + double overlap = Math.Min(hi, khi) - Math.Max(lo, klo); + double shorter = Math.Min(len, klen); + if (overlap < 0.8 * shorter) continue; + if (Math.Min(len, klen) < 0.8 * Math.Max(len, klen)) continue; + // At elevation scale, sub-pen-width boundaries of a rail read as one stroke. + bool separateElevationRail = elevationRailPenWidth > 0 && sep > elevationRailPenWidth + && (Math.Abs(dx) < 1e-6 && Math.Abs(kdx) < 1e-6 + || Math.Abs(dy) < 1e-6 && Math.Abs(kdy) < 1e-6); + if (sep > 0.1 && !edge.IsCut && !kept.IsCut + && (keepFineSectionProfiles && edge.CategoryId == (int)BuiltInCategory.OST_Doors + || IsRailingCategory(edge.CategoryId) && (keepFineSectionProfiles || separateElevationRail)) + && kept.CategoryId == edge.CategoryId + && edge.FaceA >= 0 && kept.FaceA >= 0 + && (edge.FaceA == kept.FaceA || edge.FaceA == kept.FaceB + || edge.FaceB >= 0 && (edge.FaceB == kept.FaceA || edge.FaceB == kept.FaceB))) + (fineProfiles ??= []).Add(edge); + absorbed = true; + break; + } + if (!absorbed) survivors.Add(edge); + } + survivors.Sort((left, right) => right.Depth.CompareTo(left.Depth)); + if (fineProfiles != null) + { + // Recover both edges of the same profile face without changing the model edge selection. + var inked = survivors.Select(edge => ProjectedEdgeKey(edge.X1, edge.Y1, edge.X2, edge.Y2)).ToHashSet(); + foreach (var edge in fineProfiles) + if (inked.Add(ProjectedEdgeKey(edge.X1, edge.Y1, edge.X2, edge.Y2))) + survivors.Add(edge); + } + return survivors; + } + + private static bool IsStairBodyCategory(int category) => category is + (int)BuiltInCategory.OST_Stairs or (int)BuiltInCategory.OST_StairsRuns or (int)BuiltInCategory.OST_StairsTrisers; + + private static void AddRoofLayers(List output, + IEnumerable<(double X1, double Y1, double X2, double Y2, double Nx, double Ny, double Nz, + int TypeId, int CategoryId, double Depth)> chords, + List> rings, Internal.RawCompoundStructureLayer[] layers, + double[] right, double[] up, double[] direction, (double X0, double Y0, double X1, double Y1) crop, + RvtDocument document, List? hatches, double[]? viewOrigin) + { + var sides = chords.ToArray(); + var tops = sides.Where(side => side.Nz > 0.01).Take(3).ToArray(); + if (tops.Length is 0 or > 2) return; + // A common high end and eaves on opposite sides identify a single ridge. + if (tops is [var first, var second]) + { + if (rings.Count != 1) return; + double ridgeY = Math.Max(first.Y1, first.Y2); + double ridgeX = first.Y1 > first.Y2 ? first.X1 : first.X2; + double secondRidgeY = Math.Max(second.Y1, second.Y2); + double secondRidgeX = second.Y1 > second.Y2 ? second.X1 : second.X2; + if (Math.Abs(ridgeX - secondRidgeX) > 0.1 || Math.Abs(ridgeY - secondRidgeY) > 0.1 + || Math.Min(first.Y1, first.Y2) >= ridgeY - 0.1 + || Math.Min(second.Y1, second.Y2) >= ridgeY - 0.1 + || (first.X1 + first.X2 - 2 * ridgeX) * (second.X1 + second.X2 - 2 * ridgeX) >= 0) + return; + } + + var widths = layers.Select(layer => BitConverter.Int64BitsToDouble(layer.LayerWidthBits) + * FeetToMillimetres).ToArray(); + if (widths.Any(width => !(width is >= 0 and < 10000))) return; + double thickness = widths.Sum(); + var planes = new List<(double[] Normal, double Distance)>(); + foreach (var top in tops) + { + if (Math.Abs(top.Nx * direction[0] + top.Ny * direction[1] + top.Nz * direction[2]) >= 1e-6 + || sides.Where(bottom => top.Nx * bottom.Nx + top.Ny * bottom.Ny + top.Nz * bottom.Nz < -1 + 1e-6) + .Take(2).ToArray() is not [var bottom]) + return; + var normal = new[] { top.Nx * right[0] + top.Ny * right[1] + top.Nz * right[2], + top.Nx * up[0] + top.Ny * up[1] + top.Nz * up[2], 0d }; + double measured = (top.X1 - bottom.X1) * normal[0] + (top.Y1 - bottom.Y1) * normal[1]; + if (Math.Abs(thickness - measured) >= 0.1) return; + planes.Add((normal, top.X1 * normal[0] + top.Y1 * normal[1])); + } + + foreach (var ring in rings) + { + var profile = ring.Select(point => new[] { point.X, point.Y, 0d }).ToList(); + double offset = 0; + for (int layer = 0; layer < widths.Length; layer++) + { + double start = offset, width = widths[layer]; + offset += width; + if (width <= 0) continue; + + bool drawBoundary = layer < widths.Length - 1 && offset >= 0.01 && thickness - offset >= 0.01; + var grids = hatches != null && viewOrigin is { Length: 3 } + ? DetailAnnotations.CutGrids(document, layers[layer].RawMaterialId) : null; + if (!drawBoundary && grids == null) continue; + + for (int i = 0; i < planes.Count; i++) + { + var (normal, distance) = planes[i]; + if (grids != null) + { + var band = RoofMaterialBand(ring, planes[i], planes.Count == 2 ? planes[1 - i] : null, + start, offset); + if (band.Count >= 3 && Math.Abs(PlanPrinter.SignedArea(band)) > 1e-6) + hatches!.Add(new(band, grids, Project(viewOrigin!, right), Project(viewOrigin!, up))); + } + if (!drawBoundary) continue; + var origin = new[] { normal[0] * (distance - offset), normal[1] * (distance - offset), 0d }; + foreach (var (a, b) in CutChords(profile, origin, normal)) + { + double x1 = a[0], y1 = a[1], x2 = b[0], y2 = b[1]; + if (planes.Count == 2) + { + var adjacent = planes[1 - i]; + double da = a[0] * adjacent.Normal[0] + a[1] * adjacent.Normal[1] - adjacent.Distance + offset; + double db = b[0] * adjacent.Normal[0] + b[1] * adjacent.Normal[1] - adjacent.Distance + offset; + if (da > 0 && db > 0) continue; + if (da > 0 || db > 0) + { + double t = da / (da - db); + double x = a[0] + (b[0] - a[0]) * t, y = a[1] + (b[1] - a[1]) * t; + if (da > 0) (x1, y1) = (x, y); + else (x2, y2) = (x, y); + } + } + if (ClipSegment(x1, y1, x2, y2, crop.X0, crop.Y0, crop.X1, crop.Y1, + out double ax, out double ay, out double bx, out double by)) + output.Add(new((ax, ay), (bx, by), (int)BuiltInCategory.OST_Roofs)); + } + } + } + } + } + + private static List<(double X, double Y)> RoofMaterialBand(List<(double X, double Y)> ring, + (double[] Normal, double Distance) plane, (double[] Normal, double Distance)? adjacent, double outer, double inner) + { + double Depth((double X, double Y) point) => plane.Distance - point.X * plane.Normal[0] - point.Y * plane.Normal[1]; + var band = ClipHalfPlane(ring, point => Depth(point) >= outer, point => Depth(point) - outer); + band = ClipHalfPlane(band, point => Depth(point) <= inner, point => inner - Depth(point)); + if (adjacent is { } other) + { + // The closest exterior plane owns each side of the ridge. + double RidgeDistance((double X, double Y) point) => + other.Distance - point.X * other.Normal[0] - point.Y * other.Normal[1] - Depth(point); + band = ClipHalfPlane(band, point => RidgeDistance(point) >= 0, RidgeDistance); + } + return band; + } + + internal static List ResolveRoofWallCutJoins(List edges, + IReadOnlyList> roofs, IReadOnlyList> walls, + double depth, (long Nx, long Ny, long Nz, long Off) plane) + { + const double tolerance = 1e-5; + const int roofCategory = (int)BuiltInCategory.OST_Roofs; + const int wallCategory = (int)BuiltInCategory.OST_Walls; + var wallBoundaries = Boundaries(walls).ToList(); + var seams = new List(); + foreach (var roof in Boundaries(roofs)) + { + double dx = roof.X2 - roof.X1, dy = roof.Y2 - roof.Y1; + bool horizontal = Math.Abs(dx) >= Math.Abs(dy); + foreach (var wall in wallBoundaries) + { + // Counterclockwise rings put their interiors to the left. + if (dx * (wall.X2 - wall.X1) + dy * (wall.Y2 - wall.Y1) >= 0) continue; + if (CollinearOverlap(roof, wall, horizontal, tolerance) is { } overlap) + seams.Add(WithSpan(roof, overlap.Lo, overlap.Hi, horizontal)); + } + } + if (seams.Count == 0) return edges; + + var uniqueSeams = MergeOverlaps(seams) + .DistinctBy(edge => ProjectedEdgeKey(edge.X1, edge.Y1, edge.X2, edge.Y2)).ToList(); + var result = new List(edges.Count + uniqueSeams.Count); + foreach (var edge in edges) + { + if (edge.IsCut && edge.ViewLineStyleId == 0 && edge.CategoryId is roofCategory or wallCategory) + result.AddRange(UncoveredCollinearSpans(edge, uniqueSeams, tolerance)); + else + result.Add(edge); + } + result.AddRange(uniqueSeams); + return result; + + IEnumerable Boundaries(IReadOnlyList> rings) + { + foreach (var ring in rings) + { + bool counterclockwise = PlanPrinter.SignedArea(ring) > 0; + for (int i = 0; i < ring.Count; i++) + { + var a = ring[i]; + var b = ring[(i + 1) % ring.Count]; + if (!counterclockwise) (a, b) = (b, a); + yield return new(a.X, a.Y, b.X, b.Y, depth, depth, -1, -1, + plane.Nx, plane.Ny, plane.Nz, plane.Off, CategoryId: roofCategory); + } + } + } + } + + internal static IEnumerable TrimProjectedEdgesAtCuts(IReadOnlyList edges) + { + const double tolerance = 0.1; + var cuts = edges.Where(edge => edge.IsCut).ToList(); + foreach (var edge in edges) + { + if (edge.IsCut || edge.ViewLineStyleId > 0 || cuts.Count == 0) + yield return edge; + else + foreach (var span in UncoveredCollinearSpans(edge, cuts, tolerance)) + yield return span; + } + } + + private static (double Lo, double Hi)? CollinearOverlap( + CollectedEdge edge, CollectedEdge cover, bool horizontal, double tolerance) + { + double dx = edge.X2 - edge.X1, dy = edge.Y2 - edge.Y1; + double length = Math.Sqrt(dx * dx + dy * dy); + if (length <= tolerance) return null; + + double Distance(double x, double y) => Math.Abs((x - edge.X1) * dy - (y - edge.Y1) * dx) / length; + if (Distance(cover.X1, cover.Y1) > tolerance || Distance(cover.X2, cover.Y2) > tolerance) return null; + + double a = horizontal ? edge.X1 : edge.Y1, b = horizontal ? edge.X2 : edge.Y2; + double c = horizontal ? cover.X1 : cover.Y1, d = horizontal ? cover.X2 : cover.Y2; + double lo = Math.Max(Math.Min(a, b), Math.Min(c, d)); + double hi = Math.Min(Math.Max(a, b), Math.Max(c, d)); + return hi > lo ? (lo, hi) : null; + } + + private static IEnumerable UncoveredCollinearSpans( + CollectedEdge edge, IReadOnlyList covers, double tolerance) + { + bool horizontal = Math.Abs(edge.X2 - edge.X1) >= Math.Abs(edge.Y2 - edge.Y1); + double a = horizontal ? edge.X1 : edge.Y1, b = horizontal ? edge.X2 : edge.Y2; + double start = Math.Min(a, b), end = Math.Max(a, b); + var covered = covers.Where(cover => cover.MidDepth <= edge.MidDepth + tolerance) + .Select(cover => CollinearOverlap(edge, cover, horizontal, tolerance)) + .OfType<(double Lo, double Hi)>().OrderBy(span => span.Lo); + double cursor = start; + foreach (var span in covered) + { + if (span.Lo > cursor + tolerance) yield return WithSpan(edge, cursor, span.Lo, horizontal); + cursor = Math.Max(cursor, span.Hi); + if (cursor >= end) break; + } + if (cursor == start) yield return edge; + else if (end > cursor + tolerance) yield return WithSpan(edge, cursor, end, horizontal); + } + + private static CollectedEdge WithSpan(CollectedEdge edge, double lo, double hi, bool horizontal) + { + double dx = edge.X2 - edge.X1, dy = edge.Y2 - edge.Y1; + double denom = horizontal ? dx : dy; + if (Math.Abs(denom) < 1e-12) return edge; + double baseLo = horizontal ? edge.X1 : edge.Y1; + double t0 = (lo - baseLo) / denom, t1 = (hi - baseLo) / denom; + return edge with + { + X1 = edge.X1 + t0 * dx, + Y1 = edge.Y1 + t0 * dy, + X2 = edge.X1 + t1 * dx, + Y2 = edge.Y1 + t1 * dy, + }; + } + + internal static IEnumerable VisibleTerrainEdges(IEnumerable terrainEdges, + IEnumerable> polygons, List<(double From, double To)> pads, + double minimumLengthSquared = 0.01, bool coverBoundary = true, bool coverOppositeEdges = false, + IReadOnlyDictionary, List>>? openings = null) + { + // Ground is background. Keep only its parts outside the opaque model polygons so covered lines + // do not remain as invisible strokes in the PDF. + var masks = polygons.Select(points => (Points: points, X0: points.Min(p => p.X), Y0: points.Min(p => p.Y), + X1: points.Max(p => p.X), Y1: points.Max(p => p.Y))).ToList(); + foreach (var edge in terrainEdges) + { + double dx = edge.X2 - edge.X1, dy = edge.Y2 - edge.Y1; + double lengthSquared = dx * dx + dy * dy; + if (lengthSquared < minimumLengthSquared) continue; + double crossTolerance = coverOppositeEdges ? 1e-5 * Math.Sqrt(lengthSquared) : 0; + double left = Math.Min(edge.X1, edge.X2), right = Math.Max(edge.X1, edge.X2); + double bottom = Math.Min(edge.Y1, edge.Y2), top = Math.Max(edge.Y1, edge.Y2); + var covered = new List<(double From, double To)>(); + // A building pad replaces the terrain within its footprint, at every height in the section. + foreach (var (from, to) in pads) + { + if (right <= from || left >= to) continue; + if (Math.Abs(dx) < 1e-9) + { + covered.Add((0, 1)); + break; + } + double t0 = (from - edge.X1) / dx, t1 = (to - edge.X1) / dx; + covered.Add((Math.Max(0, Math.Min(t0, t1)), Math.Min(1, Math.Max(t0, t1)))); + } + foreach (var (polygon, x0, y0, x1, y1) in masks) + { + if (x1 < left || x0 > right || y1 < bottom || y0 > top) continue; + var crossings = new List { 0, 1 }; + var holes = openings?.GetValueOrDefault(polygon); + AddCrossings(polygon); + if (holes != null) + foreach (var hole in holes) AddCrossings(hole); + crossings.Sort(); + for (int i = 1; i < crossings.Count; i++) + { + double from = crossings[i - 1], to = crossings[i]; + if (to - from < 1e-9) continue; + double mid = (from + to) / 2; + double x = edge.X1 + dx * mid, y = edge.Y1 + dy * mid; + if (PointInPolygon(x, y, polygon) && (coverBoundary || DistToPolygon(x, y, polygon) > 1e-5) + && holes?.Any(hole => PointInPolygon(x, y, hole)) != true) + covered.Add((from, to)); + } + + void AddCrossings(List<(double X, double Y)> ring) + { + for (int i = 0; i < ring.Count; i++) + { + var a = ring[i]; + var b = ring[(i + 1) % ring.Count]; + double ex = b.X - a.X, ey = b.Y - a.Y; + double ax = a.X - edge.X1, ay = a.Y - edge.Y1; + if (coverOppositeEdges && dx * ex + dy * ey < 0) + { + double bx = b.X - edge.X1, by = b.Y - edge.Y1; + if (Math.Abs(ax * dy - ay * dx) <= crossTolerance && Math.Abs(bx * dy - by * dx) <= crossTolerance) + { + // Opposite boundary directions put material on both sides of their common span. + double from = Math.Max(0, (bx * dx + by * dy) / lengthSquared); + double to = Math.Min(1, (ax * dx + ay * dy) / lengthSquared); + if (to > from) covered.Add((from, to)); + continue; + } + } + double denominator = dx * ey - dy * ex; + if (Math.Abs(denominator) < 1e-9) continue; + double t = (ax * ey - ay * ex) / denominator; + double u = (ax * dy - ay * dx) / denominator; + if (t > 0 && t < 1 && u >= 0 && u <= 1) crossings.Add(t); + } + } + } + double cursor = 0; + foreach (var (from, to) in covered.OrderBy(interval => interval.From)) + { + if (from > cursor + 1e-9) yield return Slice(cursor, from); + cursor = Math.Max(cursor, to); + } + if (cursor < 1 - 1e-9) yield return Slice(cursor, 1); + + CollectedEdge Slice(double from, double to) => edge with + { + X1 = edge.X1 + dx * from, Y1 = edge.Y1 + dy * from, + X2 = edge.X1 + dx * to, Y2 = edge.Y1 + dy * to, + }; + } + } + + private static IEnumerable> GroundSpans(TerrainHatch terrain, double baseY) + { + foreach (var edge in terrain.Profile) + { + if (Math.Abs(edge.X1 - edge.X2) < 1e-9 || baseY >= Math.Max(edge.Y1, edge.Y2)) continue; + double x1 = edge.X1, y1 = edge.Y1, x2 = edge.X2, y2 = edge.Y2; + if (y1 < baseY) + { + x1 += (x2 - x1) * (baseY - y1) / (y2 - y1); + y1 = baseY; + } + else if (y2 < baseY) + { + x2 += (x1 - x2) * (baseY - y2) / (y1 - y2); + y2 = baseY; + } + yield return [(x1, y1), (x2, y2), (x2, baseY), (x1, baseY)]; + } + } + + private static List>? ClosedSectionWithOpenings(IReadOnlyList faces, + double[] origin, double[] direction, double[] horizontal, double[] vertical) + { + if (faces.Any(face => face.CurvedSurface || face.OuterVertices is not { Count: >= 3 } + || (face.InnerLoops?.Count ?? 0) > (face.InnerVertices?.Count ?? 0))) return null; + + var rings = ClosedSectionRings(faces, origin, direction, horizontal, vertical, + requireClosed: true, includeFaceOpenings: true).ToList(); + // shortcut: nested profiles need a cut mask with holes. + return rings.Count > 0 && !HasNestedSectionRings(rings) ? rings : null; + } + + private static bool HasNestedSectionRings(List> rings) => + rings.Any(ring => rings.Any(other => other != ring && PointInPolygon(ring[0].X, ring[0].Y, other))); + + private static HashSet? OutwardConvexStairFaces(GeometryData geometry) + { + if (geometry.BrepSolids == null) return null; + var outward = new HashSet(); + foreach (var solid in geometry.BrepSolids) + { + if (!solid.IsClosed || solid.FaceIndices.Count < 4 + || solid.FaceIndices.Any(index => (uint)index >= (uint)geometry.Faces.Count)) + continue; + var faces = solid.FaceIndices.Select(index => geometry.Faces[index]).ToArray(); + if (faces.Any(face => !face.PlaneSurface || face.OuterVertices is not { Count: >= 3 })) + continue; + + var vertices = faces.SelectMany(face => face.OuterVertices!).ToArray(); + // The original face normals point outward only when the shell lies behind every supporting plane. + if (faces.All(face => + { + double depth = Project(face.OuterVertices![0], face.Normal); + return vertices.All(point => Project(point, face.Normal) <= depth + 1e-6); + })) + outward.UnionWith(faces); + } + return outward.Count > 0 ? outward : null; + } + + internal static IEnumerable> ClosedSectionRings(IReadOnlyList faces, + double[] origin, double[] direction, double[] horizontal, double[] vertical, bool requireClosed = false, + bool includeFaceOpenings = false) + { + if (!includeFaceOpenings && faces.Any(face => face.InnerVertices is { Count: > 0 } || face.InnerLoops is { Count: > 0 })) + yield break; + var points = new Dictionary<(long, long), (double X, double Y)>(); + var neighbors = new Dictionary<(long, long), HashSet<(long, long)>>(); + foreach (var face in faces) + { + if (face.CurvedSurface || face.OuterVertices is not { Count: >= 3 } corners) continue; + var ring = corners.Select(p => new[] { p[0] * FeetToMillimetres, p[1] * FeetToMillimetres, + p[2] * FeetToMillimetres }).ToList(); + var chords = CutChords(ring, origin, direction); + if (includeFaceOpenings && face.InnerVertices is { Count: > 0 } holes) + { + var openings = holes.SelectMany(hole => CutChords(hole.Select(p => new[] + { p[0] * FeetToMillimetres, p[1] * FeetToMillimetres, p[2] * FeetToMillimetres }).ToList(), + origin, direction)).ToList(); + if (openings.Count > 0) + { + var trimmed = SubtractFaceOpeningChords(chords, openings); + if (trimmed == null) yield break; + chords = trimmed; + } + } + foreach (var (from, to) in chords) + { + var a = (X: Project(from, horizontal, 1), Y: Project(from, vertical, 1)); + var b = (X: Project(to, horizontal, 1), Y: Project(to, vertical, 1)); + var ka = ((long)Math.Round(a.X * 10), (long)Math.Round(a.Y * 10)); + var kb = ((long)Math.Round(b.X * 10), (long)Math.Round(b.Y * 10)); + if (ka == kb) continue; + if (points.TryAdd(ka, a)) neighbors.Add(ka, []); + if (points.TryAdd(kb, b)) neighbors.Add(kb, []); + neighbors[ka].Add(kb); + neighbors[kb].Add(ka); + } + } + if (requireClosed && neighbors.Values.Any(end => end.Count != 2)) yield break; + var visited = new HashSet<(long, long)>(); + foreach (var start in points.Keys) + { + if (!visited.Add(start) || neighbors[start].Count != 2) continue; + var ring = new List<(double X, double Y)> { points[start] }; + var current = neighbors[start].First(); + var previous = start; + while (neighbors[current].Count == 2 && visited.Add(current)) + { + ring.Add(points[current]); + var next = neighbors[current].First(neighbor => neighbor != previous); + previous = current; + current = next; + } + if (current == start && ring.Count >= 3 && Math.Abs(PlanPrinter.SignedArea(ring)) > 1e-6) + yield return ring; } - merged.Sort((left, right) => right.Depth.CompareTo(left.Depth)); - return merged; } - /// Collapses coincident modeling drawn several times into one inked line: edges parallel within - /// 50 mm, overlapping over most of their length, at the same depth and of the same length (a railing family - /// drawing one board four times, a window jamb doubled by its frame). Only full duplicates collapse: a short - /// edge on a long one stays (a head on a wall top), lines at different depths stay (a rail in front of its - /// wall), and staggered layers stay. The nearest edge survives, the way the reference inks the visible one. - internal static List ConsolidateCoincident(List edges) + private static List<(double[] A, double[] B)>? SubtractFaceOpeningChords( + List<(double[] A, double[] B)> outer, List<(double[] A, double[] B)> openings) { - const double ToleranceMillimetres = 50.0; - var survivors = new List(edges.Count); - foreach (var edge in edges.OrderBy(e => e.MidDepth)) + if (outer.Count == 0) return null; + // Every crossing of a planar face lies on one line. Sort its endpoints along the dominant axis. + var (start, end) = outer[0]; + int axis = Enumerable.Range(0, 3).MaxBy(i => Math.Abs(end[i] - start[i])); + var holes = openings.Select(chord => Ascending(chord.A, chord.B)).OrderBy(hole => hole.Low[axis]).ToList(); + var result = new List<(double[] A, double[] B)>(); + int matched = 0; + foreach (var (a, b) in outer) { - double dx = edge.X2 - edge.X1, dy = edge.Y2 - edge.Y1; - double len = Math.Sqrt(dx * dx + dy * dy); - if (!(len > 1e-9)) continue; - bool horizontal = Math.Abs(dy) <= Math.Abs(dx); - double lo = horizontal ? Math.Min(edge.X1, edge.X2) : Math.Min(edge.Y1, edge.Y2); - double hi = horizontal ? Math.Max(edge.X1, edge.X2) : Math.Max(edge.Y1, edge.Y2); - bool absorbed = false; - foreach (var kept in survivors) + var (low, high) = Ascending(a, b); + var cursor = low; + foreach (var (first, last) in holes) { - double kdx = kept.X2 - kept.X1, kdy = kept.Y2 - kept.Y1; - double klen = Math.Sqrt(kdx * kdx + kdy * kdy); - if (!(klen > 1e-9)) continue; - bool kHorizontal = Math.Abs(kdy) <= Math.Abs(kdx); - if (kHorizontal != horizontal) continue; - // Parallel within the tolerance: the perpendicular distance of both ends. - double sep = horizontal - ? Math.Max(Math.Abs(edge.Y1 - kept.Y1), Math.Abs(edge.Y2 - kept.Y2)) - : Math.Max(Math.Abs(edge.X1 - kept.X1), Math.Abs(edge.X2 - kept.X2)); - if (sep > ToleranceMillimetres) continue; - if (Math.Abs(edge.MidDepth - kept.MidDepth) > ToleranceMillimetres) continue; - double klo = horizontal ? Math.Min(kept.X1, kept.X2) : Math.Min(kept.Y1, kept.Y2); - double khi = horizontal ? Math.Max(kept.X1, kept.X2) : Math.Max(kept.Y1, kept.Y2); - double overlap = Math.Min(hi, khi) - Math.Max(lo, klo); - double shorter = Math.Min(len, klen); - if (overlap < 0.8 * shorter) continue; - if (Math.Min(len, klen) < 0.8 * Math.Max(len, klen)) continue; - absorbed = true; - break; + if (first[axis] < low[axis] || last[axis] > high[axis]) continue; + if (first[axis] < cursor[axis]) return null; + if (first[axis] > cursor[axis]) result.Add((cursor, first)); + cursor = last; + matched++; } - if (!absorbed) survivors.Add(edge); + if (cursor[axis] < high[axis]) result.Add((cursor, high)); } - survivors.Sort((left, right) => right.Depth.CompareTo(left.Depth)); - return survivors; + return matched == holes.Count ? result : null; + + (double[] Low, double[] High) Ascending(double[] a, double[] b) => a[axis] <= b[axis] ? (a, b) : (b, a); } - private static CollectedEdge WithSpan(CollectedEdge edge, double lo, double hi, bool horizontal) + internal static IEnumerable OutlineJoinedRings(List> rings, int category, + bool coverOppositeEdges = false, bool retainSource = false) { - double dx = edge.X2 - edge.X1, dy = edge.Y2 - edge.Y1; - double denom = horizontal ? dx : dy; - if (Math.Abs(denom) < 1e-12) return edge; - double baseLo = horizontal ? edge.X1 : edge.Y1; - double t0 = (lo - baseLo) / denom, t1 = (hi - baseLo) / denom; - return edge with + var edges = new Dictionary<(long Ax, long Ay, long Bx, long By), (CollectedEdge Edge, int Sides)>(); + for (int ringIndex = 0; ringIndex < rings.Count; ringIndex++) { - X1 = edge.X1 + t0 * dx, - Y1 = edge.Y1 + t0 * dy, - X2 = edge.X1 + t1 * dx, - Y2 = edge.Y1 + t1 * dy, - }; + var ring = rings[ringIndex]; + for (int i = 0; i < ring.Count; i++) + { + var a = ring[i]; + var b = ring[(i + 1) % ring.Count]; + var key = ProjectedEdgeKey(a.X, a.Y, b.X, b.Y); + if (key.Ax == key.Bx && key.Ay == key.By) continue; + // Counterclockwise rings put their interiors on the left of each directed edge. + int side = (long)Math.Round(a.X * 10) == key.Ax && (long)Math.Round(a.Y * 10) == key.Ay ? 1 : 2; + if (edges.TryGetValue(key, out var existing)) + edges[key] = (existing.Edge, existing.Sides | side); + else + edges.Add(key, (new(a.X, a.Y, b.X, b.Y, 0, 0, -1, -1, 0, 0, 0, 0, false, category) + { SourceRingEdge = retainSource ? (ringIndex, i) : null }, side)); + } + } + return VisibleTerrainEdges(edges.Values.Where(e => e.Sides != 3).Select(e => e.Edge), rings, [], + coverBoundary: false, coverOppositeEdges: coverOppositeEdges); + } + + private static double Project(double[] point, double[] basis, double units = FeetToMillimetres) => + (point[0] * basis[0] + point[1] * basis[1] + point[2] * basis[2]) * units; + + private static IEnumerable SiteWireEdges( + List<(List Points, double Facing)> faces, double[] horizontal, double[] vertical, + double[] direction, double planeDepth, bool cutMesh) + { + var edges = new HashSet<(long Ax, long Ay, long Bx, long By)>(); + foreach (var (points, facing) in faces) + { + if (!cutMesh && facing >= 0) continue; + for (int i = 0; i < points.Count; i++) + { + var a = points[i]; + var b = points[(i + 1) % points.Count]; + double da = Project(a, direction, 1) - planeDepth, db = Project(b, direction, 1) - planeDepth; + if (da < 0 && db < 0) continue; + double ax = Project(a, horizontal, 1), ay = Project(a, vertical, 1); + double bx = Project(b, horizontal, 1), by = Project(b, vertical, 1); + if (da < 0 || db < 0) + { + double t = da / (da - db); + double x = ax + t * (bx - ax), y = ay + t * (by - ay); + if (da < 0) { ax = x; ay = y; } + else { bx = x; by = y; } + } + var key = ProjectedEdgeKey(ax, ay, bx, by); + if (key.Ax == key.Bx && key.Ay == key.By || !edges.Add(key)) continue; + yield return new CollectedEdge(ax, ay, bx, by, 0, 0, -1, -1, 0, 0, 0, 0, false, + (int)BuiltInCategory.OST_Entourage); + } + } } private static bool PointInPolygon(double x, double y, List<(double X, double Y)> polygon) @@ -798,9 +3113,13 @@ private static bool PointInPolygon(double x, double y, List<(double X, double Y) } /// The distance from a point to the boundary of a polygon, in the polygon's units. - private static double DistToPolygon(double x, double y, List<(double X, double Y)> polygon) + private static double DistToPolygon(double x, double y, List<(double X, double Y)> polygon) => + Math.Sqrt(ClosestPolygonPoint(x, y, polygon).DistanceSquared); + + private static (double X, double Y, double DistanceSquared) ClosestPolygonPoint( + double x, double y, List<(double X, double Y)> polygon) { - double best = double.PositiveInfinity; + var best = (X: x, Y: y, DistanceSquared: double.PositiveInfinity); for (int i = 0, j = polygon.Count - 1; i < polygon.Count; j = i++) { var (ax, ay) = polygon[j]; @@ -810,8 +3129,8 @@ private static double DistToPolygon(double x, double y, List<(double X, double Y double t = lengthSquared > 1e-18 ? ((x - ax) * dx + (y - ay) * dy) / lengthSquared : 0; t = Math.Clamp(t, 0, 1); double px = ax + t * dx, py = ay + t * dy; - double dist = Math.Sqrt((x - px) * (x - px) + (y - py) * (y - py)); - if (dist < best) best = dist; + double distSquared = (x - px) * (x - px) + (y - py) * (y - py); + if (distSquared < best.DistanceSquared) best = (px, py, distSquared); } return best; } @@ -865,7 +3184,8 @@ internal static void AddElevationPage(PdfDocument pdf, RvtDocument document, Ele double m = options.MarginMillimetres; page.DrawRectangle(m, m, paper.WidthMillimetres - 2 * m, paper.HeightMillimetres - 2 * m, 0.25); } - DrawContent(page, content, scale, offsetX, offsetY, view.Direction == "section" ? 0.82 : 1, document); + DrawContent(page, content, scale, offsetX, offsetY, view.Direction == "section" ? 0.82 : 1, document, + unshadedHiddenLine: document.RawData.UnshadedHiddenLineViews?.Contains(view.ViewId) == true); if (pdf.Font != null) { page.DrawText(view.Name, options.MarginMillimetres + 2, paper.HeightMillimetres - options.MarginMillimetres - 6, 4); @@ -890,7 +3210,7 @@ internal static void AddElevationPage(PdfDocument pdf, RvtDocument document, Ele return result; } - private static List<(double X, double Y)> ClipHalfPlane(List<(double X, double Y)> polygon, + internal static List<(double X, double Y)> ClipHalfPlane(List<(double X, double Y)> polygon, Func<(double X, double Y), bool> inside, Func<(double X, double Y), double> distance) { var result = new List<(double X, double Y)>(polygon.Count + 2); @@ -920,7 +3240,7 @@ internal static void AddLayerLines( RvtDocument document, List output, double[] viewDir, double[] horiz, double[] vert, - long pnx, long pny, long pnz, long poff) + long pnx, long pny, long pnz, long poff, IReadOnlySet? sectionedLayerChords = null) { var stacks = new Dictionary(); foreach (var chord in raw) @@ -953,6 +3273,8 @@ internal static void AddLayerLines( { for (int b = a + 1; b < cand.Count; b++) { + if (sectionedLayerChords?.Contains(cand[a]) == true + || sectionedLayerChords?.Contains(cand[b]) == true) continue; var first = raw[cand[a]]; var second = raw[cand[b]]; if (first.TypeId != second.TypeId) continue; @@ -1034,45 +3356,41 @@ internal static void AddLayerLines( } } - /// The part of a 3D ring whose projection lies inside a rectangle (the crop of a detail), with the - /// crossing points interpolated in 3D so the ring keeps a vertex per projected point: the cut test reads the - /// ring, and a projected-only clip lost that correspondence. - internal static List ClipToWindow3(List ring, double[] horizontal, double[] vertical, - double left, double right, double bottom, double top) + /// Clips a face for painting and occlusion, retaining which edges came from its perimeter. + private static (List Ring, bool[] IncomingEdges) ClipToWindow3(List ring, + double[] horizontal, double[] vertical, double left, double right, double bottom, double top) { - double U(double[] p) => p[0] * horizontal[0] + p[1] * horizontal[1] + p[2] * horizontal[2]; - double V(double[] p) => p[0] * vertical[0] + p[1] * vertical[1] + p[2] * vertical[2]; - var result = ClipHalfPlane3(ring, U, u => u - left); - result = ClipHalfPlane3(result, U, u => right - u); - result = ClipHalfPlane3(result, V, v => v - bottom); - return ClipHalfPlane3(result, V, v => top - v); + var vertices = ring.Select(point => (Point: point, IncomingEdge: true)).ToList(); + vertices = ClipHalfPlane3(vertices, point => Project(point, horizontal, 1) - left); + vertices = ClipHalfPlane3(vertices, point => right - Project(point, horizontal, 1)); + vertices = ClipHalfPlane3(vertices, point => Project(point, vertical, 1) - bottom); + vertices = ClipHalfPlane3(vertices, point => top - Project(point, vertical, 1)); + return (vertices.Select(vertex => vertex.Point).ToList(), vertices.Select(vertex => vertex.IncomingEdge).ToArray()); } - /// Clips a 3D ring by one half-plane of its projected coordinates: is - /// positive inside, so the crossing parameter is da / (da - db) and the new vertex interpolates in 3D. - /// - private static List ClipHalfPlane3(List ring, Func coordinate, - Func distance) + internal static List<(double[] Point, bool IncomingEdge)> ClipHalfPlane3( + List<(double[] Point, bool IncomingEdge)> ring, Func distance) { - var result = new List(ring.Count + 2); + var result = new List<(double[] Point, bool IncomingEdge)>(ring.Count + 2); for (int i = 0; i < ring.Count; i++) { var a = ring[i]; var b = ring[(i + 1) % ring.Count]; - double da = distance(coordinate(a)), db = distance(coordinate(b)); + double da = distance(a.Point), db = distance(b.Point); bool insideA = da >= 0, insideB = db >= 0; if (insideA) result.Add(a); - if (insideA != insideB) - { - double t = da / (da - db); - result.Add([a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t, - a[2] + (b[2] - a[2]) * t]); - } + if (insideA == insideB) continue; + + double t = da / (da - db); + var from = a.Point; + var to = b.Point; + // Along the crop boundary the entrance follows the previous exit across an artificial edge. + result.Add(([from[0] + (to[0] - from[0]) * t, from[1] + (to[1] - from[1]) * t, + from[2] + (to[2] - from[2]) * t], insideA && b.IncomingEdge)); } return result; } - internal static bool ClipSegment(double x0, double y0, double x1, double y1, double rx0, double ry0, double rx1, double ry1, out double cx0, out double cy0, out double cx1, out double cy1) @@ -1156,7 +3474,7 @@ internal static bool ClipSegment(double x0, double y0, double x1, double y1, /// The part of a polygon that stands behind the cutting plane (the side the view direction points /// to), the plane crossing a polygon adding the points where it crosses the plane. - private static List ClipBehind(List polygon, double[] origin, double[] direction) + internal static List ClipBehind(List polygon, double[] origin, double[] direction) { var result = new List(polygon.Count + 2); for (int i = 0; i < polygon.Count; i++) @@ -1190,10 +3508,15 @@ internal static List SectionMarks(RvtDocument document, int? viewportViewId = null, double? viewportScaleDenominator = null) { var marks = new List(); + var hidden = viewportViewId is int planId ? document.RawData.ViewHiddenElements?.GetValueOrDefault(planId) : null; + var planExtents = viewportViewId is int ownerId + && document.GetElement(ownerId) is { ViewAnnotationCropActive: false, ViewCrop: { Right: [1, 0, 0], Up: [0, 1, 0] } } + && document.RawData.DatumExtents?.GetValueOrDefault(ownerId) is { Normal: [0, 0, -1] } savedExtents + ? savedExtents.Sections : null; foreach (var view in document.Elements) { if (view.CategoryId != (int)BuiltInCategory.OST_Views) continue; - if (view.RootClassName is not ("DBViewSection" or "DBViewElevation")) continue; + if (view.RootClassName is not ("DBViewSection" or "DBViewElevation") || hidden?.Contains(view.Id) == true) continue; string name = view.Name ?? ""; if (!name.Contains("section", StringComparison.OrdinalIgnoreCase)) continue; if (view.ViewOrigin is not { Length: 3 } origin || view.ViewDirection is not { Length: 3 } direction @@ -1203,7 +3526,7 @@ internal static List SectionMarks(RvtDocument document, // section view with no decoded extent (no viewer record) leaves no trace, the way the // reference draws none for the Architectural Section (viewer -1, no extent record) while // rvt-prt draws traces only from Section m_frontCut extents. - if (view.SectionViewerId is not int viewerId || viewerId <= 0 + if (view.SectionViewerId is not int viewerId || viewerId <= 0 || hidden?.Contains(viewerId) == true || document.RawData.SectionViews?.TryGetValue(viewerId, out var section) != true) continue; // A callout of another view marks that view, not the plan; a finer-scale-only section @@ -1231,19 +3554,13 @@ internal static List SectionMarks(RvtDocument document, // The file's front-cut polyline is the true trace (a jogged section draws its jogs); without a // decoded extent the mark stays a straight ray through the plane origin, as before. List<(double X, double Y)> points; - bool bounded; + bool bounded, usesPlanExtent = false; if (section.FrontCut is { Count: >= 2 } cut) { points = cut.Select(p => (p[0] * FeetToMillimetres, p[1] * FeetToMillimetres)).ToList(); - // A measured per-view correction, in model millimetres: the reference export places the - // Longitudinal Section's mark 3,090 mm along +X from its decoded front cut while the - // Building Section's sits exactly on its own (control: both land at x = 592.1 pt). The - // shift matches no stored field — m_pntForViewData equals the first front-cut point, - // m_rotOffset.x is half the cut length, and the view origin (3,280 mm) is 190 mm away, - // nine times the measurement error — so it stays a measured constant, keyed by view name - // so it survives the id-shifted fixture. - if (MeasuredSectionTraceOffsets.ByViewName.TryGetValue(name, out var shift)) - points = points.Select(p => (p.X + shift.Dx, p.Y + shift.Dy)).ToList(); + if (planExtents?.GetValueOrDefault(viewerId) is { } extent && extent.SegmentCount == points.Count - 1 + && document.RawData.SectionTraceOrigins?.TryGetValue(viewerId, out var traceOrigin) == true) + usesPlanExtent = ApplyPlanSectionExtent(points, ux, uy, traceOrigin, extent); bounded = true; } else if (section.FrontCut != null) @@ -1271,14 +3588,72 @@ internal static List SectionMarks(RvtDocument document, return Math.Abs(mark.Points[0].X - sx) < 50 && Math.Abs(mark.Points[0].Y - sy) < 50 && Math.Abs((mdx * sdx + mdy * sdy) / (mlen * slen)) > 0.99; })) continue; - marks.Add(new SectionMark(points, bounded, name)); + marks.Add(new SectionMark(points, bounded, name, view.Id, usesPlanExtent)); } return marks; } + private static bool ApplyPlanSectionExtent(List<(double X, double Y)> points, double ux, double uy, + (double X, double Y) origin, Parsing.TfBlockDeserializer.SectionTraceExtent extent) + { + // View extents are distances along the section axis from its stored trace origin. + // Move the outer endpoints along their own legs so the jogs keep their model positions. + double zero = (origin.X * ux + origin.Y * uy) * FeetToMillimetres; + double first = zero + extent.Start * FeetToMillimetres; + double last = zero + extent.End * FeetToMillimetres; + double startLeg = Along(points[1]) - Along(points[0]); + double endLeg = Along(points[^1]) - Along(points[^2]); + if (!(startLeg > 0 && endLeg > 0 && first < Along(points[1]) && last > Along(points[^2]) + && Math.Abs(Cross(points[0]) - Cross(points[1])) < 1e-6 + && Math.Abs(Cross(points[^2]) - Cross(points[^1])) < 1e-6)) return false; + + points[0] = Extend(points[0], first); + points[^1] = Extend(points[^1], last); + return true; + + double Along((double X, double Y) p) => p.X * ux + p.Y * uy; + double Cross((double X, double Y) p) => p.X * uy - p.Y * ux; + (double X, double Y) Extend((double X, double Y) p, double distance) + { + double delta = distance - Along(p); + return (p.X + delta * ux, p.Y + delta * uy); + } + } + internal static void DrawContent(PdfPage page, ElevationContent content, double scale, double originX, double originY, double faceFill = 1, RvtDocument? document = null, - (double X0, double Y0, double X1, double Y1)? clipRect = null) + (double X0, double Y0, double X1, double Y1)? clipRect = null, bool drawNativeDatums = true, + bool unshadedHiddenLine = false) + { + if (content.SectionBands is { } bands) + { + var crop = clipRect ?? (content.MinX, content.MinY, content.MaxX, content.MaxY); + foreach (var band in bands) + { + double left = Math.Max(crop.Item1, band.Left), right = Math.Min(crop.Item3, band.Right); + if (right <= left) continue; + DrawModel(page, band.Content, scale, originX + (band.Content.MinX - content.MinX) / scale, + originY + (band.Content.MinY - content.MinY) / scale, faceFill, document, + (left, crop.Item2, right, crop.Item4), unshadedHiddenLine); + } + } + else + DrawModel(page, content, scale, originX, originY, faceFill, document, clipRect, unshadedHiddenLine); + + DrawFallbackDatums(page, content, scale, originX, originY, document, clipRect); + if (drawNativeDatums) + { + DrawNativeDatums(page, content, scale, originX, originY, document, clipRect); + CircularAnnotations.Draw(page, document, content.AnnotationSymbols ?? [], scale, + x => (x - content.MinX) / scale + originX, y => (y - content.MinY) / scale + originY); + } + } + + private const double DefaultOutlinePen = 0.2; + + private static void DrawModel(PdfPage page, ElevationContent content, double scale, double originX, + double originY, double faceFill, RvtDocument? document, + (double X0, double Y0, double X1, double Y1)? clipRect, bool unshadedHiddenLine) { double ToX(double x) => (x - content.MinX) / scale + originX; double ToY(double y) => (y - content.MinY) / scale + originY; @@ -1287,7 +3662,7 @@ internal static void DrawContent(PdfPage page, ElevationContent content, double // projection pen. Only the edges the cut created ink cut; the projected edges of a section ink thin // like the reference does. bool isSection = faceFill < 1; - double faceLine = 0.2, projLine = 0.1; + double faceLine = DefaultOutlinePen, projLine = 0.1; int penScale = (int)Math.Round(scale); if (document != null) { @@ -1300,12 +3675,125 @@ internal static void DrawContent(PdfPage page, ElevationContent content, double if (!isSection) projLine = faceLine; double clipX0 = clipRect?.X0 ?? content.MinX, clipY0 = clipRect?.Y0 ?? content.MinY; double clipX1 = clipRect?.X1 ?? content.MaxX, clipY1 = clipRect?.Y1 ?? content.MaxY; - // The faded site behind the building: the plants and the ground as light shapes without outlines. - foreach (var (contextPoints, _) in content.Context) - page.DrawPolyline(contextPoints.Select(point => (ToX(point.X), ToY(point.Y))).ToList(), 0, true, 0.9); + var groundPolygons = new List>(); + if (content.GroundHatch is { } terrain && terrain.BaseY < clipY1) + { + double baseY = Math.Max(terrain.BaseY, clipY0); + foreach (var span in GroundSpans(terrain, baseY)) + { + var polygon = ClipToWindow(span, clipX0, clipX1, baseY, clipY1); + if (polygon.Count >= 3) groundPolygons.Add(polygon.Select(p => (ToX(p.X), ToY(p.Y))).ToList()); + } + } + double groundPen = document != null + && PenWidths.TryGetWidth(document, (int)BuiltInCategory.OST_TopographySurface, true, penScale, out var soilPen) + ? soilPen : 0.1; + var groundTiles = content.GroundHatch is { } tiledGround && groundPolygons.Count > 0 + ? FillHatch.DraftingTiles(tiledGround.Grids, ToX(tiledGround.AnchorX), ToY(tiledGround.AnchorY), groundPen) : null; + if (content.SkyGradient is { } gradient) + { + if (clipY1 > 0) + { + double bottom = Math.Max(0, clipY0); + var horizon = Color(gradient.Horizon); + var sky = Color(gradient.Sky); + double t = bottom / clipY1; + page.FillVerticalGradient(ToX(clipX0), ToY(bottom), (clipX1 - clipX0) / scale, (clipY1 - bottom) / scale, + new PdfColor(horizon.R + (sky.R - horizon.R) * t, horizon.G + (sky.G - horizon.G) * t, + horizon.B + (sky.B - horizon.B) * t), sky); + } + if (clipY0 < 0 && gradient.Ground is int groundColor) + { + double top = Math.Min(0, clipY1); + page.DrawPolyline([(ToX(clipX0), ToY(clipY0)), (ToX(clipX1), ToY(clipY0)), + (ToX(clipX1), ToY(top)), (ToX(clipX0), ToY(top))], 0, true, Color(groundColor)); + } + + static PdfColor Color(int packed) => new((packed & 255) / 255d, ((packed >> 8) & 255) / 255d, + (packed >> 16) / 255d); + } + // In opaque hidden line, the site surface covers the gradient behind the building. + var terrainShadows = new List>(); + double terrainShadowFill = 1; + foreach (var (contextPoints, _, isTerrain) in content.Context) + { + var points = clipRect.HasValue ? ClipToWindow(contextPoints, clipX0, clipX1, clipY0, clipY1) : contextPoints; + if (points.Count < 3) continue; + var polygon = points.Select(point => (X: ToX(point.X), Y: ToY(point.Y))).ToList(); + double fill = isTerrain && content.SkyGradient != null ? 1 : 0.9; + page.DrawPolyline(polygon, 0, true, fill); + if (content.CastShadows?.GetValueOrDefault(contextPoints) is not { } shadow) continue; + double winding = Math.Sign(PlanPrinter.SignedArea(points)); + if (winding == 0) continue; + var sides = new List<(double X, double Y, double C)>(points.Count); + for (int i = 0; i < points.Count; i++) + { + var a = points[i]; + var b = points[(i + 1) % points.Count]; + double x = (a.Y - b.Y) * winding, y = (b.X - a.X) * winding; + sides.Add((x, y, -x * a.X - y * a.Y)); + } + if (shadow.Openings.Count > 0 || sides.Any(side => points.Any(p => + side.X * p.X + side.Y * p.Y + side.C < -0.01))) + { + DrawShadow(contextPoints, polygon, fill); + continue; + } + foreach (var ring in shadow.Rings) + { + var clipped = ring; + foreach (var (x, y, c) in sides) + { + double Distance((double X, double Y) p) => x * p.X + y * p.Y + c; + clipped = ClipHalfPlane(clipped, p => Distance(p) >= 0, Distance); + } + if (clipped.Count >= 3) terrainShadows.Add(clipped.Select(p => (ToX(p.X), ToY(p.Y))).ToList()); + } + terrainShadowFill = fill * shadow.Light; + } + if (terrainShadows.Count > 0) + { + page.BeginClip(ToX(clipX0), ToY(clipY0), (clipX1 - clipX0) / scale, (clipY1 - clipY0) / scale); + ClipShadowAtGround(ToX(clipX0), ToY(clipY0), ToX(clipX1), ToY(clipY1)); + page.FillPolygonUnion(terrainShadows, terrainShadowFill); + page.EndClip(); + } + if (content.SiteSilhouettes is { } silhouettes) + { + var background = silhouettes.Where(ring => content.ForegroundSite?.Sources.Contains(ring) != true).ToList(); + var rings = background.Select(ring => ClipToWindow(ring, clipX0, clipX1, clipY0, clipY1)) + .Where(ring => ring.Count >= 3).Select(ring => + ring.Select(point => (ToX(point.X), ToY(point.Y))).ToList()); + double fill = content.SkyGradient != null ? 1 : 0.9; + page.FillPolygonUnion(rings, fill); + if (content.PlantTones is { } shades) + foreach (var (gray, visible) in shades) + page.FillPolygonUnion(visible.Select(ring => ClipToWindow(ring, clipX0, clipX1, clipY0, clipY1)) + .Where(ring => ring.Count >= 3).Select(ToPage), gray / 255.0); + if (content.CastShadows != null) + { + var shadedPlants = background.Select(ring => content.CastShadows.GetValueOrDefault(ring)) + .OfType().ToList(); + if (shadedPlants.Count > 0) + { + page.BeginClip(ToX(clipX0), ToY(clipY0), (clipX1 - clipX0) / scale, (clipY1 - clipY0) / scale); + ClipShadowAtGround(ToX(clipX0), ToY(clipY0), ToX(clipX1), ToY(clipY1)); + page.FillPolygonUnion(shadedPlants.SelectMany(shadow => shadow.Rings) + .Select(ring => ring.Select(point => (ToX(point.X), ToY(point.Y))).ToList()), + fill * shadedPlants[0].Light); + page.EndClip(); + } + } + } + var sectionMasks = content.GroundHatch?.SectionMasks; + if (isSection && groundTiles != null && sectionMasks == null) DrawGroundTiles(groundTiles); // The faces only fill, far to near, so nearer mass covers what stands behind it; the shared edge // set below inks the visible lines, without the triangulation diagonals. A crop rectangle drops // the faces wholly outside it and clips the ones crossing it, so only the crop is drawn. + // shortcut: use the saved opaque base in sections, until local ambient shadows are supported. + double surfaceFill = unshadedHiddenLine || content.OpaqueSection ? 1 : faceFill; + var surfaceTiles = new Dictionary, List?>(); + var surfaceHatches = content.Hatch; foreach (var (points, _, _) in content.Faces) { var pagePoints = points; @@ -1324,13 +3812,274 @@ internal static void DrawContent(PdfPage page, ElevationContent content, double if (pagePoints.Count < 3) continue; } } - page.DrawPolyline(pagePoints.Select(point => (ToX(point.X), ToY(point.Y))).ToList(), 0, true, faceFill); + var polygon = pagePoints.Select(point => (X: ToX(point.X), Y: ToY(point.Y))).ToList(); + var modelHatch = content.ModelHatches?.GetValueOrDefault(points); + double fill = modelHatch != null ? 1 : surfaceFill; + double shadowBase = surfaceFill; + if (content.FaceFills?.TryGetValue(points, out double? materialFill) == true) + { + if (!materialFill.HasValue) continue; + fill = shadowBase = materialFill.Value; + } + var openings = content.FaceOpenings?.GetValueOrDefault(points); + var rings = openings == null ? null : FaceRings(polygon, openings); + var terrainVisible = content.TerrainClippedFaces?.GetValueOrDefault(points); + if (terrainVisible is { Count: 0 }) continue; + if (terrainVisible != null) page.BeginPolygonClip(terrainVisible.Select(ToPage), evenOdd: false); + if (content.DetailGlass?.TryGetValue(points, out var pane) == true) + page.FillPolygonUnion(rings ?? [polygon], pane.Gray, pane.Opacity); + else if (rings == null) + page.DrawPolyline(polygon, 0, true, fill); + else + page.FillPolygonUnion(rings, fill); + var glazing = content.Glazing; + bool paintPane = glazing?.IsPane(points) == true; + if (!paintPane && modelHatch == null && content.AmbientTones?.GetValueOrDefault(points) is { } shade) + { + page.BeginPolygonClip(rings ?? [polygon]); + double x = ToX(shade.X0), y = ToY(shade.Y0); + double width = ToX(shade.X1) - x, height = ToY(shade.Y1) - y; + page.DrawImage(shade.Image, x, y, width, height); + if (shade.ThroughGlass is { } throughGlass && shade.Glass is { } glassMasks) + { + foreach (var mask in glassMasks) + { + var paneRing = ToPage(mask.Polygon); + page.BeginPolygonClip(mask.Holes == null ? [paneRing] : FaceRings(paneRing, mask.Holes)); + page.DrawImage(throughGlass, x, y, width, height); + page.EndClip(); + } + } + page.EndClip(); + } + if (paintPane) + glazing!.Draw(page, content, points, rings ?? [polygon], ToX, ToY, FaceRings); + DrawShadow(points, polygon, shadowBase); + if (surfaceHatches is { } hatch && hatch.Faces.TryGetValue(points, out var surfacePattern)) + { + var (grid, width) = surfacePattern; + double spacing = grid.Offset * FeetToMillimetres; + double anchorX = ToX(hatch.AnchorX) + grid.OriginX * FeetToMillimetres; + double anchorY = ToY(hatch.AnchorY) + grid.OriginY * FeetToMillimetres; + if (hatch.UseClippedLines) + page.FillWithClippedParallelLines(rings ?? [polygon], spacing, grid.Angle, anchorX, anchorY, width); + else + page.FillWithParallelLines(rings ?? [polygon], spacing, grid.Angle, anchorX, anchorY, width); + } + if (surfaceHatches?.DashedFaces.TryGetValue(points, out var grids) == true) + { + if (!surfaceTiles.TryGetValue(grids, out var tiles)) + { + tiles = FillHatch.DraftingTiles(grids, ToX(surfaceHatches.AnchorX), ToY(surfaceHatches.AnchorY), 0.1); + surfaceTiles.Add(grids, tiles); + } + foreach (var tile in tiles ?? []) page.FillWithLinePattern([polygon], tile); + } + if (modelHatch != null) + { + var modelRings = FaceRings(polygon, modelHatch.Holes); + foreach (var modelGrid in modelHatch.Grids) + { + if (modelGrid.Segments == null) + page.FillWithParallelLines(modelRings, modelGrid.Spacing / scale, modelGrid.Angle, ToX(modelGrid.X), ToY(modelGrid.Y), 0.1); + else + page.FillWithLinePattern(modelRings, new PdfLinePattern(modelGrid.Spacing / scale, modelGrid.Angle, + ToX(modelGrid.X), ToY(modelGrid.Y), 0.1, modelGrid.Shift / scale, + modelGrid.Segments.Select(segment => segment / scale).ToArray())); + } + } + if (terrainVisible != null) page.EndClip(); + } + if (content.ForegroundSite is { Rings.Count: > 0 } site) + { + double fill = content.SkyGradient != null ? 1 : 0.9; + page.BeginClip(ToX(clipX0), ToY(clipY0), (clipX1 - clipX0) / scale, (clipY1 - clipY0) / scale); + page.FillPolygonUnion(site.Rings.Select(ToPage), fill); + ClipShadowAtGround(ToX(clipX0), ToY(clipY0), ToX(clipX1), ToY(clipY1)); + page.FillPolygonUnion(site.Shade.Select(ToPage), fill * site.Light); + page.EndClip(); + } + + List<(double X, double Y)> ToPage(List<(double X, double Y)> ring) => + ring.Select(point => (ToX(point.X), ToY(point.Y))).ToList(); + + if (groundTiles != null && sectionMasks != null) + { + List<(double X, double Y)> frame = + [(ToX(clipX0), ToY(clipY0)), (ToX(clipX1), ToY(clipY0)), + (ToX(clipX1), ToY(clipY1)), (ToX(clipX0), ToY(clipY1))]; + var caps = new List>(); + page.BeginPolygonClip([frame]); + foreach (var mask in sectionMasks) + { + var clipped = ClipToWindow(mask, clipX0, clipX1, clipY0, clipY1); + if (clipped.Count < 3) continue; + var polygon = clipped.Select(point => (ToX(point.X), ToY(point.Y))).ToList(); + page.IntersectPolygonClip([frame, polygon]); + if (isSection) continue; + if (PlanPrinter.SignedArea(polygon) < 0) polygon.Reverse(); + caps.Add(polygon); + } + DrawGroundTiles(groundTiles, opaque: true); + page.EndClip(); + if (caps.Count > 0) page.FillPolygonUnion(caps, 1); + } + if (content.SectionBillboards is { Count: > 0 } billboards) + { + page.BeginClip(ToX(clipX0), ToY(clipY0), (clipX1 - clipX0) / scale, (clipY1 - clipY0) / scale); + page.FillPolygonUnion(billboards.Select(ToPage), 1); + page.EndClip(); + } + if (content.DetailCutFaces is { } cutFaces) + { + // Closed cuts cover projected surfaces before the cut patterns and linework are drawn. + var caps = cutFaces.Select(face => ClipToWindow(face, clipX0, clipX1, clipY0, clipY1)) + .Where(face => face.Count >= 3).Select(ToPage).ToList(); + foreach (var cap in caps) + if (PlanPrinter.SignedArea(cap) < 0) cap.Reverse(); + if (caps.Count > 0) page.FillPolygonUnion(caps, 1); + } + if (content.SiteOutlines is { Count: > 0 } siteEdges) + foreach (var group in siteEdges.GroupBy(edge => edge.CategoryId)) + { + double width = document != null + && PenWidths.TryGetWidth(document, group.Key, false, penScale, out double savedWidth) + ? savedWidth : 0.1; + var inked = new HashSet<(long Ax, long Ay, long Bx, long By)>(); + foreach (var edge in group) + { + if (ClipSegment(edge.X1, edge.Y1, edge.X2, edge.Y2, clipX0, clipY0, clipX1, clipY1, + out double x1, out double y1, out double x2, out double y2) + && inked.Add(ProjectedEdgeKey(x1, y1, x2, y2))) + page.DrawLine(ToX(x1), ToY(y1), ToX(x2), ToY(y2), width); + } + } + List> FaceRings(List<(double X, double Y)> polygon, + IReadOnlyList> openings) + { + bool positive = PlanPrinter.SignedArea(polygon) > 0; + var rings = new List> { polygon }; + foreach (var hole in openings) + { + var clipped = clipRect.HasValue ? ClipToWindow(hole, clipX0, clipX1, clipY0, clipY1) : hole; + if (clipped.Count < 3) continue; + var ring = clipped.Select(point => (ToX(point.X), ToY(point.Y))).ToList(); + double area = PlanPrinter.SignedArea(ring); + if (area == 0) continue; + // Opposite winding keeps the opening clear in the face fill. + if ((area > 0) == positive) ring.Reverse(); + rings.Add(ring); + } + return rings; + } + + void DrawShadow(List<(double X, double Y)> face, List<(double X, double Y)> polygon, double fill) + { + if (content.CastShadows?.GetValueOrDefault(face) is not { } shadow) return; + page.BeginPolygonClip([polygon, .. shadow.Openings.Select(ring => + ring.Select(point => (ToX(point.X), ToY(point.Y))).ToList())]); + if (groundPolygons.Count > 0) + ClipShadowAtGround(polygon.Min(p => p.X), polygon.Min(p => p.Y), + polygon.Max(p => p.X), polygon.Max(p => p.Y)); + page.FillPolygonUnion(shadow.Rings.Select(ring => + ring.Select(point => (ToX(point.X), ToY(point.Y))).ToList()), fill * shadow.Light); + page.EndClip(); + } + + void ClipShadowAtGround(double left, double bottom, double right, double top) + { + // The terrain cut hides the projected shadows in its hatched area. + List<(double X, double Y)> frame = + [(ToX(clipX0), ToY(clipY0)), (ToX(clipX1), ToY(clipY0)), + (ToX(clipX1), ToY(clipY1)), (ToX(clipX0), ToY(clipY1))]; + foreach (var mask in groundPolygons) + if (mask.Max(p => p.X) > left && mask.Min(p => p.X) < right + && mask.Max(p => p.Y) > bottom && mask.Min(p => p.Y) < top) + page.IntersectPolygonClip([frame, mask]); + } + + if (groundTiles != null) + { + if (!isSection && sectionMasks == null) DrawGroundTiles(groundTiles, opaque: true); + } + else if (content.GroundHatch is { } ground && groundPolygons.Count > 0) + { + var strokes = FillHatch.Strokes(groundPolygons, ground.Grids, ToX(ground.AnchorX), ToY(ground.AnchorY)) + .Select(line => new CollectedEdge(line.X1, line.Y1, line.X2, line.Y2, 0, 0, -1, -1, 0, 0, 0, 0)); + // Covered portions must be absent from the PDF, including when compared as vectors. + if (isSection) + strokes = VisibleTerrainEdges(strokes, + content.Faces.Select(face => face.Points.Select(p => (ToX(p.X), ToY(p.Y))).ToList()), + [], 0.01 / (scale * scale)); + foreach (var line in strokes) + page.DrawLine(line.X1, line.Y1, line.X2, line.Y2, groundPen); + } + void DrawGroundTiles(List tiles, bool opaque = false) + { + foreach (var polygon in groundPolygons) + if (PlanPrinter.SignedArea(polygon) < 0) polygon.Reverse(); + if (opaque) + { + page.FillPolygonUnion(groundPolygons, 1); + if (content.GroundHatch?.Shadow is { } soilShadow) + { + page.BeginPolygonClip(groundPolygons, evenOdd: false); + page.FillPolygonUnion(soilShadow.Rings.Select(ToPage), soilShadow.Light); + page.EndClip(); + } + } + foreach (var tile in tiles) page.FillWithLinePattern(groundPolygons, tile); + } + var masks = content.DetailBreaks is { Count: > 0 } breaks + ? breaks.Select(b => b.Mask).ToList() : null; + if (masks != null) + foreach (var polygon in masks) + { + var clipped = ClipToWindow(polygon, clipX0, clipX1, clipY0, clipY1); + if (clipped.Count >= 3) + page.DrawPolyline(clipped.Select(p => (ToX(p.X), ToY(p.Y))).ToList(), 0, true, 1); + } + if (content.LayerHatches is { } hatches) + { + foreach (var group in hatches.GroupBy(p => (p.Grids, p.AnchorX, p.AnchorY, p.PenWidth))) + { + var polygons = group.Select(p => ClipToWindow(p.Polygon, clipX0, clipX1, clipY0, clipY1) + .Select(point => (ToX(point.X), ToY(point.Y))).ToList()); + double anchorX = ToX(group.Key.AnchorX), anchorY = ToY(group.Key.AnchorY); + var grids = group.Key.Grids; + double draftingPen = group.Key.PenWidth ?? 0.1; + if ((!isSection || group.Key.PenWidth.HasValue) && masks == null + && FillHatch.DraftingTiles(grids, anchorX, anchorY, draftingPen) is { } tiles) + { + var rings = polygons.Where(p => p.Count >= 3).ToList(); + foreach (var ring in rings) + if (PlanPrinter.SignedArea(ring) < 0) ring.Reverse(); + foreach (var tile in tiles) page.FillWithLinePattern(rings, tile); + foreach (var grid in grids.Where(g => g.Segments.Length == 0)) + page.FillWithParallelLines(rings, Math.Abs(grid.Offset) * FeetToMillimetres, grid.Angle, + anchorX + grid.OriginX * FeetToMillimetres, anchorY + grid.OriginY * FeetToMillimetres, draftingPen); + continue; + } + var strokes = FillHatch.Strokes(polygons, grids, anchorX, anchorY, continuousLines: true) + .Select(s => new CollectedEdge(s.X1, s.Y1, s.X2, s.Y2, 0, 0, -1, -1, 0, 0, 0, 0)); + if (masks != null) + strokes = VisibleTerrainEdges(strokes, masks.Select(p => p.Select(point => + (ToX(point.X), ToY(point.Y))).ToList()), [], 1e-9); + foreach (var stroke in strokes) + page.DrawLine(stroke.X1, stroke.Y1, stroke.X2, stroke.Y2, group.Key.PenWidth ?? 0.18); + } } - foreach (var edge in content.Edges) + HashSet<(long Ax, long Ay, long Bx, long By)>? doorProjections = content.KeepDoorDepths ? [] : null; + foreach (var edge in Unmasked(content.Edges)) { double x1 = edge.X1, y1 = edge.Y1, x2 = edge.X2, y2 = edge.Y2; - if (clipRect.HasValue && !ClipSegment(x1, y1, x2, y2, clipX0, clipY0, clipX1, clipY1, + if ((clipRect.HasValue || edge.CategoryId == (int)BuiltInCategory.OST_Topography) + && !ClipSegment(x1, y1, x2, y2, clipX0, clipY0, clipX1, clipY1, out x1, out y1, out x2, out y2)) continue; + // Different physical door edges can leave the same visible span after clipping. + if (doorProjections != null && edge.CategoryId == (int)BuiltInCategory.OST_Doors + && !edge.IsCut && edge.ViewLineStyleId == 0 + && !doorProjections.Add(ProjectedEdgeKey(x1, y1, x2, y2))) continue; // A cut edge inks with its own category's cut pen (falling back to the Walls cut pen when the // category decodes none); anything else inks with the projection pen. double width = projLine; @@ -1338,16 +4087,64 @@ internal static void DrawContent(PdfPage page, ElevationContent content, double width = document != null && PenWidths.TryGetWidth(document, edge.CategoryId, true, penScale, out double cutWidth) ? cutWidth : faceLine; + if (edge.ViewLineStyleId > 0) + { + if (document == null || document.RawData.GraphicsStylePens?.TryGetValue(edge.ViewLineStyleId, out var style) != true + || style.GStyleType != 1) continue; + var color = new PdfColor((style.Color & 255) / 255d, ((style.Color >> 8) & 255) / 255d, + ((style.Color >> 16) & 255) / 255d); + width = document.RawData.PenWidthTable is { } widths + && PenWidths.TryPenWidth(widths, style.PenNumber, penScale, out double patternPen) ? patternPen : projLine; + if (LinePatterns.TryGetPatternDashes(document, style.LinePatternId, out var dashes)) + { + double dx = x2 - x1, dy = y2 - y1; + page.SetDashPoints(LinePatterns.FitEndpointDashes(Math.Sqrt(dx * dx + dy * dy) / scale * 72 / 25.4, dashes)); + } + page.DrawLine(ToX(x1), ToY(y1), ToX(x2), ToY(y2), width, color); + page.ResetDash(); + continue; + } page.DrawLine(ToX(x1), ToY(y1), ToX(x2), ToY(y2), width); } + if (content.Insulation != null) + { + double pen = 0.18; + if (document != null && PenWidths.TryGetWidth(document, (int)BuiltInCategory.OST_InsulationLines, + false, penScale, out double width)) + pen = width; + foreach (var edge in Unmasked(content.Insulation)) + if (ClipSegment(edge.X1, edge.Y1, edge.X2, edge.Y2, clipX0, clipY0, clipX1, clipY1, + out double x1, out double y1, out double x2, out double y2)) + page.DrawLine(ToX(x1), ToY(y1), ToX(x2), ToY(y2), pen); + } + if (content.DetailBreaks is { } detailBreaks) + foreach (var detail in detailBreaks) + for (int i = 1; i < detail.Line.Count; i++) + { + var a = detail.Line[i - 1]; + var b = detail.Line[i]; + if (ClipSegment(a.X, a.Y, b.X, b.Y, clipX0, clipY0, clipX1, clipY1, + out double x1, out double y1, out double x2, out double y2)) + page.DrawLine(ToX(x1), ToY(y1), ToX(x2), ToY(y2), 0.35); + } + + IEnumerable Unmasked(List edges) => + masks == null ? edges : VisibleTerrainEdges(edges, masks, []); + } + private static void DrawFallbackDatums(PdfPage page, ElevationContent content, double scale, double originX, + double originY, RvtDocument? document, (double X0, double Y0, double X1, double Y1)? clipRect) + { + double ToX(double x) => (x - content.MinX) / scale + originX; + double ToY(double y) => (y - content.MinY) / scale + originY; + var (clipX0, clipY0, clipX1, clipY1) = clipRect ?? (content.MinX, content.MinY, content.MaxX, content.MaxY); // Grids first, then the levels: light over the faces the way an elevation prints them. The grids // dash coarsely from the grid type's line pattern ([36 9 9 9] pt on the sample, decoded below); // their bubbles print solid like the reference. if (content.Grids.Count > 0) { // Grids are datum elements: they ink with the annotation pen table (fixed weights), not the - // scale-dependent model table — pen 1 annotates 0.1 mm (0.283 pt) at every scale on the reference. + // scale-dependent model table — pen 1 annotates 0.1 mm (0.283 pt) at every scale on the reference. double gridLine = 0.1; if (document != null && PenWidths.TryGetPenNumber(document, (int)BuiltInCategory.OST_Grids, false, out int gridPen) && PenWidths.TryAnnotationWidth(document, gridPen, out double g)) @@ -1361,6 +4158,7 @@ internal static void DrawContent(PdfPage page, ElevationContent content, double double bottom = ToY(Math.Max(content.MinY, clipY0)); foreach (var (x, name) in content.Grids) { + if (content.NativeGrids?.ContainsKey(x) == true) continue; if (x < clipX0 || x > clipX1) continue; double pageX = ToX(x); // The dash pattern starts at the top of the line, as the reference grids do (a cut 36 pt @@ -1391,6 +4189,7 @@ internal static void DrawContent(PdfPage page, ElevationContent content, double double lastLabelY = double.NegativeInfinity; foreach (var (y, label, x0, x1) in content.Levels) { + if (content.NativeLevels?.ContainsKey(y) == true) continue; // A level belongs to the crop, not to the collected model bounds: stairs-only content ends // above the Foundation while the crop reaches it, and the reference draws it. if (y < clipY0 - 1 || y > clipY1 + 1) continue; @@ -1447,4 +4246,131 @@ internal static void DrawContent(PdfPage page, ElevationContent content, double page.ResetDash(); } } + + internal static void DrawNativeDatums(PdfPage page, ElevationContent content, double scale, double originX, + double originY, RvtDocument? document, (double X0, double Y0, double X1, double Y1)? crop) + { + double ToX(double x) => (x - content.MinX) / scale + originX; + double ToY(double y) => (y - content.MinY) / scale + originY; + if (content.NativeGrids is { Count: > 0 } grids) + { + double[] pattern = document != null && LinePatterns.TryGetGridDashes(document, out var gridDashes) + ? gridDashes.Select(p => p * 25.4 / 72).ToArray() + : []; + foreach (var (x, name) in content.Grids) + { + if (!grids.TryGetValue(x, out var g)) continue; + if (crop is { } c && (x < c.X0 || x > c.X1 || g.Top < c.Y0 || g.Bottom > c.Y1)) continue; + double pageX = ToX(x), top = ToY(g.Top), center = top + g.Radius; + DrawDatumDashes(page, pageX, ToY(g.Bottom), pageX, top, pattern); + page.DrawPolyline(DatumCircle(pageX, center, g.Radius, 25), 0.1, true); + page.DrawText(name, pageX, center - 2.17, 18 * 25.4 / 72, PdfTextAlignment.Center); + } + } + + if (content.NativeLevels is not { Count: > 0 } lines) return; + foreach (var (y, label, _, _) in content.Levels) + { + if (!lines.TryGetValue(y, out var line)) continue; + if (crop is { } c && (y < c.Y0 - 1 || y > c.Y1 + 1 || line.HeadX < c.X0 || line.Left > c.X1)) continue; + double left = ToX(line.Left), right = ToX(line.LineEnd), rowY = ToY(y); + DrawDatumDashes(page, left, rowY, right, rowY, [3, 1.5]); + + double headLeft = ToX(line.HeadX), headY = ToY(line.HeadY); + if (line.Elbow is { } e) + { + page.DrawLine(right, rowY, ToX(e.X), ToY(e.Y), 0.1); + page.DrawLine(ToX(e.X), ToY(e.Y), headLeft, headY, 0.1); + } + double cx = headLeft + line.Radius; + var outline = DatumCircle(cx, headY, line.Radius, 20); + page.DrawPolyline(outline, 0.1, true); + page.DrawPolyline([(cx, headY), .. outline.Skip(5).Take(6)], 0, true, 0); + page.DrawPolyline([(cx, headY), .. outline.Skip(15), outline[0]], 0, true, 0); + string elevation = $"{y:0}"; + if (DrawSavedLevelLabels(page, document, line.SymbolId, headLeft, headY, label, elevation)) continue; + page.DrawText(label, headLeft - 4, headY + 1.85, 12 * 25.4 / 72, PdfTextAlignment.Right); + page.DrawText(elevation, headLeft - 4, headY - 5.05, 12 * 25.4 / 72, PdfTextAlignment.Right); + } + } + + private static bool DrawSavedLevelLabels(PdfPage page, RvtDocument? document, int symbolId, + double x, double y, string name, string elevation) + { + if (document?.RawData.TitleBlockLabels?.GetValueOrDefault(symbolId) is not [var first, var second] labels + || first.ParamId == second.ParamId || page.Owner.Font is not { } font + || labels.Any(label => (BuiltInParameter)label.ParamId is not (BuiltInParameter.DATUM_TEXT or BuiltInParameter.LEVEL_ELEV) + || label is not { Bx: 1, By: 0, Hx: 0, Hy: 1 } || !(label.Height > 0) + || !double.IsFinite(label.Height) || !double.IsFinite(label.Ox) || !double.IsFinite(label.Oy))) return false; + + foreach (var label in labels) + { + string value = label.Prefix + (label.ParamId == (int)BuiltInParameter.DATUM_TEXT ? name : elevation) + label.Suffix; + double height = label.Height * FeetToMillimetres; + double cap = document.RawData.TitleBlockCapHeightsFeet?.GetValueOrDefault(label.AttrId) ?? 0; + double size = SheetComposer.SymbolLabelTextSize(font, height, cap); + double width = label.Width * FeetToMillimetres; + bool wrap = label.Wrap && width > 0 && page.MeasureText(value, size) > width; + var lines = PlanPrinter.WrapPlanNoteText(page, value, size, width, wrap); + bool opaque = document.RawData.OpaqueSymbolLabelStyles?.Contains(label.AttrId) == true; + bool useArialLayout = document.RawData.RegularArialSymbolLabelStyles?.Contains(label.AttrId) == true + && font.Name.Equals("Arial", StringComparison.OrdinalIgnoreCase); + SheetComposer.DrawTitleBlockText(page, lines, x + label.Ox * FeetToMillimetres, + y + label.Oy * FeetToMillimetres, size, height * lines.Count, label.Flags, + label.Bx, label.By, label.Hx, label.Hy, opaque, useArialLayout); + } + return true; + } + + internal static List<(double X, double Y)> DatumCircle(double x, double y, double radius, int count) + { + var circle = new List<(double X, double Y)>(count); + for (int i = 0; i < count; i++) + { + double a = i * 2 * Math.PI / count; + circle.Add((x + radius * Math.Cos(a), y + radius * Math.Sin(a))); + } + return circle; + } + + internal static void DrawDatumDashes(PdfPage page, double x1, double y1, double x2, double y2, + double[] pattern, double width = 0.1, bool roundCaps = false) + { + double dx = x2 - x1, dy = y2 - y1; + double length = Math.Sqrt(dx * dx + dy * dy), period = pattern.Sum(); + if (!(length > 0)) return; + int cycles = period > 0 ? (int)Math.Floor(length / period) : 0; + if (cycles <= 0) + { + Stroke(0, length); + return; + } + // Revit balances the two end dashes around the full-length interior dashes. + double endDash = (length - cycles * period + pattern[0]) / 2; + Stroke(0, endDash); + double cursor = endDash; + for (int repeat = 0; repeat < cycles; repeat++) + { + for (int i = 1; i < pattern.Length; i++) + { + double next = cursor + pattern[i]; + if (i % 2 == 0) Stroke(cursor, next); + cursor = next; + } + if (repeat + 1 < cycles) + { + Stroke(cursor, cursor + pattern[0]); + cursor += pattern[0]; + } + } + Stroke(length - endDash, length); + + void Stroke(double from, double to) + { + var a = (X: x1 + from * dx / length, Y: y1 + from * dy / length); + var b = (X: x1 + to * dx / length, Y: y1 + to * dy / length); + if (roundCaps) page.DrawRoundDashedPolyline([a, b], width, []); + else page.DrawLine(a.X, a.Y, b.X, b.Y, width); + } + } } diff --git a/src/RvtIO/Print/FillHatch.cs b/src/RvtIO/Print/FillHatch.cs index a29b254e..8deb69e1 100644 --- a/src/RvtIO/Print/FillHatch.cs +++ b/src/RvtIO/Print/FillHatch.cs @@ -1,3 +1,4 @@ +using RvtIO.Model; using RvtIO.Parsing; using RvtIO.Pdf; @@ -8,57 +9,162 @@ internal static class FillHatch { private const double FeetToMillimetres = 304.8; + internal sealed record ModelGrid(double X, double Y, double Angle, double Spacing, + double Shift = 0, double[]? Segments = null); + + // shortcut: a single continuous model grid with an authored face placement. + internal static ModelGrid? ProjectModelGrid(RvtDocument document, GeoFace face, + Func inView) + { + if (face.ModelPattern is not { } placement + || document.RawData.FillPatterns?.TryGetValue(placement.PatternId, out var pattern) != true + || pattern.Grids is not [{ Target: 1, Segments.Length: 0, Offset: > 0 } grid]) return null; + return ProjectGrid(placement, grid, inView); + } + + internal static IReadOnlyList? ProjectDashedModelGrids(RvtDocument document, GeoFace face, + Func inView) + { + if (face.ModelPattern is not { } placement + || document.RawData.FillPatterns?.TryGetValue(placement.PatternId, out var pattern) != true + || pattern.Grids.Count == 0 + || !pattern.Grids.All(grid => grid is { Target: 1, Orientation: 0, Segments.Length: > 0 })) return null; + var grids = new List(pattern.Grids.Count); + foreach (var grid in pattern.Grids) + { + if (ProjectGrid(placement, grid, inView) is not { } projected) return null; + grids.Add(projected); + } + return grids; + } + + private static ModelGrid? ProjectGrid(RvtIO.Internal.ModelFacePattern placement, + TfBlockDeserializer.PatternGrid grid, Func inView) + { + var (ax, ay) = inView(placement.Origin); + var (ux, uy) = inView(placement.U); + var (vx, vy) = inView(placement.V); + double cos = Math.Cos(grid.Angle), sin = Math.Sin(grid.Angle); + double dx = cos * ux + sin * vx, dy = cos * uy + sin * vy; + double length = Math.Sqrt(dx * dx + dy * dy); + double nx = -sin * ux + cos * vx, ny = -sin * uy + cos * vy; + double signedSpacing = (dx * ny - dy * nx) / length * grid.Offset; + double spacing = Math.Abs(signedSpacing); + double x = ax + grid.OriginX * ux + grid.OriginY * vx; + double y = ay + grid.OriginX * uy + grid.OriginY * vy; + if (!double.IsFinite(spacing) || spacing <= 1e-6 || !double.IsFinite(x) || !double.IsFinite(y)) return null; + double angle = Math.Atan2(dy, dx); + if (grid.Segments.Length == 0) return new ModelGrid(x, y, angle, spacing); + + double shift = grid.Shift * length + grid.Offset * (dx * nx + dy * ny) / length; + if (signedSpacing < 0) shift = -shift; + var segments = grid.Segments.Select(segment => segment * length).ToArray(); + double period = segments.Sum(); + return double.IsFinite(shift) && double.IsFinite(period) + && period > 0 && segments.All(segment => segment >= 0) + ? new ModelGrid(x, y, angle, spacing, shift, segments) : null; + } + /// Draws the dashes of clipped to . The polygon, /// the anchor and the pen width are in page millimetres; the pattern's own lengths are feet, read as drafting /// pattern paper lengths (they do not scale with the view). internal static void Draw(PdfPage page, IReadOnlyList<(double X, double Y)> polygon, IReadOnlyList grids, double anchorX, double anchorY, double width) { - if (polygon.Count < 3) return; + foreach (var line in Strokes([polygon], grids, anchorX, anchorY)) + page.DrawLine(line.X1, line.Y1, line.X2, line.Y2, width); + } + + internal static List? DraftingTiles(IReadOnlyList grids, + double anchorX, double anchorY, double width) + { + var tiles = new List(); foreach (var grid in grids) { if (grid.Segments.Length == 0) continue; + double spacing = Math.Abs(grid.Offset) * FeetToMillimetres; + double shift = (grid.Offset < 0 ? -grid.Shift : grid.Shift) * FeetToMillimetres; + double x = anchorX + grid.OriginX * FeetToMillimetres, y = anchorY + grid.OriginY * FeetToMillimetres; + var segments = grid.Segments.Select(segment => segment * FeetToMillimetres).ToArray(); + double period = segments.Sum(); + if (!double.IsFinite(spacing) || spacing <= width || !double.IsFinite(shift) + || !double.IsFinite(x) || !double.IsFinite(y) || !double.IsFinite(grid.Angle) + || !double.IsFinite(period) || period <= 0 || segments.Any(segment => segment < 0)) return null; + tiles.Add(new(spacing, grid.Angle, x, y, width, shift, segments)); + } + return tiles; + } + + internal static IEnumerable<(double X1, double Y1, double X2, double Y2)> Strokes( + IEnumerable> polygons, + IReadOnlyList grids, double anchorX, double anchorY, + bool continuousLines = false) + { + foreach (var grid in grids) + { + bool continuous = grid.Segments.Length == 0; + if (continuous && !continuousLines) continue; double dx = Math.Cos(grid.Angle), dy = Math.Sin(grid.Angle); double nx = -dy, ny = dx; double offset = grid.Offset * FeetToMillimetres; double shift = grid.Shift * FeetToMillimetres; double period = 0; foreach (double segment in grid.Segments) period += segment * FeetToMillimetres; - if (Math.Abs(offset) < 1e-9 || period <= 0) continue; + if (Math.Abs(offset) < 1e-9 || !continuous && period <= 0) continue; var segments = new double[grid.Segments.Length]; for (int i = 0; i < segments.Length; i++) segments[i] = grid.Segments[i] * FeetToMillimetres; double ox = anchorX + grid.OriginX * FeetToMillimetres; double oy = anchorY + grid.OriginY * FeetToMillimetres; - double minK = double.MaxValue, maxK = double.MinValue; - foreach (var point in polygon) + var rows = new SortedDictionary>(); + foreach (var polygon in polygons) { - double k = ((point.X - ox) * nx + (point.Y - oy) * ny) / offset; - if (k < minK) minK = k; - if (k > maxK) maxK = k; + if (polygon.Count < 3) continue; + double minK = double.MaxValue, maxK = double.MinValue; + foreach (var point in polygon) + { + double k = ((point.X - ox) * nx + (point.Y - oy) * ny) / offset; + if (k < minK) minK = k; + if (k > maxK) maxK = k; + } + + for (int k = (int)Math.Floor(minK); k <= (int)Math.Ceiling(maxK); k++) + { + double bx = ox + k * (shift * dx + offset * nx); + double by = oy + k * (shift * dy + offset * ny); + var crossings = new List(8); + for (int i = 0; i < polygon.Count; i++) + { + var a = polygon[i]; + var b = polygon[(i + 1) % polygon.Count]; + double ex = b.X - a.X, ey = b.Y - a.Y; + double den = dx * ey - dy * ex; + if (Math.Abs(den) < 1e-12) continue; + double t = ((a.X - bx) * ey - (a.Y - by) * ex) / den; + double u = ((bx - a.X) * dy - (by - a.Y) * dx) / -den; + if (u >= -1e-9 && u <= 1 + 1e-9) crossings.Add(t); + } + crossings.Sort(); + for (int i = 0; i + 1 < crossings.Count; i += 2) + { + if (crossings[i + 1] - crossings[i] < 1e-9) continue; + if (!rows.TryGetValue(k, out var intervals)) rows[k] = intervals = []; + intervals.Add((crossings[i], crossings[i + 1])); + } + } } - for (int k = (int)Math.Floor(minK); k <= (int)Math.Ceiling(maxK); k++) + foreach (var (k, intervals) in rows) { double bx = ox + k * (shift * dx + offset * nx); double by = oy + k * (shift * dy + offset * ny); - var crossings = new List(8); - for (int i = 0; i < polygon.Count; i++) + foreach (var (ta, tb) in UnionIntervals(intervals)) { - var a = polygon[i]; - var b = polygon[(i + 1) % polygon.Count]; - double ex = b.X - a.X, ey = b.Y - a.Y; - double den = dx * ey - dy * ex; - if (Math.Abs(den) < 1e-12) continue; - double t = ((a.X - bx) * ey - (a.Y - by) * ex) / den; - double u = ((bx - a.X) * dy - (by - a.Y) * dx) / -den; - if (u >= -1e-9 && u <= 1 + 1e-9) crossings.Add(t); - } - crossings.Sort(); - for (int i = 0; i + 1 < crossings.Count; i += 2) - { - double ta = crossings[i], tb = crossings[i + 1]; - if (tb - ta < 1e-9) continue; + if (continuous) + { + yield return (bx + ta * dx, by + ta * dy, bx + tb * dx, by + tb * dy); + continue; + } for (double start = Math.Floor(ta / period) * period; start < tb; start += period) { double cursor = start; @@ -70,7 +176,7 @@ internal static void Draw(PdfPage page, IReadOnlyList<(double X, double Y)> poly { double from = Math.Max(cursor, ta), to = Math.Min(cursor + segment, tb); if (to > from + 1e-9) - page.DrawLine(bx + from * dx, by + from * dy, bx + to * dx, by + to * dy, width); + yield return (bx + from * dx, by + from * dy, bx + to * dx, by + to * dy); } cursor += segment; } @@ -79,4 +185,22 @@ internal static void Draw(PdfPage page, IReadOnlyList<(double X, double Y)> poly } } } + + // Terrain triangles may overlap or share a boundary. Ink each grid's covered intervals once. + private static IEnumerable<(double From, double To)> UnionIntervals(List<(double From, double To)> intervals) + { + intervals.Sort((a, b) => a.From.CompareTo(b.From)); + var (from, to) = intervals[0]; + for (int i = 1; i < intervals.Count; i++) + { + var (nextFrom, nextTo) = intervals[i]; + if (nextFrom > to + 1e-9) + { + yield return (from, to); + from = nextFrom; + } + to = Math.Max(to, nextTo); + } + yield return (from, to); + } } diff --git a/src/RvtIO/Print/LinePatterns.cs b/src/RvtIO/Print/LinePatterns.cs index 1544af94..6f75143c 100644 --- a/src/RvtIO/Print/LinePatterns.cs +++ b/src/RvtIO/Print/LinePatterns.cs @@ -29,19 +29,32 @@ internal static bool TryGetGridDashes(RvtDocument document, out double[] dashes) break; } } - if (centerCategory == null) return false; + return centerCategory is int categoryId && TryGetDashes(document, categoryId, out dashes); + } + + internal static bool TryGetDashes(RvtDocument document, int categoryId, out double[] dashes) + { + dashes = []; + var info = document.RawData; + if (info.GraphicsStylePens == null || info.LinePatterns == null) return false; int patternId = 0; bool found = false; foreach (var style in info.GraphicsStylePens.Values) { - if (style.CategoryId == centerCategory && style.OwnerId == -1 && style.GStyleType == 1) + if (style.CategoryId == categoryId && style.OwnerId == -1 && style.GStyleType == 1) { patternId = style.LinePatternId; found = true; break; } } - if (!found || patternId <= 0 || !info.LinePatterns.TryGetValue(patternId, out var pattern)) + return found && TryGetPatternDashes(document, patternId, out dashes); + } + + internal static bool TryGetPatternDashes(RvtDocument document, int patternId, out double[] dashes) + { + dashes = []; + if (patternId <= 0 || document.RawData.LinePatterns?.TryGetValue(patternId, out var pattern) != true) return false; var points = new List(); var ink = new List(); @@ -59,4 +72,23 @@ internal static bool TryGetGridDashes(RvtDocument document, out double[] dashes) dashes = [.. points.Select(v => Math.Round(v, 3))]; return true; } + + internal static double[] FitEndpointDashes(double lengthPoints, double[] dashes) + { + if (dashes.Length < 2 || dashes.Length % 2 != 0 || !double.IsFinite(lengthPoints) + || dashes.Any(value => !(value > 0 && double.IsFinite(value)))) return dashes; + double period = dashes.Sum(); + double repeats = Math.Floor(lengthPoints / period); + if (repeats < 1) return []; + if (repeats * dashes.Length + 2 > 4096) return dashes; + + // Keep the interior sequence and split the remaining length equally between the terminal dashes. + double terminal = (lengthPoints - repeats * period + dashes[0]) / 2; + var fitted = new double[(int)repeats * dashes.Length + 2]; + for (int i = 0; i < fitted.Length - 2; i += dashes.Length) + Array.Copy(dashes, 0, fitted, i, dashes.Length); + fitted[0] = fitted[^2] = terminal; + fitted[^1] = dashes[1]; + return fitted; + } } diff --git a/src/RvtIO/Print/PenWidths.cs b/src/RvtIO/Print/PenWidths.cs index 5b53e923..bf00380d 100644 --- a/src/RvtIO/Print/PenWidths.cs +++ b/src/RvtIO/Print/PenWidths.cs @@ -13,8 +13,11 @@ internal static class PenWidths /// The pen number a category's cut (isCut) or projection lines use, from the document's /// Object Styles. False when the category has no style for that kind. internal static bool TryGetPenNumber(RvtDocument document, int categoryId, bool isCut, out int pen) + => TryGetStyle(document, categoryId, isCut, out pen, out _); + + internal static bool TryGetStyle(RvtDocument document, int categoryId, bool isCut, out int pen, out int color) { - pen = 0; + pen = color = 0; var styles = document.RawData.GraphicsStylePens; if (styles == null) return false; int kind = isCut ? 2 : 1; @@ -23,6 +26,7 @@ internal static bool TryGetPenNumber(RvtDocument document, int categoryId, bool if (style.CategoryId == categoryId && style.OwnerId == -1 && style.GStyleType == kind) { pen = style.PenNumber; + color = style.Color; return true; } } @@ -35,22 +39,9 @@ internal static bool TryGetWidth(RvtDocument document, int categoryId, bool isCu { widthMillimetres = 0; var info = document.RawData; - if (info.GraphicsStylePens == null || info.PenWidthTable == null) return false; - if (scaleDenominator <= 0) return false; - int kind = isCut ? 2 : 1; - int pen = 0; - bool found = false; - foreach (var style in info.GraphicsStylePens.Values) - { - if (style.CategoryId == categoryId && style.OwnerId == -1 && style.GStyleType == kind) - { - pen = style.PenNumber; - found = true; - break; - } - } - if (!found) return false; - return TryPenWidth(info.PenWidthTable.Value, pen, scaleDenominator, out widthMillimetres); + return info.PenWidthTable is { } table && scaleDenominator > 0 + && TryGetPenNumber(document, categoryId, isCut, out int pen) + && TryPenWidth(table, pen, scaleDenominator, out widthMillimetres); } /// Width in millimetres a model pen prints at for a view scale denominator. False when the pen is out diff --git a/src/RvtIO/Print/PlanElevationMarks.cs b/src/RvtIO/Print/PlanElevationMarks.cs new file mode 100644 index 00000000..2dbc93ee --- /dev/null +++ b/src/RvtIO/Print/PlanElevationMarks.cs @@ -0,0 +1,94 @@ +using RvtIO.BuiltIns; +using RvtIO.Model; +using RvtIO.Pdf; + +namespace RvtIO.Print; + +internal static class PlanElevationMarks +{ + private const double FeetToMillimetres = 304.8; + + internal static void Draw(PdfPage page, RvtDocument document, Element plan, ViewCropFrame crop, + double scale, double sheetX, double sheetY) + { + if (document.RawData.PlanElevationMarks is not { Count: > 0 } marks + || crop.Right is not [1, 0, 0] || crop.Up is not [0, 1, 0] + || document.RawData.PlanViewRanges?.GetValueOrDefault(plan.Id) is not + ({ Length: > 0 } offsets, { Length: > 0 } levels) + || document.GetElement(levels[0])?.LookupParameter(BuiltInParameter.LEVEL_ELEV)?.Value is not double level) + return; + + double cut = level + offsets[0]; + if (!double.IsFinite(cut)) return; + var hidden = document.RawData.ViewHiddenElements?.GetValueOrDefault(plan.Id); + double pen = PenWidths.TryGetPenNumber(document, (int)BuiltInCategory.OST_ElevationMarks, false, out int weight) + && PenWidths.TryAnnotationWidth(document, weight, out double width) ? width : 0.1; + foreach (var mark in marks) + { + double u = mark.X - crop.OriginX, v = mark.Y - crop.OriginY; + if (u < crop.X0 || u > crop.X1 || v < crop.Y0 || v > crop.Y1 || hidden?.Contains(mark.Id) == true + || document.GetElement(mark.BodyId) is not + { FamilyName: "M_Elevation Mark Body_Circle-12mm", BoundingBox: { Length: 6 } box }) + continue; + + double r = (box[3] - box[0]) * FeetToMillimetres / 2; + if (!(r is > 0 and <= 100) || Math.Abs(box[3] - box[0] - box[4] + box[1]) > 1e-6) continue; + double x = sheetX + u * FeetToMillimetres / scale; + double y = sheetY + v * FeetToMillimetres / scale; + double tipLength = r / Math.Cos(mark.ArrowHalfAngle); + if (plan.ViewAnnotationCropActive == true) + { + var (left, right, top, bottom) = plan.ViewAnnotationCrop ?? (0, 0, 0, 0); + double margin = tipLength * scale / FeetToMillimetres; + if (u - margin < crop.X0 - left * scale || u + margin > crop.X1 + right * scale + || v - margin < crop.Y0 - bottom * scale || v + margin > crop.Y1 + top * scale) + continue; + } + + if (hidden?.Contains(mark.ArrowId) == true || hidden?.Contains(mark.ViewId) == true + || 1 / scale < mark.CoarserScale || document.GetElement(mark.ViewId) is not + { ViewDirection: [var dx, var dy, 0], ViewCrop: { } elevationCrop } + || elevationCrop.Up is not [0, 0, 1] + || cut < elevationCrop.OriginZ + elevationCrop.Y0 || cut > elevationCrop.OriginZ + elevationCrop.Y1 + || document.GetElement(mark.ArrowSymbolId)?.FamilyName != "M_Elevation Mark Pointer_Circle") + continue; + double length = Math.Sqrt(dx * dx + dy * dy); + if (!(length > 0) || !double.IsFinite(length)) continue; + dx /= length; + dy /= length; + + var viewport = document.Elements.FirstOrDefault(element => element.ViewportViewId == mark.ViewId); + string detail = viewport?.LookupParameter(BuiltInParameter.VIEWPORT_DETAIL_NUMBER)?.Value as string ?? "-"; + string number = viewport?.OwnerViewId is int sheetId + ? document.GetElement(sheetId)?.LookupParameter(BuiltInParameter.SHEET_NUMBER)?.Value as string ?? "-" : "-"; + page.DrawPolyline(ElevationPrinter.DatumCircle(x, y, r, 25), pen, true); + DrawLabel(page, document, mark.BodyId, BuiltInParameter.VIEWER_SHEET_NUMBER, number, x, y, 0, 1); + + double direction = Math.Atan2(dy, dx); + var points = new List<(double X, double Y)> { (x + dx * tipLength, y + dy * tipLength) }; + for (int i = 0; i <= 12; i++) + { + double a = direction + mark.ArrowHalfAngle * (2.0 * i / 12 - 1); + points.Add((x + r * Math.Cos(a), y + r * Math.Sin(a))); + } + page.DrawPolyline(points, pen, true, mark.Filled ? 0 : null); + DrawLabel(page, document, mark.ArrowSymbolId, BuiltInParameter.VIEWER_DETAIL_NUMBER, detail, x, y, dx, dy); + } + } + + private static void DrawLabel(PdfPage page, RvtDocument document, int symbolId, BuiltInParameter parameter, + string value, double x, double y, double dx, double dy) + { + var label = document.RawData.TitleBlockLabels?.GetValueOrDefault(symbolId) + ?.FirstOrDefault(candidate => candidate.ParamId == (int)parameter); + if (label is not { Bx: 1, By: 0, Hx: 0, Hy: 1 } || page.Owner.Font is not { } font) return; + double cap = document.RawData.TitleBlockCapHeightsFeet?.GetValueOrDefault(label.AttrId) ?? 0; + double height = label.Height * FeetToMillimetres; + double size = SheetComposer.SymbolLabelTextSize(font, height, cap); + bool opaque = document.RawData.OpaqueSymbolLabelStyles?.Contains(label.AttrId) == true; + SheetComposer.DrawTitleBlockText(page, [label.Prefix + value + label.Suffix], + x + (label.Ox * dy + label.Oy * dx) * FeetToMillimetres, + y + (-label.Ox * dx + label.Oy * dy) * FeetToMillimetres, + size, height, label.Flags, 1, 0, 0, 1, opaque); + } +} diff --git a/src/RvtIO/Print/PlanPrinter.Columns.cs b/src/RvtIO/Print/PlanPrinter.Columns.cs new file mode 100644 index 00000000..c88360d4 --- /dev/null +++ b/src/RvtIO/Print/PlanPrinter.Columns.cs @@ -0,0 +1,91 @@ +using RvtIO.BuiltIns; +using RvtIO.Model; +using RvtIO.Parsing; +using RvtIO.Pdf; + +namespace RvtIO.Print; + +public static partial class PlanPrinter +{ + internal sealed record ColumnProfile(List<(double X, double Y)> Ring, + (double X, double Y, double Radius)? Circle, int CategoryId, int MaterialId); + + private static ColumnProfile? CutColumnProfile(RvtDocument document, Element column, double cut) + { + if (column.Geometry is not { Faces.Count: > 0 } geometry + || geometry.Faces.Any(face => face.CurvedSurface || face.OuterVertices is not { Count: >= 3 } vertices + || vertices.Any(p => p.Length != 3 || !p.All(double.IsFinite)) + || face.InnerLoops is { Count: > 0 } || face.InnerVertices is { Count: > 0 })) + return null; + + var rings = ElevationPrinter.ClosedSectionRings(geometry.Faces, [0, 0, cut * FeetToMillimetres], + [0, 0, 1], [1, 0, 0], [0, 1, 0], requireClosed: true).Take(2).ToArray(); + if (rings is not [var ring]) return null; + + int materialId = column.LookupParameter(BuiltInParameter.STRUCTURAL_MATERIAL_PARAM)?.Value is int material + ? material : 0; + return new(ring, MatchColumnCylinder(document, geometry, cut, ring), column.CategoryId.GetValueOrDefault(), materialId); + } + + private static (double X, double Y, double Radius)? MatchColumnCylinder( + RvtDocument document, GeometryData geometry, double worldCut, List<(double X, double Y)> ring) + { + if (geometry.Instances is not [{ Transform: { Length: 12 } transform } instance] + || !ElementBuilder.IsRigidPlacement(transform) || Math.Abs(Math.Abs(transform[8]) - 1) > 1e-9 + || document.GetElement(instance.SymbolId)?.Geometry is not { } symbol) + return null; + + double localCut = (worldCut - transform[11]) / transform[8]; + foreach (var face in symbol.Faces) + { + if (face.AnalyticCylinderRadius is not (> 0 and < double.PositiveInfinity) + || face.AnalyticCylinderAxis is not { Length: 3 } axis + || Math.Abs(axis[0]) > 1e-9 || Math.Abs(axis[1]) > 1e-9 || Math.Abs(Math.Abs(axis[2]) - 1) > 1e-9 + || face.AnalyticCylinderOrigin is not { Length: 3 } origin || !origin.All(double.IsFinite) + || face.OuterVertices is not { Count: >= 3 } vertices || vertices.Any(p => p.Length != 3 || !double.IsFinite(p[2])) + || localCut < vertices.Min(p => p[2]) || localCut > vertices.Max(p => p[2])) + continue; + + double x = (transform[9] + origin[0] * transform[0] + origin[1] * transform[3]) * FeetToMillimetres; + double y = (transform[10] + origin[0] * transform[1] + origin[1] * transform[4]) * FeetToMillimetres; + double radius = face.AnalyticCylinderRadius * FeetToMillimetres; + // Require the placed cut to agree with the analytic surface within the ring's join resolution. + if (ring.All(p => Math.Abs(Math.Sqrt((p.X - x) * (p.X - x) + (p.Y - y) * (p.Y - y)) - radius) <= 0.1)) + return (x, y, radius); + } + return null; + } + + private static void DrawColumns(PdfPage page, RvtDocument? document, PlanContent content, double scale, double width, + Func toX, Func toY, (double X0, double Y0, double X1, double Y1)? clip) + { + var white = new PdfColor(1, 1, 1); + for (int i = 0; i < content.Columns.Count; i++) + { + if (content.ColumnProfiles?.GetValueOrDefault(i) is not { } profile) + { + var column = content.Columns[i]; + page.DrawRectangle(toX(column.X), toY(column.Y), column.Width / scale, column.Height / scale, width, 1); + continue; + } + + double cutWidth = document != null && PenWidths.TryGetWidth(document, profile.CategoryId, true, + (int)Math.Round(scale), out double savedWidth) ? savedWidth : width; + if (profile.Circle is { } circle) + { + if (clip is { } frame) + page.BeginClip(toX(frame.X0), toY(frame.Y0), toX(frame.X1) - toX(frame.X0), toY(frame.Y1) - toY(frame.Y0)); + page.DrawFilledCircle(toX(circle.X), toY(circle.Y), circle.Radius / scale, cutWidth, white, new PdfColor(0, 0, 0)); + if (clip != null) page.EndClip(); + } + else DrawClippedOutline(page, profile.Ring, toX, toY, cutWidth, white, clip); + + if (document == null || DetailAnnotations.CutGrids(document, profile.MaterialId) is not { } grids) + continue; + var hatch = clip is { } bounds + ? ElevationPrinter.ClipToWindow(profile.Ring, bounds.X0, bounds.X1, bounds.Y0, bounds.Y1) : profile.Ring; + if (hatch.Count >= 3) + FillHatch.Draw(page, hatch.Select(p => (toX(p.X), toY(p.Y))).ToList(), grids, toX(0), toY(0), 0.1); + } + } +} diff --git a/src/RvtIO/Print/PlanPrinter.Datums.cs b/src/RvtIO/Print/PlanPrinter.Datums.cs new file mode 100644 index 00000000..79eaf999 --- /dev/null +++ b/src/RvtIO/Print/PlanPrinter.Datums.cs @@ -0,0 +1,93 @@ +using RvtIO.BuiltIns; +using RvtIO.Model; +using RvtIO.Parsing; +using RvtIO.Pdf; + +namespace RvtIO.Print; + +public static partial class PlanPrinter +{ + internal sealed record PlanGrid(int TypeId, string Name, double Radius, + (double X, double Y) Start, (double X, double Y) End, + bool StartBubble, bool EndBubble, TfBlockDeserializer.DatumLeader? StartLeader, + TfBlockDeserializer.DatumLeader? EndLeader); + + internal static List? CollectPlanGrids(RvtDocument document, Element view, ViewCropFrame crop, double scale) + { + if (!crop.Right.SequenceEqual(new double[] { 1, 0, 0 }) || !crop.Up.SequenceEqual(new double[] { 0, 1, 0 }) + || document.RawData.DatumExtents?.GetValueOrDefault(view.Id) is not { Normal: [0, 0, -1] } extents) + return null; + var box = SheetComposer.CropContentRect(crop); + var grids = new List(); + foreach (var element in document.Elements) + { + if (element.CategoryId != (int)BuiltInCategory.OST_Grids + || element.Location is not { CurveType: "Line", StartPoint.Length: >= 2, EndPoint.Length: >= 2 } line) + continue; + double x0 = line.StartPoint[0] * FeetToMillimetres, y0 = line.StartPoint[1] * FeetToMillimetres; + double x1 = line.EndPoint[0] * FeetToMillimetres, y1 = line.EndPoint[1] * FeetToMillimetres; + if (!ElevationPrinter.ClipSegment(x0, y0, x1, y1, box.X0, box.Y0, box.X1, box.Y1, + out _, out _, out _, out _)) continue; + var extent = extents.Datums.GetValueOrDefault(element.Id); + byte flags = extent?.Overrides ?? 0; + // shortcut: use the fallback plan drawing until per-view 2D endpoints are supported. + if ((flags & 0xF0) != 0 || (flags & 3) == 3 || ((flags >> 2) & 3) == 3 + || document.RawData.DatumHeads?.GetValueOrDefault(element.TypeId) is not + { EndSegmentLength: > 0 and < 1, BubbleAtEnd1: bool endBubble, BubbleAtEnd2: bool startBubble } head + || ElevationPrinter.CircleHeadRadius(document, head.SymbolId, "M_Grid Head - Circle") is not double radius) + return null; + + double margin = head.EndSegmentLength.Value * FeetToMillimetres * scale; + if (!ElevationPrinter.ClipSegment(x0, y0, x1, y1, box.X0 - margin, box.Y0 - margin, + box.X1 + margin, box.Y1 + margin, out x0, out y0, out x1, out y1)) continue; + grids.Add(new PlanGrid(element.TypeId, element.Name ?? "", radius, (x0, y0), (x1, y1), + BubbleVisible((flags >> 2) & 3, startBubble), BubbleVisible(flags & 3, endBubble), + extent?.BubbleLeader, extent?.FreeEndLeader)); + } + return grids; + + static bool BubbleVisible(int flag, bool visible) => flag == 0 ? visible : flag == 1; + } + + internal static void DrawPlanGrids(PdfPage page, RvtDocument document, List grids, + PlanContent content, double scale, double originX, double originY) + { + const double ptToMm = 25.4 / 72; + double ToX(double x) => (x - content.MinX) / scale + originX; + double ToY(double y) => (y - content.MinY) / scale + originY; + foreach (var grid in grids) + { + double dx = grid.End.X - grid.Start.X, dy = grid.End.Y - grid.Start.Y; + double length = Math.Sqrt(dx * dx + dy * dy); + if (!(length > 0)) continue; + dx /= length; + dy /= length; + var start = DrawEnd(grid.Start, -1, grid.StartBubble, grid.StartLeader); + var end = DrawEnd(grid.End, 1, grid.EndBubble, grid.EndLeader); + var pattern = document.RawData.GridCenterCategories?.GetValueOrDefault(grid.TypeId) is int category + && LinePatterns.TryGetDashes(document, category, out var dashes) + ? dashes.Select(pt => pt * ptToMm).ToArray() : []; + ElevationPrinter.DrawDatumDashes(page, start.X, start.Y, end.X, end.Y, pattern); + + (double X, double Y) DrawEnd((double X, double Y) point, int side, bool show, + TfBlockDeserializer.DatumLeader? leader) + { + var endOfLine = (X: ToX(point.X), Y: ToY(point.Y)); + if (!show) return endOfLine; + var anchor = endOfLine; + if (leader != null) + { + endOfLine = (ToX(leader.End[0] * FeetToMillimetres), ToY(leader.End[1] * FeetToMillimetres)); + anchor = (ToX(leader.Anchor[0] * FeetToMillimetres), ToY(leader.Anchor[1] * FeetToMillimetres)); + double x = ToX(leader.Elbow[0] * FeetToMillimetres), y = ToY(leader.Elbow[1] * FeetToMillimetres); + page.DrawLine(endOfLine.X, endOfLine.Y, x, y, 0.1); + page.DrawLine(x, y, anchor.X, anchor.Y, 0.1); + } + double cx = anchor.X + side * dx * grid.Radius, cy = anchor.Y + side * dy * grid.Radius; + page.DrawPolyline(ElevationPrinter.DatumCircle(cx, cy, grid.Radius, 25), 0.1, true); + page.DrawText(grid.Name, cx, cy - 2.17, 18 * ptToMm, PdfTextAlignment.Center); + return endOfLine; + } + } + } +} diff --git a/src/RvtIO/Print/PlanPrinter.Dimensions.cs b/src/RvtIO/Print/PlanPrinter.Dimensions.cs new file mode 100644 index 00000000..3df32d17 --- /dev/null +++ b/src/RvtIO/Print/PlanPrinter.Dimensions.cs @@ -0,0 +1,93 @@ +using RvtIO.Compact; +using RvtIO.Ifc; +using RvtIO.Model; +using RvtIO.Pdf; + +namespace RvtIO.Print; + +public static partial class PlanPrinter +{ + internal sealed record PrintedDimension(RevitFileInfo.PlanDimension Dimension, + RevitFileInfo.PlanDimensionStyle Style, string[] Labels, double LineWidth, double TickWidth); + + internal static List CollectPlanDimensions(RvtDocument document, int viewId, ViewCropFrame crop) + { + var data = document.RawData; + if (!crop.Right.SequenceEqual(new double[] { 1, 0, 0 }) || !crop.Up.SequenceEqual(new double[] { 0, 1, 0 }) + || data.PlanDimensions?.GetValueOrDefault(viewId) is not { Count: > 0 } dimensions + || data.PlanDimensionStyles == null || data.SerializedFormatSettings is not { } formatting) + return []; + var result = new List(dimensions.Count); + foreach (var dimension in dimensions) + { + var d = dimension.Direction; + if (Math.Abs(d[2]) > 1e-8 || Math.Abs(d[0] * d[0] + d[1] * d[1] - 1) > 1e-8 + || !data.PlanDimensionStyles.TryGetValue(dimension.StyleId, out var style)) + continue; + var labels = dimension.Values.Select(value => + CompactValueFormatter.Format(value, IfcNumericUnitPlan.LengthSpecName, formatting)).ToArray(); + if (labels.Any(string.IsNullOrEmpty)) continue; + result.Add(new(dimension, style, labels.Select(label => label!).ToArray(), + PlanAnnotationWidth(document, style.LineCategory, 0.1), PlanAnnotationWidth(document, style.TickCategory, 0.5))); + } + return result; + } + + internal static double PlanAnnotationWidth(RvtDocument document, int category, double fallback) + { + if (document.RawData.GraphicsStylePens?.Values.FirstOrDefault(pen => + pen.CategoryId == category && pen.GStyleType == 1) is { PenNumber: > 0 } pen + && PenWidths.TryAnnotationWidth(document, pen.PenNumber, out double width)) + return width; + return fallback; + } + + internal static void DrawPlanDimensions(PdfPage page, List dimensions, PlanContent content, + double scale, double originX, double originY) + { + double modelToPaper = FeetToMillimetres / scale; + double X(double feet) => feet * modelToPaper - content.MinX / scale + originX; + double Y(double feet) => feet * modelToPaper - content.MinY / scale + originY; + foreach (var printed in dimensions) + { + var (dimension, style, labels, lineWidth, tickWidth) = printed; + double dx = dimension.Direction[0], dy = dimension.Direction[1]; + double ox = dimension.Origin[0], oy = dimension.Origin[1]; + var along = dimension.References.Select(point => ((point[0] - ox) * dx + (point[1] - oy) * dy) + * modelToPaper).ToArray(); + double first = along[0], last = along[^1]; + double extension = style.LineExtensionFeet * FeetToMillimetres; + Line(Math.Min(first, last) - extension, 0, Math.Max(first, last) + extension, 0, lineWidth); + double tick = style.TickSizeFeet * FeetToMillimetres / 2; + for (int i = 0; i < along.Length; i++) + { + var reference = dimension.References[i]; + double distance = (-(reference[0] - ox) * dy + (reference[1] - oy) * dx) * modelToPaper; + double side = Math.Sign(distance); + double gap = style.WitnessGapFeet * FeetToMillimetres; + Line(along[i], distance - side * gap, along[i], side * style.WitnessExtensionFeet * FeetToMillimetres, lineWidth); + Line(along[i] - tick, -tick, along[i] + tick, tick, tickWidth); + } + + if (page.Owner.Font is not { } font) continue; + double textHeight = style.TextHeightFeet * FeetToMillimetres + / (font.CapHeight > 0 ? (double)font.CapHeight / font.UnitsPerEm : 0.7); + double textGap = style.TextGapFeet * FeetToMillimetres - textHeight * font.Descent / font.UnitsPerEm; + double rotation = Math.Atan2(dy, dx) * 180 / Math.PI; + if (rotation < -89.999) { rotation += 180; textGap = -textGap; } + else if (rotation > 90.001) { rotation -= 180; textGap = -textGap; } + for (int i = 0; i < labels.Length; i++) + { + double middle = (along[i] + along[i + 1]) / 2; + page.DrawTextRotated(labels[i], X(ox) + middle * dx - textGap * dy, + Y(oy) + middle * dy + textGap * dx, textHeight, rotation, PdfTextAlignment.Center); + } + + void Line(double u0, double v0, double u1, double v1, double width) + { + page.DrawLine(X(ox) + u0 * dx - v0 * dy, Y(oy) + u0 * dy + v0 * dx, + X(ox) + u1 * dx - v1 * dy, Y(oy) + u1 * dy + v1 * dx, width); + } + } + } +} diff --git a/src/RvtIO/Print/PlanPrinter.DoorSymbols.cs b/src/RvtIO/Print/PlanPrinter.DoorSymbols.cs new file mode 100644 index 00000000..fb353fcf --- /dev/null +++ b/src/RvtIO/Print/PlanPrinter.DoorSymbols.cs @@ -0,0 +1,78 @@ +using RvtIO.BuiltIns; +using RvtIO.Internal; +using RvtIO.Pdf; + +namespace RvtIO.Print; + +public static partial class PlanPrinter +{ + private static double? PlanCutHeight(RvtDocument document, int viewId) + { + if (document.RawData.PlanViewRanges?.GetValueOrDefault(viewId) is not + ({ Length: > 0 } offsets, { Length: > 0 } levels) + || document.GetElement(levels[0])?.LookupParameter(BuiltInParameter.LEVEL_ELEV)?.Value is not double level) + return null; + double cut = level + offsets[0]; + return double.IsFinite(cut) ? cut : null; + } + + private static DoorPlanSymbol? SelectDoorPlanSymbol( + IReadOnlyList symbols, double[] matrix, double worldCut, double[]? bounds) + { + if (matrix.Length != 12 || !matrix.All(double.IsFinite) || !double.IsFinite(worldCut)) return null; + const double tolerance = 1e-9; + if (Math.Abs(matrix[6]) > tolerance || Math.Abs(matrix[7]) > tolerance + || Math.Abs(matrix[8] - 1) > tolerance + || Math.Abs(matrix[0] * matrix[0] + matrix[3] * matrix[3] - 1) > tolerance + || Math.Abs(matrix[1] * matrix[1] + matrix[4] * matrix[4] - 1) > tolerance + || Math.Abs(matrix[0] * matrix[1] + matrix[3] * matrix[4]) > tolerance) + return null; + + double localCut = worldCut - matrix[11]; + DoorPlanSymbol? found = null; + foreach (var symbol in symbols) + { + bool matches = symbol.CutRange is { } range + ? localCut >= range.Lo && localCut <= range.Hi + : bounds is { Length: 6 } && worldCut >= bounds[2] && worldCut <= bounds[5]; + if (!matches) continue; + if (found != null) return null; + found = symbol; + } + return found; + } + + private static void DrawDoorPlanSymbol(PdfPage page, DoorPlanSymbol symbol, double[] matrix, double scale, + Func toX, Func toY, (double X0, double Y0, double X1, double Y1)? clip) + { + (double X, double Y) Direction(double[] vector) => + (matrix[0] * vector[0] + matrix[1] * vector[1] + matrix[2] * vector[2], + matrix[3] * vector[0] + matrix[4] * vector[1] + matrix[5] * vector[2]); + foreach (var curve in symbol.Curves) + { + var c = Direction(curve.C); + var x = Direction(curve.X); + double cx = (c.X + matrix[9]) * FeetToMillimetres; + double cy = (c.Y + matrix[10]) * FeetToMillimetres; + if (curve.R > 0) + { + var y = Direction(curve.Y); + double orientation = Math.Sign(x.X * y.Y - x.Y * y.X); + double angle = Math.Atan2(x.Y, x.X); + page.DrawArc(toX(cx), toY(cy), curve.R * FeetToMillimetres / scale, + (angle + orientation * curve.T0) * 180 / Math.PI, + (angle + orientation * curve.T1) * 180 / Math.PI, 0.18); + continue; + } + + double x0 = cx + curve.T0 * x.X * FeetToMillimetres; + double y0 = cy + curve.T0 * x.Y * FeetToMillimetres; + double x1 = cx + curve.T1 * x.X * FeetToMillimetres; + double y1 = cy + curve.T1 * x.Y * FeetToMillimetres; + if (clip is { } bounds && !ElevationPrinter.ClipSegment(x0, y0, x1, y1, + bounds.X0, bounds.Y0, bounds.X1, bounds.Y1, out x0, out y0, out x1, out y1)) + continue; + page.DrawLine(toX(x0), toY(y0), toX(x1), toY(y1), 0.18); + } + } +} diff --git a/src/RvtIO/Print/PlanPrinter.FixtureProfiles.cs b/src/RvtIO/Print/PlanPrinter.FixtureProfiles.cs new file mode 100644 index 00000000..fc3e32ed --- /dev/null +++ b/src/RvtIO/Print/PlanPrinter.FixtureProfiles.cs @@ -0,0 +1,244 @@ +using RvtIO.Geometry.Meshing; +using RvtIO.Ifc; +using RvtIO.Model; +using RvtIO.Parsing; + +namespace RvtIO.Print; + +public static partial class PlanPrinter +{ + private sealed record FixtureFacet(List World, List<(double X, double Y)> Ring, + double Left, double Bottom, double Right, double Top, double MaxZ); + + private static List<(double X1, double Y1, double X2, double Y2)>? FixtureProfiles(GeometryData geometry) + { + if (geometry is not { BrepSolids.Count: > 1, UnresolvedSymbol: false, PlacedSymbolBox: false, + PlacedSymbolClipped: false, UntriangulatedFaces: 0 } + || geometry.BrepSolids.Any(solid => !solid.IsClosed || solid.FaceIndices.Count == 0)) + return null; + + var groups = new List>(); + var faces = geometry.Faces; + var assigned = new HashSet(); + foreach (var solid in geometry.BrepSolids) + { + var facets = new List(); + var members = new HashSet(); + bool decoded = true; + foreach (int index in solid.FaceIndices) + { + if ((uint)index >= faces.Count || !members.Add(index)) return null; + // The reader can deduplicate an identical face referenced by different closed solids. + assigned.Add(index); + if (decoded) decoded = AddFacets(faces[index], facets); + } + if (!decoded) + { + facets.Clear(); + if (!MeshFixtureSolid(geometry, solid, facets)) return null; + } + if (facets.Count == 0) return null; + groups.Add(facets); + } + if (assigned.Count != faces.Count) return null; + + var segments = new List(); + for (int i = 0; i < groups.Count; i++) + { + var group = groups[i]; + var otherFacets = groups.Where((_, index) => index != i).SelectMany(part => part).ToList(); + var rings = group.Select(facet => facet.Ring).ToList(); + var sources = group.SelectMany(facet => Enumerable.Range(0, facet.Ring.Count).Select(vertex => + { + int next = (vertex + 1) % facet.Ring.Count; + var a = facet.Ring[vertex]; + var b = facet.Ring[next]; + var (start, end) = a.CompareTo(b) <= 0 + ? (facet.World[vertex], facet.World[next]) : (facet.World[next], facet.World[vertex]); + return (Key: ElevationPrinter.ProjectedEdgeKey(a.X, a.Y, b.X, b.Y), Start: start, End: end); + })).ToLookup(source => source.Key); + foreach (var edge in ElevationPrinter.OutlineJoinedRings(rings, 0, coverOppositeEdges: true, retainSource: true)) + { + var (ring, vertex) = edge.SourceRingEdge!.Value; + var a = rings[ring][vertex]; + var b = rings[ring][(vertex + 1) % rings[ring].Count]; + var key = ElevationPrinter.ProjectedEdgeKey(a.X, a.Y, b.X, b.Y); + // Several edges at different heights can share a projected silhouette. + // Any visible span of the original edges contributes to the outline. + foreach (var source in sources[key].DistinctBy(source => (source.Start[2], source.End[2]))) + AddVisible(edge, source.Start, source.End, otherFacets); + } + + double height = geometry.BrepSolids[i].FaceIndices.Max(index => + faces[index].OuterVertices!.Max(point => point[2])); + foreach (int index in geometry.BrepSolids[i].FaceIndices) + { + // An upward cap with a hole defines the visible rims of the vessel. + if (faces[index] is not { PlaneSurface: true, Normal: [_, _, > 0.999999], + OuterVertices: { } outer, InnerVertices: { Count: > 0 } holes } + || outer.Any(p => Math.Abs(p[2] - height) > 1e-8) + || holes.Any(hole => hole.Any(p => Math.Abs(p[2] - height) > 1e-8))) + continue; + (outer, holes) = ResampleFixtureArcs(faces[index], outer, holes); + foreach (var loop in holes.Prepend(outer)) + for (int j = 0; j < loop.Count; j++) + { + var a = loop[j]; + var b = loop[(j + 1) % loop.Count]; + var start = InPlan(a); + var end = InPlan(b); + AddVisible(new(start.X, start.Y, end.X, end.Y, 0, 0, -1, -1, 0, 0, 0, 0), + a, b, otherFacets); + } + } + } + + if (segments.Count == 0) return null; + return ElevationPrinter.MergeOverlaps(segments).Select(edge => + (edge.X1, edge.Y1, edge.X2, edge.Y2)).ToList(); + + void AddVisible(ElevationPrinter.CollectedEdge edge, double[] a, double[] b, + List otherFacets) + { + double dx = b[0] - a[0], dy = b[1] - a[1], dz = b[2] - a[2]; + double lengthSquared = dx * dx + dy * dy; + if (lengthSquared < 1e-12) return; + + // Along this edge the plane has the same height as the original straight segment. + // A projected face can obscure it only where the face lies above that plane. + double[] origin = [a[0], a[1], a[2] + 1e-8]; + double[] normal = [-dx * dz / lengthSquared, -dy * dz / lengthSquared, 1]; + double left = Math.Min(edge.X1, edge.X2), right = Math.Max(edge.X1, edge.X2); + double bottom = Math.Min(edge.Y1, edge.Y2), top = Math.Max(edge.Y1, edge.Y2); + var covers = otherFacets.Where(facet => facet.MaxZ >= Math.Min(a[2], b[2]) + && facet.Left <= right && facet.Right >= left && facet.Bottom <= top && facet.Top >= bottom) + .Select(facet => ElevationPrinter.ClipBehind(facet.World, origin, normal).Select(InPlan).ToList()) + .Where(ring => ring.Count >= 3 && Math.Abs(SignedArea(ring)) > 1e-8); + foreach (var span in ElevationPrinter.VisibleTerrainEdges([edge], covers, [], coverBoundary: false)) + segments.Add((span.X1, span.Y1).CompareTo((span.X2, span.Y2)) <= 0 ? span + : span with { X1 = span.X2, Y1 = span.Y2, X2 = span.X1, Y2 = span.Y1 }); + } + } + + private static (List Outer, List> Holes) ResampleFixtureArcs( + GeoFace face, List outer, List> holes) + { + if (face is not { PlaneSurface: true, Normal: [_, _, var z], MeshArcs: { Count: > 0 } arcs } + || !(Math.Abs(z) > 0.999999)) return (outer, holes); + + // A split face carries the arc list of the source face. Match only runs on this region. + var regionArcs = new List(); + foreach (var ring in holes.Prepend(outer)) + { + var occupied = new HashSet(); + foreach (var run in IfcExporter.FindArcRunsCurrent(ring, arcs)) + { + for (int i = 0; i < run.Steps; i++) + if (!occupied.Add((run.First + i) % ring.Count)) return (outer, holes); + regionArcs.Add(run.Arc); + } + } + return IfcExporter.TryResampleArcsCurrent(outer, holes, regionArcs, + out var curvedOuter, out var curvedHoles, out _) ? (curvedOuter, curvedHoles) : (outer, holes); + } + + private static bool AddFacets(GeoFace face, List facets) + { + if (face.OuterVertices is not { Count: >= 3 } outer + || face.InnerLoops?.Count > (face.InnerVertices?.Count ?? 0)) return false; + var holes = face.InnerVertices ?? []; + var contours = holes.Prepend(outer).ToList(); + if (contours.Any(loop => loop.Count < 3 || loop.Any(p => p.Length != 3 || !p.All(double.IsFinite)))) + return false; + (outer, holes) = ResampleFixtureArcs(face, outer, holes); + contours = holes.Prepend(outer).ToList(); + var projected = contours.Select(loop => loop.Select(InPlan).ToList()).ToList(); + if (holes.Count == 0 && (face.PlaneSurface || outer.Count == 3)) + { + AddFixtureFacet(outer, projected[0], facets); + return true; + } + + var world = contours.SelectMany(loop => loop).ToArray(); + var plan = projected.SelectMany(loop => loop).ToArray(); + if (face.Normal is not { Length: 3 } normal || !normal.All(double.IsFinite) + || normal.All(value => value == 0)) return false; + // A curved patch can fold over itself in plan. Triangulate its native ring in the + // dominant plane of the patch normal, then project the individual triangles. + int axis = Array.IndexOf(normal, normal.MaxBy(value => Math.Abs(value))); + var local = world.Select(p => (X: p[(axis + 1) % 3], Y: p[(axis + 2) % 3])).ToArray(); + int offset = 0; + var indices = contours.Select(loop => + { + var range = Enumerable.Range(offset, loop.Count).ToArray(); + offset += loop.Count; + return range; + }).ToArray(); + var outerFlags = new bool[indices.Length]; + outerFlags[0] = true; + double outerArea = Math.Abs(SignedArea(indices[0].Select(index => local[index]).ToList())); + if (outerArea < 1e-12) return true; + double expected = outerArea - indices.Skip(1).Sum(loop => + Math.Abs(SignedArea(loop.Select(index => local[index]).ToList()))); + double area = 0; + foreach (var (a, b, c) in GeTess.TriangulateProfile(local, indices, outerFlags)) + { + area += Math.Abs(SignedArea([local[a], local[b], local[c]])); + AddFixtureFacet([world[a], world[b], world[c]], [plan[a], plan[b], plan[c]], facets); + } + return expected > 0 && Math.Abs(area - expected) <= 1e-7 * outerArea; + } + + private static bool MeshFixtureSolid(GeometryData geometry, GeoBrepSolid solid, List facets) + { + var source = solid.FaceIndices.Select(index => geometry.Faces[index]).ToArray(); + int id = source[0].GeometryNode; + if (id <= 0 || source.Any(face => face.GeometryNode != id) + || geometry.MeshNodes?.Where(node => node.Node == id && !node.Ghost).Take(2).ToArray() + is not [var meshNode] + || meshNode.Placement is not { Length: 12 } placement + || !ElementBuilder.IsRigidPlacement(placement)) return false; + + var markers = meshNode.Faces.Select(face => (uint)face.Marker).ToHashSet(); + if (source.Any(face => !markers.Contains(face.SourceFace != 0 ? face.SourceFace : face.MeshMarker))) + return false; + + // Some curved trims fold across a projection of the dense polygons. In that case use + // the same authored surface and edge sampler used to mesh the node for export. + const double lod = 0.2; + bool freeform = meshNode.Faces.Any(FreeformSolid.IsFreeform); + var sampler = freeform ? FreeformSolid.Create(meshNode.Faces, lod, meshNode.Diagonal) : null; + if (freeform && sampler == null) return false; + foreach (var face in meshNode.Faces) + { + bool ok = FreeformSolid.IsFreeform(face) ? sampler!.TryMesh(face, out var mesh) + : FaceMesher.TryMesh(GRepParserV2.WithSamples(face, lod, meshNode.Diagonal, sampler), + lod, meshNode.Diagonal, out mesh); + if (!ok) return false; + var world = mesh.Vertices.Select(point => ElementBuilder.TransformGeometryPoint(point, placement)).ToArray(); + if (world.Any(point => !point.All(double.IsFinite))) return false; + var plan = world.Select(InPlan).ToArray(); + foreach (var triangle in mesh.Triangles) + AddFixtureFacet([world[triangle[0]], world[triangle[1]], world[triangle[2]]], + [plan[triangle[0]], plan[triangle[1]], plan[triangle[2]]], facets); + } + return facets.Count > 0; + } + + private static void AddFixtureFacet(List vertices, List<(double X, double Y)> ring, + List facets) + { + double signed = SignedArea(ring); + if (Math.Abs(signed) < 1e-8) return; + if (signed < 0) + { + vertices = [.. vertices.AsEnumerable().Reverse()]; + ring.Reverse(); + } + facets.Add(new(vertices, ring, ring.Min(p => p.X), ring.Min(p => p.Y), + ring.Max(p => p.X), ring.Max(p => p.Y), vertices.Max(p => p[2]))); + } + + private static (double X, double Y) InPlan(double[] point) => + (point[0] * FeetToMillimetres, point[1] * FeetToMillimetres); +} diff --git a/src/RvtIO/Print/PlanPrinter.Furniture.cs b/src/RvtIO/Print/PlanPrinter.Furniture.cs new file mode 100644 index 00000000..9a14eac8 --- /dev/null +++ b/src/RvtIO/Print/PlanPrinter.Furniture.cs @@ -0,0 +1,169 @@ +using RvtIO.BuiltIns; +using RvtIO.Internal; +using RvtIO.Model; +using RvtIO.Pdf; + +namespace RvtIO.Print; + +public static partial class PlanPrinter +{ + private sealed record FurnitureFace(List<(double X, double Y)> Outer, List> Holes, + double MinX, double MaxX, double MinY, double MaxY); + + internal static (double Bottom, double Cut, double Top)? GetPlanRange(RvtDocument document, int levelId, int? viewId) + { + if (viewId is not int id || document.RawData.PlanViewRanges?.TryGetValue(id, out var range) != true + || range.Offsets is not { Length: >= 3 } || range.LevelIds is not { Length: >= 3 }) return null; + double bottom = Plane(2, double.NegativeInfinity), cut = Plane(0, double.NaN), top = Plane(1, double.PositiveInfinity); + return bottom <= cut && cut <= top && double.IsFinite(cut) ? (bottom, cut, top) : null; + + double Plane(int index, double unlimited) + { + int level = range.LevelIds[index]; + if (level == -4) return unlimited; + if (level == -1) level = levelId; + return document.GetElement(level)?.LookupParameter(BuiltInParameter.LEVEL_ELEV)?.Value is double height + ? height + range.Offsets[index] : double.NaN; + } + } + + private static bool FurnitureInView(Element element, int levelId, (double Bottom, double Cut, double Top)? range) + { + if (range is { } planes && element.BoundingBox is { Length: 6 } box + && double.IsFinite(box[2]) && box[2] <= box[5] && double.IsFinite(box[5])) + { + double upper = element.CategoryId == (int)BuiltInCategory.OST_Casework ? planes.Top : planes.Cut; + return box[5] >= planes.Bottom && box[2] <= upper; + } + return LevelOf(element) == levelId; + } + + private static bool FixtureProjectionCoversBody(PlanFixtureProjection projection, GeometryData geometry) + => projection.Masks is [{ Count: >= 3 } mask] && HorizontalMaskCoversBody(mask, geometry); + + private static bool HorizontalMaskCoversBody(List mask, GeometryData geometry) + { + var ring = mask.Select(InPlan).ToList(); + double area = SignedArea(ring); + if (Math.Abs(area) < 1e-8) return false; + if (area < 0) ring.Reverse(); + + // A convex mask contains the full projection of a face when it contains its vertices. + for (int i = 0; i < ring.Count; i++) + if (Side(ring[i], ring[(i + 1) % ring.Count], ring[(i + 2) % ring.Count]) < -1e-7) + return false; + return geometry.Faces.Where(face => !face.ExcludedFromTopPlan) + .All(face => face.OuterVertices is { Count: >= 3 } vertices && vertices.All(point => + { + if (point[2] > mask[0][2] + 1e-7) return false; + var xy = InPlan(point); + for (int i = 0; i < ring.Count; i++) + if (Side(ring[i], ring[(i + 1) % ring.Count], xy) < -1e-7) return false; + return true; + })); + + static double Side((double X, double Y) a, (double X, double Y) b, (double X, double Y) point) => + (b.X - a.X) * (point.Y - a.Y) - (b.Y - a.Y) * (point.X - a.X); + } + + internal static void DrawFixtureLines(PdfPage page, RvtDocument? document, + List<(double X1, double Y1, double X2, double Y2, int StyleId)> lines, + double scale, double fallbackWidth, Func toX, Func toY, + (double X0, double Y0, double X1, double Y1)? clip) + { + foreach (var group in lines.GroupBy(line => line.StyleId)) + { + var color = new PdfColor(0, 0, 0); + double pen = fallbackWidth; + double[]? dashes = null; + if (document?.RawData.GraphicsStylePens?.TryGetValue(group.Key, out var style) == true && style.GStyleType == 1) + { + color = new PdfColor((style.Color & 255) / 255d, ((style.Color >> 8) & 255) / 255d, + ((style.Color >> 16) & 255) / 255d); + if (document.RawData.PenWidthTable is { } widths + && PenWidths.TryPenWidth(widths, style.PenNumber, (int)Math.Round(scale), out double savedWidth)) + pen = savedWidth; + if (LinePatterns.TryGetPatternDashes(document, style.LinePatternId, out var savedDashes)) + dashes = savedDashes; + } + foreach (var (x1, y1, x2, y2, _) in group) + { + double a = x1, b = y1, c = x2, d = y2; + if (clip is { } bounds && !ElevationPrinter.ClipSegment(a, b, c, d, + bounds.X0, bounds.Y0, bounds.X1, bounds.Y1, out a, out b, out c, out d)) + continue; + if (dashes != null) + page.SetDashPoints(LinePatterns.FitEndpointDashes(Math.Sqrt((c - a) * (c - a) + (d - b) * (d - b)) / scale * 72 / 25.4, dashes)); + page.DrawLine(toX(a), toY(b), toX(c), toY(d), pen, color); + if (dashes != null) page.ResetDash(); + } + } + } + + private static List FurnitureFaces(IEnumerable faces) + { + var result = new List(); + foreach (var face in faces) + { + if (face.OuterVertices is not { Count: >= 3 } vertices || Project(vertices, true) is not { } outer) continue; + var holes = new List>(); + foreach (var inner in face.InnerVertices ?? []) + if (Project(inner, false) is { } hole) holes.Add(hole); + result.Add(new(outer, holes, outer.Min(p => p.X), outer.Max(p => p.X), + outer.Min(p => p.Y), outer.Max(p => p.Y))); + } + return result; + + static List<(double X, double Y)>? Project(List vertices, bool isOuter) + { + if (vertices.Count < 3 || vertices.Any(v => v.Length < 2 || !(Math.Abs(v[0]) < 1e6 && Math.Abs(v[1]) < 1e6))) + return null; + var points = vertices.Select(v => (X: v[0] * FeetToMillimetres, Y: v[1] * FeetToMillimetres)).ToList(); + double area = SignedArea(points); + if (Math.Abs(area) < 1e-8) return null; + if ((area > 0) != isOuter) points.Reverse(); + return points; + } + } + + // shortcut: the silhouette stroke uses a 5 mm grid; the opaque fill uses the projected face rings. + private static List<(double X1, double Y1, double X2, double Y2)> SilhouetteLines( + List faces, double cell) + { + if (faces.Count == 0) return []; + double x0 = faces.Min(face => face.MinX), x1 = faces.Max(face => face.MaxX); + double y0 = faces.Min(face => face.MinY), y1 = faces.Max(face => face.MaxY); + int nx = (int)Math.Ceiling((x1 - x0) / cell) + 1; + int ny = (int)Math.Ceiling((y1 - y0) / cell) + 1; + if (nx < 1 || ny < 1 || (long)nx * ny > 400_000) return []; + var inside = new bool[nx, ny]; + foreach (var face in faces) + { + int startX = Math.Max(0, (int)Math.Floor((face.MinX - x0) / cell)); + int startY = Math.Max(0, (int)Math.Floor((face.MinY - y0) / cell)); + int endX = Math.Min(nx - 1, (int)Math.Floor((face.MaxX - x0) / cell)); + int endY = Math.Min(ny - 1, (int)Math.Floor((face.MaxY - y0) / cell)); + for (int i = startX; i <= endX; i++) + for (int j = startY; j <= endY; j++) + { + if (inside[i, j]) continue; + double cx = x0 + (i + 0.5) * cell, cy = y0 + (j + 0.5) * cell; + inside[i, j] = PointInPolygon(cx, cy, face.Outer) + && !face.Holes.Any(hole => PointInPolygon(cx, cy, hole)); + } + } + var lines = new List<(double X1, double Y1, double X2, double Y2)>(); + for (int i = 0; i < nx; i++) + for (int j = 0; j < ny; j++) + { + if (!inside[i, j]) continue; + double left = x0 + i * cell, right = left + cell; + double bottom = y0 + j * cell, top = bottom + cell; + if (i == 0 || !inside[i - 1, j]) lines.Add((left, bottom, left, top)); + if (i == nx - 1 || !inside[i + 1, j]) lines.Add((right, bottom, right, top)); + if (j == 0 || !inside[i, j - 1]) lines.Add((left, bottom, right, bottom)); + if (j == ny - 1 || !inside[i, j + 1]) lines.Add((left, top, right, top)); + } + return lines; + } +} diff --git a/src/RvtIO/Print/PlanPrinter.Notes.cs b/src/RvtIO/Print/PlanPrinter.Notes.cs new file mode 100644 index 00000000..8db07033 --- /dev/null +++ b/src/RvtIO/Print/PlanPrinter.Notes.cs @@ -0,0 +1,108 @@ +using RvtIO.Model; +using RvtIO.Pdf; + +namespace RvtIO.Print; + +public static partial class PlanPrinter +{ + internal static void DrawPlanNotes(PdfPage page, RvtDocument document, int viewId, ViewCropFrame crop, + PlanContent content, double scale, double originX, double originY) + { + if (page.Owner.Font == null || !crop.Right.SequenceEqual(new double[] { 1, 0, 0 }) + || !crop.Up.SequenceEqual(new double[] { 0, 1, 0 }) + || document.RawData.PlanNotes?.GetValueOrDefault(viewId) is not { Count: > 0 } notes) return; + + double X(double feet) => (feet * FeetToMillimetres - content.MinX) / scale + originX; + double Y(double feet) => (feet * FeetToMillimetres - content.MinY) / scale + originY; + + foreach (var note in notes) + DrawTextNote(page, document, note, X, Y); + } + + internal static bool DrawTextNote(PdfPage page, RvtDocument document, RevitFileInfo.PlanNote note, + Func toX, Func toY) + { + if (page.Owner.Font is not { } font) return false; + (double X, double Y) Point(double[] feet) => (toX(feet[0]), toY(feet[1])); + double width = note.WidthFeet * FeetToMillimetres, height = note.HeightFeet * FeetToMillimetres; + double padding = note.PaddingFeet * FeetToMillimetres; + double x = toX(note.X), y = toY(note.Y); + double pen = PlanAnnotationWidth(document, note.CategoryId, 0.1); + foreach (var leader in note.Leaders) + DrawPlanNoteLeader(page, Point(leader.End), Point(leader.Elbow), Point(leader.Anchor), + note.ArcLeaders, note.ArrowSizeFeet * FeetToMillimetres, note.ArrowAngle, pen); + if (note.Opaque) + page.DrawRectangle(x, y - height, width, height, 0, 1); + if (note.HasBorder) + page.DrawRectangle(x - padding, y - height - padding, width + 2 * padding, height + 2 * padding, pen); + + double size = note.FontPoints * 25.4 / 72; + var lines = WrapPlanNoteText(page, note.Text, size, width, note.Wrap); + double baseline = y - size * font.Ascent / font.UnitsPerEm; + for (int i = 0; i < lines.Count; i++) + page.DrawText(lines[i], x, baseline - i * height / lines.Count, size); + return true; + } + + internal static IReadOnlyList WrapPlanNoteText(PdfPage page, string text, double size, double width, bool wrap) + { + var paragraphs = text.Split('\n'); + if (!wrap) return paragraphs; + + var lines = new List(); + foreach (string paragraph in paragraphs) + { + if (page.MeasureText(paragraph, size) <= width) + { + lines.Add(paragraph); + continue; + } + string line = ""; + var words = paragraph.Split(' ', StringSplitOptions.RemoveEmptyEntries); + for (int i = 0; i < words.Length; i++) + { + // The space after a word counts toward the saved wrapping width. + string token = i == words.Length - 1 ? words[i] : words[i] + " "; + if (line.Length > 0 && page.MeasureText(line + token, size) > width) + { + lines.Add(line.TrimEnd()); + line = token; + } + else line += token; + } + lines.Add(line.TrimEnd()); + } + return lines; + } + + private static void DrawPlanNoteLeader(PdfPage page, (double X, double Y) end, (double X, double Y) elbow, + (double X, double Y) anchor, bool arc, double arrowSize, double arrowAngle, double pen) + { + double ux = elbow.X - end.X, uy = elbow.Y - end.Y; + double vx = anchor.X - end.X, vy = anchor.Y - end.Y; + double det = 2 * (ux * vy - uy * vx); + double direction = Math.Atan2(uy, ux); + if (arc && Math.Abs(det) > 1e-8) + { + double u = ux * ux + uy * uy, v = vx * vx + vy * vy; + double cx = (u * vy - v * uy) / det, cy = (ux * v - vx * u) / det; + double radius = Math.Sqrt(cx * cx + cy * cy); + double start = Math.Atan2(-cy, -cx), through = Math.Atan2(uy - cy, ux - cx); + double finish = Math.Atan2(vy - cy, vx - cx); + double sweep = (finish - start + 2 * Math.PI) % (2 * Math.PI); + if ((through - start + 2 * Math.PI) % (2 * Math.PI) > sweep) sweep -= 2 * Math.PI; + page.DrawArc(end.X + cx, end.Y + cy, radius, start * 180 / Math.PI, (start + sweep) * 180 / Math.PI, pen); + direction = start + Math.CopySign(Math.PI / 2, sweep); + } + else + { + page.DrawLine(end.X, end.Y, elbow.X, elbow.Y, pen); + page.DrawLine(elbow.X, elbow.Y, anchor.X, anchor.Y, pen); + } + + if (arrowSize <= 0) return; + double a = direction - arrowAngle / 2, b = direction + arrowAngle / 2; + page.DrawLine(end.X, end.Y, end.X + arrowSize * Math.Cos(a), end.Y + arrowSize * Math.Sin(a), pen); + page.DrawLine(end.X, end.Y, end.X + arrowSize * Math.Cos(b), end.Y + arrowSize * Math.Sin(b), pen); + } +} diff --git a/src/RvtIO/Print/PlanPrinter.OpeningTags.cs b/src/RvtIO/Print/PlanPrinter.OpeningTags.cs new file mode 100644 index 00000000..4c829804 --- /dev/null +++ b/src/RvtIO/Print/PlanPrinter.OpeningTags.cs @@ -0,0 +1,49 @@ +using RvtIO.BuiltIns; +using RvtIO.Pdf; + +namespace RvtIO.Print; + +public static partial class PlanPrinter +{ + private static bool DrawPlanOpeningTags(PdfPage page, RvtDocument? document, int? viewId, + Func toX, Func toY) + { + if (document == null || viewId is not int view || page.Owner.Font == null + || document.RawData.PlanOpeningTags?.GetValueOrDefault(view) is not { Count: > 0 } tags + || document.RawData.PlanOpeningTagStyles is not { Count: > 0 } styles) return false; + + bool drawn = false; + foreach (var tag in tags) + { + var element = document.GetElement(tag.ElementId); + if (element == null || !styles.TryGetValue(tag.SymbolId, out var style)) continue; + var label = style.Label; + var owner = label.ParamId == (int)BuiltInParameter.ALL_MODEL_TYPE_MARK + ? document.GetElement(element.TypeId) : element; + if (owner?.LookupParameter((BuiltInParameter)label.ParamId)?.Value is not string { Length: > 0 } value) + continue; + double x = toX(tag.X * FeetToMillimetres), y = toY(tag.Y * FeetToMillimetres); + double pen = PlanAnnotationWidth(document, + element.CategoryId == (int)BuiltInCategory.OST_Windows + ? (int)BuiltInCategory.OST_WindowTags : (int)BuiltInCategory.OST_DoorTags, 0.1); + DrawTagSymbol(page, style, value, x, y, pen); + drawn = true; + } + return drawn; + } + + internal static void DrawTagSymbol(PdfPage page, Model.RevitFileInfo.PlanOpeningTagStyle style, string value, + double x, double y, double pen) + { + if (page.Owner.Font is not { } font) return; + var label = style.Label; + var (labelX, _, baseline, size, alignment) = AnnotationLabelLayout(font, label, style.FontPoints, x, y); + foreach (var line in style.Lines) + page.DrawLine(x + line.X0 * FeetToMillimetres, y + line.Y0 * FeetToMillimetres, + x + line.X1 * FeetToMillimetres, y + line.Y1 * FeetToMillimetres, pen); + foreach (var arc in style.Arcs) + page.DrawArc(x + arc.X * FeetToMillimetres, y + arc.Y * FeetToMillimetres, + arc.Radius * FeetToMillimetres, arc.Start, arc.End, pen); + page.DrawText(label.Prefix + value + label.Suffix, labelX, baseline, size, alignment); + } +} diff --git a/src/RvtIO/Print/PlanPrinter.RoomTags.cs b/src/RvtIO/Print/PlanPrinter.RoomTags.cs new file mode 100644 index 00000000..88afab03 --- /dev/null +++ b/src/RvtIO/Print/PlanPrinter.RoomTags.cs @@ -0,0 +1,86 @@ +using System.Globalization; +using RvtIO.BuiltIns; +using RvtIO.Compact; +using RvtIO.Model; +using RvtIO.Parsing; +using RvtIO.Pdf; + +namespace RvtIO.Print; + +public static partial class PlanPrinter +{ + private static bool DrawPlanRoomTags(PdfPage page, RvtDocument? document, int? viewId, + Func toX, Func toY) + { + if (document == null || viewId is not int view || page.Owner.Font is not { } font + || document.RawData.PlanRoomTags?.GetValueOrDefault(view) is not { Count: > 0 } tags + || document.RawData.PlanRoomTagStyles is not { Count: > 0 } styles) return false; + + double pen = PlanAnnotationWidth(document, (int)BuiltInCategory.OST_RoomTags, 0.1); + bool drawn = false; + foreach (var tag in tags) + { + if (document.GetElement(tag.RoomId) is not { CategoryId: (int)BuiltInCategory.OST_Rooms } room + || !styles.TryGetValue(tag.SymbolId, out var style)) continue; + double x = toX(tag.X * FeetToMillimetres), y = toY(tag.Y * FeetToMillimetres); + foreach (var line in style.Lines) + page.DrawLine(x + line.X0 * FeetToMillimetres, y + line.Y0 * FeetToMillimetres, + x + line.X1 * FeetToMillimetres, y + line.Y1 * FeetToMillimetres, pen); + foreach (var (label, sizePoints) in style.Labels) + { + string? value = RoomTagValue(document, room, label.ParamId); + if (string.IsNullOrEmpty(value)) continue; + var (labelX, labelBottom, baseline, size, alignment) = AnnotationLabelLayout(font, label, sizePoints, x, y); + if (!(size is > 0 and < 100)) continue; + // shortcut: vertical single-label attachment only, extend after verifying the other saved attachment modes. + if (style.Labels.Count == 1 && alignment == PdfTextAlignment.Center + && tag.LeaderAnchor is { } anchor && tag.LeaderEnd is { } end + && Math.Abs(end.X - anchor.X) < 1e-8 + && Math.Abs(toX(anchor.X * FeetToMillimetres) - labelX) < 1e-6 + && Math.Abs(toY(anchor.Y * FeetToMillimetres) - labelBottom) < 1e-6) + { + double endY = toY(end.Y * FeetToMillimetres); + double attachment = endY > labelBottom ? baseline + size * font.Ascent / font.UnitsPerEm : labelBottom; + page.DrawLine(toX(end.X * FeetToMillimetres), endY, x, attachment, pen); + } + page.DrawText(label.Prefix + value + label.Suffix, labelX, baseline, size, alignment); + drawn = true; + } + } + return drawn; + } + + internal static (double X, double Bottom, double Baseline, double Size, PdfTextAlignment Alignment) + AnnotationLabelLayout(PdfTrueTypeFont font, TfBlockDeserializer.TitleBlockLabel label, double sizePoints, double x, double y) + { + const double pointsToMm = 25.4 / 72; + double size = sizePoints > 0 ? sizePoints * pointsToMm + : label.Height * FeetToMillimetres * font.UnitsPerEm / (font.Ascent - font.Descent); + var alignment = (label.Flags & 0x80) != 0 ? PdfTextAlignment.Center + : (label.Flags & 0x100) != 0 ? PdfTextAlignment.Right : PdfTextAlignment.Left; + double labelBottom = y + label.Oy * FeetToMillimetres; + if ((label.Flags & 0x400) != 0) labelBottom -= label.Height * FeetToMillimetres / 2; + return (x + label.Ox * FeetToMillimetres, labelBottom, + labelBottom - size * font.Descent / font.UnitsPerEm, size, alignment); + } + + private static string LocalizeRoomArea(string value) => + CultureInfo.CurrentUICulture.TwoLetterISOLanguageName == "ru" + && value.EndsWith("m²", StringComparison.Ordinal) ? value[..^2] + "м²" : value; + + private static string? RoomTagValue(RvtDocument document, Element room, int parameter) + { + var value = room.LookupParameter((BuiltInParameter)parameter)?.Value; + if (parameter == (int)BuiltInParameter.ROOM_NAME) return value as string ?? room.Name; + if (parameter == (int)BuiltInParameter.ROOM_NUMBER) return value as string; + if (parameter == (int)BuiltInParameter.ROOM_AREA && document.RawData.SerializedFormatSettings is { } settings) + { + var area = value as double? ?? room.SerializedRoomPlanAreaSquareFeet + ?? SolidQuantities.RoomPlanArea(room.SerializedSpaceBoundaryCurrent); + if (area is > 0 and < double.PositiveInfinity + && CompactValueFormatter.Format(area.Value, "autodesk.spec.aec:area", settings) is { } formatted) + return LocalizeRoomArea(formatted); + } + return null; + } +} diff --git a/src/RvtIO/Print/PlanPrinter.SectionMarks.cs b/src/RvtIO/Print/PlanPrinter.SectionMarks.cs new file mode 100644 index 00000000..61c0c76a --- /dev/null +++ b/src/RvtIO/Print/PlanPrinter.SectionMarks.cs @@ -0,0 +1,108 @@ +using RvtIO.BuiltIns; +using RvtIO.Pdf; + +namespace RvtIO.Print; + +public static partial class PlanPrinter +{ + private static bool TryDrawFilledSectionMark(PdfPage page, RvtDocument document, int planId, int sectionId, + IReadOnlyList<(double X, double Y)> line, (double X0, double Y0, double X1, double Y1)? frame, double pen) + { + // Filled head and tail with parallel terminal legs in an axis-aligned plan. + if (page.Owner.Font is not { } font + || document.GetElement(planId)?.ViewCrop is not { Right: [1, 0, 0], Up: [0, 1, 0] } + || document.GetElement(sectionId) is not { ViewDirection: [var dx, var dy, 0] } section + || document.RawData.ViewHiddenElements?.GetValueOrDefault(planId)?.Contains(sectionId) == true + || document.GetElement(section.TypeId)?.LookupParameter(BuiltInParameter.SECTION_TAG)?.Value is not int tag + || document.RawData.SectionMarkerSymbols?.GetValueOrDefault(tag) is not (var head, var tail) + || document.GetElement(head) is not { FamilyName: "M_Section Head - Filled", BoundingBox: { Length: 6 } headBox } + || document.GetElement(tail) is not { FamilyName: "M_Section Tail - Filled", BoundingBox: { Length: 6 } tailBox } + || document.RawData.TitleBlockLabels?.GetValueOrDefault(head) is not { } labels) + return false; + + var detail = labels.FirstOrDefault(label => label.ParamId == (int)BuiltInParameter.VIEWER_DETAIL_NUMBER); + var sheet = labels.FirstOrDefault(label => label.ParamId == (int)BuiltInParameter.VIEWER_SHEET_NUMBER); + if (detail is not { Bx: 1, By: 0, Hx: 0, Hy: 1 } || sheet is not { Bx: 1, By: 0, Hx: 0, Hy: 1 }) + return false; + var start = line[0]; + var end = line[^1]; + double ax = line[1].X - start.X, ay = line[1].Y - start.Y; + double length = double.Hypot(ax, ay); + if (!(length > 0 && double.IsFinite(length))) return false; + double ux = ax / length, uy = ay / length; + double perpendicular = ux * dy - uy * dx; + if (!(Math.Abs(perpendicular) > 1 - 1e-8)) return false; + double vx = -uy * Math.Sign(perpendicular), vy = ux * Math.Sign(perpendicular); + + double radius = -headBox[1] * FeetToMillimetres; + double tip = headBox[4] * FeetToMillimetres; + double center = (headBox[0] + headBox[3]) * FeetToMillimetres / 2; + double tailWidth = (tailBox[3] - tailBox[0]) * FeetToMillimetres; + double tailHeight = (tailBox[4] - tailBox[1]) * FeetToMillimetres; + if (!(radius is > 0 and <= 100 && tailWidth is > 0 and <= 100 && tailHeight is > 0 and <= 100 + && Math.Abs(center + radius) < 1e-6 && Math.Abs(tip - radius * Math.Sqrt(2)) < 1e-6)) + return false; + + (double X, double Y) At((double X, double Y) p, double x, double y) => + (p.X + x * ux + y * vx, p.Y + x * uy + y * vy); + bool Contains((double X, double Y) p) => frame is not { } f + || (p.X >= f.X0 && p.X <= f.X1 && p.Y >= f.Y0 && p.Y <= f.Y1); + if (!Contains(start) || !Contains(end)) return false; + + var viewport = document.Elements.FirstOrDefault(element => element.ViewportViewId == sectionId && element.OwnerViewId is > 0); + string number = viewport?.OwnerViewId is int sheetId + ? document.GetElement(sheetId)?.LookupParameter(BuiltInParameter.SHEET_NUMBER)?.Value as string ?? "---" : "---"; + string detailNumber = viewport?.LookupParameter(BuiltInParameter.VIEWPORT_DETAIL_NUMBER)?.Value as string ?? "-"; + var mid = At(start, center, 0); + var left = At(mid, -tip, 0); + var right = At(end, tailWidth, 0); + bool vertical = line.Count > 2 && Math.Abs(ux) < 1e-8; + if (line.Count == 2) + page.DrawLine(left.X, left.Y, right.X, right.Y, pen); + else + { + page.DrawPolyline(line, pen, false); + var top = At(mid, tip, 0); + page.DrawLine(top.X, top.Y, start.X, start.Y, pen); + if (vertical) page.DrawLine(mid.X - radius, mid.Y, mid.X + radius, mid.Y, pen); + else page.DrawLine(left.X, left.Y, start.X, start.Y, pen); + } + page.DrawPolyline([end, right, At(end, tailWidth, tailHeight), At(end, 0, tailHeight)], pen, true, 0); + + // The family is the portion of a right isosceles triangle outside its circular opening. + for (int eighth = 0; eighth < 4; eighth++) + { + var corner = eighth switch + { + 0 => At(mid, tip, 0), + 3 => At(mid, -tip, 0), + _ => At(mid, 0, tip), + }; + var wing = new List<(double X, double Y)>(5) { corner }; + for (int i = 0; i <= 3; i++) + { + double theta = (3 * eighth + i) * Math.PI / 12; + wing.Add(At(mid, radius * Math.Cos(theta), radius * Math.Sin(theta))); + } + page.DrawPolyline(wing, pen, true, 0); + } + page.DrawPolyline(ElevationPrinter.DatumCircle(mid.X, mid.Y, radius, 25), pen, true); + DrawLabel(detail, detailNumber); + DrawLabel(sheet, number); + return true; + + void DrawLabel(RvtIO.Parsing.TfBlockDeserializer.TitleBlockLabel label, string value) + { + double ox = label.Ox * FeetToMillimetres, oy = label.Oy * FeetToMillimetres; + var position = vertical ? (X: mid.X + ox - center, Y: mid.Y + oy) : At(start, ox, oy); + double height = label.Height * FeetToMillimetres; + double cap = document.RawData.TitleBlockCapHeightsFeet?.GetValueOrDefault(label.AttrId) ?? 0; + bool opaque = document.RawData.OpaqueSymbolLabelStyles?.Contains(label.AttrId) == true; + bool arial = document.RawData.RegularArialSymbolLabelStyles?.Contains(label.AttrId) == true; + bool flip = ux < -1e-8 || (Math.Abs(ux) <= 1e-8 && uy < 0); + double bx = vertical ? 1 : flip ? -ux : ux, by = vertical ? 0 : flip ? -uy : uy; + SheetComposer.DrawTitleBlockText(page, [label.Prefix + value + label.Suffix], position.X, position.Y, + SheetComposer.SymbolLabelTextSize(font, height, cap), height, label.Flags, bx, by, -by, bx, opaque, arial); + } + } +} diff --git a/src/RvtIO/Print/PlanPrinter.Stairs.cs b/src/RvtIO/Print/PlanPrinter.Stairs.cs new file mode 100644 index 00000000..2bc9f92a --- /dev/null +++ b/src/RvtIO/Print/PlanPrinter.Stairs.cs @@ -0,0 +1,391 @@ +using RvtIO.BuiltIns; +using RvtIO.Model; +using RvtIO.Parsing; +using RvtIO.Pdf; +using Point = (double X, double Y); + +namespace RvtIO.Print; + +public static partial class PlanPrinter +{ + internal static void DrawStairPaths(PdfPage page, RvtDocument document, int viewId, int levelId, + PlanContent content, double scale, double originX, double originY) + { + if (document.RawData.PlanStairPaths?.GetValueOrDefault(viewId) is not { Count: > 0 } paths + || GetPlanRange(document, levelId, viewId) is not { } range + || !PenWidths.TryGetStyle(document, (int)BuiltInCategory.OST_StairsPaths, false, out int pen, out int rgb)) + return; + double width = PenWidths.TryAnnotationWidth(document, pen, out double saved) ? saved : 0.1; + var color = new PdfColor((rgb & 255) / 255d, ((rgb >> 8) & 255) / 255d, ((rgb >> 16) & 255) / 255d); + var hidden = document.RawData.ViewHiddenElements?.GetValueOrDefault(viewId); + Point Paper(Point p) => ((p.X * FeetToMillimetres - content.MinX) / scale + originX, + (p.Y * FeetToMillimetres - content.MinY) / scale + originY); + static Point Mid(TfBlockDeserializer.StairPlanLine line) => + ((line.X1 + line.X2) / 2, (line.Y1 + line.Y2) / 2); + static bool Same(Point a, Point b) => Math.Abs(a.X - b.X) < 1e-7 && Math.Abs(a.Y - b.Y) < 1e-7; + foreach (var path in paths) + { + if (hidden?.Contains(path.Id) == true || hidden?.Contains(path.HostId) == true + || document.GetElement(path.HostId) is not { SerializedStairCore: [{ ClassId: 3708 } component] } stair + || stair.LookupParameter(BuiltInParameter.STAIRS_TOP_LEVEL_PARAM)?.Value is not int top || top != levelId + || stair.LookupParameter(BuiltInParameter.STAIRS_BASE_LEVEL_PARAM)?.Value is not int bottom || bottom == levelId + || document.GetElement(component.Id)?.SerializedStairRunInput is not { Numbers: { } levels, Plan: { } plan } run + || levels.TopElevation > range.Cut || levels.BeginWithRiser != 1 || levels.EndWithRiser != 0 || plan.Treads.Length < 3) + continue; + + if (run.Style == TfBlockDeserializer.StairRunStyle.Sketched) + { + // For a descending flight that crosses the lower clip, locate the first riser at the + // view's cut offset measured from the base level and the last physical riser at the top. + if (levels.BottomElevation < range.Bottom && levels.TopElevation >= range.Bottom + && document.RawData.PlanViewRanges?.TryGetValue(viewId, out var savedRange) == true + && (savedRange.LevelIds[0] == levelId || savedRange.LevelIds[0] == -1) + && document.GetElement(bottom)?.LookupParameter(BuiltInParameter.LEVEL_ELEV)?.Value is double baseHeight + && SketchedStairPath(plan, baseHeight + savedRange.Offsets[0]) is { Count: >= 2 } points) + { + var paper = points.Select(Paper).ToList(); + double dxToTail = paper[1].X - paper[0].X, dyToTail = paper[1].Y - paper[0].Y; + double headLength = Math.Sqrt(dxToTail * dxToTail + dyToTail * dyToTail); + if (!(headLength > 0 && double.IsFinite(headLength))) continue; + for (int i = 1; i < paper.Count; i++) + page.DrawLine(paper[i - 1].X, paper[i - 1].Y, paper[i].X, paper[i].Y, width, color); + DrawArrowhead(paper[0], dxToTail / headLength, dyToTail / headLength, path); + } + continue; + } + + if (run.Style != TfBlockDeserializer.StairRunStyle.Straight || plan.Center is not [var axis] + || levels.BottomElevation < range.Bottom || !Same(Mid(plan.Treads[0]), (axis.X1, axis.Y1)) + || !Same(Mid(plan.Treads[^1]), (axis.X2, axis.Y2))) + continue; + + Point tip = Paper(Mid(plan.Treads[0])), focus = Paper((axis.X2, axis.Y2)); + double dx = focus.X - tip.X, dy = focus.Y - tip.Y; + double length = Math.Sqrt(dx * dx + dy * dy); + if (!(length > 0 && double.IsFinite(length))) continue; + + Point previous = tip; + // The upper envelope ends one pitch beyond the last physical nosing when End With Riser is off. + for (int i = 1; i < plan.Treads.Length - 1; i++) + { + Point landing = Paper(Mid(plan.Treads[i])); + page.DrawLine(previous.X, previous.Y, landing.X, landing.Y, width, color); + previous = landing; + } + double ux = dx / length, uy = dy / length; + DrawArrowhead(tip, ux, uy, path); + if (path.DownText is { } text && page.Owner.Font is { CapHeight: > 0 } font + && Math.Abs(ux) < 1e-7 && uy > 0) + { + Point label = Paper((axis.X2 + path.TextX, axis.Y2 + path.TextY)); + double size = SheetComposer.SymbolLabelTextSize(font, 0, path.CapHeight); + page.DrawText(text, label.X, label.Y - path.CapHeight * FeetToMillimetres / 2, size, PdfTextAlignment.Right); + } + } + + void DrawArrowhead(Point tip, double ux, double uy, RevitFileInfo.PlanStairPath path) + { + double arrow = path.ArrowSize * FeetToMillimetres; + double halfSpan = arrow * Math.Tan(path.ArrowAngle / 2); + double x = tip.X + ux * arrow, y = tip.Y + uy * arrow; + page.DrawLine(tip.X, tip.Y, x - uy * halfSpan, y + ux * halfSpan, width, color); + page.DrawLine(tip.X, tip.Y, x + uy * halfSpan, y - ux * halfSpan, width, color); + } + } + + private static List? SketchedStairPath(TfBlockDeserializer.StairPlanInput plan, double cut) + { + const double tolerance = 1e-7; + var treads = plan.Treads; + if (plan.Center.Length < 2 || !(treads[0].Elevation < cut && cut <= treads[^2].Elevation)) return null; + var first = Array.Find(treads, tread => tread.Elevation >= cut); + if (Crossing(first) is not { } tip || Crossing(treads[^2]) is not { } tail + || tip.Segment > tail.Segment || tip.Segment == tail.Segment && tip.Fraction >= tail.Fraction) + return null; + + List path = [tip.Position]; + for (int i = tip.Segment; i < tail.Segment; i++) + { + var line = plan.Center[i]; + var next = plan.Center[i + 1]; + Point end = (line.X2, line.Y2); + if (!SamePoint(end, (next.X1, next.Y1))) return null; + if (!SamePoint(path[^1], end)) path.Add(end); + } + if (!SamePoint(path[^1], tail.Position)) path.Add(tail.Position); + return path; + + (int Segment, double Fraction, Point Position)? Crossing(TfBlockDeserializer.StairPlanLine tread) + { + (int Segment, double Fraction, Point Position)? hit = null; + double rx = tread.X2 - tread.X1, ry = tread.Y2 - tread.Y1; + for (int i = 0; i < plan.Center.Length; i++) + { + var line = plan.Center[i]; + double sx = line.X2 - line.X1, sy = line.Y2 - line.Y1; + double det = sx * ry - sy * rx; + if (Math.Abs(det) < tolerance) continue; + double x = tread.X1 - line.X1, y = tread.Y1 - line.Y1; + double alongPath = (x * ry - y * rx) / det, alongTread = (x * sy - y * sx) / det; + if (alongPath < -tolerance || alongPath > 1 + tolerance + || alongTread < -tolerance || alongTread > 1 + tolerance) continue; + double fraction = Math.Clamp(alongPath, 0, 1); + Point position = (line.X1 + fraction * sx, line.Y1 + fraction * sy); + if (hit is { } other && !SamePoint(other.Position, position)) return null; + hit = (i, fraction, position); + } + return hit; + } + + static bool SamePoint(Point a, Point b) => Math.Abs(a.X - b.X) < tolerance && Math.Abs(a.Y - b.Y) < tolerance; + } + + private static bool CollectSavedStair(RvtDocument document, Element stair, int viewId, int levelId, + (double Bottom, double Cut, double Top) range, + IEnumerable topRails, HashSet savedTopRails, + List> fills, ref List<(double X1, double Y1, double X2, double Y2, int StyleId)>? lines) + { + // shortcut: one run with linear side paths, extend when other run layouts decode. + if (stair.SerializedStairCore is not [{ ClassId: 3708 } component] + || document.GetElement(component.Id)?.SerializedStairRunInput is not { Plan: { } plan } run) + return false; + var start = plan.Treads[0]; + var end = plan.Treads[^1]; + if (!JoinsTread(start, (plan.Left[0].X1, plan.Left[0].Y1), (plan.Right[0].X1, plan.Right[0].Y1)) + || !JoinsTread(end, (plan.Left[^1].X2, plan.Left[^1].Y2), (plan.Right[^1].X2, plan.Right[^1].Y2))) + return false; + bool straightBelowCut = run is { Style: TfBlockDeserializer.StairRunStyle.Straight, Numbers: { } straightLevels } + && plan.Left.Length == 1 && plan.Right.Length == 1 && straightLevels.BottomElevation >= range.Bottom; + // The upper plan's own stair path identifies a descending projection through the opening, + // including lower treads outside the plan's ordinary bottom clip. + bool sketchedDescending = run.Style == TfBlockDeserializer.StairRunStyle.Sketched + && stair.LookupParameter(BuiltInParameter.STAIRS_TOP_LEVEL_PARAM)?.Value is int top && top == levelId + && stair.LookupParameter(BuiltInParameter.STAIRS_BASE_LEVEL_PARAM)?.Value is int bottom && bottom != levelId + && document.RawData.PlanStairPaths?.GetValueOrDefault(viewId)?.Any(path => path.HostId == stair.Id) == true; + if ((straightBelowCut || sketchedDescending) && run.Numbers is { } levels + && levels.TopElevation >= range.Bottom && levels.TopElevation <= range.Cut && end.Elevation <= range.Cut) + { + var leftBoundary = ReadSidePath(plan.Left); + var rightBoundary = ReadSidePath(plan.Right); + int edgeStyle = Style(BuiltInCategory.OST_StairsOutlines); + int treadStyle = Style(BuiltInCategory.OST_StairsNosingLines); + if (leftBoundary == null || rightBoundary == null || edgeStyle == 0 || treadStyle == 0) return false; + var projected = lines ??= []; + var railTops = new List>(); + const int railCategory = (int)BuiltInCategory.OST_RailingTopRail; + int projectionRailStyle = sketchedDescending ? Style(BuiltInCategory.OST_RailingTopRail) : 0; + if (projectionRailStyle != 0) + foreach (var rail in topRails) + { + if (rail.BoundingBox is not { Length: 6 } bounds || !(bounds[5] <= range.Cut)) continue; + var tops = rail.Geometry!.Faces.Where(face => face.Normal is [_, _, > 1e-7]).ToList(); + if (tops.Count == 0 || tops.Any(face => face.OuterVertices is not { Count: >= 3 } + || face.OuterVertices.Any(point => point.Length != 3 || point.Any(value => !double.IsFinite(value))) + || face.InnerVertices is { Count: > 0 } || face.InnerLoops is { Count: > 0 })) continue; + var rings = tops.Select(face => ProjectRailRing(face.OuterVertices!)).ToList(); + fills.AddRange(rings); + railTops.AddRange(tops.Select(face => face.OuterVertices!)); + foreach (var edge in ElevationPrinter.OutlineJoinedRings(rings, railCategory)) + projected.Add((edge.X1, edge.Y1, edge.X2, edge.Y2, projectionRailStyle)); + savedTopRails.Add(rail.Id); + } + foreach (var edge in plan.Treads) + { + if (railTops.Count == 0) + { + AddStairLine(projected, (edge.X1, edge.Y1), (edge.X2, edge.Y2), treadStyle); + continue; + } + // The attached rail can hide part of a nosing even when the run projects below the plan range. + var masks = railTops.Select(ring => ElevationPrinter.ClipBehind(ring, [0, 0, edge.Elevation], [0, 0, 1])) + .Where(ring => ring.Count >= 3).Select(ProjectRailRing); + var line = new ElevationPrinter.CollectedEdge(edge.X1 * FeetToMillimetres, edge.Y1 * FeetToMillimetres, + edge.X2 * FeetToMillimetres, edge.Y2 * FeetToMillimetres, 0, 0, -1, -1, 0, 0, 0, 0); + foreach (var span in ElevationPrinter.VisibleTerrainEdges([line], masks, [], coverBoundary: false)) + projected.Add((span.X1, span.Y1, span.X2, span.Y2, treadStyle)); + } + foreach (var edge in plan.Left.Concat(plan.Right)) + AddStairLine(projected, (edge.X1, edge.Y1), (edge.X2, edge.Y2), edgeStyle); + AddMask(leftBoundary.Concat(rightBoundary.AsEnumerable().Reverse())); + return true; + } + + double cut = range.Cut; + if (!(start.Elevation < cut && cut < end.Elevation) + || document.GetElement(stair.TypeId) is not { } stairType + || stairType.LookupParameter(BuiltInParameter.STAIRSTYPE_SHOW_CUTLINE)?.Value is 0 + || stairType.LookupParameter(BuiltInParameter.STAIRSTYPE_CUTMARK_TYPE)?.Value is not int typeId + || document.GetElement(typeId) is not { } markType + || markType.LookupParameter(BuiltInParameter.CUT_LINE_TYPE)?.Value is not 0 + || markType.LookupParameter(BuiltInParameter.CUT_LINE_ANGLE)?.Value is not double angle + || markType.LookupParameter(BuiltInParameter.CUT_LINE_EXTENSION)?.Value is not 0d + || markType.LookupParameter(BuiltInParameter.CUT_MARK_SYMBOL)?.Value is not int symbol || symbol is not (0 or 1) + || document.GetElement(viewId)?.LookupParameter(BuiltInParameter.VIEW_SCALE)?.Value is not int scale || scale <= 0) + return false; + + int tread = 0; + for (int i = 1; i < plan.Treads.Length; i++) + { + if (plan.Treads[i].Elevation <= plan.Treads[i - 1].Elevation) return false; + if (plan.Treads[i].Elevation <= cut) tread = i; + } + var atCut = plan.Treads[tread]; + Point center = ((atCut.X1 + atCut.X2) / 2, (atCut.Y1 + atCut.Y2) / 2); + double direction = Math.Atan2(atCut.Y2 - atCut.Y1, atCut.X2 - atCut.X1) + angle; + Point along = (Math.Cos(direction), Math.Sin(direction)); + double Side(Point point) => along.X * (point.Y - center.Y) - along.Y * (point.X - center.X); + double lower = Side(((start.X1 + start.X2) / 2, (start.Y1 + start.Y2) / 2)); + if (!double.IsFinite(lower) || Math.Abs(lower) < 1e-7) return false; + double sign = Math.Sign(lower); + double Distance(Point point) => Side(point) * sign; + Point Intersect(Point a, Point b, double da, double db) + { + double fraction = da / (da - db); + return (a.X + (b.X - a.X) * fraction, a.Y + (b.Y - a.Y) * fraction); + } + + if (!TrySplitSide(plan.Left, out var left, out var leftAbove) + || !TrySplitSide(plan.Right, out var right, out var rightAbove)) return false; + Point a = left[^1], b = right[^1]; + double dx = b.X - a.X, dy = b.Y - a.Y; + double length = Math.Sqrt(dx * dx + dy * dy); + if (!(length > 1e-7) || !double.IsFinite(length)) return false; + + List mark = [a, b]; + if (symbol == 1) + { + if (markType.LookupParameter(BuiltInParameter.CUT_MARK_SYMBOL_SIZE)?.Value is not double size + || !(size > 0) || !double.IsFinite(size)) return false; + double span = size * scale; + if (span >= length) return false; + double ux = dx / length, uy = dy / length; + Point mid = ((a.X + b.X) / 2, (a.Y + b.Y) / 2); + double halfDepth = span * 5 / 8; + mark = [a, (mid.X - ux * span / 2, mid.Y - uy * span / 2), + (mid.X - uy * halfDepth, mid.Y + ux * halfDepth), + (mid.X + uy * halfDepth, mid.Y - ux * halfDepth), + (mid.X + ux * span / 2, mid.Y + uy * span / 2), b]; + } + + int outline = Style(BuiltInCategory.OST_StairsOutlines), outlineAbove = Style(BuiltInCategory.OST_StairsOutlinesAboveCut); + int nosing = Style(BuiltInCategory.OST_StairsNosingLines), nosingAbove = Style(BuiltInCategory.OST_StairsNosingLinesAboveCut); + int cutMark = Style(BuiltInCategory.OST_StairsCutMarks); + if (outline == 0 || outlineAbove == 0 || nosing == 0 || nosingAbove == 0 || cutMark == 0) return false; + + var strokes = lines ??= []; + DrawPath(left, outline); + DrawPath(right, outline); + DrawPath(leftAbove, outlineAbove); + DrawPath(rightAbove, outlineAbove); + DrawPath(mark, cutMark); + foreach (var edge in plan.Treads) + DrawSplit((edge.X1, edge.Y1), (edge.X2, edge.Y2), nosing, nosingAbove); + AddMask(left.Concat(mark.Skip(1)).Concat(right.AsEnumerable().Reverse().Skip(1))); + + int railStyle = Style(BuiltInCategory.OST_RailingTopRail), railAbove = Style(BuiltInCategory.OST_RailingTopRailAboveCut); + if (railStyle != 0 && railAbove != 0) + { + foreach (var rail in topRails) + { + var faces = FurnitureFaces(rail.Geometry!.Faces.Where(face => face.Normal is [_, _, > 1e-7])); + if (faces.Count == 0 || faces.Any(face => face.Holes.Count > 0)) continue; + var rings = faces.Select(face => face.Outer).ToList(); + foreach (var ring in rings) + { + var mask = ElevationPrinter.ClipHalfPlane(ring, point => RailDistance(point) >= 0, RailDistance); + if (mask.Count >= 3) fills.Add(mask); + } + foreach (var edge in ElevationPrinter.OutlineJoinedRings(rings, (int)BuiltInCategory.OST_RailingTopRail)) + DrawSplit(ToFeet((edge.X1, edge.Y1)), ToFeet((edge.X2, edge.Y2)), railStyle, railAbove); + savedTopRails.Add(rail.Id); + } + } + return true; + + static Point ToFeet(Point point) => (point.X / FeetToMillimetres, point.Y / FeetToMillimetres); + static List ProjectRailRing(List vertices) + { + var ring = vertices.Select(point => (point[0] * FeetToMillimetres, point[1] * FeetToMillimetres)).ToList(); + if (SignedArea(ring) < 0) ring.Reverse(); + return ring; + } + double RailDistance(Point point) => Distance(ToFeet(point)); + + void DrawSplit(Point p, Point q, int belowStyle, int aboveStyle) + { + double dp = Distance(p), dq = Distance(q); + if (dp * dq < 0) + { + Point split = Intersect(p, q, dp, dq); + AddStairLine(strokes, p, split, dp > 0 ? belowStyle : aboveStyle); + AddStairLine(strokes, split, q, dq > 0 ? belowStyle : aboveStyle); + } + else AddStairLine(strokes, p, q, dp + dq >= 0 ? belowStyle : aboveStyle); + } + + int Style(BuiltInCategory category) => document.RawData.GraphicsStylePens? + .FirstOrDefault(entry => entry.Value.CategoryId == (int)category && entry.Value.OwnerId == -1 + && entry.Value.GStyleType == 1).Key ?? 0; + + void DrawPath(List path, int style) + { + for (int i = 1; i < path.Count; i++) AddStairLine(strokes, path[i - 1], path[i], style); + } + + void AddMask(IEnumerable boundary) + { + var mask = boundary.Select(p => (p.X * FeetToMillimetres, p.Y * FeetToMillimetres)).ToList(); + if (SignedArea(mask) < 0) mask.Reverse(); + fills.Add(mask); + } + + static List? ReadSidePath(TfBlockDeserializer.StairPlanLine[] side) + { + List points = [(side[0].X1, side[0].Y1)]; + foreach (var edge in side) + { + if (Math.Abs(points[^1].X - edge.X1) > 1e-7 || Math.Abs(points[^1].Y - edge.Y1) > 1e-7) + return null; + points.Add((edge.X2, edge.Y2)); + } + return points; + } + + bool TrySplitSide(TfBlockDeserializer.StairPlanLine[] side, out List below, out List above) + { + below = []; + above = []; + Point previous = (side[0].X1, side[0].Y1); + if (Distance(previous) <= 0) return false; + below.Add(previous); + foreach (var edge in side) + { + if (Math.Abs(previous.X - edge.X1) > 1e-7 || Math.Abs(previous.Y - edge.Y1) > 1e-7) return false; + Point next = (edge.X2, edge.Y2); + double dp = Distance(previous), dq = Distance(next); + if (above.Count > 0 && dq >= 0) return false; + if (dp > 0 && dq < 0) + { + Point intersection = Intersect(previous, next, dp, dq); + below.Add(intersection); + above.Add(intersection); + } + if (dq == 0) return false; + (dq > 0 ? below : above).Add(next); + previous = next; + } + return above.Count > 1; + } + } + + private static void AddStairLine(List<(double X1, double Y1, double X2, double Y2, int StyleId)> lines, + Point from, Point to, int style) => lines.Add((from.X * FeetToMillimetres, from.Y * FeetToMillimetres, + to.X * FeetToMillimetres, to.Y * FeetToMillimetres, style)); + + private static bool JoinsTread(TfBlockDeserializer.StairPlanLine tread, Point a, Point b) + { + static bool Same(Point p, Point q) => Math.Abs(p.X - q.X) <= 1e-7 && Math.Abs(p.Y - q.Y) <= 1e-7; + Point start = (tread.X1, tread.Y1), end = (tread.X2, tread.Y2); + return Same(a, start) && Same(b, end) || Same(a, end) && Same(b, start); + } +} diff --git a/src/RvtIO/Print/PlanPrinter.WallCuts.cs b/src/RvtIO/Print/PlanPrinter.WallCuts.cs new file mode 100644 index 00000000..e5a3e1c8 --- /dev/null +++ b/src/RvtIO/Print/PlanPrinter.WallCuts.cs @@ -0,0 +1,150 @@ +using RvtIO.BuiltIns; +using RvtIO.Pdf; + +namespace RvtIO.Print; + +public static partial class PlanPrinter +{ + private static List<(int CategoryId, bool IsCut, List<(double X, double Y)> Ring)> CollectCurtainProfiles( + RvtDocument document, int viewId, double cutHeight, double? bottom) + { + var result = new List<(int CategoryId, bool IsCut, List<(double X, double Y)> Ring)>(); + var hiddenElements = document.RawData.ViewHiddenElements?.GetValueOrDefault(viewId); + var hiddenCategories = document.RawData.ViewHiddenCategories?.GetValueOrDefault(viewId); + double[] origin = [0, 0, cutHeight * FeetToMillimetres]; + double[] horizontal = [1, 0, 0], vertical = [0, 1, 0], direction = [0, 0, 1]; + foreach (var part in document.Elements) + { + if (part.CategoryId is not ((int)BuiltInCategory.OST_CurtainWallPanels or (int)BuiltInCategory.OST_CurtainWallMullions) + || part.IsDiscovered || part.NativeIsSymbol == true || part.SerializedUnplacedOwnerId is > 0 + || part.SerializedHostId is not > 0 + || part.BoundingBox is not { Length: 6 } bounds || !(bounds[2] < cutHeight) + || (bounds[5] <= cutHeight + && (part.CategoryId != (int)BuiltInCategory.OST_CurtainWallMullions || !(bounds[5] > bottom))) + || hiddenCategories?.Contains(part.CategoryId.Value) == true + || hiddenElements?.Contains(part.Id) == true || hiddenElements?.Contains(part.SerializedHostId.Value) == true + || part.Geometry is not { BrepSolids: [{ IsClosed: true } solid] } geometry + || solid.FaceIndices.Count != geometry.Faces.Count + || geometry.Faces.Any(face => face.CurvedSurface || face.InnerLoops is { Count: > 0 } + || face.InnerVertices is { Count: > 0 } || face.OuterVertices is not { Count: >= 3 } vertices + || vertices.Any(p => p.Length != 3 || !p.All(double.IsFinite)))) + continue; + + if (cutHeight < bounds[5]) + { + foreach (var ring in ElevationPrinter.ClosedSectionRings(geometry.Faces, origin, direction, + horizontal, vertical, requireClosed: true)) + result.Add((part.CategoryId.Value, true, ring)); + } + else + { + // A mullion below the cut projects its saved horizontal top face. + var tops = geometry.Faces.Where(face => face.PlaneSurface && !face.ExcludedFromTopPlan + && face.Normal is [_, _, > 0] && face.OuterVertices!.All(p => Math.Abs(p[2] - bounds[5]) < 1e-7)) + .Take(2).ToArray(); + if (tops is [var top]) + result.Add((part.CategoryId.Value, false, top.OuterVertices!.Select(InPlan).ToList())); + } + } + return result; + } + + private static Dictionary> CollectProjectedWallTops( + RvtDocument document, IEnumerable wallIds, Dictionary> gaps, + double bottom, double cutHeight) + { + var result = new Dictionary>(); + foreach (int id in wallIds) + { + if (gaps.TryGetValue(id, out var openings) && openings.Count > 0) continue; + if (document.GetElement(id) is not { BoundingBox: { Length: 6 } bounds, Geometry: { Faces.Count: > 0 } geometry } + || !(bounds[2] < bounds[5] && bounds[5] >= bottom && bounds[5] < cutHeight) + || geometry.Faces.Any(face => face.CurvedSurface || !UsableWallRing(face.OuterVertices))) continue; + + var tops = geometry.Faces.Where(face => face.PlaneSurface && !face.ExcludedFromTopPlan + && face.InnerLoops is not { Count: > 0 } && face.InnerVertices is not { Count: > 0 } + && face.Normal is [_, _, > 0] && face.OuterVertices!.All(p => Math.Abs(p[2] - bounds[5]) < 1e-7)) + .Take(2).ToArray(); + if (tops is [{ OuterVertices: { } top }] && HorizontalMaskCoversBody(top, geometry)) + result.Add(id, top.Select(InPlan).ToList()); + } + return result; + } + + private static Dictionary> Rings)> CollectWallCuts( + RvtDocument document, int viewId, PlanContent content) + { + var result = new Dictionary> Rings)>(); + if (PlanCutHeight(document, viewId) is not double cutHeight) return result; + double cut = cutHeight * FeetToMillimetres; + if (!double.IsFinite(cut)) return result; + double[] origin = [0, 0, cut]; + double[] horizontal = [1, 0, 0], vertical = [0, 1, 0], direction = [0, 0, 1]; + foreach (var wall in content.Walls) + { + if (document.GetElement(wall.Id) is not + { TypeId: > 0, Geometry: { Faces.Count: > 0 } geometry } element + || geometry.Faces.Any(face => face.CurvedSurface || !UsableWallRing(face.OuterVertices) + || (face.InnerLoops?.Count ?? 0) > (face.InnerVertices?.Count ?? 0) + || (face.InnerVertices is { Count: > 0 } holes && (!face.PlaneSurface || holes.Any(hole => !UsableWallRing(hole)))))) + continue; + + var rings = ElevationPrinter.ClosedSectionRings(geometry.Faces, origin, direction, horizontal, vertical, + requireClosed: true, includeFaceOpenings: true).ToList(); + if (rings.Count == 0 || !PreserveWallOpenings(wall, rings, content.Gaps.GetValueOrDefault(wall.Id))) continue; + foreach (var ring in rings) + if (SignedArea(ring) < 0) ring.Reverse(); + result[wall.Id] = (element.TypeId, rings); + } + return result; + } + + private static bool UsableWallRing(List? ring) => + ring is { Count: >= 3 } && ring.All(point => point.Length == 3 && point.All(double.IsFinite)); + + private static bool PreserveWallOpenings((int Id, double X1, double Y1, double X2, double Y2, double Width) wall, + List> rings, List<(double From, double To)>? gaps) + { + if (rings.Count == 1 && gaps is not { Count: > 0 }) return true; + double dx = wall.X2 - wall.X1, dy = wall.Y2 - wall.Y1; + double length = Math.Sqrt(dx * dx + dy * dy); + if (!(length > 0) || !double.IsFinite(length)) return false; + double Along((double X, double Y) point) => ((point.X - wall.X1) * dx + (point.Y - wall.Y1) * dy) / length; + // The plan draws its saved hosted openings even when the model cut passes below a sash. + const double endpointResolution = 0.1; // Same model millimetre resolution as ClosedSectionRings. + double coveredThrough = double.NegativeInfinity; + foreach (var (from, to) in rings.Select(ring => (From: ring.Min(Along), To: ring.Max(Along))).OrderBy(span => span.From)) + { + if (coveredThrough - from > endpointResolution + || gaps?.Any(gap => Math.Min(gap.To, to) - Math.Max(gap.From, from) > endpointResolution) == true) + return false; + coveredThrough = Math.Max(coveredThrough, to); + } + return true; + } + + private static void DrawWallCuts(PdfPage page, Dictionary> Rings)> cuts, + Func toX, Func toY, double width, + (double X0, double Y0, double X1, double Y1)? clip) + { + foreach (var ring in cuts.Values.SelectMany(cut => cut.Rings)) + { + var fill = clip is { } frame + ? ElevationPrinter.ClipToWindow(ring, frame.X0, frame.Y0, frame.X1, frame.Y1) : ring; + if (fill.Count >= 3) + page.DrawPolyline(fill.Select(p => (toX(p.X), toY(p.Y))).ToList(), 0, true, 1); + } + foreach (var sameType in cuts.Values.GroupBy(cut => cut.TypeId)) + { + var rings = sameType.SelectMany(cut => cut.Rings).ToList(); + foreach (var edge in ElevationPrinter.OutlineJoinedRings(rings, (int)BuiltInCategory.OST_Walls, + coverOppositeEdges: true)) + { + double x0 = edge.X1, y0 = edge.Y1, x1 = edge.X2, y1 = edge.Y2; + if (clip is { } frame && !ElevationPrinter.ClipSegment(x0, y0, x1, y1, frame.X0, frame.Y0, + frame.X1, frame.Y1, out x0, out y0, out x1, out y1)) continue; + page.DrawLine(toX(x0), toY(y0), toX(x1), toY(y1), width); + } + } + } +} diff --git a/src/RvtIO/Print/PlanPrinter.cs b/src/RvtIO/Print/PlanPrinter.cs index b40185f8..7e3e675c 100644 --- a/src/RvtIO/Print/PlanPrinter.cs +++ b/src/RvtIO/Print/PlanPrinter.cs @@ -1,4 +1,5 @@ using RvtIO.BuiltIns; +using RvtIO.Internal; using RvtIO.Model; using RvtIO.Parsing; using RvtIO.Pdf; @@ -43,7 +44,7 @@ public sealed record PlanView(int ViewId, string Name, int LevelId, int Scale); /// geometry, not Revit's generated linework, so floors, stairs, annotations, room fills, dimensions, tags and the title /// block are not on the page yet (see the notes in docs/printing.md). /// -public static class PlanPrinter +public static partial class PlanPrinter { private const double FeetToMillimetres = 304.8; @@ -65,7 +66,16 @@ internal sealed record PlanContent( List<(List<(double X, double Y)> Polygon, IReadOnlyList Grids)>? RoomPatterns = null, List<(double X1, double Y1, double X2, double Y2)>? StairLines = null, List<(double X1, double Y1, double X2, double Y2)>? RailLines = null, - List<(double X1, double Y1, double X2, double Y2)>? FurnitureLines = null); + List<(double X1, double Y1, double X2, double Y2)>? FurnitureLines = null, + IReadOnlyDictionary? RoomColors = null, + List>? FurnitureFillRings = null) + { + internal List<(DoorPlanSymbol Symbol, double[] Transform)>? DoorSymbols { get; init; } + internal List<(double X1, double Y1, double X2, double Y2, int StyleId)>? FixtureLines { get; init; } + internal Dictionary? ColumnProfiles { get; init; } + internal Dictionary>? ProjectedWallTops { get; init; } + internal List<(int CategoryId, bool IsCut, List<(double X, double Y)> Ring)>? CurtainProfiles { get; init; } + } /// The same plan seen in a rotated view: every point is projected on the view's own axes, so a site /// plan whose crop basis is turned draws its building turned with it. Wall-relative data (gaps, door and @@ -142,7 +152,30 @@ void Grow(double x, double y) return content with { MinX = content.MinX, MinY = content.MinY, MaxX = content.MaxX, MaxY = content.MaxY }; return new PlanContent(walls, columns, grids, content.Gaps, content.WindowGaps, content.DoorGaps, floorLoops, openingLoops, rooms, furniture, tags, minX, minY, maxX, maxY, - roomPatterns, stairLines, railLines, furnitureLines); + roomPatterns, stairLines, railLines, furnitureLines, content.RoomColors, + content.FurnitureFillRings?.Select(MapPolygon).ToList()) + { + ProjectedWallTops = content.ProjectedWallTops?.ToDictionary(entry => entry.Key, entry => MapPolygon(entry.Value)), + CurtainProfiles = content.CurtainProfiles?.Select(profile => + (profile.CategoryId, profile.IsCut, MapPolygon(profile.Ring))).ToList(), + ColumnProfiles = content.ColumnProfiles?.ToDictionary(entry => entry.Key, entry => + { + var profile = entry.Value; + (double X, double Y, double Radius)? circle = null; + if (profile.Circle is { } source) + { + var centre = Map(source.X, source.Y); + circle = (centre.X, centre.Y, source.Radius); + } + return profile with { Ring = MapPolygon(profile.Ring), Circle = circle }; + }), + FixtureLines = content.FixtureLines?.Select(line => + { + var a = Map(line.X1, line.Y1); + var b = Map(line.X2, line.Y2); + return (a.X, a.Y, b.X, b.Y, line.StyleId); + }).ToList(), + }; } /// The levels a plan can be printed for: those that own at least one wall or column with a location line, @@ -299,6 +332,9 @@ public static PdfDocument RenderViews(RvtDocument document, IReadOnlyList v { var walls = new List<(int Id, double X1, double Y1, double X2, double Y2, double Width)>(); var columns = new List<(double X, double Y, double Width, double Height)>(); + Dictionary? columnProfiles = null; + double? cutHeight = viewId is int cutView ? PlanCutHeight(document, cutView) : null; + var planRange = GetPlanRange(document, levelId, viewId); double minX = double.MaxValue, minY = double.MaxValue, maxX = double.MinValue, maxY = double.MinValue; void Grow(double x, double y) { @@ -327,6 +363,8 @@ void Grow(double x, double y) if (box is not { Length: 6 } || box[3] <= box[0] || box[4] <= box[1]) continue; double x = box[0] * FeetToMillimetres, y = box[1] * FeetToMillimetres; double width = (box[3] - box[0]) * FeetToMillimetres, height = (box[4] - box[1]) * FeetToMillimetres; + if (cutHeight is double cut && CutColumnProfile(document, element, cut) is { } profile) + (columnProfiles ??= []).Add(columns.Count, profile); columns.Add((x, y, width, height)); Grow(x, y); Grow(x + width, y + height); } @@ -341,10 +379,21 @@ void Grow(double x, double y) var gaps = new Dictionary>(); var windowGaps = new List<(int HostId, double From, double To)>(); var doorGaps = new List<(int HostId, double From, double To)>(); + List<(DoorPlanSymbol Symbol, double[] Transform)>? doorSymbols = null; + var hiddenOpenings = viewId is int openingView ? document.RawData.ViewHiddenElements?.GetValueOrDefault(openingView) : null; var tags = new List<(double MidX, double MidY, double Nx, double Ny, string Text, bool IsWindow)>(); foreach (var insert in document.Elements) { if (insert.CategoryId is not ((int)BuiltInCategory.OST_Doors or (int)BuiltInCategory.OST_Windows)) continue; + bool savedDoor = false; + if (cutHeight is double height && hiddenOpenings?.Contains(insert.Id) != true + && insert.SerializedHostId is int planHost && wallById.ContainsKey(planHost) + && insert.OwnDoorPlanSymbols is { } display + && SelectDoorPlanSymbol(display.Symbols, display.Transform, height, insert.BoundingBox) is { } symbol) + { + (doorSymbols ??= []).Add((symbol, display.Transform)); + savedDoor = true; + } if (insert.OwnSingleFamilyCutout is not { } cutout || cutout.Transform is not { Length: 12 } matrix) continue; if (!wallById.TryGetValue(cutout.HostId, out var wall)) continue; double dx = wall.X2 - wall.X1, dy = wall.Y2 - wall.Y1; @@ -372,7 +421,7 @@ void Grow(double x, double y) if (!gaps.TryGetValue(wall.Id, out var list)) gaps[wall.Id] = list = new List<(double From, double To)>(); list.Add((from, to)); if (insert.CategoryId == (int)BuiltInCategory.OST_Windows) windowGaps.Add((wall.Id, from, to)); - else doorGaps.Add((wall.Id, from, to)); + else if (!savedDoor) doorGaps.Add((wall.Id, from, to)); // The tag of a door is its mark, the tag of a window its type mark: both are placed beside the opening on // the side it opens into. bool isWindow = insert.CategoryId == (int)BuiltInCategory.OST_Windows; @@ -409,7 +458,7 @@ void Grow(double x, double y) if (element.CategoryId != (int)BuiltInCategory.OST_Rooms) continue; if (element.LookupParameter(BuiltInParameter.ROOM_LEVEL_ID)?.Value is not int roomLevel || roomLevel != levelId) continue; - if (element.SerializedSpaceBoundary is not { Faces.Count: > 0 } boundary) continue; + if (element.SerializedSpaceBoundaryCurrent is not { Faces.Count: > 0 } boundary) continue; List<(double X, double Y)>? polygon = null; double bestArea = 0; foreach (var face in boundary.Faces) @@ -424,7 +473,8 @@ void Grow(double x, double y) polygon = candidate; } if (polygon == null) continue; - double areaFeet = element.LookupParameter(BuiltInParameter.ROOM_AREA)?.Value is double value ? value : 0; + double areaFeet = element.LookupParameter(BuiltInParameter.ROOM_AREA)?.Value is double value + ? value : bestArea / (FeetToMillimetres * FeetToMillimetres); string number = element.LookupParameter(BuiltInParameter.ROOM_NUMBER)?.Value as string ?? ""; rooms.Add((polygon, element.Name ?? "", number, areaFeet)); } @@ -448,7 +498,8 @@ void Grow(double x, double y) var layers = type?.SerializedHostTypeLayers; if (layers is not { Length: > 0 } || layers[0].RawMaterialId <= 0) continue; if (!materialPatterns.TryGetValue(layers[0].RawMaterialId, out var material) - || material.SurfacePatternId <= 0 || !fillPatterns.ContainsKey(material.SurfacePatternId)) continue; + || !fillPatterns.TryGetValue(material.SurfacePatternId, out var surfacePattern) + || surfacePattern.Grids.Count == 0) continue; List<(double X, double Y)>? top = null; double topZ = double.MinValue; foreach (var face in geometry.Faces) @@ -488,15 +539,23 @@ void Grow(double x, double y) { if (insert.CategoryId is not ((int)BuiltInCategory.OST_Doors or (int)BuiltInCategory.OST_Windows)) continue; if (insert.OwnSingleFamilyCutout is not { } cutout || cutout.Transform is not { Length: 12 } matrix) continue; + // A roof opening projects a separate plan outline. Wall loops are used for the jambs. + bool roofOpening = document.GetElement(cutout.HostId)?.CategoryId == (int)BuiltInCategory.OST_Roofs; + if (roofOpening && hiddenOpenings?.Contains(insert.Id) == true) continue; var points = new List<(double X, double Y)>(cutout.Loop.Vertices.Count); + double low = double.PositiveInfinity, high = double.NegativeInfinity; foreach (var vertex in cutout.Loop.Vertices) { double wx = (matrix[0] * vertex[0] + matrix[1] * vertex[1] + matrix[2] * vertex[2] + matrix[9]) * FeetToMillimetres; double wy = (matrix[3] * vertex[0] + matrix[4] * vertex[1] + matrix[5] * vertex[2] + matrix[10]) * FeetToMillimetres; + double z = matrix[6] * vertex[0] + matrix[7] * vertex[1] + matrix[8] * vertex[2] + matrix[11]; + low = Math.Min(low, z); + high = Math.Max(high, z); points.Add((wx, wy)); } + if (roofOpening && planRange is { } range && (high < range.Bottom || low > range.Top)) continue; if (points.Count >= 3) openingLoops.Add(points); } @@ -519,17 +578,96 @@ void Grow(double x, double y) var furniture = new List>(); var furnitureKeys = new HashSet(StringComparer.Ordinal); var furnitureLines = new List<(double X1, double Y1, double X2, double Y2)>(); + var furnitureFill = new List>(); + List<(double X1, double Y1, double X2, double Y2, int StyleId)>? fixtureLines = null; + bool opaqueFurniture = viewId is int fixtureView && document.RawData.OpaquePlanViews?.Contains(fixtureView) == true; + int? planDetail = viewId is int detailView + ? document.GetElement(detailView)?.LookupParameter(BuiltInParameter.VIEW_DETAIL_LEVEL)?.Value as int? + : null; + var hiddenFurniture = viewId is int hiddenView ? document.RawData.ViewHiddenElements?.GetValueOrDefault(hiddenView) : null; + var savedStairs = new HashSet(); + var savedTopRails = new HashSet(); + var stairTopRails = opaqueFurniture && planRange != null + ? (from rail in document.Elements + where rail is { CategoryId: (int)BuiltInCategory.OST_RailingTopRail, RootClassName: "TopRail", + SerializedOwningElementId: > 0, Geometry.Faces.Count: > 0 } + && hiddenFurniture?.Contains(rail.Id) != true + let owner = rail.SerializedOwningElementId.GetValueOrDefault() + where hiddenFurniture?.Contains(owner) != true + let host = document.GetElement(owner)?.SerializedRailingStairHostId ?? 0 + where host > 0 + select (Host: host, Rail: rail)).ToLookup(item => item.Host, item => item.Rail) + : null; foreach (var element in document.Elements) { - if (element.CategoryId is not ((int)BuiltInCategory.OST_Furniture or (int)BuiltInCategory.OST_Casework + // Generic families entirely below the cut draw their projection in the visible portion of the plan. + bool projectedFamily = element.CategoryId is (int)BuiltInCategory.OST_Furniture or (int)BuiltInCategory.OST_Casework or (int)BuiltInCategory.OST_PlumbingFixtures or (int)BuiltInCategory.OST_SpecialityEquipment - or (int)BuiltInCategory.OST_Stairs or (int)BuiltInCategory.OST_StairsRailing)) + or (int)BuiltInCategory.OST_FurnitureSystems + || element is { CategoryId: (int)BuiltInCategory.OST_GenericModel, RootClassName: "FamilyInstance", + BoundingBox: { Length: 6 } box } && planRange is { } range + && double.IsFinite(box[5]) && box[5] < range.Cut; + if (!projectedFamily && element.CategoryId is not ((int)BuiltInCategory.OST_Stairs or (int)BuiltInCategory.OST_StairsRailing)) continue; - if (LevelOf(element) != levelId || element.Geometry is not { Faces.Count: > 0 } geometry) continue; - if (element.CategoryId is (int)BuiltInCategory.OST_Furniture or (int)BuiltInCategory.OST_Casework - or (int)BuiltInCategory.OST_PlumbingFixtures or (int)BuiltInCategory.OST_SpecialityEquipment) + if (element.PlacedPlanFixtureGraphics is { } fixture && element.Geometry is not { Faces.Count: > 0 }) + { + if (hiddenFurniture?.Contains(element.Id) == true || !FurnitureInView(element, levelId, planRange)) + continue; + foreach (var line in fixture.Lines) + (fixtureLines ??= []).Add((line.Start[0] * FeetToMillimetres, line.Start[1] * FeetToMillimetres, + line.End[0] * FeetToMillimetres, line.End[1] * FeetToMillimetres, line.StyleId)); + if (opaqueFurniture) + foreach (var mask in fixture.Masks) + { + var ring = mask.Select(point => (point[0] * FeetToMillimetres, point[1] * FeetToMillimetres)).ToList(); + if (SignedArea(ring) < 0) ring.Reverse(); + furnitureFill.Add(ring); + } + continue; + } + if (element.CategoryId == (int)BuiltInCategory.OST_Stairs + && opaqueFurniture && viewId is int planView && planRange is { } stairRange + && OnLevel(element, levelId) && hiddenFurniture?.Contains(element.Id) != true + && CollectSavedStair(document, element, planView, levelId, stairRange, stairTopRails?[element.Id] ?? [], + savedTopRails, furnitureFill, ref fixtureLines)) { - var outline = SilhouetteLines(element, 5.0); + savedStairs.Add(element.Id); + continue; + } + if (element.Geometry is not { Faces.Count: > 0 } geometry) continue; + if (projectedFamily) + { + if (hiddenFurniture?.Contains(element.Id) == true || element.RootClassName == "FamilySymbol" + || !FurnitureInView(element, levelId, planRange)) + continue; + if (opaqueFurniture && planRange != null && planDetail == 2 + && element.PlacedPlanFixtureGraphics?.MediumProjection is { Masks.Count: > 0 } projection + && geometry.Faces.Any(face => face.ExcludedFromTopPlan) + && (element.CategoryId == (int)BuiltInCategory.OST_PlumbingFixtures + ? geometry.Faces.All(face => face.ExcludedFromTopPlan || face.GeometryNode < 0) + : FixtureProjectionCoversBody(projection, geometry))) + { + foreach (var line in projection.Lines) + (fixtureLines ??= []).Add((line.Start[0] * FeetToMillimetres, line.Start[1] * FeetToMillimetres, + line.End[0] * FeetToMillimetres, line.End[1] * FeetToMillimetres, line.StyleId)); + foreach (var mask in projection.Masks) + { + var ring = mask.Select(InPlan).ToList(); + if (SignedArea(ring) < 0) ring.Reverse(); + furnitureFill.Add(ring); + } + continue; + } + var faces = opaqueFurniture && element.CategoryId == (int)BuiltInCategory.OST_Furniture + ? FurnitureFaces(geometry.Faces.Where(face => !face.ExcludedFromTopPlan)) : null; + // A direction filter can replace the entire model with a symbol. Until that + // symbol is decoded, retain the model silhouette when no faces can project. + if (faces is not { Count: > 0 }) faces = FurnitureFaces(geometry.Faces); + bool containedFixture = opaqueFurniture && planRange is { } fixtureRange + && element.BoundingBox is { Length: 6 } fixtureBounds + && fixtureBounds[2] >= fixtureRange.Bottom && fixtureBounds[5] <= fixtureRange.Cut + && element.CategoryId is ((int)BuiltInCategory.OST_PlumbingFixtures or (int)BuiltInCategory.OST_GenericModel); + var outline = (containedFixture ? FixtureProfiles(geometry) : null) ?? SilhouetteLines(faces, 5.0); if (outline.Count == 0) continue; double sMinX = outline.Min(s => Math.Min(s.X1, s.X2)); double sMaxX = outline.Max(s => Math.Max(s.X1, s.X2)); @@ -538,8 +676,17 @@ void Grow(double x, double y) string silhouetteKey = $"{sMinX:0}:{sMinY:0}:{sMaxX:0}:{sMaxY:0}"; if (!furnitureKeys.Add(silhouetteKey)) continue; furnitureLines.AddRange(outline); + if (opaqueFurniture) + { + foreach (var face in faces) + { + furnitureFill.Add(face.Outer); + furnitureFill.AddRange(face.Holes); + } + } continue; } + if (LevelOf(element) != levelId) continue; foreach (var face in geometry.Faces) { if (Math.Abs(face.Normal[2]) < 0.9) continue; @@ -568,12 +715,22 @@ void Grow(double x, double y) const double annotation = 1000; minX -= annotation; minY -= annotation; maxX += annotation; maxY += annotation; var stairLines = new List<(double X1, double Y1, double X2, double Y2)>(); - CollectStairLines(document, levelId, stairLines); + CollectStairLines(document, levelId, savedStairs, stairLines); var railLines = new List<(double X1, double Y1, double X2, double Y2)>(); - CollectRailingLines(document, levelId, viewId, railLines); + CollectRailingLines(document, levelId, viewId, savedTopRails, railLines); + var colors = viewId is int planId ? document.RawData.ViewRoomColors?.GetValueOrDefault(planId) : null; return new PlanContent(walls, columns, grids, gaps, windowGaps, doorGaps, floorLoops, openingLoops, rooms, - furniture, tags, minX, minY, maxX, maxY, roomPatterns, stairLines, railLines, furnitureLines); + furniture, tags, minX, minY, maxX, maxY, roomPatterns, stairLines, railLines, furnitureLines, colors, furnitureFill) + { + DoorSymbols = doorSymbols, FixtureLines = fixtureLines, ColumnProfiles = columnProfiles, + ProjectedWallTops = viewId is int wallView && planRange is { } wallRange + && document.RawData.UnshadedHiddenLineViews?.Contains(wallView) == true + ? CollectProjectedWallTops(document, walls.Select(wall => wall.Id), gaps, wallRange.Bottom, wallRange.Cut) + : null, + CurtainProfiles = viewId is int curtainView && cutHeight is double curtainCut + ? CollectCurtainProfiles(document, curtainView, curtainCut, planRange?.Bottom) : null, + }; } /// True when the element belongs to the plan of the level. A stair runs from its base level to its top @@ -587,13 +744,14 @@ private static bool OnLevel(Element element, int levelId) /// The plan linework of a stair: the outlines of its horizontal faces (tread and landing tops) seen from /// above, which is what a plan draws as the tread courses between the stair's sides. - private static void CollectStairLines(RvtDocument document, int levelId, + private static void CollectStairLines(RvtDocument document, int levelId, HashSet savedStairs, List<(double X1, double Y1, double X2, double Y2)> lines) { var keys = new HashSet(StringComparer.Ordinal); foreach (var element in document.Elements) { - if (element.CategoryId != (int)BuiltInCategory.OST_Stairs || !OnLevel(element, levelId)) continue; + if (element.CategoryId != (int)BuiltInCategory.OST_Stairs || savedStairs.Contains(element.Id) + || !OnLevel(element, levelId)) continue; if (element.Geometry is not { Faces.Count: > 0 } geometry) continue; foreach (var face in geometry.Faces) { @@ -620,7 +778,7 @@ private static void CollectStairLines(RvtDocument document, int levelId, /// the deck edge. The view range's top and bottom clips decide which rails are visible (a roof deck's rails /// stand below the plan's level but above its bottom clip), so an element outside the band is skipped; a /// view without a decoded range keeps only the rails of the plan's own level. - private static void CollectRailingLines(RvtDocument document, int levelId, int? viewId, + private static void CollectRailingLines(RvtDocument document, int levelId, int? viewId, HashSet savedTopRails, List<(double X1, double Y1, double X2, double Y2)> lines) { double levelElevation = document.GetElement(levelId)?.LookupParameter(BuiltInParameter.LEVEL_ELEV)?.Value @@ -639,7 +797,8 @@ private static void CollectRailingLines(RvtDocument document, int levelId, int? var keys = new HashSet(StringComparer.Ordinal); foreach (var element in document.Elements) { - if (element.CategoryId != (int)BuiltInCategory.OST_RailingTopRail) continue; + if (element.CategoryId != (int)BuiltInCategory.OST_RailingTopRail || savedTopRails.Contains(element.Id) + || element.SerializedOwningElementId is int owner && savedTopRails.Contains(owner)) continue; if (element.Geometry is not { Faces.Count: > 0 } geometry) continue; if (banded) { @@ -718,7 +877,8 @@ internal static void DrawContent(PdfPage page, PlanContent content, double scale IReadOnlyList? sectionMarks = null, RvtDocument? document = null, (double X0, double Y0, double X1, double Y1)? frame = null, - (double X0, double Y0, double X1, double Y1)? clipRect = null) + (double X0, double Y0, double X1, double Y1)? clipRect = null, bool drawGrids = true, + bool drawFallbackDimensions = true, int? planViewId = null) { double ToX(double x) => (x - content.MinX) / scale + originX; double ToY(double y) => (y - content.MinY) / scale + originY; @@ -728,14 +888,13 @@ internal static void DrawContent(PdfPage page, PlanContent content, double scale // section trace with the Sections projection pen (pen 1 annotates 0.1 mm on the reference, where // the old hardcoded 0.22 mm inked every trace heavy). int scaleDenominator = (int)Math.Round(scale); - double wallLine = 0.2, gridLine = 0.18, furnitureLine = 0.12, columnLine = 0.2, sectionLine = 0.1; + double wallLine = 0.2, gridLine = 0.18, furnitureLine = 0.12, columnLine = 0.2; if (document != null) { if (PenWidths.TryGetWidth(document, (int)BuiltInCategory.OST_Walls, true, scaleDenominator, out double w)) wallLine = w; if (PenWidths.TryGetWidth(document, (int)BuiltInCategory.OST_Columns, true, scaleDenominator, out double c)) columnLine = c; if (PenWidths.TryGetWidth(document, (int)BuiltInCategory.OST_Grids, false, scaleDenominator, out double g)) gridLine = g; if (PenWidths.TryGetWidth(document, (int)BuiltInCategory.OST_Furniture, false, scaleDenominator, out double f)) furnitureLine = f; - if (PenWidths.TryGetWidth(document, (int)BuiltInCategory.OST_Sections, false, scaleDenominator, out double s)) sectionLine = s; } foreach (var floor in content.FloorLoops) @@ -743,7 +902,7 @@ internal static void DrawContent(PdfPage page, PlanContent content, double scale foreach (var room in content.Rooms) page.DrawPolyline(room.Polygon.Select(point => (ToX(point.X), ToY(point.Y))).ToList(), 0, true, - RoomFill(room.Name)); + RoomFill(room.Name, content.RoomColors)); // A room's floor material may name a surface pattern (the sunken living room's carpet names "Sand"): // the reference prints that hatch inside the room's colour fill, and both the material and the pattern @@ -758,7 +917,7 @@ internal static void DrawContent(PdfPage page, PlanContent content, double scale double[]? gridDashes = document != null && LinePatterns.TryGetGridDashes(document, out var decodedGrid) ? decodedGrid : [36.0, 9.0, 9.0, 9.0]; - foreach (var grid in content.Grids) + foreach (var grid in drawGrids ? content.Grids : []) { // Grids run past the crop to their bubbles (the reference draws them to the bubble row, like // rvt-prt growing the crop by the type end length): cutting them at the crop edge loses the @@ -771,11 +930,33 @@ internal static void DrawContent(PdfPage page, PlanContent content, double scale Bubble(page, ToX(grid.X2), ToY(grid.Y2), grid.Name, gridLine); } + if (content.FurnitureFillRings is { Count: > 0 } furnitureFill) + { + if (clipRect is { } clip) + page.BeginClip(ToX(clip.X0), ToY(clip.Y0), ToX(clip.X1) - ToX(clip.X0), ToY(clip.Y1) - ToY(clip.Y0)); + page.FillPolygonUnion(furnitureFill.Select(ring => ring.Select(point => (ToX(point.X), ToY(point.Y))).ToArray()), 1); + if (clipRect != null) page.EndClip(); + } + var wallById = new Dictionary(); foreach (var wall in content.Walls) wallById[wall.Id] = wall; - + double wallShade = planViewId is int viewId && document?.RawData.UnshadedHiddenLineViews?.Contains(viewId) == true + ? 1 : 0.72; + var wallFill = new PdfColor(wallShade, wallShade, wallShade); + var wallCuts = wallShade == 1 && document != null && planViewId is int cutView + ? CollectWallCuts(document, cutView, content) : []; + + double wallProjectionLine = document != null + && PenWidths.TryGetWidth(document, (int)BuiltInCategory.OST_Walls, false, scaleDenominator, out double projectionWidth) + ? projectionWidth : wallLine; foreach (var wall in content.Walls) { + if (wallCuts.ContainsKey(wall.Id)) continue; + if (content.ProjectedWallTops?.TryGetValue(wall.Id, out var top) == true) + { + DrawClippedOutline(page, top, ToX, ToY, wallProjectionLine, wallFill, clipRect); + continue; + } double dx = wall.X2 - wall.X1, dy = wall.Y2 - wall.Y1; double length = Math.Sqrt(dx * dx + dy * dy); if (length < 1e-9) continue; @@ -785,13 +966,24 @@ internal static void DrawContent(PdfPage page, PlanContent content, double scale { double ax = wall.X1 + ux * from, ay = wall.Y1 + uy * from; double bx = wall.X1 + ux * to, by = wall.Y1 + uy * to; - // The wall is poche: the stretch between its two sides is filled, the way a printed plan fills a cut - // wall, and the four edges are inked over it. + // The wall fill masks the plan geometry underneath before its cut edges are inked. DrawClippedOutline(page, [ (ax + nx, ay + ny), (bx + nx, by + ny), (bx - nx, by - ny), (ax - nx, ay - ny), - ], ToX, ToY, wallLine, new PdfColor(0.72, 0.72, 0.72), clipRect); + ], ToX, ToY, wallLine, wallFill, clipRect); + } + } + DrawWallCuts(page, wallCuts, ToX, ToY, wallLine, clipRect); + if (document != null && content.CurtainProfiles is { Count: > 0 } curtainProfiles) + { + foreach (var style in curtainProfiles.GroupBy(profile => (profile.IsCut, profile.CategoryId)) + .OrderBy(group => group.Key.IsCut)) + { + double width = PenWidths.TryGetWidth(document, style.Key.CategoryId, style.Key.IsCut, + scaleDenominator, out double savedWidth) ? savedWidth : wallLine; + foreach (var profile in style) + DrawClippedOutline(page, profile.Ring, ToX, ToY, width, new PdfColor(1, 1, 1), clipRect); } } @@ -807,8 +999,8 @@ internal static void DrawContent(PdfPage page, PlanContent content, double scale ToX(wall.X1 + ux * to), ToY(wall.Y1 + uy * to), 0.15, 0.35); } - // The room names and areas, at the centre of the footprint, in plan millimetres. - if (page.Owner.Font != null) + // A level-only print has no owning view and keeps the footprint-based room labels. + if (page.Owner.Font != null && !DrawPlanRoomTags(page, document, planViewId, ToX, ToY)) { foreach (var room in content.Rooms) { @@ -825,7 +1017,7 @@ internal static void DrawContent(PdfPage page, PlanContent content, double scale 0.18, true, 1); page.DrawText(room.Number, pageX - boxWidth / 2 + 2, pageY - 1.1, 2.4); if (room.AreaSquareFeet > 0) - page.DrawText($"{room.AreaSquareFeet * 0.092903:0} m²", pageX + boxWidth / 2 - 2, pageY - 1, + page.DrawText(LocalizeRoomArea($"{room.AreaSquareFeet * 0.092903:0} m²"), pageX + boxWidth / 2 - 2, pageY - 1, 2, PdfTextAlignment.Right); } } @@ -859,6 +1051,9 @@ internal static void DrawContent(PdfPage page, PlanContent content, double scale else page.DrawLine(ToX(line.X1), ToY(line.Y1), ToX(line.X2), ToY(line.Y2), furnitureLine); } + if (content.FixtureLines is { Count: > 0 } fixtureLines) + DrawFixtureLines(page, document, fixtureLines, scale, furnitureLine, ToX, ToY, clipRect); + foreach (var line in content.RailLines ?? []) { if (clipRect is { } railClip) @@ -876,8 +1071,8 @@ internal static void DrawContent(PdfPage page, PlanContent content, double scale // wall and on the side of the building the door opens into. double centerX = (content.MinX + content.MaxX) / 2, centerY = (content.MinY + content.MaxY) / 2; - // The marks of the doors and windows, in a small circle beside the opening. - if (page.Owner.Font != null) + // A generated level has no owning view for its opening marks. + if (page.Owner.Font != null && !DrawPlanOpeningTags(page, document, planViewId, ToX, ToY)) { foreach (var tag in content.Tags) { @@ -902,6 +1097,10 @@ internal static void DrawContent(PdfPage page, PlanContent content, double scale } } + if (content.DoorSymbols is { Count: > 0 } savedDoors) + foreach (var saved in savedDoors) + DrawDoorPlanSymbol(page, saved.Symbol, saved.Transform, scale, ToX, ToY, clipRect); + foreach (var door in content.DoorGaps) { if (!wallById.TryGetValue(door.HostId, out var wall)) continue; @@ -914,10 +1113,7 @@ internal static void DrawContent(PdfPage page, PlanContent content, double scale double hx = wall.X1 + ux * door.From, hy = wall.Y1 + uy * door.From; double ex = wall.X1 + ux * door.To, ey = wall.Y1 + uy * door.To; double midX = (hx + ex) / 2, midY = (hy + ey) / 2; - // The swing side: the file stores a per-instance flip that the reader does not decode, so the - // side comes from the building centroid — and it opens away from it. Measured on the sample - // plan, opening away is the side the reference draws (A102 precision 90.3 -> 90.5, 6 in fewer - // unmatched segments, recall unchanged). + // shortcut: use the existing swing approximation when no matching saved cut symbol is available. double side = (centerX - midX) * nx + (centerY - midY) * ny >= 0 ? -1 : 1; double tipX = hx + nx * side * width, tipY = hy + ny * side * width; double ex0 = hx, ey0 = hy, ex1 = tipX, ey1 = tipY; @@ -931,15 +1127,15 @@ internal static void DrawContent(PdfPage page, PlanContent content, double scale page.DrawArc(ToX(hx), ToY(hy), width / scale, a0, a1, 0.15, 0.4); } - DimChains(page, content, ToX, ToY, clipRect); + if (drawFallbackDimensions) DimChains(page, content, ToX, ToY, clipRect); foreach (var opening in content.OpeningLoops) DrawClippedOutline(page, opening, ToX, ToY, 0.18, (PdfColor?)null, clipRect); - foreach (var column in content.Columns) - page.DrawRectangle(ToX(column.X), ToY(column.Y), column.Width / scale, column.Height / scale, columnLine, 1); + DrawColumns(page, document, content, scale, columnLine, ToX, ToY, clipRect); - if (sectionMarks is { Count: > 0 }) DrawSectionMarks(page, content, scale, originX, originY, sectionMarks, frame, sectionLine); + if (sectionMarks is { Count: > 0 }) + DrawSectionMarks(page, content, scale, originX, originY, sectionMarks, frame, document, planViewId); } /// Draws the plan of a level as one page of the document. @@ -1012,10 +1208,14 @@ void Corner(double cx, double cy, double from) /// Draws the section marks of a plan: the trace of each section plane across the drawing, a tick at both /// ends and a bubble with the letter of the view, as a plan shows where it is cut. - private static void DrawSectionMarks(PdfPage page, PlanContent content, double scale, double originX, + internal static void DrawSectionMarks(PdfPage page, PlanContent content, double scale, double originX, double originY, IReadOnlyList marks, - (double X0, double Y0, double X1, double Y1)? frame = null, double sectionLine = 0.1) + (double X0, double Y0, double X1, double Y1)? frame, RvtDocument? document, int? planViewId) { + if (marks.Count == 0) return; + double sectionLine = document != null + && PenWidths.TryGetWidth(document, (int)BuiltInCategory.OST_Sections, false, (int)Math.Round(scale), out double width) + ? width : 0.1; double ToX(double x) => (x - content.MinX) / scale + originX; double ToY(double y) => (y - content.MinY) / scale + originY; // The trace runs across the building, not across the site: its ends are the bounds of the walls. @@ -1059,6 +1259,10 @@ bool inside(double value, double direction, double low, double high) line = [(px + dx * tMin, py + dy * tMin), (px + dx * tMax, py + dy * tMax)]; } if (line.Count < 2) continue; + if (document != null && planViewId is int planId && mark.Bounded + && (line.Count == 2 || mark.UsesPlanExtent) + && TryDrawFilledSectionMark(page, document, planId, mark.ViewId, line, frame, sectionLine)) + continue; // The scorer counts vectors, not the page clip: cut every leg to the viewport frame at generation, // so nothing is inked outside the drawn frame. Legs clipped apart stay apart (no connectors). var runs = new List>(); @@ -1191,8 +1395,10 @@ static List Dedupe(List values) /// green, a hall blue, a kitchen tan, a laundry brown, a living room light green, a mechanical room green, a master /// bedroom blue violet, a master bath magenta, a bedroom cyan, an entry hall yellow, a linen teal; anything else light /// grey. - internal static PdfColor RoomFill(string name) + internal static PdfColor RoomFill(string name, IReadOnlyDictionary? colors = null) { + if (colors != null && colors.TryGetValue(name, out uint rgb)) + return new PdfColor((rgb & 255) / 255.0, ((rgb >> 8) & 255) / 255.0, ((rgb >> 16) & 255) / 255.0); string lower = name.ToLowerInvariant(); PdfColor color = lower switch { @@ -1215,7 +1421,7 @@ internal static PdfColor RoomFill(string name) } /// The signed area of a polygon (shoelace); its magnitude is the area and its sign the winding. - private static double SignedArea(List<(double X, double Y)> points) + internal static double SignedArea(List<(double X, double Y)> points) { double sum = 0; for (int i = 0; i < points.Count; i++) @@ -1227,58 +1433,8 @@ private static double SignedArea(List<(double X, double Y)> points) return sum / 2; } - /// The plan silhouette of a piece of furniture: the boundary of the union of all its faces projected on - /// XY, traced on a grid of millimetres. The non-convex plan shape (a chair back, the gap - /// between legs) survives, which the convex hull and the single top face both lose. - private static List<(double X1, double Y1, double X2, double Y2)> SilhouetteLines( - Element element, double cell) - { - if (element.Geometry is not { Faces.Count: > 0 } geometry) return []; - var faces = new List<(List<(double X, double Y)> Points, double MinX, double MaxX, double MinY, double MaxY)>(); - foreach (var face in geometry.Faces) - { - if (face.OuterVertices is not { Count: >= 3 } vertices) continue; - var points = vertices.Select(vertex => (X: vertex[0] * FeetToMillimetres, - Y: vertex[1] * FeetToMillimetres)).ToList(); - faces.Add((points, points.Min(point => point.X), points.Max(point => point.X), - points.Min(point => point.Y), points.Max(point => point.Y))); - } - if (faces.Count == 0) return []; - double x0 = faces.Min(face => face.MinX), x1 = faces.Max(face => face.MaxX); - double y0 = faces.Min(face => face.MinY), y1 = faces.Max(face => face.MaxY); - int nx = (int)Math.Ceiling((x1 - x0) / cell) + 1; - int ny = (int)Math.Ceiling((y1 - y0) / cell) + 1; - if (nx < 1 || ny < 1 || (long)nx * ny > 400_000) return []; - var inside = new bool[nx, ny]; - for (int i = 0; i < nx; i++) - for (int j = 0; j < ny; j++) - { - double cx = x0 + (i + 0.5) * cell, cy = y0 + (j + 0.5) * cell; - foreach (var face in faces) - { - if (cx < face.MinX || cx > face.MaxX || cy < face.MinY || cy > face.MaxY) continue; - if (!PointInPolygon(cx, cy, face.Points)) continue; - inside[i, j] = true; - break; - } - } - var lines = new List<(double X1, double Y1, double X2, double Y2)>(); - for (int i = 0; i < nx; i++) - for (int j = 0; j < ny; j++) - { - if (!inside[i, j]) continue; - double left = x0 + i * cell, right = left + cell; - double bottom = y0 + j * cell, top = bottom + cell; - if (i == 0 || !inside[i - 1, j]) lines.Add((left, bottom, left, top)); - if (i == nx - 1 || !inside[i + 1, j]) lines.Add((right, bottom, right, top)); - if (j == 0 || !inside[i, j - 1]) lines.Add((left, bottom, right, bottom)); - if (j == ny - 1 || !inside[i, j + 1]) lines.Add((left, top, right, top)); - } - return lines; - } - /// Even-odd point-in-polygon test on a closed outline. - private static bool PointInPolygon(double x, double y, IReadOnlyList<(double X, double Y)> polygon) + internal static bool PointInPolygon(double x, double y, IReadOnlyList<(double X, double Y)> polygon) { bool inside = false; for (int i = 0, j = polygon.Count - 1; i < polygon.Count; j = i++) diff --git a/src/RvtIO/Print/RvtRaster.cs b/src/RvtIO/Print/RvtRaster.cs index 55aff259..0782eaf1 100644 --- a/src/RvtIO/Print/RvtRaster.cs +++ b/src/RvtIO/Print/RvtRaster.cs @@ -54,6 +54,31 @@ internal static class RvtRaster /// image the PDF writer embeds as it is. A rendering of a 3D view is stored that way, in the block of its image /// symbol's type. internal static PdfJpegImage? FindJpeg(string path, int elementId) + { + var block = FindBlock(path, elementId, 0x0890); + if (block == null) return null; + var payload = block.AsSpan(16); + int start = payload.IndexOf(new byte[] { 0xFF, 0xD8, 0xFF }); + int end = payload.LastIndexOf(new byte[] { 0xFF, 0xD9 }); + return start >= 0 && end > start ? new PdfJpegImage(payload[start..(end + 2)].ToArray()) : null; + } + + internal static PdfRasterImage? FindImagePng(string path, int elementId) + { + var block = FindBlock(path, elementId, 0x0890); + if (block == null) return null; + var payload = block.AsSpan(16); + int start = payload.IndexOf(new byte[] { 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A }); + return start >= 0 ? DecodePng(payload[start..].ToArray()) : null; + } + + internal static IReadOnlyList FindSheetImagePlacements(string path, int symbolId) + { + var block = FindBlock(path, symbolId, 0x07D7); + return block == null ? [] : GRepParserV2.ReadSheetImages(block); + } + + private static byte[]? FindBlock(string path, int elementId, int lowClass) { try { @@ -75,16 +100,8 @@ internal static class RvtRaster if (eid != (uint)elementId) continue; int size = BinaryPrimitives.ReadInt32LittleEndian(chunk.AsSpan(pos + 8)); uint classIdx = BinaryPrimitives.ReadUInt32LittleEndian(chunk.AsSpan(pos + 12)); - if (size <= 0 || pos + 16 + size > chunk.Length || (classIdx & 0xFFFF) != 0x0890) continue; - var payload = chunk.AsSpan(pos + 16, size); - int start = payload.IndexOf(new byte[] { 0xFF, 0xD8, 0xFF }); - if (start < 0) return null; - var jpeg = payload[start..].ToArray(); - // The end of the JPEG is its last end-of-image marker; anything after it is padding. - int end = jpeg.AsSpan().LastIndexOf(new byte[] { 0xFF, 0xD9 }); - if (end < 0) return null; - Array.Resize(ref jpeg, end + 2); - return new PdfJpegImage(jpeg); + if (size <= 0 || (long)pos + 16 + size > chunk.Length || (classIdx & 0xFFFF) != lowClass) continue; + return chunk.AsSpan(pos, 16 + size).ToArray(); } } } @@ -150,7 +167,7 @@ internal static class RvtRaster if (png.Length < 8 || png[0] != 0x89 || png[1] != 0x50 || png[2] != 0x4E || png[3] != 0x47) return null; int at = 8, width = 0, height = 0, depth = 0, colorType = 0; - var idat = new MemoryStream(); + using var idat = new MemoryStream(); byte[]? palette = null; byte[]? alpha = null; while (at + 8 <= png.Length) @@ -158,9 +175,10 @@ internal static class RvtRaster int length = BinaryPrimitives.ReadInt32BigEndian(png.AsSpan(at)); string type = System.Text.Encoding.ASCII.GetString(png, at + 4, 4); int data = at + 8; - if (length < 0 || data + length + 4 > png.Length) return null; + if (length < 0 || length > png.Length - data - 4) return null; if (type == "IHDR") { + if (length != 13) return null; width = BinaryPrimitives.ReadInt32BigEndian(png.AsSpan(data)); height = BinaryPrimitives.ReadInt32BigEndian(png.AsSpan(data + 4)); depth = png[data + 8]; @@ -175,16 +193,22 @@ internal static class RvtRaster } if (width <= 0 || height <= 0 || depth != 8) return null; int bpp = colorType switch { 2 => 3, 6 => 4, 3 => 1, 0 => 1, _ => 0 }; - if (bpp == 0) return null; + const int maxDecodedBytes = 128 * 1024 * 1024; + if (bpp == 0 || (long)width * bpp + 1 > maxDecodedBytes / height + || (long)width * height > maxDecodedBytes / 3) return null; + int stride = width * bpp; idat.Position = 0; - byte[] pixels; - using (var zlib = new ZLibStream(idat, CompressionMode.Decompress)) - using (var output = new MemoryStream()) + var pixels = new byte[(stride + 1) * height]; + try { - zlib.CopyTo(output); - pixels = output.ToArray(); + using var zlib = new ZLibStream(idat, CompressionMode.Decompress); + zlib.ReadExactly(pixels); + if (zlib.ReadByte() != -1) return null; + } + catch (Exception exception) when (exception is InvalidDataException or EndOfStreamException) + { + return null; } - int stride = width * bpp; var rows = new List(height); int pos = 0; byte[] previous = new byte[stride]; @@ -192,6 +216,7 @@ internal static class RvtRaster { if (pos + 1 + stride > pixels.Length) return null; byte filter = pixels[pos++]; + if (filter > 4) return null; var row = new byte[stride]; Array.Copy(pixels, pos, row, 0, stride); pos += stride; diff --git a/src/RvtIO/Print/ShadedViewport.cs b/src/RvtIO/Print/ShadedViewport.cs new file mode 100644 index 00000000..cb4939e7 --- /dev/null +++ b/src/RvtIO/Print/ShadedViewport.cs @@ -0,0 +1,378 @@ +using RvtIO.BuiltIns; +using RvtIO.Model; +using RvtIO.Pdf; + +namespace RvtIO.Print; + +internal static class ShadedViewport +{ + private readonly record struct Point(double X, double Y, double Depth); + private sealed record Surface(Point[][] Rings, double DepthX, double DepthY, int Rgb, bool FacesLight, double Transmission, + ViewportSurfacePattern? Pattern, ViewportSurfaceEdges? Edges); + private readonly record struct Pane(Surface Surface, int Order, int FirstRow, int LastRow); + private readonly record struct PaneSpan(Pane Pane, int Start, int End); + private readonly record struct PaneHit(Pane Pane, double Depth, double PatternInk, double EdgeInk); + + internal static (double X, double Y, double Width, double Height)? Render(PdfPage page, RvtDocument document, + Element view, double anchorX, double anchorY, int scale) + { + if (view.ViewCrop is not { } camera || view.OrthographicModelBounds is not { } box + || scale <= 0 || !double.IsFinite(anchorX) || !double.IsFinite(anchorY)) return null; + double factor = 304.8 / scale; + (double X, double Y) ProjectVector(double[] point) => + (factor * Dot(point[0], point[1], point[2], camera.Right), factor * Dot(point[0], point[1], point[2], camera.Up)); + Point Project(double[] point) + { + double x = point[0] - camera.OriginX, y = point[1] - camera.OriginY, z = point[2] - camera.OriginZ; + return new(anchorX + factor * Dot(x, y, z, camera.Right), + anchorY + factor * Dot(x, y, z, camera.Up), Dot(x, y, z, camera.Look)); + } + var solar = SolarStudyOverlay.Create(document, view, camera, factor, point => + { + var p = Project(point); + return (p.X, p.Y); + }); + var shadows = view.SolarStudy?.ShadowIntensity is > 0 and <= 100 and int intensity + && solar?.ModelSunDirection is { Z: > 0 } sun + ? new ViewportShadows(camera, sun, intensity, solar.GroundElevation) : null; + var annotation = solar is { AnnotationVisible: true } ? solar : null; + bool showPatterns = view.SolarStudy?.ShowSurfacePatterns == true; + bool showEdges = view.SolarStudy?.ShowEdges == true; + var patternOrigin = Project([0, 0, 0]); + var pens = new Dictionary(); + (double Width, int Color) Pen(int category) + { + if (pens.TryGetValue(category, out var value)) return value; + double width = PenWidths.TryGetWidth(document, category, false, scale, out double savedWidth) ? savedWidth : 0.1; + value = (width, PenWidths.TryGetStyle(document, category, false, out _, out int color) + && color is >= 0 and <= 0xffffff ? color : 0); + pens.Add(category, value); + return value; + } + + var planes = Enumerable.Range(0, 6).Where(i => box.Active[i]).Select(i => + { + double[] axis = box.Axes[i / 2]; + double sign = i % 2 == 0 ? 1 : -1; + double[] outward = [axis[0] * sign, axis[1] * sign, axis[2] * sign]; + double offset = sign * box.Offsets[i] + Dot(box.Origin[0], box.Origin[1], box.Origin[2], outward); + return (Index: i, Outward: outward, Offset: offset); + }).ToArray(); + double Distance(double[] point, double[] outward, double offset) => + offset - Dot(point[0], point[1], point[2], outward); + + List<(double[] Point, bool IncomingEdge)> Clip(List ring) + { + var clipped = ring.Select(point => (Point: point, IncomingEdge: true)).ToList(); + foreach (var (_, outward, offset) in planes) + { + if (clipped.Count < 3) break; + clipped = ElevationPrinter.ClipHalfPlane3(clipped, point => Distance(point, outward, offset)); + } + return clipped; + } + + var materials = new Dictionary(); + (int Color, bool TransmitsLight, double Transmission) Material(int id) + { + if (materials.TryGetValue(id, out var material)) return material; + var element = document.GetElement(id); + int rgb = element?.LookupParameter(BuiltInParameter.MATERIAL_PARAM_COLOR)?.Value + is int value and >= 0 and <= 0xffffff ? value : 0xc0c0c0; + // Reserve pure white for the image's transparent background. + if (rgb == 0xffffff) rgb = 0xfefefe; + double transparency = element?.SerializedMaterialTransparency is > 0 and <= 1 and double exact + ? exact : element?.LookupParameter(BuiltInParameter.MATERIAL_PARAM_TRANSPARENCY)?.Value + is int percent and > 0 and <= 100 ? percent / 100d : 0; + // Appearance assets can override the stored graphics transparency. + material = (rgb, element?.SerializedMaterialTransparency > 0, + element?.SerializedMaterialUsesRenderAppearance == true ? 0 : transparency); + materials.Add(id, material); + return material; + } + + var surfaces = new List(); + var hidden = document.RawData.ViewHiddenElements?.GetValueOrDefault(view.Id); + double left = double.PositiveInfinity, right = double.NegativeInfinity; + double bottom = double.PositiveInfinity, top = double.NegativeInfinity; + void AddSurface(Point[][] rings, double[] normal, double facing, int rgb, double transmission = 0, + ViewportSurfacePattern? pattern = null, ViewportSurfaceEdges? edges = null) + { + var outer = rings[0]; + if (transmission >= 1 || outer.Length < 3 || outer.Any(point => !double.IsFinite(point.X) + || !double.IsFinite(point.Y) || !double.IsFinite(point.Depth))) return; + left = Math.Min(left, outer.Min(p => p.X)); + right = Math.Max(right, outer.Max(p => p.X)); + bottom = Math.Min(bottom, outer.Min(p => p.Y)); + top = Math.Max(top, outer.Max(p => p.Y)); + surfaces.Add(new(rings, -Dot(normal[0], normal[1], normal[2], camera.Right) / (factor * facing), + -Dot(normal[0], normal[1], normal[2], camera.Up) / (factor * facing), rgb, + shadows?.FacesLight(normal) == true, transmission, pattern, edges)); + } + + double terrainBase = box.Origin[2] + box.Offsets[5]; + int cutMaterial = document.RawData.SiteCutGraphics?.MaterialId ?? -1; + var terrainSides = box.Active[5] && box.Axes[2][2] > 1 - 1e-8 && cutMaterial > 0 + ? planes.Where(plane => plane.Index < 4 && Math.Abs(plane.Outward[2]) < 1e-8 + && Dot(plane.Outward[0], plane.Outward[1], plane.Outward[2], camera.Look) < -1e-8).ToArray() + : []; + foreach (var element in document.Elements) + { + if (element.Geometry is not { Faces.Count: > 0 } geometry || element.IsDiscovered + || element.OwnerViewId is > 0 || element.SerializedUnplacedOwnerId is > 0 || element.NativeIsSymbol == true + || element.RootClassIs("FamilySymbol") + || element.CategoryId is null or >= 0 || hidden?.Contains(element.Id) == true + || element.CategoryId is (int)BuiltInCategory.OST_Constraints or (int)BuiltInCategory.OST_CLines + or (int)BuiltInCategory.OST_Cameras or (int)BuiltInCategory.OST_LightingFixtureSource) continue; + foreach (var face in geometry.Faces) + { + if (face.OuterVertices is not { Count: >= 3 } ring) continue; + var normal = face.Normal; + double facing = Dot(normal[0], normal[1], normal[2], camera.Look); + bool visible = facing < -1e-8, facesLight = shadows?.FacesLight(normal) == true; + if (!visible && !facesLight) continue; + var clipped = Clip(ring); + if (clipped.Count < 3) continue; + var rings = new List { clipped.Select(vertex => vertex.Point).ToArray() }; + if (face.InnerVertices != null) + rings.AddRange(face.InnerVertices.Select(Clip).Where(hole => hole.Count >= 3) + .Select(hole => hole.Select(vertex => vertex.Point).ToArray())); + var material = Material(face.RenderStyleId ?? face.NestedRenderStyleId ?? 0); + // shortcut: opaque casters, until the renderer can accumulate transmission through separate panes. + if (facesLight && !material.TransmitsLight) shadows!.AddCaster(rings, normal); + if (!visible) continue; + ViewportSurfacePattern? pattern = null; + int category = element.CategoryId.Value; + if (showPatterns && face.ModelPattern != null) + { + int pen = category == (int)BuiltInCategory.OST_Roofs ? (int)BuiltInCategory.OST_RoofsSurfacePattern : category; + pattern = ViewportSurfacePattern.Create(document, face, ProjectVector, patternOrigin.X, patternOrigin.Y, + Pen(pen).Width); + } + // shortcut: saved planar boundary loops, until non-planar source edges are projected. + ViewportSurfaceEdges? edges = showEdges && face.PlaneSurface && face.SourceLoops is { Count: > 0 } loops + ? SourceEdges(loops, category) : null; + AddSurface(rings.Select(loop => loop.Select(Project).ToArray()).ToArray(), normal, facing, + material.Color, material.Transmission, pattern, edges); + if (terrainSides.Length == 0 || element.CategoryId != (int)BuiltInCategory.OST_Topography + || normal[2] <= 0) continue; + int soil = Material(cutMaterial).Color; + for (int i = 0; i < clipped.Count; i++) + { + var a = clipped[i].Point; + var b = clipped[(i + 1) % clipped.Count].Point; + foreach (var (_, outward, offset) in terrainSides) + { + if (Math.Abs(Distance(a, outward, offset)) >= 1e-7 + || Math.Abs(Distance(b, outward, offset)) >= 1e-7) continue; + AddSurface([[Project(a), Project(b), Project([b[0], b[1], terrainBase]), + Project([a[0], a[1], terrainBase])]], outward, + Dot(outward[0], outward[1], outward[2], camera.Look), soil); + } + } + } + } + ViewportSurfaceEdges? SourceEdges(IReadOnlyList> loops, int category) + { + var lines = new List<((double X, double Y) Start, (double X, double Y) End)>(); + foreach (var loop in loops) + { + var clipped = Clip(loop); + for (int i = 0; i < clipped.Count; i++) + { + // The box can introduce a new side on the clipped face. + if (!clipped[i].IncomingEdge) continue; + var a = Project(clipped[(i + clipped.Count - 1) % clipped.Count].Point); + var b = Project(clipped[i].Point); + lines.Add(((a.X, a.Y), (b.X, b.Y))); + } + } + if (lines.Count == 0) return null; + var (edgeWidth, color) = Pen(category); + return new(lines, edgeWidth, color); + } + if (shadows?.GroundShadowBounds is { } footprint) + { + left = Math.Min(left, anchorX + factor * footprint.Left); + right = Math.Max(right, anchorX + factor * footprint.Right); + bottom = Math.Min(bottom, anchorY + factor * footprint.Bottom); + top = Math.Max(top, anchorY + factor * footprint.Top); + } + if (annotation != null) + { + double span = annotation.Radius * 1.18; + left = Math.Min(left, annotation.X - span); + right = Math.Max(right, annotation.X + span); + bottom = Math.Min(bottom, annotation.Y - span); + top = Math.Max(top, annotation.Y + span); + } + left = Math.Max(left, camera.Active ? Math.Max(0, anchorX + camera.X0 * factor) : 0); + right = Math.Min(right, camera.Active ? Math.Min(page.Size.WidthMillimetres, anchorX + camera.X1 * factor) : page.Size.WidthMillimetres); + bottom = Math.Max(bottom, camera.Active ? Math.Max(0, anchorY + camera.Y0 * factor) : 0); + top = Math.Min(top, camera.Active ? Math.Min(page.Size.HeightMillimetres, anchorY + camera.Y1 * factor) : page.Size.HeightMillimetres); + double width = right - left, height = top - bottom; + if (!(width > 0 && height > 0)) return null; + + const double pixelsPerMillimetre = 144 / 25.4; + int columns = (int)Math.Clamp(Math.Ceiling(width * pixelsPerMillimetre), 1, 2048); + int rows = (int)Math.Clamp(Math.Ceiling(height * pixelsPerMillimetre), 1, 2048); + var depth = new double[columns * rows]; + var rgbBytes = new byte[depth.Length * 3]; + var facesLightMask = shadows != null ? new bool[depth.Length] : null; + Array.Fill(depth, double.PositiveInfinity); + Array.Fill(rgbBytes, byte.MaxValue); + double stepX = width / columns, stepY = height / rows; + var crossings = new List(); + int FirstRow(Surface surface) => RasterIndex((top - surface.Rings[0].Max(p => p.Y)) / stepY, rows); + int LastRow(Surface surface) => RasterIndex((top - surface.Rings[0].Min(p => p.Y)) / stepY, rows); + int AtColumn(double x) => RasterIndex((x - left) / stepX, columns); + foreach (var surface in surfaces.Where(s => s.Transmission == 0)) + { + var outer = surface.Rings[0]; + var origin = outer[0]; + int first = FirstRow(surface), last = LastRow(surface); + for (int row = first; row < last; row++) + { + double y = top - (row + 0.5) * stepY; + GetCrossings(surface, y, crossings); + for (int i = 1; i < crossings.Count; i += 2) + { + int start = AtColumn(crossings[i - 1]); + int end = AtColumn(crossings[i]); + for (int column = start; column < end; column++) + { + double x = left + (column + 0.5) * stepX; + double z = origin.Depth + (x - origin.X) * surface.DepthX + (y - origin.Y) * surface.DepthY; + int pixel = row * columns + column; + if (!(z < depth[pixel])) continue; + depth[pixel] = z; + if (facesLightMask != null) facesLightMask[pixel] = surface.FacesLight; + if (surface.Pattern == null && surface.Edges == null) + { + rgbBytes[3 * pixel] = (byte)surface.Rgb; + rgbBytes[3 * pixel + 1] = (byte)(surface.Rgb >> 8); + rgbBytes[3 * pixel + 2] = (byte)(surface.Rgb >> 16); + continue; + } + double patternInk = surface.Pattern?.Coverage(x, y, stepX, stepY) ?? 0; + double edgeInk = surface.Edges?.Coverage(x, y, stepX, stepY) ?? 0; + for (int channel = 0; channel < 3; channel++) + { + int tint = (surface.Rgb >> (channel * 8)) & 255; + rgbBytes[3 * pixel + channel] = (byte)Math.Round(ApplyInk(surface, channel, tint, patternInk, edgeInk)); + } + } + } + } + } + if (shadows != null && facesLightMask != null) + shadows.Apply(rgbBytes, depth, facesLightMask, columns, rows, left, top, stepX, stepY, anchorX, anchorY, factor); + CompositePanes(); + annotation?.Paint(rgbBytes, columns, rows, left, top, stepX, stepY); + page.DrawImage(new PdfRasterImage(columns, rows, rgbBytes) { TransparentWhite = true }, left, bottom, width, height); + if (annotation != null) + { + page.BeginClip(left, bottom, width, height); + annotation.DrawLabels(page); + page.EndClip(); + } + return (left, bottom, width, height); + + void CompositePanes() + { + var panes = surfaces.Select((surface, order) => (surface, order)).Where(pair => pair.surface.Transmission > 0) + .Select(pair => new Pane(pair.surface, pair.order, FirstRow(pair.surface), LastRow(pair.surface))) + .Where(pane => pane.FirstRow < pane.LastRow).OrderBy(pane => pane.FirstRow).ToArray(); + if (panes.Length == 0) return; + var activePanes = new List(); + var spans = new List(); + var activeSpans = new List(); + var hits = new List(); + int nextPane = 0, lastRow = panes.Max(pane => pane.LastRow); + for (int row = panes[0].FirstRow; row < lastRow; row++) + { + activePanes.RemoveAll(pane => pane.LastRow <= row); + while (nextPane < panes.Length && panes[nextPane].FirstRow == row) + activePanes.Add(panes[nextPane++]); + double y = top - (row + 0.5) * stepY; + spans.Clear(); + foreach (var pane in activePanes) + { + GetCrossings(pane.Surface, y, crossings); + for (int i = 1; i < crossings.Count; i += 2) + { + int start = AtColumn(crossings[i - 1]), end = AtColumn(crossings[i]); + if (start < end) spans.Add(new(pane, start, end)); + } + } + if (spans.Count == 0) continue; + spans.Sort(static (a, b) => a.Start.CompareTo(b.Start)); + activeSpans.Clear(); + int nextSpan = 0, lastColumn = spans.Max(span => span.End); + for (int column = spans[0].Start; column < lastColumn; column++) + { + activeSpans.RemoveAll(span => span.End <= column); + while (nextSpan < spans.Count && spans[nextSpan].Start == column) + activeSpans.Add(spans[nextSpan++]); + hits.Clear(); + int pixel = row * columns + column; + double x = left + (column + 0.5) * stepX; + foreach (var span in activeSpans) + { + var surface = span.Pane.Surface; + var origin = surface.Rings[0][0]; + double z = origin.Depth + (x - origin.X) * surface.DepthX + (y - origin.Y) * surface.DepthY; + if (z < depth[pixel]) hits.Add(new(span.Pane, z, surface.Pattern?.Coverage(x, y, stepX, stepY) ?? 0, + surface.Edges?.Coverage(x, y, stepX, stepY) ?? 0)); + } + if (hits.Count == 0) continue; + // Surfaces can cross in the view. Sort where each output ray actually meets them. + hits.Sort(static (a, b) => a.Depth == b.Depth + ? b.Pane.Order.CompareTo(a.Pane.Order) : b.Depth.CompareTo(a.Depth)); + for (int channel = 0; channel < 3; channel++) + { + double color = rgbBytes[3 * pixel + channel]; + foreach (var hit in hits) + { + var surface = hit.Pane.Surface; + int tint = (surface.Rgb >> (channel * 8)) & 255; + color = tint * (1 - surface.Transmission) + color * surface.Transmission; + color = ApplyInk(surface, channel, color, hit.PatternInk, hit.EdgeInk); + } + rgbBytes[3 * pixel + channel] = (byte)Math.Round(color); + } + } + } + } + } + + private static double ApplyInk(Surface surface, int channel, double color, double patternInk, double edgeInk) + { + if (surface.Pattern is { } pattern) + color += (((pattern.Color >> (channel * 8)) & 255) - color) * patternInk; + if (surface.Edges is { } edges) + color += (((edges.Color >> (channel * 8)) & 255) - color) * edgeInk; + return color; + } + + private static void GetCrossings(Surface surface, double y, List crossings) + { + crossings.Clear(); + // The even-odd crossings include the face's opening loops. + foreach (var ring in surface.Rings) + { + var previous = ring[^1]; + foreach (var next in ring) + { + if ((previous.Y > y) != (next.Y > y)) + crossings.Add(previous.X + (next.X - previous.X) * (y - previous.Y) / (next.Y - previous.Y)); + previous = next; + } + } + crossings.Sort(); + } + + private static double Dot(double x, double y, double z, double[] axis) => x * axis[0] + y * axis[1] + z * axis[2]; + + private static int RasterIndex(double coordinate, int count) => (int)Math.Clamp(Math.Ceiling(coordinate - 0.5), 0, count); +} diff --git a/src/RvtIO/Print/SheetComposer.ViewportTitles.cs b/src/RvtIO/Print/SheetComposer.ViewportTitles.cs new file mode 100644 index 00000000..8e88abb6 --- /dev/null +++ b/src/RvtIO/Print/SheetComposer.ViewportTitles.cs @@ -0,0 +1,57 @@ +using RvtIO.BuiltIns; +using RvtIO.Model; +using RvtIO.Pdf; + +namespace RvtIO.Print; + +public static partial class SheetComposer +{ + private static bool DrawViewportTitle(PdfPage page, RvtDocument document, Element viewport, Element? view, + string viewName, int scale, double originX, double originY) + { + if (document.RawData.ViewportTitles?.GetValueOrDefault(viewport.Id) is not { } title) return false; + if (!title.ShowLabel) return true; + if (viewport.ViewportLabelOrigin is not { Length: >= 2 } origin + || page.Owner.Font is not { } font + || document.RawData.ViewportTitleStyles?.GetValueOrDefault(title.SymbolId) is not { } style) + return false; + + double x = origin[0] * FeetToMillimetres - originX, y = origin[1] * FeetToMillimetres - originY; + double pen = PenWidths.TryAnnotationWidth(document, 1, out double width) ? width : 0.1; + if (title.ShowExtensionLine && viewport.ViewportLabelLength is > 0 and double length) + page.DrawLine(x, y, x + length * FeetToMillimetres, y, pen); + foreach (var line in style.Lines) + page.DrawLine(x + line.X0 * FeetToMillimetres, y + line.Y0 * FeetToMillimetres, + x + line.X1 * FeetToMillimetres, y + line.Y1 * FeetToMillimetres, pen); + foreach (var arc in style.Arcs) + page.DrawArc(x + arc.X * FeetToMillimetres, y + arc.Y * FeetToMillimetres, + arc.Radius * FeetToMillimetres, arc.Start, arc.End, pen); + + string? sheetTitle = view?.LookupParameter(BuiltInParameter.VIEW_DESCRIPTION)?.Value as string; + foreach (var (label, fontPoints, wrap) in style.Labels) + { + string? value = (BuiltInParameter)label.ParamId switch + { + BuiltInParameter.VIEWPORT_VIEW_NAME => string.IsNullOrEmpty(sheetTitle) ? viewName : sheetTitle, + BuiltInParameter.VIEWPORT_DETAIL_NUMBER => + viewport.LookupParameter(BuiltInParameter.VIEWPORT_DETAIL_NUMBER)?.Value as string, + BuiltInParameter.VIEWPORT_SCALE => title.CustomScale + ?? (IsAnalysisView(view) ? null : $" 1 : {scale}"), + _ => null, + }; + if (string.IsNullOrEmpty(value)) continue; + var position = PlanPrinter.AnnotationLabelLayout(font, label, fontPoints, x, y); + string text = label.Prefix + value + label.Suffix; + double lineWidth = label.Width * FeetToMillimetres; + var lines = text.Contains('\n') || (wrap && lineWidth > 0 && page.MeasureText(text, position.Size) > lineWidth) + ? PlanPrinter.WrapPlanNoteText(page, text, position.Size, lineWidth, wrap && lineWidth > 0) + : [text]; + double lineHeight = label.Height * FeetToMillimetres; + double first = position.Baseline; + if ((label.Flags & 0x400) != 0) first += lineHeight * (lines.Count - 1) / 2; + for (int i = 0; i < lines.Count; i++) + page.DrawText(lines[i], position.X, first - i * lineHeight, position.Size, position.Alignment); + } + return true; + } +} diff --git a/src/RvtIO/Print/SheetComposer.cs b/src/RvtIO/Print/SheetComposer.cs index 3edb2333..8931e88a 100644 --- a/src/RvtIO/Print/SheetComposer.cs +++ b/src/RvtIO/Print/SheetComposer.cs @@ -1,5 +1,7 @@ +using System.Globalization; using RvtIO.BuiltIns; using RvtIO.Model; +using RvtIO.Parsing; using RvtIO.Pdf; namespace RvtIO.Print; @@ -25,8 +27,14 @@ public sealed class SheetComposeOptions /// True (the default) draws the page border and, at its lower-right corner, the sheet number and name. /// This stands in for the title block while the linework of its family is not decoded. public bool DrawPageFrame { get; set; } = true; + + /// Rendered graphics by viewport element id. Bounds are in millimetres from the sheet's lower left. + public IReadOnlyDictionary? ViewportImages { get; set; } } +/// A rendered viewport and its bounds on a sheet, in millimetres. +public sealed record SheetViewportImage(IPdfImage Image, double X, double Y, double Width, double Height); + /// A sheet that can be composed: the element id, its number and name, the page its title block spans and the /// number of placed viewports and text notes. /// The element id of the sheet. @@ -44,7 +52,7 @@ public sealed record ComposedSheet(int SheetId, string? Number, string? Name, Pd /// labelled with its name and scale, and the sheet's own text notes are written at their positions. The linework of the /// title block family and the fills of rooms are not decoded yet (see docs/printing.md). /// -public static class SheetComposer +public static partial class SheetComposer { private const double FeetToMillimetres = 304.8; @@ -100,6 +108,19 @@ public static PdfDocument RenderSheets(RvtDocument document, IReadOnlyList ArgumentNullException.ThrowIfNull(sheetIds); options ??= new SheetComposeOptions(); var pdf = new PdfDocument { Font = PdfFonts.TryFind(out _), Compress = true }; + if (options.ViewportImages != null) + { + var selected = sheetIds.ToHashSet(); + foreach (var (id, raster) in options.ViewportImages) + { + var viewport = document.GetElement(id); + if (viewport?.OwnerViewId is not int owner || !selected.Contains(owner) || viewport.ViewportViewId == null + || raster.Image == null || !double.IsFinite(raster.X) || !double.IsFinite(raster.Y) + || !double.IsFinite(raster.Width) || !double.IsFinite(raster.Height) + || raster.Width <= 0 || raster.Height <= 0) + throw new ArgumentException($"Invalid render or bounds for viewport {id} on the selected sheets.", nameof(options)); + } + } var plans = new Dictionary(); foreach (var view in PlanPrinter.Views(document)) plans[view.ViewId] = view; foreach (int sheetId in sheetIds) @@ -212,12 +233,19 @@ void ClipFrame(double frameX, double frameY, double frameWidth, double frameHeig centerY = offset[1] * FeetToMillimetres - originY; } double frameX = centerX, frameY = centerY, frameWidth = 0, frameHeight = 0; - if (placed && view?.RootClassName == "DBView3d" && !IsAnalysisView(view)) + var raster = options.ViewportImages?.GetValueOrDefault(element.Id); + bool rendered = raster != null; + if (raster != null) + page2.DrawImage(raster.Image, raster.X, raster.Y, raster.Width, raster.Height); + else if (placed && view?.RootClassName == "DBView3d" && IsAnalysisView(view)) { - // A 3D view: an isometric projection of the model, white faces with their outlines, as the massing the - // view would show without its rendering. A sun or lighting analysis prints as its shaded study, not - // as vector massing (the reference shows no such linework, and rvt-prt draws 3D only with a camera - // looking off-axis): those viewports print nothing vector, like an unplaced view. + effectiveScale = element.ViewportScale ?? scale; + if (ShadedViewport.Render(page2, document, view, centerX, centerY, effectiveScale) is { } frame) + (frameX, frameY, frameWidth, frameHeight) = frame; + } + else if (placed && view?.RootClassName == "DBView3d" && !IsAnalysisView(view)) + { + // A 3D view without a rendered study prints as isometric massing. var model = ElevationPrinter.Collect(document, "iso"); if (model != null) { @@ -237,18 +265,28 @@ void ClipFrame(double frameX, double frameY, double frameWidth, double frameHeig else if (placed && view?.RootClassName == "DBViewRendering") { // A rendering: the JPEG Revit stored for the view, placed at the offset of its viewport. - if (RenderingImage(document, viewId) is { } jpeg) + if (RenderingImage(document, viewId) is { } rendering) { + var jpeg = rendering.Image; double height = 110, width = height * jpeg.Width / jpeg.Height; - if (width > 240) + double x; + if (rendering.Size is { } size) + { + width = size.Width * FeetToMillimetres; + height = size.Height * FeetToMillimetres; + x = centerX - width / 2; + } + else { - width = 240; - height = width * jpeg.Height / jpeg.Width; + if (width > 240) + { + width = 240; + height = width * jpeg.Height / jpeg.Width; + } + double stripLeft = layout.WidthMillimetres - 5 + - Math.Min(180, layout.WidthMillimetres * 0.22) - 3; + x = Math.Min(centerX - width / 2, stripLeft - width); } - // The images keep clear of the title block strip on the right. - double stripLeft = layout.WidthMillimetres - 5 - - Math.Min(180, layout.WidthMillimetres * 0.22) - 3; - double x = Math.Min(centerX - width / 2, stripLeft - width); page2.DrawImage(jpeg, x, centerY - height / 2, width, height); } } @@ -284,22 +322,52 @@ void ClipFrame(double frameX, double frameY, double frameWidth, double frameHeig { ClipFrame(frameX, frameY, frameWidth, frameHeight); } + var planGrids = cropped && view != null && planCrop != null + ? PlanPrinter.CollectPlanGrids(document, view, planCrop, drawScale) : null; + var planDimensions = cropped && planCrop != null + ? PlanPrinter.CollectPlanDimensions(document, viewId, planCrop) : []; + var sectionMarks = ElevationPrinter.SectionMarks(document, viewId, viewScale); PlanPrinter.DrawContent(page2, content, drawScale, drawOriginX, drawOriginY, 0.9, - ElevationPrinter.SectionMarks(document, viewId, viewScale), document, + sectionMarks.Where(mark => !mark.UsesPlanExtent).ToArray(), document, (frameX, frameY, frameX + frameWidth, frameY + frameHeight), - clipRect: cropped && planCrop != null ? CropContentRect(planCrop) : null); + clipRect: cropped && planCrop != null ? CropContentRect(planCrop) : null, + drawGrids: planGrids == null, drawFallbackDimensions: planDimensions.Count == 0, planViewId: viewId); + PlanPrinter.DrawStairPaths(page2, document, viewId, plan.LevelId, content, drawScale, drawOriginX, drawOriginY); page2.EndClip(); + PlanPrinter.DrawSectionMarks(page2, content, drawScale, drawOriginX, drawOriginY, + sectionMarks.Where(mark => mark.UsesPlanExtent).ToArray(), null, document, viewId); + CircularAnnotations.DrawViewport(page2, document, view, CircularAnnotations.Project(document, viewId), + drawScale, drawOriginX, drawOriginY, content.MinX, content.MinY, cropped ? planCrop : null); + if (planGrids != null) + PlanPrinter.DrawPlanGrids(page2, document, planGrids, content, drawScale, drawOriginX, drawOriginY); + PlanPrinter.DrawPlanDimensions(page2, planDimensions, content, drawScale, drawOriginX, drawOriginY); + if (cropped && planCrop != null) + PlanPrinter.DrawPlanNotes(page2, document, viewId, planCrop, content, drawScale, drawOriginX, drawOriginY); + if (cropped && planCrop != null && view != null) + PlanElevationMarks.Draw(page2, document, view, planCrop, drawScale, centerX, centerY); effectiveScale = (int)Math.Round(drawScale); if (options.DrawRoomLegend && pdf.Font != null && content.Rooms.Count > 0) - DrawRoomLegend(page2, content.Rooms.Select(room => room.Name), Math.Max(frameX, 8), - frameY - 16); + { + var legend = document.Elements.FirstOrDefault(e => e.OwnerViewId == viewId && e.RoomLegendOrigin.HasValue); + var names = content.Rooms.Select(room => room.Name); + if (legend?.RoomLegendOrigin is { } anchor) + { + double x = drawOriginX + (anchor.X * FeetToMillimetres - content.MinX) / drawScale; + double y = drawOriginY + (anchor.Y * FeetToMillimetres - content.MinY) / drawScale; + var swatch = document.GetElement(legend.TypeId)?.ColorLegendSwatch; + DrawRoomLegend(page2, names, x, y, swatch, content.RoomColors); + } + else + { + DrawRoomLegend(page2, names, Math.Max(frameX, 8), frameY - 16, null, content.RoomColors); + } + } } } else if (placed && name.Contains("site", StringComparison.OrdinalIgnoreCase)) { - // A site view: the planting tags over the paper, not the plan of a level. The reference - // site plan draws no building, terrain or planting graphics, so no level is collected for it. - var site = SitePrinter.Collect(document); + // Site graphics and the building footprint share the site's view projection. + var site = SitePrinter.Collect(document, viewId); if (site != null) { // The building stands on the site: the walls of the level with most walls go on the same plan, @@ -319,13 +387,14 @@ void ClipFrame(double frameX, double frameY, double frameWidth, double frameHeig if (bestLevel is int levelId) sitePlan = PlanPrinter.CollectLevel(document, levelId); } - if (sitePlan != null) + if (sitePlan != null && view?.ViewCrop is not { Active: true }) site = KeepSiteNearBuilding(site, sitePlan); // A site view whose crop basis is turned prints its plan turned: the Site view's crop Right is // (0.7986, -0.6018), a -37 degree view, and the reference site plan is drawn turned with it. // Project the graphics on the view's own axes; the tags and the north arrow stay upright. - if (view?.ViewCrop is { Active: true } basisCrop - && Math.Abs(basisCrop.Right[1]) > 1e-6) + var basisCrop = view?.ViewCrop is { Active: true } basis && Math.Abs(basis.Right[1]) > 1e-6 + ? basis : null; + if (basisCrop != null) { site = SitePrinter.InViewBasis(site, basisCrop.Right, basisCrop.Up); if (sitePlan != null) @@ -362,7 +431,13 @@ void ClipFrame(double frameX, double frameY, double frameWidth, double frameHeig siteDrawOriginX = frameX; siteDrawOriginY = frameY; } - SitePrinter.DrawContent(page2, site, drawScale, siteDrawOriginX, siteDrawOriginY); + bool opaqueSite = document.RawData.OpaquePlanViews?.Contains(viewId) == true; + var graphics = opaqueSite ? SitePrinter.CollectOpaqueGraphics(document, viewId, basisCrop) : null; + var plantingTags = SitePrinter.CollectTags(document, viewId, basisCrop); + var outlines = document.RawData.PlanOutlineAnnotations?.GetValueOrDefault(viewId); + SitePrinter.DrawContent(page2, site, drawScale, siteDrawOriginX, siteDrawOriginY, document, + opaqueSite, graphics, drawFallbackTags: plantingTags.Count == 0, drawFallbackNorth: outlines == null, + viewId: viewId, basis: basisCrop); effectiveScale = (int)Math.Round(drawScale); if (sitePlan is { } building) { @@ -394,7 +469,19 @@ void ClipFrame(double frameX, double frameY, double frameWidth, double frameHeig wallsOriginX, wallsOriginY, 0.9, null, document); } + if (graphics != null) + SitePrinter.DrawSurfaces(page2, document, graphics, site, drawScale, siteDrawOriginX, siteDrawOriginY); page2.EndClip(); + SitePrinter.DrawTags(page2, document, plantingTags, site, drawScale, siteDrawOriginX, siteDrawOriginY); + SitePrinter.DrawPropertyTags(page2, document, viewId, basisCrop, + site, drawScale, siteDrawOriginX, siteDrawOriginY); + if (outlines != null) + SitePrinter.DrawOutlineAnnotations(page2, document, outlines, basisCrop, + site, drawScale, siteDrawOriginX, siteDrawOriginY); + CircularAnnotations.DrawViewport(page2, document, view, + CircularAnnotations.Project(document, viewId, basisCrop?.Right, basisCrop?.Up), + drawScale, siteDrawOriginX, siteDrawOriginY, site.MinX, site.MinY, + siteCropped ? view?.ViewCrop : null); // The planting schedule sits under the view title, clear of the site plan, unless its real // instance drew at its own origin below. if (pdf.Font != null && !SchedulesOnSheet(document, sheet).Any(schedule => schedule.CategoryId == PlantingCategoryId)) @@ -409,15 +496,17 @@ void ClipFrame(double frameX, double frameY, double frameWidth, double frameHeig // An elevation or a section: the model faces projected on the view's plane when the reader decoded it // (a section is then cut at its plane), otherwise on the plane of the direction taken from the name. Element? viewElement = document.GetElement(viewId); + bool unshadedHiddenLine = document.RawData.UnshadedHiddenLineViews?.Contains(viewId) == true; // A detail section (1:10 to 1:50) is drawn from its own file crop frame: the crop rectangle is // the detail's true extent (a roof detail's crop sits at roof height), while the old // plane-origin window showed the wrong slice (the plane origin sits floors below the crop). // Without a usable crop the invented window stays as a fallback. A stair section is printed // whole like a building section, not as a detail; a stair detail (1:20) shows the stair in // its enclosure through the file's own crop frame, the way the reference places it next to - // the stair section. + // the stair section. With the authored crop, the surrounding cut belongs in the section. bool stairSection = name.Contains("stair", StringComparison.OrdinalIgnoreCase); - bool stairsOnly = stairSection && scale >= 50; + bool stairsOnly = stairSection && scale >= 50 + && !(view?.ViewCrop is { Active: true } stairCrop && ViewBasisMatches(viewElement, stairCrop)); double stripLeftForStair = layout.WidthMillimetres - 5 - Math.Min(180, layout.WidthMillimetres * 0.22) - 3; bool detailSection = direction == "section" && scale < 100 && !stairSection @@ -429,10 +518,7 @@ void ClipFrame(double frameX, double frameY, double frameWidth, double frameHeig bool detailCropUsable = detailSection && viewElement?.ViewCrop is { Active: true } detailCrop && ViewBasisMatches(viewElement, detailCrop); (double Width, double Height)? detailWindow = detailSection && !detailCropUsable ? (3000, 2200) : null; - // A fallback-windowed detail the file puts against the border or outside the page is still - // printed: Revit lays such callouts out in a bottom row above their own titles (A104's four - // details), so the frame is anchored on the decoded title label instead of the file offset. - // A crop-drawn detail relocates the same way in the crop branch below. + // Without a model crop, an off-page detail uses the decoded title as its fallback anchor. bool detailRelocated = detailWindow != null && !(centerX > 40 && centerX < stripLeft - 40 && centerY > 40 && centerY < layout.HeightMillimetres - 40) && element.ViewportLabelOrigin is { Length: >= 2 } @@ -441,7 +527,7 @@ void ClipFrame(double frameX, double frameY, double frameWidth, double frameHeig ElevationPrinter.Collect(document, direction, stairsOnly, viewElement, detailWindow, isDetail: detailSection, cropWindow: detailSection && detailCropUsable && viewElement?.ViewCrop is { Active: true } dc - ? CropContentRect(dc) : null); + ? CropContentRect(dc) : null, viewportScale: scale); // A viewport whose view decoded a crop frame draws the crop at the view's own scale, placed by // the viewport offset (sheet = offset + view / scale): the frame is the crop rectangle and the // content is clipped to it, nothing is reduced to fit. The crop applies only where the collection @@ -456,13 +542,10 @@ void ClipFrame(double frameX, double frameY, double frameWidth, double frameHeig out frameX, out frameY, out frameWidth, out frameHeight, out double cropOriginX, out double cropOriginY)) { effectiveScale = scale; - // A crop-drawn detail the file parked off the page is laid out in a bottom row above its own - // title (A104's four details): anchor the frame on the decoded title label instead of the - // file offset. The viewport center anchors the view origin (view coordinates 0, 0), not the - // frame center, so back out the crop offset: the frame lands centered on the title with its - // bottom clearing the title text (about 20 mm above its line on A104). + // A detail's projected view origin can be far from its crop, especially at large scales. + // Fall back to the title only when the mapped crop is entirely off the sheet. if (detailSection - && !(centerX > 40 && centerX < stripLeft - 40 && centerY > 40 && centerY < layout.HeightMillimetres - 40) + && !CropOverlapsSheet(frameX, frameY, frameWidth, frameHeight, layout.WidthMillimetres, layout.HeightMillimetres) && element.ViewportLabelOrigin is { Length: >= 2 } cropLabelOrigin && element.ViewportLabelLength is double cropLabelLength && cropLabelLength > 0) { @@ -494,8 +577,16 @@ void ClipFrame(double frameX, double frameY, double frameWidth, double frameHeig double clipExtra = elevation.Levels.Count > 0 ? 45 : 0; page2.BeginClip(frameX, frameY, Math.Max(0, frameWidth + clipExtra), Math.Max(0, frameHeight)); ElevationPrinter.DrawContent(page2, elevation, scale, cropOriginX, cropOriginY, - direction == "section" ? 0.82 : 1, document, (cropX0, cropY0, cropX1, cropY1)); + direction == "section" ? 0.82 : 1, document, (cropX0, cropY0, cropX1, cropY1), + drawNativeDatums: false, unshadedHiddenLine: unshadedHiddenLine); page2.EndClip(); + ElevationPrinter.DrawNativeDatums(page2, elevation, scale, cropOriginX, cropOriginY, document, + (cropX0, cropY0, cropX1, cropY1)); + CircularAnnotations.DrawViewport(page2, document, viewElement, elevation.AnnotationSymbols ?? [], + scale, cropOriginX, cropOriginY, elevation.MinX, elevation.MinY, crop); + if (direction == "section" && viewElement != null) + DetailAnnotations.DrawCallouts(page2, document, sheet, viewElement, crop, scale, + cropOriginX - elevation.MinX / scale, cropOriginY - elevation.MinY / scale); placedRects.Add((frameX, frameY, frameWidth, frameHeight)); } else if (elevation != null) @@ -520,7 +611,8 @@ void ClipFrame(double frameX, double frameY, double frameWidth, double frameHeig effectiveScale = scale; page2.BeginClip(frameX, frameY, Math.Max(0, frameWidth), Math.Max(0, frameHeight)); ElevationPrinter.DrawContent(page2, elevation, drawScale, frameX, frameY, - direction == "section" ? 0.82 : 1, document); + direction == "section" ? 0.82 : 1, document, + unshadedHiddenLine: unshadedHiddenLine); page2.EndClip(); placedRects.Add((frameX, frameY, frameWidth, frameHeight)); } @@ -596,13 +688,15 @@ void ClipFrame(double frameX, double frameY, double frameWidth, double frameHeig } ClipFrame(frameX, frameY, frameWidth, frameHeight); ElevationPrinter.DrawContent(page2, elevation, drawScale, frameX, frameY, - direction == "section" ? 0.82 : 1, document); + direction == "section" ? 0.82 : 1, document, + unshadedHiddenLine: unshadedHiddenLine); page2.EndClip(); placedRects.Add((frameX, frameY, frameWidth, frameHeight)); } } } - if (placed && frameWidth > 0) + // The analysis viewport has its own scale label and does not determine the sheet scale. + if (placed && frameWidth > 0 && !(view?.RootClassName == "DBView3d" && IsAnalysisView(view))) { effectiveScales[effectiveScale] = effectiveScales.TryGetValue(effectiveScale, out int counted) ? counted + 1 : 1; @@ -611,7 +705,8 @@ void ClipFrame(double frameX, double frameY, double frameWidth, double frameHeig // study is a raster) is not titled either — except the analysis views: their title line and label are // sheet annotation the reference prints, even though the study itself is an image. if (options.DrawViewLabels && pdf.Font != null - && (!placed || frameHeight > 0 || IsAnalysisView(view))) + && (!placed || frameHeight > 0 || rendered || IsAnalysisView(view)) + && !DrawViewportTitle(page2, document, element, view, name, scale, originX, originY)) { // The view title as Revit draws it: a circled detail number, the view name beside it, the scale below // and the extension line under the title. The file stores the line's origin on the sheet and its @@ -662,24 +757,14 @@ void ClipFrame(double frameX, double frameY, double frameWidth, double frameHeig page2.DrawText(detail, frameX + 3, labelY + 0.2, 2.4, PdfTextAlignment.Center); textX = frameX + 8; } - page2.DrawLine(ruleX0, ruleY, ruleX1, ruleY, gridPen); + if (document.RawData.ViewportTitles?.GetValueOrDefault(element.Id)?.ShowExtensionLine != false) + page2.DrawLine(ruleX0, ruleY, ruleX1, ruleY, gridPen); page2.DrawText(name, textX, labelY, 3.5); page2.DrawText($"1:{effectiveScale}", textX, labelY - 3.5, 2.5, PdfTextAlignment.Left, 0.45); } } - foreach (var element in document.Elements) - { - if (element.OwnerViewId != sheet.Id) continue; - if (element.Text is not { Length: > 0 } text || element.TextPosition is not { Length: >= 2 } position) - continue; - double x = position[0] * FeetToMillimetres - originX; - double y = position[1] * FeetToMillimetres - originY; - double height = element.TextFontSizePoints is double points && points > 0 ? points * 25.4 / 72 : 2.5; - string[] lines = text.Split('\n'); - for (int line = 0; line < lines.Length; line++) - page2.DrawText(lines[line], x, y - line * height * 1.25, height); - } + SheetPrinter.DrawSheetNotes(page2, document, sheet.Id, -originX, -originY); // The title block goes last, over the drawings. Decoded linework draws at its sheet position with its // annotation pens (0.7 pt where the style has no pen, as rvt-prt draws it), with its fixed texts and @@ -688,6 +773,7 @@ void ClipFrame(double frameX, double frameY, double frameWidth, double frameHeig // and no drawing line runs under the strip. if (options.DrawPageFrame && pdf.Font != null) { + var titleScales = effectiveScales.Keys; string scaleText = effectiveScales.Count > 0 ? "1:" + effectiveScales.OrderByDescending(pair => pair.Value).First().Key : ""; @@ -704,16 +790,24 @@ void ClipFrame(double frameX, double frameY, double frameWidth, double frameHeig if (scale == 0) continue; nominal[scale] = nominal.TryGetValue(scale, out int count) ? count + 1 : 1; } - if (nominal.Count > 0) scaleText = "1:" + nominal.OrderByDescending(pair => pair.Value).First().Key; + if (nominal.Count > 0) + { + titleScales = nominal.Keys; + scaleText = "1:" + nominal.OrderByDescending(pair => pair.Value).First().Key; + } } if (titleLines != null) { - IReadOnlyList<(double Ox, double Oy, double Height, double Width, int Flags, double Bx, double By, byte[] Rtf)>? titleTexts = null; - IReadOnlyList<(double Ox, double Oy, double Height, double Width, int Flags, double Bx, double By, int ParamId, string Prefix, string Suffix)>? titleLabels = null; - document.RawData.TitleBlockTexts?.TryGetValue(titleSymbolId, out titleTexts); - document.RawData.TitleBlockLabels?.TryGetValue(titleSymbolId, out titleLabels); - DrawTitleBlockSymbol(page2, document, sheet, scaleText, titleLines, + var titleTexts = document.RawData.TitleBlockTexts?.GetValueOrDefault(titleSymbolId); + var titleLabels = document.RawData.TitleBlockLabels?.GetValueOrDefault(titleSymbolId); + var scaleOverride = sheet.LookupParameter(BuiltInParameter.SHEET_SCALE_OVERRIDE)?.Value as string; + string titleScale = !string.IsNullOrWhiteSpace(scaleOverride) ? scaleOverride + : TitleBlockScale(titleScales, CultureInfo.CurrentUICulture.TwoLetterISOLanguageName == "ru"); + DrawTitleBlockSymbol(page2, document, sheet, titleScale, titleLines, titleTexts, titleLabels, originX, originY); + foreach (var (image, x, y, width, height) in TitleBlockImages(document, titleSymbolId)) + page2.DrawImage(image, x * FeetToMillimetres - originX, y * FeetToMillimetres - originY, + width * FeetToMillimetres, height * FeetToMillimetres); } else { @@ -726,6 +820,8 @@ void ClipFrame(double frameX, double frameY, double frameWidth, double frameHeig // their stored rows, the header and grid always drawn (rvt-prt tables.py). DrawSchedules(page2, document, sheet, originX, originY); } + CircularAnnotations.Draw(page2, document, CircularAnnotations.Project(document, sheet.Id), 1, + x => x - originX, y => y - originY); } private const int RevisionsCategoryId = -2006070; @@ -737,8 +833,13 @@ void ClipFrame(double frameX, double frameY, double frameWidth, double frameHeig internal sealed record ScheduleOnSheet(int InstanceId, int ScheduleId, double Ox, double Oy, List<(string Heading, double WidthFt)> Columns, int CategoryId, bool ShowTitle, bool ShowHeaders, bool ShowGridLines, bool ShowOutline, string Title, - double TitleHeightFt, List<(double HeightFt, string Text)> TitleBands, List BodySections, - int GridStyleId, int OutlineStyleId, double FixedHeightFt); + double TitleHeightFt, TfBlockDeserializer.ScheduleTextStyle TitleStyle, + List<(double HeightFt, string Text, TfBlockDeserializer.ScheduleTextStyle Style)> TitleBands, + List BodySections, + int GridStyleId, int OutlineStyleId, double FixedHeightFt) + { + internal (double Header, double Body)? RevisionCapHeightsFt { get; init; } + } /// The schedule instances placed on the sheet whose placement and table both decoded: the revision /// schedules of the title block, the planting schedule and the How-do-I table. @@ -757,8 +858,9 @@ internal static List SchedulesOnSheet(RvtDocument document, Ele result.Add(new(element.Id, placement.ScheduleId, placement.Ox, placement.Oy, table.Columns, table.CategoryId, table.ShowTitle, table.ShowHeaders, table.ShowGridLines, table.ShowOutline, title, - table.TitleHeightFt, table.TitleBands, table.BodySections, - table.GridStyleId, table.OutlineStyleId, table.FixedHeightFt)); + table.TitleHeightFt, table.TitleStyle, table.TitleBands, table.BodySections, + table.GridStyleId, table.OutlineStyleId, table.FixedHeightFt) + { RevisionCapHeightsFt = table.RevisionCapHeightsFt }); } return result; } @@ -772,6 +874,16 @@ private static void DrawSchedules(PdfPage page, RvtDocument document, Element sh DrawSchedule(page, document, sheet, schedule, originX, originY); } + internal static double? ScheduleTextSize(PdfTrueTypeFont? font, TfBlockDeserializer.ScheduleTextStyle style) + { + if (font is not { CapHeight: > 0 } || style is not + { CapHeightPixels: > 0 and <= 256, HorizontalAlignment: 0 or 1, VerticalAlignment: 4 or 8 }) return null; + // The schedule style stores cap height in 96-dpi pixels; PDF places an em at the corresponding half-point size. + double emPoints = style.CapHeightPixels * 72 / 96 * font.UnitsPerEm / font.CapHeight; + double points = Math.Round(emPoints * 2, MidpointRounding.AwayFromZero) / 2; + return points > 0 ? points * 25.4 / 72 : null; + } + private static void DrawSchedule(PdfPage page, RvtDocument document, Element sheet, ScheduleOnSheet schedule, double originX, double originY) { @@ -779,7 +891,7 @@ private static void DrawSchedule(PdfPage page, RvtDocument document, Element she const double PtToMm = 25.4 / 72.0; const double InchToMm = 25.4; bool revision = schedule.CategoryId == RevisionsCategoryId; - // Measured styles (rvt-prt tables.py SCHEDULE_STYLES): the file decodes no text sizes. + // Defaults for table areas whose text style has not been decoded. // The revision body pitch is measured on the sample's reference (16.30 pt rows of 12 pt Arial); // rvt-prt's 0.2559 in overshoots here and would drift the grid out of tolerance within a few rows. double titleH = revision ? 0 : 0.37 * InchToMm; @@ -787,6 +899,28 @@ private static void DrawSchedule(PdfPage page, RvtDocument document, Element she double bodyH = revision ? 16.30 * PtToMm : 0.2395 * InchToMm; double titlePt = 19, headPt = revision ? 19 : 12.5, bodyPt = 12.5; double insetMm = 0.037 * InchToMm; + const double pixelMm = InchToMm / 96; + IReadOnlyList? revisionHeaderStyles = null; + double revisionHeaderCapMm = 0; + if (revision && schedule.RevisionCapHeightsFt is { } cap + && page.Owner.Font is { CapHeight: > 0 } revisionFont + && string.Equals(revisionFont.Name, "Arial", StringComparison.OrdinalIgnoreCase) + && schedule.BodySections is [{ HeaderStyles: { } savedRevisionStyles }] + && savedRevisionStyles.Count == schedule.Columns.Count + && savedRevisionStyles.All(style => style is { HorizontalAlignment: 1, VerticalAlignment: 8, Flags: 1 } + && string.Equals(style.FontName, "Arial", StringComparison.OrdinalIgnoreCase) + && Math.Abs(style.CapHeightPixels * pixelMm - cap.Header * FeetToMillimetres) < 1e-6)) + { + // shortcut: the measured Arial revision-cell metrics, until other fonts and styles are verified. + const double revisionRowPerCapHeight = 23d / 12; + revisionHeaderStyles = savedRevisionStyles; + revisionHeaderCapMm = cap.Header * FeetToMillimetres; + double bodyCapMm = cap.Body * FeetToMillimetres; + headH = revisionHeaderCapMm * revisionRowPerCapHeight; + bodyH = bodyCapMm * revisionRowPerCapHeight; + bodyPt = Math.Round(bodyCapMm * revisionFont.UnitsPerEm / revisionFont.CapHeight / PtToMm * 2, + MidpointRounding.AwayFromZero) / 2; + } // The stored title height wins where the file decodes it (the How-do-I title area: stored 20.2 pt // against measured 26.6; the planting title: stored 30 pt against measured 26.6). if (!revision && schedule.TitleHeightFt > 0) @@ -801,6 +935,15 @@ private static void DrawSchedule(PdfPage page, RvtDocument document, Element she for (int i = 0; i < widths.Length; i++) edges[i + 1] = edges[i] + widths[i]; List> rows = new(); + bool russian = CultureInfo.CurrentUICulture.TwoLetterISOLanguageName == "ru"; + string yes = russian ? "Да" : "Yes", no = russian ? "Нет" : "No"; + var authoredRows = document.RawData.EvaluatedScheduleRows?.GetValueOrDefault(schedule.ScheduleId) + ?.Select(row => row.Select(cell => cell.Boolean switch + { + true => yes, + false => no, + _ => cell.Text, + }).ToList()).ToList(); if (revision) { // The revisions explicitly present on this sheet (rvt-prt sheet_revs): the reference lists none, @@ -824,11 +967,6 @@ private static void DrawSchedule(PdfPage page, RvtDocument document, Element she foreach (var (mark, name, count) in PlantingRows(document)) rows.Add([mark, name, count]); } - else - { - // Other schedules draw their stored body sections below (one header per section, then the - // stored body row count as an empty grid: the body cells carry no evaluated text). - } foreach (var row in rows) while (row.Count < widths.Length) row.Add(""); @@ -850,63 +988,86 @@ double AnnotationWidth(int categoryId, double fallback) double y = yTop; double tableTop = yTop; - // Schedule titles print one ascent below the row top (measured 18.4 pt below at 19 pt on both - // the How-do-I and planting titles), not centred in the row. bool drewTitleArea = false; if (schedule.ShowTitle && titlePt > 0 && schedule.Title.Length > 0 && !schedule.Title.StartsWith("<", StringComparison.Ordinal)) { - page.DrawText(schedule.Title, (edges[0] + edges[^1]) / 2, y - 0.97 * titlePt * PtToMm, - titlePt * PtToMm, PdfTextAlignment.Center); + if (ScheduleTextSize(page.Owner.Font, schedule.TitleStyle) is double size) + DrawCellText([schedule.Title], titleH, size, schedule.TitleStyle, edges[0], edges[^1]); + else + page.DrawText(schedule.Title, (edges[0] + edges[^1]) / 2, y - 0.97 * titlePt * PtToMm, + titlePt * PtToMm, PdfTextAlignment.Center); y -= titleH; drewTitleArea = true; if (schedule.ShowGridLines) page.DrawLine(edges[0], y, edges[^1], y, gridMm); } - // Stored title bands (the How-do-I long-text band): merged rows with no internal grid, the text - // top-aligned (measured 5.5 pt below the band top at 12.5 pt). + // Stored title bands are merged rows with no internal grid. foreach (var band in schedule.TitleBands) { double bandH = band.HeightFt * FeetToMillimetres; if (!(bandH > 0) || bandH > 1000) continue; if (band.Text.Length > 0) - page.DrawText(band.Text, edges[0] + insetMm, y - 5.5 * PtToMm, bodyPt * PtToMm); + { + page.BeginClip(edges[0], y - bandH, edges[^1] - edges[0], bandH); + if (ScheduleTextSize(page.Owner.Font, band.Style) is double size) + { + var lines = Wrap(band.Text, edges[^1] - edges[0] - 6 * pixelMm, size); + DrawCellText(lines, bandH, size, band.Style, edges[0], edges[^1]); + } + else + { + double fallbackSize = bodyPt * PtToMm; + double baseline = y - insetMm - fallbackSize * 0.85; + foreach (string line in Wrap(band.Text, edges[^1] - edges[0] - 2 * insetMm, fallbackSize)) + { + page.DrawText(line, edges[0] + insetMm, baseline, fallbackSize); + baseline -= fallbackSize * 1.125; + } + } + page.EndClip(); + } y -= bandH; drewTitleArea = true; if (schedule.ShowGridLines) page.DrawLine(edges[0], y, edges[^1], y, gridMm); } + void DrawCellText(IReadOnlyList lines, double height, double size, + TfBlockDeserializer.ScheduleTextStyle style, double left, double right) + { + var font = page.Owner.Font!; + double linePitch = Math.Round(size * (font.Ascent - font.Descent) / font.UnitsPerEm / pixelMm) * pixelMm; + double baseline = style.VerticalAlignment == 8 + ? y - height + 3 * pixelMm - size * font.Descent / font.UnitsPerEm + (lines.Count - 1) * linePitch + : y - height / 2 - size * (font.Ascent + font.Descent) / (2 * font.UnitsPerEm) + + (lines.Count - 1) * linePitch / 2; + var alignment = style.HorizontalAlignment == 1 ? PdfTextAlignment.Center : PdfTextAlignment.Left; + double x = alignment == PdfTextAlignment.Center ? (left + right) / 2 : left + 3 * pixelMm; + for (int i = 0; i < lines.Count; i++) + page.DrawText(lines[i], x, baseline - i * linePitch, size, alignment); + } // Header texts wrap into their columns ("Type Mark" wraps to two lines in its narrow column): - // the header grows one body row per wrapped line after the first (measured 31.8 pt for two lines - // against 17.3 for one), each column's lines centred as a block. - List> WrapHeaders(List header, double sizeMm) + // The header expands for the tallest wrapped column before each cell applies its alignment. + List Wrap(string text, double width, double size) { - var wrapped = new List>(widths.Length); - for (int i = 0; i < widths.Length; i++) + var lines = new List(); + foreach (string word in text.Split(' ')) { - string text = i < header.Count ? header[i] : ""; - var lines = new List(); - if (text.Length > 0) - { - foreach (string word in text.Split(' ')) - { - string candidate = lines.Count == 0 ? word : lines[^1] + " " + word; - if (lines.Count > 0 && page.MeasureText(candidate, sizeMm) <= widths[i]) - lines[^1] = candidate; - else - lines.Add(word); - } - } - if (lines.Count == 0) lines.Add(""); - wrapped.Add(lines); + string candidate = lines.Count == 0 ? word : lines[^1] + " " + word; + if (lines.Count > 0 && page.MeasureText(candidate, size) <= width) + lines[^1] = candidate; + else + lines.Add(word); } - return wrapped; + return lines; } + // Header texts come from the stored section header where the file decodes one, else from the // schedule fields; other schedules draw one header per stored body section. - List<(List Header, List> Rows)> sections = new(); + List<(List Header, List> Rows, TfBlockDeserializer.ScheduleBodySection? Layout)> sections = new(); if (revision || schedule.CategoryId == PlantingCategoryId) { - sections.Add((schedule.Columns.Select(column => column.Heading).ToList(), rows)); + sections.Add((schedule.Columns.Select(column => column.Heading).ToList(), rows, + revision ? null : schedule.BodySections.FirstOrDefault())); } else { @@ -915,13 +1076,14 @@ List> WrapHeaders(List header, double sizeMm) var header = bodySection.Header.Count == widths.Length ? bodySection.Header.ToList() : schedule.Columns.Select(column => column.Heading).ToList(); - var body = new List>(); - for (int i = 0; i < bodySection.BodyRows && body.Count < 10000; i++) - body.Add(Enumerable.Repeat("", widths.Length).ToList()); - sections.Add((header, body)); + var body = authoredRows ?? new List>(); + if (authoredRows == null) + for (int i = 0; i < bodySection.BodyRows && body.Count < 10000; i++) + body.Add(Enumerable.Repeat("", widths.Length).ToList()); + sections.Add((header, body, bodySection)); } if (sections.Count == 0) - sections.Add((schedule.Columns.Select(column => column.Heading).ToList(), new())); + sections.Add((schedule.Columns.Select(column => column.Heading).ToList(), new(), null)); } // The grid starts below the title area. Outer verticals run header-top to table bottom at the // outline weight when the schedule shows its outline (else the header box stands alone at the grid @@ -931,21 +1093,38 @@ List> WrapHeaders(List header, double sizeMm) // A wrapped header line after the first adds the measured extra line pitch (the planting header: // 31.8 pt for two lines against 17.3 for one). double extraHeaderLineMm = 14.55 * PtToMm; - foreach (var (header, body) in sections) + foreach (var (header, body, layout) in sections) { if (schedule.ShowHeaders) { // The header top rule is the title-area rule above, drawn where nothing stands over it. if (firstHeader && !drewTitleArea && schedule.ShowGridLines) page.DrawLine(edges[0], y, edges[^1], y, gridMm); - var wrapped = revision - ? header.Select(text => new List { text }).ToList() - : WrapHeaders(header, headPt * PtToMm); - int headerLines = Math.Max(1, wrapped.Max(lines => lines.Count)); + var headers = new (IReadOnlyList Lines, double? Size, TfBlockDeserializer.ScheduleTextStyle Style)[widths.Length]; + var styles = revisionHeaderStyles ?? layout?.HeaderStyles; + for (int i = 0; i < widths.Length; i++) + { + string text = i < header.Count ? header[i] : ""; + var style = styles?.Count == widths.Length ? styles[i] : default; + double? size = ScheduleTextSize(page.Owner.Font, style); + headers[i] = (revision ? [text] : Wrap(text, widths[i], size ?? headPt * PtToMm), size, style); + } + int headerLines = Math.Max(1, headers.Max(cell => cell.Lines.Count)); double headerH = revision ? headH : bodyH + (headerLines - 1) * extraHeaderLineMm; for (int i = 0; i < widths.Length; i++) { - var lines = i < wrapped.Count ? wrapped[i] : new List { "" }; + var (lines, size, style) = headers[i]; + if (size is double nativeSize) + { + if (revisionHeaderStyles != null) + { + // The supported Arial revision heading baseline sits 1.42 caps below the top rule. + page.DrawText(lines[0], (edges[i] + edges[i + 1]) / 2, + y - revisionHeaderCapMm * 1.42, nativeSize, PdfTextAlignment.Center); + } + else DrawCellText(lines, headerH, nativeSize, style, edges[i], edges[i + 1]); + continue; + } for (int j = 0; j < lines.Count; j++) { if (lines[j].Length == 0) continue; @@ -975,7 +1154,8 @@ List> WrapHeaders(List header, double sizeMm) string cell = i < row.Count ? row[i] : ""; if (cell.Length == 0) continue; double sizeMm = bodyPt * PtToMm; - if (revision || i == 0) + int alignment = layout?.BodyAlignment is { } saved && saved.Count == widths.Length ? saved[i] : -1; + if (alignment == 0 || alignment != 1 && (revision || authoredRows != null || i == 0)) page.DrawText(cell, edges[i] + insetMm, y - bodyH / 2 - 0.35 * sizeMm, sizeMm); else page.DrawText(cell, (edges[i] + edges[i + 1]) / 2, y - bodyH / 2 - 0.35 * sizeMm, sizeMm, @@ -1037,8 +1217,8 @@ List> WrapHeaders(List header, double sizeMm) /// style has no pen, as rvt-prt draws it), each fixed text and label at its anchor. private static void DrawTitleBlockSymbol(PdfPage page, RvtDocument document, Element sheet, string scaleText, IReadOnlyList<(double X0, double Y0, double X1, double Y1, int StyleId)> lines, - IReadOnlyList<(double Ox, double Oy, double Height, double Width, int Flags, double Bx, double By, byte[] Rtf)>? texts, - IReadOnlyList<(double Ox, double Oy, double Height, double Width, int Flags, double Bx, double By, int ParamId, string Prefix, string Suffix)>? labels, + IReadOnlyList? texts, + IReadOnlyList? labels, double originX, double originY) { const double FeetToMillimetres = 304.8; @@ -1060,42 +1240,107 @@ private static void DrawTitleBlockSymbol(PdfPage page, RvtDocument document, Ele if (parsed?.Text is not { Length: > 0 } plain) continue; double sizeMm = parsed.Value.FontSizePoints is double points && points > 0 ? points * 25.4 / 72.0 : 2.5; - DrawTitleBlockText(page, plain, text.Ox * FeetToMillimetres - originX, - text.Oy * FeetToMillimetres - originY, sizeMm, text.Flags, text.Bx, text.By); + DrawTitleBlockText(page, plain.Split('\n'), text.Ox * FeetToMillimetres - originX, + text.Oy * FeetToMillimetres - originY, sizeMm, text.Height * FeetToMillimetres, + text.Flags, text.Bx, text.By, text.Hx, text.Hy); } } - if (labels != null) + if (labels != null && page.Owner.Font is { } font) { foreach (var label in labels) { string value = TitleBlockLabelValue(document, sheet, scaleText, label.ParamId); if (value.Length == 0) continue; value = label.Prefix + value + label.Suffix; - // A label with no decoded text type prints at its box height, as rvt-prt sizes it. - double sizeMm = label.Height * 304.8 / 1.257; - DrawTitleBlockText(page, value, label.Ox * FeetToMillimetres - originX, - label.Oy * FeetToMillimetres - originY, sizeMm, label.Flags, label.Bx, label.By); + double height = label.Height * FeetToMillimetres; + double cap = document.RawData.TitleBlockCapHeightsFeet?.GetValueOrDefault(label.AttrId) ?? 0; + double sizeMm = SymbolLabelTextSize(font, height, cap); + double width = label.Width * FeetToMillimetres; + bool wrap = label.Wrap && width > 0 && page.MeasureText(value, sizeMm) > width; + var wrapped = PlanPrinter.WrapPlanNoteText(page, value, sizeMm, width, wrap); + DrawTitleBlockText(page, wrapped, label.Ox * FeetToMillimetres - originX, + label.Oy * FeetToMillimetres - originY, sizeMm, height * wrapped.Count, + label.Flags, label.Bx, label.By, label.Hx, label.Hy); } } } - private static void DrawTitleBlockText(PdfPage page, string text, double x, double y, - double sizeMm, int flags, double bx, double by) + internal static double SymbolLabelTextSize(PdfTrueTypeFont font, double frameHeight, double capHeightFeet) { - if (string.IsNullOrEmpty(text) || sizeMm <= 0) return; + // The font element stores physical cap height. Text sizes are written in half points. + double nominalSize = capHeightFeet > 0 && font.CapHeight > 0 + ? capHeightFeet * FeetToMillimetres * font.UnitsPerEm / font.CapHeight + : frameHeight * font.UnitsPerEm / (font.Ascent - font.Descent); + return Math.Round(nominalSize * 144 / 25.4, MidpointRounding.AwayFromZero) * 25.4 / 144; + } + + internal static void DrawTitleBlockText(PdfPage page, IReadOnlyList parts, double x, double y, + double sizeMm, double height, int flags, double bx, double by, double ux, double uy, bool opaque = false, + bool useArialLayout = false) + { + if (parts.Count == 0 || !(sizeMm > 0 && double.IsFinite(sizeMm)) + || !double.IsFinite(x) || !double.IsFinite(y) + || !double.IsFinite(bx) || !double.IsFinite(by) || !double.IsFinite(ux) || !double.IsFinite(uy) + || page.Owner.Font is not { } font) return; + if (!(height > 0 && double.IsFinite(height))) height = 0; var alignment = (flags & 0x80) != 0 ? PdfTextAlignment.Center : (flags & 0x100) != 0 ? PdfTextAlignment.Right : PdfTextAlignment.Left; double angle = Math.Atan2(by, bx) * 180.0 / Math.PI; - string[] parts = text.Split('\n'); - for (int i = 0; i < parts.Length; i++) + double ascent = sizeMm * font.Ascent / font.UnitsPerEm; + double first = TitleBlockFirstBaseline(ascent, height, flags); + double spacing = height > 0 ? height / parts.Count : sizeMm * 1.25; + for (int i = 0; i < parts.Count; i++) { if (parts[i].Length == 0) continue; - double lineY = y - i * sizeMm * 1.25; - if (Math.Abs(angle) < 1e-6) page.DrawText(parts[i], x, lineY, sizeMm, alignment); - else page.DrawTextRotated(parts[i], x, lineY, sizeMm, angle, alignment); + double offset = first - i * spacing; + double lineX = x + ux * offset, lineY = y + uy * offset; + if (Math.Abs(angle) < 1e-6) + { + if (useArialLayout && WindowsArialLayout.TryMeasure(parts[i], sizeMm, out double layoutWidth, out double layoutAscent)) + { + double left = TextLeft(lineX, layoutWidth); + lineY += ascent - layoutAscent; + if (opaque) page.DrawRectangle(left, lineY + layoutAscent - spacing, layoutWidth, spacing, 0, 1); + page.DrawText(parts[i], left, lineY, sizeMm); + } + else + { + if (opaque) + { + double width = page.MeasureText(parts[i], sizeMm); + page.DrawRectangle(TextLeft(lineX, width), lineY + ascent - spacing, width, spacing, 0, 1); + } + page.DrawText(parts[i], lineX, lineY, sizeMm, alignment); + } + } + else page.DrawTextRotated(parts[i], lineX, lineY, sizeMm, angle, alignment); } + + double TextLeft(double anchor, double width) => alignment switch + { + PdfTextAlignment.Center => anchor - width / 2, + PdfTextAlignment.Right => anchor - width, + _ => anchor, + }; } + internal static double TitleBlockFirstBaseline(double ascent, double height, int flags) + => (flags & 0xe00) switch + { + 0x200 => -ascent, + 0x400 => height / 2 - ascent, + 0x800 => height - ascent, + _ => 0, + }; + + internal static string TitleBlockScale(IReadOnlyCollection scales, bool russian) + => scales.Count switch + { + 0 => "", + 1 => FormattableString.Invariant($" 1 : {scales.Single()}"), + _ => russian ? "Как указано" : "As indicated", + }; + /// The printed value of a title block label: the sheet number and name, the drawn/checked by, the /// print time, the view scale, or a project information field, as rvt-prt resolves them. private static string TitleBlockLabelValue(RvtDocument document, Element sheet, string scaleText, int paramId) @@ -1121,12 +1366,35 @@ static string Text(Element element, BuiltInParameter id) => private static readonly System.Collections.Concurrent.ConcurrentDictionary Logos = new(); - private static readonly System.Collections.Concurrent.ConcurrentDictionary<(string Path, int ViewId), PdfJpegImage?> + private static readonly System.Collections.Concurrent.ConcurrentDictionary<(string Path, int SymbolId), + IReadOnlyList<(PdfRasterImage Image, double X, double Y, double Width, double Height)>> TitleImages = new(); + + private static IReadOnlyList<(PdfRasterImage Image, double X, double Y, double Width, double Height)> + TitleBlockImages(RvtDocument document, int symbolId) + { + if (document.SourcePath is not { Length: > 0 } path) return []; + return TitleImages.GetOrAdd((path, symbolId), key => + { + var images = new List<(PdfRasterImage, double, double, double, double)>(); + foreach (var placement in RvtRaster.FindSheetImagePlacements(key.Path, key.SymbolId)) + { + var symbol = document.GetElement(placement.SymbolId); + if (symbol?.ImagePaperSize is not { } size || symbol.ImageHolderId is not int holder + || RvtRaster.FindImagePng(key.Path, holder) is not { } image) continue; + double width = size.Width * placement.ScaleX, height = size.Height * placement.ScaleY; + images.Add((image, placement.X - width / 2, placement.Y - height / 2, width, height)); + } + return images; + }); + } + + private static readonly System.Collections.Concurrent.ConcurrentDictionary<(string Path, int ViewId), + (PdfJpegImage Image, (double Width, double Height)? Size)?> Renderings = new(); /// The JPEG a rendering view stores: the image symbol the view owns carries its type, and the type's block /// holds the image. - private static PdfJpegImage? RenderingImage(RvtDocument document, int viewId) + private static (PdfJpegImage Image, (double Width, double Height)? Size)? RenderingImage(RvtDocument document, int viewId) { if (document.SourcePath is not { Length: > 0 } path) return null; return Renderings.GetOrAdd((path, viewId), key => @@ -1136,7 +1404,16 @@ static string Text(Element element, BuiltInParameter id) => if (element.OwnerViewId != key.ViewId || element.RootClassName != "ImageSymbol") continue; if (element.TypeId <= 0) continue; var image = RvtRaster.FindJpeg(key.Path, element.TypeId); - if (image != null) return image; + if (image == null) continue; + var size = element.ImagePaperSize; + if (size is { } bounds) + { + var placement = document.Elements.FirstOrDefault(e => e.OwnerViewId == key.ViewId + && e.RootClassName == "ImageInstance" && e.TypeId == element.Id); + if (placement?.ImageInstanceScale is { } scale) + size = (bounds.Width * scale.Width, bounds.Height * scale.Height); + } + return (image, size); } return null; }); @@ -1191,7 +1468,8 @@ private static void DrawPlantingSchedule(PdfPage page, RvtDocument document, dou /// Writes the room legend: a title and one row per kind of room, a colour swatch and the name. The rows /// start at (x, y) and go down. - private static void DrawRoomLegend(PdfPage page, IEnumerable names, double x, double y) + private static void DrawRoomLegend(PdfPage page, IEnumerable names, double x, double y, + (double Width, double Height)? swatch, IReadOnlyDictionary? colors) { var seen = new List(); foreach (string name in names) @@ -1201,12 +1479,28 @@ private static void DrawRoomLegend(PdfPage page, IEnumerable names, doub seen.Add(name); } if (seen.Count == 0) return; + if (swatch is { } style) + { + double width = style.Width * FeetToMillimetres, height = style.Height * FeetToMillimetres; + // shortcut: scale text and spacing from the swatch until the legend's font and row styles are decoded. + page.DrawText("Room Legend", x, y + height * 0.92, height * 0.93); + double rowTop = y; // The stored origin is the top left of the first swatch. + foreach (string name in seen.OrderBy(name => name, StringComparer.OrdinalIgnoreCase)) + { + double bottom = rowTop - height; + page.DrawPolyline([(x, bottom), (x + width, bottom), (x + width, rowTop), (x, rowTop)], 0.15, true, + PlanPrinter.RoomFill(name, colors)); + page.DrawText(name, x + width + height / 4, bottom + height * 0.27, height * 0.67); + rowTop -= height * 4 / 3; + } + return; + } page.DrawText("Room Legend", x, y, 3.5); double row = y - 6; foreach (string name in seen) { page.DrawPolyline([(x, row), (x + 4, row), (x + 4, row + 4), (x, row + 4)], 0.15, true, - PlanPrinter.RoomFill(name)); + PlanPrinter.RoomFill(name, colors)); page.DrawText(name, x + 6, row + 0.8, 2.8); row -= 5.5; } @@ -1319,6 +1613,10 @@ internal static bool TryCropFrame(double centerXMm, double centerYMm, double sca return true; } + internal static bool CropOverlapsSheet(double frameX, double frameY, double frameWidth, double frameHeight, + double sheetWidth, double sheetHeight) => + frameX + frameWidth > 0 && frameY + frameHeight > 0 && frameX < sheetWidth && frameY < sheetHeight; + /// True when the view's decoded plane matches the crop frame's basis and origin: the collection /// projected the model with these very axes, so the crop rectangle maps onto its content. Guards the crop /// path where the collection fell back to compass axes. @@ -1334,8 +1632,7 @@ static bool Same(double[] a, double[] b) => && Math.Abs(origin[0] - crop.OriginX) + Math.Abs(origin[1] - crop.OriginY) + Math.Abs(origin[2] - crop.OriginZ) < 1e-3; } - /// True when the view is a sun, lighting or energy analysis: it prints as its shaded study, - /// not as vector massing, so a sheet viewport of it draws nothing (the reference shows no such linework). + /// True for sun, lighting and energy analysis views, whose sheets use a shaded viewport. internal static bool IsAnalysisView(Element? view) => view?.Name is string name && (name.Contains("Solar", StringComparison.OrdinalIgnoreCase) || name.Contains("Lighting", StringComparison.OrdinalIgnoreCase) @@ -1386,9 +1683,13 @@ void Grow(double x, double y) foreach (var line in contours) { Grow(line.X1, line.Y1); Grow(line.X2, line.Y2); } foreach (var plant in plants) { Grow(plant.X - plant.Radius, plant.Y - plant.Radius); Grow(plant.X + plant.Radius, plant.Y + plant.Radius); } foreach (var polygon in entourage) foreach (var point in polygon) Grow(point.X, point.Y); + if (site.PropertyLines != null) + foreach (var line in site.PropertyLines) + foreach (var point in line) Grow(point.X, point.Y); Grow(building.MinX, building.MinY); Grow(building.MaxX, building.MaxY); if (!(minX <= maxX) || !(minY <= maxY)) return site; - return new SitePrinter.SiteContent(topography, contours, plants, entourage, minX, minY, maxX, maxY); + return new SitePrinter.SiteContent(topography, contours, plants, entourage, minX, minY, maxX, maxY, + site.PropertyLines, site.NativePrimaryLevels); } } diff --git a/src/RvtIO/Print/SheetPrinter.cs b/src/RvtIO/Print/SheetPrinter.cs index 26d8b9bc..c51f0e9e 100644 --- a/src/RvtIO/Print/SheetPrinter.cs +++ b/src/RvtIO/Print/SheetPrinter.cs @@ -18,8 +18,7 @@ public sealed class SheetPrintOptions /// How far the linework extent may be from a standard paper size and still snap to it. public double PaperToleranceMillimetres { get; set; } = 8; - /// True writes the sheet number and name in the upper-left corner; the title block text itself is not - /// decoded. + /// True writes the sheet number and name in a corner when the sheet has no decoded text notes. public bool DrawSheetFields { get; set; } = true; } @@ -30,15 +29,13 @@ public sealed class SheetPrintOptions /// The width of the decoded linework in millimetres, 0 when nothing is drawn. /// The height of the decoded linework in millimetres. /// The number of location curves of the sheet's own elements. -/// The number of text notes of the sheet (their text is not decoded). +/// The number of text notes belonging to the sheet. public sealed record PrintableSheet(int SheetId, string? Number, string? Name, double WidthMillimetres, double HeightMillimetres, int CurveCount, int TextCount); /// -/// Prints a sheet to a PDF page from the linework the reader decodes: the location curves of the elements the sheet -/// owns (the border, the title block frame and its rules) at their sheet coordinates. Text notes are not decoded, so a -/// title block is printed as its linework with the sheet number and name written in a corner; the placed views are not -/// composed yet (see docs/printing.md). +/// Prints a sheet's decoded linework and text notes at their sheet coordinates. +/// Use to print the placed views and title block. /// public static class SheetPrinter { @@ -196,24 +193,7 @@ void Grow(double x, double y) // The text notes of the sheet, at the positions the file stores (sheet coordinates, feet). The text is real, // selectable PDF text when the document has an embedded font. - bool drewText = false; - if (pdf.Font != null) - { - foreach (var element in document.Elements) - { - if (element.OwnerViewId != sheet.Id) continue; - if (element.Text is not { Length: > 0 } text || element.TextPosition is not { Length: >= 2 } position) - continue; - double x = position[0] * FeetToMillimetres + offsetX; - double y = position[1] * FeetToMillimetres + offsetY; - double height = element.TextFontSizePoints is double points && points > 0 - ? points * 25.4 / 72 : 2.5; - string[] lines = text.Split('\n'); - for (int line = 0; line < lines.Length; line++) - page.DrawText(lines[line], x, y - line * height * 1.25, height); - drewText = true; - } - } + bool drewText = pdf.Font != null && DrawSheetNotes(page, document, sheet.Id, offsetX, offsetY); // The number and name in a corner only when the sheet has no decoded text of its own (the stamp labels are // then missing and the corner identifies the page). @@ -226,6 +206,33 @@ void Grow(double x, double y) } } + internal static bool DrawSheetNotes(PdfPage page, RvtDocument document, int sheetId, double offsetX, double offsetY) + { + var nativeNotes = document.RawData.PlanNotes?.GetValueOrDefault(sheetId)?.ToDictionary(note => note.ElementId); + double X(double feet) => feet * FeetToMillimetres + offsetX; + double Y(double feet) => feet * FeetToMillimetres + offsetY; + bool drewText = false; + foreach (var element in document.Elements) + { + if (element.OwnerViewId != sheetId) continue; + if (nativeNotes?.TryGetValue(element.Id, out var note) == true + && PlanPrinter.DrawTextNote(page, document, note, X, Y)) + { + drewText = true; + continue; + } + if (element.Text is not { Length: > 0 } text || element.TextPosition is not { Length: >= 2 } position) + continue; + double x = X(position[0]), y = Y(position[1]); + double size = element.TextFontSizePoints is double points && points > 0 ? points * 25.4 / 72 : 2.5; + string[] lines = text.Split('\n'); + for (int i = 0; i < lines.Length; i++) + page.DrawText(lines[i], x, y - i * size * 1.25, size); + drewText = true; + } + return drewText; + } + /// The paper that holds the extent: the standard size it matches within the tolerance, else the extent /// itself plus a small margin. private static PdfPageSize PaperFor(double width, double height, double tolerance) diff --git a/src/RvtIO/Print/SitePrinter.ContourLabels.cs b/src/RvtIO/Print/SitePrinter.ContourLabels.cs new file mode 100644 index 00000000..6e58c049 --- /dev/null +++ b/src/RvtIO/Print/SitePrinter.ContourLabels.cs @@ -0,0 +1,76 @@ +using RvtIO.Compact; +using RvtIO.Ifc; +using RvtIO.Model; +using RvtIO.Pdf; + +namespace RvtIO.Print; + +public static partial class SitePrinter +{ + private sealed record PrintedContourLabel(double X, double Y, double Level, double Height, double HalfWidth, + double Baseline, double Angle, double Cosine, double Sine, string Text); + + private static List ContourLabels(PdfPage page, RvtDocument? document, int? viewId, + ViewCropFrame? basis, Func toX, Func toY) + { + var result = new List(); + if (viewId is not int view || page.Owner.Font is not { CapHeight: > 0 } font + || document?.RawData.SerializedFormatSettings is not { } formatting + || document.RawData.SiteContourLabels?.GetValueOrDefault(view) is not { } labels) + return result; + var hidden = document.RawData.ViewHiddenElements?.GetValueOrDefault(view); + foreach (var label in labels) + { + if (hidden?.Contains(label.ElementId) == true || hidden?.Contains(label.SurfaceId) == true) continue; + double level = label.Position[2]; + string? text = CompactValueFormatter.Format(level, IfcNumericUnitPlan.LengthSpecName, formatting); + if (string.IsNullOrEmpty(text)) continue; + var (x, y) = Project(label.Position); + var (dx, dy) = Project(label.Direction); + if (dx == 0 && dy == 0) continue; + if (dx < 0) { dx = -dx; dy = -dy; } + double angle = Math.Atan2(dy, dx); + double height = label.TextHeightFeet * FeetToMillimetres; + double capHeight = height * font.CapHeight / font.UnitsPerEm; + double halfWidth = (page.MeasureText(text, height) + height) / 2; + result.Add(new(toX(x * FeetToMillimetres), toY(y * FeetToMillimetres), level * FeetToMillimetres, + height, halfWidth, capHeight / 2, angle, Math.Cos(angle), Math.Sin(angle), text)); + } + return result; + + (double X, double Y) Project(double[] point) => basis == null ? (point[0], point[1]) + : (point[0] * basis.Right[0] + point[1] * basis.Right[1], point[0] * basis.Up[0] + point[1] * basis.Up[1]); + } + + private static IEnumerable<(double Start, double End)> ContourSpans(double x1, double y1, double x2, double y2, + double level, List labels) + { + var gaps = new List<(double Start, double End)>(); + foreach (var label in labels) + { + if (Math.Abs(level - label.Level) > 1e-6) continue; + var (ax, ay) = InLabel(x1, y1); + var (bx, by) = InLabel(x2, y2); + if (!ElevationPrinter.ClipSegment(ax, ay, bx, by, + -label.HalfWidth, -label.Height / 2, label.HalfWidth, label.Height / 2, + out double sx, out double sy, out double ex, out double ey)) continue; + bool horizontal = Math.Abs(bx - ax) >= Math.Abs(by - ay); + gaps.Add(horizontal ? ((sx - ax) / (bx - ax), (ex - ax) / (bx - ax)) + : ((sy - ay) / (by - ay), (ey - ay) / (by - ay))); + + (double X, double Y) InLabel(double x, double y) + { + x -= label.X; + y -= label.Y; + return (x * label.Cosine + y * label.Sine, -x * label.Sine + y * label.Cosine); + } + } + double start = 0; + foreach (var gap in gaps.OrderBy(gap => gap.Start)) + { + if (gap.Start > start) yield return (start, gap.Start); + start = Math.Max(start, gap.End); + } + if (start < 1) yield return (start, 1); + } +} diff --git a/src/RvtIO/Print/SitePrinter.Equipment.cs b/src/RvtIO/Print/SitePrinter.Equipment.cs new file mode 100644 index 00000000..42f6c0da --- /dev/null +++ b/src/RvtIO/Print/SitePrinter.Equipment.cs @@ -0,0 +1,87 @@ +using RvtIO.BuiltIns; +using RvtIO.Internal; +using RvtIO.Model; +using RvtIO.Pdf; + +namespace RvtIO.Print; + +public static partial class SitePrinter +{ + private static PlanFixtureProjection? CollectEquipment(RvtDocument document, int viewId, + double bottom, double cut, IReadOnlySet? hidden, out HashSet shadowCasters) + { + shadowCasters = []; + int? detail = document.GetElement(viewId)?.LookupParameter(BuiltInParameter.VIEW_DETAIL_LEVEL)?.Value as int?; + if (detail is not (1 or 2)) return null; + + var hiddenCategories = document.RawData.ViewHiddenCategories?.GetValueOrDefault(viewId); + var lines = new List(); + var masks = new List>(); + foreach (var element in document.Elements) + { + if (element.CategoryId is not ((int)BuiltInCategory.OST_ElectricalEquipment or (int)BuiltInCategory.OST_Site) + || element.IsDiscovered || element.SerializedUnplacedOwnerId is > 0 + || element.NativeIsSymbol == true || element.RootClassIs("FamilySymbol") + || element.OwnerViewId is > 0 && element.OwnerViewId != viewId + || hidden?.Contains(element.Id) == true || hiddenCategories?.Contains(element.CategoryId.Value) == true + || element.BoundingBox is not { Length: 6 } box || !(box[2] >= bottom && box[5] <= cut) + || element.PlacedPlanFixtureGraphics is not { } graphics) + continue; + + var projection = detail == 1 ? graphics.CoarseProjection : graphics.MediumProjection; + if (projection == null) continue; + var visibleLines = projection.Lines.Where(line => + document.RawData.GraphicsStylePens?.TryGetValue(line.StyleId, out var style) != true + || hiddenCategories?.Contains(style.CategoryId) != true).ToArray(); + if (visibleLines.Length == 0) continue; + lines.AddRange(visibleLines); + masks.AddRange(projection.Masks); + if (element.CategoryId == (int)BuiltInCategory.OST_Site) shadowCasters.Add(element.Id); + } + return lines.Count == 0 ? null : new(lines, masks); + } + + private static void DrawEquipment(PdfPage page, RvtDocument document, SiteGraphics graphics, ViewCropFrame? basis, + double scale, Func toX, Func toY) + { + var equipment = graphics.Equipment!; + var masks = new List>(); + foreach (var mask in equipment.Masks) + { + var ring = mask.Select(point => + { + var (x, y) = InView(point); + return (toX(x), toY(y)); + }).ToList(); + double area = PlanPrinter.SignedArea(ring); + if (!double.IsFinite(area) || Math.Abs(area) < 1e-9) continue; + if (area < 0) ring.Reverse(); + masks.Add(ring); + } + if (masks.Count > 0) + { + page.FillPolygonUnion(masks, 1); + // The mask hides contours behind the symbol. Cast shadows can still cross it. + if (graphics.GroundShadows.Count > 0) + { + page.BeginPolygonClip(masks, evenOdd: false); + page.FillPolygonUnion(graphics.GroundShadows.Select(ring => ring.Select(p => (toX(p.X), toY(p.Y))).ToList()), + graphics.ShadowGray); + page.EndClip(); + } + } + + var lines = equipment.Lines.Select(line => + { + var (ax, ay) = InView(line.Start); + var (bx, by) = InView(line.End); + return (ax, ay, bx, by, line.StyleId); + }).ToList(); + PlanPrinter.DrawFixtureLines(page, document, lines, scale, 0.1, toX, toY, null); + + (double X, double Y) InView(double[] point) => basis == null + ? (point[0] * FeetToMillimetres, point[1] * FeetToMillimetres) + : ((point[0] * basis.Right[0] + point[1] * basis.Right[1]) * FeetToMillimetres, + (point[0] * basis.Up[0] + point[1] * basis.Up[1]) * FeetToMillimetres); + } +} diff --git a/src/RvtIO/Print/SitePrinter.Planting.cs b/src/RvtIO/Print/SitePrinter.Planting.cs new file mode 100644 index 00000000..6f0c6ecc --- /dev/null +++ b/src/RvtIO/Print/SitePrinter.Planting.cs @@ -0,0 +1,45 @@ +using RvtIO.BuiltIns; +using RvtIO.Model; +using RvtIO.Pdf; + +namespace RvtIO.Print; + +public static partial class SitePrinter +{ + // The shared stock RPC plan symbol, measured in model axes on the Revit export. + private static readonly double[] RpcSpokeAngles = + [15, 30.75, 61, 71.75, 83.25, 104.75, 110, 160.5, 184.25, 190.25, 225, 265.75, 275, 302.75, 329.75, 342.25]; + + private static double? RpcPlanRadius(RvtDocument document, Element element) + { + var type = document.GetElement(element.TypeId); + if (type?.LookupParameter(BuiltInParameter.RENDER_RPC_FILENAME)?.Value is not string { Length: > 0 }) + return null; + var height = element.LookupParameter(BuiltInParameter.RENDER_PLANT_HEIGHT)?.Value + ?? type.LookupParameter(BuiltInParameter.RENDER_PLANT_HEIGHT)?.Value; + // The common plan mark scales with the saved RPC height, independently of the mesh bounds. + return height is double feet && feet > 0 && double.IsFinite(feet) ? feet * 0.275 * FeetToMillimetres : null; + } + + private static void DrawRpcPlant(PdfPage page, double x, double y, double radius, ViewCropFrame? basis, + double width, PdfColor color) + { + const int perimeterSegments = 64; + var previous = (X: x + radius, Y: y); + for (int i = 1; i <= perimeterSegments; i++) + { + double angle = i * (2 * Math.PI / perimeterSegments); + var point = (X: x + Math.Cos(angle) * radius, Y: y + Math.Sin(angle) * radius); + page.DrawLine(previous.X, previous.Y, point.X, point.Y, width, color); + previous = point; + } + foreach (double angle in RpcSpokeAngles) + { + double radians = angle * Math.PI / 180; + double dx = Math.Cos(radians), dy = Math.Sin(radians); + double projectedX = basis == null ? dx : dx * basis.Right[0] + dy * basis.Right[1]; + double projectedY = basis == null ? dy : dx * basis.Up[0] + dy * basis.Up[1]; + page.DrawLine(x, y, x + projectedX * radius, y + projectedY * radius, width, color); + } + } +} diff --git a/src/RvtIO/Print/SitePrinter.PropertyTags.cs b/src/RvtIO/Print/SitePrinter.PropertyTags.cs new file mode 100644 index 00000000..8410c4f6 --- /dev/null +++ b/src/RvtIO/Print/SitePrinter.PropertyTags.cs @@ -0,0 +1,93 @@ +using System.Globalization; +using RvtIO.BuiltIns; +using RvtIO.Compact; +using RvtIO.Model; +using RvtIO.Parsing; +using RvtIO.Pdf; + +namespace RvtIO.Print; + +public static partial class SitePrinter +{ + internal static void DrawPropertyTags(PdfPage page, RvtDocument document, int viewId, ViewCropFrame? basis, + SiteContent site, double scale, double originX, double originY) + { + var raw = document.RawData; + // shortcut: quadrant bearings in degrees, minutes and seconds using the resolved active location. + if (raw.PropertyBearingFormat != (1, 1) || !raw.SharedTransformIsActiveLocation + || raw.SharedTransform is not { Length: 12 } shared + || raw.SitePropertyTags?.GetValueOrDefault(viewId) is not { } tags + || raw.SitePropertyTagStyles is not { } styles + || raw.SerializedFormatSettings is not { } formatting || page.Owner.Font is not { } font) return; + + var hidden = raw.ViewHiddenElements?.GetValueOrDefault(viewId); + bool russian = CultureInfo.CurrentUICulture.TwoLetterISOLanguageName == "ru"; + foreach (var tag in tags) + { + if (hidden?.Contains(tag.ElementId) == true || !styles.TryGetValue(tag.SymbolId, out var labels) + || document.GetElement(tag.ElementId) is not { SitePropertyCurve: { Count: >= 2 } curve } segment) + continue; + var a = curve[0]; + var b = curve[^1]; + double dx = b.X - a.X, dy = b.Y - a.Y; + double distance = Math.Sqrt(dx * dx + dy * dy); + if (!(distance > 0) || !double.IsFinite(distance)) continue; + + double east = dx * shared[0] + dy * shared[3], north = dx * shared[1] + dy * shared[4]; + var (ns, bearing, ew) = PropertyBearing(east, north, russian); + var tangent = segment.SitePropertyArcCenter is { } center + ? (X: center.Y - tag.Y, Y: tag.X - center.X) : (X: dx, Y: dy); + if (curve.Count > 2 && segment.SitePropertyArcCenter == null) continue; + var (tx, ty) = InView(tangent.X, tangent.Y); + if (tx == 0 && ty == 0) continue; + if (tx < 0 || (tx == 0 && ty < 0)) { tx = -tx; ty = -ty; } + double angle = Math.Atan2(ty, tx), cos = Math.Cos(angle), sin = Math.Sin(angle); + + var (x, y) = InView(tag.X, tag.Y); + double hx = originX + (x * FeetToMillimetres - site.MinX) / scale; + double hy = originY + (y * FeetToMillimetres - site.MinY) / scale; + foreach (var (label, fontPoints) in labels) + { + string? value = (BuiltInParameter)label.ParamId switch + { + BuiltInParameter.PROPERTY_SEGMENT_N_S => ns, + BuiltInParameter.PROPERTY_SEGMENT_BEARING => bearing, + BuiltInParameter.PROPERTY_SEGMENT_E_W => ew, + BuiltInParameter.PROPERTY_SEGMENT_DISTANCE => + PropertyDistance(distance, label.SingleParameterFormat, formatting, russian), + _ => null, + }; + if (string.IsNullOrEmpty(value)) continue; + var layout = PlanPrinter.AnnotationLabelLayout(font, label, fontPoints, 0, 0); + double px = hx + layout.X * cos - layout.Baseline * sin; + double py = hy + layout.X * sin + layout.Baseline * cos; + page.DrawTextRotated(label.Prefix + value + label.Suffix, px, py, + layout.Size, angle * 180 / Math.PI, layout.Alignment); + } + } + + (double X, double Y) InView(double x, double y) => basis == null ? (x, y) + : (x * basis.Right[0] + y * basis.Right[1], x * basis.Up[0] + y * basis.Up[1]); + } + + internal static (string NorthSouth, string Bearing, string EastWest) PropertyBearing( + double east, double north, bool russian) + { + string ns = north < 0 ? (russian ? "Ю" : "S") : (russian ? "С" : "N"); + string ew = east < 0 ? (russian ? "З" : "W") : (russian ? "В" : "E"); + int seconds = (int)Math.Round(Math.Atan2(Math.Abs(east), Math.Abs(north)) * (648000 / Math.PI), + MidpointRounding.AwayFromZero); + return (ns, FormattableString.Invariant($"{seconds / 3600}° {seconds / 60 % 60:00}' {seconds % 60:00}\""), ew); + } + + private static string? PropertyDistance(double feet, TfBlockDeserializer.UnitFormatOption? option, + CompactFormatSettings formatting, bool russian) + { + if (option is not { UseDefault: 0 }) return null; + if (russian && option.Symbol == "autodesk.unit.symbol:footSingleQuote-1.0.1" + && option.Unit == "autodesk.unit.unit:feet-1.0.1") + return CompactValueFormatter.Format(feet, option with { Symbol = "" }, formatting) is { } value + ? value + "фут" : null; + return CompactValueFormatter.Format(feet, option, formatting); + } +} diff --git a/src/RvtIO/Print/SitePrinter.Roof.cs b/src/RvtIO/Print/SitePrinter.Roof.cs new file mode 100644 index 00000000..1eb3c521 --- /dev/null +++ b/src/RvtIO/Print/SitePrinter.Roof.cs @@ -0,0 +1,231 @@ +using RvtIO.BuiltIns; +using RvtIO.Internal; +using RvtIO.Model; +using RvtIO.Pdf; + +namespace RvtIO.Print; + +public static partial class SitePrinter +{ + internal sealed record SiteGraphics( + IReadOnlyList Surfaces, + IReadOnlyList> GroundShadows, + double ShadowGray, + PlanFixtureProjection? Equipment); + internal sealed record SiteSurface(List> Rings, FillHatch.ModelGrid? Grid, + IReadOnlyList>? Glazing = null, + IReadOnlyList>? Shadows = null, + IReadOnlyList>? Visible = null, + BuiltInCategory Category = BuiltInCategory.OST_Roofs, + int RailId = 0); + + internal static SiteGraphics? CollectOpaqueGraphics(RvtDocument document, int viewId, ViewCropFrame? basis) + { + if (PlanPrinter.GetPlanRange(document, -1, viewId) is not { } range) return null; + var hidden = document.RawData.ViewHiddenElements?.GetValueOrDefault(viewId); + var hiddenCategories = document.RawData.ViewHiddenCategories?.GetValueOrDefault(viewId); + bool showPatterns = document.RawData.OpaqueViewsWithSurfacePatterns?.Contains(viewId) == true; + var roofWindows = document.Elements.Where(window => + window.CategoryId == (int)BuiltInCategory.OST_Windows && !window.IsDiscovered + && window.NativeIsSymbol != true && window.SerializedUnplacedOwnerId is not > 0 + && !window.RootClassIs("FamilySymbol") && window.SerializedHostId is > 0 + && hidden?.Contains(window.Id) != true + && hiddenCategories?.Contains((int)BuiltInCategory.OST_Windows) != true + && window.Geometry is { Faces.Count: > 0 }) + .ToLookup(window => window.SerializedHostId!.Value); + var surfaces = new List<(double Height, GeoFace Face, SiteSurface Surface)>(); + var clippedFaces = new HashSet(); + var addedCasters = new Dictionary>(); + var opaquePanes = new List(); + foreach (var element in document.Elements) + { + if (element.CategoryId is not ((int)BuiltInCategory.OST_Roofs or (int)BuiltInCategory.OST_Stairs + or (int)BuiltInCategory.OST_Floors + or (int)BuiltInCategory.OST_RailingTopRail) + || element.IsDiscovered || hidden?.Contains(element.Id) == true + || element.Geometry is not { Faces.Count: > 0 } geometry) + continue; + var category = (BuiltInCategory)element.CategoryId.Value; + bool horizontal = category is BuiltInCategory.OST_Stairs or BuiltInCategory.OST_Floors; + bool rail = category == BuiltInCategory.OST_RailingTopRail; + if (horizontal && (element.NativeIsSymbol == true || element.SerializedUnplacedOwnerId is > 0 + || !element.RootClassIs(category == BuiltInCategory.OST_Stairs ? "StairsElement" : "Floor") + || hiddenCategories?.Contains((int)category) == true)) + continue; + if (rail && !VisibleTopRail(element)) continue; + var railFaces = rail ? new List() : null; + List>? glazing = null; + foreach (var face in geometry.Faces) + { + if (face.CurvedSurface || face.OuterVertices is not { Count: >= 3 } outer || !InRange(outer) + || face.InnerVertices?.Any(hole => hole.Any(p => !Valid(p))) == true) continue; + if (rail) + { + if (!face.PlaneSurface || face.InnerLoops is { Count: > 0 } && face.InnerVertices is not { Count: > 0 } + || document.GetElement(face.RenderStyleId ?? face.NestedRenderStyleId ?? -1) + ?.SerializedMaterialTransparency is > 0) continue; + railFaces!.Add(face); + } + if (face.Normal is not { Length: 3 } normal || !(normal[2] > (rail ? 1e-9 : 0))) continue; + if (horizontal && (!face.PlaneSurface || outer.Any(point => Math.Abs(point[2] - outer[0][2]) > 1e-8) + || face.InnerLoops is { Count: > 0 } && face.InnerVertices is not { Count: > 0 })) continue; + var rings = Rings(face); + if (rings.Count == 0) continue; + if (category == BuiltInCategory.OST_Roofs && rings.Count > 1) + glazing ??= CollectSkylights(element.Id); + if (horizontal || rail) clippedFaces.Add(face); + surfaces.Add((outer.Average(p => p[2]), face, new SiteSurface(rings, + showPatterns && category == BuiltInCategory.OST_Roofs + ? FillHatch.ProjectModelGrid(document, face, InView) : null, + rings.Count > 1 && glazing is { Count: > 0 } ? glazing : null, + Category: category, RailId: rail ? element.Id : 0))); + } + if (railFaces is { Count: > 0 }) addedCasters.Add(element.Id, railFaces); + } + + var equipment = CollectEquipment(document, viewId, range.Bottom, range.Cut, hidden, out var equipmentCasters); + var surfaceFaces = surfaces.Select(entry => entry.Face).ToHashSet(); + var (shadows, gray) = CollectShadows(document, viewId, basis, range.Cut, hidden, equipmentCasters, + addedCasters, opaquePanes, surfaceFaces, clippedFaces, out var surfaceShadows, out var visibility); + return surfaces.Count == 0 && shadows.Count == 0 && equipment == null ? null + : new SiteGraphics(surfaces.OrderBy(entry => entry.Surface.Category != BuiltInCategory.OST_Roofs) + .ThenBy(entry => entry.Height).Select(entry => + entry.Surface with + { + Shadows = surfaceShadows.GetValueOrDefault(entry.Face), + Visible = visibility.GetValueOrDefault(entry.Face), + }).ToList(), + shadows, gray, equipment); + + bool VisibleTopRail(Element rail) => + rail is { RootClassName: "TopRail", NativeIsSymbol: not true, SerializedUnplacedOwnerId: not > 0, + SerializedOwningElementId: > 0 and int ownerId } + && hiddenCategories?.Contains((int)BuiltInCategory.OST_RailingTopRail) != true + && hidden?.Contains(ownerId) != true + && document.GetElement(ownerId) is { RootClassName: "BaseRailing", CategoryId: int ownerCategory, + IsDiscovered: false, NativeIsSymbol: not true, SerializedUnplacedOwnerId: not > 0 } + && hiddenCategories?.Contains(ownerCategory) != true; + + List> CollectSkylights(int hostId) + { + var panes = new List>(); + foreach (var window in roofWindows[hostId]) + { + var frameFaces = new List(); + foreach (var face in window.Geometry!.Faces) + { + if (!face.PlaneSurface || face.CurvedSurface + || face.OuterVertices is not { Count: >= 3 } vertices || !InRange(vertices)) continue; + var material = document.GetElement(face.RenderStyleId ?? face.NestedRenderStyleId ?? -1); + if (material?.SerializedMaterialTransparency == 0) + frameFaces.Add(face); + else if (material?.SerializedMaterialTransparency is > 0 and <= 1 + && face.Normal is [_, _, > 0] + && face.InnerVertices is not { Count: > 0 } && face.InnerLoops is not { Count: > 0 } + && Project(vertices, true) is { } pane) + { + panes.Add(pane); + opaquePanes.Add(face); + } + } + if (frameFaces.Count > 0) addedCasters.Add(window.Id, frameFaces); + } + return panes; + } + + static bool Valid(double[] point) => point.Length == 3 && point.All(double.IsFinite); + bool InRange(List vertices) => + vertices.All(p => Valid(p) && p[2] >= range.Bottom - 1e-9 && p[2] <= range.Cut + 1e-9); + + (double X, double Y) InView(double[] point) => basis == null + ? (point[0] * FeetToMillimetres, point[1] * FeetToMillimetres) + : ((point[0] * basis.Right[0] + point[1] * basis.Right[1]) * FeetToMillimetres, + (point[0] * basis.Up[0] + point[1] * basis.Up[1]) * FeetToMillimetres); + + List> Rings(GeoFace face) + { + var outer = Project(face.OuterVertices!, true); + if (outer == null) return []; + var result = new List> { outer }; + foreach (var hole in face.InnerVertices ?? []) + if (Project(hole, false) is { } ring) result.Add(ring); + return result; + } + + List<(double X, double Y)>? Project(List vertices, bool exterior) + { + var ring = vertices.Select(InView).ToList(); + double area = PlanPrinter.SignedArea(ring); + if (!double.IsFinite(area) || Math.Abs(area) < 1e-6) return null; + if ((area > 0) != exterior) ring.Reverse(); + return ring; + } + } + + internal static void DrawSurfaces(PdfPage page, RvtDocument document, SiteGraphics graphics, SiteContent site, + double scale, double originX, double originY) + { + int printedScale = (int)Math.Round(scale); + double roofPen = PenWidths.TryGetWidth(document, (int)BuiltInCategory.OST_Roofs, false, + printedScale, out double width) ? width : 0.1; + double stairPen = PenWidths.TryGetWidth(document, (int)BuiltInCategory.OST_Stairs, false, + printedScale, out width) ? width : 0.1; + double floorPen = PenWidths.TryGetWidth(document, (int)BuiltInCategory.OST_Floors, false, + printedScale, out width) ? width : 0.1; + double railPen = PenWidths.TryGetWidth(document, (int)BuiltInCategory.OST_RailingTopRail, false, + printedScale, out width) ? width : stairPen; + foreach (var surface in graphics.Surfaces) + { + if (surface.Visible is { Count: 0 }) continue; + double pen = surface.Category switch + { + BuiltInCategory.OST_Stairs => stairPen, + BuiltInCategory.OST_Floors => floorPen, + _ => roofPen, + }; + var projected = surface.Rings.Select(OnPage).ToList(); + if (surface.Visible is { } visible) page.BeginPolygonClip(visible.Select(OnPage), evenOdd: false); + page.FillPolygonUnion(projected, 1); + if (surface.Shadows is { Count: > 0 } shadows) + { + page.BeginPolygonClip(projected); + page.FillPolygonUnion(shadows.Select(OnPage), graphics.ShadowGray); + page.EndClip(); + } + if (surface.Grid is { } grid) + page.FillWithParallelLines(projected, grid.Spacing / scale, grid.Angle, + originX + (grid.X - site.MinX) / scale, originY + (grid.Y - site.MinY) / scale, pen); + if (surface.Glazing is { Count: > 0 } glazing) + { + // The hidden-line pane covers the view through the opening. Keep the roof and its + // pattern above panes that project beyond the opening's perimeter. + page.BeginPolygonClip(projected.Skip(1)); + page.FillPolygonUnion(glazing.Select(OnPage), 1); + page.EndClip(); + } + if (surface.RailId == 0) + foreach (var ring in projected) page.DrawPolyline(ring, pen, true); + if (surface.Visible != null) page.EndClip(); + } + foreach (var rail in graphics.Surfaces.Where(surface => surface.RailId > 0).GroupBy(surface => surface.RailId)) + { + var visible = rail.SelectMany(surface => surface.Visible ?? surface.Rings).ToList(); + if (visible.Count == 0) continue; + bool clipped = rail.Any(surface => surface.Visible != null); + if (clipped) page.BeginPolygonClip(visible.Select(OnPage), evenOdd: false); + var outlines = ElevationPrinter.OutlineJoinedRings(rail.SelectMany(surface => surface.Rings).ToList(), + (int)BuiltInCategory.OST_RailingTopRail); + foreach (var edge in outlines) + { + var (x1, y1) = PagePoint((edge.X1, edge.Y1)); + var (x2, y2) = PagePoint((edge.X2, edge.Y2)); + page.DrawLine(x1, y1, x2, y2, railPen); + } + if (clipped) page.EndClip(); + } + + List<(double X, double Y)> OnPage(List<(double X, double Y)> ring) => ring.Select(PagePoint).ToList(); + (double X, double Y) PagePoint((double X, double Y) point) => + (originX + (point.X - site.MinX) / scale, originY + (point.Y - site.MinY) / scale); + } +} diff --git a/src/RvtIO/Print/SitePrinter.Shadows.cs b/src/RvtIO/Print/SitePrinter.Shadows.cs new file mode 100644 index 00000000..3cf279a5 --- /dev/null +++ b/src/RvtIO/Print/SitePrinter.Shadows.cs @@ -0,0 +1,164 @@ +using RvtIO.BuiltIns; +using RvtIO.Geometry.Meshing; +using RvtIO.Model; + +namespace RvtIO.Print; + +public static partial class SitePrinter +{ + private static (List> Rings, double Gray) CollectShadows( + RvtDocument document, int viewId, ViewCropFrame? basis, double cut, IReadOnlySet? hidden, + IReadOnlySet equipmentCasters, IReadOnlyDictionary> addedCasters, + IReadOnlyList opaquePanes, IReadOnlySet surfaceFaces, IReadOnlySet clippedFaces, + out Dictionary>> surfaceShadows, + out Dictionary>> visibility) + { + surfaceShadows = []; + visibility = []; + double ground = double.NegativeInfinity, rightShift = 0, upShift = 0, gray = 1; + if (document.RawData.ViewGroundShadows?.GetValueOrDefault(viewId) is { GroundLevel: > 0, Intensity: > 0 } sun + && document.GetElement(sun.GroundLevel)?.LookupParameter(BuiltInParameter.LEVEL_ELEV)?.Value + is double level && double.IsFinite(level)) + { + double dx = Math.Sin(sun.Azimuth) / Math.Tan(sun.Altitude); + double dy = -Math.Cos(sun.Azimuth) / Math.Tan(sun.Altitude); + if (double.IsFinite(dx) && double.IsFinite(dy)) + (ground, rightShift, upShift, gray) = (level, dx, dy, 1 - sun.Intensity / 100d); + } + bool castShadows = double.IsFinite(ground); + if (!castShadows && clippedFaces.Count == 0) return ([], 1); + double[] right = basis?.Right ?? [1, 0, 0], up = basis?.Up ?? [0, 1, 0]; + double[] down = [0, 0, -1]; + var shadows = new ElevationPrinter.ElevationShadows(right, up, down, rightShift, upShift, gray); + var sourceFaces = new Dictionary, GeoFace>(); + var paneCovers = new List(); + var hiddenCategories = document.RawData.ViewHiddenCategories?.GetValueOrDefault(viewId); + double minX = double.PositiveInfinity, minY = double.PositiveInfinity; + double maxX = double.NegativeInfinity, maxY = double.NegativeInfinity; + + foreach (var element in document.Elements) + { + bool equipment = equipmentCasters.Contains(element.Id); + var added = addedCasters.GetValueOrDefault(element.Id); + if (!equipment && added == null + && element.CategoryId is not ((int)BuiltInCategory.OST_Roofs or (int)BuiltInCategory.OST_Walls + or (int)BuiltInCategory.OST_Floors or (int)BuiltInCategory.OST_Stairs + or (int)BuiltInCategory.OST_Topography or (int)BuiltInCategory.OST_BuildingPad) + || element.IsDiscovered || element.SerializedUnplacedOwnerId is > 0 + || element.NativeIsSymbol == true || element.RootClassIs("FamilySymbol") + || element.CategoryId is int category + && category is ((int)BuiltInCategory.OST_Stairs or (int)BuiltInCategory.OST_Floors) + && hiddenCategories?.Contains(category) == true + || hidden?.Contains(element.Id) == true || element.Geometry is not { Faces.Count: > 0 } geometry) + continue; + foreach (var face in added ?? geometry.Faces) + { + // shortcut: use planar faces wholly below the cut, pending cut-solid reconstruction for shadows. + if (face.CurvedSurface || face.OuterVertices is not { Count: >= 3 } outer + || outer.Any(point => !Valid(point) || point[2] > cut) + || face.InnerLoops is { Count: > 0 } && face.InnerVertices is not { Count: > 0 } + || face.InnerVertices?.Any(ring => ring.Count < 3 || ring.Any(point => !Valid(point))) == true) + continue; + + bool aboveGround = outer.Any(point => point[2] > ground); + if (!aboveGround && clippedFaces.Count == 0) continue; + if (castShadows && aboveGround) + { + shadows.AddCaster(face, outer.Select(Millimetres).ToList()); + foreach (var vertex in outer) + { + var (x, y) = InView(vertex); + double height = vertex[2] - ground; + x -= height * rightShift; + y -= height * upShift; + minX = Math.Min(minX, x); maxX = Math.Max(maxX, x); + minY = Math.Min(minY, y); maxY = Math.Max(maxY, y); + } + } + if (equipment || added != null && element.CategoryId != (int)BuiltInCategory.OST_RailingTopRail + || face.Normal is not { Length: 3 } normal || !(normal[2] > 1e-9)) continue; + var source = surfaceFaces.Contains(face) ? face : null; + bool receivesShadow = castShadows && (aboveGround + || source != null && outer.All(point => point[2] >= ground)); + AddReceiverFacets(outer, face, source, receivesShadow); + } + } + + // The site view paints the transparent pane white. Include that cover when clipping the + // projected model below it, while retaining the existing shadow geometry behind the pane. + foreach (var pane in opaquePanes) + AddReceiverFacets(pane.OuterVertices!, pane, null, receivesShadow: false, paneCover: true); + + var targets = sourceFaces.Where(entry => clippedFaces.Contains(entry.Value)).Select(entry => entry.Key).ToHashSet(); + var clipped = shadows.ClippedReceivers(targets, paneCovers); + foreach (var source in clipped.Keys.Select(facet => sourceFaces[facet]).Distinct()) + visibility.Add(source, []); + foreach (var target in targets) + if (visibility.TryGetValue(sourceFaces[target], out var visible)) + visible.AddRange(clipped.TryGetValue(target, out var parts) ? parts : [target]); + + if (minX < maxX && minY < maxY) + { + var plane = new GeoFace { Normal = [0, 0, 1] }; + AddReceiver([World(minX, minY), World(maxX, minY), World(maxX, maxY), World(minX, maxY)], plane); + } + + var projected = castShadows ? shadows.Project(double.NegativeInfinity) : null; + if (projected != null) + foreach (var (facet, source) in sourceFaces) + { + if (!projected.TryGetValue(facet, out var shadow)) continue; + if (!surfaceShadows.TryGetValue(source, out var rings)) surfaceShadows.Add(source, rings = []); + rings.AddRange(shadow.Rings); + } + return (projected?.Values.SelectMany(shadow => shadow.Rings).ToList() ?? [], gray); + + void AddReceiverFacets(List outer, GeoFace face, GeoFace? source, bool receivesShadow, bool paneCover = false) + { + if (outer.Count == 3 && face.InnerVertices is not { Count: > 0 }) + { + AddReceiver(outer, face, source, receivesShadow, paneCover); + return; + } + var vertices = outer.ToList(); + var loops = new List { Enumerable.Range(0, outer.Count).ToArray() }; + foreach (var inner in face.InnerVertices ?? []) + { + loops.Add(Enumerable.Range(vertices.Count, inner.Count).ToArray()); + vertices.AddRange(inner); + } + var plane = new GeoFace { Normal = face.Normal }; + var outerFlags = new bool[loops.Count]; + outerFlags[0] = true; + foreach (var (a, b, c) in GeTess.TriangulateProfile(vertices.Select(InView).ToArray(), loops, outerFlags)) + AddReceiver([vertices[a], vertices[b], vertices[c]], plane, source, receivesShadow, paneCover); + } + + void AddReceiver(List vertices, GeoFace face, GeoFace? source = null, bool receivesShadow = true, + bool paneCover = false) + { + var points = vertices.Select(InView).Select(point => (point.X * FeetToMillimetres, + point.Y * FeetToMillimetres)).ToList(); + if (Math.Abs(PlanPrinter.SignedArea(points)) <= 1e-6) return; + var corners = vertices.Select(Millimetres).ToList(); + if (paneCover) + { + var cover = ElevationPrinter.ElevationShadows.CreateVisibleFacet(right, up, down, points, face, corners); + if (cover != null) paneCovers.Add(cover); + return; + } + shadows.AddVisibleFacet(points, face, corners, receivesShadow: receivesShadow); + if (source != null) sourceFaces.Add(points, source); + } + + (double X, double Y) InView(double[] point) => + (point[0] * right[0] + point[1] * right[1], point[0] * up[0] + point[1] * up[1]); + + double[] World(double x, double y) => [x * right[0] + y * up[0], x * right[1] + y * up[1], ground]; + + static double[] Millimetres(double[] vertex) => + [vertex[0] * FeetToMillimetres, vertex[1] * FeetToMillimetres, vertex[2] * FeetToMillimetres]; + + static bool Valid(double[] vertex) => vertex.Length == 3 && vertex.All(double.IsFinite); + } +} diff --git a/src/RvtIO/Print/SitePrinter.Tags.cs b/src/RvtIO/Print/SitePrinter.Tags.cs new file mode 100644 index 00000000..0c0946a0 --- /dev/null +++ b/src/RvtIO/Print/SitePrinter.Tags.cs @@ -0,0 +1,83 @@ +using RvtIO.BuiltIns; +using RvtIO.Model; +using RvtIO.Pdf; + +namespace RvtIO.Print; + +public static partial class SitePrinter +{ + internal sealed record PlantingAnnotation(string Mark, RevitFileInfo.PlanOpeningTagStyle Style, + (double X, double Y) Head, (double X, double Y) Elbow, (double X, double Y) End); + + internal static IReadOnlyList CollectTags(RvtDocument document, int viewId, ViewCropFrame? basis) + { + if (document.RawData.SitePlantingTags?.GetValueOrDefault(viewId) is not { } tags + || document.RawData.PlanOpeningTagStyles is not { } styles) return []; + var result = new List(); + foreach (var tag in tags) + { + if (!styles.TryGetValue(tag.SymbolId, out var style) || style.Lines.Count == 0 + || !IsLocalPlantingTag(document.GetElement(tag.ElementId), style.Label.ParamId, out string mark)) continue; + result.Add(new(mark, style, ToView(tag.X, tag.Y), ToView(tag.Elbow.X, tag.Elbow.Y), + ToView(tag.End.X, tag.End.Y))); + } + return result; + + (double X, double Y) ToView(double x, double y) => basis == null + ? (x * FeetToMillimetres, y * FeetToMillimetres) + : ((x * basis.Right[0] + y * basis.Right[1]) * FeetToMillimetres, + (x * basis.Up[0] + y * basis.Up[1]) * FeetToMillimetres); + + bool IsLocalPlantingTag(Element? plant, int param, out string mark) + { + mark = ""; + if (plant == null || param != (int)BuiltInParameter.ALL_MODEL_TYPE_MARK) return false; + mark = PlantingTypeOf(document, plant).Mark; + return mark.Length > 0; + } + } + + internal static void DrawOutlineAnnotations(PdfPage page, RvtDocument document, + IReadOnlyList markers, ViewCropFrame? basis, SiteContent site, + double scale, double originX, double originY) + { + foreach (var (transform, lines, arcs) in markers) + { + if (CircularAnnotations.ProjectTransform(transform, basis?.Right, basis?.Up) is not { } marker) continue; + double x = originX + (marker.X - site.MinX) / scale; + double y = originY + (marker.Y - site.MinY) / scale; + double unit = FeetToMillimetres * marker.Factor / scale; + foreach (var line in lines) + page.DrawLine(x + line.X0 * unit, y + line.Y0 * unit, x + line.X1 * unit, y + line.Y1 * unit, + Width(line.StyleId)); + foreach (var arc in arcs) + page.DrawArc(x + arc.X * unit, y + arc.Y * unit, arc.Radius * unit, arc.Start, arc.End, + Width(arc.StyleId)); + } + + double Width(int id) => document.RawData.GraphicsStylePens?.GetValueOrDefault(id) is { } style + && PenWidths.TryAnnotationWidth(document, style.PenNumber, out double width) ? width : 0.1; + } + + internal static void DrawTags(PdfPage page, RvtDocument document, IReadOnlyList tags, + SiteContent site, double scale, double originX, double originY) + { + if (page.Owner.Font == null || tags.Count == 0) return; + double pen = PlanPrinter.PlanAnnotationWidth(document, (int)BuiltInCategory.OST_PlantingTags, 0.1); + foreach (var (mark, style, head, elbow, end) in tags) + { + var (hx, hy) = PagePoint(head); + var (ex, ey) = PagePoint(elbow); + var (tx, ty) = PagePoint(end); + double edge = ex < hx ? style.Lines.Min(line => Math.Min(line.X0, line.X1)) + : style.Lines.Max(line => Math.Max(line.X0, line.X1)); + double start = hx + edge * FeetToMillimetres; + page.DrawLine(start, hy, ex, ey, pen); + page.DrawLine(ex, ey, tx, ty, pen); + PlanPrinter.DrawTagSymbol(page, style, mark, hx, hy, pen); + } + + (double X, double Y) PagePoint((double X, double Y) point) => + (originX + (point.X - site.MinX) / scale, originY + (point.Y - site.MinY) / scale); + } +} diff --git a/src/RvtIO/Print/SitePrinter.cs b/src/RvtIO/Print/SitePrinter.cs index eaf0a49f..40826efb 100644 --- a/src/RvtIO/Print/SitePrinter.cs +++ b/src/RvtIO/Print/SitePrinter.cs @@ -5,22 +5,23 @@ namespace RvtIO.Print; /// -/// Prints a site plan: the topography of the model (the edges of its faces seen from above) and the planting of the -/// site (a circle with four spokes at each plant). A site view is not the plan of a level, so it is drawn from the site -/// entities rather than from walls and rooms. +/// Prints the site terrain, property boundaries and symbols for placed planting and entourage. /// -public static class SitePrinter +public static partial class SitePrinter { private const double FeetToMillimetres = 304.8; - /// The projected site: the topography outlines, the plants and the extents they span, in millimetres. - /// Each plant carries its schedule key: the type mark (T1, T2, ...) for its tag, empty when unknown. + internal sealed record SitePlant(double X, double Y, double Radius, string Type, string Mark, bool Rpc = false); + + /// The projected site: the topography outlines, the plants and the extents they span, in millimetres. internal sealed record SiteContent( List> Topography, List<(double X1, double Y1, double X2, double Y2, double Z)> Contours, - List<(double X, double Y, double Radius, string Type, string Mark)> Plants, + List Plants, List> Entourage, - double MinX, double MinY, double MaxX, double MaxY); + double MinX, double MinY, double MaxX, double MaxY, + IReadOnlyList>? PropertyLines = null, + IReadOnlySet? NativePrimaryLevels = null); /// The same site seen in a rotated view: every point is projected on the view's own axes /// ( across the sheet, up the sheet), so a site plan whose crop @@ -41,10 +42,12 @@ internal static SiteContent InViewBasis(SiteContent site, double[] right, double var plants = site.Plants.Select(plant => { var centre = Map(plant.X, plant.Y); - return (centre.X, centre.Y, plant.Radius, plant.Type, plant.Mark); + return plant with { X = centre.X, Y = centre.Y }; }).ToList(); var entourage = site.Entourage .Select(polygon => polygon.Select(point => Map(point.X, point.Y)).ToList()).ToList(); + var propertyLines = site.PropertyLines? + .Select(line => line.Select(point => Map(point.X, point.Y)).ToList()).ToList(); double minX = double.MaxValue, minY = double.MaxValue, maxX = double.MinValue, maxY = double.MinValue; void Grow(double x, double y) { @@ -57,14 +60,23 @@ void Grow(double x, double y) foreach (var plant in plants) Grow(plant.X, plant.Y); foreach (var polygon in entourage) foreach (var point in polygon) Grow(point.X, point.Y); + if (propertyLines != null) + foreach (var line in propertyLines) + foreach (var point in line) Grow(point.X, point.Y); if (minX > maxX) return site; - return new SiteContent(topography, contours, plants, entourage, minX, minY, maxX, maxY); + return new SiteContent(topography, contours, plants, entourage, minX, minY, maxX, maxY, + propertyLines, site.NativePrimaryLevels); } - /// Projects the topography and the planting of the document on the plan. Null when the model has neither. + /// Projects the topography, planting and property boundaries of the document on the plan. /// - internal static SiteContent? Collect(RvtDocument document) + internal static SiteContent? Collect(RvtDocument document, int? viewId = null) { + var hidden = viewId is int view ? document.RawData.ViewHiddenElements?.GetValueOrDefault(view) : null; + var hiddenCategories = viewId is int categoryView + ? document.RawData.ViewHiddenCategories?.GetValueOrDefault(categoryView) : null; + var contours = new List<(double X1, double Y1, double X2, double Y2, double Z)>(); + HashSet? nativePrimaryLevels = null; var topography = new List>(); var topography3 = new List>(); double minX = double.MaxValue, minY = double.MaxValue, maxX = double.MinValue, maxY = double.MinValue; @@ -76,7 +88,30 @@ void Grow(double x, double y) foreach (var element in document.Elements) { - if (element.CategoryId != (int)BuiltInCategory.OST_Topography) continue; + if (element.CategoryId != (int)BuiltInCategory.OST_Topography || !IsPlaced(element)) continue; + bool hasContours = document.RawData.SiteContours?.TryGetValue(element.Id, out _) == true; + if (hasContours) + { + nativePrimaryLevels ??= []; + foreach (var contour in document.RawData.SiteContours![element.Id]) + { + double level = contour.Elevation * FeetToMillimetres; + if (contour.Primary) nativePrimaryLevels.Add(level); + foreach (var line in contour.Lines) + { + for (int i = 1; i < line.Count; i++) + { + var a = line[i - 1]; + var b = line[i]; + if (a == b) continue; + contours.Add((a.X * FeetToMillimetres, a.Y * FeetToMillimetres, + b.X * FeetToMillimetres, b.Y * FeetToMillimetres, level)); + Grow(a.X * FeetToMillimetres, a.Y * FeetToMillimetres); + Grow(b.X * FeetToMillimetres, b.Y * FeetToMillimetres); + } + } + } + } if (element.Geometry is not { Faces.Count: > 0 } geometry) continue; foreach (var face in geometry.Faces) { @@ -92,32 +127,32 @@ void Grow(double x, double y) Grow(x, y); } topography.Add(polygon); - topography3.Add(corners); + if (!hasContours) topography3.Add(corners); if (topography.Count >= 20000) break; } } - var plants = new List<(double X, double Y, double Radius, string Type, string Mark)>(); + var plants = new List(); foreach (var element in document.Elements) { - if (element.CategoryId != (int)BuiltInCategory.OST_Planting) continue; + if (element.CategoryId != (int)BuiltInCategory.OST_Planting || !IsPlaced(element)) continue; double[]? box = element.BoundingBox ?? element.Geometry?.BoundingBox; if (box is not { Length: 6 } || box[3] <= box[0] || box[4] <= box[1]) continue; - double x = (box[0] + box[3]) / 2 * FeetToMillimetres; - double y = (box[1] + box[4]) / 2 * FeetToMillimetres; - double radius = Math.Min(box[3] - box[0], box[4] - box[1]) / 2 * FeetToMillimetres; + double x = (element.InstanceOriginXY?.X ?? (box[0] + box[3]) / 2) * FeetToMillimetres; + double y = (element.InstanceOriginXY?.Y ?? (box[1] + box[4]) / 2) * FeetToMillimetres; + double? rpcRadius = RpcPlanRadius(document, element); + double radius = rpcRadius ?? Math.Min(box[3] - box[0], box[4] - box[1]) / 2 * FeetToMillimetres; if (radius <= 0) continue; - plants.Add((x, y, radius, element.Name ?? "", PlantingTypeOf(document, element).Mark)); + plants.Add(new(x, y, radius, element.Name ?? "", PlantingTypeOf(document, element).Mark, rpcRadius.HasValue)); Grow(x - radius, y - radius); Grow(x + radius, y + radius); } - // The cars and the people of the site (the entourage) print as their outlines seen from above, as the - // reference site plan shows a car on the drive. + // Visible entourage uses the placed instance bounds for its plan outline. var entourage = new List>(); foreach (var element in document.Elements) { - if (element.CategoryId != (int)BuiltInCategory.OST_Entourage) continue; + if (element.CategoryId != (int)BuiltInCategory.OST_Entourage || !IsPlaced(element)) continue; double[]? box = element.BoundingBox ?? element.Geometry?.BoundingBox; if (box is not { Length: 6 }) continue; double x0 = box[0] * FeetToMillimetres, y0 = box[1] * FeetToMillimetres; @@ -145,7 +180,6 @@ void Grow(double x, double y) // The contours of the terrain: the mesh is sliced at every half metre (a metre on a high site) and each slice // is drawn as the lines a site plan prints, the way the reference shows the fall of the ground. - var contours = new List<(double X1, double Y1, double X2, double Y2, double Z)>(); if (topography3.Count > 0) { double zMin = topography3.Min(corners => corners.Min(corner => corner[2])); @@ -172,8 +206,21 @@ void Grow(double x, double y) } } - if (topography.Count == 0 && plants.Count == 0) return null; - return new SiteContent(topography, contours, plants, entourage, minX, minY, maxX, maxY); + var propertyLines = new List>(); + foreach (var element in document.Elements) + { + if (element.SitePropertyCurve is not { Count: >= 2 } curve) continue; + var line = curve.Select(p => (X: p.X * FeetToMillimetres, Y: p.Y * FeetToMillimetres)).ToList(); + propertyLines.Add(line); + foreach (var point in line) Grow(point.X, point.Y); + } + if (topography.Count == 0 && contours.Count == 0 && plants.Count == 0 && propertyLines.Count == 0) return null; + return new SiteContent(topography, contours, plants, entourage, minX, minY, maxX, maxY, + propertyLines, nativePrimaryLevels); + + bool IsPlaced(Element element) => !element.IsDiscovered && element.SerializedUnplacedOwnerId is not > 0 + && element.NativeIsSymbol != true && !element.RootClassIs("FamilySymbol") && hidden?.Contains(element.Id) != true + && (element.CategoryId is not int category || hiddenCategories?.Contains(category) != true); } /// The schedule key of a planting instance: the type mark (its ALL_MODEL_TYPE_MARK) and the @@ -191,18 +238,29 @@ internal static (string Mark, string CommonName) PlantingTypeOf(RvtDocument docu } /// Draws the site with (MinX, MinY) at (originX, originY), one model unit per 1/scale. - internal static void DrawContent(PdfPage page, SiteContent content, double scale, double originX, double originY) + internal static void DrawContent(PdfPage page, SiteContent content, double scale, double originX, double originY, + RvtDocument? document = null, bool opaqueGround = false, SiteGraphics? graphics = null, bool drawFallbackTags = true, + bool drawFallbackNorth = true, int? viewId = null, ViewCropFrame? basis = null) { double ToX(double x) => (x - content.MinX) / scale + originX; double ToY(double y) => (y - content.MinY) / scale + originY; - // A light green wash under the site; only the outer edge of the terrain mesh is inked, so the triangulation does - // not cover the plan. + (double Width, PdfColor Color)? ProjectionPen(BuiltInCategory category) + { + if (document?.RawData.PenWidthTable is not { } table + || !PenWidths.TryGetStyle(document, (int)category, false, out int pen, out int rgb) + || rgb < 0 || rgb > 0xFFFFFF + || !PenWidths.TryPenWidth(table, pen, (int)Math.Round(scale), out double width)) return null; + return (width, new PdfColor((rgb & 255) / 255d, ((rgb >> 8) & 255) / 255d, (rgb >> 16) / 255d)); + } + + // Only the outer edge of the terrain mesh is inked, so the triangulation does not cover the plan. + PdfColor ground = opaqueGround ? new PdfColor(1, 1, 1) : new PdfColor(0.92, 0.95, 0.9); var edges = new Dictionary(StringComparer.Ordinal); var edgeLines = new Dictionary(StringComparer.Ordinal); foreach (var polygon in content.Topography) { var points = polygon.Select(point => (ToX(point.X), ToY(point.Y))).ToList(); - page.DrawPolyline(points, 0, true, new PdfColor(0.92, 0.95, 0.9)); + page.DrawPolyline(points, 0, true, ground); for (int i = 0; i < points.Count; i++) { var a = points[i]; @@ -221,17 +279,68 @@ internal static void DrawContent(PdfPage page, SiteContent content, double scale if (count != 1 || !edgeLines.TryGetValue(key, out var line)) continue; page.DrawLine(line.A.Item1, line.A.Item2, line.B.Item1, line.B.Item2, 0.15, 0.45); } - // The contours of the terrain go over the wash, under the planting; every fifth one is an index contour drawn - // heavier, the way a site plan reads the fall of the ground. - var contourLevels = content.Contours.Select(contour => contour.Z).Distinct().OrderBy(level => level).ToList(); + if (graphics is { GroundShadows.Count: > 0 }) + page.FillPolygonUnion(graphics.GroundShadows.Select(ring => ring.Select(p => (ToX(p.X), ToY(p.Y))).ToList()), + graphics.ShadowGray); + + var primary = content.NativePrimaryLevels == null ? null : ProjectionPen(BuiltInCategory.OST_TopographyContours); + var secondary = content.NativePrimaryLevels == null ? null : ProjectionPen(BuiltInCategory.OST_SecondaryTopographyContours); + var contourLevels = content.NativePrimaryLevels == null + ? content.Contours.Select(contour => contour.Z).Distinct().OrderBy(level => level).ToList() : null; + var contourLabels = ContourLabels(page, document, viewId, basis, ToX, ToY); foreach (var (x1, y1, x2, y2, level) in content.Contours) { - bool index = contourLevels.IndexOf(level) % 5 == 0; - page.DrawLine(ToX(x1), ToY(y1), ToX(x2), ToY(y2), index ? 0.16 : 0.07, index ? 0.5 : 0.62); + bool index = content.NativePrimaryLevels?.Contains(level) ?? contourLevels!.IndexOf(level) % 5 == 0; + var pen = index ? primary : secondary; + double ax = ToX(x1), ay = ToY(y1), bx = ToX(x2), by = ToY(y2); + foreach (var (start, end) in ContourSpans(ax, ay, bx, by, level, contourLabels)) + { + double sx = ax + start * (bx - ax), sy = ay + start * (by - ay); + double ex = ax + end * (bx - ax), ey = ay + end * (by - ay); + if (pen is { } style) page.DrawLine(sx, sy, ex, ey, style.Width, style.Color); + else page.DrawLine(sx, sy, ex, ey, index ? 0.16 : 0.07, index ? 0.5 : 0.62); + } + } + if (graphics is { Equipment: not null } && document != null) + DrawEquipment(page, document, graphics, basis, scale, ToX, ToY); + foreach (var label in contourLabels) + page.DrawTextRotated(label.Text, label.X + label.Sine * label.Baseline, + label.Y - label.Cosine * label.Baseline, label.Height, label.Angle * 180 / Math.PI, + PdfTextAlignment.Center); + if (content.PropertyLines is { Count: > 0 } properties) + { + double pen = 0.18; + int category = (int)BuiltInCategory.OST_SiteProperty; + if (document != null && PenWidths.TryGetWidth(document, category, false, (int)Math.Round(scale), out double width)) + pen = width; + double[]? dashes = document != null && LinePatterns.TryGetDashes(document, category, out double[] pattern) + ? pattern : null; + foreach (var line in properties) + { + var points = line.Select(p => (X: ToX(p.X), Y: ToY(p.Y))).ToList(); + if (dashes == null) + { + page.DrawPolyline(points, pen); + continue; + } + double length = 0; + for (int i = 1; i < points.Count; i++) + { + double dx = points[i].X - points[i - 1].X, dy = points[i].Y - points[i - 1].Y; + length += Math.Sqrt(dx * dx + dy * dy); + } + page.DrawRoundDashedPolyline(points, pen, LinePatterns.FitEndpointDashes(length * (72 / 25.4), dashes)); + } } - foreach (var (x, y, radius, _, _) in content.Plants) + var plantingPen = ProjectionPen(BuiltInCategory.OST_Planting) ?? (0.1, new PdfColor(0, 0, 0)); + foreach (var plant in content.Plants) { - double pageX = ToX(x), pageY = ToY(y), r = radius / scale; + double pageX = ToX(plant.X), pageY = ToY(plant.Y), r = plant.Radius / scale; + if (plant.Rpc) + { + DrawRpcPlant(page, pageX, pageY, r, basis, plantingPen.Item1, plantingPen.Item2); + continue; + } var circle = new List<(double X, double Y)>(24); for (int i = 0; i < 24; i++) { @@ -251,7 +360,7 @@ internal static void DrawContent(PdfPage page, SiteContent content, double scale var types = content.Plants.Where(plant => plant.Type.Length > 0).Select(plant => plant.Type) .Distinct().OrderBy(name => name, StringComparer.OrdinalIgnoreCase).ToList(); var tagged = new Dictionary(StringComparer.OrdinalIgnoreCase); - if (page.Owner.Font != null) + if (drawFallbackTags && page.Owner.Font != null) { foreach (var plant in content.Plants) { @@ -269,6 +378,7 @@ internal static void DrawContent(PdfPage page, SiteContent content, double scale } } + if (!drawFallbackNorth) return; // The north arrow at the lower right of the site. double boxRight = (content.MaxX - content.MinX) / scale + originX; double boxBottom = originY; @@ -285,4 +395,4 @@ internal static void DrawContent(PdfPage page, SiteContent content, double scale page.DrawLine(northX, northY, northX, northY + 5, 0.18); page.DrawText("N", northX, northY + 6, 2.6, PdfTextAlignment.Center); } -} \ No newline at end of file +} diff --git a/src/RvtIO/Print/SolarStudyOverlay.cs b/src/RvtIO/Print/SolarStudyOverlay.cs new file mode 100644 index 00000000..737f39dc --- /dev/null +++ b/src/RvtIO/Print/SolarStudyOverlay.cs @@ -0,0 +1,363 @@ +using System.Globalization; +using System.Numerics; +using RvtIO.BuiltIns; +using RvtIO.Model; +using RvtIO.Pdf; + +namespace RvtIO.Print; + +internal sealed class SolarStudyOverlay +{ + private const double CompassOutside = 1.05; + private const int DeclinationSteps = 2048; + private const double Radians = Math.PI / 180; + private readonly Vector3 _right, _up, _look; + private readonly double _latitude, _longitude, _zone; + private readonly (double Start, double End)[][]? _hours; + private readonly double _minDeclination, _maxDeclination; + private readonly DateTime _start; + private readonly DateTime? _active; + private readonly Vector3? _sun; + private readonly double _endMinutes; + + internal double X { get; } + internal double Y { get; } + internal double Radius { get; } + internal double GroundElevation { get; } + internal bool AnnotationVisible { get; } + internal Vector3? ModelSunDirection { get; } + + private SolarStudyOverlay(double x, double y, double radius, double groundElevation, Vector3 right, Vector3 up, Vector3 look, + ViewSolarStudy study, RevitFileInfo raw, double[] location, bool annotationVisible) + { + X = x; + Y = y; + Radius = radius; + GroundElevation = groundElevation; + _right = right; + _up = up; + _look = look; + AnnotationVisible = annotationVisible; + if (raw.SiteLatitudeRadians is not double latitude || raw.SiteLongitudeRadians is not double longitude + || raw.SiteTimeZoneHours is not double zone + || !TryDecodeDate(study.Start, out _start) || !TryDecodeDate(study.End, out var end) + || _start.Date >= end.Date || _start.TimeOfDay >= end.TimeOfDay) + return; + (_latitude, _longitude, _zone) = (latitude, longitude, zone); + if (AnnotationVisible) + (_hours, _minDeclination, _maxDeclination) = StudyHours(_start, end); + _endMinutes = end.TimeOfDay.TotalMinutes; + // shortcut: hourly frames, until the other stored interval ordinals are verified. + if (study.Interval != 3 || study.ActiveFrame is not (>= 1 and <= int.MaxValue) + || study.ActiveFrame != Math.Truncate(study.ActiveFrame)) return; + int samplesPerDay = 1 + (int)(end.TimeOfDay - _start.TimeOfDay).TotalHours; + int index = (int)study.ActiveFrame - 1; + int day = index / samplesPerDay; + if (day <= (end.Date - _start.Date).Days) + { + var active = _start.AddDays(day).AddHours(index % samplesPerDay); + _active = active; + var (declination, equation) = Ephemeris(active, active.TimeOfDay.TotalHours); + var sun = SunVector(declination, HourAngle(active.TimeOfDay.TotalMinutes, equation)); + _sun = sun; + ModelSunDirection = ToModelDirection(sun, location); + } + } + + internal static SolarStudyOverlay? Create(RvtDocument document, Element view, + ViewCropFrame camera, double millimetresPerFoot, Func project) + { + var raw = document.RawData; + if (view.SolarStudy is not { } study || !raw.SharedTransformIsActiveLocation + || raw.SharedTransform is not { Length: 12 } location + || document.GetElement(study.GroundLevelId)?.LookupParameter(BuiltInParameter.LEVEL_ELEV)?.Value + is not double elevation || !double.IsFinite(elevation)) return null; + double[] box = study.Outline; + double w = (box[3] - box[0]) / 2, d = (box[4] - box[1]) / 2; + double h = Math.Max(Math.Abs(box[5] - elevation), Math.Abs(box[2] - elevation)); + double radius = Math.Sqrt(w * w + d * d + h * h) * study.SizePercent / 100 * millimetresPerFoot; + if (!(radius > 0) || !double.IsFinite(radius)) return null; + var center = project([box[0] + w, box[1] + d, elevation]); + Vector3 ToShared(double[] v) => new( + (float)(v[0] * location[0] + v[1] * location[3]), + (float)(v[0] * location[1] + v[1] * location[4]), (float)v[2]); + bool visible = study.AnnotationId > 0 + && raw.ViewHiddenElements?.GetValueOrDefault(view.Id)?.Contains(study.AnnotationId) != true; + if (!visible && study.ShadowIntensity <= 0) return null; + return new(center.X, center.Y, radius, elevation, ToShared(camera.Right), ToShared(camera.Up), ToShared(camera.Look), + study, raw, location, visible); + } + + internal static Vector3? StillSunDirection(RevitFileInfo raw, int viewId) + { + if (raw.ViewStillSunDates?.TryGetValue(viewId, out uint packedDate) != true + || !TryDecodeDate(packedDate, out var date) || !raw.SharedTransformIsActiveLocation + || raw.SharedTransform is not { Length: 12 } location + || raw.SiteLatitudeRadians is not double latitude || raw.SiteLongitudeRadians is not double longitude + || raw.SiteTimeZoneHours is not double zone) return null; + var (declination, equation) = Ephemeris(date, date.TimeOfDay.TotalHours); + double angle = HourAngle(date.TimeOfDay.TotalMinutes, equation, longitude, zone); + var sun = SunVector(declination, angle, latitude); + return sun.Z > 0 ? ToModelDirection(sun, location) : null; + } + + private static Vector3 ToModelDirection(Vector3 sun, double[] location) => + new((float)(sun.X * location[0] + sun.Y * location[1]), + (float)(sun.X * location[3] + sun.Y * location[4]), sun.Z); + + internal static bool TryDecodeDate(uint value, out DateTime date) + { + date = default; + int year = (int)(value >> 20), month = (int)(value >> 16 & 15), day = (int)(value >> 11 & 31); + int hour = (int)(value >> 6 & 31), minute = (int)(value & 63); + if (year < 1 || month is < 1 or > 12 || day < 1 || day > DateTime.DaysInMonth(year, month) + || hour > 23 || minute > 59) return false; + date = new(year, month, day, hour, minute, 0); + return true; + } + + // NOAA's general solar position equations use local standard time and radian angles. + private static (double Declination, double Equation) Ephemeris(DateTime date, double hour) + { + double g = Math.Tau * (date.DayOfYear - 1 + (hour - 12) / 24) / (DateTime.IsLeapYear(date.Year) ? 366 : 365); + double c = Math.Cos(g), s = Math.Sin(g), c2 = Math.Cos(2 * g), s2 = Math.Sin(2 * g); + return (0.006918 - 0.399912 * c + 0.070257 * s - 0.006758 * c2 + 0.000907 * s2 + - 0.002697 * Math.Cos(3 * g) + 0.00148 * Math.Sin(3 * g), + 229.18 * (0.000075 + 0.001868 * c - 0.032077 * s - 0.014615 * c2 - 0.040849 * s2)); + } + + private double HourAngle(double minutes, double equation) => HourAngle(minutes, equation, _longitude, _zone); + + private static double HourAngle(double minutes, double equation, double longitude, double zone) => + ((minutes + equation - 60 * zone) / 4 - 180) * Radians + longitude; + + private ((double Start, double End)[][] Hours, double Min, double Max) StudyHours(DateTime start, DateTime end) + { + // A full leap cycle covers the equation's two year lengths if the study spans more years. + int days = Math.Min((end.Date - start.Date).Days, 4 * 366 + 365); + var samples = new (double Declination, double Start, double End)[days + 1]; + for (int i = 0; i < samples.Length; ++i) + { + var (declination, equation) = Ephemeris(start.AddDays(i), 12); + samples[i] = (Math.Sin(declination), HourAngle(start.TimeOfDay.TotalMinutes, equation), + HourAngle(end.TimeOfDay.TotalMinutes, equation)); + } + double min = samples.Min(s => s.Declination), max = samples.Max(s => s.Declination); + var hours = new (double Start, double End)[DeclinationSteps + 1][]; + for (int i = 0; i <= DeclinationSteps; ++i) + { + double d = min + (max - min) * i / DeclinationSteps; + var intervals = new List<(double Start, double End)>(); + for (int day = 1; day < samples.Length; ++day) + { + var a = samples[day - 1]; + var b = samples[day]; + if (d < Math.Min(a.Declination, b.Declination) || d > Math.Max(a.Declination, b.Declination)) continue; + double t = a.Declination == b.Declination ? 0 : (d - a.Declination) / (b.Declination - a.Declination); + intervals.Add((a.Start + (b.Start - a.Start) * t, a.End + (b.End - a.End) * t)); + } + hours[i] = intervals.ToArray(); + } + return (hours, min, max); + } + + private (double X, double Y) Project(double east, double north, double up) => + (X + Radius * (east * _right.X + north * _right.Y + up * _right.Z), + Y + Radius * (east * _up.X + north * _up.Y + up * _up.Z)); + + private Vector3 SunVector(double declination, double angle) => SunVector(declination, angle, _latitude); + + private static Vector3 SunVector(double declination, double angle, double latitude) + { + double decSin = Math.Sin(declination), decCos = Math.Cos(declination); + double meridian = decCos * Math.Cos(angle), sinLat = Math.Sin(latitude), cosLat = Math.Cos(latitude); + return new((float)(-decCos * Math.Sin(angle)), (float)(cosLat * decSin - sinLat * meridian), + (float)(sinLat * decSin + cosLat * meridian)); + } + + private (double X, double Y) ProjectSun(double declination, double angle) + { + var vector = SunVector(declination, angle); + return Project(vector.X, vector.Y, vector.Z); + } + + internal void Paint(byte[] rgb, int columns, int rows, double left, double top, double dx, double dy) + { + double determinant = _right.X * _up.Y - _right.Y * _up.X; + double sinLat = Math.Sin(_latitude), cosLat = Math.Cos(_latitude); + double pen = Math.Max(dx, dy) / Radius * 0.6; + for (int row = 0; row < rows; ++row) + { + double v = (top - (row + 0.5) * dy - Y) / Radius; + for (int col = 0; col < columns; ++col) + { + double u = (left + (col + 0.5) * dx - X) / Radius; + int pixel = 3 * (row * columns + col); + bool hasModel = rgb[pixel] != 255 || rgb[pixel + 1] != 255 || rgb[pixel + 2] != 255; + if (Math.Abs(determinant) > 1e-6) + { + double east = (_up.Y * u - _right.Y * v) / determinant; + double north = (_right.X * v - _up.X * u) / determinant; + double r = Math.Sqrt(east * east + north * north); + if (r <= 1.09) + { + double degrees = Math.Atan2(-east, north) / Radians; + double sector = (degrees + 360) % 30; + double tick = Math.Abs(sector - Math.Round(sector / 5) * 5); + bool major = Math.Abs(sector - Math.Round(sector / 15) * 15) * Radians * r < pen; + if (r >= 1 && r <= CompassOutside) + Blend(pixel, sector < 15 ? 138 : 250, sector < 15 ? 138 : 250, + sector < 15 ? 138 : 250, sector < 15 ? 1 : 0.45); + bool circle = Math.Abs(r - 1) < pen || Math.Abs(r - CompassOutside) < pen; + bool onTick = (major && r >= 0.97 && r <= 1.08) + || (sector >= 15 && r >= 1 && r <= CompassOutside && tick * Radians * r < pen); + if (circle || onTick) Blend(pixel, 115, 115, 115, 0.53); + if (rgb[pixel] == 255 && rgb[pixel + 1] == 255 && rgb[pixel + 2] == 255 + && Math.Min(Math.Abs(east), Math.Abs(north)) < pen) + Blend(pixel, 170, 170, 170, 0.4); + } + } + if (_hours == null || u * u + v * v >= 1) continue; + double depth = Math.Sqrt(1 - u * u - v * v); + bool front = InBand(u, v, -depth, sinLat, cosLat, out var direction); + bool back = InBand(u, v, depth, sinLat, cosLat, out _); + if (front) + { + double incidence = _sun is Vector3 sun ? Math.Max(0, Vector3.Dot(sun, direction)) : 1; + // shortcut: diffuse dome shading, until the native study shader is reproduced. + double intensity = hasModel ? Math.Min(1, 0.38 + incidence) : 1; + double green = hasModel ? 175 + 80 * Math.Pow(incidence, 6) : 165 + 70 * direction.Z; + Blend(pixel, (int)(255 * intensity), (int)(green * intensity), 6, 0.74); + } + if (back) Blend(pixel, 135, 105, 62, front ? 0.63 : 1); + } + } + if (_hours != null) + { + PaintDay(_start.Date); + if (_active is { } active) + { + if (active.Date != _start.Date) PaintDay(active.Date); + var sun = _sun!.Value; + var center = Project(sun.X, sun.Y, sun.Z); + double sunRadius = Radius * 0.05; + int fromRow = Math.Max(0, (int)Math.Floor((top - center.Y - sunRadius) / dy)); + int toRow = Math.Min(rows - 1, (int)Math.Ceiling((top - center.Y + sunRadius) / dy)); + int fromCol = Math.Max(0, (int)Math.Floor((center.X - sunRadius - left) / dx)); + int toCol = Math.Min(columns - 1, (int)Math.Ceiling((center.X + sunRadius - left) / dx)); + for (int row = fromRow; row <= toRow; ++row) + for (int col = fromCol; col <= toCol; ++col) + { + double a = (left + (col + 0.5) * dx - center.X) / sunRadius; + double b = (top - (row + 0.5) * dy - center.Y) / sunRadius; + double r2 = a * a + b * b; + if (r2 <= 1) Blend(3 * (row * columns + col), 255, r2 < 0.88 ? 245 : 175, + r2 < 0.88 ? 91 : 11, 0.85); + } + } + } + + void PaintDay(DateTime day) + { + var (dec, _) = Ephemeris(day, 12); + var horizon = Horizon(dec, 0); + if (horizon <= 0) return; + int samples = (int)Math.Clamp(Math.Ceiling(horizon * Radius * 4 / Math.Min(dx, dy)), 10, 30_000); + int previous = -1; + for (int i = 0; i <= samples; ++i) + { + var point = ProjectSun(dec, horizon * (2.0 * i / samples - 1)); + int col = (int)Math.Floor((point.X - left) / dx), row = (int)Math.Floor((top - point.Y) / dy); + if (col < 0 || col >= columns || row < 0 || row >= rows) continue; + int pixel = 3 * (row * columns + col); + if (pixel == previous) continue; + Blend(pixel, 238, 147, 12, 0.85); + previous = pixel; + } + } + + void Blend(int p, int r, int g, int b, double opacity) + { + rgb[p] = (byte)Math.Min(254, Math.Round(rgb[p] + (r - rgb[p]) * opacity)); + rgb[p + 1] = (byte)Math.Min(254, Math.Round(rgb[p + 1] + (g - rgb[p + 1]) * opacity)); + rgb[p + 2] = (byte)Math.Min(254, Math.Round(rgb[p + 2] + (b - rgb[p + 2]) * opacity)); + } + } + + private bool InBand(double u, double v, double depth, double sinLat, double cosLat, out Vector3 direction) + { + direction = default; + double height = u * _right.Z + v * _up.Z + depth * _look.Z; + if (_hours == null || height < 0) return false; + double north = u * _right.Y + v * _up.Y + depth * _look.Y; + double declination = north * cosLat + height * sinLat; + if (declination < _minDeclination || declination > _maxDeclination || !(_maxDeclination > _minDeclination)) + return false; + double east = u * _right.X + v * _up.X + depth * _look.X; + direction = new((float)east, (float)north, (float)height); + double hour = Math.Atan2(-east, height * cosLat - north * sinLat); + int row = (int)Math.Round((declination - _minDeclination) / (_maxDeclination - _minDeclination) * DeclinationSteps); + foreach (var (from, to) in _hours[row]) + if (hour >= from && hour <= to || hour + Math.Tau >= from && hour + Math.Tau <= to + || hour - Math.Tau >= from && hour - Math.Tau <= to) return true; + return false; + } + + private double Horizon(double declination, double altitude) => Math.Acos(Math.Clamp( + (Math.Sin(altitude) - Math.Sin(_latitude) * Math.Sin(declination)) / + (Math.Cos(_latitude) * Math.Cos(declination)), -1, 1)); + + internal void DrawLabels(PdfPage page) + { + bool russian = page.Owner.Font != null && CultureInfo.CurrentUICulture.TwoLetterISOLanguageName == "ru"; + Cardinal(russian ? "С" : "N", 0, 1.15); + Cardinal(russian ? "В" : "E", 1.15, 0); + Cardinal(russian ? "Ю" : "S", 0, -1.15); + Cardinal(russian ? "З" : "W", -1.15, 0); + if (_hours == null) return; + var ink = new PdfColor(0.94, 0.49, 0.01); + var timeDay = _active?.Date ?? _start.Date; + DateLabel(_start.Date, showHorizonTimes: false); + if (timeDay != _start.Date) DateLabel(timeDay, showHorizonTimes: true); + foreach (double minutes in new[] { _start.TimeOfDay.TotalMinutes, _endMinutes }) + { + var (declination, equation) = Ephemeris(timeDay, minutes / 60); + TimeLabel(ProjectSun(declination, HourAngle(minutes, equation)), minutes, ink); + } + if (_active is { } active && _sun is Vector3 sun) + { + var (x, y) = Project(sun.X, sun.Y, sun.Z); + TimeLabel((x - 4, y + Radius * 0.075), active.TimeOfDay.TotalMinutes, new PdfColor(0.85, 0.28, 0.08)); + } + + void Cardinal(string value, double east, double north) + { + var point = Project(east, north, 0); + page.DrawText(value, point.X, point.Y - 1, 4, PdfTextAlignment.Center); + } + + void DateLabel(DateTime day, bool showHorizonTimes) + { + var (dec, equation) = Ephemeris(day, 12); + double horizon = Horizon(dec, 0); + if (!(horizon > 0 && horizon < Math.PI)) return; + var rise = ProjectSun(dec, -horizon); + var set = ProjectSun(dec, horizon); + var culture = russian ? CultureInfo.GetCultureInfo("ru-RU") : CultureInfo.GetCultureInfo("en-US"); + page.DrawStyledText(day.ToString(russian ? "d MMMM" : "MMM d", culture), rise.X + 1, rise.Y - 4, + 3.4, PdfTextAlignment.Left, 0, day == _start.Date, ink); + if (!showHorizonTimes) return; + double edge = Horizon(dec, -0.833 * Radians); + double noon = 720 - equation - 4 * _longitude / Radians + 60 * _zone; + TimeLabel(rise, noon - 4 * edge / Radians, ink); + TimeLabel(set, noon + 4 * edge / Radians, ink); + } + + void TimeLabel((double X, double Y) point, double minutes, PdfColor ink) + { + int time = ((int)Math.Round(minutes) % 1440 + 1440) % 1440; + page.DrawStyledText(FormattableString.Invariant($"{time / 60}:{time % 60:00}"), + point.X + 1, point.Y + 1, 2.6, PdfTextAlignment.Left, 0, false, ink); + } + } +} diff --git a/src/RvtIO/Print/ViewportShadows.cs b/src/RvtIO/Print/ViewportShadows.cs new file mode 100644 index 00000000..e93c0c01 --- /dev/null +++ b/src/RvtIO/Print/ViewportShadows.cs @@ -0,0 +1,143 @@ +using System.Numerics; +using RvtIO.Model; + +namespace RvtIO.Print; + +internal sealed class ViewportShadows +{ + private const int GridSize = 64; + private readonly (double X, double Y, double Z) _direction, _right, _up; + private readonly ViewCropFrame _camera; + private readonly List _casters = []; + private readonly double _shade; + private readonly double? _ground; + private double _left = double.PositiveInfinity, _bottom = double.PositiveInfinity; + private double _rightEdge = double.NegativeInfinity, _top = double.NegativeInfinity; + + private sealed record Caster((double X, double Y)[][] Rings, double Z, double SlopeX, double SlopeY, + double MinX, double MinY, double MaxX, double MaxY); + + internal ViewportShadows(ViewCropFrame camera, Vector3 direction, int intensity, double? groundElevation = null) + { + _camera = camera; + double x = direction.X, y = direction.Y, z = direction.Z; + double horizontal = Math.Sqrt(x * x + y * y), magnitude = Math.Sqrt(horizontal * horizontal + z * z); + _direction = (x / magnitude, y / magnitude, z / magnitude); + _right = horizontal > 0 ? (-y / horizontal, x / horizontal, 0) : (1, 0, 0); + _up = (-_direction.Z * _right.Y, _direction.Z * _right.X, + _direction.X * _right.Y - _direction.Y * _right.X); + _shade = 1 - intensity / 100d; + if (groundElevation is double elevation && double.IsFinite(elevation) && _direction.Z > 0 + && Math.Abs(camera.Look[2]) > 1e-8) + _ground = elevation - camera.OriginZ; + } + + internal (double Left, double Bottom, double Right, double Top)? GroundShadowBounds => + _left < _rightEdge && _bottom < _top ? (_left, _bottom, _rightEdge, _top) : null; + + internal bool FacesLight(double[] normal) => Dot(normal[0], normal[1], normal[2], _direction) > 1e-8; + + internal void AddCaster(IReadOnlyList rings, double[] normal) + { + double facing = Dot(normal[0], normal[1], normal[2], _direction); + if (!(facing > 1e-8)) return; + double[] first = rings[0][0]; + double z = Dot(first[0] - _camera.OriginX, first[1] - _camera.OriginY, first[2] - _camera.OriginZ, _direction); + var projected = rings.Select(ring => ring.Select(point => + { + double x = point[0] - _camera.OriginX, y = point[1] - _camera.OriginY, h = point[2] - _camera.OriginZ; + return (X: Dot(x, y, h, _right), Y: Dot(x, y, h, _up)); + }).ToArray()).ToArray(); + var outer = projected[0]; + if (!double.IsFinite(z) || outer.Any(point => !double.IsFinite(point.X) || !double.IsFinite(point.Y))) return; + _casters.Add(new(projected, z, + -Dot(normal[0], normal[1], normal[2], _right) / facing, + -Dot(normal[0], normal[1], normal[2], _up) / facing, + outer.Min(p => p.X), outer.Min(p => p.Y), outer.Max(p => p.X), outer.Max(p => p.Y))); + if (_ground is not double ground || rings[0].All(point => point[2] <= ground + _camera.OriginZ)) return; + foreach (var point in rings[0]) + { + double t = (point[2] - _camera.OriginZ - ground) / _direction.Z; + double x = point[0] - _camera.OriginX - t * _direction.X; + double y = point[1] - _camera.OriginY - t * _direction.Y; + double u = x * _camera.Right[0] + y * _camera.Right[1] + ground * _camera.Right[2]; + double v = x * _camera.Up[0] + y * _camera.Up[1] + ground * _camera.Up[2]; + _left = Math.Min(_left, u); + _rightEdge = Math.Max(_rightEdge, u); + _bottom = Math.Min(_bottom, v); + _top = Math.Max(_top, v); + } + } + + internal void Apply(byte[] rgb, double[] depth, bool[] facesLight, int columns, int rows, + double left, double top, double stepX, double stepY, double anchorX, double anchorY, double scale) + { + // Approximate the tone of surfaces facing away from the active sun with the saved shadow strength. + for (int pixel = 0; pixel < depth.Length; pixel++) + if (!facesLight[pixel] && double.IsFinite(depth[pixel])) + Shade(pixel); + if (_casters.Count == 0) return; + double minX = _casters.Min(p => p.MinX), maxX = _casters.Max(p => p.MaxX); + double minY = _casters.Min(p => p.MinY), maxY = _casters.Max(p => p.MaxY); + if (!(maxX > minX && maxY > minY)) return; + double cellX = (maxX - minX) / GridSize, cellY = (maxY - minY) / GridSize; + int GridX(double x) => Math.Clamp((int)((x - minX) / cellX), 0, GridSize - 1); + int GridY(double y) => Math.Clamp((int)((y - minY) / cellY), 0, GridSize - 1); + var grid = new List?[GridSize * GridSize]; + foreach (var caster in _casters) + { + int lastX = GridX(caster.MaxX), lastY = GridY(caster.MaxY); + for (int y = GridY(caster.MinY); y <= lastY; y++) + for (int x = GridX(caster.MinX); x <= lastX; x++) + (grid[y * GridSize + x] ??= []).Add(caster); + } + + // The grid indexes polygons. The actual hit still uses their plane and opening loops. + for (int row = 0; row < rows; row++) + { + double y = (top - (row + 0.5) * stepY - anchorY) / scale; + for (int column = 0; column < columns; column++) + { + int pixel = row * columns + column; + double z = depth[pixel]; + bool groundPixel = double.IsPositiveInfinity(z) && _ground.HasValue; + if (!facesLight[pixel] && !groundPixel) continue; + double x = (left + (column + 0.5) * stepX - anchorX) / scale; + if (groundPixel) + { + if (x < _left || x > _rightEdge || y < _bottom || y > _top) continue; + z = (_ground!.Value - x * _camera.Right[2] - y * _camera.Up[2]) / _camera.Look[2]; + } + double wx = x * _camera.Right[0] + y * _camera.Up[0] + z * _camera.Look[0]; + double wy = x * _camera.Right[1] + y * _camera.Up[1] + z * _camera.Look[1]; + double wz = x * _camera.Right[2] + y * _camera.Up[2] + z * _camera.Look[2]; + double lx = Dot(wx, wy, wz, _right), ly = Dot(wx, wy, wz, _up); + if (lx < minX || lx > maxX || ly < minY || ly > maxY + || grid[GridY(ly) * GridSize + GridX(lx)] is not { } candidates) continue; + double receiver = Dot(wx, wy, wz, _direction); + foreach (var caster in candidates) + { + if (lx < caster.MinX || lx > caster.MaxX || ly < caster.MinY || ly > caster.MaxY) continue; + var first = caster.Rings[0][0]; + double blocker = caster.Z + (lx - first.X) * caster.SlopeX + (ly - first.Y) * caster.SlopeY; + if (!(blocker - receiver > 1e-6)) continue; + bool hit = false; + foreach (var polygon in caster.Rings) + if (PlanPrinter.PointInPolygon(lx, ly, polygon)) hit = !hit; + if (!hit) continue; + Shade(pixel); + break; + } + } + } + + void Shade(int pixel) + { + for (int channel = 0; channel < 3; channel++) + rgb[3 * pixel + channel] = (byte)Math.Round(rgb[3 * pixel + channel] * _shade); + } + } + + private static double Dot(double x, double y, double z, (double X, double Y, double Z) axis) => + x * axis.X + y * axis.Y + z * axis.Z; +} diff --git a/src/RvtIO/Print/ViewportSurfaceEdges.cs b/src/RvtIO/Print/ViewportSurfaceEdges.cs new file mode 100644 index 00000000..9c40ba94 --- /dev/null +++ b/src/RvtIO/Print/ViewportSurfaceEdges.cs @@ -0,0 +1,44 @@ +namespace RvtIO.Print; + +internal sealed class ViewportSurfaceEdges +{ + private readonly record struct Segment(double X, double Y, double Dx, double Dy, double LengthSquared, double Length); + + private readonly Segment[] _segments; + private readonly double _width; + internal int Color { get; } + + internal ViewportSurfaceEdges(IEnumerable<((double X, double Y) Start, (double X, double Y) End)> lines, + double width, int color) + { + _segments = lines.Select(line => + { + double dx = line.End.X - line.Start.X, dy = line.End.Y - line.Start.Y; + double squared = dx * dx + dy * dy; + return new Segment(line.Start.X, line.Start.Y, dx, dy, squared, Math.Sqrt(squared)); + }).Where(edge => edge.LengthSquared > 1e-12 && double.IsFinite(edge.LengthSquared)).ToArray(); + _width = width; + Color = color == 0xffffff ? 0xfefefe : color; + } + + internal double Coverage(double x, double y, double stepX, double stepY) + { + double maximum = 0; + double halfWidth = _width / 2; + double margin = halfWidth + (stepX + stepY) / 2; + foreach (var edge in _segments) + { + double dx = x - edge.X, dy = y - edge.Y; + if (dx < Math.Min(0, edge.Dx) - margin || dx > Math.Max(0, edge.Dx) + margin + || dy < Math.Min(0, edge.Dy) - margin || dy > Math.Max(0, edge.Dy) + margin) continue; + double along = Math.Clamp((dx * edge.Dx + dy * edge.Dy) / edge.LengthSquared, 0, 1); + double u = dx - along * edge.Dx, v = dy - along * edge.Dy; + double distance = Math.Sqrt(u * u + v * v); + double footprint = (Math.Abs(edge.Dy) * stepX + Math.Abs(edge.Dx) * stepY) / edge.Length; + double lo = Math.Max(distance - footprint / 2, -halfWidth); + double hi = Math.Min(distance + footprint / 2, halfWidth); + maximum = Math.Max(maximum, (hi - lo) / footprint); + } + return maximum; + } +} diff --git a/src/RvtIO/Print/ViewportSurfacePattern.cs b/src/RvtIO/Print/ViewportSurfacePattern.cs new file mode 100644 index 00000000..ba8e262d --- /dev/null +++ b/src/RvtIO/Print/ViewportSurfacePattern.cs @@ -0,0 +1,74 @@ +using RvtIO.Model; + +namespace RvtIO.Print; + +internal sealed class ViewportSurfacePattern +{ + private readonly (FillHatch.ModelGrid Model, double Cos, double Sin, double Period)[] _grids; + private readonly double _width; + internal int Color { get; } + + private ViewportSurfacePattern(IEnumerable grids, double width, int color) + { + _grids = grids.Select(grid => (grid, Math.Cos(grid.Angle), Math.Sin(grid.Angle), grid.Segments?.Sum() ?? 0)).ToArray(); + _width = width; + Color = color == 0xffffff ? 0xfefefe : color; + } + + internal static ViewportSurfacePattern? Create(RvtDocument document, GeoFace face, + Func project, double offsetX, double offsetY, double width) + { + IReadOnlyList? grids = FillHatch.ProjectModelGrid(document, face, project) is { } solid + ? [solid] : FillHatch.ProjectDashedModelGrids(document, face, project); + if (grids == null) return null; + int color = 0; + if ((face.RenderStyleId ?? face.NestedRenderStyleId) is int materialId + && document.RawData.MaterialPatterns?.TryGetValue(materialId, out var material) == true + && material.SurfacePatternId == face.ModelPattern?.PatternId + && material.SurfacePatternColor is >= 0 and <= 0xffffff and int savedColor) + color = savedColor; + return new(grids.Select(grid => grid with { X = grid.X + offsetX, Y = grid.Y + offsetY }), width, color); + } + + internal double Coverage(double x, double y, double stepX, double stepY) + { + double uncovered = 1; + foreach (var (grid, cos, sin, period) in _grids) + { + double dx = x - grid.X, dy = y - grid.Y; + double perpendicular = -dx * sin + dy * cos; + double footprint = Math.Abs(sin) * stepX + Math.Abs(cos) * stepY; + if (grid.Segments is not { } segments) + { + // Integrate the parallel bands over the pixel's projected width, including subpixel grids. + double width = Math.Min(_width, grid.Spacing); + double InkLength(double p) + { + double bands = Math.Floor(p / grid.Spacing); + return bands * width + Math.Min(p - bands * grid.Spacing, width); + } + double edge = perpendicular + width / 2 - footprint / 2; + uncovered *= 1 - Math.Clamp((InkLength(edge + footprint) - InkLength(edge)) / footprint, 0, 1); + continue; + } + + double row = Math.Round(perpendicular / grid.Spacing); + double distance = perpendicular - row * grid.Spacing; + double lo = Math.Max(distance - footprint / 2, -_width / 2); + double hi = Math.Min(distance + footprint / 2, _width / 2); + if (hi <= lo) continue; + double phase = dx * cos + dy * sin - row * grid.Shift; + phase -= Math.Floor(phase / period) * period; + for (int i = 0; i < segments.Length; i++) + { + if (phase < segments[i]) + { + if (i % 2 == 0) uncovered *= 1 - (hi - lo) / footprint; + break; + } + phase -= segments[i]; + } + } + return 1 - uncovered; + } +} diff --git a/src/RvtIO/RvtFileReader.CircularAnnotations.cs b/src/RvtIO/RvtFileReader.CircularAnnotations.cs new file mode 100644 index 00000000..9a1fb626 --- /dev/null +++ b/src/RvtIO/RvtFileReader.CircularAnnotations.cs @@ -0,0 +1,124 @@ +using System.Text; +using System.Text.RegularExpressions; +using RvtIO.BuiltIns; +using RvtIO.Internal; +using RvtIO.Model; +using RvtIO.Parsing; + +namespace RvtIO; + +public partial class RvtFileReader +{ + private static void ReadCircularAnnotations(RevitFileInfo info, ParsingState state, + IReadOnlyList frames) + { + var placed = info.Elements.Where(e => e.CategoryId == (int)BuiltInCategory.OST_GenericAnnotation + && e.OwnerViewId is > 0 && e.TypeId > 0 && e.RootClassName == "FamilyInstance").ToList(); + var keys = new Dictionary(); + foreach (int id in placed.Select(e => e.TypeId).Distinct()) + { + if (state.TitleBlockTexts.GetValueOrDefault((uint)id) is not { BlockCount: 1, Texts.Count: 1 } + || state.NativeParams.GetValueOrDefault((uint)id)?.Fields.GetValueOrDefault("1829:m_familyId") + is not (> 0 and int family)) continue; + if (state.NativeParams.GetValueOrDefault((uint)family)?.StringFields.GetValueOrDefault("1740:contentDoc") is { } key) + keys.Add(id, key); + } + if (keys.Count == 0) return; + + var members = keys.Values.Distinct().ToDictionary(key => key, + _ => new Dictionary(), StringComparer.Ordinal); + foreach (var frame in frames) + { + if (frame?.FamilyAnnotationItems is not { } items) continue; + foreach (var (key, item) in items) + { + if (item.Owner > int.MaxValue || !members.TryGetValue(key, out var group) + || group.ContainsKey((int)item.Owner)) continue; + var (data, start, _) = frame.Bytes(item); + group.Add((int)item.Owner, (data, start, BitConverter.ToUInt32(data, start + 8), + BitConverter.ToUInt16(data, start + 12))); + } + } + + var styles = new Dictionary(); + foreach (var (symbol, key) in keys) + { + var group = members[key]; + var regions = group.Values.Where(r => r.ClassId == 1860).ToArray(); + var curves = group.Values.Where(r => r.ClassId == 838).ToArray(); + var text = state.TitleBlockTexts[(uint)symbol].Texts![0]; + if (regions.Length != 1 || curves.Length != 1 || (text.Bx, text.By, text.Hx, text.Hy) != (1d, 0d, 0d, 1d)) + continue; + var region = regions[0]; + var fields = TfBlockDeserializer.ExtractParams(region.Data, region.Start, region.Size, region.ClassId)?.Fields; + if (fields == null || fields.GetValueOrDefault("1860:m_bMasking", -1) != 0 + || fields.GetValueOrDefault("1860:m_attrId") is not (> 0 and int attributeId) + || !group.TryGetValue(attributeId, out var attribute) || attribute.ClassId != 1862) continue; + var attr = TfBlockDeserializer.ExtractParams(attribute.Data, attribute.Start, attribute.Size, attribute.ClassId)?.Fields; + if (attr == null || attr.GetValueOrDefault("1862:m_backgroundPatternElemId") != -1 + || info.FillPatterns?.GetValueOrDefault(attr.GetValueOrDefault("1862:m_fillPatternElemId")).Grids is not { Count: 0 } + || attr.GetValueOrDefault("625:m_categoryId") is not (> 0 and int category)) continue; + + var curve = curves[0]; + if (TfBlockDeserializer.ReadFamilyAnnotationCurve(curve.Data, curve.Start, curve.Size) + is not { Arc: { } arc, TypeDependent: false, SketchId: > 0 } outline + || fields.GetValueOrDefault("1861:m_sketchId") != outline.SketchId + || Math.Abs(Math.Abs(arc.End - arc.Start) - 360) > 1e-6 + || info.GraphicsStylePens?.GetValueOrDefault(arc.StyleId) is not { PenNumber: > 0, LinePatternId: -3000010 } border + || border.Color is < 0 or > 0xFFFFFF + || RtfText.Parse(text.Rtf, 0, text.Rtf.Length) is not { Text.Length: > 0, FontSizePoints: > 0 and <= 200 } caption + || !TryCircularAnnotationTextStyle(text.Rtf, out int ink, out bool bold)) continue; + + var fills = new List(); + foreach (var style in group.Values.Where(m => m.ClassId == 2050)) + if (TfBlockDeserializer.TryExtractGraphicsStyleFull(style.Data, style.Start, style.Size, style.ClassId, + out int styleCategory, out _, out int type, out _, out int color, out _, out _) + && styleCategory == category && type == 1 && color is >= 0 and <= 0xFFFFFF) + fills.Add(color); + if (fills is [int fill]) + styles.Add(symbol, new(arc, fill, border.Color, border.PenNumber, + text, caption.Text, caption.FontSizePoints.Value, ink, bold)); + } + + var annotations = new Dictionary>(); + foreach (var element in placed) + { + int view = element.OwnerViewId!.Value; + if (!styles.TryGetValue(element.TypeId, out var style) + || info.ViewHiddenElements?.GetValueOrDefault(view)?.Contains(element.Id) == true + || !state.ComputedFamilySymbols.TryGetValue((uint)element.Id, out var instance) + || instance is not { BlockCount: 1, Symbol: { Transform: { Length: 12 } transform } computed } + || computed.SymbolId != element.TypeId) continue; + if (!annotations.TryGetValue(view, out var list)) annotations.Add(view, list = []); + list.Add(new(transform, style)); + } + info.CircularAnnotations = annotations; + } + + private static bool TryCircularAnnotationTextStyle(byte[] rtf, out int color, out bool bold) + { + color = 0; + bold = false; + // shortcut: a single horizontal run, extend when filled-region families need richer text. + string text = Encoding.ASCII.GetString(rtf); + var run = Regex.Match(text, + @"\\pard(?