diff --git a/CHANGELOG.md b/CHANGELOG.md index 13116ed..dcd4d40 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,10 @@ All notable changes to the `NwcIO` library, the CLI and the `NwcIO.Scene` adapte ## [Unreleased] +### Added + +- Expose the original IFC element identifier as `NwcNode.SourceIfcGlobalId` and `sourceIfcGlobalId` in scene-tree JSON (#291). + ### Fixed - Read IFC string properties and class-96 point geometry in Navisworks model files. The scene adapter preserves point geometry (#291). diff --git a/docs/format-notes.md b/docs/format-notes.md index d35830a..6ad9fe3 100644 --- a/docs/format-notes.md +++ b/docs/format-notes.md @@ -68,6 +68,7 @@ Once inflated, streams serve dedicated roles identified by their signature prefi - `52` display/internal name pair: `[str name][str internal]`. It is the node username, the property tab username and every property key. - **Attributes** (slots may be null): `86` property tab `[str name][ptr 52][i32 flags][i32 n] n x ([ptr 52 key][i32 type][value])` with value by type `0` none, `1,6,7,10,11` `f64`, `5,15` `i64` (Unix seconds and signed integer, respectively), `2,3` `i32`, `4` and `9` string (type 9 was never seen; it is read as a string), `8` class-52 pointer, `12,13` three or two `f64` coordinates; `31` material; `40` translation; `41` translation and quaternion (`x -> R(q)x + t`); `39` 3x3 column-major matrix and translation; `79` hyperlinks; `200` wraps an inline or shared class-185 material asset (§2.4). - **Class 31 material**: `[str name][15 x f64]`. The DWG variant is `[str name][ptr 52 username][i32 zero][14 x f64]`. Its username can be a new object or a back-reference. +- **Imported IFC element IDs**: The class-86 tab with internal name `lcatfconsumer_Element_tab` can hold `lcatfconsumer_parameter_GlobalId` and `lcatfconsumer_parameter_IfcGUID`. The reader exposes their valid 22-character IFC ID as `NwcNode.SourceIfcGlobalId` when all valid values agree. The ID belongs to the node carrying the tab. - **Shared subtrees**: a child pointer may back-reference an earlier node, so the hierarchy is a directed acyclic graph. A node reached through several parents appears once per path when the tree is expanded. - **Preorder index (`seq`)**: walk from the implicit root in stored order, counting groups, with a shared subtree walked again at every place it occurs. The root has index 0. Every fragment's `seq` indexes this expanded sequence and lands on a leaf; `seq` never decreases along the fragments stream, and a leaf owns one contiguous run of fragments. diff --git a/docs/public-api.md b/docs/public-api.md index ece5fd6..619314a 100644 --- a/docs/public-api.md +++ b/docs/public-api.md @@ -17,7 +17,7 @@ The supported surface is the `NwcIO` and `NwcIO.Model.*` namespaces listed here | `NwcReaderOptions` | Per-open options: which streams to read (property records, GUIDs, transforms, meshes, viewpoints, selection sets, TimeLiner), whether to read materials (`ReadMaterials`: decoded from the file on the strict path, named in property records elsewhere, with a neutral inferred colour unless a `revit_Color` record gives one), whether to build the scene tree (`BuildSceneTree`), catalog retention, and `Strict` (throw `InvalidDataException` when an error-level diagnostic is recorded). | | `NwcAssembly` | Federated multi-model assembly: `Create`, `LoadFromDirectory` (several patterns, recursion), `OpenManifest` (`.nwf.xml`), `OpenNwf` (with `UnresolvedXRefs`/`SkippedXRefs` reporting), combined meshes/materials/bounds, per-assembly exports and clash runs. | | `NwcDiagnostic` / `NwcDiagnosticSeverity` | Reader warning for skipped or substituted data (`Severity`, stable `Code`, `Message`, optional `StreamIndex` and `ByteOffset`), listed in `NwcDocument.Diagnostics` and `NwcAssembly.Diagnostics`. Codes: `meshes-skipped` (geometry records dropped because their vertex count is out of range or they are truncated or malformed; not raised on the strict DbCache path), `property-scan-failed` (the first malformed string met by the lenient property scan, with its stream index and byte offset; not raised on the strict DbCache path), `ContainerTrailingGap` (bytes after the last container stream, including a truncated zlib stream), `NwfUnresolvedXref` and `NwfSkippedXref` (from `NwcAssembly.OpenNwf`). They are included in JSON export (`diagnostics`) and printed by `nwcio --report`. | -| `NwcNode` | Scene graph tree node representing layers, categories, composite elements, and geometry instances with optional transformations and properties. For Navisworks model files read through their DbCache directory (the strict path), `Meshes` lists every mesh placed on a leaf and `Mesh` the first, ids are depth-first preorder indices, `Transform` is null; `IsElement` marks Revit element nodes, `ElementGuid` is their export GUID from `LcOpGuidStore`, `IfcGlobalId` is the GlobalId the Revit IFC export gives the element: its valid `IFC_GUID` parameter, else its export GUID in the IFC base-64 form (the rule of `RvtIO.Scene`), and `Element` points every node inside an element (and the second node of a sibling pair that repeats one element) to its element node; properties include the tabs stored in `LcOaPartitionProps`; other files leave `Meshes` empty and `Mesh` null. | +| `NwcNode` | Scene graph tree node representing layers, categories, composite elements, and geometry instances with optional transformations and properties. For Navisworks model files read through their DbCache directory (the strict path), `Meshes` lists every mesh placed on a leaf and `Mesh` the first, ids are depth-first preorder indices, `Transform` is null; `IsElement` marks Revit element nodes, `ElementGuid` is their export GUID from `LcOpGuidStore`, `IfcGlobalId` is the GlobalId the Revit IFC export gives the element: its valid `IFC_GUID` parameter, else its export GUID in the IFC base-64 form (the rule of `RvtIO.Scene`), and `Element` points every node inside an element (and the second node of a sibling pair that repeats one element) to its element node; properties include the tabs stored in `LcOaPartitionProps`; other files leave `Meshes` empty and `Mesh` null. `SourceIfcGlobalId` is the ID of the IFC object imported into this node. It is available with `ReadPropertyRecords = false` when the hierarchy is built. Scene-tree JSON writes it as `sourceIfcGlobalId` when present. | | `NwcPropertyRecord` | Property record (`Class`, `Name`, `Value`, `ValueType`, `Tag`, `FirstInt`; typed `IntValue`, `DoubleValue`, `ReferenceId`, `ReferenceTag`, `ReferenceClass`). On node properties of the strict path, `Class` is the property tab name (category, for example `Element`), `Name` the property name and `FirstInt` the key object id. Records scanned from property streams (`NwcDocument.PropertyRecords`, and node properties of other files) keep their internal class names. `TabInternalName` and `InternalName` are the internal names of the tab and the key on strict-path node properties, null on scanned records. | | `NwcPropertyTab` | One property tab of a strict-path node (`NwcNode.PropertyTabs`, in stored slot order): display `Name`, `InternalName`, `Properties`. A tab object shared by several nodes is one instance. | | `NwcMesh` | Geometry with vertices, triangle indices, `Normals` aligned with vertices, and `LineIndices` for polylines. For `IsPointSet` meshes, each vertex is a point, with optional `PointColors` and no triangle or line indices. JSON mesh summaries include `pointCount` for these meshes. CAD text meshes carry `Text`, `TextStyleIndex`, bounds and a placement. Their vertex and index lists are empty. JSON mesh summaries include `text` and `textStyleIndex`. Meshes also carry a world-space transform, bounding box, and material. Model files hold one mesh per placed fragment; `Id` is the fragment index. Meshes of fragments that share a geometry record share their `Vertices`, `Indices`, `Normals`, `LineIndices`, `LineColors` and `PointColors` arrays; do not mutate them. `GeometryIndex` (the geometry record; −1 outside model files) and `LineColors` (per vertex, line meshes of model files). | diff --git a/src/NwcIO/Internal/Json/JsonExporter.cs b/src/NwcIO/Internal/Json/JsonExporter.cs index bdfbe44..12bf727 100644 --- a/src/NwcIO/Internal/Json/JsonExporter.cs +++ b/src/NwcIO/Internal/Json/JsonExporter.cs @@ -385,6 +385,11 @@ private static async ValueTask WriteNodeRecursive(Utf8JsonWriter writer, NwcNode writer.WriteString("guid", guid.ToString("D")); } + if (node.SourceIfcGlobalId is { } sourceIfcGlobalId) + { + writer.WriteString("sourceIfcGlobalId", sourceIfcGlobalId); + } + if (node.Transform is { } transform) { writer.WriteStartObject("transform"); diff --git a/src/NwcIO/Internal/Parsing/HierarchyParser.cs b/src/NwcIO/Internal/Parsing/HierarchyParser.cs index 94f178a..e21d988 100644 --- a/src/NwcIO/Internal/Parsing/HierarchyParser.cs +++ b/src/NwcIO/Internal/Parsing/HierarchyParser.cs @@ -107,6 +107,37 @@ internal static object ReadMaterialJson(LcObjectReader reader, bool readTexture private static bool IsIfcGlobalId(string? text) => text is { Length: 22 } && text[0] is >= '0' and <= '3' && text.All(c => c is (>= '0' and <= '9') or (>= 'A' and <= 'Z') or (>= 'a' and <= 'z') or '_' or '$'); + private static string? FindSourceIfcGlobalId(List tabs) + { + string? id = null; + foreach (var tab in tabs) + { + // Type and property-set tabs also use the GlobalId key for their own IFC objects. + if (tab.InternalName != "lcatfconsumer_Element_tab") + { + continue; + } + + foreach (var record in tab.Properties) + { + if (record.InternalName is not ("lcatfconsumer_parameter_GlobalId" or "lcatfconsumer_parameter_IfcGUID") || + record.ValueType is not (4 or 9) || !IsIfcGlobalId(record.Value)) + { + continue; + } + + if (id is not null && id != record.Value) + { + return null; + } + + id = record.Value; + } + } + + return id; + } + internal static string FormatUnixSeconds(long unixSeconds) { try @@ -144,6 +175,7 @@ private static List Expand(Node[] top, string rootName, long total, boo Parent = parent, MaterialName = node.MaterialName ?? parent.MaterialName, Transform = node.Transform, + SourceIfcGlobalId = node.SourceIfcGlobalId, }; if (includeProperties) { @@ -225,6 +257,7 @@ private sealed record Node( bool IsHidden, string? MaterialName, NwcTransform? Transform, + string? SourceIfcGlobalId, List Tabs, List Hyperlinks, long OwnProperties, @@ -386,7 +419,8 @@ private Node ReadNode(int classId) } var (size, propertyReferences, height) = Measure(children, ownProperties); - return new Node(classId, name ?? username.Display ?? "", username.Internal ?? "", x, hidden, materialName, transform, tabs, hyperlinks, ownProperties, children, size, propertyReferences, height); + var sourceIfcGlobalId = FindSourceIfcGlobalId(tabs); + return new Node(classId, name ?? username.Display ?? "", username.Internal ?? "", x, hidden, materialName, transform, sourceIfcGlobalId, tabs, hyperlinks, ownProperties, children, size, propertyReferences, height); } // The NODE32 trailer starts with its light objects, then holds the source file metadata (docs/format-notes.md §2.2). diff --git a/src/NwcIO/Model/NwcAssembly.cs b/src/NwcIO/Model/NwcAssembly.cs index 96e84df..2c219da 100644 --- a/src/NwcIO/Model/NwcAssembly.cs +++ b/src/NwcIO/Model/NwcAssembly.cs @@ -439,6 +439,7 @@ NwcNode Renumber(NwcNode source, NwcNode? parent) Class = source.Class, IsHidden = source.IsHidden, Parent = parent, + SourceIfcGlobalId = source.SourceIfcGlobalId, }; copy.Properties.AddRange(source.Properties); foreach (var child in source.Children) diff --git a/src/NwcIO/Model/NwcNode.cs b/src/NwcIO/Model/NwcNode.cs index 0f73482..8391d8c 100644 --- a/src/NwcIO/Model/NwcNode.cs +++ b/src/NwcIO/Model/NwcNode.cs @@ -60,6 +60,12 @@ public sealed class NwcNode /// On a Revit element node: the GlobalId the Revit IFC export gives the element, its valid IFC_GUID parameter (tab LcRevitData_Element), else in the IFC base-64 form; null on other nodes. public string? IfcGlobalId { get; set; } + /// + /// GlobalId from this node's imported IFC element properties, when they contain a valid, unambiguous ID. + /// Available on DbCache models independently of and in addition to . + /// + public string? SourceIfcGlobalId { get; init; } + /// 3D spatial transformation (pose and bounding box) if present. public NwcTransform? Transform { get; set; } diff --git a/tests/NwcIO.Tests/ElementIdentityTests.cs b/tests/NwcIO.Tests/ElementIdentityTests.cs index c50ca23..8ed2a49 100644 --- a/tests/NwcIO.Tests/ElementIdentityTests.cs +++ b/tests/NwcIO.Tests/ElementIdentityTests.cs @@ -1,5 +1,6 @@ using System.Buffers.Binary; using System.Globalization; +using System.Text.Json; using NwcIO.Model; using Xunit; @@ -7,6 +8,10 @@ namespace NwcIO.Tests; public class ElementIdentityTests { + private const string SourceId = "3Ax9$kQwz0Bf8cYp2LmN4r"; + private const string OtherSourceId = "1x35fEForB6foERLzEFlcn"; + private const string IfcElementTab = "lcatfconsumer_Element_tab"; + private static readonly Guid G1 = Guid.Parse("7b0c5a4e-3f2d-4b1a-9c8e-6d5f4e3ef9b1"); private static readonly Guid G2 = Guid.Parse("11111111-2222-4333-8444-555555555555"); @@ -190,6 +195,62 @@ public void Open_PropertiesOff_StillReadsTheIfcGuidParameter() => public void Open_NonElementNodes_HaveNoIfcGlobalId() => Assert.Null(Open([new("L", "LcRevitLayer", Children: [new("E", "LcRevitInstance", X: 1)])], [G1]).RootNode!.Children[0].IfcGlobalId); + [Theory] + [InlineData(SourceId, null, SourceId)] + [InlineData(null, SourceId, SourceId)] + [InlineData(SourceId, SourceId, SourceId)] + [InlineData("invalid", SourceId, SourceId)] + [InlineData("invalid", "also invalid", null)] + [InlineData(SourceId, OtherSourceId, null)] + public void Open_IfcSourceIdentity_RequiresOneValidValue(string? globalId, string? ifcGuid, string? expected) + { + var own = new Tab(null, "Élément", IfcElementTab, + new Prop("GlobalId", "lcatfconsumer_parameter_GlobalId", 4, globalId), + new Prop("IfcGUID", "lcatfconsumer_parameter_IfcGUID", 4, ifcGuid), + new Prop("GlobalId", "unrelated", 4, OtherSourceId)); + var type = new Tab("Element", null, "lcatfconsumer_Type_tab", new Prop("GlobalId", "lcatfconsumer_parameter_GlobalId", 4, OtherSourceId)); + var top = new TreeNode("Parent", "Group", Children: + [ + new("Imported object", "IfcProxy", Slots: [new HTab(type), new PTab(own)], Children: [new("Geometry", "Leaf")]), + ]); + var (hierarchy, props) = SyntheticTree.Write(1, top); + var file = SyntheticNwcFile.Build(hierarchy, null, [], [], partitionProps: props); + var doc = NwcDocument.Open(new MemoryStream(file)); + var element = doc.RootNode!.Children[0].Children[0]; + + Assert.Equal(expected, element.SourceIfcGlobalId); + Assert.False(element.IsElement); + Assert.Null(element.Element); + Assert.Null(element.ElementGuid); + Assert.Null(element.IfcGlobalId); + Assert.Null(Assert.Single(element.Children).SourceIfcGlobalId); + } + + [Fact] + public void Open_IfcAndRevitIds_StayIndependentInTheModelAndExports() + { + var own = new Tab("Element", null, IfcElementTab, new Prop("GlobalId", "lcatfconsumer_parameter_GlobalId", 9, SourceId)); + var doc = Open([new("Group", "Group", Children: [new("Element", "LcRevitInstance", X: 1, Slots: [new HTab(own)])])], + [G1], new NwcReaderOptions { ReadPropertyRecords = false }); + var node = doc.RootNode!.Children[0].Children[0]; + Assert.Equal(SourceId, node.SourceIfcGlobalId); + Assert.Equal(OtherSourceId, node.IfcGlobalId); + Assert.Equal(G1, node.ElementGuid); + Assert.True(node.IsElement); + Assert.Empty(node.PropertyTabs); + + var mesh = new NwcMesh { Id = 7, Node = node, Vertices = [], Indices = [] }; + string meshId = Internal.Export.NwcElementGuid.ForMesh(mesh, "model"); + Assert.Equal(Internal.IfcGuid.FromKey($"model:element:{OtherSourceId}:mesh:7"), meshId); + + var combined = NwcAssembly.Create("Assembly", doc).ToDocument(); + using var json = JsonDocument.Parse(combined.ToJson()); + var root = json.RootElement.GetProperty("sceneTree"); + var combinedNode = root.GetProperty("children")[0].GetProperty("children")[0].GetProperty("children")[0]; + Assert.Equal(SourceId, combinedNode.GetProperty("sourceIfcGlobalId").GetString()); + Assert.False(root.TryGetProperty("sourceIfcGlobalId", out _)); + } + private static NwcDocument Open(TreeNode[] top, Guid[] guids, NwcReaderOptions? o = null) => NwcDocument.Open(new MemoryStream(SyntheticNwcFile.Build(SyntheticTree.Write(1, top).Hierarchy, null, [], [], extraStreams: [("LcOpGuidStore", SyntheticNwcFile.GuidStore(guids))])), o);