From 93686261bb5b152a5d7006c0e6638515d984a931 Mon Sep 17 00:00:00 2001 From: Mahach <79989386+mahach666@users.noreply.github.com> Date: Wed, 2 Dec 2026 00:59:41 +0300 Subject: [PATCH 01/14] Read the types of a family and compute the shape of each one from the file A family file now lists its types with their parameter values, and the scene shows the family at its saved type. Any other type gets a shape computed from the sketches, dimensions, alignments and reference planes of the family itself, with nothing from Revit. A type is computed only when the family is made of extrusions whose profiles are straight sides along the axes of the family, every record that refers to those forms is recognized, something holds the family in place, the relations leave no part of the shape free and do not contradict each other, the profiles stay valid in that type, and what is computed for the saved type is what the file stores. Otherwise the type has a refusal with a code and the record it names, and no approximate shape is shown. The relations are solved in exact fractions. RvtSceneResult.FamilyTypes carries the types, the instances of the computed ones and the refusals of the others. IOScene is unchanged. A face of a surface of revolution bounded only by its meridians that meets the axis at both ends, such as half a sphere, was drawn flat; its triangles now follow the angle between the meridians. This changes the scene of 51 of the 627 sample projects and no other project. --- CHANGELOG.md | 13 + docs/public-api.md | 11 +- docs/scene.md | 49 +- src/RvtIO.Scene/RvtSceneFamilyTypes.cs | 38 ++ src/RvtIO.Scene/RvtSceneReader.cs | 130 +++- src/RvtIO.Scene/RvtSceneResult.cs | 4 + src/RvtIO/Families/FamilyContent.cs | 45 ++ src/RvtIO/Families/FamilyContourChecks.cs | 118 ++++ src/RvtIO/Families/FamilyData.cs | 51 ++ src/RvtIO/Families/FamilyDocument.cs | 43 ++ src/RvtIO/Families/FamilyExtrusionBuilder.cs | 76 +++ src/RvtIO/Families/FamilyModel.cs | 36 ++ src/RvtIO/Families/FamilyModelBuilder.cs | 550 +++++++++++++++++ src/RvtIO/Families/FamilyRecordReader.cs | 300 +++++++++ src/RvtIO/Families/FamilyRecords.cs | 53 ++ src/RvtIO/Families/FamilyRelationReader.cs | 569 ++++++++++++++++++ src/RvtIO/Families/FamilyRules.cs | 52 ++ src/RvtIO/Families/FamilySavedState.cs | 110 ++++ src/RvtIO/Families/FamilySolver.cs | 141 +++++ src/RvtIO/Families/FamilyTypeTable.cs | 37 ++ src/RvtIO/Families/RvtFamilyRefusal.cs | 6 + src/RvtIO/Families/RvtFamilyTypes.cs | 15 + src/RvtIO/Meshes/ElementMeshes.cs | 178 +++++- src/RvtIO/Meshes/MeshSet.cs | 8 + src/RvtIO/Model/Geometry.cs | 4 + src/RvtIO/Model/RevitFileInfo.cs | 4 + src/RvtIO/Parsing/ElementBuilder.cs | 2 + src/RvtIO/Parsing/GRepParserV2.cs | 52 +- src/RvtIO/Parsing/TfClassNames.cs | 3 + src/RvtIO/Parsing/UserParameterCatalog.cs | 7 +- src/RvtIO/RvtDocument.cs | 12 + src/RvtIO/RvtFileReader.cs | 37 +- src/RvtIO/RvtReaderOptions.cs | 3 +- .../StandaloneFamilyParameterWriter.cs | 38 +- .../Families/FamilyContentTests.cs | 106 ++++ .../Families/FamilyDocumentTests.cs | 46 ++ .../Families/FamilyExtrusionTests.cs | 202 +++++++ tests/RvtIO.Tests/Families/FamilyFiles.cs | 17 + .../Families/FamilyModelBuilderTests.cs | 522 ++++++++++++++++ .../Families/FamilyRelationReaderTests.cs | 31 + .../Families/FamilyRevitOracleTests.cs | 145 +++++ .../Families/FamilySavedStateTests.cs | 101 ++++ .../RvtIO.Tests/Families/FamilySceneTests.cs | 450 ++++++++++++++ .../RvtIO.Tests/Families/FamilySolverTests.cs | 146 +++++ .../Families/FamilyTypeTableTests.cs | 120 ++++ tests/RvtIO.Tests/GRepParserV2Tests.cs | 34 ++ .../StandaloneFamilyParameterTests.cs | 25 +- 47 files changed, 4656 insertions(+), 84 deletions(-) create mode 100644 src/RvtIO.Scene/RvtSceneFamilyTypes.cs create mode 100644 src/RvtIO/Families/FamilyContent.cs create mode 100644 src/RvtIO/Families/FamilyContourChecks.cs create mode 100644 src/RvtIO/Families/FamilyData.cs create mode 100644 src/RvtIO/Families/FamilyDocument.cs create mode 100644 src/RvtIO/Families/FamilyExtrusionBuilder.cs create mode 100644 src/RvtIO/Families/FamilyModel.cs create mode 100644 src/RvtIO/Families/FamilyModelBuilder.cs create mode 100644 src/RvtIO/Families/FamilyRecordReader.cs create mode 100644 src/RvtIO/Families/FamilyRecords.cs create mode 100644 src/RvtIO/Families/FamilyRelationReader.cs create mode 100644 src/RvtIO/Families/FamilyRules.cs create mode 100644 src/RvtIO/Families/FamilySavedState.cs create mode 100644 src/RvtIO/Families/FamilySolver.cs create mode 100644 src/RvtIO/Families/FamilyTypeTable.cs create mode 100644 src/RvtIO/Families/RvtFamilyRefusal.cs create mode 100644 src/RvtIO/Families/RvtFamilyTypes.cs create mode 100644 tests/RvtIO.Tests/Families/FamilyContentTests.cs create mode 100644 tests/RvtIO.Tests/Families/FamilyDocumentTests.cs create mode 100644 tests/RvtIO.Tests/Families/FamilyExtrusionTests.cs create mode 100644 tests/RvtIO.Tests/Families/FamilyFiles.cs create mode 100644 tests/RvtIO.Tests/Families/FamilyModelBuilderTests.cs create mode 100644 tests/RvtIO.Tests/Families/FamilyRelationReaderTests.cs create mode 100644 tests/RvtIO.Tests/Families/FamilyRevitOracleTests.cs create mode 100644 tests/RvtIO.Tests/Families/FamilySavedStateTests.cs create mode 100644 tests/RvtIO.Tests/Families/FamilySceneTests.cs create mode 100644 tests/RvtIO.Tests/Families/FamilySolverTests.cs create mode 100644 tests/RvtIO.Tests/Families/FamilyTypeTableTests.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index bd8c44f2..5626fbf2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,17 @@ API between minor releases. ### Added +- `RvtDocument.FamilyOwnerId` names the owner family of a family document (`.rfa`). `ProjectElementsOnly` no longer + leaves out the content of a family document: it was the whole model, so a scene of a family had no geometry. +- The meshes and the scene of a family file show the family at its saved type: solid forms and nested families, without + the hosts, reference planes and voids of the template. A form hidden by the family parameter that drives its visibility + has no geometry. `MeshSet.FamilyGaps` and the `family-incomplete` scene diagnostic say when the shape is incomplete. +- `RvtDocument.FamilyTypes` reads the types of a family file and their parameter values from its records, and + `RvtSceneResult.FamilyTypes` lists them with value texts. The scene still holds the saved type only. +- `ElementMeshes.ComputeFamilyType` computes the shape of a family file in another of its types from the relations of the + family, and `RvtSceneResult.FamilyTypes` gives each computed type its instances. Families of extrusions with straight + sides along the family axes are computed, and only when the computed saved type is what the file stores; any other type + says why it is not computed, and no approximate shape is given. - Report progress while reading a Revit file: `RvtReadProgress` (phase, completed and total units), `RvtReaderOptions.Progress` and `RvtSceneOptions.ReadProgress` (for `RvtSceneReader.Read(path)`). The reader calls `IProgress.Report` synchronously on the reading thread, in phase order; see @@ -161,6 +172,8 @@ API between minor releases. ### Fixed +- A face of a surface of revolution that is bounded only by its meridians and meets the axis at both ends, such as half + a sphere, is no longer drawn flat: its triangles now follow the angle between the meridians. - IFC export with Revit parameters grouped (`--ifc-revit-parameter-groups`) no longer writes several properties of one name in a property set. Entries of one name and value are merged into one property; if only one is left, it keeps the plain name. If values differ, each remaining property gets ` [parameter id]` appended, then ` #2`, ` #3`, … if that diff --git a/docs/public-api.md b/docs/public-api.md index 68fda70f..ca57066b 100644 --- a/docs/public-api.md +++ b/docs/public-api.md @@ -8,10 +8,12 @@ projects through `InternalsVisibleTo`. | Type | Use | |---|---| -| `RvtDocument` | Opens a file (`Open`) or a readable, seekable stream (`OpenStream`), saves a verified lossless copy (`SaveAs`), and gives the elements, project information, file metadata and category lookups. A document opened from a stream has no `SourcePath`: `SaveAs` throws `InvalidOperationException`, and printing cannot read the images it takes from the file (the title block logo and the picture of a rendering view). | +| `RvtDocument` | Opens a file (`Open`) or a readable, seekable stream (`OpenStream`), saves a verified lossless copy (`SaveAs`), and gives the elements, project information, file metadata and category lookups. `FamilyOwnerId` is the id of the family that owns a family document, null for a project. `FamilyTypes` lists the types of such a family as its records store them, null for a family that stores none; `FamilyTypesError` says why a stored table was not read. A document opened from a stream has no `SourcePath`: `SaveAs` throws `InvalidOperationException`, and printing cannot read the images it takes from the file (the title block logo and the picture of a rendering view). | +| `RvtFamilyRefusal` | Why a type of a family has no geometry: a stable `Code` and the `Detail` it names. The `RvtIO.Scene` package lists the types of a scene with their value texts (`RvtSceneResult.FamilyTypes`, see [the scene mapping](scene.md#families)). | +| `RvtFamilyTypes`, `RvtFamilyType` | The types of the family of a family document: `CurrentIndex` is the type the file was saved at, and each type has its stored name (blank for the type Revit keeps for a family without named types) and the parameter values it stores, in Revit's internal units. A parameter of the family carries its name, the key of its definition element, its storage type and, for a number, its spec and display unit. A built-in parameter has a value only when its kind is established (the family width and height and the built-in fields the writer edits); any other is listed without one. A definition that is not read exactly keeps only its id. | | `RvtFileReader` | Lower level read that returns the `RevitFileInfo` behind a document (`Read`, `ReadStream`), or reads only container metadata without opening `Partitions/*` or decoding geometry (`ReadMetadata`, `ReadMetadataStream`). `Read` and `ReadMetadata` take a path and `ReadStream` / `ReadMetadataStream` read from the beginning of a readable, seekable stream, whatever its position. The stream is only read: it is never written to, shortened or closed, also when it is writable. A failure of the stream itself is thrown as the stream threw it. | | `RvtFileMetadataSummary`, `RvtMetadataOptions`, `RvtDocumentKind` | Lightweight container metadata summary returned by `ReadMetadata` / `ReadMetadataStream`: Revit version, build, file/template/backup kind (`.rvt`, `.rfa`, `.rte`, `.rft`), worksharing and cloud state, available save fields, aligned `FileMetadata` / `ProjectInfo` / `TransmissionData`, and optional personal-data redaction (`RedactPersonalData` / `Redact`). | -| `RvtReaderOptions` | Options of a read, including `DiagnosticOutput`, `Progress` (see below), `ResolveCurrentCopies` (keeps only the current copy of an element that several partition streams hold; default true, set it to false to decode every copy), `ReleasePartitions` (drops the decompressed partition streams before the model is built, for a caller that keeps only the result; the model is the same and the read needs less memory; a file read by its own class schema keeps its streams unless `R22Layout` rewrote them and `PreserveWideLayout` is off, and of a rewritten file the streams of the file itself go once its element records are read; the decoded geometry blocks and per-element tables of the reader go as soon as the elements are built; where `ProjectElementsOnly` leaves records unbuilt, what the reader holds for them goes as well), `ProjectElementsOnly` (builds the elements of the element table that are no content of a loaded family's document, the definitions that exist as a geometry block alone, and of the rest only what a built element refers to, and decodes no geometry for what is not built; the rest is the content of the loaded families' documents, which a file of Revit 2022 holds as records outside the table and as elements of the table whose record names their family, most of the elements and of the memory of a large read; a family listing its own content is no reference to it, the content of a family modelled in place is built as before, and an element of the table that is not built stays as an element without category or geometry; a value a rule derives from all the elements is then derived from the built ones; applies when the element table was read exactly; default false, `RvtSceneReader.Read(path)` and `ReadStream` set it), `DetailLevelQuantities` (the measures of doors, windows and structural columns at the Coarse and Medium detail levels, which only the IFC export reads; default true, a scene read turns it off and then also drops the decoded geometry blocks before the finalization passes), `PlacedFacesOnDemand` (an element whose geometry is exactly its symbols placed, an instance of a family, does not keep the placed faces, and `GeometryData.Faces` builds the same faces when it is first read; for a consumer that draws an instance from its symbol and its placement; default false, a scene read sets it), `ShareEqualVertices` (the vertices of one geometry block that are equal bit for bit are one array shared by its faces; coordinates, faces and vertex lists are the same; for a consumer that only reads the geometry, because writing into a vertex in place then moves it in every face that shares it; default false, a scene read sets it), `UndrawnFacesOnDemand` (an element that a mesh extraction never draws and that no element which may be drawn places whole does not keep the faces of its own geometry block, when the block is faces alone and small beside them and the element is not a wall, a floor, a curtain panel or a mullion; `GeometryData.Faces` decodes the block again from a copy of its bytes and builds the same faces when it is first read; with `DetailLevelQuantities` off a block that no placement reads gives its faces up inside the read itself, which lowers its peak memory; with `PlacedFacesOnDemand` on as well such an element gives up the faces of the symbols it places also where they were cut to its bounding box; default false, a scene read sets it), `RaiseLimits` and `Diagnostics`. `RevitLocalizationDirectory` is `[Obsolete]` and ignored: the texts are built in. | +| `RvtReaderOptions` | Options of a read, including `DiagnosticOutput`, `Progress` (see below), `ResolveCurrentCopies` (keeps only the current copy of an element that several partition streams hold; default true, set it to false to decode every copy), `ReleasePartitions` (drops the decompressed partition streams before the model is built, for a caller that keeps only the result; the model is the same and the read needs less memory; a file read by its own class schema keeps its streams unless `R22Layout` rewrote them and `PreserveWideLayout` is off, and of a rewritten file the streams of the file itself go once its element records are read; the decoded geometry blocks and per-element tables of the reader go as soon as the elements are built; where `ProjectElementsOnly` leaves records unbuilt, what the reader holds for them goes as well), `ProjectElementsOnly` (builds the elements of the element table that are no content of a loaded family's document, the definitions that exist as a geometry block alone, and of the rest only what a built element refers to, and decodes no geometry for what is not built; the rest is the content of the loaded families' documents, which a file of Revit 2022 holds as records outside the table and as elements of the table whose record names their family, most of the elements and of the memory of a large read; a family listing its own content is no reference to it, the content of a family modelled in place is built as before, and an element of the table that is not built stays as an element without category or geometry; a value a rule derives from all the elements is then derived from the built ones; applies when the element table was read exactly; it has no effect on a family document, whose elements are the content of its family; default false, `RvtSceneReader.Read(path)` and `ReadStream` set it), `DetailLevelQuantities` (the measures of doors, windows and structural columns at the Coarse and Medium detail levels, which only the IFC export reads; default true, a scene read turns it off and then also drops the decoded geometry blocks before the finalization passes), `PlacedFacesOnDemand` (an element whose geometry is exactly its symbols placed, an instance of a family, does not keep the placed faces, and `GeometryData.Faces` builds the same faces when it is first read; for a consumer that draws an instance from its symbol and its placement; default false, a scene read sets it), `ShareEqualVertices` (the vertices of one geometry block that are equal bit for bit are one array shared by its faces; coordinates, faces and vertex lists are the same; for a consumer that only reads the geometry, because writing into a vertex in place then moves it in every face that shares it; default false, a scene read sets it), `UndrawnFacesOnDemand` (an element that a mesh extraction never draws and that no element which may be drawn places whole does not keep the faces of its own geometry block, when the block is faces alone and small beside them and the element is not a wall, a floor, a curtain panel or a mullion; `GeometryData.Faces` decodes the block again from a copy of its bytes and builds the same faces when it is first read; with `DetailLevelQuantities` off a block that no placement reads gives its faces up inside the read itself, which lowers its peak memory; with `PlacedFacesOnDemand` on as well such an element gives up the faces of the symbols it places also where they were cut to its bounding box; default false, a scene read sets it), `RaiseLimits` and `Diagnostics`. `RevitLocalizationDirectory` is `[Obsolete]` and ignored: the texts are built in. | | `RvtReadDiagnostics`, `StreamRecord`, `ReaderLimitHit` | What a read collects when `RvtReaderOptions.Diagnostics` is set: the partition and metadata streams read (stored and inflated byte sizes and member decode counts) and the streams cut by a limit. | | `RvtReadProgress` | File-reading updates delivered through `RvtReaderOptions.Progress`. | | `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). | @@ -204,9 +206,10 @@ 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). | +| `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). `ComputeFamilyType(document, typeIndex)` returns the shape of a family file in one of the types of `RvtDocument.FamilyTypes`, computed from the relations of the family; see [the scene mapping](scene.md#families) for what is computed and for the refusal codes. It throws `ArgumentOutOfRangeException` for a document without a type of that index. | +| `RvtFamilyTypeMeshes` | What `ComputeFamilyType` returns: `Elements`, one `ElementMesh` per form of the family in document order (a form the type hides has no meshes), or null with the `Refusal` that says why the type is not computed. | | `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`). | +| `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), `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`) and `FamilyGaps` (a family file only: why its shape at the saved type is incomplete, as the codes `void`, `visibility`, `missing-geometry`, `unknown-geometry` and `owner`). For a family document, `Elements` holds the forms and nested families of its shape; one hidden by the saved type has neither meshes nor placements. | | `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. | diff --git a/docs/scene.md b/docs/scene.md index a44b83a9..2779858c 100644 --- a/docs/scene.md +++ b/docs/scene.md @@ -45,7 +45,8 @@ The final reader update, `complete`, marks the end of the file read. Mesh extrac 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. +coverage, geometries, instances and symbol placements. For a family file it also holds `FamilyTypes` (see +[Families](#families)). ### Command Line @@ -80,6 +81,50 @@ rvtio project.rvt --ifc project.ifc --compact-json project.compact.json --scene | `ScenePropertySet` | `revit:instance`: the parameters of the element. `revit:type`: the parameters of its type, one set shared by every element of the type. A parameter that carries no value in Revit (`!parameter.HasRevitValue`, covering unset sentinels such as `Double` `>= 1e29`, `ElementId` `-1` or uninitialized `0` without a resolved id-0 target, and unhosted host-id pointers, as well as unstored default placeholders synthesized by the reader) is left out, and so is one whose value the reader only estimates (`Parameter.IsApproximate`), such as the fixed thermal values of a wall; stored `0`, `0.0`, `""`, valid resolved id-0 references such as project phase `0`, and valid negative `ElementId` option or category values are kept. | | `SceneProperty` | Name: `Definition.Name` (for a built-in parameter its enum name, such as `WALL_USER_HEIGHT_PARAM`). Key: `revit:bip:` for a built-in parameter, none for the others. Value: text, the display string of the public parameter API (see below). | +### Families + +The scene of a family file (`.rfa`) is the family at its saved type, as a 3D view at the Fine detail level shows it: its +solid forms and nested families. The hosts of the family template, reference planes and lines, openings, void forms, and +annotations and detail items nested in the family are not part of it. A form that the family parameter driving its +visibility hides in the saved type is an element without instances. A combination of forms is shown in place of the forms +it combines. A family scene has no levels or grids, and its elements have no `LevelId`; `SourceFormat` stays `rvt`. + +When something the saved type may show cannot be shown as Revit shows it, the scene has the `family-incomplete` +diagnostic. A family file whose owner family is not found, such as one whose records the reader cannot read, is read as a +project and is marked too. + +`RvtSceneResult.FamilyTypes` lists the types of the family, next to the scene and not inside it: the scene holds the saved +type only, and a consumer that ignores the list has a correct scene. Each type has its name and all parameter values it +stores. The type Revit keeps without a name for a family without named types is listed only when the file was saved at +it. A family that stores no types has no list. The list is an `RvtSceneFamilyTypes`: `SavedIndex`, `Types`, and the +`Geometries` and `Materials` of the computed types that the scene does not hold. A type is an `RvtSceneFamilyType` with +`Name`, `Parameters` (each an `RvtSceneFamilyValue` of `Name` and `Text`), and `Instances` or `Refusal`. + +A type that is not the saved one is computed from the relations of the family (`ElementMeshes.ComputeFamilyType`): it has +`Instances`, each over a geometry of the scene or of the list and over an element of the scene, or a `Refusal` that says +why it has none. A form a type hides has no instances in it. The geometries and materials of the list are those the scene +does not hold; their ids follow those of the scene. + +A family is computed only when it is made of extrusions whose profiles are straight sides along the axes of the family, +placed by reference planes, dimensions, alignments and joined sketch lines the reader recognizes, with no cuts, no visible +nested family and no formula on a parameter that moves the shape, and only when what is computed for the saved type is what +the file stores for it. The code of a refusal says what stands in the way: + +| Code | The type | +|---|---| +| `unsupported-construct` | The family has a construct that is not computed, or its saved shape is incomplete. | +| `unrecognized-reference` | An element or a record refers to the forms or their relations in a way that is not recognized, or the records were not read. | +| `unverified-anchor` | Nothing recognized holds the family in place. | +| `underdetermined` | The relations and the values of the type leave a part of the shape free. No nearest shape is chosen. | +| `inconsistent` | The values of the type contradict each other in the relations. | +| `saved-state-mismatch` | What is computed for the saved type is not what the file stores: no type of the family is computed. | +| `degenerate-geometry` | The profile of a form is not a valid one in this type, as when a hole no longer fits inside it. | +| `not-computed` | The meshes the scene was made from leave out an element of the type. | + +The text of a value is, in order: the name of a referenced material; the property text below; for a length without a +property text (a parameter whose spec is length, and the family width, height and default elevation) its millimetres, +the conversion from feet being exact; otherwise none, and the parameter is still listed. + ### Property text A value is written as the text `Parameter.AsValueString` shows, with the invariant culture, and only when that text is @@ -108,6 +153,8 @@ The text a value is written with under a key is frozen with the key: changing it | `partial-geometry` | warning | Faces that could not be triangulated, or a placed symbol or Geometry node without a decoded polygon. | | `box-substitute` | warning | A rescaled symbol drawn as its bounding box. | | `no-source-id` | warning | Elements without a UniqueId; they cannot be identified outside the scene. | +| `family-incomplete` | warning | The shape of a family may be incomplete. The message lists the reasons: the codes of `MeshSet.FamilyGaps` and of the element diagnostics of this table. One per scene. | +| `family-types-unreadable` | warning | The type table of a family was not read exactly; the scene has no list of types. The message says why. One per scene. | ## Limits diff --git a/src/RvtIO.Scene/RvtSceneFamilyTypes.cs b/src/RvtIO.Scene/RvtSceneFamilyTypes.cs new file mode 100644 index 00000000..df76735c --- /dev/null +++ b/src/RvtIO.Scene/RvtSceneFamilyTypes.cs @@ -0,0 +1,38 @@ +using IOScene; +using RvtIO.Families; + +namespace RvtIO.Scene; + +/// One parameter of a type of a family. +/// The name of the parameter; its id where the file gives no name that is read exactly. +/// The value as text; null where there is no text that is exactly what Revit shows. +public sealed record RvtSceneFamilyValue(string Name, string? Text); + +/// One type of the family of a family document. +/// The name of the type. +/// All parameter values the type stores, in stored order. +public sealed record RvtSceneFamilyType(string Name, IReadOnlyList Parameters) +{ + /// The instances of a type whose geometry is computed, each over a geometry of the scene or of + /// and over elements of the scene; empty when the type shows no form. Null for + /// the saved type, whose instances are those of the scene, and for a type that is not computed. + public IReadOnlyList? Instances { get; init; } + + /// Why the type is not computed (; not-computed when + /// the meshes the scene was made from leave out one of its elements); null for the saved type and for a computed one. + public RvtFamilyRefusal? Refusal { get; init; } +} + +/// The types of the family of a family document. The scene itself holds the saved type only. +/// The type the file was saved at, an index into . +/// The types in stored order. The type Revit keeps without a name for a family without named types is +/// listed only when the file was saved at it. +public sealed record RvtSceneFamilyTypes(int SavedIndex, IReadOnlyList Types) +{ + /// The geometries of the computed types that are not equal to one of the scene, apart from those of the scene and + /// with ids that follow theirs. + public IReadOnlyList Geometries { get; init; } = []; + + /// The materials of the computed types that the scene does not hold. + public IReadOnlyList Materials { get; init; } = []; +} diff --git a/src/RvtIO.Scene/RvtSceneReader.cs b/src/RvtIO.Scene/RvtSceneReader.cs index da51032a..e76cce7e 100644 --- a/src/RvtIO.Scene/RvtSceneReader.cs +++ b/src/RvtIO.Scene/RvtSceneReader.cs @@ -3,6 +3,7 @@ using System.Reflection; using IOScene; using RvtIO.BuiltIns; +using RvtIO.Families; using RvtIO.Meshes; using RvtIO.Model; @@ -178,9 +179,11 @@ 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) + // A family file has no levels or grids of its own: those it holds come from its template. + bool family = document.FamilyOwnerId != null || meshes.FamilyGaps.Count > 0; + if (!family) AddGrids(scene, document); + var storeys = family ? null : document.GetBuildingStoreyCatalog(); + foreach (var storey in storeys?.Storeys ?? []) scene.Levels.Add(new SceneLevel { Id = storey.Id, @@ -207,6 +210,7 @@ private static RvtSceneResult Map(RvtDocument document, MeshSet meshes, string m var typeSets = new Dictionary(); var coverage = new Dictionary(); + var incomplete = new List(meshes.FamilyGaps); int withGeometry = 0, placements = 0, withoutUniqueId = 0; foreach (var mesh in meshes.Elements) { @@ -215,7 +219,7 @@ private static RvtSceneResult Map(RvtDocument document, MeshSet meshes, string m { Id = mesh.ElementId, ModelId = ModelId, - LevelId = mesh.IsDatum ? null : storeys.GetStoreyId(mesh.ElementId), + LevelId = mesh.IsDatum ? null : storeys?.GetStoreyId(mesh.ElementId), SourceId = element?.UniqueId, IfcGuid = element != null ? IfcGuidOf(element) : null, Kind = SceneNodeKind.Element, @@ -299,8 +303,15 @@ private static RvtSceneResult Map(RvtDocument document, MeshSet meshes, string m if (scene.Instances.Count > instancesBefore) withGeometry++; coverage[mesh.Coverage] = coverage.GetValueOrDefault(mesh.Coverage) + 1; - if (CoverageDiagnostic(mesh, sceneElement.SourceId) is { } diagnostic) report.Add(diagnostic); + if (CoverageDiagnostic(mesh, sceneElement.SourceId) is { } diagnostic) + { + report.Add(diagnostic); + if (family && !incomplete.Contains(diagnostic.Code)) incomplete.Add(diagnostic.Code); + } } + if (incomplete.Count > 0) + report.Add(new(SceneSeverity.Warning, "family-incomplete", + $"The shape of the family may be incomplete: {string.Join(", ", incomplete)}.")); Dictionary? sceneElements = null; foreach (var mesh in meshes.Elements) { @@ -314,9 +325,12 @@ private static RvtSceneResult Map(RvtDocument document, MeshSet meshes, string m 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.")); + var familyTypes = FamilyTypesOf(document, scene, report); + return new RvtSceneResult { Document = scene, + FamilyTypes = familyTypes, Diagnostics = report, ElementCount = scene.Elements.Count, ElementsWithGeometry = withGeometry, @@ -328,6 +342,101 @@ private static RvtSceneResult Map(RvtDocument document, MeshSet meshes, string m }; } + /// The types of the family, those computed with instances over the geometries of the scene and over geometries of + /// their own; is complete and is not changed. + private static RvtSceneFamilyTypes? FamilyTypesOf(RvtDocument document, SceneDocument scene, List report) + { + if (document.FamilyTypesError is { } error) + report.Add(new(SceneSeverity.Warning, "family-types-unreadable", $"The types of the family were not read: {error}")); + if (document.FamilyTypes is not { } types) return null; + var listed = new List(); + var geometries = new List(); + var materials = new List(); + var elementIds = scene.Elements.Select(element => element.Id).ToHashSet(); + var materialIds = scene.Materials.Select(material => (long)material.Id).ToHashSet(); + // Equal arrays have equal sums of their coordinates: only geometries of one key are compared value by value. + var equalCandidates = scene.Geometries.GroupBy(Key).ToDictionary(group => group.Key, group => group.ToList()); + int saved = 0; + for (int index = 0; index < types.Types.Count; index++) + { + var type = types.Types[index]; + bool current = index == types.CurrentIndex; + // Revit keeps a type without a name for a family that has no named types. + if (!current && string.IsNullOrWhiteSpace(type.Name)) continue; + if (current) saved = listed.Count; + var (instances, refusal) = current ? (null, null) : Computed(ElementMeshes.ComputeFamilyType(document, index)); + listed.Add(new(type.Name, type.Parameters.Select(parameter => new RvtSceneFamilyValue( + parameter.Definition?.Name ?? parameter.Id.ToString(CultureInfo.InvariantCulture), + parameter.HasRevitValue ? FamilyText(document, parameter) : null)).ToArray()) + { + Instances = instances, + Refusal = refusal, + }); + } + return new(saved, listed) { Geometries = geometries, Materials = materials }; + + (IReadOnlyList?, RvtFamilyRefusal?) Computed(RvtFamilyTypeMeshes computed) + { + if (computed.Elements is not { } meshes) return (null, computed.Refusal); + // Meshes the caller gave the scene may leave out elements: a type of them cannot be shown in this scene. + if (meshes.FirstOrDefault(mesh => mesh.Meshes.Count > 0 && !elementIds.Contains(mesh.ElementId)) is { } missing) + return (null, new("not-computed", $"element {missing.ElementId} is not in the scene")); + var instances = new List(); + foreach (var mesh in meshes) + { + if (mesh.Meshes.Count == 0) continue; + var origin = LowestCorner(mesh.Meshes); + var transform = Transform3d.Translate(Vector(origin) * MetresPerFoot); + foreach (var own in mesh.Meshes) + { + if (own.MaterialId > 0 && materialIds.Add(own.MaterialId)) materials.Add(Material(document, own.MaterialId)); + instances.Add(new SceneInstance + { + ElementId = mesh.ElementId, GeometryId = Shared(own, origin), Transform = transform, + MaterialId = own.MaterialId > 0 ? own.MaterialId : null, + }); + } + } + return (instances, null); + } + + // The id of the geometry of the mesh: that of an equal one of the scene or of another type, else a new one. + int Shared(TriangleMesh mesh, MeshVector origin) + { + var geometry = Geometry(scene.Geometries.Count + geometries.Count + 1, mesh, origin); + if (!equalCandidates.TryGetValue(Key(geometry), out var candidates)) equalCandidates[Key(geometry)] = candidates = []; + foreach (var candidate in candidates) + if (Equal(candidate, geometry)) return candidate.Id; + candidates.Add(geometry); + geometries.Add(geometry); + return geometry.Id; + } + + static (int, int, double, double, double) Key(SceneGeometry geometry) => (geometry.Vertices.Count(), + geometry.Indices.Count(), geometry.Vertices.Sum(v => v.X), geometry.Vertices.Sum(v => v.Y), geometry.Vertices.Sum(v => v.Z)); + + static bool Equal(SceneGeometry a, SceneGeometry b) => a.Topology == b.Topology + && a.Vertices.SequenceEqual(b.Vertices) && a.Indices.SequenceEqual(b.Indices) + && (a.Normals == null ? b.Normals == null : b.Normals != null && a.Normals.SequenceEqual(b.Normals)); + } + + /// The text of a value in the list of types: the name of a material, the text the scene properties give, and for a + /// length without such a text its millimetres, the conversion from feet being exact. + private static string? FamilyText(RvtDocument document, Parameter parameter) + { + if (parameter.StorageType == StorageType.ElementId && parameter.Value is int key + && document.GetElement(key) is { CategoryId: (int)BuiltInCategory.OST_Materials, Name: { Length: > 0 } material }) + return material; + if (DisplayText(parameter) is { } text) return text; + return parameter.Value is double length + && (parameter.SpecType is { } spec && (spec == LengthSpec || spec.StartsWith(LengthSpec + "-", StringComparison.Ordinal)) + || (BuiltInParameter)parameter.Id is BuiltInParameter.FAMILY_WIDTH_PARAM or BuiltInParameter.FAMILY_HEIGHT_PARAM + or BuiltInParameter.FAMILY_FREEINST_DEFAULT_ELEVATION) + ? string.Create(CultureInfo.InvariantCulture, $"{length * 304.8:G6} mm") : null; + } + + private const string LengthSpec = "autodesk.spec.aec:length"; + private static void AddGrids(SceneDocument scene, RvtDocument document) { const double GridChordErrorMetres = 0.001; @@ -482,6 +591,13 @@ private static SceneMaterial Material(RvtDocument document, int id) /// Adds the mesh as a geometry in metres, its vertices relative to (feet). private static int AddGeometry(SceneDocument scene, TriangleMesh mesh, MeshVector origin) + { + var geometry = Geometry(scene.Geometries.Count + 1, mesh, origin); + scene.Geometries.Add(geometry); + return geometry.Id; + } + + private static SceneGeometry Geometry(int id, TriangleMesh mesh, MeshVector origin) { var vertices = new Vector3d[mesh.Positions.Length / 3]; for (int vertex = 0; vertex < vertices.Length; vertex++) @@ -492,9 +608,7 @@ private static int AddGeometry(SceneDocument scene, TriangleMesh mesh, MeshVecto var normals = new Vector3d[mesh.Normals.Length / 3]; for (int vertex = 0; vertex < normals.Length; vertex++) normals[vertex] = new Vector3d(mesh.Normals[3 * vertex], mesh.Normals[3 * vertex + 1], mesh.Normals[3 * vertex + 2]); - int id = scene.Geometries.Count + 1; - scene.Geometries.Add(new SceneGeometry { Id = id, Topology = SceneTopology.Triangles, Vertices = vertices, Indices = mesh.Indices, Normals = normals }); - return id; + return new SceneGeometry { Id = id, Topology = SceneTopology.Triangles, Vertices = vertices, Indices = mesh.Indices, Normals = normals }; } /// The lowest x, y and z of the vertices of , in feet. diff --git a/src/RvtIO.Scene/RvtSceneResult.cs b/src/RvtIO.Scene/RvtSceneResult.cs index 9aacba17..c7e1f712 100644 --- a/src/RvtIO.Scene/RvtSceneResult.cs +++ b/src/RvtIO.Scene/RvtSceneResult.cs @@ -9,6 +9,10 @@ public sealed class RvtSceneResult /// The scene: one model, its elements, geometries, instances, materials and property sets, in metres. public required SceneDocument Document { get; init; } + /// The types of the family of a family document; null for a project and when the type table was not read, which a + /// family-types-unreadable diagnostic then says. + public RvtSceneFamilyTypes? FamilyTypes { get; init; } + /// What the conversion could not carry over: an error when the geometry of the file was not decoded or the read was /// cut by a reader limit, and a warning for every element whose geometry is incomplete or missing. Empty when nothing was lost. /// SourceId names the element (its Revit UniqueId) where there is one. diff --git a/src/RvtIO/Families/FamilyContent.cs b/src/RvtIO/Families/FamilyContent.cs new file mode 100644 index 00000000..660e4692 --- /dev/null +++ b/src/RvtIO/Families/FamilyContent.cs @@ -0,0 +1,45 @@ +namespace RvtIO.Families; + +/// What an element is for the shape of the family at its saved type. +internal enum FamilyContentKind +{ + /// Part of the shape. + Shown, + + /// Hidden only by the family parameter that drives its visibility: another type can show it. + Hidden, + + /// Not part of the shape of any type. + Excluded, + + /// It may be part of the shape, but it cannot be shown: the shape is incomplete. + Gap, +} + +internal static class FamilyContent +{ + /// The reason codes of an incomplete shape (). + internal const string VoidGap = "void", VisibilityGap = "visibility", MissingGeometryGap = "missing-geometry", + UnknownGeometryGap = "unknown-geometry"; + + /// What the element is for the shape, and why the shape is incomplete because of it (null: it is not). A shown + /// element can leave the shape incomplete too. + internal static (FamilyContentKind Kind, string? Gap) Classify(in FamilyElementFacts facts) + { + if (facts.DrawnInViewsOnly || FamilyRules.IsNeverShown(facts.ClassName)) return (FamilyContentKind.Excluded, null); + // An element that only places forms adds nothing: each of those is classified itself. + if (!facts.IsForm) + return facts.HasGeometry && !facts.PlacesOwnFormsOnly ? (FamilyContentKind.Gap, UnknownGeometryGap) : (FamilyContentKind.Excluded, null); + // A void is never shown. The faces of the forms it cuts are stored uncut: the combination of both holds the shape. + if (facts.Cutting) return (FamilyContentKind.Excluded, null); + if (facts.CombinationMember) + return facts.MemberShownAlways ? (FamilyContentKind.Gap, VisibilityGap) : (FamilyContentKind.Excluded, null); + if (facts.ShownInFine is not bool shown || facts.HiddenBySavedType is not bool hidden) + return (FamilyContentKind.Gap, VisibilityGap); + if (!shown) return (FamilyContentKind.Excluded, null); + if (hidden) return (FamilyContentKind.Hidden, null); + if (!facts.HasGeometry) return (FamilyContentKind.Gap, MissingGeometryGap); + // Whether the recorded faces include a cut of the element's own is not established. + return (FamilyContentKind.Shown, facts.CutByOwnStep ? VoidGap : null); + } +} diff --git a/src/RvtIO/Families/FamilyContourChecks.cs b/src/RvtIO/Families/FamilyContourChecks.cs new file mode 100644 index 00000000..81682413 --- /dev/null +++ b/src/RvtIO/Families/FamilyContourChecks.cs @@ -0,0 +1,118 @@ +using System.Globalization; + +namespace RvtIO.Families; + +/// +/// Whether the profiles of solved variable values still describe the forms of the family: every segment keeps a length +/// and its direction, segments meet only where consecutive ones of a loop share a corner, every loop stays inside the +/// loops it was inside, an extrusion ends above its start, and a labelled dimension is more than zero. +/// +internal static class FamilyContourChecks +{ + private const double Tolerance = 1e-6; // feet + + public static RvtFamilyRefusal? Check(FamilyModel model, IReadOnlyList positions, + IReadOnlyDictionary values) + { + foreach (var equation in model.Equations) + if (!equation.IsOffset && equation.ParameterId is long parameter && values.TryGetValue(parameter, out double value) + && !(value > Tolerance)) + return Refused(parameter); + var stored = model.Variables.Select(variable => variable.Stored).ToArray(); + foreach (var extrusion in model.Extrusions) + if (!Holds(extrusion, positions, stored)) return Refused(extrusion.ElementId); + return null; + } + + /// The loops of in the two axes that follow its own, which are right-handed + /// with it. + internal static List<(double U, double V)[]> Profiles(FamilyExtrusion extrusion, IReadOnlyList positions) + { + int u = (extrusion.Axis + 1) % 3, v = (extrusion.Axis + 2) % 3; + static int Component(FamilyVertex vertex, int axis) => axis == 0 ? vertex.X : axis == 1 ? vertex.Y : vertex.Z; + return extrusion.Loops.Select(loop => loop + .Select(vertex => (positions[Component(vertex, u)], positions[Component(vertex, v)])).ToArray()).ToList(); + } + + /// [i, j] is true when loop j lies inside loop i; the loops do not meet each other. + internal static bool[,] Nesting(IReadOnlyList<(double U, double V)[]> loops) + { + var inside = new bool[loops.Count, loops.Count]; + for (int i = 0; i < loops.Count; i++) + for (int j = 0; j < loops.Count; j++) + inside[i, j] = i != j && Contains(loops[i], loops[j][0]); + return inside; + } + + private static bool Holds(FamilyExtrusion extrusion, IReadOnlyList positions, double[] stored) + { + double height = positions[extrusion.End] - positions[extrusion.Start]; + if (!(height > Tolerance && double.IsFinite(height))) return false; + var loops = Profiles(extrusion, positions); + var saved = Profiles(extrusion, stored); + + var segments = new List<(int Loop, int Index, (double U, double V) A, (double U, double V) B)>(); + for (int l = 0; l < loops.Count; l++) + { + int count = loops[l].Length; + if (count < 3) return false; + for (int i = 0; i < count; i++) + { + var (a, b) = (loops[l][i], loops[l][(i + 1) % count]); + var (du, dv) = (b.U - a.U, b.V - a.V); + var (savedA, savedB) = (saved[l][i], saved[l][(i + 1) % count]); + // Both comparisons are false for a position that is not a number. + if (!(Math.Sqrt(du * du + dv * dv) > Tolerance + && du * (savedB.U - savedA.U) + dv * (savedB.V - savedA.V) > 0)) return false; + segments.Add((l, i, a, b)); + } + } + + for (int first = 0; first < segments.Count; first++) + for (int second = first + 1; second < segments.Count; second++) + { + var (s, t) = (segments[first], segments[second]); + bool follows = s.Loop == t.Loop && (s.Index + 1) % loops[s.Loop].Length == t.Index; + bool precedes = s.Loop == t.Loop && (t.Index + 1) % loops[s.Loop].Length == s.Index; + if (follows || precedes) + { + // They share a corner; neither may run back along the other. + var (before, after) = follows ? (s, t) : (t, s); + if (Distance(before.A, after.A, after.B) <= Tolerance + || Distance(after.B, before.A, before.B) <= Tolerance) return false; + } + else if (Cross(s.A, s.B, t.A) * Cross(s.A, s.B, t.B) < 0 && Cross(t.A, t.B, s.A) * Cross(t.A, t.B, s.B) < 0 + || Distance(s.A, t.A, t.B) <= Tolerance || Distance(s.B, t.A, t.B) <= Tolerance + || Distance(t.A, s.A, s.B) <= Tolerance || Distance(t.B, s.A, s.B) <= Tolerance) return false; + } + + return Nesting(loops).Cast().SequenceEqual(Nesting(saved).Cast()); + } + + private static double Cross((double U, double V) a, (double U, double V) b, (double U, double V) point) => + (b.U - a.U) * (point.V - a.V) - (b.V - a.V) * (point.U - a.U); + + // From a point to the segment a-b, which has a length. + private static double Distance((double U, double V) point, (double U, double V) a, (double U, double V) b) + { + var (du, dv) = (b.U - a.U, b.V - a.V); + double along = Math.Clamp(((point.U - a.U) * du + (point.V - a.V) * dv) / (du * du + dv * dv), 0, 1); + var (x, y) = (point.U - a.U - along * du, point.V - a.V - along * dv); + return Math.Sqrt(x * x + y * y); + } + + private static bool Contains((double U, double V)[] loop, (double U, double V) point) + { + bool inside = false; + for (int i = 0; i < loop.Length; i++) + { + var (a, b) = (loop[i], loop[(i + 1) % loop.Length]); + if ((a.V > point.V) != (b.V > point.V) && point.U < a.U + (point.V - a.V) / (b.V - a.V) * (b.U - a.U)) + inside = !inside; + } + return inside; + } + + private static RvtFamilyRefusal Refused(long id) => + new("degenerate-geometry", id.ToString(CultureInfo.InvariantCulture)); +} diff --git a/src/RvtIO/Families/FamilyData.cs b/src/RvtIO/Families/FamilyData.cs new file mode 100644 index 00000000..9a46a00b --- /dev/null +++ b/src/RvtIO/Families/FamilyData.cs @@ -0,0 +1,51 @@ +using RvtIO.Model; + +namespace RvtIO.Families; + +/// What the records of a family document say about the elements of its own family. +internal sealed class FamilyData +{ + /// The elements that can be part of the shape of the family, in document order: forms, combinations, nested + /// instances and every other own element with geometry. + internal required IReadOnlyList Elements { get; init; } + + /// The types of the family; null when the type table was not read exactly. + internal RvtFamilyTypes? Types { get; init; } + + /// Why is null for a table that exists. + internal string? TypesError { get; init; } + + /// What places the forms of the family; null when the family has no types to recompute or its records were + /// not read. + internal FamilyRecords? Records { get; init; } + + /// What computing a type needs, made at the first one that is computed. + internal FamilyPreparation? Prepared { get; set; } +} + +/// A model of a family whose saved state it reproduces, with the stored face each of its faces is and the elements +/// of the saved type in document order; or why no type of the family is computed. +internal sealed record FamilyPreparation(FamilyModel? Model, + IReadOnlyDictionary<(int ElementId, FamilyFaceKey Face), GeoFace>? Faces, IReadOnlyList Elements, + RvtFamilyRefusal? Refusal); + +/// What the file records about one element, for the shape of the family at its saved type in a 3D view at the Fine +/// detail level. +/// The key of the element in . +/// The class of the element. +/// A form (a sweep of any kind), a combination of forms or a nested family instance. +/// The reader holds faces or placed symbols for it. +/// The form is a void. +/// Whether the element's own settings show it: its visibility flags, and its "Visible" checkbox when +/// no family parameter drives it. Null when the record does not give them in a recognised form. +/// Whether a family parameter that drives its visibility hides it in the saved type. Null when +/// not recognised. +/// The form is part of a combination, which holds the combined shape. +/// The combination records that this member is shown besides the combined shape. +/// The geometry of the element records a cut of its own. +/// A nested instance that only views draw, such as an annotation or a detail item. +/// All its geometry places other forms of the family, as a model group places its +/// members. +internal readonly record struct FamilyElementFacts(int ElementId, string ClassName, bool IsForm, bool HasGeometry, + bool Cutting, bool? ShownInFine, bool? HiddenBySavedType, bool CombinationMember = false, bool MemberShownAlways = false, + bool CutByOwnStep = false, bool DrawnInViewsOnly = false, bool PlacesOwnFormsOnly = false); diff --git a/src/RvtIO/Families/FamilyDocument.cs b/src/RvtIO/Families/FamilyDocument.cs new file mode 100644 index 00000000..d90b20eb --- /dev/null +++ b/src/RvtIO/Families/FamilyDocument.cs @@ -0,0 +1,43 @@ +using System.Buffers.Binary; +using OpenMcdf; +using RvtIO.Parsing; +using RvtIO.Writing; + +namespace RvtIO.Families; + +/// What makes a file a family document: the family its document header names as the owner of the document. +internal static class FamilyDocument +{ + private static readonly string[] OwnerFields = ["m_ownerFamilyId", "m_ownerFamilyContainingGroupId"]; + + /// The id of the owner family of a family document; null for a project, for a family inside a group and for a header + /// that cannot be read exactly. + public static long? OwnerId(RootStorage root) + { + try + { + if (TfSchemaReader.Read(root) is not { } schema) return null; + var walker = new WideBlockWalker(schema, + (declaring, field) => declaring.Name == "ADocument" && OwnerFields.Contains(field.Name) ? "ADocument." + field.Name : null, + ["ForgeTypeId", "FormatOptions", "AUnits"]); + return PagedGzipStream.Read(root, "Global", "Latest") is { } latest + && Header(latest, new FormatsSchema(schema), walker) is { } header ? OwnerOf(header) : null; + } + // A damaged stream does not make the file a family document; the read of its elements reports the damage. + catch (Exception ex) when (MalformedInput.Is(ex)) { return null; } + } + + /// The root object of , the bytes of Global/Latest, walked alone; null when they do not + /// start with the document. + internal static WideBlockWalker.Walk? Header(byte[] latest, FormatsSchema formats, WideBlockWalker walker) => + latest.Length >= 2 && BinaryPrimitives.ReadUInt16LittleEndian(latest) == formats.IdOf("ADocument") + ? walker.Run(latest, 0, latest.Length, BinaryPrimitives.ReadUInt16LittleEndian(latest), rootOnly: true) + : null; + + /// The owner family the walked header names, outside any group; the walker must capture both owner fields. + internal static long? OwnerOf(WideBlockWalker.Walk header) => + header.RootRead && UserParameterWriter.Integer(header, "ADocument.m_ownerFamilyId") is long id and > 0 + && UserParameterWriter.Integer(header, "ADocument.m_ownerFamilyContainingGroupId") == -1 + ? id + : null; +} diff --git a/src/RvtIO/Families/FamilyExtrusionBuilder.cs b/src/RvtIO/Families/FamilyExtrusionBuilder.cs new file mode 100644 index 00000000..9f8dacc2 --- /dev/null +++ b/src/RvtIO/Families/FamilyExtrusionBuilder.cs @@ -0,0 +1,76 @@ +using RvtIO.Model; + +namespace RvtIO.Families; + +/// The faces of an extrusion for solved variable values; the profiles have passed +/// . +internal static class FamilyExtrusionBuilder +{ + /// A side face per segment and, for every loop that is not a hole, a face at each end with its holes. A loop + /// inside an odd number of others is a hole. Normals point out of the solid; gives the + /// material of each face. + public static List Faces(FamilyExtrusion extrusion, IReadOnlyList positions, + Func material) + { + var loops = FamilyContourChecks.Profiles(extrusion, positions); + var inside = FamilyContourChecks.Nesting(loops); + var depth = Enumerable.Range(0, loops.Count) + .Select(loop => Enumerable.Range(0, loops.Count).Count(other => inside[other, loop])).ToArray(); + // 1 for a loop drawn counter-clockwise seen from the end of the axis, -1 for the other way round. + var turn = loops.Select(loop => Math.Sign(Enumerable.Range(0, loop.Length) + .Sum(i => loop[i].U * loop[(i + 1) % loop.Length].V - loop[(i + 1) % loop.Length].U * loop[i].V))).ToArray(); + + double[] Point((double U, double V) corner, double along) + { + var point = new double[3]; + point[(extrusion.Axis + 1) % 3] = corner.U; + point[(extrusion.Axis + 2) % 3] = corner.V; + point[extrusion.Axis] = along; + return point; + } + // The corners of a loop, counter-clockwise (way 1) or clockwise (way -1) seen from the end of the axis. + List Ring(int loop, double along, int way) + { + var ring = loops[loop].Select(corner => Point(corner, along)).ToList(); + if (turn[loop] != way) ring.Reverse(); + return ring; + } + GeoFace Face(List outer, double[] normal, FamilyFaceKey key) => + new((double[])outer[0].Clone(), normal) { OuterVertices = outer, RenderStyleId = material(key) }; + + double start = positions[extrusion.Start], end = positions[extrusion.End]; + var faces = new List(); + for (int loop = 0; loop < loops.Count; loop++) + { + if (depth[loop] % 2 != 0) continue; + var holes = Enumerable.Range(0, loops.Count) + .Where(hole => inside[loop, hole] && depth[hole] == depth[loop] + 1).ToList(); + foreach (var (kind, along, way) in new[] + { (FamilyFaceKind.StartCap, start, -1), (FamilyFaceKind.EndCap, end, 1) }) + { + var normal = new double[3]; + normal[extrusion.Axis] = way; + var cap = Face(Ring(loop, along, way), normal, new(kind, loop)); + if (holes.Count > 0) cap.InnerVertices = holes.Select(hole => Ring(hole, along, -way)).ToList(); + faces.Add(cap); + } + } + for (int loop = 0; loop < loops.Count; loop++) + { + // The right side of a segment is outside a counter-clockwise loop; the solid of a hole lies outside it. + int outward = depth[loop] % 2 == 0 ? turn[loop] : -turn[loop]; + for (int i = 0; i < loops[loop].Length; i++) + { + var (a, b) = (loops[loop][i], loops[loop][(i + 1) % loops[loop].Length]); + double length = Math.Sqrt((b.U - a.U) * (b.U - a.U) + (b.V - a.V) * (b.V - a.V)); + var normal = new double[3]; + normal[(extrusion.Axis + 1) % 3] = outward * (b.V - a.V) / length; + normal[(extrusion.Axis + 2) % 3] = outward * (a.U - b.U) / length; + List quad = [Point(a, start), Point(b, start), Point(b, end), Point(a, end)]; + if (outward < 0) quad.Reverse(); + faces.Add(Face(quad, normal, new(FamilyFaceKind.Side, loop, i))); + } + } + return faces; + } +} diff --git a/src/RvtIO/Families/FamilyModel.cs b/src/RvtIO/Families/FamilyModel.cs new file mode 100644 index 00000000..7f3aa8c4 --- /dev/null +++ b/src/RvtIO/Families/FamilyModel.cs @@ -0,0 +1,36 @@ +namespace RvtIO.Families; + +/// A coordinate of the family along one axis, in feet; an anchored one keeps its stored value. +internal readonly record struct FamilyVariable(double Stored, bool Anchored); + +internal readonly record struct FamilyTerm(int Variable, int Coefficient); + +/// +/// Σ Coefficient·variable = Sign·the value of ParameterId when it is set, otherwise Constant. +/// SourceElementId is the record of the family the relation comes from. A weak relation, from an unlocked dimension, +/// holds only what the others leave free. An offset relation places an end of an extrusion from its sketch plane: its +/// parameter may be zero or below, where a labelled dimension has to be above zero. +/// +internal sealed record FamilyEquation(IReadOnlyList Terms, long? ParameterId, int Sign, double Constant, + int SourceElementId, bool IsWeak = false, bool IsOffset = false); + +/// The variables of a profile vertex; the component along the axis of its extrusion is not used. +internal readonly record struct FamilyVertex(int X, int Y, int Z); + +internal enum FamilyFaceKind { StartCap, EndCap, Side } + +internal readonly record struct FamilyFaceKey(FamilyFaceKind Kind, int Loop = -1, int Segment = -1); + +/// +/// An extrusion of closed loops along Axis (0, 1 or 2 for X, Y or Z), from the variable Start to the +/// variable End. +/// +internal sealed record FamilyExtrusion(int ElementId, IReadOnlyList> Loops, int Axis, int Start, + int End, IReadOnlyDictionary Materials, long? MaterialParameterId, long? VisibilityParameterId); + +/// The forms of a family and the relations that place them. +internal sealed record FamilyModel(IReadOnlyList Variables, IReadOnlyList Equations, + IReadOnlyList Extrusions); + +/// The value of every variable for one type, or why there is none. +internal sealed record FamilySolution(double[]? Positions, RvtFamilyRefusal? Refusal); diff --git a/src/RvtIO/Families/FamilyModelBuilder.cs b/src/RvtIO/Families/FamilyModelBuilder.cs new file mode 100644 index 00000000..d7f1be98 --- /dev/null +++ b/src/RvtIO/Families/FamilyModelBuilder.cs @@ -0,0 +1,550 @@ +using System.Globalization; +using RvtIO.BuiltIns; +using RvtIO.Parsing; + +namespace RvtIO.Families; + +/// +/// Makes the model of the forms of a family and the relations that place them from its records. Anything not read or not +/// understood refuses the whole family, and equal coordinates alone never join two records. +/// +internal static class FamilyModelBuilder +{ + private const double Tolerance = 1e-6; // feet + + public static (FamilyModel? Model, RvtFamilyRefusal? Refusal) Build(FamilyRecords records) + { + try { return (new Builder(records).Build(), null); } + catch (Refused refused) { return (null, refused.Refusal); } + } + + private sealed class Refused(string code, string detail) : Exception + { + public RvtFamilyRefusal Refusal { get; } = new(code, detail); + } + + private static Refused Unsupported(string detail) => new("unsupported-construct", detail); + + private static Refused Unrecognized(string detail) => new("unrecognized-reference", detail); + + private static string Text(long number) => number.ToString(CultureInfo.InvariantCulture); + + /// The axis a direction runs along, or null for a slanted or empty one. + private static int? AxisOf(double[] direction) + { + double length = Math.Sqrt(direction.Sum(component => component * component)); + if (!(length > Tolerance)) return null; + for (int axis = 0; axis < 3; axis++) + if (Math.Abs(Math.Abs(direction[axis]) / length - 1) <= Tolerance) return axis; + return null; + } + + /// The axis a straight line runs along, or null for a curve or a slanted line. + private static int? Direction(FamilySketchLine line) => + line.IsStraight ? AxisOf([.. Enumerable.Range(0, 3).Select(axis => line.End[axis] - line.Start[axis])]) : null; + + private sealed class Builder(FamilyRecords records) + { + // A coordinate; the coordinates the records join share the root of one tree. + private sealed class Node + { + public int Parent; + public double Stored; + public bool Anchored; + public List Elements = []; + } + + private sealed record Equation(List<(int Node, int Coefficient)> Terms, long? Parameter, int Sign, double Constant, + int Source, bool IsWeak, bool IsOffset = false); + + private readonly Dictionary _lines = records.Lines.ToDictionary(line => line.Id); + private readonly Dictionary _planes = records.Planes.ToDictionary(plane => plane.ElementId); + private readonly Dictionary _extrusions = + records.Extrusions.ToDictionary(extrusion => extrusion.Id); + private readonly List _nodes = []; + private readonly Dictionary _keys = []; + private readonly List _equations = []; + private readonly HashSet _heldCaps = []; + + public FamilyModel Build() + { + if (records.UnsupportedContent.Count > 0) + throw Unsupported(string.Join(", ", records.UnsupportedContent.Distinct())); + var axes = _extrusions.Values.ToDictionary(extrusion => extrusion.Id, CheckProfile); + + var dimensions = records.Dimensions.Select(dimension => (Record: dimension, Nodes: Measured(dimension))).ToList(); + Join(); + var referencedLines = records.Dimensions.SelectMany(d => d.References).Select(r => r.ElementId) + .Where(_lines.ContainsKey).ToHashSet(); + var modelLines = _extrusions.Values + .SelectMany(e => e.Loops.SelectMany(loop => loop).Select(key => e.ProfileCurves[key].LineId)) + .Concat(referencedLines).ToHashSet(); + CheckConstraints(modelLines); + CheckAssociations(modelLines); + CheckReferrers(modelLines); + CheckFormulas(); + + PlaceHostFaces(dimensions); + foreach (var (record, nodes) in dimensions) Relate(record, nodes); + var caps = _extrusions.Values.ToDictionary(e => e.Id, e => PlaceCaps(e, axes[e.Id])); + var vertices = _extrusions.Values.ToDictionary(e => e.Id, e => Vertices(e, axes[e.Id])); + Anchor(vertices.Values.SelectMany(loops => loops.SelectMany(loop => loop.SelectMany(v => v))) + .Where(node => node >= 0).Concat(caps.Values.SelectMany(pair => new[] { pair.Low, pair.High }))); + return Assemble(axes, caps, vertices); + } + + /// The axis of an extrusion whose profile is straight lines along the two other axes. + private int CheckProfile(FamilyExtrusionRecord extrusion) + { + if (AxisOf(extrusion.PlaneNormal) is not int axis) throw Unsupported($"sketch plane of {extrusion.Id}"); + foreach (var loop in extrusion.Loops) + { + if (loop.Count < 3) throw Unsupported($"profile of {extrusion.Id}"); + foreach (int key in loop) + { + if (!extrusion.ProfileCurves.TryGetValue(key, out var curve) + || !_lines.TryGetValue(curve.LineId, out var line) || line.SketchId != extrusion.SketchId) + throw Unrecognized($"profile curve {key} of {extrusion.Id}"); + if (Direction(line) is not int along || along == axis) throw Unsupported($"curve {line.Id}"); + } + } + if (extrusion.Loops.Count == 0) throw Unsupported($"profile of {extrusion.Id}"); + return axis; + } + + private int[] Measured(FamilyDimensionRecord dimension) + { + string id = Text(dimension.Id); + int segments = dimension.SegmentFlags.Count; + if (!FamilyRules.IsKnownDimensionFlags(dimension.IsAlignment, dimension.Flags)) + throw Unrecognized($"flags {dimension.Flags} of dimension {id}"); + bool equality = !dimension.IsAlignment && (dimension.Flags & FamilyRules.EqualityDimensionFlag) != 0; + bool known = dimension.References.Count == segments + 1 && dimension.ParameterIds.Count == segments + && dimension.SegmentValues.Count == segments + && Enumerable.Range(0, segments).All(i => + { + long flags = dimension.SegmentFlags[i]; + bool labelled = dimension.ParameterIds[i] != -1; + return dimension.IsAlignment ? !labelled && flags == FamilyRules.LockedSegmentFlag + : equality ? !labelled && flags == FamilyRules.EqualSegmentFlag + : flags is FamilyRules.UnlockedSegmentFlag or FamilyRules.LockedSegmentFlag; + }); + if (!known) throw Unrecognized($"segments of dimension {id}"); + if (AxisOf(dimension.Axis) is not int axis) throw Unsupported($"slanted dimension {id}"); + return [.. dimension.References.Select(reference => Resolve(reference, axis, dimension.Id))]; + } + + /// The coordinate along of what a reference names. + private int Resolve(FamilyReference reference, int axis, int source) + { + int id = reference.ElementId; + if (_planes.TryGetValue(id, out var plane)) + { + // A host has a face for every tag; where it is comes from what is aligned to it. + if (plane.Origin.Length == 0) + return Keyed(("host", reference.ElementId, reference.GeometryTag, reference.SubTag, axis), + double.NaN, id); + if (AxisOf(plane.Normal) != axis) throw Unsupported($"plane {id} measured by {source}"); + int datum = Keyed(("datum", id), plane.Origin[axis], id); + _nodes[datum].Anchored |= plane.ClassName == "Level" || plane.Pinned; + return datum; + } + if (_lines.TryGetValue(id, out var line) && reference.GeometryTag == 0) + { + if (reference.SubTag == -1) + return Direction(line) is int along && along != axis ? Slot(line, -1, axis) + : throw Unsupported($"line {id} measured by {source}"); + if (reference.SubTag is 0 or 1) + return Direction(line) != null ? Slot(line, reference.SubTag, axis) + : throw Unsupported($"curve {id} measured by {source}"); + } + if (_extrusions.TryGetValue(id, out var extrusion)) return OnExtrusion(extrusion, reference, axis, source); + throw Unrecognized($"reference of {source} to element {id}"); + } + + private int OnExtrusion(FamilyExtrusionRecord extrusion, FamilyReference reference, int axis, int source) + { + int ext = AxisOf(extrusion.PlaneNormal)!.Value; + var unknown = Unrecognized($"reference of {source} to tag {reference.GeometryTag} of element {extrusion.Id}"); + FamilySketchLine Line(int key) => extrusion.ProfileCurves.TryGetValue(key, out var curve) + && _lines.TryGetValue(curve.LineId, out var line) ? line : throw unknown; + bool Across(int key) => Direction(Line(key)) is int along && along != axis; + + if (extrusion.FaceHistory.TryGetValue(reference.GeometryTag, out var face)) + { + if (reference.SubTag != -1) throw unknown; + return face switch + { + [1] when axis == ext => Cap(extrusion, false), + [2] when axis == ext => Cap(extrusion, true), + [3, var key] when axis != ext && Across(key) => Slot(Line(key), -1, axis), + _ => throw unknown, + }; + } + if (!extrusion.EdgeHistory.TryGetValue(reference.GeometryTag, out var edge)) throw unknown; + switch (edge) + { + // The edge of a profile curve on the end cap (0) or the start cap (1). + case [1, var key, var cap and (0 or 1)]: + if (axis == ext) return Cap(extrusion, cap == 0); + var line = Line(key); + if (Across(key)) return Slot(line, -1, axis); + if (reference.SubTag is not (0 or 1)) throw unknown; + // An edge of the start cap runs against its profile curve. + int profileEnd = cap == 0 ? reference.SubTag : 1 - reference.SubTag; + return Slot(line, extrusion.ProfileCurves[key].Reversed ? 1 - profileEnd : profileEnd, axis); + // The edge along the extrusion where the sides of two curves meet. + case [2, var first, var second] when axis != ext: + return (Across(first), Across(second)) switch + { + (true, false) => Slot(Line(first), -1, axis), + (false, true) => Slot(Line(second), -1, axis), + _ => throw unknown, + }; + default: + throw unknown; + } + } + + private int Cap(FamilyExtrusionRecord extrusion, bool end) + { + int axis = AxisOf(extrusion.PlaneNormal)!.Value; + double stored = extrusion.PlaneOrigin[axis] + + Math.Sign(extrusion.PlaneNormal[axis]) * (end ? extrusion.End : extrusion.Start); + return Keyed(("cap", extrusion.Id, end), stored, extrusion.Id); + } + + /// The coordinate of an end of a curve, or of a whole line ( -1). Along an axis + /// across a straight line both its ends and the line itself are one coordinate. + private int Slot(FamilySketchLine line, int end, int axis) + { + if (Direction(line) is int along && along != axis) end = -1; + return Keyed(("slot", line.Id, end, axis), end == 1 ? line.End[axis] : line.Start[axis], line.Id); + } + + private int Keyed(object key, double stored, int element) + { + if (!_keys.TryGetValue(key, out int node)) + { + node = Add(stored); + _nodes[node].Elements.Add(element); + _keys.Add(key, node); + } + return Root(node); + } + + private int Add(double stored, bool anchored = false) + { + _nodes.Add(new Node { Parent = _nodes.Count, Stored = stored, Anchored = anchored }); + return _nodes.Count - 1; + } + + private int Root(int node) + { + while (_nodes[node].Parent != node) node = _nodes[node].Parent = _nodes[_nodes[node].Parent].Parent; + return node; + } + + private void Merge(int first, int second, int source) + { + (first, second) = (Root(first), Root(second)); + if (first == second) return; + if (!(Math.Abs(_nodes[first].Stored - _nodes[second].Stored) <= Tolerance)) + throw new Refused("inconsistent", Text(source)); + _nodes[second].Parent = first; + _nodes[first].Anchored |= _nodes[second].Anchored; + _nodes[first].Elements.AddRange(_nodes[second].Elements); + } + + // Joins of curves that are not straight lines along an axis add nothing: what such a curve would hold stays free. + private void Join() + { + foreach (var joint in records.Joints) + { + if (!_lines.TryGetValue(joint.LineId, out var line) || !_lines.TryGetValue(joint.OtherLineId, out var other) + || Direction(line) == null || Direction(other) is not int along) continue; + if (joint.End is not (0 or 1) || joint.OtherEnd is not (-1 or 0 or 1)) + throw Unrecognized($"join of curve {line.Id}"); + for (int axis = 0; axis < 3; axis++) + if (joint.OtherEnd >= 0 || axis != along) + Merge(Slot(line, joint.End, axis), Slot(other, joint.OtherEnd, axis), line.Id); + } + } + + private void CheckConstraints(HashSet modelLines) + { + var profiles = _extrusions.Values.Select(e => e.SketchId).ToHashSet(); + var sketches = profiles.Concat(modelLines.Select(id => _lines[id].SketchId)).ToHashSet(); + foreach (var group in records.Constraints.Where(c => sketches.Contains(c.SketchId)) + .GroupBy(c => (c.SketchId, c.ClassName))) + { + var (sketch, name) = group.Key; + // Why each may stay: point-point is the join of two curves (read in Join), horizontal/vertical is the axis a + // line keeps (Direction), perpendicular lines is the corner of two axis lines; an arc end angle concerns an + // arc, never a straight line read here (an arc in a profile is refused in CheckProfile). + bool known = name is "VarSketchPPConstrObj" or "VarSketchHorVerConstrObj" or "VarSketchArcEndAngleConstrObj" + or "VarSketchLSegPerpToLSegConstrObj" + // The point and the line of this one are read from the joins of the curves. + || name == "VarSketchPtOnLSegConstrObj" && !profiles.Contains(sketch) && group.Count() <= records.Joints + .Count(j => j.OtherEnd == -1 && _lines.TryGetValue(j.LineId, out var l) && l.SketchId == sketch); + if (!known) throw Unrecognized($"{name} of sketch {sketch}"); + } + } + + private void CheckAssociations(HashSet modelLines) + { + foreach (var association in records.Associations) + { + bool onExtrusion = _extrusions.ContainsKey(association.ElementId); + if (!onExtrusion && !modelLines.Contains(association.ElementId) + && !_planes.ContainsKey(association.ElementId)) continue; + if (!onExtrusion || (BuiltInParameter)association.ElementPropertyId is not (BuiltInParameter.MATERIAL_ID_PARAM + or BuiltInParameter.IS_VISIBLE_PARAM or BuiltInParameter.EXTRUSION_START_PARAM + or BuiltInParameter.EXTRUSION_END_PARAM)) + throw Unrecognized($"association {association.ElementPropertyId} of element {association.ElementId}"); + } + } + + // Every record that refers to what takes part is either a relation read here or one that moves nothing. + private void CheckReferrers(HashSet modelLines) + { + var model = _extrusions.Keys.Concat(_extrusions.Values.Select(e => e.SketchId)).Concat(modelLines) + .Concat(modelLines.Select(id => _lines[id].SketchId)) + .Concat(records.Dimensions.SelectMany(d => d.References).Select(r => r.ElementId)) + .Concat(_extrusions.Values.Where(e => e.PlaneHost != null).Select(e => e.PlaneHost!.Value.ElementId)) + .Where(id => id > 0).ToHashSet(); + foreach (var referrer in records.Referrers) + { + if (!model.Contains(referrer.TargetId) || referrer.RecordId == referrer.TargetId + || referrer.Field == "Element.m_assocLevelId") continue; + // Why each class may stay: dimensions and alignments are the relations read in Dimensions; a sketch, an + // extrusion and a sketch plane are the forms themselves; a curve is checked below; views and their companions + // (extents, sun settings) only look at the form; a host, its openings and the connectors, warnings and + // imports on it have their own level or cut the host, and move none of the family's forms. + bool known = referrer.ClassName switch + { + "LinearDimString" or "Alignment" or "VarSketch" or "ExtrusionElem" or "SketchPlane" => true, + "CurveElem" => !modelLines.Contains(referrer.RecordId) || referrer.Field is + "CurveElemDriver.EndInfo.m_elemId" or "CurveElem.m_sketchPlaneId" + or "SketchMembership.GroupMembership.m_groupId" + // The side of a line records the ends that lie on it; each must be the join of that end. + || referrer.Field == "CDJoinInfo.EndInfo.m_elemId" && records.Joints.Any(j => + j.LineId == referrer.TargetId && j.OtherLineId == referrer.RecordId && j.OtherEnd == -1), + "ExtentElem" or "DBViewPlan" or "DBViewSection" or "DBView3d" or "SunAndShadowSettings" or "Opening" + or "ComplexOpening" or "ConnectorElem" or "PostedWarningElem" or "ImportInstance" => true, + var name => TfClassNames.IsSubclassOf(name, "HostObj"), + }; + if (!known) throw Unrecognized($"{referrer.ClassName} {referrer.RecordId}"); + } + } + + private void CheckFormulas() + { + var driving = records.Dimensions.SelectMany(d => d.ParameterIds) + .Concat(records.Associations.Where(a => _extrusions.ContainsKey(a.ElementId) + && a.ElementPropertyId != (long)BuiltInParameter.MATERIAL_ID_PARAM).Select(a => a.FamilyParameterId)); + var formulas = driving.Where(records.FormulaParameterIds.Contains).Distinct().Order().ToList(); + if (formulas.Count > 0) throw Unsupported("formula of parameter " + string.Join(", ", formulas)); + } + + private void PlaceHostFaces(List<(FamilyDimensionRecord Record, int[] Nodes)> dimensions) + { + for (bool placed = true; placed;) + { + placed = false; + foreach (var (_, nodes) in dimensions.Where(d => d.Record.IsAlignment)) + { + var known = nodes.Select(Root).Where(node => !double.IsNaN(_nodes[node].Stored)).ToList(); + if (known.Count == 0) continue; + foreach (int node in nodes.Select(Root).Where(node => double.IsNaN(_nodes[node].Stored))) + { + _nodes[node].Stored = _nodes[known[0]].Stored; + placed = true; + } + } + } + foreach (var (record, nodes) in dimensions) + if (nodes.Any(node => double.IsNaN(_nodes[Root(node)].Stored))) + throw Unrecognized($"host face measured by {record.Id}"); + } + + private void Relate(FamilyDimensionRecord dimension, int[] nodes) + { + double Stored(int i) => _nodes[Root(nodes[i])].Stored; + // 1 or -1 for the way segment i runs along the axis, 0 for one without a length. + int Way(int i) => Math.Abs(Stored(i + 1) - Stored(i)) <= Tolerance ? 0 : Math.Sign(Stored(i + 1) - Stored(i)); + void Hold(long? parameter, int sign, double constant, bool weak, params (int Node, int Coefficient)[] terms) + { + _equations.Add(new([.. terms], parameter, sign, constant, dimension.Id, weak)); + if (!weak) _heldCaps.UnionWith(terms.Select(term => Root(term.Node))); + } + + int segments = dimension.SegmentFlags.Count; + if (!dimension.IsAlignment && (dimension.Flags & FamilyRules.EqualityDimensionFlag) != 0) + { + for (int i = 0; i + 1 < segments; i++) + { + var (first, second) = (Way(i), Way(i + 1)); + if (first == 0 || second == 0) throw Unrecognized($"empty segment of dimension {dimension.Id}"); + Hold(null, 1, 0, false, (nodes[i], -first), (nodes[i + 1], first + second), (nodes[i + 2], -second)); + } + return; + } + for (int i = 0; i < segments; i++) + { + (int, int)[] length = [(nodes[i + 1], 1), (nodes[i], -1)]; + double value = dimension.IsAlignment ? 0 + : (Stored(i + 1) < Stored(i) ? -1 : 1) * Math.Abs(dimension.SegmentValues[i]); + if (dimension.ParameterIds[i] is var parameter && parameter != -1) + { + if (Way(i) == 0) throw Unrecognized($"empty segment of dimension {dimension.Id}"); + Hold(parameter, Way(i), 0, false, length); + } + else if (dimension.SegmentFlags[i] == FamilyRules.LockedSegmentFlag) Hold(null, 1, value, false, length); + else if (!dimension.DrivenSegments.Contains(i)) Hold(null, 1, value, true, length); + } + } + + /// The coordinates of the two ends of an extrusion, the lower one first, and the relations that place them + /// from the sketch plane. An end that a strong relation holds keeps no offset of its own. + private (int Low, int High, bool Swapped) PlaceCaps(FamilyExtrusionRecord extrusion, int axis) + { + int way = Math.Sign(extrusion.PlaneNormal[axis]); + int plane; + if (extrusion.PlaneHost is { } host) + { + int followed = Resolve(host, axis, extrusion.Id); + if (double.IsNaN(_nodes[followed].Stored)) _nodes[followed].Stored = extrusion.PlaneOrigin[axis]; + plane = Add(extrusion.PlaneOrigin[axis]); + _equations.Add(new([(plane, 1), (followed, -1)], null, 1, + extrusion.PlaneOrigin[axis] - _nodes[followed].Stored, extrusion.Id, false)); + } + else plane = Add(extrusion.PlaneOrigin[axis], anchored: true); + + int start = Cap(extrusion, false), end = Cap(extrusion, true); + foreach (var (cap, offset, property) in new[] + { + (start, extrusion.Start, BuiltInParameter.EXTRUSION_START_PARAM), + (end, extrusion.End, BuiltInParameter.EXTRUSION_END_PARAM), + }) + { + long? bound = records.Associations.Where(a => a.ElementId == extrusion.Id + && a.ElementPropertyId == (long)property).Select(a => (long?)a.FamilyParameterId).FirstOrDefault(); + if (bound != null || !_heldCaps.Contains(cap)) + _equations.Add(new([(cap, 1), (plane, -1)], bound, bound != null ? way : 1, + bound != null ? 0 : way * offset, extrusion.Id, false, IsOffset: true)); + } + return _nodes[start].Stored <= _nodes[end].Stored ? (start, end, false) : (end, start, true); + } + + /// [loop][i] is the corner between curves i - 1 and i of the loop; its coordinate along the extrusion is + /// -1. A corner without a join is free. + private int[][][] Vertices(FamilyExtrusionRecord extrusion, int axis) => + [.. extrusion.Loops.Select(loop => Enumerable.Range(0, loop.Count).Select(i => + { + var before = _lines[extrusion.ProfileCurves[loop[(i + loop.Count - 1) % loop.Count]].LineId]; + var curve = extrusion.ProfileCurves[loop[i]]; + var line = _lines[curve.LineId]; + var join = records.Joints.Where(j => j.OtherEnd >= 0).Select(j => + j.LineId == before.Id && j.OtherLineId == line.Id ? (int?)j.End + : j.LineId == line.Id && j.OtherLineId == before.Id ? j.OtherEnd : null) + .FirstOrDefault(end => end != null); + var corner = curve.Reversed ? line.End : line.Start; + return Enumerable.Range(0, 3).Select(c => c == axis ? -1 + : join is int end ? Slot(before, end, c) : Add(corner[c])).ToArray(); + }).ToArray())]; + + // A group of related coordinates without a level or a pinned plane is held by its oldest element, when that is a + // centre or origin plane or a host. + private void Anchor(IEnumerable shown) + { + var parent = new Dictionary(); + int Find(int node) + { + if (!parent.TryGetValue(node, out int up)) parent[node] = up = node; + return up == node ? node : parent[node] = Find(up); + } + foreach (var equation in _equations) + { + int first = Find(Root(equation.Terms[0].Node)); + foreach (var (node, _) in equation.Terms) parent[Find(Root(node))] = Find(first); + } + var used = shown.Select(node => Find(Root(node))).ToHashSet(); + foreach (var group in parent.Keys.ToList().GroupBy(Find).Where(g => used.Contains(g.Key) && g.Count() > 1)) + { + if (group.Any(node => _nodes[node].Anchored)) continue; + var elements = group.SelectMany(node => _nodes[node].Elements).ToList(); + if (elements.Count == 0) continue; + int oldest = elements.Min(); + bool holds = _planes.TryGetValue(oldest, out var plane) && (plane.Origin.Length == 0 + || FamilyRules.IsCentreReferenceName(plane.ReferenceName) || plane.DefinesOrigin); + if (!holds) throw new Refused("unverified-anchor", Text(oldest)); + foreach (int node in group.Where(node => _nodes[node].Elements.Contains(oldest))) + _nodes[node].Anchored = true; + } + } + + private FamilyModel Assemble(Dictionary axes, Dictionary caps, + Dictionary vertices) + { + var variables = new List(); + var index = new Dictionary(); + int Variable(int node) + { + int root = Root(node); + if (!index.TryGetValue(root, out int variable)) + { + index.Add(root, variable = variables.Count); + variables.Add(new(_nodes[root].Stored, _nodes[root].Anchored)); + } + return variable; + } + var equations = _equations.Select(e => new FamilyEquation( + [.. e.Terms.Select(term => new FamilyTerm(Variable(term.Node), term.Coefficient))], + e.Parameter, e.Sign, e.Constant, e.Source, e.IsWeak, e.IsOffset)).ToList(); + + var extrusions = records.Extrusions.Select(extrusion => + { + var (low, high, swapped) = caps[extrusion.Id]; + int lower = Variable(low); + var loops = vertices[extrusion.Id].Select(loop => (IReadOnlyList)loop.Select(corner => + { + int Component(int axis) => corner[axis] < 0 ? lower : Variable(corner[axis]); + return new FamilyVertex(Component(0), Component(1), Component(2)); + }).ToList()).ToList(); + long? Bound(BuiltInParameter property) => records.Associations + .Where(a => a.ElementId == extrusion.Id && a.ElementPropertyId == (long)property) + .Select(a => (long?)a.FamilyParameterId).FirstOrDefault(); + return new FamilyExtrusion(extrusion.Id, loops, axes[extrusion.Id], lower, Variable(high), + Materials(extrusion, swapped), Bound(BuiltInParameter.MATERIAL_ID_PARAM), + Bound(BuiltInParameter.IS_VISIBLE_PARAM)); + }).ToList(); + return new(variables, equations, extrusions); + } + + /// The stored materials by the faces of the model, whose start cap is the lower one. + private static Dictionary Materials(FamilyExtrusionRecord extrusion, bool swapped) + { + var materials = new Dictionary(); + foreach (var (tag, material) in extrusion.FaceMaterials) + { + if (!extrusion.FaceHistory.TryGetValue(tag, out var face)) + throw Unrecognized($"face tag {tag} of element {extrusion.Id}"); + for (int loop = 0; loop < extrusion.Loops.Count; loop++) + { + FamilyFaceKey? key = face switch + { + [1] or [2] => new((face[0] == 1) != swapped ? FamilyFaceKind.StartCap : FamilyFaceKind.EndCap, loop), + [3, var curve] when extrusion.Loops[loop].ToList().IndexOf(curve) is >= 0 and var segment => + new(FamilyFaceKind.Side, loop, segment), + _ => null, + }; + // Two faces at one end with different materials cannot be told apart by their loops. + if (key is { } found && !materials.TryAdd(found, material) && materials[found] != material) + throw Unsupported($"materials of element {extrusion.Id}"); + } + } + return materials; + } + } +} diff --git a/src/RvtIO/Families/FamilyRecordReader.cs b/src/RvtIO/Families/FamilyRecordReader.cs new file mode 100644 index 00000000..40ac23b0 --- /dev/null +++ b/src/RvtIO/Families/FamilyRecordReader.cs @@ -0,0 +1,300 @@ +using System.Buffers.Binary; +using OpenMcdf; +using RvtIO.BuiltIns; +using RvtIO.Lookup; +using RvtIO.Model; +using RvtIO.Parsing; +using RvtIO.Writing; + +namespace RvtIO.Families; + +/// Reads the of a family document from the records of its elements and the model read from +/// it. +internal static class FamilyRecordReader +{ + private sealed record ElementRecord(string ClassName, bool IsForm, bool IsCombination, bool Exact, long? FamilyId, + bool Cutting, long? VisibilityFlags, bool VisibilityDriven, long? GroupId, bool IsMember, bool MemberShownAlways, + bool CutByOwnStep, long[] Members); + + /// The facts of the elements of the family (its id in the file). + /// names the partition of the current record of every element that several partitions hold. + /// A file whose records cannot be read gives facts without settings, which leaves the shape incomplete and says so. + internal static FamilyData Read(RootStorage root, RevitFileInfo info, ElementIdMap? ids, long ownerId, + IReadOnlyDictionary? currentCopies) + { + var elements = new Dictionary(); + foreach (var element in info.Elements) + if (!element.IsBlockOnly && !(info.ElemTableIsExact && element.IsDiscovered)) elements.TryAdd(element.Id, element); + + var records = new Dictionary(); + try { ReadRecords(root, elements, ids, currentCopies, records); } + // What was read before the failure stands; every other element is reported as unrecognised below. + catch (Exception ex) when (ex is RvtWriteRefusedException || MalformedInput.Is(ex)) { } + + var own = records.Where(pair => pair.Value is { Exact: true } record && record.FamilyId == ownerId) + .ToDictionary(pair => pair.Key, pair => pair.Value!); + var memberships = Memberships(own, ids); + + var facts = new List(); + foreach (var element in elements.Values) + { + bool hasGeometry = HasGeometry(element); + if (own.TryGetValue(element.Id, out var record)) + { + var (shown, hidden) = record.IsCombination + ? Combined(element.Id, own, memberships, elements, []) + : Settings(element, record); + bool combined = memberships.ContainsKey(element.Id); + // A member whose combination was not read would be left out without the shape that replaces it. + if (record.IsMember && !combined) shown = null; + facts.Add(new(element.Id, record.ClassName, record.IsForm, hasGeometry, record.Cutting, shown, hidden, + combined, combined && record.MemberShownAlways, record.CutByOwnStep, + FamilyRules.IsDrawnInViewsOnly(record.ClassName, element.Category), + FamilyRules.PlacesOnlyForms(element.Id, Body(element), + id => own.TryGetValue(id, out var placed) && placed.IsForm))); + continue; + } + // The content of a nested family names that family: it is not content of this one. + var other = records.GetValueOrDefault(element.Id); + if (other != null ? other.FamilyId is > 0 && other.FamilyId != ownerId + : element.SerializedFamilyId is > 0 && element.SerializedFamilyId != info.FamilyOwnerId) continue; + // Its record was not read exactly: reported when it has geometry or is a form that names this family. + string className = other?.ClassName ?? element.RootClassName ?? "?"; + bool form = other?.IsForm ?? FamilyRules.FormClasses.Any(name => TfClassNames.IsSubclassOf(className, name)); + if (hasGeometry || form && (other != null || element.SerializedFamilyId == info.FamilyOwnerId)) + facts.Add(new(element.Id, className, form, hasGeometry, false, null, null, + DrawnInViewsOnly: FamilyRules.IsDrawnInViewsOnly(className, element.Category))); + } + var (types, typesError) = ReadTypes(root, ownerId, ids, currentCopies); + var relations = types is { Types.Count: > 0 } + ? FamilyRelationReader.Read(root, elements, ids, ownerId, currentCopies, facts) : null; + return new FamilyData { Elements = facts, Types = types, TypesError = typesError, Records = relations }; + } + + /// The types of the family from its record, with their parameters. A family that stores + /// no types gives neither types nor a reason; a table that is not read exactly gives no types and the reason. + internal static (RvtFamilyTypes? Types, string? Error) ReadTypes(RootStorage root, long ownerId, ElementIdMap? ids, + IReadOnlyDictionary? currentCopies) + { + try + { + if (TfSchemaReader.Read(root) is not { } schema) + throw ParameterWriter.Unverified("The family schema could not be read exactly."); + var formats = new FormatsSchema(schema); + if (PartitionFraming.TagsOf(formats) is not { } tags || ElemTableLayout.IdWidth(formats) is not int idWidth) + throw ParameterWriter.Unverified("The partition layout of the family could not be read."); + var walker = new WideBlockWalker(schema, StandaloneFamilyParameterWriter.CaptureKey, ["ForgeTypeId", "FormatOptions", "AUnits"]); + walker.UseEntitySchemas(EntitySchemaReader.Read(root, schema)); + + // The family record and the records of the parameter definitions; null for an element with copies that differ. + var bodies = new Dictionary(); + ParameterWriter.ScanPartitions(root, tags, idWidth, (partition, record) => + { + if (currentCopies != null && currentCopies.TryGetValue(record.Owner, out int current) && current != partition) return; + if (record.Block != 0 || record.Channel != 102 || record.Body.Length < 2 || record.Owner > long.MaxValue) return; + long owner = (long)record.Owner; + int cls = BinaryPrimitives.ReadUInt16LittleEndian(record.Body.Span); + if (owner != ownerId && !walker.IsA(cls, "ParamElem")) return; + byte[] data = record.Body.ToArray(); + if (!bodies.TryAdd(owner, data) && bodies[owner] is { } first && !data.AsSpan().SequenceEqual(first)) + bodies[owner] = null; + }, new ParameterWriter.Pending()); + + if (bodies.GetValueOrDefault(ownerId) is not { } body) + throw ParameterWriter.Unverified("The record of the family was not found or has copies that differ."); + int familyClass = BinaryPrimitives.ReadUInt16LittleEndian(body); + var family = walker.Run(body, 0, body.Length, familyClass); + if (walker.Class(familyClass)?.Name != "Family" || UserParameterWriter.Integer(family, "m_id") != ownerId) + throw ParameterWriter.Unverified("The record of the family could not be read exactly."); + + var (stored, saved) = FamilyTypeTable.Read(walker, family); + if (stored.Length == 0) return (null, null); + var definitions = new Dictionary(); + var types = stored.Select(type => + { + if (type.Values.Rows.Select(row => row.Id).Distinct().Count() != type.Values.Rows.Length) + throw ParameterWriter.Unverified($"The family type \"{type.Name}\" stores a parameter twice."); + return new RvtFamilyType(type.Name, type.Values.Rows.Select(row => + { + if (!definitions.TryGetValue(row.Id, out var definition)) + definitions.Add(row.Id, definition = Describe(walker, bodies, ids, row.Id)); + return ToParameter(definition, row, ids); + }).ToArray()); + }).ToArray(); + return (new RvtFamilyTypes(saved, types), null); + } + catch (Exception ex) when (ex is RvtWriteRefusedException || MalformedInput.Is(ex)) + { + return (null, ex.Message); + } + } + + /// What every type says alike about one parameter. + private sealed record TypeParameter(int Key, Definition Definition, StorageType Storage, Parameter.Metadata? Units); + + /// A parameter of the family is described by its definition record; one that is not read exactly keeps only its + /// id. A built-in parameter has a kind of value only when that kind is established. + private static TypeParameter Describe(WideBlockWalker walker, Dictionary bodies, ElementIdMap? ids, long id) + { + if (id < 0) + { + if (id < int.MinValue) throw ParameterWriter.Unverified($"A family type refers to the unknown parameter {id}."); + string? builtIn = BipNames.Lookup.GetValueOrDefault((int)id); + var storage = (BuiltInParameter)(int)id is BuiltInParameter.FAMILY_WIDTH_PARAM or BuiltInParameter.FAMILY_HEIGHT_PARAM + ? StorageType.Double : StandaloneFamilyParameterWriter.VerifiedStorage(id) ?? StorageType.None; + return new((int)id, new Definition { Id = (int)id, Name = builtIn, BuiltInParameter = builtIn }, storage, + storage == StorageType.Double ? RvtFileReader.DisplayUnits(null, builtIn) : null); + } + + int key = Key(ids, id) ?? throw ParameterWriter.Unverified($"A family type refers to parameter {id}, which has no element key."); + var unknown = new TypeParameter(key, new Definition { Id = key }, StorageType.None, null); + if (bodies.GetValueOrDefault(id) is not { Length: >= 2 } data) return unknown; + var walk = walker.Run(data, 0, data.Length, BinaryPrimitives.ReadUInt16LittleEndian(data)); + if (!walk.Exact || UserParameterWriter.Integer(walk, "m_id") != id + || UserParameterWriter.Integer(walk, "ParamElem.m_pParamDef") is not long tag + || walk.Queue.Select((cls, index) => (cls, index)).Where(p => p.cls == tag).ToArray() is not [{ index: var slot }] + || UserParameterWriter.Integer(walk, "ParamDef.m_paramElemId", slot) != id + || walk.Captures.Where(c => c.QueueIndex == slot && c.Key == "ParamDef.m_caption").ToArray() is not [{ Text: { } caption }]) + return unknown; + + var specField = walk.Captures.FirstOrDefault(c => c.QueueIndex == slot && c.Key == "ParamDefValue.m_specTypeId"); + string? spec = specField.Text is { Length: > 0 } text ? text + // Releases before the spec ids number the quantity. + : ParameterMeasurement.Spec(walk, slot) switch + { + UnitType.UT_Length => "autodesk.spec.aec:length", + UnitType.UT_Area => "autodesk.spec.aec:area", + UnitType.UT_Volume => "autodesk.spec.aec:volume", + UnitType.UT_Angle => "autodesk.spec.aec:angle", + UnitType.UT_Number => "autodesk.spec.aec:number", + _ => null, + }; + var kind = TfClassNames.TryIdOf(walker.Class((int)tag)?.Name ?? "", out int definitionClass) + ? UserParameterDefinition.StorageOf(definitionClass, spec != null || LegacyQuantity(walk, slot)) + : StorageType.None; + return new(key, new Definition { Id = key, Name = caption }, kind, + kind == StorageType.Double && spec != null ? RvtFileReader.DisplayUnits(spec, null) : null); + } + + private static bool LegacyQuantity(WideBlockWalker.Walk walk, int slot) => + walk.Captures.Any(c => c.QueueIndex == slot && c.Key == "ParamDefValue.m_unitType"); + + private static Parameter ToParameter(TypeParameter parameter, LoadedFamilyParameterWriter.NamedValue row, ElementIdMap? ids) + { + var result = new Parameter(parameter.Definition) { Id = parameter.Key, StorageType = parameter.Storage }; + switch (parameter.Storage) + { + case StorageType.String: result.Value = row.Value(StorageType.String).Text; break; + case StorageType.Double: result.Value = Parameter.BoxParsedValue(row.Value(StorageType.Double).Real); break; + case StorageType.Integer: result.Value = Parameter.BoxParsedValue(checked((int)row.Value(StorageType.Integer).Integer)); break; + case StorageType.ElementId: + long source = row.Value(StorageType.ElementId).Integer; + int? reference = source <= 0 ? source >= int.MinValue ? (int)source : null : Key(ids, source); + result.Value = reference; + if (reference != source) result.NativeElementId = source; + break; + } + if (parameter.Units is { } units) result.SetDisplayUnits(units); + return result; + } + + /// The combination of every member, by the lists of the combinations and by the records of the members. + private static Dictionary Memberships(Dictionary own, ElementIdMap? ids) + { + var memberships = new Dictionary(); + foreach (var (key, record) in own) + { + foreach (long id in record.Members) + if (Key(ids, id) is int member) memberships.TryAdd(member, key); + if (record.IsMember && record.GroupId is long group && Key(ids, group) is int combination + && own.TryGetValue(combination, out var holder) && holder.IsCombination) + memberships.TryAdd(key, combination); + } + return memberships; + } + + /// A combination has no settings of its own: it shows the forms it combines. What Revit shows of it is + /// established only when every solid member is shown. + private static (bool? Shown, bool? Hidden) Combined(int key, Dictionary own, + Dictionary memberships, Dictionary elements, HashSet visited) + { + if (!visited.Add(key)) return (null, null); + foreach (var (member, combination) in memberships) + { + if (combination != key) continue; + if (!own.TryGetValue(member, out var record)) return (null, null); + if (record.Cutting) continue; + var settings = record.IsCombination ? Combined(member, own, memberships, elements, visited) + : Settings(elements[member], record); + if (settings != (true, false)) return (null, null); + } + return (true, false); + } + + private static (bool? Shown, bool? Hidden) Settings(Element element, ElementRecord record) + { + object? visible = element.Parameters.FirstOrDefault(p => p.Id == (int)BuiltInParameter.IS_VISIBLE_PARAM)?.Value; + if (record.VisibilityFlags is not long flags || visible is not (0 or 1)) return (null, null); + bool checkedOff = visible is 0; + return ((flags & FamilyRules.ShownInFineFlag) != 0 && (record.VisibilityDriven || !checkedOff), + record.VisibilityDriven && checkedOff); + } + + internal static GeometryData? Body(Element element) => element.SerializedComputedSymbolGeometry ?? element.Geometry; + + private static bool HasGeometry(Element element) => + Body(element) is { } body + && ((body.FacesOnDemand?.Count ?? body.Faces.Count) > 0 || body.ExactMappedInstances is { Count: > 0 }); + + private static int? Key(ElementIdMap? ids, long id) => + ids != null ? ids.TryGetKey(id, out int key) ? key : null + : id is > 0 and <= int.MaxValue ? (int)id : null; + + /// The records of the elements, by element key; null for an element with more than one record. + private static void ReadRecords(RootStorage root, Dictionary elements, ElementIdMap? ids, + IReadOnlyDictionary? currentCopies, Dictionary records) + { + if (TfSchemaReader.Read(root) is not { } schema) return; + var formats = new FormatsSchema(schema); + if (PartitionFraming.TagsOf(formats) is not { } tags || ElemTableLayout.IdWidth(formats) is not int idWidth) return; + var walker = new WideBlockWalker(schema, CaptureKey, []); + walker.UseEntitySchemas(EntitySchemaReader.Read(root, schema)); + var bodies = new Dictionary(); + ParameterWriter.ScanPartitions(root, tags, idWidth, (partition, record) => + { + if (currentCopies != null && currentCopies.TryGetValue(record.Owner, out int current) && current != partition) return; + if (record.Block != 0 || record.Channel != 102 || record.Body.Length < 2 || record.Owner > long.MaxValue + || Key(ids, (long)record.Owner) is not int key || !elements.TryGetValue(key, out var element)) return; + int cls = BinaryPrimitives.ReadUInt16LittleEndian(record.Body.Span); + bool form = FamilyRules.FormClasses.Any(name => walker.IsA(cls, name)); + if (!form && !HasGeometry(element)) return; + byte[] data = record.Body.ToArray(); + // Equal copies are interchangeable; copies that differ leave the element unrecognised. + if (!bodies.TryAdd(key, data)) + { + if (!data.AsSpan().SequenceEqual(bodies[key])) records[key] = null; + return; + } + var walk = walker.Run(data, 0, data.Length, cls); + long? Value(string name) => walk.Captures.Where(c => c.Key == name).Select(c => (long?)c.Integer).FirstOrDefault(); + records.Add(key, new(walker.Class(cls)?.Name ?? "?", form, walker.IsA(cls, "GeomCombination"), walk.Exact, + Value("Element.m_famId"), Value("GenSweep.m_cutting") is not (null or 0), + Value("FamElemVisibility.m_flags"), + walk.Captures.Any(c => c.Key == "ParamIdPair.m_elemPropId" && c.Integer == (int)BuiltInParameter.IS_VISIBLE_PARAM), + Value("GroupMembership.m_groupId"), Value("GeomCombinationMembership.m_alwaysVisible") != null, + Value("GeomCombinationMembership.m_alwaysVisible") is not (null or 0), + walk.Captures.Any(c => c.Key is "GeomStepList.m_bRepCutOutGList#" or "GeomStepList.m_bRepPostCutOutGList#" + && c.Integer > 0), + walk.Captures.Where(c => c.Key == "AddGeomToCombinationGStep.m_memberId").Select(c => c.Integer).ToArray())); + }, new ParameterWriter.Pending()); + } + + private static string? CaptureKey(SchemaClass declaring, SchemaField field) => (declaring.Name, field.Name) switch + { + ("Element", "m_famId") or ("GenSweep", "m_cutting") or ("FamElemVisibility", "m_flags") or + ("ParamIdPair", "m_elemPropId") or ("GroupMembership", "m_groupId") or + ("GeomCombinationMembership", "m_alwaysVisible") or ("AddGeomToCombinationGStep", "m_memberId") or + ("GeomStepList", "m_bRepCutOutGList" or "m_bRepPostCutOutGList") => declaring.Name + "." + field.Name, + _ => null, + }; +} diff --git a/src/RvtIO/Families/FamilyRecords.cs b/src/RvtIO/Families/FamilyRecords.cs new file mode 100644 index 00000000..c0c10fdd --- /dev/null +++ b/src/RvtIO/Families/FamilyRecords.cs @@ -0,0 +1,53 @@ +namespace RvtIO.Families; + +/// What a dimension or an alignment measures: an element, a tag of its geometry and a sub tag. The sub tag is -1 +/// for a whole face, edge or line, and 0 or 1 for an end of a line or an edge. +internal readonly record struct FamilyReference(int ElementId, int GeometryTag, int SubTag); + +/// A linear dimension or an alignment. Segment i lies between references i and i + 1 along Axis. +/// ParameterIds holds -1 for a segment without a label; DrivenSegments are those the family's dimension +/// manager computes from others. +internal sealed record FamilyDimensionRecord(int Id, bool IsAlignment, double[] Axis, long Flags, + IReadOnlyList SegmentFlags, IReadOnlyList References, IReadOnlyList ParameterIds, + IReadOnlyList SegmentValues, IReadOnlySet DrivenSegments); + +/// A curve element: a line of a sketch, or one in no sketch (SketchId 0). +internal sealed record FamilySketchLine(int Id, int SketchId, bool IsStraight, double[] Start, double[] End); + +/// End End of a curve joins end OtherEnd of another; OtherEnd -1: it lies on that curve. +internal sealed record FamilySketchJoint(int LineId, int End, int OtherLineId, int OtherEnd); + +/// The class of a constraint object of the solver of a sketch. +internal sealed record FamilySketchConstraint(int SketchId, string ClassName); + +/// A reference plane, a level or a host element. A host has no plane of its own: Origin and Normal +/// are empty. +internal sealed record FamilyPlaneRecord(int ElementId, string ClassName, long ReferenceName, double[] Origin, + double[] Normal, bool Pinned = false, bool DefinesOrigin = false); + +/// The sketch line a profile curve copies; Reversed when the curve runs from the line's end to its +/// start. +internal readonly record struct FamilyProfileCurve(int LineId, bool Reversed); + +/// An extrusion: its start and end offsets from the sketch plane along its normal, what the sketch plane follows +/// (null when nothing), its profile loops as keys of ProfileCurves in order, and the history of its faces and +/// edges by their geometry tags. FaceMaterials gives the stored material of each face tag. +internal sealed record FamilyExtrusionRecord(int Id, int SketchId, double Start, double End, double[] PlaneOrigin, + double[] PlaneNormal, FamilyReference? PlaneHost, IReadOnlyList> Loops, + IReadOnlyDictionary ProfileCurves, IReadOnlyDictionary FaceHistory, + IReadOnlyDictionary EdgeHistory, IReadOnlyDictionary FaceMaterials); + +/// A field of a record of the family that refers to another element. +internal sealed record FamilyReferrer(int RecordId, string ClassName, string Field, int TargetId); + +/// A property of an element that a family parameter drives. +internal sealed record FamilyAssociation(int ElementId, long ElementPropertyId, long FamilyParameterId); + +/// What the records of a family say about the placing of its forms, as plain values. +/// UnsupportedContent names what is shown and cannot be recomputed. +internal sealed record FamilyRecords(IReadOnlyList Dimensions, + IReadOnlyList Lines, IReadOnlyList Joints, + IReadOnlyList Constraints, IReadOnlyList Planes, + IReadOnlyList Extrusions, IReadOnlyList Referrers, + IReadOnlyList Associations, IReadOnlySet FormulaParameterIds, + IReadOnlyList UnsupportedContent); diff --git a/src/RvtIO/Families/FamilyRelationReader.cs b/src/RvtIO/Families/FamilyRelationReader.cs new file mode 100644 index 00000000..1455ae89 --- /dev/null +++ b/src/RvtIO/Families/FamilyRelationReader.cs @@ -0,0 +1,569 @@ +using System.Buffers.Binary; +using OpenMcdf; +using RvtIO.Model; +using RvtIO.Parsing; +using RvtIO.Writing; + +namespace RvtIO.Families; + +/// Reads the of a family document: what places its forms, as the records of its +/// elements and of the family say it. A record that is not read as expected is named in +/// . +internal static class FamilyRelationReader +{ + /// The records of the family (its id in the file) among + /// ; null when the records of the file cannot be read. + internal static FamilyRecords? Read(RootStorage root, IReadOnlyDictionary elements, ElementIdMap? ids, + long ownerId, IReadOnlyDictionary? currentCopies, IReadOnlyList facts) + { + try { return new Reader(root, elements, ids, ownerId, currentCopies).Read(facts); } + catch (Exception ex) when (ex is RvtWriteRefusedException or Unread || MalformedInput.Is(ex)) { return null; } + } + + private sealed class Unread(string detail) : Exception(detail); + + /// A field the reader needs that a class of the schema lacks: another version of Revit may name it otherwise, + /// and then nothing would be read without a sign of it, so no association would refuse a form. Null when there is + /// none; a class the schema lacks has no records. + internal static string? MissingField(SchemaDocument schema) + { + var declared = schema.Classes.ToLookup(c => c.Name); + return Fields.Concat(WholeArrays) + .Append("FamDimConstrMgrImpl.m_drivenDimSegs").Append("ElementIdIntPair.m_elementId") + .Append("ElementIdIntPair." + string.Join('|', PairNumberFields)) + .FirstOrDefault(needed => + { + var (name, fields) = (needed[..needed.IndexOf('.')], needed[(needed.IndexOf('.') + 1)..].Split('|')); + return declared[name].Any() && !declared[name].Any(c => c.Fields.Any(f => fields.Contains(f.Name))); + }); + } + + /// The number of an element and number pair: newer files hold it as m_int64. + private static readonly string[] PairNumberFields = ["m_int", "m_int64"]; + + /// The fields read besides the references to elements. + private static readonly HashSet Fields = + [ + "Element.m_famId", "Element.m_locked", "Element.m_pParamValueSetDouble", + "Dimension.m_flags", "Dimension.m_ArrSegInfo", "DimSegInfo.m_pDimSegInfoBase", "DimSegInfo.m_paramId", + "DimSegInfo.m_flags", "DimSegValue.m_value", "WitnessRefInfo.m_pWitnessRef", "GeomRef.m_elemId", + "GeomRef.m_geomTag", "GeomRef.m_subTag", "Alignment.m_constrDir", "LinearConstraint.m_pDimLine", + "GLine.m_origin", "GLine.m_dirVec", "GCurve.m_endParams", "GInfo.m_tag", + "CurveElem.m_pCurveDriver", "CurveDriver.m_pCrv", "GroupMembership.m_groupId", "EndInfo.m_elemId", + "EndInfo.m_joinedEnd", "IndexJoinPair.m_index", + "DatumPlane.m_pSurface", "Plane.m_origin", "Plane.m_xVec", "Plane.m_yVec", "RefPlaneBase.m_refName", + "RefPlaneBase.m_definesOrigin", + "Sketch.m_pPlane", "Sketch.m_sketchPlaneId", "Sketch.m_elemIdsPairSet", "ElementIdPlusIndex.m_elementId", + "ElementIdPlusIndex.m_index", "CurveHistEntry.m_id", "CurveHist.m_keys", + "SketchPlane.m_oPlaneRef", "OneElementMovablePlaneRef.m_datumPlaneId", + "ExtrusionHelper.m_sketchId", "ParamValueDouble.m_paramId", "ParamValueDouble.m_value", "FaceHistEntry.m_id", + "FaceHist.m_keys", "EdgeHistEntry.m_id", "EdgeHist.m_keys", + "ParamIdPair.m_famParamId", "ParamIdPair.m_elemPropId", + ]; + + /// Counted arrays that are read whole besides the arrays of references to elements. + private static readonly HashSet WholeArrays = ["ElementExtrusionHelper.m_pCurveLoops", "CurveLoop.m_curves"]; + + /// One walked record, with its captured values by the object (slot) that holds them; -1 is the record + /// itself. + private sealed class Record + { + private readonly WideBlockWalker _walker; + private readonly WideBlockWalker.Walk _walk; + private readonly ILookup _slots; + + public Record(int key, string className, WideBlockWalker walker, WideBlockWalker.Walk walk) + { + (Key, ClassName, _walker, _walk) = (key, className, walker, walk); + _slots = walk.Captures.ToLookup(c => c.QueueIndex, + c => (c.Key.StartsWith(WideBlockWalker.AllItemsKeyPrefix, StringComparison.Ordinal) + ? c.Key[WideBlockWalker.AllItemsKeyPrefix.Length..] : c.Key, c)); + } + + public int Key { get; } + public string ClassName { get; } + + public string SlotClass(int slot) => + slot < 0 ? ClassName : _walker.Class(_walk.Queue[slot])?.Name ?? "?"; + + public IEnumerable Slots => Enumerable.Range(0, _walk.Queue.Count); + + public IEnumerable<(string Name, WideBlockWalker.Capture Value)> In(int slot) => _slots[slot]; + + public IEnumerable<(int Slot, string Name, WideBlockWalker.Capture Value)> Values => + _slots.SelectMany(group => group.Select(item => (group.Key, item.Name, item.Value))); + + private Unread Missing(string name) => new($"{name} of {ClassName} {Key}"); + + public WideBlockWalker.Capture? Find(string name, int slot) => + _slots[slot].Where(item => item.Name == name).Select(item => (WideBlockWalker.Capture?)item.Value) + .FirstOrDefault(); + + public long Integer(string name, int slot = -1) => Find(name, slot)?.Integer ?? throw Missing(name); + + public double Real(string name, int slot) => Find(name, slot)?.Real ?? throw Missing(name); + + public double[] Vector(string name, int slot) => + [Real(name + "@0", slot), Real(name + "@1", slot), Real(name + "@2", slot)]; + + /// The slot a pointer capture queued. + public int Target(WideBlockWalker.Capture pointer) => + pointer is { Kind: WideBlockWalker.CaptureKind.PointerClass, Integer: > 0, QueuePosition: >= 0 } + && pointer.QueuePosition < _walk.Queue.Count && _walk.Queue[pointer.QueuePosition] == pointer.Integer + ? pointer.QueuePosition : throw Missing(pointer.DeclaringClass + "." + pointer.Field); + + public int Pointer(string name, int slot = -1) => Target(Find(name, slot) ?? throw Missing(name)); + + /// The slots of a counted array of pointers, all of them. + public int[] Pointers(string name, int slot) + { + var items = _slots[slot].Where(item => item.Name.StartsWith(name + "@", StringComparison.Ordinal)) + .Select(item => Target(item.Value)).ToArray(); + return items.Length == Integer(name + "#", slot) ? items : throw Missing(name); + } + } + + private sealed class Reader(RootStorage root, IReadOnlyDictionary elements, ElementIdMap? ids, + long ownerId, IReadOnlyDictionary? currentCopies) + { + private readonly Dictionary _own = []; + private readonly List _unsupported = []; + + public FamilyRecords? Read(IReadOnlyList facts) + { + if (TfSchemaReader.Read(root) is not { } schema || MissingField(schema) != null + || schema.Classes.FirstOrDefault(c => c.Name == "ElementId") is not { Id: var elementId }) return null; + var formats = new FormatsSchema(schema); + if (PartitionFraming.TagsOf(formats) is not { } tags || ElemTableLayout.IdWidth(formats) is not int idWidth) + return null; + + var references = schema.Classes.SelectMany(c => c.Fields + .Where(f => f.Ref == elementId || Holds(f.Args, elementId)).Select(f => c.Name + "." + f.Name)).ToHashSet(); + var walker = new WideBlockWalker(schema, (c, f) => + { + string name = c.Name + "." + f.Name; + return references.Contains(name) || WholeArrays.Contains(name) ? WideBlockWalker.AllItemsKeyPrefix + name + : Fields.Contains(name) ? name : null; + }, []); + var entities = EntitySchemaReader.Read(root, schema); + walker.UseEntitySchemas(entities); + + var bodies = new Dictionary(); + var differing = new HashSet(); + byte[]? familyBody = null; + ParameterWriter.ScanPartitions(root, tags, idWidth, (partition, record) => + { + if (currentCopies != null && currentCopies.TryGetValue(record.Owner, out int current) + && current != partition) return; + if (record.Block != 0 || record.Channel != 102 || record.Body.Length < 2 || record.Owner > long.MaxValue) + return; + if ((long)record.Owner == ownerId) { familyBody ??= record.Body.ToArray(); return; } + if (Key((long)record.Owner) is not int key || !elements.ContainsKey(key)) return; + if (!bodies.TryGetValue(key, out var first)) bodies.Add(key, record.Body.ToArray()); + else if (!record.Body.Span.SequenceEqual(first)) differing.Add(key); + }, new ParameterWriter.Pending()); + + foreach (var (key, body) in bodies.OrderBy(pair => pair.Key)) + { + int cls = BinaryPrimitives.ReadUInt16LittleEndian(body); + var walk = walker.Run(body, 0, body.Length, cls); + var family = walk.Captures.FirstOrDefault(c => c.AtRoot && c.Key.EndsWith("Element.m_famId", StringComparison.Ordinal)); + // The record of another family: the content of a nested one. + if (family.Key != null && family.Integer != ownerId) continue; + string className = walker.Class(cls)?.Name ?? "?"; + if (!walk.Exact || differing.Contains(key)) + { + if (family.Key != null || elements[key].SerializedFamilyId == ownerId) + _unsupported.Add($"record of {className} {key}"); + continue; + } + if (family.Key != null) _own.Add(key, new(key, className, walker, walk)); + } + + if (familyBody == null) return null; + var (driven, formulas) = Family(schema, entities, familyBody); + AddShownContent(facts); + + var lines = new List(); + var joints = new List(); + var constraints = new List(); + var planes = new List(); + var dimensions = new List(); + var referrers = new HashSet(); + var associations = new List(); + foreach (var record in _own.Values) + { + References(record, references, referrers); + try + { + Associations(record, associations); + if (record.ClassName == "CurveElem") lines.Add(Line(record, joints)); + else if (record.ClassName is "LinearDimString" or "Alignment") dimensions.Add(Dimension(record, driven)); + else if (record.ClassName is "RefPlane" or "Level") planes.Add(Plane(record)); + else if (TfClassNames.IsSubclassOf(record.ClassName, "HostObj")) + planes.Add(new(record.Key, record.ClassName, 0, [], [])); + else if (TfClassNames.IsSubclassOf(record.ClassName, "Sketch")) + constraints.AddRange(record.Slots.Select(record.SlotClass) + .Where(name => name.Contains("Constr", StringComparison.Ordinal)) + .Select(name => new FamilySketchConstraint(record.Key, name))); + } + catch (Unread unread) { _unsupported.Add(unread.Message); } + } + + var byId = lines.ToDictionary(line => line.Id); + var extrusions = new List(); + foreach (var fact in facts.Where(IsRecomputed)) + { + try { extrusions.Add(Extrusion(fact.ElementId, byId)); } + catch (Unread unread) { _unsupported.Add(unread.Message); } + } + + return new(dimensions, lines, joints, constraints, planes, extrusions, [.. referrers], associations, + formulas, _unsupported); + } + + private static bool Holds(List? arguments, int reference) => + arguments != null && arguments.Any(a => a.Ref == reference || Holds(a.Args, reference)); + + private int? Key(long id) => + ids != null ? ids.TryGetKey(id, out int key) ? key : null + : id is > 0 and <= int.MaxValue ? (int)id : null; + + /// The key of what a reference names; ids that name nothing stay as stored, and an id without an element + /// gets a number no element has. + private int Referenced(long id) => id <= 0 ? (int)Math.Max(id, int.MinValue) : Key(id) ?? int.MinValue; + + private long ParameterKey(long id) => id <= 0 ? id : Referenced(id); + + /// The segments the dimension manager computes from others, by dimension, and the parameters a formula + /// or a measurement sets. + private (Dictionary> Driven, HashSet Formulas) Family(SchemaDocument schema, + IReadOnlyDictionary entities, byte[] body) + { + var walker = new WideBlockWalker(schema, (c, f) => c.Name is "FamDimConstrMgrImpl" or "ElementIdIntPair" + ? c.Name + "." + f.Name : StandaloneFamilyParameterWriter.CaptureKey(c, f), + ["ForgeTypeId", "FormatOptions", "AUnits"]); + walker.UseEntitySchemas(entities); + var walk = walker.Run(body, 0, body.Length, BinaryPrimitives.ReadUInt16LittleEndian(body)); + var (types, _) = FamilyTypeTable.Read(walker, walk); + var formulas = types.SelectMany(type => type.Values.Rows).Where(row => row.IsDriven) + .Select(row => ParameterKey(row.Id)).ToHashSet(); + + var driven = new Dictionary>(); + var manager = walk.Captures.Where(c => c.DeclaringClass is "FamDimConstrMgrImpl" or "ElementIdIntPair") + .SkipWhile(c => c.Key != "FamDimConstrMgrImpl.m_drivenDimSegs#").ToArray(); + if (manager.Length == 0) return (driven, formulas); + var pairs = manager.Skip(1).TakeWhile(c => c.DeclaringClass == "ElementIdIntPair").ToArray(); + long? element = null; + int read = 0; + foreach (var capture in pairs) + { + if (read == manager[0].Integer) break; + if (capture.Field == "m_elementId") element = capture.Integer; + else if (PairNumberFields.Contains(capture.Field) && element is long id) + { + int dimension = Referenced(id); + if (!driven.TryGetValue(dimension, out var segments)) driven.Add(dimension, segments = []); + segments.Add((int)capture.Integer); + (element, read) = (null, read + 1); + } + } + if (read != manager[0].Integer) throw new Unread("driven dimension segments"); + return (driven, formulas); + } + + /// An extrusion whose faces are computed: a solid one the family shows in a 3D view at the Fine detail + /// level, in some type or in all. + private static bool IsRecomputed(FamilyElementFacts fact) => + fact is { ClassName: "ExtrusionElem", IsForm: true, Cutting: false, ShownInFine: true, CombinationMember: false, + DrawnInViewsOnly: false, CutByOwnStep: false }; + + // Everything else that is shown, in this type or in another, cannot be computed. + private void AddShownContent(IReadOnlyList facts) + { + foreach (var fact in facts) + { + if (!(fact.IsForm || fact.HasGeometry) || FamilyRules.IsNeverShown(fact.ClassName) + || fact.DrawnInViewsOnly || fact.PlacesOwnFormsOnly || IsRecomputed(fact)) continue; + if (fact.CutByOwnStep) _unsupported.Add($"cut of {fact.ElementId}"); + // A void is not drawn by itself. + else if (!fact.Cutting && (fact.ShownInFine != false || fact.CombinationMember)) + _unsupported.Add($"{fact.ClassName} {fact.ElementId}"); + } + } + + private void References(Record record, HashSet references, HashSet referrers) + { + foreach (var (slot, name, value) in record.Values) + { + if (value.Kind != WideBlockWalker.CaptureKind.Integer || value.Integer <= 0 + || name.EndsWith('#') || !references.Contains(value.DeclaringClass + "." + value.Field)) continue; + string field = value.DeclaringClass + "." + value.Field; + referrers.Add(new(record.Key, record.ClassName, slot < 0 ? field : record.SlotClass(slot) + "." + field, + Referenced(value.Integer))); + } + } + + private void Associations(Record record, List associations) + { + long? parameter = null; + foreach (var (_, name, value) in record.Values) + { + if (name == "ParamIdPair.m_famParamId") parameter = value.Integer; + else if (name == "ParamIdPair.m_elemPropId" && parameter is long family) + { + associations.Add(new(record.Key, value.Integer, ParameterKey(family))); + parameter = null; + } + } + } + + private FamilySketchLine Line(Record record, List joints) + { + var membership = record.Values.FirstOrDefault(item => item.Name == "GroupMembership.m_groupId" + && record.SlotClass(item.Slot) == "SketchMembership"); + int sketch = membership.Name == null ? 0 : Math.Max(0, Referenced(membership.Value.Integer)); + if (record.Find("CurveElem.m_pCurveDriver", -1) is not { Integer: > 0 } driverPointer) + return new(record.Key, sketch, false, new double[3], new double[3]); + int driver = record.Target(driverPointer); + + // For each end of this curve the (curve, end) pairs joined there, listed before the number of the end. + var pending = new List<(long Element, long End)>(); + long? element = null; + foreach (var (name, value) in record.In(driver)) + { + if (name == "EndInfo.m_elemId") element = value.Integer; + else if (name == "EndInfo.m_joinedEnd" && element is long joined) pending.Add((joined, value.Integer)); + else if (name == "IndexJoinPair.m_index") + { + foreach (var (other, otherEnd) in pending) + { + int id = Referenced(other); + if (id == record.Key && otherEnd == value.Integer) continue; + // 0 and 1 are the ends of the other curve; 2 and 3 say that this end lies on it. + joints.Add(new(record.Key, (int)value.Integer, id, + otherEnd is 2 or 3 ? -1 : (int)otherEnd)); + } + pending.Clear(); + } + } + + var curve = record.Values.Where(item => item.Name == "CurveDriver.m_pCrv") + .Select(item => (int?)record.Target(item.Value)).FirstOrDefault(); + if (curve is not int slot || record.SlotClass(slot) != "GLine") + return new(record.Key, sketch, false, new double[3], new double[3]); + var (start, end) = Ends(record, slot); + return new(record.Key, sketch, true, start, end); + } + + private static (double[] Start, double[] End) Ends(Record record, int slot) + { + var origin = record.Vector("GLine.m_origin", slot); + var direction = record.Vector("GLine.m_dirVec", slot); + double[] At(double parameter) => [.. Enumerable.Range(0, 3).Select(i => origin[i] + direction[i] * parameter)]; + return (At(record.Real("GCurve.m_endParams@0", slot)), At(record.Real("GCurve.m_endParams@1", slot))); + } + + private FamilyDimensionRecord Dimension(Record record, Dictionary> driven) + { + bool alignment = record.ClassName == "Alignment"; + long count = record.Integer("Dimension.m_ArrSegInfo#"); + var segments = new List<(long? Parameter, long? Flags, double? Value)>(); + var references = new List(); + foreach (var (name, value) in record.In(-1)) + { + int last = segments.Count - 1; + if (name == "DimSegInfo.m_pDimSegInfoBase") segments.Add(default); + else if (name == "DimSegInfo.m_paramId" && last >= 0) + segments[last] = segments[last] with { Parameter = segments[last].Parameter ?? value.Integer }; + else if (name == "DimSegInfo.m_flags" && last >= 0) + segments[last] = segments[last] with { Flags = segments[last].Flags ?? value.Integer }; + else if (name == "DimSegValue.m_value" && last >= 0) + segments[last] = segments[last] with { Value = segments[last].Value ?? value.Real }; + else if (name == "WitnessRefInfo.m_pWitnessRef") + { + int witness = record.Target(value); + references.Add(new(Referenced(record.Integer("GeomRef.m_elemId", witness)), + (int)record.Integer("GeomRef.m_geomTag", witness), + (int)record.Integer("GeomRef.m_subTag", witness))); + } + } + if (count < 0 || count > segments.Count) throw new Unread($"segments of dimension {record.Key}"); + var held = segments.Take((int)count).ToList(); + if (held.Any(s => s.Parameter == null || s.Flags == null || s.Value == null)) + throw new Unread($"segments of dimension {record.Key}"); + var axis = alignment ? record.Vector("Alignment.m_constrDir", -1) + : record.Vector("GLine.m_dirVec", record.Pointer("LinearConstraint.m_pDimLine")); + return new(record.Key, alignment, axis, record.Integer("Dimension.m_flags"), + [.. held.Select(s => s.Flags!.Value)], references, [.. held.Select(s => ParameterKey(s.Parameter!.Value))], + [.. held.Select(s => s.Value!.Value)], driven.GetValueOrDefault(record.Key) ?? []); + } + + private static (double[] Origin, double[] Normal) Surface(Record record, int slot) + { + if (record.SlotClass(slot) != "Plane") throw new Unread($"surface of {record.ClassName} {record.Key}"); + var x = record.Vector("Plane.m_xVec", slot); + var y = record.Vector("Plane.m_yVec", slot); + double[] normal = [x[1] * y[2] - x[2] * y[1], x[2] * y[0] - x[0] * y[2], x[0] * y[1] - x[1] * y[0]]; + return (record.Vector("Plane.m_origin", slot), normal); + } + + private static FamilyPlaneRecord Plane(Record record) + { + var (origin, normal) = Surface(record, record.Pointer("DatumPlane.m_pSurface")); + return new(record.Key, record.ClassName, record.Find("RefPlaneBase.m_refName", -1)?.Integer ?? 0, origin, normal, + record.Integer("Element.m_locked") != 0, + record.Find("RefPlaneBase.m_definesOrigin", -1)?.Integer is not (null or 0)); + } + + private Record Own(int key, string what) => + _own.GetValueOrDefault(key) ?? throw new Unread($"{what} {key}"); + + private FamilyExtrusionRecord Extrusion(int key, Dictionary lines) + { + var record = Own(key, "extrusion"); + if (record.Slots.Where(i => record.Find("ExtrusionHelper.m_sketchId", i) != null).ToArray() is not [var helper]) + throw new Unread($"sketch of {key}"); + var sketch = Own(Referenced(record.Integer("ExtrusionHelper.m_sketchId", helper)), "sketch of extrusion " + key); + if (!TfClassNames.IsSubclassOf(sketch.ClassName, "Sketch")) throw new Unread($"sketch of {key}"); + var (origin, normal) = Surface(sketch, sketch.Pointer("Sketch.m_pPlane")); + + var offsets = new Dictionary(); + double? value = null; + foreach (var (name, item) in record.In(record.Pointer("Element.m_pParamValueSetDouble"))) + { + if (name == "ParamValueDouble.m_value") value = item.Real; + else if (name == "ParamValueDouble.m_paramId" && value is double offset) + (offsets[item.Integer], value) = (offset, null); + } + if (!offsets.TryGetValue((long)BuiltIns.BuiltInParameter.EXTRUSION_START_PARAM, out double start) + || !offsets.TryGetValue((long)BuiltIns.BuiltInParameter.EXTRUSION_END_PARAM, out double end)) + throw new Unread($"start and end of {key}"); + + var (faces, edges) = History(record); + var numbers = CurveNumbers(sketch); + var elementsByNumber = SketchElements(sketch); + var loops = new List>(); + var profile = new Dictionary(); + foreach (int loop in record.Pointers("ElementExtrusionHelper.m_pCurveLoops", helper)) + { + var tags = new List(); + foreach (int curve in record.Pointers("CurveLoop.m_curves", loop)) + { + int tag = (int)record.Integer("GInfo.m_tag", curve); + tags.Add(tag); + if (!numbers.TryGetValue(tag, out long number) || !elementsByNumber.TryGetValue(number, out int lineId) + || !lines.TryGetValue(lineId, out var line)) continue; + // A curve that is not straight is refused by what builds the model; its direction does not matter. + bool reversed = line.IsStraight && record.SlotClass(curve) == "GLine" + && Reversed(Ends(record, curve), line, normal, key); + if (!profile.TryAdd(tag, new(lineId, reversed))) throw new Unread($"profile of {key}"); + } + loops.Add(tags); + } + + var host = Host(sketch); + return new(key, sketch.Key, start, end, origin, normal, host, loops, profile, faces, edges, + Materials(elements[key])); + } + + private static (Dictionary Faces, Dictionary Edges) History(Record record) + { + if (record.Slots.Where(i => record.SlotClass(i) == "ExtrusionGStep").ToArray() is not [var step]) + throw new Unread($"history of {record.Key}"); + var faces = new Dictionary>(); + var edges = new Dictionary>(); + List? current = null; + foreach (var (name, value) in record.In(step)) + { + if (name is "FaceHistEntry.m_id" or "EdgeHistEntry.m_id") + { + var table = name == "FaceHistEntry.m_id" ? faces : edges; + if (!table.TryAdd((int)value.Integer, current = [])) throw new Unread($"history of {record.Key}"); + } + else if (name.StartsWith("FaceHist.m_keys", StringComparison.Ordinal) + || name.StartsWith("EdgeHist.m_keys", StringComparison.Ordinal)) + { + if (!name.EndsWith('#') && value.Integer != -1) current?.Add((int)value.Integer); + } + } + return (faces.ToDictionary(p => p.Key, p => p.Value.ToArray()), + edges.ToDictionary(p => p.Key, p => p.Value.ToArray())); + } + + /// The number of the sketch element of each profile curve tag, by the step that rebuilds the curves. + private static Dictionary CurveNumbers(Record sketch) + { + var keys = new Dictionary>(); + foreach (int step in sketch.Slots.Where(i => sketch.SlotClass(i) == "RegenSketchCurvesGStep")) + { + List? current = null; + foreach (var (name, value) in sketch.In(step)) + { + if (name == "CurveHistEntry.m_id") + { + if (!keys.TryGetValue((int)value.Integer, out current)) keys.Add((int)value.Integer, current = []); + } + else if (name.StartsWith("CurveHist.m_keys@", StringComparison.Ordinal) && value.Integer != -1) + current?.Add(value.Integer); + } + } + return keys.Where(p => p.Value is [1, _]).ToDictionary(p => p.Key, p => p.Value[1]); + } + + private Dictionary SketchElements(Record sketch) + { + int set = sketch.Pointer("Sketch.m_elemIdsPairSet"); + var found = sketch.In(set).Where(i => i.Name == "ElementIdPlusIndex.m_elementId").Select(i => i.Value.Integer).ToList(); + var numbers = sketch.In(set).Where(i => i.Name == "ElementIdPlusIndex.m_index").Select(i => i.Value.Integer).ToList(); + if (found.Count != numbers.Count || numbers.Distinct().Count() != numbers.Count) + throw new Unread($"elements of sketch {sketch.Key}"); + return numbers.Zip(found).ToDictionary(p => p.First, p => Referenced(p.Second)); + } + + /// Whether a profile curve runs from the end of its sketch line to the start; their ends differ only along + /// the normal of the sketch. The link between them is already recorded. + private static bool Reversed((double[] Start, double[] End) curve, FamilySketchLine line, double[] normal, + int extrusion) + { + bool Same(double[] a, double[] b) + { + double along = Enumerable.Range(0, 3).Sum(i => (a[i] - b[i]) * normal[i]); + return Enumerable.Range(0, 3).All(i => Math.Abs(a[i] - b[i] - along * normal[i]) <= 1e-6); + } + if (Same(curve.Start, line.Start) && Same(curve.End, line.End)) return false; + if (Same(curve.Start, line.End) && Same(curve.End, line.Start)) return true; + throw new Unread($"profile curve of {extrusion} off its line {line.Id}"); + } + + /// What the sketch plane of a sketch follows; null when it follows nothing. + private FamilyReference? Host(Record sketch) + { + var plane = Own(Referenced(sketch.Integer("Sketch.m_sketchPlaneId")), "sketch plane of sketch " + sketch.Key); + int reference = plane.Pointer("SketchPlane.m_oPlaneRef"); + switch (plane.SlotClass(reference)) + { + case "DummyPlaneRef" when plane.Integer("GeomRef.m_elemId", reference) <= 0: + return null; + case "OnDatumPlaneRef": + return new(Referenced(plane.Integer("OneElementMovablePlaneRef.m_datumPlaneId", reference)), -1, -1); + case "GeomOnPlaneRef": + return new(Referenced(plane.Integer("GeomRef.m_elemId", reference)), + (int)plane.Integer("GeomRef.m_geomTag", reference), + (int)plane.Integer("GeomRef.m_subTag", reference)); + default: + throw new Unread($"{plane.SlotClass(reference)} of sketch plane {plane.Key}"); + } + } + + private static Dictionary Materials(Element element) + { + var materials = new Dictionary(); + foreach (var face in FamilyRecordReader.Body(element)?.Faces ?? []) + if (face.GInfoFlags != null && face.RenderStyleId is int material + && !materials.TryAdd(face.GInfoTag, material) && materials[face.GInfoTag] != material) + throw new Unread($"materials of {element.Id}"); + return materials; + } + } +} diff --git a/src/RvtIO/Families/FamilyRules.cs b/src/RvtIO/Families/FamilyRules.cs new file mode 100644 index 00000000..b5560ba9 --- /dev/null +++ b/src/RvtIO/Families/FamilyRules.cs @@ -0,0 +1,52 @@ +using RvtIO.Model; +using RvtIO.Parsing; + +namespace RvtIO.Families; + +/// What the file of a family records about what is visible, as checked against Revit 2022. +internal static class FamilyRules +{ + /// The bit of FamElemVisibility.m_flags of the Fine detail level. The bits of the view directions do not affect a + /// 3D view. + internal const long ShownInFineFlag = 0x8000; + + /// The classes whose geometry is never part of the shape of a family: the hosts of a family template, lines and + /// sketches, reference planes, openings (they cut a host) and type definitions. + internal static bool IsNeverShown(string className) => + className is "CurveElem" or "NonPlanarSketch" or "RefPlane" or "Opening" or "FamilySymbol" + || TfClassNames.IsSubclassOf(className, "HostObj"); + + /// A nested instance of a category that is not a physical object (annotations, detail items): a 3D view does not + /// draw it. + internal static bool IsDrawnInViewsOnly(string className, string? category) => + TfClassNames.IsSubclassOf(className, "FamilyInstance") && ProductRules.IsNonPhysicalCategory(category); + + /// All the geometry of the element places other elements that are forms, as a model group places its members. A + /// placed type does not count: nothing else draws it. + internal static bool PlacesOnlyForms(int elementId, GeometryData? body, Func isForm) => + body?.ExactMappedInstances is { Count: > 0 } mapped + && mapped.All(instance => instance.SymbolId != elementId && isForm(instance.SymbolId)); + + /// The classes that make the shape of a family. Sweeps of every kind derive from GenSweep. + internal static readonly string[] FormClasses = ["GenSweep", "GeomCombination", "FamilyInstance"]; + + /// The values of Dimension.m_flags, of a linear dimension or of an alignment, that occur in families whose + /// relations were checked against Revit 2022; any other value is not recognised. + internal static bool IsKnownDimensionFlags(bool isAlignment, long flags) => + isAlignment ? flags is 10 or 14 or 26 or 30 : flags is 0 or 8 or 12 or 24 or 28 or 136 or 140; + + /// The bit of Dimension.m_flags of an equality dimension, whose segments keep equal lengths. + internal const long EqualityDimensionFlag = 0x80; + + /// The values of DimSegInfo.m_flags. A segment holds when it is locked, an equality or labelled with a family + /// parameter. An unlocked one holds only what those leave free, unless the family's dimension manager lists it as driven + /// (FamDimConstrMgrImpl.m_drivenDimSegs): then its value follows from others and it holds nothing. It never moves an end + /// of an extrusion. + internal const long UnlockedSegmentFlag = 0, LockedSegmentFlag = 1, EqualSegmentFlag = 2; + + /// RefPlaneBase.m_refName of Center (Left/Right), Center (Front/Back) and Center (Elevation), the numbers of the + /// "Is Reference" setting. A level or a pinned reference plane (Element.m_locked) stays where it is. This setting, or + /// "Defines Origin", does not hold a plane against an older element, so such a plane holds its group only when nothing in + /// the group is older. + internal static bool IsCentreReferenceName(long referenceName) => referenceName is 1 or 4 or 7; +} diff --git a/src/RvtIO/Families/FamilySavedState.cs b/src/RvtIO/Families/FamilySavedState.cs new file mode 100644 index 00000000..85941870 --- /dev/null +++ b/src/RvtIO/Families/FamilySavedState.cs @@ -0,0 +1,110 @@ +using RvtIO.Model; + +namespace RvtIO.Families; + +/// Whether the relations and the builder reproduce what the file stores for the type it was saved at: every +/// relation holds at the stored positions, and the faces built there are one for one the stored ones. +internal static class FamilySavedState +{ + private const double Tolerance = 1e-6; // feet + + public static RvtFamilyRefusal? Check(FamilyModel model, IReadOnlyDictionary values, + Func material, IReadOnlyDictionary> stored) => + Match(model, values, material, stored).Refusal; + + /// The stored face that each face built at the stored positions is, by the element and the face of the model; + /// or why the stored state is not reproduced. are those of the saved type, and + /// gives the material of a face in it. + internal static (Dictionary<(int ElementId, FamilyFaceKey Face), GeoFace>? Faces, RvtFamilyRefusal? Refusal) Match( + FamilyModel model, IReadOnlyDictionary values, Func material, + IReadOnlyDictionary> stored) + { + static (Dictionary<(int, FamilyFaceKey), GeoFace>?, RvtFamilyRefusal?) Mismatch(string detail) => + (null, new("saved-state-mismatch", detail)); + + var positions = model.Variables.Select(variable => variable.Stored).ToArray(); + foreach (var equation in model.Equations) + { + double target = equation.ParameterId is not long parameter ? equation.Constant + : values.TryGetValue(parameter, out double value) ? equation.Sign * value : double.NaN; + if (!(Math.Abs(equation.Terms.Sum(term => term.Coefficient * positions[term.Variable]) - target) <= Tolerance)) + return Mismatch($"relation of {equation.SourceElementId}"); + } + if (FamilyContourChecks.Check(model, positions, values) is { } contour) return Mismatch($"profile of {contour.Detail}"); + + var matched = new Dictionary<(int, FamilyFaceKey), GeoFace>(); + foreach (var extrusion in model.Extrusions) + { + if (!stored.TryGetValue(extrusion.ElementId, out var faces)) return Mismatch($"element {extrusion.ElementId}"); + // The builder asks for the material of each face as it makes it, in the order of the faces. + var keys = new List(); + var built = FamilyExtrusionBuilder.Faces(extrusion, positions, key => + { + keys.Add(key); + return material(extrusion, key); + }); + var left = faces.ToList(); + foreach (var (face, key) in built.Zip(keys)) + { + int found = left.FindIndex(candidate => Same(face, candidate)); + if (found < 0) return Mismatch($"element {extrusion.ElementId}"); + matched.Add((extrusion.ElementId, key), left[found]); + left.RemoveAt(found); + } + if (left.Count > 0) return Mismatch($"element {extrusion.ElementId}"); + } + return (matched, null); + } + + private static bool Same(GeoFace built, GeoFace stored) + { + // No material is stored as nothing or as an id that is not one. + if (Math.Max(built.RenderStyleId ?? 0, 0) != Math.Max(stored.RenderStyleId ?? 0, 0) + || !Close(built.Normal, stored.Normal) || !SameLoop(built.OuterVertices, stored.OuterVertices)) return false; + var holes = stored.InnerVertices?.ToList() ?? []; + foreach (var hole in built.InnerVertices ?? []) + { + int found = holes.FindIndex(candidate => SameLoop(hole, candidate)); + if (found < 0) return false; + holes.RemoveAt(found); + } + return holes.Count == 0; + } + + private static bool Close(double[] a, double[] b) => + a.Length == 3 && b.Length == 3 && Enumerable.Range(0, 3).All(i => Math.Abs(a[i] - b[i]) <= Tolerance); + + /// The same corners in the same order, from any of them; points in the middle of a side do not count. + private static bool SameLoop(List? built, List? stored) + { + if (built == null || stored == null || stored.Any(point => point.Length != 3)) return false; + var (a, b) = (Corners(built), Corners(stored)); + return a.Count == b.Count && a.Count >= 3 && Enumerable.Range(0, a.Count) + .Any(shift => Enumerable.Range(0, a.Count).All(i => Close(a[i], b[(i + shift) % b.Count]))); + } + + private static List Corners(List loop) + { + var corners = loop.ToList(); + for (int i = 0; i < corners.Count && corners.Count > 2;) + { + var (previous, point, next) = (corners[(i + corners.Count - 1) % corners.Count], corners[i], + corners[(i + 1) % corners.Count]); + if (OnSide(point, previous, next)) + { + corners.RemoveAt(i); + i = 0; + } + else i++; + } + return corners; + } + + private static bool OnSide(double[] point, double[] start, double[] end) + { + double[] side = [end[0] - start[0], end[1] - start[1], end[2] - start[2]]; + double length = side[0] * side[0] + side[1] * side[1] + side[2] * side[2]; + double along = length > 0 ? Math.Clamp(Enumerable.Range(0, 3).Sum(i => (point[i] - start[i]) * side[i]) / length, 0, 1) : 0; + return Math.Sqrt(Enumerable.Range(0, 3).Sum(i => Math.Pow(point[i] - start[i] - along * side[i], 2))) <= Tolerance; + } +} diff --git a/src/RvtIO/Families/FamilySolver.cs b/src/RvtIO/Families/FamilySolver.cs new file mode 100644 index 00000000..78b76765 --- /dev/null +++ b/src/RvtIO/Families/FamilySolver.cs @@ -0,0 +1,141 @@ +using System.Globalization; +using System.Numerics; + +namespace RvtIO.Families; + +/// +/// Solves the relations of a family for the values of one type. The coefficients are whole numbers, so which variables +/// the relations determine is found exactly: the coefficients are eliminated as fractions, and the right sides go through +/// the same operations in double. A weak relation holds only what the others leave free; weak ones that disagree are a +/// contradiction. A variable the relations leave free keeps its stored value. +/// +internal static class FamilySolver +{ + private const double Tolerance = 1e-6; // feet + + public static FamilySolution Solve(FamilyModel model, IReadOnlyDictionary values) + { + var targets = new double[model.Equations.Count]; + for (int e = 0; e < model.Equations.Count; e++) + { + var equation = model.Equations[e]; + if (equation.ParameterId is not long parameter) targets[e] = equation.Constant; + else if (values.TryGetValue(parameter, out double value)) targets[e] = equation.Sign * value; + else return Refused("underdetermined", [parameter]); + } + + var pivots = new Dictionary(); // reduced: each row holds its own pivot, with 1, and free variables + Row Reduced(int e) + { + var row = new Row { Right = targets[e] }; + foreach (var (variable, coefficient) in model.Equations[e].Terms) + { + if (model.Variables[variable].Anchored) row.Right -= coefficient * model.Variables[variable].Stored; + else row.Add(variable, new Fraction(coefficient)); + } + foreach (int variable in row.Coefficients.Keys.Where(pivots.ContainsKey).ToList()) + row.Subtract(pivots[variable], row.Coefficients[variable]); + return row; + } + void Hold(Row row) + { + // A row left without variables repeats or contradicts the others: the check of the equations tells which. + if (row.Coefficients.Count == 0) return; + int pivot = row.Coefficients.Keys.Min(); + row.Divide(row.Coefficients[pivot]); + foreach (var other in pivots.Values) + if (other.Coefficients.TryGetValue(pivot, out var factor)) other.Subtract(row, factor); + pivots.Add(pivot, row); + } + + var all = Enumerable.Range(0, model.Equations.Count).ToList(); + foreach (int e in all.Where(e => !model.Equations[e].IsWeak)) Hold(Reduced(e)); + // A weak equation about nothing the strong ones leave free yields to them. The others must all hold together. + var yielding = all.Where(e => model.Equations[e].IsWeak && Reduced(e).Coefficients.Count == 0).ToHashSet(); + foreach (int e in all.Where(e => model.Equations[e].IsWeak && !yielding.Contains(e))) Hold(Reduced(e)); + + bool Determined(int variable) => + model.Variables[variable].Anchored || pivots.TryGetValue(variable, out var row) && row.Coefficients.Count == 1; + var undetermined = model.Extrusions.Where(extrusion => !UsedBy(extrusion).All(Determined)) + .Select(extrusion => (long)extrusion.ElementId).ToList(); + if (undetermined.Count > 0) return Refused("underdetermined", undetermined); + + var positions = model.Variables.Select(variable => variable.Stored).ToArray(); + foreach (var (pivot, row) in pivots) + positions[pivot] = row.Right - row.Coefficients.Where(term => term.Key != pivot) + .Sum(term => term.Value.Value * model.Variables[term.Key].Stored); + + var broken = all.Where(e => !yielding.Contains(e) && !(Math.Abs( + model.Equations[e].Terms.Sum(term => term.Coefficient * positions[term.Variable]) - targets[e]) <= Tolerance)) + .Select(e => (long)model.Equations[e].SourceElementId).ToList(); + return broken.Count > 0 ? Refused("inconsistent", broken) : new(positions, null); + } + + private static IEnumerable UsedBy(FamilyExtrusion extrusion) + { + foreach (var loop in extrusion.Loops) + foreach (var vertex in loop) + { + if (extrusion.Axis != 0) yield return vertex.X; + if (extrusion.Axis != 1) yield return vertex.Y; + if (extrusion.Axis != 2) yield return vertex.Z; + } + yield return extrusion.Start; + yield return extrusion.End; + } + + private static FamilySolution Refused(string code, IEnumerable ids) => new(null, new(code, + string.Join(", ", ids.Distinct().Order().Select(id => id.ToString(CultureInfo.InvariantCulture))))); + + private sealed class Row + { + public Dictionary Coefficients { get; } = []; + public double Right { get; set; } + + public void Add(int variable, Fraction value) + { + if (Coefficients.TryGetValue(variable, out var present)) value = present + value; + if (value.IsZero) Coefficients.Remove(variable); + else Coefficients[variable] = value; + } + + public void Subtract(Row other, Fraction factor) + { + foreach (var (variable, value) in other.Coefficients) Add(variable, -(factor * value)); + Right -= factor.Value * other.Right; + } + + public void Divide(Fraction divisor) + { + foreach (int variable in Coefficients.Keys.ToList()) Coefficients[variable] /= divisor; + Right /= divisor.Value; + } + } + + private readonly struct Fraction + { + private readonly BigInteger _numerator; + private readonly BigInteger _denominator; + + public Fraction(BigInteger numerator, BigInteger denominator) + { + var common = BigInteger.GreatestCommonDivisor(numerator, denominator); + if (denominator.Sign < 0) common = -common; + _numerator = numerator / common; + _denominator = denominator / common; + } + + public Fraction(int whole) : this(whole, BigInteger.One) { } + + public bool IsZero => _numerator.IsZero; + public double Value => (double)_numerator / (double)_denominator; + + public static Fraction operator +(Fraction a, Fraction b) => + new(a._numerator * b._denominator + b._numerator * a._denominator, a._denominator * b._denominator); + public static Fraction operator -(Fraction a) => new(-a._numerator, a._denominator); + public static Fraction operator *(Fraction a, Fraction b) => + new(a._numerator * b._numerator, a._denominator * b._denominator); + public static Fraction operator /(Fraction a, Fraction b) => + new(a._numerator * b._denominator, a._denominator * b._numerator); + } +} diff --git a/src/RvtIO/Families/FamilyTypeTable.cs b/src/RvtIO/Families/FamilyTypeTable.cs new file mode 100644 index 00000000..1c0a23dd --- /dev/null +++ b/src/RvtIO/Families/FamilyTypeTable.cs @@ -0,0 +1,37 @@ +using RvtIO.Parsing; +using static RvtIO.Writing.LoadedFamilyParameterWriter; +using static RvtIO.Writing.ParameterWriter; +using static RvtIO.Writing.UserParameterWriter; + +namespace RvtIO.Families; + +/// The type table of the record of a family (class FamilyTypeTable), for the reader and the writer. +internal static class FamilyTypeTable +{ + internal sealed record StoredType(string Name, FamilyStore Values); + + /// The types in stored order and the index of the current one; a family that stores no types has none and the + /// index -1. Throws for a table that is not read exactly. + internal static (StoredType[] Types, int Current) Read(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 + || (names.Length == 0 ? current != -1 : 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 StoredType[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 StoredType(names[i].capture.Text!, ReadStore(fields[(names[i].index + 1)..end])); + } + return (types, (int)current); + } +} diff --git a/src/RvtIO/Families/RvtFamilyRefusal.cs b/src/RvtIO/Families/RvtFamilyRefusal.cs new file mode 100644 index 00000000..662b989b --- /dev/null +++ b/src/RvtIO/Families/RvtFamilyRefusal.cs @@ -0,0 +1,6 @@ +namespace RvtIO.Families; + +/// Why a type of a family has no geometry. +/// A stable code, such as not-computed. +/// What in the family it names, empty when there is nothing to name. +public sealed record RvtFamilyRefusal(string Code, string Detail = ""); diff --git a/src/RvtIO/Families/RvtFamilyTypes.cs b/src/RvtIO/Families/RvtFamilyTypes.cs new file mode 100644 index 00000000..9186a9c1 --- /dev/null +++ b/src/RvtIO/Families/RvtFamilyTypes.cs @@ -0,0 +1,15 @@ +using RvtIO.Model; + +namespace RvtIO; + +/// One type of the family of a family document. +/// The name as stored; blank for the type Revit keeps for a family without named types. +/// The values the type stores, with ids that are keys of for the +/// parameters of the family and negative for built-in ones. A value is in Revit's internal units. A built-in parameter whose +/// kind of value is not established has and no value. +public sealed record RvtFamilyType(string Name, IReadOnlyList Parameters); + +/// The types of the family of a family document, in stored order. +/// The type the file was saved at, whose geometry the file holds. +/// The types. +public sealed record RvtFamilyTypes(int CurrentIndex, IReadOnlyList Types); diff --git a/src/RvtIO/Meshes/ElementMeshes.cs b/src/RvtIO/Meshes/ElementMeshes.cs index af3fd34b..c5956e9b 100644 --- a/src/RvtIO/Meshes/ElementMeshes.cs +++ b/src/RvtIO/Meshes/ElementMeshes.cs @@ -1,4 +1,6 @@ +using System.Globalization; using RvtIO.BuiltIns; +using RvtIO.Families; using RvtIO.Geometry.Meshing; using RvtIO.Internal; using RvtIO.Model; @@ -46,21 +48,16 @@ public static MeshSet Extract(RvtDocument document, ElementMeshOptions? options ArgumentNullException.ThrowIfNull(document); options ??= new ElementMeshOptions(); var info = document.RawData; - var drawable = DrawableElements(info, options.IncludeModelLinesAndReinforcement); + // A family document shows the content of its own family: no project rules, lines or datums apply to it. + (List<(Element Element, GeometryData? Body)> Listed, HashSet Hidden, string[] Gaps)? familyShape = + info.Family is { } family ? FamilyElements(info, family) : null; + if (familyShape != null) options = new ElementMeshOptions { UseSymbolPlacements = options.UseSymbolPlacements }; + var drawable = familyShape?.Listed ?? DrawableElements(info, options.IncludeModelLinesAndReinforcement); var drawableIds = drawable.Select(item => item.Element.Id).ToHashSet(); var symbolCache = new Dictionary(); var placedSymbols = new Dictionary>(); - bool IsMaterial(int id) => document.GetElement(id)?.CategoryId == MaterialsCategoryId; - int MaterialOf(GeoFace face) - { - if (face.RenderStyleId is > 0 and int own && IsMaterial(own)) return own; - if (face.NestedRenderStyleId is > 0 and int nested && IsMaterial(nested)) return nested; - if (face.GeometryStyle > 0 && info.GraphicsStyles?.TryGetValue(face.GeometryStyle, out var style) == true - && style.Material > 0 && IsMaterial(style.Material)) - return style.Material; - return 0; - } + int MaterialOf(GeoFace face) => ElementMeshes.MaterialOf(document, face); SymbolMeshes? SymbolOf(int symbolId) { @@ -111,6 +108,12 @@ int MaterialOf(GeoFace face) var elements = new List(); foreach (var (element, body) in drawable) { + // Hidden by the saved type: listed without geometry, so that another type has the element to show. + if (familyShape?.Hidden.Contains(element.Id) == true) + { + elements.Add(new ElementMesh { ElementId = element.Id, Coverage = MeshCoverage.Complete }); + continue; + } if (options.IncludeModelLinesAndReinforcement && IsStairContainer(element, body, drawableIds)) { elements.Add(new ElementMesh @@ -183,7 +186,152 @@ int MaterialOf(GeoFace face) }); } } - return new MeshSet { Elements = elements, Symbols = placedSymbols, GeometryUndecoded = info.WideLayoutNotRewritten }; + return new MeshSet + { + Elements = elements, Symbols = placedSymbols, GeometryUndecoded = info.WideLayoutNotRewritten, + FamilyGaps = familyShape?.Gaps ?? (info.IsStandaloneFamily ? ["owner"] : []), + }; + } + + /// The material of a face: its own, else that of the symbol face it was placed from, else that of the graphics + /// style of its Geometry node, else none (0). + private static int MaterialOf(RvtDocument document, GeoFace face) + { + bool IsMaterial(int id) => document.GetElement(id)?.CategoryId == MaterialsCategoryId; + if (face.RenderStyleId is > 0 and int own && IsMaterial(own)) return own; + if (face.NestedRenderStyleId is > 0 and int nested && IsMaterial(nested)) return nested; + if (face.GeometryStyle > 0 && document.RawData.GraphicsStyles?.TryGetValue(face.GeometryStyle, out var style) == true + && style.Material > 0 && IsMaterial(style.Material)) + return style.Material; + return 0; + } + + /// The shape of a family file in the type of , + /// computed from the relations of the family, or why it is not computed. The relations are used only when they and the + /// forms built from them reproduce what the file stores for the type it was saved at. + /// is null. + /// The document has no family type of that index. + public static RvtFamilyTypeMeshes ComputeFamilyType(RvtDocument document, int typeIndex) + { + ArgumentNullException.ThrowIfNull(document); + if (document.RawData.Family is not { Types: { } types } family || typeIndex < 0 || typeIndex >= types.Types.Count) + throw new ArgumentOutOfRangeException(nameof(typeIndex), typeIndex, "The document has no family type of this index."); + var prepared = family.Prepared ??= PrepareFamily(document, family, types); + if (prepared.Refusal is { } refused) return new(null, refused); + + var model = prepared.Model!; + var values = ValuesOf(types.Types[typeIndex]); + RvtFamilyTypeMeshes Refused(string code, long id) => new(null, new(code, id.ToString(CultureInfo.InvariantCulture))); + foreach (var extrusion in model.Extrusions) + if (extrusion.VisibilityParameterId is long visibility && !values.ContainsKey(visibility)) + return Refused("underdetermined", visibility); + var shown = model with { Extrusions = [.. model.Extrusions.Where(extrusion => IsShown(extrusion, values))] }; + foreach (var extrusion in shown.Extrusions) + if (extrusion.MaterialParameterId is long finish && !values.ContainsKey(finish)) + return Refused("underdetermined", finish); + var solution = FamilySolver.Solve(shown, values); + if (solution.Positions is not { } positions) return new(null, solution.Refusal); + if (FamilyContourChecks.Check(shown, positions, values) is { } degenerate) return new(null, degenerate); + + var material = MaterialIn(values); + var built = shown.Extrusions.ToDictionary(extrusion => extrusion.ElementId); + var elements = new List(); + foreach (int id in prepared.Elements) + { + if (!built.TryGetValue(id, out var extrusion)) + { + elements.Add(new ElementMesh { ElementId = id, Coverage = MeshCoverage.Complete }); + continue; + } + var keys = new List(); + var faces = FamilyExtrusionBuilder.Faces(extrusion, positions, key => + { + keys.Add(key); + return material(extrusion, key); + }); + foreach (var (face, key) in faces.Zip(keys)) + { + if (!prepared.Faces!.TryGetValue((id, key), out var stored)) return Refused("degenerate-geometry", id); + // What gives a face without a material of its own one is that of the stored face it is computed for. + face.GeometryStyle = stored.GeometryStyle; + face.NestedRenderStyleId = stored.NestedRenderStyleId; + } + var (meshes, failed) = Triangulate(faces, face => MaterialOf(document, face)); + if (failed > 0) return Refused("degenerate-geometry", id); + elements.Add(new ElementMesh { ElementId = id, Meshes = meshes, Coverage = MeshCoverage.Complete }); + } + return new(elements, null); + } + + /// The model of a family, once its saved state is reproduced, or why no type of it is computed. + private static FamilyPreparation PrepareFamily(RvtDocument document, FamilyData family, RvtFamilyTypes types) + { + static FamilyPreparation No(string code, string detail) => new(null, null, [], new(code, detail)); + var (listed, hidden, gaps) = FamilyElements(document.RawData, family); + // A shape that is incomplete in the saved type cannot be computed complete in another. + if (gaps.Length > 0) return No("unsupported-construct", "incomplete: " + string.Join(", ", gaps)); + if (family.Records is not { } records) return No("unrecognized-reference", "the records of the family"); + var (model, refusal) = FamilyModelBuilder.Build(records); + if (model == null) return No(refusal!.Code, refusal.Detail); + + // The forms of the model are those the saved type lists, and its values show and hide them as the file does. + var saved = ValuesOf(types.Types[types.CurrentIndex]); + if (!listed.Select(item => item.Element.Id).Order().SequenceEqual(model.Extrusions.Select(e => e.ElementId).Order()) + || model.Extrusions.Any(extrusion => IsShown(extrusion, saved) == hidden.Contains(extrusion.ElementId))) + return No("saved-state-mismatch", "the forms of the saved type"); + + var storedFaces = new Dictionary>(); + foreach (var (element, body) in listed) + { + // Faces the file holds only in part cannot be compared. + if (body == null || body.PlacedSymbolBox || body.UnresolvedSymbol || body.UntriangulatedFaces > 0 + || body.GhostNodes is { Count: > 0 }) continue; + bool dropUntaken = DropsUntakenNodes(body.Faces, false); + storedFaces[element.Id] = body.Faces.Where(face => !dropUntaken || face.GeometryNode >= 0).ToList(); + } + var (matched, mismatch) = FamilySavedState.Match(model, saved, MaterialIn(saved), storedFaces); + return matched == null ? No(mismatch!.Code, mismatch.Detail) + : new(model, matched, listed.Select(item => item.Element.Id).ToArray(), null); + } + + /// The numbers of a type by parameter: lengths and other measures, yes/no as 1 or 0, and element keys. + private static Dictionary ValuesOf(RvtFamilyType type) + { + var values = new Dictionary(); + foreach (var parameter in type.Parameters) + if (parameter.StorageType is StorageType.Double or StorageType.Integer or StorageType.ElementId) + { + if (parameter.Value is double real) values[parameter.Id] = real; + else if (parameter.Value is int whole) values[parameter.Id] = whole; + } + return values; + } + + private static bool IsShown(FamilyExtrusion extrusion, IReadOnlyDictionary values) => + extrusion.VisibilityParameterId is not long parameter || values.TryGetValue(parameter, out double value) && value != 0; + + /// The material of each face in a type: that of the parameter that gives it, else the stored one. + private static Func MaterialIn(IReadOnlyDictionary values) => + (extrusion, key) => extrusion.MaterialParameterId is not long parameter ? extrusion.Materials.GetValueOrDefault(key) + : values.TryGetValue(parameter, out double material) ? (int)material : 0; + + /// The elements of a family document that are listed (shown or hidden by the saved type), in document order, each + /// with the geometry that is its body, and why the shape is incomplete. + private static (List<(Element Element, GeometryData? Body)> Listed, HashSet Hidden, string[] Gaps) FamilyElements( + RevitFileInfo info, FamilyData family) + { + var classified = family.Elements.ToDictionary(facts => facts.ElementId, facts => FamilyContent.Classify(facts)); + var listed = new List<(Element, GeometryData?)>(); + var hidden = new HashSet(); + foreach (var element in info.Elements) + { + if (element.IsBlockOnly || !classified.TryGetValue(element.Id, out var content)) continue; + if (content.Kind == FamilyContentKind.Hidden) hidden.Add(element.Id); + else if (content.Kind != FamilyContentKind.Shown) continue; + listed.Add((element, element.SerializedComputedSymbolGeometry ?? element.Geometry)); + } + return (listed, hidden, classified.Values.Select(content => content.Gap).OfType().Distinct() + .Order(StringComparer.Ordinal).ToArray()); } private static MeshVector[]? DatumLinePairs(Element element, double lowestLevel) @@ -517,3 +665,9 @@ public void AddTriangle(int a, int b, int c) }; } } + +/// The meshes of the shape of a family in one of its types. +/// The elements of the shape in document order, those the type hides without geometry; null for a +/// type that is not computed. +/// Why the type is not computed; null for one that is. +public sealed record RvtFamilyTypeMeshes(IReadOnlyList? Elements, RvtFamilyRefusal? Refusal); diff --git a/src/RvtIO/Meshes/MeshSet.cs b/src/RvtIO/Meshes/MeshSet.cs index 991c7691..875105c6 100644 --- a/src/RvtIO/Meshes/MeshSet.cs +++ b/src/RvtIO/Meshes/MeshSet.cs @@ -15,6 +15,14 @@ public sealed class MeshSet /// 2022, such as the Revit 2020 and 2025 samples) opened without . Its elements are listed /// with . public bool GeometryUndecoded { get; init; } + + /// For a family document: why the shape of the family at its saved type is incomplete, empty when it is not. Each + /// code is listed once: void (an element has a cut of its own that its faces may not include), visibility + /// (what the file records about the visibility of an element is not recognised), missing-geometry (a shown form or + /// nested instance has no geometry) and unknown-geometry (an element of a kind that is not recognised has + /// geometry). A family file whose owner family is not found is read as a project, which leaves family content out: its only + /// code is owner. + public IReadOnlyList FamilyGaps { get; init; } = []; } /// The geometry of one element: its own triangles in the coordinates of the document, plus symbols placed whole. diff --git a/src/RvtIO/Model/Geometry.cs b/src/RvtIO/Model/Geometry.cs index f496f79b..d8881294 100644 --- a/src/RvtIO/Model/Geometry.cs +++ b/src/RvtIO/Model/Geometry.cs @@ -408,6 +408,10 @@ internal IReadOnlyList>? SourceLoops /// or not read (see ). internal uint? GInfoFlags { get; set; } + /// GInfo tag of that face, the number its element's geometry history gives it; meaningful only with + /// . + internal int GInfoTag { get; set; } + /// The material of a face that was placed here from a nested symbol (GInstance); RenderStyleId is /// left unset for such faces. The solids of nested instances are collected like the instance's own. internal int? NestedRenderStyleId { get; set; } diff --git a/src/RvtIO/Model/RevitFileInfo.cs b/src/RvtIO/Model/RevitFileInfo.cs index 016ffb49..cd6ffce7 100644 --- a/src/RvtIO/Model/RevitFileInfo.cs +++ b/src/RvtIO/Model/RevitFileInfo.cs @@ -9,6 +9,10 @@ public partial class RevitFileInfo internal IReadOnlyList CurvedGridAxes { get; set; } = []; internal IReadOnlySet? GridChainMemberIds { get; set; } internal bool IsStandaloneFamily { get; set; } + /// The owner family of a family document, as a key of ; null for a project. + internal int? FamilyOwnerId { get; set; } + /// What the family document records about its own elements; null for a project. + internal Families.FamilyData? Family { get; set; } /// The basic file information. public FileMetadata Metadata { get; set; } = new(); diff --git a/src/RvtIO/Parsing/ElementBuilder.cs b/src/RvtIO/Parsing/ElementBuilder.cs index 847c85e9..2639fc05 100644 --- a/src/RvtIO/Parsing/ElementBuilder.cs +++ b/src/RvtIO/Parsing/ElementBuilder.cs @@ -1028,6 +1028,7 @@ List EnvelopeToCorners(double[] env, double[] origin, double[] xv, dou NodeOrder = fp.NodeOrder, GeometryStyle = fp.GeometryStyle, GInfoFlags = fp.GInfoFlags, + GInfoTag = fp.GInfoTag ?? 0, }; int added = geo.Faces.Count; geo.Faces.Add(gf); @@ -1064,6 +1065,7 @@ List EnvelopeToCorners(double[] env, double[] origin, double[] xv, dou NodeOrder = fp.NodeOrder, GeometryStyle = fp.GeometryStyle, GInfoFlags = fp.GInfoFlags, + GInfoTag = fp.GInfoTag ?? 0, }; if (fp.Envelope is { Length: 4 } env2) { diff --git a/src/RvtIO/Parsing/GRepParserV2.cs b/src/RvtIO/Parsing/GRepParserV2.cs index 85705b31..acaf69e0 100644 --- a/src/RvtIO/Parsing/GRepParserV2.cs +++ b/src/RvtIO/Parsing/GRepParserV2.cs @@ -4711,7 +4711,7 @@ double[] P(double u, double v) /// around the axis (surface O, Z). u = revolution angle, v = profile arc parameter (radians). /// Pipe elbows are the common case (torus patch). /// - private static IEnumerable> TessellateRevolution(RingGraph ringGraph, SurfaceRec s, ArcRec arc, + internal static IEnumerable> TessellateRevolution(RingGraph ringGraph, SurfaceRec s, ArcRec arc, List<(double U1, double V1, double U2, double V2)> edges, List<(double U1, double V1, double U2, double V2)> samplingEdges, bool hasAuthoredTrim, bool emitPolygons = true) { @@ -4781,6 +4781,7 @@ double[] Point(double u, double v) vSamples = RefineAngularSamples(vSamples, Math.Max(Math.Abs(arc.R), Math.Abs(arc.RY))); } + else uSamples = RefineUncrossedAngles(uSamples, samplingEdges, arc, maxRevolutionRadius); } var trimPoint = emitPolygons ? TrimBoundaryEvaluator(samplingEdges, Point) : null; var trimmed = TessellateTrimmedGrid( @@ -4805,6 +4806,41 @@ double[] Point(double u, double v) } } + /// + /// The angular samples of a trimmed surface of revolution, with the steps of in every + /// gap that no trim edge off the axis spans. A face closed through the poles has only edges of no length there, so + /// without this the angles between its meridians would be one flat strip. + /// + private static List RefineUncrossedAngles(List samples, + List<(double U1, double V1, double U2, double V2)> edges, ArcRec profile, double radius) + { + if (samples.Count < 2) return samples; + double eps = 2 * Math.Max(1e-10, Math.Abs(samples[^1] - samples[0]) * 1e-10); + var turning = edges.Where(edge => Math.Abs(edge.U2 - edge.U1) > eps + && !(Math.Abs(edge.V2 - edge.V1) <= PoleEdgeResolution && IsOnAxis(profile, (edge.V1 + edge.V2) / 2))).ToList(); + var result = new List(samples.Count) { samples[0] }; + for (int i = 0; i + 1 < samples.Count; i++) + { + double low = samples[i], high = samples[i + 1]; + if (turning.Any(edge => Math.Min(edge.U1, edge.U2) <= low + eps && Math.Max(edge.U1, edge.U2) >= high - eps)) + result.Add(high); + else result.AddRange(RefineAngularSamples([low, high], radius).Skip(1)); + } + return result; + } + + // The distance in the parameters within which two ends of trim edges are one corner of the loop. + private const double PoleEdgeResolution = 1e-4; + + /// True when the profile point at is on the axis (its radial coordinate is zero). + private static bool IsOnAxis(ArcRec profile, double v) + { + var point = profile.Eval(v); + if (point.Any(value => !IsFinite(value))) return false; + double scale = Math.Max(1, point.Max(Math.Abs)); + return Math.Abs(point[0]) <= scale * 64 * Math.ScaleB(1.0, -52); + } + private static List ParameterSamples( List<(double U1, double V1, double U2, double V2)> edges, bool useU, double min, double max) @@ -5004,9 +5040,8 @@ int Node(double u, double v) List<(double U1, double V1, double U2, double V2)> edges, ArcRec profile) { if (edges.Count < 2) return edges; - const double endpointResolution = 1e-4; static (long U, long V) Key(double u, double v) => - ((long)Math.Round(u / endpointResolution), (long)Math.Round(v / endpointResolution)); + ((long)Math.Round(u / PoleEdgeResolution), (long)Math.Round(v / PoleEdgeResolution)); // Two ends per edge, and one node per end of a closed loop: the table is not regrown while it is filled. var nodes = new Dictionary<(long U, long V), (int Degree, double U, double V)>(edges.Count); @@ -5026,16 +5061,11 @@ void Add(double u, double v) var additions = new List<(double U1, double V1, double U2, double V2)>(); foreach (var group in nodes.Values.Where(node => node.Degree % 2 != 0) - .GroupBy(node => (long)Math.Round(node.V / endpointResolution))) + .GroupBy(node => (long)Math.Round(node.V / PoleEdgeResolution))) { var ends = group.OrderBy(node => node.U).ToList(); if (ends.Count != 2) continue; - double v = (ends[0].V + ends[1].V) / 2; - var point = profile.Eval(v); - if (point.Any(value => !IsFinite(value))) continue; - double scale = Math.Max(1, point.Max(Math.Abs)); - double roundoff = scale * 64 * Math.ScaleB(1.0, -52); - if (Math.Abs(point[0]) > roundoff) continue; + if (!IsOnAxis(profile, (ends[0].V + ends[1].V) / 2)) continue; additions.Add((ends[0].U, ends[0].V, ends[1].U, ends[1].V)); } if (additions.Count == 0) return edges; @@ -6060,7 +6090,7 @@ double[] Point(double u, double v) } // Each decoder reuses these buffers across faces. Returned rings own their lists and point references. - private sealed class RingGraph + internal sealed class RingGraph { private readonly Dictionary<(long, long, long), int> nodeByKey = new(); private readonly HashSet<(int, int)> seenEdges = new(); diff --git a/src/RvtIO/Parsing/TfClassNames.cs b/src/RvtIO/Parsing/TfClassNames.cs index df9f6959..5ddfd485 100644 --- a/src/RvtIO/Parsing/TfClassNames.cs +++ b/src/RvtIO/Parsing/TfClassNames.cs @@ -23,6 +23,9 @@ internal static class TfClassNames internal static int IdOf(string className) => Ids.Value.TryGetValue(className, out int id) ? id : throw new KeyNotFoundException($"no Revit 2022 class named {className}"); + /// The 2022 class id of a name read from a file, which the table may not have. + internal static bool TryIdOf(string className, out int id) => Ids.Value.TryGetValue(className, out id); + /// The name of a 2022 class id, or null when the table has none. internal static string? NameOf(int classId) => TfBlockDeserializer.Schemas.TryGetValue(classId, out var schema) ? schema.Name : null; diff --git a/src/RvtIO/Parsing/UserParameterCatalog.cs b/src/RvtIO/Parsing/UserParameterCatalog.cs index f39f2626..b13b4b59 100644 --- a/src/RvtIO/Parsing/UserParameterCatalog.cs +++ b/src/RvtIO/Parsing/UserParameterCatalog.cs @@ -22,12 +22,15 @@ internal sealed record UserParameterDefinition( string? SpecTypeId, bool ReadOnly, bool UserVisible, bool? Instance, string? GroupTypeId = null) { /// Storage kind of the values, from the class of the owned ParamDef (None for a class that is not validated). - public StorageType Storage => DefinitionClass switch + public StorageType Storage => StorageOf(DefinitionClass, SpecTypeId != null); + + /// The storage kind of a ParamDef class (2022 numbering); a number class needs its measurable spec. + internal static StorageType StorageOf(int definitionClass, bool measured) => definitionClass switch { 606 or 2852 or 2848 => StorageType.String, 2866 or 2756 or 2786 or 3200 => StorageType.Integer, 2781 or 2737 or 2814 or 2752 or 1291 => StorageType.ElementId, - 612 or 2742 when SpecTypeId != null => StorageType.Double, + 612 or 2742 when measured => StorageType.Double, _ => StorageType.None, }; diff --git a/src/RvtIO/RvtDocument.cs b/src/RvtIO/RvtDocument.cs index 95b66193..f15369c7 100644 --- a/src/RvtIO/RvtDocument.cs +++ b/src/RvtIO/RvtDocument.cs @@ -25,6 +25,18 @@ public class RvtDocument /// Full local file path when opened via ; null when opened via or created via . public string? SourcePath => _sourcePath; + /// For a family document, the element id of the family that owns the document; null for a project and for a + /// document whose owner cannot be read from its header. A family document has no loaded-family content to leave out, so + /// has no effect on it. + public int? FamilyOwnerId => _info.FamilyOwnerId; + + /// The types of the family of a family document, as its records store them. Null for a project, for a family that + /// stores no types, and when the type table was not read exactly, which then says. + public RvtFamilyTypes? FamilyTypes => _info.Family?.Types; + + /// Why the type table of a family document was not read; null when it was, or when the file holds none. + public string? FamilyTypesError => _info.Family?.TypesError; + /// Project information (name, number, client, address, etc.). public ProjectInfo ProjectInformation => _projectInfo ??= FillProjectInformation(_info.ProjectInfo); diff --git a/src/RvtIO/RvtFileReader.cs b/src/RvtIO/RvtFileReader.cs index 377b469b..1fd65044 100644 --- a/src/RvtIO/RvtFileReader.cs +++ b/src/RvtIO/RvtFileReader.cs @@ -1,4 +1,5 @@ using OpenMcdf; +using RvtIO.Families; using RvtIO.Internal; using RvtIO.Model; using RvtIO.Parsing; @@ -98,6 +99,11 @@ private RevitFileInfo ReadCore(RootStorage root) diag?.WriteLine($"ProjectInfo: {projectInfo.Count} fields"); bool isStandaloneFamily = root.TryOpenStream("PartAtom", out var partAtom); partAtom?.Dispose(); + // Only a file with the family catalogue entry is asked for its owner: the question decompresses the document stream. + long? owner = isStandaloneFamily ? FamilyDocument.OwnerId(root) : null; + int? familyOwnerId = owner is not long id ? null : ids != null ? ids.Key(id) : id <= int.MaxValue ? (int)id : null; + // The content of a family document is its elements: nothing of it is left out as a loaded family's content. + bool projectElementsOnly = _options.ProjectElementsOnly && familyOwnerId == null; var transmissionData = TransmissionDataReader.Read(root); diag?.WriteLine($"TransmissionData: {transmissionData?.ExternalReferences.Count ?? 0} external refs"); @@ -137,8 +143,9 @@ private RevitFileInfo ReadCore(RootStorage root) 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, routing, elemTableIsExact, previewBase64, previewMime, diag, LogPhase, ids); + staleCopiesRemoved, routing, elemTableIsExact, previewBase64, previewMime, diag, LogPhase, ids, projectElementsOnly); wideInfo.IsStandaloneFamily = isStandaloneFamily; + wideInfo.FamilyOwnerId = familyOwnerId; WideModel = wideInfo; WideState = wideState; } @@ -166,10 +173,12 @@ private RevitFileInfo ReadCore(RootStorage root) var (rvtInfo, state) = ParseModel(root, chunks, readFrames, partitionChunkCount, r22View, partitionStreams, framedStreams, wideSchema, elemTable, elemWorksets, fileMetadata, projectInfo, transmissionData, episodeTable, elemRecHistories, elemRecOwners, tfSchemas, ownPartitionWallParts, - staleCopiesRemoved, routing, elemTableIsExact, previewBase64, previewMime, diag, LogPhase, ids, progress); + staleCopiesRemoved, routing, elemTableIsExact, previewBase64, previewMime, diag, LogPhase, ids, projectElementsOnly, progress); rvtInfo.IsStandaloneFamily = isStandaloneFamily; + rvtInfo.FamilyOwnerId = familyOwnerId; if (!releasePartitions) storage = ExtensibleStorageReader.Read(root, elemTableIsExact, framedStreams); storage?.Apply(rvtInfo); + if (owner is long familyId) rvtInfo.Family = FamilyRecordReader.Read(root, rvtInfo, ids, familyId, routing.Current); ElementBuilder.ReportUndrawnFacesBuiltAgain(state, diag); LastParsingState = state; progress?.Report(new("complete", 1, 1)); @@ -237,6 +246,7 @@ private static void ReleaseStreams(List>? streams, List LogPhase, ElementIdMap? ids, + bool projectElementsOnly, IProgress? progress = null) { if (ids != null && !r22View) @@ -294,7 +304,7 @@ private static void ReleaseStreams(List>? streams, List !state.ElemTable.ContainsKey(id)).ToHashSet(); var unreadableGReps = GRepParserV2.IsDecodeTracingEnabled() ? null : new HashSet(); var blockGeometry = ParseBlocks(state, diag, progress, unreadableGReps, @@ -933,7 +943,7 @@ void ScanElementStrings() // of a loaded family document, or a record no longer in the document) unless a built element refers to it, and neither // is an element of the table that belongs to a family document; only those referred to are built. HashSet? leftOut = null; - if (_options.ProjectElementsOnly && elemTableIsExact && (extraRecordIds.Count > 0 || familyContent is { Count: > 0 })) + if (projectElementsOnly && elemTableIsExact && (extraRecordIds.Count > 0 || familyContent is { Count: > 0 })) { leftOut = BuildReferredToOutsideTheTable(state, rvtInfo.Elements, [.. extraRecordIds, .. (IEnumerable?)familyContent?.Keys ?? []], ids => { @@ -3955,18 +3965,25 @@ private static void FinalizeParameterValues(RevitFileInfo rvtInfo, ParsingState var units = bySource.GetOrAdd(key, static (source, parsingState) => { string? specType = source.ForgeId == null ? null : parsingState.ForgeParamSpecs.GetValueOrDefault(source.ForgeId); - string? unitCat = specType != null ? GetUnitCategory(specType) : null; - if (unitCat == null && source.Name is { } bipName) - unitCat = GetUnitCategoryFromBipName(bipName); - if (unitCat == null) return null; - var (symbol, factor) = GetUnitDisplay(unitCat); - return new Parameter.Metadata(SpecType: specType, Symbol: symbol, Factor: factor); + return DisplayUnits(specType, source.Name); }, state); if (units != null) param.SetDisplayUnits(units); } }); } + /// The display unit of a number: by its spec, else by the words of its built-in name; null when neither gives + /// one. + internal static Parameter.Metadata? DisplayUnits(string? specType, string? name) + { + string? unitCat = specType != null ? GetUnitCategory(specType) : null; + if (unitCat == null && name != null) + unitCat = GetUnitCategoryFromBipName(name); + if (unitCat == null) return null; + var (symbol, factor) = GetUnitDisplay(unitCat); + return new Parameter.Metadata(SpecType: specType, Symbol: symbol, Factor: factor); + } + /// Extract unit category from spec type URN. private static string? GetUnitCategory(string specType) { diff --git a/src/RvtIO/RvtReaderOptions.cs b/src/RvtIO/RvtReaderOptions.cs index e68071a5..20ecff39 100644 --- a/src/RvtIO/RvtReaderOptions.cs +++ b/src/RvtIO/RvtReaderOptions.cs @@ -72,7 +72,8 @@ public class RvtReaderOptions /// the type given to an element whose own one was not decoded) is derived from the built elements only, as it is for a /// file read by its own class schema, where the records outside the table are never built. For a consumer that draws or /// lists the project, such as a scene. It applies when the element table of the file was read exactly; otherwise every - /// element is built. Off by default. + /// element is built. It has no effect on a family document (), whose elements are + /// the content of its family. Off by default. public bool ProjectElementsOnly { get; set; } /// Measure doors, windows and structural columns at the detail levels the IFC export measures them at: the surface of diff --git a/src/RvtIO/Writing/StandaloneFamilyParameterWriter.cs b/src/RvtIO/Writing/StandaloneFamilyParameterWriter.cs index 3120c924..595ece10 100644 --- a/src/RvtIO/Writing/StandaloneFamilyParameterWriter.cs +++ b/src/RvtIO/Writing/StandaloneFamilyParameterWriter.cs @@ -4,19 +4,20 @@ using System.Xml.Linq; using OpenMcdf; using RvtIO.BuiltIns; +using RvtIO.Families; 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; +using FamilyType = RvtIO.Families.FamilyTypeTable.StoredType; 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) { @@ -40,6 +41,10 @@ private sealed record BuiltInField(string Name, string Type, string? DisplayName private static readonly string[] ConstraintFields = ["m_paramExprs", "m_drivenDimSegs", "m_additionalParamExprs", "m_dimSegDataMap"]; + /// The kind of value of a built-in family parameter whose storage is established; null for any other. + internal static StorageType? VerifiedStorage(long parameterId) => + BuiltInFields.TryGetValue(parameterId, out var field) ? field.Storage : null; + internal static void Validate(long parameterId, string? value) { if (parameterId < 0) @@ -54,7 +59,7 @@ internal static void Validate(long parameterId, string? value) ParameterWriter.Validate(parameterId, value); } - private static string? CaptureKey(SchemaClass declaring, SchemaField field) => (declaring.Name, field.Name) switch + internal static string? CaptureKey(SchemaClass declaring, SchemaField field) => (declaring.Name, field.Name) switch { ("AUnits", "m_formatOptionsArr") => ParameterMeasurement.LegacyFormats, ("ADocument", "m_ownerFamilyId" or "m_ownerFamilyContainingGroupId") or @@ -82,12 +87,10 @@ internal static void Validate(long parameterId, string? value) 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")) + if (PagedGzipStream.Read(root, "Global", "Latest") is not { } latest + || FamilyDocument.Header(latest, formats, walker) is not { } header) 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) + if (FamilyDocument.OwnerOf(header) is not long familyId) throw Unverified("The family document's owner could not be verified."); if (ElemTableLayout.IdWidth(formats) != idWidth || PagedGzipStream.Read(root, "Global", "ElemTable") is not { } table @@ -543,24 +546,9 @@ private static byte[] EncodeNamedParam(long id, StorageType storage, int idWidth 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]); + var (types, current) = FamilyTypeTable.Read(walker, family); + // A family without types has no value this writer could set. + return current < 0 ? throw Unverified("The family type names or current type could not be verified.") : (types, types[current]); } private static byte[]? EditBuiltInPartAtom(RootStorage root, Pending pending, BuiltInField field, FamilyType[] types, FamilyType selected, diff --git a/tests/RvtIO.Tests/Families/FamilyContentTests.cs b/tests/RvtIO.Tests/Families/FamilyContentTests.cs new file mode 100644 index 00000000..3fba1374 --- /dev/null +++ b/tests/RvtIO.Tests/Families/FamilyContentTests.cs @@ -0,0 +1,106 @@ +using RvtIO.Families; +using RvtIO.Meshes; +using RvtIO.Model; +using Xunit; + +namespace RvtIO.Tests.Families; + +public sealed class FamilyContentTests +{ + [Theory] + // class, form, geometry, void, shown in Fine, hidden by the saved type, kind, gap + [InlineData("ExtrusionElem", true, true, false, true, false, "Shown", null)] + [InlineData("SWall", false, true, false, true, false, "Excluded", null)] + [InlineData("Floor", false, true, false, true, false, "Excluded", null)] + [InlineData("RefPlane", false, false, false, true, false, "Excluded", null)] + [InlineData("Opening", false, true, false, true, false, "Excluded", null)] + [InlineData("CurveElem", false, true, false, true, false, "Excluded", null)] + [InlineData("NonPlanarSketch", false, true, false, true, false, "Excluded", null)] + [InlineData("FamilySymbol", false, true, false, true, false, "Excluded", null)] + // A void is never shown: the shape it cuts is the geometry of the combination. + [InlineData("ExtrusionElem", true, true, true, true, false, "Excluded", null)] + [InlineData("ExtrusionElem", true, true, false, false, false, "Excluded", null)] + [InlineData("ExtrusionElem", true, true, false, true, true, "Hidden", null)] + [InlineData("ExtrusionElem", true, true, false, null, false, "Gap", "visibility")] + [InlineData("ExtrusionElem", true, true, false, true, null, "Gap", "visibility")] + [InlineData("FamilyInstance", true, false, false, true, false, "Gap", "missing-geometry")] + [InlineData("SomethingElse", false, true, false, true, false, "Gap", "unknown-geometry")] + public void ContentIsClassified(string className, bool isForm, bool hasGeometry, bool cutting, bool? shownInFine, + bool? hidden, string kind, string? gap) + { + var facts = new FamilyElementFacts(1, className, isForm, hasGeometry, cutting, shownInFine, hidden); + + Assert.Equal((Enum.Parse(kind), gap), FamilyContent.Classify(facts)); + } + + [Fact] + public void ANestedInstanceThatViewsAloneDrawIsNoPartOfTheShape() + { + var facts = new FamilyElementFacts(1, "FamilyInstance", true, false, false, true, false, DrawnInViewsOnly: true); + + Assert.Equal((FamilyContentKind.Excluded, (string?)null), FamilyContent.Classify(facts)); + } + + [Fact] + public void AnElementThatOnlyPlacesFormsOfTheFamilyAddsNothing() + { + // A model group holds the geometry of its members again. + var facts = new FamilyElementFacts(1, "ElementGroup", false, true, false, true, false, PlacesOwnFormsOnly: true); + + Assert.Equal((FamilyContentKind.Excluded, (string?)null), FamilyContent.Classify(facts)); + } + + [Fact] + public void OnlyPlacedFormsCountAsDrawnElsewhere() + { + var body = new GeometryData { ExactMappedInstances = [new GeoInstance { SymbolId = 2 }, new GeoInstance { SymbolId = 3 }] }; + + Assert.True(FamilyRules.PlacesOnlyForms(1, body, id => id is 2 or 3)); + // A placed type is drawn by nothing else, so an element that places one keeps its own geometry. + Assert.False(FamilyRules.PlacesOnlyForms(1, body, id => id == 2)); + Assert.False(FamilyRules.PlacesOnlyForms(2, body, id => id is 2 or 3)); + Assert.False(FamilyRules.PlacesOnlyForms(1, new GeometryData(), _ => true)); + } + + [Theory] + // combination member, member shown always, a cut step of its own, kind, gap + [InlineData(true, false, false, "Excluded", null)] + [InlineData(true, true, false, "Gap", "visibility")] + // Whether the recorded faces include such a cut is not established: they are shown and the scene is incomplete. + [InlineData(false, false, true, "Shown", "void")] + public void FormsInCombinationsAndFormsCutByAStepAreClassified(bool member, bool alwaysVisible, bool ownCut, string kind, + string? gap) + { + var facts = new FamilyElementFacts(1, "ExtrusionElem", true, true, false, true, false, member, alwaysVisible, ownCut); + + Assert.Equal((Enum.Parse(kind), gap), FamilyContent.Classify(facts)); + } + + [SkippableFact] + public void NoOwnElementWithGeometryIsDroppedSilently() + { + foreach (string path in FamilyFiles.All()) + { + var document = RvtDocument.Open(path, new() { R22Layout = true }); + var meshes = ElementMeshes.Extract(document); + var family = Assert.IsType(document.RawData.Family); + var facts = family.Elements.ToDictionary(item => item.ElementId); + var listed = meshes.Elements.Select(mesh => mesh.ElementId).ToHashSet(); + foreach (var element in document.RawData.Elements) + { + // A record outside an exact element table is a leftover, not an element. + if (element.SerializedFamilyId != document.FamilyOwnerId || !HasFaces(element) + || document.RawData.ElemTableIsExact && element.IsDiscovered) continue; + Assert.True(facts.TryGetValue(element.Id, out var own), $"{path}: element {element.Id} has no facts"); + var (kind, gap) = FamilyContent.Classify(own); + if (gap != null) Assert.Contains(gap, meshes.FamilyGaps); + else Assert.NotEqual(FamilyContentKind.Gap, kind); + if (kind is FamilyContentKind.Shown or FamilyContentKind.Hidden) Assert.Contains(element.Id, listed); + } + Assert.All(meshes.Elements, mesh => Assert.True(facts.ContainsKey(mesh.ElementId), + $"{path}: element {mesh.ElementId} is not of the family itself")); + } + } + + private static bool HasFaces(Element element) => element.Geometry is { Faces.Count: > 0 }; +} diff --git a/tests/RvtIO.Tests/Families/FamilyDocumentTests.cs b/tests/RvtIO.Tests/Families/FamilyDocumentTests.cs new file mode 100644 index 00000000..744bc801 --- /dev/null +++ b/tests/RvtIO.Tests/Families/FamilyDocumentTests.cs @@ -0,0 +1,46 @@ +using OpenMcdf; +using RvtIO.Families; +using RvtIO.Model; +using Xunit; + +namespace RvtIO.Tests.Families; + +public sealed class FamilyDocumentTests +{ + private static long? OwnerIdOfHeader(int owner, int group) + { + using var source = new StandaloneFamilyParameterTests(); + using var root = RootStorage.OpenRead(source.CreateSource(headerOwner: owner, headerGroup: group)); + return FamilyDocument.OwnerId(root); + } + + [Fact] + public void OwnerIdOfAFamilyDocumentIsItsOwnerFamily() => Assert.Equal(70, OwnerIdOfHeader(70, -1)); + + [Fact] + public void AProjectHeaderHasNoOwner() => Assert.Null(OwnerIdOfHeader(-1, -1)); + + [Fact] + public void AFamilyInsideAGroupHasNoOwner() => Assert.Null(OwnerIdOfHeader(70, 5)); + + [Fact] + public void TheReaderReportsTheOwnerOfAFamilyDocument() + { + using var source = new StandaloneFamilyParameterTests(); + Assert.Equal(70, RvtDocument.Open(source.CreateSource()).FamilyOwnerId); + Assert.Null(RvtDocument.FromInfo(new RevitFileInfo()).FamilyOwnerId); + } + + [SkippableFact] + public void ProjectElementsOnlyDoesNotCutAFamilyDocument() + { + foreach (string path in FamilyFiles.All()) + { + var narrow = RvtDocument.Open(path, new() { R22Layout = true, ProjectElementsOnly = true }); + var whole = RvtDocument.Open(path, new() { R22Layout = true }); + Assert.NotNull(narrow.FamilyOwnerId); + Assert.Equal(whole.RawData.Elements.Count(e => e.Geometry != null), + narrow.RawData.Elements.Count(e => e.Geometry != null)); + } + } +} diff --git a/tests/RvtIO.Tests/Families/FamilyExtrusionTests.cs b/tests/RvtIO.Tests/Families/FamilyExtrusionTests.cs new file mode 100644 index 00000000..ef3d0a8f --- /dev/null +++ b/tests/RvtIO.Tests/Families/FamilyExtrusionTests.cs @@ -0,0 +1,202 @@ +using RvtIO.Families; +using RvtIO.Meshes; +using RvtIO.Model; +using Xunit; + +namespace RvtIO.Tests.Families; + +public class FamilyExtrusionTests +{ + private const long Width = 100; + + /// + /// An extrusion along from 1 to 1 + of loops given in the two other + /// axes, in the order that makes them right-handed with the axis. Every coordinate is a variable of its own. + /// + private static (FamilyModel Model, double[] Positions) Prism(int axis, double depth, params (double U, double V)[][] loops) + { + var stored = new List(); + int Add(double value) + { + stored.Add(value); + return stored.Count - 1; + } + var vertexLoops = loops.Select(loop => (IReadOnlyList)loop.Select(point => + { + var components = new[] { -1, -1, -1 }; + components[(axis + 1) % 3] = Add(point.U); + components[(axis + 2) % 3] = Add(point.V); + return new FamilyVertex(components[0], components[1], components[2]); + }).ToList()).ToList(); + var extrusion = new FamilyExtrusion(20, vertexLoops, axis, Add(1), Add(1 + depth), + new Dictionary(), null, null); + var labelled = new FamilyEquation([new(0, 1)], Width, 1, 0, 11); + return (new([.. stored.Select(value => new FamilyVariable(value, false))], [labelled], [extrusion]), [.. stored]); + } + + private static (double U, double V)[] Rectangle(double u0, double v0, double u1, double v1) => + [(u0, v0), (u1, v0), (u1, v1), (u0, v1)]; + + private static (double Volume, int Failed) Measure(List faces) + { + var (meshes, failed) = ElementMeshes.Triangulate(faces, face => 0); + double volume = 0; + foreach (var mesh in meshes) + for (int i = 0; i < mesh.Indices.Length; i += 3) + { + double P(int corner, int component) => mesh.Positions[3 * mesh.Indices[i + corner] + component]; + volume += (P(0, 0) * (P(1, 1) * P(2, 2) - P(1, 2) * P(2, 1)) + + P(0, 1) * (P(1, 2) * P(2, 0) - P(1, 0) * P(2, 2)) + + P(0, 2) * (P(1, 0) * P(2, 1) - P(1, 1) * P(2, 0))) / 6; + } + return (volume, failed); + } + + private static List Build((FamilyModel Model, double[] Positions) prism, Func? material = null) => + FamilyExtrusionBuilder.Faces(prism.Model.Extrusions[0], prism.Positions, material ?? (_ => 0)); + + // The box stands away from the origin, so that a face turned inward changes the signed volume. + [Theory] + [InlineData(0, false)] + [InlineData(1, false)] + [InlineData(2, false)] + [InlineData(2, true)] // a loop drawn the other way round gives the same solid + public void ABoxHasSixOutwardFaces(int axis, bool clockwise) + { + var rectangle = Rectangle(1, 1, 3, 2); + if (clockwise) Array.Reverse(rectangle); + + var faces = Build(Prism(axis, 0.1, rectangle)); + + Assert.Equal(6, faces.Count); + var (volume, failed) = Measure(faces); + Assert.Equal(0, failed); + Assert.Equal(0.2, volume, 1e-9); + double[] centre = new double[3]; + centre[axis] = 1.05; + centre[(axis + 1) % 3] = 2; + centre[(axis + 2) % 3] = 1.5; + Assert.All(faces, face => Assert.True(Enumerable.Range(0, 3) + .Sum(i => face.Normal[i] * (face.OuterVertices![0][i] - centre[i])) > 0)); + } + + [Fact] + public void EveryFaceTakesTheMaterialOfItsKey() + { + var keys = new List(); + + var faces = Build(Prism(2, 1, Rectangle(0, 0, 4, 3), Rectangle(1, 1, 3, 2)), key => + { + keys.Add(key); + return 1000 + keys.Count; + }); + + Assert.Equal(faces.Count, keys.Distinct().Count()); + Assert.Equal(faces.Count, faces.Select(face => face.RenderStyleId).Distinct().Count()); + Assert.Contains(new FamilyFaceKey(FamilyFaceKind.StartCap, 0), keys); + Assert.Contains(new FamilyFaceKey(FamilyFaceKind.EndCap, 0), keys); + Assert.Contains(new FamilyFaceKey(FamilyFaceKind.Side, 1, 3), keys); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void AFrameHasHolesInItsCaps(bool clockwiseHole) + { + var hole = Rectangle(1, 1, 3, 2); + if (clockwiseHole) Array.Reverse(hole); + + var faces = Build(Prism(2, 0.5, Rectangle(0, 0, 4, 3), hole)); + + Assert.Equal(10, faces.Count); + var (volume, failed) = Measure(faces); + Assert.Equal(0, failed); + Assert.Equal((12 - 2) * 0.5, volume, 1e-9); + } + + [Fact] + public void AnIslandInAHoleHasCapsOfItsOwn() + { + var faces = Build(Prism(2, 1, Rectangle(2, 2, 3, 3), Rectangle(0, 0, 8, 8), Rectangle(1, 1, 5, 5))); + + Assert.Equal(3 * 4 + 2 * 2, faces.Count); + var (volume, failed) = Measure(faces); + Assert.Equal(0, failed); + Assert.Equal(64 - 16 + 1, volume, 1e-9); + } + + // The frame: outer loop in variables 0-7 (u and v of each corner in turn), hole in 8-15, then the two ends. + private static (FamilyModel Model, double[] Positions) Frame() => + Prism(2, 1, Rectangle(0, 0, 4, 3), Rectangle(1, 1, 3, 2)); + + // A loop with a notch from the top; the floor of the notch is at v = 1. + private static (FamilyModel Model, double[] Positions) Notched() => + Prism(2, 1, [(0, 0), (5, 0), (5, 3), (3, 3), (3, 1), (2, 1), (2, 3), (0, 3)]); + + private static void Move((FamilyModel Model, double[] Positions) prism, int loop, int component, double from, double to) + { + foreach (var vertex in prism.Model.Extrusions[0].Loops[loop]) + { + int variable = component == 0 ? vertex.X : vertex.Y; + if (prism.Positions[variable] == from) prism.Positions[variable] = to; + } + } + + [Theory] + [InlineData("collapsed segment")] + [InlineData("reversed segment")] + [InlineData("self-intersection")] + [InlineData("loops cross")] + [InlineData("loops touch")] + [InlineData("hole moved outside")] + [InlineData("extrusion end not above start")] + [InlineData("a position that is not a number")] + [InlineData("labelled dimension of zero")] + [InlineData("negative labelled dimension")] + [InlineData("loop flattened to a line")] + public void Degenerate(string change) + { + var prism = change == "self-intersection" ? Notched() + : change == "loop flattened to a line" ? Prism(2, 1, [(0, 0), (4, 0), (2, 1)]) : Frame(); + var values = new Dictionary { [Width] = 4 }; + switch (change) + { + case "collapsed segment": Move(prism, 1, 0, 3, 1); break; + case "reversed segment": Move(prism, 1, 0, 3, 0.5); break; + case "self-intersection": Move(prism, 0, 1, 1, -1); break; + case "loops cross": Move(prism, 1, 0, 3, 5); break; + case "loops touch": Move(prism, 1, 0, 3, 4); break; + case "hole moved outside": Move(prism, 1, 0, 3, 7); Move(prism, 1, 0, 1, 5); break; + case "extrusion end not above start": prism.Positions[^1] = prism.Positions[^2]; break; + case "a position that is not a number": prism.Positions[0] = double.NaN; break; + case "labelled dimension of zero": values[Width] = 0; break; + case "loop flattened to a line": Move(prism, 0, 1, 1, 0); break; + default: values[Width] = -1; break; + } + + var refusal = FamilyContourChecks.Check(prism.Model, prism.Positions, values); + + Assert.Equal("degenerate-geometry", refusal?.Code); + Assert.Equal(change.Contains("labelled", StringComparison.Ordinal) + ? "100" : "20", refusal!.Detail); + } + + [Fact] + public void AValidChangePasses() + { + var prism = Frame(); + Move(prism, 0, 0, 4, 5); + Move(prism, 1, 0, 3, 3.5); + + Assert.Null(FamilyContourChecks.Check(prism.Model, prism.Positions, new Dictionary { [Width] = 5 })); + } + + [Fact] + public void AValidNotchedLoopPasses() + { + var prism = Notched(); + Move(prism, 0, 1, 1, 0.5); + + Assert.Null(FamilyContourChecks.Check(prism.Model, prism.Positions, new Dictionary { [Width] = 5 })); + } +} diff --git a/tests/RvtIO.Tests/Families/FamilyFiles.cs b/tests/RvtIO.Tests/Families/FamilyFiles.cs new file mode 100644 index 00000000..9180a610 --- /dev/null +++ b/tests/RvtIO.Tests/Families/FamilyFiles.cs @@ -0,0 +1,17 @@ +namespace RvtIO.Tests.Families; + +/// The private family files: every .rfa in the folder "families" of a fixture folder. A test that needs them is +/// reported as skipped when there are none. +internal static class FamilyFiles +{ + public static IReadOnlyList All() + { + foreach (string root in TestFiles.Roots()) + { + string folder = Path.Combine(root, "families"); + if (Directory.Exists(folder) && Directory.GetFiles(folder, "*.rfa") is { Length: > 0 } files) + return files.Order(StringComparer.Ordinal).ToArray(); + } + throw TestFiles.Missing("families/*.rfa"); + } +} diff --git a/tests/RvtIO.Tests/Families/FamilyModelBuilderTests.cs b/tests/RvtIO.Tests/Families/FamilyModelBuilderTests.cs new file mode 100644 index 00000000..2d6cd013 --- /dev/null +++ b/tests/RvtIO.Tests/Families/FamilyModelBuilderTests.cs @@ -0,0 +1,522 @@ +using RvtIO.Families; +using Xunit; + +namespace RvtIO.Tests.Families; + +public class FamilyModelBuilderTests +{ + private const long Width = 100, Height = 101; + + private static Dictionary Values(double width = 3, double height = 2) => + new() { [Width] = width, [Height] = height }; + + private static FamilyModel Model(FamilyRecords records) + { + var (model, refusal) = FamilyModelBuilder.Build(records); + Assert.Null(refusal); + return model!; + } + + private static FamilySolution Solve(FamilyRecords records, double width = 3, double height = 2) => + FamilySolver.Solve(Model(records), Values(width, height)); + + /// The corners of the first loop of the only extrusion, and its two ends. + private static (List<(double X, double Y)> Corners, double Start, double End) Shape(FamilyRecords records, + double width = 3, double height = 2) + { + var model = Model(records); + var solution = FamilySolver.Solve(model, Values(width, height)); + Assert.Null(solution.Refusal); + var positions = solution.Positions!; + var extrusion = Assert.Single(model.Extrusions); + Assert.Equal(2, extrusion.Axis); + return (extrusion.Loops[0].Select(v => (Math.Round(positions[v.X], 9), Math.Round(positions[v.Y], 9))).ToList(), + positions[extrusion.Start], positions[extrusion.End]); + } + + [Fact] + public void TheLeafBuildsAndSolvesToANewWidth() + { + var (corners, start, end) = Shape(SyntheticFamily.Leaf(), 4, 3); + + Assert.Equal([(-2, -0.5), (2, -0.5), (2, 0.5), (-2, 0.5)], corners); + Assert.Equal(0, start, 1e-12); + Assert.Equal(3, end, 1e-12); + } + + [Fact] + public void TheStoredValuesGiveTheStoredShape() + { + var (corners, start, end) = Shape(SyntheticFamily.Leaf()); + + Assert.Equal([(-1.5, -0.5), (1.5, -0.5), (1.5, 0.5), (-1.5, 0.5)], corners); + Assert.Equal((0, 2), (start, end)); + } + + // With the alignment to the top plane the end follows it; without it the end keeps its stored offset. + [Fact] + public void ACapWithoutAStrongRelationKeepsItsOffset() + { + var leaf = SyntheticFamily.Leaf(); + var (_, _, end) = Shape(leaf.Without(34), 3, 5); + + Assert.Equal(2, end, 1e-12); + } + + [Fact] + public void AnUnlockedDimensionDoesNotMoveACap() + { + var leaf = SyntheticFamily.Leaf().Without(34); + var unlocked = SyntheticFamily.Linear(35, 2, 28, [(8, 0, -1), (SyntheticFamily.Extrusion, 0, -1)], [0], [-1], [0]); + var (_, _, end) = Shape(leaf with { Dimensions = [.. leaf.Dimensions, unlocked] }, 3, 5); + + Assert.Equal(2, end, 1e-12); + } + + [Fact] + public void AParameterBoundEndFollowsTheParameter() + { + var leaf = SyntheticFamily.Leaf().Without(34); + var bound = leaf with { Associations = [new(SyntheticFamily.Extrusion, -1001801, Height)] }; + + var (_, start, end) = Shape(bound, 3, 5); + + Assert.Equal((0, 5), (start, end)); + } + + // The parameter of an extrusion end is an offset from the sketch plane: zero or below is a valid place for it, while + // the same value of a labelled dimension would collapse a segment. + [Theory] + [InlineData(0)] + [InlineData(-0.5)] + public void AParameterBoundStartMayBeAtOrBelowTheSketchPlane(double offset) + { + const long Offset = 102; + var leaf = SyntheticFamily.Leaf().Without(34); + var model = Model(leaf with { Associations = [new(SyntheticFamily.Extrusion, -1001800, Offset)] }); + var values = new Dictionary { [Width] = 3, [Height] = 2, [Offset] = offset }; + + var solution = FamilySolver.Solve(model, values); + + Assert.Null(solution.Refusal); + Assert.Null(FamilyContourChecks.Check(model, solution.Positions!, values)); + Assert.Equal(offset, solution.Positions![model.Extrusions[0].Start], 1e-12); + } + + [Fact] + public void ADownwardSketchPlaneSwapsTheCapsOfTheModel() + { + var leaf = SyntheticFamily.Leaf().Without(34); + var (_, start, end) = Shape(leaf.WithExtrusion(e => e with { PlaneNormal = [0, 0, -1] })); + + Assert.Equal((-2, 0), (start, end)); + } + + // Edge 6 is the edge of the first profile curve on the cap j: 0 the end cap, 1 the start cap. The right side plane + // aligned to the end of that edge holds only when that end is read as the right one; the left one contradicts the width. + // The profile curve runs to the right either way, also when the sketch line is drawn the other way. + [Theory] + [InlineData(0, 1, false)] + [InlineData(1, 0, false)] + [InlineData(0, 1, true)] + [InlineData(1, 0, true)] + public void AnEdgeEndFollowsItsProfileCurve(int cap, int sub, bool reversed) + { + var leaf = SyntheticFamily.Leaf(); + if (reversed) leaf = leaf.WithFirstCurveReversed(); + var aligned = leaf.WithExtrusion(e => e with { EdgeHistory = new Dictionary { [6] = [1, 0, cap] } }) + .Add(SyntheticFamily.Alignment(35, 0, (3, 0, -1), (SyntheticFamily.Extrusion, 6, sub))); + + Assert.Null(Solve(aligned).Refusal); + Assert.Null(Solve(aligned, 4).Refusal); + } + + [Fact] + public void AWholeCapEdgeAlongTheExtrusionIsItsCap() + { + var leaf = SyntheticFamily.Leaf().WithExtrusion(e => e with + { + EdgeHistory = new Dictionary { [6] = [1, 0, 0], [7] = [1, 0, 1] }, + }); + // The labelled height now runs from the edge on the start cap to the edge on the end cap, and the level holds the + // lower one. + var labelled = leaf.Without(24).Without(34) + .Add(SyntheticFamily.Linear(24, 2, 8, + [(SyntheticFamily.Extrusion, 7, -1), (SyntheticFamily.Extrusion, 6, -1)], [0], [Height], [2])) + .Add(SyntheticFamily.Alignment(36, 2, (7, 0, -1), (SyntheticFamily.Extrusion, 7, -1))); + + var (_, start, end) = Shape(labelled, 3, 5); + + Assert.Equal((0, 5), (start, end)); + } + + [Fact] + public void ASideEdgeTakesTheCurveAcrossTheAxis() + { + var leaf = SyntheticFamily.Leaf().WithExtrusion(e => e with + { + EdgeHistory = new Dictionary { [8] = [2, 0, 1] }, + }); + var aligned = leaf.Add(SyntheticFamily.Alignment(35, 0, (3, 0, -1), (SyntheticFamily.Extrusion, 8, -1))); + + Assert.Null(Solve(aligned, 4).Refusal); + } + + [Fact] + public void AnArcInTheProfileIsUnsupported() => + AssertRefused(SyntheticFamily.Leaf().WithLine(41, line => line with { IsStraight = false }), + "unsupported-construct", "41"); + + [Fact] + public void ASlantedLineIsUnsupported() => + AssertRefused(SyntheticFamily.Leaf().WithLine(41, line => line with { End = [1.5, -0.4, 0] }), + "unsupported-construct", "41"); + + [Fact] + public void ASlantedDimensionIsUnsupported() + { + var leaf = SyntheticFamily.Leaf(); + AssertRefused(leaf with + { + Dimensions = leaf.Dimensions.Select(d => d.Id == 21 ? d with { Axis = [0.6, 0.8, 0] } : d).ToList(), + }, "unsupported-construct", "21"); + } + + [Theory] + [InlineData(Width)] + [InlineData(Height)] + public void AFormulaOnADrivingParameterIsUnsupported(long parameter) => + AssertRefused(SyntheticFamily.Leaf() with { FormulaParameterIds = new HashSet { parameter } }, + "unsupported-construct", parameter.ToString()); + + [Fact] + public void VisibleUnsupportedContentRefuses() => + AssertRefused(SyntheticFamily.Leaf() with { UnsupportedContent = ["FamilyInstance 70"] }, + "unsupported-construct", "FamilyInstance 70"); + + [Theory] + [InlineData(false, 4)] + [InlineData(false, 14)] + [InlineData(true, 8)] + public void UnknownDimensionFlagsRefuse(bool alignment, long flags) + { + var leaf = SyntheticFamily.Leaf(); + int id = alignment ? 30 : 21; + AssertRefused(leaf with + { + Dimensions = leaf.Dimensions.Select(d => d.Id == id ? d with { Flags = flags } : d).ToList(), + }, "unrecognized-reference", id.ToString()); + } + + [Fact] + public void AnUnlockedAlignmentRefuses() + { + var leaf = SyntheticFamily.Leaf(); + AssertRefused(leaf with + { + Dimensions = leaf.Dimensions.Select(d => d.Id == 30 ? d with { SegmentFlags = [0] } : d).ToList(), + }, "unrecognized-reference", "30"); + } + + [Fact] + public void AnUnknownReferrerRefuses() => + AssertRefused(SyntheticFamily.Leaf().Add(new FamilyReferrer(60, "AngularDimString", + "GeomSegInPlaneRef.GeomRef.m_elemId", 2)), "unrecognized-reference", "AngularDimString"); + + [Fact] + public void ReferrersOfNoEffectAreAccepted() => + Model(SyntheticFamily.Leaf() + .Add(new FamilyReferrer(60, "DBViewPlan", "PlanViewRange2.PlanViewRange2.m_levelIds", 7)) + .Add(new FamilyReferrer(61, "ConnectorElem", "GeomOnPlaneRef.GeomRef.m_elemId", SyntheticFamily.Extrusion)) + .Add(new FamilyReferrer(62, "FamilyInstance", "Element.m_assocLevelId", 7)) + .Add(new FamilyReferrer(63, "RadialDim", "ArcRef.GeomRef.m_elemId", 999))); + + // A line that follows a form edge is placed by that edge, which nothing here models. + [Fact] + public void AProfileLineThatFollowsAnEdgeRefuses() => + AssertRefused(SyntheticFamily.Leaf().Add(new FamilyReferrer(41, "CurveElem", + "EdgeRefCurveData.GeomRef.m_elemId", SyntheticFamily.Extrusion)), "unrecognized-reference", "CurveElem"); + + // A line that the end of another lies on records that join on its side; the other records it as the join of its end. + [Theory] + [InlineData(true)] + [InlineData(false)] + public void ASideJoinNeedsTheJoinOfTheOtherEnd(bool recorded) + { + var leaf = SyntheticFamily.Leaf(); + var sided = (leaf with + { + Joints = [.. leaf.Joints, .. recorded ? [new FamilySketchJoint(42, 0, 41, -1)] : Array.Empty()], + }).Add(new FamilyReferrer(41, "CurveElem", "CDJoinInfo.EndInfo.m_elemId", 42)); + + if (recorded) Model(sided); + else AssertRefused(sided, "unrecognized-reference", "CurveElem 41"); + } + + [Fact] + public void AnUnknownAssociationRefuses() => + AssertRefused(SyntheticFamily.Leaf() with { Associations = [new(SyntheticFamily.Extrusion, -1234, Width)] }, + "unrecognized-reference", "-1234"); + + [Fact] + public void AnUnknownSketchConstraintRefuses() => + AssertRefused(SyntheticFamily.Leaf() with { Constraints = [new(40, "VarSketchEqualRadiusConstrObj")] }, + "unrecognized-reference", "VarSketchEqualRadiusConstrObj"); + + // A helper sketch no extrusion uses holds the end of one line on another; the join says where. + [Theory] + [InlineData(true)] + [InlineData(false)] + public void APointOnLineConstraintNeedsItsJoin(bool joined) + { + var leaf = SyntheticFamily.Leaf(); + var helper = leaf with + { + Lines = [.. leaf.Lines, new(61, 60, true, [-1.5, 0, 0], [1.5, 0, 0]), + new(62, 60, true, [1.5, -1, 0], [1.5, 1, 0])], + Joints = [.. leaf.Joints, .. joined ? [new FamilySketchJoint(61, 1, 62, -1)] : Array.Empty()], + Constraints = [.. leaf.Constraints, new(60, "VarSketchPtOnLSegConstrObj")], + Dimensions = [.. leaf.Dimensions, SyntheticFamily.Alignment(35, 0, (3, 0, -1), (62, 0, -1))], + }; + + if (joined) Assert.Null(Solve(helper, 4).Refusal); + else AssertRefused(helper, "unrecognized-reference", "VarSketchPtOnLSegConstrObj"); + } + + // The X group is held by the centre plane, the oldest in it; without that setting no anchor of a checked kind holds it. + [Fact] + public void AnUnverifiedAnchorRefuses() + { + var leaf = SyntheticFamily.Leaf(); + AssertRefused(leaf with + { + Planes = leaf.Planes.Select(p => p.ElementId == 1 ? p with { ReferenceName = 12 } : p).ToList(), + }, "unverified-anchor", "1"); + } + + [Fact] + public void APinnedPlaneAnchorsAGroupWithOlderElements() + { + var leaf = SyntheticFamily.Leaf(); + var pinned = leaf with + { + Planes = leaf.Planes.Select(p => p.ElementId switch + { + 1 => p with { ReferenceName = 12 }, + 3 => p with { Pinned = true }, + _ => p, + }).ToList(), + }; + + var (corners, _, _) = Shape(pinned, 4); + + // The right side stays; the centre and the left side move. + Assert.Equal([(-2.5, -0.5), (1.5, -0.5), (1.5, 0.5), (-2.5, 0.5)], corners); + } + + [Fact] + public void AnUnlockedSegmentHoldsUnlessDriven() + { + var leaf = SyntheticFamily.Leaf().Without(22); + var unlocked = SyntheticFamily.Linear(35, 1, 28, [(4, 0, -1), (5, 0, -1)], [0], [-1], [0.5]); + + var (corners, _, _) = Shape(leaf.Add(unlocked)); + Assert.Equal((-1.5, -0.5), corners[0]); + + var driven = leaf.Add(unlocked with { DrivenSegments = new HashSet { 0 } }); + AssertRefused(driven, "unverified-anchor", "5"); + } + + // A joint is what makes two curves share a corner: equal coordinates alone do not. + [Fact] + public void AMissingJointLeavesTheShapeUnderdetermined() + { + var leaf = SyntheticFamily.Leaf(); + var solution = Solve(leaf with { Joints = leaf.Joints.Where(j => j.LineId != 41).ToList() }, 4); + + Assert.Equal("underdetermined", solution.Refusal!.Code); + } + + // At the saved values, joined ends that are apart show that the records are not read right. + [Fact] + public void AJointBetweenEndsThatAreApartIsInconsistent() => + AssertRefused(SyntheticFamily.Leaf().WithLine(42, line => line with { Start = [1.5, -0.6, 0] }), + "inconsistent", "41"); + + [Fact] + public void AReferenceToAnUnknownElementRefuses() => + AssertRefused(SyntheticFamily.Leaf().Add(SyntheticFamily.Alignment(35, 0, (3, 0, -1), (999, 0, -1))), + "unrecognized-reference", "999"); + + [Fact] + public void AHostFaceTakesItsPlaceFromAnAlignment() + { + var leaf = SyntheticFamily.Leaf(); + // The level goes; the host, older than the top plane, holds the Z group instead. + var hosted = leaf with + { + Planes = [.. leaf.Planes.Where(p => p.ElementId != 7), new(7, "SWall", 0, [], [])], + Dimensions = [.. leaf.Dimensions, SyntheticFamily.Alignment(35, 2, (7, 3, -1), (SyntheticFamily.Extrusion, 1, -1))], + }; + var bottom = hosted.WithExtrusion(e => e with { PlaneHost = null }); + var records = bottom with + { + Dimensions = bottom.Dimensions.Select(d => d.Id == 24 + ? d with { References = [new(7, 3, -1), new(8, 0, -1)] } : d).ToList(), + }; + + var (_, start, end) = Shape(records, 3, 5); + + Assert.Equal((0, 5), (start, end)); + } + + [Fact] + public void AMaterialOfAFaceIsKeptForItsSide() + { + var leaf = SyntheticFamily.Leaf().WithExtrusion(e => e with + { + FaceMaterials = new Dictionary { [0] = 11, [1] = 12, [3] = 13 }, + }); + var materials = Assert.Single(Model(leaf).Extrusions).Materials; + + Assert.Equal(12, materials[new(FamilyFaceKind.StartCap, 0)]); + Assert.Equal(11, materials[new(FamilyFaceKind.EndCap, 0)]); + Assert.Equal(13, materials[new(FamilyFaceKind.Side, 0, 1)]); + } + + [Fact] + public void MaterialAndVisibilityParametersAreCarried() + { + var model = Model(SyntheticFamily.Leaf() with + { + Associations = [new(SyntheticFamily.Extrusion, -1002107, 200), new(SyntheticFamily.Extrusion, -1006205, 201)], + }); + + Assert.Equal((200L, 201L), (model.Extrusions[0].MaterialParameterId, model.Extrusions[0].VisibilityParameterId)); + } + + [SkippableFact] + public void EveryPrivateFamilyBuildsOrRefuses() + { + foreach (string path in FamilyFiles.All()) + { + var document = RvtDocument.Open(path); + if (document.RawData.Family is not { Types.Types.Count: > 0 } family) continue; + Assert.True(family.Records is not null, $"{path}: the records of a family with types"); + var records = family.Records!; + var (model, refusal) = FamilyModelBuilder.Build(records); + Assert.True(model != null ^ refusal != null, $"{path}: a model or a refusal"); + if (refusal != null) + Assert.Contains(refusal.Code, new[] { "unsupported-construct", "unrecognized-reference", + "unverified-anchor", "inconsistent", "underdetermined" }); + } + } + + private static void AssertRefused(FamilyRecords records, string code, string detail) + { + var (model, refusal) = FamilyModelBuilder.Build(records); + + Assert.Null(model); + Assert.Equal(code, refusal!.Code); + Assert.Contains(detail, refusal.Detail); + } +} + +/// A box 3 wide, 1 deep and 2 high, made as a family template makes one: sides held by reference planes, equally +/// far from centre planes, a labelled width, a locked depth, and a labelled height from the level to a top plane that the +/// end of the extrusion is aligned to. +internal static class SyntheticFamily +{ + public const int Extrusion = 50; + private const long Width = 100, Height = 101; + + public static FamilyRecords Leaf() + { + // Planes: 1 centre left/right, 2 left, 3 right, 4 centre front/back, 5 front, 6 back, 7 level, 8 top. + FamilyPlaneRecord[] planes = + [ + new(1, "RefPlane", 1, [0, 0, 0], [1, 0, 0]), new(2, "RefPlane", 12, [-1.5, 0, 0], [1, 0, 0]), + new(3, "RefPlane", 12, [1.5, 0, 0], [1, 0, 0]), new(4, "RefPlane", 4, [0, 0, 0], [0, 1, 0]), + new(5, "RefPlane", 3, [0, -0.5, 0], [0, 1, 0]), new(6, "RefPlane", 5, [0, 0.5, 0], [0, 1, 0]), + new(7, "Level", 0, [0, 0, 0], [0, 0, 1]), new(8, "RefPlane", 8, [0, 0, 2], [0, 0, 1]), + ]; + FamilyDimensionRecord[] dimensions = + [ + Linear(20, 0, 136, [(2, 0, -1), (1, 0, -1), (3, 0, -1)], [2, 2], [-1, -1], [1.5, 1.5]), + Linear(21, 0, 8, [(2, 0, -1), (3, 0, -1)], [0], [Width], [3]), + Linear(22, 1, 140, [(5, 0, -1), (4, 0, -1), (6, 0, -1)], [2, 2], [-1, -1], [0.5, 0.5]), + Linear(23, 1, 12, [(5, 0, -1), (6, 0, -1)], [1], [-1], [1]), + Linear(24, 2, 8, [(7, 0, -1), (8, 0, -1)], [0], [Height], [2]), + Alignment(30, 1, (5, 0, -1), (41, 0, -1)), Alignment(31, 0, (3, 0, -1), (42, 0, -1)), + Alignment(32, 1, (6, 0, -1), (43, 0, -1)), Alignment(33, 0, (2, 0, -1), (44, 0, -1)), + Alignment(34, 2, (8, 0, -1), (Extrusion, 0, -1)), + ]; + // Lines 41-44: front, right, back and left, drawn counter-clockwise on the level. + FamilySketchLine[] lines = + [ + new(41, 40, true, [-1.5, -0.5, 0], [1.5, -0.5, 0]), new(42, 40, true, [1.5, -0.5, 0], [1.5, 0.5, 0]), + new(43, 40, true, [1.5, 0.5, 0], [-1.5, 0.5, 0]), new(44, 40, true, [-1.5, 0.5, 0], [-1.5, -0.5, 0]), + ]; + FamilySketchJoint[] joints = [new(41, 1, 42, 0), new(42, 1, 43, 0), new(43, 1, 44, 0), new(44, 1, 41, 0)]; + var extrusion = new FamilyExtrusionRecord(Extrusion, 40, 0, 2, [0, 0, 0], [0, 0, 1], new(7, 0, -1), [[0, 1, 2, 3]], + new Dictionary + { + [0] = new(41, false), [1] = new(42, false), [2] = new(43, false), [3] = new(44, false), + }, + new Dictionary { [1] = [1], [0] = [2], [2] = [3, 0], [3] = [3, 1], [4] = [3, 2], [5] = [3, 3] }, + new Dictionary(), new Dictionary()); + return new FamilyRecords(dimensions, lines, joints, + [new(40, "VarSketchPPConstrObj"), new(40, "VarSketchHorVerConstrObj")], planes, [extrusion], + [ + new(20, "LinearDimString", "GeomSegInPlaneRef.GeomRef.m_elemId", 2), + new(30, "Alignment", "GeomSegInPlaneRef.GeomRef.m_elemId", 41), + new(51, "SketchPlane", "OnDatumPlaneRef.OneElementMovablePlaneRef.m_datumPlaneId", 7), + new(Extrusion, "ExtrusionElem", "ExtrusionElemExtrusionHelper.ExtrusionHelper.m_sketchId", 40), + new(41, "CurveElem", "CurveElemDriver.EndInfo.m_elemId", 42), + new(40, "VarSketch", "ElementIdIndexPairSet.ElementIdPlusIndex.m_elementId", 41), + ], [], new HashSet(), []); + } + + public static FamilyDimensionRecord Linear(int id, int axis, long flags, (int, int, int)[] references, + long[] segmentFlags, long[] parameters, double[] values) => + new(id, false, Axis(axis), flags, segmentFlags, References(references), parameters, values, new HashSet()); + + public static FamilyDimensionRecord Alignment(int id, int axis, params (int, int, int)[] references) => + new(id, true, Axis(axis), 14, [1], References(references), [-1], [0], new HashSet()); + + private static double[] Axis(int axis) => [axis == 0 ? 1 : 0, axis == 1 ? 1 : 0, axis == 2 ? 1 : 0]; + + private static FamilyReference[] References((int Element, int Tag, int Sub)[] references) => + references.Select(r => new FamilyReference(r.Element, r.Tag, r.Sub)).ToArray(); + + public static FamilyRecords Without(this FamilyRecords records, int dimension) => + records with { Dimensions = records.Dimensions.Where(d => d.Id != dimension).ToList() }; + + public static FamilyRecords Add(this FamilyRecords records, FamilyDimensionRecord dimension) => + records with { Dimensions = [.. records.Dimensions, dimension] }; + + public static FamilyRecords Add(this FamilyRecords records, FamilyReferrer referrer) => + records with { Referrers = [.. records.Referrers, referrer] }; + + public static FamilyRecords WithExtrusion(this FamilyRecords records, + Func change) => + records with { Extrusions = [change(records.Extrusions[0])] }; + + public static FamilyRecords WithLine(this FamilyRecords records, int id, + Func change) => + records with { Lines = records.Lines.Select(line => line.Id == id ? change(line) : line).ToList() }; + + /// Line 41 drawn from right to left, so that its profile curve runs against it. + public static FamilyRecords WithFirstCurveReversed(this FamilyRecords records) => + records.WithLine(41, line => line with { Start = line.End, End = line.Start }) with + { + Joints = [new(41, 0, 42, 0), new(42, 1, 43, 0), new(43, 1, 44, 0), new(44, 1, 41, 1)], + Extrusions = [records.Extrusions[0] with + { + ProfileCurves = new Dictionary(records.Extrusions[0].ProfileCurves) + { + [0] = new(41, true), + }, + }], + }; +} diff --git a/tests/RvtIO.Tests/Families/FamilyRelationReaderTests.cs b/tests/RvtIO.Tests/Families/FamilyRelationReaderTests.cs new file mode 100644 index 00000000..9f01202c --- /dev/null +++ b/tests/RvtIO.Tests/Families/FamilyRelationReaderTests.cs @@ -0,0 +1,31 @@ +using RvtIO.Families; +using RvtIO.Parsing; +using Xunit; + +namespace RvtIO.Tests.Families; + +public class FamilyRelationReaderTests +{ + private static SchemaDocument Schema(string name, params string[] fields) + { + var schema = new SchemaDocument(); + schema.Classes.Add(new(1, name, 0, 1, + [.. fields.Select(field => new SchemaField(field, 0, 0, 0, null, null, null, null))], [])); + return schema; + } + + // A field another version names otherwise would not be read, and nothing would say so: no association is read, say. + [Fact] + public void AClassWithoutAFieldTheReaderNeedsIsNotRead() => + Assert.Equal("ParamIdPair.m_elemPropId", + FamilyRelationReader.MissingField(Schema("ParamIdPair", "m_famParamId", "m_renamed"))); + + [Theory] + [InlineData("m_int")] + [InlineData("m_int64")] + public void EitherNameOfThePairNumberIsEnough(string number) => + Assert.Null(FamilyRelationReader.MissingField(Schema("ElementIdIntPair", "m_elementId", number))); + + [Fact] + public void AClassTheSchemaLacksIsNotMissed() => Assert.Null(FamilyRelationReader.MissingField(Schema("Other", "m_a"))); +} diff --git a/tests/RvtIO.Tests/Families/FamilyRevitOracleTests.cs b/tests/RvtIO.Tests/Families/FamilyRevitOracleTests.cs new file mode 100644 index 00000000..d0a7e243 --- /dev/null +++ b/tests/RvtIO.Tests/Families/FamilyRevitOracleTests.cs @@ -0,0 +1,145 @@ +using System.Globalization; +using RvtIO.Meshes; +using Xunit; +using Xunit.Abstractions; + +namespace RvtIO.Tests.Families; + +/// The computed types of private families against what Revit builds for them. An oracle is a file +/// "families/*.revit.tsv" of a fixture folder. Its first line, "file TAB path", names the family; then for each type either +/// "type TAB refused", or "type TAB applied" and a line "type TAB element id TAB x TAB y TAB z" per vertex, in +/// millimetres, of each form Revit shows. +public sealed class FamilyRevitOracleTests(ITestOutputHelper output) +{ + private const double Tolerance = 0.01, MillimetresPerFoot = 304.8; + + private sealed record Oracle(string Name, string Family, + Dictionary>> Applied, List Refused); + + private static List Oracles() + { + foreach (string root in TestFiles.Roots()) + { + string folder = Path.Combine(root, "families"); + if (Directory.Exists(folder) && Directory.GetFiles(folder, "*.revit.tsv") is { Length: > 0 } files) + return files.Order(StringComparer.Ordinal).Select(Read).ToList(); + } + throw TestFiles.Missing("families/*.revit.tsv"); + } + + private static Oracle Read(string path) + { + string[] lines = File.ReadAllLines(path); + string[] head = lines[0].Split('\t'); + Assert.Equal("file", head[0]); + var applied = new Dictionary>>(StringComparer.Ordinal); + var refused = new List(); + foreach (string[] cells in lines.Skip(1).Select(line => line.Split('\t'))) + { + if (cells is [var rejected, "refused"]) refused.Add(rejected); + else if (cells is [var accepted, "applied"]) applied.Add(accepted, []); + else + { + Assert.Equal(5, cells.Length); + int element = int.Parse(cells[1], CultureInfo.InvariantCulture); + if (!applied[cells[0]].TryGetValue(element, out var vertices)) applied[cells[0]][element] = vertices = []; + vertices.Add(cells.Skip(2).Select(cell => double.Parse(cell, CultureInfo.InvariantCulture)).ToArray()); + } + } + return new(Path.GetFileName(path), head[1], applied, refused); + } + + /// The document and its type indices by name, the name cleaned as the oracle writes it. + private static (RvtDocument Document, Dictionary Types) Open(Oracle oracle) + { + var document = RvtDocument.Open(oracle.Family, new RvtReaderOptions { R22Layout = true }); + var types = document.FamilyTypes!.Types + .Select((type, index) => (Name: type.Name.Replace('\t', ' ').Replace('\r', ' ').Replace('\n', ' '), index)) + .ToDictionary(type => type.Name, type => type.index, StringComparer.Ordinal); + return (document, types); + } + + private static List Differences(Dictionary> expected, IReadOnlyList shown) + { + var ours = shown.Where(element => element.Meshes.Count > 0).ToDictionary(element => element.ElementId, + element => element.Meshes.SelectMany(mesh => Enumerable.Range(0, mesh.Positions.Length / 3).Select(vertex => + Enumerable.Range(0, 3).Select(axis => mesh.Positions[3 * vertex + axis] * MillimetresPerFoot).ToArray())).ToList()); + return expected.Keys.Union(ours.Keys).Where(id => !expected.TryGetValue(id, out var there) + || !ours.TryGetValue(id, out var here) || !Covered(there, here) || !Covered(here, there)).ToList(); + + static bool Covered(List points, List by) => points.All(point => + by.Any(other => Math.Sqrt(Enumerable.Range(0, 3).Sum(axis => Math.Pow(point[axis] - other[axis], 2))) <= Tolerance)); + } + + [SkippableFact] + public void NoShownTypeDiffersFromRevit() + { + var wrong = new List(); + int compared = 0; + foreach (var oracle in Oracles()) + { + var (document, types) = Open(oracle); + int shown = 0; + var refusals = new List(); + foreach (var (name, expected) in oracle.Applied) + { + var computed = ElementMeshes.ComputeFamilyType(document, types[name]); + if (computed.Elements is not { } elements) + { + refusals.Add($"{name}: {computed.Refusal!.Code} {computed.Refusal.Detail}"); + continue; + } + shown++; + if (Differences(expected, elements) is { Count: > 0 } ids) + wrong.Add($"{oracle.Name} '{name}': elements {string.Join(",", ids)}"); + } + // A type that is shown without Revit's answer for it is not verified. + foreach (var (name, index) in types) + if (!oracle.Applied.ContainsKey(name) && !oracle.Refused.Contains(name) + && ElementMeshes.ComputeFamilyType(document, index).Elements != null) + wrong.Add($"{oracle.Name} '{name}': not in the oracle"); + output.WriteLine($"{oracle.Name}: Revit applied {oracle.Applied.Count} types, shown {shown}; " + + $"not shown: {string.Join("; ", refusals)}"); + compared += shown; + } + Assert.Empty(wrong); + Assert.True(compared > 0, "No type was compared."); + } + + [SkippableFact] + public void ATypeRevitRefusesIsRefused() + { + foreach (var oracle in Oracles().Where(oracle => oracle.Refused.Count > 0)) + { + var (document, types) = Open(oracle); + foreach (string name in oracle.Refused) + { + var computed = ElementMeshes.ComputeFamilyType(document, types[name]); + output.WriteLine($"{oracle.Name} '{name}': {computed.Refusal?.Code}"); + Assert.True(computed.Elements == null, $"{oracle.Name} '{name}' is shown"); + } + } + } + + [SkippableFact] + public void TheComparisonIsSensitive() + { + foreach (var oracle in Oracles()) + { + var (document, types) = Open(oracle); + foreach (var (name, expected) in oracle.Applied.Where(type => type.Value.Count > 0)) + { + if (ElementMeshes.ComputeFamilyType(document, types[name]).Elements is not { } elements) continue; + var (element, vertices) = expected.First(); + var moved = new Dictionary>(expected) + { + [element] = [[vertices[0][0] + 0.05, vertices[0][1], vertices[0][2]], .. vertices.Skip(1)], + }; + + Assert.Equal([element], Differences(moved, elements)); + return; + } + } + Assert.Fail("No oracle has a type that is shown."); + } +} diff --git a/tests/RvtIO.Tests/Families/FamilySavedStateTests.cs b/tests/RvtIO.Tests/Families/FamilySavedStateTests.cs new file mode 100644 index 00000000..20286354 --- /dev/null +++ b/tests/RvtIO.Tests/Families/FamilySavedStateTests.cs @@ -0,0 +1,101 @@ +using RvtIO.Families; +using RvtIO.Model; +using Xunit; + +namespace RvtIO.Tests.Families; + +public class FamilySavedStateTests +{ + private const int Material = 40; + + private static int Own(FamilyExtrusion extrusion, FamilyFaceKey key) => Material; + + private static Dictionary Values(double width = 3) => new() { [100] = width, [101] = 2 }; + + private static FamilyModel Leaf() => FamilyModelBuilder.Build(SyntheticFamily.Leaf()).Model!; + + private static List Stored(FamilyModel model, int extrusion = 0) => FamilyExtrusionBuilder.Faces( + model.Extrusions[extrusion], model.Variables.Select(v => v.Stored).ToArray(), _ => Material); + + private static Dictionary> Of(int element, List faces) => new() { [element] = faces }; + + /// A plate 4 by 4 and 1 high, with a square hole 2 by 2, whose variables are all anchored. + private static FamilyModel Plate() + { + double[] stored = [0, 4, 1, 3, 0, 1]; + var variables = stored.Select(value => new FamilyVariable(value, true)).ToList(); + FamilyVertex[] Square(int low, int high) => [new(low, low, 4), new(high, low, 4), new(high, high, 4), new(low, high, 4)]; + return new(variables, [], + [new(7, [Square(0, 1), Square(2, 3)], 2, 4, 5, new Dictionary(), null, null)]); + } + + [Fact] + public void TheStoredStateMatches() + { + Assert.Null(FamilySavedState.Check(Leaf(), Values(), Own, Of(50, Stored(Leaf())))); + Assert.Null(FamilySavedState.Check(Plate(), Values(), Own, Of(7, Stored(Plate())))); + } + + // A stored loop may start at any corner and keep a point in the middle of a straight side. + [Fact] + public void AStoredLoopMayStartElsewhereAndKeepPointsOnItsSides() + { + var faces = Stored(Leaf()); + foreach (var face in faces) + { + var loop = face.OuterVertices!; + double[] middle = [(loop[0][0] + loop[1][0]) / 2, (loop[0][1] + loop[1][1]) / 2, (loop[0][2] + loop[1][2]) / 2]; + face.OuterVertices = [loop[2], loop[3], loop[0], middle, loop[1]]; + } + + Assert.Null(FamilySavedState.Check(Leaf(), Values(), Own, Of(50, faces))); + } + + [Theory] + [InlineData("vertex")] + [InlineData("material")] + [InlineData("missing face")] + [InlineData("extra face")] + [InlineData("reversed loop")] + [InlineData("normal")] + public void AStoredFaceThatDiffersIsAMismatch(string difference) + { + var faces = Stored(Leaf()); + if (difference == "vertex") faces[2].OuterVertices![1][0] += 2e-6; + if (difference == "material") faces[2].RenderStyleId = 41; + if (difference == "missing face") faces.RemoveAt(2); + if (difference == "extra face") faces.Add(faces[2]); + if (difference == "reversed loop") faces[2].OuterVertices!.Reverse(); + if (difference == "normal") faces[2].Normal = faces[2].Normal.Select(v => -v).ToArray(); + + var refusal = FamilySavedState.Check(Leaf(), Values(), Own, Of(50, faces)); + + Assert.Equal("saved-state-mismatch", refusal!.Code); + Assert.Contains("50", refusal.Detail); + } + + [Fact] + public void AHoleThatDiffersIsAMismatch() + { + var faces = Stored(Plate()); + faces.First(f => f.InnerVertices != null).InnerVertices![0][0][0] += 2e-6; + + Assert.Equal("saved-state-mismatch", FamilySavedState.Check(Plate(), Values(), Own, Of(7, faces))!.Code); + } + + // No stored faces to compare with is a mismatch, not a pass. + [Fact] + public void NoStoredGeometryIsAMismatch() => + Assert.Equal("saved-state-mismatch", + FamilySavedState.Check(Leaf(), Values(), Own, new Dictionary>())!.Code); + + // The stored positions give a width of 3: the type the file was saved at must say so. + [Fact] + public void ARelationThatTheStoredPositionsBreakIsAMismatch() + { + var refusal = FamilySavedState.Check(Leaf(), Values(3.1), Own, Of(50, Stored(Leaf()))); + + Assert.Equal("saved-state-mismatch", refusal!.Code); + Assert.Contains("21", refusal.Detail); + } +} diff --git a/tests/RvtIO.Tests/Families/FamilySceneTests.cs b/tests/RvtIO.Tests/Families/FamilySceneTests.cs new file mode 100644 index 00000000..7051328a --- /dev/null +++ b/tests/RvtIO.Tests/Families/FamilySceneTests.cs @@ -0,0 +1,450 @@ +using IOScene; +using RvtIO.BuiltIns; +using RvtIO.Families; +using RvtIO.Meshes; +using RvtIO.Model; +using RvtIO.Scene; +using Xunit; + +namespace RvtIO.Tests.Families; + +public sealed class FamilySceneTests +{ + private const int Owner = 5, Form = 100, LevelElement = 10, GridElement = 20; + + private static RevitFileInfo Info(int? owner) => new() + { + FamilyOwnerId = owner, + IsStandaloneFamily = owner != null, + Elements = + [ + new Element { Id = Form, UniqueId = "form" }, + new Element + { + Id = LevelElement, Name = "Level", CategoryId = (int)BuiltInCategory.OST_Levels, + IsNativeLevel = true, SerializedFamilyId = -1, SerializedUnplacedOwnerId = -1, SerializedOwnerDbViewId = -1, + Parameters = + [ + new Parameter { Id = (int)BuiltInParameter.LEVEL_ELEV, StorageType = StorageType.Double, Value = 0.0 }, + new Parameter { Id = (int)BuiltInParameter.LEVEL_IS_BUILDING_STORY, StorageType = StorageType.Integer, Value = 1 }, + ], + }, + new Element + { + Id = GridElement, Name = "A", CategoryId = (int)BuiltInCategory.OST_Grids, + Location = new LocationCurve { StartPoint = [0, 0, 0], EndPoint = [1, 0, 0] }, + }, + ], + }; + + private static ElementMesh Mesh(MeshCoverage coverage = MeshCoverage.Complete, bool drawn = true) => new() + { + ElementId = Form, + Coverage = coverage, + Meshes = drawn ? [new TriangleMesh { Positions = [0, 0, 0, 1, 0, 0, 0, 1, 0], Indices = [0, 1, 2], Normals = [0, 0, 1, 0, 0, 1, 0, 0, 1] }] : [], + }; + + private static RvtSceneResult Map(ElementMesh mesh, int? owner = Owner, string[]? gaps = null) => + RvtSceneReader.Read(RvtDocument.FromInfo(Info(owner)), new MeshSet { Elements = [mesh], FamilyGaps = gaps ?? [] }, + new RvtSceneOptions { ModelKey = "family.rfa" }); + + [Fact] + public void AFamilySceneHasNoLevelsOrGrids() + { + var project = Map(Mesh(), owner: null); + // The same elements give a project a level and a grid. + Assert.Single(project.Document.Levels); + Assert.Single(project.Document.Grids); + + var family = Map(Mesh()); + Assert.Empty(family.Document.Levels); + Assert.Empty(family.Document.Grids); + Assert.Null(Assert.Single(family.Document.Elements).LevelId); + } + + [Fact] + public void AGapMarksTheFamilyIncomplete() + { + var mark = Assert.Single(Map(Mesh(), gaps: ["void", "visibility"]).Diagnostics, d => d.Code == "family-incomplete"); + + Assert.Equal(SceneSeverity.Warning, mark.Severity); + Assert.Contains("void, visibility", mark.Message); + } + + [Fact] + public void APartialElementMarksItToo() + { + var mark = Assert.Single(Map(Mesh(MeshCoverage.Partial)).Diagnostics, d => d.Code == "family-incomplete"); + + Assert.Contains("partial-geometry", mark.Message); + } + + [Fact] + public void ACompleteFamilyIsNotMarked() => + Assert.DoesNotContain(Map(Mesh()).Diagnostics, d => d.Code == "family-incomplete"); + + [Fact] + public void AHiddenFormIsAnElementWithoutInstances() + { + var result = Map(Mesh(drawn: false)); + + Assert.Single(result.Document.Elements); + Assert.Empty(result.Document.Instances); + Assert.DoesNotContain(result.Diagnostics, d => d.Code == "family-incomplete"); + } + + private const int Material = 40, Other = 41; + + private static RvtSceneResult MapTypes(RvtFamilyTypes? types, string? error = null) + { + var info = Info(Owner); + info.Elements.Add(new Element { Id = Material, Name = "Concrete", CategoryId = (int)BuiltInCategory.OST_Materials }); + info.Elements.Add(new Element { Id = Other, Name = "Something", CategoryId = (int)BuiltInCategory.OST_GenericModel }); + info.Family = new FamilyData { Elements = [], Types = types, TypesError = error }; + return RvtSceneReader.Read(RvtDocument.FromInfo(info), new MeshSet { Elements = [Mesh()] }, + new RvtSceneOptions { ModelKey = "family.rfa" }); + } + + private static RvtFamilyTypes Types(int saved, params string[] names) => + new(saved, names.Select(name => new RvtFamilyType(name, [])).ToArray()); + + [Fact] + public void TheSavedTypeIsTheSceneAndAFamilyWithoutRecordsComputesNothing() + { + var types = MapTypes(Types(1, "A", "B")).FamilyTypes!; + + Assert.Equal(1, types.SavedIndex); + Assert.Equal(["A", "B"], types.Types.Select(t => t.Name)); + Assert.All(types.Types, t => Assert.Null(t.Instances)); + Assert.Equal("unrecognized-reference", types.Types[0].Refusal!.Code); + Assert.Null(types.Types[1].Refusal); + Assert.Empty(types.Geometries); + Assert.Empty(types.Materials); + } + + private const int Steel = 42, Extrusion = SyntheticFamily.Extrusion, Free = 80, Shown = 200, Finish = 201; + + /// A family whose saved type is the first one, with the forms of stored as the builder + /// makes them at their stored positions, in concrete. + private static RevitFileInfo Computed(RvtFamilyType[] types, FamilyRecords? records = null, + IEnumerable? hidden = null, Action>? alter = null, params FamilyElementFacts[] others) + { + records = InConcrete(records ?? SyntheticFamily.Leaf()); + var model = FamilyModelBuilder.Build(records).Model!; + var positions = model.Variables.Select(variable => variable.Stored).ToArray(); + var info = new RevitFileInfo { FamilyOwnerId = Owner, IsStandaloneFamily = true }; + info.Elements.Add(new Element { Id = Material, Name = "Concrete", CategoryId = (int)BuiltInCategory.OST_Materials }); + info.Elements.Add(new Element { Id = Steel, Name = "Steel", CategoryId = (int)BuiltInCategory.OST_Materials }); + var facts = new List(); + foreach (var extrusion in model.Extrusions) + { + var faces = FamilyExtrusionBuilder.Faces(extrusion, positions, _ => Material); + alter?.Invoke(faces); + var geometry = new GeometryData(); + geometry.Faces.AddRange(faces); + info.Elements.Add(new Element { Id = extrusion.ElementId, UniqueId = "x" + extrusion.ElementId, Geometry = geometry }); + facts.Add(new(extrusion.ElementId, "ExtrusionElem", true, true, false, true, + hidden?.Contains(extrusion.ElementId) == true)); + } + foreach (var other in others) + { + info.Elements.Add(new Element { Id = other.ElementId, UniqueId = "o" + other.ElementId }); + facts.Add(other); + } + info.Family = new FamilyData { Elements = facts, Types = new(0, types), Records = records }; + return info; + } + + private static FamilyRecords InConcrete(FamilyRecords records) => records with + { + Extrusions = [.. records.Extrusions.Select(extrusion => extrusion with + { + FaceMaterials = extrusion.FaceHistory.Keys.ToDictionary(tag => tag, _ => Material), + })], + }; + + private static RvtFamilyType Type(string name, double width, params Parameter[] more) => + new(name, [Value(100, StorageType.Double, width), Value(101, StorageType.Double, 2.0), .. more]); + + private static RvtSceneResult Scene(RevitFileInfo info) + { + var document = RvtDocument.FromInfo(info); + return RvtSceneReader.Read(document, ElementMeshes.Extract(document), new RvtSceneOptions { ModelKey = "family.rfa" }); + } + + /// The width of the instances of a type, in metres. + private static double WidthOf(RvtSceneResult result, RvtSceneFamilyType type) + { + var geometries = result.Document.Geometries.Concat(result.FamilyTypes!.Geometries).ToDictionary(g => g.Id); + var x = type.Instances!.SelectMany(i => geometries[i.GeometryId].Vertices.Select(v => i.Transform!.Value.Apply(v).X)).ToList(); + return x.Max() - x.Min(); + } + + private static FamilyAssociation Visibility(int element) => + new(element, (long)BuiltInParameter.IS_VISIBLE_PARAM, Shown); + + private static Parameter YesNo(bool shown) => Value(Shown, StorageType.Integer, shown ? 1 : 0); + + /// The leaf and a second box no relation holds: lines 71-74 of sketch 70 and the extrusion + /// . + private static FamilyRecords WithAFreeForm() + { + var leaf = SyntheticFamily.Leaf(); + var box = leaf.Extrusions[0] with + { + Id = Free, SketchId = 70, PlaneHost = null, + ProfileCurves = new Dictionary + { + [0] = new(71, false), [1] = new(72, false), [2] = new(73, false), [3] = new(74, false), + }, + }; + return leaf with + { + Lines = [.. leaf.Lines, new(71, 70, true, [3, -0.5, 0], [4, -0.5, 0]), new(72, 70, true, [4, -0.5, 0], [4, 0.5, 0]), + new(73, 70, true, [4, 0.5, 0], [3, 0.5, 0]), new(74, 70, true, [3, 0.5, 0], [3, -0.5, 0])], + Joints = [.. leaf.Joints, new(71, 1, 72, 0), new(72, 1, 73, 0), new(73, 1, 74, 0), new(74, 1, 71, 0)], + Extrusions = [.. leaf.Extrusions, box], + }; + } + + [Fact] + public void AComputedTypeHasItsOwnGeometry() + { + var result = Scene(Computed([Type("A", 3), Type("B", 4)])); + + var b = result.FamilyTypes!.Types[1]; + Assert.Null(b.Refusal); + Assert.Equal(4 * 0.3048, WidthOf(result, b), 1e-9); + Assert.All(b.Instances!, i => Assert.Equal(Extrusion, i.ElementId)); + Assert.All(b.Instances!, i => Assert.Equal(Material, i.MaterialId)); + } + + [Fact] + public void ADegenerateTypeIsRefused() + { + var c = Scene(Computed([Type("A", 3), Type("C", 0)])).FamilyTypes!.Types[1]; + + Assert.Equal("degenerate-geometry", c.Refusal!.Code); + Assert.Null(c.Instances); + } + + [Fact] + public void EqualTypesShareGeometry() + { + var result = Scene(Computed([Type("A", 3), Type("B", 4), Type("D", 4), Type("E", 3)])); + + var types = result.FamilyTypes!.Types; + Assert.Equal(types[1].Instances!.Select(i => i.GeometryId), types[2].Instances!.Select(i => i.GeometryId)); + Assert.Single(result.FamilyTypes.Geometries); + // The shape of the saved type is the geometry the scene already holds. + Assert.Equal(result.Document.Instances.Select(i => i.GeometryId), types[3].Instances!.Select(i => i.GeometryId)); + } + + [Fact] + public void VisibilityFollowsTheType() + { + var records = SyntheticFamily.Leaf() with { Associations = [Visibility(Extrusion)] }; + + var result = Scene(Computed([Type("A", 3, YesNo(false)), Type("B", 3, YesNo(true))], records, hidden: [Extrusion])); + + Assert.Single(result.Document.Elements); + Assert.Empty(result.Document.Instances); + var b = result.FamilyTypes!.Types[1]; + Assert.Null(b.Refusal); + Assert.Equal(Extrusion, Assert.Single(b.Instances!).ElementId); + } + + [Fact] + public void AHiddenFormDoesNotBlockAType() + { + var records = WithAFreeForm() with { Associations = [Visibility(Free)] }; + + var types = Scene(Computed([Type("A", 3, YesNo(true)), Type("B", 4, YesNo(false)), Type("C", 4, YesNo(true))], + records)).FamilyTypes!.Types; + + Assert.Null(types[1].Refusal); + Assert.Equal(Extrusion, Assert.Single(types[1].Instances!).ElementId); + Assert.Equal("underdetermined", types[2].Refusal!.Code); + } + + [Fact] + public void MaterialFollowsTheType() + { + var records = SyntheticFamily.Leaf() with + { + Associations = [new(Extrusion, (long)BuiltInParameter.MATERIAL_ID_PARAM, Finish)], + }; + + var result = Scene(Computed([Type("A", 3, Value(Finish, StorageType.ElementId, Material)), + Type("B", 3, Value(Finish, StorageType.ElementId, Steel))], records)); + + Assert.All(result.FamilyTypes!.Types[1].Instances!, i => Assert.Equal(Steel, i.MaterialId)); + Assert.Equal(Steel, Assert.Single(result.FamilyTypes.Materials).Id); + } + + [Fact] + public void TheSceneHoldsNothingOfOtherTypes() + { + var info = Computed([Type("A", 3), Type("B", 4)]); + var with = Scene(info); + Assert.NotEmpty(with.FamilyTypes!.Geometries); + info.Family = new FamilyData { Elements = info.Family!.Elements }; + + Assert.Equal(SceneJson.Write(Scene(info).Document), SceneJson.Write(with.Document)); + } + + [Theory] + [InlineData("geometry")] + [InlineData("visibility")] + [InlineData("shown form")] + public void ASavedStateMismatchRefusesEveryComputedType(string difference) + { + var records = difference == "visibility" + ? SyntheticFamily.Leaf() with { Associations = [Visibility(Extrusion)] } : null; + // The saved type hides the form by its parameter, but the form is shown; or a shown form is not in the model. + var types = new[] { "A", "B", "E" }.Select((name, i) => + difference == "visibility" ? Type(name, i == 1 ? 4 : 3, YesNo(false)) : Type(name, i == 1 ? 4 : 3)).ToArray(); + FamilyElementFacts[] others = difference == "shown form" + ? [new(90, "ExtrusionElem", true, true, false, true, false)] : []; + Action>? alter = difference == "geometry" ? faces => faces[0].OuterVertices![0][0] += 0.01 : null; + + var computed = Scene(Computed(types, records, alter: alter, others: others)).FamilyTypes!.Types.Skip(1).ToList(); + + Assert.All(computed, t => Assert.Equal("saved-state-mismatch", t.Refusal!.Code)); + Assert.All(computed, t => Assert.Null(t.Instances)); + } + + [Fact] + public void AnIncompleteFamilyComputesNothing() + { + // A shown form without stored geometry leaves the saved shape incomplete. + var result = Scene(Computed([Type("A", 3), Type("B", 4)], others: new FamilyElementFacts(90, "SweepElem", true, + false, false, true, false))); + + Assert.Contains(result.Diagnostics, d => d.Code == "family-incomplete"); + Assert.Equal("unsupported-construct", result.FamilyTypes!.Types[1].Refusal!.Code); + } + + [Fact] + public void ARefusalOfTheModelIsThatOfEveryComputedType() + { + var info = Computed([Type("A", 3), Type("B", 4)]); + info.Family = new FamilyData + { + Elements = info.Family!.Elements, Types = info.Family.Types, + Records = info.Family.Records! with { UnsupportedContent = ["FamilyInstance 9"] }, + }; + + var refusal = Scene(info).FamilyTypes!.Types[1].Refusal!; + + Assert.Equal(("unsupported-construct", "FamilyInstance 9"), (refusal.Code, refusal.Detail)); + } + + // Meshes the caller gives the scene may leave out elements, and no instance may name an element the scene lacks. + [Fact] + public void ATypeWithAFormTheSceneLacksIsNotShown() + { + var document = RvtDocument.FromInfo(Computed([Type("A", 3), Type("B", 4)])); + + var result = RvtSceneReader.Read(document, new MeshSet { Elements = [] }, + new RvtSceneOptions { ModelKey = "family.rfa" }); + + var b = result.FamilyTypes!.Types[1]; + Assert.Equal("not-computed", b.Refusal!.Code); + Assert.Contains($"{Extrusion}", b.Refusal.Detail); + Assert.Null(b.Instances); + } + + [Fact] + public void ATypeThatIsNotThereCannotBeComputed() + { + var document = RvtDocument.FromInfo(Computed([Type("A", 3)])); + + Assert.Throws(() => ElementMeshes.ComputeFamilyType(document, 1)); + Assert.Throws(() => ElementMeshes.ComputeFamilyType(document, -1)); + } + + private static Parameter Value(int id, StorageType storage, object value, string? spec = null, long? source = null) => + new(new Definition { Id = id, Name = "p" + id }) { Id = id, StorageType = storage, Value = value, SpecType = spec, NativeElementId = source }; + + [Fact] + public void ValueText() + { + const string Length = "autodesk.spec.aec:length-2.0.0"; + const long Wide = 5_000_000_000; + var exact = Value(1, StorageType.Double, 3.0, Length); + (exact.UnitSymbol, exact.ConversionFactor) = ("mm", 304.8); + Parameter[] parameters = + [ + exact, + Value(2, StorageType.Double, 3.0, Length), + Value((int)BuiltInParameter.FAMILY_WIDTH_PARAM, StorageType.Double, 3.0), + Value((int)BuiltInParameter.ALL_MODEL_COST, StorageType.Double, 3.0), + Value(3, StorageType.ElementId, Material), + Value(4, StorageType.ElementId, Material, source: Wide), + Value(5, StorageType.ElementId, Other, source: Wide), + Value(6, StorageType.ElementId, Other), + Value(7, StorageType.String, "Text"), + new() { Id = 8, StorageType = StorageType.None, Definition = new Definition { Id = 8 } }, + ]; + + var values = MapTypes(new(0, [new RvtFamilyType("A", parameters)])).FamilyTypes!.Types[0].Parameters; + + Assert.Equal(["914.4 mm", "914.4 mm", "914.4 mm", null, "Concrete", "Concrete", "5000000000", null, "Text", null], + values.Select(v => v.Text)); + Assert.Equal("p1", values[0].Name); + Assert.Equal("8", values[^1].Name); // a parameter whose definition was not read is listed by its id + } + + [Theory] + [InlineData(0, new[] { "A", " " }, new[] { "A" }, 0)] + [InlineData(1, new[] { "A", " " }, new[] { "A", " " }, 1)] + [InlineData(1, new[] { " ", "B" }, new[] { "B" }, 0)] + public void ABlankNamedTypeIsLeftOutUnlessSaved(int saved, string[] stored, string[] listed, int savedListed) + { + var types = MapTypes(Types(saved, stored)).FamilyTypes!; + + Assert.Equal(listed, types.Types.Select(t => t.Name)); + Assert.Equal(savedListed, types.SavedIndex); + } + + [Fact] + public void AnUnreadableTableKeepsTheSceneAndSaysSo() + { + var result = MapTypes(null, "The type table is broken."); + + Assert.Null(result.FamilyTypes); + Assert.Single(result.Document.Elements); + var mark = Assert.Single(result.Diagnostics, d => d.Code == "family-types-unreadable"); + Assert.Equal(SceneSeverity.Warning, mark.Severity); + Assert.Contains("The type table is broken.", mark.Message); + } + + [Fact] + public void TheSceneIsTheSameWithAndWithoutTheTypeList() + { + var parameters = new[] { Value(3, StorageType.ElementId, Material) }; + var with = MapTypes(new(0, [new RvtFamilyType("A", parameters), new RvtFamilyType("B", parameters)])); + var without = MapTypes(null); + + Assert.Equal(SceneJson.Write(without.Document), SceneJson.Write(with.Document)); + Assert.Null(without.FamilyTypes); + } + + [Fact] + public void AProjectNeverGetsTheMark() => + Assert.DoesNotContain(Map(Mesh(MeshCoverage.Partial), owner: null).Diagnostics, d => d.Code == "family-incomplete"); + + [Fact] + public void AFamilyFileThatNamesNoOwnerFamilyIsMarkedIncomplete() + { + // Such a file is read as a project, which leaves out family content: the scene must not look complete. + var document = RvtDocument.FromInfo(new RevitFileInfo { IsStandaloneFamily = true }); + var meshes = ElementMeshes.Extract(document); + Assert.Equal(["owner"], meshes.FamilyGaps); + + var result = RvtSceneReader.Read(document, meshes, new RvtSceneOptions { ModelKey = "family.rfa" }); + var mark = Assert.Single(result.Diagnostics, d => d.Code == "family-incomplete"); + Assert.Contains("owner", mark.Message); + } +} diff --git a/tests/RvtIO.Tests/Families/FamilySolverTests.cs b/tests/RvtIO.Tests/Families/FamilySolverTests.cs new file mode 100644 index 00000000..d0fbce70 --- /dev/null +++ b/tests/RvtIO.Tests/Families/FamilySolverTests.cs @@ -0,0 +1,146 @@ +using RvtIO.Families; +using Xunit; + +namespace RvtIO.Tests.Families; + +public class FamilySolverTests +{ + private const long Width = 100; + + // 0: the centre plane, anchored; 1: the left side; 2: the right side; 3-6: anchored depth and extrusion ends. + // v2 - 2·v0 + v1 = 0 keeps the sides equally far from the centre, v2 - v1 = the width. + private static FamilyModel Model(double centre = 0, int sign = 1, FamilyVariable[]? moreVariables = null, + params FamilyEquation[] more) + { + FamilyVariable[] variables = + [ + new(centre, true), new(centre - 1.5, false), new(centre + 1.5, false), + new(0, true), new(1, true), new(0, true), new(0.1, true), + .. moreVariables ?? [], + ]; + FamilyEquation[] equations = + [ + Constant(0, 10, (2, 1), (0, -2), (1, 1)), + new([new(sign > 0 ? 2 : 1, 1), new(sign > 0 ? 1 : 2, -1)], Width, sign, 0, 11), + .. more, + ]; + var extrusion = new FamilyExtrusion(20, [[new(1, 3, -1), new(2, 3, -1), new(2, 4, -1), new(1, 4, -1)]], 2, 5, 6, + new Dictionary(), null, null); + return new(variables, equations, [extrusion]); + } + + private static FamilyEquation Constant(double value, int source, params (int Variable, int Coefficient)[] terms) => + new([.. terms.Select(term => new FamilyTerm(term.Variable, term.Coefficient))], null, 1, value, source); + + private static Dictionary Values(double width) => new() { [Width] = width }; + + [Theory] + [InlineData(0, 1)] + [InlineData(10, 1)] + [InlineData(10, -1)] // a dimension measured the other way: the lower side minus the higher one is minus the value + public void SolvesAnotherWidth(double centre, int sign) + { + var solution = FamilySolver.Solve(Model(centre, sign), Values(4)); + + Assert.Null(solution.Refusal); + Assert.Equal(centre - 2, solution.Positions![1], 1e-12); + Assert.Equal(centre + 2, solution.Positions[2], 1e-12); + Assert.Equal(centre, solution.Positions[0]); + } + + [Fact] + public void WithoutTheEqualityItIsUnderdetermined() + { + var model = Model(); + var solution = FamilySolver.Solve(model with { Equations = [model.Equations[1]] }, Values(4)); + + Assert.Equal(new RvtFamilyRefusal("underdetermined", "20"), solution.Refusal); + Assert.Null(solution.Positions); + } + + [Fact] + public void ContradictionIsInconsistent() + { + var solution = FamilySolver.Solve(Model(more: Constant(1.5, 12, (2, 1), (0, -1))), Values(4)); + + Assert.Equal("inconsistent", solution.Refusal!.Code); + Assert.Equal("12", solution.Refusal.Detail); + Assert.Null(solution.Positions); + } + + [Fact] + public void AMissingValueRefuses() + { + var solution = FamilySolver.Solve(Model(), new Dictionary()); + + Assert.Equal(new RvtFamilyRefusal("underdetermined", "100"), solution.Refusal); + } + + [Fact] + public void AValueThatIsNotANumberIsInconsistent() => + Assert.Equal("inconsistent", FamilySolver.Solve(Model(), Values(double.NaN)).Refusal!.Code); + + [Fact] + public void AFreeVariableThatNothingShownUsesIsAllowed() + { + var solution = FamilySolver.Solve( + Model(moreVariables: [new(5, false), new(2, false)], more: Constant(1, 13, (7, 1), (8, -1))), Values(4)); + + Assert.Null(solution.Refusal); + Assert.Equal(2, solution.Positions![8]); // free: kept as stored + Assert.Equal(3, solution.Positions[7], 1e-12); // follows it + } + + private static FamilyEquation Unlocked(double value, int source, params (int Variable, int Coefficient)[] terms) => + Constant(value, source, terms) with { IsWeak = true }; + + // The right side is the width from the centre; the left side has no other strong relation. + private static FamilyModel RightSideModel(params FamilyEquation[] unlocked) => Model() with + { + Equations = [new([new(2, 1), new(0, -1)], Width, 1, 0, 11), .. unlocked], + }; + + [Fact] + public void AnUnlockedDimensionHoldsWhatTheOthersLeaveFree() + { + var solution = FamilySolver.Solve(RightSideModel(Unlocked(3, 21, (2, 1), (1, -1))), Values(4)); + + Assert.Null(solution.Refusal); + Assert.Equal(1, solution.Positions![1], 1e-12); + Assert.Equal(4, solution.Positions[2], 1e-12); + } + + [Fact] + public void AnUnlockedDimensionYieldsToTheOthers() + { + var solution = FamilySolver.Solve(Model(more: Unlocked(-1.5, 21, (1, 1), (0, -1))), Values(4)); + + Assert.Null(solution.Refusal); + Assert.Equal(-2, solution.Positions![1], 1e-12); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void UnlockedDimensionsThatDisagreeRefuse(bool reversed) + { + FamilyEquation[] unlocked = [Unlocked(3, 21, (2, 1), (1, -1)), Unlocked(-1.5, 22, (1, 1), (0, -1))]; + if (reversed) Array.Reverse(unlocked); + + Assert.Null(FamilySolver.Solve(RightSideModel(unlocked), Values(1.5)).Refusal); // they agree at the stored width + var solution = FamilySolver.Solve(RightSideModel(unlocked), Values(4)); + + Assert.Equal("inconsistent", solution.Refusal!.Code); + Assert.Null(solution.Positions); + } + + [Fact] + public void RedundantConsistentEquationsAreAccepted() + { + var solution = FamilySolver.Solve( + Model(more: [Constant(2, 12, (2, 1), (0, -1)), Constant(0, 14, (2, 3), (0, -6), (1, 3))]), Values(4)); + + Assert.Null(solution.Refusal); + Assert.Equal(-2, solution.Positions![1], 1e-12); + } +} diff --git a/tests/RvtIO.Tests/Families/FamilyTypeTableTests.cs b/tests/RvtIO.Tests/Families/FamilyTypeTableTests.cs new file mode 100644 index 00000000..0061a364 --- /dev/null +++ b/tests/RvtIO.Tests/Families/FamilyTypeTableTests.cs @@ -0,0 +1,120 @@ +using RvtIO.BuiltIns; +using RvtIO.Families; +using RvtIO.Model; +using Xunit; + +namespace RvtIO.Tests.Families; + +public sealed class FamilyTypeTableTests +{ + private const int ParameterId = 71; + + private static RvtDocument Open(Func create) + { + using var source = new StandaloneFamilyParameterTests(); + return RvtDocument.Open(create(source)); + } + + private static Parameter Of(RvtFamilyType type, int id) => Assert.Single(type.Parameters, p => p.Id == id); + + [Fact] + public void TypesComeInStoredOrderWithTheCurrentOne() + { + var types = Open(s => s.CreateSource()).FamilyTypes!; + + Assert.Equal(["A", "B"], types.Types.Select(t => t.Name)); + Assert.Equal(1, types.CurrentIndex); // the fixture stores B as the current type + } + + [Fact] + public void EachTypeHasItsOwnValues() + { + var document = Open(s => s.CreateSource()); + + var values = document.FamilyTypes!.Types.Select(t => Of(t, ParameterId)).ToArray(); + Assert.Equal(["Original A", "Original B"], values.Select(p => p.Value)); + Assert.All(values, p => Assert.Equal(StorageType.String, p.StorageType)); + Assert.All(values, p => Assert.Equal("Proof", p.Definition.Name)); + Assert.Null(document.FamilyTypesError); + } + + [Fact] + public void ABuiltInRowHasItsBuiltInNameAndAVerifiedStorage() + { + var types = Open(s => s.CreateSource(comments: ("First", "Second"))).FamilyTypes!; + + var comments = types.Types.Select(t => Of(t, (int)BuiltInParameter.ALL_MODEL_TYPE_COMMENTS)).ToArray(); + Assert.Equal(["First", "Second"], comments.Select(p => p.Value)); + Assert.All(comments, p => Assert.Equal("ALL_MODEL_TYPE_COMMENTS", p.Definition.BuiltInParameter)); + Assert.All(comments, p => Assert.Equal(StorageType.String, p.StorageType)); + } + + [Theory] + [InlineData(2022, "autodesk.spec.aec:length-2.0.0")] + [InlineData(2020, "autodesk.spec.aec:length")] + public void ALengthHasItsSpecAndUnit(int release, string spec) + { + var number = StandaloneFamilyParameterTests.BuiltInNumber.CustomLength; + var types = Open(s => s.CreateSource(release: release, number: number)).FamilyTypes!; + + var lengths = types.Types.Select(t => Of(t, ParameterId)).ToArray(); + Assert.Equal([number.A, number.B], lengths.Select(p => (double)p.Value!)); + Assert.All(lengths, p => Assert.Equal(StorageType.Double, p.StorageType)); + Assert.All(lengths, p => Assert.Equal(spec, p.SpecType)); + Assert.All(lengths, p => Assert.Equal("mm", p.UnitSymbol)); + Assert.All(lengths, p => Assert.Equal(304.8, p.ConversionFactor)); + } + + [Fact] + public void WideIdsAreTheElementKeys() + { + var document = Open(s => s.CreateSource(release: 2024)); + + var parameter = Assert.Single(document.FamilyTypes!.Types[0].Parameters); + Assert.Equal("Original A", parameter.Value); + Assert.Equal("Proof", parameter.Definition.Name); + Assert.Contains(document.RawData.Elements, e => e.Id == parameter.Id); + } + + [Theory] + [InlineData(1, "A")] // two types with one name + [InlineData(2, "B")] // the current index is past the last type + public void ABrokenTableIsAnErrorNotAnException(int current, string second) + { + var document = Open(s => s.CreateSource(typeTable: (current, second))); + + Assert.Null(document.FamilyTypes); + Assert.NotNull(document.FamilyTypesError); + } + + [Fact] + public void AFamilyThatStoresNoTypesHasNoListAndNoError() + { + var document = Open(s => s.CreateSource(typeTable: (-1, null))); + + Assert.Null(document.FamilyTypes); + Assert.Null(document.FamilyTypesError); + } + + [Fact] + public void TheWriterStillRefusesAFamilyThatStoresNoTypes() + { + using var source = new StandaloneFamilyParameterTests(); + string path = source.CreateSource(typeTable: (-1, null)); + + var error = Assert.Throws(() => RvtWriter.SetFamilyParameters(path, path + ".out.rfa", + [new("A", ParameterId, "Changed")])); + + Assert.Equal("The family type names or current type could not be verified.", error.Message); + Assert.False(File.Exists(path + ".out.rfa")); + } + + [Fact] + public void AProjectHasNoFamilyTypes() + { + var project = RvtDocument.FromInfo(new RevitFileInfo()); + + Assert.Null(project.FamilyTypes); + Assert.Null(project.FamilyTypesError); + } +} diff --git a/tests/RvtIO.Tests/GRepParserV2Tests.cs b/tests/RvtIO.Tests/GRepParserV2Tests.cs index e3c7f432..790edeab 100644 --- a/tests/RvtIO.Tests/GRepParserV2Tests.cs +++ b/tests/RvtIO.Tests/GRepParserV2Tests.cs @@ -519,6 +519,40 @@ public void RevolutionTrim_ClosesAtSerializedZeroRadiusPole() Assert.Single(rings); } + // Half a sphere bounded by its two meridians: at the poles the boundary has no edge with a length, so no edge gives + // the angles between the meridians. + [Fact] + public void TessellateRevolution_of_a_face_closed_through_both_poles_follows_the_sphere() + { + var profile = new GRepParserV2.ArcRec { C = [0, 0, 0], X = [0, 0, -1], Y = [1, 0, 0], R = 1 }; + var surface = new GRepParserV2.SurfaceRec + { + Kind = GRepParserV2.SurfKind.Rev, O = [0, 0, 0], X = [1, 0, 0], Y = [0, 1, 0], Z = [0, 0, 1], + }; + var meridians = new List<(double U1, double V1, double U2, double V2)>(); + for (int i = 0; i < 9; i++) + { + double low = Math.PI * i / 9, high = Math.PI * (i + 1) / 9; + meridians.Add((0, low, 0, high)); + meridians.Add((Math.PI, high, Math.PI, low)); + } + var trim = GRepParserV2.CloseRevolutionPoleEdges(meridians, profile); + + var polygons = GRepParserV2.TessellateRevolution(new GRepParserV2.RingGraph(), surface, profile, trim, trim, + hasAuthoredTrim: true).ToList(); + + var points = polygons.SelectMany(polygon => polygon).ToList(); + // The middle of the half reaches at least sin 80 degrees: the profile steps do not sample the equator itself. + Assert.InRange(points.Max(p => p[1]), 0.98, 1.0 + 1e-9); + Assert.InRange(points.Min(p => p[1]), -1e-9, 1e-9); + foreach (var polygon in polygons) + { + // The chords of the 20-degree profile steps stay within 0.025 of the unit sphere; a flat face does not. + double[] centre = [polygon.Average(p => p[0]), polygon.Average(p => p[1]), polygon.Average(p => p[2])]; + Assert.InRange(Math.Sqrt(centre.Sum(x => x * x)), 0.975, 1.0 + 1e-9); + } + } + [Fact] public void TrimTriangulation_PreservesExactInnerLoop() { diff --git a/tests/RvtIO.Tests/StandaloneFamilyParameterTests.cs b/tests/RvtIO.Tests/StandaloneFamilyParameterTests.cs index e79ac705..393d1d00 100644 --- a/tests/RvtIO.Tests/StandaloneFamilyParameterTests.cs +++ b/tests/RvtIO.Tests/StandaloneFamilyParameterTests.cs @@ -21,14 +21,14 @@ public sealed class StandaloneFamilyParameterTests : IDisposable 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, + internal sealed record FamilyShape(BuiltInCategory Category, int? DimensionDriver = null, bool HasUnnamedType = false, string? UnnamedComment = null, bool Formula = false, bool CurrencyInstance = false); private const int UnitsId = 90, CostId = (int)BuiltInParameter.ALL_MODEL_COST, ElevationId = (int)BuiltInParameter.FAMILY_FREEINST_DEFAULT_ELEVATION; private const double MillimetreToFeet = 0.001 / 0.3048; /// A numeric built-in value row stored in both types and the active copy, with the units element and the PartAtom entry /// that go with it; the fixture holds exactly one display option, the one of this value. - private sealed record BuiltInNumber(int Id, string Element, string? DisplayName, string Type, string? Unit, double A, double B, + internal sealed record BuiltInNumber(int Id, string Element, string? DisplayName, string Type, string? Unit, double A, double B, string Spec, string UnitId, double Accuracy, Func Text, bool Custom = false, UnitType Quantity = UnitType.UT_Length, bool UnitsElement = true, int DecimalSymbol = 0) { @@ -856,11 +856,12 @@ public void RefusesAmbiguousOrDrivenEdits(string type, bool readOnly, bool repor Assert.False(File.Exists(Output)); } - private string CreateSource(bool readOnly = false, bool reporting = false, bool association = false, bool staleMetadata = false, + internal 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, bool plainName = false, BuiltInNumber? number = null, string elementName = "Proof") + (int A, int B)? customImage = null, bool plainName = false, BuiltInNumber? number = null, string elementName = "Proof", + int headerOwner = OwnerId, int headerGroup = -1, (int Current, string? Second)? typeTable = null) { var references = customImage is { } values ? (values.A, values.B, false) : nested; importedImage |= customImage.HasValue; @@ -960,7 +961,7 @@ private string CreateSource(bool readOnly = false, bool reporting = false, bool 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); + w.Write((ushort)30); WriteId(w, headerOwner, wide); WriteId(w, headerGroup, wide); if (unitsElement) { Pointer(w, 52); Pointer(w, 53); // the schema storage (empty) and the units tracking object that names the units element @@ -1007,7 +1008,7 @@ private string CreateSource(bool readOnly = false, bool reporting = false, bool var records = new List<(ulong, ushort, byte[])> { ((ulong)Id(OwnerId, wide), FamilyClass, FamilyBody(b, a, b, reporting, wide, comments, shape: shape, nested: references, - number: number is null ? null : (number.Id, number.A, number.B))), + number: number is null ? null : (number.Id, number.A, number.B), typeTable: typeTable)), ((ulong)Id(ParameterId, wide), shared ? (ushort)35 : (ushort)29, Pack(w => { WriteId(w, ParameterId, wide); @@ -1144,7 +1145,8 @@ XElement Part(string type, string value) 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, (int Id, double A, double B)? number = null) => Pack(w => + (int A, int B, bool Instance)? nested = null, (int Id, double A, double B)? number = null, + (int Current, string? Second)? typeTable = 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); @@ -1158,10 +1160,13 @@ private static byte[] FamilyBody(string active, string a, string b, bool reporti } else { - w.Write(1); w.Write(2); + w.Write(typeTable?.Current ?? 1); w.Write(typeTable is (-1, null) ? 0 : 2); + } + if (typeTable is not (-1, null)) + { + Text(w, "A"); Store(w, a, reporting, wide, comments?.A, images?.A, formula, nested?.A, nested?.Instance ?? false, currencyInstance, number is { } nA ? (nA.Id, nA.A) : null); + Text(w, typeTable?.Second ?? "B"); Store(w, b, reporting, wide, comments?.B, images?.B, formula, nested?.B, nested?.Instance ?? false, currencyInstance, number is { } nB ? (nB.Id, nB.B) : null); } - Text(w, "A"); Store(w, a, reporting, wide, comments?.A, images?.A, formula, nested?.A, nested?.Instance ?? false, currencyInstance, number is { } nA ? (nA.Id, nA.A) : null); - Text(w, "B"); Store(w, b, reporting, wide, comments?.B, images?.B, formula, nested?.B, nested?.Instance ?? false, currencyInstance, number is { } nB ? (nB.Id, nB.B) : null); if (shape?.DimensionDriver is int driver) { w.Write(1); WriteId(w, -1, wide); w.Write(0); From 1a453f445d86785fb0e2e2ed288e64ca9f3a5f6e Mon Sep 17 00:00:00 2001 From: Mahach <79989386+mahach666@users.noreply.github.com> Date: Wed, 2 Dec 2026 11:57:21 +0300 Subject: [PATCH 02/14] Compute arcs, circles and revolutions of a family from the file A family whose extrusions have arcs and circles in their profiles, or that holds a revolution, is now computed in every one of its types, with nothing from Revit. An arc is computed when its ends lie on the axes of the family through its centre, a whole number of quarter turns, and the dimensions fix its centre and radius; a circle is two such arcs or one closed arc, and the circle of a hole is read whichever way round the file draws its halves. A circle takes the faces the file stores for it, and a circle the file tessellates otherwise than evenly is refused as saved-state-mismatch. A revolution of a whole turn about a line of its sketch along an axis of the sketch plane, whose profile is closed loops of straight lines, is cut into 18 facets per turn. A loop inside an odd number of loops is a hole. A profile that crosses the axis or itself, loops that meet or stand on both sides of the axis, or a loop that changes direction or nesting from the saved type, is refused as degenerate-geometry. The saved type is matched analytically, because the file cuts round surfaces as it likes: every corner of a stored face lies on one surface, every surface has faces that reach both its circles, and the faces of a surface share one material. The way a stored face faces is not compared, as the cone sample stores half of its side facing into the solid. The reader can read the records of the document of a family loaded into a family file, which the file keeps in a block of the partitions other than 0, and gives only the elements of that document. A nest of combinations of forms is followed to a depth of 64 and no further. RvtReaderOptions.FineCircularEdges and RvtSceneOptions.FineCircularEdges are new and off by default. A circle where a cylinder meets a plane is sampled as Revit's low detail level samples it; with the option the faces take the finer points the file stores. A cylinder or a surface of revolution with no trim edge takes no more grid cells than a trimmed face may, so that a damaged file cannot ask for tens of gigabytes. A family with a combination of forms or with nested family instances is still refused as unsupported-construct. --- CHANGELOG.md | 22 +- docs/public-api.md | 2 +- docs/scene.md | 16 +- src/RvtIO.Scene/RvtSceneOptions.cs | 6 + src/RvtIO.Scene/RvtSceneReader.cs | 1 + src/RvtIO/Diff/RvtRevisionDiffer.cs | 1 + src/RvtIO/Families/FamilyContourChecks.cs | 40 +- src/RvtIO/Families/FamilyExtrusionBuilder.cs | 20 +- src/RvtIO/Families/FamilyModel.cs | 31 +- src/RvtIO/Families/FamilyModelBuilder.cs | 418 +++++++++-- src/RvtIO/Families/FamilyRecordReader.cs | 50 +- src/RvtIO/Families/FamilyRecords.cs | 43 +- src/RvtIO/Families/FamilyRelationReader.cs | 262 ++++++- src/RvtIO/Families/FamilyRevolutionBuilder.cs | 284 ++++++++ src/RvtIO/Families/FamilyRules.cs | 5 + src/RvtIO/Families/FamilySavedState.cs | 18 +- src/RvtIO/Families/FamilySolver.cs | 23 +- src/RvtIO/Internal/ParsingState.cs | 3 + src/RvtIO/Meshes/ElementMeshes.cs | 49 +- src/RvtIO/Parsing/BlockParser.cs | 4 +- .../Parsing/ElementBuilder.UndrawnFaces.cs | 16 +- src/RvtIO/Parsing/GRepParserV2.cs | 74 +- src/RvtIO/RvtFileReader.cs | 7 +- src/RvtIO/RvtReaderOptions.cs | 7 + .../RvtIO.Tests/Families/AquaFixValveTests.cs | 45 ++ tests/RvtIO.Tests/Families/FamilyArcTests.cs | 665 ++++++++++++++++++ .../RvtIO.Tests/Families/FamilyBoundsTests.cs | 111 +++ .../Families/FamilyModelBuilderTests.cs | 3 +- .../Families/FamilyRevolutionLoopsTests.cs | 148 ++++ .../Families/FamilyRevolutionTests.cs | 451 ++++++++++++ .../Families/FineCircularEdgesTests.cs | 53 ++ .../Families/NestedFamilyDocumentTests.cs | 42 ++ 32 files changed, 2742 insertions(+), 178 deletions(-) create mode 100644 src/RvtIO/Families/FamilyRevolutionBuilder.cs create mode 100644 tests/RvtIO.Tests/Families/AquaFixValveTests.cs create mode 100644 tests/RvtIO.Tests/Families/FamilyArcTests.cs create mode 100644 tests/RvtIO.Tests/Families/FamilyBoundsTests.cs create mode 100644 tests/RvtIO.Tests/Families/FamilyRevolutionLoopsTests.cs create mode 100644 tests/RvtIO.Tests/Families/FamilyRevolutionTests.cs create mode 100644 tests/RvtIO.Tests/Families/FineCircularEdgesTests.cs create mode 100644 tests/RvtIO.Tests/Families/NestedFamilyDocumentTests.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index 5626fbf2..3abf38c6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,9 +16,22 @@ API between minor releases. - `RvtDocument.FamilyTypes` reads the types of a family file and their parameter values from its records, and `RvtSceneResult.FamilyTypes` lists them with value texts. The scene still holds the saved type only. - `ElementMeshes.ComputeFamilyType` computes the shape of a family file in another of its types from the relations of the - family, and `RvtSceneResult.FamilyTypes` gives each computed type its instances. Families of extrusions with straight - sides along the family axes are computed, and only when the computed saved type is what the file stores; any other type - says why it is not computed, and no approximate shape is given. + family, and `RvtSceneResult.FamilyTypes` gives each computed type its instances. Families of extrusions whose sides are + straight lines along the family axes, or arcs and circles whose centre and radius the dimensions fix, are computed, and only + when the computed saved type is what the file stores; any other type says why it is not computed, and no approximate shape + is given. A circle takes the faces the file stores for it: the caps of a loop of arcs alone face inward, as the file keeps + them, and a circle the file tessellates otherwise than evenly is refused as `saved-state-mismatch`. The circle of a hole + is read whichever way round the file draws its halves. +- A revolution of a whole turn about a line of its sketch along an axis of the sketch plane, whose profile is closed loops of + straight lines (a cylinder, a ring, a cone, a stepped body, a slanted side) is computed like an extrusion: the surface of each + line is cut into 18 facets, a line on the axis makes no face, a loop inside an odd number of loops is a hole, and a profile that + crosses the axis or itself, or loops that meet, are refused as `degenerate-geometry`. For the saved type the file's own faces of a + revolution are accepted when every corner of each lies on one surface of the revolution, every surface has faces that reach both + its circles, and the faces of a surface share a material (the one its parameter gives), because the file cuts round surfaces as + it likes; the way a stored face faces is not compared, since the file stores half of the side of a cone facing into the solid. +- `RvtReaderOptions.FineCircularEdges` and `RvtSceneOptions.FineCircularEdges` (off by default). A circle where a cylinder meets a + plane is sampled by default as Revit's low detail level samples it, a polygon of about eight sides for a pipe; with the option the + faces take the finer points the file stores, so the circle looks round. The faces of other surfaces do not change. - Report progress while reading a Revit file: `RvtReadProgress` (phase, completed and total units), `RvtReaderOptions.Progress` and `RvtSceneOptions.ReadProgress` (for `RvtSceneReader.Read(path)`). The reader calls `IProgress.Report` synchronously on the reading thread, in phase order; see @@ -172,6 +185,9 @@ API between minor releases. ### Fixed +- A cylinder or a surface of revolution with no trim edge, or a trimmed one with a single row of samples, takes no more + grid cells than a trimmed face may (20000; 1024 at the coarse level), and the angular samples of a surface of a huge + radius are bounded. A damaged file could otherwise ask for tens of gigabytes. - A face of a surface of revolution that is bounded only by its meridians and meets the axis at both ends, such as half a sphere, is no longer drawn flat: its triangles now follow the angle between the meridians. - IFC export with Revit parameters grouped (`--ifc-revit-parameter-groups`) no longer writes several properties of one diff --git a/docs/public-api.md b/docs/public-api.md index ca57066b..94726efd 100644 --- a/docs/public-api.md +++ b/docs/public-api.md @@ -13,7 +13,7 @@ projects through `InternalsVisibleTo`. | `RvtFamilyTypes`, `RvtFamilyType` | The types of the family of a family document: `CurrentIndex` is the type the file was saved at, and each type has its stored name (blank for the type Revit keeps for a family without named types) and the parameter values it stores, in Revit's internal units. A parameter of the family carries its name, the key of its definition element, its storage type and, for a number, its spec and display unit. A built-in parameter has a value only when its kind is established (the family width and height and the built-in fields the writer edits); any other is listed without one. A definition that is not read exactly keeps only its id. | | `RvtFileReader` | Lower level read that returns the `RevitFileInfo` behind a document (`Read`, `ReadStream`), or reads only container metadata without opening `Partitions/*` or decoding geometry (`ReadMetadata`, `ReadMetadataStream`). `Read` and `ReadMetadata` take a path and `ReadStream` / `ReadMetadataStream` read from the beginning of a readable, seekable stream, whatever its position. The stream is only read: it is never written to, shortened or closed, also when it is writable. A failure of the stream itself is thrown as the stream threw it. | | `RvtFileMetadataSummary`, `RvtMetadataOptions`, `RvtDocumentKind` | Lightweight container metadata summary returned by `ReadMetadata` / `ReadMetadataStream`: Revit version, build, file/template/backup kind (`.rvt`, `.rfa`, `.rte`, `.rft`), worksharing and cloud state, available save fields, aligned `FileMetadata` / `ProjectInfo` / `TransmissionData`, and optional personal-data redaction (`RedactPersonalData` / `Redact`). | -| `RvtReaderOptions` | Options of a read, including `DiagnosticOutput`, `Progress` (see below), `ResolveCurrentCopies` (keeps only the current copy of an element that several partition streams hold; default true, set it to false to decode every copy), `ReleasePartitions` (drops the decompressed partition streams before the model is built, for a caller that keeps only the result; the model is the same and the read needs less memory; a file read by its own class schema keeps its streams unless `R22Layout` rewrote them and `PreserveWideLayout` is off, and of a rewritten file the streams of the file itself go once its element records are read; the decoded geometry blocks and per-element tables of the reader go as soon as the elements are built; where `ProjectElementsOnly` leaves records unbuilt, what the reader holds for them goes as well), `ProjectElementsOnly` (builds the elements of the element table that are no content of a loaded family's document, the definitions that exist as a geometry block alone, and of the rest only what a built element refers to, and decodes no geometry for what is not built; the rest is the content of the loaded families' documents, which a file of Revit 2022 holds as records outside the table and as elements of the table whose record names their family, most of the elements and of the memory of a large read; a family listing its own content is no reference to it, the content of a family modelled in place is built as before, and an element of the table that is not built stays as an element without category or geometry; a value a rule derives from all the elements is then derived from the built ones; applies when the element table was read exactly; it has no effect on a family document, whose elements are the content of its family; default false, `RvtSceneReader.Read(path)` and `ReadStream` set it), `DetailLevelQuantities` (the measures of doors, windows and structural columns at the Coarse and Medium detail levels, which only the IFC export reads; default true, a scene read turns it off and then also drops the decoded geometry blocks before the finalization passes), `PlacedFacesOnDemand` (an element whose geometry is exactly its symbols placed, an instance of a family, does not keep the placed faces, and `GeometryData.Faces` builds the same faces when it is first read; for a consumer that draws an instance from its symbol and its placement; default false, a scene read sets it), `ShareEqualVertices` (the vertices of one geometry block that are equal bit for bit are one array shared by its faces; coordinates, faces and vertex lists are the same; for a consumer that only reads the geometry, because writing into a vertex in place then moves it in every face that shares it; default false, a scene read sets it), `UndrawnFacesOnDemand` (an element that a mesh extraction never draws and that no element which may be drawn places whole does not keep the faces of its own geometry block, when the block is faces alone and small beside them and the element is not a wall, a floor, a curtain panel or a mullion; `GeometryData.Faces` decodes the block again from a copy of its bytes and builds the same faces when it is first read; with `DetailLevelQuantities` off a block that no placement reads gives its faces up inside the read itself, which lowers its peak memory; with `PlacedFacesOnDemand` on as well such an element gives up the faces of the symbols it places also where they were cut to its bounding box; default false, a scene read sets it), `RaiseLimits` and `Diagnostics`. `RevitLocalizationDirectory` is `[Obsolete]` and ignored: the texts are built in. | +| `RvtReaderOptions` | Options of a read, including `DiagnosticOutput`, `Progress` (see below), `ResolveCurrentCopies` (keeps only the current copy of an element that several partition streams hold; default true, set it to false to decode every copy), `ReleasePartitions` (drops the decompressed partition streams before the model is built, for a caller that keeps only the result; the model is the same and the read needs less memory; a file read by its own class schema keeps its streams unless `R22Layout` rewrote them and `PreserveWideLayout` is off, and of a rewritten file the streams of the file itself go once its element records are read; the decoded geometry blocks and per-element tables of the reader go as soon as the elements are built; where `ProjectElementsOnly` leaves records unbuilt, what the reader holds for them goes as well), `ProjectElementsOnly` (builds the elements of the element table that are no content of a loaded family's document, the definitions that exist as a geometry block alone, and of the rest only what a built element refers to, and decodes no geometry for what is not built; the rest is the content of the loaded families' documents, which a file of Revit 2022 holds as records outside the table and as elements of the table whose record names their family, most of the elements and of the memory of a large read; a family listing its own content is no reference to it, the content of a family modelled in place is built as before, and an element of the table that is not built stays as an element without category or geometry; a value a rule derives from all the elements is then derived from the built ones; applies when the element table was read exactly; it has no effect on a family document, whose elements are the content of its family; default false, `RvtSceneReader.Read(path)` and `ReadStream` set it), `DetailLevelQuantities` (the measures of doors, windows and structural columns at the Coarse and Medium detail levels, which only the IFC export reads; default true, a scene read turns it off and then also drops the decoded geometry blocks before the finalization passes), `PlacedFacesOnDemand` (an element whose geometry is exactly its symbols placed, an instance of a family, does not keep the placed faces, and `GeometryData.Faces` builds the same faces when it is first read; for a consumer that draws an instance from its symbol and its placement; default false, a scene read sets it), `ShareEqualVertices` (the vertices of one geometry block that are equal bit for bit are one array shared by its faces; coordinates, faces and vertex lists are the same; for a consumer that only reads the geometry, because writing into a vertex in place then moves it in every face that shares it; default false, a scene read sets it), `UndrawnFacesOnDemand` (an element that a mesh extraction never draws and that no element which may be drawn places whole does not keep the faces of its own geometry block, when the block is faces alone and small beside them and the element is not a wall, a floor, a curtain panel or a mullion; `GeometryData.Faces` decodes the block again from a copy of its bytes and builds the same faces when it is first read; with `DetailLevelQuantities` off a block that no placement reads gives its faces up inside the read itself, which lowers its peak memory; with `PlacedFacesOnDemand` on as well such an element gives up the faces of the symbols it places also where they were cut to its bounding box; default false, a scene read sets it), `FineCircularEdges` (the circular edge where a cylinder meets a plane square to its axis keeps the points the file stores, where the default samples it as Revit's low detail level does; more faces; for a consumer that shows the geometry and does not export it; default false, `RvtSceneOptions.FineCircularEdges` sets it for a scene read), `RaiseLimits` and `Diagnostics`. `RevitLocalizationDirectory` is `[Obsolete]` and ignored: the texts are built in. | | `RvtReadDiagnostics`, `StreamRecord`, `ReaderLimitHit` | What a read collects when `RvtReaderOptions.Diagnostics` is set: the partition and metadata streams read (stored and inflated byte sizes and member decode counts) and the streams cut by a limit. | | `RvtReadProgress` | File-reading updates delivered through `RvtReaderOptions.Progress`. | | `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). | diff --git a/docs/scene.md b/docs/scene.md index 2779858c..bd3a7263 100644 --- a/docs/scene.md +++ b/docs/scene.md @@ -44,6 +44,10 @@ The final reader update, `complete`, marks the end of the file read. Mesh extrac 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. +Set `RvtSceneOptions.FineCircularEdges` to draw the circular edges of cylinders with the points the file stores. By default a circle +is sampled as Revit's low detail level samples it, about eight points for a pipe of the size of a hand, so the scene equals what the IFC +export builds; with the option the circle looks round and more triangles are built. A viewer of one family file sets it. + `RvtSceneResult` holds the `Document`, the `Diagnostics` and counts: elements, elements with geometry, elements by coverage, geometries, instances and symbol placements. For a family file it also holds `FamilyTypes` (see [Families](#families)). @@ -105,10 +109,14 @@ A type that is not the saved one is computed from the relations of the family (` why it has none. A form a type hides has no instances in it. The geometries and materials of the list are those the scene does not hold; their ids follow those of the scene. -A family is computed only when it is made of extrusions whose profiles are straight sides along the axes of the family, -placed by reference planes, dimensions, alignments and joined sketch lines the reader recognizes, with no cuts, no visible -nested family and no formula on a parameter that moves the shape, and only when what is computed for the saved type is what -the file stores for it. The code of a refusal says what stands in the way: +A family is computed only when it is made of extrusions whose profiles are straight sides along the axes of the family and +arcs whose ends lie on the axes through their centre, a whole number of quarter turns, and whose centre and radius the family fixes (a circle is two such arcs, or one closed arc), +and of revolutions of a whole turn whose profile is closed loops of straight lines about a line of the sketch along an axis of +its plane (each surface is cut into 18 facets; a revolution of an arc, a part of a turn or a combination of forms is not computed), +placed by reference planes, dimensions, radius and diameter dimensions, alignments and joined sketch lines the reader +recognizes, with no cuts, no visible nested family and no formula on a parameter that moves the shape, and only when what +is computed for the saved type is what the file stores for it. A control icon (the arrow that flips a form) of the family +is not a relation; a dimension to it that no parameter labels is ignored. The code of a refusal says what stands in the way: | Code | The type | |---|---| diff --git a/src/RvtIO.Scene/RvtSceneOptions.cs b/src/RvtIO.Scene/RvtSceneOptions.cs index ca64db1b..ed288a91 100644 --- a/src/RvtIO.Scene/RvtSceneOptions.cs +++ b/src/RvtIO.Scene/RvtSceneOptions.cs @@ -18,4 +18,10 @@ public sealed class RvtSceneOptions /// Includes reference geometry for project grids and levels. public bool IncludeDatumGeometry { get; set; } + + /// Draws the circular edges of cylinders with the points the file stores, so a circle looks round instead of a polygon + /// of about eight sides. It is of the read; default false, which keeps the + /// scene equal to Revit's low detail level. More faces are built, so a viewer of a single family asks for it and a viewer of a + /// large project leaves it off. + public bool FineCircularEdges { get; set; } } diff --git a/src/RvtIO.Scene/RvtSceneReader.cs b/src/RvtIO.Scene/RvtSceneReader.cs index e76cce7e..ff2650a1 100644 --- a/src/RvtIO.Scene/RvtSceneReader.cs +++ b/src/RvtIO.Scene/RvtSceneReader.cs @@ -100,6 +100,7 @@ internal static RvtReaderOptions ReaderOptions(RvtReadDiagnostics diagnostics, R // An element that is never drawn and that nothing places whole keeps no faces of its own, and none of the // symbols it places. UndrawnFacesOnDemand = true, + FineCircularEdges = options?.FineCircularEdges ?? false, Diagnostics = diagnostics, Progress = options?.ReadProgress, }; diff --git a/src/RvtIO/Diff/RvtRevisionDiffer.cs b/src/RvtIO/Diff/RvtRevisionDiffer.cs index 6972429a..a815a922 100644 --- a/src/RvtIO/Diff/RvtRevisionDiffer.cs +++ b/src/RvtIO/Diff/RvtRevisionDiffer.cs @@ -1107,6 +1107,7 @@ internal static RvtReaderOptions CloneReaderOptions(RvtReaderOptions? source, Rv DetailLevelQuantities = source.DetailLevelQuantities, PlacedFacesOnDemand = source.PlacedFacesOnDemand, ShareEqualVertices = source.ShareEqualVertices, + FineCircularEdges = source.FineCircularEdges, UndrawnFacesOnDemand = source.UndrawnFacesOnDemand, Diagnostics = diag, Progress = source.Progress, diff --git a/src/RvtIO/Families/FamilyContourChecks.cs b/src/RvtIO/Families/FamilyContourChecks.cs index 81682413..b1413692 100644 --- a/src/RvtIO/Families/FamilyContourChecks.cs +++ b/src/RvtIO/Families/FamilyContourChecks.cs @@ -21,19 +21,44 @@ internal static class FamilyContourChecks var stored = model.Variables.Select(variable => variable.Stored).ToArray(); foreach (var extrusion in model.Extrusions) if (!Holds(extrusion, positions, stored)) return Refused(extrusion.ElementId); + foreach (var revolution in model.Revolutions) + if (!FamilyRevolutionBuilder.Holds(revolution, positions, stored)) return Refused(revolution.ElementId); return null; } - /// The loops of in the two axes that follow its own, which are right-handed - /// with it. - internal static List<(double U, double V)[]> Profiles(FamilyExtrusion extrusion, IReadOnlyList positions) + /// The outlines of the loops of in the two axes that follow its own, which are + /// right-handed with it: the corners, with the points between them where a segment is an arc, which the file stores as a + /// row of flat faces. Segments[p] is the segment of the loop whose outline edge starts at point p. + internal static List<((double U, double V)[] Points, int[] Segments)> Outlines(FamilyExtrusion extrusion, + IReadOnlyList positions) { int u = (extrusion.Axis + 1) % 3, v = (extrusion.Axis + 2) % 3; static int Component(FamilyVertex vertex, int axis) => axis == 0 ? vertex.X : axis == 1 ? vertex.Y : vertex.Z; - return extrusion.Loops.Select(loop => loop - .Select(vertex => (positions[Component(vertex, u)], positions[Component(vertex, v)])).ToArray()).ToList(); + return [.. extrusion.Loops.Select((loop, l) => + { + var points = new List<(double U, double V)>(); + var segments = new List(); + for (int i = 0; i < loop.Count; i++) + { + points.Add((positions[Component(loop[i], u)], positions[Component(loop[i], v)])); + segments.Add(i); + if (extrusion.Arcs?[l][i] is not { } arc) continue; + for (int facet = 1; facet < arc.Facets; facet++) + { + // The ends lie on the axes through the centre, so the direction of the start is a multiple of a quarter turn. + double angle = Math.PI / 2 * (arc.StartQuarter + (double)arc.Way * arc.Quarters * facet / arc.Facets); + points.Add((positions[arc.CenterU] + positions[arc.Radius] * Math.Cos(angle), + positions[arc.CenterV] + positions[arc.Radius] * Math.Sin(angle))); + segments.Add(i); + } + } + return (points.ToArray(), segments.ToArray()); + })]; } + internal static List<(double U, double V)[]> Profiles(FamilyExtrusion extrusion, IReadOnlyList positions) => + [.. Outlines(extrusion, positions).Select(outline => outline.Points)]; + /// [i, j] is true when loop j lies inside loop i; the loops do not meet each other. internal static bool[,] Nesting(IReadOnlyList<(double U, double V)[]> loops) { @@ -48,6 +73,9 @@ private static bool Holds(FamilyExtrusion extrusion, IReadOnlyList posit { double height = positions[extrusion.End] - positions[extrusion.Start]; if (!(height > Tolerance && double.IsFinite(height))) return false; + // A radius that is not above zero is no arc. + foreach (var arc in (extrusion.Arcs ?? []).SelectMany(loop => loop).OfType()) + if (!(positions[arc.Radius] > Tolerance && double.IsFinite(positions[arc.Radius]))) return false; var loops = Profiles(extrusion, positions); var saved = Profiles(extrusion, stored); @@ -93,7 +121,7 @@ private static double Cross((double U, double V) a, (double U, double V) b, (dou (b.U - a.U) * (point.V - a.V) - (b.V - a.V) * (point.U - a.U); // From a point to the segment a-b, which has a length. - private static double Distance((double U, double V) point, (double U, double V) a, (double U, double V) b) + internal static double Distance((double U, double V) point, (double U, double V) a, (double U, double V) b) { var (du, dv) = (b.U - a.U, b.V - a.V); double along = Math.Clamp(((point.U - a.U) * du + (point.V - a.V) * dv) / (du * du + dv * dv), 0, 1); diff --git a/src/RvtIO/Families/FamilyExtrusionBuilder.cs b/src/RvtIO/Families/FamilyExtrusionBuilder.cs index 9f8dacc2..1eb5e376 100644 --- a/src/RvtIO/Families/FamilyExtrusionBuilder.cs +++ b/src/RvtIO/Families/FamilyExtrusionBuilder.cs @@ -6,13 +6,14 @@ namespace RvtIO.Families; /// . internal static class FamilyExtrusionBuilder { - /// A side face per segment and, for every loop that is not a hole, a face at each end with its holes. A loop + /// A side face per segment (per flat piece of an arc) and, for every loop that is not a hole, a face at each end with its holes. A loop /// inside an odd number of others is a hole. Normals point out of the solid; gives the /// material of each face. public static List Faces(FamilyExtrusion extrusion, IReadOnlyList positions, Func material) { - var loops = FamilyContourChecks.Profiles(extrusion, positions); + var outlines = FamilyContourChecks.Outlines(extrusion, positions); + var loops = outlines.Select(outline => outline.Points).ToList(); var inside = FamilyContourChecks.Nesting(loops); var depth = Enumerable.Range(0, loops.Count) .Select(loop => Enumerable.Range(0, loops.Count).Count(other => inside[other, loop])).ToArray(); @@ -45,13 +46,19 @@ GeoFace Face(List outer, double[] normal, FamilyFaceKey key) => if (depth[loop] % 2 != 0) continue; var holes = Enumerable.Range(0, loops.Count) .Where(hole => inside[loop, hole] && depth[hole] == depth[loop] + 1).ToList(); + // The file stores the caps of a loop of arcs alone, a circle, facing inward (every one of the 17 such extrusions of + // the corpus, whichever way the circle is drawn), and the caps of the other loops facing outward. A loop of arcs + // with a hole, or a loop of arcs and lines, is not measured: it takes the outward way, and a family whose + // stored caps differ is refused by the saved-state check. + bool circle = holes.Count == 0 && extrusion.Arcs?[loop].All(arc => arc != null) == true; foreach (var (kind, along, way) in new[] { (FamilyFaceKind.StartCap, start, -1), (FamilyFaceKind.EndCap, end, 1) }) { + int facing = circle ? -way : way; var normal = new double[3]; - normal[extrusion.Axis] = way; - var cap = Face(Ring(loop, along, way), normal, new(kind, loop)); - if (holes.Count > 0) cap.InnerVertices = holes.Select(hole => Ring(hole, along, -way)).ToList(); + normal[extrusion.Axis] = facing; + var cap = Face(Ring(loop, along, facing), normal, new(kind, loop)); + if (holes.Count > 0) cap.InnerVertices = holes.Select(hole => Ring(hole, along, -facing)).ToList(); faces.Add(cap); } } @@ -68,7 +75,8 @@ GeoFace Face(List outer, double[] normal, FamilyFaceKey key) => normal[(extrusion.Axis + 2) % 3] = outward * (a.U - b.U) / length; List quad = [Point(a, start), Point(b, start), Point(b, end), Point(a, end)]; if (outward < 0) quad.Reverse(); - faces.Add(Face(quad, normal, new(FamilyFaceKind.Side, loop, i))); + // A curved segment is a row of flat faces, which all go by the segment. + faces.Add(Face(quad, normal, new(FamilyFaceKind.Side, loop, outlines[loop].Segments[i]))); } } return faces; diff --git a/src/RvtIO/Families/FamilyModel.cs b/src/RvtIO/Families/FamilyModel.cs index 7f3aa8c4..a41fc61c 100644 --- a/src/RvtIO/Families/FamilyModel.cs +++ b/src/RvtIO/Families/FamilyModel.cs @@ -21,16 +21,41 @@ internal enum FamilyFaceKind { StartCap, EndCap, Side } internal readonly record struct FamilyFaceKey(FamilyFaceKind Kind, int Loop = -1, int Segment = -1); +/// +/// The segment of a profile loop from its corner to the next one when it is an arc about the point (CenterU, +/// CenterV) of the radius Radius, in the two axes that follow the axis of the extrusion. Its ends lie on the +/// axes through the centre: it starts in the direction StartQuarter (0, 1, 2, 3 for U, V, -U, -V) and turns +/// Quarters (1 to 3) quarter turns the way Way says, 1 counter-clockwise seen from the end of the axis and -1 +/// clockwise. A face of its side, like the outline of an end, is made of Facets equal turns. +/// +internal readonly record struct FamilyArcSegment(int CenterU, int CenterV, int Radius, int Way, int StartQuarter, int Quarters, + int Facets); + /// /// An extrusion of closed loops along Axis (0, 1 or 2 for X, Y or Z), from the variable Start to the -/// variable End. +/// variable End. Arcs[loop][i] is set when the segment of that loop that starts at its corner i is an arc; +/// without arcs it is null. /// internal sealed record FamilyExtrusion(int ElementId, IReadOnlyList> Loops, int Axis, int Start, - int End, IReadOnlyDictionary Materials, long? MaterialParameterId, long? VisibilityParameterId); + int End, IReadOnlyDictionary Materials, long? MaterialParameterId, long? VisibilityParameterId, + IReadOnlyList>? Arcs = null); + +/// +/// A whole turn of closed loops of straight lines about a line along Axis (0, 1 or 2 for X, Y or Z) that lies in the +/// plane of the sketch, whose normal runs along Normal. AxisPosition is the coordinate of the axis along the +/// third axis and PlanePosition that of the plane along Normal, which is the coordinate along it of every +/// corner. Materials is keyed by the line of a loop (, loop, curve). +/// +internal sealed record FamilyRevolution(int ElementId, IReadOnlyList> Loops, int Axis, int Normal, + int AxisPosition, int PlanePosition, IReadOnlyDictionary Materials, long? MaterialParameterId, + long? VisibilityParameterId); /// The forms of a family and the relations that place them. internal sealed record FamilyModel(IReadOnlyList Variables, IReadOnlyList Equations, - IReadOnlyList Extrusions); + IReadOnlyList Extrusions) +{ + public IReadOnlyList Revolutions { get; init; } = []; +} /// The value of every variable for one type, or why there is none. internal sealed record FamilySolution(double[]? Positions, RvtFamilyRefusal? Refusal); diff --git a/src/RvtIO/Families/FamilyModelBuilder.cs b/src/RvtIO/Families/FamilyModelBuilder.cs index d7f1be98..ddbca804 100644 --- a/src/RvtIO/Families/FamilyModelBuilder.cs +++ b/src/RvtIO/Families/FamilyModelBuilder.cs @@ -18,6 +18,20 @@ public static (FamilyModel? Model, RvtFamilyRefusal? Refusal) Build(FamilyRecord catch (Refused refused) { return (null, refused.Refusal); } } + /// The root of the group of in a forest of parents, with the path halved; a node not yet in + /// the forest is a root. No recursion: a file can chain a group as long as it has nodes. + internal static int FindGroup(Dictionary parent, int node) + { + while (true) + { + if (!parent.TryGetValue(node, out int up)) parent[node] = up = node; + if (up == node) return node; + if (!parent.TryGetValue(up, out int grand)) grand = up; + parent[node] = grand; + node = grand; + } + } + private sealed class Refused(string code, string detail) : Exception { public RvtFamilyRefusal Refusal { get; } = new(code, detail); @@ -51,9 +65,16 @@ private sealed class Node public int Parent; public double Stored; public bool Anchored; + // A radius: a length, not a place, so it does not tie the coordinates along the axes together. + public bool Length; public List Elements = []; } + /// The arc of a profile curve in the two axes that follow the axis of its extrusion: the way its own + /// direction (from its start to its end) turns, the whole quarter turns it makes, and the direction from the centre + /// to each of its ends (U, V components of 1, 0 or -1). + private sealed record ArcShape(int Way, int Quarters, (int U, int V) StartDirection, (int U, int V) EndDirection); + private sealed record Equation(List<(int Node, int Coefficient)> Terms, long? Parameter, int Sign, double Constant, int Source, bool IsWeak, bool IsOffset = false); @@ -61,24 +82,44 @@ private sealed record Equation(List<(int Node, int Coefficient)> Terms, long? Pa private readonly Dictionary _planes = records.Planes.ToDictionary(plane => plane.ElementId); private readonly Dictionary _extrusions = records.Extrusions.ToDictionary(extrusion => extrusion.Id); + private readonly Dictionary _revolutions = + (records.Revolutions ?? []).ToDictionary(revolution => revolution.Id); + // Lines of the profile of a revolution that run along no axis: their ends are places the joins of the profile fix. + private HashSet _slanted = []; private readonly List _nodes = []; private readonly Dictionary _keys = []; private readonly List _equations = []; private readonly HashSet _heldCaps = []; + private HashSet _profileArcs = []; + private HashSet _circles = []; + + private bool IsProfileArc(int id) => _profileArcs.Contains(id) || _circles.Contains(id); public FamilyModel Build() { if (records.UnsupportedContent.Count > 0) throw Unsupported(string.Join(", ", records.UnsupportedContent.Distinct())); var axes = _extrusions.Values.ToDictionary(extrusion => extrusion.Id, CheckProfile); - - var dimensions = records.Dimensions.Select(dimension => (Record: dimension, Nodes: Measured(dimension))).ToList(); + var turns = _revolutions.Values.ToDictionary(revolution => revolution.Id, CheckRevolution); + _slanted = _revolutions.Values.SelectMany(revolution => revolution.Loops.SelectMany(loop => loop)) + .Select(curve => _lines[curve.LineId]).Where(line => Direction(line) == null).Select(line => line.Id).ToHashSet(); + var arcs = _extrusions.Values.SelectMany(e => e.Loops.SelectMany(loop => loop) + .Select(key => _lines[e.ProfileCurves[key].LineId])).Where(line => line.Arc != null).DistinctBy(line => line.Id) + .ToList(); + _profileArcs = arcs.Select(line => line.Id).ToHashSet(); + // What the sketch holds of a closed circle (its radius, its centre) holds the halves the profile has of it. + _circles = arcs.Select(line => line.CircleId).OfType().ToHashSet(); + + var dimensions = records.Dimensions.Where(dimension => !OnControlIcon(dimension)) + .Select(dimension => (Record: dimension, Nodes: Measured(dimension))).ToList(); Join(); + RelateArcs(axes); var referencedLines = records.Dimensions.SelectMany(d => d.References).Select(r => r.ElementId) .Where(_lines.ContainsKey).ToHashSet(); var modelLines = _extrusions.Values .SelectMany(e => e.Loops.SelectMany(loop => loop).Select(key => e.ProfileCurves[key].LineId)) - .Concat(referencedLines).ToHashSet(); + .Concat(_revolutions.Values.SelectMany(r => r.Loops.SelectMany(loop => loop.Select(c => c.LineId)).Append(r.AxisLineId))) + .Concat(referencedLines).Concat(_circles).ToHashSet(); CheckConstraints(modelLines); CheckAssociations(modelLines); CheckReferrers(modelLines); @@ -86,32 +127,143 @@ public FamilyModel Build() PlaceHostFaces(dimensions); foreach (var (record, nodes) in dimensions) Relate(record, nodes); + RelateRadii(); var caps = _extrusions.Values.ToDictionary(e => e.Id, e => PlaceCaps(e, axes[e.Id])); var vertices = _extrusions.Values.ToDictionary(e => e.Id, e => Vertices(e, axes[e.Id])); + var placed = _revolutions.Values.ToDictionary(r => r.Id, r => PlaceRevolution(r, turns[r.Id])); Anchor(vertices.Values.SelectMany(loops => loops.SelectMany(loop => loop.SelectMany(v => v))) - .Where(node => node >= 0).Concat(caps.Values.SelectMany(pair => new[] { pair.Low, pair.High }))); - return Assemble(axes, caps, vertices); + .Where(node => node >= 0).Concat(caps.Values.SelectMany(pair => new[] { pair.Low, pair.High })) + .Concat(placed.Values.SelectMany(p => p.Corners.SelectMany(loop => loop.SelectMany(v => v)).Append(p.Plane).Append(p.AxisPosition)))); + return Assemble(axes, caps, vertices, turns, placed); } - /// The axis of an extrusion whose profile is straight lines along the two other axes. + /// The axis of an extrusion whose profile is straight lines along the two other axes and quarter-turn arcs + /// about points of the plane of the sketch. private int CheckProfile(FamilyExtrusionRecord extrusion) { if (AxisOf(extrusion.PlaneNormal) is not int axis) throw Unsupported($"sketch plane of {extrusion.Id}"); foreach (var loop in extrusion.Loops) { - if (loop.Count < 3) throw Unsupported($"profile of {extrusion.Id}"); + // Two arcs make a circle, an arc and a line a segment of one. + bool arcs = loop.Any(key => extrusion.ProfileCurves.TryGetValue(key, out var curve) + && _lines.TryGetValue(curve.LineId, out var line) && line.Arc != null); + if (loop.Count < (arcs ? 2 : 3)) throw Unsupported($"profile of {extrusion.Id}"); foreach (int key in loop) { if (!extrusion.ProfileCurves.TryGetValue(key, out var curve) || !_lines.TryGetValue(curve.LineId, out var line) || line.SketchId != extrusion.SketchId) throw Unrecognized($"profile curve {key} of {extrusion.Id}"); - if (Direction(line) is not int along || along == axis) throw Unsupported($"curve {line.Id}"); + if (line.Arc != null) + { + Shape(line, axis); + // A half of a closed circle has no ends of its own to hold: the circle is where its centre and radius put it. + if (line.CircleId != null) + { + if (!IsHalfOfCircle(line)) throw Unrecognized($"circle of curve {line.Id}"); + } + // Without the constraint that holds an end at its angle the solver of the sketch may turn the arc. + else if (!HeldEnds(line).All(held => held) && !CompletesCircle(extrusion, loop, line, axis)) + throw Unsupported($"curve {line.Id}"); + } + else if (Direction(line) is not int along || along == axis) throw Unsupported($"curve {line.Id}"); } } if (extrusion.Loops.Count == 0) throw Unsupported($"profile of {extrusion.Id}"); return axis; } + /// The axis and the normal of the sketch plane of a revolution of a whole turn whose profile is straight lines + /// of some length, about a line along an axis of the plane of the sketch. + private (int Axis, int Normal) CheckRevolution(FamilyRevolutionRecord revolution) + { + if (AxisOf(revolution.PlaneNormal) is not int normal) throw Unsupported($"sketch plane of {revolution.Id}"); + if (!(Math.Abs(revolution.EndAngle - revolution.StartAngle - 2 * Math.PI) <= Tolerance)) + throw Unsupported($"sweep of {revolution.Id}"); + if (!_lines.TryGetValue(revolution.AxisLineId, out var axisLine) || axisLine.SketchId != revolution.SketchId) + throw Unrecognized($"axis of {revolution.Id}"); + if (Direction(axisLine) is not int axis || axis == normal + || !(Math.Abs(axisLine.Start[normal] - revolution.PlaneOrigin[normal]) <= Tolerance)) + throw Unsupported($"axis of {revolution.Id}"); + foreach (var loop in revolution.Loops) + { + if (loop.Count < 3) throw Unsupported($"profile of {revolution.Id}"); + foreach (var curve in loop) + { + if (!_lines.TryGetValue(curve.LineId, out var line) || line.SketchId != revolution.SketchId || !line.IsStraight) + throw Unrecognized($"profile curve {curve.LineId} of {revolution.Id}"); + if (!(Enumerable.Range(0, 3).Sum(c => Math.Abs(line.End[c] - line.Start[c])) > Tolerance) + || !(Math.Abs(line.Start[normal] - revolution.PlaneOrigin[normal]) <= Tolerance + && Math.Abs(line.End[normal] - revolution.PlaneOrigin[normal]) <= Tolerance)) + throw Unsupported($"curve {line.Id}"); + } + } + return (axis, normal); + } + + /// The coordinate of the plane of a sketch along its normal, and of the axis along the third axis, and the + /// corners of the loops (the plane for the coordinate along the normal). + private (int Plane, int AxisPosition, int[][][] Corners) PlaceRevolution(FamilyRevolutionRecord revolution, + (int Axis, int Normal) turn) + { + int plane = PlaneNode(revolution.PlaneHost, revolution.PlaneOrigin[turn.Normal], turn.Normal, revolution.Id); + int axisPosition = Slot(_lines[revolution.AxisLineId], -1, 3 - turn.Axis - turn.Normal); + // The corner between two curves of a loop is where the first stops and the second starts: their join. + var corners = revolution.Loops.Select(loop => Enumerable.Range(0, loop.Count).Select(i => + { + var previous = loop[(i + loop.Count - 1) % loop.Count]; + var before = _lines[previous.LineId]; + return Enumerable.Range(0, 3).Select(c => c == turn.Normal ? plane : Slot(before, previous.Reversed ? 0 : 1, c)).ToArray(); + }).ToArray()).ToArray(); + return (plane, axisPosition, corners); + } + + /// Whether is an arc of the closed arc it names: the same plane, centre and radius. A + /// hole is drawn the other way round, so the half may turn the other way (the opposite normal). + private bool IsHalfOfCircle(FamilySketchLine half) => + half.CircleId is int id && _lines.TryGetValue(id, out var whole) && whole.Arc is { } circle && half.Arc is { } part + && whole.SketchId == half.SketchId + && Enumerable.Range(0, 3).All(i => Math.Abs(whole.Start[i] - whole.End[i]) <= Tolerance + && Math.Abs(circle.Center[i] - part.Center[i]) <= Tolerance) + && (Enumerable.Range(0, 3).All(i => Math.Abs(Normal(circle)[i] - Normal(part)[i]) <= Tolerance) + || Enumerable.Range(0, 3).All(i => Math.Abs(Normal(circle)[i] + Normal(part)[i]) <= Tolerance)) + && Math.Abs(circle.Radius - part.Radius) <= Tolerance; + + private bool[] HeldEnds(FamilySketchLine line) => [.. Enumerable.Range(0, 2).Select(end => + records.ArcEndAngles?.Any(held => held.SketchId == line.SketchId && held.ArcLineId == line.Id && held.End == end) == true)]; + + /// Whether the arc , with an end the sketch holds at no angle, is one half of a circle: + /// the loop is two arcs that join at both ends and turn four quarters between them, the other holds both its ends and + /// this one at least one. The free end then is where the other half joins it, and the arc keeps the centre and the + /// radius of the other half, which the joins and the held ends fix. + private bool CompletesCircle(FamilyExtrusionRecord extrusion, IReadOnlyList loop, FamilySketchLine line, int axis) + { + if (loop.Count != 2) return false; + var pair = loop.Select(key => _lines[extrusion.ProfileCurves[key].LineId]).ToList(); + if (pair.Any(curve => curve.Arc == null) || pair[0].Id == pair[1].Id) return false; + var other = pair.Single(curve => curve.Id != line.Id); + return Shape(line, axis).Quarters + Shape(other, axis).Quarters == 4 + // A join is listed from one curve, or from both. + && Enumerable.Range(0, 2).All(end => records.Joints.Any(joint => joint.OtherEnd is 0 or 1 + && (joint.LineId == line.Id && joint.End == end && joint.OtherLineId == other.Id + || joint.OtherLineId == line.Id && joint.OtherEnd == end && joint.LineId == other.Id))) + && HeldEnds(other).All(held => held) && HeldEnds(line).Any(held => held); + } + + /// Whether the dimension measures a control icon (the arrow that flips an element), which has no place the + /// family keeps. One that is unlocked and unlabelled only shows a distance and holds nothing; any other would hold + /// something to a place this does not know. + private bool OnControlIcon(FamilyDimensionRecord dimension) + { + var icon = dimension.References.Where(reference => records.ControlIconIds?.Contains(reference.ElementId) == true) + .Select(reference => (FamilyReference?)reference).FirstOrDefault(); + if (icon == null) return false; + bool shows = !dimension.IsAlignment && FamilyRules.IsKnownDimensionFlags(false, dimension.Flags) + && (dimension.Flags & FamilyRules.EqualityDimensionFlag) == 0 + && dimension.ParameterIds.All(parameter => parameter == -1) + && dimension.SegmentFlags.All(flags => flags == FamilyRules.UnlockedSegmentFlag); + return shows ? true : throw Unrecognized($"reference of {Text(dimension.Id)} to element {icon.Value.ElementId}"); + } + private int[] Measured(FamilyDimensionRecord dimension) { string id = Text(dimension.Id); @@ -154,10 +306,17 @@ private int Resolve(FamilyReference reference, int axis, int source) if (reference.SubTag == -1) return Direction(line) is int along && along != axis ? Slot(line, -1, axis) : throw Unsupported($"line {id} measured by {source}"); + // An end of an arc, or of a line along no axis, outside the profile is a place of its own that no form stands + // on: it takes part as it is. if (reference.SubTag is 0 or 1) - return Direction(line) != null ? Slot(line, reference.SubTag, axis) + return line.IsStraight || line.Arc != null ? Slot(line, reference.SubTag, axis) : throw Unsupported($"curve {id} measured by {source}"); } + // The centre of an arc, likewise; of a profile arc, along an axis of its plane. What is measured to the whole arc + // is no place. + if (_lines.TryGetValue(id, out var arc) && arc.Arc != null && reference is { GeometryTag: 1, SubTag: -1 }) + return !IsProfileArc(id) || AxisOf(Normal(arc.Arc)) is int square && square != axis + ? Centre(arc, axis) : throw Unsupported($"centre of arc {id} measured by {source}"); if (_extrusions.TryGetValue(id, out var extrusion)) return OnExtrusion(extrusion, reference, axis, source); throw Unrecognized($"reference of {source} to element {id}"); } @@ -219,7 +378,7 @@ private int Cap(FamilyExtrusionRecord extrusion, bool end) private int Slot(FamilySketchLine line, int end, int axis) { if (Direction(line) is int along && along != axis) end = -1; - return Keyed(("slot", line.Id, end, axis), end == 1 ? line.End[axis] : line.Start[axis], line.Id); + return Keyed(("slot", line.Id, end, axis), end == 1 ? line.End[axis] : line.Start[axis], line.CircleId ?? line.Id); } private int Keyed(object key, double stored, int element) @@ -256,13 +415,123 @@ private void Merge(int first, int second, int source) _nodes[first].Elements.AddRange(_nodes[second].Elements); } - // Joins of curves that are not straight lines along an axis add nothing: what such a curve would hold stays free. + private static double[] Normal(FamilyArc arc) => + [ + arc.XAxis[1] * arc.YAxis[2] - arc.XAxis[2] * arc.YAxis[1], arc.XAxis[2] * arc.YAxis[0] - arc.XAxis[0] * arc.YAxis[2], + arc.XAxis[0] * arc.YAxis[1] - arc.XAxis[1] * arc.YAxis[0], + ]; + + /// The arc of a curve whose plane is square to , when it makes one to three quarter + /// turns and both its ends lie on the axes through its centre, which is what lets the ends be linear in the centre and + /// the radius. + private static ArcShape Shape(FamilySketchLine line, int axis) + { + var arc = line.Arc!; + var normal = Normal(arc); + double sweep = arc.EndAngle - arc.StartAngle; + double quarters = Math.Abs(sweep) / (Math.PI / 2); + int whole = (int)Math.Round(quarters); + if (AxisOf(normal) != axis || !(Math.Abs(quarters - whole) <= Tolerance) || whole is < 1 or > 3 + || !(arc.Radius > Tolerance)) + throw Unsupported($"curve {line.Id}"); + int u = (axis + 1) % 3, v = (axis + 2) % 3; + (int, int) Towards(double angle) + { + double along(int component) => + Math.Cos(angle) * arc.XAxis[component] + Math.Sin(angle) * arc.YAxis[component]; + // Compared as doubles: a frame of any size is refused, and no int is made of one that does not fit. + double du = Math.Round(along(u)), dv = Math.Round(along(v)); + // One component is 1 or -1 and the other 0, the ends lying on the axes through the centre. + return Math.Abs(du) + Math.Abs(dv) == 1 && Math.Abs(along(u) - du) <= Tolerance + && Math.Abs(along(v) - dv) <= Tolerance ? ((int)du, (int)dv) : throw Unsupported($"curve {line.Id}"); + } + return new(Math.Sign(normal[axis]) * Math.Sign(sweep), whole, Towards(arc.StartAngle), Towards(arc.EndAngle)); + } + + // The halves of a closed circle share its centre and radius, and are the element it is. + private int Centre(FamilySketchLine line, int axis) => + Keyed(("centre", line.CircleId ?? line.Id, axis), line.Arc!.Center[axis], line.CircleId ?? line.Id); + + private int Radius(FamilySketchLine line) + { + int node = Keyed(("radius", line.CircleId ?? line.Id), line.Arc!.Radius, line.CircleId ?? line.Id); + _nodes[node].Length = true; + return node; + } + + // Each end of an arc is the centre plus the radius along the direction the end has from it. + private void RelateArcs(Dictionary axes) + { + foreach (var extrusion in _extrusions.Values) + { + int axis = axes[extrusion.Id]; + foreach (var line in extrusion.Loops.SelectMany(loop => loop).Select(key => _lines[extrusion.ProfileCurves[key].LineId]) + .Where(line => line.Arc != null).DistinctBy(line => line.Id)) + { + var shape = Shape(line, axis); + foreach (var (end, direction) in new[] { (0, shape.StartDirection), (1, shape.EndDirection) }) + foreach (var (component, along) in new[] { ((axis + 1) % 3, direction.U), ((axis + 2) % 3, direction.V) }) + { + List<(int Node, int Coefficient)> terms = [(Slot(line, end, component), 1), (Centre(line, component), -1)]; + if (along != 0) terms.Add((Radius(line), -along)); + _equations.Add(new(terms, null, 1, 0, line.Id, false)); + } + } + } + } + + // A radius or a diameter holds as a length does, in the unit of its own measure. + private void RelateRadii() + { + foreach (var radial in records.RadialDimensions ?? []) + { + string id = Text(radial.Id); + if (!_lines.TryGetValue(radial.Arc.ElementId, out var arc) || arc.Arc == null) + throw Unrecognized($"reference of {id} to element {radial.Arc.ElementId}"); + if (!IsProfileArc(arc.Id)) continue; + if (radial.Arc.GeometryTag != 0 || radial.Arc.SubTag != -1) + throw Unrecognized($"reference of {id} to tag {radial.Arc.GeometryTag} of element {arc.Id}"); + // The kinds of dimension style that measure a radius (0, 2) and a diameter (9) were read from the files. + int times = FamilyRules.RadialStyleFactor(radial.StyleType) + ?? throw Unrecognized($"style {radial.StyleType} of dimension {id}"); + if (!FamilyRules.IsKnownDimensionFlags(false, radial.Flags)) + throw Unrecognized($"flags {radial.Flags} of dimension {id}"); + if (radial.SegmentFlags is not (FamilyRules.UnlockedSegmentFlag or FamilyRules.LockedSegmentFlag)) + throw Unrecognized($"segments of dimension {id}"); + (int, int)[] length = [(Radius(arc), times)]; + if (radial.ParameterId != -1) _equations.Add(new([.. length], radial.ParameterId, 1, 0, radial.Id, false)); + else if (radial.SegmentFlags == FamilyRules.LockedSegmentFlag) + _equations.Add(new([.. length], null, 1, radial.Value, radial.Id, false)); + else if (!radial.Driven) _equations.Add(new([.. length], null, 1, radial.Value, radial.Id, true)); + } + } + + // Joins of curves that are not straight lines along an axis add nothing: what such a curve would hold stays free, + // unless the curve is an arc of a profile, which holds its ends where they join. private void Join() { foreach (var joint in records.Joints) { - if (!_lines.TryGetValue(joint.LineId, out var line) || !_lines.TryGetValue(joint.OtherLineId, out var other) - || Direction(line) == null || Direction(other) is not int along) continue; + if (!_lines.TryGetValue(joint.LineId, out var line) || !_lines.TryGetValue(joint.OtherLineId, out var other)) + continue; + if (_profileArcs.Contains(line.Id) || _profileArcs.Contains(other.Id)) + { + // An end on a curve or a join that is not between ends leaves the arc's end somewhere this does not know. + if (joint.End is not (0 or 1) || joint.OtherEnd is not (0 or 1)) + throw Unsupported($"join of curve {line.Id}"); + for (int axis = 0; axis < 3; axis++) + Merge(Slot(line, joint.End, axis), Slot(other, joint.OtherEnd, axis), line.Id); + continue; + } + if (_slanted.Contains(line.Id) || _slanted.Contains(other.Id)) + { + // The ends of a slanted line of a revolution are the places its neighbours put them. + if (joint.End is not (0 or 1) || joint.OtherEnd is not (0 or 1)) throw Unsupported($"join of curve {line.Id}"); + for (int axis = 0; axis < 3; axis++) + Merge(Slot(line, joint.End, axis), Slot(other, joint.OtherEnd, axis), line.Id); + continue; + } + if (Direction(line) == null || Direction(other) is not int along) continue; if (joint.End is not (0 or 1) || joint.OtherEnd is not (-1 or 0 or 1)) throw Unrecognized($"join of curve {line.Id}"); for (int axis = 0; axis < 3; axis++) @@ -273,15 +542,15 @@ private void Join() private void CheckConstraints(HashSet modelLines) { - var profiles = _extrusions.Values.Select(e => e.SketchId).ToHashSet(); + var profiles = _extrusions.Values.Select(e => e.SketchId).Concat(_revolutions.Values.Select(r => r.SketchId)).ToHashSet(); var sketches = profiles.Concat(modelLines.Select(id => _lines[id].SketchId)).ToHashSet(); foreach (var group in records.Constraints.Where(c => sketches.Contains(c.SketchId)) .GroupBy(c => (c.SketchId, c.ClassName))) { var (sketch, name) = group.Key; // Why each may stay: point-point is the join of two curves (read in Join), horizontal/vertical is the axis a - // line keeps (Direction), perpendicular lines is the corner of two axis lines; an arc end angle concerns an - // arc, never a straight line read here (an arc in a profile is refused in CheckProfile). + // line keeps (Direction), perpendicular lines is the corner of two axis lines; an arc end angle holds the end + // of an arc where it is, and each arc of a profile is checked for it in CheckProfile. bool known = name is "VarSketchPPConstrObj" or "VarSketchHorVerConstrObj" or "VarSketchArcEndAngleConstrObj" or "VarSketchLSegPerpToLSegConstrObj" // The point and the line of this one are read from the joins of the curves. @@ -296,11 +565,14 @@ private void CheckAssociations(HashSet modelLines) foreach (var association in records.Associations) { bool onExtrusion = _extrusions.ContainsKey(association.ElementId); - if (!onExtrusion && !modelLines.Contains(association.ElementId) + bool onRevolution = _revolutions.ContainsKey(association.ElementId); + if (!onExtrusion && !onRevolution && !modelLines.Contains(association.ElementId) && !_planes.ContainsKey(association.ElementId)) continue; - if (!onExtrusion || (BuiltInParameter)association.ElementPropertyId is not (BuiltInParameter.MATERIAL_ID_PARAM - or BuiltInParameter.IS_VISIBLE_PARAM or BuiltInParameter.EXTRUSION_START_PARAM - or BuiltInParameter.EXTRUSION_END_PARAM)) + var property = (BuiltInParameter)association.ElementPropertyId; + bool known = onExtrusion && property is BuiltInParameter.MATERIAL_ID_PARAM or BuiltInParameter.IS_VISIBLE_PARAM + or BuiltInParameter.EXTRUSION_START_PARAM or BuiltInParameter.EXTRUSION_END_PARAM + || onRevolution && property is BuiltInParameter.MATERIAL_ID_PARAM or BuiltInParameter.IS_VISIBLE_PARAM; + if (!known) throw Unrecognized($"association {association.ElementPropertyId} of element {association.ElementId}"); } } @@ -308,10 +580,11 @@ or BuiltInParameter.IS_VISIBLE_PARAM or BuiltInParameter.EXTRUSION_START_PARAM // Every record that refers to what takes part is either a relation read here or one that moves nothing. private void CheckReferrers(HashSet modelLines) { - var model = _extrusions.Keys.Concat(_extrusions.Values.Select(e => e.SketchId)).Concat(modelLines) + var model = _extrusions.Keys.Concat(_revolutions.Keys).Concat(_extrusions.Values.Select(e => e.SketchId)).Concat(modelLines) .Concat(modelLines.Select(id => _lines[id].SketchId)) .Concat(records.Dimensions.SelectMany(d => d.References).Select(r => r.ElementId)) .Concat(_extrusions.Values.Where(e => e.PlaneHost != null).Select(e => e.PlaneHost!.Value.ElementId)) + .Concat(_revolutions.Values.Where(r => r.PlaneHost != null).Select(r => r.PlaneHost!.Value.ElementId)) .Where(id => id > 0).ToHashSet(); foreach (var referrer in records.Referrers) { @@ -319,11 +592,12 @@ private void CheckReferrers(HashSet modelLines) || referrer.Field == "Element.m_assocLevelId") continue; // Why each class may stay: dimensions and alignments are the relations read in Dimensions; a sketch, an // extrusion and a sketch plane are the forms themselves; a curve is checked below; views and their companions - // (extents, sun settings) only look at the form; a host, its openings and the connectors, warnings and - // imports on it have their own level or cut the host, and move none of the family's forms. + // (extents, sun settings) only look at the form; a filled region is a drawing of the views that stands on its + // own sketch; a host, its openings and the connectors, warnings and imports on it have their own level or cut + // the host, and move none of the family's forms. bool known = referrer.ClassName switch { - "LinearDimString" or "Alignment" or "VarSketch" or "ExtrusionElem" or "SketchPlane" => true, + "LinearDimString" or "Alignment" or "RadialDim" or "VarSketch" or "ExtrusionElem" or "RevolutionElem" or "SketchPlane" => true, "CurveElem" => !modelLines.Contains(referrer.RecordId) || referrer.Field is "CurveElemDriver.EndInfo.m_elemId" or "CurveElem.m_sketchPlaneId" or "SketchMembership.GroupMembership.m_groupId" @@ -331,7 +605,7 @@ private void CheckReferrers(HashSet modelLines) || referrer.Field == "CDJoinInfo.EndInfo.m_elemId" && records.Joints.Any(j => j.LineId == referrer.TargetId && j.OtherLineId == referrer.RecordId && j.OtherEnd == -1), "ExtentElem" or "DBViewPlan" or "DBViewSection" or "DBView3d" or "SunAndShadowSettings" or "Opening" - or "ComplexOpening" or "ConnectorElem" or "PostedWarningElem" or "ImportInstance" => true, + or "ComplexOpening" or "ConnectorElem" or "PostedWarningElem" or "ImportInstance" or "FilledRegion" => true, var name => TfClassNames.IsSubclassOf(name, "HostObj"), }; if (!known) throw Unrecognized($"{referrer.ClassName} {referrer.RecordId}"); @@ -341,7 +615,8 @@ private void CheckReferrers(HashSet modelLines) private void CheckFormulas() { var driving = records.Dimensions.SelectMany(d => d.ParameterIds) - .Concat(records.Associations.Where(a => _extrusions.ContainsKey(a.ElementId) + .Concat((records.RadialDimensions ?? []).Select(r => r.ParameterId).Where(parameter => parameter != -1)) + .Concat(records.Associations.Where(a => (_extrusions.ContainsKey(a.ElementId) || _revolutions.ContainsKey(a.ElementId)) && a.ElementPropertyId != (long)BuiltInParameter.MATERIAL_ID_PARAM).Select(a => a.FamilyParameterId)); var formulas = driving.Where(records.FormulaParameterIds.Contains).Distinct().Order().ToList(); if (formulas.Count > 0) throw Unsupported("formula of parameter " + string.Join(", ", formulas)); @@ -405,21 +680,24 @@ void Hold(long? parameter, int sign, double constant, bool weak, params (int Nod } } + /// The coordinate along of a sketch plane: where it is, when it follows nothing, else + /// what it follows, as far from it as it stands. + private int PlaneNode(FamilyReference? host, double origin, int axis, int source) + { + if (host is not { } followedReference) return Add(origin, anchored: true); + int followed = Resolve(followedReference, axis, source); + if (double.IsNaN(_nodes[followed].Stored)) _nodes[followed].Stored = origin; + int plane = Add(origin); + _equations.Add(new([(plane, 1), (followed, -1)], null, 1, origin - _nodes[followed].Stored, source, false)); + return plane; + } + /// The coordinates of the two ends of an extrusion, the lower one first, and the relations that place them /// from the sketch plane. An end that a strong relation holds keeps no offset of its own. private (int Low, int High, bool Swapped) PlaceCaps(FamilyExtrusionRecord extrusion, int axis) { int way = Math.Sign(extrusion.PlaneNormal[axis]); - int plane; - if (extrusion.PlaneHost is { } host) - { - int followed = Resolve(host, axis, extrusion.Id); - if (double.IsNaN(_nodes[followed].Stored)) _nodes[followed].Stored = extrusion.PlaneOrigin[axis]; - plane = Add(extrusion.PlaneOrigin[axis]); - _equations.Add(new([(plane, 1), (followed, -1)], null, 1, - extrusion.PlaneOrigin[axis] - _nodes[followed].Stored, extrusion.Id, false)); - } - else plane = Add(extrusion.PlaneOrigin[axis], anchored: true); + int plane = PlaneNode(extrusion.PlaneHost, extrusion.PlaneOrigin[axis], axis, extrusion.Id); int start = Cap(extrusion, false), end = Cap(extrusion, true); foreach (var (cap, offset, property) in new[] @@ -442,16 +720,18 @@ void Hold(long? parameter, int sign, double constant, bool weak, params (int Nod private int[][][] Vertices(FamilyExtrusionRecord extrusion, int axis) => [.. extrusion.Loops.Select(loop => Enumerable.Range(0, loop.Count).Select(i => { - var before = _lines[extrusion.ProfileCurves[loop[(i + loop.Count - 1) % loop.Count]].LineId]; + var previous = extrusion.ProfileCurves[loop[(i + loop.Count - 1) % loop.Count]]; var curve = extrusion.ProfileCurves[loop[i]]; - var line = _lines[curve.LineId]; - var join = records.Joints.Where(j => j.OtherEnd >= 0).Select(j => - j.LineId == before.Id && j.OtherLineId == line.Id ? (int?)j.End - : j.LineId == line.Id && j.OtherLineId == before.Id ? j.OtherEnd : null) - .FirstOrDefault(end => end != null); + var (before, line) = (_lines[previous.LineId], _lines[curve.LineId]); + // The corner is where the previous curve stops and this one starts; of two curves that join at both ends, + // only the join between those two ends is it. + int stops = previous.Reversed ? 0 : 1, starts = curve.Reversed ? 1 : 0; + bool joined = records.Joints.Any(j => j.OtherEnd >= 0 && ( + j.LineId == before.Id && j.End == stops && j.OtherLineId == line.Id && j.OtherEnd == starts + || j.LineId == line.Id && j.End == starts && j.OtherLineId == before.Id && j.OtherEnd == stops)); var corner = curve.Reversed ? line.End : line.Start; return Enumerable.Range(0, 3).Select(c => c == axis ? -1 - : join is int end ? Slot(before, end, c) : Add(corner[c])).ToArray(); + : joined ? Slot(before, stops, c) : Add(corner[c])).ToArray(); }).ToArray())]; // A group of related coordinates without a level or a pinned plane is held by its oldest element, when that is a @@ -459,15 +739,13 @@ [.. extrusion.Loops.Select(loop => Enumerable.Range(0, loop.Count).Select(i => private void Anchor(IEnumerable shown) { var parent = new Dictionary(); - int Find(int node) - { - if (!parent.TryGetValue(node, out int up)) parent[node] = up = node; - return up == node ? node : parent[node] = Find(up); - } + int Find(int node) => FindGroup(parent, node); foreach (var equation in _equations) { - int first = Find(Root(equation.Terms[0].Node)); - foreach (var (node, _) in equation.Terms) parent[Find(Root(node))] = Find(first); + var places = equation.Terms.Select(term => Root(term.Node)).Where(node => !_nodes[node].Length).ToList(); + if (places.Count == 0) continue; + int first = Find(places[0]); + foreach (int node in places) parent[Find(node)] = Find(first); } var used = shown.Select(node => Find(Root(node))).ToHashSet(); foreach (var group in parent.Keys.ToList().GroupBy(Find).Where(g => used.Contains(g.Key) && g.Count() > 1)) @@ -485,7 +763,8 @@ int Find(int node) } private FamilyModel Assemble(Dictionary axes, Dictionary caps, - Dictionary vertices) + Dictionary vertices, Dictionary turns, + Dictionary placed) { var variables = new List(); var index = new Dictionary(); @@ -515,11 +794,42 @@ int Variable(int node) long? Bound(BuiltInParameter property) => records.Associations .Where(a => a.ElementId == extrusion.Id && a.ElementPropertyId == (long)property) .Select(a => (long?)a.FamilyParameterId).FirstOrDefault(); - return new FamilyExtrusion(extrusion.Id, loops, axes[extrusion.Id], lower, Variable(high), + int axis = axes[extrusion.Id]; + FamilyArcSegment? Arc(int key) + { + var curve = extrusion.ProfileCurves[key]; + var line = _lines[curve.LineId]; + if (line.Arc == null) return null; + var shape = Shape(line, axis); + var (start, way) = curve.Reversed ? (shape.EndDirection, -shape.Way) : (shape.StartDirection, shape.Way); + // The file stores a curved side as a row of flat faces, as many as its face tag has faces. + int facets = extrusion.FaceHistory.Where(face => face.Value is [3, var side] && side == key) + .Select(face => extrusion.FaceFacets?.GetValueOrDefault(face.Key)).FirstOrDefault(count => count > 0) + ?? 3 * shape.Quarters; + return new(Variable(Centre(line, (axis + 1) % 3)), Variable(Centre(line, (axis + 2) % 3)), + Variable(Radius(line)), way, start switch { (1, 0) => 0, (0, 1) => 1, (-1, 0) => 2, _ => 3 }, + shape.Quarters, facets); + } + IReadOnlyList>? arcs = !extrusion.Loops.Any(loop => loop.Any(key => Arc(key) != null)) + ? null : [.. extrusion.Loops.Select(loop => (IReadOnlyList)[.. loop.Select(Arc)])]; + return new FamilyExtrusion(extrusion.Id, loops, axis, lower, Variable(high), Materials(extrusion, swapped), Bound(BuiltInParameter.MATERIAL_ID_PARAM), - Bound(BuiltInParameter.IS_VISIBLE_PARAM)); + Bound(BuiltInParameter.IS_VISIBLE_PARAM), arcs); + }).ToList(); + long? BoundOf(int element, BuiltInParameter property) => records.Associations + .Where(a => a.ElementId == element && a.ElementPropertyId == (long)property) + .Select(a => (long?)a.FamilyParameterId).FirstOrDefault(); + var revolutions = _revolutions.Values.Select(revolution => + { + var (axis, normal) = turns[revolution.Id]; + var (plane, axisPosition, corners) = placed[revolution.Id]; + var loops = corners.Select(loop => (IReadOnlyList)loop + .Select(corner => new FamilyVertex(Variable(corner[0]), Variable(corner[1]), Variable(corner[2]))).ToList()).ToList(); + return new FamilyRevolution(revolution.Id, loops, axis, normal, Variable(axisPosition), Variable(plane), + new Dictionary(), BoundOf(revolution.Id, BuiltInParameter.MATERIAL_ID_PARAM), + BoundOf(revolution.Id, BuiltInParameter.IS_VISIBLE_PARAM)); }).ToList(); - return new(variables, equations, extrusions); + return new(variables, equations, extrusions) { Revolutions = revolutions }; } /// The stored materials by the faces of the model, whose start cap is the lower one. diff --git a/src/RvtIO/Families/FamilyRecordReader.cs b/src/RvtIO/Families/FamilyRecordReader.cs index 40ac23b0..64d2f8c4 100644 --- a/src/RvtIO/Families/FamilyRecordReader.cs +++ b/src/RvtIO/Families/FamilyRecordReader.cs @@ -12,37 +12,45 @@ namespace RvtIO.Families; /// it. internal static class FamilyRecordReader { - private sealed record ElementRecord(string ClassName, bool IsForm, bool IsCombination, bool Exact, long? FamilyId, + internal sealed record ElementRecord(string ClassName, bool IsForm, bool IsCombination, bool Exact, long? FamilyId, bool Cutting, long? VisibilityFlags, bool VisibilityDriven, long? GroupId, bool IsMember, bool MemberShownAlways, bool CutByOwnStep, long[] Members); /// The facts of the elements of the family (its id in the file). /// names the partition of the current record of every element that several partitions hold. + /// is the block of the partitions that holds the records: 0 for the family of the file, another for + /// the document of a family loaded into it. /// A file whose records cannot be read gives facts without settings, which leaves the shape incomplete and says so. internal static FamilyData Read(RootStorage root, RevitFileInfo info, ElementIdMap? ids, long ownerId, - IReadOnlyDictionary? currentCopies) + IReadOnlyDictionary? currentCopies, int block = 0) { var elements = new Dictionary(); foreach (var element in info.Elements) - if (!element.IsBlockOnly && !(info.ElemTableIsExact && element.IsDiscovered)) elements.TryAdd(element.Id, element); + if (!element.IsBlockOnly && !(info.ElemTableIsExact && element.IsDiscovered && block == 0)) + elements.TryAdd(element.Id, element); var records = new Dictionary(); - try { ReadRecords(root, elements, ids, currentCopies, records); } + bool recordsRead = true; + try { ReadRecords(root, elements, ids, currentCopies, records, block); } // What was read before the failure stands; every other element is reported as unrecognised below. - catch (Exception ex) when (ex is RvtWriteRefusedException || MalformedInput.Is(ex)) { } + catch (Exception ex) when (ex is RvtWriteRefusedException || MalformedInput.Is(ex)) { recordsRead = false; } var own = records.Where(pair => pair.Value is { Exact: true } record && record.FamilyId == ownerId) .ToDictionary(pair => pair.Key, pair => pair.Value!); var memberships = Memberships(own, ids); + var membersOf = memberships.ToLookup(pair => pair.Value, pair => pair.Key); var facts = new List(); foreach (var element in elements.Values) { + // An element belongs to the document of a block when that block holds its record; the others are the documents of + // other families. When the records could not be read, nothing says which they are, and all stay to be reported. + if (block != 0 && recordsRead && !records.ContainsKey(element.Id)) continue; bool hasGeometry = HasGeometry(element); if (own.TryGetValue(element.Id, out var record)) { var (shown, hidden) = record.IsCombination - ? Combined(element.Id, own, memberships, elements, []) + ? Combined(element.Id, own, membersOf, elements, []) : Settings(element, record); bool combined = memberships.ContainsKey(element.Id); // A member whose combination was not read would be left out without the shape that replaces it. @@ -57,24 +65,24 @@ internal static FamilyData Read(RootStorage root, RevitFileInfo info, ElementIdM // The content of a nested family names that family: it is not content of this one. var other = records.GetValueOrDefault(element.Id); if (other != null ? other.FamilyId is > 0 && other.FamilyId != ownerId - : element.SerializedFamilyId is > 0 && element.SerializedFamilyId != info.FamilyOwnerId) continue; + : element.SerializedFamilyId is > 0 && element.SerializedFamilyId != ownerId) continue; // Its record was not read exactly: reported when it has geometry or is a form that names this family. string className = other?.ClassName ?? element.RootClassName ?? "?"; bool form = other?.IsForm ?? FamilyRules.FormClasses.Any(name => TfClassNames.IsSubclassOf(className, name)); - if (hasGeometry || form && (other != null || element.SerializedFamilyId == info.FamilyOwnerId)) + if (hasGeometry || form && (other != null || element.SerializedFamilyId == ownerId)) facts.Add(new(element.Id, className, form, hasGeometry, false, null, null, DrawnInViewsOnly: FamilyRules.IsDrawnInViewsOnly(className, element.Category))); } - var (types, typesError) = ReadTypes(root, ownerId, ids, currentCopies); + var (types, typesError) = ReadTypes(root, ownerId, ids, currentCopies, block); var relations = types is { Types.Count: > 0 } - ? FamilyRelationReader.Read(root, elements, ids, ownerId, currentCopies, facts) : null; + ? FamilyRelationReader.Read(root, elements, ids, ownerId, currentCopies, facts, block) : null; return new FamilyData { Elements = facts, Types = types, TypesError = typesError, Records = relations }; } /// The types of the family from its record, with their parameters. A family that stores /// no types gives neither types nor a reason; a table that is not read exactly gives no types and the reason. internal static (RvtFamilyTypes? Types, string? Error) ReadTypes(RootStorage root, long ownerId, ElementIdMap? ids, - IReadOnlyDictionary? currentCopies) + IReadOnlyDictionary? currentCopies, int block = 0) { try { @@ -91,7 +99,7 @@ internal static (RvtFamilyTypes? Types, string? Error) ReadTypes(RootStorage roo ParameterWriter.ScanPartitions(root, tags, idWidth, (partition, record) => { if (currentCopies != null && currentCopies.TryGetValue(record.Owner, out int current) && current != partition) return; - if (record.Block != 0 || record.Channel != 102 || record.Body.Length < 2 || record.Owner > long.MaxValue) return; + if (record.Block != block || record.Channel != 102 || record.Body.Length < 2 || record.Owner > long.MaxValue) return; long owner = (long)record.Owner; int cls = BinaryPrimitives.ReadUInt16LittleEndian(record.Body.Span); if (owner != ownerId && !walker.IsA(cls, "ParamElem")) return; @@ -213,18 +221,20 @@ private static Dictionary Memberships(Dictionary o return memberships; } + private const int MaxCombinationDepth = 64; + /// A combination has no settings of its own: it shows the forms it combines. What Revit shows of it is /// established only when every solid member is shown. - private static (bool? Shown, bool? Hidden) Combined(int key, Dictionary own, - Dictionary memberships, Dictionary elements, HashSet visited) + internal static (bool? Shown, bool? Hidden) Combined(int key, Dictionary own, + ILookup membersOf, Dictionary elements, HashSet visited, int depth = 0) { - if (!visited.Add(key)) return (null, null); - foreach (var (member, combination) in memberships) + // A family nests a few levels of combinations; a file with more is not established, rather than followed to the end. + if (depth > MaxCombinationDepth || !visited.Add(key)) return (null, null); + foreach (int member in membersOf[key]) { - if (combination != key) continue; if (!own.TryGetValue(member, out var record)) return (null, null); if (record.Cutting) continue; - var settings = record.IsCombination ? Combined(member, own, memberships, elements, visited) + var settings = record.IsCombination ? Combined(member, own, membersOf, elements, visited, depth + 1) : Settings(elements[member], record); if (settings != (true, false)) return (null, null); } @@ -252,7 +262,7 @@ private static bool HasGeometry(Element element) => /// The records of the elements, by element key; null for an element with more than one record. private static void ReadRecords(RootStorage root, Dictionary elements, ElementIdMap? ids, - IReadOnlyDictionary? currentCopies, Dictionary records) + IReadOnlyDictionary? currentCopies, Dictionary records, int block) { if (TfSchemaReader.Read(root) is not { } schema) return; var formats = new FormatsSchema(schema); @@ -263,7 +273,7 @@ private static void ReadRecords(RootStorage root, Dictionary eleme ParameterWriter.ScanPartitions(root, tags, idWidth, (partition, record) => { if (currentCopies != null && currentCopies.TryGetValue(record.Owner, out int current) && current != partition) return; - if (record.Block != 0 || record.Channel != 102 || record.Body.Length < 2 || record.Owner > long.MaxValue + if (record.Block != block || record.Channel != 102 || record.Body.Length < 2 || record.Owner > long.MaxValue || Key(ids, (long)record.Owner) is not int key || !elements.TryGetValue(key, out var element)) return; int cls = BinaryPrimitives.ReadUInt16LittleEndian(record.Body.Span); bool form = FamilyRules.FormClasses.Any(name => walker.IsA(cls, name)); diff --git a/src/RvtIO/Families/FamilyRecords.cs b/src/RvtIO/Families/FamilyRecords.cs index c0c10fdd..2d79b622 100644 --- a/src/RvtIO/Families/FamilyRecords.cs +++ b/src/RvtIO/Families/FamilyRecords.cs @@ -11,8 +11,28 @@ internal sealed record FamilyDimensionRecord(int Id, bool IsAlignment, double[] IReadOnlyList SegmentFlags, IReadOnlyList References, IReadOnlyList ParameterIds, IReadOnlyList SegmentValues, IReadOnlySet DrivenSegments); -/// A curve element: a line of a sketch, or one in no sketch (SketchId 0). -internal sealed record FamilySketchLine(int Id, int SketchId, bool IsStraight, double[] Start, double[] End); +/// The circle or arc a curve is: its centre, the unit axes of its plane, its radius, and the angles of its ends +/// (a point of it is the centre plus the radius times the cosine of the angle along XAxis and the sine along +/// YAxis). +internal sealed record FamilyArc(double[] Center, double[] XAxis, double[] YAxis, double Radius, double StartAngle, + double EndAngle); + +/// A radius or diameter dimension of an arc: the arc it measures, its label (-1 for none), the value it holds, +/// its flags and the kind of its dimension style (DimensionStyle.m_dimensionStyleType; -1 when not read). +internal sealed record FamilyRadialDimension(int Id, FamilyReference Arc, long ParameterId, double Value, long Flags, + long SegmentFlags, bool Driven, long StyleType); + +/// A constraint of a sketch that holds the end End (0 or 1) of the arc curve ArcLineId at an +/// angle of its own. +internal sealed record FamilyArcEndAngle(int SketchId, int ArcLineId, int End); + +/// A curve element: a line of a sketch, or one in no sketch (SketchId 0). Arc is set for an arc; its +/// ends are in Start and End as for a line. A circle that is one closed arc of the sketch is two half arcs in +/// the profile of an extrusion; each half is a line of its own, with an id no element has, and CircleId names the +/// closed arc whose centre and radius it shares. IsRevolutionAxis marks the line a revolution turns about +/// (RevolutionCurveData.m_axis), which is no part of its profile. +internal sealed record FamilySketchLine(int Id, int SketchId, bool IsStraight, double[] Start, double[] End, + FamilyArc? Arc = null, int? CircleId = null, bool IsRevolutionAxis = false); /// End End of a curve joins end OtherEnd of another; OtherEnd -1: it lies on that curve. internal sealed record FamilySketchJoint(int LineId, int End, int OtherLineId, int OtherEnd); @@ -31,11 +51,19 @@ internal sealed record FamilyPlaneRecord(int ElementId, string ClassName, long R /// An extrusion: its start and end offsets from the sketch plane along its normal, what the sketch plane follows /// (null when nothing), its profile loops as keys of ProfileCurves in order, and the history of its faces and -/// edges by their geometry tags. FaceMaterials gives the stored material of each face tag. +/// edges by their geometry tags. FaceMaterials gives the stored material of each face tag, and FaceFacets how +/// many faces the file stores for it (a curved side is stored as a row of flat ones). internal sealed record FamilyExtrusionRecord(int Id, int SketchId, double Start, double End, double[] PlaneOrigin, double[] PlaneNormal, FamilyReference? PlaneHost, IReadOnlyList> Loops, IReadOnlyDictionary ProfileCurves, IReadOnlyDictionary FaceHistory, - IReadOnlyDictionary EdgeHistory, IReadOnlyDictionary FaceMaterials); + IReadOnlyDictionary EdgeHistory, IReadOnlyDictionary FaceMaterials, + IReadOnlyDictionary? FaceFacets = null); + +/// A revolution: its start and end angles (from the sketch plane, about the axis), what the sketch plane follows +/// (null when nothing), the closed loops of straight lines that are its profile (each curve a sketch line, with the way it is +/// run) and the sketch line it turns about. +internal sealed record FamilyRevolutionRecord(int Id, int SketchId, double StartAngle, double EndAngle, double[] PlaneOrigin, + double[] PlaneNormal, FamilyReference? PlaneHost, IReadOnlyList> Loops, int AxisLineId); /// A field of a record of the family that refers to another element. internal sealed record FamilyReferrer(int RecordId, string ClassName, string Field, int TargetId); @@ -44,10 +72,13 @@ internal sealed record FamilyReferrer(int RecordId, string ClassName, string Fie internal sealed record FamilyAssociation(int ElementId, long ElementPropertyId, long FamilyParameterId); /// What the records of a family say about the placing of its forms, as plain values. -/// UnsupportedContent names what is shown and cannot be recomputed. +/// UnsupportedContent names what is shown and cannot be recomputed. ControlIconIds are the control icons (the +/// arrows that flip an element) of the family. internal sealed record FamilyRecords(IReadOnlyList Dimensions, IReadOnlyList Lines, IReadOnlyList Joints, IReadOnlyList Constraints, IReadOnlyList Planes, IReadOnlyList Extrusions, IReadOnlyList Referrers, IReadOnlyList Associations, IReadOnlySet FormulaParameterIds, - IReadOnlyList UnsupportedContent); + IReadOnlyList UnsupportedContent, IReadOnlyList? RadialDimensions = null, + IReadOnlyList? ArcEndAngles = null, IReadOnlySet? ControlIconIds = null, + IReadOnlyList? Revolutions = null); diff --git a/src/RvtIO/Families/FamilyRelationReader.cs b/src/RvtIO/Families/FamilyRelationReader.cs index 1455ae89..f8e08971 100644 --- a/src/RvtIO/Families/FamilyRelationReader.cs +++ b/src/RvtIO/Families/FamilyRelationReader.cs @@ -14,9 +14,9 @@ internal static class FamilyRelationReader /// The records of the family (its id in the file) among /// ; null when the records of the file cannot be read. internal static FamilyRecords? Read(RootStorage root, IReadOnlyDictionary elements, ElementIdMap? ids, - long ownerId, IReadOnlyDictionary? currentCopies, IReadOnlyList facts) + long ownerId, IReadOnlyDictionary? currentCopies, IReadOnlyList facts, int block = 0) { - try { return new Reader(root, elements, ids, ownerId, currentCopies).Read(facts); } + try { return new Reader(root, elements, ids, ownerId, currentCopies, block).Read(facts); } catch (Exception ex) when (ex is RvtWriteRefusedException or Unread || MalformedInput.Is(ex)) { return null; } } @@ -49,6 +49,8 @@ private sealed class Unread(string detail) : Exception(detail); "DimSegInfo.m_flags", "DimSegValue.m_value", "WitnessRefInfo.m_pWitnessRef", "GeomRef.m_elemId", "GeomRef.m_geomTag", "GeomRef.m_subTag", "Alignment.m_constrDir", "LinearConstraint.m_pDimLine", "GLine.m_origin", "GLine.m_dirVec", "GCurve.m_endParams", "GInfo.m_tag", + "GArc.m_xVec", "GArc.m_yVec", "GArc.m_radius", "GArc.m_center", "ArcWitnessRefInfo.m_pWitnessRef", "DimensionStyle.m_dimensionStyleType", + "VarSketchArcEndAngleConstrObj.m_end", "VarSketchObj.m_objId", "CurveElem.m_pCurveDriver", "CurveDriver.m_pCrv", "GroupMembership.m_groupId", "EndInfo.m_elemId", "EndInfo.m_joinedEnd", "IndexJoinPair.m_index", "DatumPlane.m_pSurface", "Plane.m_origin", "Plane.m_xVec", "Plane.m_yVec", "RefPlaneBase.m_refName", @@ -56,13 +58,14 @@ private sealed class Unread(string detail) : Exception(detail); "Sketch.m_pPlane", "Sketch.m_sketchPlaneId", "Sketch.m_elemIdsPairSet", "ElementIdPlusIndex.m_elementId", "ElementIdPlusIndex.m_index", "CurveHistEntry.m_id", "CurveHist.m_keys", "SketchPlane.m_oPlaneRef", "OneElementMovablePlaneRef.m_datumPlaneId", - "ExtrusionHelper.m_sketchId", "ParamValueDouble.m_paramId", "ParamValueDouble.m_value", "FaceHistEntry.m_id", + "ExtrusionHelper.m_sketchId", "RevolutionElem.m_sketchId", "RevolutionCurveData.m_axis", "ParamValueDouble.m_paramId", "ParamValueDouble.m_value", "FaceHistEntry.m_id", "FaceHist.m_keys", "EdgeHistEntry.m_id", "EdgeHist.m_keys", "ParamIdPair.m_famParamId", "ParamIdPair.m_elemPropId", ]; /// Counted arrays that are read whole besides the arrays of references to elements. - private static readonly HashSet WholeArrays = ["ElementExtrusionHelper.m_pCurveLoops", "CurveLoop.m_curves"]; + private static readonly HashSet WholeArrays = + ["ElementExtrusionHelper.m_pCurveLoops", "CurveLoop.m_curves", "VarSketchConstrObj.m_constrElems", "VarSketch.m_elemRecs", "VarSketch.m_pointRecs"]; /// One walked record, with its captured values by the object (slot) that holds them; -1 is the record /// itself. @@ -124,9 +127,10 @@ public int[] Pointers(string name, int slot) } private sealed class Reader(RootStorage root, IReadOnlyDictionary elements, ElementIdMap? ids, - long ownerId, IReadOnlyDictionary? currentCopies) + long ownerId, IReadOnlyDictionary? currentCopies, int block) { private readonly Dictionary _own = []; + private readonly Dictionary _styleTypes = []; private readonly List _unsupported = []; public FamilyRecords? Read(IReadOnlyList facts) @@ -155,7 +159,7 @@ private sealed class Reader(RootStorage root, IReadOnlyDictionary { if (currentCopies != null && currentCopies.TryGetValue(record.Owner, out int current) && current != partition) return; - if (record.Block != 0 || record.Channel != 102 || record.Body.Length < 2 || record.Owner > long.MaxValue) + if (record.Block != block || record.Channel != 102 || record.Body.Length < 2 || record.Owner > long.MaxValue) return; if ((long)record.Owner == ownerId) { familyBody ??= record.Body.ToArray(); return; } if (Key((long)record.Owner) is not int key || !elements.ContainsKey(key)) return; @@ -167,6 +171,9 @@ private sealed class Reader(RootStorage root, IReadOnlyDictionary { int cls = BinaryPrimitives.ReadUInt16LittleEndian(body); var walk = walker.Run(body, 0, body.Length, cls); + if (walk.Exact && walker.Class(cls)?.Name == "DimensionStyle" + && walk.Captures.FirstOrDefault(c => c.AtRoot && c.Key == "DimensionStyle.m_dimensionStyleType") is { Key: not null } type) + _styleTypes[key] = type.Integer; var family = walk.Captures.FirstOrDefault(c => c.AtRoot && c.Key.EndsWith("Element.m_famId", StringComparison.Ordinal)); // The record of another family: the content of a nested one. if (family.Key != null && family.Integer != ownerId) continue; @@ -189,6 +196,8 @@ private sealed class Reader(RootStorage root, IReadOnlyDictionary var constraints = new List(); var planes = new List(); var dimensions = new List(); + var radials = new List(); + var angles = new List(); var referrers = new HashSet(); var associations = new List(); foreach (var record in _own.Values) @@ -199,27 +208,38 @@ private sealed class Reader(RootStorage root, IReadOnlyDictionary Associations(record, associations); if (record.ClassName == "CurveElem") lines.Add(Line(record, joints)); else if (record.ClassName is "LinearDimString" or "Alignment") dimensions.Add(Dimension(record, driven)); + else if (record.ClassName == "RadialDim") radials.Add(Radial(record, driven)); else if (record.ClassName is "RefPlane" or "Level") planes.Add(Plane(record)); else if (TfClassNames.IsSubclassOf(record.ClassName, "HostObj")) planes.Add(new(record.Key, record.ClassName, 0, [], [])); else if (TfClassNames.IsSubclassOf(record.ClassName, "Sketch")) + { constraints.AddRange(record.Slots.Select(record.SlotClass) .Where(name => name.Contains("Constr", StringComparison.Ordinal)) .Select(name => new FamilySketchConstraint(record.Key, name))); + angles.AddRange(ArcEndAngles(record)); + } } catch (Unread unread) { _unsupported.Add(unread.Message); } } var byId = lines.ToDictionary(line => line.Id); var extrusions = new List(); + var revolutions = new List(); foreach (var fact in facts.Where(IsRecomputed)) { - try { extrusions.Add(Extrusion(fact.ElementId, byId)); } + try + { + if (fact.ClassName == "RevolutionElem") revolutions.Add(Revolution(fact.ElementId, lines, joints)); + else extrusions.Add(Extrusion(fact.ElementId, byId, lines, joints)); + } catch (Unread unread) { _unsupported.Add(unread.Message); } } return new(dimensions, lines, joints, constraints, planes, extrusions, [.. referrers], associations, - formulas, _unsupported); + formulas, _unsupported, radials, angles, + _own.Values.Where(record => record.ClassName == "ControlIconElem").Select(record => record.Key).ToHashSet(), + revolutions); } private static bool Holds(List? arguments, int reference) => @@ -272,10 +292,10 @@ private static bool Holds(List? arguments, int reference) => return (driven, formulas); } - /// An extrusion whose faces are computed: a solid one the family shows in a 3D view at the Fine detail - /// level, in some type or in all. + /// An extrusion or a revolution whose faces are computed: a solid one the family shows in a 3D view at the + /// Fine detail level, in some type or in all. private static bool IsRecomputed(FamilyElementFacts fact) => - fact is { ClassName: "ExtrusionElem", IsForm: true, Cutting: false, ShownInFine: true, CombinationMember: false, + fact is { ClassName: "ExtrusionElem" or "RevolutionElem", IsForm: true, Cutting: false, ShownInFine: true, CombinationMember: false, DrawnInViewsOnly: false, CutByOwnStep: false }; // Everything else that is shown, in this type or in another, cannot be computed. @@ -319,6 +339,14 @@ private void Associations(Record record, List associations) } private FamilySketchLine Line(Record record, List joints) + { + var line = ReadLine(record, joints); + // The line a revolution turns about is marked in the data of its curve. + return record.Values.Any(item => item.Name == "RevolutionCurveData.m_axis" && item.Value.Integer != 0) + ? line with { IsRevolutionAxis = true } : line; + } + + private FamilySketchLine ReadLine(Record record, List joints) { var membership = record.Values.FirstOrDefault(item => item.Name == "GroupMembership.m_groupId" && record.SlotClass(item.Slot) == "SketchMembership"); @@ -350,12 +378,49 @@ private FamilySketchLine Line(Record record, List joints) var curve = record.Values.Where(item => item.Name == "CurveDriver.m_pCrv") .Select(item => (int?)record.Target(item.Value)).FirstOrDefault(); - if (curve is not int slot || record.SlotClass(slot) != "GLine") - return new(record.Key, sketch, false, new double[3], new double[3]); - var (start, end) = Ends(record, slot); - return new(record.Key, sketch, true, start, end); + if (curve is not int slot) return new(record.Key, sketch, false, new double[3], new double[3]); + switch (record.SlotClass(slot)) + { + case "GLine": + var (start, end) = Ends(record, slot); + return new(record.Key, sketch, true, start, end); + case "GArc": + var arc = Arc(record, slot); + return new(record.Key, sketch, false, At(arc, arc.StartAngle), At(arc, arc.EndAngle), arc); + default: + return new(record.Key, sketch, false, new double[3], new double[3]); + } + } + + /// The constraints of a sketch that hold the end of an arc at an angle. + private IEnumerable ArcEndAngles(Record sketch) + { + var constraints = sketch.Slots.Where(i => sketch.SlotClass(i) == "VarSketchArcEndAngleConstrObj").ToList(); + if (constraints.Count == 0) yield break; + // A constraint names its curve by an index that counts the curves of the sketch and four more objects ahead of + // them (measured on sketches of up to 20 curves, none with points); the curve it names must be an arc. + int[] curves = sketch.Pointers("VarSketch.m_elemRecs", -1); + if (sketch.Integer("VarSketch.m_pointRecs#", -1) != 0) throw new Unread($"points of sketch {sketch.Key}"); + foreach (int slot in constraints) + { + if (sketch.Integer("VarSketchConstrObj.m_constrElems#", slot) != 1) throw new Unread($"arc end angle of sketch {sketch.Key}"); + long index = sketch.Integer("VarSketchConstrObj.m_constrElems@0", slot) - curves.Length - 4; + if (index < 0 || index >= curves.Length || sketch.SlotClass(curves[index]) != "VarSketchArcObj") + throw new Unread($"arc end angle of sketch {sketch.Key}"); + yield return new(sketch.Key, Referenced(sketch.Integer("VarSketchObj.m_objId", curves[index])), + (int)sketch.Integer("VarSketchArcEndAngleConstrObj.m_end", slot)); + } } + private static FamilyArc Arc(Record record, int slot) => new(record.Vector("GArc.m_center", slot), + record.Vector("GArc.m_xVec", slot), record.Vector("GArc.m_yVec", slot), record.Real("GArc.m_radius", slot), + record.Real("GCurve.m_endParams@0", slot), record.Real("GCurve.m_endParams@1", slot)); + + private static double[] At(FamilyArc arc, double angle) => [.. Enumerable.Range(0, 3).Select(i => + arc.Center[i] + arc.Radius * (Math.Cos(angle) * arc.XAxis[i] + Math.Sin(angle) * arc.YAxis[i]))]; + + private static (double[] Start, double[] End) ArcEnds(FamilyArc arc) => (At(arc, arc.StartAngle), At(arc, arc.EndAngle)); + private static (double[] Start, double[] End) Ends(Record record, int slot) { var origin = record.Vector("GLine.m_origin", slot); @@ -364,9 +429,10 @@ private static (double[] Start, double[] End) Ends(Record record, int slot) return (At(record.Real("GCurve.m_endParams@0", slot)), At(record.Real("GCurve.m_endParams@1", slot))); } - private FamilyDimensionRecord Dimension(Record record, Dictionary> driven) + /// The segments of a dimension (label, flags and value of each) and what its witness lines refer to. + private (List<(long? Parameter, long? Flags, double? Value)> Held, List References) Segments( + Record record) { - bool alignment = record.ClassName == "Alignment"; long count = record.Integer("Dimension.m_ArrSegInfo#"); var segments = new List<(long? Parameter, long? Flags, double? Value)>(); var references = new List(); @@ -380,7 +446,7 @@ private FamilyDimensionRecord Dimension(Record record, Dictionary= 0) segments[last] = segments[last] with { Value = segments[last].Value ?? value.Real }; - else if (name == "WitnessRefInfo.m_pWitnessRef") + else if (name is "WitnessRefInfo.m_pWitnessRef" or "ArcWitnessRefInfo.m_pWitnessRef") { int witness = record.Target(value); references.Add(new(Referenced(record.Integer("GeomRef.m_elemId", witness)), @@ -392,6 +458,24 @@ private FamilyDimensionRecord Dimension(Record record, Dictionary s.Parameter == null || s.Flags == null || s.Value == null)) throw new Unread($"segments of dimension {record.Key}"); + return (held, references); + } + + /// A radius or diameter dimension: one segment and the arc it measures. + private FamilyRadialDimension Radial(Record record, Dictionary> driven) + { + var (held, references) = Segments(record); + if (held.Count != 1 || references.Count != 1) throw new Unread($"segments of dimension {record.Key}"); + int style = Referenced(record.Integer("Dimension.m_styleSymbolId")); + return new(record.Key, references[0], ParameterKey(held[0].Parameter!.Value), held[0].Value!.Value, + record.Integer("Dimension.m_flags"), held[0].Flags!.Value, driven.GetValueOrDefault(record.Key)?.Contains(0) == true, + _styleTypes.GetValueOrDefault(style, -1)); + } + + private FamilyDimensionRecord Dimension(Record record, Dictionary> driven) + { + bool alignment = record.ClassName == "Alignment"; + var (held, references) = Segments(record); var axis = alignment ? record.Vector("Alignment.m_constrDir", -1) : record.Vector("GLine.m_dirVec", record.Pointer("LinearConstraint.m_pDimLine")); return new(record.Key, alignment, axis, record.Integer("Dimension.m_flags"), @@ -419,7 +503,48 @@ private static FamilyPlaneRecord Plane(Record record) private Record Own(int key, string what) => _own.GetValueOrDefault(key) ?? throw new Unread($"{what} {key}"); - private FamilyExtrusionRecord Extrusion(int key, Dictionary lines) + /// A loop that is a circle the sketch holds as one closed arc: the file splits it into two half arcs, the + /// one the sketch numbers as the closed arc and one it numbers by no element. Returns the tag and a line of its own + /// for each half, or null when the loop is anything else (the circle must be that of the closed arc, and the halves + /// must turn a whole turn between them, each leaving where the other stops). + private static List<(int Tag, FamilySketchLine Half)>? SplitCircle(Record record, int[] curves, + Dictionary numbers, Dictionary elementsByNumber, Dictionary lines) + { + if (curves.Length != 2 || curves.Any(curve => record.SlotClass(curve) != "GArc")) return null; + var found = curves.Select(curve => + { + int tag = (int)record.Integer("GInfo.m_tag", curve); + lines.TryGetValue(numbers.TryGetValue(tag, out long number) && elementsByNumber.TryGetValue(number, out int id) + ? id : 0, out var line); + return (Tag: tag, Arc: Arc(record, curve), Line: line); + }).ToArray(); + // Exactly one half is the closed arc of the sketch. + if (found.Count(half => half.Line != null) != 1) return null; + var circle = found.Single(half => half.Line != null).Line!; + if (circle.Arc is not { } whole || Enumerable.Range(0, 3).Any(i => Math.Abs(circle.Start[i] - circle.End[i]) > 1e-6)) + return null; + double[] Normal(FamilyArc arc) => + [ + arc.XAxis[1] * arc.YAxis[2] - arc.XAxis[2] * arc.YAxis[1], arc.XAxis[2] * arc.YAxis[0] - arc.XAxis[0] * arc.YAxis[2], + arc.XAxis[0] * arc.YAxis[1] - arc.XAxis[1] * arc.YAxis[0], + ]; + // A hole is drawn the other way round: its halves may turn the other way from the closed arc (the opposite normal). + bool OfCircle(FamilyArc part) => Math.Abs(part.Radius - whole.Radius) <= 1e-6 + && Enumerable.Range(0, 3).All(i => Math.Abs(part.Center[i] - whole.Center[i]) <= 1e-6) + && (Enumerable.Range(0, 3).All(i => Math.Abs(Normal(part)[i] - Normal(whole)[i]) <= 1e-6) + || Enumerable.Range(0, 3).All(i => Math.Abs(Normal(part)[i] + Normal(whole)[i]) <= 1e-6)); + bool Meets(double[] a, double[] b) => Enumerable.Range(0, 3).All(i => Math.Abs(a[i] - b[i]) <= 1e-6); + var (first, second) = (ArcEnds(found[0].Arc), ArcEnds(found[1].Arc)); + if (!found.All(half => OfCircle(half.Arc)) + || Math.Abs(found.Sum(half => Math.Abs(half.Arc.EndAngle - half.Arc.StartAngle)) - 2 * Math.PI) > 1e-6 + || !Meets(first.End, second.Start) || !Meets(second.End, first.Start)) + return null; + return [.. found.Select((half, index) => (half.Tag, new FamilySketchLine(-(circle.Id * 2 + index) - 1, circle.SketchId, + false, ArcEnds(half.Arc).Start, ArcEnds(half.Arc).End, half.Arc, circle.Id)))]; + } + + private FamilyExtrusionRecord Extrusion(int key, Dictionary lines, List all, + List joints) { var record = Own(key, "extrusion"); if (record.Slots.Where(i => record.Find("ExtrusionHelper.m_sketchId", i) != null).ToArray() is not [var helper]) @@ -448,15 +573,33 @@ private FamilyExtrusionRecord Extrusion(int key, Dictionary(); - foreach (int curve in record.Pointers("CurveLoop.m_curves", loop)) + var curves = record.Pointers("CurveLoop.m_curves", loop); + if (SplitCircle(record, curves, numbers, elementsByNumber, lines) is { } split) + { + foreach (var (tag, half) in split) + { + tags.Add(tag); + profile.Add(tag, new(half.Id, false)); + lines.Add(half.Id, half); + all.Add(half); + } + // The halves meet at both ends of the circle. + joints.Add(new(split[0].Half.Id, 1, split[1].Half.Id, 0)); + joints.Add(new(split[1].Half.Id, 1, split[0].Half.Id, 0)); + loops.Add(tags); + continue; + } + foreach (int curve in curves) { int tag = (int)record.Integer("GInfo.m_tag", curve); tags.Add(tag); if (!numbers.TryGetValue(tag, out long number) || !elementsByNumber.TryGetValue(number, out int lineId) || !lines.TryGetValue(lineId, out var line)) continue; - // A curve that is not straight is refused by what builds the model; its direction does not matter. + // A curve that is neither a straight line nor an arc is refused by what builds the model. bool reversed = line.IsStraight && record.SlotClass(curve) == "GLine" - && Reversed(Ends(record, curve), line, normal, key); + && Reversed(Ends(record, curve), line, normal, key) + || line.Arc != null && record.SlotClass(curve) == "GArc" + && Reversed(ArcEnds(Arc(record, curve)), line, normal, key); if (!profile.TryAdd(tag, new(lineId, reversed))) throw new Unread($"profile of {key}"); } loops.Add(tags); @@ -464,7 +607,80 @@ private FamilyExtrusionRecord Extrusion(int key, DictionaryA revolution: its sketch, the angles of its sweep, the loops of straight lines that are its profile (each + /// closed by the joins of the lines, run from a line's start or its end as the chain goes) and the line it turns + /// about. + private FamilyRevolutionRecord Revolution(int key, List all, List joints) + { + var record = Own(key, "revolution"); + var sketch = Own(Referenced(record.Integer("RevolutionElem.m_sketchId")), "sketch of revolution " + key); + if (!TfClassNames.IsSubclassOf(sketch.ClassName, "Sketch")) throw new Unread($"sketch of {key}"); + var (origin, normal) = Surface(sketch, sketch.Pointer("Sketch.m_pPlane")); + + var angles = new Dictionary(); + double? value = null; + foreach (var (name, item) in record.In(record.Pointer("Element.m_pParamValueSetDouble"))) + { + if (name == "ParamValueDouble.m_value") value = item.Real; + else if (name == "ParamValueDouble.m_paramId" && value is double angle) + (angles[item.Integer], value) = (angle, null); + } + if (!angles.TryGetValue((long)BuiltIns.BuiltInParameter.REVOLUTION_START_ANGLE, out double start) + || !angles.TryGetValue((long)BuiltIns.BuiltInParameter.REVOLUTION_END_ANGLE, out double end)) + throw new Unread($"start and end angles of {key}"); + + var lines = all.Where(line => line.SketchId == sketch.Key).ToList(); + if (lines.Where(line => line.IsRevolutionAxis).ToArray() is not [{ IsStraight: true } axis]) + throw new Unread($"axis of {key}"); + var profile = lines.Where(line => !line.IsRevolutionAxis).OrderBy(line => line.Id).ToList(); + if (profile.Any(line => !line.IsStraight)) throw new Unread($"curve of revolution {key}"); + + // The curve that follows each end of a profile line, from the joins; a join is listed from one curve or both. + var follows = new Dictionary<(int Line, int End), (int Line, int End)>(); + var ids = profile.Select(line => line.Id).ToHashSet(); + foreach (var joint in joints.Where(j => j.OtherEnd is 0 or 1 && ids.Contains(j.LineId) && ids.Contains(j.OtherLineId))) + { + var (from, to) = ((joint.LineId, joint.End), (joint.OtherLineId, joint.OtherEnd)); + if (follows.TryGetValue(from, out var known) && known != to) throw new Unread($"profile of {key}"); + follows[from] = to; + } + + var used = new HashSet(); + var loops = new List>(); + foreach (var first in profile.Where(line => !used.Contains(line.Id)).ToList()) + { + if (used.Contains(first.Id)) continue; + var loop = new List(); + var (current, entered) = (first.Id, 0); + while (true) + { + if (!used.Add(current)) throw new Unread($"profile of {key}"); + loop.Add(new(current, entered == 1)); + if (!follows.TryGetValue((current, 1 - entered), out var next)) throw new Unread($"profile of {key}"); + if (next.Line == first.Id) + { + if (next.End != 0) throw new Unread($"profile of {key}"); + break; + } + (current, entered) = next; + } + loops.Add(loop); + } + if (loops.Count == 0) throw new Unread($"profile of {key}"); + return new(key, sketch.Key, start, end, origin, normal, Host(sketch), loops, axis.Id); + } + + /// How many faces the file stores for each face tag: a curved side is a row of flat faces. The faces counted + /// are those the saved state is compared with, which leave out the faces of untaken geometry nodes. + private static Dictionary Facets(Element element) + { + var faces = FamilyRecordReader.Body(element)?.Faces ?? []; + bool dropUntaken = faces.Any(face => face.GeometryNode > 0); + return faces.Where(face => face.GInfoFlags != null && (!dropUntaken || face.GeometryNode >= 0)) + .GroupBy(face => face.GInfoTag).ToDictionary(group => group.Key, group => group.Count()); } private static (Dictionary Faces, Dictionary Edges) History(Record record) diff --git a/src/RvtIO/Families/FamilyRevolutionBuilder.cs b/src/RvtIO/Families/FamilyRevolutionBuilder.cs new file mode 100644 index 00000000..f63644ed --- /dev/null +++ b/src/RvtIO/Families/FamilyRevolutionBuilder.cs @@ -0,0 +1,284 @@ +using RvtIO.Model; + +namespace RvtIO.Families; + +/// +/// The faces of a revolution for solved variable values, and the checks of its profile. A line of a loop turned a whole +/// turn about the axis is a surface of revolution: a cylinder when it runs along the axis, a plane (a ring or a disc) when +/// it runs across it, a cone otherwise; a line on the axis makes none. The surfaces are cut into equal +/// turns, so that the faces of neighbouring surfaces share their corners. A loop inside an odd number of loops is a hole. +/// +internal static class FamilyRevolutionBuilder +{ + private const double Tolerance = 1e-6; // feet + + /// The facets a full turn is cut into: a step of 20 degrees, which is what the file stores for the round + /// surfaces of the cone sample of the corpus. + public const int Facets = 18; + + private static int Component(FamilyVertex vertex, int axis) => axis == 0 ? vertex.X : axis == 1 ? vertex.Y : vertex.Z; + + /// The corners of each loop as (distance from the axis along the in-plane axis across it, signed; position along + /// the axis). + internal static List<(double D, double V)[]> Profiles(FamilyRevolution revolution, IReadOnlyList positions) + { + int across = 3 - revolution.Axis - revolution.Normal; + double axis = positions[revolution.AxisPosition]; + return [.. revolution.Loops.Select(loop => loop + .Select(corner => (positions[Component(corner, across)] - axis, positions[Component(corner, revolution.Axis)])).ToArray())]; + } + + // The sign of the side of the axis the profile stands on (the first corner off the axis); 0 when all lie on it. + private static int SideOfAxis(List<(double D, double V)[]> loops) => + loops.SelectMany(loop => loop).Select(corner => Math.Abs(corner.D) > Tolerance ? Math.Sign(corner.D) : 0) + .FirstOrDefault(sign => sign != 0); + + // The loops as seen from the side they stand on, to tell what lies inside what. + private static List<(double U, double V)[]> OneSide(List<(double D, double V)[]> loops, int side) => + [.. loops.Select(loop => loop.Select(corner => (U: corner.D * side, corner.V)).ToArray())]; + + private static double Area((double D, double V)[] loop) => + Enumerable.Range(0, loop.Length).Sum(i => loop[i].D * loop[(i + 1) % loop.Length].V - loop[(i + 1) % loop.Length].D * loop[i].V) / 2; + + /// Whether the loops are simple closed outlines of lines of some length that stand on one side of the axis, meet + /// neither themselves nor each other, keep the direction of every line they had at the stored positions and keep what + /// lies inside what. + internal static bool Holds(FamilyRevolution revolution, IReadOnlyList positions, IReadOnlyList stored) + { + var loops = Profiles(revolution, positions); + var saved = Profiles(revolution, stored); + // Every comparison is false for a position that is not a number. + if (!loops.Concat(saved).SelectMany(loop => loop).All(corner => double.IsFinite(corner.D) && double.IsFinite(corner.V))) + return false; + // Loops on both sides of the axis would turn into solids that overlap. + int side = SideOfAxis(loops); + if (side == 0 || loops.Any(loop => loop.Any(corner => corner.D * side < -Tolerance))) return false; + + var segments = new List<(int Loop, int Index, (double D, double V) A, (double D, double V) B)>(); + for (int l = 0; l < loops.Count; l++) + { + int count = loops[l].Length; + if (count < 3 || !(Math.Abs(Area(loops[l])) > Tolerance)) return false; + for (int i = 0; i < count; i++) + { + var (a, b) = (loops[l][i], loops[l][(i + 1) % count]); + var (savedA, savedB) = (saved[l][i], saved[l][(i + 1) % count]); + double dd = b.D - a.D, dv = b.V - a.V; + if (!(Math.Sqrt(dd * dd + dv * dv) > Tolerance && dd * (savedB.D - savedA.D) + dv * (savedB.V - savedA.V) > 0)) + return false; + segments.Add((l, i, a, b)); + } + } + + for (int first = 0; first < segments.Count; first++) + for (int second = first + 1; second < segments.Count; second++) + { + var (s, t) = (segments[first], segments[second]); + bool follows = s.Loop == t.Loop && (s.Index + 1) % loops[s.Loop].Length == t.Index; + bool precedes = s.Loop == t.Loop && (t.Index + 1) % loops[s.Loop].Length == s.Index; + if (follows || precedes) + { + // They share a corner; neither may run back along the other. + var (before, after) = follows ? (s, t) : (t, s); + if (FamilyContourChecks.Distance(before.A, after.A, after.B) <= Tolerance + || FamilyContourChecks.Distance(after.B, before.A, before.B) <= Tolerance) return false; + } + else if (Meet(s.A, s.B, t.A, t.B)) return false; + } + + return FamilyContourChecks.Nesting(OneSide(loops, side)).Cast() + .SequenceEqual(FamilyContourChecks.Nesting(OneSide(saved, side)).Cast()); + } + + /// Whether the segments a-b and c-d have a point in common. + private static bool Meet((double D, double V) a, (double D, double V) b, (double D, double V) c, (double D, double V) d) + { + static double Cross((double D, double V) o, (double D, double V) p, (double D, double V) q) => + (p.D - o.D) * (q.V - o.V) - (p.V - o.V) * (q.D - o.D); + double d1 = Cross(c, d, a), d2 = Cross(c, d, b), d3 = Cross(a, b, c), d4 = Cross(a, b, d); + double scale = Math.Max(1, Math.Max(Math.Abs(b.D - a.D) + Math.Abs(b.V - a.V), Math.Abs(d.D - c.D) + Math.Abs(d.V - c.V))); + double eps = Tolerance * scale; + bool Opposite(double x, double y) => x > eps && y < -eps || x < -eps && y > eps; + if (Opposite(d1, d2) && Opposite(d3, d4)) return true; + // A line that touches the other, or lies along it. + bool On((double D, double V) s, (double D, double V) e, (double D, double V) p) => + Math.Abs(Cross(s, e, p)) <= eps && p.D >= Math.Min(s.D, e.D) - Tolerance && p.D <= Math.Max(s.D, e.D) + Tolerance + && p.V >= Math.Min(s.V, e.V) - Tolerance && p.V <= Math.Max(s.V, e.V) + Tolerance; + return On(c, d, a) || On(c, d, b) || On(a, b, c) || On(a, b, d); + } + + /// A line of a loop that is not on the axis: the face key, its ends (distance from the axis, signed; position along + /// it) and the way out of the solid in the plane of the profile (along the distance, along the axis). + private readonly record struct Side(FamilyFaceKey Key, double D1, double V1, double D2, double V2, double OutD, double OutV); + + private static List Sides(FamilyRevolution revolution, IReadOnlyList positions) + { + var profiles = Profiles(revolution, positions); + var nesting = FamilyContourChecks.Nesting(OneSide(profiles, SideOfAxis(profiles))); + var sides = new List(); + for (int l = 0; l < profiles.Count; l++) + { + var loop = profiles[l]; + // The loop runs counter-clockwise in (distance, position) when its area is positive; the solid is then on the left of + // each line, and what faces out is on its right. Inside an odd number of loops it is a hole: the solid is outside it. + int depth = Enumerable.Range(0, profiles.Count).Count(other => nesting[other, l]); + double turn = Math.Sign(Area(loop)) * (depth % 2 == 0 ? 1 : -1); + for (int i = 0; i < loop.Length; i++) + { + var ((d1, v1), (d2, v2)) = (loop[i], loop[(i + 1) % loop.Length]); + if (Math.Abs(d1) <= Tolerance && Math.Abs(d2) <= Tolerance) continue; + double dd = d2 - d1, dv = v2 - v1, length = Math.Sqrt(dd * dd + dv * dv); + sides.Add(new(new(FamilyFaceKind.Side, l, i), d1, v1, d2, v2, turn * dv / length, -turn * dd / length)); + } + } + return sides; + } + + /// A face for each line of each loop that is not on the axis (the cylinder, ring, disc or cone is one face per + /// facet, a ring or a disc one face), in the order of the loops and their lines. Normals point out of the solid; + /// gives the material of each face. + public static List Faces(FamilyRevolution revolution, IReadOnlyList positions, Func material) + { + int axis = revolution.Axis, normal = revolution.Normal, across = 3 - axis - normal; + double centre = positions[revolution.AxisPosition], plane = positions[revolution.PlanePosition]; + double[] Point(double d, double v, int facet) + { + double angle = 2 * Math.PI * facet / Facets; + var point = new double[3]; + point[axis] = v; + point[across] = centre + d * Math.Cos(angle); + point[normal] = plane + d * Math.Sin(angle); + return point; + } + + var faces = new List(); + foreach (var (key, d1, v1, d2, v2, outD, outV) in Sides(revolution, positions)) + { + if (Math.Abs(v2 - v1) <= Tolerance) + faces.Add(Flat(Math.Abs(d1), Math.Abs(d2), v1, Math.Sign(d1 + d2) * 1.0, outV, key)); + else + for (int facet = 0; facet < Facets; facet++) + { + List ring = [Point(d1, v1, facet), Point(d1, v1, facet + 1), Point(d2, v2, facet + 1), Point(d2, v2, facet)]; + // The end on the axis is one point. + if (Math.Abs(d1) <= Tolerance) ring.RemoveAt(1); + else if (Math.Abs(d2) <= Tolerance) ring.RemoveAt(3); + faces.Add(Face(ring, outD, outV, facet, key)); + } + } + return faces; + + // A facet of a surface, wound to face along the outward direction of the profile turned to the middle of the facet. + GeoFace Face(List ring, double outD, double outV, int facet, FamilyFaceKey key) + { + double middle = 2 * Math.PI * (facet + 0.5) / Facets; + var outward = new double[3]; + outward[axis] = outV; + outward[across] = outD * Math.Cos(middle); + outward[normal] = outD * Math.Sin(middle); + return Wound(ring, outward, key); + } + + // The disc or the ring at a position along the axis: its outer circle and, for a ring, the circle of the hole. + GeoFace Flat(double outer, double inner, double v, double side, double outV, FamilyFaceKey key) + { + if (outer < inner) (outer, inner) = (inner, outer); + side = side < 0 ? -1 : 1; + var up = new double[3]; + up[axis] = Math.Sign(outV); + List Circle(double radius) => [.. Enumerable.Range(0, Facets).Select(facet => Point(side * radius, v, facet))]; + var face = Wound(Circle(outer), up, key); + if (inner > Tolerance) + { + var hole = Circle(inner); + // A hole runs the other way round from the outline. + if (Winding(face.OuterVertices!, up) * Winding(hole, up) > 0) hole.Reverse(); + face.InnerVertices = [hole]; + } + return face; + } + + GeoFace Wound(List ring, double[] outward, FamilyFaceKey key) + { + if (Winding(ring, outward) < 0) ring.Reverse(); + var (x, y, z) = Newell(ring); + double length = Math.Sqrt(x * x + y * y + z * z); + double[] facing = length > 0 && Winding(ring, outward) != 0 ? [x / length, y / length, z / length] : outward; + return new((double[])ring[0].Clone(), facing) { OuterVertices = ring, RenderStyleId = material(key) }; + } + } + + /// The stored face that stands for each surface of the revolution at the stored positions, or null when they are + /// not the surfaces the file stores. The file cuts its round surfaces as it likes, so faces are not compared one for one: + /// every corner of every stored face lies on one surface of the revolution (the line of a loop, turned), every surface has + /// stored faces that reach both its circles, the faces of a surface share one material ( when a + /// parameter gives it). The way a stored face faces is not compared: the file stores the caps of a circle facing inward and + /// one half of the side of a cone facing into the solid, so the way the solid goes is held by the loops (). + internal static Dictionary? Match(FamilyRevolution revolution, IReadOnlyList positions, + IReadOnlyList stored, int? material = null) + { + int axis = revolution.Axis, normal = revolution.Normal, across = 3 - axis - normal; + double centre = positions[revolution.AxisPosition], plane = positions[revolution.PlanePosition]; + var surfaces = Sides(revolution, positions) + .Select(side => (Side: side, Start: (R: Math.Abs(side.D1), V: side.V1), End: (R: Math.Abs(side.D2), V: side.V2))).ToList(); + + var reached = surfaces.ToDictionary(surface => surface.Side.Key, _ => new List<(double R, double V)>()); + var matched = new Dictionary(); + foreach (var face in stored) + { + var corners = (face.OuterVertices ?? []).Concat(face.InnerVertices?.SelectMany(hole => hole) ?? []).ToList(); + if (corners.Count == 0 || corners.Any(corner => corner.Length != 3)) return null; + var polar = corners.Select(corner => (R: Math.Sqrt(Math.Pow(corner[across] - centre, 2) + Math.Pow(corner[normal] - plane, 2)), + V: corner[axis])).ToList(); + // A face on a cylinder or a cone reaches along the axis; one at a single position along it is flat, on a disc or a ring, + // though its corners lie on the circle where a cylinder ends. A face of two surfaces is no face of either. + double reach = polar.Max(point => point.V) - polar.Min(point => point.V); + var onSurface = surfaces.Where(surface => polar.All(point => Near(point, surface.Start, surface.End)) + && (Math.Abs(surface.End.V - surface.Start.V) <= Tolerance || reach > Tolerance)).ToList(); + if (onSurface.Count != 1) return null; + var (side, start, end) = onSurface[0]; + var key = side.Key; + // No material is stored as nothing or as an id that is not one. + int own = Math.Max(face.RenderStyleId ?? 0, 0); + if (material is int expected && own != Math.Max(expected, 0)) return null; + if (!matched.TryAdd(key, face) && Math.Max(matched[key].RenderStyleId ?? 0, 0) != own) return null; + reached[key].AddRange(polar); + } + foreach (var (side, start, end) in surfaces) + { + // An end on the axis is no corner of any face. + bool Reaches((double R, double V) tip) => tip.R <= Tolerance + || reached[side.Key].Any(point => Math.Abs(point.R - tip.R) <= Tolerance && Math.Abs(point.V - tip.V) <= Tolerance); + if (!matched.ContainsKey(side.Key) || !Reaches(start) || !Reaches(end)) return null; + } + return matched; + } + + // The point (distance from the axis, position along it) is on the segment from a to b, to the tolerance. + private static bool Near((double R, double V) point, (double R, double V) a, (double R, double V) b) + { + double dr = b.R - a.R, dv = b.V - a.V, length = dr * dr + dv * dv; + double t = length > 0 ? Math.Clamp(((point.R - a.R) * dr + (point.V - a.V) * dv) / length, 0, 1) : 0; + return Math.Sqrt(Math.Pow(point.R - a.R - t * dr, 2) + Math.Pow(point.V - a.V - t * dv, 2)) <= Tolerance; + } + + // The sign of the turn of a ring seen from the end of it faces: positive when counter-clockwise. + private static double Winding(List ring, double[] outward) + { + var (x, y, z) = Newell(ring); + return x * outward[0] + y * outward[1] + z * outward[2]; + } + + private static (double X, double Y, double Z) Newell(List ring) + { + double x = 0, y = 0, z = 0; + for (int i = 0; i < ring.Count; i++) + { + var (a, b) = (ring[i], ring[(i + 1) % ring.Count]); + x += (a[1] - b[1]) * (a[2] + b[2]); + y += (a[2] - b[2]) * (a[0] + b[0]); + z += (a[0] - b[0]) * (a[1] + b[1]); + } + return (x, y, z); + } +} diff --git a/src/RvtIO/Families/FamilyRules.cs b/src/RvtIO/Families/FamilyRules.cs index b5560ba9..a6095beb 100644 --- a/src/RvtIO/Families/FamilyRules.cs +++ b/src/RvtIO/Families/FamilyRules.cs @@ -35,6 +35,11 @@ internal static bool PlacesOnlyForms(int elementId, GeometryData? body, Func isAlignment ? flags is 10 or 14 or 26 or 30 : flags is 0 or 8 or 12 or 24 or 28 or 136 or 140; + /// How many radii the number of a radial dimension measures, by the kind of its dimension style + /// (DimensionStyle.m_dimensionStyleType): 1 for a radius (kinds 0 and 2), 2 for a diameter (kind 9), null for another + /// kind. The kinds were read from the files, and the stored state of each family confirms the choice. + internal static int? RadialStyleFactor(long styleType) => styleType switch { 0 or 2 => 1, 9 => 2, _ => null }; + /// The bit of Dimension.m_flags of an equality dimension, whose segments keep equal lengths. internal const long EqualityDimensionFlag = 0x80; diff --git a/src/RvtIO/Families/FamilySavedState.cs b/src/RvtIO/Families/FamilySavedState.cs index 85941870..63dd007f 100644 --- a/src/RvtIO/Families/FamilySavedState.cs +++ b/src/RvtIO/Families/FamilySavedState.cs @@ -48,11 +48,27 @@ internal static (Dictionary<(int ElementId, FamilyFaceKey Face), GeoFace>? Faces { int found = left.FindIndex(candidate => Same(face, candidate)); if (found < 0) return Mismatch($"element {extrusion.ElementId}"); - matched.Add((extrusion.ElementId, key), left[found]); + // The flat faces of one curved side share a key: each is compared for its material above, and the first gives + // the style the faces computed for the key take. + matched.TryAdd((extrusion.ElementId, key), left[found]); left.RemoveAt(found); } if (left.Count > 0) return Mismatch($"element {extrusion.ElementId}"); } + foreach (var revolution in model.Revolutions) + { + // A parameter that gives the material gives it to every face; its value in the saved type must be a value it has. + int? finish = null; + if (revolution.MaterialParameterId is long parameter) + { + if (!values.TryGetValue(parameter, out double chosen)) return Mismatch($"element {revolution.ElementId}"); + finish = (int)chosen; + } + if (!stored.TryGetValue(revolution.ElementId, out var faces) + || FamilyRevolutionBuilder.Match(revolution, positions, faces, finish) is not { } surfaces) + return Mismatch($"element {revolution.ElementId}"); + foreach (var (key, face) in surfaces) matched.Add((revolution.ElementId, key), face); + } return (matched, null); } diff --git a/src/RvtIO/Families/FamilySolver.cs b/src/RvtIO/Families/FamilySolver.cs index 78b76765..ce11440b 100644 --- a/src/RvtIO/Families/FamilySolver.cs +++ b/src/RvtIO/Families/FamilySolver.cs @@ -57,7 +57,9 @@ void Hold(Row row) bool Determined(int variable) => model.Variables[variable].Anchored || pivots.TryGetValue(variable, out var row) && row.Coefficients.Count == 1; var undetermined = model.Extrusions.Where(extrusion => !UsedBy(extrusion).All(Determined)) - .Select(extrusion => (long)extrusion.ElementId).ToList(); + .Select(extrusion => (long)extrusion.ElementId) + .Concat(model.Revolutions.Where(revolution => !UsedBy(revolution).All(Determined)).Select(revolution => (long)revolution.ElementId)) + .ToList(); if (undetermined.Count > 0) return Refused("underdetermined", undetermined); var positions = model.Variables.Select(variable => variable.Stored).ToArray(); @@ -80,10 +82,29 @@ private static IEnumerable UsedBy(FamilyExtrusion extrusion) if (extrusion.Axis != 1) yield return vertex.Y; if (extrusion.Axis != 2) yield return vertex.Z; } + foreach (var arc in (extrusion.Arcs ?? []).SelectMany(loop => loop).OfType()) + { + yield return arc.CenterU; + yield return arc.CenterV; + yield return arc.Radius; + } yield return extrusion.Start; yield return extrusion.End; } + // The corners of a revolution are in its plane, so their coordinates along its normal are the plane's. + private static IEnumerable UsedBy(FamilyRevolution revolution) + { + foreach (var vertex in revolution.Loops.SelectMany(loop => loop)) + { + if (revolution.Normal != 0) yield return vertex.X; + if (revolution.Normal != 1) yield return vertex.Y; + if (revolution.Normal != 2) yield return vertex.Z; + } + yield return revolution.PlanePosition; + yield return revolution.AxisPosition; + } + private static FamilySolution Refused(string code, IEnumerable ids) => new(null, new(code, string.Join(", ", ids.Distinct().Order().Select(id => id.ToString(CultureInfo.InvariantCulture))))); diff --git a/src/RvtIO/Internal/ParsingState.cs b/src/RvtIO/Internal/ParsingState.cs index d2fb1636..96106a05 100644 --- a/src/RvtIO/Internal/ParsingState.cs +++ b/src/RvtIO/Internal/ParsingState.cs @@ -23,6 +23,9 @@ internal class ParsingState : JsonReadFacts /// Set with : the equal vertices of a decoded block are one array. internal bool ShareEqualVertices { get; init; } + /// Set with : the circular edges of the faces keep the points the file stores. + internal bool FineCircularEdges { get; init; } + /// Set with : a decoded block remembers where its bytes lie until /// is chosen. internal bool KeepBlockSources { get; init; } diff --git a/src/RvtIO/Meshes/ElementMeshes.cs b/src/RvtIO/Meshes/ElementMeshes.cs index c5956e9b..084d0ea8 100644 --- a/src/RvtIO/Meshes/ElementMeshes.cs +++ b/src/RvtIO/Meshes/ElementMeshes.cs @@ -222,33 +222,46 @@ public static RvtFamilyTypeMeshes ComputeFamilyType(RvtDocument document, int ty var model = prepared.Model!; var values = ValuesOf(types.Types[typeIndex]); RvtFamilyTypeMeshes Refused(string code, long id) => new(null, new(code, id.ToString(CultureInfo.InvariantCulture))); - foreach (var extrusion in model.Extrusions) - if (extrusion.VisibilityParameterId is long visibility && !values.ContainsKey(visibility)) - return Refused("underdetermined", visibility); - var shown = model with { Extrusions = [.. model.Extrusions.Where(extrusion => IsShown(extrusion, values))] }; - foreach (var extrusion in shown.Extrusions) - if (extrusion.MaterialParameterId is long finish && !values.ContainsKey(finish)) - return Refused("underdetermined", finish); + foreach (long visibility in model.Extrusions.Select(extrusion => extrusion.VisibilityParameterId) + .Concat(model.Revolutions.Select(revolution => revolution.VisibilityParameterId)).OfType()) + if (!values.ContainsKey(visibility)) return Refused("underdetermined", visibility); + var shown = model with + { + Extrusions = [.. model.Extrusions.Where(extrusion => IsShown(extrusion.VisibilityParameterId, values))], + Revolutions = [.. model.Revolutions.Where(revolution => IsShown(revolution.VisibilityParameterId, values))], + }; + foreach (long finish in shown.Extrusions.Select(extrusion => extrusion.MaterialParameterId) + .Concat(shown.Revolutions.Select(revolution => revolution.MaterialParameterId)).OfType()) + if (!values.ContainsKey(finish)) return Refused("underdetermined", finish); var solution = FamilySolver.Solve(shown, values); if (solution.Positions is not { } positions) return new(null, solution.Refusal); if (FamilyContourChecks.Check(shown, positions, values) is { } degenerate) return new(null, degenerate); var material = MaterialIn(values); var built = shown.Extrusions.ToDictionary(extrusion => extrusion.ElementId); + var turned = shown.Revolutions.ToDictionary(revolution => revolution.ElementId); var elements = new List(); foreach (int id in prepared.Elements) { - if (!built.TryGetValue(id, out var extrusion)) + if (!built.TryGetValue(id, out var extrusion) && !turned.ContainsKey(id)) { elements.Add(new ElementMesh { ElementId = id, Coverage = MeshCoverage.Complete }); continue; } var keys = new List(); - var faces = FamilyExtrusionBuilder.Faces(extrusion, positions, key => - { - keys.Add(key); - return material(extrusion, key); - }); + var faces = extrusion != null + ? FamilyExtrusionBuilder.Faces(extrusion, positions, key => + { + keys.Add(key); + return material(extrusion, key); + }) + : FamilyRevolutionBuilder.Faces(turned[id], positions, key => + { + keys.Add(key); + return turned[id].MaterialParameterId is long finish ? values.TryGetValue(finish, out double chosen) ? (int)chosen : 0 + // No material is stored as nothing or as an id that is not one. + : prepared.Faces!.TryGetValue((id, key), out var own) ? Math.Max(own.RenderStyleId ?? 0, 0) : 0; + }); foreach (var (face, key) in faces.Zip(keys)) { if (!prepared.Faces!.TryGetValue((id, key), out var stored)) return Refused("degenerate-geometry", id); @@ -276,8 +289,10 @@ private static FamilyPreparation PrepareFamily(RvtDocument document, FamilyData // The forms of the model are those the saved type lists, and its values show and hide them as the file does. var saved = ValuesOf(types.Types[types.CurrentIndex]); - if (!listed.Select(item => item.Element.Id).Order().SequenceEqual(model.Extrusions.Select(e => e.ElementId).Order()) - || model.Extrusions.Any(extrusion => IsShown(extrusion, saved) == hidden.Contains(extrusion.ElementId))) + if (!listed.Select(item => item.Element.Id).Order() + .SequenceEqual(model.Extrusions.Select(e => e.ElementId).Concat(model.Revolutions.Select(r => r.ElementId)).Order()) + || model.Extrusions.Any(extrusion => IsShown(extrusion.VisibilityParameterId, saved) == hidden.Contains(extrusion.ElementId)) + || model.Revolutions.Any(revolution => IsShown(revolution.VisibilityParameterId, saved) == hidden.Contains(revolution.ElementId))) return No("saved-state-mismatch", "the forms of the saved type"); var storedFaces = new Dictionary>(); @@ -307,8 +322,8 @@ private static Dictionary ValuesOf(RvtFamilyType type) return values; } - private static bool IsShown(FamilyExtrusion extrusion, IReadOnlyDictionary values) => - extrusion.VisibilityParameterId is not long parameter || values.TryGetValue(parameter, out double value) && value != 0; + private static bool IsShown(long? visibilityParameterId, IReadOnlyDictionary values) => + visibilityParameterId is not long parameter || values.TryGetValue(parameter, out double value) && value != 0; /// The material of each face in a type: that of the parameter that gives it, else the stored one. private static Func MaterialIn(IReadOnlyDictionary values) => diff --git a/src/RvtIO/Parsing/BlockParser.cs b/src/RvtIO/Parsing/BlockParser.cs index f93d10b7..268da738 100644 --- a/src/RvtIO/Parsing/BlockParser.cs +++ b/src/RvtIO/Parsing/BlockParser.cs @@ -46,7 +46,7 @@ internal static void ApplyPendingGReps(ParsingState state, List pen foreach (var job in pending) { var geometry = GRepParserV2.Parse(job.Chunk, job.Start, job.Size, shareEqualVertices: state.ShareEqualVertices, - keepSource: state.KeepBlockSources && !job.IsFamilyCut); + keepSource: state.KeepBlockSources && !job.IsFamilyCut, fineCircularEdges: state.FineCircularEdges); if (geometry != null && !job.IsFamilyCut) ElementBuilder.LeaveBlockAtDecode(state, job.Eid, geometry, job.Chunk, job.Start, job.Size); if (geometry == null) unreadable?.Add(new(job.Chunk, job.Start, job.Size)); ApplyPendingGRep(state, job, geometry); @@ -64,7 +64,7 @@ internal static void ApplyPendingGReps(ParsingState state, List pen if (unreadable?.Contains(new GRepRange(job.Chunk, job.Start, job.Size)) != true) { var geometry = GRepParserV2.Parse(job.Chunk, job.Start, job.Size, shareEqualVertices: state.ShareEqualVertices, - keepSource: state.KeepBlockSources && !job.IsFamilyCut); + keepSource: state.KeepBlockSources && !job.IsFamilyCut, fineCircularEdges: state.FineCircularEdges); if (geometry != null && !job.IsFamilyCut) ElementBuilder.LeaveBlockAtDecode(state, job.Eid, geometry, job.Chunk, job.Start, job.Size); decoded[index] = geometry; } diff --git a/src/RvtIO/Parsing/ElementBuilder.UndrawnFaces.cs b/src/RvtIO/Parsing/ElementBuilder.UndrawnFaces.cs index 5535adf9..e1bd6168 100644 --- a/src/RvtIO/Parsing/ElementBuilder.UndrawnFaces.cs +++ b/src/RvtIO/Parsing/ElementBuilder.UndrawnFaces.cs @@ -237,10 +237,10 @@ private static bool LeaveBlockToDemand(ParsingState state, ParsingState.UndrawnF is not { ExactMappedInstances: null, Instances: null, Vertices: null, Edges: null, Faces.Count: > 0 } geometry) return false; geometry.LeaveGeometryToDemand(FactsOf(geometry, geometry.Faces, measureShell: false), - GeometryOf(bytes, size, state.ShareEqualVertices, state.SeparateFacesWithDistinctOpenings, chosen.Rebuilt)); + GeometryOf(bytes, size, state.ShareEqualVertices, state.FineCircularEdges, state.SeparateFacesWithDistinctOpenings, chosen.Rebuilt)); chosen.Prebuilt[owner] = (geometry, block); } - block.LeaveFacesToDemand(summary, BlockOf(bytes, size, state.ShareEqualVertices, chosen.BlocksDecodedAgain)); + block.LeaveFacesToDemand(summary, BlockOf(bytes, size, state.ShareEqualVertices, state.FineCircularEdges, chosen.BlocksDecodedAgain)); Interlocked.Increment(ref chosen.BlocksLeft.Value); return true; } @@ -276,10 +276,11 @@ private static bool NeedsTheFacesOfItsBlock(uint owner, ParsingState state) } // A method of its own: the delegate holds its arguments and nothing else, so not the state of the read. - private static Func BlockOf(byte[] bytes, uint size, bool shareEqualVertices, System.Runtime.CompilerServices.StrongBox decodedAgain) => () => + private static Func BlockOf(byte[] bytes, uint size, bool shareEqualVertices, bool fineCircularEdges, + System.Runtime.CompilerServices.StrongBox decodedAgain) => () => { Interlocked.Increment(ref decodedAgain.Value); - return GRepParserV2.Parse(bytes, 0, size, shareEqualVertices: shareEqualVertices); + return GRepParserV2.Parse(bytes, 0, size, shareEqualVertices: shareEqualVertices, fineCircularEdges: fineCircularEdges); }; /// What a reader on the way to a scene asks of faces that are not there (see GeometryData.FaceFacts). @@ -318,17 +319,18 @@ private static void LeaveUndrawnFacesToDemand(Element elem, uint elemId, Parsing return; // The shell of a block of hundreds of thousands of faces is long to measure and nothing on the way to a scene asks for it. geometry.LeaveGeometryToDemand(FactsOf(geometry, faces, measureShell: false), - GeometryOf(block.Bytes, block.Size, state.ShareEqualVertices, state.SeparateFacesWithDistinctOpenings, undrawn.Rebuilt)); + GeometryOf(block.Bytes, block.Size, state.ShareEqualVertices, state.FineCircularEdges, state.SeparateFacesWithDistinctOpenings, undrawn.Rebuilt)); Interlocked.Increment(ref undrawn.Left.Value); Interlocked.Add(ref undrawn.LeftFaces.Value, faces.Count); } // A method of its own: the delegate holds its arguments and nothing else, so not the state of the read. - private static Func GeometryOf(byte[] bytes, uint size, bool shareEqualVertices, bool separateFacesWithDistinctOpenings, + private static Func GeometryOf(byte[] bytes, uint size, bool shareEqualVertices, bool fineCircularEdges, + bool separateFacesWithDistinctOpenings, System.Runtime.CompilerServices.StrongBox rebuilt) => () => { Interlocked.Increment(ref rebuilt.Value); - return GRepParserV2.Parse(bytes, 0, size, shareEqualVertices: shareEqualVertices) is { } block + return GRepParserV2.Parse(bytes, 0, size, shareEqualVertices: shareEqualVertices, fineCircularEdges: fineCircularEdges) is { } block ? BuildGeometryData(block, separateFacesWithDistinctOpenings) : null; }; diff --git a/src/RvtIO/Parsing/GRepParserV2.cs b/src/RvtIO/Parsing/GRepParserV2.cs index acaf69e0..31ecf38f 100644 --- a/src/RvtIO/Parsing/GRepParserV2.cs +++ b/src/RvtIO/Parsing/GRepParserV2.cs @@ -19,6 +19,9 @@ internal static partial class GRepParserV2 /// private const int CoarseTessellationFaceBudget = 100000; + /// The block being decoded keeps the stored points of its circular edges (see ). + [ThreadStatic] private static bool t_fineCircularEdges; + [ThreadStatic] private static bool t_coarseTessellation; /// Faces of the geometry being built that were left out because their trim triangulation ran out of its budget. @@ -842,12 +845,20 @@ internal enum BodyMeasure { None, VisibleVolume, RawBodies, DirectionalRawSurfac /// Use native Low edge sampling only after confirming a unique own wall root and GRep. /// Make the equal vertices of the block one array (). /// Remember on the block where its bytes lie (). + /// Keep the points the file stores on the circular edge of a cylinder and a plane, which the low detail level + /// of Revit samples more coarsely (). 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, - bool shareEqualVertices = false, bool keepSource = false) + bool shareEqualVertices = false, bool keepSource = false, bool fineCircularEdges = false) { - var block = ParseLevels(d, blockStart, dataSize, nativeWallBody, requireCompleteWalk, measureSourceNodes, measureLighting, - measureFills, bodyMeasure); + GRepData? block; + t_fineCircularEdges = fineCircularEdges; + try + { + block = ParseLevels(d, blockStart, dataSize, nativeWallBody, requireCompleteWalk, measureSourceNodes, measureLighting, + measureFills, bodyMeasure); + } + finally { t_fineCircularEdges = false; } if (shareEqualVertices && block != null) ShareEqualVertices(block); if (keepSource && block != null) block.Source = (d, blockStart, dataSize); return block; @@ -2808,14 +2819,14 @@ void SampleCircularEdge(EdgeRec edge, SurfaceRec firstSurface, SurfaceRec second if (sharedCylinderEdges.Contains(edge.Handle) && c.DirectSurfaceByFace.TryGetValue(edge.FaceA, out var firstSurface) && c.DirectSurfaceByFace.TryGetValue(edge.FaceB, out var secondSurface)) - SampleCircularEdge(edge, firstSurface, secondSurface, true); + SampleCircularEdge(edge, firstSurface, secondSurface, !t_fineCircularEdges); // Every other circular edge between a vertical-axis cylinder and a plane square to it is // sampled the same way (the renderer samples each edge of a Brep with the arc sampler); the // file stores its own, finer points. foreach (var edge in c.Edges) if (!arcEdges.Contains(edge.Handle) && handleToSurf.TryGetValue(edge.FaceA, out var anySurfaceA) && handleToSurf.TryGetValue(edge.FaceB, out var anySurfaceB)) - SampleCircularEdge(edge, anySurfaceA, anySurfaceB, !c.NativeWallBody); + SampleCircularEdge(edge, anySurfaceA, anySurfaceB, !c.NativeWallBody && !t_fineCircularEdges); foreach (var edge in c.Edges) if (sharedCylinderEdges.Contains(edge.Handle) && (edge.Flags & 6) == 6 && TryGetEdgePoints(c, edge) is { } shared && shared.Count == edge.Interior.Count + 2) @@ -4646,7 +4657,23 @@ internal static List ThinSamples(List samples, double[] knots, i return kept.ToList(); } - private static IEnumerable> TessellateCylinder(RingGraph ringGraph, SurfaceRec s, + /// + /// The sample lists, thinned so that their grid has no more cells than a face may have: every trim vertex is a grid line + /// in both directions, so a surface of a huge radius or a densely trimmed one would otherwise reach tens of gigabytes. A + /// list of two samples keeps its cell, and the other takes what the limit leaves it. + /// + private static (List U, List V) LimitGridCells(List uSamples, List vSamples) + { + int maxCells = t_coarseTessellation ? 1024 : 20000; + long cells = (long)(uSamples.Count - 1) * (vSamples.Count - 1); + if (cells <= maxCells) return (uSamples, vSamples); + double scale = Math.Sqrt((double)maxCells / cells); + int uCells = (int)Math.Min(maxCells, Math.Max(1, (uSamples.Count - 1) * scale)); + int vCells = (int)Math.Min(maxCells / uCells, Math.Max(1, (vSamples.Count - 1) * scale)); + return (ThinSamples(uSamples, [], uCells + 1), ThinSamples(vSamples, [], vCells + 1)); + } + + internal static IEnumerable> TessellateCylinder(RingGraph ringGraph, SurfaceRec s, List<(double U1, double V1, double U2, double V2)> edges, List<(double U1, double V1, double U2, double V2)> samplingEdges, bool hasAuthoredTrim, IReadOnlyList<(double[] First, double[] Second)>? worldBoundary = null, bool emitPolygons = true) @@ -4692,6 +4719,7 @@ double[] P(double u, double v) foreach (var polygon in trimmed) yield return polygon; yield break; } + (uSamples, vSamples) = LimitGridCells(uSamples, vSamples); for (int i = 0; i + 1 < uSamples.Count; i++) { double ua = uSamples[i], ub = uSamples[i + 1]; @@ -4792,6 +4820,7 @@ double[] Point(double u, double v) foreach (var polygon in trimmed) yield return polygon; yield break; } + (uSamples, vSamples) = LimitGridCells(uSamples, vSamples); for (int i = 0; i + 1 < uSamples.Count; i++) { double ua = uSamples[i], ub = uSamples[i + 1]; @@ -4811,7 +4840,7 @@ double[] Point(double u, double v) /// gap that no trim edge off the axis spans. A face closed through the poles has only edges of no length there, so /// without this the angles between its meridians would be one flat strip. /// - private static List RefineUncrossedAngles(List samples, + internal static List RefineUncrossedAngles(List samples, List<(double U1, double V1, double U2, double V2)> edges, ArcRec profile, double radius) { if (samples.Count < 2) return samples; @@ -4825,6 +4854,7 @@ private static List RefineUncrossedAngles(List samples, if (turning.Any(edge => Math.Min(edge.U1, edge.U2) <= low + eps && Math.Max(edge.U1, edge.U2) >= high - eps)) result.Add(high); else result.AddRange(RefineAngularSamples([low, high], radius).Skip(1)); + if (result.Count > MaxRefinedSamples) return samples; } return result; } @@ -5665,17 +5695,9 @@ int Depth(int index) Func? evaluate, bool refineV) { if (edges.Count < 3 || uSamples.Count < 2 || vSamples.Count < 2) return null; - // Every trim vertex is a grid line in both directions, so the cell count is the product of - // the two line counts: a densely trimmed cylinder of an equipment model reaches hundreds of - // thousands of cells and tens of gigabytes for one section. - int MaxGridCells = t_coarseTessellation ? 1024 : 20000; - long cells = (long)(uSamples.Count - 1) * (vSamples.Count - 1); - if (cells > MaxGridCells) - { - double scale = Math.Sqrt((double)MaxGridCells / cells); - uSamples = ThinSamples(uSamples, [], Math.Max(2, (int)((uSamples.Count - 1) * scale) + 1)); - vSamples = ThinSamples(vSamples, [], Math.Max(2, (int)((vSamples.Count - 1) * scale) + 1)); - } + // A densely trimmed cylinder of an equipment model reaches hundreds of thousands of cells and tens of gigabytes + // for one section. + (uSamples, vSamples) = LimitGridCells(uSamples, vSamples); var rings = ringGraph.OrderUvRings(edges); if (rings.Count == 0 || rings.Any(ring => ring.Count < 3)) return null; @@ -5906,6 +5928,9 @@ internal static double MinPropagatingNaN(double[] points, int count, int compone return value; } + /// The most samples the angular refinement of one face gives; a face that asks for more keeps its source samples. + internal const int MaxRefinedSamples = 1 << 20; + internal static List RefineAngularSamples(List source, double radius) { if (source.Count < 2 || !IsFinite(radius) || radius <= 1e-12) return source; @@ -5916,13 +5941,20 @@ internal static List RefineAngularSamples(List source, double ra maxStep = Math.Min(maxStep, Math.PI / 2); if (!IsFinite(maxStep) || maxStep <= 1e-12) return source; - static int Segments(double a, double b, double maxStep) => - Math.Max(1, (int)Math.Ceiling(Math.Abs(b - a) / maxStep)); + // More than a face may have: an angle read from a file can be of any size, even infinite. + static int Segments(double a, double b, double maxStep) + { + double steps = Math.Abs(b - a) / maxStep; + return steps > MaxRefinedSamples ? MaxRefinedSamples + 1 : Math.Max(1, (int)Math.Ceiling(steps)); + } // The exact length of the result: the first sample and every segment of every pair. long total = 1; for (int i = 0; i + 1 < source.Count; i++) + { total += Segments(source[i], source[i + 1], maxStep); - var refined = new List((int)Math.Min(total, Array.MaxLength)) { source[0] }; + if (total > MaxRefinedSamples) return source; + } + var refined = new List((int)total) { source[0] }; for (int i = 0; i + 1 < source.Count; i++) { double a = source[i], b = source[i + 1]; diff --git a/src/RvtIO/RvtFileReader.cs b/src/RvtIO/RvtFileReader.cs index 1fd65044..6b86923b 100644 --- a/src/RvtIO/RvtFileReader.cs +++ b/src/RvtIO/RvtFileReader.cs @@ -260,6 +260,7 @@ private static void ReleaseStreams(List>? streams, List 2000 || geometry?.Faces.Count > 100000)) DiagnosticSink.WriteLine($"slow GRep eid={job.Eid} ms={clock.ElapsedMilliseconds} faces={geometry?.Faces.Count}"); return geometry; diff --git a/src/RvtIO/RvtReaderOptions.cs b/src/RvtIO/RvtReaderOptions.cs index 20ecff39..64adbcb0 100644 --- a/src/RvtIO/RvtReaderOptions.cs +++ b/src/RvtIO/RvtReaderOptions.cs @@ -101,6 +101,13 @@ public class RvtReaderOptions /// of one face in place then moves it in every face that shares it. Off by default. public bool ShareEqualVertices { get; set; } + /// The circular edge where a cylinder meets a plane square to its axis is sampled for the faces of a body the way Revit's + /// low detail level samples it: about eight points to the circle of a pipe of the size of a hand. The file stores finer points for + /// the same edge. With the option the faces take the stored points, so a circle looks round where the default shows a polygon. A + /// consumer that shows the geometry asks for it; an export that has to equal the low level leaves it off, which is the default. + /// More faces are built, and the faces of the other kinds of surface do not change. + public bool FineCircularEdges { get; set; } + /// Some elements are never drawn by a mesh extraction: a group template and its members, an element outside an exact /// element table (a record found outside it, a definition that is a geometry block alone) and, with /// , the content of the document of a loaded family. Nothing on the way to a scene reads diff --git a/tests/RvtIO.Tests/Families/AquaFixValveTests.cs b/tests/RvtIO.Tests/Families/AquaFixValveTests.cs new file mode 100644 index 00000000..8cd73bc6 --- /dev/null +++ b/tests/RvtIO.Tests/Families/AquaFixValveTests.cs @@ -0,0 +1,45 @@ +using RvtIO.Families; +using Xunit; + +namespace RvtIO.Tests.Families; + +/// The real valve of the corpus, «Задвижка чугунная клиновая_AquaFix»: a family of 14 types made of revolutions, a +/// ring extrusion, a combination of forms and four nested flanges. What of it is read from the file is pinned here. +public class AquaFixValveTests +{ + private static FamilyRecords Records() => + RvtDocument.Open(TestFiles.FindRelative("families/aquafix-valve.rfa"), new RvtReaderOptions { R22Layout = true }) + .RawData.Family!.Records!; + + // The profile of the body: ten straight lines, one of them slanted, about the vertical line the sketch turns about. + [SkippableFact] + public void TheRevolutionOfTheBodyIsReadWithItsSlantedLine() + { + var records = Records(); + + var revolution = Assert.Single(records.Revolutions!); + Assert.Equal(10164308, revolution.Id); + Assert.Equal(10164318, revolution.AxisLineId); + Assert.Equal(2 * Math.PI, revolution.EndAngle - revolution.StartAngle, 1e-9); + var loop = Assert.Single(revolution.Loops); + Assert.Equal(10, loop.Count); + Assert.Contains(loop, curve => curve.LineId == 10164338); + Assert.False(records.Lines.Single(line => line.Id == 10164338).IsRevolutionAxis); + Assert.True(records.Lines.Single(line => line.Id == 10164318).IsRevolutionAxis); + } + + // The ring of the flange: an outer circle and a hole drawn the other way round, each a closed arc of the sketch that the + // profile holds as two halves. + [SkippableFact] + public void TheRingExtrusionIsReadWithItsHoleAsTwoHalvesOfItsCircle() + { + var records = Records(); + + var ring = Assert.Single(records.Extrusions, extrusion => extrusion.Id == 10164267); + Assert.Equal(2, ring.Loops.Count); + Assert.All(ring.Loops, loop => Assert.Equal(2, loop.Count)); + var circles = ring.Loops.Select(loop => loop + .Select(key => records.Lines.Single(line => line.Id == ring.ProfileCurves[key].LineId).CircleId).Distinct().Single()).ToList(); + Assert.Equal([10164277, 10164280], circles.Select(circle => circle!.Value)); + } +} diff --git a/tests/RvtIO.Tests/Families/FamilyArcTests.cs b/tests/RvtIO.Tests/Families/FamilyArcTests.cs new file mode 100644 index 00000000..f9b11757 --- /dev/null +++ b/tests/RvtIO.Tests/Families/FamilyArcTests.cs @@ -0,0 +1,665 @@ +using RvtIO.Families; +using RvtIO.Meshes; +using RvtIO.Model; +using Xunit; + +namespace RvtIO.Tests.Families; + +public class FamilyArcTests +{ + private const long Width = 100, Height = 101, Diameter = 102, Radius = 103; + + private static FamilyModel Model(FamilyRecords records) + { + var (model, refusal) = FamilyModelBuilder.Build(records); + Assert.Null(refusal); + return model!; + } + + private static (FamilyModel Model, double[] Positions) Solve(FamilyRecords records, + params (long Parameter, double Value)[] changes) + { + var model = Model(records); + var values = new Dictionary + { [Width] = 3, [Height] = 2, [Diameter] = 2, [Radius] = 0.25 }; + foreach (var (parameter, value) in changes) values[parameter] = value; + var solution = FamilySolver.Solve(model, values); + Assert.Null(solution.Refusal); + return (model, solution.Positions!); + } + + private static void AssertRefused(FamilyRecords records, string code, string detail) + { + var (model, refusal) = FamilyModelBuilder.Build(records); + + Assert.Null(model); + Assert.Equal(code, refusal!.Code); + Assert.Contains(detail, refusal.Detail); + } + + private static (double U, double V) Corner(FamilyModel model, double[] positions, int loop, int i) + { + var vertex = model.Extrusions[0].Loops[loop][i]; + return (Math.Round(positions[vertex.X], 9), Math.Round(positions[vertex.Y], 9)); + } + + [Fact] + public void ACircleOfTwoHalfArcsHasItsStoredShape() + { + var (model, positions) = Solve(SyntheticArcs.Disc()); + + var extrusion = Assert.Single(model.Extrusions); + Assert.Equal(2, extrusion.Loops[0].Count); + Assert.Equal((1, 0), Corner(model, positions, 0, 0)); + Assert.Equal((-1, 0), Corner(model, positions, 0, 1)); + var arcs = extrusion.Arcs![0].Select(arc => arc!.Value).ToArray(); + Assert.All(arcs, arc => + { + Assert.Equal(1, positions[arc.Radius], 1e-12); + Assert.Equal((0, 0), (Math.Round(positions[arc.CenterU], 9), Math.Round(positions[arc.CenterV], 9))); + Assert.Equal((1, 2), (arc.Way, arc.Quarters)); + }); + Assert.Equal([0, 2], arcs.Select(arc => arc.StartQuarter)); + } + + // A circle that is one closed arc of the sketch: the profile has its two halves, and what the sketch holds of the circle + // (the radial dimension, the alignments of its centre) holds both. + [Fact] + public void ACircleOfOneClosedArcHasItsStoredShape() + { + var (model, positions) = Solve(SyntheticArcs.ClosedDisc()); + + var extrusion = Assert.Single(model.Extrusions); + Assert.Equal(2, extrusion.Loops[0].Count); + Assert.Equal((1, 0), Corner(model, positions, 0, 0)); + Assert.Equal((-1, 0), Corner(model, positions, 0, 1)); + Assert.All(extrusion.Arcs![0], arc => + { + Assert.Equal(1, positions[arc!.Value.Radius], 1e-12); + Assert.Equal((0, 0), (Math.Round(positions[arc.Value.CenterU], 9), Math.Round(positions[arc.Value.CenterV], 9))); + }); + } + + [Fact] + public void ADiameterOfAClosedArcSetsTheRadiusOfBothHalves() + { + var (model, positions) = Solve(SyntheticArcs.ClosedDisc(), (Diameter, 3)); + + Assert.Equal((1.5, 0), Corner(model, positions, 0, 0)); + Assert.Equal((-1.5, 0), Corner(model, positions, 0, 1)); + Assert.All(model.Extrusions[0].Arcs![0], arc => Assert.Equal(1.5, positions[arc!.Value.Radius], 1e-12)); + } + + // The circle of a hole is drawn the other way round: its halves turn the other way from the closed arc of the sketch, about + // the same centre and radius (the hole of the extrusion of the AquaFix valve is stored so). + [Fact] + public void ACircleWhoseHalvesTurnTheOtherWayFromTheClosedArcIsTheSameCircle() + { + var (model, positions) = Solve(SyntheticArcs.ClosedDisc(halvesFlipped: true), (Diameter, 3)); + + Assert.Equal((1.5, 0), Corner(model, positions, 0, 0)); + Assert.Equal((-1.5, 0), Corner(model, positions, 0, 1)); + Assert.All(model.Extrusions[0].Arcs![0], arc => + { + Assert.Equal(-1, arc!.Value.Way); + Assert.Equal(1.5, positions[arc.Value.Radius], 1e-12); + }); + } + + // A half is of a circle only when the closed arc it names is that circle. + [Theory] + [InlineData(0)] + [InlineData(1)] + [InlineData(2)] + public void AHalfOfNoSuchCircleIsRefused(int fault) + { + var disc = SyntheticArcs.ClosedDisc(); + var halves = disc.Lines.Select(line => line.Id switch + { + -1 when fault == 0 => line with { CircleId = 999 }, + -1 when fault == 1 => line with { CircleId = 41, Arc = line.Arc! with { Radius = 1.5 } }, + 41 when fault == 2 => line with { Arc = line.Arc! with { Center = [0.5, 0, 0] } }, + _ => line, + }).ToList(); + + AssertRefused(disc with { Lines = halves }, "unrecognized-reference", "curve -1"); + } + + // The sample family of the Revit MEP extension: its round forms are circles that are one closed arc of the sketch, each + // split in two half arcs in the profile of its extrusion. + [SkippableFact] + public void EveryTypeOfAFamilyWithClosedCirclesComputes() + { + var document = RvtDocument.Open(TestFiles.FindRelative("families/rme_advanced_sample_family.rfa"), + new RvtReaderOptions { R22Layout = true }); + + var halves = document.RawData.Family!.Records!.Lines.Where(line => line.CircleId != null).ToList(); + Assert.Equal(6, halves.Count); + Assert.Equal(7, document.FamilyTypes!.Types.Count); + for (int type = 0; type < document.FamilyTypes.Types.Count; type++) + { + var computed = ElementMeshes.ComputeFamilyType(document, type); + Assert.True(computed.Elements is { Count: > 0 }, $"type {type}: {computed.Refusal?.Code} {computed.Refusal?.Detail}"); + } + } + + // The diameter of the radial dimension is twice the radius of both halves, which meet where the circle ends. + [Fact] + public void ADiameterSetsTheRadiusOfBothHalves() + { + var (model, positions) = Solve(SyntheticArcs.Disc(), (Diameter, 3)); + + Assert.Equal((1.5, 0), Corner(model, positions, 0, 0)); + Assert.Equal((-1.5, 0), Corner(model, positions, 0, 1)); + Assert.All(model.Extrusions[0].Arcs![0], arc => Assert.Equal(1.5, positions[arc!.Value.Radius], 1e-12)); + } + + [Fact] + public void ARadiusStyleSetsTheRadiusItself() + { + var disc = SyntheticArcs.Disc(style: 0, value: 1, parameter: Radius); + + var (model, positions) = Solve(disc, (Radius, 1.5)); + + Assert.All(model.Extrusions[0].Arcs![0], arc => Assert.Equal(1.5, positions[arc!.Value.Radius], 1e-12)); + } + + [Fact] + public void AnArcDrawnTheOtherWayRoundTurnsTheOtherWay() + { + var (model, _) = Solve(SyntheticArcs.Disc(flipped: true)); + + Assert.All(model.Extrusions[0].Arcs![0], arc => Assert.Equal((-1, 2), (arc!.Value.Way, arc.Value.Quarters))); + } + + [Fact] + public void AProfileCurveThatRunsAgainstItsArcTurnsTheOtherWay() + { + var disc = SyntheticArcs.Disc().WithExtrusion(e => e with + { + ProfileCurves = new Dictionary { [0] = new(41, true), [1] = new(42, true) }, + }); + + var (model, positions) = Solve(disc); + + // It leaves from the end of the line it copies, and turns the other way. + Assert.Equal((-1, 0), Corner(model, positions, 0, 0)); + Assert.Equal((1, 0), Corner(model, positions, 0, 1)); + var arcs = model.Extrusions[0].Arcs![0].Select(arc => arc!.Value).ToArray(); + Assert.Equal([-1, -1], arcs.Select(arc => arc.Way)); + Assert.Equal([2, 0], arcs.Select(arc => arc.StartQuarter)); + } + + [Fact] + public void TheFacetsOfTheStoredFacesAreKept() + { + var defaults = Assert.Single(Model(SyntheticArcs.Disc()).Extrusions).Arcs![0]; + var stored = Model(SyntheticArcs.Disc().WithExtrusion(e => e with + { + FaceFacets = new Dictionary { [2] = 4, [3] = 5 }, + })).Extrusions[0].Arcs![0]; + + // Three to a quarter turn when the file stores none. + Assert.Equal([6, 6], defaults.Select(arc => arc!.Value.Facets)); + Assert.Equal([4, 5], stored.Select(arc => arc!.Value.Facets)); + } + + [Fact] + public void ARoundedRectangleKeepsItsLinesBetweenItsArcs() + { + var (model, positions) = Solve(SyntheticArcs.RoundedLeaf(), (Width, 4), (Radius, 0.4)); + + var corners = Enumerable.Range(0, 8).Select(i => Corner(model, positions, 0, i)).ToList(); + Assert.Equal([(-1.6, -0.5), (1.6, -0.5), (2, -0.1), (2, 0.1), (1.6, 0.5), (-1.6, 0.5), (-2, 0.1), (-2, -0.1)], + corners); + var arcs = model.Extrusions[0].Arcs![0]; + Assert.Equal([false, true, false, true, false, true, false, true], arcs.Select(arc => arc != null)); + Assert.All(arcs.OfType(), arc => + { + Assert.Equal(0.4, positions[arc.Radius], 1e-12); + Assert.Equal((1, 1, 3), (arc.Way, arc.Quarters, arc.Facets)); + }); + Assert.Equal([3, 0, 1, 2], arcs.OfType().Select(arc => arc.StartQuarter)); + Assert.Null(FamilyContourChecks.Check(model, positions, + new Dictionary { [Width] = 4, [Height] = 2, [Radius] = 0.4 })); + } + + // Two corners of 0.6 leave the right line of 1 high with a length of -0.2. + [Fact] + public void ARadiusThatTurnsALineBackIsDegenerate() + { + var (model, positions) = Solve(SyntheticArcs.RoundedLeaf(), (Radius, 0.6)); + + var refusal = FamilyContourChecks.Check(model, positions, + new Dictionary { [Width] = 3, [Height] = 2, [Radius] = 0.6 }); + + Assert.Equal("degenerate-geometry", refusal?.Code); + } + + [Fact] + public void ARadiusOfZeroIsDegenerate() + { + var (model, positions) = Solve(SyntheticArcs.Disc(), (Diameter, 0)); + + var refusal = FamilyContourChecks.Check(model, positions, new Dictionary { [Height] = 2, [Diameter] = 0 }); + + Assert.Equal("degenerate-geometry", refusal?.Code); + } + + [Fact] + public void AnArcOffTheAxesThroughItsCentreIsUnsupported() => + AssertRefused(SyntheticArcs.Disc().WithLine(41, _ => SyntheticArcs.Arc(41, 40, [0, 0, 0], 1, 0.1, Math.PI)), + "unsupported-construct", "41"); + + // A frame of 1e10 puts the direction of an end at 1e10 along an axis: it is refused whatever the runtime does with a + // double that no int holds (the .NET 8 cast gives int.MinValue, whose absolute value throws). + [Fact] + public void AnArcWithAnHugeFrameIsUnsupported() => + AssertRefused(SyntheticArcs.Disc().WithLine(41, line => line with + { Arc = line.Arc! with { XAxis = [1e10, 0, 0], YAxis = [0, 1e10, 0] } }), "unsupported-construct", "41"); + + [Fact] + public void AnArcWhoseEndsAreNotHeldAtAnAngleRefuses() + { + var leaf = SyntheticArcs.RoundedLeaf(); + + AssertRefused(leaf with { ArcEndAngles = Without(leaf, (45, 1)) }, "unsupported-construct", "45"); + AssertRefused(leaf with { ArcEndAngles = Without(leaf, (47, 0), (47, 1)) }, "unsupported-construct", "47"); + AssertRefused(leaf with { ArcEndAngles = null }, "unsupported-construct", "45"); + } + + private static List Without(FamilyRecords records, params (int Arc, int End)[] ends) => + records.ArcEndAngles!.Where(a => !ends.Contains((a.ArcLineId, a.End))).ToList(); + + // The circle tool holds three of the four ends of its two half arcs at an angle: the fourth end is where the other half + // joins it, so the two halves are one circle. + [Theory] + [InlineData(42, 1)] + [InlineData(42, 0)] + [InlineData(41, 0)] + public void ACircleWithOneEndOfOneHalfFreeIsStillACircle(int arc, int end) + { + var disc = SyntheticArcs.Disc(); + var circle = disc with { ArcEndAngles = Without(disc, (arc, end)) }; + + var (model, positions) = Solve(circle, (Diameter, 3)); + + Assert.Equal((1.5, 0), Corner(model, positions, 0, 0)); + Assert.All(model.Extrusions[0].Arcs![0], a => Assert.Equal(1.5, positions[a!.Value.Radius], 1e-12)); + } + + // Free ends of both halves, or of one half at both ends, leave a half that may be any arc through its two points. + [Fact] + public void ACircleWithMoreFreeEndsIsUnsupported() + { + var disc = SyntheticArcs.Disc(); + + AssertRefused(disc with { ArcEndAngles = Without(disc, (41, 1), (42, 1)) }, "unsupported-construct", "41"); + AssertRefused(disc with { ArcEndAngles = Without(disc, (42, 0), (42, 1)) }, "unsupported-construct", "42"); + AssertRefused(disc with { ArcEndAngles = null }, "unsupported-construct", "41"); + } + + // Two arcs that are not both joined at both ends and turn a full circle between them are no circle. + [Fact] + public void ATwoArcLoopOfOtherTurnsNeedsEveryEndHeld() + { + var disc = SyntheticArcs.Disc().WithLine(42, line => SyntheticArcs.Arc(42, 40, [0, 0, 0], 1, Math.PI, 1.5 * Math.PI)); + + AssertRefused(disc with { ArcEndAngles = Without(disc, (42, 1)) }, "unsupported-construct", "42"); + } + + [Fact] + public void AnArcOfAFullTurnIsUnsupported() => + AssertRefused(SyntheticArcs.Disc().WithLine(41, _ => SyntheticArcs.Arc(41, 40, [0, 0, 0], 1, 0, 2 * Math.PI)), + "unsupported-construct", "41"); + + [Fact] + public void ALoopOfTwoLinesIsUnsupported() + { + var leaf = SyntheticFamily.Leaf(); + AssertRefused(leaf.WithExtrusion(e => e with { Loops = [[0, 1]] }), "unsupported-construct", "profile of 50"); + } + + [Fact] + public void AnUnknownKindOfRadialDimensionStyleRefuses() + { + var disc = SyntheticArcs.Disc(); + + AssertRefused(disc with { RadialDimensions = [disc.RadialDimensions![0] with { StyleType = 5 }] }, + "unrecognized-reference", "25"); + } + + [Fact] + public void ARadialDimensionOfAnUnknownArcRefuses() + { + var disc = SyntheticArcs.Disc(); + + AssertRefused(disc with { RadialDimensions = [disc.RadialDimensions![0] with { Arc = new(999, 0, -1) }] }, + "unrecognized-reference", "25"); + } + + [Fact] + public void ALinearDimensionToAWholeArcIsUnsupported() => + AssertRefused(SyntheticArcs.Disc().Add(SyntheticFamily.Alignment(32, 0, (1, 0, -1), (41, 0, -1))), + "unsupported-construct", "41"); + + [Fact] + public void ALinearDimensionToAnArcEndIsRead() + { + var withEnd = SyntheticArcs.Disc().Add(SyntheticFamily.Alignment(32, 1, (4, 0, -1), (41, 0, 0))); + + Assert.Null(FamilyModelBuilder.Build(withEnd).Refusal); + } + + [Fact] + public void ADimensionToTheCentreAlongTheExtrusionIsUnsupported() => + AssertRefused(SyntheticArcs.Disc().Add(SyntheticFamily.Alignment(32, 2, (7, 0, -1), (41, 1, -1))), + "unsupported-construct", "centre of arc 41"); + + // An arc of a sketch that makes no form of the shown extrusions: a dimension to its centre or its ends is one more relation + // about a place of its own, which leaves the other forms where they are. + private static FamilyRecords WithHiddenArc(params FamilyDimensionRecord[] dimensions) + { + var leaf = SyntheticFamily.Leaf(); + return leaf with + { + Lines = [.. leaf.Lines, SyntheticArcs.Arc(60, 90, [0.3, 0.2, 0], 0.1, 0, Math.PI / 2)], + Dimensions = [.. leaf.Dimensions, .. dimensions], + Referrers = [.. leaf.Referrers, .. dimensions.Select(d => + new FamilyReferrer(d.Id, "LinearDimString", "GeomSegInPlaneRef.GeomRef.m_elemId", 60))], + }; + } + + [Theory] + [InlineData(1, -1)] + [InlineData(0, 1)] + public void ADimensionToTheCentreOrAnEndOfAnArcOutsideTheProfileIsRead(int tag, int sub) + { + var records = WithHiddenArc(SyntheticFamily.Linear(36, 0, 12, [(2, 0, -1), (60, tag, sub)], [0], [-1], [1.8])); + + var (model, positions) = Solve(records, (Width, 4)); + + Assert.Equal([(-2, -0.5), (2, -0.5), (2, 0.5), (-2, 0.5)], + Enumerable.Range(0, 4).Select(i => Corner(model, positions, 0, i))); + } + + [Fact] + public void ADimensionToAWholeArcOutsideTheProfileIsUnsupported() => + AssertRefused(WithHiddenArc(SyntheticFamily.Linear(36, 0, 12, [(2, 0, -1), (60, 0, -1)], [0], [-1], [1.8])), + "unsupported-construct", "60"); + + // A straight line of such a sketch that runs along no axis is a place of its own at each end likewise. + private static FamilyRecords WithHiddenSlant(FamilyDimensionRecord dimension) + { + var leaf = SyntheticFamily.Leaf(); + return leaf with + { + Lines = [.. leaf.Lines, new FamilySketchLine(61, 90, true, [0.3, 0.2, 0], [0.9, 0.7, 0])], + Dimensions = [.. leaf.Dimensions, dimension], + Referrers = [.. leaf.Referrers, + new FamilyReferrer(dimension.Id, "LinearDimString", "GeomSegInPlaneRef.GeomRef.m_elemId", 61)], + }; + } + + [Theory] + [InlineData(0, 1.8)] + [InlineData(1, 2.4)] + public void ADimensionToAnEndOfASlantedLineOutsideTheProfileIsRead(int end, double distance) + { + var records = WithHiddenSlant(SyntheticFamily.Linear(36, 0, 12, [(2, 0, -1), (61, 0, end)], [0], [-1], [distance])); + + var (model, positions) = Solve(records, (Width, 4)); + + Assert.Equal([(-2, -0.5), (2, -0.5), (2, 0.5), (-2, 0.5)], + Enumerable.Range(0, 4).Select(i => Corner(model, positions, 0, i))); + } + + [Fact] + public void ADimensionToAWholeSlantedLineIsUnsupported() => + AssertRefused(WithHiddenSlant(SyntheticFamily.Linear(36, 0, 12, [(2, 0, -1), (61, 0, -1)], [0], [-1], [1.8])), + "unsupported-construct", "61"); + + // A control icon is the arrow that flips an element: it has no place the family keeps. A dimension to it that holds nothing + // changes nothing; one that holds something is a relation to a place this does not know. + private static FamilyRecords WithIconDimension(long segmentFlags, long parameter, bool listed) + { + var leaf = SyntheticFamily.Leaf(); + var dimension = SyntheticFamily.Linear(36, 0, 12, [(2, 0, -1), (99, 0, -1)], [segmentFlags], [parameter], [0.5]); + return leaf with + { + Dimensions = [.. leaf.Dimensions, dimension], + ControlIconIds = listed ? new HashSet { 99 } : null, + }; + } + + [Fact] + public void AnUnlabelledUnlockedDimensionToAControlIconChangesNothing() + { + var (model, positions) = Solve(WithIconDimension(0, -1, listed: true), (Width, 4)); + + Assert.Equal([(-2, -0.5), (2, -0.5), (2, 0.5), (-2, 0.5)], + Enumerable.Range(0, 4).Select(i => Corner(model, positions, 0, i))); + } + + [Theory] + [InlineData(1, -1, true)] + [InlineData(0, 100, true)] + [InlineData(0, -1, false)] + public void AnyOtherDimensionToAControlIconIsARelationToAnUnknownPlace(long segmentFlags, long parameter, bool listed) => + AssertRefused(WithIconDimension(segmentFlags, parameter, listed), "unrecognized-reference", "99"); + + [Fact] + public void AFormulaOnTheParameterOfARadialDimensionIsUnsupported() => + AssertRefused(SyntheticArcs.Disc() with { FormulaParameterIds = new HashSet { Diameter } }, + "unsupported-construct", Diameter.ToString()); + + // The circle faces: two ends of the outline made of the facets, and a row of flat sides for each half. + [Fact] + public void ACircleExtrudesToAFacetedCylinder() + { + var (model, positions) = Solve(SyntheticArcs.Disc()); + var keys = new List(); + + var faces = FamilyExtrusionBuilder.Faces(model.Extrusions[0], positions, key => + { + keys.Add(key); + return 0; + }); + + Assert.Equal(2 + 12, faces.Count); + Assert.Equal(6, keys.Count(key => key == new FamilyFaceKey(FamilyFaceKind.Side, 0, 0))); + Assert.Equal(6, keys.Count(key => key == new FamilyFaceKey(FamilyFaceKind.Side, 0, 1))); + var caps = faces.Where(face => face.OuterVertices!.Count == 12).ToList(); + Assert.Equal(2, caps.Count); + Assert.All(faces.SelectMany(face => face.OuterVertices!), + point => Assert.Equal(1, Math.Sqrt(point[0] * point[0] + point[1] * point[1]), 1e-9)); + // The sides face outward. The caps face inward, as the file stores the caps of every circle it holds (17 extrusions + // of the corpus, drawn either way round), and the corners of each face wind round its normal. + foreach (var face in faces) + { + double outward = Enumerable.Range(0, 3).Sum(i => face.Normal[i] * (face.OuterVertices![0][i] - (i == 2 ? 1 : 0))); + Assert.True(face.OuterVertices!.Count == 12 ? outward < 0 : outward > 0); + var corners = face.OuterVertices; + var wound = new double[3]; + for (int i = 0; i < corners.Count; i++) + { + var (a, b) = (corners[i], corners[(i + 1) % corners.Count]); + wound[0] += a[1] * b[2] - a[2] * b[1]; + wound[1] += a[2] * b[0] - a[0] * b[2]; + wound[2] += a[0] * b[1] - a[1] * b[0]; + } + Assert.True(Enumerable.Range(0, 3).Sum(i => face.Normal[i] * wound[i]) > 0); + } + } + + [Fact] + public void ASideFacetOfAnArcFacesOutwardAtTheMiddleOfItsTurn() + { + var (model, positions) = Solve(SyntheticArcs.RoundedLeaf()); + + var faces = FamilyExtrusionBuilder.Faces(model.Extrusions[0], positions, _ => 0); + + // The first facet of the corner at the front right turns from -90° to -60°: its normal is at -75°. + var facet = faces.First(face => face.OuterVertices!.Count == 4 && Math.Abs(face.Normal[0] - Math.Cos(-Math.PI * 5 / 12)) < 1e-9); + Assert.Equal(Math.Sin(-Math.PI * 5 / 12), facet.Normal[1], 1e-9); + } + + [Fact] + public void TheStoredFacetedStateMatches() + { + foreach (var records in new[] { SyntheticArcs.Disc(), SyntheticArcs.RoundedLeaf() }) + { + var model = Model(records); + var stored = FamilyExtrusionBuilder.Faces(model.Extrusions[0], + model.Variables.Select(v => v.Stored).ToArray(), _ => 40); + var values = new Dictionary + { [Width] = 3, [Height] = 2, [Diameter] = 2, [Radius] = 0.25 }; + + var refusal = FamilySavedState.Check(model, values, (_, _) => 40, + new Dictionary> { [50] = stored }); + + Assert.Null(refusal); + } + } + + [Fact] + public void AStoredCylinderWithOtherFacetsIsAMismatch() + { + var model = Model(SyntheticArcs.Disc()); + var other = Model(SyntheticArcs.Disc().WithExtrusion(e => e with + { + FaceFacets = new Dictionary { [2] = 4, [3] = 4 }, + })); + var stored = FamilyExtrusionBuilder.Faces(other.Extrusions[0], other.Variables.Select(v => v.Stored).ToArray(), _ => 40); + + var refusal = FamilySavedState.Check(model, new Dictionary { [Height] = 2, [Diameter] = 2 }, + (_, _) => 40, new Dictionary> { [50] = stored }); + + Assert.Equal("saved-state-mismatch", refusal?.Code); + } +} + +/// Families with arcs in the profile of their extrusion. +internal static class SyntheticArcs +{ + public static FamilySketchLine Arc(int id, int sketch, double[] centre, double radius, double start, double end, + bool flipped = false) + { + double[] x = [1, 0, 0], y = flipped ? [0, -1, 0] : [0, 1, 0]; + double[] At(double angle) => [.. Enumerable.Range(0, 3) + .Select(i => centre[i] + radius * (Math.Cos(angle) * x[i] + Math.Sin(angle) * y[i]))]; + return new(id, sketch, false, At(start), At(end), new FamilyArc(centre, x, y, radius, start, end)); + } + + private static FamilySketchLine Line(int id, double[] start, double[] end) => new(id, 40, true, start, end); + + private static FamilyArcEndAngle[] EndAngles(params int[] arcs) => + [.. arcs.SelectMany(arc => new[] { new FamilyArcEndAngle(40, arc, 0), new FamilyArcEndAngle(40, arc, 1) })]; + + /// A circle of the diameter 2 made of two half arcs about the origin, extruded 2 up from the level; its centre + /// is on both centre planes and the radial dimension 25 labels it (by default its diameter, with the parameter 102). + public static FamilyRecords Disc(bool flipped = false, long style = 9, double value = 2, long parameter = 102) + { + FamilyPlaneRecord[] planes = + [ + new(1, "RefPlane", 1, [0, 0, 0], [1, 0, 0]), new(4, "RefPlane", 4, [0, 0, 0], [0, 1, 0]), + new(7, "Level", 0, [0, 0, 0], [0, 0, 1]), new(8, "RefPlane", 8, [0, 0, 2], [0, 0, 1]), + ]; + FamilyDimensionRecord[] dimensions = + [ + SyntheticFamily.Linear(24, 2, 8, [(7, 0, -1), (8, 0, -1)], [0], [101], [2]), + SyntheticFamily.Alignment(30, 0, (1, 0, -1), (41, 1, -1)), SyntheticFamily.Alignment(31, 1, (4, 0, -1), (41, 1, -1)), + SyntheticFamily.Alignment(34, 2, (8, 0, -1), (SyntheticFamily.Extrusion, 0, -1)), + ]; + FamilySketchLine[] lines = + [ + Arc(41, 40, [0, 0, 0], 1, 0, Math.PI, flipped), Arc(42, 40, [0, 0, 0], 1, Math.PI, 2 * Math.PI, flipped), + ]; + FamilySketchJoint[] joints = [new(41, 1, 42, 0), new(42, 1, 41, 0)]; + var extrusion = new FamilyExtrusionRecord(SyntheticFamily.Extrusion, 40, 0, 2, [0, 0, 0], [0, 0, 1], new(7, 0, -1), + [[0, 1]], new Dictionary { [0] = new(41, false), [1] = new(42, false) }, + new Dictionary { [1] = [1], [0] = [2], [2] = [3, 0], [3] = [3, 1] }, + new Dictionary(), new Dictionary()); + return new FamilyRecords(dimensions, lines, joints, + [new(40, "VarSketchPPConstrObj"), new(40, "VarSketchArcEndAngleConstrObj")], planes, [extrusion], + [ + new(24, "LinearDimString", "GeomSegInPlaneRef.GeomRef.m_elemId", 7), + new(30, "Alignment", "GeomSegInPlaneRef.GeomRef.m_elemId", 41), + new(25, "RadialDim", "ArcRef.GeomRef.m_elemId", 41), + new(51, "SketchPlane", "OnDatumPlaneRef.OneElementMovablePlaneRef.m_datumPlaneId", 7), + new(SyntheticFamily.Extrusion, "ExtrusionElem", "ExtrusionElemExtrusionHelper.ExtrusionHelper.m_sketchId", 40), + new(41, "CurveElem", "CurveElemDriver.EndInfo.m_elemId", 42), + new(42, "CurveElem", "CurveElemDriver.EndInfo.m_elemId", 41), + new(40, "VarSketch", "ElementIdIndexPairSet.ElementIdPlusIndex.m_elementId", 41), + ], [], new HashSet(), [], [new FamilyRadialDimension(25, new(41, 0, -1), parameter, value, 12, 0, false, style)], + EndAngles(41, 42)); + } + + /// The circle of as the file has it: the closed arc 41 is all the sketch holds, and the profile + /// has two half arcs, -1 and -2, that copy it. + public static FamilyRecords ClosedDisc(bool halvesFlipped = false) + { + var disc = Disc(); + var circle = disc.Lines[0].Arc!; + FamilySketchLine[] lines = + [ + Arc(41, 40, [0, 0, 0], 1, 0, 0) with { End = disc.Lines[0].Start }, + Arc(-1, 40, [0, 0, 0], 1, 0, Math.PI, halvesFlipped) with { CircleId = 41 }, + Arc(-2, 40, [0, 0, 0], 1, Math.PI, 2 * Math.PI, halvesFlipped) with { CircleId = 41 }, + ]; + return disc with + { + Lines = lines, + Joints = [new(-1, 1, -2, 0), new(-2, 1, -1, 0)], + Constraints = [new(40, "VarSketchPPConstrObj")], + ArcEndAngles = [], + Extrusions = [disc.Extrusions[0] with + { + ProfileCurves = new Dictionary { [0] = new(-1, false), [1] = new(-2, false) }, + }], + Referrers = disc.Referrers.Where(r => r.ClassName != "CurveElem").ToList(), + }; + } + + /// The box of with its four corners rounded: lines 41 to 44 as before, and + /// the arcs 45 to 48 at the corners, each labelled by the parameter 103 (a radius, 0.25 at the stored state). + public static FamilyRecords RoundedLeaf() + { + var leaf = SyntheticFamily.Leaf(); + const double a = 1.5, b = 0.5, c = 0.25; + FamilySketchLine[] lines = + [ + Line(41, [-a + c, -b, 0], [a - c, -b, 0]), Line(42, [a, -b + c, 0], [a, b - c, 0]), + Line(43, [a - c, b, 0], [-a + c, b, 0]), Line(44, [-a, b - c, 0], [-a, -b + c, 0]), + Arc(45, 40, [a - c, -b + c, 0], c, -Math.PI / 2, 0), Arc(46, 40, [a - c, b - c, 0], c, 0, Math.PI / 2), + Arc(47, 40, [-a + c, b - c, 0], c, Math.PI / 2, Math.PI), + Arc(48, 40, [-a + c, -b + c, 0], c, Math.PI, 3 * Math.PI / 2), + ]; + FamilySketchJoint[] joints = + [ + new(41, 1, 45, 0), new(45, 1, 42, 0), new(42, 1, 46, 0), new(46, 1, 43, 0), + new(43, 1, 47, 0), new(47, 1, 44, 0), new(44, 1, 48, 0), new(48, 1, 41, 0), + ]; + int[] order = [41, 45, 42, 46, 43, 47, 44, 48]; + var extrusion = leaf.Extrusions[0] with + { + Loops = [[0, 1, 2, 3, 4, 5, 6, 7]], + ProfileCurves = order.Select((line, key) => (line, key)) + .ToDictionary(item => item.key, item => new FamilyProfileCurve(item.line, false)), + FaceHistory = new Dictionary[] { new() { [1] = [1], [0] = [2] } }[0] + .Concat(Enumerable.Range(0, 8).ToDictionary(i => 2 + i, i => new[] { 3, i })).ToDictionary(p => p.Key, p => p.Value), + }; + var radials = Enumerable.Range(0, 4) + .Select(i => new FamilyRadialDimension(61 + i, new(45 + i, 0, -1), 103, c, 12, 0, false, 0)).ToList(); + return leaf with + { + Lines = lines, + Joints = joints, + Constraints = [.. leaf.Constraints, new(40, "VarSketchArcEndAngleConstrObj")], + Extrusions = [extrusion], + Referrers = [.. leaf.Referrers, .. radials.Select(r => new FamilyReferrer(r.Id, "RadialDim", "ArcRef.GeomRef.m_elemId", r.Arc.ElementId))], + RadialDimensions = radials, + ArcEndAngles = EndAngles(45, 46, 47, 48), + }; + } +} diff --git a/tests/RvtIO.Tests/Families/FamilyBoundsTests.cs b/tests/RvtIO.Tests/Families/FamilyBoundsTests.cs new file mode 100644 index 00000000..66813707 --- /dev/null +++ b/tests/RvtIO.Tests/Families/FamilyBoundsTests.cs @@ -0,0 +1,111 @@ +using RvtIO.Families; +using RvtIO.Parsing; +using Xunit; + +namespace RvtIO.Tests.Families; + +/// A crafted file chooses how long a chain of related coordinates or nested combinations is, and how wide an angle a +/// face spans; none of them may take the stack or the memory of the reader. +public class FamilyBoundsTests +{ + [Fact] + public void AGroupChainAsLongAsAFileCanMakeIsFoundWithoutRecursion() + { + // 0 -> 1 -> ... -> n: the shape the union of places in an order of one's choosing leaves behind. + const int n = 2_000_000; + var parent = new Dictionary(n + 1); + for (int i = 0; i < n; i++) parent[i] = i + 1; + parent[n] = n; + + Assert.Equal(n, FamilyModelBuilder.FindGroup(parent, 0)); + Assert.Equal(n, FamilyModelBuilder.FindGroup(parent, n / 2)); + Assert.Equal(n + 8, FamilyModelBuilder.FindGroup(parent, n + 8)); + } + + private static (Dictionary Own, ILookup MembersOf) Chain(int length) + { + // Combination i holds combination i + 1; the last one holds nothing. + var own = new Dictionary(); + for (int i = 0; i < length; i++) + own[i] = new("FamilyGeomCombination", true, true, true, 1, false, null, false, null, false, false, false, []); + var membersOf = Enumerable.Range(1, length - 1).ToLookup(member => member - 1, member => member); + return (own, membersOf); + } + + [Fact] + public void ANestedCombinationOfFewLevelsIsShown() + { + var (own, membersOf) = Chain(4); + Assert.Equal((true, false), FamilyRecordReader.Combined(0, own, membersOf, [], [])); + } + + [Fact] + public void ACombinationNestedBeyondAnyFamilyIsUnknownWithoutRecursion() + { + var (own, membersOf) = Chain(300_000); + Assert.Equal((null, null), FamilyRecordReader.Combined(0, own, membersOf, [], [])); + } + + [Fact] + public void AnAngleNoFaceSpansKeepsItsSamples() + { + // About 1.2 million steps for a circle of a foot: more than a face may ask for. + Assert.Equal([0, 1e5], GRepParserV2.RefineAngularSamples([0, 1e5], 1)); + } + + [Fact] + public void AnAngleWithNoCountOfStepsKeepsItsSamples() + { + Assert.Equal([0, 1e12], GRepParserV2.RefineAngularSamples([0, 1e12], 1)); + Assert.Equal([0, double.PositiveInfinity], GRepParserV2.RefineAngularSamples([0, double.PositiveInfinity], 1)); + Assert.Equal(2, GRepParserV2.RefineAngularSamples([0, double.NaN], 1).Count); + } + + [Fact] + public void AnAngleOfARealCircleIsStillRefined() + { + var refined = GRepParserV2.RefineAngularSamples([0, 2 * Math.PI], 1); + Assert.InRange(refined.Count, 20, 1000); + Assert.Equal(2 * Math.PI, refined[^1], 1e-12); + } + + [Fact] + public void ManyGapsTogetherAskForNoMoreThanAFaceMay() + { + // 20 gaps of 3 radians at a radius of 5 million feet: about 83 thousand steps each, which one gap may ask for, and + // 1.7 million together, which a face may not. + var samples = Enumerable.Range(0, 21).Select(i => 3.0 * i).ToList(); + Assert.InRange(GRepParserV2.RefineAngularSamples([0, 3], 5e6).Count, 50_000, GRepParserV2.MaxRefinedSamples - 1); + + var refined = GRepParserV2.RefineUncrossedAngles(samples, [], default, 5e6); + + Assert.InRange(refined.Count, 21, GRepParserV2.MaxRefinedSamples); + } + // With no trim edge the faces are the cells of the grid of the samples, which are many for a surface of a huge radius. + private const int CellsOfAFace = 20_000; + + [Fact] + public void ACylinderOfNoTrimIsNoMoreCellsThanAFaceMay() + { + var surface = new GRepParserV2.SurfaceRec { Kind = GRepParserV2.SurfKind.Cylinder, O = [0, 0, 0], X = [1, 0, 0], + Y = [0, 1, 0], Z = [0, 0, 1], R = 5e6, Env = [0, 0, 6, 1] }; + + int cells = GRepParserV2.TessellateCylinder(new GRepParserV2.RingGraph(), surface, [], [], hasAuthoredTrim: false) + .Take(10 * CellsOfAFace).Count(); + + Assert.InRange(cells, 1, CellsOfAFace); + } + + [Fact] + public void ARevolutionOfNoTrimIsNoMoreCellsThanAFaceMay() + { + var profile = new GRepParserV2.ArcRec { C = [0, 0, 0], X = [1, 0, 0], Y = [0, 0, 1], R = 5e6 }; + var surface = new GRepParserV2.SurfaceRec { Kind = GRepParserV2.SurfKind.Rev, O = [0, 0, 0], X = [1, 0, 0], + Y = [0, 1, 0], Z = [0, 0, 1], Env = [0, 0, 6, 1.4] }; + + int cells = GRepParserV2.TessellateRevolution(new GRepParserV2.RingGraph(), surface, profile, [], [], + hasAuthoredTrim: false).Take(10 * CellsOfAFace).Count(); + + Assert.InRange(cells, 1, CellsOfAFace); + } +} diff --git a/tests/RvtIO.Tests/Families/FamilyModelBuilderTests.cs b/tests/RvtIO.Tests/Families/FamilyModelBuilderTests.cs index 2d6cd013..c04bf152 100644 --- a/tests/RvtIO.Tests/Families/FamilyModelBuilderTests.cs +++ b/tests/RvtIO.Tests/Families/FamilyModelBuilderTests.cs @@ -229,7 +229,8 @@ public void ReferrersOfNoEffectAreAccepted() => .Add(new FamilyReferrer(60, "DBViewPlan", "PlanViewRange2.PlanViewRange2.m_levelIds", 7)) .Add(new FamilyReferrer(61, "ConnectorElem", "GeomOnPlaneRef.GeomRef.m_elemId", SyntheticFamily.Extrusion)) .Add(new FamilyReferrer(62, "FamilyInstance", "Element.m_assocLevelId", 7)) - .Add(new FamilyReferrer(63, "RadialDim", "ArcRef.GeomRef.m_elemId", 999))); + .Add(new FamilyReferrer(63, "RadialDim", "ArcRef.GeomRef.m_elemId", 999)) + .Add(new FamilyReferrer(64, "FilledRegion", "SketchedRegion.m_sketchId", 40))); // A line that follows a form edge is placed by that edge, which nothing here models. [Fact] diff --git a/tests/RvtIO.Tests/Families/FamilyRevolutionLoopsTests.cs b/tests/RvtIO.Tests/Families/FamilyRevolutionLoopsTests.cs new file mode 100644 index 00000000..55ce0f13 --- /dev/null +++ b/tests/RvtIO.Tests/Families/FamilyRevolutionLoopsTests.cs @@ -0,0 +1,148 @@ +using RvtIO.Families; +using RvtIO.Model; +using Xunit; + +namespace RvtIO.Tests.Families; + +/// A revolution may have several loops: one inside another is a hole of the solid, whichever way round it is drawn; +/// loops that meet or that stand on both sides of the axis are no profile. +public class FamilyRevolutionLoopsTests +{ + private static double Polygon(double radius) => + FamilyRevolutionBuilder.Facets * Math.Sin(2 * Math.PI / FamilyRevolutionBuilder.Facets) / 2 * radius * radius; + + // Loops of corners (distance from the axis, position along it) in the plane of a sketch square to the second axis, about + // the vertical through the origin. + private static (FamilyRevolution Revolution, double[] Positions) Outlines(params (double D, double V)[][] loops) + { + var positions = new List { 0, 0 }; + var shapes = new List>(); + foreach (var loop in loops) + { + var vertices = new List(); + foreach (var (d, v) in loop) + { + positions.Add(d); + positions.Add(v); + vertices.Add(new(positions.Count - 2, 1, positions.Count - 1)); + } + shapes.Add(vertices); + } + return (new(7, shapes, 2, 1, 0, 1, new Dictionary(), null, null), [.. positions]); + } + + private static double Volume(IEnumerable faces) + { + double volume = 0; + foreach (var face in faces) + foreach (var ring in new[] { face.OuterVertices! }.Concat(face.InnerVertices ?? [])) + { + double x = 0, y = 0, z = 0; + for (int i = 0; i < ring.Count; i++) + { + var (a, b) = (ring[i], ring[(i + 1) % ring.Count]); + x += (a[1] - b[1]) * (a[2] + b[2]); + y += (a[2] - b[2]) * (a[0] + b[0]); + z += (a[0] - b[0]) * (a[1] + b[1]); + } + volume += (ring[0][0] * x + ring[0][1] * y + ring[0][2] * z) / 6; + } + return volume; + } + + // A cylinder of radius 4 and height 4 with a ring-shaped void of 1 to 2 from the axis and 1 to 2 high. + [Theory] + [InlineData(false, false)] + [InlineData(true, false)] + [InlineData(false, true)] + [InlineData(true, true)] + public void ALoopInsideAnotherIsAHoleWhicheverWayRoundEachIsDrawn(bool outerClockwise, bool holeClockwise) + { + (double, double)[] Rectangle(double d0, double v0, double d1, double v1, bool clockwise) => clockwise + ? [(d0, v0), (d0, v1), (d1, v1), (d1, v0)] + : [(d0, v0), (d1, v0), (d1, v1), (d0, v1)]; + var (revolution, positions) = Outlines(Rectangle(0, 0, 4, 4, outerClockwise), Rectangle(1, 1, 2, 2, holeClockwise)); + + Assert.True(FamilyRevolutionBuilder.Holds(revolution, positions, positions)); + + var faces = FamilyRevolutionBuilder.Faces(revolution, positions, _ => 0); + Assert.Equal(Polygon(4) * 4 - (Polygon(2) - Polygon(1)), Volume(faces), 1e-9); + } + + [Theory] + [InlineData("loops that meet")] + [InlineData("loops that cross")] + [InlineData("loops on both sides of the axis")] + public void LoopsThatMeetOrStandOnBothSidesOfTheAxisAreNoProfile(string fault) + { + var (revolution, positions) = fault switch + { + "loops that meet" => Outlines([(1, 0), (2, 0), (2, 1), (1, 1)], [(2, 0), (3, 0), (3, 1), (2, 1)]), + "loops that cross" => Outlines([(1, 0), (3, 0), (3, 2), (1, 2)], [(2, 1), (4, 1), (4, 3), (2, 3)]), + _ => Outlines([(1, 0), (2, 0), (2, 1), (1, 1)], [(-2, 0), (-1, 0), (-1, 1), (-2, 1)]), + }; + + Assert.False(FamilyRevolutionBuilder.Holds(revolution, positions, positions)); + } + + // A loop without an area has no inside: three corners on a line. + [Fact] + public void ALoopWithoutAreaIsNoProfile() + { + var (revolution, positions) = Outlines([(1, 0), (1, 2), (1, 1)]); + + Assert.False(FamilyRevolutionBuilder.Holds(revolution, positions, positions)); + } + + // The solid is the same on the other side of the axis, and so is each wall of a tube, however its outline runs. + [Theory] + [InlineData(1, false)] + [InlineData(1, true)] + [InlineData(-1, false)] + [InlineData(-1, true)] + public void ATubeIsTwoRingsAndTwoCylindersOnEitherSideOfTheAxis(int side, bool clockwise) + { + (double, double)[] Rectangle() => clockwise + ? [(side * 1.0, 0), (side * 1.0, 1), (side * 2.0, 1), (side * 2.0, 0)] + : [(side * 1.0, 0), (side * 2.0, 0), (side * 2.0, 1), (side * 1.0, 1)]; + var (revolution, positions) = Outlines(Rectangle()); + + Assert.True(FamilyRevolutionBuilder.Holds(revolution, positions, positions)); + + var faces = FamilyRevolutionBuilder.Faces(revolution, positions, _ => 0); + Assert.Equal(Polygon(2) - Polygon(1), Volume(faces), 1e-9); + Assert.Equal(2, faces.Count(face => face.InnerVertices is { Count: 1 })); + } + + // Loops that keep their directions and their nesting are the loops of the saved state; a hole that leaves its loop, or a + // side that runs the other way, is not. + [Fact] + public void ALoopThatLeavesTheLoopItWasInsideIsNoProfile() + { + var (revolution, saved) = Outlines([(0, 0), (4, 0), (4, 4), (0, 4)], [(1, 1), (2, 1), (2, 2), (1, 2)]); + var moved = (double[])saved.Clone(); + foreach (int index in new[] { 10, 12, 14, 16 }) moved[index] += 5; + + Assert.True(FamilyRevolutionBuilder.Holds(revolution, saved, saved)); + Assert.False(FamilyRevolutionBuilder.Holds(revolution, moved, saved)); + } + + [Fact] + public void ASideThatRunsTheOtherWayFromTheSavedOneIsNoProfile() + { + var (revolution, saved) = Outlines([(1, 0), (2, 0), (2, 1), (1, 1)]); + var (_, turned) = Outlines([(1, 0), (1, 1), (2, 1), (2, 0)]); + + Assert.False(FamilyRevolutionBuilder.Holds(revolution, turned, saved)); + } + + [Fact] + public void LoopsApartAreEachASolid() + { + var (revolution, positions) = Outlines([(1, 0), (2, 0), (2, 1), (1, 1)], [(3, 0), (4, 0), (4, 2), (3, 2)]); + + Assert.True(FamilyRevolutionBuilder.Holds(revolution, positions, positions)); + Assert.Equal((Polygon(2) - Polygon(1)) * 1 + (Polygon(4) - Polygon(3)) * 2, + Volume(FamilyRevolutionBuilder.Faces(revolution, positions, _ => 0)), 1e-9); + } +} diff --git a/tests/RvtIO.Tests/Families/FamilyRevolutionTests.cs b/tests/RvtIO.Tests/Families/FamilyRevolutionTests.cs new file mode 100644 index 00000000..65849f9b --- /dev/null +++ b/tests/RvtIO.Tests/Families/FamilyRevolutionTests.cs @@ -0,0 +1,451 @@ +using RvtIO.Families; +using RvtIO.Meshes; +using RvtIO.Model; +using Xunit; + +namespace RvtIO.Tests.Families; + +/// A revolution turns the closed profile of its sketch about the sketch line that is its axis; its faces are +/// computed from the lines of the profile, a surface of revolution for each. +public class FamilyRevolutionTests +{ + private const double Millimetre = 1 / 304.8; + private const long Radius = 100, Height = 101, TopRadius = 102; + + private static RvtDocument Cone() => + RvtDocument.Open(TestFiles.FindRelative("families/RR_Cone_R100_H300.rfa"), new RvtReaderOptions()); + + private static FamilyModel Model(FamilyRecords records) + { + var (model, refusal) = FamilyModelBuilder.Build(records); + Assert.Null(refusal); + return model!; + } + + private static double[] Stored(FamilyModel model) => [.. model.Variables.Select(variable => variable.Stored)]; + + private static double[] Solved(FamilyModel model, double radius, double height, double top = 0.5) + { + var solution = FamilySolver.Solve(model, + new Dictionary { [Radius] = radius, [Height] = height, [TopRadius] = top }); + Assert.Null(solution.Refusal); + return solution.Positions!; + } + + private static List Faces(FamilyModel model, double[] positions) => + FamilyRevolutionBuilder.Faces(Assert.Single(model.Revolutions), positions, _ => 0); + + // The area of a regular polygon of Facets sides inscribed in a circle. + private static double Polygon(double radius) => + FamilyRevolutionBuilder.Facets * Math.Sin(2 * Math.PI / FamilyRevolutionBuilder.Facets) / 2 * radius * radius; + + // The cone of RR_Cone_R100_H300: the triangle (0, 0), (100 mm, 0), (0, 300 mm) in the plane of the sketch, turned about + // its fourth line, the axis, which is the vertical through the origin. + [SkippableFact] + public void ARevolutionIsReadWithItsProfileItsAxisAndItsSweep() + { + var records = Cone().RawData.Family!.Records!; + + var revolution = Assert.Single(records.Revolutions!); + Assert.Equal(2814, revolution.Id); + Assert.Equal(2813, revolution.SketchId); + Assert.Equal(2818, revolution.AxisLineId); + Assert.Equal(0, revolution.StartAngle); + Assert.Equal(2 * Math.PI, revolution.EndAngle, 1e-12); + var loop = Assert.Single(revolution.Loops); + Assert.Equal([2815, 2816, 2817], loop.Select(curve => curve.LineId)); + Assert.All(loop, curve => Assert.False(curve.Reversed)); + Assert.Empty(records.UnsupportedContent); + } + + [SkippableFact] + public void ARevolutionOfTheFileBuildsTheSolidItsSketchTurnsAtTheStoredPositions() + { + var model = Model(Cone().RawData.Family!.Records!); + + double radius = 100 * Millimetre, height = 300 * Millimetre; + // The solid is inscribed in the cone: a pyramid of as many sides as the turn has facets. + Assert.Equal(Polygon(radius) * height / 3, Volume(Faces(model, Stored(model))), 1e-9); + } + + [SkippableFact] + public void TheFacesTheFileStoresForARevolutionAreTheSurfacesItTurns() + { + var document = Cone(); + var model = Model(document.RawData.Family!.Records!); + var stored = document.RawData.Elements.Single(element => element.Id == 2814).Geometry!.Faces; + + var refusal = FamilySavedState.Check(model, new Dictionary(), (_, _) => 0, + new Dictionary> { [2814] = stored }); + + Assert.Null(refusal); + } + + // Nothing sets the size of this cone, and no nearest shape is chosen for what the file does not hold. + [SkippableFact] + public void AConeWhoseSizeNothingHoldsIsRefusedAsUnderdetermined() + { + var computed = ElementMeshes.ComputeFamilyType(Cone(), 0); + + Assert.Null(computed.Elements); + Assert.Equal("underdetermined", computed.Refusal!.Code); + } + + [Fact] + public void ACylinderBuildsToTheSolidItsProfileTurnsAtTheStoredPositions() + { + var model = Model(SyntheticRevolution.Cylinder()); + + // A radius 1 and a height 2. + Assert.Equal(Polygon(1) * 2, Volume(Faces(model, Stored(model))), 1e-9); + } + + [Fact] + public void ACylinderHasADiscAtEachEndAndASideAndNoFaceOnTheAxis() + { + var model = Model(SyntheticRevolution.Cylinder()); + var faces = new List(); + + FamilyRevolutionBuilder.Faces(Assert.Single(model.Revolutions), Stored(model), key => + { + faces.Add(key); + return 0; + }); + + // Lines 0 and 2 of the loop are the bottom and the top, 1 is the side, 3 lies on the axis. + Assert.Equal(1 + FamilyRevolutionBuilder.Facets + 1, faces.Count); + Assert.Equal(1, faces.Count(key => key.Segment == 0)); + Assert.Equal(FamilyRevolutionBuilder.Facets, faces.Count(key => key.Segment == 1)); + Assert.Equal(1, faces.Count(key => key.Segment == 2)); + Assert.DoesNotContain(faces, key => key.Segment == 3); + } + + [Fact] + public void EveryFaceOfARevolutionFacesOutOfTheSolid() + { + var model = Model(SyntheticRevolution.Cylinder()); + var positions = Stored(model); + // The middle of the solid: the axis at half the height. + double[] middle = [0, 0, 1]; + + foreach (var face in Faces(model, positions)) + { + var corner = face.OuterVertices![0]; + Assert.True(face.Normal.Zip(corner.Zip(middle, (c, m) => c - m), (n, d) => n * d).Sum() > 0, + $"{string.Join(",", face.Normal)} at {string.Join(",", corner)}"); + } + } + + [Fact] + public void ACylinderFollowsItsRadiusAndItsHeight() + { + var model = Model(SyntheticRevolution.Cylinder()); + + Assert.Equal(Polygon(2) * 3, Volume(Faces(model, Solved(model, 2, 3))), 1e-9); + } + + [Fact] + public void AConeFrustumFollowsItsTwoRadiiAndItsHeight() + { + var model = Model(SyntheticRevolution.Frustum()); + + Assert.Equal(Polygon(1) * 2 / 3 + Polygon(0.5) * 2 / 3 + Math.Sqrt(Polygon(1) * Polygon(0.5)) * 2 / 3, + Volume(Faces(model, Stored(model))), 1e-9); + double bottom = Polygon(3), top = Polygon(1.5); + Assert.Equal((bottom + top + Math.Sqrt(bottom * top)) * 4 / 3, Volume(Faces(model, Solved(model, 3, 4, 1.5))), 1e-9); + } + + [Fact] + public void ARevolutionWithoutItsSketchPlaneInTheWayOfItsAxisIsRefused() + { + foreach (var (records, detail) in new[] + { + (SyntheticRevolution.Cylinder() with { Revolutions = [SyntheticRevolution.Turn() with { EndAngle = Math.PI }] }, + "sweep of 50"), + (SyntheticRevolution.Cylinder() with { Revolutions = [SyntheticRevolution.Turn() with { PlaneNormal = [1, 1, 0] }] }, + "sketch plane of 50"), + (SyntheticRevolution.Cylinder() with { Revolutions = [SyntheticRevolution.Turn() with { PlaneOrigin = [0, 3, 0] }] }, + "axis of 50"), + // An axis that runs along no axis of the plane of the sketch. + (SyntheticRevolution.Cylinder().WithLine(SyntheticRevolution.AxisLine, line => line with { End = [1, 0, 2] }), + "axis of 50"), + }) + { + var (model, refusal) = FamilyModelBuilder.Build(records); + + Assert.Null(model); + Assert.Equal("unsupported-construct", refusal!.Code); + Assert.Contains(detail, refusal.Detail); + } + } + + [Fact] + public void ACurvedLineOfTheProfileIsRefused() + { + var curved = SyntheticRevolution.Cylinder().WithLine(42, line => line with { IsStraight = false }); + + var (model, refusal) = FamilyModelBuilder.Build(curved); + + Assert.Null(model); + Assert.Equal("unrecognized-reference", refusal!.Code); + } + + [Fact] + public void AMaterialAndAVisibilityParameterAreCarried() + { + var model = Model(SyntheticRevolution.Cylinder() with + { + Associations = [new(50, -1002107, 200), new(50, -1006205, 201)], + }); + + var revolution = Assert.Single(model.Revolutions); + Assert.Equal((200L, 201L), (revolution.MaterialParameterId, revolution.VisibilityParameterId)); + } + + [Fact] + public void ADimensionThatLeavesTheProfileOnBothSidesOfTheAxisIsDegenerate() + { + var model = Model(SyntheticRevolution.Frustum()); + var revolution = Assert.Single(model.Revolutions); + + // A top radius of -0.5 puts the top of the slanted line across the axis. + double[] crossed = Solved(model, 1, 2, -0.5); + + Assert.False(FamilyRevolutionBuilder.Holds(revolution, crossed, Stored(model))); + Assert.Equal("degenerate-geometry", FamilyContourChecks.Check(model, crossed, new Dictionary())!.Code); + } + + // A loop of corners (distance from the axis, position along it) in the plane of a sketch square to the second axis, about + // the vertical through the origin. + private static (FamilyRevolution Revolution, double[] Positions) Outline(params (double D, double V)[] corners) + { + var positions = new List { 0, 0 }; + var vertices = new List(); + foreach (var (d, v) in corners) + { + positions.Add(d); + positions.Add(v); + vertices.Add(new(positions.Count - 2, 1, positions.Count - 1)); + } + return (new(7, [vertices], 2, 1, 0, 1, new Dictionary(), null, null), [.. positions]); + } + + [Theory] + [InlineData(true, 0, 0, 1, 0, 1, 2, 0, 2)] // a rectangle against the axis + [InlineData(true, 0, 0, 2, 0, 1, 3, 0, 3)] // a trapezoid with a slanted side + [InlineData(true, 0, 0, -2, 0, -2, 1, 0, 1)] // a rectangle on the other side of the axis + [InlineData(false, 1, 0, 2, 2, 2, 0, 1, 2)] // the sides cross + [InlineData(false, 1, 0, 3, 0, 3, 2, 2, 0)] // a corner on a side that is no neighbour + [InlineData(false, 1, 0, 1, 0, 1, 2, 2, 2)] // a side without a length + [InlineData(false, -1, 0, 1, 0, 1, 2, -1, 2)] // on both sides of the axis + [InlineData(false, 0, 0, 0, 1, 0, 2, 0, 3)] // on the axis + public void AProfileHoldsOnlyAsASimpleOutlineOnOneSideOfTheAxis(bool holds, double d0, double v0, double d1, double v1, + double d2, double v2, double d3, double v3) + { + var (revolution, positions) = Outline((d0, v0), (d1, v1), (d2, v2), (d3, v3)); + + Assert.Equal(holds, FamilyRevolutionBuilder.Holds(revolution, positions, positions)); + } + + [Fact] + public void TheStoredFacesOfARevolutionMatchWhateverWayTheFileCutsItsRoundSurfaces() + { + var model = Model(SyntheticRevolution.Cylinder()); + var revolution = Assert.Single(model.Revolutions); + var positions = Stored(model); + + // The discs as built, the side as a row of twice as many strips of radius 1 and height 0 to 2. + var stored = Faces(model, positions).Where(face => face.OuterVertices!.Count != 4).ToList(); + for (int strip = 0; strip < 2 * FamilyRevolutionBuilder.Facets; strip++) + { + double[] Round(int step, double z) => + [Math.Cos(Math.PI * step / FamilyRevolutionBuilder.Facets), Math.Sin(Math.PI * step / FamilyRevolutionBuilder.Facets), z]; + double middle = Math.PI * (strip + 0.5) / FamilyRevolutionBuilder.Facets; + stored.Add(new(new double[3], [Math.Cos(middle), Math.Sin(middle), 0]) + { + OuterVertices = [Round(strip, 0), Round(strip + 1, 0), Round(strip + 1, 2), Round(strip, 2)], + }); + } + + var matched = FamilyRevolutionBuilder.Match(revolution, positions, stored); + + Assert.NotNull(matched); + Assert.Equal(3, matched!.Count); + } + + [Theory] + [InlineData("vertex off the surface")] + [InlineData("surface without faces")] + [InlineData("circle not reached")] + [InlineData("material of a surface")] + [InlineData("face of no surface")] + public void StoredFacesThatAreNotTheSurfacesOfTheRevolutionDoNotMatch(string change) + { + var model = Model(SyntheticRevolution.Cylinder()); + var revolution = Assert.Single(model.Revolutions); + var positions = Stored(model); + var stored = Faces(model, positions); + var side = stored.Where(face => face.OuterVertices!.Count == 4).ToList(); + // The unchanged faces are the surfaces: what follows is a change that no longer is. + Assert.NotNull(FamilyRevolutionBuilder.Match(revolution, positions, stored)); + + switch (change) + { + case "vertex off the surface": side[0].OuterVertices![0][0] += 0.01; break; + case "surface without faces": stored.RemoveAll(side.Contains); break; + // The faces of the side stop half way up: the circle at the top of the side is reached by none. + case "circle not reached": + foreach (var corner in side.SelectMany(face => face.OuterVertices!).Where(corner => corner[2] > 1)) corner[2] = 1; + break; + case "material of a surface": side[1].RenderStyleId = 7; break; + case "face of no surface": + stored.Add(new(new double[3], [0, 0, 1]) + { + OuterVertices = [[0, 0, 5], [1, 0, 5], [1, 1, 5]], + }); + break; + } + + Assert.Null(FamilyRevolutionBuilder.Match(revolution, positions, stored)); + } + + // The cone sample stores the facets of one half of its side facing into the solid, the other half facing out: the way a + // stored face faces says nothing about the surface it is on. + [Fact] + public void AStoredFaceOfTheSideMatchesWhicheverWayItFaces() + { + var model = Model(SyntheticRevolution.Cylinder()); + var stored = Faces(model, Stored(model)); + foreach (var side in stored.Where(face => face.OuterVertices!.Count == 4).Where((_, index) => index % 2 == 0)) + side.Normal = [.. side.Normal.Select(component => -component)]; + + Assert.NotNull(FamilyRevolutionBuilder.Match(Assert.Single(model.Revolutions), Stored(model), stored)); + } + + // The file stores the caps of a circle facing inward, so a disc or a ring is a face of its surface whichever way it faces. + [Fact] + public void AFlatStoredFaceMatchesWhicheverWayItFaces() + { + var model = Model(SyntheticRevolution.Cylinder()); + var stored = Faces(model, Stored(model)); + foreach (var disc in stored.Where(face => face.OuterVertices!.Count != 4)) + disc.Normal = [.. disc.Normal.Select(component => -component)]; + + Assert.NotNull(FamilyRevolutionBuilder.Match(Assert.Single(model.Revolutions), Stored(model), stored)); + } + + // A face whose corners lie on two surfaces is a face of neither: two rings at one height that overlap. + [Fact] + public void AFaceThatFitsTwoSurfacesDoesNotMatch() + { + var model = Model(SyntheticRevolution.Cylinder()); + var revolution = Assert.Single(model.Revolutions); + var positions = Stored(model); + var loops = revolution.Loops.Concat(revolution.Loops).ToList(); + var doubled = revolution with { Loops = loops }; + var stored = Faces(model, positions); + + Assert.Null(FamilyRevolutionBuilder.Match(doubled, positions, stored)); + } + + // The material a parameter gives is the material of every stored face of the revolution. + [Fact] + public void TheStoredFacesOfARevolutionTakeTheMaterialOfItsParameter() + { + var model = Model(SyntheticRevolution.Cylinder()); + var revolution = Assert.Single(model.Revolutions); + var positions = Stored(model); + var stored = FamilyRevolutionBuilder.Faces(revolution, positions, _ => 7); + + Assert.NotNull(FamilyRevolutionBuilder.Match(revolution, positions, stored, 7)); + Assert.Null(FamilyRevolutionBuilder.Match(revolution, positions, stored, 8)); + Assert.Null(FamilyRevolutionBuilder.Match(revolution, positions, Faces(model, positions), 7)); + } + + // Whatever else refers to the plane a revolution is drawn on is a relation that is read or one that moves nothing. + [Fact] + public void ARecordOfAnUnknownClassThatRefersToTheSketchPlaneOfARevolutionIsRefused() + { + var records = SyntheticRevolution.Cylinder(); + + var (model, refusal) = FamilyModelBuilder.Build(records.Add(new FamilyReferrer(99, "SomeUnreadClass", "X.m_id", 3))); + + Assert.Null(model); + Assert.Equal("unrecognized-reference", refusal!.Code); + } + + private static double Volume(IEnumerable faces) + { + double volume = 0; + foreach (var face in faces) + foreach (var ring in new[] { face.OuterVertices! }.Concat(face.InnerVertices ?? [])) + { + // The vector area of the ring, twice, and a point of it: a sixth of their product is the part of the volume + // that the ring bounds with the origin. + double x = 0, y = 0, z = 0; + for (int i = 0; i < ring.Count; i++) + { + var (a, b) = (ring[i], ring[(i + 1) % ring.Count]); + x += (a[1] - b[1]) * (a[2] + b[2]); + y += (a[2] - b[2]) * (a[0] + b[0]); + z += (a[0] - b[0]) * (a[1] + b[1]); + } + volume += (ring[0][0] * x + ring[0][1] * y + ring[0][2] * z) / 6; + } + return volume; + } +} + +/// A cylinder of radius 1 and height 2 about the vertical through the origin, drawn in the plane of the sketch +/// through the origin square to the second axis (a rectangle of four lines and the axis line), held by reference planes, a +/// labelled radius and a labelled height; and the same with a top that is narrower than the bottom, a slanted side, and a +/// labelled top radius. +internal static class SyntheticRevolution +{ + private const long Radius = 100, Height = 101, TopRadius = 102; + public const int AxisLine = 45; + + public static FamilyRevolutionRecord Turn() => new(50, 40, 0, 2 * Math.PI, [0, 0, 0], [0, 1, 0], new(3, 0, -1), + [[new(41, false), new(42, false), new(43, false), new(44, false)]], AxisLine); + + public static FamilyRecords Cylinder() => Records(1, 1); + + public static FamilyRecords Frustum() => Records(1, 0.5); + + // Planes: 1 centre left/right, 2 right, 3 centre front/back, 4 level, 5 top, 6 top radius. Lines 41-44, counter-clockwise + // in the plane of the sketch seen along its normal, 45 the axis. + private static FamilyRecords Records(double bottom, double top) + { + bool slanted = top != bottom; + FamilyPlaneRecord[] planes = + [ + new(1, "RefPlane", 1, [0, 0, 0], [1, 0, 0]), new(2, "RefPlane", 12, [bottom, 0, 0], [1, 0, 0]), + new(3, "RefPlane", 4, [0, 0, 0], [0, 1, 0]), new(4, "Level", 0, [0, 0, 0], [0, 0, 1]), + new(5, "RefPlane", 8, [0, 0, 2], [0, 0, 1]), new(6, "RefPlane", 12, [top, 0, 0], [1, 0, 0]), + ]; + List dimensions = + [ + SyntheticFamily.Linear(20, 0, 8, [(1, 0, -1), (2, 0, -1)], [0], [Radius], [bottom]), + SyntheticFamily.Linear(21, 2, 8, [(4, 0, -1), (5, 0, -1)], [0], [Height], [2]), + SyntheticFamily.Alignment(30, 0, (1, 0, -1), (44, 0, -1)), SyntheticFamily.Alignment(31, 0, (1, 0, -1), (AxisLine, 0, -1)), + SyntheticFamily.Alignment(32, 2, (4, 0, -1), (41, 0, -1)), SyntheticFamily.Alignment(33, 2, (5, 0, -1), (43, 0, -1)), + SyntheticFamily.Alignment(34, 0, (2, 0, -1), slanted ? (41, 0, 1) : (42, 0, -1)), + ]; + if (slanted) + { + dimensions.Add(SyntheticFamily.Linear(22, 0, 8, [(1, 0, -1), (6, 0, -1)], [0], [TopRadius], [top])); + dimensions.Add(SyntheticFamily.Alignment(35, 0, (6, 0, -1), (43, 0, 0))); + } + FamilySketchLine[] lines = + [ + new(41, 40, true, [0, 0, 0], [bottom, 0, 0]), + slanted ? new(42, 40, true, [bottom, 0, 0], [top, 0, 2]) : new(42, 40, true, [bottom, 0, 0], [bottom, 0, 2]), + new(43, 40, true, [top, 0, 2], [0, 0, 2]), new(44, 40, true, [0, 0, 2], [0, 0, 0]), + new(AxisLine, 40, true, [0, 0, 0], [0, 0, 2], IsRevolutionAxis: true), + ]; + FamilySketchJoint[] joints = [new(41, 1, 42, 0), new(42, 1, 43, 0), new(43, 1, 44, 0), new(44, 1, 41, 0)]; + return new FamilyRecords(dimensions, lines, joints, + [new(40, "VarSketchPPConstrObj"), new(40, "VarSketchHorVerConstrObj")], planes, [], [], [], new HashSet(), [], + Revolutions: [Turn()]); + } +} diff --git a/tests/RvtIO.Tests/Families/FineCircularEdgesTests.cs b/tests/RvtIO.Tests/Families/FineCircularEdgesTests.cs new file mode 100644 index 00000000..a80498f7 --- /dev/null +++ b/tests/RvtIO.Tests/Families/FineCircularEdgesTests.cs @@ -0,0 +1,53 @@ +using RvtIO.Scene; +using Xunit; + +namespace RvtIO.Tests.Families; + +public sealed class FineCircularEdgesTests +{ + private static int Faces(string path, bool fine) => + RvtDocument.Open(path, new() { R22Layout = true, FineCircularEdges = fine }) + .RawData.Elements.Sum(element => element.Geometry?.Faces.Count ?? 0); + + [SkippableFact] + public void TheStoredPointsOfACircularEdgeGiveMoreFacesThanTheLowDetailSampling() + { + int plain = 0, fine = 0; + foreach (string path in FamilyFiles.All()) + { + int withOption = Faces(path, true); + // A circle is never given fewer points than the low detail level takes. + Assert.True(withOption >= Faces(path, false), path); + fine += withOption; + plain += Faces(path, false); + } + Assert.True(fine > plain); + } + + [SkippableFact] + public void TheOptionIsOffByDefault() + { + Assert.False(new RvtReaderOptions().FineCircularEdges); + Assert.False(new RvtSceneOptions().FineCircularEdges); + } + + private static int Triangles(string path, RvtSceneOptions? options) => + RvtSceneReader.Read(path, options).Document.Geometries.Sum(geometry => geometry.Indices.Count() / 3); + + [SkippableFact] + public void ASceneReadWithTheOptionDrawsMoreTrianglesAndWithoutItTheSameAsBefore() + { + int plain = 0, fine = 0; + foreach (string path in FamilyFiles.All()) + { + int none = Triangles(path, null); + // The option off is the default: the scene is the one of a read without options. + Assert.Equal(none, Triangles(path, new RvtSceneOptions { FineCircularEdges = false })); + int withOption = Triangles(path, new RvtSceneOptions { FineCircularEdges = true }); + Assert.True(withOption >= none, path); + plain += none; + fine += withOption; + } + Assert.True(fine > plain); + } +} diff --git a/tests/RvtIO.Tests/Families/NestedFamilyDocumentTests.cs b/tests/RvtIO.Tests/Families/NestedFamilyDocumentTests.cs new file mode 100644 index 00000000..e52856f4 --- /dev/null +++ b/tests/RvtIO.Tests/Families/NestedFamilyDocumentTests.cs @@ -0,0 +1,42 @@ +using OpenMcdf; +using RvtIO.Families; +using Xunit; + +namespace RvtIO.Tests.Families; + +/// A family loaded into a family file keeps its whole document in a block of the partitions other than 0, and the +/// records of the host are block 0: the reader can be asked for the document of the loaded family. +public class NestedFamilyDocumentTests +{ + // The cast-iron bend ADSK_ДетальЧугуннаяБезраструбная_Отвод loads the clamp families Norma Rapid and Kombi Grip. Kombi Grip + // Kralle is the loaded family whose document is block 2 (its Family record 8459142 is the owner of the document), with + // one extrusion, 8459688. + private const long KombiGripFamily = 8459142; + private const int KombiGripBlock = 2, KombiGripExtrusion = 8459688; + + [SkippableFact] + public void TheDocumentOfALoadedFamilyIsReadFromItsBlock() + { + string path = TestFiles.FindRelative("families/cast-iron-bend.rfa"); + var document = RvtDocument.Open(path, new RvtReaderOptions { R22Layout = true }); + using var root = RootStorage.OpenRead(path); + + var nested = FamilyRecordReader.Read(root, document.RawData, null, KombiGripFamily, null, KombiGripBlock); + + Assert.True(nested.Types is { Types.Count: > 0 }, nested.TypesError); + // Only the elements of this document: the elements of the other loaded families and the symbols of the host are not. + var fact = Assert.Single(nested.Elements); + Assert.Equal(KombiGripExtrusion, fact.ElementId); + Assert.Equal("ExtrusionElem", fact.ClassName); + Assert.True(fact.IsForm); + // Its own flags (0x603E) do not show it at the Fine detail level, so it is not a shape to recompute. + Assert.False(fact.ShownInFine); + var records = Assert.IsType(nested.Records); + Assert.NotEmpty(records.Lines); + Assert.Empty(records.Extrusions); + Assert.Empty(records.UnsupportedContent); + // The host stays what it was: the block 0 read of its own owner. + Assert.Empty(FamilyRecordReader.Read(root, document.RawData, null, document.FamilyOwnerId!.Value, null).Elements + .Where(fact => fact.ElementId == KombiGripExtrusion)); + } +} From ff6814e6c1f72cf9e211fd4f71efb2c92e90babd Mon Sep 17 00:00:00 2001 From: Mahach <79989386+mahach666@users.noreply.github.com> Date: Wed, 2 Dec 2026 12:03:52 +0300 Subject: [PATCH 03/14] Refuse a loop of two arcs whose other curve is no line of the sketch When an arc of a two-arc loop has an end the sketch holds at no angle, the loop is looked at for the circle it may complete, and the other curve of the loop was taken from the lines of the sketch before it was checked to be one. A damaged file whose other curve names a line that was not read threw a KeyNotFoundException out of the family model builder and through the read of the scene. Every curve of a loop is now checked to be a line of the sketch before any is looked at with the others, so such a file is refused as unrecognized-reference. --- src/RvtIO/Families/FamilyModelBuilder.cs | 5 ++++- tests/RvtIO.Tests/Families/FamilyArcTests.cs | 18 ++++++++++++++++++ 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/src/RvtIO/Families/FamilyModelBuilder.cs b/src/RvtIO/Families/FamilyModelBuilder.cs index ddbca804..84e85d41 100644 --- a/src/RvtIO/Families/FamilyModelBuilder.cs +++ b/src/RvtIO/Families/FamilyModelBuilder.cs @@ -148,11 +148,14 @@ private int CheckProfile(FamilyExtrusionRecord extrusion) bool arcs = loop.Any(key => extrusion.ProfileCurves.TryGetValue(key, out var curve) && _lines.TryGetValue(curve.LineId, out var line) && line.Arc != null); if (loop.Count < (arcs ? 2 : 3)) throw Unsupported($"profile of {extrusion.Id}"); + // Every curve of the loop is a line of the sketch before any is looked at with the others (a circle of two arcs). foreach (int key in loop) - { if (!extrusion.ProfileCurves.TryGetValue(key, out var curve) || !_lines.TryGetValue(curve.LineId, out var line) || line.SketchId != extrusion.SketchId) throw Unrecognized($"profile curve {key} of {extrusion.Id}"); + foreach (int key in loop) + { + var line = _lines[extrusion.ProfileCurves[key].LineId]; if (line.Arc != null) { Shape(line, axis); diff --git a/tests/RvtIO.Tests/Families/FamilyArcTests.cs b/tests/RvtIO.Tests/Families/FamilyArcTests.cs index f9b11757..cf667972 100644 --- a/tests/RvtIO.Tests/Families/FamilyArcTests.cs +++ b/tests/RvtIO.Tests/Families/FamilyArcTests.cs @@ -308,6 +308,24 @@ public void ATwoArcLoopOfOtherTurnsNeedsEveryEndHeld() AssertRefused(disc with { ArcEndAngles = Without(disc, (42, 1)) }, "unsupported-construct", "42"); } + // A damaged file: the other curve of a two-arc loop is a line that was not read. It is a refusal, not an exception, whichever + // curve of the loop is looked at first. + [Theory] + [InlineData(0)] + [InlineData(1)] + public void ALoopWhoseOtherCurveIsNoLineOfTheSketchIsRefusedAsUnrecognized(int missing) + { + var disc = SyntheticArcs.Disc(); + var damaged = disc.WithExtrusion(e => e with + { + ProfileCurves = new Dictionary { [0] = new(missing == 0 ? 99 : 41, false), [1] = new(missing == 1 ? 99 : 42, false) }, + }); + + // The arc that is read first has a free end, so that the loop is looked at for the circle it may complete. + AssertRefused(damaged with { ArcEndAngles = Without(disc, (missing == 0 ? 42 : 41, 1)) }, "unrecognized-reference", + $"profile curve {missing} of"); + } + [Fact] public void AnArcOfAFullTurnIsUnsupported() => AssertRefused(SyntheticArcs.Disc().WithLine(41, _ => SyntheticArcs.Arc(41, 40, [0, 0, 0], 1, 0, 2 * Math.PI)), From f67a7fdfa08d6da66b95701da5549d7cab871af2 Mon Sep 17 00:00:00 2001 From: Mahach <79989386+mahach666@users.noreply.github.com> Date: Wed, 2 Dec 2026 13:09:40 +0300 Subject: [PATCH 04/14] Compute a combination of forms of a family and check revolutions against Revit A combination of forms (joined solid geometry) whose members are extrusions and revolutions the family already computes is now computed in every type. It is drawn as the faces of its members, whole: where the members overlap, the faces inside the union stay, so the shell is a drawing of the union and not a trimmed closed one. For the saved type each member is checked on its own stored faces, since the file stores the members uncut; the joined shape, which the file stores trimmed and tessellated again, is checked only by its bounding box against that of the stored faces of its members. A combination without members, a form that two combinations hold, a member that is no extrusion or revolution of the family or that a family parameter shows or hides, and a parameter that drives the combination itself are refused. Nested combinations and a member that cuts keep the refusal unsupported-construct. The caps of a circle that has circular holes (a ring) face inward, as the file stores them, like those of a circle alone. A side alignment of two joined lines of a sketch that run along one axis is read as the relation the join already gives. The volume of a revolution at the stored positions is pinned to what Revit 2022 gives for the two cone families of the corpus. A valve whose revolutions the file stores with corners inside their surfaces, and whose flanges are nested family instances, is still refused. --- CHANGELOG.md | 11 +- docs/scene.md | 4 +- src/RvtIO/Families/FamilyData.cs | 4 +- src/RvtIO/Families/FamilyExtrusionBuilder.cs | 10 +- src/RvtIO/Families/FamilyModel.cs | 9 + src/RvtIO/Families/FamilyModelBuilder.cs | 66 +++-- src/RvtIO/Families/FamilyRecordReader.cs | 5 +- src/RvtIO/Families/FamilyRecords.cs | 5 +- src/RvtIO/Families/FamilyRelationReader.cs | 22 +- src/RvtIO/Families/FamilySavedState.cs | 29 +++ src/RvtIO/Meshes/ElementMeshes.cs | 61 +++-- .../RvtIO.Tests/Families/AquaFixValveTests.cs | 151 +++++++++++- tests/RvtIO.Tests/Families/FamilyArcTests.cs | 29 +++ .../Families/FamilyCombinationTests.cs | 233 ++++++++++++++++++ .../Families/FamilyModelBuilderTests.cs | 9 + .../Families/FamilyRevolutionTests.cs | 18 ++ 16 files changed, 610 insertions(+), 56 deletions(-) create mode 100644 tests/RvtIO.Tests/Families/FamilyCombinationTests.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index 3abf38c6..285b59f6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,8 +19,8 @@ API between minor releases. family, and `RvtSceneResult.FamilyTypes` gives each computed type its instances. Families of extrusions whose sides are straight lines along the family axes, or arcs and circles whose centre and radius the dimensions fix, are computed, and only when the computed saved type is what the file stores; any other type says why it is not computed, and no approximate shape - is given. A circle takes the faces the file stores for it: the caps of a loop of arcs alone face inward, as the file keeps - them, and a circle the file tessellates otherwise than evenly is refused as `saved-state-mismatch`. The circle of a hole + is given. A circle takes the faces the file stores for it: the caps of a loop of arcs alone, or of a circle with circular + holes (a ring), face inward, as the file keeps them, and a circle the file tessellates otherwise than evenly is refused as `saved-state-mismatch`. The circle of a hole is read whichever way round the file draws its halves. - A revolution of a whole turn about a line of its sketch along an axis of the sketch plane, whose profile is closed loops of straight lines (a cylinder, a ring, a cone, a stepped body, a slanted side) is computed like an extrusion: the surface of each @@ -29,6 +29,13 @@ API between minor releases. revolution are accepted when every corner of each lies on one surface of the revolution, every surface has faces that reach both its circles, and the faces of a surface share a material (the one its parameter gives), because the file cuts round surfaces as it likes; the way a stored face faces is not compared, since the file stores half of the side of a cone facing into the solid. +- A combination of forms (`FamilyGeomCombination`, joined solid geometry) of extrusions and revolutions of the family is + computed: it is drawn as the faces of its members, whole, so where the members overlap the faces inside the union stay and the + shell is not a trimmed one. The file stores the joined shape trimmed and tessellated again, so for the saved type each member is + checked on its own stored faces and the joined shape only by its bounding box against that of the stored faces of its members. + A combination without members, a form that two combinations hold, a member that is no extrusion or revolution of the family or + that a family parameter shows or hides, and a parameter that drives the combination itself are refused. A side alignment of two + joined lines of a sketch that run along one axis is read as the relation the join already gives. - `RvtReaderOptions.FineCircularEdges` and `RvtSceneOptions.FineCircularEdges` (off by default). A circle where a cylinder meets a plane is sampled by default as Revit's low detail level samples it, a polygon of about eight sides for a pipe; with the option the faces take the finer points the file stores, so the circle looks round. The faces of other surfaces do not change. diff --git a/docs/scene.md b/docs/scene.md index bd3a7263..69a5245c 100644 --- a/docs/scene.md +++ b/docs/scene.md @@ -112,7 +112,9 @@ does not hold; their ids follow those of the scene. A family is computed only when it is made of extrusions whose profiles are straight sides along the axes of the family and arcs whose ends lie on the axes through their centre, a whole number of quarter turns, and whose centre and radius the family fixes (a circle is two such arcs, or one closed arc), and of revolutions of a whole turn whose profile is closed loops of straight lines about a line of the sketch along an axis of -its plane (each surface is cut into 18 facets; a revolution of an arc, a part of a turn or a combination of forms is not computed), +its plane (each surface is cut into 18 facets; a revolution of an arc or a part of a turn is not computed), +and of combinations of such forms (drawn as the faces of their members, whole; the trimmed faces the file stores for the joined +shape are compared by their box only), placed by reference planes, dimensions, radius and diameter dimensions, alignments and joined sketch lines the reader recognizes, with no cuts, no visible nested family and no formula on a parameter that moves the shape, and only when what is computed for the saved type is what the file stores for it. A control icon (the arrow that flips a form) of the family diff --git a/src/RvtIO/Families/FamilyData.cs b/src/RvtIO/Families/FamilyData.cs index 9a46a00b..dd8fef19 100644 --- a/src/RvtIO/Families/FamilyData.cs +++ b/src/RvtIO/Families/FamilyData.cs @@ -46,6 +46,8 @@ internal sealed record FamilyPreparation(FamilyModel? Model, /// A nested instance that only views draw, such as an annotation or a detail item. /// All its geometry places other forms of the family, as a model group places its /// members. +/// The forms a combination joins, by element key; null for an element that is no combination. internal readonly record struct FamilyElementFacts(int ElementId, string ClassName, bool IsForm, bool HasGeometry, bool Cutting, bool? ShownInFine, bool? HiddenBySavedType, bool CombinationMember = false, bool MemberShownAlways = false, - bool CutByOwnStep = false, bool DrawnInViewsOnly = false, bool PlacesOwnFormsOnly = false); + bool CutByOwnStep = false, bool DrawnInViewsOnly = false, bool PlacesOwnFormsOnly = false, + IReadOnlyList? Members = null); diff --git a/src/RvtIO/Families/FamilyExtrusionBuilder.cs b/src/RvtIO/Families/FamilyExtrusionBuilder.cs index 1eb5e376..e850c4e5 100644 --- a/src/RvtIO/Families/FamilyExtrusionBuilder.cs +++ b/src/RvtIO/Families/FamilyExtrusionBuilder.cs @@ -47,10 +47,12 @@ GeoFace Face(List outer, double[] normal, FamilyFaceKey key) => var holes = Enumerable.Range(0, loops.Count) .Where(hole => inside[loop, hole] && depth[hole] == depth[loop] + 1).ToList(); // The file stores the caps of a loop of arcs alone, a circle, facing inward (every one of the 17 such extrusions of - // the corpus, whichever way the circle is drawn), and the caps of the other loops facing outward. A loop of arcs - // with a hole, or a loop of arcs and lines, is not measured: it takes the outward way, and a family whose - // stored caps differ is refused by the saved-state check. - bool circle = holes.Count == 0 && extrusion.Arcs?[loop].All(arc => arc != null) == true; + // the corpus, whichever way the circle is drawn; and the ring of the AquaFix valve, a circle with a circle for its + // hole), and the caps of the other loops facing outward. A loop of arcs with a hole of lines, or a loop of arcs and + // lines, is not measured: it takes the outward way, and a family whose stored caps differ is refused by the + // saved-state check. + bool OfArcs(int of) => extrusion.Arcs?[of].All(arc => arc != null) == true; + bool circle = OfArcs(loop) && holes.All(OfArcs); foreach (var (kind, along, way) in new[] { (FamilyFaceKind.StartCap, start, -1), (FamilyFaceKind.EndCap, end, 1) }) { diff --git a/src/RvtIO/Families/FamilyModel.cs b/src/RvtIO/Families/FamilyModel.cs index a41fc61c..a8f5ceca 100644 --- a/src/RvtIO/Families/FamilyModel.cs +++ b/src/RvtIO/Families/FamilyModel.cs @@ -50,11 +50,20 @@ internal sealed record FamilyRevolution(int ElementId, IReadOnlyList Materials, long? MaterialParameterId, long? VisibilityParameterId); +/// +/// A combination of forms: the shape of the family is that of the extrusions and revolutions Members names, which are +/// all solid and always shown, and which no other combination holds. Its faces are those of its members, whole: the union +/// is not trimmed where they overlap. +/// +internal sealed record FamilyCombination(int ElementId, IReadOnlyList Members); + /// The forms of a family and the relations that place them. internal sealed record FamilyModel(IReadOnlyList Variables, IReadOnlyList Equations, IReadOnlyList Extrusions) { public IReadOnlyList Revolutions { get; init; } = []; + + public IReadOnlyList Combinations { get; init; } = []; } /// The value of every variable for one type, or why there is none. diff --git a/src/RvtIO/Families/FamilyModelBuilder.cs b/src/RvtIO/Families/FamilyModelBuilder.cs index 84e85d41..f05ebf6b 100644 --- a/src/RvtIO/Families/FamilyModelBuilder.cs +++ b/src/RvtIO/Families/FamilyModelBuilder.cs @@ -84,6 +84,8 @@ private sealed record Equation(List<(int Node, int Coefficient)> Terms, long? Pa records.Extrusions.ToDictionary(extrusion => extrusion.Id); private readonly Dictionary _revolutions = (records.Revolutions ?? []).ToDictionary(revolution => revolution.Id); + private readonly Dictionary _combinations = + (records.Combinations ?? []).ToDictionary(combination => combination.Id); // Lines of the profile of a revolution that run along no axis: their ends are places the joins of the profile fix. private HashSet _slanted = []; private readonly List _nodes = []; @@ -101,6 +103,7 @@ public FamilyModel Build() throw Unsupported(string.Join(", ", records.UnsupportedContent.Distinct())); var axes = _extrusions.Values.ToDictionary(extrusion => extrusion.Id, CheckProfile); var turns = _revolutions.Values.ToDictionary(revolution => revolution.Id, CheckRevolution); + CheckCombinations(); _slanted = _revolutions.Values.SelectMany(revolution => revolution.Loops.SelectMany(loop => loop)) .Select(curve => _lines[curve.LineId]).Where(line => Direction(line) == null).Select(line => line.Id).ToHashSet(); var arcs = _extrusions.Values.SelectMany(e => e.Loops.SelectMany(loop => loop) @@ -563,10 +566,33 @@ private void CheckConstraints(HashSet modelLines) } } + /// A combination joins forms of the model that are always shown and that no other combination holds. + private void CheckCombinations() + { + var held = new HashSet(); + foreach (var combination in _combinations.Values) + { + if (combination.Members.Count == 0) throw Unsupported($"combination {combination.Id}"); + foreach (int member in combination.Members) + { + if (!_extrusions.ContainsKey(member) && !_revolutions.ContainsKey(member)) + throw Unrecognized($"member {member} of {combination.Id}"); + if (!held.Add(member)) throw Unsupported($"member {member} of {combination.Id}"); + // What Revit shows of the joined shape while a member is hidden is not recorded. + if (records.Associations.Any(a => a.ElementId == member + && a.ElementPropertyId == (long)BuiltInParameter.IS_VISIBLE_PARAM)) + throw Unsupported($"visibility of member {member}"); + } + } + } + private void CheckAssociations(HashSet modelLines) { foreach (var association in records.Associations) { + // The shape of a combination is that of its members: nothing else of it is read. + if (_combinations.ContainsKey(association.ElementId)) + throw Unrecognized($"association {association.ElementPropertyId} of element {association.ElementId}"); bool onExtrusion = _extrusions.ContainsKey(association.ElementId); bool onRevolution = _revolutions.ContainsKey(association.ElementId); if (!onExtrusion && !onRevolution && !modelLines.Contains(association.ElementId) @@ -583,7 +609,8 @@ or BuiltInParameter.EXTRUSION_START_PARAM or BuiltInParameter.EXTRUSION_END_PARA // Every record that refers to what takes part is either a relation read here or one that moves nothing. private void CheckReferrers(HashSet modelLines) { - var model = _extrusions.Keys.Concat(_revolutions.Keys).Concat(_extrusions.Values.Select(e => e.SketchId)).Concat(modelLines) + var model = _extrusions.Keys.Concat(_revolutions.Keys).Concat(_combinations.Keys) + .Concat(_extrusions.Values.Select(e => e.SketchId)).Concat(modelLines) .Concat(modelLines.Select(id => _lines[id].SketchId)) .Concat(records.Dimensions.SelectMany(d => d.References).Select(r => r.ElementId)) .Concat(_extrusions.Values.Where(e => e.PlaneHost != null).Select(e => e.PlaneHost!.Value.ElementId)) @@ -598,19 +625,26 @@ private void CheckReferrers(HashSet modelLines) // (extents, sun settings) only look at the form; a filled region is a drawing of the views that stands on its // own sketch; a host, its openings and the connectors, warnings and imports on it have their own level or cut // the host, and move none of the family's forms. - bool known = referrer.ClassName switch - { - "LinearDimString" or "Alignment" or "RadialDim" or "VarSketch" or "ExtrusionElem" or "RevolutionElem" or "SketchPlane" => true, - "CurveElem" => !modelLines.Contains(referrer.RecordId) || referrer.Field is - "CurveElemDriver.EndInfo.m_elemId" or "CurveElem.m_sketchPlaneId" - or "SketchMembership.GroupMembership.m_groupId" - // The side of a line records the ends that lie on it; each must be the join of that end. - || referrer.Field == "CDJoinInfo.EndInfo.m_elemId" && records.Joints.Any(j => - j.LineId == referrer.TargetId && j.OtherLineId == referrer.RecordId && j.OtherEnd == -1), - "ExtentElem" or "DBViewPlan" or "DBViewSection" or "DBView3d" or "SunAndShadowSettings" or "Opening" - or "ComplexOpening" or "ConnectorElem" or "PostedWarningElem" or "ImportInstance" or "FilledRegion" => true, - var name => TfClassNames.IsSubclassOf(name, "HostObj"), - }; + // A combination refers to the forms it joins, and to nothing else that takes part. + bool known = _combinations.TryGetValue(referrer.RecordId, out var joined) ? joined.Members.Contains(referrer.TargetId) + : referrer.ClassName switch + { + "LinearDimString" or "Alignment" or "RadialDim" or "VarSketch" or "ExtrusionElem" or "RevolutionElem" or "SketchPlane" => true, + "CurveElem" => !modelLines.Contains(referrer.RecordId) || referrer.Field is + "CurveElemDriver.EndInfo.m_elemId" or "CurveElem.m_sketchPlaneId" + or "SketchMembership.GroupMembership.m_groupId" + // The side of a line records the ends that lie on it; each must be the join of that end. + || referrer.Field == "CDJoinInfo.EndInfo.m_elemId" && records.Joints.Any(j => + j.LineId == referrer.TargetId && j.OtherLineId == referrer.RecordId && j.OtherEnd == -1) + // Two lines that keep one axis and meet at an end are collinear: aligning their sides moves nothing. + || referrer.Field == "CurveElemDriver.std::pair< ElementId, SideAlignment >.first" + && records.Joints.Any(j => j.LineId == referrer.RecordId && j.OtherLineId == referrer.TargetId && j.OtherEnd >= 0) + && _lines.TryGetValue(referrer.RecordId, out var side) && Direction(side) is int along + && _lines.TryGetValue(referrer.TargetId, out var next) && Direction(next) == along, + "ExtentElem" or "DBViewPlan" or "DBViewSection" or "DBView3d" or "SunAndShadowSettings" or "Opening" + or "ComplexOpening" or "ConnectorElem" or "PostedWarningElem" or "ImportInstance" or "FilledRegion" => true, + var name => TfClassNames.IsSubclassOf(name, "HostObj"), + }; if (!known) throw Unrecognized($"{referrer.ClassName} {referrer.RecordId}"); } } @@ -832,7 +866,9 @@ int Variable(int node) new Dictionary(), BoundOf(revolution.Id, BuiltInParameter.MATERIAL_ID_PARAM), BoundOf(revolution.Id, BuiltInParameter.IS_VISIBLE_PARAM)); }).ToList(); - return new(variables, equations, extrusions) { Revolutions = revolutions }; + var combinations = (records.Combinations ?? []) + .Select(combination => new FamilyCombination(combination.Id, [.. combination.Members])).ToList(); + return new(variables, equations, extrusions) { Revolutions = revolutions, Combinations = combinations }; } /// The stored materials by the faces of the model, whose start cap is the lower one. diff --git a/src/RvtIO/Families/FamilyRecordReader.cs b/src/RvtIO/Families/FamilyRecordReader.cs index 64d2f8c4..a28403ec 100644 --- a/src/RvtIO/Families/FamilyRecordReader.cs +++ b/src/RvtIO/Families/FamilyRecordReader.cs @@ -55,11 +55,14 @@ internal static FamilyData Read(RootStorage root, RevitFileInfo info, ElementIdM bool combined = memberships.ContainsKey(element.Id); // A member whose combination was not read would be left out without the shape that replaces it. if (record.IsMember && !combined) shown = null; + // A combination that lists a member this file has no element for joins more than its members say. + if (record.IsCombination && record.Members.Any(id => Key(ids, id) is null)) shown = null; facts.Add(new(element.Id, record.ClassName, record.IsForm, hasGeometry, record.Cutting, shown, hidden, combined, combined && record.MemberShownAlways, record.CutByOwnStep, FamilyRules.IsDrawnInViewsOnly(record.ClassName, element.Category), FamilyRules.PlacesOnlyForms(element.Id, Body(element), - id => own.TryGetValue(id, out var placed) && placed.IsForm))); + id => own.TryGetValue(id, out var placed) && placed.IsForm), + record.IsCombination ? membersOf[element.Id].ToArray() : null)); continue; } // The content of a nested family names that family: it is not content of this one. diff --git a/src/RvtIO/Families/FamilyRecords.cs b/src/RvtIO/Families/FamilyRecords.cs index 2d79b622..5d04dfe1 100644 --- a/src/RvtIO/Families/FamilyRecords.cs +++ b/src/RvtIO/Families/FamilyRecords.cs @@ -65,6 +65,9 @@ internal sealed record FamilyExtrusionRecord(int Id, int SketchId, double Start, internal sealed record FamilyRevolutionRecord(int Id, int SketchId, double StartAngle, double EndAngle, double[] PlaneOrigin, double[] PlaneNormal, FamilyReference? PlaneHost, IReadOnlyList> Loops, int AxisLineId); +/// A combination of forms ("Joined Solid Geometry"): the solid forms it joins into one shape. +internal sealed record FamilyCombinationRecord(int Id, IReadOnlyList Members); + /// A field of a record of the family that refers to another element. internal sealed record FamilyReferrer(int RecordId, string ClassName, string Field, int TargetId); @@ -81,4 +84,4 @@ internal sealed record FamilyRecords(IReadOnlyList Dimens IReadOnlyList Associations, IReadOnlySet FormulaParameterIds, IReadOnlyList UnsupportedContent, IReadOnlyList? RadialDimensions = null, IReadOnlyList? ArcEndAngles = null, IReadOnlySet? ControlIconIds = null, - IReadOnlyList? Revolutions = null); + IReadOnlyList? Revolutions = null, IReadOnlyList? Combinations = null); diff --git a/src/RvtIO/Families/FamilyRelationReader.cs b/src/RvtIO/Families/FamilyRelationReader.cs index f8e08971..e56ad6b1 100644 --- a/src/RvtIO/Families/FamilyRelationReader.cs +++ b/src/RvtIO/Families/FamilyRelationReader.cs @@ -189,7 +189,8 @@ private sealed class Reader(RootStorage root, IReadOnlyDictionary if (familyBody == null) return null; var (driven, formulas) = Family(schema, entities, familyBody); - AddShownContent(facts); + var factsById = facts.ToDictionary(fact => fact.ElementId); + AddShownContent(facts, factsById); var lines = new List(); var joints = new List(); @@ -224,6 +225,8 @@ private sealed class Reader(RootStorage root, IReadOnlyDictionary } var byId = lines.ToDictionary(line => line.Id); + var combinations = facts.Where(fact => IsJoinedShape(fact, factsById)) + .Select(fact => new FamilyCombinationRecord(fact.ElementId, fact.Members!)).ToList(); var extrusions = new List(); var revolutions = new List(); foreach (var fact in facts.Where(IsRecomputed)) @@ -239,7 +242,7 @@ private sealed class Reader(RootStorage root, IReadOnlyDictionary return new(dimensions, lines, joints, constraints, planes, extrusions, [.. referrers], associations, formulas, _unsupported, radials, angles, _own.Values.Where(record => record.ClassName == "ControlIconElem").Select(record => record.Key).ToHashSet(), - revolutions); + revolutions, combinations); } private static bool Holds(List? arguments, int reference) => @@ -293,18 +296,25 @@ private static bool Holds(List? arguments, int reference) => } /// An extrusion or a revolution whose faces are computed: a solid one the family shows in a 3D view at the - /// Fine detail level, in some type or in all. + /// Fine detail level, in some type or in all, on its own or as a member of a combination. private static bool IsRecomputed(FamilyElementFacts fact) => - fact is { ClassName: "ExtrusionElem" or "RevolutionElem", IsForm: true, Cutting: false, ShownInFine: true, CombinationMember: false, + fact is { ClassName: "ExtrusionElem" or "RevolutionElem", IsForm: true, Cutting: false, ShownInFine: true, DrawnInViewsOnly: false, CutByOwnStep: false }; + /// A combination whose faces are those of its members: it is shown, has no cut of its own, is no member of + /// another, and joins solid forms that are all recomputed. + private static bool IsJoinedShape(FamilyElementFacts fact, IReadOnlyDictionary byId) => + fact is { Members: { Count: > 0 } members, IsForm: true, Cutting: false, ShownInFine: true, CombinationMember: false, + DrawnInViewsOnly: false, CutByOwnStep: false } + && members.All(member => byId.TryGetValue(member, out var form) && IsRecomputed(form)); + // Everything else that is shown, in this type or in another, cannot be computed. - private void AddShownContent(IReadOnlyList facts) + private void AddShownContent(IReadOnlyList facts, IReadOnlyDictionary byId) { foreach (var fact in facts) { if (!(fact.IsForm || fact.HasGeometry) || FamilyRules.IsNeverShown(fact.ClassName) - || fact.DrawnInViewsOnly || fact.PlacesOwnFormsOnly || IsRecomputed(fact)) continue; + || fact.DrawnInViewsOnly || fact.PlacesOwnFormsOnly || IsRecomputed(fact) || IsJoinedShape(fact, byId)) continue; if (fact.CutByOwnStep) _unsupported.Add($"cut of {fact.ElementId}"); // A void is not drawn by itself. else if (!fact.Cutting && (fact.ShownInFine != false || fact.CombinationMember)) diff --git a/src/RvtIO/Families/FamilySavedState.cs b/src/RvtIO/Families/FamilySavedState.cs index 63dd007f..8740a2c7 100644 --- a/src/RvtIO/Families/FamilySavedState.cs +++ b/src/RvtIO/Families/FamilySavedState.cs @@ -69,9 +69,38 @@ internal static (Dictionary<(int ElementId, FamilyFaceKey Face), GeoFace>? Faces return Mismatch($"element {revolution.ElementId}"); foreach (var (key, face) in surfaces) matched.Add((revolution.ElementId, key), face); } + // Revit stores the joined shape trimmed where its members overlap, and cuts a curved face of it again into facets of its + // own: its faces are not those of the members. What is compared is the box of the shape, with the box of the members. + foreach (var combination in model.Combinations) + if (!stored.TryGetValue(combination.ElementId, out var joined) + || !SameBox(joined, combination.Members.SelectMany(member => stored[member]))) + return Mismatch($"element {combination.ElementId}"); return (matched, null); } + /// Whether two sets of faces have the same box, within the tolerance; no box is the same as any. + private static bool SameBox(IEnumerable a, IEnumerable b) + { + static double[]? Box(IEnumerable faces) + { + double[]? box = null; + foreach (var corner in faces.SelectMany(face => face.OuterVertices ?? [])) + { + if (corner.Length != 3) return null; + box ??= [.. corner, .. corner]; + for (int axis = 0; axis < 3; axis++) + { + box[axis] = Math.Min(box[axis], corner[axis]); + box[3 + axis] = Math.Max(box[3 + axis], corner[axis]); + } + } + return box; + } + + var (first, second) = (Box(a), Box(b)); + return first != null && second != null && first.Zip(second).All(pair => Math.Abs(pair.First - pair.Second) <= Tolerance); + } + private static bool Same(GeoFace built, GeoFace stored) { // No material is stored as nothing or as an id that is not one. diff --git a/src/RvtIO/Meshes/ElementMeshes.cs b/src/RvtIO/Meshes/ElementMeshes.cs index 084d0ea8..bbb1ba35 100644 --- a/src/RvtIO/Meshes/ElementMeshes.cs +++ b/src/RvtIO/Meshes/ElementMeshes.cs @@ -240,34 +240,42 @@ public static RvtFamilyTypeMeshes ComputeFamilyType(RvtDocument document, int ty var material = MaterialIn(values); var built = shown.Extrusions.ToDictionary(extrusion => extrusion.ElementId); var turned = shown.Revolutions.ToDictionary(revolution => revolution.ElementId); + var joined = shown.Combinations.ToDictionary(combination => combination.ElementId); var elements = new List(); foreach (int id in prepared.Elements) { - if (!built.TryGetValue(id, out var extrusion) && !turned.ContainsKey(id)) + joined.TryGetValue(id, out var combination); + if (combination == null && !built.ContainsKey(id) && !turned.ContainsKey(id)) { elements.Add(new ElementMesh { ElementId = id, Coverage = MeshCoverage.Complete }); continue; } - var keys = new List(); - var faces = extrusion != null - ? FamilyExtrusionBuilder.Faces(extrusion, positions, key => - { - keys.Add(key); - return material(extrusion, key); - }) - : FamilyRevolutionBuilder.Faces(turned[id], positions, key => - { - keys.Add(key); - return turned[id].MaterialParameterId is long finish ? values.TryGetValue(finish, out double chosen) ? (int)chosen : 0 - // No material is stored as nothing or as an id that is not one. - : prepared.Faces!.TryGetValue((id, key), out var own) ? Math.Max(own.RenderStyleId ?? 0, 0) : 0; - }); - foreach (var (face, key) in faces.Zip(keys)) + // A combination is drawn as the faces of its members, whole: they are always shown, and the model has them all. + var faces = new List(); + foreach (int part in combination?.Members ?? [id]) { - if (!prepared.Faces!.TryGetValue((id, key), out var stored)) return Refused("degenerate-geometry", id); - // What gives a face without a material of its own one is that of the stored face it is computed for. - face.GeometryStyle = stored.GeometryStyle; - face.NestedRenderStyleId = stored.NestedRenderStyleId; + var keys = new List(); + var own = built.TryGetValue(part, out var extrusion) + ? FamilyExtrusionBuilder.Faces(extrusion, positions, key => + { + keys.Add(key); + return material(extrusion, key); + }) + : FamilyRevolutionBuilder.Faces(turned[part], positions, key => + { + keys.Add(key); + return turned[part].MaterialParameterId is long finish ? values.TryGetValue(finish, out double chosen) ? (int)chosen : 0 + // No material is stored as nothing or as an id that is not one. + : prepared.Faces!.TryGetValue((part, key), out var held) ? Math.Max(held.RenderStyleId ?? 0, 0) : 0; + }); + foreach (var (face, key) in own.Zip(keys)) + { + if (!prepared.Faces!.TryGetValue((part, key), out var stored)) return Refused("degenerate-geometry", part); + // What gives a face without a material of its own one is that of the stored face it is computed for. + face.GeometryStyle = stored.GeometryStyle; + face.NestedRenderStyleId = stored.NestedRenderStyleId; + } + faces.AddRange(own); } var (meshes, failed) = Triangulate(faces, face => MaterialOf(document, face)); if (failed > 0) return Refused("degenerate-geometry", id); @@ -287,16 +295,20 @@ private static FamilyPreparation PrepareFamily(RvtDocument document, FamilyData var (model, refusal) = FamilyModelBuilder.Build(records); if (model == null) return No(refusal!.Code, refusal.Detail); - // The forms of the model are those the saved type lists, and its values show and hide them as the file does. + // The forms of the model are those the saved type lists, and its values show and hide them as the file does. The members + // of a combination are not listed: the combination is. var saved = ValuesOf(types.Types[types.CurrentIndex]); + var joined = model.Combinations.SelectMany(combination => combination.Members).ToHashSet(); if (!listed.Select(item => item.Element.Id).Order() - .SequenceEqual(model.Extrusions.Select(e => e.ElementId).Concat(model.Revolutions.Select(r => r.ElementId)).Order()) + .SequenceEqual(model.Extrusions.Select(e => e.ElementId).Concat(model.Revolutions.Select(r => r.ElementId)) + .Where(id => !joined.Contains(id)).Concat(model.Combinations.Select(combination => combination.ElementId)).Order()) || model.Extrusions.Any(extrusion => IsShown(extrusion.VisibilityParameterId, saved) == hidden.Contains(extrusion.ElementId)) || model.Revolutions.Any(revolution => IsShown(revolution.VisibilityParameterId, saved) == hidden.Contains(revolution.ElementId))) return No("saved-state-mismatch", "the forms of the saved type"); var storedFaces = new Dictionary>(); - foreach (var (element, body) in listed) + foreach (var (element, body) in listed.Concat(document.RawData.Elements + .Where(element => !element.IsBlockOnly && joined.Contains(element.Id)).Select(Held))) { // Faces the file holds only in part cannot be compared. if (body == null || body.PlacedSymbolBox || body.UnresolvedSymbol || body.UntriangulatedFaces > 0 @@ -309,6 +321,9 @@ private static FamilyPreparation PrepareFamily(RvtDocument document, FamilyData : new(model, matched, listed.Select(item => item.Element.Id).ToArray(), null); } + private static (Element Element, GeometryData? Body) Held(Element element) => + (element, element.SerializedComputedSymbolGeometry ?? element.Geometry); + /// The numbers of a type by parameter: lengths and other measures, yes/no as 1 or 0, and element keys. private static Dictionary ValuesOf(RvtFamilyType type) { diff --git a/tests/RvtIO.Tests/Families/AquaFixValveTests.cs b/tests/RvtIO.Tests/Families/AquaFixValveTests.cs index 8cd73bc6..a734265c 100644 --- a/tests/RvtIO.Tests/Families/AquaFixValveTests.cs +++ b/tests/RvtIO.Tests/Families/AquaFixValveTests.cs @@ -1,4 +1,6 @@ using RvtIO.Families; +using RvtIO.Meshes; +using RvtIO.Model; using Xunit; namespace RvtIO.Tests.Families; @@ -17,8 +19,7 @@ public void TheRevolutionOfTheBodyIsReadWithItsSlantedLine() { var records = Records(); - var revolution = Assert.Single(records.Revolutions!); - Assert.Equal(10164308, revolution.Id); + var revolution = Assert.Single(records.Revolutions!, item => item.Id == 10164308); Assert.Equal(10164318, revolution.AxisLineId); Assert.Equal(2 * Math.PI, revolution.EndAngle - revolution.StartAngle, 1e-9); var loop = Assert.Single(revolution.Loops); @@ -42,4 +43,150 @@ public void TheRingExtrusionIsReadWithItsHoleAsTwoHalvesOfItsCircle() .Select(key => records.Lines.Single(line => line.Id == ring.ProfileCurves[key].LineId).CircleId).Distinct().Single()).ToList(); Assert.Equal([10164277, 10164280], circles.Select(circle => circle!.Value)); } + + // The stem with its rim, a revolution, and the bar across the rim, an extrusion, are joined into one shape. + [SkippableFact] + public void TheCombinationOfTheStemTheRimAndTheBarIsReadWithItsMembers() + { + var records = Records(); + + var combination = Assert.Single(records.Combinations!); + Assert.Equal(10164354, combination.Id); + Assert.Equal([10164322, 10164350], combination.Members.Order()); + Assert.Contains(records.Revolutions!, revolution => revolution.Id == 10164322); + Assert.Contains(records.Extrusions, extrusion => extrusion.Id == 10164350); + } + + // The valve with its four flanges taken away from what the file says of it: what the family computes of all the rest. + private static readonly int[] Flanges = [10164284, 10164292, 10164298, 10164299]; + + private static RvtDocument WithoutFlanges() + { + var document = RvtDocument.Open(TestFiles.FindRelative("families/aquafix-valve.rfa"), new RvtReaderOptions { R22Layout = true }); + var family = document.RawData.Family!; + document.RawData.Family = new FamilyData + { + Elements = [.. family.Elements.Where(facts => !Flanges.Contains(facts.ElementId))], + Types = family.Types, TypesError = family.TypesError, + Records = family.Records! with + { + // What places the flanges: four alignments of a face of each to a reference plane, and the line (10164399) that + // turns a work plane, with its sketch. Two more alignments (10164355, 10164372) hold a face of the combination. + Dimensions = [.. family.Records!.Dimensions.Where(d => !d.References.Any(r => Flanges.Contains(r.ElementId) || r.ElementId == 10164354 || r.ElementId == 10164399))], + Constraints = [.. family.Records.Constraints.Where(constraint => constraint.SketchId != 10164398)], + Referrers = [.. family.Records.Referrers.Where(referrer => !Flanges.Contains(referrer.RecordId) && referrer.RecordId != 10164402)], + // Five parameters of the valve are given by formulas; the values its types store for them are taken as they are. + FormulaParameterIds = new HashSet(), + UnsupportedContent = [.. family.Records.UnsupportedContent.Where(entry => !Flanges.Any(id => entry.EndsWith(" " + id)))], + }, + }; + return document; + } + + // The family type the file was saved at, «Ду=80». + private const int SavedType = 1; + + private static (FamilyModel Model, double[] Positions) Solved(string typeName) + { + var family = WithoutFlanges().RawData.Family!; + var (model, refusal) = FamilyModelBuilder.Build(family.Records!); + Assert.Null(refusal); + var type = family.Types!.Types.Single(candidate => candidate.Name == typeName); + var values = new Dictionary(); + foreach (var parameter in type.Parameters) + if (parameter.Value is double real) values[parameter.Id] = real; + else if (parameter.Value is int whole) values[parameter.Id] = whole; + var solution = FamilySolver.Solve(model!, values); + Assert.Null(solution.Refusal); + return (model!, solution.Positions!); + } + + private const double Millimetre = 1 / 304.8; + + // Revit 2022 opened the valve on 2026-12-02 and gave, for each of its 14 types, the volume of the revolution of the body (10164308) + // and of the ring (10164267), in mm3. Revit lists the types in an order of its own; the types are named here by what the volumes + // and the box of the combination below say of them, three quantities that agree on all 14. The sizes solved from the values the + // file stores for a type give the volumes Revit gives: the ring to 1e-4 of them (5.2e-5 at most), the body to 1e-3 (7.8e-4 at most). What is left of + // the body is not explained; five parameters of the valve are given by formulas, which Revit computes again and the file stores the values of. + [SkippableTheory] + [InlineData("Ду=100", 2299298.2, 802199)] + [InlineData("Ду=80", 1777020.7, 624267.7)] + [InlineData("Ду=300", 9040708.9, 3175622.4)] + [InlineData("Ду=125", 2713790.1, 1032906.6)] + [InlineData("Ду=250", 7125858.2, 2469174.6)] + [InlineData("Ду=600", 36099331.9, 8997908.2)] + [InlineData("Ду=150", 3540699.4, 1282462.9)] + [InlineData("Ду=50", 1189951.1, 350585.1)] + [InlineData("Ду=450", 19303709.4, 5747482.9)] + [InlineData("Ду=200", 4953679.7, 1838121.4)] + [InlineData("Ду=500", 25978657.1, 6755673.7)] + [InlineData("Ду=65", 1480374.7, 493458)] + [InlineData("Ду=400", 14533062, 4814761.1)] + [InlineData("Ду=350", 12026178.5, 3957855.8)] + public void TheBodyAndTheRingOfTheValveHaveTheVolumeRevitGivesInEveryType(string type, double body, double ring) + { + var (model, positions) = Solved(type); + + // The body turns a loop of straight lines: by Pappus, the volume is that of the area of the loop turned about its centroid. + var loop = Assert.Single(FamilyRevolutionBuilder.Profiles(model.Revolutions.Single(item => item.ElementId == 10164308), positions)); + double sum = 0; + for (int i = 0; i < loop.Length; i++) + { + var (a, b) = (loop[i], loop[(i + 1) % loop.Length]); + sum += (Math.Abs(a.D) + Math.Abs(b.D)) * (Math.Abs(a.D) * b.V - Math.Abs(b.D) * a.V); + } + Assert.Equal(body, Math.PI / 3 * Math.Abs(sum) / Math.Pow(Millimetre, 3), body * 1e-3); + + // The ring is a cylinder with a hole: the length of the extrusion times the area between its circles. + var extrusion = model.Extrusions.Single(item => item.ElementId == 10164267); + double outer = positions[extrusion.Arcs![0][0]!.Value.Radius], inner = positions[extrusion.Arcs[1][0]!.Value.Radius]; + double length = Math.Abs(positions[extrusion.End] - positions[extrusion.Start]); + Assert.Equal(ring, Math.PI * length * (outer * outer - inner * inner) / Math.Pow(Millimetre, 3), ring * 1e-4); + } + + // The box of the combination of the stem, the rim and the bar, in the two types where Revit's bar sits where the file puts it + // (in the others the bar follows the rim, and the alignments that say so hold a face of the combination, which is not read) and + // whose rim Revit cuts, as here, into 18 facets: half the width along x and along y, and the top. + [SkippableTheory] + [InlineData("Ду=100", 101, 99.466, 340)] + [InlineData("Ду=80", 97.5, 96.019, 290)] + public void TheBoxOfTheCombinationOfTheValveIsTheBoxRevitGives(string type, double halfX, double halfY, double top) + { + var (model, positions) = Solved(type); + + var combination = Assert.Single(model.Combinations); + var corners = combination.Members.SelectMany(member => model.Extrusions.SingleOrDefault(item => item.ElementId == member) is { } extrusion + ? FamilyExtrusionBuilder.Faces(extrusion, positions, _ => 0) + : FamilyRevolutionBuilder.Faces(model.Revolutions.Single(item => item.ElementId == member), positions, _ => 0)) + .SelectMany(face => face.OuterVertices!).ToList(); + + Assert.Equal(halfX, corners.Max(corner => Math.Abs(corner[0])) / Millimetre, 1e-3); + Assert.Equal(halfY, corners.Max(corner => Math.Abs(corner[1])) / Millimetre, 1e-3); + Assert.Equal(top, corners.Max(corner => corner[2]) / Millimetre, 1e-3); + } + + // The file stores the faces of the revolutions of the valve with corners inside their surfaces, on the chords of an octagon where + // the sections of Revit's mesh meet (in the body, 50 of 72 faces, by up to 3.8 mm), so they are not the surfaces the revolution + // turns: the check of the saved state refuses the valve, and no shape is given in any of its types. + [SkippableFact] + public void TheValveIsRefusedWhileTheFileStoresItsRevolutionsOffTheirSurfaces() + { + var computed = ElementMeshes.ComputeFamilyType(WithoutFlanges(), SavedType); + + Assert.Null(computed.Elements); + Assert.Equal("saved-state-mismatch", computed.Refusal!.Code); + Assert.Equal("element 10164308", computed.Refusal.Detail); + } + + // What the valve still holds that cannot be computed: the four flanges, each a family loaded into it and placed. + [SkippableFact] + public void OnlyTheFourNestedFlangesAreStillUnsupported() + { + var unsupported = Records().UnsupportedContent.Distinct().Order().ToList(); + + Assert.Equal(4, unsupported.Count); + Assert.All(unsupported, entry => Assert.StartsWith("FamilyInstance ", entry)); + Assert.Equal([10164284, 10164292, 10164298, 10164299], + unsupported.Select(entry => int.Parse(entry["FamilyInstance ".Length..])).Order()); + } } diff --git a/tests/RvtIO.Tests/Families/FamilyArcTests.cs b/tests/RvtIO.Tests/Families/FamilyArcTests.cs index cf667972..4f3591fb 100644 --- a/tests/RvtIO.Tests/Families/FamilyArcTests.cs +++ b/tests/RvtIO.Tests/Families/FamilyArcTests.cs @@ -510,6 +510,35 @@ public void ACircleExtrudesToAFacetedCylinder() } } + // A ring of two circles, the hole drawn the other way round (the extrusion of the flange ring of the AquaFix valve): the + // caps of the outer circle face inward, as those of a circle alone, and carry the hole. + [Fact] + public void ARingOfTwoCirclesHasItsCapsFacingInward() + { + // 0, 1 centre; 2, 3 outer and inner radius; 4, 5 ends of the extrusion; 6..9 the corners at +-2 and +-1 on the axis of U. + double[] positions = [0, 0, 2, 1, 0, 1, 2, -2, 1, -1]; + FamilyVertex Corner(int u) => new(u, 1, 1); + FamilyArcSegment Half(int radius, int way, int quarter) => new(0, 1, radius, way, quarter, 2, 6); + var ring = new FamilyExtrusion(50, [[Corner(6), Corner(7)], [Corner(8), Corner(9)]], 2, 4, 5, + new Dictionary(), null, null, + [[Half(2, 1, 0), Half(2, 1, 2)], [Half(3, -1, 0), Half(3, -1, 2)]]); + + var faces = FamilyExtrusionBuilder.Faces(ring, positions, _ => 0); + + var caps = faces.Where(face => face.InnerVertices != null).ToList(); + Assert.Equal(2, caps.Count); + Assert.Equal([1.0, -1.0], caps.Select(cap => cap.Normal[2])); + Assert.All(caps, cap => Assert.Single(cap.InnerVertices!)); + // Each corner of a face winds round its normal, the hole against the outline. + foreach (var cap in caps) + { + double Wound(List loop) => Enumerable.Range(0, loop.Count) + .Sum(i => loop[i][0] * loop[(i + 1) % loop.Count][1] - loop[(i + 1) % loop.Count][0] * loop[i][1]); + Assert.True(cap.Normal[2] * Wound(cap.OuterVertices!) > 0); + Assert.True(cap.Normal[2] * Wound(cap.InnerVertices![0]) < 0); + } + } + [Fact] public void ASideFacetOfAnArcFacesOutwardAtTheMiddleOfItsTurn() { diff --git a/tests/RvtIO.Tests/Families/FamilyCombinationTests.cs b/tests/RvtIO.Tests/Families/FamilyCombinationTests.cs new file mode 100644 index 00000000..069d064d --- /dev/null +++ b/tests/RvtIO.Tests/Families/FamilyCombinationTests.cs @@ -0,0 +1,233 @@ +using RvtIO.Families; +using RvtIO.Meshes; +using RvtIO.Model; +using Xunit; + +namespace RvtIO.Tests.Families; + +/// A combination of forms joins solid forms into one shape. The family draws it as the faces of its members, whole; +/// the faces Revit stores for the joined shape are trimmed where the members overlap, and are not compared one by one. +public class FamilyCombinationTests +{ + private const int Combination = 60, Extrusion = SyntheticFamily.Extrusion, Material = 40; + + private static FamilyRecords Leaf(params FamilyCombinationRecord[] combinations) => + SyntheticFamily.Leaf() with { Combinations = combinations }; + + private static FamilyCombinationRecord Of(params int[] members) => new(Combination, members); + + private static void AssertRefused(FamilyRecords records, string code, string detail) + { + var (model, refusal) = FamilyModelBuilder.Build(records); + + Assert.Null(model); + Assert.Equal(code, refusal!.Code); + Assert.Contains(detail, refusal.Detail); + } + + [Fact] + public void ACombinationOfTheFormsOfTheModelIsCarriedWithItsMembers() + { + var (model, refusal) = FamilyModelBuilder.Build(Leaf(Of(Extrusion))); + + Assert.Null(refusal); + var combination = Assert.Single(model!.Combinations); + Assert.Equal(Combination, combination.ElementId); + Assert.Equal([Extrusion], combination.Members); + } + + [Fact] + public void AFamilyWithoutCombinationsHasNone() => + Assert.Empty(FamilyModelBuilder.Build(SyntheticFamily.Leaf()).Model!.Combinations); + + [Fact] + public void AMemberThatIsNoSolidFormOfTheModelIsRefused() => + AssertRefused(Leaf(Of(Extrusion, 99)), "unrecognized-reference", "member 99 of 60"); + + [Fact] + public void ACombinationOfNothingIsRefused() => AssertRefused(Leaf(Of()), "unsupported-construct", "combination 60"); + + [Fact] + public void AFormThatTwoCombinationsHoldIsRefused() => + AssertRefused(Leaf(Of(Extrusion), new(61, [Extrusion])), "unsupported-construct", "member 50 of 61"); + + // Whether a form that a parameter can hide is part of the joined shape is not recorded: the shape of another type is not + // known. + [Fact] + public void AMemberWhoseVisibilityAParameterDrivesIsRefused() => + AssertRefused(Leaf(Of(Extrusion)) with { Associations = [new(Extrusion, -1006205, 201)] }, "unsupported-construct", + "visibility of member 50"); + + [Fact] + public void AMemberWhoseMaterialAParameterGivesIsCarried() + { + var (model, refusal) = FamilyModelBuilder.Build(Leaf(Of(Extrusion)) with { Associations = [new(Extrusion, -1002107, 200)] }); + + Assert.Null(refusal); + Assert.Equal(200, Assert.Single(model!.Extrusions).MaterialParameterId); + } + + [Fact] + public void AParameterThatDrivesTheCombinationItselfIsRefused() => + AssertRefused(Leaf(Of(Extrusion)) with { Associations = [new(Combination, -1006205, 201)] }, "unrecognized-reference", + "element 60"); + + [Fact] + public void ACombinationMayReferToItsMembersAndToNothingElseInTheModel() + { + var members = new FamilyReferrer(Combination, "GeomCombination", "AddGeomToCombinationGStep.m_memberId", Extrusion); + var back = new FamilyReferrer(Extrusion, "ExtrusionElem", "GroupMembership.m_groupId", Combination); + Assert.Null(FamilyModelBuilder.Build(Leaf(Of(Extrusion)).Add(members).Add(back)).Refusal); + + // The sketch of the extrusion, a plane: the combination moves none of them. + AssertRefused(Leaf(Of(Extrusion)).Add(members).Add(new FamilyReferrer(Combination, "GeomCombination", "X.m_id", 40)), + "unrecognized-reference", "GeomCombination 60"); + // A record that is no combination of the model and refers to a member. + AssertRefused(Leaf(Of(Extrusion)).Add(new FamilyReferrer(99, "GeomCombination", "X.m_id", Extrusion)), + "unrecognized-reference", "GeomCombination 99"); + } + + private static FamilyModel Joined() + { + var model = FamilyModelBuilder.Build(Leaf(Of(Extrusion))).Model!; + Assert.Single(model.Combinations); + return model; + } + + private static List Built(FamilyModel model) => FamilyExtrusionBuilder.Faces( + model.Extrusions[0], model.Variables.Select(v => v.Stored).ToArray(), _ => Material); + + private static Dictionary> Stored(IReadOnlyList member, IReadOnlyList? joined) => + joined == null ? new() { [Extrusion] = member } : new() { [Extrusion] = member, [Combination] = joined }; + + private static (Dictionary<(int ElementId, FamilyFaceKey Face), GeoFace>? Faces, RvtFamilyRefusal? Refusal) Match( + FamilyModel model, IReadOnlyList member, IReadOnlyList? joined) => + FamilySavedState.Match(model, new Dictionary { [100] = 3, [101] = 2 }, (_, _) => Material, + Stored(member, joined)); + + [Fact] + public void TheStoredStateOfACombinationMatchesWhenItsMembersDoAndTheJoinedShapeHasTheirBox() + { + var model = Joined(); + + var matched = Match(model, Built(model), Built(model)); + + Assert.Null(matched.Refusal); + // Each face of a member is the stored face of the member: the combination adds no face of its own. + Assert.NotEmpty(matched.Faces!); + Assert.All(matched.Faces!.Keys, key => Assert.Equal(Extrusion, key.ElementId)); + } + + [Fact] + public void AJoinedShapeThatIsSmallerThanItsMembersIsAMismatch() + { + var model = Joined(); + var joined = Built(model); + foreach (var face in joined) + foreach (var corner in face.OuterVertices!) + corner[0] *= 0.5; + + var matched = Match(model, Built(model), joined); + + Assert.Equal("saved-state-mismatch", matched.Refusal!.Code); + Assert.Contains("element 60", matched.Refusal.Detail); + } + + [Fact] + public void AJoinedShapeThatReachesBeyondItsMembersIsAMismatch() + { + var model = Joined(); + var joined = Built(model); + joined.SelectMany(face => face.OuterVertices!).MaxBy(corner => corner[2])![2] += 1e-3; + + Assert.Contains("element 60", Match(model, Built(model), joined).Refusal!.Detail); + } + + [Fact] + public void ACombinationWithoutStoredFacesIsAMismatch() + { + var model = Joined(); + + Assert.Contains("element 60", Match(model, Built(model), null).Refusal!.Detail); + Assert.Contains("element 60", Match(model, Built(model), []).Refusal!.Detail); + } + + [Fact] + public void AMemberThatDiffersFromItsStoredFacesIsAMismatchOfTheMember() + { + var model = Joined(); + var member = Built(model); + member[2].OuterVertices![1][0] += 2e-6; + + Assert.Contains("element 50", Match(model, member, Built(model)).Refusal!.Detail); + } + + // The sample family of the Revit MEP extension (seven extrusions, seven types), with two of its forms joined into a combination + // that the document did not have: the body of the combination holds the stored faces of its two members. + private const int FirstForm = 2507, SecondForm = 2553, JoinedForm = 99999; + + private static RvtDocument WithACombination(bool storedShapeIsTheFirstMemberOnly = false) + { + var document = RvtDocument.Open(TestFiles.FindRelative("families/rme_advanced_sample_family.rfa"), + new RvtReaderOptions { R22Layout = true }); + var family = document.RawData.Family!; + var members = document.RawData.Elements.Where(element => element.Id is FirstForm or SecondForm).OrderBy(element => element.Id).ToList(); + var stored = members.Take(storedShapeIsTheFirstMemberOnly ? 1 : 2).SelectMany(member => + (member.SerializedComputedSymbolGeometry ?? member.Geometry)!.Faces).ToList(); + var joined = members[0].ShallowCopy(); + joined.Id = JoinedForm; + joined.SerializedComputedSymbolGeometry = null; + joined.Geometry = new GeometryData { Faces = stored }; + document.RawData.Elements.Add(joined); + document.RawData.Family = new FamilyData + { + Elements = [.. family.Elements.Select(facts => facts.ElementId is FirstForm or SecondForm ? facts with { CombinationMember = true } : facts), + new FamilyElementFacts(JoinedForm, "FamilyGeomCombination", true, true, false, true, false, Members: [FirstForm, SecondForm])], + Types = family.Types, TypesError = family.TypesError, + Records = family.Records! with { Combinations = [new FamilyCombinationRecord(JoinedForm, [FirstForm, SecondForm])] }, + }; + return document; + } + + private static HashSet Corners(ElementMesh mesh) => + [.. mesh.Meshes.SelectMany(part => part.Positions.Chunk(3)).Select(corner => string.Join(' ', corner.Select(value => value.ToString("F6"))))]; + + [SkippableFact] + public void ACombinationOfAFamilyIsDrawnAsTheFacesItsMembersDrawAloneInEveryType() + { + var plain = RvtDocument.Open(TestFiles.FindRelative("families/rme_advanced_sample_family.rfa"), new RvtReaderOptions { R22Layout = true }); + var document = WithACombination(); + + Assert.Equal(7, document.FamilyTypes!.Types.Count); + for (int type = 0; type < 7; type++) + { + var computed = ElementMeshes.ComputeFamilyType(document, type); + Assert.True(computed.Elements != null, $"type {type}: {computed.Refusal?.Code} {computed.Refusal?.Detail}"); + + var alone = ElementMeshes.ComputeFamilyType(plain, type).Elements!; + // The members are no elements of their own: the combination holds them. + Assert.Equal(alone.Select(mesh => mesh.ElementId).Where(id => id is not (FirstForm or SecondForm)).Append(JoinedForm).Order(), + computed.Elements!.Select(mesh => mesh.ElementId).Order()); + var joined = Assert.Single(computed.Elements!, mesh => mesh.ElementId == JoinedForm); + Assert.Equal(MeshCoverage.Complete, joined.Coverage); + var expected = alone.Where(mesh => mesh.ElementId is FirstForm or SecondForm).SelectMany(Corners).ToHashSet(); + Assert.NotEmpty(expected); + Assert.Equal(expected, Corners(joined)); + // The forms that are not joined are drawn as before. + foreach (var other in computed.Elements!.Where(mesh => mesh.ElementId != JoinedForm)) + Assert.Equal(Corners(alone.Single(mesh => mesh.ElementId == other.ElementId)), Corners(other)); + } + } + + // What the file stores for the joined shape is held against its members by its box: a joined shape that is not that of the + // two members is no combination of them, and the family is not computed. + [SkippableFact] + public void ACombinationWhoseStoredShapeHasNotTheBoxOfItsMembersIsRefused() + { + var computed = ElementMeshes.ComputeFamilyType(WithACombination(storedShapeIsTheFirstMemberOnly: true), 0); + + Assert.Null(computed.Elements); + Assert.Equal("saved-state-mismatch", computed.Refusal!.Code); + Assert.Equal("element 99999", computed.Refusal.Detail); + } +} diff --git a/tests/RvtIO.Tests/Families/FamilyModelBuilderTests.cs b/tests/RvtIO.Tests/Families/FamilyModelBuilderTests.cs index c04bf152..936bb6d7 100644 --- a/tests/RvtIO.Tests/Families/FamilyModelBuilderTests.cs +++ b/tests/RvtIO.Tests/Families/FamilyModelBuilderTests.cs @@ -254,6 +254,15 @@ public void ASideJoinNeedsTheJoinOfTheOtherEnd(bool recorded) else AssertRefused(sided, "unrecognized-reference", "CurveElem 41"); } + // Two lines of one side that meet at an end and keep their axis are collinear already: the alignment of their sides moves + // nothing. Joined lines of two axes, or lines of one axis that do not meet, are another matter. + [Theory] + [InlineData(42)] // joined to 41 at its end, along the other axis + [InlineData(43)] // along the same axis as 41, joined to nothing of it + public void ASideAlignmentOfLinesThatAreNotCollinearHalvesOfOneSideRefuses(int other) => + AssertRefused(SyntheticFamily.Leaf().Add(new FamilyReferrer(41, "CurveElem", + "CurveElemDriver.std::pair< ElementId, SideAlignment >.first", other)), "unrecognized-reference", "CurveElem 41"); + [Fact] public void AnUnknownAssociationRefuses() => AssertRefused(SyntheticFamily.Leaf() with { Associations = [new(SyntheticFamily.Extrusion, -1234, Width)] }, diff --git a/tests/RvtIO.Tests/Families/FamilyRevolutionTests.cs b/tests/RvtIO.Tests/Families/FamilyRevolutionTests.cs index 65849f9b..0f5843db 100644 --- a/tests/RvtIO.Tests/Families/FamilyRevolutionTests.cs +++ b/tests/RvtIO.Tests/Families/FamilyRevolutionTests.cs @@ -68,6 +68,24 @@ public void ARevolutionOfTheFileBuildsTheSolidItsSketchTurnsAtTheStoredPositions Assert.Equal(Polygon(radius) * height / 3, Volume(Faces(model, Stored(model))), 1e-9); } + // Revit 2022 opened each family on 2026-12-02 and gave the volume of its revolution (the exact surfaces, not facets), in mm3: + // the cones of radius 100 and height 300, and of radius 500 and height 1500. The solid built here has its facets inscribed in + // the circle, so its volume is the exact one by the ratio of the area of the polygon to that of the circle. + [SkippableTheory] + [InlineData("families/RR_Cone_R100_H300.rfa", 3141592.7)] + [InlineData("families/RR_Shape_cone.rfa", 392699081.7)] + public void TheVolumeOfARevolutionAtTheStoredPositionsIsTheVolumeRevitGives(string file, double revitVolume) + { + var document = RvtDocument.Open(TestFiles.FindRelative(file), new RvtReaderOptions()); + var model = Model(document.RawData.Family!.Records!); + + double facets = FamilyRevolutionBuilder.Facets; + double polygonToCircle = facets * Math.Sin(2 * Math.PI / facets) / (2 * Math.PI); + double cubicMillimetres = Volume(Faces(model, Stored(model))) / polygonToCircle / Math.Pow(Millimetre, 3); + + Assert.Equal(revitVolume, cubicMillimetres, 0.1); + } + [SkippableFact] public void TheFacesTheFileStoresForARevolutionAreTheSurfacesItTurns() { From d4f0abba9528cb869353996fd960afccbc685a55 Mon Sep 17 00:00:00 2001 From: Mahach <79989386+mahach666@users.noreply.github.com> Date: Wed, 2 Dec 2026 15:16:52 +0300 Subject: [PATCH 05/14] Accept chords of cut circles in revolutions and formula parameters The faces the file stores for a revolution are now accepted when a corner lies on a side of the polygon the file cuts a circle into: a chord between two neighbouring stored corners of the circle that go round the axis or, where the file leaves a corner out (the rim of the valve at 90 degrees), a chord between two corners of the regular polygon that all the stored corners of the circle lie on the grid of. A corner inside the circle that is on no such side stays a saved-state-mismatch, to 1e-6 feet. A parameter that drives a dimension or a form and is given by a formula no longer makes a family refuse: each type stores the value the parameter has, and it is used as stored. The check of the saved type against the stored faces stays. With both, the valve without its four nested flanges is computed in all 14 types, and the volumes of its body and ring agree with Revit 2022 to 7.8e-4. The valve itself is still refused as unsupported-construct for the flanges: the file stores their shape for the saved type only, so the other types are not shown. --- CHANGELOG.md | 14 +- src/RvtIO/Families/FamilyModelBuilder.cs | 11 -- src/RvtIO/Families/FamilyRecords.cs | 5 +- src/RvtIO/Families/FamilyRevolutionBuilder.cs | 106 +++++++++++-- .../RvtIO.Tests/Families/AquaFixValveTests.cs | 47 ++++-- tests/RvtIO.Tests/Families/FamilyArcTests.cs | 12 +- .../Families/FamilyModelBuilderTests.cs | 14 +- .../Families/FamilyRevolutionTests.cs | 143 ++++++++++++++++++ 8 files changed, 311 insertions(+), 41 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 285b59f6..c296d85f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -26,9 +26,14 @@ API between minor releases. straight lines (a cylinder, a ring, a cone, a stepped body, a slanted side) is computed like an extrusion: the surface of each line is cut into 18 facets, a line on the axis makes no face, a loop inside an odd number of loops is a hole, and a profile that crosses the axis or itself, or loops that meet, are refused as `degenerate-geometry`. For the saved type the file's own faces of a - revolution are accepted when every corner of each lies on one surface of the revolution, every surface has faces that reach both - its circles, and the faces of a surface share a material (the one its parameter gives), because the file cuts round surfaces as - it likes; the way a stored face faces is not compared, since the file stores half of the side of a cone facing into the solid. + revolution are accepted when every corner of each lies on one surface of the revolution (or inside it, on a side of the polygon + the file cuts a circle of it into: a chord between two neighbouring stored corners of the circle that go round the axis, up to + 3.8 mm inside the body of the valve; where the file leaves a corner out, as the rim of the valve at 90 degrees, a chord between + two corners of the regular polygon the stored corners define, when they are all on the grid of one whole number of sections to + the turn, the step being the smallest gap), every surface has faces that reach both its circles, and the faces of a surface + share a material (the one its parameter gives), because the file cuts round surfaces as it likes; the way a stored face faces + is not compared, since the file stores half of the side of a cone facing into the solid. A corner inside the circle that is on + no such side (to the tolerance of 1e-6 feet) is a `saved-state-mismatch`. - A combination of forms (`FamilyGeomCombination`, joined solid geometry) of extrusions and revolutions of the family is computed: it is drawn as the faces of its members, whole, so where the members overlap the faces inside the union stay and the shell is not a trimmed one. The file stores the joined shape trimmed and tessellated again, so for the saved type each member is @@ -36,6 +41,9 @@ API between minor releases. A combination without members, a form that two combinations hold, a member that is no extrusion or revolution of the family or that a family parameter shows or hides, and a parameter that drives the combination itself are refused. A side alignment of two joined lines of a sketch that run along one axis is read as the relation the join already gives. +- A parameter that drives a dimension or a form of a family and is given by a formula no longer makes the family refuse: each + type stores the value its parameter has, that value is used as stored, and the formula is not evaluated again. For the saved + type the computed faces are still checked against the stored ones. - `RvtReaderOptions.FineCircularEdges` and `RvtSceneOptions.FineCircularEdges` (off by default). A circle where a cylinder meets a plane is sampled by default as Revit's low detail level samples it, a polygon of about eight sides for a pipe; with the option the faces take the finer points the file stores, so the circle looks round. The faces of other surfaces do not change. diff --git a/src/RvtIO/Families/FamilyModelBuilder.cs b/src/RvtIO/Families/FamilyModelBuilder.cs index f05ebf6b..c2c43e67 100644 --- a/src/RvtIO/Families/FamilyModelBuilder.cs +++ b/src/RvtIO/Families/FamilyModelBuilder.cs @@ -126,7 +126,6 @@ public FamilyModel Build() CheckConstraints(modelLines); CheckAssociations(modelLines); CheckReferrers(modelLines); - CheckFormulas(); PlaceHostFaces(dimensions); foreach (var (record, nodes) in dimensions) Relate(record, nodes); @@ -649,16 +648,6 @@ private void CheckReferrers(HashSet modelLines) } } - private void CheckFormulas() - { - var driving = records.Dimensions.SelectMany(d => d.ParameterIds) - .Concat((records.RadialDimensions ?? []).Select(r => r.ParameterId).Where(parameter => parameter != -1)) - .Concat(records.Associations.Where(a => (_extrusions.ContainsKey(a.ElementId) || _revolutions.ContainsKey(a.ElementId)) - && a.ElementPropertyId != (long)BuiltInParameter.MATERIAL_ID_PARAM).Select(a => a.FamilyParameterId)); - var formulas = driving.Where(records.FormulaParameterIds.Contains).Distinct().Order().ToList(); - if (formulas.Count > 0) throw Unsupported("formula of parameter " + string.Join(", ", formulas)); - } - private void PlaceHostFaces(List<(FamilyDimensionRecord Record, int[] Nodes)> dimensions) { for (bool placed = true; placed;) diff --git a/src/RvtIO/Families/FamilyRecords.cs b/src/RvtIO/Families/FamilyRecords.cs index 5d04dfe1..01b856cc 100644 --- a/src/RvtIO/Families/FamilyRecords.cs +++ b/src/RvtIO/Families/FamilyRecords.cs @@ -75,8 +75,9 @@ internal sealed record FamilyReferrer(int RecordId, string ClassName, string Fie internal sealed record FamilyAssociation(int ElementId, long ElementPropertyId, long FamilyParameterId); /// What the records of a family say about the placing of its forms, as plain values. -/// UnsupportedContent names what is shown and cannot be recomputed. ControlIconIds are the control icons (the -/// arrows that flip an element) of the family. +/// UnsupportedContent names what is shown and cannot be recomputed. FormulaParameterIds are the parameters a +/// formula or a measurement sets: the value a type stores for one is the value it has, so it is used as stored. +/// ControlIconIds are the control icons (the arrows that flip an element) of the family. internal sealed record FamilyRecords(IReadOnlyList Dimensions, IReadOnlyList Lines, IReadOnlyList Joints, IReadOnlyList Constraints, IReadOnlyList Planes, diff --git a/src/RvtIO/Families/FamilyRevolutionBuilder.cs b/src/RvtIO/Families/FamilyRevolutionBuilder.cs index f63644ed..79a5c011 100644 --- a/src/RvtIO/Families/FamilyRevolutionBuilder.cs +++ b/src/RvtIO/Families/FamilyRevolutionBuilder.cs @@ -212,8 +212,12 @@ GeoFace Wound(List ring, double[] outward, FamilyFaceKey key) /// not the surfaces the file stores. The file cuts its round surfaces as it likes, so faces are not compared one for one: /// every corner of every stored face lies on one surface of the revolution (the line of a loop, turned), every surface has /// stored faces that reach both its circles, the faces of a surface share one material ( when a - /// parameter gives it). The way a stored face faces is not compared: the file stores the caps of a circle facing inward and - /// one half of the side of a cone facing into the solid, so the way the solid goes is held by the loops (). + /// parameter gives it). A corner is on the surface or inside it on a chord of a circle of it: the file cuts a circle into the + /// sections of a polygon inscribed in it, and where the sections of two surfaces meet, a corner lies on a side of that polygon, + /// between two neighbouring corners that are on the circle, or between two corners of the regular polygon those define where + /// the file leaves a corner out (see and ). The way a stored face faces is not + /// compared: the file stores the caps of a circle facing inward and one half of the side of a cone facing into the solid, so + /// the way the solid goes is held by the loops (). internal static Dictionary? Match(FamilyRevolution revolution, IReadOnlyList positions, IReadOnlyList stored, int? material = null) { @@ -222,27 +226,39 @@ GeoFace Wound(List ring, double[] outward, FamilyFaceKey key) var surfaces = Sides(revolution, positions) .Select(side => (Side: side, Start: (R: Math.Abs(side.D1), V: side.V1), End: (R: Math.Abs(side.D2), V: side.V2))).ToList(); - var reached = surfaces.ToDictionary(surface => surface.Side.Key, _ => new List<(double R, double V)>()); - var matched = new Dictionary(); + // Every corner as the distance from the axis, the position along it and the angle about it. + var polars = new List>(); foreach (var face in stored) { var corners = (face.OuterVertices ?? []).Concat(face.InnerVertices?.SelectMany(hole => hole) ?? []).ToList(); if (corners.Count == 0 || corners.Any(corner => corner.Length != 3)) return null; - var polar = corners.Select(corner => (R: Math.Sqrt(Math.Pow(corner[across] - centre, 2) + Math.Pow(corner[normal] - plane, 2)), - V: corner[axis])).ToList(); + polars.Add([.. corners.Select(corner => + { + double x = corner[across] - centre, y = corner[normal] - plane; + return (Math.Sqrt(x * x + y * y), corner[axis], Math.Atan2(y, x)); + })]); + } + var circles = surfaces.ToDictionary(surface => surface.Side.Key, + surface => Circles(polars.SelectMany(polar => polar), surface.Start, surface.End)); + + var reached = surfaces.ToDictionary(surface => surface.Side.Key, _ => new List<(double R, double V)>()); + var matched = new Dictionary(); + for (int f = 0; f < stored.Count; f++) + { + var (face, polar) = (stored[f], polars[f]); // A face on a cylinder or a cone reaches along the axis; one at a single position along it is flat, on a disc or a ring, // though its corners lie on the circle where a cylinder ends. A face of two surfaces is no face of either. double reach = polar.Max(point => point.V) - polar.Min(point => point.V); - var onSurface = surfaces.Where(surface => polar.All(point => Near(point, surface.Start, surface.End)) + var onSurface = surfaces.Where(surface => polar.All(point => Near((point.R, point.V), surface.Start, surface.End) + || OnChord(point, circles[surface.Side.Key])) && (Math.Abs(surface.End.V - surface.Start.V) <= Tolerance || reach > Tolerance)).ToList(); if (onSurface.Count != 1) return null; - var (side, start, end) = onSurface[0]; - var key = side.Key; + var key = onSurface[0].Side.Key; // No material is stored as nothing or as an id that is not one. int own = Math.Max(face.RenderStyleId ?? 0, 0); if (material is int expected && own != Math.Max(expected, 0)) return null; if (!matched.TryAdd(key, face) && Math.Max(matched[key].RenderStyleId ?? 0, 0) != own) return null; - reached[key].AddRange(polar); + reached[key].AddRange(polar.Select(point => (point.R, point.V))); } foreach (var (side, start, end) in surfaces) { @@ -254,6 +270,76 @@ bool Reaches((double R, double V) tip) => tip.R <= Tolerance return matched; } + /// The circles about the axis that corners lie on and that the line from to + /// of the profile passes through, with the angles of the corners on each, sorted. Corners that do not go + /// round the axis (a gap of half a turn between neighbours) make no circle: a chord between them is no side of a polygon that + /// holds the axis, and says nothing of the surface. The file cuts a circle into the sections of a regular polygon and leaves a + /// corner of it out where another form trims it away: when every corner of a circle is on the grid of the regular polygon whose + /// step is the smallest gap between them (a whole number of sections to the turn), that polygon is the circle's + /// (Grid is its step, otherwise 0 and the polygon is the corners there are). + private static List<(double R, double V, double[] Angles, double Grid)> Circles(IEnumerable<(double R, double V, double Angle)> points, + (double R, double V) start, (double R, double V) end) + { + var found = new List<(double R, double V, List Angles)>(); + foreach (var (r, v, angle) in points) + { + // A corner on the axis is on no circle. + if (r <= Tolerance || !Near((r, v), start, end)) continue; + int at = found.FindIndex(circle => Math.Abs(circle.R - r) <= Tolerance && Math.Abs(circle.V - v) <= Tolerance); + if (at < 0) found.Add((r, v, [angle])); + else found[at].Angles.Add(angle); + } + + var circles = new List<(double R, double V, double[] Angles, double Grid)>(); + foreach (var (r, v, all) in found) + { + all.Sort(); + // A corner is in many faces; and the angle of a turn is the same at either end of the range. + double same = Tolerance / r; + var angles = new List(); + foreach (var angle in all) + if (angles.Count == 0 || angle - angles[^1] > same) angles.Add(angle); + if (angles.Count > 1 && angles[0] + 2 * Math.PI - angles[^1] <= same) angles.RemoveAt(angles.Count - 1); + double Gap(int i) => i + 1 < angles.Count ? angles[i + 1] - angles[i] : angles[0] + 2 * Math.PI - angles[i]; + if (angles.Count < 3 || !Enumerable.Range(0, angles.Count).All(i => Gap(i) < Math.PI - same)) continue; + + int sections = (int)Math.Round(2 * Math.PI / Enumerable.Range(0, angles.Count).Min(Gap)); + double unit = 2 * Math.PI / sections; + bool regular = sections >= 3 && angles.All(angle => + { + double steps = (angle - angles[0]) / unit; + return Math.Abs(steps - Math.Round(steps)) * unit <= 2 * same; + }); + circles.Add((r, v, [.. angles], regular ? unit : 0)); + } + return circles; + } + + // The corner lies on a side of the polygon of one of the circles, to the tolerance: a chord between two neighbouring corners of + // the circle, or between two corners of its regular polygon where the file leaves some of them out. + private static bool OnChord((double R, double V, double Angle) point, List<(double R, double V, double[] Angles, double Grid)> circles) + { + double x = point.R * Math.Cos(point.Angle), y = point.R * Math.Sin(point.Angle); + foreach (var (radius, v, angles, grid) in circles) + { + if (Math.Abs(v - point.V) > Tolerance) continue; + for (int i = 0; i < angles.Length; i++) + { + double from = angles[i], gap = (i + 1 < angles.Length ? angles[i + 1] : angles[0] + 2 * Math.PI) - from; + // The angle of the corner, counted from the first corner of the pair: only the sides between the two are its. + double turn = point.Angle - from; + turn -= 2 * Math.PI * Math.Floor(turn / (2 * Math.PI)); + if (turn > gap) continue; + int sides = grid > 0 ? (int)Math.Round(gap / grid) : 1; + double side = gap / sides; + int j = Math.Min((int)(turn / side), sides - 1); + double a = from + j * side, b = from + (j + 1) * side; + if (Near((x, y), (radius * Math.Cos(a), radius * Math.Sin(a)), (radius * Math.Cos(b), radius * Math.Sin(b)))) return true; + } + } + return false; + } + // The point (distance from the axis, position along it) is on the segment from a to b, to the tolerance. private static bool Near((double R, double V) point, (double R, double V) a, (double R, double V) b) { diff --git a/tests/RvtIO.Tests/Families/AquaFixValveTests.cs b/tests/RvtIO.Tests/Families/AquaFixValveTests.cs index a734265c..6ae39d8c 100644 --- a/tests/RvtIO.Tests/Families/AquaFixValveTests.cs +++ b/tests/RvtIO.Tests/Families/AquaFixValveTests.cs @@ -75,8 +75,6 @@ private static RvtDocument WithoutFlanges() Dimensions = [.. family.Records!.Dimensions.Where(d => !d.References.Any(r => Flanges.Contains(r.ElementId) || r.ElementId == 10164354 || r.ElementId == 10164399))], Constraints = [.. family.Records.Constraints.Where(constraint => constraint.SketchId != 10164398)], Referrers = [.. family.Records.Referrers.Where(referrer => !Flanges.Contains(referrer.RecordId) && referrer.RecordId != 10164402)], - // Five parameters of the valve are given by formulas; the values its types store for them are taken as they are. - FormulaParameterIds = new HashSet(), UnsupportedContent = [.. family.Records.UnsupportedContent.Where(entry => !Flanges.Any(id => entry.EndsWith(" " + id)))], }, }; @@ -165,17 +163,48 @@ public void TheBoxOfTheCombinationOfTheValveIsTheBoxRevitGives(string type, doub Assert.Equal(top, corners.Max(corner => corner[2]) / Millimetre, 1e-3); } - // The file stores the faces of the revolutions of the valve with corners inside their surfaces, on the chords of an octagon where - // the sections of Revit's mesh meet (in the body, 50 of 72 faces, by up to 3.8 mm), so they are not the surfaces the revolution - // turns: the check of the saved state refuses the valve, and no shape is given in any of its types. + // The file stores the faces of the body with corners inside its surfaces, on the chords of an octagon where the sections of + // Revit's mesh meet (50 of 72 faces, by up to 3.8 mm inside): corners on a chord between two neighbouring corners of the circle + // are corners of its surface, and the body matches. [SkippableFact] - public void TheValveIsRefusedWhileTheFileStoresItsRevolutionsOffTheirSurfaces() + public void TheStoredFacesOfTheBodyOfTheValveMatchItsSurfacesWithTheirCornersOnChords() + { + var document = WithoutFlanges(); + var (model, positions) = Solved("Ду=80"); + var element = document.RawData.Elements.Single(item => item.Id == 10164308); + + var matched = FamilyRevolutionBuilder.Match(model.Revolutions.Single(item => item.ElementId == 10164308), positions, + (element.SerializedComputedSymbolGeometry ?? element.Geometry)!.Faces); + + Assert.NotNull(matched); + } + + // The stem and the rim: the file stores the rim as an octagon with its corners at ±90 degrees cut at y = ±96.02 mm (corners at + // 96.085 mm and ±87.9, ±92.1 degrees), the height of the top side of Revit's own rim of 18 facets, and stores no corner at 90 + // degrees. Those corners are on the sides of the octagon the other corners of the circle define, to 1e-12 mm: the corners the + // file cut away are corners of that polygon all the same, and the valve, without its flanges, is computed. + [SkippableFact] + public void TheValveWithoutItsFlangesIsComputedInTheTypeTheFileWasSavedAt() { var computed = ElementMeshes.ComputeFamilyType(WithoutFlanges(), SavedType); - Assert.Null(computed.Elements); - Assert.Equal("saved-state-mismatch", computed.Refusal!.Code); - Assert.Equal("element 10164308", computed.Refusal.Detail); + Assert.Null(computed.Refusal); + Assert.Equal([10164267, 10164308, 10164354], computed.Elements!.Select(element => element.ElementId).Order()); + } + + [SkippableFact] + public void TheValveWithoutItsFlangesIsComputedInEveryType() + { + var document = WithoutFlanges(); + var types = document.RawData.Family!.Types!.Types; + + var outcome = Enumerable.Range(0, types.Count).Select(index => + { + var computed = ElementMeshes.ComputeFamilyType(document, index); + return types[index].Name + ": " + (computed.Refusal is { } refusal ? refusal.Code + " " + refusal.Detail : "computed"); + }).ToList(); + + Assert.Equal([], outcome.Where(line => !line.EndsWith("computed"))); } // What the valve still holds that cannot be computed: the four flanges, each a family loaded into it and placed. diff --git a/tests/RvtIO.Tests/Families/FamilyArcTests.cs b/tests/RvtIO.Tests/Families/FamilyArcTests.cs index 4f3591fb..7096beb8 100644 --- a/tests/RvtIO.Tests/Families/FamilyArcTests.cs +++ b/tests/RvtIO.Tests/Families/FamilyArcTests.cs @@ -467,9 +467,15 @@ public void AnyOtherDimensionToAControlIconIsARelationToAnUnknownPlace(long segm AssertRefused(WithIconDimension(segmentFlags, parameter, listed), "unrecognized-reference", "99"); [Fact] - public void AFormulaOnTheParameterOfARadialDimensionIsUnsupported() => - AssertRefused(SyntheticArcs.Disc() with { FormulaParameterIds = new HashSet { Diameter } }, - "unsupported-construct", Diameter.ToString()); + public void AFormulaOnTheParameterOfARadialDimensionTakesTheValueTheTypeStores() + { + var (_, positions) = Solve(SyntheticArcs.Disc(), (Diameter, 3)); + + var (_, formulaPositions) = Solve( + SyntheticArcs.Disc() with { FormulaParameterIds = new HashSet { Diameter } }, (Diameter, 3)); + + Assert.Equal(positions, formulaPositions); + } // The circle faces: two ends of the outline made of the facets, and a row of flat sides for each half. [Fact] diff --git a/tests/RvtIO.Tests/Families/FamilyModelBuilderTests.cs b/tests/RvtIO.Tests/Families/FamilyModelBuilderTests.cs index 936bb6d7..9e1e4009 100644 --- a/tests/RvtIO.Tests/Families/FamilyModelBuilderTests.cs +++ b/tests/RvtIO.Tests/Families/FamilyModelBuilderTests.cs @@ -185,9 +185,17 @@ public void ASlantedDimensionIsUnsupported() [Theory] [InlineData(Width)] [InlineData(Height)] - public void AFormulaOnADrivingParameterIsUnsupported(long parameter) => - AssertRefused(SyntheticFamily.Leaf() with { FormulaParameterIds = new HashSet { parameter } }, - "unsupported-construct", parameter.ToString()); + public void AFormulaOnADrivingParameterTakesTheValueTheTypeStores(long parameter) + { + var leaf = SyntheticFamily.Leaf(); + var (corners, start, end) = Shape(leaf, 4, 3); + + var (formulaCorners, formulaStart, formulaEnd) = + Shape(leaf with { FormulaParameterIds = new HashSet { parameter } }, 4, 3); + + Assert.Equal(corners, formulaCorners); + Assert.Equal((start, end), (formulaStart, formulaEnd)); + } [Fact] public void VisibleUnsupportedContentRefuses() => diff --git a/tests/RvtIO.Tests/Families/FamilyRevolutionTests.cs b/tests/RvtIO.Tests/Families/FamilyRevolutionTests.cs index 0f5843db..a35c795f 100644 --- a/tests/RvtIO.Tests/Families/FamilyRevolutionTests.cs +++ b/tests/RvtIO.Tests/Families/FamilyRevolutionTests.cs @@ -291,6 +291,149 @@ double[] Round(int step, double z) => Assert.Equal(3, matched!.Count); } + // A corner of the circle of a radius about the vertical through the origin, at an angle in degrees and a height. + private static double[] OnCircle(double radius, double degrees, double z) => + [radius * Math.Cos(degrees * Math.PI / 180), radius * Math.Sin(degrees * Math.PI / 180), z]; + + private static double[] Halfway(double[] a, double[] b) => [(a[0] + b[0]) / 2, (a[1] + b[1]) / 2, (a[2] + b[2]) / 2]; + + private static GeoFace Face(params double[][] corners) => new(new double[3], [0, 0, 1]) { OuterVertices = [.. corners] }; + + // A circle as the file stores it, an octagon: its corners at every 45 degrees. + private static IEnumerable Octagon(double radius, double z) => Enumerable.Range(0, 8).Select(step => OnCircle(radius, 45 * step, z)); + + // The side between two heights as eight strips; where a strip meets a circle, its corners hold the middle of the chord too, as + // the sections of the mesh of Revit meet there. + private static IEnumerable Strips(double radius, double from, double to) => + Enumerable.Range(0, 8).Select(step => + { + double[] a = OnCircle(radius, 45 * step, from), b = OnCircle(radius, 45 * (step + 1), from); + double[] c = OnCircle(radius, 45 * (step + 1), to), d = OnCircle(radius, 45 * step, to); + return Face(a, Halfway(a, b), b, c, Halfway(c, d), d); + }); + + // Revit cuts a circle into the sections of a polygon inscribed in it: a corner of a face is on the circle or on a chord between + // two neighbouring corners of the circle, inside it. + [Fact] + public void ACornerOnAChordBetweenTwoNeighbouringCornersOfItsCircleMatches() + { + var (revolution, positions) = Outline((0, 0), (1, 0), (1, 2), (0, 2)); + List stored = [Face([.. Octagon(1, 0)]), Face([.. Octagon(1, 2)]), .. Strips(1, 0, 2)]; + + var matched = FamilyRevolutionBuilder.Match(revolution, positions, stored); + + Assert.NotNull(matched); + Assert.Equal(3, matched!.Count); + } + + private static double[] Along(double[] a, double[] b, double fraction) => + [a[0] + fraction * (b[0] - a[0]), a[1] + fraction * (b[1] - a[1]), a[2] + fraction * (b[2] - a[2])]; + + // What the file stores of the cylinder when it cuts the corner of the octagon at 90 degrees away (as the rim of the valve): no + // corner there, two on the sides that meet at it, on the way to a corner that is stored nowhere. Irregular: the corners of the + // bottom circle are at 0, 45, 135, 180, 240 and 300 degrees, gaps of 45, 90, 45, 60, 60 and 60: a step of 45 degrees and no + // regular polygon. + private static List WithTheCornerAtNinetyCutAway(double fraction = 0.93, bool irregular = false) + { + double[] Side(double from, double z) => Along(OnCircle(1, from, z), OnCircle(1, 90, z), fraction); + GeoFace Cap(double z) => Face([.. (irregular && z == 0 ? new[] { 0.0, 45, 135, 180, 240, 300 } : new[] { 0.0, 45, 135, 180, 225, 270, 315 }) + .Select(angle => OnCircle(1, angle, z)), Side(45, z), Side(135, z)]); + return + [ + Cap(0), Cap(2), + .. Strips(1, 0, 2).Where((_, step) => irregular ? step is 0 or 3 : step != 1 && step != 2), + Face(OnCircle(1, 45, 0), Side(45, 0), Side(45, 2), OnCircle(1, 45, 2)), + Face(Side(135, 0), OnCircle(1, 135, 0), OnCircle(1, 135, 2), Side(135, 2)), + ]; + } + + // The sections the file cuts a circle into are those of a regular polygon: a corner the file leaves out, where another form + // trims it away, is a corner of that polygon all the same, and the corners left on the two sides that meet there are on them. + [Fact] + public void ACornerOnAChordToACornerTheFileCutAwayMatches() + { + var (revolution, positions) = Outline((0, 0), (1, 0), (1, 2), (0, 2)); + + var matched = FamilyRevolutionBuilder.Match(revolution, positions, WithTheCornerAtNinetyCutAway()); + + Assert.NotNull(matched); + Assert.Equal(3, matched!.Count); + } + + [Theory] + [InlineData("pushed in towards the axis")] + [InlineData("an irregular polygon")] + public void ACornerOnNoChordToACornerTheFileCutAwayDoesNotMatch(string change) + { + var (revolution, positions) = Outline((0, 0), (1, 0), (1, 2), (0, 2)); + Assert.NotNull(FamilyRevolutionBuilder.Match(revolution, positions, WithTheCornerAtNinetyCutAway())); + + // The same corners with one off the side (a corner of a face of the side: a point of the disc is on the disc wherever it is), + // or corners of the circle that are not those of a regular polygon. + var stored = WithTheCornerAtNinetyCutAway(irregular: change == "an irregular polygon"); + if (change == "pushed in towards the axis") + { + var corner = stored[^2].OuterVertices![1]; + stored[^2].OuterVertices![1] = [corner[0], corner[1] - 0.05, corner[2]]; + } + + Assert.Null(FamilyRevolutionBuilder.Match(revolution, positions, stored)); + } + + // The same on a ring, whose face holds the chords of the circle it meets the inner cylinder at. + [Fact] + public void ACornerOnAChordOfTheInnerCircleOfARingMatches() + { + var (revolution, positions) = Outline((1, 0), (2, 0), (2, 1), (1, 1)); + GeoFace Ring(double z) => Face([.. Octagon(2, z), .. Octagon(1, z), .. Enumerable.Range(0, 8).Select(step => + Halfway(OnCircle(1, 45 * step, z), OnCircle(1, 45 * (step + 1), z)))]); + List stored = [Ring(0), Ring(1), .. Strips(2, 0, 1), .. Strips(1, 0, 1)]; + + var matched = FamilyRevolutionBuilder.Match(revolution, positions, stored); + + Assert.NotNull(matched); + Assert.Equal(4, matched!.Count); + } + + [Theory] + [InlineData("inside the circle, off every chord")] + [InlineData("on a chord that passes a corner of the circle")] + public void ACornerInsideItsCircleThatIsOnNoChordBetweenNeighboursDoesNotMatch(string change) + { + var (revolution, positions) = Outline((0, 0), (1, 0), (1, 2), (0, 2)); + var strips = Strips(1, 0, 2).ToList(); + List stored = [Face([.. Octagon(1, 0)]), Face([.. Octagon(1, 2)]), .. strips]; + Assert.NotNull(FamilyRevolutionBuilder.Match(revolution, positions, stored)); + + switch (change) + { + // The middle of the chord pushed in towards the axis, off the chord. + case "inside the circle, off every chord": strips[0].OuterVertices![1] = OnCircle(0.8, 22.5, 0); break; + // A corner of the circle between the ends of the chord: the neighbours are not those two. + case "on a chord that passes a corner of the circle": stored[0].OuterVertices!.Add(OnCircle(1, 20, 0)); break; + } + + Assert.Null(FamilyRevolutionBuilder.Match(revolution, positions, stored)); + } + + // Corners that do not go round the axis (here three, a quarter turn apart, over half of it) are no polygon inscribed in the + // circle: the chord between two of them says nothing of the surface. + [Fact] + public void ACornerOnAChordOfCornersThatDoNotGoRoundTheAxisDoesNotMatch() + { + var (revolution, positions) = Outline((0, 0), (1, 0), (1, 2), (0, 2)); + List FacesWith(bool chord) => + [ + Face(OnCircle(1, 0, 0), OnCircle(1, 90, 0), OnCircle(1, 180, 0), OnCircle(0, 0, 0)), + Face([.. Octagon(1, 2)]), + Face([OnCircle(1, 0, 0), .. chord ? [Halfway(OnCircle(1, 0, 0), OnCircle(1, 90, 0))] : Array.Empty(), + OnCircle(1, 90, 0), OnCircle(1, 180, 0), OnCircle(1, 180, 2), OnCircle(1, 0, 2)]), + ]; + + Assert.NotNull(FamilyRevolutionBuilder.Match(revolution, positions, FacesWith(false))); + Assert.Null(FamilyRevolutionBuilder.Match(revolution, positions, FacesWith(true))); + } + [Theory] [InlineData("vertex off the surface")] [InlineData("surface without faces")] From f1f210e69b8a066a973e4e11769e1a361fd3ddf2 Mon Sep 17 00:00:00 2001 From: Mahach <79989386+mahach666@users.noreply.github.com> Date: Wed, 2 Dec 2026 18:09:46 +0300 Subject: [PATCH 06/14] Compute the loaded families of a family in every type and show them placed An instance of a family loaded into a family file (the four flanges of the AquaFix valve) is computed in every type from the document of the loaded family, which the file keeps in a block of its own. The loaded family takes the values of the type of the host through the associations of the instance, its extrusions are solved like those of the host, and its faces are placed by the origin and basis of the instance. For the saved type the placed faces must be the faces the file stores for the instance, one for one, and each face takes the style of the stored face it is. A type that chooses another type of the loaded family is refused alone; a loaded family of several types, hidden or void content, a revolution, a combination, an instance or a parameter of visibility or material of its own, and a basis that is no rotation are refused with the reason. A shared parameter that a loaded family uses is read from the first block of the file. A dimension that holds an angle, reference lines that lie apart from the drawn lines of a sketch, and an instance tied to a work plane are read as relations. The 14 types of the valve are computed with their flanges; the ends of every flange, its sizes across the pipe and its volume agree with the measure taken in Revit 2022 (see the flange tests for the tolerances). --- CHANGELOG.md | 9 + docs/scene.md | 5 +- src/RvtIO/Families/FamilyData.cs | 22 +- src/RvtIO/Families/FamilyFormulas.cs | 318 ++++++++++++++++++ src/RvtIO/Families/FamilyModel.cs | 13 +- src/RvtIO/Families/FamilyModelBuilder.cs | 171 +++++++++- src/RvtIO/Families/FamilyNested.cs | 160 +++++++++ src/RvtIO/Families/FamilyRecordReader.cs | 113 +++++-- src/RvtIO/Families/FamilyRecords.cs | 35 +- src/RvtIO/Families/FamilyRelationReader.cs | 134 +++++++- src/RvtIO/Families/FamilySavedState.cs | 11 +- src/RvtIO/Families/FamilySolver.cs | 1 + src/RvtIO/Families/NestedFamilies.cs | 103 ++++++ src/RvtIO/Meshes/ElementMeshes.cs | 98 +++++- src/RvtIO/Writing/ParameterMeasurement.cs | 6 + .../Families/AquaFixFlangeTests.cs | 271 +++++++++++++++ .../RvtIO.Tests/Families/AquaFixValveTests.cs | 29 +- .../Families/FamilyCombinationFaceTests.cs | 78 +++++ .../Families/FamilyFormulaTests.cs | 82 +++++ .../Families/FamilyPlacementTests.cs | 174 ++++++++++ .../Families/FamilyReferenceLineTests.cs | 161 +++++++++ .../Families/NestedFamilyLinkTests.cs | 53 +++ .../Families/NestedInstanceRecordTests.cs | 100 ++++++ 23 files changed, 2066 insertions(+), 81 deletions(-) create mode 100644 src/RvtIO/Families/FamilyFormulas.cs create mode 100644 src/RvtIO/Families/FamilyNested.cs create mode 100644 src/RvtIO/Families/NestedFamilies.cs create mode 100644 tests/RvtIO.Tests/Families/AquaFixFlangeTests.cs create mode 100644 tests/RvtIO.Tests/Families/FamilyCombinationFaceTests.cs create mode 100644 tests/RvtIO.Tests/Families/FamilyFormulaTests.cs create mode 100644 tests/RvtIO.Tests/Families/FamilyPlacementTests.cs create mode 100644 tests/RvtIO.Tests/Families/FamilyReferenceLineTests.cs create mode 100644 tests/RvtIO.Tests/Families/NestedFamilyLinkTests.cs create mode 100644 tests/RvtIO.Tests/Families/NestedInstanceRecordTests.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index c296d85f..04b16692 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -41,6 +41,15 @@ API between minor releases. A combination without members, a form that two combinations hold, a member that is no extrusion or revolution of the family or that a family parameter shows or hides, and a parameter that drives the combination itself are refused. A side alignment of two joined lines of a sketch that run along one axis is read as the relation the join already gives. +- An instance of a family loaded into the family (the flanges of a valve) is computed in every type from the document of the + loaded family, which the file keeps in a block of its own: that family takes the values of the type of the host through the + associations of the instance, its extrusions are solved like those of the host, and its faces are placed by the origin and + the basis of the instance. For the saved type the placed faces must be the faces the file stores for the instance, one for + one, and each face takes the style of the stored face it is. A type of the host that chooses another type of the loaded + family is refused alone. A loaded family of several types, with hidden or void content, a revolution, a combination, an + instance or a parameter of visibility or material of its own, or an instance whose basis is no rotation, is refused with the + reason. A shared parameter that a loaded family uses is read from the first block of the file. A dimension that holds an + angle, reference lines that lie apart from the drawn lines of a sketch and an instance tied to a work plane are read as relations. - A parameter that drives a dimension or a form of a family and is given by a formula no longer makes the family refuse: each type stores the value its parameter has, that value is used as stored, and the formula is not evaluated again. For the saved type the computed faces are still checked against the stored ones. diff --git a/docs/scene.md b/docs/scene.md index 69a5245c..b03974b1 100644 --- a/docs/scene.md +++ b/docs/scene.md @@ -114,9 +114,10 @@ arcs whose ends lie on the axes through their centre, a whole number of quarter and of revolutions of a whole turn whose profile is closed loops of straight lines about a line of the sketch along an axis of its plane (each surface is cut into 18 facets; a revolution of an arc or a part of a turn is not computed), and of combinations of such forms (drawn as the faces of their members, whole; the trimmed faces the file stores for the joined -shape are compared by their box only), +shape are compared by their box only), and of instances of a family loaded into it (each solved from the document of the loaded +family with the values its associations take from the type, and placed by the origin and basis of the instance), placed by reference planes, dimensions, radius and diameter dimensions, alignments and joined sketch lines the reader -recognizes, with no cuts, no visible nested family and no formula on a parameter that moves the shape, and only when what +recognizes, with no cuts, and no formula on a parameter that moves the shape, and only when what is computed for the saved type is what the file stores for it. A control icon (the arrow that flips a form) of the family is not a relation; a dimension to it that no parameter labels is ignored. The code of a refusal says what stands in the way: diff --git a/src/RvtIO/Families/FamilyData.cs b/src/RvtIO/Families/FamilyData.cs index dd8fef19..18408ffd 100644 --- a/src/RvtIO/Families/FamilyData.cs +++ b/src/RvtIO/Families/FamilyData.cs @@ -19,15 +19,35 @@ internal sealed class FamilyData /// not read. internal FamilyRecords? Records { get; init; } + /// The families loaded into the family that its shown instances are of, with their documents; null when it has no + /// shown instance or one of those cannot be read ( says why). + internal IReadOnlyList? Nested { get; init; } + + /// Why is null for a family with a shown instance. + internal string? NestedError { get; init; } + /// What computing a type needs, made at the first one that is computed. internal FamilyPreparation? Prepared { get; set; } } +/// A family loaded into the family: where its document is, what its records say and what its formulas and size tables +/// give. +internal sealed record NestedFamilyData(LoadedFamily Link, FamilyData Data, FamilyFormulas Formulas); + +/// What one placed instance of a loaded family needs to be computed: the model of the loaded family and the stored face +/// each face of it is in the instance at the saved type, by the element of the loaded family and the face of its model. +internal sealed record NestedPlacementState(NestedShape Shape, + IReadOnlyDictionary<(int ElementId, FamilyFaceKey Face), GeoFace> Stored); + /// A model of a family whose saved state it reproduces, with the stored face each of its faces is and the elements /// of the saved type in document order; or why no type of the family is computed. internal sealed record FamilyPreparation(FamilyModel? Model, IReadOnlyDictionary<(int ElementId, FamilyFaceKey Face), GeoFace>? Faces, IReadOnlyList Elements, - RvtFamilyRefusal? Refusal); + RvtFamilyRefusal? Refusal) +{ + /// The placed instances of loaded families, by element of the instance. + public IReadOnlyDictionary? Nested { get; init; } +} /// What the file records about one element, for the shape of the family at its saved type in a 3D view at the Fine /// detail level. diff --git a/src/RvtIO/Families/FamilyFormulas.cs b/src/RvtIO/Families/FamilyFormulas.cs new file mode 100644 index 00000000..b229489e --- /dev/null +++ b/src/RvtIO/Families/FamilyFormulas.cs @@ -0,0 +1,318 @@ +using System.Globalization; +using OpenMcdf; +using RvtIO.Lookup; +using RvtIO.Model; +using RvtIO.Parsing; +using RvtIO.Writing; +using static RvtIO.Writing.LoadedFamilyParameterWriter; + +namespace RvtIO.Families; + +/// The parameters of a family document with their formulas and size tables, read from its record, and the values they +/// give for the inputs of a type. Every calculation is Revit's or it is refused: an expression, a function or a table the +/// reader does not know gives a refusal, never a nearby value. Lengths are in feet, as the file stores them. +internal sealed class FamilyFormulas +{ + private const double Tolerance = 1e-9; // Revit's relative tolerance for comparing numbers + private const double RevitPi = 3.14159265358979; + private const string TableCount = "size-tables", TableName = "size-table-name", RowCount = "size-table-rows", + ColumnCount = "size-table-columns", ColumnName = "size-table-column-name", ColumnUnit = "size-table-column-unit", + RowCells = WideBlockWalker.AllItemsKeyPrefix + "size-table-row"; + private const string Arguments = WideBlockWalker.AllItemsKeyPrefix + "FunctionExpression.m_subexpressions"; + + 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, SizeLookup = 21, Ln = 22, + } + + /// A size table: its columns by name and its rows of numbers and texts, in the order of the file; a number is in + /// feet, or whatever internal unit its column measures. The first column names the row; the lookup keys of a formula are + /// matched against the columns after it. + internal sealed record SizeTable(string Name, IReadOnlyList Columns, IReadOnlyList> Rows); + + private sealed record Row(long Id, StorageType Storage, int? Formula, bool Reporting, Val Stored); + + private readonly record struct Val(double Number = 0, string? Text = null, bool Boolean = false); + + private sealed class Refused(string code, string detail) : Exception + { + public RvtFamilyRefusal Refusal { get; } = new(code, detail); + } + + private readonly WideBlockWalker _walker; + private readonly WideBlockWalker.Walk _walk; + private readonly Dictionary _rows; + + private FamilyFormulas(WideBlockWalker walker, WideBlockWalker.Walk walk, Dictionary rows, SizeTable[] tables) + { + (_walker, _walk, _rows, Tables) = (walker, walk, rows, tables); + } + + /// The size tables of the document. + internal IReadOnlyList Tables { get; } + + /// The parameters a formula gives the value of. + internal IReadOnlySet Driven => _rows.Values.Where(row => row.Formula != null).Select(row => row.Id).ToHashSet(); + + /// The parameters whose value is measured from the geometry of the document: no formula calculates them, and + /// another type has another value. + internal IReadOnlySet Reporting => _rows.Values.Where(row => row.Reporting).Select(row => row.Id).ToHashSet(); + + /// The numbers the document stores for its parameters. + internal IReadOnlyDictionary Stored => + _rows.Values.Where(row => row.Storage is StorageType.Double or StorageType.Integer or StorageType.ElementId) + .ToDictionary(row => row.Id, row => row.Stored.Number); + + /// The formulas and tables of the family in the partitions of , or why + /// they are not read. + internal static (FamilyFormulas? Formulas, string? Error) Read(RootStorage root, long ownerId, ElementIdMap? ids, + IReadOnlyDictionary? currentCopies, int block) + { + try + { + var (walker, family, bodies) = FamilyRecordReader.WalkFamilyRecord(root, ownerId, currentCopies, block, CaptureKey); + var store = ReadStore(walker, family, "FamilyBase.m_familyParams"); + var rows = new Dictionary(); + foreach (var named in store.Rows) + { + var storage = FamilyRecordReader.StorageOf(walker, bodies, ids, named.Id); + int? formula = named.Fields[1].Integer != 0 ? ParameterFormulaEvaluator.ChildSlot(named.Fields[1], family) : null; + var stored = storage switch + { + StorageType.Double => new Val(named.Fields[2].Real), + StorageType.Integer or StorageType.ElementId => new Val(named.Value(storage).Integer), + StorageType.String => new Val(Text: named.Fields[0].Text ?? ""), + _ => default, + }; + if (!rows.TryAdd(named.Id, new(named.Id, storage, formula, named.Fields[7].Integer != 0, stored))) + throw ParameterWriter.Unverified($"The family stores parameter {named.Id} twice."); + } + return (new FamilyFormulas(walker, family, rows, ReadTables(family)), null); + } + catch (RvtWriteRefusedException ex) { return (null, ex.Message); } + } + + private static string? CaptureKey(SchemaClass declaring, SchemaField field) => (declaring.Name, field.Name) switch + { + ("FamilySizeTableManager", "m_mapSizeTables") => TableCount, + ("std::pair< AString, FamilySizeTable >", "first") => TableName, + ("FamilySizeTable", "m_cellValues") => RowCount, + ("FamilySizeTable", "m_columns") => ColumnCount, + ("FamilySizeTableColumn", "m_name") => ColumnName, + ("ForgeTypeId", "m_typeId") => ColumnUnit, + ("FamilySizeTableRow", "m_rowValues") => RowCells, + ("DoubleParameterValue" or "IntegerParameterValue" or "StringParameterValue", "m_value") => declaring.Name + ".m_value", + _ => StandaloneFamilyParameterWriter.CaptureKey(declaring, field), + }; + + private static SizeTable[] ReadTables(WideBlockWalker.Walk walk) + { + if (walk.Captures.Where(c => c.Key == TableCount + "#").ToArray() is not [var count]) return []; + var items = walk.Captures.Where(c => c.QueueIndex == count.QueueIndex).ToArray(); + int at = Array.IndexOf(items, count) + 1; + var tables = new List(); + for (long t = 0; t < count.Integer; t++) + { + string name = Next(TableName).Text ?? throw Bad(); + var rowCount = Next(RowCount + "#"); + var rows = new List>(); + for (long r = 0; r < rowCount.Integer; r++) + { + long cells = Next(RowCells + "#").Integer; + var row = new List(); + for (long c = 0; c < cells; c++) + { + int cell = ParameterFormulaEvaluator.ChildSlot(Next(RowCells + "@" + c), walk); + var values = walk.Captures.Where(x => x.QueueIndex == cell && x.Key.EndsWith(".m_value", StringComparison.Ordinal)).ToArray(); + row.Add(values is [var value] ? value.Key switch + { + "DoubleParameterValue.m_value" => value.Real, + "IntegerParameterValue.m_value" => (double)value.Integer, + "StringParameterValue.m_value" => value.Text ?? "", + _ => throw Bad(), + } : throw Bad()); + } + rows.Add(row); + } + long columnCount = Next(ColumnCount + "#").Integer; + var columns = new string[columnCount]; + var factors = new double[columnCount]; + for (int c = 0; c < columnCount; c++) + { + columns[c] = Next(ColumnName).Text ?? throw Bad(); + // The specification of the column, then its unit: a column of texts has neither. + _ = Next(ColumnUnit); + string unit = Next(ColumnUnit).Text ?? throw Bad(); + factors[c] = unit.Length == 0 ? 1 : ParameterMeasurement.InternalPerUnit(unit) + ?? throw ParameterWriter.Unverified("A size table column has the unit " + unit + ", which is not known."); + } + if (rows.Any(row => row.Count != columns.Length)) throw Bad(); + rows = [.. rows.Select(row => (IReadOnlyList)[.. row.Select((cell, c) => cell is double number ? number * factors[c] : cell)])]; + tables.Add(new(name, columns, rows)); + } + return [.. tables]; + + WideBlockWalker.Capture Next(string key) => at < items.Length && items[at].Key == key ? items[at++] : throw Bad(); + static RvtWriteRefusedException Bad() => ParameterWriter.Unverified("A size table of the family could not be read exactly."); + } + + /// Why a formula does not reproduce the value the document stores for its parameter; null when every one does. + internal string? CheckStored() + { + var (values, refusal) = Evaluate(_ => null); + if (values == null) return $"{refusal!.Code}: {refusal.Detail}"; + foreach (var row in _rows.Values.Where(row => row.Formula != null && row.Storage is StorageType.Double or StorageType.Integer)) + if (!Close(values[row.Id], row.Stored.Number)) return $"parameter {row.Id} is {values[row.Id]:R}, stored {row.Stored.Number:R}"; + return null; + } + + /// The number of every numeric parameter for the inputs of a type: gives the value of a + /// parameter no formula calculates (null: the stored one); the formulas are calculated from them. Or why it cannot be done. + internal (Dictionary? Values, RvtFamilyRefusal? Refusal) Evaluate(Func input) + { + var memo = new Dictionary(); + var active = new HashSet(); + try + { + foreach (var row in _rows.Values.Where(row => row.Storage is StorageType.Double or StorageType.Integer or StorageType.ElementId)) + Parameter(row.Id); + return (_rows.Values.Where(row => memo.ContainsKey(row.Id) && row.Storage is StorageType.Double or StorageType.Integer or StorageType.ElementId) + .ToDictionary(row => row.Id, row => memo[row.Id].Number), null); + } + catch (Refused refused) { return (null, refused.Refusal); } + catch (RvtWriteRefusedException ex) { return (null, new("unsupported-construct", ex.Message)); } + + Val Parameter(long id) + { + if (memo.TryGetValue(id, out var known)) return known; + if (!_rows.TryGetValue(id, out var row)) throw new Refused("unrecognized-reference", "formula parameter " + Text(id)); + if (!active.Add(id)) throw new Refused("unsupported-construct", "formulas of parameter " + Text(id) + " depend on each other"); + Val value; + if (row.Formula is int slot) value = Visit(slot); + else if (input(id) is double given) value = new(given); + else if (row.Reporting) throw new Refused("underdetermined", "measured parameter " + Text(id)); + else value = row.Stored; + active.Remove(id); + memo[id] = value; + return value; + } + + Val Visit(int slot) + { + switch (_walker.Class(_walk.Queue[slot])?.Name) + { + case "ParameterExpression": return Parameter(Field(slot, "formula-reference").Integer); + case "NumberConstantExpression": return new(Field(slot, "NumberConstantExpression.m_value").Real); + case "StringConstantExpression": return new(Text: Field(slot, "StringConstantExpression.m_value").Text ?? ""); + case "ParenExpression": return Visit(Child(slot, "ParenExpression.m_pSubexpression")); + case "UnaryOperatorExpression": + if (Field(slot, "UnaryOperatorExpression.m_unaryOperator").Integer != 1) throw Unsupported("unary operator"); + return new(-Number(Visit(Child(slot, "UnaryOperatorExpression.m_pSubexpression")))); + case "BinaryOperatorExpression": + long operation = Field(slot, "BinaryOperatorExpression.m_binaryOperator").Integer; + double left = Number(Visit(Child(slot, "BinaryOperatorExpression.m_pLeftSubexpression"))); + double right = Number(Visit(Child(slot, "BinaryOperatorExpression.m_pRightSubexpression"))); + return operation switch + { + 1 => new(left + right), + 2 => new(left - right), + 3 => new(left * right), + 4 when Math.Abs(right) > Tolerance => new(left / right), + 5 when Math.Pow(left, right) is double power && double.IsFinite(power) => new(power), + 6 => new(Boolean: Compare(left, right) == 0), + 7 => new(Boolean: Compare(left, right) > 0), + 8 => new(Boolean: Compare(left, right) < 0), + _ => throw Unsupported("binary operator " + Text(operation)), + }; + case "FunctionExpression": return Call(slot); + default: throw Unsupported(_walker.Class(_walk.Queue[slot])?.Name ?? "an expression"); + } + } + + Val Call(int slot) + { + var function = (Function)Field(slot, "FunctionExpression.m_function").Integer; + int count = (int)Field(slot, Arguments + "#").Integer; + Val Argument(int index) => Visit(Child(slot, Arguments + "@" + index)); + if (function == Function.SizeLookup) return Lookup(count, Argument); + if (function == Function.Pi && count == 0) return new(RevitPi); + switch (function, count) + { + case (Function.If, 3): return Argument(Flag(Argument(0)) ? 1 : 2); + case (Function.And, 2): return new(Boolean: Flag(Argument(0)) && Flag(Argument(1))); + case (Function.Or, 2): return new(Boolean: Flag(Argument(0)) || Flag(Argument(1))); + case (Function.Not, 1): return new(Boolean: !Flag(Argument(0))); + } + double x = count == 1 ? Number(Argument(0)) : throw Unsupported("function " + Text((long)function)); + return function switch + { + Function.Abs => new(Math.Abs(x)), + Function.Sqrt when x >= 0 => new(Math.Sqrt(x)), + Function.Exp when Math.Exp(x) is double e && Math.Abs(e) <= 1e30 => new(e), + Function.Log when x >= Tolerance => new(Math.Log10(x)), + Function.Ln when x >= Tolerance => new(Math.Log(x)), + Function.Sin => new(Math.Sin(x)), + Function.Cos => new(Math.Cos(x)), + Function.Tan when Math.Abs(Math.Cos(x)) > Tolerance => new(Math.Tan(x)), + Function.Asin when Math.Abs(x) <= 1 => new(Math.Asin(x)), + Function.Acos when Math.Abs(x) <= 1 => new(Math.Acos(x)), + Function.Atan => new(Math.Atan(x)), + Function.Round => new(ParameterFormulaEvaluator.Round(x)), + Function.RoundUp => new(Math.Ceiling(x)), + Function.RoundDown => new(Math.Floor(x)), + _ => throw Unsupported("argument of function " + Text((long)function)), + }; + } + + // size_lookup(table, column, default, key...): the value of the column in the row whose columns after the first are the keys. + Val Lookup(int count, Func argument) + { + if (count < 4 || argument(0).Text is not { } tableName || argument(1).Text is not { } columnName) + throw Unsupported("size_lookup arguments"); + var table = Tables.SingleOrDefault(candidate => candidate.Name == tableName) + ?? throw new Refused("unrecognized-reference", "size table " + tableName); + int column = IndexOf(table.Columns, columnName); + double[] keys = [.. Enumerable.Range(3, count - 3).Select(index => Number(argument(index)))]; + if (keys.Length >= table.Columns.Count) throw Unsupported("size_lookup keys"); + // Only a row that has every key is the row; no row is no value, as the default Revit gives is not a size of the family. + var rows = table.Rows.Where(row => keys.Select((key, index) => row[index + 1] is double cell && Close(cell, key)).All(match => match)).ToArray(); + return rows is [var found] && found[column] is double result ? new(result) + : throw new Refused("underdetermined", $"row of {tableName} for {string.Join(", ", keys.Select(key => key.ToString("R", CultureInfo.InvariantCulture)))}"); + } + + int Child(int parent, string key) => ParameterFormulaEvaluator.ChildSlot(FieldOf(parent, key), _walk); + + WideBlockWalker.Capture Field(int slot, string key) => FieldOf(slot, key); + + WideBlockWalker.Capture FieldOf(int slot, string key) => + _walk.Captures.Where(c => c.QueueIndex == slot && c.Key == key).ToArray() is [var field] ? field + : throw Unsupported("expression field " + key); + } + + private static int IndexOf(IReadOnlyList columns, string name) + { + for (int i = 0; i < columns.Count; i++) + if (columns[i] == name) return i; + throw new Refused("unrecognized-reference", "size table column " + name); + } + + private static double Number(Val value) => + value.Text == null ? value.Number : throw Unsupported("a text where a number is"); + + private static bool Flag(Val value) => value.Text == null ? value.Number != 0 : throw Unsupported("a text where a condition is"); + + private static bool Close(double a, double b) => Math.Abs(a - b) <= Tolerance * (Math.Abs(a) + Math.Abs(b)); + + // Two numbers that differ by no more than Revit's tolerance are not told apart the way it does: that is not established. + private static int Compare(double a, double b) + { + if (a == b) return 0; + if (Close(a, b)) throw Unsupported("a comparison within Revit's tolerance"); + return a < b ? -1 : 1; + } + + private static string Text(long number) => number.ToString(CultureInfo.InvariantCulture); + + private static Refused Unsupported(string what) => new("unsupported-construct", what); +} diff --git a/src/RvtIO/Families/FamilyModel.cs b/src/RvtIO/Families/FamilyModel.cs index a8f5ceca..670a0ba8 100644 --- a/src/RvtIO/Families/FamilyModel.cs +++ b/src/RvtIO/Families/FamilyModel.cs @@ -9,7 +9,7 @@ namespace RvtIO.Families; /// Σ Coefficient·variable = Sign·the value of ParameterId when it is set, otherwise Constant. /// SourceElementId is the record of the family the relation comes from. A weak relation, from an unlocked dimension, /// holds only what the others leave free. An offset relation places an end of an extrusion from its sketch plane: its -/// parameter may be zero or below, where a labelled dimension has to be above zero. +/// parameter may be zero or below, where a labelled dimension has to be above zero; so does an angle that its label holds. /// internal sealed record FamilyEquation(IReadOnlyList Terms, long? ParameterId, int Sign, double Constant, int SourceElementId, bool IsWeak = false, bool IsOffset = false); @@ -57,6 +57,15 @@ internal sealed record FamilyRevolution(int ElementId, IReadOnlyList internal sealed record FamilyCombination(int ElementId, IReadOnlyList Members); +/// +/// A family loaded into the family and placed in it. Origin holds the variables of the three coordinates of the point +/// it stands at; Basis its stand, the images in the frame of the family of the three axes of its symbol, which no type +/// changes. SymbolId is the symbol the instance is of and MasterSymbolId the one that holds what its +/// parameters are associated with. The shape of the family includes the shape of the instance, placed. +/// +internal sealed record FamilyPlacement(int ElementId, int SymbolId, int MasterSymbolId, IReadOnlyList Origin, + double[][] Basis, long? VisibilityParameterId); + /// The forms of a family and the relations that place them. internal sealed record FamilyModel(IReadOnlyList Variables, IReadOnlyList Equations, IReadOnlyList Extrusions) @@ -64,6 +73,8 @@ internal sealed record FamilyModel(IReadOnlyList Variables, IRea public IReadOnlyList Revolutions { get; init; } = []; public IReadOnlyList Combinations { get; init; } = []; + + public IReadOnlyList Placements { get; init; } = []; } /// The value of every variable for one type, or why there is none. diff --git a/src/RvtIO/Families/FamilyModelBuilder.cs b/src/RvtIO/Families/FamilyModelBuilder.cs index c2c43e67..a3f2bc56 100644 --- a/src/RvtIO/Families/FamilyModelBuilder.cs +++ b/src/RvtIO/Families/FamilyModelBuilder.cs @@ -82,6 +82,10 @@ private sealed record Equation(List<(int Node, int Coefficient)> Terms, long? Pa private readonly Dictionary _planes = records.Planes.ToDictionary(plane => plane.ElementId); private readonly Dictionary _extrusions = records.Extrusions.ToDictionary(extrusion => extrusion.Id); + private readonly Dictionary _instances = (records.Instances ?? []).ToDictionary(instance => instance.Id); + private readonly Dictionary _symbols = (records.Symbols ?? []).ToDictionary(symbol => symbol.Id); + // The instances whose origin is tied to the plane they stand on. + private readonly HashSet _stood = []; private readonly Dictionary _revolutions = (records.Revolutions ?? []).ToDictionary(revolution => revolution.Id); private readonly Dictionary _combinations = @@ -94,6 +98,11 @@ private sealed record Equation(List<(int Node, int Coefficient)> Terms, long? Pa private readonly HashSet _heldCaps = []; private HashSet _profileArcs = []; private HashSet _circles = []; + // Reference lines in sketches of their own that only dimensions to planes that stay put (or to each other) touch. + private HashSet _apartSketches = []; + private HashSet _apartLines = []; + private readonly Dictionary _angles = + (records.AngularDimensions ?? []).ToDictionary(angle => angle.Id); private bool IsProfileArc(int id) => _profileArcs.Contains(id) || _circles.Contains(id); @@ -101,6 +110,7 @@ public FamilyModel Build() { if (records.UnsupportedContent.Count > 0) throw Unsupported(string.Join(", ", records.UnsupportedContent.Distinct())); + foreach (var instance in _instances.Values.Where(instance => instance.Shown)) CheckInstance(instance); var axes = _extrusions.Values.ToDictionary(extrusion => extrusion.Id, CheckProfile); var turns = _revolutions.Values.ToDictionary(revolution => revolution.Id, CheckRevolution); CheckCombinations(); @@ -113,12 +123,16 @@ public FamilyModel Build() // What the sketch holds of a closed circle (its radius, its centre) holds the halves the profile has of it. _circles = arcs.Select(line => line.CircleId).OfType().ToHashSet(); - var dimensions = records.Dimensions.Where(dimension => !OnControlIcon(dimension)) + FindApart(); + HoldAngles(); + var dimensions = records.Dimensions + .Where(dimension => !dimension.References.Any(reference => _apartLines.Contains(reference.ElementId)) + && !OnControlIcon(dimension)) .Select(dimension => (Record: dimension, Nodes: Measured(dimension))).ToList(); Join(); RelateArcs(axes); var referencedLines = records.Dimensions.SelectMany(d => d.References).Select(r => r.ElementId) - .Where(_lines.ContainsKey).ToHashSet(); + .Where(id => _lines.ContainsKey(id) && !_apartLines.Contains(id)).ToHashSet(); var modelLines = _extrusions.Values .SelectMany(e => e.Loops.SelectMany(loop => loop).Select(key => e.ProfileCurves[key].LineId)) .Concat(_revolutions.Values.SelectMany(r => r.Loops.SelectMany(loop => loop.Select(c => c.LineId)).Append(r.AxisLineId))) @@ -130,13 +144,20 @@ public FamilyModel Build() PlaceHostFaces(dimensions); foreach (var (record, nodes) in dimensions) Relate(record, nodes); RelateRadii(); + // What no relation holds of an instance stands where the file left it. + var origins = _instances.Values.Where(instance => instance.Shown).ToDictionary(instance => instance.Id, + instance => Enumerable.Range(0, 3).Select(axis => OriginNode(instance, axis)).ToArray()); var caps = _extrusions.Values.ToDictionary(e => e.Id, e => PlaceCaps(e, axes[e.Id])); var vertices = _extrusions.Values.ToDictionary(e => e.Id, e => Vertices(e, axes[e.Id])); var placed = _revolutions.Values.ToDictionary(r => r.Id, r => PlaceRevolution(r, turns[r.Id])); + var related = _equations.SelectMany(equation => equation.Terms.Select(term => Root(term.Node))).ToHashSet(); + foreach (int node in origins.Values.SelectMany(origin => origin).Select(Root).Where(node => !related.Contains(node))) + _nodes[node].Anchored = true; Anchor(vertices.Values.SelectMany(loops => loops.SelectMany(loop => loop.SelectMany(v => v))) .Where(node => node >= 0).Concat(caps.Values.SelectMany(pair => new[] { pair.Low, pair.High })) - .Concat(placed.Values.SelectMany(p => p.Corners.SelectMany(loop => loop.SelectMany(v => v)).Append(p.Plane).Append(p.AxisPosition)))); - return Assemble(axes, caps, vertices, turns, placed); + .Concat(placed.Values.SelectMany(p => p.Corners.SelectMany(loop => loop.SelectMany(v => v)).Append(p.Plane).Append(p.AxisPosition))) + .Concat(origins.Values.SelectMany(origin => origin))); + return Assemble(axes, caps, vertices, turns, placed, origins); } /// The axis of an extrusion whose profile is straight lines along the two other axes and quarter-turn arcs @@ -323,9 +344,61 @@ private int Resolve(FamilyReference reference, int axis, int source) return !IsProfileArc(id) || AxisOf(Normal(arc.Arc)) is int square && square != axis ? Centre(arc, axis) : throw Unsupported($"centre of arc {id} measured by {source}"); if (_extrusions.TryGetValue(id, out var extrusion)) return OnExtrusion(extrusion, reference, axis, source); + if (_instances.TryGetValue(id, out var instance)) return OnInstance(instance, reference, axis, source); + // A face of a combination is a face of one of its members, as the steps that added the members say. + if (_combinations.TryGetValue(id, out var combination)) + return combination.Faces?.GetValueOrDefault(reference.GeometryTag) is { } origin && combination.Members.Contains(origin.Member) + ? Resolve(new(origin.Member, origin.Tag, reference.SubTag), axis, source) + : throw Unrecognized($"reference of {source} to tag {reference.GeometryTag} of element {id}"); throw Unrecognized($"reference of {source} to element {id}"); } + /// The stand of an instance is a turn or a reflection, and the plane it stands on, when it names one, is square + /// to an axis. + private void CheckInstance(FamilyInstanceRecord instance) + { + if (!_symbols.ContainsKey(instance.SymbolId)) throw Unrecognized($"symbol of instance {instance.Id}"); + var basis = instance.Basis; + double Dot(int a, int b) => Enumerable.Range(0, 3).Sum(row => basis[a][row] * basis[b][row]); + if (instance.Origin.Length != 3 || basis.Length != 3 || basis.Any(column => column.Length != 3) + || !Enumerable.Range(0, 3).All(a => Enumerable.Range(0, 3).All(b => Math.Abs(Dot(a, b) - (a == b ? 1 : 0)) <= Tolerance))) + throw Unsupported($"stand of instance {instance.Id}"); + if (instance.HostId > 0 && (instance.HostNormal == null || AxisOf(instance.HostNormal) == null)) + throw Unsupported($"work plane of instance {instance.Id}"); + } + + /// The coordinate along of a plane of the symbol of an instance, which is the coordinate + /// of the point the instance stands at when the plane goes through it: where a plane that does not goes depends on the + /// parameters of the family it is of. + private int OnInstance(FamilyInstanceRecord instance, FamilyReference reference, int axis, int source) + { + CheckInstance(instance); + if (reference.SubTag != -1 || !_symbols[instance.SymbolId].Planes.TryGetValue(reference.GeometryTag, out var plane)) + throw Unrecognized($"reference of {source} to tag {reference.GeometryTag} of element {instance.Id}"); + double[] normal = [.. Enumerable.Range(0, 3).Select(row => Enumerable.Range(0, 3).Sum(column => plane.Normal[column] * instance.Basis[column][row]))]; + if (AxisOf(normal) != axis || !(Math.Abs(Enumerable.Range(0, 3).Sum(i => plane.Normal[i] * plane.Origin[i])) <= Tolerance)) + throw Unsupported($"plane {reference.GeometryTag} of instance {instance.Id} measured by {source}"); + return OriginNode(instance, axis); + } + + /// The coordinate along of the point an instance stands at. An instance on a work plane + /// stands as far from what the plane follows as it stood; one on a plane that follows nothing keeps its place. + private int OriginNode(FamilyInstanceRecord instance, int axis) + { + int node = Keyed(("origin", instance.Id, axis), instance.Origin[axis], instance.Id); + if (instance.HostId > 0 && AxisOf(instance.HostNormal!) == axis && _stood.Add(instance.Id)) + { + if (instance.Host is { } followedReference) + { + int followed = Resolve(followedReference, axis, instance.Id); + if (double.IsNaN(_nodes[followed].Stored)) _nodes[followed].Stored = instance.Origin[axis]; + _equations.Add(new([(node, 1), (followed, -1)], null, 1, instance.Origin[axis] - _nodes[followed].Stored, instance.Id, false)); + } + else _nodes[Root(node)].Anchored = true; + } + return Root(node); + } + private int OnExtrusion(FamilyExtrusionRecord extrusion, FamilyReference reference, int axis, int source) { int ext = AxisOf(extrusion.PlaneNormal)!.Value; @@ -383,7 +456,10 @@ private int Cap(FamilyExtrusionRecord extrusion, bool end) private int Slot(FamilySketchLine line, int end, int axis) { if (Direction(line) is int along && along != axis) end = -1; - return Keyed(("slot", line.Id, end, axis), end == 1 ? line.End[axis] : line.Start[axis], line.CircleId ?? line.Id); + int node = Keyed(("slot", line.Id, end, axis), end == 1 ? line.End[axis] : line.Start[axis], line.CircleId ?? line.Id); + // A line apart stays where the file has it. + if (_apartLines.Contains(line.Id)) _nodes[node].Anchored = true; + return node; } private int Keyed(object key, double stored, int element) @@ -517,7 +593,8 @@ private void Join() { foreach (var joint in records.Joints) { - if (!_lines.TryGetValue(joint.LineId, out var line) || !_lines.TryGetValue(joint.OtherLineId, out var other)) + if (!_lines.TryGetValue(joint.LineId, out var line) || !_lines.TryGetValue(joint.OtherLineId, out var other) + || _apartLines.Contains(line.Id)) continue; if (_profileArcs.Contains(line.Id) || _profileArcs.Contains(other.Id)) { @@ -545,6 +622,68 @@ private void Join() } } + /// The sketches of reference lines that stay where they are in every type: no parameter drives them, and the + /// dimensions of their lines are none with a label and reach only planes that stay where they are (a level, a pinned + /// plane, a centre plane) and lines of such sketches. Such a line is where the file has it, and a form or an instance + /// that stands on a plane through it stands as far from it as it stood; what the sketch holds of it moves nothing. + private void FindApart() + { + var profiles = _extrusions.Values.Select(e => e.SketchId).Concat(_revolutions.Values.Select(r => r.SketchId)).ToHashSet(); + var held = records.Associations.Select(a => a.ElementId).ToHashSet(); + // The label of an angle holds it at the angle the file has (HoldAngles), so only the label of a length moves a line. + var measured = records.Dimensions.Select(d => (d.References, Moves: d.ParameterIds.Any(parameter => parameter != -1))) + .Concat(_angles.Values.Select(angle => (angle.References, Moves: false))).ToList(); + var sketches = measured.SelectMany(m => m.References).Select(r => r.ElementId) + .Where(id => _lines.TryGetValue(id, out var line) && line.SketchId > 0 && !profiles.Contains(line.SketchId)) + .Select(id => _lines[id].SketchId).ToHashSet(); + sketches.ExceptWith(held); + sketches.ExceptWith(_lines.Values.Where(line => held.Contains(line.Id)).Select(line => line.SketchId)); + bool Apart(FamilyReference reference) => _lines.TryGetValue(reference.ElementId, out var line) && sketches.Contains(line.SketchId); + for (bool changed = true; changed;) + { + changed = false; + foreach (var (references, _) in measured.Where(m => m.References.Any(Apart) + && (m.Moves || !m.References.All(reference => Apart(reference) || Stays(reference.ElementId))))) + foreach (var reference in references.Where(Apart)) + changed |= sketches.Remove(_lines[reference.ElementId].SketchId); + } + _apartSketches = sketches; + _apartLines = _lines.Values.Where(line => sketches.Contains(line.SketchId)).Select(line => line.Id).ToHashSet(); + } + + /// A plane that stays where it is whatever the parameters are: a level, a pinned plane, a plane that defines + /// the origin or one of the centre planes. + private bool Stays(int id) => _planes.TryGetValue(id, out var plane) && plane.Origin.Length > 0 + && (plane.ClassName == "Level" || plane.Pinned || plane.DefinesOrigin || FamilyRules.IsCentreReferenceName(plane.ReferenceName)); + + // What refers to a line apart, or to its sketch: the lines and sketches of the same kind, the plane drawn through the + // line, the dimensions skipped for it, and an angle that measures only such lines and planes that stay. + private bool IsApartReferrer(FamilyReferrer referrer) => + _apartLines.Contains(referrer.RecordId) || _apartSketches.Contains(referrer.RecordId) + || referrer.ClassName is "SketchPlane" or "Alignment" or "LinearDimString" + || referrer.ClassName == "AngularDim" && AngleApart(referrer.RecordId); + + // An angle that measures a line apart to what stays (the fixed point of FindApart has dropped the sketches of the others). + private bool AngleApart(int id) => _angles.TryGetValue(id, out var angle) + && angle.References.Any(reference => _apartLines.Contains(reference.ElementId)) + && angle.References.All(reference => _apartLines.Contains(reference.ElementId) || Stays(reference.ElementId)); + + /// The line apart stays as the file has it, and so does its angle: a label of the angle (a parameter) can only + /// have the angle of the file in a type, any other value turns the line, which the model does not follow. The solver + /// holds the label to the stored angle, and refuses the type that has another. + private void HoldAngles() + { + foreach (var angle in _angles.Values.Where(angle => AngleApart(angle.Id))) + { + if (!FamilyRules.IsKnownDimensionFlags(false, angle.Flags)) + throw Unrecognized($"flags {angle.Flags} of dimension {Text(angle.Id)}"); + if (angle.SegmentFlags is not (FamilyRules.UnlockedSegmentFlag or FamilyRules.LockedSegmentFlag)) + throw Unrecognized($"segments of dimension {Text(angle.Id)}"); + if (angle.ParameterId != -1 && !angle.Driven) + _equations.Add(new([(Add(angle.Value, anchored: true), 1)], angle.ParameterId, 1, 0, angle.Id, false, true)); + } + } + private void CheckConstraints(HashSet modelLines) { var profiles = _extrusions.Values.Select(e => e.SketchId).Concat(_revolutions.Values.Select(r => r.SketchId)).ToHashSet(); @@ -611,13 +750,14 @@ private void CheckReferrers(HashSet modelLines) var model = _extrusions.Keys.Concat(_revolutions.Keys).Concat(_combinations.Keys) .Concat(_extrusions.Values.Select(e => e.SketchId)).Concat(modelLines) .Concat(modelLines.Select(id => _lines[id].SketchId)) - .Concat(records.Dimensions.SelectMany(d => d.References).Select(r => r.ElementId)) + .Concat(records.Dimensions.SelectMany(d => d.References).Select(r => r.ElementId).Where(id => !_apartLines.Contains(id))) .Concat(_extrusions.Values.Where(e => e.PlaneHost != null).Select(e => e.PlaneHost!.Value.ElementId)) .Concat(_revolutions.Values.Where(r => r.PlaneHost != null).Select(r => r.PlaneHost!.Value.ElementId)) .Where(id => id > 0).ToHashSet(); foreach (var referrer in records.Referrers) { - if (!model.Contains(referrer.TargetId) || referrer.RecordId == referrer.TargetId + bool apart = _apartLines.Contains(referrer.TargetId) || _apartSketches.Contains(referrer.TargetId); + if (!apart && !model.Contains(referrer.TargetId) || referrer.RecordId == referrer.TargetId || referrer.Field == "Element.m_assocLevelId") continue; // Why each class may stay: dimensions and alignments are the relations read in Dimensions; a sketch, an // extrusion and a sketch plane are the forms themselves; a curve is checked below; views and their companions @@ -625,7 +765,12 @@ private void CheckReferrers(HashSet modelLines) // own sketch; a host, its openings and the connectors, warnings and imports on it have their own level or cut // the host, and move none of the family's forms. // A combination refers to the forms it joins, and to nothing else that takes part. - bool known = _combinations.TryGetValue(referrer.RecordId, out var joined) ? joined.Members.Contains(referrer.TargetId) + bool known = apart ? IsApartReferrer(referrer) + : _combinations.TryGetValue(referrer.RecordId, out var joined) ? joined.Members.Contains(referrer.TargetId) + // An instance refers to its family, its symbols, the level it is listed at and the plane it stands on: the + // plane is read in OriginNode and the rest moves nothing. + : _instances.ContainsKey(referrer.RecordId) ? referrer.Field is "Element.m_famId" or "FamilyInstance.m_scheduleOnlyLevelId" + or "FamilyInstance.m_masterSymbolId" or "InstanceInfo.InstInfoBase.m_symbolId" or "InsertableInst.m_hostId" : referrer.ClassName switch { "LinearDimString" or "Alignment" or "RadialDim" or "VarSketch" or "ExtrusionElem" or "RevolutionElem" or "SketchPlane" => true, @@ -640,6 +785,7 @@ private void CheckReferrers(HashSet modelLines) && records.Joints.Any(j => j.LineId == referrer.RecordId && j.OtherLineId == referrer.TargetId && j.OtherEnd >= 0) && _lines.TryGetValue(referrer.RecordId, out var side) && Direction(side) is int along && _lines.TryGetValue(referrer.TargetId, out var next) && Direction(next) == along, + "AngularDim" => AngleApart(referrer.RecordId), "ExtentElem" or "DBViewPlan" or "DBViewSection" or "DBView3d" or "SunAndShadowSettings" or "Opening" or "ComplexOpening" or "ConnectorElem" or "PostedWarningElem" or "ImportInstance" or "FilledRegion" => true, var name => TfClassNames.IsSubclassOf(name, "HostObj"), @@ -790,7 +936,7 @@ private void Anchor(IEnumerable shown) private FamilyModel Assemble(Dictionary axes, Dictionary caps, Dictionary vertices, Dictionary turns, - Dictionary placed) + Dictionary placed, Dictionary origins) { var variables = new List(); var index = new Dictionary(); @@ -857,7 +1003,10 @@ int Variable(int node) }).ToList(); var combinations = (records.Combinations ?? []) .Select(combination => new FamilyCombination(combination.Id, [.. combination.Members])).ToList(); - return new(variables, equations, extrusions) { Revolutions = revolutions, Combinations = combinations }; + var placements = _instances.Values.Where(instance => instance.Shown).Select(instance => new FamilyPlacement( + instance.Id, instance.SymbolId, instance.MasterSymbolId, [.. origins[instance.Id].Select(Variable)], instance.Basis, + BoundOf(instance.Id, BuiltInParameter.IS_VISIBLE_PARAM))).ToList(); + return new(variables, equations, extrusions) { Revolutions = revolutions, Combinations = combinations, Placements = placements }; } /// The stored materials by the faces of the model, whose start cap is the lower one. diff --git a/src/RvtIO/Families/FamilyNested.cs b/src/RvtIO/Families/FamilyNested.cs new file mode 100644 index 00000000..a42e9ea9 --- /dev/null +++ b/src/RvtIO/Families/FamilyNested.cs @@ -0,0 +1,160 @@ +using System.Globalization; +using RvtIO.Meshes; +using RvtIO.Model; + +namespace RvtIO.Families; + +/// The model of a family loaded into another, once it reproduces what its document stores: the model, the formulas and +/// size tables that give its parameters, and the numbers the only type of the loaded family stores. +internal sealed class NestedShape +{ + internal required LoadedFamily Link { get; init; } + + internal required FamilyModel Model { get; init; } + + internal required FamilyFormulas Formulas { get; init; } + + internal required IReadOnlyDictionary TypeValues { get; init; } +} + +/// A placed instance of a loaded family solved for the values of a type of the host: the variables of the loaded family +/// and the point of the host the instance stands at. +internal sealed record NestedSolution(NestedShape Shape, double[] Positions, double[] Origin); + +/// Computes the shape of an instance of a family loaded into the family: the loaded family is solved for the parameters +/// that the host's type gives it through the associations of the instance, and its faces are placed where the instance stands. +/// Anything the code does not know how to do is refused, never approximated. +internal static class FamilyNested +{ + private const double Tolerance = 1e-9; + + /// The loaded family as a model, or why it is not computed. The loaded family must have one type and only forms that + /// are always shown, and what it stores of its forms and its parameters must be reproduced by the model and by its + /// formulas; a loaded family with more than that is refused until it is read. + internal static (NestedShape? Shape, RvtFamilyRefusal? Refusal) Prepare(NestedFamilyData nested, RevitFileInfo info) + { + string family = nested.Link.OwnerId.ToString(CultureInfo.InvariantCulture); + (NestedShape?, RvtFamilyRefusal?) No(string code, string detail) => (null, new(code, $"nested family {family}: {detail}")); + var data = nested.Data; + if (data.Types is not { Types.Count: 1 } types) + return No("unsupported-construct", data.Types == null ? data.TypesError ?? "no types read" : $"{data.Types.Types.Count} types"); + if (data.Records is not { } records) return No("unrecognized-reference", "its records are not read"); + var (listed, hidden, gaps) = ElementMeshes.FamilyElements(info, data); + if (gaps.Length > 0) return No("unsupported-construct", "incomplete: " + string.Join(", ", gaps)); + if (hidden.Count > 0) return No("unsupported-construct", "forms that a parameter hides"); + var (model, refusal) = FamilyModelBuilder.Build(records); + if (model == null) return No(refusal!.Code, refusal.Detail); + if (model.Revolutions.Count > 0 || model.Combinations.Count > 0 || model.Placements.Count > 0) + return No("unsupported-construct", "revolutions, combinations or instances of its own"); + if (model.Extrusions.Any(extrusion => extrusion.VisibilityParameterId != null || extrusion.MaterialParameterId != null)) + return No("unsupported-construct", "forms with a visibility or a material parameter"); + if (!listed.Select(item => item.Element.Id).Order().SequenceEqual(model.Extrusions.Select(extrusion => extrusion.ElementId).Order())) + return No("saved-state-mismatch", "the forms of its type"); + + var saved = ElementMeshes.ValuesOf(types.Types[types.CurrentIndex]); + var stored = new Dictionary>(); + foreach (var (element, body) in listed) + { + if (body == null || body.PlacedSymbolBox || body.UnresolvedSymbol || body.UntriangulatedFaces > 0 + || body.GhostNodes is { Count: > 0 }) continue; + bool dropUntaken = ElementMeshes.DropsUntakenNodes(body.Faces, false); + stored[element.Id] = body.Faces.Where(face => !dropUntaken || face.GeometryNode >= 0).ToList(); + } + var (matched, mismatch) = FamilySavedState.Match(model, saved, + (extrusion, key) => extrusion.Materials.GetValueOrDefault(key), stored); + if (matched == null) return No(mismatch!.Code, mismatch.Detail); + if (nested.Formulas.CheckStored() is { } wrong) return No("unsupported-construct", "formulas: " + wrong); + return (new NestedShape { Link = nested.Link, Model = model, Formulas = nested.Formulas, TypeValues = saved }, null); + } + + /// The loaded family solved for the instance at the values of a type of the host + /// () and the positions of the host (). A parameter of the loaded + /// family that the instance or its symbols associate with a host parameter takes the value of that parameter; every other one + /// is what the type of the loaded family stores, or what its formulas give from those. + internal static (NestedSolution? Solution, RvtFamilyRefusal? Refusal) Solve(NestedShape shape, FamilyPlacement placement, + FamilyRecords host, IReadOnlyDictionary hostValues, IReadOnlyList hostPositions) + { + (NestedSolution?, RvtFamilyRefusal?) No(string code, string detail) => (null, new(code, detail)); + string instance = placement.ElementId.ToString(CultureInfo.InvariantCulture); + if (!IsRotation(placement.Basis)) return No("unsupported-construct", $"instance {instance} is not placed by a rotation or a mirror"); + + var associations = host.Associations.Where(association => association.ElementId == placement.ElementId).ToList(); + foreach (int id in new[] { placement.SymbolId, placement.MasterSymbolId }.Distinct()) + associations.AddRange(host.Symbols!.Single(symbol => symbol.Id == id).Associations); + var input = new Dictionary(); + foreach (var association in associations.Distinct()) + { + string parameter = association.FamilyParameterId.ToString(CultureInfo.InvariantCulture); + if (!hostValues.TryGetValue(association.FamilyParameterId, out double value)) return No("underdetermined", parameter); + // A parameter of the host that chooses the type of the loaded family gives the element the instance is of. + if (association.ElementPropertyId == -1) + { + if (value != placement.SymbolId && value != placement.MasterSymbolId) + return No("unsupported-construct", $"parameter {parameter} chooses another type for instance {instance}"); + continue; + } + if (!shape.Link.HostToNested.TryGetValue(association.ElementPropertyId, out long target)) + return No("unrecognized-reference", $"association {association.ElementPropertyId} of instance {instance}"); + if (input.TryGetValue(target, out double known) && known != value) + return No("unsupported-construct", $"two parameters of the host give parameter {target} of the loaded family"); + input[target] = value; + } + + var reporting = shape.Formulas.Reporting; + double? Given(long id) => input.TryGetValue(id, out double value) ? value + : !reporting.Contains(id) && shape.TypeValues.TryGetValue(id, out double stored) ? stored : null; + var (values, refusal) = shape.Formulas.Evaluate(Given); + if (values == null) return (null, refusal); + var solution = FamilySolver.Solve(shape.Model, values); + if (solution.Positions is not { } positions) return (null, solution.Refusal); + if (FamilyContourChecks.Check(shape.Model, positions, values) is { } degenerate) return (null, degenerate); + return (new NestedSolution(shape, positions, [.. placement.Origin.Select(variable => hostPositions[variable])]), null); + } + + /// The faces of the loaded family in the frame of the host, for each form and face of its model: the point of + /// the loaded family p stands at origin + Σ p[c]·basis[c]. A mirror turns the corners of a face the other + /// way round. + internal static List<(int ElementId, FamilyFaceKey Key, GeoFace Face)> Faces(NestedSolution solution, FamilyPlacement placement) + { + var basis = placement.Basis; + bool mirrored = Determinant(basis) < 0; + double[] Direction(double[] local) => [.. Enumerable.Range(0, 3).Select(axis => Enumerable.Range(0, 3).Sum(c => local[c] * basis[c][axis]))]; + double[] Point(double[] local) => [.. Direction(local).Select((value, axis) => solution.Origin[axis] + value)]; + List Ring(IEnumerable corners) + { + var ring = corners.Select(Point).ToList(); + if (mirrored) ring.Reverse(); + return ring; + } + + var faces = new List<(int, FamilyFaceKey, GeoFace)>(); + foreach (var extrusion in solution.Shape.Model.Extrusions) + { + var keys = new List(); + var built = FamilyExtrusionBuilder.Faces(extrusion, solution.Positions, key => + { + keys.Add(key); + return 0; + }); + foreach (var (face, key) in built.Zip(keys)) + { + var outer = Ring(face.OuterVertices!); + faces.Add((extrusion.ElementId, key, new GeoFace(outer[0], Direction(face.Normal)) + { + OuterVertices = outer, + InnerVertices = face.InnerVertices?.Select(hole => Ring(hole)).ToList(), + })); + } + } + return faces; + } + + private static double Determinant(double[][] b) => + b[0][0] * (b[1][1] * b[2][2] - b[1][2] * b[2][1]) - b[0][1] * (b[1][0] * b[2][2] - b[1][2] * b[2][0]) + + b[0][2] * (b[1][0] * b[2][1] - b[1][1] * b[2][0]); + + /// Whether the three vectors are unit vectors at right angles: a placement by a rotation or a mirror. + private static bool IsRotation(double[][] b) => b.Length == 3 && b.All(vector => vector.Length == 3) + && Enumerable.Range(0, 3).All(i => Enumerable.Range(0, 3).All(j => + Math.Abs(Enumerable.Range(0, 3).Sum(axis => b[i][axis] * b[j][axis]) - (i == j ? 1 : 0)) <= Tolerance)); +} diff --git a/src/RvtIO/Families/FamilyRecordReader.cs b/src/RvtIO/Families/FamilyRecordReader.cs index a28403ec..d9b5353a 100644 --- a/src/RvtIO/Families/FamilyRecordReader.cs +++ b/src/RvtIO/Families/FamilyRecordReader.cs @@ -79,7 +79,85 @@ internal static FamilyData Read(RootStorage root, RevitFileInfo info, ElementIdM var (types, typesError) = ReadTypes(root, ownerId, ids, currentCopies, block); var relations = types is { Types.Count: > 0 } ? FamilyRelationReader.Read(root, elements, ids, ownerId, currentCopies, facts, block) : null; - return new FamilyData { Elements = facts, Types = types, TypesError = typesError, Records = relations }; + var (nested, nestedError) = block == 0 && relations?.Instances?.Any(instance => instance.Shown) == true + ? ReadNested(root, info, ids, ownerId, currentCopies, relations) : (null, null); + return new FamilyData + { + Elements = facts, Types = types, TypesError = typesError, Records = relations, Nested = nested, NestedError = nestedError, + }; + } + + /// The documents of the families that the shown instances of the family are of, read as families themselves; or why + /// one of them cannot be. A family loaded into a nested one is not read: it is refused when the nested one is computed. + private static (IReadOnlyList? Nested, string? Error) ReadNested(RootStorage root, RevitFileInfo info, + ElementIdMap? ids, long ownerId, IReadOnlyDictionary? currentCopies, FamilyRecords relations) + { + var symbols = (relations.Symbols ?? []).ToDictionary(symbol => symbol.Id); + var wanted = new SortedSet(); + foreach (var instance in relations.Instances!.Where(instance => instance.Shown)) + foreach (int id in new[] { instance.SymbolId, instance.MasterSymbolId }.Distinct()) + { + if (!symbols.TryGetValue(id, out var symbol)) return (null, $"symbol {id} of the instance {instance.Id} is not read"); + wanted.Add(symbol.FamilyId); + } + var (loaded, error) = NestedFamilies.Read(root, currentCopies, ownerId); + if (error != null) return (null, "the families loaded into the family are not read: " + error); + + var nested = new List(); + foreach (long family in wanted) + { + var links = loaded.Where(link => link.HostFamilyId == family).ToList(); + if (links.Count != 1) return (null, $"the family {family} has no document of its own in the file"); + var link = links[0]; + var data = Read(root, info, ids, link.OwnerId, currentCopies, link.Block); + var (formulas, formulaError) = FamilyFormulas.Read(root, link.OwnerId, ids, currentCopies, link.Block); + if (formulas == null) return (null, $"the formulas of the family {family} are not read: {formulaError}"); + nested.Add(new(link, data, formulas)); + } + return (nested, null); + } + + /// The record of a family walked, and the records of the parameter definitions of the document (null for an element + /// with copies that differ). + internal sealed record FamilyRecordWalk(WideBlockWalker Walker, WideBlockWalker.Walk Family, Dictionary Bodies); + + /// The record of the family in the partitions of . Throws + /// for a record that is not found, has copies that differ or is not read exactly. + internal static FamilyRecordWalk WalkFamilyRecord(RootStorage root, long ownerId, + IReadOnlyDictionary? currentCopies, int block, Func captureKey) + { + if (TfSchemaReader.Read(root) is not { } schema) + throw ParameterWriter.Unverified("The family schema could not be read exactly."); + var formats = new FormatsSchema(schema); + if (PartitionFraming.TagsOf(formats) is not { } tags || ElemTableLayout.IdWidth(formats) is not int idWidth) + throw ParameterWriter.Unverified("The partition layout of the family could not be read."); + var walker = new WideBlockWalker(schema, captureKey, ["ForgeTypeId", "FormatOptions", "AUnits"]); + walker.UseEntitySchemas(EntitySchemaReader.Read(root, schema)); + + // The family record and the records of the parameter definitions; null for an element with copies that differ. + var bodies = new Dictionary(); + ParameterWriter.ScanPartitions(root, tags, idWidth, (partition, record) => + { + if (currentCopies != null && currentCopies.TryGetValue(record.Owner, out int current) && current != partition) return; + if (record.Channel != 102 || record.Body.Length < 2 || record.Owner > long.MaxValue) return; + long owner = (long)record.Owner; + int cls = BinaryPrimitives.ReadUInt16LittleEndian(record.Body.Span); + // A shared parameter is defined once in the first block, for the family of the file and for every family loaded into it. + bool shared = block != 0 && record.Block == 0 && walker.IsA(cls, "ParamElemExternal"); + if (record.Block != block && !shared) return; + if (owner != ownerId && !walker.IsA(cls, "ParamElem")) return; + byte[] data = record.Body.ToArray(); + if (!bodies.TryAdd(owner, data) && bodies[owner] is { } first && !data.AsSpan().SequenceEqual(first)) + bodies[owner] = null; + }, new ParameterWriter.Pending()); + + if (bodies.GetValueOrDefault(ownerId) is not { } body) + throw ParameterWriter.Unverified("The record of the family was not found or has copies that differ."); + int familyClass = BinaryPrimitives.ReadUInt16LittleEndian(body); + var family = walker.Run(body, 0, body.Length, familyClass); + if (walker.Class(familyClass)?.Name != "Family" || UserParameterWriter.Integer(family, "m_id") != ownerId) + throw ParameterWriter.Unverified("The record of the family could not be read exactly."); + return new(walker, family, bodies); } /// The types of the family from its record, with their parameters. A family that stores @@ -89,34 +167,7 @@ internal static (RvtFamilyTypes? Types, string? Error) ReadTypes(RootStorage roo { try { - if (TfSchemaReader.Read(root) is not { } schema) - throw ParameterWriter.Unverified("The family schema could not be read exactly."); - var formats = new FormatsSchema(schema); - if (PartitionFraming.TagsOf(formats) is not { } tags || ElemTableLayout.IdWidth(formats) is not int idWidth) - throw ParameterWriter.Unverified("The partition layout of the family could not be read."); - var walker = new WideBlockWalker(schema, StandaloneFamilyParameterWriter.CaptureKey, ["ForgeTypeId", "FormatOptions", "AUnits"]); - walker.UseEntitySchemas(EntitySchemaReader.Read(root, schema)); - - // The family record and the records of the parameter definitions; null for an element with copies that differ. - var bodies = new Dictionary(); - ParameterWriter.ScanPartitions(root, tags, idWidth, (partition, record) => - { - if (currentCopies != null && currentCopies.TryGetValue(record.Owner, out int current) && current != partition) return; - if (record.Block != block || record.Channel != 102 || record.Body.Length < 2 || record.Owner > long.MaxValue) return; - long owner = (long)record.Owner; - int cls = BinaryPrimitives.ReadUInt16LittleEndian(record.Body.Span); - if (owner != ownerId && !walker.IsA(cls, "ParamElem")) return; - byte[] data = record.Body.ToArray(); - if (!bodies.TryAdd(owner, data) && bodies[owner] is { } first && !data.AsSpan().SequenceEqual(first)) - bodies[owner] = null; - }, new ParameterWriter.Pending()); - - if (bodies.GetValueOrDefault(ownerId) is not { } body) - throw ParameterWriter.Unverified("The record of the family was not found or has copies that differ."); - int familyClass = BinaryPrimitives.ReadUInt16LittleEndian(body); - var family = walker.Run(body, 0, body.Length, familyClass); - if (walker.Class(familyClass)?.Name != "Family" || UserParameterWriter.Integer(family, "m_id") != ownerId) - throw ParameterWriter.Unverified("The record of the family could not be read exactly."); + var (walker, family, bodies) = WalkFamilyRecord(root, ownerId, currentCopies, block, StandaloneFamilyParameterWriter.CaptureKey); var (stored, saved) = FamilyTypeTable.Read(walker, family); if (stored.Length == 0) return (null, null); @@ -140,6 +191,10 @@ internal static (RvtFamilyTypes? Types, string? Error) ReadTypes(RootStorage roo } } + /// The kind of value a parameter of the document holds (none when its definition is not read exactly). + internal static StorageType StorageOf(WideBlockWalker walker, Dictionary bodies, ElementIdMap? ids, long id) => + Describe(walker, bodies, ids, id).Storage; + /// What every type says alike about one parameter. private sealed record TypeParameter(int Key, Definition Definition, StorageType Storage, Parameter.Metadata? Units); diff --git a/src/RvtIO/Families/FamilyRecords.cs b/src/RvtIO/Families/FamilyRecords.cs index 01b856cc..4a2e2af6 100644 --- a/src/RvtIO/Families/FamilyRecords.cs +++ b/src/RvtIO/Families/FamilyRecords.cs @@ -22,6 +22,11 @@ internal sealed record FamilyArc(double[] Center, double[] XAxis, double[] YAxis internal sealed record FamilyRadialDimension(int Id, FamilyReference Arc, long ParameterId, double Value, long Flags, long SegmentFlags, bool Driven, long StyleType); +/// An angular dimension: the two lines or planes it measures between, its label (-1 for none), the angle it holds +/// in radians, its flags and segment flags, and whether the family's dimension manager computes it from others. +internal sealed record FamilyAngularDimension(int Id, IReadOnlyList References, long ParameterId, double Value, + long Flags, long SegmentFlags, bool Driven); + /// A constraint of a sketch that holds the end End (0 or 1) of the arc curve ArcLineId at an /// angle of its own. internal sealed record FamilyArcEndAngle(int SketchId, int ArcLineId, int End); @@ -65,8 +70,14 @@ internal sealed record FamilyExtrusionRecord(int Id, int SketchId, double Start, internal sealed record FamilyRevolutionRecord(int Id, int SketchId, double StartAngle, double EndAngle, double[] PlaneOrigin, double[] PlaneNormal, FamilyReference? PlaneHost, IReadOnlyList> Loops, int AxisLineId); -/// A combination of forms ("Joined Solid Geometry"): the solid forms it joins into one shape. -internal sealed record FamilyCombinationRecord(int Id, IReadOnlyList Members); +/// The face of a member of a combination that a face of the combination is: the member, and the tag its face has in it. +internal readonly record struct FamilyFaceOrigin(int Member, int Tag); + +/// A combination of forms ("Joined Solid Geometry"): the solid forms it joins into one shape. Faces says which +/// face of which member each face of the combination is, by the tag of the face of the combination; null when the steps that +/// add the members do not read the way the files seen so far do. +internal sealed record FamilyCombinationRecord(int Id, IReadOnlyList Members, + IReadOnlyDictionary? Faces = null); /// A field of a record of the family that refers to another element. internal sealed record FamilyReferrer(int RecordId, string ClassName, string Field, int TargetId); @@ -74,6 +85,22 @@ internal sealed record FamilyReferrer(int RecordId, string ClassName, string Fie /// A property of an element that a family parameter drives. internal sealed record FamilyAssociation(int ElementId, long ElementPropertyId, long FamilyParameterId); +/// A plane of a symbol in the frame of the symbol: a point on it and its unit normal. +internal sealed record FamilyLocalPlane(double[] Origin, double[] Normal); + +/// A family loaded into the family and placed in it: its element and symbol (keys), and where it stands in the frame of +/// the family: the image of the origin, and of each of the three axes of the symbol. HostId is the element the instance +/// stands on (-1 for none); when it is a work plane, Host is what that plane follows (null when nothing) and +/// HostNormal its normal. Shown: the family shows it in some type. +internal sealed record FamilyInstanceRecord(int Id, int SymbolId, int MasterSymbolId, double[] Origin, double[][] Basis, int HostId, + FamilyReference? Host = null, double[]? HostNormal = null, bool Shown = false); + +/// A symbol of a loaded family: the id of its family in the file, the host parameters its parameters are associated +/// with (ElementPropertyId is the id of the parameter in the file, FamilyParameterId the key of the host +/// parameter), and its reference planes by geometry tag. +internal sealed record FamilySymbolRecord(int Id, long FamilyId, IReadOnlyList Associations, + IReadOnlyDictionary Planes); + /// What the records of a family say about the placing of its forms, as plain values. /// UnsupportedContent names what is shown and cannot be recomputed. FormulaParameterIds are the parameters a /// formula or a measurement sets: the value a type stores for one is the value it has, so it is used as stored. @@ -85,4 +112,6 @@ internal sealed record FamilyRecords(IReadOnlyList Dimens IReadOnlyList Associations, IReadOnlySet FormulaParameterIds, IReadOnlyList UnsupportedContent, IReadOnlyList? RadialDimensions = null, IReadOnlyList? ArcEndAngles = null, IReadOnlySet? ControlIconIds = null, - IReadOnlyList? Revolutions = null, IReadOnlyList? Combinations = null); + IReadOnlyList? Revolutions = null, IReadOnlyList? Combinations = null, + IReadOnlyList? Instances = null, IReadOnlyList? Symbols = null, + IReadOnlyList? AngularDimensions = null); diff --git a/src/RvtIO/Families/FamilyRelationReader.cs b/src/RvtIO/Families/FamilyRelationReader.cs index e56ad6b1..c7f51179 100644 --- a/src/RvtIO/Families/FamilyRelationReader.cs +++ b/src/RvtIO/Families/FamilyRelationReader.cs @@ -61,11 +61,14 @@ private sealed class Unread(string detail) : Exception(detail); "ExtrusionHelper.m_sketchId", "RevolutionElem.m_sketchId", "RevolutionCurveData.m_axis", "ParamValueDouble.m_paramId", "ParamValueDouble.m_value", "FaceHistEntry.m_id", "FaceHist.m_keys", "EdgeHistEntry.m_id", "EdgeHist.m_keys", "ParamIdPair.m_famParamId", "ParamIdPair.m_elemPropId", + "Trf.m_3x3", "Trf.m_or", "InstInfoBase.m_symbolId", "FamilyInstance.m_masterSymbolId", "InsertableInst.m_hostId", + "FamilySymbol.m_familyId", "Face.m_pSurf", ]; /// Counted arrays that are read whole besides the arrays of references to elements. private static readonly HashSet WholeArrays = - ["ElementExtrusionHelper.m_pCurveLoops", "CurveLoop.m_curves", "VarSketchConstrObj.m_constrElems", "VarSketch.m_elemRecs", "VarSketch.m_pointRecs"]; + ["ElementExtrusionHelper.m_pCurveLoops", "CurveLoop.m_curves", "VarSketchConstrObj.m_constrElems", "VarSketch.m_elemRecs", "VarSketch.m_pointRecs", + "FamilySymbol.m_refFaces"]; /// One walked record, with its captured values by the object (slot) that holds them; -1 is the record /// itself. @@ -130,6 +133,7 @@ private sealed class Reader(RootStorage root, IReadOnlyDictionary long ownerId, IReadOnlyDictionary? currentCopies, int block) { private readonly Dictionary _own = []; + private readonly Dictionary _symbols = []; private readonly Dictionary _styleTypes = []; private readonly List _unsupported = []; @@ -175,9 +179,15 @@ private sealed class Reader(RootStorage root, IReadOnlyDictionary && walk.Captures.FirstOrDefault(c => c.AtRoot && c.Key == "DimensionStyle.m_dimensionStyleType") is { Key: not null } type) _styleTypes[key] = type.Integer; var family = walk.Captures.FirstOrDefault(c => c.AtRoot && c.Key.EndsWith("Element.m_famId", StringComparison.Ordinal)); - // The record of another family: the content of a nested one. - if (family.Key != null && family.Integer != ownerId) continue; string className = walker.Class(cls)?.Name ?? "?"; + // The record of another family: the content of a nested one. A symbol of a loaded family belongs to none + // (-1), and the instances of the family name it. + if (family.Key != null && family.Integer != ownerId) + { + if (family.Integer == -1 && className == "FamilySymbol" && walk.Exact && !differing.Contains(key)) + _symbols.Add(key, new(key, className, walker, walk)); + continue; + } if (!walk.Exact || differing.Contains(key)) { if (family.Key != null || elements[key].SerializedFamilyId == ownerId) @@ -185,6 +195,7 @@ private sealed class Reader(RootStorage root, IReadOnlyDictionary continue; } if (family.Key != null) _own.Add(key, new(key, className, walker, walk)); + if (family.Key != null && className == "FamilySymbol") _symbols.Add(key, _own[key]); } if (familyBody == null) return null; @@ -198,18 +209,22 @@ private sealed class Reader(RootStorage root, IReadOnlyDictionary var planes = new List(); var dimensions = new List(); var radials = new List(); + var turns = new List(); var angles = new List(); var referrers = new HashSet(); var associations = new List(); + var instances = new List(); foreach (var record in _own.Values) { References(record, references, referrers); try { Associations(record, associations); - if (record.ClassName == "CurveElem") lines.Add(Line(record, joints)); + if (TfClassNames.IsSubclassOf(record.ClassName, "FamilyInstance")) instances.Add(Instance(record)); + else if (record.ClassName == "CurveElem") lines.Add(Line(record, joints)); else if (record.ClassName is "LinearDimString" or "Alignment") dimensions.Add(Dimension(record, driven)); else if (record.ClassName == "RadialDim") radials.Add(Radial(record, driven)); + else if (record.ClassName == "AngularDim") turns.Add(Angular(record, driven)); else if (record.ClassName is "RefPlane" or "Level") planes.Add(Plane(record)); else if (TfClassNames.IsSubclassOf(record.ClassName, "HostObj")) planes.Add(new(record.Key, record.ClassName, 0, [], [])); @@ -224,9 +239,22 @@ private sealed class Reader(RootStorage root, IReadOnlyDictionary catch (Unread unread) { _unsupported.Add(unread.Message); } } + // What is read is no longer content the family cannot compute; what the family shows is the instance that places. + var shownInstances = instances.Where(instance => _unsupported.Contains($"{_own[instance.Id].ClassName} {instance.Id}")) + .Select(instance => instance.Id).ToHashSet(); + _unsupported.RemoveAll(entry => instances.Any(instance => entry == $"{_own[instance.Id].ClassName} {instance.Id}")); + instances = [.. instances.Select(instance => instance with { Shown = shownInstances.Contains(instance.Id) })]; + var symbols = new List(); + foreach (var record in _symbols.Values.OrderBy(record => record.Key)) + { + try { symbols.Add(Symbol(record)); } + catch (Unread unread) { _unsupported.Add(unread.Message); } + } + var byId = lines.ToDictionary(line => line.Id); - var combinations = facts.Where(fact => IsJoinedShape(fact, factsById)) - .Select(fact => new FamilyCombinationRecord(fact.ElementId, fact.Members!)).ToList(); + var combinations = facts.Where(fact => IsJoinedShape(fact, factsById)).Select(fact => new FamilyCombinationRecord( + fact.ElementId, fact.Members!, _own.TryGetValue(fact.ElementId, out var holder) ? CombinationFaces(holder, fact.Members!) : null)) + .ToList(); var extrusions = new List(); var revolutions = new List(); foreach (var fact in facts.Where(IsRecomputed)) @@ -242,7 +270,7 @@ private sealed class Reader(RootStorage root, IReadOnlyDictionary return new(dimensions, lines, joints, constraints, planes, extrusions, [.. referrers], associations, formulas, _unsupported, radials, angles, _own.Values.Where(record => record.ClassName == "ControlIconElem").Select(record => record.Key).ToHashSet(), - revolutions, combinations); + revolutions, combinations, instances, symbols, turns); } private static bool Holds(List? arguments, int reference) => @@ -348,6 +376,55 @@ private void Associations(Record record, List associations) } } + /// A family loaded into this one and placed in it: its symbol, where its origin lies and how its axes stand + /// (the columns of the transform), and the element it is hosted on. + private FamilyInstanceRecord Instance(Record record) + { + if (record.Slots.Where(i => record.Find("InstInfoBase.m_symbolId", i) != null).ToArray() is not [var info]) + throw new Unread($"placement of instance {record.Key}"); + double[][] basis = [.. Enumerable.Range(0, 3).Select(column => + (double[])[.. Enumerable.Range(0, 3).Select(row => record.Real($"Trf.m_3x3@{row}/{column}", info))])]; + int host = Referenced(record.Integer("InsertableInst.m_hostId")); + var (follows, normal) = host > 0 ? WorkPlane(record, host) : (null, null); + return new(record.Key, Referenced(record.Integer("InstInfoBase.m_symbolId", info)), + Referenced(record.Integer("FamilyInstance.m_masterSymbolId")), record.Vector("Trf.m_or", info), basis, host, + follows, normal); + } + + /// What the work plane of an instance follows and its normal: the third axis of its + /// frame. The file does not say whether a frame is stored by its axes or by their rows, so a frame whose third axis + /// differs between the two readings is not read. + private (FamilyReference? Follows, double[] Normal) WorkPlane(Record instance, int host) + { + var plane = Own(host, $"host of instance {instance.Key}"); + if (plane.ClassName != "SketchPlane" + || plane.Slots.Where(i => plane.Find("Trf.m_3x3@0/0", i) != null).ToArray() is not [var frame]) + throw new Unread($"host {host} of instance {instance.Key}"); + double[] column = [.. Enumerable.Range(0, 3).Select(row => plane.Real($"Trf.m_3x3@{row}/2", frame))]; + double[] row = [.. Enumerable.Range(0, 3).Select(c => plane.Real($"Trf.m_3x3@2/{c}", frame))]; + if (Enumerable.Range(0, 3).Any(i => Math.Abs(Math.Abs(column[i]) - Math.Abs(row[i])) > 1e-9)) + throw new Unread($"frame of work plane {host}"); + return (Follows(plane), column); + } + + /// A symbol of a loaded family: the family it is of, the parameters of the host its parameters follow, and its + /// reference planes by tag (the faces that are no planes are left out: nothing aligns to them here). + private FamilySymbolRecord Symbol(Record record) + { + var associations = new List(); + Associations(record, associations); + var planes = new Dictionary(); + foreach (int face in record.Pointers("FamilySymbol.m_refFaces", -1)) + { + int surface = record.Pointer("Face.m_pSurf", face); + if (record.SlotClass(surface) != "Plane") continue; + var (origin, normal) = Surface(record, surface); + if (!planes.TryAdd((int)record.Integer("GInfo.m_tag", face), new(origin, normal))) + throw new Unread($"reference faces of symbol {record.Key}"); + } + return new(record.Key, record.Integer("FamilySymbol.m_familyId"), associations, planes); + } + private FamilySketchLine Line(Record record, List joints) { var line = ReadLine(record, joints); @@ -482,6 +559,15 @@ private FamilyRadialDimension Radial(Record record, Dictionary _styleTypes.GetValueOrDefault(style, -1)); } + /// An angular dimension: one segment and the two lines or planes it measures between. + private FamilyAngularDimension Angular(Record record, Dictionary> driven) + { + var (held, references) = Segments(record); + if (held.Count != 1 || references.Count != 2) throw new Unread($"segments of dimension {record.Key}"); + return new(record.Key, references, ParameterKey(held[0].Parameter!.Value), held[0].Value!.Value, + record.Integer("Dimension.m_flags"), held[0].Flags!.Value, driven.GetValueOrDefault(record.Key)?.Contains(0) == true); + } + private FamilyDimensionRecord Dimension(Record record, Dictionary> driven) { bool alignment = record.ClassName == "Alignment"; @@ -693,6 +779,33 @@ private static Dictionary Facets(Element element) .GroupBy(face => face.GInfoTag).ToDictionary(group => group.Key, group => group.Count()); } + /// The face of a member that each face of a combination is, by the tag of the face of the combination. Each + /// step that adds a member lists the faces it makes with the keys 5, the tag the face has in the member, and the place of + /// the step among those that add members; a step that does not read so, or a tag it gives twice, names no face at all. + private IReadOnlyDictionary? CombinationFaces(Record record, IReadOnlyList members) + { + var faces = new Dictionary(); + var added = new HashSet(); + foreach (int step in record.Slots.Where(slot => record.SlotClass(slot) == "AddGeomToCombinationGStep")) + { + var entries = new List<(int Tag, List Keys)>(); + int? member = null; + foreach (var (name, value) in record.In(step)) + { + if (name == "FaceHistEntry.m_id") entries.Add(((int)value.Integer, [])); + else if (name.StartsWith("FaceHist.m_keys@", StringComparison.Ordinal) && entries.Count > 0) + entries[^1].Keys.Add(value.Integer); + else if (name == "AddGeomToCombinationGStep.m_memberId") member = Referenced(value.Integer); + } + if (member is not int owner || !members.Contains(owner) || !added.Add(owner)) return null; + foreach (var (tag, keys) in entries) + if (keys is not [5, >= 0 and < int.MaxValue and var memberTag, var place] || place != added.Count - 1 + || !faces.TryAdd(tag, new(owner, (int)memberTag))) + return null; + } + return faces.Count == 0 ? null : faces; + } + private static (Dictionary Faces, Dictionary Edges) History(Record record) { if (record.Slots.Where(i => record.SlotClass(i) == "ExtrusionGStep").ToArray() is not [var step]) @@ -763,9 +876,12 @@ bool Same(double[] a, double[] b) } /// What the sketch plane of a sketch follows; null when it follows nothing. - private FamilyReference? Host(Record sketch) + private FamilyReference? Host(Record sketch) => + Follows(Own(Referenced(sketch.Integer("Sketch.m_sketchPlaneId")), "sketch plane of sketch " + sketch.Key)); + + /// What a sketch plane follows; null when it follows nothing. + private FamilyReference? Follows(Record plane) { - var plane = Own(Referenced(sketch.Integer("Sketch.m_sketchPlaneId")), "sketch plane of sketch " + sketch.Key); int reference = plane.Pointer("SketchPlane.m_oPlaneRef"); switch (plane.SlotClass(reference)) { diff --git a/src/RvtIO/Families/FamilySavedState.cs b/src/RvtIO/Families/FamilySavedState.cs index 8740a2c7..a51892fb 100644 --- a/src/RvtIO/Families/FamilySavedState.cs +++ b/src/RvtIO/Families/FamilySavedState.cs @@ -101,11 +101,14 @@ private static bool SameBox(IEnumerable a, IEnumerable b) return first != null && second != null && first.Zip(second).All(pair => Math.Abs(pair.First - pair.Second) <= Tolerance); } - private static bool Same(GeoFace built, GeoFace stored) + // No material is stored as nothing or as an id that is not one. + private static bool Same(GeoFace built, GeoFace stored) => + Math.Max(built.RenderStyleId ?? 0, 0) == Math.Max(stored.RenderStyleId ?? 0, 0) && SameShape(built, stored); + + /// Whether two faces have the same normal and the same corners, with the same holes; their styles are not compared. + internal static bool SameShape(GeoFace built, GeoFace stored) { - // No material is stored as nothing or as an id that is not one. - if (Math.Max(built.RenderStyleId ?? 0, 0) != Math.Max(stored.RenderStyleId ?? 0, 0) - || !Close(built.Normal, stored.Normal) || !SameLoop(built.OuterVertices, stored.OuterVertices)) return false; + if (!Close(built.Normal, stored.Normal) || !SameLoop(built.OuterVertices, stored.OuterVertices)) return false; var holes = stored.InnerVertices?.ToList() ?? []; foreach (var hole in built.InnerVertices ?? []) { diff --git a/src/RvtIO/Families/FamilySolver.cs b/src/RvtIO/Families/FamilySolver.cs index ce11440b..87a62eea 100644 --- a/src/RvtIO/Families/FamilySolver.cs +++ b/src/RvtIO/Families/FamilySolver.cs @@ -59,6 +59,7 @@ bool Determined(int variable) => var undetermined = model.Extrusions.Where(extrusion => !UsedBy(extrusion).All(Determined)) .Select(extrusion => (long)extrusion.ElementId) .Concat(model.Revolutions.Where(revolution => !UsedBy(revolution).All(Determined)).Select(revolution => (long)revolution.ElementId)) + .Concat(model.Placements.Where(placement => !placement.Origin.All(Determined)).Select(placement => (long)placement.ElementId)) .ToList(); if (undetermined.Count > 0) return Refused("underdetermined", undetermined); diff --git a/src/RvtIO/Families/NestedFamilies.cs b/src/RvtIO/Families/NestedFamilies.cs new file mode 100644 index 00000000..d4850850 --- /dev/null +++ b/src/RvtIO/Families/NestedFamilies.cs @@ -0,0 +1,103 @@ +using System.Buffers.Binary; +using OpenMcdf; +using RvtIO.Parsing; +using RvtIO.Writing; + +namespace RvtIO.Families; + +/// A family loaded into a family file: the record of the host that stands for it, the block of the partitions that holds +/// its document, the id of that document's own family, and how ids of the host are paired with ids of the document. +internal sealed record LoadedFamily(long HostFamilyId, int Block, long OwnerId, IReadOnlyDictionary HostToNested); + +internal static class NestedFamilies +{ + private const string PairCount = "pairs", PairHost = "pair-host", PairNested = "pair-nested", OwnerOfElement = "owner"; + + private static string? CaptureKey(SchemaClass declaring, SchemaField field) => (declaring.Name, field.Name) switch + { + ("FamilyDocument", "m_big2SmallMap2") => PairCount, + ("std::pair< ElementId, ForeignElemRef >", "first") => PairHost, + ("ForeignElemRef", "m_id") => PairNested, + ("Element", "m_famId") => OwnerOfElement, + _ => null, + }; + + /// The families loaded into the family document of the family , with their documents. + /// A loaded family is linked to the one block whose records hold every id its pairs name, and to the family that block's + /// records say they belong to; one that is not linked that way has no entry. Or why the records cannot be read. + internal static (IReadOnlyList Families, string? Error) Read(RootStorage root, + IReadOnlyDictionary? currentCopies, long hostOwnerId) + { + try + { + if (TfSchemaReader.Read(root) is not { } schema) + throw ParameterWriter.Unverified("The family schema could not be read exactly."); + var formats = new FormatsSchema(schema); + if (PartitionFraming.TagsOf(formats) is not { } tags || ElemTableLayout.IdWidth(formats) is not int idWidth) + throw ParameterWriter.Unverified("The partition layout of the family could not be read."); + var walker = new WideBlockWalker(schema, CaptureKey, ["ForgeTypeId", "FormatOptions", "AUnits"]); + walker.UseEntitySchemas(EntitySchemaReader.Read(root, schema)); + + // The ids each block holds, and the records of the families of the host. + var held = new Dictionary>(); + var families = new Dictionary(); + ParameterWriter.ScanPartitions(root, tags, idWidth, (partition, record) => + { + if (currentCopies != null && currentCopies.TryGetValue(record.Owner, out int current) && current != partition) return; + if (record.Channel != 102 || record.Body.Length < 2) return; + if (!held.TryGetValue(record.Block, out var ids)) held[record.Block] = ids = []; + ids.Add(record.Owner); + if (record.Block != 0 || record.Owner == (ulong)hostOwnerId + || walker.Class(BinaryPrimitives.ReadUInt16LittleEndian(record.Body.Span))?.Name != "Family") return; + byte[] data = record.Body.ToArray(); + if (!families.TryAdd(record.Owner, data) && families[record.Owner] is { } first && !data.AsSpan().SequenceEqual(first)) + families[record.Owner] = null; + }, new ParameterWriter.Pending()); + + var candidates = new List<(long Family, int Block, Dictionary Pairs)>(); + foreach (var (id, body) in families) + { + if (body == null || PairsOf(walker, body) is not { Count: > 0 } pairs) continue; + var blocks = held.Where(block => block.Key != 0 && pairs.Values.All(nested => block.Value.Contains((ulong)nested))) + .Select(block => block.Key).ToArray(); + if (blocks is [var only]) candidates.Add(((long)id, only, pairs)); + } + + // The family a block's records say they belong to: that of the ids the pairs name that belong to one. + var owners = candidates.ToDictionary(candidate => candidate.Family, _ => new HashSet()); + var wanted = candidates.ToLookup(candidate => candidate.Block); + ParameterWriter.ScanPartitions(root, tags, idWidth, (partition, record) => + { + if (record.Channel != 102 || record.Body.Length < 2 || !wanted[record.Block].Any()) return; + if (currentCopies != null && currentCopies.TryGetValue(record.Owner, out int current) && current != partition) return; + foreach (var candidate in wanted[record.Block].Where(c => c.Pairs.ContainsValue((long)record.Owner))) + { + var walk = walker.Run(record.Body.ToArray(), 0, record.Body.Length, BinaryPrimitives.ReadUInt16LittleEndian(record.Body.Span)); + // An element that belongs to no family stores -1. + if (walk.Captures.Where(c => c.Key == OwnerOfElement).ToArray() is [{ Integer: > 0 } owner]) + owners[candidate.Family].Add(owner.Integer); + } + }, new ParameterWriter.Pending()); + + return ([.. candidates.Where(candidate => owners[candidate.Family] is { Count: 1 }) + .Select(candidate => new LoadedFamily(candidate.Family, candidate.Block, owners[candidate.Family].Single(), candidate.Pairs))], null); + } + catch (Exception ex) when (ex is RvtWriteRefusedException || MalformedInput.Is(ex)) { return ([], ex.Message); } + } + + /// The ids of the host that the record of a family pairs with ids of its document; null when the record is not + /// read exactly. + private static Dictionary? PairsOf(WideBlockWalker walker, byte[] body) + { + var walk = walker.Run(body, 0, body.Length, BinaryPrimitives.ReadUInt16LittleEndian(body)); + if (!walk.Exact || walk.Captures.Where(c => c.Key == PairCount + "#").ToArray() is not [var count]) return null; + var items = walk.Captures.Where(c => c.QueueIndex == count.QueueIndex).SkipWhile(c => c.Key != PairCount + "#").Skip(1) + .Where(c => c.Key is PairHost or PairNested).ToArray(); + if (items.Length != 2 * count.Integer) return null; + var pairs = new Dictionary(); + for (int i = 0; i < items.Length; i += 2) + if (items[i].Key != PairHost || items[i + 1].Key != PairNested || !pairs.TryAdd(items[i].Integer, items[i + 1].Integer)) + return null; + return pairs; + } +} diff --git a/src/RvtIO/Meshes/ElementMeshes.cs b/src/RvtIO/Meshes/ElementMeshes.cs index bbb1ba35..5ad9522f 100644 --- a/src/RvtIO/Meshes/ElementMeshes.cs +++ b/src/RvtIO/Meshes/ElementMeshes.cs @@ -223,7 +223,8 @@ public static RvtFamilyTypeMeshes ComputeFamilyType(RvtDocument document, int ty var values = ValuesOf(types.Types[typeIndex]); RvtFamilyTypeMeshes Refused(string code, long id) => new(null, new(code, id.ToString(CultureInfo.InvariantCulture))); foreach (long visibility in model.Extrusions.Select(extrusion => extrusion.VisibilityParameterId) - .Concat(model.Revolutions.Select(revolution => revolution.VisibilityParameterId)).OfType()) + .Concat(model.Revolutions.Select(revolution => revolution.VisibilityParameterId)) + .Concat(model.Placements.Select(placement => placement.VisibilityParameterId)).OfType()) if (!values.ContainsKey(visibility)) return Refused("underdetermined", visibility); var shown = model with { @@ -244,6 +245,32 @@ public static RvtFamilyTypeMeshes ComputeFamilyType(RvtDocument document, int ty var elements = new List(); foreach (int id in prepared.Elements) { + // An instance of a family loaded into this one: the faces of that family, solved for what this type gives it. + if (prepared.Nested?.TryGetValue(id, out var instance) == true) + { + var placement = model.Placements.Single(item => item.ElementId == id); + if (!IsShown(placement.VisibilityParameterId, values)) + { + elements.Add(new ElementMesh { ElementId = id, Coverage = MeshCoverage.Complete }); + continue; + } + var (placed, why) = FamilyNested.Solve(instance.Shape, placement, family.Records!, values, positions); + if (placed == null) return new(null, why); + var nestedFaces = new List(); + foreach (var (elementId, key, face) in FamilyNested.Faces(placed, placement)) + { + if (!instance.Stored.TryGetValue((elementId, key), out var held)) return Refused("degenerate-geometry", id); + // The style of a face of the instance is that of the stored face it is computed for. + face.RenderStyleId = held.RenderStyleId; + face.GeometryStyle = held.GeometryStyle; + face.NestedRenderStyleId = held.NestedRenderStyleId; + nestedFaces.Add(face); + } + var (nestedMeshes, nestedFailed) = Triangulate(nestedFaces, face => MaterialOf(document, face)); + if (nestedFailed > 0) return Refused("degenerate-geometry", id); + elements.Add(new ElementMesh { ElementId = id, Meshes = nestedMeshes, Coverage = MeshCoverage.Complete }); + continue; + } joined.TryGetValue(id, out var combination); if (combination == null && !built.ContainsKey(id) && !turned.ContainsKey(id)) { @@ -301,9 +328,11 @@ private static FamilyPreparation PrepareFamily(RvtDocument document, FamilyData var joined = model.Combinations.SelectMany(combination => combination.Members).ToHashSet(); if (!listed.Select(item => item.Element.Id).Order() .SequenceEqual(model.Extrusions.Select(e => e.ElementId).Concat(model.Revolutions.Select(r => r.ElementId)) - .Where(id => !joined.Contains(id)).Concat(model.Combinations.Select(combination => combination.ElementId)).Order()) + .Where(id => !joined.Contains(id)).Concat(model.Combinations.Select(combination => combination.ElementId)) + .Concat(model.Placements.Select(placement => placement.ElementId)).Order()) || model.Extrusions.Any(extrusion => IsShown(extrusion.VisibilityParameterId, saved) == hidden.Contains(extrusion.ElementId)) - || model.Revolutions.Any(revolution => IsShown(revolution.VisibilityParameterId, saved) == hidden.Contains(revolution.ElementId))) + || model.Revolutions.Any(revolution => IsShown(revolution.VisibilityParameterId, saved) == hidden.Contains(revolution.ElementId)) + || model.Placements.Any(placement => IsShown(placement.VisibilityParameterId, saved) == hidden.Contains(placement.ElementId))) return No("saved-state-mismatch", "the forms of the saved type"); var storedFaces = new Dictionary>(); @@ -317,15 +346,68 @@ private static FamilyPreparation PrepareFamily(RvtDocument document, FamilyData storedFaces[element.Id] = body.Faces.Where(face => !dropUntaken || face.GeometryNode >= 0).ToList(); } var (matched, mismatch) = FamilySavedState.Match(model, saved, MaterialIn(saved), storedFaces); - return matched == null ? No(mismatch!.Code, mismatch.Detail) - : new(model, matched, listed.Select(item => item.Element.Id).ToArray(), null); + if (matched == null) return No(mismatch!.Code, mismatch.Detail); + Dictionary? nested = null; + if (model.Placements.Count > 0) + { + var (states, refused) = PrepareNested(document, family, model, saved, storedFaces); + if (states == null) return new(null, null, [], refused); + nested = states; + } + return new(model, matched, listed.Select(item => item.Element.Id).ToArray(), null) { Nested = nested }; + } + + /// The loaded family of each instance placed in the family, once the instance at the saved type is the faces the file + /// stores for it: each face the loaded family gives, placed, is one of those and no stored face is left. The stored face + /// that each face of the loaded family is gives the style of that face in every type. + private static (Dictionary? States, RvtFamilyRefusal? Refusal) PrepareNested(RvtDocument document, + FamilyData family, FamilyModel model, IReadOnlyDictionary saved, + IReadOnlyDictionary> storedFaces) + { + (Dictionary?, RvtFamilyRefusal?) No(string code, string detail) => (null, new(code, detail)); + if (family.NestedError is { } why) return No("unsupported-construct", why); + var records = family.Records!; + var shapes = new Dictionary(); + var states = new Dictionary(); + var positions = model.Variables.Select(variable => variable.Stored).ToArray(); + foreach (var placement in model.Placements) + { + var families = records.Symbols!.Where(symbol => symbol.Id == placement.SymbolId || symbol.Id == placement.MasterSymbolId) + .Select(symbol => symbol.FamilyId).Distinct().ToList(); + if (families.Count != 1) return No("unrecognized-reference", $"the family of instance {placement.ElementId}"); + long familyId = families[0]; + if (!shapes.TryGetValue(familyId, out var shape)) + { + if (family.Nested?.SingleOrDefault(candidate => candidate.Link.HostFamilyId == familyId) is not { } data) + return No("unrecognized-reference", $"the document of family {familyId}"); + var (prepared, refusal) = FamilyNested.Prepare(data, document.RawData); + if (prepared == null) return (null, refusal); + shapes[familyId] = shape = prepared; + } + var (solution, solved) = FamilyNested.Solve(shape, placement, records, saved, positions); + if (solution == null) return (null, solved); + if (!storedFaces.TryGetValue(placement.ElementId, out var held)) return No("saved-state-mismatch", $"element {placement.ElementId}"); + var left = held.ToList(); + var stored = new Dictionary<(int ElementId, FamilyFaceKey Face), GeoFace>(); + foreach (var (elementId, key, face) in FamilyNested.Faces(solution, placement)) + { + int found = left.FindIndex(candidate => FamilySavedState.SameShape(face, candidate)); + if (found < 0) return No("saved-state-mismatch", $"element {placement.ElementId}"); + // The flat faces of one curved side share a key: the first gives the style. + stored.TryAdd((elementId, key), left[found]); + left.RemoveAt(found); + } + if (left.Count > 0) return No("saved-state-mismatch", $"element {placement.ElementId}"); + states[placement.ElementId] = new(shape, stored); + } + return (states, null); } private static (Element Element, GeometryData? Body) Held(Element element) => (element, element.SerializedComputedSymbolGeometry ?? element.Geometry); /// The numbers of a type by parameter: lengths and other measures, yes/no as 1 or 0, and element keys. - private static Dictionary ValuesOf(RvtFamilyType type) + internal static Dictionary ValuesOf(RvtFamilyType type) { var values = new Dictionary(); foreach (var parameter in type.Parameters) @@ -347,7 +429,7 @@ private static Func MaterialIn(IReadOnlyDic /// The elements of a family document that are listed (shown or hidden by the saved type), in document order, each /// with the geometry that is its body, and why the shape is incomplete. - private static (List<(Element Element, GeometryData? Body)> Listed, HashSet Hidden, string[] Gaps) FamilyElements( + internal static (List<(Element Element, GeometryData? Body)> Listed, HashSet Hidden, string[] Gaps) FamilyElements( RevitFileInfo info, FamilyData family) { var classified = family.Elements.ToDictionary(facts => facts.ElementId, facts => FamilyContent.Classify(facts)); @@ -410,7 +492,7 @@ private sealed record SymbolMeshes(IReadOnlyList Meshes, int Faile /// Whether the faces of untaken Geometry nodes are left out: when a face of a taken node is there and the geometry has /// no ghost node, the rule of the IFC export of the current profile. - private static bool DropsUntakenNodes(IReadOnlyList faces, bool hasGhostNodes) => + internal static bool DropsUntakenNodes(IReadOnlyList faces, bool hasGhostNodes) => !hasGhostNodes && faces.Any(face => face.GeometryNode > 0); /// The drawable elements (see ) in document order, each with the geometry that is its body: diff --git a/src/RvtIO/Writing/ParameterMeasurement.cs b/src/RvtIO/Writing/ParameterMeasurement.cs index 96923d59..edc85fd6 100644 --- a/src/RvtIO/Writing/ParameterMeasurement.cs +++ b/src/RvtIO/Writing/ParameterMeasurement.cs @@ -80,6 +80,12 @@ private sealed record MeasurableSpec(UnitType Unit, string Forge, string Atom); }; } + /// How many internal units (feet, square feet, radians, ...) one of the unit is, for a + /// unit of the table above; null for any other. + internal static double? InternalPerUnit(string unitTypeId) => + UnitSchemaEvaluator.DisplayNameKey(unitTypeId) is { } key && key.StartsWith(UnitPrefix, StringComparison.Ordinal) + ? Units.FirstOrDefault(unit => unit.Forge == key[UnitPrefix.Length..])?.ToInternal : null; + internal static double? Parse(UnitType spec, string input) { var text = input.AsSpan().Trim(); diff --git a/tests/RvtIO.Tests/Families/AquaFixFlangeTests.cs b/tests/RvtIO.Tests/Families/AquaFixFlangeTests.cs new file mode 100644 index 00000000..6bbff31c --- /dev/null +++ b/tests/RvtIO.Tests/Families/AquaFixFlangeTests.cs @@ -0,0 +1,271 @@ +using RvtIO.Families; +using RvtIO.Meshes; +using RvtIO.Model; +using Xunit; + +namespace RvtIO.Tests.Families; + +/// The four flanges of the valve «Задвижка чугунная клиновая_AquaFix»: two families loaded into it, placed four times. +/// Every type of the valve shows them where Revit puts them. +public class AquaFixFlangeTests +{ + private static readonly Lazy Valve = new(() => + RvtDocument.Open(TestFiles.FindRelative("families/aquafix-valve.rfa"), new RvtReaderOptions { R22Layout = true })); + + private const double Millimetre = 1 / 304.8; + + // The family type the file was saved at, «Ду=80». + private const int SavedType = 1; + + // The flange of the DIN family stands on the outside of each end of the valve and the plain flange of the other family on the + // inside of it: the one at +x is 10164284 (DIN) and 10164299 (plain), the one at -x 10164292 and 10164298. + private const int DinRight = 10164284, DinLeft = 10164292, PlainLeft = 10164298, PlainRight = 10164299; + + private static (double[] Min, double[] Max) Box(ElementMesh element) + { + double[] min = [double.MaxValue, double.MaxValue, double.MaxValue], max = [double.MinValue, double.MinValue, double.MinValue]; + foreach (var mesh in element.Meshes) + for (int i = 0; i < mesh.Positions.Length; i++) + { + double value = mesh.Positions[i] / Millimetre; + min[i % 3] = Math.Min(min[i % 3], value); + max[i % 3] = Math.Max(max[i % 3], value); + } + return (min, max); + } + + private static IReadOnlyList Computed(string type) + { + var types = Valve.Value.FamilyTypes!.Types.ToList(); + var result = ElementMeshes.ComputeFamilyType(Valve.Value, types.FindIndex(candidate => candidate.Name == type)); + Assert.Null(result.Refusal); + return result.Elements!; + } + + // Revit 2022 opened the valve on 2026-12-02 and gave, for each flange in each of the 14 types, the box of its solid, in mm: the + // distances of its two ends from the middle of the valve, and the half-width of its section along y and along z. Revit cuts a + // circle into as many flat faces as it likes (the half-width along z is smaller than the one along y where its flat faces + // have no corner on the z axis); the file stores the circle of these flanges as eight, and the flanges are drawn with them. + // The ends are exact; the half-width is that of the circle where a corner of the eight lies on the axis, and at most 1 % of it + // above what Revit gives for the other axis. + [SkippableTheory] + [InlineData("Ду=100", 95, 115, 110, 110, 75, 95, 110, 110)] + [InlineData("Ду=80", 90, 110, 100, 100, 70, 90, 100, 100)] + [InlineData("Ду=300", 135, 163, 230, 230, 107, 135, 235, 235)] + [InlineData("Ду=125", 100, 122, 125, 125, 78, 100, 110, 110)] + [InlineData("Ду=250", 125, 151, 202.5, 201.024, 99, 125, 202.5, 201.024)] + [InlineData("Ду=600", 195, 231, 420, 418.565, 149, 195, 420, 418.565)] + [InlineData("Ду=150", 105, 127, 142.5, 142.5, 83, 105, 142.5, 142.5)] + [InlineData("Ду=50", 75, 93, 82.5, 82.5, 59, 75, 82.5, 82.5)] + [InlineData("Ду=450", 165, 199, 320, 320, 127, 165, 320, 320)] + [InlineData("Ду=200", 115, 139, 170, 170, 91, 115, 170, 170)] + [InlineData("Ду=500", 175, 209, 357.5, 355.975, 133, 175, 357.5, 355.975)] + [InlineData("Ду=65", 85, 103, 92.5, 92.5, 67, 85, 92.5, 92.5)] + [InlineData("Ду=400", 155, 187, 290, 288.411, 119, 155, 290, 288.411)] + [InlineData("Ду=350", 145, 175, 260, 258.576, 113, 145, 260, 258.576)] + public void TheFlangesStandWhereRevitPutsThemInEveryType(string type, double dinIn, double dinOut, double dinY, double dinZ, + double plainIn, double plainOut, double plainY, double plainZ) + { + var elements = Computed(type); + + void Check(int id, double from, double to, double y, double z) + { + var element = Assert.Single(elements, candidate => candidate.ElementId == id); + Assert.NotEmpty(element.Meshes); + var (min, max) = Box(element); + Assert.Equal(from, min[0], 1e-3); + Assert.Equal(to, max[0], 1e-3); + foreach (var (found, revit, axis) in new[] { (max[1], y, "y"), (max[2], z, "z"), (-min[1], y, "-y"), (-min[2], z, "-z") }) + Assert.True(found >= revit - 1e-3 && found <= revit * 1.01, $"{id} {axis}: {found} against Revit's {revit}"); + } + Check(DinRight, dinIn, dinOut, dinY, dinZ); + Check(DinLeft, -dinOut, -dinIn, dinY, dinZ); + Check(PlainLeft, -plainOut, -plainIn, plainY, plainZ); + Check(PlainRight, plainIn, plainOut, plainY, plainZ); + } + + // Every type of the valve is drawn: the body, the ring, the stem with its rim and the bar, and the four flanges. + [SkippableFact] + public void EveryTypeOfTheValveIsDrawnWithItsFourFlanges() + { + var types = Valve.Value.FamilyTypes!.Types; + Assert.Equal(14, types.Count); + foreach (var type in types) + { + var elements = Computed(type.Name); + foreach (int id in new[] { 10164267, 10164308, 10164354, DinRight, DinLeft, PlainLeft, PlainRight }) + Assert.True(elements.Single(element => element.ElementId == id).Meshes.Count > 0, $"{type.Name}: {id} has no shape"); + } + } + + // The volume of a flange is that of what its two circles and its length draw, from the sizes solved for the type. Revit gives the + // volume of the exact circles: the faces the file stores cut a circle into eight, and are drawn so, but the volume is not taken + // from them. + private static double ExactVolume(RvtDocument document, string type, int placementId) + { + var family = document.RawData.Family!; + var types = family.Types!.Types.ToList(); + int index = types.FindIndex(candidate => candidate.Name == type); + Assert.Null(ElementMeshes.ComputeFamilyType(document, index).Refusal); + var prepared = family.Prepared!; + var values = ElementMeshes.ValuesOf(types[index]); + var host = FamilySolver.Solve(prepared.Model!, values); + var placement = prepared.Model!.Placements.Single(item => item.ElementId == placementId); + var (nested, refusal) = FamilyNested.Solve(prepared.Nested![placementId].Shape, placement, family.Records!, values, host.Positions!); + Assert.Null(refusal); + double volume = 0; + foreach (var extrusion in nested!.Shape.Model.Extrusions) + { + double length = Math.Abs(nested.Positions[extrusion.End] - nested.Positions[extrusion.Start]); + var radii = extrusion.Arcs!.Select(loop => nested.Positions[loop[0]!.Value.Radius]).OrderByDescending(radius => radius).ToList(); + Assert.Equal(2, radii.Count); + volume += Math.PI * length * (radii[0] * radii[0] - radii[1] * radii[1]); + } + return volume / Math.Pow(Millimetre, 3); + } + + // Revit's volume of a flange of each family in each type, mm3: the two flanges of a family are alike. The volume solved here is + // within 1e-4 of them (4.8e-5 at most, for the DIN flange; the plain one within 1e-4 as well); the tolerance is chosen here, as + // twice the largest deviation measured, the way the ring of the valve is held to 1e-4. + [SkippableTheory] + [InlineData("Ду=100", 547940, 544276.3)] + [InlineData("Ду=80", 478388.4, 474571.6)] + [InlineData("Ду=300", 2458238.3, 2703333.7)] + [InlineData("Ду=125", 745921.6, 532017.6)] + [InlineData("Ду=250", 1927920.6, 1920440.1)] + [InlineData("Ду=600", 9064856.9, 11750826.7)] + [InlineData("Ду=150", 929166, 924230)] + [InlineData("Ду=50", 309893.2, 266486.3)] + [InlineData("Ду=450", 5193811.5, 5837533.7)] + [InlineData("Ду=200", 1321818.9, 1309425.9)] + [InlineData("Ду=500", 6538515.8, 8175999.7)] + [InlineData("Ду=65", 378525.9, 376264)] + [InlineData("Ду=400", 4130859.8, 4654560.9)] + [InlineData("Ду=350", 3238036, 3445836.3)] + public void TheFlangesHaveTheVolumeRevitGivesInEveryType(string type, double din, double plain) + { + var document = Valve.Value; + + foreach (int id in new[] { DinRight, DinLeft }) + Assert.Equal(din, ExactVolume(document, type, id), din * 1e-4); + foreach (int id in new[] { PlainLeft, PlainRight }) + Assert.Equal(plain, ExactVolume(document, type, id), plain * 1e-4); + } + + private static RvtDocument Fresh() => + RvtDocument.Open(TestFiles.FindRelative("families/aquafix-valve.rfa"), new RvtReaderOptions { R22Layout = true }); + + // The definition of a shared parameter is in the first block of the file, for the family of the file and for every family loaded + // into it: a dimension of the DIN flange is labelled by one, which holds 100 mm. + [SkippableFact] + public void TheSharedParameterOfALoadedFamilyIsReadFromTheFirstBlock() + { + var family = Fresh().RawData.Family!; + + var din = Assert.Single(family.Nested!, nested => nested.Link.OwnerId == 9999520); + var shared = Assert.Single(din.Data.Types!.Types[0].Parameters, parameter => parameter.Id == 7000448); + Assert.Equal(StorageType.Double, shared.StorageType); + Assert.Equal(100 * Millimetre, (double)shared.Value!, 1e-9); + } + + private static FamilyData With(FamilyData family, IReadOnlyList? nested = null) => new() + { + Elements = family.Elements, Types = family.Types, TypesError = family.TypesError, Records = family.Records, + Nested = nested ?? family.Nested, NestedError = family.NestedError, + }; + + // A flange whose family has no document of its own in the file is not drawn in any type, and the refusal names the family. + [SkippableFact] + public void AFlangeWhoseFamilyHasNoDocumentIsRefused() + { + var document = Fresh(); + var family = document.RawData.Family!; + document.RawData.Family = With(family, [.. family.Nested!.Where(nested => nested.Link.HostFamilyId != 10164490)]); + + var result = ElementMeshes.ComputeFamilyType(document, SavedType); + + Assert.Null(result.Elements); + Assert.Equal("unrecognized-reference", result.Refusal!.Code); + Assert.Contains("10164490", result.Refusal.Detail); + } + + // The type of the host that chooses another type of the loaded family for a flange has a flange this code does not know: that + // type is refused, and the others are drawn. + [SkippableFact] + public void ATypeThatChoosesAnotherTypeForAFlangeIsRefusedAlone() + { + var document = Fresh(); + var types = document.RawData.Family!.Types!.Types; + int other = types.ToList().FindIndex(candidate => candidate.Name == "Ду=100"); + types[other].Parameters.Single(parameter => parameter.Id == 10164283).Value = 10164382; + + var refused = ElementMeshes.ComputeFamilyType(document, other); + var saved = ElementMeshes.ComputeFamilyType(document, SavedType); + + Assert.Null(refused.Elements); + Assert.Equal("unsupported-construct", refused.Refusal!.Code); + Assert.Contains("10164283", refused.Refusal.Detail); + Assert.Null(saved.Refusal); + } + + // A loaded family of several types is refused with its number of types: which type an instance is of cannot be told from one. + [SkippableFact] + public void ALoadedFamilyOfSeveralTypesIsRefused() + { + var document = Fresh(); + var nested = document.RawData.Family!.Nested![0]; + var type = nested.Data.Types!.Types[0]; + var two = new FamilyData + { + Elements = nested.Data.Elements, Records = nested.Data.Records, + Types = new RvtFamilyTypes(0, [type, type with { Name = "other" }]), + }; + + var (shape, refusal) = FamilyNested.Prepare(nested with { Data = two }, document.RawData); + + Assert.Null(shape); + Assert.Equal("unsupported-construct", refusal!.Code); + Assert.Contains("2 types", refusal.Detail); + } + + // A box of 1 by 1 by 2 along x, placed with its x axis turned about (-1) or kept (1): it stands from 0 to 2 or from -2 to 0, and + // every face looks outward, the corners running the way the normal says. The mirror (a negative determinant) is the one that + // turns the corners the other way round. + [Theory] + [InlineData(1, 1, 1)] + [InlineData(-1, 1, 1)] + [InlineData(-1, -1, 1)] + [InlineData(1, -1, 1)] + public void AnInstanceKeepsItsFacesLookingOutwardWhateverItsBasis(double x, double y, double z) + { + var square = new FamilyVertex[] { new(0, 0, 0), new(0, 1, 0), new(0, 1, 1), new(0, 0, 1) }; + var extrusion = new FamilyExtrusion(7, [square], 0, 0, 2, new Dictionary(), null, null); + var model = new FamilyModel([new(0, false), new(1, false), new(2, false)], [], [extrusion]); + var shape = new NestedShape + { + Link = new(1, 1, 1, new Dictionary()), Model = model, Formulas = null!, TypeValues = new Dictionary(), + }; + var placement = new FamilyPlacement(8, 1, 1, [0, 0, 0], [[x, 0, 0], [0, y, 0], [0, 0, z]], null); + + var faces = FamilyNested.Faces(new NestedSolution(shape, [0, 1, 2], [0, 0, 0]), placement); + + Assert.Equal(6, faces.Count); + double[] middle = [x, 0.5 * y, 0.5 * z]; + foreach (var (_, _, face) in faces) + { + var corners = face.OuterVertices!; + // The normal of the corners in their order (Newell's method) is the normal of the face. + double[] newell = [0, 0, 0]; + for (int i = 0; i < corners.Count; i++) + { + var (a, b) = (corners[i], corners[(i + 1) % corners.Count]); + newell[0] += (a[1] - b[1]) * (a[2] + b[2]); + newell[1] += (a[2] - b[2]) * (a[0] + b[0]); + newell[2] += (a[0] - b[0]) * (a[1] + b[1]); + } + Assert.True(newell[0] * face.Normal[0] + newell[1] * face.Normal[1] + newell[2] * face.Normal[2] > 0); + // Outward: the corner of the face lies on the side of the middle of the box that its normal points to. + Assert.True(Enumerable.Range(0, 3).Sum(axis => (corners[0][axis] - middle[axis]) * face.Normal[axis]) > 0); + } + } +} diff --git a/tests/RvtIO.Tests/Families/AquaFixValveTests.cs b/tests/RvtIO.Tests/Families/AquaFixValveTests.cs index 6ae39d8c..40bdea18 100644 --- a/tests/RvtIO.Tests/Families/AquaFixValveTests.cs +++ b/tests/RvtIO.Tests/Families/AquaFixValveTests.cs @@ -182,20 +182,23 @@ public void TheStoredFacesOfTheBodyOfTheValveMatchItsSurfacesWithTheirCornersOnC // The stem and the rim: the file stores the rim as an octagon with its corners at ±90 degrees cut at y = ±96.02 mm (corners at // 96.085 mm and ±87.9, ±92.1 degrees), the height of the top side of Revit's own rim of 18 facets, and stores no corner at 90 // degrees. Those corners are on the sides of the octagon the other corners of the circle define, to 1e-12 mm: the corners the - // file cut away are corners of that polygon all the same, and the valve, without its flanges, is computed. + // file cut away are corners of that polygon all the same, and the valve is computed with its four flanges. [SkippableFact] - public void TheValveWithoutItsFlangesIsComputedInTheTypeTheFileWasSavedAt() + public void TheValveIsComputedInTheTypeTheFileWasSavedAt() { - var computed = ElementMeshes.ComputeFamilyType(WithoutFlanges(), SavedType); + var document = RvtDocument.Open(TestFiles.FindRelative("families/aquafix-valve.rfa"), new RvtReaderOptions { R22Layout = true }); + + var computed = ElementMeshes.ComputeFamilyType(document, SavedType); Assert.Null(computed.Refusal); - Assert.Equal([10164267, 10164308, 10164354], computed.Elements!.Select(element => element.ElementId).Order()); + Assert.Equal([10164267, 10164284, 10164292, 10164298, 10164299, 10164308, 10164354], + computed.Elements!.Select(element => element.ElementId).Order()); } [SkippableFact] - public void TheValveWithoutItsFlangesIsComputedInEveryType() + public void TheValveIsComputedInEveryType() { - var document = WithoutFlanges(); + var document = RvtDocument.Open(TestFiles.FindRelative("families/aquafix-valve.rfa"), new RvtReaderOptions { R22Layout = true }); var types = document.RawData.Family!.Types!.Types; var outcome = Enumerable.Range(0, types.Count).Select(index => @@ -207,15 +210,15 @@ public void TheValveWithoutItsFlangesIsComputedInEveryType() Assert.Equal([], outcome.Where(line => !line.EndsWith("computed"))); } - // What the valve still holds that cannot be computed: the four flanges, each a family loaded into it and placed. + // The valve holds nothing that is shown and cannot be computed: its four flanges are families loaded into it and placed, and + // the symbol of the parking space is not shown in the Fine level. [SkippableFact] - public void OnlyTheFourNestedFlangesAreStillUnsupported() + public void NothingTheValveShowsIsLeftUnsupported() { - var unsupported = Records().UnsupportedContent.Distinct().Order().ToList(); + var records = Records(); - Assert.Equal(4, unsupported.Count); - Assert.All(unsupported, entry => Assert.StartsWith("FamilyInstance ", entry)); - Assert.Equal([10164284, 10164292, 10164298, 10164299], - unsupported.Select(entry => int.Parse(entry["FamilyInstance ".Length..])).Order()); + Assert.Empty(records.UnsupportedContent); + Assert.Equal([10164284, 10164292, 10164298, 10164299], records.Instances!.Where(instance => instance.Shown).Select(instance => instance.Id).Order()); + Assert.Contains(records.Instances!, instance => instance.Id == 10164406 && !instance.Shown); } } diff --git a/tests/RvtIO.Tests/Families/FamilyCombinationFaceTests.cs b/tests/RvtIO.Tests/Families/FamilyCombinationFaceTests.cs new file mode 100644 index 00000000..1841f4a1 --- /dev/null +++ b/tests/RvtIO.Tests/Families/FamilyCombinationFaceTests.cs @@ -0,0 +1,78 @@ +using RvtIO.Families; +using Xunit; + +namespace RvtIO.Tests.Families; + +/// A face of a combination of forms has a tag of its own, and the steps that add the members to the combination say +/// which face of which member it is. An alignment to a face of the combination holds that face of the member. +public class FamilyCombinationFaceTests +{ + private const int Combination = 60, Extrusion = SyntheticFamily.Extrusion; + + // The top of the box is held by the alignment 34 of its extrusion's end cap (tag 0) to the plane 8; here it names the tag 7 of + // a combination of the extrusion instead, which is that cap. + private static FamilyRecords Aligned(int tag, IReadOnlyDictionary? faces) => + SyntheticFamily.Leaf().Without(34).Add(SyntheticFamily.Alignment(34, 2, (8, 0, -1), (Combination, tag, -1))) with + { + Combinations = [new(Combination, [Extrusion], faces)], + }; + + private static readonly Dictionary Faces = new() { [7] = new(Extrusion, 0), [9] = new(Extrusion, 1) }; + + private static void AssertRefused(FamilyRecords records, string code, string detail) + { + var (model, refusal) = FamilyModelBuilder.Build(records); + + Assert.Null(model); + Assert.Equal(code, refusal!.Code); + Assert.Contains(detail, refusal.Detail); + } + + [Fact] + public void AnAlignmentToAFaceOfACombinationHoldsTheFaceOfTheMemberItIs() + { + var (model, refusal) = FamilyModelBuilder.Build(Aligned(7, Faces)); + + Assert.Null(refusal); + var solution = FamilySolver.Solve(model!, new Dictionary { [100] = 3, [101] = 5 }); + Assert.Null(solution.Refusal); + Assert.Equal(5, solution.Positions![model!.Extrusions.Single().End], 1e-9); + } + + [Fact] + public void ATagTheCombinationHasNoFaceForIsRefused() => + AssertRefused(Aligned(8, Faces), "unrecognized-reference", "tag 8 of element 60"); + + // The steps of a combination that do not read the way the files seen so far do leave no face named. + [Fact] + public void ACombinationWhoseFacesAreNotReadIsRefused() => + AssertRefused(Aligned(7, null), "unrecognized-reference", "tag 7 of element 60"); + + [Fact] + public void AFaceOfAFormThatIsNoMemberIsRefused() => + AssertRefused(Aligned(7, new Dictionary { [7] = new(99, 0) }), "unrecognized-reference", + "tag 7 of element 60"); + + [Fact] + public void AFaceThatTheMemberHasNoTagForIsRefused() => + AssertRefused(Aligned(7, new Dictionary { [7] = new(Extrusion, 77) }), "unrecognized-reference", + "tag 77 of element 50"); + + // The valve joins a revolution and an extrusion; each step lists the faces of its member by the tag they have in it. + [SkippableFact] + public void TheFacesOfTheCombinationOfTheValveAreReadFromTheStepsThatAddItsMembers() + { + var combination = Assert.Single(RvtDocument.Open(TestFiles.FindRelative("families/aquafix-valve.rfa"), + new RvtReaderOptions { R22Layout = true }).RawData.Family!.Records!.Combinations!); + + var faces = combination.Faces!; + // The bar (10164350): its top (tag 0) and its bottom (tag 1) are the faces 0 and 15 of the combination. + Assert.Equal(new FamilyFaceOrigin(10164350, 0), faces[0]); + Assert.Equal(new FamilyFaceOrigin(10164350, 1), faces[15]); + Assert.Equal(new FamilyFaceOrigin(10164350, 71), faces[369]); + // The revolution (10164322). + Assert.Equal(new FamilyFaceOrigin(10164322, 16), faces[74]); + Assert.Equal(new FamilyFaceOrigin(10164322, 33), faces[97]); + Assert.Equal(34, faces.Count); + } +} diff --git a/tests/RvtIO.Tests/Families/FamilyFormulaTests.cs b/tests/RvtIO.Tests/Families/FamilyFormulaTests.cs new file mode 100644 index 00000000..4941c439 --- /dev/null +++ b/tests/RvtIO.Tests/Families/FamilyFormulaTests.cs @@ -0,0 +1,82 @@ +using OpenMcdf; +using RvtIO.Families; +using Xunit; + +namespace RvtIO.Tests.Families; + +/// The formulas and the size tables of a family document are read from its record and calculated: the flange families +/// loaded into the AquaFix valve (the documents of blocks 8 and 10) give their sizes by a table that a nominal diameter picks a +/// row of. +public class FamilyFormulaTests +{ + private const double FeetPerMillimetre = 1 / 304.8; + // The ids of the two documents are those of the elements in the file; the host reads them from its families (see + // NestedFamilyLinkTests). + private const long Din2633Owner = 9999520, Din2633Radius = 10000091, Din2633Outer = 10000090; + private const int Din2633Block = 8; + + private static (FamilyFormulas Formulas, RootStorage Root) Open(long owner, int block) + { + var root = RootStorage.OpenRead(TestFiles.FindRelative("families/aquafix-valve.rfa")); + var (formulas, error) = FamilyFormulas.Read(root, owner, null, null, block); + return (formulas ?? throw new Xunit.Sdk.XunitException("not read: " + error), root); + } + + // Every formula of the family reproduces the value the file stores for it: the table is read and the formulas are calculated + // the way Revit does, or this is not shown. + [SkippableTheory] + [InlineData(Din2633Owner, Din2633Block)] + [InlineData(10161440L, 10)] + public void EveryFormulaReproducesItsStoredValue(long owner, int block) + { + var (formulas, root) = Open(owner, block); + using (root) + { + Assert.NotEmpty(formulas.Driven); + Assert.Null(formulas.CheckStored()); + } + } + + [SkippableFact] + public void ARadiusPicksTheRowsOfTheSizeTableForTheSizesOfTheFlange() + { + var (formulas, root) = Open(Din2633Owner, Din2633Block); + using (root) + { + // DN 80: the outer diameter of the flange is 200 mm. + var (values, refusal) = formulas.Evaluate(id => id == Din2633Radius ? 40 * FeetPerMillimetre : null); + + Assert.Null(refusal); + Assert.Equal(200 * FeetPerMillimetre, values![Din2633Outer], 12); + } + } + + [SkippableFact] + public void ARadiusThatNoRowOfTheTableHasIsRefusedNotApproximated() + { + var (formulas, root) = Open(Din2633Owner, Din2633Block); + using (root) + { + var (values, refusal) = formulas.Evaluate(id => id == Din2633Radius ? 41 * FeetPerMillimetre : null); + + Assert.Null(values); + Assert.Equal("underdetermined", refusal!.Code); + } + } + + [SkippableFact] + public void TheTableHasARowForEveryNominalDiameterOfTheValve() + { + var (formulas, root) = Open(Din2633Owner, Din2633Block); + using (root) + { + var table = Assert.Single(formulas.Tables); + + Assert.Equal("ГеометрияФланца DIN 2633 PN16", table.Name); + Assert.Equal(24, table.Rows.Count); + foreach (int diameter in new[] { 50, 65, 80, 100, 125, 150, 200, 250, 300, 350, 400, 450, 500, 600 }) + Assert.Contains(table.Rows, row => Math.Abs((double)row[1] - diameter * FeetPerMillimetre) < 1e-9); + Assert.Equal(["", "DN", "D", "k", "d4", "b", "Massa", "n", "d2", "f"], table.Columns); + } + } +} diff --git a/tests/RvtIO.Tests/Families/FamilyPlacementTests.cs b/tests/RvtIO.Tests/Families/FamilyPlacementTests.cs new file mode 100644 index 00000000..a8d09ba8 --- /dev/null +++ b/tests/RvtIO.Tests/Families/FamilyPlacementTests.cs @@ -0,0 +1,174 @@ +using RvtIO.Families; +using Xunit; + +namespace RvtIO.Tests.Families; + +/// A family loaded into a family and placed in it stands at a point of the frame of the family, and what a dimension or +/// an alignment measures to one of its reference planes (a plane of its symbol, through the point it stands at) is that point. +/// The model gives it a variable for each coordinate of the point. +public class FamilyPlacementTests +{ + private const int Instance = 60, Symbol = 61, Host = 52; + private static readonly double[][] Identity = [[1, 0, 0], [0, 1, 0], [0, 0, 1]]; + + private static FamilySymbolRecord Planes() => new(Symbol, 999, [], new Dictionary + { + [1] = new([0, 0, 0], [1, 0, 0]), [2] = new([0.5, 0, 0], [1, 0, 0]), [3] = new([0, 0, 0], [0, 1, 0]), + [4] = new([0, 0, 0], [0, 0, 1]), + }); + + // The box of SyntheticFamily with an instance of a symbol at (1.5, 0.25, 2), where its right side and top stand. + private static FamilyRecords WithInstance(FamilyRecords records, FamilyDimensionRecord? alignment = null, + FamilyInstanceRecord? instance = null, params FamilyReferrer[] referrers) => + records with + { + Instances = [instance ?? new FamilyInstanceRecord(Instance, Symbol, Symbol, [1.5, 0.25, 2], Identity, -1, Shown: true)], + Symbols = [Planes()], + Dimensions = alignment == null ? records.Dimensions : [.. records.Dimensions, alignment], + Referrers = [.. records.Referrers, .. referrers], + }; + + private static FamilyModel Built(FamilyRecords records) + { + var (model, refusal) = FamilyModelBuilder.Build(records); + Assert.Null(refusal); + return model!; + } + + private static double[] Solved(FamilyModel model, double width = 3, double height = 2) + { + var solution = FamilySolver.Solve(model, new Dictionary { [100] = width, [101] = height }); + Assert.Null(solution.Refusal); + return solution.Positions!; + } + + private static void AssertRefused(FamilyRecords records, string code, string detail) + { + var (model, refusal) = FamilyModelBuilder.Build(records); + + Assert.Null(model); + Assert.Equal(code, refusal!.Code); + Assert.Contains(detail, refusal.Detail); + } + + // The plane of the symbol with tag 1 stands at the origin of the instance: aligned to the right side of the box, the origin + // goes where that side goes, which is half the width from the centre plane. + [Fact] + public void AnInstanceAlignedToAPlaneStandsWhereThePlaneGoes() + { + var model = Built(WithInstance(SyntheticFamily.Leaf(), SyntheticFamily.Alignment(62, 0, (3, 0, -1), (Instance, 1, -1)))); + + var placement = Assert.Single(model.Placements); + Assert.Equal(Instance, placement.ElementId); + Assert.Equal(Symbol, placement.SymbolId); + Assert.Equal(Identity, placement.Basis); + Assert.Equal(1.5, Solved(model, width: 3)[placement.Origin[0]], 1e-9); + Assert.Equal(4, Solved(model, width: 8)[placement.Origin[0]], 1e-9); + } + + // What nothing holds keeps the place the file gave it, in any type. + [Fact] + public void WhatNothingHoldsOfTheOriginStaysWhereTheFileLeftIt() + { + var model = Built(WithInstance(SyntheticFamily.Leaf(), SyntheticFamily.Alignment(62, 0, (3, 0, -1), (Instance, 1, -1)))); + + var placement = Assert.Single(model.Placements); + var positions = Solved(model, width: 8, height: 5); + Assert.Equal(0.25, positions[placement.Origin[1]], 1e-9); + Assert.Equal(2, positions[placement.Origin[2]], 1e-9); + } + + // An instance on a work plane stands as far from what the plane follows as it stood. + [Fact] + public void AnInstanceOnAWorkPlaneFollowsWhatThePlaneFollows() + { + var onTop = new FamilyInstanceRecord(Instance, Symbol, Symbol, [1.5, 0.25, 2.5], Identity, Host, new(8, 0, -1), [0, 0, 1], + Shown: true); + var model = Built(WithInstance(SyntheticFamily.Leaf(), instance: onTop)); + + var placement = Assert.Single(model.Placements); + Assert.Equal(7.5, Solved(model, height: 7)[placement.Origin[2]], 1e-9); + Assert.Equal(0.25, Solved(model, height: 7)[placement.Origin[1]], 1e-9); + } + + // An instance that is not shown in any type is no part of the shape: what places it places nothing. + [Fact] + public void AnInstanceNoTypeShowsIsNotPlaced() + { + var hidden = new FamilyInstanceRecord(Instance, Symbol, Symbol, [1.5, 0.25, 2], Identity, -1); + var model = Built(WithInstance(SyntheticFamily.Leaf(), instance: hidden)); + + Assert.Empty(model.Placements); + } + + [Fact] + public void ATagTheSymbolHasNoPlaneForIsRefused() + { + AssertRefused(WithInstance(SyntheticFamily.Leaf(), SyntheticFamily.Alignment(62, 0, (3, 0, -1), (Instance, 9, -1))), + "unrecognized-reference", "62"); + } + + // A plane at a distance from the origin stands where the family it is of puts it, and that depends on its parameters. + [Fact] + public void APlaneAtADistanceFromTheOriginIsRefused() + { + AssertRefused(WithInstance(SyntheticFamily.Leaf(), SyntheticFamily.Alignment(62, 0, (3, 0, -1), (Instance, 2, -1))), + "unsupported-construct", "62"); + } + + [Fact] + public void APlaneThatDoesNotFaceTheAxisOfTheDimensionIsRefused() + { + AssertRefused(WithInstance(SyntheticFamily.Leaf(), SyntheticFamily.Alignment(62, 0, (3, 0, -1), (Instance, 3, -1))), + "unsupported-construct", "62"); + } + + // The stand of the instance turns the planes of its symbol: a half turn about the vertical axis keeps the plane of tag 1 square to x. + [Fact] + public void ATurnedInstanceStandsAtItsOriginToo() + { + double[][] turned = [[-1, 0, 0], [0, -1, 0], [0, 0, 1]]; + var model = Built(WithInstance(SyntheticFamily.Leaf(), SyntheticFamily.Alignment(62, 0, (3, 0, -1), (Instance, 1, -1)), + new FamilyInstanceRecord(Instance, Symbol, Symbol, [1.5, 0.25, 2], turned, -1, Shown: true))); + + var placement = Assert.Single(model.Placements); + Assert.Equal(turned, placement.Basis); + Assert.Equal(4, Solved(model, width: 8)[placement.Origin[0]], 1e-9); + } + + [Fact] + public void AStandThatIsNoRotationOrReflectionIsRefused() + { + double[][] sheared = [[1, 0, 0], [1, 1, 0], [0, 0, 1]]; + AssertRefused(WithInstance(SyntheticFamily.Leaf(), + instance: new FamilyInstanceRecord(Instance, Symbol, Symbol, [1.5, 0.25, 2], sheared, -1, Shown: true)), + "unsupported-construct", Instance.ToString()); + } + + // A work plane that is no plane of an axis cannot tie the origin to anything. + [Fact] + public void AWorkPlaneThatIsSlantedIsRefused() + { + var slanted = new FamilyInstanceRecord(Instance, Symbol, Symbol, [1.5, 0.25, 2], Identity, Host, new(8, 0, -1), + [0, 0.6, 0.8], Shown: true); + AssertRefused(WithInstance(SyntheticFamily.Leaf(), instance: slanted), "unsupported-construct", Instance.ToString()); + } + + // A record of the instance that refers to a form of the family and is none of what is read could move it. + [Fact] + public void ARecordOfTheInstanceThatRefersToTheFamilyInAnUnknownWayIsRefused() + { + AssertRefused(WithInstance(SyntheticFamily.Leaf(), SyntheticFamily.Alignment(62, 0, (3, 0, -1), (Instance, 1, -1)), + referrers: new FamilyReferrer(Instance, "FamilyInstance", "Unknown.m_elemId", 3)), + "unrecognized-reference", "FamilyInstance 60"); + } + + [Fact] + public void TheLevelAnInstanceIsListedAtMovesNothing() + { + var model = Built(WithInstance(SyntheticFamily.Leaf(), SyntheticFamily.Alignment(62, 0, (3, 0, -1), (Instance, 1, -1)), + referrers: new FamilyReferrer(Instance, "FamilyInstance", "FamilyInstance.m_scheduleOnlyLevelId", 7))); + + Assert.Single(model.Placements); + } +} diff --git a/tests/RvtIO.Tests/Families/FamilyReferenceLineTests.cs b/tests/RvtIO.Tests/Families/FamilyReferenceLineTests.cs new file mode 100644 index 00000000..1705ec0c --- /dev/null +++ b/tests/RvtIO.Tests/Families/FamilyReferenceLineTests.cs @@ -0,0 +1,161 @@ +using RvtIO.Families; +using Xunit; + +namespace RvtIO.Tests.Families; + +/// A reference line in a sketch of its own, whose dimensions reach only planes that stay where they are (a level, a +/// pinned plane, a centre plane) and lines like it, shapes nothing: no form of the family and no plane that moves is held to it, +/// whatever the sketch holds of it. It is the line a work plane is drawn through, for something that is not shown. +public class FamilyReferenceLineTests +{ + private const int Line = 70, Sketch = 71, Level = 7, Centre = 1, Top = 8, AngleParameter = 102; + + // The angle between the line and `with`, held by the label `parameter` (-1 for none) at 0, the angle the line has in the file. + private static FamilyAngularDimension Angle(int with, long parameter = AngleParameter) => + new(74, [new(Line, 0, -1), new(with, 0, -1)], parameter, 0, 12, 0, false); + + // The line along x, on the level and 1 from the centre plane, in a sketch with a constraint nothing here reads; a dimension + // holds it to `to` along z; an angular dimension (not a relation this reads) measures it to the plane `angleTo`. + private static FamilyRecords WithLine(int to, int angleTo) => SyntheticFamily.Leaf() with + { + Lines = [.. SyntheticFamily.Leaf().Lines, new(Line, Sketch, true, [0, 0, 0], [1, 0, 0])], + Constraints = [.. SyntheticFamily.Leaf().Constraints, new(Sketch, "VarSketchDistConstrObj")], + Dimensions = [.. SyntheticFamily.Leaf().Dimensions, SyntheticFamily.Alignment(72, 2, (to, 0, -1), (Line, 0, 0))], + Referrers = + [ + .. SyntheticFamily.Leaf().Referrers, + new(72, "Alignment", "GeomSegInPlaneRef.GeomRef.m_elemId", Line), + new(73, "SketchPlane", "GeomOnPlaneRef.GeomRef.m_elemId", Line), + new(74, "AngularDim", "GeomSegInPlaneRef.GeomRef.m_elemId", Line), + new(74, "AngularDim", "GeomSegInPlaneRef.GeomRef.m_elemId", angleTo), + new(74, "AngularDim", "SketchMembership.GroupMembership.m_groupId", Sketch), + ], + AngularDimensions = [Angle(angleTo)], + }; + + private static void AssertRefused(FamilyRecords records, string code, string detail) + { + var (model, refusal) = FamilyModelBuilder.Build(records); + + Assert.Null(model); + Assert.Equal(code, refusal!.Code); + Assert.Contains(detail, refusal.Detail); + } + + [Fact] + public void AReferenceLineHeldOnlyToAPlaneThatStaysMovesNothing() + { + var (model, refusal) = FamilyModelBuilder.Build(WithLine(Level, Centre)); + + Assert.Null(refusal); + var solution = FamilySolver.Solve(model!, new Dictionary { [100] = 3, [101] = 5, [AngleParameter] = 0 }); + Assert.Null(solution.Refusal); + Assert.Equal(5, solution.Positions![model!.Extrusions.Single().End], 1e-9); + } + + // The line stays as the file has it, so a label of its angle can only have the angle the file has: another value in some + // type is a line that turns, which the model does not follow. + [Fact] + public void AnAngleLabelledByAParameterMustHoldTheStoredAngleInEveryType() + { + var (model, refusal) = FamilyModelBuilder.Build(WithLine(Level, Centre)); + + Assert.Null(refusal); + var solution = FamilySolver.Solve(model!, new Dictionary { [100] = 3, [101] = 5, [AngleParameter] = 0.5 }); + Assert.Null(solution.Positions); + Assert.Equal("inconsistent", solution.Refusal!.Code); + Assert.Equal("74", solution.Refusal.Detail); + } + + [Fact] + public void AnAngleWithoutALabelHoldsNothing() + { + var records = WithLine(Level, Centre) with { AngularDimensions = [Angle(Centre, -1)] }; + + var (model, refusal) = FamilyModelBuilder.Build(records); + + Assert.Null(refusal); + Assert.Null(FamilySolver.Solve(model!, new Dictionary { [100] = 3, [101] = 5 }).Refusal); + } + + // The records say an angle is there, and nothing says what it measures. + [Fact] + public void AnAngleThatIsNotReadIsRefused() => + AssertRefused(WithLine(Level, Centre) with { AngularDimensions = [] }, "unrecognized-reference", "AngularDim 74"); + + // The top of the box moves with the height: a line held to it is held to a form. + [Fact] + public void AReferenceLineHeldToAPlaneThatMovesIsNotApart() => + AssertRefused(WithLine(Top, Centre), "unrecognized-reference", "VarSketchDistConstrObj of sketch 71"); + + // An angle to a plane that moves turns the line with it: the line is held to a form. + [Fact] + public void AnAngleToAPlaneThatMovesIsNotApart() => + AssertRefused(WithLine(Level, Top), "unrecognized-reference", "VarSketchDistConstrObj of sketch 71"); + + // A dimension with a label ties the line to the plane by a parameter: the line moves with it, so it is held to a form. + [Fact] + public void ALineWhoseDimensionIsLabelledIsNotApart() => + AssertRefused(WithLine(Level, Centre).Without(72) + .Add(SyntheticFamily.Linear(72, 2, 12, [(Level, 0, -1), (Line, 0, 0)], [0], [100], [0.5])), + "unrecognized-reference", "VarSketchDistConstrObj of sketch 71"); + + // A work plane drawn through the line, and what stands on it: the line stays, so what stands on it stays where it stood + // from the line, in every type. + private static readonly double[][] Identity = [[1, 0, 0], [0, 1, 0], [0, 0, 1]]; + + private static FamilyRecords WithInstanceOnTheLine(int to) => WithLine(to, Centre) with + { + Instances = [new FamilyInstanceRecord(60, 61, 61, [0.5, 0, 0.25], Identity, 73, new FamilyReference(Line, 0, -1), [0, 0, 1], + Shown: true)], + Symbols = [new FamilySymbolRecord(61, 999, [], new Dictionary())], + }; + + [Fact] + public void AnInstanceOnAPlaneThroughALineThatStaysStandsWhereItStood() + { + var (model, refusal) = FamilyModelBuilder.Build(WithInstanceOnTheLine(Level)); + + Assert.Null(refusal); + var placement = Assert.Single(model!.Placements); + foreach (double height in new[] { 2.0, 7.0 }) + { + var solution = FamilySolver.Solve(model, new Dictionary { [100] = 3, [101] = height, [AngleParameter] = 0 }); + Assert.Null(solution.Refusal); + Assert.Equal(0.25, solution.Positions![placement.Origin[2]], 1e-9); + Assert.Equal(0.5, solution.Positions![placement.Origin[0]], 1e-9); + } + } + + // A line held to the top of the box moves with it, and the instance on a plane through the line would move too. + [Fact] + public void AnInstanceOnAPlaneThroughALineThatMovesIsRefused() => + AssertRefused(WithInstanceOnTheLine(Top), "unrecognized-reference", "VarSketchDistConstrObj of sketch 71"); + + // The valve draws a work plane through a reference line and holds the line's angle to a plane by a label. + [SkippableFact] + public void TheAngleOfTheValveIsReadFromTheFile() + { + var records = RvtDocument.Open(TestFiles.FindRelative("families/aquafix-valve.rfa"), + new RvtReaderOptions { R22Layout = true }).RawData.Family!.Records!; + + var angle = Assert.Single(records.AngularDimensions!); + Assert.Equal(10164402, angle.Id); + Assert.Equal([new FamilyReference(10164399, 0, -1), new FamilyReference(10163781, 0, -1)], angle.References); + Assert.NotEqual(-1, angle.ParameterId); + Assert.Equal(0, angle.Value); + Assert.False(angle.Driven); + } + + // A line of the profile of a form is a line of the model, whatever else it is held to. + [Fact] + public void ALineOfAProfileIsNotApart() + { + var records = SyntheticFamily.Leaf() with + { + Constraints = [.. SyntheticFamily.Leaf().Constraints, new(40, "VarSketchDistConstrObj")], + Dimensions = [.. SyntheticFamily.Leaf().Dimensions, SyntheticFamily.Alignment(72, 2, (Level, 0, -1), (41, 0, 0))], + }; + AssertRefused(records, "unrecognized-reference", "VarSketchDistConstrObj of sketch 40"); + } +} diff --git a/tests/RvtIO.Tests/Families/NestedFamilyLinkTests.cs b/tests/RvtIO.Tests/Families/NestedFamilyLinkTests.cs new file mode 100644 index 00000000..1ced3965 --- /dev/null +++ b/tests/RvtIO.Tests/Families/NestedFamilyLinkTests.cs @@ -0,0 +1,53 @@ +using OpenMcdf; +using RvtIO.Families; +using Xunit; + +namespace RvtIO.Tests.Families; + +/// A family loaded into a family file is a record of the host that pairs the host's ids with the ids of the loaded +/// document, which sits in a block of the partitions: the link of each loaded family to its document is read from those pairs. +public class NestedFamilyLinkTests +{ + private static IReadOnlyList LoadedFamilies() + { + string path = TestFiles.FindRelative("families/aquafix-valve.rfa"); + var document = RvtDocument.Open(path, new RvtReaderOptions { R22Layout = true }); + using var root = RootStorage.OpenRead(path); + var (families, error) = NestedFamilies.Read(root, null, document.FamilyOwnerId!.Value); + Assert.NotNull(families); + Assert.Null(error); + return families; + } + + // The two flange families of the valve: «(Общ)_DIN_2633_PN16_(15-1000)_Фланец приварной» and «Фланец(Обобщ)». + [SkippableTheory] + [InlineData(10164755L, 8, 9999520L)] + [InlineData(10164490L, 10, 10161440L)] + public void ALoadedFamilyIsLinkedToTheBlockAndOwnerOfItsDocument(long hostFamily, int block, long owner) + { + var loaded = Assert.Single(LoadedFamilies(), family => family.HostFamilyId == hostFamily); + + Assert.Equal(block, loaded.Block); + Assert.Equal(owner, loaded.OwnerId); + Assert.True(loaded.HostToNested.Count > 50); + } + + // A parameter of the loaded family has a host id and an id in its own document: the nominal radius of the DIN 2633 flange. + [SkippableFact] + public void TheIdsOfTheHostArePairedWithTheIdsOfTheLoadedDocument() + { + var loaded = Assert.Single(LoadedFamilies(), family => family.HostFamilyId == 10164755); + + Assert.Equal(10000091, loaded.HostToNested[10164385]); + } + + // The host's own family and a family that names no document are not loaded families. + [SkippableFact] + public void TheHostItselfIsNotALoadedFamily() + { + string path = TestFiles.FindRelative("families/aquafix-valve.rfa"); + long own = RvtDocument.Open(path, new RvtReaderOptions { R22Layout = true }).FamilyOwnerId!.Value; + + Assert.DoesNotContain(LoadedFamilies(), family => family.HostFamilyId == own); + } +} diff --git a/tests/RvtIO.Tests/Families/NestedInstanceRecordTests.cs b/tests/RvtIO.Tests/Families/NestedInstanceRecordTests.cs new file mode 100644 index 00000000..7c071ce8 --- /dev/null +++ b/tests/RvtIO.Tests/Families/NestedInstanceRecordTests.cs @@ -0,0 +1,100 @@ +using RvtIO.Families; +using Xunit; + +namespace RvtIO.Tests.Families; + +/// A family loaded into a family and placed in it is a record of the host that names its symbol, its place and its +/// stand (a transform), and a record of the symbol that names the family it is of, the host parameters its parameters follow and +/// its reference planes by tag. The four flanges of the valve are read from those. +public class NestedInstanceRecordTests +{ + private const double Millimetre = 1 / 304.8; + + private static FamilyRecords Records() => + RvtDocument.Open(TestFiles.FindRelative("families/aquafix-valve.rfa"), new RvtReaderOptions { R22Layout = true }) + .RawData.Family!.Records!; + + // «Ду=80» is the type the valve was saved at: its flanges stand at x = ±90 mm. + [SkippableFact] + public void TheFourFlangesOfTheValveAreReadWithTheirSymbolsAndTheirStand() + { + var instances = Records().Instances!; + + Assert.Equal([10164284, 10164292, 10164298, 10164299], instances.Select(item => item.Id).Where(id => id != 10164406).Order()); + var din = instances.Single(item => item.Id == 10164284); + Assert.Equal(10164390, din.MasterSymbolId); + Assert.Equal(10164818, din.SymbolId); + AssertNear([90 * Millimetre, 0, 0], din.Origin); + AssertNear([1, 0, 0], din.Basis[0]); + AssertNear([0, 1, 0], din.Basis[1]); + AssertNear([0, 0, 1], din.Basis[2]); + + // The other flange of the pair faces the other way: it is turned half a turn about the vertical axis. + var turned = instances.Single(item => item.Id == 10164292); + AssertNear([-90 * Millimetre, 0, 0], turned.Origin); + AssertNear([-1, 0, 0], turned.Basis[0]); + AssertNear([0, -1, 0], turned.Basis[1]); + AssertNear([0, 0, 1], turned.Basis[2]); + + var plain = instances.Single(item => item.Id == 10164298); + Assert.Equal(10164382, plain.MasterSymbolId); + Assert.Equal(10164382, plain.SymbolId); + } + + // The two flanges of the first pair stand on a work plane that follows the level; the others stand on nothing. The valve shows + // the four, and the instance that parks a fifth is not shown. + [SkippableFact] + public void AnInstanceNamesTheWorkPlaneItStandsOnAndWhetherItIsShown() + { + var instances = Records().Instances!; + + var din = instances.Single(item => item.Id == 10164284); + Assert.Equal(10164276, din.HostId); + Assert.Equal(new FamilyReference(10163755, -1, -1), din.Host); + AssertNear([0, 0, 1], din.HostNormal!); + var plain = instances.Single(item => item.Id == 10164298); + Assert.Equal(-1, plain.HostId); + Assert.Null(plain.Host); + Assert.Equal([10164284, 10164292, 10164298, 10164299], instances.Where(item => item.Shown).Select(item => item.Id).Order()); + Assert.False(instances.Single(item => item.Id == 10164406).Shown); + } + + // The symbol of a flange of the second pair: the family it is of, the three parameters of that family that follow + // parameters of the valve (D, D2 and r), and its reference planes, the one at the back of the flange (tag 1) at x = 0. + [SkippableFact] + public void TheSymbolOfAFlangeIsReadWithItsFamilyItsAssociationsAndItsPlanes() + { + var symbol = Assert.Single(Records().Symbols!, item => item.Id == 10164382); + + Assert.Equal(10164490, symbol.FamilyId); + Assert.Equal([(10164376L, 10164278L), (10164377L, 10164279L), (10164381L, 10164485L)], + symbol.Associations.Select(a => (a.ElementPropertyId, a.FamilyParameterId)).Order()); + var back = symbol.Planes[1]; + Assert.Equal(0, back.Origin[0], 1e-9); + AssertNear([1, 0, 0], back.Normal); + Assert.Equal(20 * Millimetre, symbol.Planes[2].Origin[0], 1e-9); + } + + // The master symbol of the two flanges of the first pair belongs to no family of the valve (it names none), yet it is read. + [SkippableFact] + public void ASymbolThatBelongsToNoFamilyOfTheValveIsReadToo() + { + var symbol = Assert.Single(Records().Symbols!, item => item.Id == 10164390); + + Assert.Equal(10164755, symbol.FamilyId); + Assert.Equal(1, symbol.Planes[1].Normal[0], 1e-9); + } + + // What is read is no longer reported as content the family cannot compute. + [SkippableFact] + public void TheFlangesAreNoLongerReportedAsUnsupported() + { + Assert.DoesNotContain(Records().UnsupportedContent, entry => entry.StartsWith("FamilyInstance ")); + } + + private static void AssertNear(double[] expected, double[] actual) + { + Assert.Equal(expected.Length, actual.Length); + for (int i = 0; i < expected.Length; i++) Assert.Equal(expected[i], actual[i], 1e-9); + } +} From a8d38217ac53da1eb94564606ec9afc6b880a8f5 Mon Sep 17 00:00:00 2001 From: Mahach <79989386+mahach666@users.noreply.github.com> Date: Wed, 2 Dec 2026 18:22:44 +0300 Subject: [PATCH 07/14] Limit the depth of family formulas and check the counts of size tables A family file could nest formulas deeper than the stack allows, or give a column or argument count that sizes an array before the record is checked. Formulas nested deeper than 200 are refused with the reason, a size table whose count the record cannot hold is not read, and a call with more than 1024 arguments is refused. --- src/RvtIO/Families/FamilyFormulas.cs | 25 +++++++++++-- .../Families/FamilyFormulaTests.cs | 36 +++++++++++++++++++ 2 files changed, 58 insertions(+), 3 deletions(-) diff --git a/src/RvtIO/Families/FamilyFormulas.cs b/src/RvtIO/Families/FamilyFormulas.cs index b229489e..b354fbfe 100644 --- a/src/RvtIO/Families/FamilyFormulas.cs +++ b/src/RvtIO/Families/FamilyFormulas.cs @@ -135,7 +135,9 @@ private static SizeTable[] ReadTables(WideBlockWalker.Walk walk) } rows.Add(row); } - long columnCount = Next(ColumnCount + "#").Integer; + // Every column holds at least its name and two units: a count the rest of the record cannot hold is not read, and no + // array is made from a number the file gives. + int columnCount = Count(Next(ColumnCount + "#").Integer, (items.Length - at) / 3); var columns = new string[columnCount]; var factors = new double[columnCount]; for (int c = 0; c < columnCount; c++) @@ -157,6 +159,14 @@ private static SizeTable[] ReadTables(WideBlockWalker.Walk walk) static RvtWriteRefusedException Bad() => ParameterWriter.Unverified("A size table of the family could not be read exactly."); } + /// A count the file gives, when it is not negative and the record can hold that many items. + internal static int Count(long count, long available) => + count >= 0 && count <= available ? (int)count : throw ParameterWriter.Unverified("A size table of the family could not be read exactly."); + + /// How deep the expressions of a formula may nest, parameters that give a value to one another included: a file + /// made to nest deeper must not be able to use up the stack. + internal const int MaxDepth = 200; + /// Why a formula does not reproduce the value the document stores for its parameter; null when every one does. internal string? CheckStored() { @@ -169,10 +179,11 @@ private static SizeTable[] ReadTables(WideBlockWalker.Walk walk) /// The number of every numeric parameter for the inputs of a type: gives the value of a /// parameter no formula calculates (null: the stored one); the formulas are calculated from them. Or why it cannot be done. - internal (Dictionary? Values, RvtFamilyRefusal? Refusal) Evaluate(Func input) + internal (Dictionary? Values, RvtFamilyRefusal? Refusal) Evaluate(Func input, int maxDepth = MaxDepth) { var memo = new Dictionary(); var active = new HashSet(); + int depth = 0; try { foreach (var row in _rows.Values.Where(row => row.Storage is StorageType.Double or StorageType.Integer or StorageType.ElementId)) @@ -199,6 +210,13 @@ Val Parameter(long id) } Val Visit(int slot) + { + if (++depth > maxDepth) throw Unsupported("formulas nested deeper than " + Text(maxDepth)); + try { return Evaluated(slot); } + finally { depth--; } + } + + Val Evaluated(int slot) { switch (_walker.Class(_walk.Queue[slot])?.Name) { @@ -233,7 +251,8 @@ Val Visit(int slot) Val Call(int slot) { var function = (Function)Field(slot, "FunctionExpression.m_function").Integer; - int count = (int)Field(slot, Arguments + "#").Integer; + long given = Field(slot, Arguments + "#").Integer; + int count = given is >= 0 and <= 1024 ? (int)given : throw Unsupported("number of arguments " + Text(given)); Val Argument(int index) => Visit(Child(slot, Arguments + "@" + index)); if (function == Function.SizeLookup) return Lookup(count, Argument); if (function == Function.Pi && count == 0) return new(RevitPi); diff --git a/tests/RvtIO.Tests/Families/FamilyFormulaTests.cs b/tests/RvtIO.Tests/Families/FamilyFormulaTests.cs index 4941c439..8af475fb 100644 --- a/tests/RvtIO.Tests/Families/FamilyFormulaTests.cs +++ b/tests/RvtIO.Tests/Families/FamilyFormulaTests.cs @@ -79,4 +79,40 @@ public void TheTableHasARowForEveryNominalDiameterOfTheValve() Assert.Equal(["", "DN", "D", "k", "d4", "b", "Massa", "n", "d2", "f"], table.Columns); } } + + // A file made to nest its formulas deeper than the limit must not use up the stack: the type is refused with the reason. + [SkippableFact] + public void FormulasNestedDeeperThanTheLimitAreRefused() + { + var (formulas, root) = Open(Din2633Owner, Din2633Block); + using (root) + { + var (values, refusal) = formulas.Evaluate(id => id == Din2633Radius ? 40 * FeetPerMillimetre : null, maxDepth: 2); + + Assert.Null(values); + Assert.Equal("unsupported-construct", refusal!.Code); + Assert.Contains("nested deeper than 2", refusal.Detail); + } + } + + // The columns of a size table are counted by the file: a count the record cannot hold, or a negative one, is not read, and no + // array is made from it. + [Theory] + [InlineData(-1, 10)] + [InlineData(11, 10)] + [InlineData(long.MaxValue, 5)] + [InlineData(1, 0)] + public void ACountTheRecordCannotHoldIsNotRead(long count, long available) + { + Assert.Throws(() => FamilyFormulas.Count(count, available)); + } + + [Theory] + [InlineData(0, 0)] + [InlineData(3, 10)] + [InlineData(10, 10)] + public void ACountTheRecordCanHoldIsRead(long count, long available) + { + Assert.Equal((int)count, FamilyFormulas.Count(count, available)); + } } From a1bc3a18f87269b11a432195d53a559473d4b0ad Mon Sep 17 00:00:00 2001 From: Mahach <79989386+mahach666@users.noreply.github.com> Date: Wed, 2 Dec 2026 18:51:10 +0300 Subject: [PATCH 08/14] Draw the circles of a family smooth and show the saved type as the others The file stores a circle of a family as a few flat faces (eight for the flanges of the valve, 18 for a revolution), so what was drawn had a tenth less volume than Revit gives. For showing, circles and revolutions are cut into 720 facets (ElementMeshes.SmoothFacets, 1.3e-5 of the volume lost), and the saved type is drawn so too, in place of the coarse meshes of its elements, so the shape does not change when the type does. The faces that are checked against the file keep the facets the file stores, and the members of a combination keep their 18 facets, as Revit draws them. FamilySmoothTests checks the volume of what is drawn in all 14 types of the valve against Revit: body 1e-3, ring and flanges 1e-4. --- CHANGELOG.md | 8 + docs/scene.md | 7 + src/RvtIO.Scene/RvtSceneFamilyTypes.cs | 2 +- src/RvtIO.Scene/RvtSceneReader.cs | 31 ++- src/RvtIO/Families/FamilyContourChecks.cs | 11 +- src/RvtIO/Families/FamilyExtrusionBuilder.cs | 7 +- src/RvtIO/Families/FamilyNested.cs | 7 +- src/RvtIO/Families/FamilyRevolutionBuilder.cs | 16 +- src/RvtIO/Meshes/ElementMeshes.cs | 24 +- .../RvtIO.Tests/Families/FamilySmoothTests.cs | 206 ++++++++++++++++++ 10 files changed, 297 insertions(+), 22 deletions(-) create mode 100644 tests/RvtIO.Tests/Families/FamilySmoothTests.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index 04b16692..a9adaea9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -50,6 +50,14 @@ API between minor releases. instance or a parameter of visibility or material of its own, or an instance whose basis is no rotation, is refused with the reason. A shared parameter that a loaded family uses is read from the first block of the file. A dimension that holds an angle, reference lines that lie apart from the drawn lines of a sketch and an instance tied to a work plane are read as relations. +- The scene of a family file and the computed types of it draw a round form round: a circle of an extrusion or a surface of a + revolution that the file keeps as a few flat faces (eight facets for the circles of the flanges of the valve, 18 for a revolution) + is cut into 720 facets, so the volume of what is drawn is the exact volume to 1.3e-5 (the valve: the body to 1e-3, the ring and + the flanges to 1e-4 of the volumes Revit gives) and not a tenth below it. The saved type is drawn so too, as the other types are, + in place of the coarse meshes of its elements, so that the shape does not change when the type does. The members of a + combination keep their 18 facets, as Revit draws them. The faces that are checked against the file are those it stores, and + `ElementMeshes.ComputeFamilyType(document, index, smooth)` is the overload that gives the finer ones. A scene of a family has + many more vertices than before (the valve: some 25 MB of viewer page for all its types, from 1.8 MB). - A parameter that drives a dimension or a form of a family and is given by a formula no longer makes the family refuse: each type stores the value its parameter has, that value is used as stored, and the formula is not evaluated again. For the saved type the computed faces are still checked against the stored ones. diff --git a/docs/scene.md b/docs/scene.md index b03974b1..f031c5a5 100644 --- a/docs/scene.md +++ b/docs/scene.md @@ -109,6 +109,13 @@ A type that is not the saved one is computed from the relations of the family (` why it has none. A form a type hides has no instances in it. The geometries and materials of the list are those the scene does not hold; their ids follow those of the scene. +What is drawn of a family is smoother than what the file stores: where the file keeps a circle or a round surface as a few flat +faces (eight facets for the circles of the flanges of the valve, 18 for a revolution), the scene and the computed types cut it +into 720 facets (`ElementMeshes.SmoothFacets`), so that the volume drawn differs from the exact one by 1.3e-5, where the file's +own facets leave it about a tenth below. The shape of the saved type is drawn so too, in place of the meshes of its elements, +which are the same shape, checked against the file before it is replaced. The members of a combination keep the 18 facets +Revit itself draws them with. Faces are still checked against the file with the facets the file stores. + A family is computed only when it is made of extrusions whose profiles are straight sides along the axes of the family and arcs whose ends lie on the axes through their centre, a whole number of quarter turns, and whose centre and radius the family fixes (a circle is two such arcs, or one closed arc), and of revolutions of a whole turn whose profile is closed loops of straight lines about a line of the sketch along an axis of diff --git a/src/RvtIO.Scene/RvtSceneFamilyTypes.cs b/src/RvtIO.Scene/RvtSceneFamilyTypes.cs index df76735c..231a6228 100644 --- a/src/RvtIO.Scene/RvtSceneFamilyTypes.cs +++ b/src/RvtIO.Scene/RvtSceneFamilyTypes.cs @@ -18,7 +18,7 @@ public sealed record RvtSceneFamilyType(string Name, IReadOnlyList public IReadOnlyList? Instances { get; init; } - /// Why the type is not computed (; not-computed when + /// Why the type is not computed (; not-computed when /// the meshes the scene was made from leave out one of its elements); null for the saved type and for a computed one. public RvtFamilyRefusal? Refusal { get; init; } } diff --git a/src/RvtIO.Scene/RvtSceneReader.cs b/src/RvtIO.Scene/RvtSceneReader.cs index ff2650a1..7026f7ba 100644 --- a/src/RvtIO.Scene/RvtSceneReader.cs +++ b/src/RvtIO.Scene/RvtSceneReader.cs @@ -175,6 +175,7 @@ private static string RequiredKey(RvtSceneOptions? options) => options?.ModelKey /// The scene of the meshes of ; the element facts come from the document. private static RvtSceneResult Map(RvtDocument document, MeshSet meshes, string modelKey, IEnumerable? diagnostics = null) { + meshes = Smoothed(document, meshes); var scene = new SceneDocument { Title = modelKey }; scene.Models.Add(new SceneModel { @@ -343,6 +344,34 @@ private static RvtSceneResult Map(RvtDocument document, MeshSet meshes, string m }; } + /// The meshes of a family file with the shape of its saved type drawn as the shape of its other types is: the circles + /// cut into facets of a degree (), where the file stores a few. + /// The shape of the saved type is the one the file stores, so the elements that have a shape of their own (meshes, or symbols + /// placed) are given the computed meshes, which the check of the saved type has found to be the same shape; any other element, + /// and every element of a family whose saved type is not computed, is left as it is. + private static MeshSet Smoothed(RvtDocument document, MeshSet meshes) + { + if (document.FamilyTypes is not { } types || types.CurrentIndex < 0 || types.CurrentIndex >= types.Types.Count) return meshes; + if (ElementMeshes.ComputeFamilyType(document, types.CurrentIndex, smooth: true).Elements is not { } computed) return meshes; + var drawn = computed.Where(element => element.Meshes.Count > 0).ToDictionary(element => element.ElementId); + var elements = meshes.Elements.Select(element => + (element.Meshes.Count > 0 || element.Placements.Count > 0) && drawn.TryGetValue(element.ElementId, out var smooth) + ? new ElementMesh + { + ElementId = element.ElementId, Meshes = smooth.Meshes, ComponentIds = element.ComponentIds, + Line = element.Line, Arc = element.Arc, LinePairs = element.LinePairs, IsDatum = element.IsDatum, + Coverage = element.Coverage, UntriangulatedFaces = element.UntriangulatedFaces, + } + : element).ToList(); + // A symbol that no element places any more is not part of the scene. + var placed = elements.SelectMany(element => element.Placements).Select(placement => placement.SymbolId).ToHashSet(); + return new MeshSet + { + Elements = elements, GeometryUndecoded = meshes.GeometryUndecoded, FamilyGaps = meshes.FamilyGaps, + Symbols = meshes.Symbols.Where(symbol => placed.Contains(symbol.Key)).ToDictionary(symbol => symbol.Key, symbol => symbol.Value), + }; + } + /// The types of the family, those computed with instances over the geometries of the scene and over geometries of /// their own; is complete and is not changed. private static RvtSceneFamilyTypes? FamilyTypesOf(RvtDocument document, SceneDocument scene, List report) @@ -365,7 +394,7 @@ private static RvtSceneResult Map(RvtDocument document, MeshSet meshes, string m // Revit keeps a type without a name for a family that has no named types. if (!current && string.IsNullOrWhiteSpace(type.Name)) continue; if (current) saved = listed.Count; - var (instances, refusal) = current ? (null, null) : Computed(ElementMeshes.ComputeFamilyType(document, index)); + var (instances, refusal) = current ? (null, null) : Computed(ElementMeshes.ComputeFamilyType(document, index, smooth: true)); listed.Add(new(type.Name, type.Parameters.Select(parameter => new RvtSceneFamilyValue( parameter.Definition?.Name ?? parameter.Id.ToString(CultureInfo.InvariantCulture), parameter.HasRevitValue ? FamilyText(document, parameter) : null)).ToArray()) diff --git a/src/RvtIO/Families/FamilyContourChecks.cs b/src/RvtIO/Families/FamilyContourChecks.cs index b1413692..22439068 100644 --- a/src/RvtIO/Families/FamilyContourChecks.cs +++ b/src/RvtIO/Families/FamilyContourChecks.cs @@ -28,9 +28,11 @@ internal static class FamilyContourChecks /// The outlines of the loops of in the two axes that follow its own, which are /// right-handed with it: the corners, with the points between them where a segment is an arc, which the file stores as a - /// row of flat faces. Segments[p] is the segment of the loop whose outline edge starts at point p. + /// row of flat faces. Segments[p] is the segment of the loop whose outline edge starts at point p. With + /// above 0 an arc is cut into as many facets as a circle of that many has for it, never fewer than the + /// file cuts it. internal static List<((double U, double V)[] Points, int[] Segments)> Outlines(FamilyExtrusion extrusion, - IReadOnlyList positions) + IReadOnlyList positions, int facetsPerTurn = 0) { int u = (extrusion.Axis + 1) % 3, v = (extrusion.Axis + 2) % 3; static int Component(FamilyVertex vertex, int axis) => axis == 0 ? vertex.X : axis == 1 ? vertex.Y : vertex.Z; @@ -43,10 +45,11 @@ internal static class FamilyContourChecks points.Add((positions[Component(loop[i], u)], positions[Component(loop[i], v)])); segments.Add(i); if (extrusion.Arcs?[l][i] is not { } arc) continue; - for (int facet = 1; facet < arc.Facets; facet++) + int facets = facetsPerTurn > 0 ? Math.Max(arc.Facets, (int)Math.Ceiling(arc.Quarters * facetsPerTurn / 4.0)) : arc.Facets; + for (int facet = 1; facet < facets; facet++) { // The ends lie on the axes through the centre, so the direction of the start is a multiple of a quarter turn. - double angle = Math.PI / 2 * (arc.StartQuarter + (double)arc.Way * arc.Quarters * facet / arc.Facets); + double angle = Math.PI / 2 * (arc.StartQuarter + (double)arc.Way * arc.Quarters * facet / facets); points.Add((positions[arc.CenterU] + positions[arc.Radius] * Math.Cos(angle), positions[arc.CenterV] + positions[arc.Radius] * Math.Sin(angle))); segments.Add(i); diff --git a/src/RvtIO/Families/FamilyExtrusionBuilder.cs b/src/RvtIO/Families/FamilyExtrusionBuilder.cs index e850c4e5..7a2e760c 100644 --- a/src/RvtIO/Families/FamilyExtrusionBuilder.cs +++ b/src/RvtIO/Families/FamilyExtrusionBuilder.cs @@ -8,11 +8,12 @@ internal static class FamilyExtrusionBuilder { /// A side face per segment (per flat piece of an arc) and, for every loop that is not a hole, a face at each end with its holes. A loop /// inside an odd number of others is a hole. Normals point out of the solid; gives the - /// material of each face. + /// material of each face. With above 0 the arcs are cut into facets of a circle of that many + /// (see ): the shape to show, where the facets of the file are the shape to compare. public static List Faces(FamilyExtrusion extrusion, IReadOnlyList positions, - Func material) + Func material, int facetsPerTurn = 0) { - var outlines = FamilyContourChecks.Outlines(extrusion, positions); + var outlines = FamilyContourChecks.Outlines(extrusion, positions, facetsPerTurn); var loops = outlines.Select(outline => outline.Points).ToList(); var inside = FamilyContourChecks.Nesting(loops); var depth = Enumerable.Range(0, loops.Count) diff --git a/src/RvtIO/Families/FamilyNested.cs b/src/RvtIO/Families/FamilyNested.cs index a42e9ea9..767c9be5 100644 --- a/src/RvtIO/Families/FamilyNested.cs +++ b/src/RvtIO/Families/FamilyNested.cs @@ -113,8 +113,9 @@ internal static (NestedSolution? Solution, RvtFamilyRefusal? Refusal) Solve(Nest /// The faces of the loaded family in the frame of the host, for each form and face of its model: the point of /// the loaded family p stands at origin + Σ p[c]·basis[c]. A mirror turns the corners of a face the other - /// way round. - internal static List<(int ElementId, FamilyFaceKey Key, GeoFace Face)> Faces(NestedSolution solution, FamilyPlacement placement) + /// way round. is as in . + internal static List<(int ElementId, FamilyFaceKey Key, GeoFace Face)> Faces(NestedSolution solution, FamilyPlacement placement, + int facetsPerTurn = 0) { var basis = placement.Basis; bool mirrored = Determinant(basis) < 0; @@ -135,7 +136,7 @@ List Ring(IEnumerable corners) { keys.Add(key); return 0; - }); + }, facetsPerTurn); foreach (var (face, key) in built.Zip(keys)) { var outer = Ring(face.OuterVertices!); diff --git a/src/RvtIO/Families/FamilyRevolutionBuilder.cs b/src/RvtIO/Families/FamilyRevolutionBuilder.cs index 79a5c011..b161be7e 100644 --- a/src/RvtIO/Families/FamilyRevolutionBuilder.cs +++ b/src/RvtIO/Families/FamilyRevolutionBuilder.cs @@ -136,14 +136,18 @@ private static List Sides(FamilyRevolution revolution, IReadOnlyListA face for each line of each loop that is not on the axis (the cylinder, ring, disc or cone is one face per /// facet, a ring or a disc one face), in the order of the loops and their lines. Normals point out of the solid; - /// gives the material of each face. - public static List Faces(FamilyRevolution revolution, IReadOnlyList positions, Func material) + /// gives the material of each face. With above 0 a turn is cut into + /// that many facets, never into fewer than : the shape to show, where the facets of the file are the + /// shape to compare. + public static List Faces(FamilyRevolution revolution, IReadOnlyList positions, Func material, + int facetsPerTurn = 0) { int axis = revolution.Axis, normal = revolution.Normal, across = 3 - axis - normal; double centre = positions[revolution.AxisPosition], plane = positions[revolution.PlanePosition]; + int facets = Math.Max(Facets, facetsPerTurn); double[] Point(double d, double v, int facet) { - double angle = 2 * Math.PI * facet / Facets; + double angle = 2 * Math.PI * facet / facets; var point = new double[3]; point[axis] = v; point[across] = centre + d * Math.Cos(angle); @@ -157,7 +161,7 @@ double[] Point(double d, double v, int facet) if (Math.Abs(v2 - v1) <= Tolerance) faces.Add(Flat(Math.Abs(d1), Math.Abs(d2), v1, Math.Sign(d1 + d2) * 1.0, outV, key)); else - for (int facet = 0; facet < Facets; facet++) + for (int facet = 0; facet < facets; facet++) { List ring = [Point(d1, v1, facet), Point(d1, v1, facet + 1), Point(d2, v2, facet + 1), Point(d2, v2, facet)]; // The end on the axis is one point. @@ -171,7 +175,7 @@ double[] Point(double d, double v, int facet) // A facet of a surface, wound to face along the outward direction of the profile turned to the middle of the facet. GeoFace Face(List ring, double outD, double outV, int facet, FamilyFaceKey key) { - double middle = 2 * Math.PI * (facet + 0.5) / Facets; + double middle = 2 * Math.PI * (facet + 0.5) / facets; var outward = new double[3]; outward[axis] = outV; outward[across] = outD * Math.Cos(middle); @@ -186,7 +190,7 @@ GeoFace Flat(double outer, double inner, double v, double side, double outV, Fam side = side < 0 ? -1 : 1; var up = new double[3]; up[axis] = Math.Sign(outV); - List Circle(double radius) => [.. Enumerable.Range(0, Facets).Select(facet => Point(side * radius, v, facet))]; + List Circle(double radius) => [.. Enumerable.Range(0, facets).Select(facet => Point(side * radius, v, facet))]; var face = Wound(Circle(outer), up, key); if (inner > Tolerance) { diff --git a/src/RvtIO/Meshes/ElementMeshes.cs b/src/RvtIO/Meshes/ElementMeshes.cs index 5ad9522f..eca93777 100644 --- a/src/RvtIO/Meshes/ElementMeshes.cs +++ b/src/RvtIO/Meshes/ElementMeshes.cs @@ -211,9 +211,25 @@ private static int MaterialOf(RvtDocument document, GeoFace face) /// forms built from them reproduce what the file stores for the type it was saved at. /// is null. /// The document has no family type of that index. - public static RvtFamilyTypeMeshes ComputeFamilyType(RvtDocument document, int typeIndex) + public static RvtFamilyTypeMeshes ComputeFamilyType(RvtDocument document, int typeIndex) => + ComputeFamilyType(document, typeIndex, false); + + /// The facets a circle is cut into to be shown: the area of the polygon is less than that of the circle by + /// (2 pi / n)^2 / 6, 1.3e-5 for 720 where the facets of the file lose a tenth. The ring of the valve is held to 1e-4 of the volume + /// Revit gives, where the sizes solved from the file already differ by up to 5.2e-5: the facets may lose 4.8e-5 at most, which + /// 370 facets do. + internal const int SmoothFacets = 720; + + /// The shape of a family file in the type , as . + /// With the circles of the forms and of the loaded families are cut into facets of + /// facets, as a viewer shows them, where the file stores them as a few flat faces and the type is + /// compared with those faces. The members of a combination keep the facets of the file: Revit cuts the combination so. + /// is null. + /// The document has no family type of that index. + public static RvtFamilyTypeMeshes ComputeFamilyType(RvtDocument document, int typeIndex, bool smooth) { ArgumentNullException.ThrowIfNull(document); + int facetsPerTurn = smooth ? SmoothFacets : 0; if (document.RawData.Family is not { Types: { } types } family || typeIndex < 0 || typeIndex >= types.Types.Count) throw new ArgumentOutOfRangeException(nameof(typeIndex), typeIndex, "The document has no family type of this index."); var prepared = family.Prepared ??= PrepareFamily(document, family, types); @@ -257,7 +273,7 @@ public static RvtFamilyTypeMeshes ComputeFamilyType(RvtDocument document, int ty var (placed, why) = FamilyNested.Solve(instance.Shape, placement, family.Records!, values, positions); if (placed == null) return new(null, why); var nestedFaces = new List(); - foreach (var (elementId, key, face) in FamilyNested.Faces(placed, placement)) + foreach (var (elementId, key, face) in FamilyNested.Faces(placed, placement, facetsPerTurn)) { if (!instance.Stored.TryGetValue((elementId, key), out var held)) return Refused("degenerate-geometry", id); // The style of a face of the instance is that of the stored face it is computed for. @@ -287,14 +303,14 @@ public static RvtFamilyTypeMeshes ComputeFamilyType(RvtDocument document, int ty { keys.Add(key); return material(extrusion, key); - }) + }, combination == null ? facetsPerTurn : 0) : FamilyRevolutionBuilder.Faces(turned[part], positions, key => { keys.Add(key); return turned[part].MaterialParameterId is long finish ? values.TryGetValue(finish, out double chosen) ? (int)chosen : 0 // No material is stored as nothing or as an id that is not one. : prepared.Faces!.TryGetValue((part, key), out var held) ? Math.Max(held.RenderStyleId ?? 0, 0) : 0; - }); + }, combination == null ? facetsPerTurn : 0); foreach (var (face, key) in own.Zip(keys)) { if (!prepared.Faces!.TryGetValue((part, key), out var stored)) return Refused("degenerate-geometry", part); diff --git a/tests/RvtIO.Tests/Families/FamilySmoothTests.cs b/tests/RvtIO.Tests/Families/FamilySmoothTests.cs new file mode 100644 index 00000000..92d751ad --- /dev/null +++ b/tests/RvtIO.Tests/Families/FamilySmoothTests.cs @@ -0,0 +1,206 @@ +using RvtIO.Families; +using RvtIO.Meshes; +using RvtIO.Scene; +using Xunit; + +namespace RvtIO.Tests.Families; + +/// The file stores a circle of a family as a few flat faces (eight for the circles of the flanges of the valve), Revit shows it +/// smooth. For showing, the circles are cut into 720 facets: the volume of the solid drawn is that of the exact solid to 1.3e-5. +public class FamilySmoothTests +{ + private const double Millimetre = 1 / 304.8; + + // The ring of the flange of the valve in miniature: two circles, the hole drawn the other way round, an outer radius 2, an inner + // radius 1 and a length 1. Each circle is two halves of six facets. + private static (FamilyExtrusion Ring, double[] Positions) Ring() + { + // 0, 1 centre; 2, 3 outer and inner radius; 4, 5 ends of the extrusion; 6..9 the corners at +-2 and +-1 on the axis of U. + double[] positions = [0, 0, 2, 1, 0, 1, 2, -2, 1, -1]; + FamilyVertex Corner(int u) => new(u, 1, 1); + FamilyArcSegment Half(int radius, int way, int quarter) => new(0, 1, radius, way, quarter, 2, 6); + var ring = new FamilyExtrusion(50, [[Corner(6), Corner(7)], [Corner(8), Corner(9)]], 2, 4, 5, + new Dictionary(), null, null, + [[Half(2, 1, 0), Half(2, 1, 2)], [Half(3, -1, 0), Half(3, -1, 2)]]); + return (ring, positions); + } + + private static double Area(List loop) => + Math.Abs(Enumerable.Range(0, loop.Count).Sum(i => loop[i][0] * loop[(i + 1) % loop.Count][1] - loop[(i + 1) % loop.Count][0] * loop[i][1])) / 2; + + [Fact] + public void TheCirclesOfAnExtrusionAreCutIntoTheFacetsAskedFor() + { + var (ring, positions) = Ring(); + + var cap = FamilyExtrusionBuilder.Faces(ring, positions, _ => 0, 720).First(face => face.InnerVertices != null); + + Assert.Equal(720, cap.OuterVertices!.Count); + Assert.Equal(720, Assert.Single(cap.InnerVertices!).Count); + // The length is 1, so the volume is the area between the circles: 3 pi. + Assert.Equal(3 * Math.PI, Area(cap.OuterVertices) - Area(cap.InnerVertices[0]), 3 * Math.PI * 2e-5); + } + + [Fact] + public void TheFacetsOfTheFileAreKeptWhenNoDegreeIsAskedAndNeverCutCoarser() + { + var (ring, positions) = Ring(); + + Assert.Equal(12, FamilyExtrusionBuilder.Faces(ring, positions, _ => 0).First(face => face.InnerVertices != null).OuterVertices!.Count); + // Four facets for a circle would give two for a half, fewer than the six of the file. + Assert.Equal(12, FamilyExtrusionBuilder.Faces(ring, positions, _ => 0, 4).First(face => face.InnerVertices != null).OuterVertices!.Count); + } + + // A cylinder of radius 1 and height 2: a disc at each end and a side of facets. + [Fact] + public void ARevolutionIsCutIntoTheFacetsAskedFor() + { + var (model, refusal) = FamilyModelBuilder.Build(SyntheticRevolution.Cylinder()); + Assert.Null(refusal); + double[] stored = [.. model!.Variables.Select(variable => variable.Stored)]; + + var faces = FamilyRevolutionBuilder.Faces(Assert.Single(model.Revolutions), stored, _ => 0, 720); + + Assert.Equal(1 + 720 + 1, faces.Count); + double volume = 0; + foreach (var face in faces) + { + var ring = face.OuterVertices!; + // A sixth of the vector area of the ring, twice, times a point of it: the part of the volume it bounds with the origin. + double x = 0, y = 0, z = 0; + for (int i = 0; i < ring.Count; i++) + { + var (a, b) = (ring[i], ring[(i + 1) % ring.Count]); + x += (a[1] - b[1]) * (a[2] + b[2]); + y += (a[2] - b[2]) * (a[0] + b[0]); + z += (a[0] - b[0]) * (a[1] + b[1]); + } + volume += (x * ring[0][0] + y * ring[0][1] + z * ring[0][2]) / 6; + } + Assert.Equal(2 * Math.PI, Math.Abs(volume), 2 * Math.PI * 2e-5); + } + + // The volume of what is drawn. The file stores the caps of a circle facing inward, so the triangles of a mesh do not all wind + // the same way: they are turned to one side by walking over the edges that two of them share, and each closed piece counts + // for its own volume. A piece with an open edge is not a solid. + private static double DrawnVolume(ElementMesh element) + { + double total = 0; + foreach (var mesh in element.Meshes) + { + var p = mesh.Positions; + int triangles = mesh.Indices.Length / 3; + long Key(int vertex) => (long)Math.Round(p[vertex * 3] / Millimetre * 100) * 1000003L * 1000003L + + (long)Math.Round(p[vertex * 3 + 1] / Millimetre * 100) * 1000003L + (long)Math.Round(p[vertex * 3 + 2] / Millimetre * 100); + var corner = new long[triangles, 3]; + var edges = new Dictionary<(long, long), List>(); + double Signed(int t, bool flip) + { + int i = mesh.Indices[t * 3] * 3, j = mesh.Indices[t * 3 + 1] * 3, k = mesh.Indices[t * 3 + 2] * 3; + if (flip) (j, k) = (k, j); + return (p[i] * (p[j + 1] * p[k + 2] - p[j + 2] * p[k + 1]) - p[i + 1] * (p[j] * p[k + 2] - p[j + 2] * p[k]) + + p[i + 2] * (p[j] * p[k + 1] - p[j + 1] * p[k])) / 6; + } + for (int t = 0; t < triangles; t++) + for (int c = 0; c < 3; c++) + { + corner[t, c] = Key(mesh.Indices[t * 3 + c]); + long a = corner[t, c], b = Key(mesh.Indices[t * 3 + (c + 1) % 3]); + var edge = a < b ? (a, b) : (b, a); + if (!edges.TryGetValue(edge, out var list)) edges[edge] = list = []; + list.Add(t); + } + var turned = new int[triangles]; + Array.Fill(turned, -1); + for (int start = 0; start < triangles; start++) + { + if (turned[start] != -1) continue; + turned[start] = 0; + var queue = new Queue([start]); + double piece = 0; + while (queue.Count > 0) + { + int t = queue.Dequeue(); + piece += Signed(t, turned[t] == 1); + for (int c = 0; c < 3; c++) + { + long a = corner[t, c], b = corner[t, (c + 1) % 3]; + if (turned[t] == 1) (a, b) = (b, a); + var list = edges[a < b ? (a, b) : (b, a)]; + Assert.True(list.Count >= 2, $"element {element.ElementId} has an open edge"); + if (list.Count > 2) continue; + int other = list[0] == t ? list[1] : list[0]; + int at = Enumerable.Range(0, 3).First(n => corner[other, n] == a && corner[other, (n + 1) % 3] == b + || corner[other, n] == b && corner[other, (n + 1) % 3] == a); + if (turned[other] == -1) + { + // The neighbour must walk the shared edge the other way round. + turned[other] = corner[other, at] == a ? 1 : 0; + queue.Enqueue(other); + } + } + } + total += Math.Abs(piece); + } + } + return total / Math.Pow(Millimetre, 3); + } + + private static readonly Lazy Valve = new(() => + RvtDocument.Open(TestFiles.FindRelative("families/aquafix-valve.rfa"), new RvtReaderOptions { R22Layout = true })); + + // Revit 2022 gave the volume of the body (10164308), the ring (10164267) and a flange of each family (10164284, the DIN flange, + // and 10164298, the plain one) in each of the 14 types, mm3 (the same figures as in AquaFixValveTests and AquaFixFlangeTests). + // What the viewer shows of them, with the circles cut into 720 facets, has those volumes: the ring to 1e-4 and the body to 1e-3, + // as the exact sizes do (measured at most 6.4e-5 for the ring and 7.7e-4 for the body), and the flanges to 1e-4, the tolerance + // chosen here for the flanges at about three times the largest deviation measured, 3.5e-5. + [SkippableTheory] + [InlineData("Ду=100", 2299298.2, 802199, 547940, 544276.3)] + [InlineData("Ду=80", 1777020.7, 624267.7, 478388.4, 474571.6)] + [InlineData("Ду=300", 9040708.9, 3175622.4, 2458238.3, 2703333.7)] + [InlineData("Ду=125", 2713790.1, 1032906.6, 745921.6, 532017.6)] + [InlineData("Ду=250", 7125858.2, 2469174.6, 1927920.6, 1920440.1)] + [InlineData("Ду=600", 36099331.9, 8997908.2, 9064856.9, 11750826.7)] + [InlineData("Ду=150", 3540699.4, 1282462.9, 929166, 924230)] + [InlineData("Ду=50", 1189951.1, 350585.1, 309893.2, 266486.3)] + [InlineData("Ду=450", 19303709.4, 5747482.9, 5193811.5, 5837533.7)] + [InlineData("Ду=200", 4953679.7, 1838121.4, 1321818.9, 1309425.9)] + [InlineData("Ду=500", 25978657.1, 6755673.7, 6538515.8, 8175999.7)] + [InlineData("Ду=65", 1480374.7, 493458, 378525.9, 376264)] + [InlineData("Ду=400", 14533062, 4814761.1, 4130859.8, 4654560.9)] + [InlineData("Ду=350", 12026178.5, 3957855.8, 3238036, 3445836.3)] + public void WhatIsShownOfTheValveHasTheVolumeRevitGivesInEveryType(string type, double body, double ring, double din, double plain) + { + var document = Valve.Value; + int index = document.FamilyTypes!.Types.ToList().FindIndex(candidate => candidate.Name == type); + + var computed = ElementMeshes.ComputeFamilyType(document, index, smooth: true); + + Assert.Null(computed.Refusal); + double VolumeOf(int id) => DrawnVolume(Assert.Single(computed.Elements!, element => element.ElementId == id)); + Assert.Equal(body, VolumeOf(10164308), body * 1e-3); + Assert.Equal(ring, VolumeOf(10164267), ring * 1e-4); + foreach (int id in new[] { 10164284, 10164292 }) Assert.Equal(din, VolumeOf(id), din * 1e-4); + foreach (int id in new[] { 10164298, 10164299 }) Assert.Equal(plain, VolumeOf(id), plain * 1e-4); + } + + // The saved type is the shape the file stores, and is shown as the others are: with the circles cut into 720 facets, so + // that nothing changes in the look of a circle when the type changes. + [SkippableFact] + public void TheSavedTypeOfTheValveIsShownAsSmoothAsTheOtherTypes() + { + var document = Valve.Value; + var result = RvtSceneReader.Read(document, ElementMeshes.Extract(document), new RvtSceneOptions { ModelKey = "valve.rfa" }); + var smooth = ElementMeshes.ComputeFamilyType(document, document.FamilyTypes!.CurrentIndex, smooth: true).Elements!; + + var geometries = result.Document.Geometries.ToDictionary(geometry => geometry.Id); + foreach (int id in new[] { 10164267, 10164308, 10164284, 10164292, 10164298, 10164299 }) + { + int shown = result.Document.Instances.Where(instance => instance.ElementId == id) + .Sum(instance => geometries[instance.GeometryId].Vertices.Count()); + int computed = smooth.Single(element => element.ElementId == id).Meshes.Sum(mesh => mesh.Positions.Length / 3); + Assert.Equal(computed, shown); + Assert.True(shown > 1000, $"{id} shows {shown} vertices"); + } + } +} From 06d28ffcb806044376146607734b5faf0da32dd6 Mon Sep 17 00:00:00 2001 From: Mahach <79989386+mahach666@users.noreply.github.com> Date: Wed, 2 Dec 2026 19:40:19 +0300 Subject: [PATCH 09/14] Check the box of the body and the ring of the valve against Revit in every type The volumes of the body and the ring were held to Revit's in the 14 types, their boxes were not. The viewer shows the circle cut into 720 facets, and its box has the height of the body and the length of the ring as Revit's to 1e-3 mm, and on each axis across it the larger of Revit's two half-widths: Revit's own cut of a circle has no corner on one axis, so its smaller half-width is up to 2.5 % below. --- .../RvtIO.Tests/Families/FamilySmoothTests.cs | 60 +++++++++++++++++++ 1 file changed, 60 insertions(+) diff --git a/tests/RvtIO.Tests/Families/FamilySmoothTests.cs b/tests/RvtIO.Tests/Families/FamilySmoothTests.cs index 92d751ad..84f86912 100644 --- a/tests/RvtIO.Tests/Families/FamilySmoothTests.cs +++ b/tests/RvtIO.Tests/Families/FamilySmoothTests.cs @@ -184,6 +184,66 @@ public void WhatIsShownOfTheValveHasTheVolumeRevitGivesInEveryType(string type, foreach (int id in new[] { 10164298, 10164299 }) Assert.Equal(plain, VolumeOf(id), plain * 1e-4); } + // Revit 2022 gave the box of the body (10164308) and of the ring (10164267) in each of the 14 types, mm: the half-widths of the + // body along x and y and its height, the half-length of the ring and its half-widths along y and z. Revit's box is that of its + // own cut of a circle, which has a corner on one axis and may have none on the other, so its two half-widths differ by up to + // 2.5 % (the body of Ду=50: 57.857 and 56.407). What the viewer shows is the circle cut into 720 facets, with corners on both + // axes: its half-width on each is the larger of Revit's two, so it is never smaller than Revit's and equals it where Revit has + // a corner. The height of the body and the length of the ring are Revit's to 1e-3. + [SkippableTheory] + [InlineData("Ду=100", 69.286, 69.286, 290, 95, 62, 62)] + [InlineData("Ду=80", 66.429, 66.429, 240, 90, 52, 52)] + [InlineData("Ду=300", 92.143, 90.743, 640, 135, 162, 162)] + [InlineData("Ду=125", 72.143, 72.143, 315, 100, 74.5, 74.5)] + [InlineData("Ду=250", 86.429, 85.116, 580, 125, 137, 137)] + [InlineData("Ду=600", 126.429, 126.429, 1300, 195, 312, 312)] + [InlineData("Ду=150", 75, 75, 385, 105, 87, 87)] + [InlineData("Ду=50", 57.857, 56.407, 220, 75, 37, 37)] + [InlineData("Ду=450", 109.286, 109.286, 950, 165, 237, 237)] + [InlineData("Ду=200", 80.714, 80.714, 463, 115, 112, 112)] + [InlineData("Ду=500", 115, 115, 1150, 175, 262, 260.565)] + [InlineData("Ду=65", 63.571, 63.571, 218, 85, 44.5, 44.5)] + [InlineData("Ду=400", 103.571, 101.998, 800, 155, 212, 210.454)] + [InlineData("Ду=350", 97.857, 96.37, 750, 145, 187, 185.637)] + public void TheBoxOfWhatIsShownOfTheBodyAndTheRingIsTheBoxRevitGivesInEveryType(string type, double bodyX, double bodyY, + double bodyTop, double ringHalf, double ringY, double ringZ) + { + var document = Valve.Value; + int index = document.FamilyTypes!.Types.ToList().FindIndex(candidate => candidate.Name == type); + + var computed = ElementMeshes.ComputeFamilyType(document, index, smooth: true); + + Assert.Null(computed.Refusal); + (double[] Min, double[] Max) Box(int id) + { + double[] min = [double.MaxValue, double.MaxValue, double.MaxValue], max = [double.MinValue, double.MinValue, double.MinValue]; + foreach (var mesh in Assert.Single(computed.Elements!, element => element.ElementId == id).Meshes) + for (int i = 0; i < mesh.Positions.Length; i++) + { + double value = mesh.Positions[i] / Millimetre; + min[i % 3] = Math.Min(min[i % 3], value); + max[i % 3] = Math.Max(max[i % 3], value); + } + return (min, max); + } + var (bodyMin, bodyMax) = Box(10164308); + Assert.Equal(0, bodyMin[2], 1e-3); + Assert.Equal(bodyTop, bodyMax[2], 1e-3); + var (ringMin, ringMax) = Box(10164267); + Assert.Equal(-ringHalf, ringMin[0], 1e-3); + Assert.Equal(ringHalf, ringMax[0], 1e-3); + foreach (int axis in new[] { 0, 1 }) + { + Assert.Equal(-Math.Max(bodyX, bodyY), bodyMin[axis], 1e-3); + Assert.Equal(Math.Max(bodyX, bodyY), bodyMax[axis], 1e-3); + } + foreach (int axis in new[] { 1, 2 }) + { + Assert.Equal(-Math.Max(ringY, ringZ), ringMin[axis], 1e-3); + Assert.Equal(Math.Max(ringY, ringZ), ringMax[axis], 1e-3); + } + } + // The saved type is the shape the file stores, and is shown as the others are: with the circles cut into 720 facets, so // that nothing changes in the look of a circle when the type changes. [SkippableFact] From 5e6b60bea4e1048e53bc4f5c850613d0097b3049 Mon Sep 17 00:00:00 2001 From: Mahach <79989386+mahach666@users.noreply.github.com> Date: Wed, 2 Dec 2026 19:46:30 +0300 Subject: [PATCH 10/14] Read Revit's answer for the valve from its own file in one test The figures of Revit's volumes and boxes were copied into the InlineData of three tests. One test now reads families/aquafix-valve.oracle.tsv of the fixture folder and holds the body, the ring and the four flanges of all 14 types to it: the drawn volumes, the ends of the flanges to 1e-3 mm, the half widths as in the tests of the boxes. --- .../RvtIO.Tests/Families/FamilySmoothTests.cs | 91 ++++++++++++++++--- 1 file changed, 79 insertions(+), 12 deletions(-) diff --git a/tests/RvtIO.Tests/Families/FamilySmoothTests.cs b/tests/RvtIO.Tests/Families/FamilySmoothTests.cs index 84f86912..8a518e45 100644 --- a/tests/RvtIO.Tests/Families/FamilySmoothTests.cs +++ b/tests/RvtIO.Tests/Families/FamilySmoothTests.cs @@ -1,3 +1,4 @@ +using System.Globalization; using RvtIO.Families; using RvtIO.Meshes; using RvtIO.Scene; @@ -146,6 +147,20 @@ double Signed(int t, bool flip) return total / Math.Pow(Millimetre, 3); } + // The box of what is shown of an element, in mm. + private static (double[] Min, double[] Max) BoxOf(ElementMesh element) + { + double[] min = [double.MaxValue, double.MaxValue, double.MaxValue], max = [double.MinValue, double.MinValue, double.MinValue]; + foreach (var mesh in element.Meshes) + for (int i = 0; i < mesh.Positions.Length; i++) + { + double value = mesh.Positions[i] / Millimetre; + min[i % 3] = Math.Min(min[i % 3], value); + max[i % 3] = Math.Max(max[i % 3], value); + } + return (min, max); + } + private static readonly Lazy Valve = new(() => RvtDocument.Open(TestFiles.FindRelative("families/aquafix-valve.rfa"), new RvtReaderOptions { R22Layout = true })); @@ -214,18 +229,7 @@ public void TheBoxOfWhatIsShownOfTheBodyAndTheRingIsTheBoxRevitGivesInEveryType( var computed = ElementMeshes.ComputeFamilyType(document, index, smooth: true); Assert.Null(computed.Refusal); - (double[] Min, double[] Max) Box(int id) - { - double[] min = [double.MaxValue, double.MaxValue, double.MaxValue], max = [double.MinValue, double.MinValue, double.MinValue]; - foreach (var mesh in Assert.Single(computed.Elements!, element => element.ElementId == id).Meshes) - for (int i = 0; i < mesh.Positions.Length; i++) - { - double value = mesh.Positions[i] / Millimetre; - min[i % 3] = Math.Min(min[i % 3], value); - max[i % 3] = Math.Max(max[i % 3], value); - } - return (min, max); - } + (double[] Min, double[] Max) Box(int id) => BoxOf(Assert.Single(computed.Elements!, element => element.ElementId == id)); var (bodyMin, bodyMax) = Box(10164308); Assert.Equal(0, bodyMin[2], 1e-3); Assert.Equal(bodyTop, bodyMax[2], 1e-3); @@ -244,6 +248,69 @@ public void TheBoxOfWhatIsShownOfTheBodyAndTheRingIsTheBoxRevitGivesInEveryType( } } + // The same, read from the file Revit's answer was kept in, families/aquafix-valve.oracle.tsv of the fixture folder: for each of the + // 14 types a line "geometry TAB type TAB element id TAB faces TAB volume TAB box" of the body, the ring and the four flanges. The + // volumes drawn are held to 1e-3 for the body and 1e-4 for the ring and the flanges; the boxes as in the two tests above and in + // AquaFixFlangeTests: the ends of a flange to 1e-3 mm, its half-width along y and z not below Revit's and at most 1 % above it. + [SkippableFact] + public void WhatIsShownOfTheValveMatchesTheOracleFileInEveryType() + { + var names = new Dictionary(); + var oracle = new Dictionary<(string Type, int Id), (double Volume, double[] Min, double[] Max)>(); + foreach (string line in File.ReadAllLines(TestFiles.FindRelative("families/aquafix-valve.oracle.tsv"))) + { + string[] cells = line.Split(' '); + if (cells[0] == "type") names[int.Parse(cells[1], CultureInfo.InvariantCulture)] = cells[2]; + else if (cells[0] == "geometry") + { + var fields = cells.Skip(3).Select(cell => cell.Split('=', 2)).ToDictionary(pair => pair[0], pair => pair[1]); + var box = fields["box"].Split(';').Select(corner => corner.Split(',') + .Select(value => double.Parse(value, CultureInfo.InvariantCulture)).ToArray()).ToArray(); + oracle[(names[int.Parse(cells[1], CultureInfo.InvariantCulture)], int.Parse(cells[2], CultureInfo.InvariantCulture))] = + (double.Parse(fields["volume"], CultureInfo.InvariantCulture), box[0], box[1]); + } + } + Assert.Equal(14, names.Count); + + var document = Valve.Value; + var types = document.FamilyTypes!.Types.ToList(); + int compared = 0; + foreach (string type in names.Values) + { + var computed = ElementMeshes.ComputeFamilyType(document, types.FindIndex(candidate => candidate.Name == type), smooth: true); + Assert.Null(computed.Refusal); + foreach (int id in new[] { 10164308, 10164267, 10164284, 10164292, 10164298, 10164299 }) + { + var element = Assert.Single(computed.Elements!, candidate => candidate.ElementId == id); + var (volume, revitMin, revitMax) = oracle[(type, id)]; + var (min, max) = BoxOf(element); + string where = $"{type} {id}"; + double tolerance = id == 10164308 ? 1e-3 : 1e-4; + Assert.True(Math.Abs(DrawnVolume(element) - volume) <= volume * tolerance, $"{where}: volume {DrawnVolume(element)} against Revit's {volume}"); + if (id == 10164308 || id == 10164267) + { + // The body stands on z = 0 and the ring lies along x; across them the shape is the exact circle, as large as the larger + // of Revit's two half-widths. + int along = id == 10164267 ? 0 : 2; + int[] across = id == 10164267 ? [1, 2] : [0, 1]; + Assert.True(Math.Abs(min[along] - revitMin[along]) <= 1e-3 && Math.Abs(max[along] - revitMax[along]) <= 1e-3, $"{where}: length"); + double radius = across.Max(axis => revitMax[axis]); + foreach (int axis in across) + Assert.True(Math.Abs(max[axis] - radius) <= 1e-3 && Math.Abs(min[axis] + radius) <= 1e-3, $"{where}: half-width along {axis}"); + } + else + { + Assert.True(Math.Abs(min[0] - revitMin[0]) <= 1e-3 && Math.Abs(max[0] - revitMax[0]) <= 1e-3, $"{where}: ends"); + foreach (int axis in new[] { 1, 2 }) + Assert.True(max[axis] >= revitMax[axis] - 1e-3 && max[axis] <= revitMax[axis] * 1.01 + && -min[axis] >= -revitMin[axis] - 1e-3 && -min[axis] <= -revitMin[axis] * 1.01, $"{where}: half-width along {axis}"); + } + compared++; + } + } + Assert.Equal(14 * 6, compared); + } + // The saved type is the shape the file stores, and is shown as the others are: with the circles cut into 720 facets, so // that nothing changes in the look of a circle when the type changes. [SkippableFact] From 1abb8219442d2a43ee2d5d524463dee430486504 Mon Sep 17 00:00:00 2001 From: Mahach <79989386+mahach666@users.noreply.github.com> Date: Wed, 2 Dec 2026 23:16:42 +0300 Subject: [PATCH 11/14] Cut the members of a combination as fine as the other forms when drawing a family The combination of the valve (stem, collar and the bar of the handwheel) was drawn with the 18 facets of the file, on the belief that Revit draws it faceted. Revit 2022 gives it as exact cylinders (6) and planes (10); the box 101 x 99.466 it reports is that of its own coarse cut of a circle of 101. The members are now cut into SmoothFacets like the body, so the collar and the cone of the stem meet without a saw-tooth. The match with the saved state still compares the facets of the file. TheCombinationOfTheValveIsShownAsRoundAsTheBodyInEveryType was red (half-width along y 99.466 against 101) and is green in all 14 types; the saved-type test now covers the combination too. --- src/RvtIO/Meshes/ElementMeshes.cs | 7 +-- .../RvtIO.Tests/Families/FamilySmoothTests.cs | 47 ++++++++++++++++--- 2 files changed, 44 insertions(+), 10 deletions(-) diff --git a/src/RvtIO/Meshes/ElementMeshes.cs b/src/RvtIO/Meshes/ElementMeshes.cs index eca93777..d8db9970 100644 --- a/src/RvtIO/Meshes/ElementMeshes.cs +++ b/src/RvtIO/Meshes/ElementMeshes.cs @@ -223,7 +223,8 @@ public static RvtFamilyTypeMeshes ComputeFamilyType(RvtDocument document, int ty /// The shape of a family file in the type , as . /// With the circles of the forms and of the loaded families are cut into facets of /// facets, as a viewer shows them, where the file stores them as a few flat faces and the type is - /// compared with those faces. The members of a combination keep the facets of the file: Revit cuts the combination so. + /// compared with those faces. The members of a combination are cut so too: Revit's combination of the valve is exact cylinders and + /// planes, and its box is that of Revit's own coarse cut of them. /// is null. /// The document has no family type of that index. public static RvtFamilyTypeMeshes ComputeFamilyType(RvtDocument document, int typeIndex, bool smooth) @@ -303,14 +304,14 @@ public static RvtFamilyTypeMeshes ComputeFamilyType(RvtDocument document, int ty { keys.Add(key); return material(extrusion, key); - }, combination == null ? facetsPerTurn : 0) + }, facetsPerTurn) : FamilyRevolutionBuilder.Faces(turned[part], positions, key => { keys.Add(key); return turned[part].MaterialParameterId is long finish ? values.TryGetValue(finish, out double chosen) ? (int)chosen : 0 // No material is stored as nothing or as an id that is not one. : prepared.Faces!.TryGetValue((part, key), out var held) ? Math.Max(held.RenderStyleId ?? 0, 0) : 0; - }, combination == null ? facetsPerTurn : 0); + }, facetsPerTurn); foreach (var (face, key) in own.Zip(keys)) { if (!prepared.Faces!.TryGetValue((part, key), out var stored)) return Refused("degenerate-geometry", part); diff --git a/tests/RvtIO.Tests/Families/FamilySmoothTests.cs b/tests/RvtIO.Tests/Families/FamilySmoothTests.cs index 8a518e45..2f14eed2 100644 --- a/tests/RvtIO.Tests/Families/FamilySmoothTests.cs +++ b/tests/RvtIO.Tests/Families/FamilySmoothTests.cs @@ -248,12 +248,9 @@ public void TheBoxOfWhatIsShownOfTheBodyAndTheRingIsTheBoxRevitGivesInEveryType( } } - // The same, read from the file Revit's answer was kept in, families/aquafix-valve.oracle.tsv of the fixture folder: for each of the - // 14 types a line "geometry TAB type TAB element id TAB faces TAB volume TAB box" of the body, the ring and the four flanges. The - // volumes drawn are held to 1e-3 for the body and 1e-4 for the ring and the flanges; the boxes as in the two tests above and in - // AquaFixFlangeTests: the ends of a flange to 1e-3 mm, its half-width along y and z not below Revit's and at most 1 % above it. - [SkippableFact] - public void WhatIsShownOfTheValveMatchesTheOracleFileInEveryType() + // The file Revit's answer was kept in, families/aquafix-valve.oracle.tsv of the fixture folder: the name of each type by its number, + // and for each type and element the line "geometry TAB type TAB element id TAB faces TAB volume TAB box". + private static (Dictionary Names, Dictionary<(string Type, int Id), (double Volume, double[] Min, double[] Max)> Oracle) ReadOracle() { var names = new Dictionary(); var oracle = new Dictionary<(string Type, int Id), (double Volume, double[] Min, double[] Max)>(); @@ -270,6 +267,17 @@ public void WhatIsShownOfTheValveMatchesTheOracleFileInEveryType() (double.Parse(fields["volume"], CultureInfo.InvariantCulture), box[0], box[1]); } } + return (names, oracle); + } + + // The same, read from the file Revit's answer was kept in, families/aquafix-valve.oracle.tsv of the fixture folder: for each of the + // 14 types a line "geometry TAB type TAB element id TAB faces TAB volume TAB box" of the body, the ring and the four flanges. The + // volumes drawn are held to 1e-3 for the body and 1e-4 for the ring and the flanges; the boxes as in the two tests above and in + // AquaFixFlangeTests: the ends of a flange to 1e-3 mm, its half-width along y and z not below Revit's and at most 1 % above it. + [SkippableFact] + public void WhatIsShownOfTheValveMatchesTheOracleFileInEveryType() + { + var (names, oracle) = ReadOracle(); Assert.Equal(14, names.Count); var document = Valve.Value; @@ -311,6 +319,31 @@ public void WhatIsShownOfTheValveMatchesTheOracleFileInEveryType() Assert.Equal(14 * 6, compared); } + // Revit 2022 gives the faces of the combination of the valve (10164354: the stem, the collar and the bar of the handwheel) as + // exact cylinders and planes, not as facets: its box is that of its own cut of the circle (the half-width of Ду=50 along y is + // 99.466, the 18-gon of 101 along x), as for the body. What is shown of it is the circle cut into 720 facets, as the body is, with + // corners on both axes: the larger of Revit's two half-widths on each, and Revit's height. + [SkippableFact] + public void TheCombinationOfTheValveIsShownAsRoundAsTheBodyInEveryType() + { + var (names, oracle) = ReadOracle(); + var document = Valve.Value; + var types = document.FamilyTypes!.Types.ToList(); + foreach (string type in names.Values) + { + var computed = ElementMeshes.ComputeFamilyType(document, types.FindIndex(candidate => candidate.Name == type), smooth: true); + Assert.Null(computed.Refusal); + var combination = Assert.Single(computed.Elements!, candidate => candidate.ElementId == 10164354); + var (_, revitMin, revitMax) = oracle[(type, 10164354)]; + var (min, max) = BoxOf(combination); + double radius = Math.Max(revitMax[0], revitMax[1]); + Assert.True(Math.Abs(min[2] - revitMin[2]) <= 1e-3 && Math.Abs(max[2] - revitMax[2]) <= 1e-3, $"{type}: height"); + foreach (int axis in new[] { 0, 1 }) + Assert.True(Math.Abs(max[axis] - radius) <= 1e-3 && Math.Abs(min[axis] + radius) <= 1e-3, + $"{type}: half-width along {axis} is {max[axis]}, the circle's is {radius}"); + } + } + // The saved type is the shape the file stores, and is shown as the others are: with the circles cut into 720 facets, so // that nothing changes in the look of a circle when the type changes. [SkippableFact] @@ -321,7 +354,7 @@ public void TheSavedTypeOfTheValveIsShownAsSmoothAsTheOtherTypes() var smooth = ElementMeshes.ComputeFamilyType(document, document.FamilyTypes!.CurrentIndex, smooth: true).Elements!; var geometries = result.Document.Geometries.ToDictionary(geometry => geometry.Id); - foreach (int id in new[] { 10164267, 10164308, 10164284, 10164292, 10164298, 10164299 }) + foreach (int id in new[] { 10164267, 10164308, 10164354, 10164284, 10164292, 10164298, 10164299 }) { int shown = result.Document.Instances.Where(instance => instance.ElementId == id) .Sum(instance => geometries[instance.GeometryId].Vertices.Count()); From d6750c20b0d5f8af32f9b14e5fa9da6426e3362c Mon Sep 17 00:00:00 2001 From: mahach666 <79989386+mahach666@users.noreply.github.com> Date: Thu, 3 Dec 2026 11:19:34 +0300 Subject: [PATCH 12/14] Call the sample valve by a neutral name in the tests and comments The names of sample files are not to be published. The test classes of the sample gate valve are named after what it is, and they read it and Revit's answer for it as families/gate-valve.rfa and families/gate-valve.oracle.tsv of the fixture folder. Nothing but names and comments is changed. --- src/RvtIO/Families/FamilyExtrusionBuilder.cs | 2 +- tests/RvtIO.Tests/Families/FamilyArcTests.cs | 4 ++-- .../Families/FamilyCombinationFaceTests.cs | 2 +- tests/RvtIO.Tests/Families/FamilyFormulaTests.cs | 4 ++-- .../RvtIO.Tests/Families/FamilyReferenceLineTests.cs | 2 +- tests/RvtIO.Tests/Families/FamilySmoothTests.cs | 12 ++++++------ ...AquaFixFlangeTests.cs => GateValveFlangeTests.cs} | 8 ++++---- .../{AquaFixValveTests.cs => GateValveTests.cs} | 12 ++++++------ tests/RvtIO.Tests/Families/NestedFamilyLinkTests.cs | 4 ++-- .../Families/NestedInstanceRecordTests.cs | 2 +- 10 files changed, 26 insertions(+), 26 deletions(-) rename tests/RvtIO.Tests/Families/{AquaFixFlangeTests.cs => GateValveFlangeTests.cs} (96%) rename tests/RvtIO.Tests/Families/{AquaFixValveTests.cs => GateValveTests.cs} (95%) diff --git a/src/RvtIO/Families/FamilyExtrusionBuilder.cs b/src/RvtIO/Families/FamilyExtrusionBuilder.cs index 7a2e760c..ed051b2f 100644 --- a/src/RvtIO/Families/FamilyExtrusionBuilder.cs +++ b/src/RvtIO/Families/FamilyExtrusionBuilder.cs @@ -48,7 +48,7 @@ GeoFace Face(List outer, double[] normal, FamilyFaceKey key) => var holes = Enumerable.Range(0, loops.Count) .Where(hole => inside[loop, hole] && depth[hole] == depth[loop] + 1).ToList(); // The file stores the caps of a loop of arcs alone, a circle, facing inward (every one of the 17 such extrusions of - // the corpus, whichever way the circle is drawn; and the ring of the AquaFix valve, a circle with a circle for its + // the corpus, whichever way the circle is drawn; and the ring of the sample valve, a circle with a circle for its // hole), and the caps of the other loops facing outward. A loop of arcs with a hole of lines, or a loop of arcs and // lines, is not measured: it takes the outward way, and a family whose stored caps differ is refused by the // saved-state check. diff --git a/tests/RvtIO.Tests/Families/FamilyArcTests.cs b/tests/RvtIO.Tests/Families/FamilyArcTests.cs index 7096beb8..5f805917 100644 --- a/tests/RvtIO.Tests/Families/FamilyArcTests.cs +++ b/tests/RvtIO.Tests/Families/FamilyArcTests.cs @@ -91,7 +91,7 @@ public void ADiameterOfAClosedArcSetsTheRadiusOfBothHalves() } // The circle of a hole is drawn the other way round: its halves turn the other way from the closed arc of the sketch, about - // the same centre and radius (the hole of the extrusion of the AquaFix valve is stored so). + // the same centre and radius (the hole of the extrusion of the sample valve is stored so). [Fact] public void ACircleWhoseHalvesTurnTheOtherWayFromTheClosedArcIsTheSameCircle() { @@ -516,7 +516,7 @@ public void ACircleExtrudesToAFacetedCylinder() } } - // A ring of two circles, the hole drawn the other way round (the extrusion of the flange ring of the AquaFix valve): the + // A ring of two circles, the hole drawn the other way round (the extrusion of the flange ring of the sample valve): the // caps of the outer circle face inward, as those of a circle alone, and carry the hole. [Fact] public void ARingOfTwoCirclesHasItsCapsFacingInward() diff --git a/tests/RvtIO.Tests/Families/FamilyCombinationFaceTests.cs b/tests/RvtIO.Tests/Families/FamilyCombinationFaceTests.cs index 1841f4a1..3bfcc5a5 100644 --- a/tests/RvtIO.Tests/Families/FamilyCombinationFaceTests.cs +++ b/tests/RvtIO.Tests/Families/FamilyCombinationFaceTests.cs @@ -62,7 +62,7 @@ public void AFaceThatTheMemberHasNoTagForIsRefused() => [SkippableFact] public void TheFacesOfTheCombinationOfTheValveAreReadFromTheStepsThatAddItsMembers() { - var combination = Assert.Single(RvtDocument.Open(TestFiles.FindRelative("families/aquafix-valve.rfa"), + var combination = Assert.Single(RvtDocument.Open(TestFiles.FindRelative("families/gate-valve.rfa"), new RvtReaderOptions { R22Layout = true }).RawData.Family!.Records!.Combinations!); var faces = combination.Faces!; diff --git a/tests/RvtIO.Tests/Families/FamilyFormulaTests.cs b/tests/RvtIO.Tests/Families/FamilyFormulaTests.cs index 8af475fb..8b0b47b9 100644 --- a/tests/RvtIO.Tests/Families/FamilyFormulaTests.cs +++ b/tests/RvtIO.Tests/Families/FamilyFormulaTests.cs @@ -5,7 +5,7 @@ namespace RvtIO.Tests.Families; /// The formulas and the size tables of a family document are read from its record and calculated: the flange families -/// loaded into the AquaFix valve (the documents of blocks 8 and 10) give their sizes by a table that a nominal diameter picks a +/// loaded into the sample valve (the documents of blocks 8 and 10) give their sizes by a table that a nominal diameter picks a /// row of. public class FamilyFormulaTests { @@ -17,7 +17,7 @@ public class FamilyFormulaTests private static (FamilyFormulas Formulas, RootStorage Root) Open(long owner, int block) { - var root = RootStorage.OpenRead(TestFiles.FindRelative("families/aquafix-valve.rfa")); + var root = RootStorage.OpenRead(TestFiles.FindRelative("families/gate-valve.rfa")); var (formulas, error) = FamilyFormulas.Read(root, owner, null, null, block); return (formulas ?? throw new Xunit.Sdk.XunitException("not read: " + error), root); } diff --git a/tests/RvtIO.Tests/Families/FamilyReferenceLineTests.cs b/tests/RvtIO.Tests/Families/FamilyReferenceLineTests.cs index 1705ec0c..24be108c 100644 --- a/tests/RvtIO.Tests/Families/FamilyReferenceLineTests.cs +++ b/tests/RvtIO.Tests/Families/FamilyReferenceLineTests.cs @@ -136,7 +136,7 @@ public void AnInstanceOnAPlaneThroughALineThatMovesIsRefused() => [SkippableFact] public void TheAngleOfTheValveIsReadFromTheFile() { - var records = RvtDocument.Open(TestFiles.FindRelative("families/aquafix-valve.rfa"), + var records = RvtDocument.Open(TestFiles.FindRelative("families/gate-valve.rfa"), new RvtReaderOptions { R22Layout = true }).RawData.Family!.Records!; var angle = Assert.Single(records.AngularDimensions!); diff --git a/tests/RvtIO.Tests/Families/FamilySmoothTests.cs b/tests/RvtIO.Tests/Families/FamilySmoothTests.cs index 2f14eed2..adbb8020 100644 --- a/tests/RvtIO.Tests/Families/FamilySmoothTests.cs +++ b/tests/RvtIO.Tests/Families/FamilySmoothTests.cs @@ -162,10 +162,10 @@ private static (double[] Min, double[] Max) BoxOf(ElementMesh element) } private static readonly Lazy Valve = new(() => - RvtDocument.Open(TestFiles.FindRelative("families/aquafix-valve.rfa"), new RvtReaderOptions { R22Layout = true })); + RvtDocument.Open(TestFiles.FindRelative("families/gate-valve.rfa"), new RvtReaderOptions { R22Layout = true })); // Revit 2022 gave the volume of the body (10164308), the ring (10164267) and a flange of each family (10164284, the DIN flange, - // and 10164298, the plain one) in each of the 14 types, mm3 (the same figures as in AquaFixValveTests and AquaFixFlangeTests). + // and 10164298, the plain one) in each of the 14 types, mm3 (the same figures as in GateValveTests and GateValveFlangeTests). // What the viewer shows of them, with the circles cut into 720 facets, has those volumes: the ring to 1e-4 and the body to 1e-3, // as the exact sizes do (measured at most 6.4e-5 for the ring and 7.7e-4 for the body), and the flanges to 1e-4, the tolerance // chosen here for the flanges at about three times the largest deviation measured, 3.5e-5. @@ -248,13 +248,13 @@ public void TheBoxOfWhatIsShownOfTheBodyAndTheRingIsTheBoxRevitGivesInEveryType( } } - // The file Revit's answer was kept in, families/aquafix-valve.oracle.tsv of the fixture folder: the name of each type by its number, + // The file Revit's answer was kept in, families/gate-valve.oracle.tsv of the fixture folder: the name of each type by its number, // and for each type and element the line "geometry TAB type TAB element id TAB faces TAB volume TAB box". private static (Dictionary Names, Dictionary<(string Type, int Id), (double Volume, double[] Min, double[] Max)> Oracle) ReadOracle() { var names = new Dictionary(); var oracle = new Dictionary<(string Type, int Id), (double Volume, double[] Min, double[] Max)>(); - foreach (string line in File.ReadAllLines(TestFiles.FindRelative("families/aquafix-valve.oracle.tsv"))) + foreach (string line in File.ReadAllLines(TestFiles.FindRelative("families/gate-valve.oracle.tsv"))) { string[] cells = line.Split(' '); if (cells[0] == "type") names[int.Parse(cells[1], CultureInfo.InvariantCulture)] = cells[2]; @@ -270,10 +270,10 @@ private static (Dictionary Names, Dictionary<(string Type, int Id), return (names, oracle); } - // The same, read from the file Revit's answer was kept in, families/aquafix-valve.oracle.tsv of the fixture folder: for each of the + // The same, read from the file Revit's answer was kept in, families/gate-valve.oracle.tsv of the fixture folder: for each of the // 14 types a line "geometry TAB type TAB element id TAB faces TAB volume TAB box" of the body, the ring and the four flanges. The // volumes drawn are held to 1e-3 for the body and 1e-4 for the ring and the flanges; the boxes as in the two tests above and in - // AquaFixFlangeTests: the ends of a flange to 1e-3 mm, its half-width along y and z not below Revit's and at most 1 % above it. + // GateValveFlangeTests: the ends of a flange to 1e-3 mm, its half-width along y and z not below Revit's and at most 1 % above it. [SkippableFact] public void WhatIsShownOfTheValveMatchesTheOracleFileInEveryType() { diff --git a/tests/RvtIO.Tests/Families/AquaFixFlangeTests.cs b/tests/RvtIO.Tests/Families/GateValveFlangeTests.cs similarity index 96% rename from tests/RvtIO.Tests/Families/AquaFixFlangeTests.cs rename to tests/RvtIO.Tests/Families/GateValveFlangeTests.cs index 6bbff31c..529acbfa 100644 --- a/tests/RvtIO.Tests/Families/AquaFixFlangeTests.cs +++ b/tests/RvtIO.Tests/Families/GateValveFlangeTests.cs @@ -5,12 +5,12 @@ namespace RvtIO.Tests.Families; -/// The four flanges of the valve «Задвижка чугунная клиновая_AquaFix»: two families loaded into it, placed four times. +/// The four flanges of the sample gate valve: two families loaded into it, placed four times. /// Every type of the valve shows them where Revit puts them. -public class AquaFixFlangeTests +public class GateValveFlangeTests { private static readonly Lazy Valve = new(() => - RvtDocument.Open(TestFiles.FindRelative("families/aquafix-valve.rfa"), new RvtReaderOptions { R22Layout = true })); + RvtDocument.Open(TestFiles.FindRelative("families/gate-valve.rfa"), new RvtReaderOptions { R22Layout = true })); private const double Millimetre = 1 / 304.8; @@ -153,7 +153,7 @@ public void TheFlangesHaveTheVolumeRevitGivesInEveryType(string type, double din } private static RvtDocument Fresh() => - RvtDocument.Open(TestFiles.FindRelative("families/aquafix-valve.rfa"), new RvtReaderOptions { R22Layout = true }); + RvtDocument.Open(TestFiles.FindRelative("families/gate-valve.rfa"), new RvtReaderOptions { R22Layout = true }); // The definition of a shared parameter is in the first block of the file, for the family of the file and for every family loaded // into it: a dimension of the DIN flange is labelled by one, which holds 100 mm. diff --git a/tests/RvtIO.Tests/Families/AquaFixValveTests.cs b/tests/RvtIO.Tests/Families/GateValveTests.cs similarity index 95% rename from tests/RvtIO.Tests/Families/AquaFixValveTests.cs rename to tests/RvtIO.Tests/Families/GateValveTests.cs index 40bdea18..15dda9c5 100644 --- a/tests/RvtIO.Tests/Families/AquaFixValveTests.cs +++ b/tests/RvtIO.Tests/Families/GateValveTests.cs @@ -5,12 +5,12 @@ namespace RvtIO.Tests.Families; -/// The real valve of the corpus, «Задвижка чугунная клиновая_AquaFix»: a family of 14 types made of revolutions, a +/// The real gate valve of the corpus: a family of 14 types made of revolutions, a /// ring extrusion, a combination of forms and four nested flanges. What of it is read from the file is pinned here. -public class AquaFixValveTests +public class GateValveTests { private static FamilyRecords Records() => - RvtDocument.Open(TestFiles.FindRelative("families/aquafix-valve.rfa"), new RvtReaderOptions { R22Layout = true }) + RvtDocument.Open(TestFiles.FindRelative("families/gate-valve.rfa"), new RvtReaderOptions { R22Layout = true }) .RawData.Family!.Records!; // The profile of the body: ten straight lines, one of them slanted, about the vertical line the sketch turns about. @@ -62,7 +62,7 @@ public void TheCombinationOfTheStemTheRimAndTheBarIsReadWithItsMembers() private static RvtDocument WithoutFlanges() { - var document = RvtDocument.Open(TestFiles.FindRelative("families/aquafix-valve.rfa"), new RvtReaderOptions { R22Layout = true }); + var document = RvtDocument.Open(TestFiles.FindRelative("families/gate-valve.rfa"), new RvtReaderOptions { R22Layout = true }); var family = document.RawData.Family!; document.RawData.Family = new FamilyData { @@ -186,7 +186,7 @@ public void TheStoredFacesOfTheBodyOfTheValveMatchItsSurfacesWithTheirCornersOnC [SkippableFact] public void TheValveIsComputedInTheTypeTheFileWasSavedAt() { - var document = RvtDocument.Open(TestFiles.FindRelative("families/aquafix-valve.rfa"), new RvtReaderOptions { R22Layout = true }); + var document = RvtDocument.Open(TestFiles.FindRelative("families/gate-valve.rfa"), new RvtReaderOptions { R22Layout = true }); var computed = ElementMeshes.ComputeFamilyType(document, SavedType); @@ -198,7 +198,7 @@ public void TheValveIsComputedInTheTypeTheFileWasSavedAt() [SkippableFact] public void TheValveIsComputedInEveryType() { - var document = RvtDocument.Open(TestFiles.FindRelative("families/aquafix-valve.rfa"), new RvtReaderOptions { R22Layout = true }); + var document = RvtDocument.Open(TestFiles.FindRelative("families/gate-valve.rfa"), new RvtReaderOptions { R22Layout = true }); var types = document.RawData.Family!.Types!.Types; var outcome = Enumerable.Range(0, types.Count).Select(index => diff --git a/tests/RvtIO.Tests/Families/NestedFamilyLinkTests.cs b/tests/RvtIO.Tests/Families/NestedFamilyLinkTests.cs index 1ced3965..8505aa80 100644 --- a/tests/RvtIO.Tests/Families/NestedFamilyLinkTests.cs +++ b/tests/RvtIO.Tests/Families/NestedFamilyLinkTests.cs @@ -10,7 +10,7 @@ public class NestedFamilyLinkTests { private static IReadOnlyList LoadedFamilies() { - string path = TestFiles.FindRelative("families/aquafix-valve.rfa"); + string path = TestFiles.FindRelative("families/gate-valve.rfa"); var document = RvtDocument.Open(path, new RvtReaderOptions { R22Layout = true }); using var root = RootStorage.OpenRead(path); var (families, error) = NestedFamilies.Read(root, null, document.FamilyOwnerId!.Value); @@ -45,7 +45,7 @@ public void TheIdsOfTheHostArePairedWithTheIdsOfTheLoadedDocument() [SkippableFact] public void TheHostItselfIsNotALoadedFamily() { - string path = TestFiles.FindRelative("families/aquafix-valve.rfa"); + string path = TestFiles.FindRelative("families/gate-valve.rfa"); long own = RvtDocument.Open(path, new RvtReaderOptions { R22Layout = true }).FamilyOwnerId!.Value; Assert.DoesNotContain(LoadedFamilies(), family => family.HostFamilyId == own); diff --git a/tests/RvtIO.Tests/Families/NestedInstanceRecordTests.cs b/tests/RvtIO.Tests/Families/NestedInstanceRecordTests.cs index 7c071ce8..a1942a2b 100644 --- a/tests/RvtIO.Tests/Families/NestedInstanceRecordTests.cs +++ b/tests/RvtIO.Tests/Families/NestedInstanceRecordTests.cs @@ -11,7 +11,7 @@ public class NestedInstanceRecordTests private const double Millimetre = 1 / 304.8; private static FamilyRecords Records() => - RvtDocument.Open(TestFiles.FindRelative("families/aquafix-valve.rfa"), new RvtReaderOptions { R22Layout = true }) + RvtDocument.Open(TestFiles.FindRelative("families/gate-valve.rfa"), new RvtReaderOptions { R22Layout = true }) .RawData.Family!.Records!; // «Ду=80» is the type the valve was saved at: its flanges stand at x = ±90 mm. From 9421e929372d0f2830ed9bb34ae9ec03a7c7ac6a Mon Sep 17 00:00:00 2001 From: mahach666 <79989386+mahach666@users.noreply.github.com> Date: Fri, 4 Dec 2026 01:23:20 +0300 Subject: [PATCH 13/14] Compute the family types in the page and cover more families An HTML page of a family held the meshes of every type, so it grew with their number, and a family can have thousands. With RvtSceneOptions.FamilyTypeProgram a scene gives a script and its data instead (FamilyTypeProgram, Resources/family_types.js): the page solves the relations of the type chosen, checks its contours, builds and triangulates its faces, and refuses with the codes of C#. Reading the file, preparing the model and the formulas of loaded families stay in C#, which still computes every type itself; tests run the script under Node and hold the two to each other. The round surfaces of any family are shown round, not only those of computed types. For a family file the parser keeps the exact surface of a curved face, and with ElementMeshOptions.SmoothFamilySurfaces (set by FineCircularEdges of a scene) the corners are put on it and the edges cut to 6 degrees. Projects keep their facets. More families are computed in every type: - free ends and free angles of reference lines, angular dimensions of several segments or between things that only slide, arcs in the profile of a revolution and a radial dimension on a reference circle; - a loaded instance that is not computed is taken from the file in the types that give it what the saved type gives it; - imported drawings are part of a family and move with it. Their triangles lie in the program compressed, so familyTypeProgram returns a promise and the page unpacks them with DecompressionStream; - instances that draw nothing, and dimensions that cannot change anything a type shows, no longer make a family refuse; - a loaded family that has another family loaded into it is read. Also fixed: comparisons, "and", "or" and "not" in family formulas always gave no; a constraint of a sketch could name the wrong curve when curves of the sketch were absorbed or deleted; and the clipping of a geometry to its bounding box, which projects use too, no longer cuts what lies on the box within 1e-9 ft. The new rules are not compared with Revit. --- src/RvtIO.Scene/RvtSceneFamilyTypes.cs | 12 +- src/RvtIO.Scene/RvtSceneOptions.cs | 12 +- src/RvtIO.Scene/RvtSceneReader.cs | 48 +- src/RvtIO/Families/FamilyContent.cs | 12 +- src/RvtIO/Families/FamilyContourChecks.cs | 32 +- src/RvtIO/Families/FamilyData.cs | 28 +- src/RvtIO/Families/FamilyEmptyContent.cs | 213 +++ src/RvtIO/Families/FamilyFormulas.cs | 21 +- src/RvtIO/Families/FamilyModel.cs | 17 +- src/RvtIO/Families/FamilyModelBuilder.cs | 360 ++++- src/RvtIO/Families/FamilyNested.cs | 177 ++- src/RvtIO/Families/FamilyRecordReader.cs | 123 +- src/RvtIO/Families/FamilyRecords.cs | 29 +- src/RvtIO/Families/FamilyRelationReader.cs | 67 +- src/RvtIO/Families/FamilyRevolutionBuilder.cs | 148 +- src/RvtIO/Families/FamilyRules.cs | 26 +- src/RvtIO/Families/FamilySavedState.cs | 8 +- src/RvtIO/Families/FamilySolver.cs | 6 + src/RvtIO/Families/FamilyTypeProgram.cs | 342 ++++ src/RvtIO/Families/NestedFamilies.cs | 33 +- src/RvtIO/Families/RvtFamilyTypes.cs | 6 +- src/RvtIO/Internal/ExactSurface.cs | 131 ++ src/RvtIO/Internal/GRepData.cs | 12 +- src/RvtIO/Internal/ParsingState.cs | 4 + src/RvtIO/Meshes/ElementMeshOptions.cs | 5 + src/RvtIO/Meshes/ElementMeshes.cs | 286 +++- src/RvtIO/Meshes/MeshSet.cs | 4 +- src/RvtIO/Meshes/SurfaceRefinement.cs | 430 ++++++ src/RvtIO/Model/Geometry.cs | 18 + src/RvtIO/Parsing/BlockParser.cs | 4 +- .../Parsing/ElementBuilder.UndrawnFaces.cs | 18 +- src/RvtIO/Parsing/ElementBuilder.cs | 22 +- .../Parsing/GRepParserV2.CylinderPatches.cs | 23 + src/RvtIO/Parsing/GRepParserV2.cs | 20 +- src/RvtIO/Resources/family_types.js | 1371 +++++++++++++++++ src/RvtIO/RvtFileReader.cs | 12 +- src/RvtIO/RvtIO.csproj | 1 + .../ElementBuilderGeometryTests.cs | 27 + tests/RvtIO.Tests/FaceLayoutTests.cs | 1 + .../Families/CarriedInstanceTests.cs | 256 +++ .../Families/FamilyCombinationTests.cs | 14 + .../Families/FamilyContentTests.cs | 28 + .../Families/FamilyEmptyContentTests.cs | 273 ++++ .../RvtIO.Tests/Families/FamilyImportTests.cs | 175 +++ .../Families/FamilyModelBuilderTests.cs | 31 + .../Families/FamilyReferenceLineTests.cs | 297 ++++ .../Families/FamilyRelationReaderTests.cs | 19 + .../Families/FamilyRevolutionTests.cs | 141 ++ .../RvtIO.Tests/Families/FamilySceneTests.cs | 68 + .../Families/FamilyTypeProgramTests.cs | 454 ++++++ .../Families/FineCircularEdgesTests.cs | 14 + .../Families/NestedFamilyLinkTests.cs | 11 + .../Meshes/SurfaceRefinementTests.cs | 398 +++++ .../ParameterFormulaEvaluatorTests.cs | 40 +- 54 files changed, 5992 insertions(+), 336 deletions(-) create mode 100644 src/RvtIO/Families/FamilyEmptyContent.cs create mode 100644 src/RvtIO/Families/FamilyTypeProgram.cs create mode 100644 src/RvtIO/Internal/ExactSurface.cs create mode 100644 src/RvtIO/Meshes/SurfaceRefinement.cs create mode 100644 src/RvtIO/Resources/family_types.js create mode 100644 tests/RvtIO.Tests/Families/CarriedInstanceTests.cs create mode 100644 tests/RvtIO.Tests/Families/FamilyEmptyContentTests.cs create mode 100644 tests/RvtIO.Tests/Families/FamilyImportTests.cs create mode 100644 tests/RvtIO.Tests/Families/FamilyTypeProgramTests.cs create mode 100644 tests/RvtIO.Tests/Meshes/SurfaceRefinementTests.cs diff --git a/src/RvtIO.Scene/RvtSceneFamilyTypes.cs b/src/RvtIO.Scene/RvtSceneFamilyTypes.cs index 231a6228..77b16b88 100644 --- a/src/RvtIO.Scene/RvtSceneFamilyTypes.cs +++ b/src/RvtIO.Scene/RvtSceneFamilyTypes.cs @@ -15,7 +15,8 @@ public sealed record RvtSceneFamilyType(string Name, IReadOnlyListThe instances of a type whose geometry is computed, each over a geometry of the scene or of /// and over elements of the scene; empty when the type shows no form. Null for - /// the saved type, whose instances are those of the scene, and for a type that is not computed. + /// the saved type, whose instances are those of the scene, for a type that is not computed, and for every type that + /// computes. public IReadOnlyList? Instances { get; init; } /// Why the type is not computed (; not-computed when @@ -33,6 +34,13 @@ public sealed record RvtSceneFamilyTypes(int SavedIndex, IReadOnlyList public IReadOnlyList Geometries { get; init; } = []; - /// The materials of the computed types that the scene does not hold. + /// The materials of the computed types that the scene does not hold; with , those a type can + /// have. public IReadOnlyList Materials { get; init; } = []; + + /// The program that computes the types other than the saved one in a page, in place of their instances + /// (); null otherwise, for a family listing the saved type only, and when no + /// type is computed, which every other type then says. It numbers the types as lists them; its corners + /// are metres of the scene and its elements and materials are named by their ids in the scene. + public Meshes.RvtFamilyTypeProgram? Program { get; init; } } diff --git a/src/RvtIO.Scene/RvtSceneOptions.cs b/src/RvtIO.Scene/RvtSceneOptions.cs index ed288a91..d62fde58 100644 --- a/src/RvtIO.Scene/RvtSceneOptions.cs +++ b/src/RvtIO.Scene/RvtSceneOptions.cs @@ -20,8 +20,14 @@ public sealed class RvtSceneOptions public bool IncludeDatumGeometry { get; set; } /// Draws the circular edges of cylinders with the points the file stores, so a circle looks round instead of a polygon - /// of about eight sides. It is of the read; default false, which keeps the - /// scene equal to Revit's low detail level. More faces are built, so a viewer of a single family asks for it and a viewer of a - /// large project leaves it off. + /// of about eight sides. It is of the read, and for a family file it also cuts + /// the curved faces finer on their surfaces (); default false, + /// which keeps the scene equal to Revit's low detail level. More faces are built, so a viewer of a single family asks for it and + /// a viewer of a large project leaves it off. public bool FineCircularEdges { get; set; } + + /// Gives the types of a family file other than its saved one as a program a page computes them with + /// () instead of computing their instances here; default false. A scene does not + /// grow with the number of types then, and the consumer runs JavaScript to show them. + public bool FamilyTypeProgram { get; set; } } diff --git a/src/RvtIO.Scene/RvtSceneReader.cs b/src/RvtIO.Scene/RvtSceneReader.cs index 7026f7ba..a6a2848f 100644 --- a/src/RvtIO.Scene/RvtSceneReader.cs +++ b/src/RvtIO.Scene/RvtSceneReader.cs @@ -55,7 +55,7 @@ public static RvtSceneResult Read(string path, RvtSceneOptions? options = null) if (key.Length == 0) throw new ArgumentException("The model key is empty.", nameof(options)); var readDiagnostics = new RvtReadDiagnostics(); var document = RvtDocument.Open(path, ReaderOptions(readDiagnostics, options)); - return Map(document, ElementMeshes.Extract(document, MeshOptions(options)), key, ReadDiagnostics(readDiagnostics)); + return Map(document, ElementMeshes.Extract(document, MeshOptions(options)), key, options, ReadDiagnostics(readDiagnostics)); } /// Reads a scene and its diagnostics from a readable, seekable RVT stream with the same @@ -77,7 +77,7 @@ public static RvtSceneResult ReadStream(Stream stream, RvtSceneOptions options) string key = RequiredKey(options); var readDiagnostics = new RvtReadDiagnostics(); var document = RvtDocument.OpenStream(stream, ReaderOptions(readDiagnostics, options)); - return Map(document, ElementMeshes.Extract(document, MeshOptions(options)), key, ReadDiagnostics(readDiagnostics)); + return Map(document, ElementMeshes.Extract(document, MeshOptions(options)), key, options, ReadDiagnostics(readDiagnostics)); } internal static RvtReaderOptions ReaderOptions(RvtReadDiagnostics diagnostics, RvtSceneOptions? options) @@ -142,7 +142,7 @@ internal static IEnumerable ReadDiagnostics(RvtReadDiagnostics public static RvtSceneResult Read(RvtDocument document, RvtSceneOptions? options) { ArgumentNullException.ThrowIfNull(document); - return Map(document, ElementMeshes.Extract(document, MeshOptions(options)), RequiredKey(options)); + return Map(document, ElementMeshes.Extract(document, MeshOptions(options)), RequiredKey(options), options); } /// Turns an opened document into a scene with meshes the caller extracted from it, for example with @@ -159,7 +159,7 @@ public static RvtSceneResult Read(RvtDocument document, MeshSet meshes, RvtScene { ArgumentNullException.ThrowIfNull(document); ArgumentNullException.ThrowIfNull(meshes); - return Map(document, meshes, RequiredKey(options)); + return Map(document, meshes, RequiredKey(options), options); } private static ElementMeshOptions? MeshOptions(RvtSceneOptions? options) => @@ -167,13 +167,16 @@ public static RvtSceneResult Read(RvtDocument document, MeshSet meshes, RvtScene { IncludeModelLinesAndReinforcement = options.IncludeModelLinesAndReinforcement, IncludeDatumGeometry = options.IncludeDatumGeometry, + // Who asks for round circles gets the other round faces of a family round too. + SmoothFamilySurfaces = options.FineCircularEdges, }; 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)); /// The scene of the meshes of ; the element facts come from the document. - private static RvtSceneResult Map(RvtDocument document, MeshSet meshes, string modelKey, IEnumerable? diagnostics = null) + private static RvtSceneResult Map(RvtDocument document, MeshSet meshes, string modelKey, RvtSceneOptions? options, + IEnumerable? diagnostics = null) { meshes = Smoothed(document, meshes); var scene = new SceneDocument { Title = modelKey }; @@ -327,7 +330,7 @@ private static RvtSceneResult Map(RvtDocument document, MeshSet meshes, string m 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.")); - var familyTypes = FamilyTypesOf(document, scene, report); + var familyTypes = FamilyTypesOf(document, scene, options?.FamilyTypeProgram == true, report); return new RvtSceneResult { @@ -373,8 +376,10 @@ private static MeshSet Smoothed(RvtDocument document, MeshSet meshes) } /// The types of the family, those computed with instances over the geometries of the scene and over geometries of - /// their own; is complete and is not changed. - private static RvtSceneFamilyTypes? FamilyTypesOf(RvtDocument document, SceneDocument scene, List report) + /// their own, or with with the program that computes them in a page; is + /// complete and is not changed. + private static RvtSceneFamilyTypes? FamilyTypesOf(RvtDocument document, SceneDocument scene, bool inPage, + List report) { if (document.FamilyTypesError is { } error) report.Add(new(SceneSeverity.Warning, "family-types-unreadable", $"The types of the family were not read: {error}")); @@ -387,14 +392,18 @@ private static MeshSet Smoothed(RvtDocument document, MeshSet meshes) // Equal arrays have equal sums of their coordinates: only geometries of one key are compared value by value. var equalCandidates = scene.Geometries.GroupBy(Key).ToDictionary(group => group.Key, group => group.ToList()); int saved = 0; - for (int index = 0; index < types.Types.Count; index++) + // Revit keeps a type without a name for a family that has no named types. + var indexes = Enumerable.Range(0, types.Types.Count) + .Where(index => index == types.CurrentIndex || !string.IsNullOrWhiteSpace(types.Types[index].Name)).ToList(); + var (program, unavailable) = inPage && indexes.Count > 1 ? Programmed() : default; + foreach (int index in indexes) { var type = types.Types[index]; bool current = index == types.CurrentIndex; - // Revit keeps a type without a name for a family that has no named types. - if (!current && string.IsNullOrWhiteSpace(type.Name)) continue; if (current) saved = listed.Count; - var (instances, refusal) = current ? (null, null) : Computed(ElementMeshes.ComputeFamilyType(document, index, smooth: true)); + var (instances, refusal) = current ? (null, null) + : inPage ? (null, unavailable) + : Computed(ElementMeshes.ComputeFamilyType(document, index, smooth: true)); listed.Add(new(type.Name, type.Parameters.Select(parameter => new RvtSceneFamilyValue( parameter.Definition?.Name ?? parameter.Id.ToString(CultureInfo.InvariantCulture), parameter.HasRevitValue ? FamilyText(document, parameter) : null)).ToArray()) @@ -403,7 +412,20 @@ private static MeshSet Smoothed(RvtDocument document, MeshSet meshes) Refusal = refusal, }); } - return new(saved, listed) { Geometries = geometries, Materials = materials }; + return new(saved, listed) { Geometries = geometries, Materials = materials, Program = program }; + + // The program for the listed types, or why they are not computed. + (RvtFamilyTypeProgram?, RvtFamilyRefusal?) Programmed() + { + var built = ElementMeshes.BuildFamilyTypeProgram(document, indexes, MetresPerFoot); + if (built.Refusal is { } refused) return (null, refused); + // The program names the elements of the shape: the scene must hold them all. + foreach (int id in built.ElementIds) + if (!elementIds.Contains(id)) return (null, new("not-computed", $"element {id} is not in the scene")); + foreach (int id in built.MaterialIds) + if (materialIds.Add(id)) materials.Add(Material(document, id)); + return (built, null); + } (IReadOnlyList?, RvtFamilyRefusal?) Computed(RvtFamilyTypeMeshes computed) { diff --git a/src/RvtIO/Families/FamilyContent.cs b/src/RvtIO/Families/FamilyContent.cs index 660e4692..7ed10f74 100644 --- a/src/RvtIO/Families/FamilyContent.cs +++ b/src/RvtIO/Families/FamilyContent.cs @@ -22,13 +22,19 @@ internal static class FamilyContent internal const string VoidGap = "void", VisibilityGap = "visibility", MissingGeometryGap = "missing-geometry", UnknownGeometryGap = "unknown-geometry"; + /// Whether the element is a form no type draws. A member of a combination is drawn as part of it. + internal static bool IsUndrawnForm(in FamilyElementFacts facts) => + facts.IsForm && !facts.CombinationMember && Classify(facts).Kind == FamilyContentKind.Excluded; + /// What the element is for the shape, and why the shape is incomplete because of it (null: it is not). A shown /// element can leave the shape incomplete too. internal static (FamilyContentKind Kind, string? Gap) Classify(in FamilyElementFacts facts) { - if (facts.DrawnInViewsOnly || FamilyRules.IsNeverShown(facts.ClassName)) return (FamilyContentKind.Excluded, null); - // An element that only places forms adds nothing: each of those is classified itself. - if (!facts.IsForm) + if (facts.DrawsNothing || facts.DrawnInViewsOnly || FamilyRules.IsNeverShown(facts.ClassName)) + return (FamilyContentKind.Excluded, null); + // An element that only places forms adds nothing: each of those is classified itself. An imported drawing is geometry of + // its own, shown and hidden as a form is. + if (!facts.IsForm && facts.ClassName != FamilyRules.ImportClass) return facts.HasGeometry && !facts.PlacesOwnFormsOnly ? (FamilyContentKind.Gap, UnknownGeometryGap) : (FamilyContentKind.Excluded, null); // A void is never shown. The faces of the forms it cuts are stored uncut: the combination of both holds the shape. if (facts.Cutting) return (FamilyContentKind.Excluded, null); diff --git a/src/RvtIO/Families/FamilyContourChecks.cs b/src/RvtIO/Families/FamilyContourChecks.cs index 22439068..67d14521 100644 --- a/src/RvtIO/Families/FamilyContourChecks.cs +++ b/src/RvtIO/Families/FamilyContourChecks.cs @@ -5,7 +5,8 @@ namespace RvtIO.Families; /// /// Whether the profiles of solved variable values still describe the forms of the family: every segment keeps a length /// and its direction, segments meet only where consecutive ones of a loop share a corner, every loop stays inside the -/// loops it was inside, an extrusion ends above its start, and a labelled dimension is more than zero. +/// loops it was inside, an extrusion ends above its start, and a labelled dimension is more than zero, or not less +/// where the family itself is saved with none. /// internal static class FamilyContourChecks { @@ -16,7 +17,7 @@ internal static class FamilyContourChecks { foreach (var equation in model.Equations) if (!equation.IsOffset && equation.ParameterId is long parameter && values.TryGetValue(parameter, out double value) - && !(value > Tolerance)) + && !(value > Tolerance || equation.MayBeEmpty && value >= -Tolerance)) return Refused(parameter); var stored = model.Variables.Select(variable => variable.Stored).ToArray(); foreach (var extrusion in model.Extrusions) @@ -26,11 +27,24 @@ internal static class FamilyContourChecks return null; } + /// The points between the ends of an arc, in the order it is run, where it is cut into its facets. With + /// above 0 it is cut into as many as a circle of that many has for it, never fewer. + internal static IEnumerable<(double U, double V)> Between(FamilyArcSegment arc, IReadOnlyList positions, int facetsPerTurn) + { + int facets = facetsPerTurn > 0 ? Math.Max(arc.Facets, (int)Math.Ceiling(arc.Quarters * facetsPerTurn / 4.0)) : arc.Facets; + for (int facet = 1; facet < facets; facet++) + { + // The ends lie on the axes through the centre, so the direction of the start is a multiple of a quarter turn. + double angle = Math.PI / 2 * (arc.StartQuarter + (double)arc.Way * arc.Quarters * facet / facets); + yield return (positions[arc.CenterU] + positions[arc.Radius] * Math.Cos(angle), + positions[arc.CenterV] + positions[arc.Radius] * Math.Sin(angle)); + } + } + /// The outlines of the loops of in the two axes that follow its own, which are /// right-handed with it: the corners, with the points between them where a segment is an arc, which the file stores as a - /// row of flat faces. Segments[p] is the segment of the loop whose outline edge starts at point p. With - /// above 0 an arc is cut into as many facets as a circle of that many has for it, never fewer than the - /// file cuts it. + /// row of flat faces (see ). Segments[p] is the segment of the loop whose outline edge starts at + /// point p. internal static List<((double U, double V)[] Points, int[] Segments)> Outlines(FamilyExtrusion extrusion, IReadOnlyList positions, int facetsPerTurn = 0) { @@ -45,13 +59,9 @@ internal static class FamilyContourChecks points.Add((positions[Component(loop[i], u)], positions[Component(loop[i], v)])); segments.Add(i); if (extrusion.Arcs?[l][i] is not { } arc) continue; - int facets = facetsPerTurn > 0 ? Math.Max(arc.Facets, (int)Math.Ceiling(arc.Quarters * facetsPerTurn / 4.0)) : arc.Facets; - for (int facet = 1; facet < facets; facet++) + foreach (var point in Between(arc, positions, facetsPerTurn)) { - // The ends lie on the axes through the centre, so the direction of the start is a multiple of a quarter turn. - double angle = Math.PI / 2 * (arc.StartQuarter + (double)arc.Way * arc.Quarters * facet / facets); - points.Add((positions[arc.CenterU] + positions[arc.Radius] * Math.Cos(angle), - positions[arc.CenterV] + positions[arc.Radius] * Math.Sin(angle))); + points.Add(point); segments.Add(i); } } diff --git a/src/RvtIO/Families/FamilyData.cs b/src/RvtIO/Families/FamilyData.cs index 18408ffd..d7c1bfaf 100644 --- a/src/RvtIO/Families/FamilyData.cs +++ b/src/RvtIO/Families/FamilyData.cs @@ -9,6 +9,9 @@ internal sealed class FamilyData /// instances and every other own element with geometry. internal required IReadOnlyList Elements { get; init; } + /// Whether the records of the elements were read: when not, may lack some of them. + internal bool ElementRecordsRead { get; init; } + /// The types of the family; null when the type table was not read exactly. internal RvtFamilyTypes? Types { get; init; } @@ -26,6 +29,10 @@ internal sealed class FamilyData /// Why is null for a family with a shown instance. internal string? NestedError { get; init; } + /// The form that stands for the face a family placed on one is hosted by; no instance of the family holds it. + /// Null for another family, or when the record does not name it. + internal int? HostStandIn { get; init; } + /// What computing a type needs, made at the first one that is computed. internal FamilyPreparation? Prepared { get; set; } } @@ -39,14 +46,30 @@ internal sealed record NestedFamilyData(LoadedFamily Link, FamilyData Data, Fami internal sealed record NestedPlacementState(NestedShape Shape, IReadOnlyDictionary<(int ElementId, FamilyFaceKey Face), GeoFace> Stored); +/// One placed instance of a loaded family that is not computed, as the file stores it: its faces at the saved type, +/// the number that type gives it through each parameter it takes (null for none), and why the loaded family is not +/// computed. Cut is false for faces as fine as they are (an imported drawing), which showing the family smooth leaves +/// uncut. +internal sealed record CarriedInstance(IReadOnlyList Faces, IReadOnlyDictionary Inputs, RvtFamilyRefusal Why, + bool Cut = true) +{ + /// Whether a type gives the instance what the saved one does: its shape is then the stored one, moved to where + /// the instance stands. + public bool TakesTheSame(IReadOnlyDictionary values) => + Inputs.All(input => (values.TryGetValue(input.Key, out double given) ? given : (double?)null) == input.Value); +} + /// A model of a family whose saved state it reproduces, with the stored face each of its faces is and the elements /// of the saved type in document order; or why no type of the family is computed. internal sealed record FamilyPreparation(FamilyModel? Model, IReadOnlyDictionary<(int ElementId, FamilyFaceKey Face), GeoFace>? Faces, IReadOnlyList Elements, RvtFamilyRefusal? Refusal) { - /// The placed instances of loaded families, by element of the instance. + /// The placed instances of loaded families that are computed, by element of the instance. public IReadOnlyDictionary? Nested { get; init; } + + /// The placed instances of loaded families that are taken as the file stores them, by element. + public IReadOnlyDictionary? Carried { get; init; } } /// What the file records about one element, for the shape of the family at its saved type in a 3D view at the Fine @@ -67,7 +90,8 @@ internal sealed record FamilyPreparation(FamilyModel? Model, /// All its geometry places other forms of the family, as a model group places its /// members. /// The forms a combination joins, by element key; null for an element that is no combination. +/// An instance without geometry of a loaded family that draws nothing in any type. internal readonly record struct FamilyElementFacts(int ElementId, string ClassName, bool IsForm, bool HasGeometry, bool Cutting, bool? ShownInFine, bool? HiddenBySavedType, bool CombinationMember = false, bool MemberShownAlways = false, bool CutByOwnStep = false, bool DrawnInViewsOnly = false, bool PlacesOwnFormsOnly = false, - IReadOnlyList? Members = null); + IReadOnlyList? Members = null, bool DrawsNothing = false); diff --git a/src/RvtIO/Families/FamilyEmptyContent.cs b/src/RvtIO/Families/FamilyEmptyContent.cs new file mode 100644 index 00000000..05865328 --- /dev/null +++ b/src/RvtIO/Families/FamilyEmptyContent.cs @@ -0,0 +1,213 @@ +using RvtIO.BuiltIns; + +namespace RvtIO.Families; + +/// A family document and the documents of the families loaded into it, by the id of the family in it (null for one +/// that has no document of its own). +internal sealed record FamilyDocumentTree(FamilyData Data, Func Loaded); + +/// Content that draws nothing in any type, such as the parts of an assembly that only schedules list: instances of +/// loaded families with no form of their own, and what only places them. +internal static class FamilyEmptyContent +{ + // Families nest a few levels; a deeper chain is not established. + private const int MaxDepth = 32; + + /// Whether nothing of the family can be drawn in any type: every element of it is no part of its shape, or is an + /// instance without geometry of a family that draws nothing. A void counts as drawn: it can cut what the family is placed + /// in. + internal static bool DrawsNothing(FamilyDocumentTree family) => DrawsNothing(family, 0); + + private static bool DrawsNothing(FamilyDocumentTree family, int depth) => + depth < MaxDepth && family.Data.ElementRecordsRead && family.Data.Elements.All(fact => + !fact.Cutting && (FamilyContent.Classify(fact).Kind == FamilyContentKind.Excluded + || !fact.HasGeometry && InstanceDrawsNothing(family, fact.ElementId, depth))); + + /// Whether the instance of the family is of loaded families that draw nothing, + /// whichever of its types a type of the family gives it. + internal static bool InstanceDrawsNothing(FamilyDocumentTree family, int instanceId, int depth = 0) + { + if (family.Data.Records is not { } records || records.Instances?.FirstOrDefault(i => i.Id == instanceId) is not { } instance) + return false; + var wanted = new HashSet { instance.SymbolId, instance.MasterSymbolId }; + // A parameter that chooses the type of the instance (property -1) can give it any symbol a type of the family holds. + foreach (var association in records.Associations.Where(a => a.ElementId == instanceId && a.ElementPropertyId == -1)) + { + if (family.Data.Types is not { } types) return false; + foreach (var type in types.Types) + { + if (type.Parameters.FirstOrDefault(p => p.Id == association.FamilyParameterId)?.Value is not int chosen) return false; + wanted.Add(chosen); + } + } + var symbols = (records.Symbols ?? []).ToDictionary(symbol => symbol.Id); + // What the instance hands to its family can there choose the type of an instance, one that draws. + bool hands = records.Associations.Any(a => a.ElementId == instanceId + && a.ElementPropertyId is not -1 and not (long)BuiltInParameter.IS_VISIBLE_PARAM) + || wanted.Any(id => symbols.TryGetValue(id, out var symbol) && symbol.Associations.Count > 0); + return wanted.All(id => symbols.TryGetValue(id, out var symbol) && family.Loaded(symbol.FamilyId) is { } loaded + && !(hands && loaded.Data.Records?.Associations.Any(a => a.ElementPropertyId == -1) == true) + && DrawsNothing(loaded, depth + 1)); + } + + /// The records without the dimensions that only concern content no type shows. + internal static FamilyRecords Prune(FamilyRecords records) + { + // Taken from all the dimensions: one of those left out can be what ties a plane to a pinned one. + var standing = Standing(records); + return PruneForms(PruneInstances(records, standing), standing); + } + + /// The planes that stand where they are whatever the parameters are: those that stay + /// (), but for a centre plane or one that defines the origin that dimensions along its + /// normal tie to a level or a pinned plane, which then holds it. + private static HashSet Standing(FamilyRecords records) + { + static bool Holds(FamilyPlaneRecord plane) => plane.ClassName == "Level" || plane.Pinned; + var tied = new Dictionary[] { [], [], [] }; + foreach (var dimension in records.Dimensions.Where(d => !d.OnlyShows)) + if (FamilyModelBuilder.AxisOf(dimension.Axis) is int along) + foreach (var reference in dimension.References.Skip(1)) + tied[along][FamilyModelBuilder.FindGroup(tied[along], reference.ElementId)] = + FamilyModelBuilder.FindGroup(tied[along], dimension.References[0].ElementId); + bool Tied(FamilyPlaneRecord plane) => FamilyModelBuilder.AxisOf(plane.Normal) is int axis && records.Planes.Any(other => + Holds(other) && FamilyModelBuilder.AxisOf(other.Normal) == axis + && FamilyModelBuilder.FindGroup(tied[axis], other.ElementId) == FamilyModelBuilder.FindGroup(tied[axis], plane.ElementId)); + return records.Planes.Where(plane => plane.Stays && (Holds(plane) || !Tied(plane))).Select(plane => plane.ElementId).ToHashSet(); + } + + /// The records without the dimensions of the sketches of a form no type draws, when nothing else reaches into + /// them: each dimension in those sketches, or that names something in them, names nothing outside but planes that stand, + /// and nothing else refers to anything in them. + private static FamilyRecords PruneForms(FamilyRecords records, HashSet standing) + { + if (records.UndrawnForms is not { Count: > 0 } forms) return records; + var users = records.Referrers.Where(r => r.Field == "SketchPlane.m_userId").ToLookup(r => r.RecordId, r => r.TargetId); + var dropped = new HashSet(ReferenceEqualityComparer.Instance); + foreach (int form in forms) + { + // The sketches and paths of the form, what is in them, and the sketch planes only they use. + var own = records.Referrers.Where(r => r.Field == "SketchBase.m_userId" && r.TargetId == form) + .Select(r => r.RecordId).ToHashSet(); + if (own.Count == 0) continue; + for (bool changed = true; changed;) + { + changed = false; + foreach (var r in records.Referrers.Where(r => own.Contains(r.TargetId))) + if (r.Field is "SketchBase.m_userId" or "SketchMembership.GroupMembership.m_groupId" + or "Path3dMembership.GroupMembership.m_groupId" + || r.Field == "SketchPlane.m_userId" && users[r.RecordId].All(own.Contains)) + changed |= own.Add(r.RecordId); + } + var inside = records.Dimensions.Where(d => own.Contains(d.Id) || d.References.Any(r => own.Contains(r.ElementId))).ToList(); + var known = own.Concat(inside.Select(d => d.Id)).Append(form).ToHashSet(); + if (inside.All(d => d.References.All(r => own.Contains(r.ElementId) || standing.Contains(r.ElementId))) + && records.Referrers.All(r => !own.Contains(r.TargetId) || known.Contains(r.RecordId))) + dropped.UnionWith(inside); + } + return dropped.Count == 0 ? records : records with { Dimensions = records.Dimensions.Where(d => !dropped.Contains(d)).ToList() }; + } + + /// The planes that lengths from plane to plane, each labelled or locked, hold to one that stands: each goes where + /// those say, whatever is locked to it. + private static HashSet Held(FamilyRecords records, HashSet standing) + { + var planes = records.Planes.ToDictionary(plane => plane.ElementId); + var parents = new Dictionary[] { [], [], [] }; + foreach (var dimension in records.Dimensions) + if (dimension is { References.Count: 2, SegmentFlags: [var flags], ParameterIds: [var parameter] } + && (parameter != -1 || flags == FamilyRules.LockedSegmentFlag) && !dimension.DrivenSegments.Contains(0) + && FamilyModelBuilder.AxisOf(dimension.Axis) is int along + && dimension.References.All(r => planes.ContainsKey(r.ElementId))) + parents[along][FamilyModelBuilder.FindGroup(parents[along], dimension.References[1].ElementId)] = + FamilyModelBuilder.FindGroup(parents[along], dimension.References[0].ElementId); + return records.Planes.Where(plane => FamilyModelBuilder.AxisOf(plane.Normal) is int axis && standing.Any(other => + FamilyModelBuilder.AxisOf(planes[other].Normal) == axis + && FamilyModelBuilder.FindGroup(parents[axis], other) == FamilyModelBuilder.FindGroup(parents[axis], plane.ElementId))) + .Select(plane => plane.ElementId).ToHashSet(); + } + + /// The records without the dimensions that only place instances no type shows, and the groups of such: those that + /// only show a distance, and the locks along an axis in which what the instances hold together is held only to planes that + /// stand, or to one thing: a plane held from one that stands, or anything while nothing changes the instances. The others + /// stay: what they tie together stays tied, or the family is refused. + private static FamilyRecords PruneInstances(FamilyRecords records, HashSet standing) + { + var instances = (records.Instances ?? []).Where(instance => !instance.Shown).ToList(); + if (instances.Count == 0) return records; + var unseen = instances.Select(instance => instance.Id).ToHashSet(); + var groups = records.Referrers + .Where(r => r is { ClassName: "ElementGroup", Field: "ElementIdIndexPairSet.ElementIdPlusIndex.m_elementId" }) + .GroupBy(r => r.RecordId, r => r.TargetId).ToList(); + for (bool changed = true; changed;) + { + changed = false; + foreach (var group in groups) + if (group.All(unseen.Contains)) changed |= unseen.Add(group.Key); + } + + // What groups, shared parts and dimensions hold together moves together. + var parents = new Dictionary(); + int Part(int id) => FamilyModelBuilder.FindGroup(parents, id); + void Together(IEnumerable ids) + { + int? first = null; + foreach (int id in ids.Where(unseen.Contains)) + if (first is int other) parents[Part(id)] = Part(other); + else first = id; + } + foreach (var group in groups.Where(group => unseen.Contains(group.Key))) Together(group.Append(group.Key)); + foreach (var r in records.Referrers.Where(r => r.Field == FamilyRules.SuperInstanceField)) Together([r.RecordId, r.TargetId]); + foreach (var dimension in records.Dimensions) Together(dimension.References.Select(r => r.ElementId)); + + var planes = records.Planes.ToDictionary(plane => plane.ElementId); + // A plane is one thing whatever a reference names of it. + FamilyReference Target(FamilyReference r) => planes.ContainsKey(r.ElementId) ? new(r.ElementId, 0, 0) : r; + // A work plane that follows nothing stands too. + var still = instances.Where(i => i.HostId > 0 && i.Host == null).Select(i => i.HostId).ToHashSet(); + bool Stays(FamilyReference r) => still.Contains(r.ElementId) || standing.Contains(r.ElementId); + var held = Held(records, standing); + // A parameter that reaches an instance can change it in a type. + var changeable = instances.Where(i => records.Associations.Any(a => a.ElementId == i.Id + && a.ElementPropertyId != (long)BuiltInParameter.IS_VISIBLE_PARAM) + || (records.Symbols ?? []).Any(s => (s.Id == i.SymbolId || s.Id == i.MasterSymbolId) && s.Associations.Count > 0)) + .Select(i => Part(i.Id)).ToHashSet(); + + // Whether the dimension can only ever place the instances. + bool OnlyPlaces(FamilyDimensionRecord dimension) => + dimension.ParameterIds.All(parameter => parameter == -1) + && (dimension.References.All(r => unseen.Contains(r.ElementId)) + || dimension.References.Count == 2 && FamilyRules.IsKnownDimensionFlags(dimension.IsAlignment, dimension.Flags) + && (dimension.IsAlignment || (dimension.Flags & FamilyRules.EqualityDimensionFlag) == 0)); + + var involved = records.Dimensions.Where(d => !d.OnlyShows && d.References.Any(r => unseen.Contains(r.ElementId))).ToList(); + IEnumerable<(int Part, int Axis)> Along(FamilyDimensionRecord dimension) => + dimension.References.Where(r => unseen.Contains(r.ElementId)) + .Select(r => (Part(r.ElementId), FamilyModelBuilder.AxisOf(dimension.Axis) ?? -1)); + var targets = new Dictionary<(int Part, int Axis), HashSet>(); + HashSet TargetsOf((int, int) key) => + targets.TryGetValue(key, out var held) ? held : targets[key] = []; + var tied = new HashSet<(int Part, int Axis)>(); + foreach (var dimension in involved) + foreach (var key in Along(dimension)) + { + if (!OnlyPlaces(dimension)) tied.Add(key); + TargetsOf(key).UnionWith(dimension.References.Where(r => !unseen.Contains(r.ElementId)).Select(Target)); + } + // A work plane holds what stands on it, along its normal, to what it follows. + foreach (var instance in instances.Where(i => i.HostId > 0)) + if (instance.HostNormal is { } normal && FamilyModelBuilder.AxisOf(normal) is int axis) + TargetsOf((Part(instance.Id), axis)).Add(Target(instance.Host ?? new(instance.HostId, 0, 0))); + + bool Free((int Part, int Axis) key) => !tied.Contains(key) + && (TargetsOf(key).All(Stays) || TargetsOf(key).Count == 1 + && (!changeable.Contains(key.Part) || TargetsOf(key).All(target => held.Contains(target.ElementId)))); + var dropped = new HashSet(involved.Where(d => OnlyPlaces(d) + && FamilyModelBuilder.AxisOf(d.Axis) != null && Along(d).All(Free)), ReferenceEqualityComparer.Instance); + return records with + { + Dimensions = records.Dimensions.Where(d => !dropped.Contains(d) + && !(d.OnlyShows && d.References.Any(r => unseen.Contains(r.ElementId)))).ToList(), + }; + } +} diff --git a/src/RvtIO/Families/FamilyFormulas.cs b/src/RvtIO/Families/FamilyFormulas.cs index b354fbfe..cfe82654 100644 --- a/src/RvtIO/Families/FamilyFormulas.cs +++ b/src/RvtIO/Families/FamilyFormulas.cs @@ -31,9 +31,9 @@ private enum Function : long /// matched against the columns after it. internal sealed record SizeTable(string Name, IReadOnlyList Columns, IReadOnlyList> Rows); - private sealed record Row(long Id, StorageType Storage, int? Formula, bool Reporting, Val Stored); + internal sealed record Row(long Id, StorageType Storage, int? Formula, bool Reporting, Val Stored); - private readonly record struct Val(double Number = 0, string? Text = null, bool Boolean = false); + internal readonly record struct Val(double Number = 0, string? Text = null); private sealed class Refused(string code, string detail) : Exception { @@ -44,7 +44,7 @@ private sealed class Refused(string code, string detail) : Exception private readonly WideBlockWalker.Walk _walk; private readonly Dictionary _rows; - private FamilyFormulas(WideBlockWalker walker, WideBlockWalker.Walk walk, Dictionary rows, SizeTable[] tables) + internal FamilyFormulas(WideBlockWalker walker, WideBlockWalker.Walk walk, Dictionary rows, SizeTable[] tables) { (_walker, _walk, _rows, Tables) = (walker, walk, rows, tables); } @@ -238,9 +238,9 @@ Val Evaluated(int slot) 3 => new(left * right), 4 when Math.Abs(right) > Tolerance => new(left / right), 5 when Math.Pow(left, right) is double power && double.IsFinite(power) => new(power), - 6 => new(Boolean: Compare(left, right) == 0), - 7 => new(Boolean: Compare(left, right) > 0), - 8 => new(Boolean: Compare(left, right) < 0), + 6 => Truth(Compare(left, right) == 0), + 7 => Truth(Compare(left, right) > 0), + 8 => Truth(Compare(left, right) < 0), _ => throw Unsupported("binary operator " + Text(operation)), }; case "FunctionExpression": return Call(slot); @@ -259,9 +259,9 @@ Val Call(int slot) switch (function, count) { case (Function.If, 3): return Argument(Flag(Argument(0)) ? 1 : 2); - case (Function.And, 2): return new(Boolean: Flag(Argument(0)) && Flag(Argument(1))); - case (Function.Or, 2): return new(Boolean: Flag(Argument(0)) || Flag(Argument(1))); - case (Function.Not, 1): return new(Boolean: !Flag(Argument(0))); + case (Function.And, 2): return Truth(Flag(Argument(0)) && Flag(Argument(1))); + case (Function.Or, 2): return Truth(Flag(Argument(0)) || Flag(Argument(1))); + case (Function.Not, 1): return Truth(!Flag(Argument(0))); } double x = count == 1 ? Number(Argument(0)) : throw Unsupported("function " + Text((long)function)); return function switch @@ -321,6 +321,9 @@ private static double Number(Val value) => private static bool Flag(Val value) => value.Text == null ? value.Number != 0 : throw Unsupported("a text where a condition is"); + /// A yes or a no, as a yes/no parameter holds it. + private static Val Truth(bool holds) => new(holds ? 1 : 0); + private static bool Close(double a, double b) => Math.Abs(a - b) <= Tolerance * (Math.Abs(a) + Math.Abs(b)); // Two numbers that differ by no more than Revit's tolerance are not told apart the way it does: that is not established. diff --git a/src/RvtIO/Families/FamilyModel.cs b/src/RvtIO/Families/FamilyModel.cs index 670a0ba8..b0305dee 100644 --- a/src/RvtIO/Families/FamilyModel.cs +++ b/src/RvtIO/Families/FamilyModel.cs @@ -10,9 +10,10 @@ namespace RvtIO.Families; /// SourceElementId is the record of the family the relation comes from. A weak relation, from an unlocked dimension, /// holds only what the others leave free. An offset relation places an end of an extrusion from its sketch plane: its /// parameter may be zero or below, where a labelled dimension has to be above zero; so does an angle that its label holds. +/// A segment the family is saved without a length of may have none in a type, but not less. /// internal sealed record FamilyEquation(IReadOnlyList Terms, long? ParameterId, int Sign, double Constant, - int SourceElementId, bool IsWeak = false, bool IsOffset = false); + int SourceElementId, bool IsWeak = false, bool IsOffset = false, bool MayBeEmpty = false); /// The variables of a profile vertex; the component along the axis of its extrusion is not used. internal readonly record struct FamilyVertex(int X, int Y, int Z); @@ -23,7 +24,8 @@ internal enum FamilyFaceKind { StartCap, EndCap, Side } /// /// The segment of a profile loop from its corner to the next one when it is an arc about the point (CenterU, -/// CenterV) of the radius Radius, in the two axes that follow the axis of the extrusion. Its ends lie on the +/// CenterV) of the radius Radius, in the two axes that follow the axis of the extrusion or the normal of the +/// sketch plane of the revolution. Its ends lie on the /// axes through the centre: it starts in the direction StartQuarter (0, 1, 2, 3 for U, V, -U, -V) and turns /// Quarters (1 to 3) quarter turns the way Way says, 1 counter-clockwise seen from the end of the axis and -1 /// clockwise. A face of its side, like the outline of an end, is made of Facets equal turns. @@ -41,14 +43,15 @@ internal sealed record FamilyExtrusion(int ElementId, IReadOnlyList>? Arcs = null); /// -/// A whole turn of closed loops of straight lines about a line along Axis (0, 1 or 2 for X, Y or Z) that lies in the -/// plane of the sketch, whose normal runs along Normal. AxisPosition is the coordinate of the axis along the -/// third axis and PlanePosition that of the plane along Normal, which is the coordinate along it of every -/// corner. Materials is keyed by the line of a loop (, loop, curve). +/// A whole turn of closed loops of straight lines and arcs about a line along Axis (0, 1 or 2 for X, Y or Z) that +/// lies in the plane of the sketch, whose normal runs along Normal. AxisPosition is the coordinate of the axis +/// along the third axis and PlanePosition that of the plane along Normal, which is the coordinate along it of +/// every corner. Materials is keyed by the curve of a loop (, loop, curve). +/// Arcs is as that of an extrusion. /// internal sealed record FamilyRevolution(int ElementId, IReadOnlyList> Loops, int Axis, int Normal, int AxisPosition, int PlanePosition, IReadOnlyDictionary Materials, long? MaterialParameterId, - long? VisibilityParameterId); + long? VisibilityParameterId, IReadOnlyList>? Arcs = null); /// /// A combination of forms: the shape of the family is that of the extrusions and revolutions Members names, which are diff --git a/src/RvtIO/Families/FamilyModelBuilder.cs b/src/RvtIO/Families/FamilyModelBuilder.cs index a3f2bc56..cccaa3f7 100644 --- a/src/RvtIO/Families/FamilyModelBuilder.cs +++ b/src/RvtIO/Families/FamilyModelBuilder.cs @@ -1,3 +1,4 @@ +using System.Diagnostics.CodeAnalysis; using System.Globalization; using RvtIO.BuiltIns; using RvtIO.Parsing; @@ -14,7 +15,7 @@ internal static class FamilyModelBuilder public static (FamilyModel? Model, RvtFamilyRefusal? Refusal) Build(FamilyRecords records) { - try { return (new Builder(records).Build(), null); } + try { return (new Builder(FamilyEmptyContent.Prune(records)).Build(), null); } catch (Refused refused) { return (null, refused.Refusal); } } @@ -44,7 +45,7 @@ private sealed class Refused(string code, string detail) : Exception private static string Text(long number) => number.ToString(CultureInfo.InvariantCulture); /// The axis a direction runs along, or null for a slanted or empty one. - private static int? AxisOf(double[] direction) + internal static int? AxisOf(double[] direction) { double length = Math.Sqrt(direction.Sum(component => component * component)); if (!(length > Tolerance)) return null; @@ -76,7 +77,7 @@ private sealed class Node private sealed record ArcShape(int Way, int Quarters, (int U, int V) StartDirection, (int U, int V) EndDirection); private sealed record Equation(List<(int Node, int Coefficient)> Terms, long? Parameter, int Sign, double Constant, - int Source, bool IsWeak, bool IsOffset = false); + int Source, bool IsWeak, bool IsOffset = false, bool MayBeEmpty = false); private readonly Dictionary _lines = records.Lines.ToDictionary(line => line.Id); private readonly Dictionary _planes = records.Planes.ToDictionary(plane => plane.ElementId); @@ -101,11 +102,21 @@ private sealed record Equation(List<(int Node, int Coefficient)> Terms, long? Pa // Reference lines in sketches of their own that only dimensions to planes that stay put (or to each other) touch. private HashSet _apartSketches = []; private HashSet _apartLines = []; - private readonly Dictionary _angles = - (records.AngularDimensions ?? []).ToDictionary(angle => angle.Id); + private readonly HashSet<(int Line, int End)> _freeEnds = []; + // The centres and radii of the arcs that stay where the file draws them. + private readonly List _keptArcs = []; + private readonly HashSet _freeAngles = []; + // The segments of each angular dimension, each an angle between two things. + private readonly ILookup _angles = + (records.AngularDimensions ?? []).ToLookup(angle => angle.Id); private bool IsProfileArc(int id) => _profileArcs.Contains(id) || _circles.Contains(id); + private IEnumerable Angles => records.AngularDimensions ?? []; + + // Whether the dimension is an angle that is read, and every segment of it is as asked. + private bool EverySegment(int id, Func asked) => _angles[id].Any() && _angles[id].All(asked); + public FamilyModel Build() { if (records.UnsupportedContent.Count > 0) @@ -114,23 +125,25 @@ public FamilyModel Build() var axes = _extrusions.Values.ToDictionary(extrusion => extrusion.Id, CheckProfile); var turns = _revolutions.Values.ToDictionary(revolution => revolution.Id, CheckRevolution); CheckCombinations(); + CheckImports(); _slanted = _revolutions.Values.SelectMany(revolution => revolution.Loops.SelectMany(loop => loop)) .Select(curve => _lines[curve.LineId]).Where(line => Direction(line) == null).Select(line => line.Id).ToHashSet(); - var arcs = _extrusions.Values.SelectMany(e => e.Loops.SelectMany(loop => loop) - .Select(key => _lines[e.ProfileCurves[key].LineId])).Where(line => line.Arc != null).DistinctBy(line => line.Id) - .ToList(); + var arcs = _extrusions.Values.SelectMany(Curves).Concat(_revolutions.Values.SelectMany(Curves)) + .Where(line => line.Arc != null).DistinctBy(line => line.Id).ToList(); _profileArcs = arcs.Select(line => line.Id).ToHashSet(); // What the sketch holds of a closed circle (its radius, its centre) holds the halves the profile has of it. _circles = arcs.Select(line => line.CircleId).OfType().ToHashSet(); FindApart(); + FindFreeEnds(); + FindLooseAngles(); HoldAngles(); var dimensions = records.Dimensions .Where(dimension => !dimension.References.Any(reference => _apartLines.Contains(reference.ElementId)) - && !OnControlIcon(dimension)) + && !OnFreeEnd(dimension) && !OnControlIcon(dimension)) .Select(dimension => (Record: dimension, Nodes: Measured(dimension))).ToList(); Join(); - RelateArcs(axes); + RelateArcs(axes, turns); var referencedLines = records.Dimensions.SelectMany(d => d.References).Select(r => r.ElementId) .Where(id => _lines.ContainsKey(id) && !_apartLines.Contains(id)).ToHashSet(); var modelLines = _extrusions.Values @@ -157,6 +170,8 @@ public FamilyModel Build() .Where(node => node >= 0).Concat(caps.Values.SelectMany(pair => new[] { pair.Low, pair.High })) .Concat(placed.Values.SelectMany(p => p.Corners.SelectMany(loop => loop.SelectMany(v => v)).Append(p.Plane).Append(p.AxisPosition))) .Concat(origins.Values.SelectMany(origin => origin))); + // After what holds each group is found: a kept arc is no place that the rest of its family can hang from. + foreach (int node in _keptArcs) _nodes[Root(node)].Anchored = true; return Assemble(axes, caps, vertices, turns, placed, origins); } @@ -198,8 +213,14 @@ private int CheckProfile(FamilyExtrusionRecord extrusion) return axis; } + private IEnumerable Curves(FamilyExtrusionRecord extrusion) => + extrusion.Loops.SelectMany(loop => loop).Select(key => _lines[extrusion.ProfileCurves[key].LineId]); + + private IEnumerable Curves(FamilyRevolutionRecord revolution) => + revolution.Loops.SelectMany(loop => loop).Select(curve => _lines[curve.LineId]); + /// The axis and the normal of the sketch plane of a revolution of a whole turn whose profile is straight lines - /// of some length, about a line along an axis of the plane of the sketch. + /// of some length and quarter-turn arcs, about a line along an axis of the plane of the sketch. private (int Axis, int Normal) CheckRevolution(FamilyRevolutionRecord revolution) { if (AxisOf(revolution.PlaneNormal) is not int normal) throw Unsupported($"sketch plane of {revolution.Id}"); @@ -212,15 +233,19 @@ private int CheckProfile(FamilyExtrusionRecord extrusion) throw Unsupported($"axis of {revolution.Id}"); foreach (var loop in revolution.Loops) { - if (loop.Count < 3) throw Unsupported($"profile of {revolution.Id}"); + bool arcs = loop.Any(curve => _lines.TryGetValue(curve.LineId, out var line) && line.Arc != null); + if (loop.Count < (arcs ? 2 : 3)) throw Unsupported($"profile of {revolution.Id}"); foreach (var curve in loop) { - if (!_lines.TryGetValue(curve.LineId, out var line) || line.SketchId != revolution.SketchId || !line.IsStraight) + if (!_lines.TryGetValue(curve.LineId, out var line) || line.SketchId != revolution.SketchId + || !line.IsStraight && line.Arc == null) throw Unrecognized($"profile curve {curve.LineId} of {revolution.Id}"); if (!(Enumerable.Range(0, 3).Sum(c => Math.Abs(line.End[c] - line.Start[c])) > Tolerance) || !(Math.Abs(line.Start[normal] - revolution.PlaneOrigin[normal]) <= Tolerance && Math.Abs(line.End[normal] - revolution.PlaneOrigin[normal]) <= Tolerance)) throw Unsupported($"curve {line.Id}"); + // Refuses an arc whose ends are not on the axes through its centre. + if (line.Arc != null) Shape(line, normal); } } return (axis, normal); @@ -283,11 +308,7 @@ private bool OnControlIcon(FamilyDimensionRecord dimension) var icon = dimension.References.Where(reference => records.ControlIconIds?.Contains(reference.ElementId) == true) .Select(reference => (FamilyReference?)reference).FirstOrDefault(); if (icon == null) return false; - bool shows = !dimension.IsAlignment && FamilyRules.IsKnownDimensionFlags(false, dimension.Flags) - && (dimension.Flags & FamilyRules.EqualityDimensionFlag) == 0 - && dimension.ParameterIds.All(parameter => parameter == -1) - && dimension.SegmentFlags.All(flags => flags == FamilyRules.UnlockedSegmentFlag); - return shows ? true : throw Unrecognized($"reference of {Text(dimension.Id)} to element {icon.Value.ElementId}"); + return dimension.OnlyShows ? true : throw Unrecognized($"reference of {Text(dimension.Id)} to element {icon.Value.ElementId}"); } private int[] Measured(FamilyDimensionRecord dimension) @@ -357,7 +378,8 @@ private int Resolve(FamilyReference reference, int axis, int source) /// to an axis. private void CheckInstance(FamilyInstanceRecord instance) { - if (!_symbols.ContainsKey(instance.SymbolId)) throw Unrecognized($"symbol of instance {instance.Id}"); + if (!_symbols.ContainsKey(instance.SymbolId) || !_symbols.ContainsKey(instance.MasterSymbolId)) + throw Unrecognized($"symbol of instance {instance.Id}"); var basis = instance.Basis; double Dot(int a, int b) => Enumerable.Range(0, 3).Sum(row => basis[a][row] * basis[b][row]); if (instance.Origin.Length != 3 || basis.Length != 3 || basis.Any(column => column.Length != 3) @@ -541,13 +563,12 @@ private int Radius(FamilySketchLine line) } // Each end of an arc is the centre plus the radius along the direction the end has from it. - private void RelateArcs(Dictionary axes) + private void RelateArcs(Dictionary axes, Dictionary turns) { - foreach (var extrusion in _extrusions.Values) - { - int axis = axes[extrusion.Id]; - foreach (var line in extrusion.Loops.SelectMany(loop => loop).Select(key => _lines[extrusion.ProfileCurves[key].LineId]) - .Where(line => line.Arc != null).DistinctBy(line => line.Id)) + var profiles = _extrusions.Values.Select(e => (Axis: axes[e.Id], Curves: Curves(e), Turned: false)) + .Concat(_revolutions.Values.Select(r => (Axis: turns[r.Id].Normal, Curves: Curves(r), Turned: true))); + foreach (var (axis, curves, turned) in profiles) + foreach (var line in curves.Where(line => line.Arc != null).DistinctBy(line => line.Id)) { var shape = Shape(line, axis); foreach (var (end, direction) in new[] { (0, shape.StartDirection), (1, shape.EndDirection) }) @@ -557,8 +578,11 @@ private void RelateArcs(Dictionary axes) if (along != 0) terms.Add((Radius(line), -along)); _equations.Add(new(terms, null, 1, 0, line.Id, false)); } + // An end the sketch of a revolution holds at no angle leaves the arc wherever the solver of Revit puts it once + // something moves: it stays as the file draws it, and a type that would move it is refused. + if (turned && !HeldEnds(line).All(held => held)) + _keptArcs.AddRange([Centre(line, (axis + 1) % 3), Centre(line, (axis + 2) % 3), Radius(line)]); } - } } // A radius or a diameter holds as a length does, in the unit of its own measure. @@ -632,7 +656,7 @@ private void FindApart() var held = records.Associations.Select(a => a.ElementId).ToHashSet(); // The label of an angle holds it at the angle the file has (HoldAngles), so only the label of a length moves a line. var measured = records.Dimensions.Select(d => (d.References, Moves: d.ParameterIds.Any(parameter => parameter != -1))) - .Concat(_angles.Values.Select(angle => (angle.References, Moves: false))).ToList(); + .Concat(Angles.Select(angle => (angle.References, Moves: false))).ToList(); var sketches = measured.SelectMany(m => m.References).Select(r => r.ElementId) .Where(id => _lines.TryGetValue(id, out var line) && line.SketchId > 0 && !profiles.Contains(line.SketchId)) .Select(id => _lines[id].SketchId).ToHashSet(); @@ -651,37 +675,200 @@ private void FindApart() _apartLines = _lines.Values.Where(line => sketches.Contains(line.SketchId)).Select(line => line.Id).ToHashSet(); } - /// A plane that stays where it is whatever the parameters are: a level, a pinned plane, a plane that defines - /// the origin or one of the centre planes. - private bool Stays(int id) => _planes.TryGetValue(id, out var plane) && plane.Origin.Length > 0 - && (plane.ClassName == "Level" || plane.Pinned || plane.DefinesOrigin || FamilyRules.IsCentreReferenceName(plane.ReferenceName)); + private bool Stays(int id) => _planes.TryGetValue(id, out var plane) && plane.Stays; // What refers to a line apart, or to its sketch: the lines and sketches of the same kind, the plane drawn through the // line, the dimensions skipped for it, and an angle that measures only such lines and planes that stay. private bool IsApartReferrer(FamilyReferrer referrer) => _apartLines.Contains(referrer.RecordId) || _apartSketches.Contains(referrer.RecordId) || referrer.ClassName is "SketchPlane" or "Alignment" or "LinearDimString" - || referrer.ClassName == "AngularDim" && AngleApart(referrer.RecordId); + || referrer.ClassName == "AngularDim" && EverySegment(referrer.RecordId, AngleApart) + || referrer.ClassName == "RadialDim" && Alone(referrer.TargetId); + + // A radius changes the size of what it measures, and what stands on that or is held to it would change with it: only + // a sketch that nothing touches but its own curves, the dimensions among them and the planes that stay, and the sketch + // plane it is drawn on may be resized. + private bool Alone(int target) + { + int sketch = _apartSketches.Contains(target) ? target : _lines[target].SketchId; + var lines = _lines.Values.Where(line => line.SketchId == sketch).Select(line => line.Id).ToHashSet(); + var own = records.Dimensions.Where(d => d.References.All(r => lines.Contains(r.ElementId) || Stays(r.ElementId))) + .Select(d => d.Id) + .Concat((records.RadialDimensions ?? []).Where(r => lines.Contains(r.Arc.ElementId)).Select(r => r.Id)) + .Concat(lines).Append(sketch).ToHashSet(); + return records.Referrers.Where(r => r.TargetId == sketch || lines.Contains(r.TargetId)) + .All(r => own.Contains(r.RecordId) || r.Field == "SketchPlane.m_userId"); + } // An angle that measures a line apart to what stays (the fixed point of FindApart has dropped the sketches of the others). - private bool AngleApart(int id) => _angles.TryGetValue(id, out var angle) - && angle.References.Any(reference => _apartLines.Contains(reference.ElementId)) + private bool AngleApart(FamilyAngularDimension angle) => + angle.References.Any(reference => _apartLines.Contains(reference.ElementId)) && angle.References.All(reference => _apartLines.Contains(reference.ElementId) || Stays(reference.ElementId)); - /// The line apart stays as the file has it, and so does its angle: a label of the angle (a parameter) can only - /// have the angle of the file in a type, any other value turns the line, which the model does not follow. The solver - /// holds the label to the stored angle, and refuses the type that has another. + /// The line apart stays as the file has it, and so does its angle. private void HoldAngles() { - foreach (var angle in _angles.Values.Where(angle => AngleApart(angle.Id))) + foreach (var angle in Angles.Where(angle => AngleApart(angle) && !_freeAngles.Contains(angle))) + HoldAngle(angle); + } + + // A segment of an angle whose flags are known: nothing else of an angle may be dropped. + private static bool IsReadAngle(FamilyAngularDimension angle) => FamilyRules.IsKnownDimensionFlags(false, angle.Flags) + && angle.SegmentFlags is FamilyRules.UnlockedSegmentFlag or FamilyRules.LockedSegmentFlag; + + /// A reference line of a sketch of its own with an end that nothing holds but a length from its other end, + /// turned by a labelled angle to a plane across an axis, and that nothing stands on or is measured to as a whole. The + /// length and the angle place that end and nothing else, whatever a type gives them: they are no relations of the + /// model. + private void FindFreeEnds() + { + var profiles = _extrusions.Values.Select(e => e.SketchId).Concat(_revolutions.Values.Select(r => r.SketchId)).ToHashSet(); + foreach (var line in _lines.Values) + { + int id = line.Id; + var angles = Angles.Where(angle => angle.References.Any(r => r.ElementId == id)).ToList(); + if (!angles.Any(angle => angle.ParameterId != -1 && !angle.Driven) || !line.IsStraight || line.IsRevolutionAxis + || line.SketchId <= 0 || profiles.Contains(line.SketchId) + || records.Constraints.Any(c => c.SketchId == line.SketchId) + || records.Joints.Any(j => j.LineId == id || j.OtherLineId == id) + || records.Associations.Any(a => a.ElementId == id || a.ElementId == line.SketchId) + || !angles.All(angle => IsReadAngle(angle) && angle.References.Count == 2 && angle.References.All(r => + r.ElementId == id ? r is { GeometryTag: 0, SubTag: -1 } + : _planes.TryGetValue(r.ElementId, out var plane) && AxisOf(plane.Normal) != null)) + || records.Referrers.Any(r => r.TargetId == id && r.RecordId != id && r.RecordId != line.SketchId + && r.ClassName is not ("AngularDim" or "LinearDimString" or "Alignment" or "ConnectorElem"))) + continue; + var measured = records.Dimensions.Where(d => d.References.Any(r => r.ElementId == id)).ToList(); + if (measured.Any(d => d.References.Any(r => r.ElementId == id && r is not { GeometryTag: 0, SubTag: 0 or 1 }))) + continue; + var free = new[] { 0, 1 }.Where(end => measured.Where(d => d.References.Contains(new(id, 0, end))) + .All(d => !d.IsAlignment && d.References.All(r => r.ElementId == id))).ToList(); + if (free.Count == 0) continue; + _freeEnds.UnionWith(free.Select(end => (id, end))); + _freeAngles.UnionWith(angles); + } + } + + /// Angles of slanted reference lines to planes that stay, that restrict nothing: one after another, each is met + /// by a coordinate of its line that no dimension holds and no angle still left needs. Nothing but dimensions refers to + /// such lines, so whatever a type gives the rest, they can be drawn at their angles, and move nothing. + private void FindLooseAngles() + { + var profiles = _extrusions.Values.Select(e => e.SketchId).Concat(_revolutions.Values.Select(r => r.SketchId)).ToHashSet(); + var lines = _lines.Values.GroupBy(line => line.SketchId) + .Where(sketch => sketch.Key > 0 && !profiles.Contains(sketch.Key) && StandsAlone(sketch.Key, [.. sketch])) + .SelectMany(sketch => sketch).ToDictionary(line => line.Id); + + // The coordinates of ends that are one: where two lines join, and across a line along an axis. + var parents = new Dictionary<(int Line, int End, int Axis), (int, int, int)>(); + (int, int, int) One((int Line, int End, int Axis) key) + { + while (parents.TryGetValue(key, out var parent)) key = parent; + return key; + } + void Unite((int, int, int) first, (int, int, int) second) + { + if (One(first) != One(second)) parents[One(first)] = One(second); + } + foreach (var joint in records.Joints.Where(j => lines.ContainsKey(j.LineId))) + for (int axis = 0; axis < 3; axis++) + Unite((joint.LineId, joint.End, axis), (joint.OtherLineId, joint.OtherEnd, axis)); + foreach (var line in lines.Values) + if (Direction(line) is int along) + for (int axis = 0; axis < 3; axis++) + if (axis != along) Unite((line.Id, 0, axis), (line.Id, 1, axis)); + + // The angle of a slanted line to a plane that stays, as the file draws the two. + bool Measures(FamilyAngularDimension angle, [NotNullWhen(true)] out FamilySketchLine? slanted) { - if (!FamilyRules.IsKnownDimensionFlags(false, angle.Flags)) - throw Unrecognized($"flags {angle.Flags} of dimension {Text(angle.Id)}"); - if (angle.SegmentFlags is not (FamilyRules.UnlockedSegmentFlag or FamilyRules.LockedSegmentFlag)) - throw Unrecognized($"segments of dimension {Text(angle.Id)}"); - if (angle.ParameterId != -1 && !angle.Driven) - _equations.Add(new([(Add(angle.Value, anchored: true), 1)], angle.ParameterId, 1, 0, angle.Id, false, true)); + slanted = null; + if (!IsReadAngle(angle) || angle.References is not [var first, var second]) return false; + var (reference, other) = lines.ContainsKey(first.ElementId) ? (first, second) : (second, first); + if (reference is not { GeometryTag: 0, SubTag: -1 } || !lines.TryGetValue(reference.ElementId, out var line) + || Direction(line) != null || !Stays(other.ElementId) + || !_planes.TryGetValue(other.ElementId, out var plane) || AxisOf(plane.Normal) is not int normal) return false; + double[] run = [.. Enumerable.Range(0, 3).Select(axis => line.End[axis] - line.Start[axis])]; + double drawn = Math.Asin(Math.Min(1, Math.Abs(run[normal]) / Math.Sqrt(run.Sum(v => v * v)))); + if (!(Math.Abs(Math.Acos(Math.Min(1, Math.Abs(Math.Cos(angle.Value)))) - drawn) <= Tolerance)) return false; + slanted = line; + return true; } + + var held = new HashSet<(int, int, int)>(); + void Hold(int line, IEnumerable ends, IEnumerable axes) + { + foreach (int end in ends) + foreach (int axis in axes) + held.Add(One((line, end, axis))); + } + foreach (var dimension in records.Dimensions) + foreach (var reference in dimension.References.Where(r => lines.ContainsKey(r.ElementId))) + Hold(reference.ElementId, reference is { GeometryTag: 0, SubTag: 0 or 1 } ? [reference.SubTag] : [0, 1], + reference.GeometryTag == 0 && AxisOf(dimension.Axis) is int along ? [along] : [0, 1, 2]); + + var left = new List<(FamilyAngularDimension Angle, List<(int, int, int)> Coordinates)>(); + foreach (var angle in Angles) + if (Measures(angle, out var line)) + left.Add((angle, [.. Enumerable.Range(0, 3) + .Where(axis => Math.Abs(line.End[axis] - line.Start[axis]) > Tolerance) + .SelectMany(axis => new[] { One((line.Id, 0, axis)), One((line.Id, 1, axis)) })])); + // Any other angle of such a line holds it wherever it is. + else + foreach (var reference in angle.References.Where(r => lines.ContainsKey(r.ElementId))) + Hold(reference.ElementId, [0, 1], [0, 1, 2]); + + while (left.FindIndex(segment => segment.Coordinates.Any(coordinate => !held.Contains(coordinate) + && left.All(other => other.Angle == segment.Angle || !other.Coordinates.Contains(coordinate)))) is >= 0 and int met) + { + _freeAngles.Add(left[met].Angle); + left.RemoveAt(met); + } + } + + // Whether the lines of a sketch are straight reference lines joined end to end that only dimensions refer to: no + // constraint ties them otherwise, nothing is bound to them and nothing stands on them. + private bool StandsAlone(int sketch, List lines) + { + var ids = lines.Select(line => line.Id).ToHashSet(); + return lines.All(line => line.IsStraight && !line.IsRevolutionAxis) + && records.Constraints.All(c => c.SketchId != sketch + || c.ClassName is "VarSketchPPConstrObj" or "VarSketchHorVerConstrObj") + && !records.Associations.Any(a => a.ElementId == sketch || ids.Contains(a.ElementId)) + && records.Joints.All(j => ids.Contains(j.LineId) == ids.Contains(j.OtherLineId) + && (!ids.Contains(j.LineId) || j.End is 0 or 1 && j.OtherEnd is 0 or 1)) + && records.Referrers.All(r => !ids.Contains(r.TargetId) || r.RecordId == sketch || ids.Contains(r.RecordId) + || r.ClassName is "AngularDim" or "LinearDimString" or "Alignment" or "ConnectorElem"); + } + + private bool OnFreeEnd(FamilyDimensionRecord dimension) => + dimension.References.Any(reference => _freeEnds.Contains((reference.ElementId, reference.SubTag))); + + /// A label of an angle (a parameter) can only have the angle of the file in a type, any other value turns a + /// line, which the model does not follow. The solver holds the label to the stored angle, and refuses the type that + /// has another. + private void HoldAngle(FamilyAngularDimension angle) + { + if (!FamilyRules.IsKnownDimensionFlags(false, angle.Flags)) + throw Unrecognized($"flags {angle.Flags} of dimension {Text(angle.Id)}"); + if (angle.SegmentFlags is not (FamilyRules.UnlockedSegmentFlag or FamilyRules.LockedSegmentFlag)) + throw Unrecognized($"segments of dimension {Text(angle.Id)}"); + if (angle.ParameterId != -1 && !angle.Driven) + _equations.Add(new([(Add(angle.Value, anchored: true), 1)], angle.ParameterId, 1, 0, angle.Id, false, true)); + } + + // A line that keeps its axis and a plane across an axis are only moved, never turned. + private bool NeverTurns(int id) => _lines.TryGetValue(id, out var line) ? Direction(line) != null + : _planes.TryGetValue(id, out var plane) && AxisOf(plane.Normal) != null; + + // An angle of the model between such things is the one of the file wherever they are moved: only its label is held. + // Each of them must stay or be of the model, whose referrers are all checked: another angle could turn it otherwise. + private bool HoldUnturned(FamilyAngularDimension angle, HashSet model, HashSet held) + { + if (!angle.References.All(reference => + NeverTurns(reference.ElementId) && (Stays(reference.ElementId) || model.Contains(reference.ElementId)))) + return false; + if (held.Add(angle)) HoldAngle(angle); + return true; } private void CheckConstraints(HashSet modelLines) @@ -724,12 +911,29 @@ private void CheckCombinations() } } + // An imported drawing stands where the file has it: nothing may tie it to a place, and a parameter may only show or hide + // it. A dimension to it is refused as a reference to an element that takes no part. + private void CheckImports() + { + foreach (int id in records.Imports ?? new HashSet()) + { + if (records.Referrers.FirstOrDefault(r => r.RecordId == id && !FamilyRules.TiesNoImport(r.Field)) is { } tie) + throw Unrecognized($"{tie.Field} of import {id}"); + if (records.Associations.FirstOrDefault(a => a.ElementId == id + && a.ElementPropertyId != (long)BuiltInParameter.IS_VISIBLE_PARAM) is { } driven) + throw Unrecognized($"association {driven.ElementPropertyId} of element {id}"); + } + } + private void CheckAssociations(HashSet modelLines) { foreach (var association in records.Associations) { - // The shape of a combination is that of its members: nothing else of it is read. - if (_combinations.ContainsKey(association.ElementId)) + // The shape of a combination is that of its members: nothing else of it is read, but a material that every + // member takes too, which gives a face the same whichever of the two it takes it from. + if (_combinations.TryGetValue(association.ElementId, out var combination) + && !(association.ElementPropertyId == (long)BuiltInParameter.MATERIAL_ID_PARAM && combination.Members.All(member => + records.Associations.Contains(association with { ElementId = member })))) throw Unrecognized($"association {association.ElementPropertyId} of element {association.ElementId}"); bool onExtrusion = _extrusions.ContainsKey(association.ElementId); bool onRevolution = _revolutions.ContainsKey(association.ElementId); @@ -754,6 +958,7 @@ private void CheckReferrers(HashSet modelLines) .Concat(_extrusions.Values.Where(e => e.PlaneHost != null).Select(e => e.PlaneHost!.Value.ElementId)) .Concat(_revolutions.Values.Where(r => r.PlaneHost != null).Select(r => r.PlaneHost!.Value.ElementId)) .Where(id => id > 0).ToHashSet(); + var unturned = new HashSet(); foreach (var referrer in records.Referrers) { bool apart = _apartLines.Contains(referrer.TargetId) || _apartSketches.Contains(referrer.TargetId); @@ -769,8 +974,10 @@ private void CheckReferrers(HashSet modelLines) : _combinations.TryGetValue(referrer.RecordId, out var joined) ? joined.Members.Contains(referrer.TargetId) // An instance refers to its family, its symbols, the level it is listed at and the plane it stands on: the // plane is read in OriginNode and the rest moves nothing. - : _instances.ContainsKey(referrer.RecordId) ? referrer.Field is "Element.m_famId" or "FamilyInstance.m_scheduleOnlyLevelId" + : _instances.TryGetValue(referrer.RecordId, out var referring) ? referrer.Field is "Element.m_famId" or "FamilyInstance.m_scheduleOnlyLevelId" or "FamilyInstance.m_masterSymbolId" or "InstanceInfo.InstInfoBase.m_symbolId" or "InsertableInst.m_hostId" + // A shared part no type shows goes with its instance and takes nothing along. + || !referring.Shown && referrer.Field == FamilyRules.SuperInstanceField : referrer.ClassName switch { "LinearDimString" or "Alignment" or "RadialDim" or "VarSketch" or "ExtrusionElem" or "RevolutionElem" or "SketchPlane" => true, @@ -785,7 +992,8 @@ private void CheckReferrers(HashSet modelLines) && records.Joints.Any(j => j.LineId == referrer.RecordId && j.OtherLineId == referrer.TargetId && j.OtherEnd >= 0) && _lines.TryGetValue(referrer.RecordId, out var side) && Direction(side) is int along && _lines.TryGetValue(referrer.TargetId, out var next) && Direction(next) == along, - "AngularDim" => AngleApart(referrer.RecordId), + "AngularDim" => EverySegment(referrer.RecordId, angle => _freeAngles.Contains(angle) || AngleApart(angle) + || HoldUnturned(angle, model, unturned)), "ExtentElem" or "DBViewPlan" or "DBViewSection" or "DBView3d" or "SunAndShadowSettings" or "Opening" or "ComplexOpening" or "ConnectorElem" or "PostedWarningElem" or "ImportInstance" or "FilledRegion" => true, var name => TfClassNames.IsSubclassOf(name, "HostObj"), @@ -818,11 +1026,13 @@ private void PlaceHostFaces(List<(FamilyDimensionRecord Record, int[] Nodes)> di private void Relate(FamilyDimensionRecord dimension, int[] nodes) { double Stored(int i) => _nodes[Root(nodes[i])].Stored; - // 1 or -1 for the way segment i runs along the axis, 0 for one without a length. - int Way(int i) => Math.Abs(Stored(i + 1) - Stored(i)) <= Tolerance ? 0 : Math.Sign(Stored(i + 1) - Stored(i)); - void Hold(long? parameter, int sign, double constant, bool weak, params (int Node, int Coefficient)[] terms) + bool Empty(int i) => Math.Abs(Stored(i + 1) - Stored(i)) <= Tolerance; + // 1 or -1 for the way segment i runs along the axis. The axis of a dimension points from each reference to the + // next, which still tells the way of a segment saved without a length. + int Way(int i) => Math.Sign(Empty(i) ? dimension.Axis[AxisOf(dimension.Axis)!.Value] : Stored(i + 1) - Stored(i)); + void Hold(long? parameter, int sign, double constant, bool weak, (int Node, int Coefficient)[] terms, bool mayBeEmpty = false) { - _equations.Add(new([.. terms], parameter, sign, constant, dimension.Id, weak)); + _equations.Add(new([.. terms], parameter, sign, constant, dimension.Id, weak, MayBeEmpty: mayBeEmpty)); if (!weak) _heldCaps.UnionWith(terms.Select(term => Root(term.Node))); } @@ -832,8 +1042,7 @@ void Hold(long? parameter, int sign, double constant, bool weak, params (int Nod for (int i = 0; i + 1 < segments; i++) { var (first, second) = (Way(i), Way(i + 1)); - if (first == 0 || second == 0) throw Unrecognized($"empty segment of dimension {dimension.Id}"); - Hold(null, 1, 0, false, (nodes[i], -first), (nodes[i + 1], first + second), (nodes[i + 2], -second)); + Hold(null, 1, 0, false, [(nodes[i], -first), (nodes[i + 1], first + second), (nodes[i + 2], -second)]); } return; } @@ -843,10 +1052,7 @@ void Hold(long? parameter, int sign, double constant, bool weak, params (int Nod double value = dimension.IsAlignment ? 0 : (Stored(i + 1) < Stored(i) ? -1 : 1) * Math.Abs(dimension.SegmentValues[i]); if (dimension.ParameterIds[i] is var parameter && parameter != -1) - { - if (Way(i) == 0) throw Unrecognized($"empty segment of dimension {dimension.Id}"); - Hold(parameter, Way(i), 0, false, length); - } + Hold(parameter, Way(i), 0, false, length, Empty(i)); else if (dimension.SegmentFlags[i] == FamilyRules.LockedSegmentFlag) Hold(null, 1, value, false, length); else if (!dimension.DrivenSegments.Contains(i)) Hold(null, 1, value, true, length); } @@ -952,8 +1158,17 @@ int Variable(int node) } var equations = _equations.Select(e => new FamilyEquation( [.. e.Terms.Select(term => new FamilyTerm(Variable(term.Node), term.Coefficient))], - e.Parameter, e.Sign, e.Constant, e.Source, e.IsWeak, e.IsOffset)).ToList(); + e.Parameter, e.Sign, e.Constant, e.Source, e.IsWeak, e.IsOffset, e.MayBeEmpty)).ToList(); + // An arc of a profile in the plane square to the axis, run from its end when the loop runs it that way. + FamilyArcSegment Segment(FamilySketchLine line, int axis, bool reversed, int facets) + { + var shape = Shape(line, axis); + var (start, way) = reversed ? (shape.EndDirection, -shape.Way) : (shape.StartDirection, shape.Way); + return new(Variable(Centre(line, (axis + 1) % 3)), Variable(Centre(line, (axis + 2) % 3)), + Variable(Radius(line)), way, start switch { (1, 0) => 0, (0, 1) => 1, (-1, 0) => 2, _ => 3 }, + shape.Quarters, facets); + } var extrusions = records.Extrusions.Select(extrusion => { var (low, high, swapped) = caps[extrusion.Id]; @@ -972,15 +1187,11 @@ int Variable(int node) var curve = extrusion.ProfileCurves[key]; var line = _lines[curve.LineId]; if (line.Arc == null) return null; - var shape = Shape(line, axis); - var (start, way) = curve.Reversed ? (shape.EndDirection, -shape.Way) : (shape.StartDirection, shape.Way); // The file stores a curved side as a row of flat faces, as many as its face tag has faces. int facets = extrusion.FaceHistory.Where(face => face.Value is [3, var side] && side == key) .Select(face => extrusion.FaceFacets?.GetValueOrDefault(face.Key)).FirstOrDefault(count => count > 0) - ?? 3 * shape.Quarters; - return new(Variable(Centre(line, (axis + 1) % 3)), Variable(Centre(line, (axis + 2) % 3)), - Variable(Radius(line)), way, start switch { (1, 0) => 0, (0, 1) => 1, (-1, 0) => 2, _ => 3 }, - shape.Quarters, facets); + ?? 3 * Shape(line, axis).Quarters; + return Segment(line, axis, curve.Reversed, facets); } IReadOnlyList>? arcs = !extrusion.Loops.Any(loop => loop.Any(key => Arc(key) != null)) ? null : [.. extrusion.Loops.Select(loop => (IReadOnlyList)[.. loop.Select(Arc)])]; @@ -997,15 +1208,32 @@ int Variable(int node) var (plane, axisPosition, corners) = placed[revolution.Id]; var loops = corners.Select(loop => (IReadOnlyList)loop .Select(corner => new FamilyVertex(Variable(corner[0]), Variable(corner[1]), Variable(corner[2]))).ToList()).ToList(); + FamilyArcSegment? Arc(FamilyProfileCurve curve) + { + var line = _lines[curve.LineId]; + // Along the profile a quarter turn has the facets of one of a whole turn, so a circle is cut alike both ways. + return line.Arc == null ? null : Segment(line, normal, curve.Reversed, + Shape(line, normal).Quarters * (int)Math.Ceiling(FamilyRevolutionBuilder.Facets / 4.0)); + } + IReadOnlyList>? arcs = !Curves(revolution).Any(line => line.Arc != null) + ? null : [.. revolution.Loops.Select(loop => (IReadOnlyList)[.. loop.Select(Arc)])]; return new FamilyRevolution(revolution.Id, loops, axis, normal, Variable(axisPosition), Variable(plane), new Dictionary(), BoundOf(revolution.Id, BuiltInParameter.MATERIAL_ID_PARAM), - BoundOf(revolution.Id, BuiltInParameter.IS_VISIBLE_PARAM)); + BoundOf(revolution.Id, BuiltInParameter.IS_VISIBLE_PARAM), arcs); }).ToList(); var combinations = (records.Combinations ?? []) .Select(combination => new FamilyCombination(combination.Id, [.. combination.Members])).ToList(); var placements = _instances.Values.Where(instance => instance.Shown).Select(instance => new FamilyPlacement( instance.Id, instance.SymbolId, instance.MasterSymbolId, [.. origins[instance.Id].Select(Variable)], instance.Basis, BoundOf(instance.Id, BuiltInParameter.IS_VISIBLE_PARAM))).ToList(); + // Every imported drawing stands at one point nothing moves, as the file has it. + if (records.Imports is { Count: > 0 } imports) + { + int still = variables.Count; + variables.Add(new(0, true)); + placements.AddRange(imports.Order().Select(id => new FamilyPlacement(id, 0, 0, [still, still, still], + [[1, 0, 0], [0, 1, 0], [0, 0, 1]], BoundOf(id, BuiltInParameter.IS_VISIBLE_PARAM)))); + } return new(variables, equations, extrusions) { Revolutions = revolutions, Combinations = combinations, Placements = placements }; } diff --git a/src/RvtIO/Families/FamilyNested.cs b/src/RvtIO/Families/FamilyNested.cs index 767c9be5..81650073 100644 --- a/src/RvtIO/Families/FamilyNested.cs +++ b/src/RvtIO/Families/FamilyNested.cs @@ -1,4 +1,5 @@ using System.Globalization; +using RvtIO.BuiltIns; using RvtIO.Meshes; using RvtIO.Model; @@ -54,12 +55,7 @@ internal static (NestedShape? Shape, RvtFamilyRefusal? Refusal) Prepare(NestedFa var saved = ElementMeshes.ValuesOf(types.Types[types.CurrentIndex]); var stored = new Dictionary>(); foreach (var (element, body) in listed) - { - if (body == null || body.PlacedSymbolBox || body.UnresolvedSymbol || body.UntriangulatedFaces > 0 - || body.GhostNodes is { Count: > 0 }) continue; - bool dropUntaken = ElementMeshes.DropsUntakenNodes(body.Faces, false); - stored[element.Id] = body.Faces.Where(face => !dropUntaken || face.GeometryNode >= 0).ToList(); - } + if (ElementMeshes.WholeFaces(body) is { } whole) stored[element.Id] = whole; var (matched, mismatch) = FamilySavedState.Match(model, saved, (extrusion, key) => extrusion.Materials.GetValueOrDefault(key), stored); if (matched == null) return No(mismatch!.Code, mismatch.Detail); @@ -74,15 +70,25 @@ internal static (NestedShape? Shape, RvtFamilyRefusal? Refusal) Prepare(NestedFa internal static (NestedSolution? Solution, RvtFamilyRefusal? Refusal) Solve(NestedShape shape, FamilyPlacement placement, FamilyRecords host, IReadOnlyDictionary hostValues, IReadOnlyList hostPositions) { - (NestedSolution?, RvtFamilyRefusal?) No(string code, string detail) => (null, new(code, detail)); + var (values, refusal) = Values(shape, placement, host, hostValues); + if (values == null) return (null, refusal); + var solution = FamilySolver.Solve(shape.Model, values); + if (solution.Positions is not { } positions) return (null, solution.Refusal); + if (FamilyContourChecks.Check(shape.Model, positions, values) is { } degenerate) return (null, degenerate); + return (new NestedSolution(shape, positions, [.. placement.Origin.Select(variable => hostPositions[variable])]), null); + } + + /// The values of the parameters of the loaded family for the instance at the values of a + /// type of the host, as takes them; they depend on no position of the host. + internal static (IReadOnlyDictionary? Values, RvtFamilyRefusal? Refusal) Values(NestedShape shape, + FamilyPlacement placement, FamilyRecords host, IReadOnlyDictionary hostValues) + { + (IReadOnlyDictionary?, RvtFamilyRefusal?) No(string code, string detail) => (null, new(code, detail)); string instance = placement.ElementId.ToString(CultureInfo.InvariantCulture); if (!IsRotation(placement.Basis)) return No("unsupported-construct", $"instance {instance} is not placed by a rotation or a mirror"); - var associations = host.Associations.Where(association => association.ElementId == placement.ElementId).ToList(); - foreach (int id in new[] { placement.SymbolId, placement.MasterSymbolId }.Distinct()) - associations.AddRange(host.Symbols!.Single(symbol => symbol.Id == id).Associations); var input = new Dictionary(); - foreach (var association in associations.Distinct()) + foreach (var association in AssociationsOf(placement, host)) { string parameter = association.FamilyParameterId.ToString(CultureInfo.InvariantCulture); if (!hostValues.TryGetValue(association.FamilyParameterId, out double value)) return No("underdetermined", parameter); @@ -103,31 +109,103 @@ internal static (NestedSolution? Solution, RvtFamilyRefusal? Refusal) Solve(Nest var reporting = shape.Formulas.Reporting; double? Given(long id) => input.TryGetValue(id, out double value) ? value : !reporting.Contains(id) && shape.TypeValues.TryGetValue(id, out double stored) ? stored : null; - var (values, refusal) = shape.Formulas.Evaluate(Given); - if (values == null) return (null, refusal); - var solution = FamilySolver.Solve(shape.Model, values); - if (solution.Positions is not { } positions) return (null, solution.Refusal); - if (FamilyContourChecks.Check(shape.Model, positions, values) is { } degenerate) return (null, degenerate); - return (new NestedSolution(shape, positions, [.. placement.Origin.Select(variable => hostPositions[variable])]), null); + return shape.Formulas.Evaluate(Given); + } + + /// The instance as the file stores it, for a loaded family that is not computed + /// (): its stored faces , once they are the faces the loaded family's document + /// stores for what it shows, placed where the instance stands; or null. The types of the host () + /// that give the instance what the saved one does have that shape, moved with the instance. + internal static CarriedInstance? Carry(NestedFamilyData nested, RevitFileInfo info, FamilyPlacement placement, FamilyRecords host, + RvtFamilyTypes types, IReadOnlyList positions, IReadOnlyList held, RvtFamilyRefusal why) + { + var (listed, hidden, gaps) = ElementMeshes.FamilyElements(info, nested.Data); + if (gaps.Length > 0 || held.Count == 0 || !IsRotation(placement.Basis)) return null; + // A loaded family of several types shows in an instance what the type that placed it shows, not what its saved one does. + if (nested.Data.Types is { Types.Count: > 1 } own) + { + if (HiddenInType(nested.Data, own, info, placement.MasterSymbolId) is not { } unseen) return null; + hidden = unseen; + } + double[] origin = [.. placement.Origin.Select(variable => positions[variable])]; + var left = held.ToList(); + var earlier = new List(); + foreach (var (element, body) in listed.Where(item => !hidden.Contains(item.Element.Id) && item.Element.Id != nested.Data.HostStandIn)) + { + if (ElementMeshes.WholeFaces(body) is not { } faces) return null; + var matched = new List(); + foreach (var face in faces) + { + if (face.OuterVertices is not { Count: >= 3 } || face.Normal.Length != 3 + || (face.InnerVertices ?? []).Prepend(face.OuterVertices).Any(ring => ring.Any(point => point.Length != 3))) + return null; + var placed = Place(placement.Basis, origin, face.Normal, face.OuterVertices, face.InnerVertices); + // The file does not wind every face of the two copies the same way; the instance is drawn as the host stores it. + var turned = TurnedOver(placed); + bool Same(GeoFace candidate) => FamilySavedState.SameShape(placed, candidate) || FamilySavedState.SameShape(turned, candidate); + int found = left.FindIndex(Same); + if (found >= 0) + { + matched.Add(left[found]); + left.RemoveAt(found); + } + // Where two forms touch, the instance holds the face they have in the same place once. + else if (!earlier.Exists(Same)) return null; + } + earlier.AddRange(matched); + } + if (left.Count > 0) return null; + + var saved = ElementMeshes.ValuesOf(types.Types[types.CurrentIndex]); + var numbers = types.Types.Select(ElementMeshes.ValuesOf).ToList(); + var inputs = new Dictionary(); + foreach (var association in AssociationsOf(placement, host)) + { + // What shows or hides the instance gives it nothing of its shape. + if (association.ElementId == placement.ElementId + && association.ElementPropertyId == (long)BuiltInParameter.IS_VISIBLE_PARAM) continue; + long parameter = association.FamilyParameterId; + // The types are compared by their numbers. A text that is the same in all of them, or any value they store alike, + // gives each the same; any other parameter without a number in some type could differ between them unseen. + var texts = types.Types.Select(type => type.Parameters.FirstOrDefault(item => item.Id == parameter) + is { StorageType: StorageType.String } text ? text.Value as string ?? "" : null).Distinct().ToList(); + if (texts is not [not null] && !types.StoredAlike.Contains(parameter) + && !numbers.All(values => values.ContainsKey(parameter))) return null; + inputs[parameter] = saved.TryGetValue(parameter, out double value) ? value : null; + } + return new CarriedInstance(held, inputs, why); + } + + /// The forms hidden in the type of the loaded family that is named as the symbol of the + /// host; null when the loaded family has no one such type, or that type does not say what shows each form. + private static HashSet? HiddenInType(FamilyData data, RvtFamilyTypes types, RevitFileInfo info, int symbolId) + { + string? name = info.Elements.FirstOrDefault(element => element.Id == symbolId && !element.IsBlockOnly)?.Name; + if (types.Types.Where(type => type.Name == name).ToList() is not [var type] || data.Records is not { } records) return null; + var values = ElementMeshes.ValuesOf(type); + var hidden = new HashSet(); + foreach (var association in records.Associations + .Where(association => association.ElementPropertyId == (long)BuiltInParameter.IS_VISIBLE_PARAM)) + { + if (!values.TryGetValue(association.FamilyParameterId, out double shows)) return null; + if (shows == 0) hidden.Add(association.ElementId); + } + return hidden; } + /// What gives an instance its parameters: its own associations and those of its symbols. + private static IEnumerable AssociationsOf(FamilyPlacement placement, FamilyRecords host) => + host.Associations.Where(association => association.ElementId == placement.ElementId) + .Concat(new[] { placement.SymbolId, placement.MasterSymbolId }.Distinct() + .SelectMany(id => host.Symbols!.Single(symbol => symbol.Id == id).Associations)) + .Distinct(); + /// The faces of the loaded family in the frame of the host, for each form and face of its model: the point of /// the loaded family p stands at origin + Σ p[c]·basis[c]. A mirror turns the corners of a face the other /// way round. is as in . internal static List<(int ElementId, FamilyFaceKey Key, GeoFace Face)> Faces(NestedSolution solution, FamilyPlacement placement, int facetsPerTurn = 0) { - var basis = placement.Basis; - bool mirrored = Determinant(basis) < 0; - double[] Direction(double[] local) => [.. Enumerable.Range(0, 3).Select(axis => Enumerable.Range(0, 3).Sum(c => local[c] * basis[c][axis]))]; - double[] Point(double[] local) => [.. Direction(local).Select((value, axis) => solution.Origin[axis] + value)]; - List Ring(IEnumerable corners) - { - var ring = corners.Select(Point).ToList(); - if (mirrored) ring.Reverse(); - return ring; - } - var faces = new List<(int, FamilyFaceKey, GeoFace)>(); foreach (var extrusion in solution.Shape.Model.Extrusions) { @@ -138,18 +216,45 @@ List Ring(IEnumerable corners) return 0; }, facetsPerTurn); foreach (var (face, key) in built.Zip(keys)) - { - var outer = Ring(face.OuterVertices!); - faces.Add((extrusion.ElementId, key, new GeoFace(outer[0], Direction(face.Normal)) - { - OuterVertices = outer, - InnerVertices = face.InnerVertices?.Select(hole => Ring(hole)).ToList(), - })); - } + faces.Add((extrusion.ElementId, key, + Place(placement.Basis, solution.Origin, face.Normal, face.OuterVertices!, face.InnerVertices))); } return faces; } + /// The face seen from its other side. + private static GeoFace TurnedOver(GeoFace face) + { + static List Back(List ring) => [.. ring.AsEnumerable().Reverse()]; + var outer = Back(face.OuterVertices!); + return new GeoFace(outer[0], [.. face.Normal.Select(value => -value)]) + { + OuterVertices = outer, + InnerVertices = face.InnerVertices?.Select(Back).ToList(), + }; + } + + /// A face of a loaded family in the frame of the host, where the instance stands at . + private static GeoFace Place(double[][] basis, double[] origin, double[] normal, List outer, List>? inner) + { + bool mirrored = Determinant(basis) < 0; + double[] Direction(double[] local) => [.. Enumerable.Range(0, 3).Select(axis => Enumerable.Range(0, 3).Sum(c => local[c] * basis[c][axis]))]; + double[] Point(double[] local) => [.. Direction(local).Select((value, axis) => origin[axis] + value)]; + List Ring(IEnumerable corners) + { + var ring = corners.Select(Point).ToList(); + if (mirrored) ring.Reverse(); + return ring; + } + + var placed = Ring(outer); + return new GeoFace(placed[0], Direction(normal)) + { + OuterVertices = placed, + InnerVertices = inner?.Select(hole => Ring(hole)).ToList(), + }; + } + private static double Determinant(double[][] b) => b[0][0] * (b[1][1] * b[2][2] - b[1][2] * b[2][1]) - b[0][1] * (b[1][0] * b[2][2] - b[1][2] * b[2][0]) + b[0][2] * (b[1][0] * b[2][1] - b[1][1] * b[2][0]); diff --git a/src/RvtIO/Families/FamilyRecordReader.cs b/src/RvtIO/Families/FamilyRecordReader.cs index d9b5353a..2b0def01 100644 --- a/src/RvtIO/Families/FamilyRecordReader.cs +++ b/src/RvtIO/Families/FamilyRecordReader.cs @@ -30,10 +30,11 @@ internal static FamilyData Read(RootStorage root, RevitFileInfo info, ElementIdM elements.TryAdd(element.Id, element); var records = new Dictionary(); - bool recordsRead = true; - try { ReadRecords(root, elements, ids, currentCopies, records, block); } + bool recordsRead = false, formsListed = false; + int? standIn = null; + try { (recordsRead, formsListed, standIn) = ReadRecords(root, elements, ids, ownerId, currentCopies, records, block); } // What was read before the failure stands; every other element is reported as unrecognised below. - catch (Exception ex) when (ex is RvtWriteRefusedException || MalformedInput.Is(ex)) { recordsRead = false; } + catch (Exception ex) when (ex is RvtWriteRefusedException || MalformedInput.Is(ex)) { } var own = records.Where(pair => pair.Value is { Exact: true } record && record.FamilyId == ownerId) .ToDictionary(pair => pair.Key, pair => pair.Value!); @@ -59,7 +60,7 @@ internal static FamilyData Read(RootStorage root, RevitFileInfo info, ElementIdM if (record.IsCombination && record.Members.Any(id => Key(ids, id) is null)) shown = null; facts.Add(new(element.Id, record.ClassName, record.IsForm, hasGeometry, record.Cutting, shown, hidden, combined, combined && record.MemberShownAlways, record.CutByOwnStep, - FamilyRules.IsDrawnInViewsOnly(record.ClassName, element.Category), + FamilyRules.IsDrawnInViewsOnly(record.ClassName, element.Category, element.OwnerViewId), FamilyRules.PlacesOnlyForms(element.Id, Body(element), id => own.TryGetValue(id, out var placed) && placed.IsForm), record.IsCombination ? membersOf[element.Id].ToArray() : null)); @@ -74,19 +75,59 @@ internal static FamilyData Read(RootStorage root, RevitFileInfo info, ElementIdM bool form = other?.IsForm ?? FamilyRules.FormClasses.Any(name => TfClassNames.IsSubclassOf(className, name)); if (hasGeometry || form && (other != null || element.SerializedFamilyId == ownerId)) facts.Add(new(element.Id, className, form, hasGeometry, false, null, null, - DrawnInViewsOnly: FamilyRules.IsDrawnInViewsOnly(className, element.Category))); + DrawnInViewsOnly: FamilyRules.IsDrawnInViewsOnly(className, element.Category, element.OwnerViewId))); } var (types, typesError) = ReadTypes(root, ownerId, ids, currentCopies, block); var relations = types is { Types.Count: > 0 } ? FamilyRelationReader.Read(root, elements, ids, ownerId, currentCopies, facts, block) : null; + bool elementsRead = recordsRead && formsListed; + if (block == 0 && relations?.Instances != null) + { + var host = new FamilyData { Elements = facts, ElementRecordsRead = elementsRead, Types = types, Records = relations }; + var empty = EmptyInstances(Documents(root, info, ids, currentCopies, host, ownerId, block, [])); + if (empty.Count > 0) + { + facts = facts.Select(fact => empty.Contains(fact.ElementId) ? fact with { DrawsNothing = true } : fact).ToList(); + relations = relations with + { + Instances = relations.Instances.Select(instance => empty.Contains(instance.Id) + ? instance with { Shown = false } : instance).ToList(), + }; + } + } var (nested, nestedError) = block == 0 && relations?.Instances?.Any(instance => instance.Shown) == true ? ReadNested(root, info, ids, ownerId, currentCopies, relations) : (null, null); return new FamilyData { - Elements = facts, Types = types, TypesError = typesError, Records = relations, Nested = nested, NestedError = nestedError, + Elements = facts, ElementRecordsRead = elementsRead, Types = types, TypesError = typesError, Records = relations, + Nested = nested, NestedError = nestedError, HostStandIn = standIn, }; } + /// The shown instances without geometry whose loaded families draw nothing in any type. + private static HashSet EmptyInstances(FamilyDocumentTree host) + { + var bare = host.Data.Elements.Where(fact => !fact.HasGeometry).Select(fact => fact.ElementId).ToHashSet(); + return host.Data.Records!.Instances!.Where(instance => instance.Shown && bare.Contains(instance.Id) + && FamilyEmptyContent.InstanceDrawsNothing(host, instance.Id)).Select(instance => instance.Id).ToHashSet(); + } + + /// The document of a family and, as they are asked for, those of the families loaded into it; + /// keeps the data of the blocks read already. + private static FamilyDocumentTree Documents(RootStorage root, RevitFileInfo info, ElementIdMap? ids, + IReadOnlyDictionary? currentCopies, FamilyData data, long ownerId, int block, Dictionary read) + { + IReadOnlyList? links = null; + return new(data, family => + { + links ??= NestedFamilies.Read(root, currentCopies, ownerId, block).Families; + if (links.Where(link => link.HostFamilyId == family).ToList() is not [var link]) return null; + if (!read.TryGetValue(link.Block, out var loaded)) + read.Add(link.Block, loaded = Read(root, info, ids, link.OwnerId, currentCopies, link.Block)); + return Documents(root, info, ids, currentCopies, loaded, link.OwnerId, link.Block, read); + }); + } + /// The documents of the families that the shown instances of the family are of, read as families themselves; or why /// one of them cannot be. A family loaded into a nested one is not read: it is refused when the nested one is computed. private static (IReadOnlyList? Nested, string? Error) ReadNested(RootStorage root, RevitFileInfo info, @@ -183,7 +224,8 @@ internal static (RvtFamilyTypes? Types, string? Error) ReadTypes(RootStorage roo return ToParameter(definition, row, ids); }).ToArray()); }).ToArray(); - return (new RvtFamilyTypes(saved, types), null); + var alike = StoredAlike(stored).Select(id => (long)definitions[id].Key).ToHashSet(); + return (new RvtFamilyTypes(saved, types) { StoredAlike = alike }, null); } catch (Exception ex) when (ex is RvtWriteRefusedException || MalformedInput.Is(ex)) { @@ -191,6 +233,15 @@ internal static (RvtFamilyTypes? Types, string? Error) ReadTypes(RootStorage roo } } + /// The ids of the parameters that every one of the types has with the same value slots. A value of a kind that is + /// not established is not read, but one stored alike differs in no type. + internal static HashSet StoredAlike(IReadOnlyList types) => + types.SelectMany(type => type.Values.Rows).GroupBy(row => row.Id) + .Where(rows => rows.Count() == types.Count && rows.Select(row => ( + row.Value(StorageType.String).Text, BitConverter.DoubleToInt64Bits(row.Value(StorageType.Double).Real), + row.Value(StorageType.ElementId).Integer, row.Value(StorageType.Integer).Integer)).Distinct().Count() == 1) + .Select(rows => rows.Key).ToHashSet(); + /// The kind of value a parameter of the document holds (none when its definition is not read exactly). internal static StorageType StorageOf(WideBlockWalker walker, Dictionary bodies, ElementIdMap? ids, long id) => Describe(walker, bodies, ids, id).Storage; @@ -318,23 +369,40 @@ private static bool HasGeometry(Element element) => ids != null ? ids.TryGetKey(id, out int key) ? key : null : id is > 0 and <= int.MaxValue ? (int)id : null; - /// The records of the elements, by element key; null for an element with more than one record. - private static void ReadRecords(RootStorage root, Dictionary elements, ElementIdMap? ids, - IReadOnlyDictionary? currentCopies, Dictionary records, int block) + /// The records of the elements, by element key; null for an element with more than one record. Whether they were + /// read, whether every record of a form or of an imported drawing in the block is that of one of the elements, and the + /// element that the record of the family names as standing for its face + /// (). + private static (bool Read, bool FormsListed, int? HostStandIn) ReadRecords(RootStorage root, Dictionary elements, + ElementIdMap? ids, long ownerId, IReadOnlyDictionary? currentCopies, Dictionary records, int block) { - if (TfSchemaReader.Read(root) is not { } schema) return; + if (TfSchemaReader.Read(root) is not { } schema) return (false, false, null); var formats = new FormatsSchema(schema); - if (PartitionFraming.TagsOf(formats) is not { } tags || ElemTableLayout.IdWidth(formats) is not int idWidth) return; + if (PartitionFraming.TagsOf(formats) is not { } tags || ElemTableLayout.IdWidth(formats) is not int idWidth) + return (false, false, null); var walker = new WideBlockWalker(schema, CaptureKey, []); walker.UseEntitySchemas(EntitySchemaReader.Read(root, schema)); var bodies = new Dictionary(); + bool formsListed = true; + // The record of the family itself; copies that differ name no face. + byte[]? family = null; + bool familyCopiesDiffer = false; ParameterWriter.ScanPartitions(root, tags, idWidth, (partition, record) => { if (currentCopies != null && currentCopies.TryGetValue(record.Owner, out int current) && current != partition) return; - if (record.Block != block || record.Channel != 102 || record.Body.Length < 2 || record.Owner > long.MaxValue - || Key(ids, (long)record.Owner) is not int key || !elements.TryGetValue(key, out var element)) return; + if (record.Block != block || record.Channel != 102 || record.Body.Length < 2 || record.Owner > long.MaxValue) return; int cls = BinaryPrimitives.ReadUInt16LittleEndian(record.Body.Span); + if ((long)record.Owner == ownerId && walker.Class(cls)?.Name == "Family") + { + if (family == null) family = record.Body.ToArray(); + else familyCopiesDiffer |= !record.Body.Span.SequenceEqual(family); + } bool form = FamilyRules.FormClasses.Any(name => walker.IsA(cls, name)); + if (Key(ids, (long)record.Owner) is not int key || !elements.TryGetValue(key, out var element)) + { + formsListed &= !(form || walker.IsA(cls, FamilyRules.ImportClass)); + return; + } if (!form && !HasGeometry(element)) return; byte[] data = record.Body.ToArray(); // Equal copies are interchangeable; copies that differ leave the element unrecognised. @@ -355,10 +423,37 @@ private static void ReadRecords(RootStorage root, Dictionary eleme && c.Integer > 0), walk.Captures.Where(c => c.Key == "AddGeomToCombinationGStep.m_memberId").Select(c => c.Integer).ToArray())); }, new ParameterWriter.Pending()); + + int? standIn = null; + if (family != null && !familyCopiesDiffer + && walker.Run(family, 0, family.Length, BinaryPrimitives.ReadUInt16LittleEndian(family)) is { Exact: true } walked + && FaceHost(walked.Captures, tag => walker.IsA(tag, "FamilyElemRef")) is long named) + standIn = Key(ids, named); + return (true, formsListed, standIn); + } + + // Family.m_refTypeIds of a family placed on a face, and of one placed on a work plane. + private const long FaceReferenceType = 7; + + /// The element a family record names as standing for the face the family is placed on: that of its one reference, + /// when its one reference type is that of a face. Null otherwise. tells by its class + /// whether what a reference points to names an element. + internal static long? FaceHost(IReadOnlyList captures, Func isElementReference) + { + WideBlockWalker.Capture? One(string key) => captures.Where(c => c.Key == key).ToArray() is [var only] ? only : null; + if (One("all:Family.m_refTypeIds#")?.Integer != 1 || One("all:Family.m_refTypeIds@0")?.Integer != FaceReferenceType + || One("all:Family.m_refs#")?.Integer != 1 + || One("all:Family.m_refs@0") is not { Integer: > 0 } reference || !isElementReference((int)reference.Integer)) + return null; + return captures.Where(c => c.Key == "FamilyElemRef.m_elemId" && c.QueueIndex == reference.QueuePosition).ToArray() + is [var named] ? named.Integer : null; } private static string? CaptureKey(SchemaClass declaring, SchemaField field) => (declaring.Name, field.Name) switch { + // Every item of these: a family record with more than one reference names no face. + ("Family", "m_refTypeIds" or "m_refs") => WideBlockWalker.AllItemsKeyPrefix + declaring.Name + "." + field.Name, + ("FamilyElemRef", "m_elemId") => declaring.Name + "." + field.Name, ("Element", "m_famId") or ("GenSweep", "m_cutting") or ("FamElemVisibility", "m_flags") or ("ParamIdPair", "m_elemPropId") or ("GroupMembership", "m_groupId") or ("GeomCombinationMembership", "m_alwaysVisible") or ("AddGeomToCombinationGStep", "m_memberId") or diff --git a/src/RvtIO/Families/FamilyRecords.cs b/src/RvtIO/Families/FamilyRecords.cs index 4a2e2af6..dfeded23 100644 --- a/src/RvtIO/Families/FamilyRecords.cs +++ b/src/RvtIO/Families/FamilyRecords.cs @@ -9,7 +9,13 @@ namespace RvtIO.Families; /// manager computes from others. internal sealed record FamilyDimensionRecord(int Id, bool IsAlignment, double[] Axis, long Flags, IReadOnlyList SegmentFlags, IReadOnlyList References, IReadOnlyList ParameterIds, - IReadOnlyList SegmentValues, IReadOnlySet DrivenSegments); + IReadOnlyList SegmentValues, IReadOnlySet DrivenSegments) +{ + /// An unlocked, unlabelled dimension that is no equality only shows a distance and holds nothing. + public bool OnlyShows => !IsAlignment && FamilyRules.IsKnownDimensionFlags(false, Flags) + && (Flags & FamilyRules.EqualityDimensionFlag) == 0 && ParameterIds.All(parameter => parameter == -1) + && SegmentFlags.All(flags => flags == FamilyRules.UnlockedSegmentFlag); +} /// The circle or arc a curve is: its centre, the unit axes of its plane, its radius, and the angles of its ends /// (a point of it is the centre plus the radius times the cosine of the angle along XAxis and the sine along @@ -22,8 +28,9 @@ internal sealed record FamilyArc(double[] Center, double[] XAxis, double[] YAxis internal sealed record FamilyRadialDimension(int Id, FamilyReference Arc, long ParameterId, double Value, long Flags, long SegmentFlags, bool Driven, long StyleType); -/// An angular dimension: the two lines or planes it measures between, its label (-1 for none), the angle it holds -/// in radians, its flags and segment flags, and whether the family's dimension manager computes it from others. +/// A segment of an angular dimension: the two lines or planes it measures between, its label (-1 for none), the +/// angle it holds in radians, the flags of the dimension and of the segment, and whether the family's dimension manager +/// computes it from others. A dimension of several segments is one such record for each, all with its id. internal sealed record FamilyAngularDimension(int Id, IReadOnlyList References, long ParameterId, double Value, long Flags, long SegmentFlags, bool Driven); @@ -48,7 +55,13 @@ internal sealed record FamilySketchConstraint(int SketchId, string ClassName); /// A reference plane, a level or a host element. A host has no plane of its own: Origin and Normal /// are empty. internal sealed record FamilyPlaneRecord(int ElementId, string ClassName, long ReferenceName, double[] Origin, - double[] Normal, bool Pinned = false, bool DefinesOrigin = false); + double[] Normal, bool Pinned = false, bool DefinesOrigin = false) +{ + /// A plane that stays where it is whatever the parameters are: a level, a pinned plane, a plane that defines the + /// origin or one of the centre planes. + public bool Stays => Origin.Length > 0 + && (ClassName == "Level" || Pinned || DefinesOrigin || FamilyRules.IsCentreReferenceName(ReferenceName)); +} /// The sketch line a profile curve copies; Reversed when the curve runs from the line's end to its /// start. @@ -65,7 +78,7 @@ internal sealed record FamilyExtrusionRecord(int Id, int SketchId, double Start, IReadOnlyDictionary? FaceFacets = null); /// A revolution: its start and end angles (from the sketch plane, about the axis), what the sketch plane follows -/// (null when nothing), the closed loops of straight lines that are its profile (each curve a sketch line, with the way it is +/// (null when nothing), the closed loops of lines and arcs that are its profile (each curve a sketch line, with the way it is /// run) and the sketch line it turns about. internal sealed record FamilyRevolutionRecord(int Id, int SketchId, double StartAngle, double EndAngle, double[] PlaneOrigin, double[] PlaneNormal, FamilyReference? PlaneHost, IReadOnlyList> Loops, int AxisLineId); @@ -104,7 +117,8 @@ internal sealed record FamilySymbolRecord(int Id, long FamilyId, IReadOnlyListWhat the records of a family say about the placing of its forms, as plain values. /// UnsupportedContent names what is shown and cannot be recomputed. FormulaParameterIds are the parameters a /// formula or a measurement sets: the value a type stores for one is the value it has, so it is used as stored. -/// ControlIconIds are the control icons (the arrows that flip an element) of the family. +/// ControlIconIds are the control icons (the arrows that flip an element) of the family. UndrawnForms are the +/// forms no type draws. Imports are the imported drawings the family shows in some type. internal sealed record FamilyRecords(IReadOnlyList Dimensions, IReadOnlyList Lines, IReadOnlyList Joints, IReadOnlyList Constraints, IReadOnlyList Planes, @@ -114,4 +128,5 @@ internal sealed record FamilyRecords(IReadOnlyList Dimens IReadOnlyList? ArcEndAngles = null, IReadOnlySet? ControlIconIds = null, IReadOnlyList? Revolutions = null, IReadOnlyList? Combinations = null, IReadOnlyList? Instances = null, IReadOnlyList? Symbols = null, - IReadOnlyList? AngularDimensions = null); + IReadOnlyList? AngularDimensions = null, IReadOnlySet? UndrawnForms = null, + IReadOnlySet? Imports = null); diff --git a/src/RvtIO/Families/FamilyRelationReader.cs b/src/RvtIO/Families/FamilyRelationReader.cs index c7f51179..3635c220 100644 --- a/src/RvtIO/Families/FamilyRelationReader.cs +++ b/src/RvtIO/Families/FamilyRelationReader.cs @@ -22,6 +22,16 @@ internal static class FamilyRelationReader private sealed class Unread(string detail) : Exception(detail); + /// The curve an element index of a sketch constraint names among the of the curves + /// of the sketch, or null. The index follows four objects of the sketch and its curves, and + /// counts the filled places only. Checked against the stored geometry of sketches without points. + internal static int? ConstrainedCurve(long element, long absorbed, IReadOnlyList places) + { + long index = element - 4 - absorbed; + return index >= 0 && index < places.Count + ? places.Where(place => place != null).Skip((int)index).FirstOrDefault() : null; + } + /// A field the reader needs that a class of the schema lacks: another version of Revit may name it otherwise, /// and then nothing would be read without a sign of it, so no association would refuse a form. Null when there is /// none; a class the schema lacks has no records. @@ -68,7 +78,7 @@ private sealed class Unread(string detail) : Exception(detail); /// Counted arrays that are read whole besides the arrays of references to elements. private static readonly HashSet WholeArrays = ["ElementExtrusionHelper.m_pCurveLoops", "CurveLoop.m_curves", "VarSketchConstrObj.m_constrElems", "VarSketch.m_elemRecs", "VarSketch.m_pointRecs", - "FamilySymbol.m_refFaces"]; + "Sketch.m_absorbedCurves", "FamilySymbol.m_refFaces"]; /// One walked record, with its captured values by the object (slot) that holds them; -1 is the record /// itself. @@ -121,10 +131,15 @@ public int Target(WideBlockWalker.Capture pointer) => public int Pointer(string name, int slot = -1) => Target(Find(name, slot) ?? throw Missing(name)); /// The slots of a counted array of pointers, all of them. - public int[] Pointers(string name, int slot) + public int[] Pointers(string name, int slot) => + [.. Places(name, slot).Select(place => place ?? throw Missing(name))]; + + /// The places of a counted array of pointers: the slot each one queued, null for an empty one. + public int?[] Places(string name, int slot) { var items = _slots[slot].Where(item => item.Name.StartsWith(name + "@", StringComparison.Ordinal)) - .Select(item => Target(item.Value)).ToArray(); + .Select(item => item.Value is { Kind: WideBlockWalker.CaptureKind.PointerClass, Integer: 0 } + ? (int?)null : Target(item.Value)).ToArray(); return items.Length == Integer(name + "#", slot) ? items : throw Missing(name); } } @@ -224,7 +239,7 @@ private sealed class Reader(RootStorage root, IReadOnlyDictionary else if (record.ClassName == "CurveElem") lines.Add(Line(record, joints)); else if (record.ClassName is "LinearDimString" or "Alignment") dimensions.Add(Dimension(record, driven)); else if (record.ClassName == "RadialDim") radials.Add(Radial(record, driven)); - else if (record.ClassName == "AngularDim") turns.Add(Angular(record, driven)); + else if (record.ClassName == "AngularDim") turns.AddRange(Angular(record, driven)); else if (record.ClassName is "RefPlane" or "Level") planes.Add(Plane(record)); else if (TfClassNames.IsSubclassOf(record.ClassName, "HostObj")) planes.Add(new(record.Key, record.ClassName, 0, [], [])); @@ -270,7 +285,9 @@ private sealed class Reader(RootStorage root, IReadOnlyDictionary return new(dimensions, lines, joints, constraints, planes, extrusions, [.. referrers], associations, formulas, _unsupported, radials, angles, _own.Values.Where(record => record.ClassName == "ControlIconElem").Select(record => record.Key).ToHashSet(), - revolutions, combinations, instances, symbols, turns); + revolutions, combinations, instances, symbols, turns, + facts.Where(fact => FamilyContent.IsUndrawnForm(fact)).Select(fact => fact.ElementId).ToHashSet(), + facts.Where(IsImport).Select(fact => fact.ElementId).ToHashSet()); } private static bool Holds(List? arguments, int reference) => @@ -336,13 +353,18 @@ private static bool IsJoinedShape(FamilyElementFacts fact, IReadOnlyDictionary byId.TryGetValue(member, out var form) && IsRecomputed(form)); + /// An imported drawing the family shows or hides, whose record is read: it stands where the file has it. + private bool IsImport(FamilyElementFacts fact) => fact.ClassName == FamilyRules.ImportClass && _own.ContainsKey(fact.ElementId) + && FamilyContent.Classify(fact).Kind is FamilyContentKind.Shown or FamilyContentKind.Hidden; + // Everything else that is shown, in this type or in another, cannot be computed. private void AddShownContent(IReadOnlyList facts, IReadOnlyDictionary byId) { foreach (var fact in facts) { if (!(fact.IsForm || fact.HasGeometry) || FamilyRules.IsNeverShown(fact.ClassName) - || fact.DrawnInViewsOnly || fact.PlacesOwnFormsOnly || IsRecomputed(fact) || IsJoinedShape(fact, byId)) continue; + || fact.DrawnInViewsOnly || fact.PlacesOwnFormsOnly || IsRecomputed(fact) || IsJoinedShape(fact, byId) + || IsImport(fact) && !fact.CutByOwnStep) continue; if (fact.CutByOwnStep) _unsupported.Add($"cut of {fact.ElementId}"); // A void is not drawn by itself. else if (!fact.Cutting && (fact.ShownInFine != false || fact.CombinationMember)) @@ -414,7 +436,8 @@ private FamilySymbolRecord Symbol(Record record) var associations = new List(); Associations(record, associations); var planes = new Dictionary(); - foreach (int face in record.Pointers("FamilySymbol.m_refFaces", -1)) + // A place without a face gives nothing to align to. + foreach (int face in record.Places("FamilySymbol.m_refFaces", -1).OfType()) { int surface = record.Pointer("Face.m_pSurf", face); if (record.SlotClass(surface) != "Plane") continue; @@ -484,17 +507,17 @@ private IEnumerable ArcEndAngles(Record sketch) { var constraints = sketch.Slots.Where(i => sketch.SlotClass(i) == "VarSketchArcEndAngleConstrObj").ToList(); if (constraints.Count == 0) yield break; - // A constraint names its curve by an index that counts the curves of the sketch and four more objects ahead of - // them (measured on sketches of up to 20 curves, none with points); the curve it names must be an arc. - int[] curves = sketch.Pointers("VarSketch.m_elemRecs", -1); + // A constraint names its curve by an element index (see ConstrainedCurve); the curve it names must be an arc. + var places = sketch.Places("VarSketch.m_elemRecs", -1); + long absorbed = sketch.Integer("Sketch.m_absorbedCurves#", -1); if (sketch.Integer("VarSketch.m_pointRecs#", -1) != 0) throw new Unread($"points of sketch {sketch.Key}"); foreach (int slot in constraints) { if (sketch.Integer("VarSketchConstrObj.m_constrElems#", slot) != 1) throw new Unread($"arc end angle of sketch {sketch.Key}"); - long index = sketch.Integer("VarSketchConstrObj.m_constrElems@0", slot) - curves.Length - 4; - if (index < 0 || index >= curves.Length || sketch.SlotClass(curves[index]) != "VarSketchArcObj") + if (ConstrainedCurve(sketch.Integer("VarSketchConstrObj.m_constrElems@0", slot), absorbed, places) is not int curve + || sketch.SlotClass(curve) != "VarSketchArcObj") throw new Unread($"arc end angle of sketch {sketch.Key}"); - yield return new(sketch.Key, Referenced(sketch.Integer("VarSketchObj.m_objId", curves[index])), + yield return new(sketch.Key, Referenced(sketch.Integer("VarSketchObj.m_objId", curve)), (int)sketch.Integer("VarSketchArcEndAngleConstrObj.m_end", slot)); } } @@ -559,13 +582,15 @@ private FamilyRadialDimension Radial(Record record, Dictionary _styleTypes.GetValueOrDefault(style, -1)); } - /// An angular dimension: one segment and the two lines or planes it measures between. - private FamilyAngularDimension Angular(Record record, Dictionary> driven) + /// An angular dimension: its segments, each an angle between two of the lines or planes it measures in turn. + private IEnumerable Angular(Record record, Dictionary> driven) { var (held, references) = Segments(record); - if (held.Count != 1 || references.Count != 2) throw new Unread($"segments of dimension {record.Key}"); - return new(record.Key, references, ParameterKey(held[0].Parameter!.Value), held[0].Value!.Value, - record.Integer("Dimension.m_flags"), held[0].Flags!.Value, driven.GetValueOrDefault(record.Key)?.Contains(0) == true); + if (held.Count == 0 || references.Count != held.Count + 1) throw new Unread($"segments of dimension {record.Key}"); + long flags = record.Integer("Dimension.m_flags"); + return [.. held.Select((segment, i) => new FamilyAngularDimension(record.Key, [references[i], references[i + 1]], + ParameterKey(segment.Parameter!.Value), segment.Value!.Value, flags, segment.Flags!.Value, + driven.GetValueOrDefault(record.Key)?.Contains(i) == true))]; } private FamilyDimensionRecord Dimension(Record record, Dictionary> driven) @@ -706,8 +731,8 @@ private FamilyExtrusionRecord Extrusion(int key, DictionaryA revolution: its sketch, the angles of its sweep, the loops of straight lines that are its profile (each - /// closed by the joins of the lines, run from a line's start or its end as the chain goes) and the line it turns + /// A revolution: its sketch, the angles of its sweep, the loops of lines and arcs that are its profile (each + /// closed by the joins of the curves, run from a curve's start or its end as the chain goes) and the line it turns /// about. private FamilyRevolutionRecord Revolution(int key, List all, List joints) { @@ -732,7 +757,7 @@ private FamilyRevolutionRecord Revolution(int key, List all, L if (lines.Where(line => line.IsRevolutionAxis).ToArray() is not [{ IsStraight: true } axis]) throw new Unread($"axis of {key}"); var profile = lines.Where(line => !line.IsRevolutionAxis).OrderBy(line => line.Id).ToList(); - if (profile.Any(line => !line.IsStraight)) throw new Unread($"curve of revolution {key}"); + if (profile.Any(line => !line.IsStraight && line.Arc == null)) throw new Unread($"curve of revolution {key}"); // The curve that follows each end of a profile line, from the joins; a join is listed from one curve or both. var follows = new Dictionary<(int Line, int End), (int Line, int End)>(); diff --git a/src/RvtIO/Families/FamilyRevolutionBuilder.cs b/src/RvtIO/Families/FamilyRevolutionBuilder.cs index b161be7e..007b9a95 100644 --- a/src/RvtIO/Families/FamilyRevolutionBuilder.cs +++ b/src/RvtIO/Families/FamilyRevolutionBuilder.cs @@ -5,8 +5,9 @@ namespace RvtIO.Families; /// /// The faces of a revolution for solved variable values, and the checks of its profile. A line of a loop turned a whole /// turn about the axis is a surface of revolution: a cylinder when it runs along the axis, a plane (a ring or a disc) when -/// it runs across it, a cone otherwise; a line on the axis makes none. The surfaces are cut into equal -/// turns, so that the faces of neighbouring surfaces share their corners. A loop inside an odd number of loops is a hole. +/// it runs across it, a cone otherwise; a line on the axis makes none; an arc of a loop turns into a torus or a sphere. The +/// surfaces are cut into equal turns, so that the faces of neighbouring surfaces share their corners; +/// an arc is cut along the profile too. A loop inside an odd number of loops is a hole. /// internal static class FamilyRevolutionBuilder { @@ -16,6 +17,11 @@ internal static class FamilyRevolutionBuilder /// surfaces of the cone sample of the corpus. public const int Facets = 18; + /// The facets of a turn an arc of a profile is cut into at most when shown: 6 degrees, the angle a curve of a + /// surface of the file is left uncut at (). Cut as fine as the turn about + /// the axis, the facets of the two multiply into far more triangles than the shape needs. + public const int ProfileFacets = 60; + private static int Component(FamilyVertex vertex, int axis) => axis == 0 ? vertex.X : axis == 1 ? vertex.Y : vertex.Z; /// The corners of each loop as (distance from the axis along the in-plane axis across it, signed; position along @@ -28,6 +34,36 @@ internal static class FamilyRevolutionBuilder .Select(corner => (positions[Component(corner, across)] - axis, positions[Component(corner, revolution.Axis)])).ToArray())]; } + // The loops as Profiles, with the points between the ends of the arcs; Segments[p] is the curve of the loop whose outline + // edge starts at point p. + private static List<((double D, double V)[] Points, int[] Segments)> Outlines(FamilyRevolution revolution, + IReadOnlyList positions, int facetsPerTurn = 0) + { + double axis = positions[revolution.AxisPosition]; + // An arc is in the two axes that follow the normal; one of them is across the axis of the turn, the other along it. + bool acrossFirst = AcrossFirst(revolution); + return [.. Profiles(revolution, positions).Select((loop, l) => + { + var points = new List<(double D, double V)>(); + var segments = new List(); + for (int i = 0; i < loop.Length; i++) + { + points.Add(loop[i]); + segments.Add(i); + if (revolution.Arcs?[l][i] is not { } arc) continue; + foreach (var (u, v) in FamilyContourChecks.Between(arc, positions, facetsPerTurn)) + { + points.Add(acrossFirst ? (u - axis, v) : (v - axis, u)); + segments.Add(i); + } + } + return (points.ToArray(), segments.ToArray()); + })]; + } + + private static bool AcrossFirst(FamilyRevolution revolution) => + 3 - revolution.Axis - revolution.Normal == (revolution.Normal + 1) % 3; + // The sign of the side of the axis the profile stands on (the first corner off the axis); 0 when all lie on it. private static int SideOfAxis(List<(double D, double V)[]> loops) => loops.SelectMany(loop => loop).Select(corner => Math.Abs(corner.D) > Tolerance ? Math.Sign(corner.D) : 0) @@ -45,8 +81,11 @@ private static double Area((double D, double V)[] loop) => /// lies inside what. internal static bool Holds(FamilyRevolution revolution, IReadOnlyList positions, IReadOnlyList stored) { - var loops = Profiles(revolution, positions); - var saved = Profiles(revolution, stored); + // A radius that is not above zero is no arc. + foreach (var arc in (revolution.Arcs ?? []).SelectMany(loop => loop).OfType()) + if (!(positions[arc.Radius] > Tolerance && double.IsFinite(positions[arc.Radius]))) return false; + var loops = Outlines(revolution, positions).Select(outline => outline.Points).ToList(); + var saved = Outlines(revolution, stored).Select(outline => outline.Points).ToList(); // Every comparison is false for a position that is not a number. if (!loops.Concat(saved).SelectMany(loop => loop).All(corner => double.IsFinite(corner.D) && double.IsFinite(corner.V))) return false; @@ -107,13 +146,15 @@ bool On((double D, double V) s, (double D, double V) e, (double D, double V) p) return On(c, d, a) || On(c, d, b) || On(a, b, c) || On(a, b, d); } - /// A line of a loop that is not on the axis: the face key, its ends (distance from the axis, signed; position along - /// it) and the way out of the solid in the plane of the profile (along the distance, along the axis). + /// An edge of an outline that is not on the axis: the face key of its curve, its ends (distance from the axis, + /// signed; position along it) and the way out of the solid in the plane of the profile (along the distance, along the + /// axis). private readonly record struct Side(FamilyFaceKey Key, double D1, double V1, double D2, double V2, double OutD, double OutV); - private static List Sides(FamilyRevolution revolution, IReadOnlyList positions) + private static List Sides(FamilyRevolution revolution, IReadOnlyList positions, int facetsPerTurn) { - var profiles = Profiles(revolution, positions); + var outlines = Outlines(revolution, positions, facetsPerTurn); + var profiles = outlines.Select(outline => outline.Points).ToList(); var nesting = FamilyContourChecks.Nesting(OneSide(profiles, SideOfAxis(profiles))); var sides = new List(); for (int l = 0; l < profiles.Count; l++) @@ -128,17 +169,18 @@ private static List Sides(FamilyRevolution revolution, IReadOnlyListA face for each line of each loop that is not on the axis (the cylinder, ring, disc or cone is one face per - /// facet, a ring or a disc one face), in the order of the loops and their lines. Normals point out of the solid; + /// A face for each edge of each outline that is not on the axis (the cylinder or cone is one face per + /// facet, a ring or a disc one face), in the order of the loops and their curves. Normals point out of the solid; /// gives the material of each face. With above 0 a turn is cut into - /// that many facets, never into fewer than : the shape to show, where the facets of the file are the - /// shape to compare. + /// that many facets, never into fewer than , and the arcs of the profile into at most + /// a turn: the shape to show, where the facets of the file are the shape to compare. public static List Faces(FamilyRevolution revolution, IReadOnlyList positions, Func material, int facetsPerTurn = 0) { @@ -156,7 +198,7 @@ double[] Point(double d, double v, int facet) } var faces = new List(); - foreach (var (key, d1, v1, d2, v2, outD, outV) in Sides(revolution, positions)) + foreach (var (key, d1, v1, d2, v2, outD, outV) in Sides(revolution, positions, Math.Min(facetsPerTurn, ProfileFacets))) { if (Math.Abs(v2 - v1) <= Tolerance) faces.Add(Flat(Math.Abs(d1), Math.Abs(d2), v1, Math.Sign(d1 + d2) * 1.0, outV, key)); @@ -214,7 +256,7 @@ GeoFace Wound(List ring, double[] outward, FamilyFaceKey key) /// The stored face that stands for each surface of the revolution at the stored positions, or null when they are /// not the surfaces the file stores. The file cuts its round surfaces as it likes, so faces are not compared one for one: - /// every corner of every stored face lies on one surface of the revolution (the line of a loop, turned), every surface has + /// every corner of every stored face lies on one surface of the revolution (the line or arc of a loop, turned), every surface has /// stored faces that reach both its circles, the faces of a surface share one material ( when a /// parameter gives it). A corner is on the surface or inside it on a chord of a circle of it: the file cuts a circle into the /// sections of a polygon inscribed in it, and where the sections of two surfaces meet, a corner lies on a side of that polygon, @@ -227,8 +269,7 @@ GeoFace Wound(List ring, double[] outward, FamilyFaceKey key) { int axis = revolution.Axis, normal = revolution.Normal, across = 3 - axis - normal; double centre = positions[revolution.AxisPosition], plane = positions[revolution.PlanePosition]; - var surfaces = Sides(revolution, positions) - .Select(side => (Side: side, Start: (R: Math.Abs(side.D1), V: side.V1), End: (R: Math.Abs(side.D2), V: side.V2))).ToList(); + var surfaces = Surfaces(revolution, positions); // Every corner as the distance from the axis, the position along it and the angle about it. var polars = new List>(); @@ -242,53 +283,94 @@ GeoFace Wound(List ring, double[] outward, FamilyFaceKey key) return (Math.Sqrt(x * x + y * y), corner[axis], Math.Atan2(y, x)); })]); } - var circles = surfaces.ToDictionary(surface => surface.Side.Key, - surface => Circles(polars.SelectMany(polar => polar), surface.Start, surface.End)); + var circles = surfaces.ToDictionary(surface => surface.Key, + surface => Circles(polars.SelectMany(polar => polar), surface.Holds)); - var reached = surfaces.ToDictionary(surface => surface.Side.Key, _ => new List<(double R, double V)>()); + var reached = surfaces.ToDictionary(surface => surface.Key, _ => new List<(double R, double V)>()); var matched = new Dictionary(); for (int f = 0; f < stored.Count; f++) { var (face, polar) = (stored[f], polars[f]); - // A face on a cylinder or a cone reaches along the axis; one at a single position along it is flat, on a disc or a ring, - // though its corners lie on the circle where a cylinder ends. A face of two surfaces is no face of either. + // A face on a cylinder, a cone or a turned arc reaches along the axis; one at a single position along it is flat, on a + // disc or a ring, though its corners lie on the circle where a cylinder ends. A face of two surfaces is no face of either. double reach = polar.Max(point => point.V) - polar.Min(point => point.V); - var onSurface = surfaces.Where(surface => polar.All(point => Near((point.R, point.V), surface.Start, surface.End) - || OnChord(point, circles[surface.Side.Key])) - && (Math.Abs(surface.End.V - surface.Start.V) <= Tolerance || reach > Tolerance)).ToList(); + var onSurface = surfaces.Where(surface => polar.All(point => surface.Holds((point.R, point.V)) + || OnChord(point, circles[surface.Key])) + && (surface.Flat || reach > Tolerance)).ToList(); if (onSurface.Count != 1) return null; - var key = onSurface[0].Side.Key; + var key = onSurface[0].Key; // No material is stored as nothing or as an id that is not one. int own = Math.Max(face.RenderStyleId ?? 0, 0); if (material is int expected && own != Math.Max(expected, 0)) return null; if (!matched.TryAdd(key, face) && Math.Max(matched[key].RenderStyleId ?? 0, 0) != own) return null; reached[key].AddRange(polar.Select(point => (point.R, point.V))); } - foreach (var (side, start, end) in surfaces) + foreach (var surface in surfaces) { // An end on the axis is no corner of any face. bool Reaches((double R, double V) tip) => tip.R <= Tolerance - || reached[side.Key].Any(point => Math.Abs(point.R - tip.R) <= Tolerance && Math.Abs(point.V - tip.V) <= Tolerance); - if (!matched.ContainsKey(side.Key) || !Reaches(start) || !Reaches(end)) return null; + || reached[surface.Key].Any(point => Math.Abs(point.R - tip.R) <= Tolerance && Math.Abs(point.V - tip.V) <= Tolerance); + if (!matched.ContainsKey(surface.Key) || !Reaches(surface.Start) || !Reaches(surface.End)) return null; } return matched; } - /// The circles about the axis that corners lie on and that the line from to - /// of the profile passes through, with the angles of the corners on each, sorted. Corners that do not go + /// A curve of the profile that turns into a surface: its ends and what lies on it, each as (distance from the + /// axis, position along it); Flat for a line at one position along the axis. + private sealed record Surface(FamilyFaceKey Key, (double R, double V) Start, (double R, double V) End, + Func<(double R, double V), bool> Holds, bool Flat); + + private static List Surfaces(FamilyRevolution revolution, IReadOnlyList positions) + { + var profiles = Profiles(revolution, positions); + int side = SideOfAxis([.. Outlines(revolution, positions).Select(outline => outline.Points)]); + var surfaces = new List(); + for (int l = 0; l < profiles.Count; l++) + for (int i = 0; i < profiles[l].Length; i++) + { + var ((d1, v1), (d2, v2)) = (profiles[l][i], profiles[l][(i + 1) % profiles[l].Length]); + var arc = revolution.Arcs?[l][i]; + // A line on the axis turns into nothing. + if (arc == null && Math.Abs(d1) <= Tolerance && Math.Abs(d2) <= Tolerance) continue; + (double R, double V) start = (Math.Abs(d1), v1), end = (Math.Abs(d2), v2); + surfaces.Add(new(new(FamilyFaceKind.Side, l, i), start, end, + arc is { } turned ? point => OnArc(point, turned, revolution, positions, side) : point => Near(point, start, end), + arc == null && Math.Abs(v2 - v1) <= Tolerance)); + } + return surfaces; + } + + // Whether the point (distance from the axis, position along it) is on the arc of a profile that stands on of the axis, to the tolerance. + private static bool OnArc((double R, double V) point, FamilyArcSegment arc, FamilyRevolution revolution, + IReadOnlyList positions, int side) + { + double across = positions[revolution.AxisPosition] + side * point.R; + var (u, v) = AcrossFirst(revolution) ? (across, point.V) : (point.V, across); + double du = u - positions[arc.CenterU], dv = v - positions[arc.CenterV], radius = positions[arc.Radius]; + if (!(Math.Abs(Math.Sqrt(du * du + dv * dv) - radius) <= Tolerance)) return false; + // The angle from the start of the arc, the way it turns. + double turn = arc.Way * (Math.Atan2(dv, du) - Math.PI / 2 * arc.StartQuarter); + turn -= 2 * Math.PI * Math.Floor(turn / (2 * Math.PI)); + double slack = Tolerance / radius; + return turn <= Math.PI / 2 * arc.Quarters + slack || turn >= 2 * Math.PI - slack; + } + + /// The circles about the axis that corners lie on and that the curve of the profile holds + /// passes through, with the angles of the corners on each, sorted. Corners that do not go /// round the axis (a gap of half a turn between neighbours) make no circle: a chord between them is no side of a polygon that /// holds the axis, and says nothing of the surface. The file cuts a circle into the sections of a regular polygon and leaves a /// corner of it out where another form trims it away: when every corner of a circle is on the grid of the regular polygon whose /// step is the smallest gap between them (a whole number of sections to the turn), that polygon is the circle's /// (Grid is its step, otherwise 0 and the polygon is the corners there are). private static List<(double R, double V, double[] Angles, double Grid)> Circles(IEnumerable<(double R, double V, double Angle)> points, - (double R, double V) start, (double R, double V) end) + Func<(double R, double V), bool> on) { var found = new List<(double R, double V, List Angles)>(); foreach (var (r, v, angle) in points) { // A corner on the axis is on no circle. - if (r <= Tolerance || !Near((r, v), start, end)) continue; + if (r <= Tolerance || !on((r, v))) continue; int at = found.FindIndex(circle => Math.Abs(circle.R - r) <= Tolerance && Math.Abs(circle.V - v) <= Tolerance); if (at < 0) found.Add((r, v, [angle])); else found[at].Angles.Add(angle); diff --git a/src/RvtIO/Families/FamilyRules.cs b/src/RvtIO/Families/FamilyRules.cs index a6095beb..736e6eb9 100644 --- a/src/RvtIO/Families/FamilyRules.cs +++ b/src/RvtIO/Families/FamilyRules.cs @@ -13,13 +13,26 @@ internal static class FamilyRules /// The classes whose geometry is never part of the shape of a family: the hosts of a family template, lines and /// sketches, reference planes, openings (they cut a host) and type definitions. internal static bool IsNeverShown(string className) => - className is "CurveElem" or "NonPlanarSketch" or "RefPlane" or "Opening" or "FamilySymbol" + className is "CurveElem" or "NonPlanarSketch" or "RefPlane" or "Opening" or "FamilySymbol" or ImportSymbolClass || TfClassNames.IsSubclassOf(className, "HostObj"); - /// A nested instance of a category that is not a physical object (annotations, detail items): a 3D view does not - /// draw it. - internal static bool IsDrawnInViewsOnly(string className, string? category) => - TfClassNames.IsSubclassOf(className, "FamilyInstance") && ProductRules.IsNonPhysicalCategory(category); + /// The class of a drawing imported into a family: geometry of its own that places its drawing, an element of + /// . + internal const string ImportClass = "ImportInstance"; + + /// The class of the element that holds an imported drawing. + internal const string ImportSymbolClass = "MasterImportSymbol"; + + /// The fields of the record of an imported drawing that tie it to no place: its own id, its family, the level it + /// is listed at, the drawing it places and the parameter that drives it. + internal static bool TiesNoImport(string field) => field is "Element.m_id" or "Element.m_famId" or "Element.m_assocLevelId" + or "InstanceInfo.InstInfoBase.m_symbolId" or "FamilyParametrizedElemParamsCell.ParamIdPair.m_famParamId"; + + /// A nested instance of a category that is not a physical object (annotations, detail items), or a drawing + /// imported into one view: a 3D view does not draw it. + internal static bool IsDrawnInViewsOnly(string className, string? category, int? ownerViewId = null) => + className == ImportClass && ownerViewId > 0 + || TfClassNames.IsSubclassOf(className, "FamilyInstance") && ProductRules.IsNonPhysicalCategory(category); /// All the geometry of the element places other elements that are forms, as a model group places its members. A /// placed type does not count: nothing else draws it. @@ -43,6 +56,9 @@ internal static bool IsKnownDimensionFlags(bool isAlignment, long flags) => /// The bit of Dimension.m_flags of an equality dimension, whose segments keep equal lengths. internal const long EqualityDimensionFlag = 0x80; + /// The field of the record of a shared part of an instance that names the instance it is part of. + internal const string SuperInstanceField = "FamilyInstance.m_superInstanceId"; + /// The values of DimSegInfo.m_flags. A segment holds when it is locked, an equality or labelled with a family /// parameter. An unlocked one holds only what those leave free, unless the family's dimension manager lists it as driven /// (FamDimConstrMgrImpl.m_drivenDimSegs): then its value follows from others and it holds nothing. It never moves an end diff --git a/src/RvtIO/Families/FamilySavedState.cs b/src/RvtIO/Families/FamilySavedState.cs index a51892fb..1a35294a 100644 --- a/src/RvtIO/Families/FamilySavedState.cs +++ b/src/RvtIO/Families/FamilySavedState.cs @@ -126,11 +126,15 @@ private static bool Close(double[] a, double[] b) => private static bool SameLoop(List? built, List? stored) { if (built == null || stored == null || stored.Any(point => point.Length != 3)) return false; + // The same points are the same loop, also for a sliver that has all of them on one line. + if (InTurn(built, stored)) return true; var (a, b) = (Corners(built), Corners(stored)); - return a.Count == b.Count && a.Count >= 3 && Enumerable.Range(0, a.Count) - .Any(shift => Enumerable.Range(0, a.Count).All(i => Close(a[i], b[(i + shift) % b.Count]))); + return InTurn(a, b); } + private static bool InTurn(List a, List b) => a.Count == b.Count && a.Count >= 3 && Enumerable.Range(0, a.Count) + .Any(shift => Enumerable.Range(0, a.Count).All(i => Close(a[i], b[(i + shift) % b.Count]))); + private static List Corners(List loop) { var corners = loop.ToList(); diff --git a/src/RvtIO/Families/FamilySolver.cs b/src/RvtIO/Families/FamilySolver.cs index 87a62eea..10bfe393 100644 --- a/src/RvtIO/Families/FamilySolver.cs +++ b/src/RvtIO/Families/FamilySolver.cs @@ -102,6 +102,12 @@ private static IEnumerable UsedBy(FamilyRevolution revolution) if (revolution.Normal != 1) yield return vertex.Y; if (revolution.Normal != 2) yield return vertex.Z; } + foreach (var arc in (revolution.Arcs ?? []).SelectMany(loop => loop).OfType()) + { + yield return arc.CenterU; + yield return arc.CenterV; + yield return arc.Radius; + } yield return revolution.PlanePosition; yield return revolution.AxisPosition; } diff --git a/src/RvtIO/Families/FamilyTypeProgram.cs b/src/RvtIO/Families/FamilyTypeProgram.cs new file mode 100644 index 00000000..dde47c13 --- /dev/null +++ b/src/RvtIO/Families/FamilyTypeProgram.cs @@ -0,0 +1,342 @@ +using System.Globalization; +using System.IO.Compression; +using System.Runtime.InteropServices; +using System.Text; +using System.Text.Json; +using RvtIO.Meshes; +using RvtIO.Model; + +namespace RvtIO.Families; + +/// What a page needs to compute the types of a family itself: the script that computes them and what it reads about one +/// family. The script is the twin of and of what that uses. Reading the file, building the +/// model, checking the saved type and calculating the formulas of the loaded families stay here. +internal static class FamilyTypeProgram +{ + public static string Script { get; } = ReadScript(); + + /// The data of a prepared family for the types with the values , in their order, and the + /// materials a mesh of those types can have. + public static (string Data, IReadOnlyList MaterialIds) Describe(FamilyPreparation prepared, FamilyRecords? records, + IReadOnlyList> types, Func materialOf, Func isMaterial, + double unitsPerFoot, int facetsPerTurn) + { + var model = prepared.Model!; + var nested = prepared.Nested ?? new Dictionary(); + var shapes = nested.Values.Select(state => state.Shape).Distinct().ToList(); + var forms = model.Extrusions.Select(extrusion => (extrusion.MaterialParameterId, extrusion.VisibilityParameterId)) + .Concat(model.Revolutions.Select(revolution => (revolution.MaterialParameterId, revolution.VisibilityParameterId))) + .ToList(); + // The parameters of the host a page reads. + var read = model.Equations.Select(equation => equation.ParameterId) + .Concat(forms.SelectMany(form => new[] { form.MaterialParameterId, form.VisibilityParameterId })) + .Concat(model.Placements.Select(placement => placement.VisibilityParameterId)) + .OfType().Distinct().Order().ToList(); + + // The stored face of each face of a form: the material it has without a parameter, and what gives it one without its own. + var extrusions = model.Extrusions.ToDictionary(extrusion => extrusion.ElementId); + var faces = prepared.Faces!.Select(pair => + { + var ((element, key), held) = (pair.Key, pair.Value); + bool extruded = extrusions.TryGetValue(element, out var extrusion); + int own = extruded ? extrusion!.Materials.GetValueOrDefault(key) : Math.Max(held.RenderStyleId ?? 0, 0); + int fallback = materialOf(new GeoFace([0, 0, 0], [0, 0, 1]) + { + GeometryStyle = held.GeometryStyle, NestedRenderStyleId = held.NestedRenderStyleId, + }); + long? parameter = extruded ? extrusion!.MaterialParameterId + : model.Revolutions.Single(revolution => revolution.ElementId == element).MaterialParameterId; + return (Element: element, Key: key, Own: own, Fallback: fallback, Parameter: parameter); + }).ToList(); + var candidates = faces.SelectMany(face => face.Parameter is long parameter + ? types.Where(values => values.ContainsKey(parameter)).Select(values => (int)values[parameter]) + : [face.Own]) + .Distinct().Where(id => id > 0 && isMaterial(id)).Order().ToList(); + var constant = nested.ToDictionary(pair => pair.Key, + pair => pair.Value.Stored.ToDictionary(face => face.Key, face => materialOf(face.Value))); + // An instance taken from the file has its triangles already: a page only moves them. + var carried = (prepared.Carried ?? new Dictionary()).ToDictionary(pair => pair.Key, + pair => ElementMeshes.CarriedMeshes(pair.Value, materialOf, facetsPerTurn > 0)); + var used = candidates.Concat(faces.Select(face => face.Fallback)) + .Concat(constant.Values.SelectMany(materials => materials.Values)) + .Concat(carried.Values.SelectMany(instance => instance.Meshes.Select(mesh => mesh.MaterialId))) + .Where(id => id > 0).Distinct().Order().ToList(); + + var stream = new MemoryStream(); + using (var json = new Utf8JsonWriter(stream)) + { + json.WriteStartObject(); + Number("scale", unitsPerFoot); + json.WriteNumber("facets", facetsPerTurn); + Integers("materials", candidates.Select(id => (long)id)); + json.WritePropertyName("model"); + WriteModel(model); + Integers("elements", prepared.Elements.Select(id => (long)id)); + json.WriteStartObject("faces"); + foreach (var element in faces.GroupBy(face => face.Element)) + { + json.WriteStartObject(Id(element.Key)); + foreach (var face in element) Integers(Key(face.Key), [face.Own, face.Fallback]); + json.WriteEndObject(); + } + json.WriteEndObject(); + json.WriteStartArray("shapes"); + foreach (var shape in shapes) WriteModel(shape.Model); + json.WriteEndArray(); + json.WriteStartObject("nested"); + foreach (var (id, state) in nested) + { + json.WriteStartObject(Id(id)); + json.WriteNumber("shape", shapes.IndexOf(state.Shape)); + json.WriteStartObject("faces"); + foreach (var ((element, key), material) in constant[id]) json.WriteNumber($"{Id(element)} {Key(key)}", material); + json.WriteEndObject(); + json.WriteEndObject(); + } + foreach (var (id, (meshes, failed)) in carried) + { + json.WriteStartObject(Id(id)); + if (failed > 0) json.WriteNull("meshes"); + else Meshes(meshes); + json.WriteEndObject(); + } + json.WriteEndObject(); + json.WriteStartArray("types"); + foreach (var values in types) + { + json.WriteStartObject(); + Values("values", read.Where(values.ContainsKey).Select(id => KeyValuePair.Create(id, values[id]))); + json.WriteStartObject("nested"); + foreach (var placement in model.Placements) + { + if (!ElementMeshes.IsShown(placement.VisibilityParameterId, values)) continue; + json.WriteStartObject(Id(placement.ElementId)); + if (nested.TryGetValue(placement.ElementId, out var state)) + { + var (given, refusal) = FamilyNested.Values(state.Shape, placement, records!, values); + if (given == null) Refusal(refusal!); + else + { + var needed = state.Shape.Model.Equations.Select(equation => equation.ParameterId).OfType().Distinct(); + Values("values", needed.Where(given.ContainsKey).Select(id => KeyValuePair.Create(id, given[id]))); + } + } + else if (!prepared.Carried![placement.ElementId].TakesTheSame(values)) Refusal(prepared.Carried[placement.ElementId].Why); + json.WriteEndObject(); + } + json.WriteEndObject(); + json.WriteEndObject(); + } + json.WriteEndArray(); + json.WriteEndObject(); + + // JSON has no number for the values that are not finite: they are written as the text a page reads back as the number. + void Number(string? name, double value) + { + if (name != null) json.WritePropertyName(name); + if (double.IsFinite(value)) json.WriteNumberValue(value); + else json.WriteStringValue(value.ToString(CultureInfo.InvariantCulture)); + } + void Integers(string name, IEnumerable values) + { + json.WriteStartArray(name); + foreach (long value in values) json.WriteNumberValue(value); + json.WriteEndArray(); + } + void Optional(string name, long? value) + { + if (value is long present) json.WriteNumber(name, present); + else json.WriteNull(name); + } + void Values(string name, IEnumerable> values) + { + json.WriteStartObject(name); + foreach (var (id, value) in values) Number(id.ToString(CultureInfo.InvariantCulture), value); + json.WriteEndObject(); + } + void Refusal(RvtFamilyRefusal refusal) + { + json.WriteStartObject("refusal"); + json.WriteString("code", refusal.Code); + json.WriteString("detail", refusal.Detail); + json.WriteEndObject(); + } + // Triangles in the units of the page, compressed: single precision positions and normals, and the indices, each as + // its difference from the one before, which repeats in a mesh of many small faces. + void Meshes(IReadOnlyList meshes) + { + json.WriteStartArray("meshes"); + foreach (var mesh in meshes) + { + json.WriteStartObject(); + json.WriteNumber("material", mesh.MaterialId); + json.WriteNumber("vertices", mesh.Positions.Length / 3); + var steps = new int[mesh.Indices.Length]; + for (int i = 0; i < steps.Length; i++) steps[i] = mesh.Indices[i] - (i > 0 ? mesh.Indices[i - 1] : 0); + var packed = new MemoryStream(); + using (var gzip = new GZipStream(packed, CompressionLevel.Optimal, leaveOpen: true)) + { + gzip.Write(Singles(mesh.Positions, unitsPerFoot)); + gzip.Write(Singles(mesh.Normals, 1)); + gzip.Write(MemoryMarshal.AsBytes(steps)); + } + json.WriteBase64String("triangles", packed.ToArray()); + json.WriteEndObject(); + } + json.WriteEndArray(); + + static ReadOnlySpan Singles(double[] values, double scale) => + MemoryMarshal.AsBytes(Array.ConvertAll(values, value => (float)(value * scale))); + } + void Loops(IReadOnlyList> loops) + { + json.WriteStartArray("loops"); + foreach (var loop in loops) + { + json.WriteStartArray(); + foreach (var vertex in loop) + { + json.WriteStartArray(); + json.WriteNumberValue(vertex.X); + json.WriteNumberValue(vertex.Y); + json.WriteNumberValue(vertex.Z); + json.WriteEndArray(); + } + json.WriteEndArray(); + } + json.WriteEndArray(); + } + void Arcs(IReadOnlyList>? arcs) + { + if (arcs == null) + { + json.WriteNull("arcs"); + return; + } + json.WriteStartArray("arcs"); + foreach (var loop in arcs) + { + json.WriteStartArray(); + foreach (var segment in loop) + { + if (segment is not { } arc) json.WriteNullValue(); + else + { + json.WriteStartArray(); + foreach (int item in new[] { arc.CenterU, arc.CenterV, arc.Radius, arc.Way, arc.StartQuarter, arc.Quarters, arc.Facets }) + json.WriteNumberValue(item); + json.WriteEndArray(); + } + } + json.WriteEndArray(); + } + json.WriteEndArray(); + } + void WriteModel(FamilyModel written) + { + json.WriteStartObject(); + json.WriteStartArray("stored"); + foreach (var variable in written.Variables) Number(null, variable.Stored); + json.WriteEndArray(); + json.WriteStartArray("anchored"); + foreach (var variable in written.Variables) json.WriteBooleanValue(variable.Anchored); + json.WriteEndArray(); + json.WriteStartArray("equations"); + foreach (var equation in written.Equations) + { + json.WriteStartObject(); + json.WriteStartArray("terms"); + foreach (var term in equation.Terms) + { + json.WriteStartArray(); + json.WriteNumberValue(term.Variable); + json.WriteNumberValue(term.Coefficient); + json.WriteEndArray(); + } + json.WriteEndArray(); + Optional("parameter", equation.ParameterId); + json.WriteNumber("sign", equation.Sign); + Number("constant", equation.Constant); + json.WriteNumber("source", equation.SourceElementId); + json.WriteBoolean("weak", equation.IsWeak); + json.WriteBoolean("offset", equation.IsOffset); + json.WriteBoolean("mayBeEmpty", equation.MayBeEmpty); + json.WriteEndObject(); + } + json.WriteEndArray(); + json.WriteStartArray("extrusions"); + foreach (var extrusion in written.Extrusions) + { + json.WriteStartObject(); + json.WriteNumber("id", extrusion.ElementId); + Loops(extrusion.Loops); + json.WriteNumber("axis", extrusion.Axis); + json.WriteNumber("start", extrusion.Start); + json.WriteNumber("end", extrusion.End); + Arcs(extrusion.Arcs); + Optional("material", extrusion.MaterialParameterId); + Optional("visibility", extrusion.VisibilityParameterId); + json.WriteEndObject(); + } + json.WriteEndArray(); + json.WriteStartArray("revolutions"); + foreach (var revolution in written.Revolutions) + { + json.WriteStartObject(); + json.WriteNumber("id", revolution.ElementId); + Loops(revolution.Loops); + json.WriteNumber("axis", revolution.Axis); + json.WriteNumber("normal", revolution.Normal); + json.WriteNumber("axisPosition", revolution.AxisPosition); + json.WriteNumber("planePosition", revolution.PlanePosition); + Arcs(revolution.Arcs); + Optional("material", revolution.MaterialParameterId); + Optional("visibility", revolution.VisibilityParameterId); + json.WriteEndObject(); + } + json.WriteEndArray(); + json.WriteStartArray("combinations"); + foreach (var combination in written.Combinations) + { + json.WriteStartObject(); + json.WriteNumber("id", combination.ElementId); + Integers("members", combination.Members.Select(id => (long)id)); + json.WriteEndObject(); + } + json.WriteEndArray(); + json.WriteStartArray("placements"); + foreach (var placement in written.Placements) + { + json.WriteStartObject(); + json.WriteNumber("id", placement.ElementId); + Integers("origin", placement.Origin.Select(variable => (long)variable)); + json.WriteStartArray("basis"); + foreach (var vector in placement.Basis) + { + json.WriteStartArray(); + foreach (double component in vector) Number(null, component); + json.WriteEndArray(); + } + json.WriteEndArray(); + Optional("visibility", placement.VisibilityParameterId); + json.WriteEndObject(); + } + json.WriteEndArray(); + json.WriteEndObject(); + } + } + return (Encoding.UTF8.GetString(stream.ToArray()), used); + + static string Id(int id) => id.ToString(CultureInfo.InvariantCulture); + static string Key(FamilyFaceKey key) => string.Create(CultureInfo.InvariantCulture, $"{(int)key.Kind} {key.Loop} {key.Segment}"); + } + + private static string ReadScript() + { + var assembly = typeof(FamilyTypeProgram).Assembly; + using var stream = assembly.GetManifestResourceStream("RvtIO.Resources.family_types.js") + ?? throw new InvalidOperationException("The assembly lacks the script of the family types."); + using var reader = new StreamReader(stream, Encoding.UTF8); + return reader.ReadToEnd(); + } +} diff --git a/src/RvtIO/Families/NestedFamilies.cs b/src/RvtIO/Families/NestedFamilies.cs index d4850850..53f038e4 100644 --- a/src/RvtIO/Families/NestedFamilies.cs +++ b/src/RvtIO/Families/NestedFamilies.cs @@ -22,11 +22,12 @@ internal static class NestedFamilies _ => null, }; - /// The families loaded into the family document of the family , with their documents. - /// A loaded family is linked to the one block whose records hold every id its pairs name, and to the family that block's - /// records say they belong to; one that is not linked that way has no entry. Or why the records cannot be read. + /// The families loaded into the family document of the family , held by the block + /// , with their documents. A loaded family is linked to the one other block whose records hold + /// every id its pairs name, and to the family that block's records say they belong to; one that is not linked that way has + /// no entry. Or why the records cannot be read. internal static (IReadOnlyList Families, string? Error) Read(RootStorage root, - IReadOnlyDictionary? currentCopies, long hostOwnerId) + IReadOnlyDictionary? currentCopies, long hostOwnerId, int hostBlock = 0) { try { @@ -47,7 +48,7 @@ internal static (IReadOnlyList Families, string? Error) Read(RootS if (record.Channel != 102 || record.Body.Length < 2) return; if (!held.TryGetValue(record.Block, out var ids)) held[record.Block] = ids = []; ids.Add(record.Owner); - if (record.Block != 0 || record.Owner == (ulong)hostOwnerId + if (record.Block != hostBlock || record.Owner == (ulong)hostOwnerId || walker.Class(BinaryPrimitives.ReadUInt16LittleEndian(record.Body.Span))?.Name != "Family") return; byte[] data = record.Body.ToArray(); if (!families.TryAdd(record.Owner, data) && families[record.Owner] is { } first && !data.AsSpan().SequenceEqual(first)) @@ -58,33 +59,45 @@ internal static (IReadOnlyList Families, string? Error) Read(RootS foreach (var (id, body) in families) { if (body == null || PairsOf(walker, body) is not { Count: > 0 } pairs) continue; - var blocks = held.Where(block => block.Key != 0 && pairs.Values.All(nested => block.Value.Contains((ulong)nested))) + var blocks = held.Where(block => block.Key != 0 && block.Key != hostBlock + && pairs.Values.All(nested => block.Value.Contains((ulong)nested))) .Select(block => block.Key).ToArray(); if (blocks is [var only]) candidates.Add(((long)id, only, pairs)); } - // The family a block's records say they belong to: that of the ids the pairs name that belong to one. + // The families a block's records say they belong to, among those of the ids the pairs name; and the families + // loaded into the document of the block, each a family record of it with pairs of its own. var owners = candidates.ToDictionary(candidate => candidate.Family, _ => new HashSet()); var wanted = candidates.ToLookup(candidate => candidate.Block); + var loadedInto = candidates.Select(candidate => candidate.Block).Distinct().ToDictionary(block => block, _ => new HashSet()); ParameterWriter.ScanPartitions(root, tags, idWidth, (partition, record) => { if (record.Channel != 102 || record.Body.Length < 2 || !wanted[record.Block].Any()) return; if (currentCopies != null && currentCopies.TryGetValue(record.Owner, out int current) && current != partition) return; + int cls = BinaryPrimitives.ReadUInt16LittleEndian(record.Body.Span); + if (walker.Class(cls)?.Name == "Family" && PairsOf(walker, record.Body.ToArray()) is { Count: > 0 }) + loadedInto[record.Block].Add((long)record.Owner); foreach (var candidate in wanted[record.Block].Where(c => c.Pairs.ContainsValue((long)record.Owner))) { - var walk = walker.Run(record.Body.ToArray(), 0, record.Body.Length, BinaryPrimitives.ReadUInt16LittleEndian(record.Body.Span)); + var walk = walker.Run(record.Body.ToArray(), 0, record.Body.Length, cls); // An element that belongs to no family stores -1. if (walk.Captures.Where(c => c.Key == OwnerOfElement).ToArray() is [{ Integer: > 0 } owner]) owners[candidate.Family].Add(owner.Integer); } }, new ParameterWriter.Pending()); - return ([.. candidates.Where(candidate => owners[candidate.Family] is { Count: 1 }) - .Select(candidate => new LoadedFamily(candidate.Family, candidate.Block, owners[candidate.Family].Single(), candidate.Pairs))], null); + return ([.. candidates.Select(candidate => (candidate, Own: OwnFamily(owners[candidate.Family], loadedInto[candidate.Block]))) + .Where(item => item.Own != null) + .Select(item => new LoadedFamily(item.candidate.Family, item.candidate.Block, item.Own!.Value, item.candidate.Pairs))], null); } catch (Exception ex) when (ex is RvtWriteRefusedException || MalformedInput.Is(ex)) { return ([], ex.Message); } } + /// The family a document belongs to, among those its records name: the others are families loaded into it, + /// whose records the document holds too. Null when that leaves none or several. + internal static long? OwnFamily(IEnumerable owners, IReadOnlySet loadedIntoIt) => + owners.Where(owner => !loadedIntoIt.Contains(owner)).ToArray() is [var own] ? own : null; + /// The ids of the host that the record of a family pairs with ids of its document; null when the record is not /// read exactly. private static Dictionary? PairsOf(WideBlockWalker walker, byte[] body) diff --git a/src/RvtIO/Families/RvtFamilyTypes.cs b/src/RvtIO/Families/RvtFamilyTypes.cs index 9186a9c1..3c4f05d8 100644 --- a/src/RvtIO/Families/RvtFamilyTypes.cs +++ b/src/RvtIO/Families/RvtFamilyTypes.cs @@ -12,4 +12,8 @@ public sealed record RvtFamilyType(string Name, IReadOnlyList Paramet /// The types of the family of a family document, in stored order. /// The type the file was saved at, whose geometry the file holds. /// The types. -public sealed record RvtFamilyTypes(int CurrentIndex, IReadOnlyList Types); +public sealed record RvtFamilyTypes(int CurrentIndex, IReadOnlyList Types) +{ + /// The parameters every type stores the same value for, read or not. + internal IReadOnlySet StoredAlike { get; init; } = new HashSet(); +} diff --git a/src/RvtIO/Internal/ExactSurface.cs b/src/RvtIO/Internal/ExactSurface.cs new file mode 100644 index 00000000..2e30a717 --- /dev/null +++ b/src/RvtIO/Internal/ExactSurface.cs @@ -0,0 +1,131 @@ +namespace RvtIO.Internal; + +/// +/// A curved surface of the file as a surface of revolution: a profile in the half plane of the radius and the height, turned +/// about the axis Z. The profile is a line (a cylinder, a cone, a revolved line) or a circle (a revolved arc). +/// +internal sealed class ExactSurface +{ + private readonly double[] _origin, _x, _y, _z; + // The profile: with a radius of 0 the line through (_radial, _height) along the unit (_along, _up), else the circle about that point. + private readonly double _radial, _height, _along, _up, _radius; + + private ExactSurface(double[] origin, double[] x, double[] y, double[] z, double radial, double height, double along, double up, + double radius) + => (_origin, _x, _y, _z, _radial, _height, _along, _up, _radius) = (origin, x, y, z, radial, height, along, up, radius); + + /// The cylinder of radius || about the axis, or null when the frame is not of unit axes. + internal static ExactSurface? Cylinder(double[] origin, double[] x, double[] y, double[] z, double radius) + => double.IsFinite(radius) && radius != 0 ? Of(origin, x, y, z, Math.Abs(radius), 0, 0, 1, 0) : null; + + /// The cone of the half angle about the axis with its apex at the origin, or null. + internal static ExactSurface? Cone(double[] origin, double[] x, double[] y, double[] z, double halfAngle) + => double.IsFinite(halfAngle) ? Of(origin, x, y, z, 0, 0, Math.Sin(halfAngle), Math.Cos(halfAngle), 0) : null; + + /// The line through (radius, height) along (, ) turned about the axis, or null. + internal static ExactSurface? RevolvedLine(double[] origin, double[] x, double[] y, double[] z, double radial, double height, + double along, double up) + { + double length = Math.Sqrt(along * along + up * up); + return length > 0 && double.IsFinite(length) ? Of(origin, x, y, z, radial, height, along / length, up / length, 0) : null; + } + + /// The circle of about (radius, height) turned about the axis (a torus, a sphere), or null. + internal static ExactSurface? RevolvedCircle(double[] origin, double[] x, double[] y, double[] z, double radial, double height, + double radius) + => double.IsFinite(radius) && radius != 0 ? Of(origin, x, y, z, radial, height, 0, 0, Math.Abs(radius)) : null; + + private static ExactSurface? Of(double[] origin, double[] x, double[] y, double[] z, double radial, double height, double along, + double up, double radius) + { + static bool Unit(double[] a) => Math.Abs(Dot(a, a) - 1) < 1e-8; + if (!double.IsFinite(radial) || !double.IsFinite(height) || !origin.Take(3).All(double.IsFinite) + || !Unit(x) || !Unit(y) || !Unit(z) || Math.Abs(Dot(x, y)) > 1e-8 || Math.Abs(Dot(x, z)) > 1e-8 || Math.Abs(Dot(y, z)) > 1e-8) + return null; + return new((double[])origin.Clone(), (double[])x.Clone(), (double[])y.Clone(), (double[])z.Clone(), radial, height, along, up, radius); + } + + /// The surface moved by a rigid placement of twelve values (see GeoInstance.Transform). + internal ExactSurface Placed(double[] t) + { + double[] Turn(double[] a) => + [ + a[0] * t[0] + a[1] * t[1] + a[2] * t[2], a[0] * t[3] + a[1] * t[4] + a[2] * t[5], a[0] * t[6] + a[1] * t[7] + a[2] * t[8], + ]; + var origin = Turn(_origin); + for (int axis = 0; axis < 3; axis++) origin[axis] += t[9 + axis]; + return new(origin, Turn(_x), Turn(_y), Turn(_z), _radial, _height, _along, _up, _radius); + } + + /// The surface moved by a placement of twelve values that also scales it the same every way, or null for another + /// placement. + internal ExactSurface? Scaled(double[] t) + { + var moved = Placed(t); + double scale = Math.Sqrt(Dot(moved._x, moved._x)); + if (!(scale > 0)) return null; + double[] Unit(double[] a) => [a[0] / scale, a[1] / scale, a[2] / scale]; + // Axes that the placement stretches differently are no unit axes that are square to one another. + return Of(moved._origin, Unit(moved._x), Unit(moved._y), Unit(moved._z), _radial * scale, _height * scale, _along, _up, + _radius * scale); + } + + /// The unit normal of the surface beside a point, or null where it has no one: on the axis only a normal along the + /// axis is the same from every side (the apex of a cone has another along each). + internal double[]? NormalAt(double[] point) + { + if (!TryLocate(point, out _, out var normal, out _, out _)) return null; + if (Math.Abs(Dot(normal, _z)) > 1 - 1e-9) return normal; + double[] d = [point[0] - _origin[0], point[1] - _origin[1], point[2] - _origin[2]]; + double a = Dot(d, _x), b = Dot(d, _y); + // Nearer the axis than a millionth of a foot, the side the point is on is the noise of its numbers. + return a * a + b * b > 1e-12 ? normal : null; + } + + /// Where a point stands on the surface: the nearest point of it, its unit normal there, the angle about the axis (NaN for + /// a point of the axis) and, for a revolved circle, the angle along the profile (else 0). False where the nearest point is not one. + internal bool TryLocate(double[] point, out double[] nearest, out double[] normal, out double turn, out double along) + { + double[] d = [point[0] - _origin[0], point[1] - _origin[1], point[2] - _origin[2]]; + double a = Dot(d, _x), b = Dot(d, _y), h = Dot(d, _z), rho = Math.Sqrt(a * a + b * b); + bool onAxis = rho < 1e-9; + double cos = onAxis ? 1 : a / rho, sin = onAxis ? 0 : b / rho; + double best = double.PositiveInfinity, radial = 0, height = 0, outRadial = 0, outHeight = 0, side = 1; + along = 0; + // The point lies in the half plane of the profile at its own angle, or at the opposite angle with a negative radius. + foreach (double s in (ReadOnlySpan)[1, -1]) + { + double qr = s * rho - _radial, qh = h - _height, r, v, nr, nh, turned = 0; + if (_radius == 0) + { + double t = qr * _along + qh * _up; + (r, v, nr, nh) = (_radial + t * _along, _height + t * _up, -_up, _along); + } + else + { + double length = Math.Sqrt(qr * qr + qh * qh); + if (length < 1e-12) continue; + (nr, nh) = (qr / length, qh / length); + (r, v) = (_radial + _radius * nr, _height + _radius * nh); + turned = Math.Atan2(nh, nr); + } + double distance = (s * rho - r) * (s * rho - r) + (h - v) * (h - v); + // The other half plane is taken only when it is clearly nearer: for a sphere both hold the same circle, and the noise + // of the numbers would choose between them. + if (distance < best - 1e-14) (best, radial, height, outRadial, outHeight, side, along) = (distance, r, v, nr, nh, s, turned); + } + double[] Combine(double r, double v) => + [ + side * r * (cos * _x[0] + sin * _y[0]) + v * _z[0], side * r * (cos * _x[1] + sin * _y[1]) + v * _z[1], + side * r * (cos * _x[2] + sin * _y[2]) + v * _z[2], + ]; + nearest = Combine(radial, height); + for (int axis = 0; axis < 3; axis++) nearest[axis] += _origin[axis]; + normal = Combine(outRadial, outHeight); + turn = onAxis ? double.NaN : Math.Atan2(side * sin, side * cos); + // A point of the axis has no direction off it, so only a point of the surface there is one. + return double.IsFinite(best) && (!onAxis || best < 1e-14); + } + + private static double Dot(double[] a, double[] b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; +} diff --git a/src/RvtIO/Internal/GRepData.cs b/src/RvtIO/Internal/GRepData.cs index bca403df..b31f5796 100644 --- a/src/RvtIO/Internal/GRepData.cs +++ b/src/RvtIO/Internal/GRepData.cs @@ -260,6 +260,7 @@ private sealed class RareFields public double? QuadratureArea; public double? FileNormalZ; public double[]? PlaneX, PlaneY; + public ExactSurface? Surface; internal RareFields Copy() => (RareFields)MemberwiseClone(); @@ -276,7 +277,8 @@ internal static bool Same(RareFields? one, RareFields? other) && ReferenceEquals(one.AlternativeOuterVertices, other.AlternativeOuterVertices) && ReferenceEquals(one.MeshPlaneEnvelopeCorners, other.MeshPlaneEnvelopeCorners) && ReferenceEquals(one.MeshArcs, other.MeshArcs) && Nullable.Equals(one.QuadratureArea, other.QuadratureArea) && Nullable.Equals(one.FileNormalZ, other.FileNormalZ) - && ReferenceEquals(one.PlaneX, other.PlaneX) && ReferenceEquals(one.PlaneY, other.PlaneY); + && ReferenceEquals(one.PlaneX, other.PlaneX) && ReferenceEquals(one.PlaneY, other.PlaneY) + && ReferenceEquals(one.Surface, other.Surface); } } @@ -371,6 +373,14 @@ public double[]? PlaneY init { if (value != null || _rare != null) Rare.PlaneY = value; } } + /// The surface a patch of a curved face lies on, read only where the faces are to be shown round (a family file); + /// null for every other face, and for a surface that is not read. + public ExactSurface? Surface + { + get => _rare?.Surface; + set { if (value != null || _rare != null) Rare.Surface = value; } + } + public GRepFace() { } // The copy of a 'with' expression: every field, and the rare ones in an object of its own, so that a value given to the diff --git a/src/RvtIO/Internal/ParsingState.cs b/src/RvtIO/Internal/ParsingState.cs index 96106a05..aa19aa12 100644 --- a/src/RvtIO/Internal/ParsingState.cs +++ b/src/RvtIO/Internal/ParsingState.cs @@ -26,6 +26,10 @@ internal class ParsingState : JsonReadFacts /// Set with : the circular edges of the faces keep the points the file stores. internal bool FineCircularEdges { get; init; } + /// Set for a family file: the patches of its curved faces keep their surfaces, to be shown round + /// (). + internal bool KeepSurfaces { get; init; } + /// Set with : a decoded block remembers where its bytes lie until /// is chosen. internal bool KeepBlockSources { get; init; } diff --git a/src/RvtIO/Meshes/ElementMeshOptions.cs b/src/RvtIO/Meshes/ElementMeshOptions.cs index 8bdf99e4..b94b6877 100644 --- a/src/RvtIO/Meshes/ElementMeshOptions.cs +++ b/src/RvtIO/Meshes/ElementMeshOptions.cs @@ -12,4 +12,9 @@ public sealed class ElementMeshOptions /// Includes the finite reference lines of grids and levels for native cache export. public bool IncludeDatumGeometry { get; set; } + + /// For a family file, shows the round faces round: cylinders, cones and surfaces of revolution are cut finer on the + /// surfaces the file gives them and carry their normals. Other documents are not changed; default false, which keeps the flat + /// patches the file stores. + public bool SmoothFamilySurfaces { get; set; } } diff --git a/src/RvtIO/Meshes/ElementMeshes.cs b/src/RvtIO/Meshes/ElementMeshes.cs index d8db9970..1387a961 100644 --- a/src/RvtIO/Meshes/ElementMeshes.cs +++ b/src/RvtIO/Meshes/ElementMeshes.cs @@ -51,6 +51,7 @@ public static MeshSet Extract(RvtDocument document, ElementMeshOptions? options // A family document shows the content of its own family: no project rules, lines or datums apply to it. (List<(Element Element, GeometryData? Body)> Listed, HashSet Hidden, string[] Gaps)? familyShape = info.Family is { } family ? FamilyElements(info, family) : null; + bool smooth = familyShape != null && options.SmoothFamilySurfaces; if (familyShape != null) options = new ElementMeshOptions { UseSymbolPlacements = options.UseSymbolPlacements }; var drawable = familyShape?.Listed ?? DrawableElements(info, options.IncludeModelLinesAndReinforcement); var drawableIds = drawable.Select(item => item.Element.Id).ToHashSet(); @@ -59,16 +60,19 @@ public static MeshSet Extract(RvtDocument document, ElementMeshOptions? options int MaterialOf(GeoFace face) => ElementMeshes.MaterialOf(document, face); + (List Meshes, int Failed) Draw(IReadOnlyList faces, bool ghosts, bool cut = true) => + Triangulate(smooth && cut ? SurfaceRefinement.Refine(faces) : faces, MaterialOf, ghosts, smooth); + SymbolMeshes? SymbolOf(int symbolId) { if (symbolCache.TryGetValue(symbolId, out var cached)) return cached; SymbolMeshes? symbol = null; // The symbol element holds the symbol in the frame of its family; it is the placed symbol only when its own nested // symbols were placed whole. - if (document.GetElement(symbolId)?.Geometry is { PlacedSymbolClipped: false, PlacedSymbolBox: false } geometry) + if (document.GetElement(symbolId) is { Geometry: { PlacedSymbolClipped: false, PlacedSymbolBox: false } geometry } of) { bool ghosts = geometry.GhostNodes is { Count: > 0 }; - var (meshes, failed) = Triangulate(geometry.Faces, MaterialOf, ghosts); + var (meshes, failed) = Draw(geometry.Faces, ghosts, of.RootClassName != FamilyRules.ImportSymbolClass); if (meshes.Count > 0) symbol = new SymbolMeshes(meshes, failed + geometry.UntriangulatedFaces, geometry.UntriangulatedFaces, DropsUntakenNodes(geometry.Faces, ghosts), geometry.Faces.Any(face => face.GeometryNode < 0), ghosts); @@ -161,7 +165,7 @@ public static MeshSet Extract(RvtDocument document, ElementMeshOptions? options }); continue; } - var (meshes, failed) = Triangulate(body.Faces, MaterialOf, body.GhostNodes is { Count: > 0 }); + var (meshes, failed) = Draw(body.Faces, body.GhostNodes is { Count: > 0 }, element.RootClassName != FamilyRules.ImportClass); // A face left out of the reader's triangulation of its trim loops (see GeometryData.UntriangulatedFaces). failed += body.UntriangulatedFaces; elements.Add(new ElementMesh @@ -197,15 +201,16 @@ public static MeshSet Extract(RvtDocument document, ElementMeshOptions? options /// style of its Geometry node, else none (0). private static int MaterialOf(RvtDocument document, GeoFace face) { - bool IsMaterial(int id) => document.GetElement(id)?.CategoryId == MaterialsCategoryId; - if (face.RenderStyleId is > 0 and int own && IsMaterial(own)) return own; - if (face.NestedRenderStyleId is > 0 and int nested && IsMaterial(nested)) return nested; + if (face.RenderStyleId is > 0 and int own && IsMaterial(document, own)) return own; + if (face.NestedRenderStyleId is > 0 and int nested && IsMaterial(document, nested)) return nested; if (face.GeometryStyle > 0 && document.RawData.GraphicsStyles?.TryGetValue(face.GeometryStyle, out var style) == true - && style.Material > 0 && IsMaterial(style.Material)) + && style.Material > 0 && IsMaterial(document, style.Material)) return style.Material; return 0; } + private static bool IsMaterial(RvtDocument document, int id) => document.GetElement(id)?.CategoryId == MaterialsCategoryId; + /// The shape of a family file in the type of , /// computed from the relations of the family, or why it is not computed. The relations are used only when they and the /// forms built from them reproduce what the file stores for the type it was saved at. @@ -235,9 +240,40 @@ public static RvtFamilyTypeMeshes ComputeFamilyType(RvtDocument document, int ty throw new ArgumentOutOfRangeException(nameof(typeIndex), typeIndex, "The document has no family type of this index."); var prepared = family.Prepared ??= PrepareFamily(document, family, types); if (prepared.Refusal is { } refused) return new(null, refused); + return ComputeShape(prepared, family.Records, ValuesOf(types.Types[typeIndex]), face => MaterialOf(document, face), + facetsPerTurn); + } + + /// What a page needs to compute the types of + /// itself, as computes them smooth, with corners in units of which + /// make a foot; or why no type of the family is computed. The page numbers the types as + /// lists them. + /// or is null. + /// The document has no family type of one of the indexes, or + /// is not a positive number. + public static RvtFamilyTypeProgram BuildFamilyTypeProgram(RvtDocument document, IReadOnlyList typeIndexes, double unitsPerFoot) + { + ArgumentNullException.ThrowIfNull(document); + ArgumentNullException.ThrowIfNull(typeIndexes); + if (!(unitsPerFoot > 0 && double.IsFinite(unitsPerFoot))) + throw new ArgumentOutOfRangeException(nameof(unitsPerFoot), unitsPerFoot, "Not a positive number."); + if (document.RawData.Family is not { Types: { } types } family + || typeIndexes.Any(index => index < 0 || index >= types.Types.Count)) + throw new ArgumentOutOfRangeException(nameof(typeIndexes), "The document has no family type of an index."); + var prepared = family.Prepared ??= PrepareFamily(document, family, types); + if (prepared.Refusal is { } refused) return new(null, [], [], refused); + var (data, materials) = FamilyTypeProgram.Describe(prepared, family.Records, + [.. typeIndexes.Select(index => ValuesOf(types.Types[index]))], face => MaterialOf(document, face), + id => IsMaterial(document, id), unitsPerFoot, SmoothFacets); + return new(data, prepared.Elements, materials, null); + } + /// The shape of a prepared family for the values of one type. Its twin in a page is family_types.js: + /// a change here is made there too (FamilyTypeProgramTests compares them). + internal static RvtFamilyTypeMeshes ComputeShape(FamilyPreparation prepared, FamilyRecords? records, + IReadOnlyDictionary values, Func materialOf, int facetsPerTurn) + { var model = prepared.Model!; - var values = ValuesOf(types.Types[typeIndex]); RvtFamilyTypeMeshes Refused(string code, long id) => new(null, new(code, id.ToString(CultureInfo.InvariantCulture))); foreach (long visibility in model.Extrusions.Select(extrusion => extrusion.VisibilityParameterId) .Concat(model.Revolutions.Select(revolution => revolution.VisibilityParameterId)) @@ -262,6 +298,30 @@ public static RvtFamilyTypeMeshes ComputeFamilyType(RvtDocument document, int ty var elements = new List(); foreach (int id in prepared.Elements) { + // An instance taken as the file stores it: the same shape, moved to where this type has the instance. + if (prepared.Carried?.TryGetValue(id, out var carried) == true) + { + var placement = model.Placements.Single(item => item.ElementId == id); + if (!IsShown(placement.VisibilityParameterId, values)) + { + elements.Add(new ElementMesh { ElementId = id, Coverage = MeshCoverage.Complete }); + continue; + } + if (!carried.TakesTheSame(values)) return new(null, carried.Why); + var (kept, keptFailed) = CarriedMeshes(carried, materialOf, facetsPerTurn > 0); + if (keptFailed > 0) return Refused("degenerate-geometry", id); + double[] moved = [.. placement.Origin.Select(variable => positions[variable] - model.Variables[variable].Stored)]; + elements.Add(new ElementMesh + { + ElementId = id, Coverage = MeshCoverage.Complete, + Meshes = [.. kept.Select(mesh => new TriangleMesh + { + MaterialId = mesh.MaterialId, Indices = mesh.Indices, Normals = mesh.Normals, + Positions = [.. mesh.Positions.Select((value, index) => value + moved[index % 3])], + })], + }); + continue; + } // An instance of a family loaded into this one: the faces of that family, solved for what this type gives it. if (prepared.Nested?.TryGetValue(id, out var instance) == true) { @@ -271,7 +331,7 @@ public static RvtFamilyTypeMeshes ComputeFamilyType(RvtDocument document, int ty elements.Add(new ElementMesh { ElementId = id, Coverage = MeshCoverage.Complete }); continue; } - var (placed, why) = FamilyNested.Solve(instance.Shape, placement, family.Records!, values, positions); + var (placed, why) = FamilyNested.Solve(instance.Shape, placement, records!, values, positions); if (placed == null) return new(null, why); var nestedFaces = new List(); foreach (var (elementId, key, face) in FamilyNested.Faces(placed, placement, facetsPerTurn)) @@ -283,7 +343,7 @@ public static RvtFamilyTypeMeshes ComputeFamilyType(RvtDocument document, int ty face.NestedRenderStyleId = held.NestedRenderStyleId; nestedFaces.Add(face); } - var (nestedMeshes, nestedFailed) = Triangulate(nestedFaces, face => MaterialOf(document, face)); + var (nestedMeshes, nestedFailed) = Triangulate(nestedFaces, materialOf); if (nestedFailed > 0) return Refused("degenerate-geometry", id); elements.Add(new ElementMesh { ElementId = id, Meshes = nestedMeshes, Coverage = MeshCoverage.Complete }); continue; @@ -321,13 +381,58 @@ public static RvtFamilyTypeMeshes ComputeFamilyType(RvtDocument document, int ty } faces.AddRange(own); } - var (meshes, failed) = Triangulate(faces, face => MaterialOf(document, face)); + var (meshes, failed) = Triangulate(faces, materialOf); if (failed > 0) return Refused("degenerate-geometry", id); elements.Add(new ElementMesh { ElementId = id, Meshes = meshes, Coverage = MeshCoverage.Complete }); } return new(elements, null); } + /// The triangles of an instance taken from the file, where the file has it; smooth as the saved shape of a family + /// is drawn. + internal static (List Meshes, int Failed) CarriedMeshes(CarriedInstance instance, Func materialOf, + bool smooth) + { + var (meshes, failed) = Triangulate(smooth && instance.Cut ? SurfaceRefinement.Refine(instance.Faces) : instance.Faces, + materialOf, false, smooth); + return (meshes.ConvertAll(Welded), failed); + } + + // An imported drawing is hundreds of thousands of small faces that repeat their points: one vertex for each point and + // normal draws the same, and the page that holds these triangles is half the size. + private static TriangleMesh Welded(TriangleMesh mesh) + { + var numberOf = new Dictionary<(double, double, double, double, double, double), int>(); + var positions = new List(); + var normals = new List(); + var number = new int[mesh.Positions.Length / 3]; + for (int vertex = 0, at = 0; vertex < number.Length; vertex++, at += 3) + { + var key = (mesh.Positions[at], mesh.Positions[at + 1], mesh.Positions[at + 2], + mesh.Normals[at], mesh.Normals[at + 1], mesh.Normals[at + 2]); + if (!numberOf.TryGetValue(key, out number[vertex])) + { + numberOf.Add(key, number[vertex] = numberOf.Count); + positions.AddRange(mesh.Positions.AsSpan(at, 3)); + normals.AddRange(mesh.Normals.AsSpan(at, 3)); + } + } + return new() + { + MaterialId = mesh.MaterialId, Positions = [.. positions], Normals = [.. normals], + Indices = [.. mesh.Indices.Select(index => number[index])], + }; + } + + /// The faces of a body that the file holds whole, those Revit takes; null otherwise. + internal static IReadOnlyList? WholeFaces(GeometryData? body) + { + if (body == null || body.PlacedSymbolBox || body.UnresolvedSymbol || body.UntriangulatedFaces > 0 + || body.GhostNodes is { Count: > 0 }) return null; + bool dropUntaken = DropsUntakenNodes(body.Faces, false); + return body.Faces.Where(face => !dropUntaken || face.GeometryNode >= 0).ToList(); + } + /// The model of a family, once its saved state is reproduced, or why no type of it is computed. private static FamilyPreparation PrepareFamily(RvtDocument document, FamilyData family, RvtFamilyTypes types) { @@ -355,69 +460,77 @@ private static FamilyPreparation PrepareFamily(RvtDocument document, FamilyData var storedFaces = new Dictionary>(); foreach (var (element, body) in listed.Concat(document.RawData.Elements .Where(element => !element.IsBlockOnly && joined.Contains(element.Id)).Select(Held))) - { // Faces the file holds only in part cannot be compared. - if (body == null || body.PlacedSymbolBox || body.UnresolvedSymbol || body.UntriangulatedFaces > 0 - || body.GhostNodes is { Count: > 0 }) continue; - bool dropUntaken = DropsUntakenNodes(body.Faces, false); - storedFaces[element.Id] = body.Faces.Where(face => !dropUntaken || face.GeometryNode >= 0).ToList(); - } + if (WholeFaces(body) is { } whole) storedFaces[element.Id] = whole; var (matched, mismatch) = FamilySavedState.Match(model, saved, MaterialIn(saved), storedFaces); if (matched == null) return No(mismatch!.Code, mismatch.Detail); - Dictionary? nested = null; - if (model.Placements.Count > 0) - { - var (states, refused) = PrepareNested(document, family, model, saved, storedFaces); - if (states == null) return new(null, null, [], refused); - nested = states; - } - return new(model, matched, listed.Select(item => item.Element.Id).ToArray(), null) { Nested = nested }; + var preparation = new FamilyPreparation(model, matched, listed.Select(item => item.Element.Id).ToArray(), null); + return model.Placements.Count == 0 ? preparation : PrepareInstances(document, family, types, preparation, storedFaces); } - /// The loaded family of each instance placed in the family, once the instance at the saved type is the faces the file - /// stores for it: each face the loaded family gives, placed, is one of those and no stored face is left. The stored face - /// that each face of the loaded family is gives the style of that face in every type. - private static (Dictionary? States, RvtFamilyRefusal? Refusal) PrepareNested(RvtDocument document, - FamilyData family, FamilyModel model, IReadOnlyDictionary saved, - IReadOnlyDictionary> storedFaces) + /// The family with each instance placed in it: computed from its loaded family, or taken as the file stores it where + /// that family is not computed; or why one of the instances is neither. + private static FamilyPreparation PrepareInstances(RvtDocument document, FamilyData family, RvtFamilyTypes types, + FamilyPreparation prepared, IReadOnlyDictionary> storedFaces) { - (Dictionary?, RvtFamilyRefusal?) No(string code, string detail) => (null, new(code, detail)); - if (family.NestedError is { } why) return No("unsupported-construct", why); + static FamilyPreparation No(RvtFamilyRefusal refusal) => new(null, null, [], refusal); + if (family.NestedError is { } why) return No(new("unsupported-construct", why)); + var model = prepared.Model!; var records = family.Records!; - var shapes = new Dictionary(); - var states = new Dictionary(); + var saved = ValuesOf(types.Types[types.CurrentIndex]); var positions = model.Variables.Select(variable => variable.Stored).ToArray(); + var shapes = new Dictionary(); + var computed = new Dictionary(); + var carried = new Dictionary(); foreach (var placement in model.Placements) { + // An imported drawing is the same in every type that shows it. + if (records.Imports?.Contains(placement.ElementId) == true) + { + var drawing = new RvtFamilyRefusal("unsupported-construct", $"imported drawing {placement.ElementId}"); + if (!storedFaces.TryGetValue(placement.ElementId, out var drawn)) return No(drawing); + carried[placement.ElementId] = new(drawn, new Dictionary(), drawing, Cut: false); + continue; + } var families = records.Symbols!.Where(symbol => symbol.Id == placement.SymbolId || symbol.Id == placement.MasterSymbolId) .Select(symbol => symbol.FamilyId).Distinct().ToList(); - if (families.Count != 1) return No("unrecognized-reference", $"the family of instance {placement.ElementId}"); + if (families.Count != 1) return No(new("unrecognized-reference", $"the family of instance {placement.ElementId}")); long familyId = families[0]; - if (!shapes.TryGetValue(familyId, out var shape)) - { - if (family.Nested?.SingleOrDefault(candidate => candidate.Link.HostFamilyId == familyId) is not { } data) - return No("unrecognized-reference", $"the document of family {familyId}"); - var (prepared, refusal) = FamilyNested.Prepare(data, document.RawData); - if (prepared == null) return (null, refusal); - shapes[familyId] = shape = prepared; - } - var (solution, solved) = FamilyNested.Solve(shape, placement, records, saved, positions); - if (solution == null) return (null, solved); - if (!storedFaces.TryGetValue(placement.ElementId, out var held)) return No("saved-state-mismatch", $"element {placement.ElementId}"); - var left = held.ToList(); - var stored = new Dictionary<(int ElementId, FamilyFaceKey Face), GeoFace>(); - foreach (var (elementId, key, face) in FamilyNested.Faces(solution, placement)) - { - int found = left.FindIndex(candidate => FamilySavedState.SameShape(face, candidate)); - if (found < 0) return No("saved-state-mismatch", $"element {placement.ElementId}"); - // The flat faces of one curved side share a key: the first gives the style. - stored.TryAdd((elementId, key), left[found]); - left.RemoveAt(found); - } - if (left.Count > 0) return No("saved-state-mismatch", $"element {placement.ElementId}"); - states[placement.ElementId] = new(shape, stored); + if (family.Nested?.SingleOrDefault(candidate => candidate.Link.HostFamilyId == familyId) is not { } data) + return No(new("unrecognized-reference", $"the document of family {familyId}")); + if (!shapes.TryGetValue(familyId, out var shape)) shapes[familyId] = shape = FamilyNested.Prepare(data, document.RawData); + var held = storedFaces.GetValueOrDefault(placement.ElementId); + var (state, refusal) = shape.Shape == null ? (null, shape.Refusal) + : Computed(shape.Shape, placement, records, saved, positions, held); + if (state != null) computed[placement.ElementId] = state; + else if (held != null && FamilyNested.Carry(data, document.RawData, placement, records, types, positions, held, refusal!) + is { } kept) carried[placement.ElementId] = kept; + else return No(refusal!); + } + return prepared with { Nested = computed, Carried = carried }; + } + + /// An instance computed from its loaded family, once the instance at the saved type is the faces the file stores for + /// it (): each face the loaded family gives, placed, is one of those and no stored face is left. The + /// stored face that each face of the loaded family is gives the style of that face in every type. + private static (NestedPlacementState? State, RvtFamilyRefusal? Refusal) Computed(NestedShape shape, FamilyPlacement placement, + FamilyRecords records, IReadOnlyDictionary saved, IReadOnlyList positions, IReadOnlyList? held) + { + (NestedPlacementState?, RvtFamilyRefusal?) Mismatch() => (null, new("saved-state-mismatch", $"element {placement.ElementId}")); + var (solution, refusal) = FamilyNested.Solve(shape, placement, records, saved, positions); + if (solution == null) return (null, refusal); + if (held == null) return Mismatch(); + var left = held.ToList(); + var stored = new Dictionary<(int ElementId, FamilyFaceKey Face), GeoFace>(); + foreach (var (elementId, key, face) in FamilyNested.Faces(solution, placement)) + { + int found = left.FindIndex(candidate => FamilySavedState.SameShape(face, candidate)); + if (found < 0) return Mismatch(); + // The flat faces of one curved side share a key: the first gives the style. + stored.TryAdd((elementId, key), left[found]); + left.RemoveAt(found); } - return (states, null); + return left.Count > 0 ? Mismatch() : (new(shape, stored), null); } private static (Element Element, GeometryData? Body) Held(Element element) => @@ -436,7 +549,7 @@ internal static Dictionary ValuesOf(RvtFamilyType type) return values; } - private static bool IsShown(long? visibilityParameterId, IReadOnlyDictionary values) => + internal static bool IsShown(long? visibilityParameterId, IReadOnlyDictionary values) => visibilityParameterId is not long parameter || values.TryGetValue(parameter, out double value) && value != 0; /// The material of each face in a type: that of the parameter that gives it, else the stored one. @@ -457,12 +570,31 @@ internal static (List<(Element Element, GeometryData? Body)> Listed, HashSet content.Gap).OfType().Distinct() .Order(StringComparer.Ordinal).ToArray()); } + /// The faces of the drawings a body places, each placed whole, or null when one of them is not held whole. + private static GeometryData? PlacedWhole(RevitFileInfo info, GeometryData body) + { + if (body is not { PlacedSymbolClipped: false, UnresolvedSymbol: false, ExactMappedInstances: { Count: > 0 } mapped }) return null; + var faces = new List(); + foreach (var instance in mapped) + { + var symbol = info.Elements.FirstOrDefault(element => element.Id == instance.SymbolId && !element.IsBlockOnly)?.Geometry; + if (symbol is { PlacedSymbolClipped: true } || WholeFaces(symbol) is not { } whole + || ElementBuilder.TransformGeometry(new GeometryData { Faces = [.. whole] }, instance.Transform, areaOnly: false) + is not { } placed || placed.Faces.Count != whole.Count) return null; + faces.AddRange(placed.Faces); + } + return new GeometryData { Faces = faces }; + } + private static MeshVector[]? DatumLinePairs(Element element, double lowestLevel) { var plane = element.CategoryId switch @@ -650,7 +782,7 @@ private static (MeshVector Start, MeshVector End)? ModelLine(LocationCurve? curv /// 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 (). internal static (List Meshes, int Failed) Triangulate(IReadOnlyList faces, Func materialOf, - bool hasGhostNodes = false) + bool hasGhostNodes = false, bool smoothNormals = false) { bool dropUntakenNodes = DropsUntakenNodes(faces, hasGhostNodes); var builders = new List(); @@ -666,7 +798,7 @@ internal static (List Meshes, int Failed) Triangulate(IReadOnlyLis builderOfMaterial[material] = builder; builders.Add(builder); } - if (!AppendFace(face, builder)) failed++; + if (!AppendFace(face, builder, smoothNormals ? face.Surface : null)) failed++; } return (builders.Where(builder => builder.Indices.Count > 0).Select(builder => builder.ToMesh()).ToList(), failed); } @@ -674,7 +806,7 @@ internal static (List Meshes, int Failed) Triangulate(IReadOnlyLis /// Appends the triangles of one polygon face with its holes; false when the face has no polygon, its triangles do not /// cover its area, or (for a face with holes) they cover more than its area: a hole that is filled. A face of no area is drawn /// as nothing and counts as triangulated. - internal static bool AppendFace(GeoFace face, MeshBuilder target) + internal static bool AppendFace(GeoFace face, MeshBuilder target, ExactSurface? surface = null) { if (face.OuterVertices is not { Count: >= 3 } outer) return false; var rings = new List> { outer }; @@ -747,7 +879,13 @@ internal static bool AppendFace(GeoFace face, MeshBuilder target) int first = target.VertexCount; foreach (var ring in rings) foreach (var point in ring) - target.AddVertex(point, nx, ny, nz); + // The normal of a curved surface at the point, turned to the side of the face; at a point with none, that of the face. + if (surface?.NormalAt(point) is { } own) + { + double side = own[0] * nx + own[1] * ny + own[2] * nz < 0 ? -1 : 1; + target.AddVertex(point, side * own[0], side * own[1], side * own[2]); + } + else target.AddVertex(point, nx, ny, nz); foreach (var (a, b, c) in triangles) { var (pa, pb, pc) = (points[a], points[b], points[c]); @@ -800,3 +938,19 @@ public void AddTriangle(int a, int b, int c) /// type that is not computed. /// Why the type is not computed; null for one that is. public sealed record RvtFamilyTypeMeshes(IReadOnlyList? Elements, RvtFamilyRefusal? Refusal); + +/// What a page needs to compute the types of a family itself, so that it does not hold the meshes of every type. +/// The script assigns globalThis.familyTypeProgram: called with it gives a +/// promise of { count, compute(index) }, and compute gives either { elements: [{ id, meshes: [{ material, positions, +/// normals, indices }] }] } — the elements of the shape in document order, a mesh for each material (its Revit id, 0 for +/// none) — or { refusal: { code, detail } }. +/// What the script reads about the family; null when no type of it is computed. +/// The elements of the shape, by element key. +/// The materials a mesh of the types can have, by Revit id. +/// Why no type of the family is computed; null with . +public sealed record RvtFamilyTypeProgram(string? Data, IReadOnlyList ElementIds, IReadOnlyList MaterialIds, + RvtFamilyRefusal? Refusal) +{ + /// The script that computes the types; the same for every family. It holds no <!--. + public static string Script => FamilyTypeProgram.Script; +} diff --git a/src/RvtIO/Meshes/MeshSet.cs b/src/RvtIO/Meshes/MeshSet.cs index 875105c6..7a08ba7d 100644 --- a/src/RvtIO/Meshes/MeshSet.cs +++ b/src/RvtIO/Meshes/MeshSet.cs @@ -91,8 +91,8 @@ public sealed class TriangleMesh /// Three vertex indices per triangle, counter-clockwise seen from the side the normals point to. public int[] Indices { get; init; } = []; - /// Unit normal x, y, z per vertex. Vertices are not shared between faces, so a face keeps its own normal and the - /// edges between faces stay sharp. + /// Unit normal x, y, z per vertex. Faces whose normals differ do not share vertices, so a face keeps its own normal + /// and the edges between faces stay sharp. public double[] Normals { get; init; } = []; /// The material element id of the triangles, 0 for none. diff --git a/src/RvtIO/Meshes/SurfaceRefinement.cs b/src/RvtIO/Meshes/SurfaceRefinement.cs new file mode 100644 index 00000000..c2b7445a --- /dev/null +++ b/src/RvtIO/Meshes/SurfaceRefinement.cs @@ -0,0 +1,430 @@ +using RvtIO.Internal; +using RvtIO.Model; + +namespace RvtIO.Meshes; + +/// +/// Cuts the curved faces of a body finer, on the surfaces of the file, to show them round. A corner of the stored patches that +/// lies on the chord of a neighbour is first put on the surfaces. Then an edge is cut by what the faces it lies between are: +/// every new point is on all of their surfaces, and both faces take the same points, so no crack opens. An edge of a patch +/// whose surface is not read, an edge with an end off its surfaces, and one whose middle is not found on all of them, is left +/// whole. +/// +internal static class SurfaceRefinement +{ + /// The widest angle of an edge about the axis of a surface, or along its profile arc, that is left uncut. + internal const double MaxAngle = 6 * Math.PI / 180; + + // Points closer than this are one corner of the body, and a point this far from a surface is on it (feet). + private const double Tolerance = 1e-6; + + // Every cut halves the angle of an edge: no edge of a surface needs more. + private const int MaxDepth = 12; + + internal static IReadOnlyList Refine(IReadOnlyList faces, double maxAngle = MaxAngle) => + faces.Any(face => face.Surface != null) ? Cut(Settle(faces), maxAngle) : faces; + + // What a corner or an edge lies on. + private class Bounds + { + public List Curved { get; } = []; + public List<(double[] Origin, double[] Normal)> Flat { get; } = []; + // It lies on a patch whose surface is not read: it is left as the file has it. + public bool Fixed; + + public void Add(GeoFace face, (double[] Origin, double[] Normal)? plane) + { + if (face.Surface is { } surface) + { + if (!Curved.Contains(surface)) Curved.Add(surface); + } + else if (plane is { } flat) Flat.Add(flat); + else Fixed = true; + } + } + + private sealed class Edge : Bounds + { + // The corner in the middle: 0 not asked for yet, -1 none, else its number plus 1. + public int Middle; + } + + private sealed class Corner : Bounds + { + // The longest edge of a face at the corner. + public double Reach; + } + + // The corners of the faces: points closer than the tolerance are one. + private sealed class Weld + { + private readonly Dictionary<(long, long, long), List> _cells = new(); + + public List Points { get; } = []; + + public int Number(double[] point) + { + var cell = (X: (long)Math.Floor(point[0] / (4 * Tolerance)), Y: (long)Math.Floor(point[1] / (4 * Tolerance)), + Z: (long)Math.Floor(point[2] / (4 * Tolerance))); + for (long x = cell.X - 1; x <= cell.X + 1; x++) + for (long y = cell.Y - 1; y <= cell.Y + 1; y++) + for (long z = cell.Z - 1; z <= cell.Z + 1; z++) + if (_cells.TryGetValue((x, y, z), out var near)) + foreach (int index in near) + if (Distance(Points[index], point) <= Tolerance) return index; + if (!_cells.TryGetValue(cell, out var own)) _cells[cell] = own = []; + own.Add(Points.Count); + Points.Add(point); + return Points.Count - 1; + } + + // The rings of a face as numbers of corners, the same rings as its triangulation takes and in the order of its vertices; + // null for a face without a polygon of finite points. + public List[]? Rings(GeoFace face) + { + if (face.OuterVertices is not { Count: >= 3 } outer) return null; + var loops = new List> { outer }; + if (face.InnerVertices != null) loops.AddRange(face.InnerVertices.Where(ring => ring is { Count: >= 3 })); + if (loops.Any(loop => loop.Any(p => p.Length < 3 || !double.IsFinite(p[0]) || !double.IsFinite(p[1]) || !double.IsFinite(p[2])))) + return null; + return loops.Select(loop => loop.Select(Number).ToList()).ToArray(); + } + } + + private static GeoFace WithRings(GeoFace face, IReadOnlyList> rings, List points) + { + var copy = face.Copy(); + copy.OuterVertices = rings[0].Select(i => points[i]).ToList(); + copy.InnerVertices = rings.Count > 1 ? rings.Skip(1).Select(ring => ring.Select(i => points[i]).ToList()).ToList() : null; + return copy; + } + + // The stored patches can have a corner on the straight chord of a neighbour, off their surface. Such a corner is given to + // every face whose chord it lies on without naming it, and put where the surfaces and planes of its faces meet. + private static IReadOnlyList Settle(IReadOnlyList faces) + { + var weld = new Weld(); + var rings = faces.Select(weld.Rings).ToArray(); + var points = weld.Points; + var off = new Dictionary>(); // by geometry node + for (int index = 0; index < faces.Count; index++) + if (faces[index].Surface is { } surface && rings[index] is { } loops) + foreach (int corner in loops.SelectMany(loop => loop)) + if (!On(surface, points[corner])) + { + if (!off.TryGetValue(faces[index].GeometryNode, out var set)) off[faces[index].GeometryNode] = set = []; + set.Add(corner); + } + if (off.Count == 0) return faces; + + var changed = new bool[faces.Count]; + var sorted = off.ToDictionary(node => node.Key, node => + { + var numbers = node.Value.OrderBy(c => points[c][0]).ToArray(); + return (Numbers: numbers, X: numbers.Select(c => points[c][0]).ToArray()); + }); + for (int index = 0; index < faces.Count; index++) + { + if (rings[index] is not { } loops || !sorted.TryGetValue(faces[index].GeometryNode, out var near)) continue; + foreach (var loop in loops) + { + var named = loop.ToHashSet(); + // From the last edge to the first, so that what is put into one edge does not move those still to be seen. + for (int i = loop.Count - 1; i >= 0; i--) + { + double[] a = points[loop[i]], b = points[loop[(i + 1) % loop.Count]], chord = Subtract(b, a); + double length = Math.Sqrt(Dot(chord, chord)); + if (!(length > 2 * Tolerance)) continue; + int first = Array.BinarySearch(near.X, Math.Min(a[0], b[0]) - Tolerance); + var on = new List<(double At, int Corner)>(); + for (int k = first < 0 ? ~first : first; k < near.X.Length && near.X[k] <= Math.Max(a[0], b[0]) + Tolerance; k++) + { + int c = near.Numbers[k]; + var from = Subtract(points[c], a); + double at = Dot(from, chord) / (length * length); + if (at * length <= Tolerance || (1 - at) * length <= Tolerance || named.Contains(c)) continue; + if (Distance(from, [at * chord[0], at * chord[1], at * chord[2]]) <= Tolerance) on.Add((at, c)); + } + if (on.Count == 0) continue; + loop.InsertRange(i + 1, on.OrderBy(item => item.At).Select(item => item.Corner)); + changed[index] = true; + } + } + } + + var corners = off.Values.SelectMany(set => set).Distinct().ToDictionary(c => c, _ => new Corner()); + for (int index = 0; index < faces.Count; index++) + { + if (rings[index] is not { } loops) continue; + var plane = faces[index].Surface == null ? Plane(faces[index], loops, points) : null; + foreach (var loop in loops) + for (int i = 0; i < loop.Count; i++) + { + if (!corners.TryGetValue(loop[i], out var corner)) continue; + corner.Add(faces[index], plane); + corner.Reach = Math.Max(corner.Reach, Math.Max(Distance(points[loop[i]], points[loop[(i + 1) % loop.Count]]), + Distance(points[loop[i]], points[loop[(i + loop.Count - 1) % loop.Count]]))); + } + } + var moved = new List<(int Number, double[] There)>(); + foreach (var (number, corner) in corners) + // The corner cuts its chord in two, and the longer part is at least half of it; a chord of at most a quarter turn is no + // farther from its arc than a quarter of the chord: so no farther than half the longest edge at the corner. + if (!corner.Fixed && Meet(points[number], null, corner) is { } there && Distance(there, points[number]) <= corner.Reach / 2) + moved.Add((number, there)); + foreach (var (number, there) in moved) points[number] = there; + var movedNumbers = moved.Select(item => item.Number).ToHashSet(); + + return faces.Select((face, index) => rings[index] is { } loops && (changed[index] || loops.Any(loop => loop.Any(movedNumbers.Contains))) + ? WithRings(face, loops, points) : face).ToList(); + } + + private static List Cut(IReadOnlyList faces, double maxAngle) + { + var weld = new Weld(); + var corners = weld.Points; + var edges = new Dictionary<(int Node, int Low, int High), Edge>(); + + Edge Between(int node, int a, int b) + { + var key = (node, Math.Min(a, b), Math.Max(a, b)); + if (!edges.TryGetValue(key, out var edge)) edges[key] = edge = new Edge(); + return edge; + } + + // A face whose corners came to fewer than three has no area left, and is dropped: cut along its edges it would fold + // onto itself, and its triangles would span a chord that its neighbours have left for the arc. + static bool Gone(List[] loops) => loops[0].Distinct().Count() < 3; + + // What each edge of the polygons lies between. + var rings = faces.Select(weld.Rings).ToArray(); + for (int index = 0; index < faces.Count; index++) + { + if (rings[index] is not { } loops || Gone(loops)) continue; + var face = faces[index]; + var plane = face.Surface == null ? Plane(face, loops, corners) : null; + foreach (var ring in loops) + for (int i = 0; i < ring.Count; i++) + Between(face.GeometryNode, ring[i], ring[(i + 1) % ring.Count]).Add(face, plane); + } + + // The corner that cuts the edge from a to b, or -1. + int Middle(Edge edge, int node, int a, int b) + { + if (edge.Middle != 0) return edge.Middle < 0 ? -1 : edge.Middle - 1; + edge.Middle = -1; + if (edge.Fixed || edge.Curved.Count == 0) return -1; + // The two faces of an edge give its ends in either order: the middle is made from them in one order. + var (low, high) = (corners[Math.Min(a, b)], corners[Math.Max(a, b)]); + if (!edge.Curved.Any(surface => Wide(surface, low, high, maxAngle))) return -1; + // An end off a surface of the edge could not be put on it: a point between would fold the faces over one another. + if (edge.Curved.Any(surface => !On(surface, low) || !On(surface, high))) return -1; + double[] chord = Subtract(high, low), halfway = [(low[0] + high[0]) / 2, (low[1] + high[1]) / 2, (low[2] + high[2]) / 2]; + double length = Math.Sqrt(Dot(chord, chord)); + // The middle of an arc of at most half a turn is no farther from the middle of its chord than half the chord. + if (!(length > 0) || Meet(halfway, [chord[0] / length, chord[1] / length, chord[2] / length], edge) is not { } point + || Distance(point, halfway) > length / 2 + Tolerance) + return -1; + int middle = weld.Number(point); + if (middle == a || middle == b) return -1; + edge.Middle = middle + 1; + foreach (int end in (ReadOnlySpan)[a, b]) + { + var half = Between(node, end, middle); + foreach (var surface in edge.Curved) + if (!half.Curved.Contains(surface)) half.Curved.Add(surface); + half.Flat.AddRange(edge.Flat); + } + return middle; + } + + void Along(List ring, int node, int a, int b, int depth) + { + int middle = depth < MaxDepth ? Middle(Between(node, a, b), node, a, b) : -1; + if (middle < 0) { ring.Add(a); return; } + Along(ring, node, a, middle, depth + 1); + Along(ring, node, middle, b, depth + 1); + } + + var result = new List(faces.Count); + for (int index = 0; index < faces.Count; index++) + { + var face = faces[index]; + if (rings[index] is not { } loops) { result.Add(face); continue; } + if (Gone(loops)) continue; + if (face.Surface is not { } surface || !Patch(face, surface, loops)) Outline(face, loops); + } + return result; + + // A face that keeps its loops: a flat one, or a patch that is not cut inside; its edges take the new corners. + void Outline(GeoFace face, List[] loops) + { + var cut = loops.Select(loop => + { + var ring = new List(loop.Count); + for (int i = 0; i < loop.Count; i++) Along(ring, face.GeometryNode, loop[i], loop[(i + 1) % loop.Count], 0); + return ring; + }).ToList(); + result.Add(cut.Sum(ring => ring.Count) == loops.Sum(loop => loop.Count) ? face : WithRings(face, cut, corners)); + } + + // A patch of a curved surface: its triangles are cut until no edge of them is wide. False when none of it is cut. + bool Patch(GeoFace face, ExactSurface surface, List[] loops) + { + var builder = new ElementMeshes.MeshBuilder(0); + if (!ElementMeshes.AppendFace(face, builder) || builder.Indices.Count == 0) return false; + var numbers = loops.SelectMany(loop => loop).ToArray(); + int node = face.GeometryNode; + var cut = new List<(int, int, int)>(); + for (int t = 0; t < builder.Indices.Count; t += 3) + Triangle(numbers[builder.Indices[t]], numbers[builder.Indices[t + 1]], numbers[builder.Indices[t + 2]], 0); + if (cut.Count == builder.Indices.Count / 3) return false; // nothing of it is wide: it stays one polygon + foreach (var (a, b, c) in cut) + { + if (a == b || b == c || c == a) continue; + var triangle = WithRings(face, [[a, b, c]], corners); + triangle.Origin = corners[a]; + var normal = CrossProduct(Subtract(corners[b], corners[a]), Subtract(corners[c], corners[a])); + double length = Math.Sqrt(Dot(normal, normal)); + if (length > 0) triangle.Normal = [normal[0] / length, normal[1] / length, normal[2] / length]; + result.Add(triangle); + } + return true; + + int Split(int a, int b, int depth) + { + if (depth >= MaxDepth) return -1; + var edge = Between(node, a, b); + // An edge made inside the patch lies on its surface alone. + if (edge.Curved.Count == 0 && edge.Flat.Count == 0 && !edge.Fixed) edge.Curved.Add(surface); + return Middle(edge, node, a, b); + } + + void Triangle(int a, int b, int c, int depth) + { + int ab = Split(a, b, depth), bc = Split(b, c, depth), ca = Split(c, a, depth); + int next = depth + 1; + switch ((ab >= 0, bc >= 0, ca >= 0)) + { + case (true, true, true): + Triangle(a, ab, ca, next); Triangle(ab, b, bc, next); Triangle(ca, bc, c, next); Triangle(ab, bc, ca, next); + break; + case (true, true, false): Triangle(ab, b, bc, next); Triangle(a, ab, bc, next); Triangle(a, bc, c, next); break; + case (false, true, true): Triangle(bc, c, ca, next); Triangle(b, bc, ca, next); Triangle(b, ca, a, next); break; + case (true, false, true): Triangle(ca, a, ab, next); Triangle(c, ca, ab, next); Triangle(c, ab, b, next); break; + case (true, false, false): Triangle(a, ab, c, next); Triangle(ab, b, c, next); break; + case (false, true, false): Triangle(b, bc, a, next); Triangle(bc, c, a, next); break; + case (false, false, true): Triangle(c, ca, b, next); Triangle(ca, a, b, next); break; + default: cut.Add((a, b, c)); break; + } + } + } + } + + // Whether the edge from a to b turns about the axis of the surface, or along its profile arc, by more than the angle. + // shortcut: beside a pole the angle about the axis cuts finer than the surface needs (some thousands of triangles); a + // measure by the surface itself has to keep the circles of a torus round and stay bounded where surfaces touch. + private static bool Wide(ExactSurface surface, double[] a, double[] b, double maxAngle) + { + if (!surface.TryLocate(a, out _, out _, out double turnA, out double alongA)) { turnA = double.NaN; alongA = double.NaN; } + if (!surface.TryLocate(b, out _, out _, out double turnB, out double alongB)) { turnB = double.NaN; alongB = double.NaN; } + static double Apart(double one, double other) => + double.IsNaN(one) || double.IsNaN(other) ? 0 : Math.Abs(Math.IEEERemainder(one - other, 2 * Math.PI)); + return Apart(turnA, turnB) > maxAngle || Apart(alongA, alongB) > maxAngle; + } + + private static bool On(ExactSurface surface, double[] point) => + surface.TryLocate(point, out var nearest, out _, out _, out _) && Distance(nearest, point) <= Tolerance; + + // The point beside the start that lies on every surface and plane of the bounds and, with a direction, on the plane square + // to it through the start; null when Newton's steps find none. + private static double[]? Meet(double[] start, double[]? across, Bounds bounds) + { + var x = start; + var normals = new List(3); + var offsets = new List(3); + var square = new List(3); // the normals taken, made square to one another + + // Takes one condition of the step, unless it says what those taken already say (surfaces that touch). + void Take(double[] normal, double offset) + { + if (square.Count == 3) return; + double[] rest = normal; + foreach (var axis in square) + { + double part = Dot(rest, axis); + rest = [rest[0] - part * axis[0], rest[1] - part * axis[1], rest[2] - part * axis[2]]; + } + double length = Math.Sqrt(Dot(rest, rest)); + if (length < 1e-3) return; + square.Add([rest[0] / length, rest[1] / length, rest[2] / length]); + normals.Add(normal); + offsets.Add(offset); + } + + for (int step = 0; step < 50; step++) + { + normals.Clear(); offsets.Clear(); square.Clear(); + if (across != null) Take(across, Dot(Subtract(x, start), across)); + foreach (var surface in bounds.Curved) + { + if (!surface.TryLocate(x, out var nearest, out var normal, out _, out _)) return null; + Take(normal, Dot(Subtract(x, nearest), normal)); + } + foreach (var (origin, normal) in bounds.Flat) Take(normal, Dot(Subtract(x, origin), normal)); + if (offsets.All(offset => Math.Abs(offset) < 1e-11)) break; + // The shortest step that takes the offsets away is along the normals: the sum of (n_i . n_j) k_j is -offset_i. + int count = normals.Count; + var system = new double[count, count + 1]; + for (int i = 0; i < count; i++) + { + for (int j = 0; j < count; j++) system[i, j] = Dot(normals[i], normals[j]); + system[i, count] = -offsets[i]; + } + // The matrix is positive definite, as the normals are independent: no row has to be exchanged. + for (int i = 0; i < count; i++) + for (int row = 0; row < count; row++) + { + if (row == i) continue; + double factor = system[row, i] / system[i, i]; + for (int j = i; j <= count; j++) system[row, j] -= factor * system[i, j]; + } + double[] next = [x[0], x[1], x[2]]; + for (int i = 0; i < count; i++) + for (int axis = 0; axis < 3; axis++) next[axis] += system[i, count] / system[i, i] * normals[i][axis]; + x = next; + } + + if (across != null && Math.Abs(Dot(Subtract(x, start), across)) > Tolerance) return null; + if (bounds.Curved.Any(surface => !On(surface, x))) return null; + return bounds.Flat.Any(plane => Math.Abs(Dot(Subtract(x, plane.Origin), plane.Normal)) > Tolerance) ? null : x; + } + + // The plane of a face the file puts on a plane: a corner and the unit Newell normal of its outer ring; null for another + // face and when a corner of the face is off the plane. Corners in one plane do not make a face flat: those of a patch of a + // surface of revolution are in one, and such a patch can come without its surface and its mark (placed or cut). + private static (double[] Origin, double[] Normal)? Plane(GeoFace face, List[] loops, List points) + { + if (!face.PlaneSurface) return null; + var ring = loops[0]; + var origin = points[ring[0]]; + double x = 0, y = 0, z = 0; + for (int i = 0; i < ring.Count; i++) + { + double[] a = Subtract(points[ring[i]], origin), b = Subtract(points[ring[(i + 1) % ring.Count]], origin); + x += (a[1] - b[1]) * (a[2] + b[2]); + y += (a[2] - b[2]) * (a[0] + b[0]); + z += (a[0] - b[0]) * (a[1] + b[1]); + } + double length = Math.Sqrt(x * x + y * y + z * z); + if (!(length > 0)) return null; + double[] normal = [x / length, y / length, z / length]; + return loops.All(loop => loop.All(corner => Math.Abs(Dot(Subtract(points[corner], origin), normal)) <= Tolerance)) + ? (origin, normal) : null; + } + + private static double[] Subtract(double[] a, double[] b) => [a[0] - b[0], a[1] - b[1], a[2] - b[2]]; + private static double[] CrossProduct(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 Dot(double[] a, double[] b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; + private static double Distance(double[] a, double[] b) { var d = Subtract(a, b); return Math.Sqrt(Dot(d, d)); } +} diff --git a/src/RvtIO/Model/Geometry.cs b/src/RvtIO/Model/Geometry.cs index d8881294..2a68514c 100644 --- a/src/RvtIO/Model/Geometry.cs +++ b/src/RvtIO/Model/Geometry.cs @@ -244,6 +244,24 @@ private sealed class RareFields public IReadOnlyList? FirstSourceLoop; public IReadOnlyList>? SourceLoops; public List? EdgeIndices; + public RvtIO.Internal.ExactSurface? Surface; + + internal RareFields Copy() => (RareFields)MemberwiseClone(); + } + + /// The curved surface of the file a patch lies on; read only for the faces of a family document. + internal RvtIO.Internal.ExactSurface? Surface + { + get => _rare?.Surface; + set { if (value != null || _rare != null) Rare.Surface = value; } + } + + /// A face with every value of this one: giving the copy a value leaves this face as it is. + internal GeoFace Copy() + { + var copy = (GeoFace)MemberwiseClone(); + copy._rare = _rare?.Copy(); + return copy; } // Placed polygon faces expose writable zero axes, which a mesh export rarely reads. diff --git a/src/RvtIO/Parsing/BlockParser.cs b/src/RvtIO/Parsing/BlockParser.cs index 268da738..4a458b2f 100644 --- a/src/RvtIO/Parsing/BlockParser.cs +++ b/src/RvtIO/Parsing/BlockParser.cs @@ -46,7 +46,7 @@ internal static void ApplyPendingGReps(ParsingState state, List pen foreach (var job in pending) { var geometry = GRepParserV2.Parse(job.Chunk, job.Start, job.Size, shareEqualVertices: state.ShareEqualVertices, - keepSource: state.KeepBlockSources && !job.IsFamilyCut, fineCircularEdges: state.FineCircularEdges); + keepSource: state.KeepBlockSources && !job.IsFamilyCut, fineCircularEdges: state.FineCircularEdges, keepSurfaces: state.KeepSurfaces); if (geometry != null && !job.IsFamilyCut) ElementBuilder.LeaveBlockAtDecode(state, job.Eid, geometry, job.Chunk, job.Start, job.Size); if (geometry == null) unreadable?.Add(new(job.Chunk, job.Start, job.Size)); ApplyPendingGRep(state, job, geometry); @@ -64,7 +64,7 @@ internal static void ApplyPendingGReps(ParsingState state, List pen if (unreadable?.Contains(new GRepRange(job.Chunk, job.Start, job.Size)) != true) { var geometry = GRepParserV2.Parse(job.Chunk, job.Start, job.Size, shareEqualVertices: state.ShareEqualVertices, - keepSource: state.KeepBlockSources && !job.IsFamilyCut, fineCircularEdges: state.FineCircularEdges); + keepSource: state.KeepBlockSources && !job.IsFamilyCut, fineCircularEdges: state.FineCircularEdges, keepSurfaces: state.KeepSurfaces); if (geometry != null && !job.IsFamilyCut) ElementBuilder.LeaveBlockAtDecode(state, job.Eid, geometry, job.Chunk, job.Start, job.Size); decoded[index] = geometry; } diff --git a/src/RvtIO/Parsing/ElementBuilder.UndrawnFaces.cs b/src/RvtIO/Parsing/ElementBuilder.UndrawnFaces.cs index e1bd6168..8a1a3621 100644 --- a/src/RvtIO/Parsing/ElementBuilder.UndrawnFaces.cs +++ b/src/RvtIO/Parsing/ElementBuilder.UndrawnFaces.cs @@ -237,10 +237,11 @@ private static bool LeaveBlockToDemand(ParsingState state, ParsingState.UndrawnF is not { ExactMappedInstances: null, Instances: null, Vertices: null, Edges: null, Faces.Count: > 0 } geometry) return false; geometry.LeaveGeometryToDemand(FactsOf(geometry, geometry.Faces, measureShell: false), - GeometryOf(bytes, size, state.ShareEqualVertices, state.FineCircularEdges, state.SeparateFacesWithDistinctOpenings, chosen.Rebuilt)); + GeometryOf(bytes, size, state.ShareEqualVertices, state.FineCircularEdges, state.KeepSurfaces, state.SeparateFacesWithDistinctOpenings, + chosen.Rebuilt)); chosen.Prebuilt[owner] = (geometry, block); } - block.LeaveFacesToDemand(summary, BlockOf(bytes, size, state.ShareEqualVertices, state.FineCircularEdges, chosen.BlocksDecodedAgain)); + block.LeaveFacesToDemand(summary, BlockOf(bytes, size, state.ShareEqualVertices, state.FineCircularEdges, state.KeepSurfaces, chosen.BlocksDecodedAgain)); Interlocked.Increment(ref chosen.BlocksLeft.Value); return true; } @@ -276,11 +277,12 @@ private static bool NeedsTheFacesOfItsBlock(uint owner, ParsingState state) } // A method of its own: the delegate holds its arguments and nothing else, so not the state of the read. - private static Func BlockOf(byte[] bytes, uint size, bool shareEqualVertices, bool fineCircularEdges, + private static Func BlockOf(byte[] bytes, uint size, bool shareEqualVertices, bool fineCircularEdges, bool keepSurfaces, System.Runtime.CompilerServices.StrongBox decodedAgain) => () => { Interlocked.Increment(ref decodedAgain.Value); - return GRepParserV2.Parse(bytes, 0, size, shareEqualVertices: shareEqualVertices, fineCircularEdges: fineCircularEdges); + return GRepParserV2.Parse(bytes, 0, size, shareEqualVertices: shareEqualVertices, fineCircularEdges: fineCircularEdges, + keepSurfaces: keepSurfaces); }; /// What a reader on the way to a scene asks of faces that are not there (see GeometryData.FaceFacts). @@ -319,18 +321,20 @@ private static void LeaveUndrawnFacesToDemand(Element elem, uint elemId, Parsing return; // The shell of a block of hundreds of thousands of faces is long to measure and nothing on the way to a scene asks for it. geometry.LeaveGeometryToDemand(FactsOf(geometry, faces, measureShell: false), - GeometryOf(block.Bytes, block.Size, state.ShareEqualVertices, state.FineCircularEdges, state.SeparateFacesWithDistinctOpenings, undrawn.Rebuilt)); + GeometryOf(block.Bytes, block.Size, state.ShareEqualVertices, state.FineCircularEdges, state.KeepSurfaces, + state.SeparateFacesWithDistinctOpenings, undrawn.Rebuilt)); Interlocked.Increment(ref undrawn.Left.Value); Interlocked.Add(ref undrawn.LeftFaces.Value, faces.Count); } // A method of its own: the delegate holds its arguments and nothing else, so not the state of the read. private static Func GeometryOf(byte[] bytes, uint size, bool shareEqualVertices, bool fineCircularEdges, - bool separateFacesWithDistinctOpenings, + bool keepSurfaces, bool separateFacesWithDistinctOpenings, System.Runtime.CompilerServices.StrongBox rebuilt) => () => { Interlocked.Increment(ref rebuilt.Value); - return GRepParserV2.Parse(bytes, 0, size, shareEqualVertices: shareEqualVertices, fineCircularEdges: fineCircularEdges) is { } block + return GRepParserV2.Parse(bytes, 0, size, shareEqualVertices: shareEqualVertices, fineCircularEdges: fineCircularEdges, + keepSurfaces: keepSurfaces) is { } block ? BuildGeometryData(block, separateFacesWithDistinctOpenings) : null; }; diff --git a/src/RvtIO/Parsing/ElementBuilder.cs b/src/RvtIO/Parsing/ElementBuilder.cs index 2639fc05..4624c57c 100644 --- a/src/RvtIO/Parsing/ElementBuilder.cs +++ b/src/RvtIO/Parsing/ElementBuilder.cs @@ -589,7 +589,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, bool areaOnly) + internal static GeometryData? TransformGeometry(GeometryData sym, double[] t, bool areaOnly) { if (t.Length < 12) return null; double[] MapCoordinates(double x, double y, double z) => @@ -635,6 +635,7 @@ double[] MapCoordinates(double x, double y, double z) => InnerVertices = inner is { Count: > 0 } ? inner : null, Area = f.Area, PlaneSurface = f.PlaneSurface, + Surface = rigid ? f.Surface?.Placed(t) : f.Surface?.Scaled(t), NestedRenderStyleId = f.NestedRenderStyleId ?? f.RenderStyleId, GeometryNode = f.GeometryNode, NodeOrder = f.NodeOrder, @@ -696,11 +697,15 @@ double[] MapCoordinates(double x, double y, double z) => || bounds[0] > bounds[3] || bounds[1] > bounds[4] || bounds[2] > bounds[5]) return source; + // The stored box and the stored corners of what lies on it differ in their last bits: a corner this close to a plane, in + // feet, is on it. + const double OnPlane = 1e-9; + static bool Inside(double[] point, double[] box) => point.Length >= 3 - && point[0] >= box[0] && point[0] <= box[3] - && point[1] >= box[1] && point[1] <= box[4] - && point[2] >= box[2] && point[2] <= box[5]; + && point[0] >= box[0] - OnPlane && point[0] <= box[3] + OnPlane + && point[1] >= box[1] - OnPlane && point[1] <= box[4] + OnPlane + && point[2] >= box[2] - OnPlane && point[2] <= box[5] + OnPlane; foreach (var face in source.Faces) if (face.InnerVertices is { Count: > 0 } @@ -719,9 +724,12 @@ static List ClipPlane( List polygon, int axis, double limit, bool keepGreater, ref bool changed) { if (polygon.Count == 0) return polygon; - bool IsInside(double[] point) => keepGreater ? point[axis] >= limit : point[axis] <= limit; + bool IsInside(double[] point) => keepGreater ? point[axis] >= limit - OnPlane : point[axis] <= limit + OnPlane; double[] Intersect(double[] a, double[] b) { + // A side that leaves from a corner on the plane meets it at that corner. + if (Math.Abs(a[axis] - limit) <= OnPlane) return a; + if (Math.Abs(b[axis] - limit) <= OnPlane) return b; double denominator = b[axis] - a[axis]; double t = denominator == 0 ? 0 : (limit - a[axis]) / denominator; var point = new[] @@ -804,6 +812,8 @@ double[] Intersect(double[] a, double[] b) face.OuterVertices = polygon; face.Envelope = null; face.QuadratureArea = null; + // The corners a cut makes are on the box, not on the surface of the face. + if (faceChanged) face.Surface = null; result.Faces.Add(face); } else @@ -819,6 +829,7 @@ double[] Intersect(double[] a, double[] b) ring.Select(point => (double[])point.Clone()).ToList()).ToList(), Area = face.Area, PlaneSurface = face.PlaneSurface, + Surface = faceChanged ? null : face.Surface, NestedRenderStyleId = face.NestedRenderStyleId ?? face.RenderStyleId, GeometryNode = face.GeometryNode, NodeOrder = face.NodeOrder, @@ -1017,6 +1028,7 @@ List EnvelopeToCorners(double[] env, double[] origin, double[] xv, dou MeshArcs = fp.MeshArcs, QuadratureArea = fp.QuadratureArea, CurvedSurface = fp.CurvedSurface, + Surface = fp.Surface, PlaneSurface = fp.PlaneSurface, PlaneXAxis = fp.PlaneX, PlaneYAxis = fp.PlaneY, diff --git a/src/RvtIO/Parsing/GRepParserV2.CylinderPatches.cs b/src/RvtIO/Parsing/GRepParserV2.CylinderPatches.cs index 9875620d..515ad908 100644 --- a/src/RvtIO/Parsing/GRepParserV2.CylinderPatches.cs +++ b/src/RvtIO/Parsing/GRepParserV2.CylinderPatches.cs @@ -12,6 +12,29 @@ internal static partial class GRepParserV2 ? [(double[])surface.O.Clone(), (double[])surface.Z.Clone(), (double[])surface.X.Clone()] : null; + /// + /// The surface of a face as a surface of revolution, to show its patches round; null for a surface that is not read as one: + /// a plane, a ruled or Hermite surface, and a revolved profile that is not a line or a circle in the plane of the axis. + /// + internal static ExactSurface? ExactSurfaceOf(SurfaceRec surface, IReadOnlyDictionary curves) + { + if (surface.Kind == SurfKind.Cylinder) return ExactSurface.Cylinder(surface.O, surface.X, surface.Y, surface.Z, surface.R); + if (surface.Kind == SurfKind.Cone) return ExactSurface.Cone(surface.O, surface.X, surface.Y, surface.Z, surface.R); + if (surface.Kind != SurfKind.Rev || !curves.TryGetValue(surface.ProfileHandle, out var profile) + || profile.HermiteNodes != null || profile.NurbControlPoints != null) + return null; + // The profile lies in the local xz plane of the surface (see TessellateRevolution). + static bool InPlane(double[] v) => Math.Abs(v[1]) < 1e-9; + double[] centre = profile.C, x = profile.X, y = profile.Y; + if (!InPlane(centre) || !InPlane(x)) return null; + if (profile.R == 0) return ExactSurface.RevolvedLine(surface.O, surface.X, surface.Y, surface.Z, centre[0], centre[2], x[0], x[2]); + // A circle, not an ellipse: equal radii along unit axes square to each other. + bool circle = (profile.RY == 0 || Math.Abs(Math.Abs(profile.RY) - Math.Abs(profile.R)) < 1e-9) && InPlane(y) + && Math.Abs(x[0] * x[0] + x[2] * x[2] - 1) < 1e-8 && Math.Abs(y[0] * y[0] + y[2] * y[2] - 1) < 1e-8 + && Math.Abs(x[0] * y[0] + x[2] * y[2]) < 1e-8; + return circle ? ExactSurface.RevolvedCircle(surface.O, surface.X, surface.Y, surface.Z, centre[0], centre[2], profile.R) : null; + } + /// /// One patch of a tessellated cylinder or cone; is the result of /// for the surface, shared by its patches. diff --git a/src/RvtIO/Parsing/GRepParserV2.cs b/src/RvtIO/Parsing/GRepParserV2.cs index 31ecf38f..dab0182e 100644 --- a/src/RvtIO/Parsing/GRepParserV2.cs +++ b/src/RvtIO/Parsing/GRepParserV2.cs @@ -22,6 +22,9 @@ internal static partial class GRepParserV2 /// The block being decoded keeps the stored points of its circular edges (see ). [ThreadStatic] private static bool t_fineCircularEdges; + /// The patches of the curved faces of the block being decoded keep their surfaces (see ). + [ThreadStatic] private static bool t_keepSurfaces; + [ThreadStatic] private static bool t_coarseTessellation; /// Faces of the geometry being built that were left out because their trim triangulation ran out of its budget. @@ -847,18 +850,21 @@ internal enum BodyMeasure { None, VisibleVolume, RawBodies, DirectionalRawSurfac /// Remember on the block where its bytes lie (). /// Keep the points the file stores on the circular edge of a cylinder and a plane, which the low detail level /// of Revit samples more coarsely (). + /// Keep on every patch of a curved face the surface it lies on (), to show + /// the face round; asked for a family file. 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, - bool shareEqualVertices = false, bool keepSource = false, bool fineCircularEdges = false) + bool shareEqualVertices = false, bool keepSource = false, bool fineCircularEdges = false, bool keepSurfaces = false) { GRepData? block; t_fineCircularEdges = fineCircularEdges; + t_keepSurfaces = keepSurfaces; try { block = ParseLevels(d, blockStart, dataSize, nativeWallBody, requireCompleteWalk, measureSourceNodes, measureLighting, measureFills, bodyMeasure); } - finally { t_fineCircularEdges = false; } + finally { t_fineCircularEdges = false; t_keepSurfaces = false; } if (shareEqualVertices && block != null) ShareEqualVertices(block); if (keepSource && block != null) block.Source = (d, blockStart, dataSize); return block; @@ -3220,6 +3226,14 @@ void AddFractions(double start, double end, var rejectedFaceHandles = new HashSet(); var kindCounts = new Dictionary(); bool kindDiag = Environment.GetEnvironmentVariable("RVTIO_GREP_SLOW") is { Length: > 0 }; + // One surface for all the patches of a face. + var exactSurfaces = t_keepSurfaces ? new Dictionary() : null; + ExactSurface? ExactOf(uint handle) + { + if (!exactSurfaces!.TryGetValue(handle, out var exact)) + exactSurfaces[handle] = exact = handleToSurf.TryGetValue(handle, out var surface) ? ExactSurfaceOf(surface, c.Curves) : null; + return exact; + } void AddFace(uint handle, GRepFace face) { if (kindDiag) @@ -3243,6 +3257,8 @@ void AddFace(uint handle, GRepFace face) return; } if (!ReferenceEquals(boundedFace, face)) rejectedFaceHandles.Add(handle); + // A patch the bounds cut keeps no surface: the corners the cut makes are not on it. + else if (exactSurfaces != null && face.CurvedSurface) boundedFace.Surface = ExactOf(handle); var (faceNode, faceStyle) = geometryNodeByFace.GetValueOrDefault(handle, (0, -1)); bool hasFaceGInfo = c.ObjectGInfo.TryGetValue((int)handle, out var faceGInfo); // Every caller hands over a face it has just made, and the clip returns that face or a new one: nothing else diff --git a/src/RvtIO/Resources/family_types.js b/src/RvtIO/Resources/family_types.js new file mode 100644 index 00000000..d1bbd6f9 --- /dev/null +++ b/src/RvtIO/Resources/family_types.js @@ -0,0 +1,1371 @@ +// Computes the types of a Revit family in a page from the data RvtIO describes the family with. It is the twin of the C# of +// RvtIO: ElementMeshes.ComputeShape and AppendFace, FamilySolver, FamilyContourChecks, FamilyExtrusionBuilder, +// FamilyRevolutionBuilder, FamilyNested and GeTess. A change there is made here too: FamilyTypeProgramTests runs both on the +// same families and compares the refusals, the materials, the triangles and the corners. +(() => { + 'use strict'; + + const TOLERANCE = 1e-6; // feet + const FACETS = 18; // the facets the file cuts a turn of a revolution into + const PROFILE_FACETS = 60; // at most, for a turn of an arc of a profile of a revolution when shown: 6 degrees + const MESHER_TOLERANCE = -1e-10; + const START_CAP = 0; + const END_CAP = 1; + const SIDE = 2; + + const refusal = (code, detail) => ({ refusal: { code, detail: String(detail) } }); + const refusalOfIds = (code, ids) => refusal(code, [...new Set(ids)].sort((a, b) => a - b).join(', ')); + const keyOf = (kind, loop, segment) => `${kind} ${loop} ${segment}`; + const isShown = (parameter, values) => parameter === null || (values.has(parameter) && values.get(parameter) !== 0); + + // ---- The relations (FamilySolver): the coefficients are eliminated as fractions of whole numbers. + + const gcd = (a, b) => { + if (a < 0n) a = -a; + if (b < 0n) b = -b; + while (b !== 0n) [a, b] = [b, a % b]; + return a; + }; + const fraction = (n, d) => { + let common = gcd(n, d); + if (d < 0n) common = -common; + return { n: n / common, d: d / common }; + }; + const add = (a, b) => fraction(a.n * b.d + b.n * a.d, a.d * b.d); + const negate = (a) => fraction(-a.n, a.d); + const multiply = (a, b) => fraction(a.n * b.n, a.d * b.d); + const divide = (a, b) => fraction(a.n * b.d, a.d * b.n); + const numberOf = (a) => Number(a.n) / Number(a.d); + + const addTo = (row, variable, value) => { + const present = row.coefficients.get(variable); + if (present !== undefined) value = add(present, value); + if (value.n === 0n) row.coefficients.delete(variable); + else row.coefficients.set(variable, value); + }; + const subtract = (row, other, factor) => { + for (const [variable, value] of other.coefficients) addTo(row, variable, negate(multiply(factor, value))); + row.right -= numberOf(factor) * other.right; + }; + + const usedByExtrusion = (extrusion) => { + const used = []; + for (const loop of extrusion.loops) { + for (const vertex of loop) { + for (let axis = 0; axis < 3; axis++) if (extrusion.axis !== axis) used.push(vertex[axis]); + } + } + for (const loop of extrusion.arcs ?? []) { + for (const arc of loop) if (arc !== null) used.push(arc[0], arc[1], arc[2]); + } + used.push(extrusion.start, extrusion.end); + return used; + }; + const usedByRevolution = (revolution) => { + const used = []; + for (const loop of revolution.loops) { + for (const vertex of loop) { + for (let axis = 0; axis < 3; axis++) if (revolution.normal !== axis) used.push(vertex[axis]); + } + } + for (const loop of revolution.arcs ?? []) { + for (const arc of loop) if (arc !== null) used.push(arc[0], arc[1], arc[2]); + } + used.push(revolution.planePosition, revolution.axisPosition); + return used; + }; + + const solve = (model, values) => { + const targets = []; + for (const equation of model.equations) { + if (equation.parameter === null) targets.push(equation.constant); + else if (values.has(equation.parameter)) targets.push(equation.sign * values.get(equation.parameter)); + else return refusalOfIds('underdetermined', [equation.parameter]); + } + const pivots = new Map(); // reduced: each row holds its own pivot, with 1, and free variables + const reduced = (e) => { + const row = { coefficients: new Map(), right: targets[e] }; + for (const [variable, coefficient] of model.equations[e].terms) { + if (model.anchored[variable]) row.right -= coefficient * model.stored[variable]; + else addTo(row, variable, fraction(BigInt(coefficient), 1n)); + } + for (const variable of [...row.coefficients.keys()].filter((key) => pivots.has(key))) { + subtract(row, pivots.get(variable), row.coefficients.get(variable)); + } + return row; + }; + const hold = (row) => { + // A row left without variables repeats or contradicts the others: the check of the equations tells which. + if (row.coefficients.size === 0) return; + let pivot = Infinity; + for (const variable of row.coefficients.keys()) pivot = Math.min(pivot, variable); + const divisor = row.coefficients.get(pivot); + for (const [variable, value] of row.coefficients) row.coefficients.set(variable, divide(value, divisor)); + row.right /= numberOf(divisor); + for (const other of pivots.values()) { + const factor = other.coefficients.get(pivot); + if (factor !== undefined) subtract(other, row, factor); + } + pivots.set(pivot, row); + }; + + const all = model.equations.map((_, e) => e); + for (const e of all) if (!model.equations[e].weak) hold(reduced(e)); + // A weak equation about nothing the strong ones leave free yields to them. The others must all hold together. + const yielding = new Set(all.filter((e) => model.equations[e].weak && reduced(e).coefficients.size === 0)); + for (const e of all) if (model.equations[e].weak && !yielding.has(e)) hold(reduced(e)); + + const determined = (variable) => model.anchored[variable] || pivots.get(variable)?.coefficients.size === 1; + const undetermined = [ + ...model.extrusions.filter((extrusion) => !usedByExtrusion(extrusion).every(determined)), + ...model.revolutions.filter((revolution) => !usedByRevolution(revolution).every(determined)), + ...model.placements.filter((placement) => !placement.origin.every(determined)), + ].map((item) => item.id); + if (undetermined.length > 0) return refusalOfIds('underdetermined', undetermined); + + const positions = model.stored.slice(); + for (const [pivot, row] of pivots) { + let sum = 0; + for (const [variable, value] of row.coefficients) if (variable !== pivot) sum += numberOf(value) * model.stored[variable]; + positions[pivot] = row.right - sum; + } + const broken = all.filter((e) => { + if (yielding.has(e)) return false; + let sum = 0; + for (const [variable, coefficient] of model.equations[e].terms) sum += coefficient * positions[variable]; + return !(Math.abs(sum - targets[e]) <= TOLERANCE); + }).map((e) => model.equations[e].source); + return broken.length > 0 ? refusalOfIds('inconsistent', broken) : { positions }; + }; + + // ---- The profiles (FamilyContourChecks). A point of a profile is [u, v]. + + // The points between the ends of an arc, in the order it is run, where it is cut into its facets. + const between = (arc, positions, facetsPerTurn) => { + const [centreU, centreV, radius, way, startQuarter, quarters, stored] = arc; + const facets = facetsPerTurn > 0 ? Math.max(stored, Math.ceil(quarters * facetsPerTurn / 4)) : stored; + const points = []; + for (let facet = 1; facet < facets; facet++) { + // The ends lie on the axes through the centre, so the direction of the start is a multiple of a quarter turn. + const angle = Math.PI / 2 * (startQuarter + way * quarters * facet / facets); + points.push([positions[centreU] + positions[radius] * Math.cos(angle), + positions[centreV] + positions[radius] * Math.sin(angle)]); + } + return points; + }; + + const outlines = (extrusion, positions, facetsPerTurn) => { + const u = (extrusion.axis + 1) % 3; + const v = (extrusion.axis + 2) % 3; + return extrusion.loops.map((loop, l) => { + const points = []; + const segments = []; + for (let i = 0; i < loop.length; i++) { + points.push([positions[loop[i][u]], positions[loop[i][v]]]); + segments.push(i); + const arc = extrusion.arcs === null ? null : extrusion.arcs[l][i]; + if (arc === null) continue; + for (const point of between(arc, positions, facetsPerTurn)) { + points.push(point); + segments.push(i); + } + } + return { points, segments }; + }); + }; + + const contains = (loop, point) => { + let inside = false; + for (let i = 0; i < loop.length; i++) { + const a = loop[i]; + const b = loop[(i + 1) % loop.length]; + if ((a[1] > point[1]) !== (b[1] > point[1]) && point[0] < a[0] + (point[1] - a[1]) / (b[1] - a[1]) * (b[0] - a[0])) { + inside = !inside; + } + } + return inside; + }; + // nesting[i][j] is true when loop j lies inside loop i; the loops do not meet each other. + const nesting = (loops) => loops.map((outer, i) => loops.map((inner, j) => i !== j && contains(outer, inner[0]))); + const sameNesting = (a, b) => { + const first = nesting(a).flat(); + const second = nesting(b).flat(); + return first.length === second.length && first.every((value, i) => value === second[i]); + }; + + // From a point to the segment a-b, which has a length. + const distance = (point, a, b) => { + const du = b[0] - a[0]; + const dv = b[1] - a[1]; + const along = Math.min(Math.max(((point[0] - a[0]) * du + (point[1] - a[1]) * dv) / (du * du + dv * dv), 0), 1); + const x = point[0] - a[0] - along * du; + const y = point[1] - a[1] - along * dv; + return Math.sqrt(x * x + y * y); + }; + const cross = (a, b, point) => (b[0] - a[0]) * (point[1] - a[1]) - (b[1] - a[1]) * (point[0] - a[0]); + + // Every segment keeps a length and its direction, and consecutive segments of a loop do not run back along each other; + // `apart` says whether two other segments meet. + const segmentsHold = (loops, saved, apart) => { + const segments = []; + for (let l = 0; l < loops.length; l++) { + const count = loops[l].length; + for (let i = 0; i < count; i++) { + const a = loops[l][i]; + const b = loops[l][(i + 1) % count]; + const du = b[0] - a[0]; + const dv = b[1] - a[1]; + const savedA = saved[l][i]; + const savedB = saved[l][(i + 1) % count]; + // Both comparisons are false for a position that is not a number. + if (!(Math.sqrt(du * du + dv * dv) > TOLERANCE && du * (savedB[0] - savedA[0]) + dv * (savedB[1] - savedA[1]) > 0)) { + return false; + } + segments.push({ loop: l, index: i, a, b }); + } + } + for (let first = 0; first < segments.length; first++) { + for (let second = first + 1; second < segments.length; second++) { + const s = segments[first]; + const t = segments[second]; + const follows = s.loop === t.loop && (s.index + 1) % loops[s.loop].length === t.index; + const precedes = s.loop === t.loop && (t.index + 1) % loops[s.loop].length === s.index; + if (follows || precedes) { + // They share a corner; neither may run back along the other. + const before = follows ? s : t; + const after = follows ? t : s; + if (distance(before.a, after.a, after.b) <= TOLERANCE || distance(after.b, before.a, before.b) <= TOLERANCE) return false; + } else if (apart(s, t)) return false; + } + } + return true; + }; + + const extrusionHolds = (extrusion, positions, stored) => { + const height = positions[extrusion.end] - positions[extrusion.start]; + if (!(height > TOLERANCE && Number.isFinite(height))) return false; + // A radius that is not above zero is no arc. + for (const loop of extrusion.arcs ?? []) { + for (const arc of loop) if (arc !== null && !(positions[arc[2]] > TOLERANCE && Number.isFinite(positions[arc[2]]))) return false; + } + const loops = outlines(extrusion, positions, 0).map((outline) => outline.points); + const saved = outlines(extrusion, stored, 0).map((outline) => outline.points); + if (loops.some((loop) => loop.length < 3)) return false; + return segmentsHold(loops, saved, (s, t) => + (cross(s.a, s.b, t.a) * cross(s.a, s.b, t.b) < 0 && cross(t.a, t.b, s.a) * cross(t.a, t.b, s.b) < 0) + || distance(s.a, t.a, t.b) <= TOLERANCE || distance(s.b, t.a, t.b) <= TOLERANCE + || distance(t.a, s.a, s.b) <= TOLERANCE || distance(t.b, s.a, s.b) <= TOLERANCE) + && sameNesting(loops, saved); + }; + + // ---- Revolutions (FamilyRevolutionBuilder). A corner of a profile is [distance from the axis, position along it]. + + const profiles = (revolution, positions) => { + const across = 3 - revolution.axis - revolution.normal; + const axis = positions[revolution.axisPosition]; + return revolution.loops.map((loop) => loop.map((corner) => [positions[corner[across]] - axis, positions[corner[revolution.axis]]])); + }; + // The loops as `profiles`, with the points between the ends of the arcs; segments[p] is the curve of the loop whose + // outline edge starts at point p. + const profileOutlines = (revolution, positions, facetsPerTurn) => { + const axis = positions[revolution.axisPosition]; + // An arc is in the two axes that follow the normal; one of them is across the axis of the turn, the other along it. + const acrossFirst = 3 - revolution.axis - revolution.normal === (revolution.normal + 1) % 3; + return profiles(revolution, positions).map((loop, l) => { + const points = []; + const segments = []; + for (let i = 0; i < loop.length; i++) { + points.push(loop[i]); + segments.push(i); + const arc = revolution.arcs === null ? null : revolution.arcs[l][i]; + if (arc === null) continue; + for (const [u, v] of between(arc, positions, facetsPerTurn)) { + points.push(acrossFirst ? [u - axis, v] : [v - axis, u]); + segments.push(i); + } + } + return { points, segments }; + }); + }; + // The sign of the side of the axis the profile stands on (the first corner off the axis); 0 when all lie on it. + const sideOfAxis = (loops) => { + for (const loop of loops) for (const corner of loop) if (Math.abs(corner[0]) > TOLERANCE) return Math.sign(corner[0]); + return 0; + }; + // The loops as seen from the side they stand on, to tell what lies inside what. + const oneSide = (loops, side) => loops.map((loop) => loop.map((corner) => [corner[0] * side, corner[1]])); + const areaOfProfile = (loop) => { + let sum = 0; + for (let i = 0; i < loop.length; i++) { + sum += loop[i][0] * loop[(i + 1) % loop.length][1] - loop[(i + 1) % loop.length][0] * loop[i][1]; + } + return sum / 2; + }; + + // Whether the segments a-b and c-d have a point in common. + const meet = (a, b, c, d) => { + const turnOf = (o, p, q) => (p[0] - o[0]) * (q[1] - o[1]) - (p[1] - o[1]) * (q[0] - o[0]); + const d1 = turnOf(c, d, a); + const d2 = turnOf(c, d, b); + const d3 = turnOf(a, b, c); + const d4 = turnOf(a, b, d); + const scale = Math.max(1, Math.max(Math.abs(b[0] - a[0]) + Math.abs(b[1] - a[1]), Math.abs(d[0] - c[0]) + Math.abs(d[1] - c[1]))); + const eps = TOLERANCE * scale; + const opposite = (x, y) => (x > eps && y < -eps) || (x < -eps && y > eps); + if (opposite(d1, d2) && opposite(d3, d4)) return true; + // A line that touches the other, or lies along it. + const on = (s, e, p) => Math.abs(turnOf(s, e, p)) <= eps + && p[0] >= Math.min(s[0], e[0]) - TOLERANCE && p[0] <= Math.max(s[0], e[0]) + TOLERANCE + && p[1] >= Math.min(s[1], e[1]) - TOLERANCE && p[1] <= Math.max(s[1], e[1]) + TOLERANCE; + return on(c, d, a) || on(c, d, b) || on(a, b, c) || on(a, b, d); + }; + + const revolutionHolds = (revolution, positions, stored) => { + // A radius that is not above zero is no arc. + for (const loop of revolution.arcs ?? []) { + for (const arc of loop) if (arc !== null && !(positions[arc[2]] > TOLERANCE && Number.isFinite(positions[arc[2]]))) return false; + } + const loops = profileOutlines(revolution, positions, 0).map((outline) => outline.points); + const saved = profileOutlines(revolution, stored, 0).map((outline) => outline.points); + if (![...loops, ...saved].every((loop) => loop.every((corner) => Number.isFinite(corner[0]) && Number.isFinite(corner[1])))) { + return false; + } + // Loops on both sides of the axis would turn into solids that overlap. + const side = sideOfAxis(loops); + if (side === 0 || loops.some((loop) => loop.some((corner) => corner[0] * side < -TOLERANCE))) return false; + if (loops.some((loop) => loop.length < 3 || !(Math.abs(areaOfProfile(loop)) > TOLERANCE))) return false; + return segmentsHold(loops, saved, (s, t) => meet(s.a, s.b, t.a, t.b)) && sameNesting(oneSide(loops, side), oneSide(saved, side)); + }; + + const check = (model, positions, values) => { + for (const equation of model.equations) { + if (!equation.offset && equation.parameter !== null && values.has(equation.parameter) + && !(values.get(equation.parameter) > TOLERANCE + || equation.mayBeEmpty && values.get(equation.parameter) >= -TOLERANCE)) { + return refusal('degenerate-geometry', equation.parameter); + } + } + for (const extrusion of model.extrusions) { + if (!extrusionHolds(extrusion, positions, model.stored)) return refusal('degenerate-geometry', extrusion.id); + } + for (const revolution of model.revolutions) { + if (!revolutionHolds(revolution, positions, model.stored)) return refusal('degenerate-geometry', revolution.id); + } + return null; + }; + + // ---- Faces. A face is { key, outer, inner, normal }; a corner is [x, y, z]. + + const extrusionFaces = (extrusion, positions, facetsPerTurn) => { + const shapes = outlines(extrusion, positions, facetsPerTurn); + const loops = shapes.map((shape) => shape.points); + const inside = nesting(loops); + const depth = loops.map((_, loop) => inside.filter((row) => row[loop]).length); + // 1 for a loop drawn counter-clockwise seen from the end of the axis, -1 for the other way round. + const turn = loops.map((loop) => { + let sum = 0; + for (let i = 0; i < loop.length; i++) { + sum += loop[i][0] * loop[(i + 1) % loop.length][1] - loop[(i + 1) % loop.length][0] * loop[i][1]; + } + return Math.sign(sum); + }); + const pointAt = (corner, along) => { + const point = [0, 0, 0]; + point[(extrusion.axis + 1) % 3] = corner[0]; + point[(extrusion.axis + 2) % 3] = corner[1]; + point[extrusion.axis] = along; + return point; + }; + // The corners of a loop, counter-clockwise (way 1) or clockwise (way -1) seen from the end of the axis. + const ringOf = (loop, along, way) => { + const ring = loops[loop].map((corner) => pointAt(corner, along)); + if (turn[loop] !== way) ring.reverse(); + return ring; + }; + const ofArcs = (loop) => extrusion.arcs !== null && extrusion.arcs[loop].every((arc) => arc !== null); + + const start = positions[extrusion.start]; + const end = positions[extrusion.end]; + const faces = []; + for (let loop = 0; loop < loops.length; loop++) { + if (depth[loop] % 2 !== 0) continue; + const holes = loops.map((_, hole) => hole).filter((hole) => inside[loop][hole] && depth[hole] === depth[loop] + 1); + // The file stores the caps of a loop of arcs alone, a circle, facing inward, and those of the other loops outward. + const circle = ofArcs(loop) && holes.every(ofArcs); + for (const [kind, along, way] of [[START_CAP, start, -1], [END_CAP, end, 1]]) { + const facing = circle ? -way : way; + const normal = [0, 0, 0]; + normal[extrusion.axis] = facing; + faces.push({ + key: keyOf(kind, loop, -1), outer: ringOf(loop, along, facing), + inner: holes.length > 0 ? holes.map((hole) => ringOf(hole, along, -facing)) : null, normal, + }); + } + } + for (let loop = 0; loop < loops.length; loop++) { + // The right side of a segment is outside a counter-clockwise loop; the solid of a hole lies outside it. + const outward = depth[loop] % 2 === 0 ? turn[loop] : -turn[loop]; + for (let i = 0; i < loops[loop].length; i++) { + const a = loops[loop][i]; + const b = loops[loop][(i + 1) % loops[loop].length]; + const length = Math.sqrt((b[0] - a[0]) * (b[0] - a[0]) + (b[1] - a[1]) * (b[1] - a[1])); + const normal = [0, 0, 0]; + normal[(extrusion.axis + 1) % 3] = outward * (b[1] - a[1]) / length; + normal[(extrusion.axis + 2) % 3] = outward * (a[0] - b[0]) / length; + const quad = [pointAt(a, start), pointAt(b, start), pointAt(b, end), pointAt(a, end)]; + if (outward < 0) quad.reverse(); + // A curved segment is a row of flat faces, which all go by the segment. + faces.push({ key: keyOf(SIDE, loop, shapes[loop].segments[i]), outer: quad, inner: null, normal }); + } + } + return faces; + }; + + const newell = (ring) => { + let x = 0; + let y = 0; + let z = 0; + for (let i = 0; i < ring.length; i++) { + const a = ring[i]; + const b = ring[(i + 1) % ring.length]; + x += (a[1] - b[1]) * (a[2] + b[2]); + y += (a[2] - b[2]) * (a[0] + b[0]); + z += (a[0] - b[0]) * (a[1] + b[1]); + } + return [x, y, z]; + }; + // The sign of the turn of a ring seen from the end of `outward` it faces: positive when counter-clockwise. + const winding = (ring, outward) => { + const [x, y, z] = newell(ring); + return x * outward[0] + y * outward[1] + z * outward[2]; + }; + + // An edge of an outline that is not on the axis: its ends and the way out of the solid in the plane of the profile. + const sidesOf = (revolution, positions, facetsPerTurn) => { + const shapes = profileOutlines(revolution, positions, facetsPerTurn); + const loops = shapes.map((shape) => shape.points); + const inside = nesting(oneSide(loops, sideOfAxis(loops))); + const sides = []; + for (let l = 0; l < loops.length; l++) { + const loop = loops[l]; + // The loop runs counter-clockwise when its area is positive; the solid is then on the left of each line. Inside an odd + // number of loops it is a hole: the solid is outside it. + const depth = inside.filter((row) => row[l]).length; + const turn = Math.sign(areaOfProfile(loop)) * (depth % 2 === 0 ? 1 : -1); + for (let i = 0; i < loop.length; i++) { + const [d1, v1] = loop[i]; + const [d2, v2] = loop[(i + 1) % loop.length]; + if (Math.abs(d1) <= TOLERANCE && Math.abs(d2) <= TOLERANCE) continue; + const dd = d2 - d1; + const dv = v2 - v1; + const length = Math.sqrt(dd * dd + dv * dv); + const key = keyOf(SIDE, l, shapes[l].segments[i]); + sides.push({ key, d1, v1, d2, v2, outD: turn * dv / length, outV: -turn * dd / length }); + } + } + return sides; + }; + + const revolutionFaces = (revolution, positions, facetsPerTurn) => { + const { axis, normal } = revolution; + const across = 3 - axis - normal; + const centre = positions[revolution.axisPosition]; + const plane = positions[revolution.planePosition]; + const facets = Math.max(FACETS, facetsPerTurn); + const pointAt = (d, v, facet) => { + const angle = 2 * Math.PI * facet / facets; + const point = [0, 0, 0]; + point[axis] = v; + point[across] = centre + d * Math.cos(angle); + point[normal] = plane + d * Math.sin(angle); + return point; + }; + const wound = (ring, outward, key) => { + if (winding(ring, outward) < 0) ring.reverse(); + const [x, y, z] = newell(ring); + const length = Math.sqrt(x * x + y * y + z * z); + const facing = length > 0 && winding(ring, outward) !== 0 ? [x / length, y / length, z / length] : outward; + return { key, outer: ring, inner: null, normal: facing }; + }; + // The disc or the ring at a position along the axis: its outer circle and, for a ring, the circle of the hole. + const flat = (first, second, v, side, outV, key) => { + const outer = Math.max(first, second); + const inner = Math.min(first, second); + const way = side < 0 ? -1 : 1; + const up = [0, 0, 0]; + up[axis] = Math.sign(outV); + const circle = (radius) => Array.from({ length: facets }, (_, facet) => pointAt(way * radius, v, facet)); + const face = wound(circle(outer), up, key); + if (inner > TOLERANCE) { + const hole = circle(inner); + // A hole runs the other way round from the outline. + if (winding(face.outer, up) * winding(hole, up) > 0) hole.reverse(); + face.inner = [hole]; + } + return face; + }; + + const faces = []; + for (const { key, d1, v1, d2, v2, outD, outV } of sidesOf(revolution, positions, Math.min(facetsPerTurn, PROFILE_FACETS))) { + if (Math.abs(v2 - v1) <= TOLERANCE) { + faces.push(flat(Math.abs(d1), Math.abs(d2), v1, Math.sign(d1 + d2), outV, key)); + continue; + } + for (let facet = 0; facet < facets; facet++) { + const ring = [pointAt(d1, v1, facet), pointAt(d1, v1, facet + 1), pointAt(d2, v2, facet + 1), pointAt(d2, v2, facet)]; + // The end on the axis is one point. + if (Math.abs(d1) <= TOLERANCE) ring.splice(1, 1); + else if (Math.abs(d2) <= TOLERANCE) ring.splice(3, 1); + // A facet is wound to face along the outward direction of the profile turned to the middle of the facet. + const middle = 2 * Math.PI * (facet + 0.5) / facets; + const outward = [0, 0, 0]; + outward[axis] = outV; + outward[across] = outD * Math.cos(middle); + outward[normal] = outD * Math.sin(middle); + faces.push(wound(ring, outward, key)); + } + } + return faces; + }; + + // ---- A loaded family placed in the family (FamilyNested): the point p of it stands at origin + sum of p[c] basis[c]. + + const placedFaces = (shape, positions, origin, placement, facetsPerTurn) => { + const { basis } = placement; + const mirrored = basis[0][0] * (basis[1][1] * basis[2][2] - basis[1][2] * basis[2][1]) + - basis[0][1] * (basis[1][0] * basis[2][2] - basis[1][2] * basis[2][0]) + + basis[0][2] * (basis[1][0] * basis[2][1] - basis[1][1] * basis[2][0]) < 0; + const direction = (local) => [0, 1, 2].map((axis) => local[0] * basis[0][axis] + local[1] * basis[1][axis] + local[2] * basis[2][axis]); + const point = (local) => direction(local).map((value, axis) => origin[axis] + value); + const ring = (corners) => { + const placed = corners.map(point); + if (mirrored) placed.reverse(); + return placed; + }; + const faces = []; + for (const extrusion of shape.extrusions) { + for (const face of extrusionFaces(extrusion, positions, facetsPerTurn)) { + faces.push({ + key: `${extrusion.id} ${face.key}`, outer: ring(face.outer), + inner: face.inner === null ? null : face.inner.map(ring), normal: direction(face.normal), + }); + } + } + return faces; + }; + + // ---- The mesher (GeTess). A point is [x, y]; a contour is a ring of vertices that name points by index. + + const makeContour = (points) => ({ points, head: null, next: null, clockwise: false, flag: 0, tolerance: 0 }); + const addVertex = (contour, index) => { + const vertex = { index, contour, next: null, previous: null }; + const head = contour.head; + if (head !== null) { + head.previous.next = vertex; + vertex.previous = head.previous; + head.previous = vertex; + vertex.next = head; + } else { + contour.head = vertex; + vertex.previous = vertex; + vertex.next = vertex; + } + return vertex; + }; + const pointOf = (vertex) => vertex.contour.points[vertex.index]; + const isLine = (contour) => contour.head !== null && contour.head.next === contour.head.previous; + const isTriangle = (contour) => contour.head !== null && contour.head.next.next === contour.head.previous; + const countOf = (contour) => { + if (contour.head === null) return 0; + let n = 0; + let v = contour.head; + do { n++; v = v.next; } while (v !== contour.head); + return n; + }; + const reverseContour = (contour) => { + const head = contour.head; + if (head !== null) { + let v = head; + do { + const old = v.next; + v.next = v.previous; + v.previous = old; + v = old; + } while (v !== head); + } + contour.clockwise = !contour.clockwise; + }; + const hypot = (x, y) => Math.sqrt(x * x + y * y); + + const maxCoordinate = (contour) => { + let minX = Number.MAX_VALUE; + let minY = Number.MAX_VALUE; + let maxX = -Number.MAX_VALUE; + let maxY = -Number.MAX_VALUE; + const head = contour.head; + if (head !== null) { + let v = head; + do { + const p = pointOf(v); + minX = Math.min(minX, p[0]); + maxX = Math.max(maxX, p[0]); + minY = Math.min(minY, p[1]); + maxY = Math.max(maxY, p[1]); + v = v.next; + } while (v !== head); + } + return hypot(maxX - minX, maxY - minY); + }; + + const squareTolerance = (contour, a2, relative) => { + const head = contour.head; + let sx = 0; + let sy = 0; + let mx = 0; + let my = 0; + let minX = Math.abs(pointOf(head)[0]); + let minY = Math.abs(pointOf(head)[1]); + let n = 0; + let v = head; + do { + const p = pointOf(v); + const ax = Math.abs(p[0]); + const ay = Math.abs(p[1]); + sx += ax; + sy += ay; + minX = Math.min(minX, ax); + minY = Math.min(minY, ay); + mx = Math.max(ax, mx); + my = Math.max(ay, my); + n++; + v = v.next; + } while (v !== head); + const m = Math.max(my, mx); + if (relative) { + const k = (my - minY + mx - minX) * n; + return Math.max(m * 2.220446049250313e-16 * k * 1000.0, k * a2); + } + const sum = m === mx ? sy : sx; + return Math.max((m + m) * (sum * 2.220446049250313e-16), (sy + sx) * a2); + }; + + const areaOfContour = (contour, relative) => { + const head = contour.head; + const first = pointOf(head); + const x0 = relative ? first[0] : 0.0; + const y0 = relative ? first[1] : 0.0; + let sum = 0.0; + let p = first; + let v = head; + do { + const q = pointOf(v.next); + sum += (p[1] - y0) * (q[0] - x0) - (q[1] - y0) * (p[0] - x0); + p = q; + v = v.next; + } while (v !== head); + return sum * 0.5; + }; + + const checkClockwise = (contour, tolerance) => { + let area = contour.head !== null ? areaOfContour(contour, false) : 0.0; + let square = contour.head !== null ? squareTolerance(contour, tolerance, false) : 0.0; + if (area > square || -square > area) { + contour.clockwise = area >= 0.0; + return; + } + area = contour.head !== null ? areaOfContour(contour, true) : 0.0; + square = contour.head !== null ? squareTolerance(contour, tolerance, true) : 0.0; + if (area > square || -square > area) contour.clockwise = area >= 0.0; + else contour.flag |= 1; + }; + + const removeEqualVertices = (first, tolerance) => { + for (let contour = first; contour !== null; contour = contour.next) { + let v = contour.head; + if (v === null || v === v.next) continue; + for (;;) { + let next; + let found = false; + for (;;) { + next = v.next; + const p = pointOf(v); + const q = pointOf(next); + if (hypot(p[0] - q[0], p[1] - q[1]) <= tolerance) { found = true; break; } + v = next; + if (next === contour.head) break; + } + if (!found) break; + if (next === contour.head) { + if (v === contour.head) contour.head = v.next === v ? null : v.next; + const a = v.previous; + const b = v.next; + a.next = b; + b.previous = a; + break; + } + const a = next.previous; + const b = next.next; + a.next = b; + b.previous = a; + } + } + }; + + const isIncoming = (a, b) => { + const pa = pointOf(a); + const pp = pointOf(a.previous); + const pn = pointOf(a.next); + const pb = pointOf(b); + const ix = pa[0] - pp[0]; + const iy = pa[1] - pp[1]; + const ox = pa[0] - pn[0]; + const oy = pa[1] - pn[1]; + const wx = pa[0] - pb[0]; + const wy = pa[1] - pb[1]; + const v19 = wy * ix; + const v20 = wx * iy; + if (oy * ix - ox * iy >= 0.0) { + if (v19 - v20 <= 0.0 || wx * oy - wy * ox <= 0.0) return false; + } else if (v20 - v19 >= 0.0 && wy * ox - wx * oy >= 0.0) return false; + return true; + }; + + const inRange = (t, lengthSquared, toleranceSquared) => + t < 0.0 ? toleranceSquared >= lengthSquared * t * t : t < 1.0 && toleranceSquared < (1.0 - t) * lengthSquared * (1.0 - t); + + // The parameter on a-b at which the segment c-d hits it, or null. + const segmentHit = (a, b, lengthSquared, c, d, toleranceSquared) => { + const abx = b[0] - a[0]; + const aby = b[1] - a[1]; + const acx = c[0] - a[0]; + const acy = c[1] - a[1]; + const cr = acy * abx - acx * aby; + if (cr * cr <= toleranceSquared) { + const t = (acy * aby + acx * abx) / lengthSquared; + return inRange(t, lengthSquared, toleranceSquared) ? t : null; + } + const cdx = d[0] - c[0]; + const cdy = d[1] - c[1]; + const denominator = cdx * aby - cdy * abx; + if (denominator * denominator <= toleranceSquared) return null; + const inverse = 1.0 / denominator; + const s = inverse * cr; + const lengthCd = cdy * cdy + cdx * cdx; + if (s >= 0.0) { + if (s >= 1.0 || toleranceSquared >= (1.0 - s) * lengthCd * (1.0 - s)) return null; + } else if (toleranceSquared < lengthCd * s * s) return null; + const t = (cdx * acy - cdy * acx) * inverse; + return inRange(t, lengthSquared, toleranceSquared) ? t : null; + }; + + // The edges of the contour chain hit by the segment a-b, sorted by the parameter on it (a stable sort); edges that touch + // either end (by point index) are skipped. + const collect = (chain, skipA, a, b, skipB, tolerance, allContours) => { + const lengthSquared = (a[0] - b[0]) * (a[0] - b[0]) + (a[1] - b[1]) * (a[1] - b[1]); + const toleranceSquared = tolerance * tolerance; + const minX = Math.min(a[0], b[0]); + const maxX = Math.max(a[0], b[0]); + const minY = Math.min(a[1], b[1]); + const maxY = Math.max(a[1], b[1]); + const output = []; + for (let contour = chain; contour !== null; contour = contour.next) { + const head = contour.head; + if (head !== null) { + let v1 = head; + do { + const v2 = v1.next; + if (!(v1.index === skipA || v2.index === skipA || v1.index === skipB || v2.index === skipB)) { + const c = pointOf(v1); + const d = pointOf(v2); + if ((minX - tolerance <= c[0] || minX - tolerance <= d[0]) && (c[0] <= tolerance + maxX || d[0] <= tolerance + maxX) + && (minY - tolerance <= c[1] || minY - tolerance <= d[1]) && (c[1] <= tolerance + maxY || d[1] <= tolerance + maxY)) { + const t = segmentHit(a, b, lengthSquared, c, d, toleranceSquared); + if (t !== null) output.push({ vertex: v1, t }); + } + } + v1 = v2; + } while (v1 !== head); + } + if (!allContours) break; + } + for (let i = 1; i < output.length; i++) { + const x = output[i]; + let j = i - 1; + while (j >= 0 && output[j].t > x.t) { output[j + 1] = output[j]; j--; } + output[j + 1] = x; + } + return output; + }; + + const chooseTarget = (root, v, list, allContours) => { + let best = 1e300; + const tolerance = root.tolerance; + for (;;) { + if (list.length === 0) return null; + const e0 = list[0].vertex; + const e1 = e0.next; + if (allContours && e0.contour === v.contour) return null; + let candidate = null; + let d0 = best; + let dist; + if (e0.previous !== v && isIncoming(e0, v) && isIncoming(v, e0)) { + const p = pointOf(e0); + const q = pointOf(v); + d0 = (p[1] - q[1]) * (p[1] - q[1]) + (p[0] - q[0]) * (p[0] - q[0]); + candidate = e0; + } + if (e1.next !== v && isIncoming(e1, v) && isIncoming(v, e1)) { + const p = pointOf(e1); + const q = pointOf(v); + const d1 = (p[1] - q[1]) * (p[1] - q[1]) + (p[0] - q[0]) * (p[0] - q[0]); + if (candidate !== null) { + if (d1 <= d0) { candidate = e1; dist = d1; } else dist = d0; + } else { candidate = e1; dist = d1; } + } else if (candidate !== null) dist = d0; + else { + if (list.length <= 1) return null; + const second = list[1].vertex; + if (list[0].vertex.index !== second.next.index || list[0].vertex.next.index !== second.index) return null; + list = list.slice(1); + continue; + } + if (dist >= best || (dist <= tolerance && -tolerance <= dist)) return null; + best = dist; + const next = collect(root, v.index, pointOf(v), pointOf(candidate), candidate.index, tolerance, allContours); + if (next.length === 0) return candidate; + list = next; + } + }; + + const relabel = (contour) => { + const head = contour.head; + if (head === null) return; + let v = head; + do { v.contour = contour; v = v.next; } while (v !== head); + }; + + // c keeps [v..w], a new contour [w..v] is inserted behind it. + const splitPolygon = (c, v, w) => { + const n = makeContour(c.points); + n.clockwise = c.clockwise; + c.head = v; + addVertex(c, v.index); + c.head = w; + addVertex(c, w.index); + const v10 = w.previous; + const v11 = v.previous; + v10.next = v; + v.previous = v10; + v11.next = w; + w.previous = v11; + n.head = w; + n.next = c.next; + c.next = n; + c.head = v; + relabel(n); + relabel(c); + }; + + const concatContours = (self, a2, other, a4) => { + self.head = a2; + addVertex(self, a2.index); + other.head = a4; + addVertex(other, a4.index); + const v7 = self.head; + const v8 = other.head; + const v9 = v7.previous; + const v10 = v8.previous; + v9.next = v8; + v8.previous = v9; + v10.next = v7; + v7.previous = v10; + relabel(self); + other.head = null; + }; + + // The ray test of normalize and breakToConvex: a reflex vertex (turn below 0.1) shoots a ray of the length `reach`. + const rayFor = (v, tolerance, reach) => { + const p = pointOf(v); + const previous = pointOf(v.previous); + const next = pointOf(v.next); + const ay = p[1] - previous[1]; + const ax = p[0] - previous[0]; + const la2 = ay * ay + ax * ax; + const tolerance2 = tolerance * tolerance; + if (!(la2 > tolerance2 || -tolerance2 > la2)) return null; + const by = p[1] - next[1]; + const bx = p[0] - next[0]; + const lb2 = by * by + bx * bx; + if (!(lb2 > tolerance2 || -tolerance2 > lb2)) return null; + const v24 = Math.sqrt(lb2 * la2); + const v25 = (by * ax - ay * bx) / v24; + if (!(v25 <= 0.1 && (v25 <= 0.0 || by * ay + bx * ax <= 0.0))) return null; + if (v25 >= -0.2) { + const la = Math.sqrt(la2); + const v29 = -reach / la; + return [p[0] - ay * v29, v29 * ax + p[1]]; + } + let dx = bx + ax; + let dy = by + ay; + const length = hypot(dx, dy); + if (length > tolerance) { dx /= length; dy /= length; } + return [reach * dx + p[0], reach * dy + p[1]]; + }; + + const segmentParameter = (a, b, p) => { + const abx = b[0] - a[0]; + const aby = b[1] - a[1]; + const l2 = abx * abx + aby * aby; + if (l2 === 0.0) return [0.0, hypot(p[0] - a[0], p[1] - a[1])]; + const t = ((p[0] - a[0]) * abx + (p[1] - a[1]) * aby) / l2; + const clamped = Math.min(1.0, Math.max(0.0, t)); + return [t, hypot(p[0] - (a[0] + abx * clamped), p[1] - (a[1] + aby * clamped))]; + }; + + // A vertex that lies on a non adjacent edge pinches the contour: it is cut into two contours at that point. + const splitOnCoincidentPoint = (c) => { + let v3 = c.head; + do { + let v4 = v3.next.next; + let v5 = v4.next; + const v6 = v3.previous; + const p = pointOf(v3); + for (;;) { + const [t, dist] = segmentParameter(pointOf(v4), pointOf(v5), p); + if (dist <= 1e-10) { + c.flag &= ~1; + if (Math.abs(t - 1.0) > 1e-10) { + c.head = v5; + v5 = addVertex(c, v3.index); + } + const n = makeContour(c.points); + n.clockwise = c.clockwise; + const a = v3.previous; + c.head = a; + a.next = v5; + v5.previous = a; + v4.next = v3; + v3.previous = v4; + n.head = v3; + n.next = c.next; + c.next = n; + relabel(n); + relabel(c); + return true; + } + v4 = v5; + v5 = v5.next; + if (v4 === v6) break; + } + v3 = v3.next; + } while (v3 !== c.head); + return false; + }; + + const breakToConvex = (root, maxc) => { + const reach = maxc * 1.1; + for (let c = root; c !== null; c = c.next) { + c.tolerance = root.tolerance; + while (!isLine(c) && !isTriangle(c)) { + let v = c.head; + let w = null; + if (v !== null) { + for (;;) { + const ray = rayFor(v, root.tolerance, reach); + if (ray !== null) { + c.flag |= 1; + const list = collect(c, v.index, pointOf(v), ray, -1, root.tolerance, false); + if (list.length > 0) { + w = chooseTarget(c, v, list, false); + if (w !== null) break; + } + } + v = v.next; + if (v === c.head) break; + } + } + if (w !== null) { + c.flag &= ~1; + splitPolygon(c, v, w); + continue; + } + if ((c.flag & 1) === 0 || !splitOnCoincidentPoint(c)) break; + } + } + }; + + // Removes equal vertices, fixes the orientation (outer clockwise, holes counter-clockwise) and merges the holes into the + // outer contour by bridges. False when the outer contour has no area. + const normalize = (root, maxc, tolerance) => { + const reach = maxc * 1.1; + removeEqualVertices(root, root.tolerance); + checkClockwise(root, tolerance); + if ((root.flag & 1) !== 0) return false; + if (!root.clockwise) reverseContour(root); + for (let h = root.next; h !== null; h = h.next) { + checkClockwise(h, tolerance); + if (h.clockwise) reverseContour(h); + } + let hole = root.next; + while (hole !== null) { + let flipped = false; + let v = hole.head; + if (v === null || v.next === v.previous) { + hole = hole.next; + root.next = hole; + continue; + } + let w = null; + for (;;) { + let list = []; + const ray = rayFor(v, root.tolerance, reach); + if (ray !== null) { + list = collect(root, v.index, pointOf(v), ray, -1, root.tolerance, true); + if (list.length > 0 && list[0].vertex.contour !== hole) { + w = chooseTarget(root, v, list, true); + if (w !== null) break; + } + } + v = v.next; + if (v === hole.head) { + root.flag |= 2; + let count = 1; + for (let k = 1; k < list.length; k++) if (list[k].vertex.contour === hole) count++; + if ((count & 1) === 0 || flipped) { + hole = hole.next; + root.next = hole; + w = null; + break; + } + reverseContour(hole); + flipped = true; + v = hole.head.next; + } + } + if (w === null) continue; + const target = w.contour; + if (target === root) { + concatContours(root, w, hole, v); + hole = hole.next; + root.next = hole; + } else { + concatContours(hole, v, target, w); + let i = hole.next; + let previous = hole; + while (i !== target) { previous = i; i = i.next; } + previous.next = target.next; + target.next = null; + hole = root.next; + } + } + return true; + }; + + const convexPieces = (points, loops) => { + let root = null; + let previous = null; + for (const loop of loops) { + const c = makeContour(points); + for (const index of loop) addVertex(c, index); + if (root === null) root = c; + else previous.next = c; + previous = c; + } + const pieces = []; + if (root === null) return pieces; + const maxc = maxCoordinate(root); + root.tolerance = Math.min(-MESHER_TOLERANCE, maxc * 1e-9); + if (normalize(root, maxc, MESHER_TOLERANCE)) breakToConvex(root, maxc); + for (let c = root; c !== null; c = c.next) { + const count = countOf(c); + if (count < 3) continue; + const piece = []; + let v = c.head; + for (let i = 0; i < count; i++, v = v.next) piece.push(v.index); + pieces.push(piece); + } + return pieces; + }; + + const signedArea = (polygon) => { + let sum = 0.0; + for (let i = 0; i < polygon.length; i++) { + const a = polygon[i]; + const b = polygon[(i + 1) % polygon.length]; + sum += a[0] * b[1] - b[0] * a[1]; + } + return sum / 2; + }; + + const insideEvenOdd = (point, polygon) => { + let inside = false; + for (let i = 0; i < polygon.length; i++) { + const a = polygon[i]; + const b = polygon[(i + 1) % polygon.length]; + if ((a[1] > point[1]) !== (b[1] > point[1]) && a[0] + (point[1] - a[1]) * (b[0] - a[0]) / (b[1] - a[1]) > point[0]) { + inside = !inside; + } + } + return inside; + }; + + // The triangles of the loops of one face: the first loop is the outline, the others its holes. + const triangulateFace = (points, loops) => { + const polygons = loops.map((loop) => loop.map((index) => points[index])); + // The outline holds the holes most of whose points lie in it. + const holes = polygons.map((_, h) => h).slice(1) + .filter((h) => polygons[h].filter((point) => insideEvenOdd(point, polygons[0])).length * 2 > polygons[h].length); + const triangles = []; + for (const piece of convexPieces(points, [loops[0], ...holes.map((h) => loops[h])])) { + for (let j = 1; j < piece.length - 1; j++) triangles.push(piece[0], piece[j], piece[j + 1]); + } + return triangles; + }; + + // ---- Meshes (ElementMeshes.AppendFace and Triangulate). + + const appendFace = (face, target) => { + const { outer } = face; + if (outer.length < 3) return false; + const rings = [outer, ...(face.inner ?? []).filter((ring) => ring.length >= 3)]; + if (!rings.every((ring) => ring.every((point) => Number.isFinite(point[0]) && Number.isFinite(point[1]) && Number.isFinite(point[2])))) { + return false; + } + // The plane of the face: the Newell normal of its outer ring (relative to its first corner), turned to the side of the + // face normal. + const origin = outer[0]; + let nx = 0; + let ny = 0; + let nz = 0; + for (let index = 0; index < outer.length; index++) { + const a = outer[index]; + const b = outer[(index + 1) % outer.length]; + const ay = a[1] - origin[1]; + const az = a[2] - origin[2]; + const ax = a[0] - origin[0]; + const by = b[1] - origin[1]; + const bz = b[2] - origin[2]; + const bx = b[0] - origin[0]; + nx += (ay - by) * (az + bz); + ny += (az - bz) * (ax + bx); + nz += (ax - bx) * (ay + by); + } + const length = Math.sqrt(nx * nx + ny * ny + nz * nz); + if (!(length > 0)) return true; + nx /= length; + ny /= length; + nz /= length; + if (nx * face.normal[0] + ny * face.normal[1] + nz * face.normal[2] < 0) { + nx = -nx; + ny = -ny; + nz = -nz; + } + // In-plane axes u, v with u x v = n. + let hx = 0; + let hy = 0; + let hz = 0; + if (Math.abs(nx) <= Math.abs(ny) && Math.abs(nx) <= Math.abs(nz)) hx = 1; + else if (Math.abs(ny) <= Math.abs(nz)) hy = 1; + else hz = 1; + let ux = hy * nz - hz * ny; + let uy = hz * nx - hx * nz; + let uz = hx * ny - hy * nx; + const uLength = Math.sqrt(ux * ux + uy * uy + uz * uz); + ux /= uLength; + uy /= uLength; + uz /= uLength; + const vx = ny * uz - nz * uy; + const vy = nz * ux - nx * uz; + const vz = nx * uy - ny * ux; + + const points = []; + const loops = []; + let expected = 0; + let outerArea = 0; + for (let ringIndex = 0; ringIndex < rings.length; ringIndex++) { + const projected = rings[ringIndex].map((point) => { + const dx = point[0] - origin[0]; + const dy = point[1] - origin[1]; + const dz = point[2] - origin[2]; + return [dx * ux + dy * uy + dz * uz, dx * vx + dy * vy + dz * vz]; + }); + loops.push(projected.map((point) => points.push(point) - 1)); + const area = Math.abs(signedArea(projected)); + expected += ringIndex === 0 ? area : -area; + if (ringIndex === 0) outerArea = area; + } + + const triangles = triangulateFace(points, loops); + let covered = 0; + if (triangles.length > 0) { + const first = target.positions.length / 3; + for (const ring of rings) { + for (const point of ring) { + target.positions.push(point[0], point[1], point[2]); + target.normals.push(nx, ny, nz); + } + } + for (let i = 0; i < triangles.length; i += 3) { + const a = triangles[i]; + const b = triangles[i + 1]; + const c = triangles[i + 2]; + const pa = points[a]; + const pb = points[b]; + const pc = points[c]; + const area = (pb[0] - pa[0]) * (pc[1] - pa[1]) - (pb[1] - pa[1]) * (pc[0] - pa[0]); + covered += Math.abs(area) / 2; + // Counter-clockwise in (u, v) is counter-clockwise around n. + if (area < 0) target.indices.push(first + a, first + c, first + b); + else target.indices.push(first + a, first + b, first + c); + } + } + // Without holes, more area than the outline is a fold of a polygon that is not quite planar, which still covers the face. + const tolerance = 1e-6 * outerArea + 1e-12; + return covered >= expected - tolerance && (rings.length === 1 || covered <= expected + tolerance); + }; + + // One mesh for each material in the order the materials first appear, in the units of the page; null when a face fails. + const meshesOf = (faces, materialOf, scale) => { + const builders = new Map(); + let failed = false; + for (const face of faces) { + const material = materialOf(face); + let builder = builders.get(material); + if (builder === undefined) builders.set(material, builder = { material, positions: [], normals: [], indices: [] }); + if (!appendFace(face, builder)) failed = true; + } + if (failed) return null; + return [...builders.values()].filter((builder) => builder.indices.length > 0).map((builder) => ({ + material: builder.material, + positions: Float64Array.from(builder.positions, (value) => value * scale), + normals: Float64Array.from(builder.normals), + indices: Uint32Array.from(builder.indices), + })); + }; + + // ---- A type of the family (ElementMeshes.ComputeShape). + + const mapOf = (object) => new Map(Object.entries(object).map(([key, value]) => [Number(key), value])); + + // The triangles of an instance taken from the file, as they come in the data: compressed with gzip, single precision + // positions and normals and then the indices, each as its difference from the one before. + const readMesh = async ({ material, vertices, triangles }) => { + const text = atob(triangles); + const packed = new Uint8Array(text.length); + for (let i = 0; i < text.length; i++) packed[i] = text.charCodeAt(i); + const buffer = await new Response(new Blob([packed]).stream().pipeThrough(new DecompressionStream('gzip'))).arrayBuffer(); + const indices = new Uint32Array(buffer, vertices * 24); + for (let i = 1; i < indices.length; i++) indices[i] += indices[i - 1]; + return { + material, + positions: new Float32Array(buffer, 0, vertices * 3), + normals: Float64Array.from(new Float32Array(buffer, vertices * 12, vertices * 3)), + indices, + }; + }; + + globalThis.familyTypeProgram = async (json) => { + // The numbers that are not finite are written as their text. + const data = JSON.parse(json, (key, value) => + value === 'NaN' || value === 'Infinity' || value === '-Infinity' ? Number(value) : value); + const { model, shapes, facets, scale } = data; + const materials = new Set(data.materials); + const extrusions = new Map(model.extrusions.map((extrusion) => [extrusion.id, extrusion])); + const revolutions = new Map(model.revolutions.map((revolution) => [revolution.id, revolution])); + const combinations = new Map(model.combinations.map((combination) => [combination.id, combination])); + const placements = new Map(model.placements.map((placement) => [placement.id, placement])); + // Unpacked once, before the first type. + const carried = new Map(await Promise.all(Object.entries(data.nested) + .filter(([, instance]) => instance.meshes) + .map(async ([id, instance]) => [Number(id), await Promise.all(instance.meshes.map(readMesh))]))); + + const compute = (index) => { + const type = data.types[index]; + if (type === undefined) throw new RangeError(`The family has no type ${index}.`); + const values = mapOf(type.values); + for (const { visibility } of [...model.extrusions, ...model.revolutions, ...model.placements]) { + if (visibility !== null && !values.has(visibility)) return refusal('underdetermined', visibility); + } + const shown = { + ...model, + extrusions: model.extrusions.filter((extrusion) => isShown(extrusion.visibility, values)), + revolutions: model.revolutions.filter((revolution) => isShown(revolution.visibility, values)), + }; + for (const { material } of [...shown.extrusions, ...shown.revolutions]) { + if (material !== null && !values.has(material)) return refusal('underdetermined', material); + } + const solution = solve(shown, values); + if (solution.refusal) return solution; + const { positions } = solution; + const degenerate = check(shown, positions, values); + if (degenerate !== null) return degenerate; + + const shownIds = new Set([...shown.extrusions, ...shown.revolutions].map((form) => form.id)); + const elements = []; + for (const id of data.elements) { + const instance = data.nested[id]; + if (instance !== undefined) { + // An instance of a family loaded into this one: the faces of that family, solved for what this type gives it. + const placement = placements.get(id); + if (!isShown(placement.visibility, values)) { + elements.push({ id, meshes: [] }); + continue; + } + const given = type.nested[id]; + if (given.refusal) return { refusal: given.refusal }; + if (instance.meshes !== undefined) { + // An instance taken as the file stores it: the same shape, moved to where this type has the instance. + if (instance.meshes === null) return refusal('degenerate-geometry', id); + const moved = placement.origin.map((variable) => (positions[variable] - model.stored[variable]) * scale); + elements.push({ + id, + meshes: carried.get(id).map((mesh) => ({ + ...mesh, + positions: Float64Array.from(mesh.positions, (value, i) => value + moved[i % 3]), + })), + }); + continue; + } + const shape = shapes[instance.shape]; + const own = mapOf(given.values); + const solved = solve(shape, own); + if (solved.refusal) return solved; + const wrong = check(shape, solved.positions, own); + if (wrong !== null) return wrong; + const faces = placedFaces(shape, solved.positions, placement.origin.map((variable) => positions[variable]), placement, facets); + if (faces.some((face) => instance.faces[face.key] === undefined)) return refusal('degenerate-geometry', id); + const meshes = meshesOf(faces, (face) => instance.faces[face.key], scale); + if (meshes === null) return refusal('degenerate-geometry', id); + elements.push({ id, meshes }); + continue; + } + const combination = combinations.get(id); + if (combination === undefined && !shownIds.has(id)) { + elements.push({ id, meshes: [] }); + continue; + } + // A combination is drawn as the faces of its members, whole. + const faces = []; + for (const part of combination === undefined ? [id] : combination.members) { + const extrusion = extrusions.get(part); + const form = extrusion ?? revolutions.get(part); + const built = extrusion !== undefined ? extrusionFaces(extrusion, positions, facets) : revolutionFaces(form, positions, facets); + for (const face of built) { + const stored = data.faces[part]?.[face.key]; + if (stored === undefined) return refusal('degenerate-geometry', part); + // The material of the parameter that gives it, else the stored one; else what gives a face without one its own. + const own = form.material === null ? stored[0] : Math.trunc(values.get(form.material) ?? 0); + face.material = own > 0 && materials.has(own) ? own : stored[1]; + faces.push(face); + } + } + const meshes = meshesOf(faces, (face) => face.material, scale); + if (meshes === null) return refusal('degenerate-geometry', id); + elements.push({ id, meshes }); + } + return { elements }; + }; + + return { count: data.types.length, compute }; + }; +})(); diff --git a/src/RvtIO/RvtFileReader.cs b/src/RvtIO/RvtFileReader.cs index 6b86923b..fbb08c3b 100644 --- a/src/RvtIO/RvtFileReader.cs +++ b/src/RvtIO/RvtFileReader.cs @@ -143,7 +143,8 @@ private RevitFileInfo ReadCore(RootStorage root) 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, routing, elemTableIsExact, previewBase64, previewMime, diag, LogPhase, ids, projectElementsOnly); + staleCopiesRemoved, routing, elemTableIsExact, previewBase64, previewMime, diag, LogPhase, ids, projectElementsOnly, + keepSurfaces: familyOwnerId != null); wideInfo.IsStandaloneFamily = isStandaloneFamily; wideInfo.FamilyOwnerId = familyOwnerId; WideModel = wideInfo; @@ -173,7 +174,8 @@ private RevitFileInfo ReadCore(RootStorage root) var (rvtInfo, state) = ParseModel(root, chunks, readFrames, partitionChunkCount, r22View, partitionStreams, framedStreams, wideSchema, elemTable, elemWorksets, fileMetadata, projectInfo, transmissionData, episodeTable, elemRecHistories, elemRecOwners, tfSchemas, ownPartitionWallParts, - staleCopiesRemoved, routing, elemTableIsExact, previewBase64, previewMime, diag, LogPhase, ids, projectElementsOnly, progress); + staleCopiesRemoved, routing, elemTableIsExact, previewBase64, previewMime, diag, LogPhase, ids, projectElementsOnly, + keepSurfaces: familyOwnerId != null, progress); rvtInfo.IsStandaloneFamily = isStandaloneFamily; rvtInfo.FamilyOwnerId = familyOwnerId; if (!releasePartitions) storage = ExtensibleStorageReader.Read(root, elemTableIsExact, framedStreams); @@ -247,6 +249,7 @@ private static void ReleaseStreams(List>? streams, List LogPhase, ElementIdMap? ids, bool projectElementsOnly, + bool keepSurfaces, IProgress? progress = null) { if (ids != null && !r22View) @@ -261,6 +264,7 @@ private static void ReleaseStreams(List>? streams, List 2000 || geometry?.Faces.Count > 100000)) DiagnosticSink.WriteLine($"slow GRep eid={job.Eid} ms={clock.ElapsedMilliseconds} faces={geometry?.Faces.Count}"); return geometry; diff --git a/src/RvtIO/RvtIO.csproj b/src/RvtIO/RvtIO.csproj index fc3e0554..9afd2379 100644 --- a/src/RvtIO/RvtIO.csproj +++ b/src/RvtIO/RvtIO.csproj @@ -32,6 +32,7 @@ + diff --git a/tests/RvtIO.Tests/ElementBuilderGeometryTests.cs b/tests/RvtIO.Tests/ElementBuilderGeometryTests.cs index 1a8d6cda..220fa4f5 100644 --- a/tests/RvtIO.Tests/ElementBuilderGeometryTests.cs +++ b/tests/RvtIO.Tests/ElementBuilderGeometryTests.cs @@ -264,6 +264,33 @@ public void ClipGeometryToBounds_UsesExactSerializedPlane() point => BitConverter.DoubleToInt64Bits(point[2]) == BitConverter.DoubleToInt64Bits(1.25)); } + // The stored box and the stored corners of a face that lies on it differ in their last bits: nothing is cut there, where a cut + // between two such corners would put a point anywhere along their side. + [Fact] + public void ClipGeometryToBounds_LeavesAFaceOnAPlaneUpToTheLastBits() + { + double below = Math.BitDecrement(1.0), above = Math.BitIncrement(Math.BitIncrement(1.0)); + List outline = [[0, 0, above], [1, 0, below], [2, 0, 1], [1, 1, above]]; + var source = new GeometryData { Faces = [new GeoFace { OuterVertices = outline }] }; + + var clipped = ElementBuilder.ClipGeometryToBounds(source, [0, 0, 1, 2, 1, 2], out bool changed); + + Assert.False(changed); + Assert.Equal(outline, Assert.Single(clipped!.Faces).OuterVertices); + } + + [Fact] + public void ClipGeometryToBounds_CutsASideThatLeavesFromACornerOnThePlaneAtThatCorner() + { + double below = Math.BitDecrement(1.0); + var source = new GeometryData { Faces = [new GeoFace { OuterVertices = [[0, 0, below], [1, 0, 2], [2, 0, below], [1, 0, 0]] }] }; + + var clipped = ElementBuilder.ClipGeometryToBounds(source, [0, 0, 1, 2, 1, 2], out bool changed); + + Assert.True(changed); + Assert.Equal([[0, 0, below], [1, 0, 2], [2, 0, below]], Assert.Single(clipped!.Faces).OuterVertices); + } + [Fact] public void ClipGeometryToBounds_CopiesAndDeduplicatesAnUncutFace() { diff --git a/tests/RvtIO.Tests/FaceLayoutTests.cs b/tests/RvtIO.Tests/FaceLayoutTests.cs index 3cdd97db..1c951ec0 100644 --- a/tests/RvtIO.Tests/FaceLayoutTests.cs +++ b/tests/RvtIO.Tests/FaceLayoutTests.cs @@ -211,6 +211,7 @@ private static object Sample(Type type) if (type == typeof(List>) || type == typeof(IReadOnlyList>)) return new List> { new() }; if (type == typeof(IReadOnlyList)) return new Arc[] { new([0, 0, 0], [1, 0, 0], [0, 1, 0], 1, 0, 1) }; if (type == typeof(List)) return new List { 1 }; + if (type == typeof(ExactSurface)) return ExactSurface.Cylinder([0, 0, 0], [1, 0, 0], [0, 1, 0], [0, 0, 1], 1)!; throw new InvalidOperationException($"no sample value for {type}"); } } diff --git a/tests/RvtIO.Tests/Families/CarriedInstanceTests.cs b/tests/RvtIO.Tests/Families/CarriedInstanceTests.cs new file mode 100644 index 00000000..b67f228c --- /dev/null +++ b/tests/RvtIO.Tests/Families/CarriedInstanceTests.cs @@ -0,0 +1,256 @@ +using RvtIO.BuiltIns; +using RvtIO.Families; +using RvtIO.Model; +using RvtIO.Parsing; +using RvtIO.Writing; +using Xunit; + +namespace RvtIO.Tests.Families; + +/// An instance of a loaded family that is not computed is taken as the file stores it, once that is the loaded family's +/// own stored shape placed where the instance stands, and serves the types that give the instance what the saved one does. +public class CarriedInstanceTests +{ + private const int Form = 7, Instance = 60, Symbol = 61; + private const long Length = 100, Label = 101, Visible = 200, OfTheInstance = 4000, OfTheSymbol = 4001; + private static readonly RvtFamilyRefusal Why = new("unsupported-construct", "nested family 5: forms that a parameter hides"); + + // A turn by a quarter about z: x of the loaded family goes along y of the host. + private static readonly double[][] Turn = [[0, 1, 0], [-1, 0, 0], [0, 0, 1]]; + + private static GeoFace Square(double[] a, double[] b, double[] c, double[] d) => new(a, [0, 0, 1]) { OuterVertices = [a, b, c, d] }; + + // The face the loaded family stores, placed at (x, 0, z). + private static GeoFace Placed(double x = 2, double z = 1) => Square([x, 0, z], [x, 1, z], [x - 1, 1, z], [x - 1, 0, z]); + + private static CarriedInstance? Carry(IReadOnlyList held, params RvtFamilyType[] types) => + CarryOf([Square([0, 0, 0], [1, 0, 0], [1, 1, 0], [0, 1, 0])], held, types); + + private static CarriedInstance? CarryOf(List own, IReadOnlyList held, params RvtFamilyType[] types) => + CarryOf(own, held, new RvtFamilyTypes(0, types)); + + private static CarriedInstance? CarryOf(List own, IReadOnlyList held, RvtFamilyTypes types) + { + var info = new RevitFileInfo { Elements = [new Element { Id = Form, Geometry = new GeometryData { Faces = own } }] }; + var nested = new NestedFamilyData(new LoadedFamily(999, 1, 5, new Dictionary()), + new FamilyData { Elements = [new FamilyElementFacts(Form, "ExtrusionElem", true, true, false, true, false)] }, null!); + var host = SyntheticFamily.Leaf() with + { + Associations = [new(Instance, OfTheInstance, Length), new(Instance, (long)BuiltInParameter.IS_VISIBLE_PARAM, Visible)], + Symbols = [new FamilySymbolRecord(Symbol, 999, [new(Symbol, OfTheSymbol, Label)], new Dictionary())], + }; + var placement = new FamilyPlacement(Instance, Symbol, Symbol, [0, 1, 2], Turn, Visible); + return FamilyNested.Carry(nested, info, placement, host, types, [2, 0, 1], held, Why); + } + + private static RvtFamilyType Type(double length, string label = "a", int visible = 1) => new("T", + [ + new Parameter { Id = (int)Length, StorageType = StorageType.Double, Value = length }, + new Parameter { Id = (int)Label, StorageType = StorageType.String, Value = label }, + new Parameter { Id = (int)Visible, StorageType = StorageType.Integer, Value = visible }, + ]); + + [Fact] + public void AStoredInstanceThatIsItsFamilyPlacedIsTaken() + { + var held = Placed(); + + var carried = Carry([held], Type(1), Type(2, visible: 0)); + + Assert.NotNull(carried); + Assert.Same(held, Assert.Single(carried.Faces)); + Assert.Equal(Why, carried.Why); + // What shows the instance gives it nothing. + Assert.True(carried.TakesTheSame(new Dictionary { [Length] = 1, [Visible] = 0 })); + Assert.False(carried.TakesTheSame(new Dictionary { [Length] = 2, [Visible] = 1 })); + Assert.False(carried.TakesTheSame(new Dictionary { [Visible] = 1 })); + } + + // The loaded family's own copy of a combination winds some of its faces the other way round: the instance is drawn as the + // host stores it. + [Fact] + public void AStoredInstanceWithAFaceWoundTheOtherWayRoundIsTaken() + { + var turned = new GeoFace([2, 0, 1], [0, 0, -1]) { OuterVertices = [[1, 0, 1], [1, 1, 1], [2, 1, 1], [2, 0, 1]] }; + + var carried = Carry([turned], Type(1)); + + Assert.NotNull(carried); + Assert.Same(turned, Assert.Single(carried.Faces)); + } + + // A tessellated surface has slivers with all their points on one line: each is still the face it is. + [Fact] + public void AStoredInstanceWithSliversIsTaken() + { + var sliver = new GeoFace([0, 0, 0], [0, 0, 0]) { OuterVertices = [[0, 0, 0], [1, 0, 0], [1, 0, 0]] }; + var placed = new GeoFace([2, 0, 1], [0, 0, 0]) { OuterVertices = [[2, 0, 1], [2, 1, 1], [2, 1, 1]] }; + + Assert.NotNull(CarryOf([sliver], [placed], Type(1))); + Assert.Null(CarryOf([sliver], [new GeoFace([2, 0, 1], [0, 0, 0]) { OuterVertices = [[2, 0, 1], [2, 1, 1], [2, 2, 1]] }], Type(1))); + } + + [Fact] + public void AStoredInstanceThatIsSomethingElseIsNotTaken() + { + Assert.Null(Carry([Placed(3)], Type(1))); + Assert.Null(Carry([Placed(), Placed(3)], Type(1))); + Assert.Null(Carry([], Type(1))); + } + + // The faces come from the file: one that is no face leaves the instance untaken. + [Theory] + [InlineData("no corners")] + [InlineData("a corner of two numbers")] + [InlineData("a normal of two numbers")] + [InlineData("a hole with a corner of two numbers")] + public void AnInstanceOfAFamilyWithABrokenFaceIsNotTaken(string broken) + { + double[][] square = [[0, 0, 0], [1, 0, 0], [1, 1, 0], [0, 1, 0]]; + var face = broken switch + { + "no corners" => new GeoFace([0, 0, 0], [0, 0, 1]) { OuterVertices = [] }, + "a corner of two numbers" => new GeoFace([0, 0, 0], [0, 0, 1]) { OuterVertices = [square[0], square[1], [1, 1]] }, + "a normal of two numbers" => new GeoFace([0, 0, 0], [0, 0]) { OuterVertices = [.. square] }, + _ => new GeoFace([0, 0, 0], [0, 0, 1]) { OuterVertices = [.. square], InnerVertices = [[[0.5, 0.5]]] }, + }; + + Assert.Null(CarryOf([face], [Placed()], Type(1))); + } + + // The types are compared by their numbers: a text that differs between them would go unseen. + [Fact] + public void AnInstanceGivenATextThatDiffersBetweenTheTypesIsNotTaken() => + Assert.Null(Carry([Placed()], Type(1), Type(1, "b"))); + + // So would a parameter whose value is not read as a number, such as a built-in of a kind that is not established, or an + // element that has no key. + [Theory] + [InlineData(StorageType.None)] + [InlineData(StorageType.ElementId)] + public void AnInstanceGivenAParameterThatHasNoNumberInATypeIsNotTaken(StorageType storage) + { + var unread = new RvtFamilyType("U", [.. Type(1).Parameters.Where(parameter => parameter.Id != Length), + new Parameter { Id = (int)Length, StorageType = storage }]); + + Assert.Null(Carry([Placed()], unread)); + Assert.Null(Carry([Placed()], Type(1), unread)); + // Unless every type stores it the same, whatever it holds. + Assert.NotNull(CarryOf([Square([0, 0, 0], [1, 0, 0], [1, 1, 0], [0, 1, 0])], [Placed()], + new RvtFamilyTypes(0, [unread, unread]) { StoredAlike = new HashSet { Length } })); + } + + [Fact] + public void TheParametersThatEveryTypeStoresAlikeAreTold() + { + static WideBlockWalker.Capture Slot(long integer = 0, double real = 0, string? text = null) => + new("slot", WideBlockWalker.CaptureKind.Integer, integer, real, text, true, -1, "", ""); + // The slots of a row: a text, a formula, a number, an element, the parameter, a whole number, and two flags. + static LoadedFamilyParameterWriter.NamedValue Row(long id, double real = 0, string text = "", long element = -1, long whole = 0) => + new([Slot(text: text), Slot(), Slot(real: real), Slot(element), Slot(id), Slot(whole), Slot(), Slot()]); + static FamilyTypeTable.StoredType Stored(params LoadedFamilyParameterWriter.NamedValue[] rows) => + new("T", new LoadedFamilyParameterWriter.FamilyStore(0, rows)); + + var alike = FamilyRecordReader.StoredAlike( + [ + Stored(Row(-1, 0.5), Row(2, 1), Row(3, text: "a"), Row(4, element: 8), Row(5, whole: 1)), + Stored(Row(-1, 0.5), Row(2, 2), Row(3, text: "b"), Row(4, element: 9), Row(5, whole: 2), Row(6)), + ]); + + Assert.Equal([-1], alike); + } + + private const int Other = 8; + private const long ShowsForm = 5000, ShowsOther = 5001; + + private static RvtFamilyType Showing(string name, params (long Parameter, int Value)[] values) => + new(name, [.. values.Select(value => new Parameter { Id = (int)value.Parameter, StorageType = StorageType.Integer, Value = value.Value })]); + + // A loaded family of two forms, each shown by a parameter of its own, saved with the type "one"; the instance is of the + // host's symbol named . The second form is a square two above the first unless given. + private static CarriedInstance? CarryOfTypes(string symbol, IReadOnlyList held, GeoFace? second = null, int? standIn = null) + { + var info = new RevitFileInfo + { + Elements = + [ + new Element { Id = Form, Geometry = new GeometryData { Faces = [Square([0, 0, 0], [1, 0, 0], [1, 1, 0], [0, 1, 0])] } }, + new Element { Id = Other, Geometry = new GeometryData { Faces = [second ?? Square([0, 0, 2], [1, 0, 2], [1, 1, 2], [0, 1, 2])] } }, + new Element { Id = Symbol, Name = symbol }, + ], + }; + var nested = new NestedFamilyData(new LoadedFamily(999, 1, 5, new Dictionary()), new FamilyData + { + Elements = + [ + new FamilyElementFacts(Form, "ExtrusionElem", true, true, false, true, false), + new FamilyElementFacts(Other, "ExtrusionElem", true, true, false, true, true), + ], + Types = new RvtFamilyTypes(0, + [ + Showing("one", (ShowsForm, 1), (ShowsOther, 0)), + Showing("two", (ShowsForm, 0), (ShowsOther, 1)), + Showing("both", (ShowsForm, 1), (ShowsOther, 1)), + Showing("silent"), + ]), + Records = SyntheticFamily.Leaf() with + { + Associations = + [ + new(Form, (long)BuiltInParameter.IS_VISIBLE_PARAM, ShowsForm), + new(Other, (long)BuiltInParameter.IS_VISIBLE_PARAM, ShowsOther), + ], + }, + HostStandIn = standIn, + }, null!); + var host = SyntheticFamily.Leaf() with { Symbols = [new FamilySymbolRecord(Symbol, 999, [], new Dictionary())] }; + var placement = new FamilyPlacement(Instance, Symbol, Symbol, [0, 1, 2], Turn, null); + return FamilyNested.Carry(nested, info, placement, host, new RvtFamilyTypes(0, [new("T", [])]), [2, 0, 1], held, Why); + } + + // The loaded family is saved with one of its types; an instance shows what the type it was placed with shows. + [Theory] + [InlineData("two", true)] + [InlineData("one", false)] + [InlineData("no such type", false)] + public void AnInstanceIsItsFamilyAtTheTypeNamedAsItsSymbol(string symbol, bool taken) => + Assert.Equal(taken, CarryOfTypes(symbol, [Placed(z: 3)]) != null); + + [Fact] + public void ATypeThatDoesNotSayWhatShowsAFormTakesNoInstance() => + Assert.Null(CarryOfTypes("silent", [Placed(), Placed(z: 3)])); + + // A family placed on a face has a form that stands for the face. + [Fact] + public void TheFormStandingForTheFaceIsNoPartOfAnInstance() + { + Assert.Null(CarryOfTypes("both", [Placed()])); + Assert.NotNull(CarryOfTypes("both", [Placed()], standIn: Other)); + } + + // Two forms that touch have a face in the same place, seen from its two sides, which the instance holds once. + [Fact] + public void AFaceTwoFormsShareIsHeldOnce() => + Assert.NotNull(CarryOfTypes("both", [Placed()], + second: new GeoFace([0, 1, 0], [0, 0, -1]) { OuterVertices = [[0, 1, 0], [1, 1, 0], [1, 0, 0], [0, 0, 0]] })); + + // A family record names the element standing for the face when its one reference type is that of a face. + [Theory] + [InlineData(7, 1, true, 1234L)] + [InlineData(1, 1, true, null)] + [InlineData(7, 2, true, null)] + [InlineData(7, 1, false, null)] + public void TheFormStandingForTheFaceIsReadFromTheFamilyRecord(int referenceType, int references, bool elementReference, long? named) + { + static WideBlockWalker.Capture Read(string key, long value, int queue = -1, int position = -1) => + new(key, WideBlockWalker.CaptureKind.Integer, value, 0, null, queue < 0, queue, "", "", QueuePosition: position); + WideBlockWalker.Capture[] captures = + [ + Read("all:Family.m_refTypeIds#", 1), Read("all:Family.m_refTypeIds@0", referenceType), + Read("all:Family.m_refs#", references), Read("all:Family.m_refs@0", 40, position: 3), + Read("FamilyElemRef.m_elemId", 999, queue: 2), Read("FamilyElemRef.m_elemId", 1234, queue: 3), + ]; + + Assert.Equal(named, FamilyRecordReader.FaceHost(captures, tag => elementReference && tag == 40)); + } +} diff --git a/tests/RvtIO.Tests/Families/FamilyCombinationTests.cs b/tests/RvtIO.Tests/Families/FamilyCombinationTests.cs index 069d064d..1126e9f2 100644 --- a/tests/RvtIO.Tests/Families/FamilyCombinationTests.cs +++ b/tests/RvtIO.Tests/Families/FamilyCombinationTests.cs @@ -67,6 +67,20 @@ public void AMemberWhoseMaterialAParameterGivesIsCarried() Assert.Equal(200, Assert.Single(model!.Extrusions).MaterialParameterId); } + // Whichever of the two gives a face its material, it is the same. + [Fact] + public void AMaterialOfTheCombinationThatItsMembersTakeTooIsCarried() => Assert.Null(FamilyModelBuilder + .Build(Leaf(Of(Extrusion)) with { Associations = [new(Extrusion, -1002107, 200), new(Combination, -1002107, 200)] }).Refusal); + + [Theory] + [InlineData(null)] + [InlineData(201L)] + public void AMaterialOfTheCombinationThatAMemberDoesNotTakeIsRefused(long? member) => AssertRefused( + Leaf(Of(Extrusion)) with + { + Associations = [new(Combination, -1002107, 200), .. member is long own ? [new FamilyAssociation(Extrusion, -1002107, own)] : Array.Empty()], + }, "unrecognized-reference", "element 60"); + [Fact] public void AParameterThatDrivesTheCombinationItselfIsRefused() => AssertRefused(Leaf(Of(Extrusion)) with { Associations = [new(Combination, -1006205, 201)] }, "unrecognized-reference", diff --git a/tests/RvtIO.Tests/Families/FamilyContentTests.cs b/tests/RvtIO.Tests/Families/FamilyContentTests.cs index 3fba1374..f124d069 100644 --- a/tests/RvtIO.Tests/Families/FamilyContentTests.cs +++ b/tests/RvtIO.Tests/Families/FamilyContentTests.cs @@ -25,6 +25,10 @@ public sealed class FamilyContentTests [InlineData("ExtrusionElem", true, true, false, true, null, "Gap", "visibility")] [InlineData("FamilyInstance", true, false, false, true, false, "Gap", "missing-geometry")] [InlineData("SomethingElse", false, true, false, true, false, "Gap", "unknown-geometry")] + // An imported drawing is geometry of the family, shown or hidden as its settings say; the drawing it places is a type. + [InlineData("ImportInstance", false, true, false, true, false, "Shown", null)] + [InlineData("ImportInstance", false, true, false, true, true, "Hidden", null)] + [InlineData("MasterImportSymbol", false, true, false, null, null, "Excluded", null)] public void ContentIsClassified(string className, bool isForm, bool hasGeometry, bool cutting, bool? shownInFine, bool? hidden, string kind, string? gap) { @@ -41,6 +45,30 @@ public void ANestedInstanceThatViewsAloneDrawIsNoPartOfTheShape() Assert.Equal((FamilyContentKind.Excluded, (string?)null), FamilyContent.Classify(facts)); } + [Fact] + public void AnInstanceOfAFamilyThatDrawsNothingIsNoPartOfTheShape() + { + var facts = new FamilyElementFacts(1, "FamilyInstance", true, false, false, true, false, DrawsNothing: true); + + Assert.Equal((FamilyContentKind.Excluded, (string?)null), FamilyContent.Classify(facts)); + } + + [Theory] + // class, form, void, shown in Fine, combination member, no type draws it + [InlineData("SweepElem", true, false, false, false, true)] + [InlineData("SweepElem", true, true, true, false, true)] + [InlineData("SweepElem", true, false, true, false, false)] + [InlineData("ExtrusionElem", true, false, null, false, false)] + // The combination it is a member of may draw what it is. + [InlineData("ExtrusionElem", true, false, false, true, false)] + [InlineData("CurveElem", false, false, false, false, false)] + public void FormsNoTypeDrawsAreTold(string className, bool isForm, bool cutting, bool? shownInFine, bool member, bool undrawn) + { + var facts = new FamilyElementFacts(1, className, isForm, true, cutting, shownInFine, false, member); + + Assert.Equal(undrawn, FamilyContent.IsUndrawnForm(facts)); + } + [Fact] public void AnElementThatOnlyPlacesFormsOfTheFamilyAddsNothing() { diff --git a/tests/RvtIO.Tests/Families/FamilyEmptyContentTests.cs b/tests/RvtIO.Tests/Families/FamilyEmptyContentTests.cs new file mode 100644 index 00000000..c46bb79a --- /dev/null +++ b/tests/RvtIO.Tests/Families/FamilyEmptyContentTests.cs @@ -0,0 +1,273 @@ +using RvtIO.BuiltIns; +using RvtIO.Families; +using RvtIO.Model; +using Xunit; + +namespace RvtIO.Tests.Families; + +/// A family loaded into a family can hold nothing that is drawn in any type (parts that only exist for schedules): +/// its instances are no part of the shape, and what only places them moves nothing. +public class FamilyEmptyContentTests +{ + private const int Instance = 60, Symbol = 61, Choice = 90; + private static readonly double[][] Identity = [[1, 0, 0], [0, 1, 0], [0, 0, 1]]; + + // The family 999 of Symbol, and the family 998 of the symbol 66. + private static readonly FamilySymbolRecord[] Symbols = + [ + new(Symbol, 999, [], new Dictionary + { + [1] = new([0, 0, 0], [1, 0, 0]), [3] = new([0, 0, 0], [0, 1, 0]), [4] = new([0, 0, 0], [0, 0, 1]), + }), + new(66, 998, [], new Dictionary()), + ]; + + private static FamilyData Document(FamilyElementFacts[]? facts = null, FamilyRecords? records = null, bool read = true, + RvtFamilyTypes? types = null) => + new() { Elements = facts ?? [], ElementRecordsRead = read, Records = records, Types = types }; + + private static FamilyDocumentTree Tree(FamilyData data, params (long Family, FamilyData Data)[] loaded) => + new(data, family => loaded.Where(item => item.Family == family).Select(item => Tree(item.Data)).FirstOrDefault()); + + private static FamilyElementFacts Nested(int id, bool geometry = false) => + new(id, "FamilyInstance", true, geometry, false, true, false); + + private static FamilyInstanceRecord Placed(int id, int symbol = Symbol, int host = -1, FamilyReference? follows = null, + double[]? normal = null) => + new(id, symbol, symbol, [0, 0, 0], Identity, host, follows, normal); + + private static FamilyRecords Instances(params FamilyInstanceRecord[] instances) => + SyntheticFamily.Leaf() with { Instances = instances, Symbols = Symbols }; + + private static FamilyData Part() => Document(); + + private static FamilyData Solid() => Document([new(1, "ExtrusionElem", true, true, false, true, false)]); + + [Fact] + public void AFamilyWithoutContentDrawsNothing() => Assert.True(FamilyEmptyContent.DrawsNothing(Tree(Document()))); + + [Fact] + public void AFamilyWhoseElementsWereNotReadIsNotKnownToDrawNothing() => + Assert.False(FamilyEmptyContent.DrawsNothing(Tree(Document(read: false)))); + + [Theory] + // void, shown in Fine, hidden by the saved type, draws nothing + [InlineData(false, true, false, false)] + [InlineData(false, true, true, false)] + [InlineData(false, false, false, true)] + // A void can cut what the family is placed in. + [InlineData(true, true, false, false)] + public void AFormCounts(bool cutting, bool shown, bool hidden, bool nothing) => + Assert.Equal(nothing, FamilyEmptyContent.DrawsNothing(Tree(Document([new(1, "ExtrusionElem", true, true, cutting, shown, hidden)])))); + + [Fact] + public void AFamilyOfInstancesOfFamiliesThatDrawNothingDrawsNothing() + { + var family = Document([Nested(Instance)], Instances(Placed(Instance))); + + Assert.True(FamilyEmptyContent.DrawsNothing(Tree(family, (999, Part())))); + Assert.False(FamilyEmptyContent.DrawsNothing(Tree(family))); + Assert.False(FamilyEmptyContent.DrawsNothing(Tree(family, (999, Solid())))); + Assert.False(FamilyEmptyContent.DrawsNothing(Tree(Document([Nested(Instance, geometry: true)], Instances(Placed(Instance))), (999, Part())))); + // Without records the families the instances are of are not known. + Assert.False(FamilyEmptyContent.DrawsNothing(Tree(Document([Nested(Instance)]), (999, Part())))); + } + + [Theory] + // the symbol one of the types gives the parameter that chooses the type of the instance, draws nothing + [InlineData(Symbol, true)] + [InlineData(66, false)] + [InlineData(null, false)] + public void AParameterThatChoosesTheTypeCanOnlyChooseWhatDrawsNothing(int? second, bool nothing) + { + RvtFamilyType Type(string name, int? symbol) => new(name, + [new Parameter(new Definition { Id = Choice }) { Id = Choice, StorageType = StorageType.ElementId, Value = symbol }]); + var records = Instances(Placed(Instance)) with { Associations = [new(Instance, -1, Choice)] }; + var family = Document([Nested(Instance)], records, types: new RvtFamilyTypes(0, [Type("a", Symbol), Type("b", second)])); + + Assert.Equal(nothing, FamilyEmptyContent.InstanceDrawsNothing(Tree(family, (999, Part()), (998, Solid())), Instance)); + } + + // A loaded family that chooses the type of an instance of its own by a parameter can be given one that draws. + [Theory] + // a parameter the instance takes; one its symbol takes; only what shows the instance + [InlineData(500, false, false)] + [InlineData(null, true, false)] + [InlineData((int)BuiltInParameter.IS_VISIBLE_PARAM, false, true)] + public void AnInstanceThatHandsAParameterToAFamilyThatChoosesTypesIsNotKnownToDrawNothing(int? taken, bool ofTheSymbol, + bool nothing) + { + var chooses = Document(records: SyntheticFamily.Leaf() with { Associations = [new(70, -1, 91)] }); + var records = Instances(Placed(Instance)) with + { + Associations = taken is int property ? [new(Instance, property, Choice)] : [], + Symbols = ofTheSymbol ? [Symbols[0] with { Associations = [new(Symbol, 500, Choice)] }, Symbols[1]] : Symbols, + }; + + Assert.Equal(nothing, FamilyEmptyContent.InstanceDrawsNothing( + Tree(Document([Nested(Instance)], records), (999, chooses)), Instance)); + } + + private static FamilyRecords With(FamilyInstanceRecord[] instances, params FamilyDimensionRecord[] dimensions) => + Instances(instances) with { Dimensions = [.. SyntheticFamily.Leaf().Dimensions, .. dimensions] }; + + private static FamilyRecords Group(FamilyRecords records, int group, int member) => + records.Add(new FamilyReferrer(group, "ElementGroup", "ElementIdIndexPairSet.ElementIdPlusIndex.m_elementId", member)) + .Add(new FamilyReferrer(member, "FamilyInstance", "ElementGroupMembership.GroupMembership.m_groupId", group)); + + private static void AssertBuilt(FamilyRecords records) + { + var (model, refusal) = FamilyModelBuilder.Build(records); + + Assert.Null(refusal); + Assert.Empty(model!.Placements); + Assert.Null(FamilySolver.Solve(model, new Dictionary { [100] = 5, [101] = 4 }).Refusal); + } + + private static void AssertRefused(FamilyRecords records, string detail) + { + var (model, refusal) = FamilyModelBuilder.Build(records); + + Assert.Null(model); + Assert.Contains(detail, refusal!.Detail); + } + + // A parameter of the family changes the loaded one in the instance. + private static FamilyRecords Changed(FamilyRecords records, int instance = Instance) => + records with { Associations = [.. records.Associations, new(instance, 500, 100)] }; + + // The centre plane and the level never move, so a lock to them holds only the instance, whatever it is locked by. + [Fact] + public void ALockOfAnInstanceNoTypeShowsToPlanesThatStayMovesNothing() => AssertBuilt(Changed(With([Placed(Instance)], + SyntheticFamily.Alignment(62, 0, (1, 0, -1), (Instance, 9, 0)), SyntheticFamily.Alignment(63, 2, (7, 0, -1), (Instance, 9, 0))))); + + // An instance nothing changes goes with the one plane it is locked to along an axis. + [Fact] + public void ALockToOnePlaneThatMovesPlacesOnlyAnInstanceNothingChanges() + { + var records = With([Placed(Instance)], SyntheticFamily.Alignment(62, 0, (3, 0, -1), (Instance, 9, 0))); + + AssertBuilt(records); + // Whether the plane would go where a changed loaded family puts that part of the instance is not known. + AssertRefused(Changed(records), "62"); + AssertRefused(records with { Symbols = [Symbols[0] with { Associations = [new(Symbol, 500, 100)] }, Symbols[1]] }, "62"); + } + + // The planes 9, pinned, and 10, with the records given. + private static FamilyRecords Between(FamilyRecords records) => records with + { + Planes = [.. records.Planes, new(9, "RefPlane", 12, [-3, 0, 0], [1, 0, 0], Pinned: true), new(10, "RefPlane", 12, [3, 0, 0], [1, 0, 0])], + }; + + // A pinned plane holds what a dimension ties to it, so the centre plane moves from it. + [Fact] + public void ACentrePlaneHeldFromAPinnedPlaneDoesNotStay() => AssertRefused(Between(Changed(With([Placed(Instance)], + SyntheticFamily.Alignment(62, 0, (1, 0, -1), (Instance, 9, 0)), + SyntheticFamily.Linear(63, 0, 136, [(9, 0, -1), (1, 0, -1), (10, 0, -1)], [2, 2], [-1, -1], [3, 3])))), "62"); + + // A plane that a length or a lock holds from one that stays goes where that says, so a lock of an instance to it places + // only the instance, whatever the instance is and whatever the part of it the lock names. + [Theory] + // a labelled length; a locked one; a length the family computes from others holds nothing + [InlineData(100, 0, false, true)] + [InlineData(-1, 1, false, true)] + [InlineData(100, 0, true, false)] + public void ALockToAPlaneHeldFromOneThatStaysPlacesOnlyTheInstance(int parameter, int segment, bool driven, bool built) + { + var length = SyntheticFamily.Linear(63, 0, 8, [(9, 0, -1), (10, 0, -1)], [segment], [parameter], [6]); + if (driven) length = length with { DrivenSegments = new HashSet { 0 } }; + var records = Between(Changed(With([Placed(Instance)], + SyntheticFamily.Alignment(62, 0, (10, 0, -1), (Instance, 9, 0)), length))); + + if (built) AssertBuilt(records); + else AssertRefused(records, "62"); + } + + [Fact] + public void LocksToTwoPlanesAlongAnAxisAreStillRead() => AssertRefused(With([Placed(Instance)], + SyntheticFamily.Alignment(62, 0, (3, 0, -1), (Instance, 9, 0)), SyntheticFamily.Alignment(63, 0, (1, 0, -1), (Instance, 9, 0))), "62"); + + // An array holds its copies by a dimension between their groups. + [Fact] + public void WhatHoldsEmptyInstancesAmongThemselvesMovesNothing() + { + var array = new FamilyDimensionRecord(72, false, [1, 0, 0], 76, [0], [new(70, 0, -1), new(71, 0, -1)], [-1], [0], new HashSet()); + var records = With([Placed(Instance), Placed(63)], array, + SyntheticFamily.Alignment(62, 0, (1, 0, -1), (Instance, 9, 0)), SyntheticFamily.Alignment(64, 0, (1, 0, -1), (63, 9, 0))); + + AssertBuilt(Group(Group(records, 70, Instance), 71, 63)); + // Held together, they could carry a plane that moves with one of them to the other. + AssertRefused(Group(Group(records.Add(SyntheticFamily.Alignment(65, 0, (3, 0, -1), (63, 1, -1))), 70, Instance), 71, 63), "72"); + } + + [Fact] + public void ALabelledDimensionToAnEmptyInstanceIsStillRead() => AssertRefused( + With([Placed(Instance)], SyntheticFamily.Linear(62, 0, 8, [(1, 0, -1), (Instance, 9, 0)], [0], [100], [1])), "62"); + + [Fact] + public void ADimensionThatOnlyShowsTheDistanceToAnEmptyInstanceMovesNothing() => AssertBuilt( + With([Placed(Instance)], SyntheticFamily.Linear(62, 0, 8, [(3, 0, -1), (Instance, 9, 0)], [0], [-1], [1]))); + + // A shared part of a part is an instance of the family too. + [Fact] + public void APartNoTypeShowsOfAnInstanceMovesNothingWithIt() + { + var records = Changed(With([Placed(Instance), Placed(63)], SyntheticFamily.Alignment(62, 0, (3, 0, -1), (Instance, 1, -1)))); + + AssertBuilt(records.Add(new FamilyReferrer(63, "FamilyInstance", "FamilyInstance.m_superInstanceId", Instance))); + } + + // A form no type draws, 80, with a sketch of its own, 81: a plane of the sketch 82, a line 83 of it and a dimension 84 of + // the sketch between the two, which names a plane nothing reads. + private static FamilyRecords Undrawn(params FamilyDimensionRecord[] dimensions) + { + var leaf = SyntheticFamily.Leaf(); + FamilyReferrer Member(int member, string className, string by) => new(member, className, by + "Membership.GroupMembership.m_groupId", 81); + return leaf with + { + UndrawnForms = new HashSet { 80 }, + Lines = [.. leaf.Lines, new(83, 81, true, [0, 0, 0], [0, 1, 0])], + Dimensions = [.. leaf.Dimensions, SyntheticFamily.Linear(84, 0, 8, [(82, 0, -1), (83, 0, -1)], [0], [-1], [1]), .. dimensions], + Referrers = [.. leaf.Referrers, new(81, "VarSketch", "SketchBase.m_userId", 80), Member(82, "ProfileRefPlane", "Sketch"), + Member(83, "CurveElem", "Sketch"), Member(84, "LinearDimString", "Sketch"), new(80, "SweepElem", "ProfileData.m_thirdRefPlaneId", 82), + new(87, "SketchPlane", "SketchPlane.m_userId", 81), new(81, "VarSketch", "Sketch.m_sketchPlaneId", 87)], + }; + } + + [Fact] + public void ASketchOfAFormNoTypeDrawsMovesNothing() => AssertBuilt(Undrawn( + // A lock of what is in it to a plane that stays moves nothing either. + SyntheticFamily.Alignment(85, 0, (1, 0, -1), (83, 0, -1)))); + + [Fact] + public void ASketchOfADrawnFormIsRead() => AssertRefused(Undrawn() with { UndrawnForms = new HashSet() }, "84"); + + // What reaches out of the sketch could carry what is in it to the rest of the family. + [Fact] + public void ASketchTiedToAPlaneThatMovesIsRead() => + AssertRefused(Undrawn(SyntheticFamily.Alignment(85, 0, (3, 0, -1), (83, 0, -1))), "84"); + + [Fact] + public void ASketchWithADimensionBetweenPlanesThatMoveIsRead() => AssertRefused(Undrawn( + SyntheticFamily.Alignment(85, 0, (3, 0, -1), (2, 0, -1))) + .Add(new FamilyReferrer(85, "Alignment", "SketchMembership.GroupMembership.m_groupId", 81)), "84"); + + [Theory] + // another record stands on what is in the sketch; the sketch plane of the sketch is that of another sketch too + [InlineData(90, "ExtrusionElem", "ElementPlaneRef.m_elemId", 82)] + [InlineData(87, "SketchPlane", "SketchPlane.m_userId", 91)] + public void ASketchThatSomethingElseRefersToIsRead(int record, string className, string field, int target) + { + var records = Undrawn().Add(new FamilyReferrer(record, className, field, target)); + // The shared sketch plane follows the plane of the sketch. + AssertRefused(records.Add(new FamilyReferrer(87, "SketchPlane", "OnDatumPlaneRef.OneElementMovablePlaneRef.m_datumPlaneId", 82)), "84"); + } + + // The instance goes where the plane it stands on goes, and so would what it is locked to. + [Theory] + [InlineData(true)] + [InlineData(false)] + public void AWorkPlaneHoldsWhatStandsOnItAlongItsNormal(bool moves) => AssertRefused( + With([Placed(Instance, host: 52, follows: moves ? new(8, 0, -1) : null, normal: [0, 0, 1])], + SyntheticFamily.Alignment(62, 2, (moves ? 7 : 8, 0, -1), (Instance, 9, 0))), "62"); +} diff --git a/tests/RvtIO.Tests/Families/FamilyImportTests.cs b/tests/RvtIO.Tests/Families/FamilyImportTests.cs new file mode 100644 index 00000000..816430b6 --- /dev/null +++ b/tests/RvtIO.Tests/Families/FamilyImportTests.cs @@ -0,0 +1,175 @@ +using RvtIO.BuiltIns; +using RvtIO.Families; +using RvtIO.Internal; +using RvtIO.Meshes; +using RvtIO.Model; +using Xunit; + +namespace RvtIO.Tests.Families; + +/// A drawing imported into a family is geometry of its shape: it is placed whole where the file has it, and a type +/// only shows or hides it. +public class FamilyImportTests +{ + private const int Import = 900, Symbol = 899; + private const long Shows = 300; + + // The leaf family with an imported drawing that a parameter shows, tied as the records of such a drawing tie it. + private static FamilyRecords WithImport(params FamilyReferrer[] more) + { + var leaf = SyntheticFamily.Leaf(); + return leaf with + { + Imports = new HashSet { Import }, + Associations = [new(Import, (long)BuiltInParameter.IS_VISIBLE_PARAM, Shows)], + Referrers = + [ + .. leaf.Referrers, + new(Import, "ImportInstance", "Element.m_id", Import), + new(Import, "ImportInstance", "Element.m_assocLevelId", 7), + new(Import, "ImportInstance", "Element.m_famId", 700), + new(Import, "ImportInstance", "InstanceInfo.InstInfoBase.m_symbolId", Symbol), + new(Import, "ImportInstance", "FamilyParametrizedElemParamsCell.ParamIdPair.m_famParamId", (int)Shows), + .. more, + ], + }; + } + + [Fact] + public void AnImportedDrawingStandsWhereTheFileHasIt() + { + var (model, refusal) = FamilyModelBuilder.Build(WithImport()); + + Assert.Null(refusal); + var placement = Assert.Single(model!.Placements); + Assert.Equal((Import, (long?)Shows), (placement.ElementId, placement.VisibilityParameterId)); + var solved = FamilySolver.Solve(model, new Dictionary { [100] = 5, [101] = 4, [Shows] = 1 }).Positions!; + Assert.All(placement.Origin, variable => Assert.Equal(model.Variables[variable].Stored, solved[variable])); + } + + // A work plane can follow a plane that a type moves. + [Fact] + public void AnImportedDrawingTiedToAPlaceIsRefused() + { + var (model, refusal) = FamilyModelBuilder.Build( + WithImport(new FamilyReferrer(Import, "ImportInstance", "InsertableInst.m_hostId", 8))); + + Assert.Null(model); + Assert.Contains($"import {Import}", refusal!.Detail); + } + + [Fact] + public void AParameterThatDrivesMoreThanTheVisibilityOfAnImportedDrawingIsRefused() + { + var records = WithImport(); + + var (model, refusal) = FamilyModelBuilder.Build(records with { Associations = [.. records.Associations, new(Import, 4000, 301)] }); + + Assert.Null(model); + Assert.Contains($"{Import}", refusal!.Detail); + } + + [Fact] + public void AnImportPlacedInOneViewIsDrawnThere() + { + Assert.True(FamilyRules.IsDrawnInViewsOnly("ImportInstance", null, 5)); + Assert.False(FamilyRules.IsDrawnInViewsOnly("ImportInstance", null, null)); + } + + // A file with an imported drawing the reader draws as its box: the symbol holds one face of a cylinder of radius 2. + private static RevitFileInfo ImportedFile(double[] transform, bool symbolClipped = false) + { + var face = new GeoFace([2, 0, 0], [1, 0, 0]) + { + OuterVertices = [[2, 0, 0], [0, 2, 0], [0, 2, 2], [2, 0, 2]], RenderStyleId = 5, GeometryNode = 1, + Surface = ExactSurface.Cylinder([0, 0, 0], [1, 0, 0], [0, 1, 0], [0, 0, 1], 2), + }; + return new RevitFileInfo + { + Family = new FamilyData { Elements = [new FamilyElementFacts(Import, "ImportInstance", false, true, false, true, false)] }, + Elements = + [ + new Element + { + Id = Import, NativeRootClassName = "ImportInstance", + Geometry = new GeometryData + { + PlacedSymbolBox = true, ExactMappedInstances = [new GeoInstance { SymbolId = Symbol, Transform = transform }], + }, + }, + new Element { Id = Symbol, Geometry = new GeometryData { Faces = [face], PlacedSymbolClipped = symbolClipped } }, + ], + }; + } + + private static GeometryData Body(RevitFileInfo info) + { + var (listed, _, gaps) = ElementMeshes.FamilyElements(info, info.Family!); + Assert.Empty(gaps); + return Assert.Single(listed).Body!; + } + + [Fact] + public void ALargeImportedDrawingIsPlacedWholeInPlaceOfItsBox() + { + var body = Body(ImportedFile([0.5, 0, 0, 0, 0.5, 0, 0, 0, 0.5, 10, 0, 0])); + + Assert.False(body.PlacedSymbolBox); + var face = Assert.Single(body.Faces); + Assert.Equal([[11, 0, 0], [10, 1, 0], [10, 1, 1], [11, 0, 1]], face.OuterVertices); + Assert.Equal(5, face.NestedRenderStyleId); + // The surface of the face is scaled with it: a point of the placed cylinder of radius 1 has its normal there. + Assert.Equal(1, Math.Abs(face.Surface!.NormalAt([11, 0, 0.5])![0]), 12); + Assert.True(face.Surface.TryLocate([11, 0, 0.5], out var nearest, out _, out _, out _)); + Assert.Equal(11, nearest[0], 12); + } + + // A drawing is imported as fine as it is: showing the family smooth takes the normals of its surfaces and cuts nothing. + [Fact] + public void AnImportedDrawingShownSmoothIsNotCutFiner() + { + var info = ImportedFile([1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0]); + + var drawn = Assert.Single(Assert.Single(ElementMeshes.Extract(RvtDocument.FromInfo(info), + new ElementMeshOptions { SmoothFamilySurfaces = true }).Elements).Meshes); + var carried = Assert.Single(ElementMeshes.CarriedMeshes( + new CarriedInstance(Body(info).Faces, new Dictionary(), new("unsupported-construct", "x"), Cut: false), + _ => 0, smooth: true).Meshes); + + Assert.All([drawn, carried], mesh => + { + Assert.Equal(2, mesh.Indices.Length / 3); + Assert.NotEqual(mesh.Normals[0], mesh.Normals[3]); + }); + } + + // A drawing repeats a point once for every one of its small faces: one vertex serves where the normal is the same too. + [Fact] + public void TheFacesOfADrawingShareTheVerticesThatAreTheSame() + { + static GeoFace Floor(double x) => new() { Normal = [0, 0, 1], OuterVertices = [[x, 0, 0], [x + 1, 0, 0], [x + 1, 1, 0], [x, 1, 0]] }; + var wall = new GeoFace { Normal = [1, 0, 0], OuterVertices = [[1, 0, 0], [1, 1, 0], [1, 1, 1], [1, 0, 1]] }; + GeoFace[] faces = [Floor(0), Floor(1), wall]; + + var apart = Assert.Single(ElementMeshes.Triangulate(faces, _ => 0).Meshes); + var carried = Assert.Single(ElementMeshes.CarriedMeshes( + new CarriedInstance(faces, new Dictionary(), new("unsupported-construct", "x"), Cut: false), + _ => 0, smooth: false).Meshes); + + Assert.Equal(12, apart.Positions.Length / 3); + // The two floors share the two points of their edge; the wall on it keeps its own, for its normal. + Assert.Equal(10, carried.Positions.Length / 3); + Assert.Equal(Corners(apart), Corners(carried)); + + static IEnumerable Corners(TriangleMesh mesh) => mesh.Indices.SelectMany(index => + mesh.Positions.Skip(index * 3).Take(3).Concat(mesh.Normals.Skip(index * 3).Take(3))); + } + + [Fact] + public void ASurfaceStretchedOneWayIsNotKept() => + Assert.Null(Assert.Single(Body(ImportedFile([0.5, 0, 0, 0, 1, 0, 0, 0, 0.5, 0, 0, 0])).Faces).Surface); + + [Fact] + public void AnImportedDrawingWhoseSymbolIsNotWholeStaysABox() => + Assert.True(Body(ImportedFile([0.5, 0, 0, 0, 0.5, 0, 0, 0, 0.5, 0, 0, 0], symbolClipped: true)).PlacedSymbolBox); +} diff --git a/tests/RvtIO.Tests/Families/FamilyModelBuilderTests.cs b/tests/RvtIO.Tests/Families/FamilyModelBuilderTests.cs index 9e1e4009..6ecc990e 100644 --- a/tests/RvtIO.Tests/Families/FamilyModelBuilderTests.cs +++ b/tests/RvtIO.Tests/Families/FamilyModelBuilderTests.cs @@ -103,6 +103,27 @@ public void AParameterBoundStartMayBeAtOrBelowTheSketchPlane(double offset) Assert.Equal(offset, solution.Positions![model.Extrusions[0].Start], 1e-12); } + // A dimension runs along its axis from each reference to the next: the only thing that tells which way a segment the + // file saves without a length grows. The family is saved so, which is why a type may give that segment none. + [Theory] + [InlineData(1)] + [InlineData(-1)] + public void ASegmentSavedWithoutALengthRunsTheWayOfItsDimension(int way) + { + const long Apron = 102; + var model = Model(SyntheticFamily.Apron(Apron, way)); + + foreach (var (apron, code) in new (double, string?)[] { (0.5, null), (0, null), (-0.5, "degenerate-geometry") }) + { + var values = new Dictionary { [Width] = 3, [Height] = 2, [Apron] = apron }; + var solution = FamilySolver.Solve(model, values); + + Assert.Null(solution.Refusal); + Assert.Equal(apron * way, solution.Positions![model.Extrusions[0].Start], 1e-12); + Assert.Equal(code, FamilyContourChecks.Check(model, solution.Positions!, values)?.Code); + } + } + [Fact] public void ADownwardSketchPlaneSwapsTheCapsOfTheModel() { @@ -507,6 +528,16 @@ public static FamilyDimensionRecord Alignment(int id, int axis, params (int, int private static FamilyReference[] References((int Element, int Tag, int Sub)[] references) => references.Select(r => new FamilyReference(r.Element, r.Tag, r.Sub)).ToArray(); + /// The box with the start of its extrusion on a plane at the level, which a dimension along + /// , labelled and saved without a length, holds to the level. + public static FamilyRecords Apron(long parameter, int way) + { + var leaf = Leaf(); + return (leaf with { Planes = [.. leaf.Planes, new(9, "RefPlane", 12, [0, 0, 0], [0, 0, 1])] }) + .Add(Linear(35, 2, 8, [(7, 0, -1), (9, 0, -1)], [0], [parameter], [0]) with { Axis = [0, 0, way] }) + .Add(Alignment(36, 2, (9, 0, -1), (Extrusion, 1, -1))); + } + public static FamilyRecords Without(this FamilyRecords records, int dimension) => records with { Dimensions = records.Dimensions.Where(d => d.Id != dimension).ToList() }; diff --git a/tests/RvtIO.Tests/Families/FamilyReferenceLineTests.cs b/tests/RvtIO.Tests/Families/FamilyReferenceLineTests.cs index 24be108c..5daf8f99 100644 --- a/tests/RvtIO.Tests/Families/FamilyReferenceLineTests.cs +++ b/tests/RvtIO.Tests/Families/FamilyReferenceLineTests.cs @@ -33,6 +33,76 @@ .. SyntheticFamily.Leaf().Referrers, AngularDimensions = [Angle(angleTo)], }; + private const int Circle = 80, CircleSketch = 81, Radius = 84, Diameter = 103; + + // A circle of radius 0.5 in a sketch of its own, centred by alignments on the two centre planes, with a labelled diameter. + private static FamilyRecords WithCircle() => WithLine(Level, Centre) with + { + Lines = + [ + .. WithLine(Level, Centre).Lines, + new(Circle, CircleSketch, false, [0.5, 0, 0], [0.5, 0, 0], new([0, 0, 0], [1, 0, 0], [0, 1, 0], 0.5, 0, 2 * Math.PI)), + ], + Dimensions = + [ + .. WithLine(Level, Centre).Dimensions, + SyntheticFamily.Alignment(82, 0, (Centre, 0, -1), (Circle, 0, -1)), + SyntheticFamily.Alignment(83, 1, (4, 0, -1), (Circle, 0, -1)), + ], + Referrers = + [ + .. WithLine(Level, Centre).Referrers, + new(85, "SketchPlane", "SketchPlane.m_userId", CircleSketch), + new(Circle, "CurveElem", "SketchMembership.GroupMembership.m_groupId", CircleSketch), + new(CircleSketch, "VarSketch", "VarSketchArcObj.VarSketchObj.m_objId", Circle), + new(82, "Alignment", "GeomSegInPlaneRef.GeomRef.m_elemId", Circle), + new(83, "Alignment", "GeomSegInPlaneRef.GeomRef.m_elemId", Circle), + new(Radius, "RadialDim", "ArcRef.GeomRef.m_elemId", Circle), + new(Radius, "RadialDim", "SketchMembership.GroupMembership.m_groupId", CircleSketch), + ], + RadialDimensions = [new(Radius, new(Circle, 0, -1), Diameter, 1, 12, 0, false, 9)], + }; + + [Fact] + public void ADiameterOfACircleNothingStandsOnMovesNothing() + { + var (model, refusal) = FamilyModelBuilder.Build(WithCircle()); + + Assert.Null(refusal); + var solution = FamilySolver.Solve(model!, + new Dictionary { [100] = 3, [101] = 5, [AngleParameter] = 0, [Diameter] = 7 }); + Assert.Null(solution.Refusal); + Assert.Equal(5, solution.Positions![model!.Extrusions.Single().End], 1e-9); + } + + // What stands on the circle or is held to it would change with its size. + [Theory] + [InlineData("a plane drawn through it")] + [InlineData("a line of another sketch aligned to it")] + [InlineData("a curve of another sketch joined to it")] + public void ADiameterOfACircleSomethingStandsOnIsRefused(string dependent) + { + var records = WithCircle(); + records = dependent switch + { + "a plane drawn through it" => records with + { + Referrers = [.. records.Referrers, new(86, "SketchPlane", "GeomOnPlaneRef.GeomRef.m_elemId", Circle)], + }, + "a line of another sketch aligned to it" => records with + { + Dimensions = [.. records.Dimensions, SyntheticFamily.Alignment(87, 1, (Circle, 0, -1), (Line, 0, -1))], + Referrers = [.. records.Referrers, new(87, "Alignment", "GeomSegInPlaneRef.GeomRef.m_elemId", Circle)], + }, + _ => records with + { + Referrers = [.. records.Referrers, new(Line, "CurveElem", "CurveElemDriver.EndInfo.m_elemId", Circle)], + }, + }; + + AssertRefused(records, "unrecognized-reference", $"RadialDim {Radius}"); + } + private static void AssertRefused(FamilyRecords records, string code, string detail) { var (model, refusal) = FamilyModelBuilder.Build(records); @@ -127,6 +197,16 @@ public void AnInstanceOnAPlaneThroughALineThatStaysStandsWhereItStood() } } + // What gives an instance its parameters is read from both its symbols: one that is not read is refused, not a failure. + [Fact] + public void AnInstanceWithoutItsMasterSymbolIsRefused() + { + var records = WithInstanceOnTheLine(Level); + + AssertRefused(records with { Instances = [records.Instances![0] with { MasterSymbolId = 62 }] }, + "unrecognized-reference", "symbol of instance 60"); + } + // A line held to the top of the box moves with it, and the instance on a plane through the line would move too. [Fact] public void AnInstanceOnAPlaneThroughALineThatMovesIsRefused() => @@ -147,6 +227,223 @@ public void TheAngleOfTheValveIsReadFromTheFile() Assert.False(angle.Driven); } + // The angle between the front line of the box (along x) and `plane`, labelled by a parameter. + private static FamilyRecords WithAngleOnTheBox(FamilyPlaneRecord plane) => SyntheticFamily.Leaf() with + { + Planes = [.. SyntheticFamily.Leaf().Planes.Where(other => other.ElementId != plane.ElementId), plane], + Referrers = + [ + .. SyntheticFamily.Leaf().Referrers, + new(74, "AngularDim", "GeomSegInPlaneRef.GeomRef.m_elemId", 41), + new(74, "AngularDim", "GeomSegInPlaneRef.GeomRef.m_elemId", plane.ElementId), + ], + AngularDimensions = [new(74, [new(41, 0, -1), new(plane.ElementId, 0, -1)], AngleParameter, 0, 12, 0, false)], + }; + + // A line that keeps its axis and a plane across an axis are only moved, never turned: their angle is the one of the + // file in every type, whatever moves them, and a type that labels it with another value is refused. + [Fact] + public void AnAngleBetweenThingsThatNeverTurnOnlyHoldsItsLabel() + { + var (model, refusal) = FamilyModelBuilder.Build( + WithAngleOnTheBox(new(8, "RefPlane", 8, [0, 0, 2], [0, 0, 1]))); + + Assert.Null(refusal); + var kept = FamilySolver.Solve(model!, new Dictionary { [100] = 3, [101] = 5, [AngleParameter] = 0 }); + Assert.Null(kept.Refusal); + Assert.Equal(5, kept.Positions![model!.Extrusions.Single().End], 1e-9); + var turned = FamilySolver.Solve(model, new Dictionary { [100] = 3, [101] = 5, [AngleParameter] = 0.5 }); + Assert.Equal("inconsistent", turned.Refusal!.Code); + Assert.Equal("74", turned.Refusal.Detail); + } + + [Fact] + public void AnAngleToASlantedPlaneIsRefused() => AssertRefused( + WithAngleOnTheBox(new(9, "RefPlane", 12, [0, 0, 0], [0.6, 0.8, 0])), "unrecognized-reference", "AngularDim 74"); + + // A plane that no relation of the model holds may be turned by another angle, here a labelled one to a slanted plane, + // and the angle it keeps to a side of the box would turn that side with it. + [Fact] + public void AnAngleToAPlaneNothingElseHoldsIsRefused() => AssertRefused( + SyntheticFamily.Leaf() with + { + Planes = + [ + .. SyntheticFamily.Leaf().Planes, + new(9, "RefPlane", 12, [0, 0, 0], [0, 1, 0]), new(10, "RefPlane", 12, [0, 0, 0], [0.6, 0.8, 0]), + ], + Referrers = + [ + .. SyntheticFamily.Leaf().Referrers, + new(74, "AngularDim", "GeomSegInPlaneRef.GeomRef.m_elemId", 3), + new(74, "AngularDim", "GeomSegInPlaneRef.GeomRef.m_elemId", 9), + new(75, "AngularDim", "GeomSegInPlaneRef.GeomRef.m_elemId", 9), + new(75, "AngularDim", "GeomSegInPlaneRef.GeomRef.m_elemId", 10), + ], + AngularDimensions = + [ + new(74, [new(3, 0, -1), new(9, 0, -1)], -1, Math.PI / 2, 12, 0, false), + new(75, [new(9, 0, -1), new(10, 0, -1)], AngleParameter, 0.9, 12, 0, false), + ], + }, "unrecognized-reference", "AngularDim 74"); + + private const long LengthParameter = 103; + + // A line along z whose upper end is held to the top and the right side of the box; its lower end is a length from it, + // and an angle to the top turns it about the upper end. A connector stands on it. + private static FamilyRecords WithTurnedLine() => SyntheticFamily.Leaf() with + { + Lines = [.. SyntheticFamily.Leaf().Lines, new(Line, Sketch, true, [1.5, 0, 1], [1.5, 0, 2])], + Dimensions = + [ + .. SyntheticFamily.Leaf().Dimensions, + SyntheticFamily.Alignment(72, 2, (Top, 0, -1), (Line, 0, 1)), SyntheticFamily.Alignment(73, 0, (3, 0, -1), (Line, 0, 1)), + SyntheticFamily.Linear(76, 2, 12, [(Line, 0, 0), (Line, 0, 1)], [0], [LengthParameter], [1]), + ], + Referrers = + [ + .. SyntheticFamily.Leaf().Referrers, + new(72, "Alignment", "GeomSegInPlaneRef.GeomRef.m_elemId", Line), + new(73, "Alignment", "GeomSegInPlaneRef.GeomRef.m_elemId", Line), + new(76, "LinearDimString", "GeomSegInPlaneRef.GeomRef.m_elemId", Line), + new(74, "AngularDim", "GeomSegInPlaneRef.GeomRef.m_elemId", Line), + new(74, "AngularDim", "GeomSegInPlaneRef.GeomRef.m_elemId", Top), + new(74, "AngularDim", "SketchMembership.GroupMembership.m_groupId", Sketch), + new(Sketch, "VarSketch", "ElementIdIndexPairSet.ElementIdPlusIndex.m_elementId", Line), + new(75, "ConnectorElem", "GeomOnPlaneRef.GeomRef.m_elemId", Line), + ], + AngularDimensions = [new(74, [new(Top, 0, -1), new(Line, 0, -1)], AngleParameter, Math.PI / 2, 12, 0, false)], + }; + + private static readonly Dictionary Turned = new() + { + [100] = 3, [101] = 5, [AngleParameter] = 0.5, [LengthParameter] = 4, + }; + + // The length and the angle place the lower end and nothing else: whatever a type gives them, the box is solved. + [Fact] + public void ALineWithAFreeEndTurnsWithoutMovingAnything() + { + var (model, refusal) = FamilyModelBuilder.Build(WithTurnedLine()); + + Assert.Null(refusal); + var solution = FamilySolver.Solve(model!, Turned); + Assert.Null(solution.Refusal); + Assert.Equal(5, solution.Positions![model!.Extrusions.Single().End], 1e-9); + } + + private static string? TypeRefusal(FamilyRecords records) + { + var (model, refusal) = FamilyModelBuilder.Build(records); + if (model == null) return refusal!.Code; + return FamilySolver.Solve(model, Turned).Refusal?.Code; + } + + // What stands on a work plane through the line turns with it. + [Fact] + public void ALineAWorkPlaneGoesThroughIsHeldAtItsAngle() => Assert.NotNull(TypeRefusal(WithTurnedLine() + .Add(new FamilyReferrer(77, "SketchPlane", "GeomOnPlaneRef.GeomRef.m_elemId", Line)))); + + // An end that something else is aligned to carries the turn to it. + [Fact] + public void ALineWithBothEndsHeldIsHeldAtItsAngle() => Assert.NotNull(TypeRefusal(WithTurnedLine() + .Add(SyntheticFamily.Alignment(77, 2, (Level, 0, -1), (Line, 0, 0))) + .Add(new FamilyReferrer(77, "Alignment", "GeomSegInPlaneRef.GeomRef.m_elemId", Line)))); + + // A dimension to the line as a whole moves what it is measured to with the line. + [Fact] + public void ALineSomethingIsMeasuredToIsHeldAtItsAngle() => Assert.NotNull(TypeRefusal(WithTurnedLine() + .Add(SyntheticFamily.Alignment(77, 0, (Line, 0, -1), (2, 0, -1))) + .Add(new FamilyReferrer(77, "Alignment", "GeomSegInPlaneRef.GeomRef.m_elemId", Line)))); + + // A reference to something of the line that is not one of its ends or the line itself is not read: its dimension may hold + // what the length of a free end would drop. + [Fact] + public void ALineSomethingMeasuresByAnotherTagIsHeldAtItsAngle() => Assert.NotNull(TypeRefusal(WithTurnedLine() + .Add(new FamilyDimensionRecord(77, true, [0, 0, 1], 10, [0], [new(Level, 0, -1), new(Line, 2, 0)], [-1], [0], + new HashSet())) + .Add(new FamilyReferrer(77, "Alignment", "GeomSegInPlaneRef.GeomRef.m_elemId", Line)))); + + // An angle of a free end is dropped only when it is read as an angle is: its flags, its segment, the line as a whole. + [Theory] + [InlineData(2, 0, 0)] + [InlineData(12, 2, 0)] + [InlineData(12, 0, 3)] + public void AnAngleOfALineThatIsNotReadIsNotDropped(long flags, long segment, int tag) => Assert.NotNull(TypeRefusal( + WithTurnedLine() with + { + AngularDimensions = [new(74, [new(Top, 0, -1), new(Line, tag, -1)], AngleParameter, Math.PI / 2, flags, segment, false)], + })); + + private const int Left = 70, Right = 76, Down = 77, Membership = 79; + + // Two slanted reference lines in a V under the box: their outer ends follow its sides, a line down from the apex keeps it + // on the centre plane, and one dimension of two segments holds each at an eighth of a turn to that plane. Nothing stands on + // them: whatever the sides do, the apex and the end it leaves free meet the angles. + private static FamilyRecords WithV(double angle = Math.PI / 4) => SyntheticFamily.Leaf() with + { + Lines = + [ + .. SyntheticFamily.Leaf().Lines, new(Left, Sketch, true, [-1.5, 0, 0], [0, 0, -1.5]), + new(Right, Sketch, true, [0, 0, -1.5], [1.5, 0, 0]), new(Down, Sketch, true, [0, 0, -1.5], [0, 0, -2]), + ], + Joints = [.. SyntheticFamily.Leaf().Joints, new(Left, 1, Right, 0), new(Left, 1, Down, 0), new(Right, 0, Down, 0)], + Constraints = [.. SyntheticFamily.Leaf().Constraints, new(Sketch, "VarSketchPPConstrObj")], + Dimensions = + [ + .. SyntheticFamily.Leaf().Dimensions, + SyntheticFamily.Alignment(72, 2, (Level, 0, -1), (Left, 0, 0)), SyntheticFamily.Alignment(73, 0, (2, 0, -1), (Left, 0, 0)), + SyntheticFamily.Alignment(75, 0, (3, 0, -1), (Right, 0, 1)), SyntheticFamily.Alignment(78, 0, (Centre, 0, -1), (Down, 0, -1)), + ], + Referrers = + [ + .. SyntheticFamily.Leaf().Referrers, + new(72, "Alignment", "GeomSegInPlaneRef.GeomRef.m_elemId", Left), + new(73, "Alignment", "GeomSegInPlaneRef.GeomRef.m_elemId", Left), + new(75, "Alignment", "GeomSegInPlaneRef.GeomRef.m_elemId", Right), + new(78, "Alignment", "GeomSegInPlaneRef.GeomRef.m_elemId", Down), + new(74, "AngularDim", "GeomSegInPlaneRef.GeomRef.m_elemId", Right), + new(74, "AngularDim", "GeomSegInPlaneRef.GeomRef.m_elemId", Centre), + new(74, "AngularDim", "GeomSegInPlaneRef.GeomRef.m_elemId", Left), + new(74, "AngularDim", "SketchMembership.GroupMembership.m_groupId", Sketch), + new(Right, "CurveElem", "CurveElemDriver.EndInfo.m_elemId", Left), + ], + AngularDimensions = + [ + new(74, [new(Right, 0, -1), new(Centre, 0, -1)], -1, angle, 12, 1, false), + new(74, [new(Centre, 0, -1), new(Left, 0, -1)], -1, angle, 12, 1, false), + ], + }; + + [Fact] + public void AnglesThatEachLeaveACoordinateOfTheirOwnRestrictNothing() + { + var (model, refusal) = FamilyModelBuilder.Build(WithV()); + + Assert.Null(refusal); + var solution = FamilySolver.Solve(model!, new Dictionary { [100] = 4, [101] = 5 }); + Assert.Null(solution.Refusal); + Assert.Equal(5, solution.Positions![model!.Extrusions.Single().End], 1e-9); + } + + // A length holds the depth of the apex: the angle of one of the lines is then held by the sides alone, and holds them. + [Fact] + public void AnAngleWithNoCoordinateLeftIsRefused() => AssertRefused(WithV() + .Add(SyntheticFamily.Linear(Membership, 2, 12, [(Level, 0, -1), (Left, 0, 1)], [1], [-1], [1.5])) + .Add(new FamilyReferrer(Membership, "LinearDimString", "GeomSegInPlaneRef.GeomRef.m_elemId", Left)), + "unrecognized-reference", "AngularDim 74"); + + // What stands on a work plane through one of the lines turns with it. + [Fact] + public void AnAngleOfALineAWorkPlaneGoesThroughIsRefused() => AssertRefused( + WithV().Add(new FamilyReferrer(Membership, "SketchPlane", "GeomOnPlaneRef.GeomRef.m_elemId", Left)), + "unrecognized-reference", "AngularDim 74"); + + // The angle read is not the one the lines stand at: what it measures is not what it is taken for. + [Fact] + public void AnAngleTheStoredLinesDoNotMakeIsRefused() => + AssertRefused(WithV(Math.PI / 6), "unrecognized-reference", "AngularDim 74"); + // A line of the profile of a form is a line of the model, whatever else it is held to. [Fact] public void ALineOfAProfileIsNotApart() diff --git a/tests/RvtIO.Tests/Families/FamilyRelationReaderTests.cs b/tests/RvtIO.Tests/Families/FamilyRelationReaderTests.cs index 9f01202c..10be9090 100644 --- a/tests/RvtIO.Tests/Families/FamilyRelationReaderTests.cs +++ b/tests/RvtIO.Tests/Families/FamilyRelationReaderTests.cs @@ -28,4 +28,23 @@ public void EitherNameOfThePairNumberIsEnough(string number) => [Fact] public void AClassTheSchemaLacksIsNotMissed() => Assert.Null(FamilyRelationReader.MissingField(Schema("Other", "m_a"))); + + // An element index of a sketch constraint follows four objects of the sketch and its absorbed curves, and counts only + // the filled places among the curves: a curve removed from a sketch leaves its place empty. + [Theory] + [InlineData(11, 20)] + [InlineData(14, 23)] + [InlineData(16, 25)] + [InlineData(10, null)] + [InlineData(17, null)] + public void AConstraintIndexPassesTheEmptyPlacesOfTheCurves(long element, int? curve) => + Assert.Equal(curve, FamilyRelationReader.ConstrainedCurve(element, 7, [20, 21, 22, null, null, 23, 24, 25])); + + [Theory] + [InlineData(3, 9, 15)] + [InlineData(5, 11, 15)] + [InlineData(5, 8, null)] + [InlineData(2, 5, null)] + public void AConstraintIndexFollowsTheAbsorbedCurvesHoweverManyTheCurvesAre(long absorbed, long element, int? curve) => + Assert.Equal(curve, FamilyRelationReader.ConstrainedCurve(element, absorbed, [13, 14, 15])); } diff --git a/tests/RvtIO.Tests/Families/FamilyRevolutionTests.cs b/tests/RvtIO.Tests/Families/FamilyRevolutionTests.cs index a35c795f..b6f2d952 100644 --- a/tests/RvtIO.Tests/Families/FamilyRevolutionTests.cs +++ b/tests/RvtIO.Tests/Families/FamilyRevolutionTests.cs @@ -535,6 +535,113 @@ public void ARecordOfAnUnknownClassThatRefersToTheSketchPlaneOfARevolutionIsRefu Assert.Equal("unrecognized-reference", refusal!.Code); } + // The volume of the solid a profile of straight pieces turns into, its circles cut into the facets of the file: that of the + // circles by the ratio of the area of the polygon to the circle. + private static double Turned(params (double R, double Z)[] side) + { + double ratio = Polygon(1) / Math.PI; + return Enumerable.Range(0, side.Length - 1).Sum(i => Math.PI * (side[i + 1].Z - side[i].Z) + * (side[i].R * side[i].R + side[i].R * side[i + 1].R + side[i + 1].R * side[i + 1].R) / 3) * ratio; + } + + // The side of the rounded cylinder of the radius R, the height H and the rounding r, the arc cut into equal pieces. + private static (double R, double Z)[] RoundedSide(double radius, double height, double rounding, int pieces) => + [ + (radius, 0), + .. Enumerable.Range(0, pieces + 1).Select(i => Math.PI / 2 * i / pieces) + .Select(angle => (radius - rounding + rounding * Math.Cos(angle), height - rounding + rounding * Math.Sin(angle))), + ]; + + private static double[] Rounded(FamilyModel model, double radius, double height, double rounding) => + Solved(model, radius, height, rounding); + + // Of the eighteen facets of a turn an arc of a quarter has five along the profile. + [Fact] + public void ARevolutionWithAnArcInItsProfileFollowsItsRadiiAndItsHeight() + { + var model = Model(SyntheticRevolution.Rounded()); + + Assert.Equal(Turned(RoundedSide(2, 2, 0.5, 5)), Volume(Faces(model, Stored(model))), 1e-9); + Assert.Equal(Turned(RoundedSide(3, 4, 1, 5)), Volume(Faces(model, Rounded(model, 3, 4, 1))), 1e-9); + } + + // Cut as fine along the profile as about the axis, the facets of the two multiply: the arc is cut at the angle an arc of a + // surface of the file is left uncut at, 6 degrees, 15 facets for its quarter. + [Fact] + public void AnArcOfAProfileIsCutAtTheAngleOfASurfaceOfTheFileWhenShown() + { + var model = Model(SyntheticRevolution.Rounded()); + + var faces = FamilyRevolutionBuilder.Faces(Assert.Single(model.Revolutions), Stored(model), _ => 0, 720); + + // The corners along the arc of radius 0.5 about (1.5, 1.5) in radius and height. + var along = faces.SelectMany(face => face.OuterVertices!) + .Select(p => (R: Math.Round(Math.Sqrt(p[0] * p[0] + p[1] * p[1]), 9), Z: Math.Round(p[2], 9))) + .Where(p => p.R >= 1.5 && p.Z >= 1.5 && Math.Abs(Math.Sqrt(Math.Pow(p.R - 1.5, 2) + Math.Pow(p.Z - 1.5, 2)) - 0.5) < 1e-6) + .Distinct(); + Assert.Equal(16, along.Count()); + // The exact solid: a cylinder of radius 2 up to 1.5, and above it the turned quarter of a circle of radius 0.5. + double exact = Math.PI * (4 * 1.5 + 1.5 * 1.5 * 0.5 + 2 * 1.5 * Math.PI * 0.25 / 4 + 2 * 0.125 / 3); + Assert.Equal(exact, Volume(faces), exact * 2e-4); + } + + [Fact] + public void ARadiusAsLargeAsTheHeightIsDegenerate() + { + var model = Model(SyntheticRevolution.Rounded()); + var revolution = Assert.Single(model.Revolutions); + + Assert.True(FamilyRevolutionBuilder.Holds(revolution, Rounded(model, 2, 2, 1), Stored(model))); + Assert.False(FamilyRevolutionBuilder.Holds(revolution, Rounded(model, 2, 2, 2), Stored(model))); + Assert.False(FamilyRevolutionBuilder.Holds(revolution, Rounded(model, 2, 2, 0), Stored(model))); + } + + // The file cuts the arc as it likes along the profile, so the stored faces are held to the surface, not to the pieces. + [Theory] + [InlineData(2)] + [InlineData(3)] + [InlineData(5)] + public void TheStoredFacesOfAnArcAreOnItsSurfaceHoweverTheFileCutsIt(int pieces) + { + var model = Model(SyntheticRevolution.Rounded()); + var revolution = Assert.Single(model.Revolutions); + var cut = revolution with + { + Arcs = [.. revolution.Arcs!.Select(loop => (IReadOnlyList)[.. loop.Select(arc => arc is { } one + ? one with { Facets = pieces } : (FamilyArcSegment?)null)])], + }; + var stored = FamilyRevolutionBuilder.Faces(cut, Stored(model), _ => 0); + + var matched = FamilyRevolutionBuilder.Match(revolution, Stored(model), stored); + + // The bottom, the side, the arc and the top; the line on the axis makes none. + Assert.Equal([0, 1, 2, 3], matched!.Keys.Select(key => key.Segment).Order()); + } + + // Faces of an arc of another radius between the same two ends of the straight lines are on no surface of the revolution. + [Fact] + public void TheStoredFacesOfAnotherArcDoNotMatch() + { + var model = Model(SyntheticRevolution.Rounded()); + var revolution = Assert.Single(model.Revolutions); + var other = FamilyRevolutionBuilder.Faces(revolution, Rounded(model, 2, 2, 0.75), _ => 0); + + Assert.Null(FamilyRevolutionBuilder.Match(revolution, Stored(model), other)); + } + + // An end the sketch holds at no angle leaves the arc anywhere the solver of Revit puts it once something moves: it is + // where the file has it, and a type that would move it is refused. + [Fact] + public void AnArcWithAnUnheldEndStaysAsTheFileDrawsItAndRefusesATypeThatMovesIt() + { + var model = Model(SyntheticRevolution.Rounded(heldEnds: 1)); + + Assert.Equal(Turned(RoundedSide(2, 2, 0.5, 5)), Volume(Faces(model, Rounded(model, 2, 2, 0.5))), 1e-9); + var codes = new[] { (3.0, 2.0, 0.5), (2, 3, 0.5), (2, 2, 0.75) }.Select(type => FamilySolver.Solve(model, + new Dictionary { [Radius] = type.Item1, [Height] = type.Item2, [TopRadius] = type.Item3 }).Refusal?.Code); + Assert.Equal(["inconsistent", "inconsistent", "inconsistent"], codes); + } + private static double Volume(IEnumerable faces) { double volume = 0; @@ -573,6 +680,40 @@ internal static class SyntheticRevolution public static FamilyRecords Frustum() => Records(1, 0.5); + /// A cylinder of radius 2 and height 2 whose top edge is a quarter circle of radius 0.5, labelled by the radial + /// dimension 36 with the parameter of the top radius; the sketch holds the first ends of the arc + /// 43 at their angles. Lines 41 bottom, 42 side, 43 arc, 44 top, 46 on the axis, 45 the axis. + public static FamilyRecords Rounded(int heldEnds = 2) + { + const double radius = 2, height = 2, rounding = 0.5; + var cylinder = Records(radius, radius); + var arc = new FamilyArc([radius - rounding, 0, height - rounding], [1, 0, 0], [0, 0, 1], rounding, 0, Math.PI / 2); + FamilySketchLine[] lines = + [ + new(41, 40, true, [0, 0, 0], [radius, 0, 0]), new(42, 40, true, [radius, 0, 0], [radius, 0, height - rounding]), + new(43, 40, false, [radius, 0, height - rounding], [radius - rounding, 0, height], arc), + new(44, 40, true, [radius - rounding, 0, height], [0, 0, height]), new(46, 40, true, [0, 0, height], [0, 0, 0]), + new(AxisLine, 40, true, [0, 0, 0], [0, 0, height], IsRevolutionAxis: true), + ]; + return cylinder with + { + Lines = lines, + Joints = [new(41, 1, 42, 0), new(42, 1, 43, 0), new(43, 1, 44, 0), new(44, 1, 46, 0), new(46, 1, 41, 0)], + Constraints = [.. cylinder.Constraints, new(40, "VarSketchArcEndAngleConstrObj")], + Dimensions = + [ + SyntheticFamily.Linear(20, 0, 8, [(1, 0, -1), (2, 0, -1)], [0], [Radius], [radius]), + SyntheticFamily.Linear(21, 2, 8, [(4, 0, -1), (5, 0, -1)], [0], [Height], [height]), + SyntheticFamily.Alignment(30, 0, (1, 0, -1), (46, 0, -1)), SyntheticFamily.Alignment(31, 0, (1, 0, -1), (AxisLine, 0, -1)), + SyntheticFamily.Alignment(32, 2, (4, 0, -1), (41, 0, -1)), SyntheticFamily.Alignment(33, 2, (5, 0, -1), (44, 0, -1)), + SyntheticFamily.Alignment(34, 0, (2, 0, -1), (42, 0, -1)), + ], + RadialDimensions = [new(36, new(43, 0, -1), TopRadius, rounding, 8, 0, false, 2)], + ArcEndAngles = [.. Enumerable.Range(0, heldEnds).Select(end => new FamilyArcEndAngle(40, 43, end))], + Revolutions = [Turn() with { Loops = [[new(41, false), new(42, false), new(43, false), new(44, false), new(46, false)]] }], + }; + } + // Planes: 1 centre left/right, 2 right, 3 centre front/back, 4 level, 5 top, 6 top radius. Lines 41-44, counter-clockwise // in the plane of the sketch seen along its normal, 45 the axis. private static FamilyRecords Records(double bottom, double top) diff --git a/tests/RvtIO.Tests/Families/FamilySceneTests.cs b/tests/RvtIO.Tests/Families/FamilySceneTests.cs index 7051328a..ae5bf805 100644 --- a/tests/RvtIO.Tests/Families/FamilySceneTests.cs +++ b/tests/RvtIO.Tests/Families/FamilySceneTests.cs @@ -1,3 +1,4 @@ +using System.Text.Json; using IOScene; using RvtIO.BuiltIns; using RvtIO.Families; @@ -355,6 +356,73 @@ public void ATypeWithAFormTheSceneLacksIsNotShown() Assert.Null(b.Instances); } + private static RvtSceneResult ProgramScene(RevitFileInfo info, MeshSet? meshes = null) + { + var document = RvtDocument.FromInfo(info); + return RvtSceneReader.Read(document, meshes ?? ElementMeshes.Extract(document), + new RvtSceneOptions { ModelKey = "family.rfa", FamilyTypeProgram = true }); + } + + [Fact] + public void AProgramStandsForTheInstancesOfTheOtherTypes() + { + // The type without a name is not listed, so the program numbers B as the second type. + var result = ProgramScene(Computed([Type("A", 3), Type(" ", 5), Type("B", 4)])); + + var types = result.FamilyTypes!; + Assert.Equal(["A", "B"], types.Types.Select(type => type.Name)); + Assert.All(types.Types, type => Assert.Null(type.Instances)); + Assert.All(types.Types, type => Assert.Null(type.Refusal)); + Assert.Empty(types.Geometries); + using var data = JsonDocument.Parse(types.Program!.Data!); + var computed = data.RootElement.GetProperty("types"); + Assert.Equal(2, computed.GetArrayLength()); + Assert.Equal(4, computed[1].GetProperty("values").GetProperty("100").GetDouble()); + } + + [Fact] + public void TheMaterialsOfTheProgramAreGiven() + { + var records = SyntheticFamily.Leaf() with + { + Associations = [new(Extrusion, (long)BuiltInParameter.MATERIAL_ID_PARAM, Finish)], + }; + + var types = ProgramScene(Computed([Type("A", 3, Value(Finish, StorageType.ElementId, Material)), + Type("B", 3, Value(Finish, StorageType.ElementId, Steel))], records)).FamilyTypes!; + + Assert.Equal(Steel, Assert.Single(types.Materials).Id); + } + + [Fact] + public void AFamilyOfOneTypeNeedsNoProgram() => Assert.Null(ProgramScene(Computed([Type("A", 3)])).FamilyTypes!.Program); + + [Fact] + public void ARefusalOfTheModelLeavesNoProgram() + { + var info = Computed([Type("A", 3), Type("B", 4)]); + info.Family = new FamilyData + { + Elements = info.Family!.Elements, Types = info.Family.Types, + Records = info.Family.Records! with { UnsupportedContent = ["FamilyInstance 9"] }, + }; + + var types = ProgramScene(info).FamilyTypes!; + + Assert.Null(types.Program); + Assert.Equal("unsupported-construct", types.Types[1].Refusal!.Code); + } + + [Fact] + public void AProgramIsNotGivenForASceneThatLacksAForm() + { + var types = ProgramScene(Computed([Type("A", 3), Type("B", 4)]), new MeshSet { Elements = [] }).FamilyTypes!; + + Assert.Null(types.Program); + Assert.Equal("not-computed", types.Types[1].Refusal!.Code); + Assert.Contains($"{Extrusion}", types.Types[1].Refusal!.Detail); + } + [Fact] public void ATypeThatIsNotThereCannotBeComputed() { diff --git a/tests/RvtIO.Tests/Families/FamilyTypeProgramTests.cs b/tests/RvtIO.Tests/Families/FamilyTypeProgramTests.cs new file mode 100644 index 00000000..075a7795 --- /dev/null +++ b/tests/RvtIO.Tests/Families/FamilyTypeProgramTests.cs @@ -0,0 +1,454 @@ +using System.ComponentModel; +using System.Diagnostics; +using System.Reflection; +using System.Text; +using RvtIO.Families; +using RvtIO.Meshes; +using RvtIO.Model; +using Xunit; + +namespace RvtIO.Tests.Families; + +/// The script a page computes the types of a family with, run in Node, gives what gives: +/// the same refusals, elements, materials and triangles, with corners and normals to 1e-9. Without Node on the PATH the +/// comparisons are skipped. +public class FamilyTypeProgramTests +{ + private const double Scale = 0.3048, Tolerance = 1e-9; + private const long Width = 100, Height = 101, Diameter = 102, Radius = 103, Finish = 200, Visible = 201; + + // The materials of the synthetic families, and the graphics style 5 that gives material 9. + private static bool IsMaterial(int id) => id is 7 or 8 or 9; + + private static int MaterialOf(GeoFace face) => + face.RenderStyleId is { } own && IsMaterial(own) ? own + : face.NestedRenderStyleId is { } nested && IsMaterial(nested) ? nested + : face.GeometryStyle == 5 ? 9 : 0; + + [Fact] + public void TheScriptCanStandInAPage() + { + Assert.NotEmpty(RvtFamilyTypeProgram.Script); + Assert.DoesNotContain("