diff --git a/CHANGELOG.md b/CHANGELOG.md index 9e601fb..2d4e392 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,7 @@ API between minor releases. ### Added +- Read IFC distribution port attachments and connections from older reference caches and show them in scene properties. - Restore recognized IFC classes, storey elevations and spatial containment in scenes from older reference caches. - Read saved property sets from older reference caches and export typed values using the IFC project's declared units. - Read saved object material names from older reference caches and show them in scene metadata. diff --git a/README.md b/README.md index e2cec09..fcbdb30 100644 --- a/README.md +++ b/README.md @@ -223,7 +223,7 @@ extension and the property fields. | `.idrm` | `IdRanges` | Next free value, ranges | One field of each range | | `guid.mapper` | `GuidMapper` | GUID pairs | The header line (raw bytes) | | TrimBIM caches (`.trb`, TRB8) | `TrimBim` | Source object GUIDs, names, classes, descriptions, placements, relationships and geometry | Original cache bytes | -| Older reference cache tables (`layers.tsfodat`, `materials.tsfodat`, `instances.tsfodat`, `foreignobjects.tsfodat`, `hierarchy.tsfodat`, `attributes.tsfodat`, `definitions.tsfodat`, `textures.tsfodat`) | Legacy reference cache documents | Geometry instances, IFC GlobalIds, recognized IFC classes and storeys, object relationships, labels, materials and property sets, polygon meshes with holes and UV or normals, layer names, colors and images | Saved layer state code | +| Older reference cache tables (`layers.tsfodat`, `materials.tsfodat`, `instances.tsfodat`, `foreignobjects.tsfodat`, `hierarchy.tsfodat`, `attributes.tsfodat`, `definitions.tsfodat`, `textures.tsfodat`) | Legacy reference cache documents | Geometry instances, IFC GlobalIds, recognized IFC classes and storeys, object relationships including distribution port connections, labels, materials and property sets, polygon meshes with holes and UV or normals, layer names, colors and images | Saved layer state code | | `history.db` | `History` | Header, revisions and linked object actions | Stored times, action codes and time GUIDs | | `.nc1` (DSTV NC) | `Nc1` | Header fields, geometry, manufacturing data, information entries and comments | Original lines for all blocks, including unrecognized codes | | `.tpl`, `.rpt` | `Template` | Block tree, properties, strings, numbers, identifiers, tuples | Expressions inside strings are not evaluated | diff --git a/src/TdbIO.Scene/TdbSceneReader.LegacyReferencePorts.cs b/src/TdbIO.Scene/TdbSceneReader.LegacyReferencePorts.cs new file mode 100644 index 0000000..ba24e5e --- /dev/null +++ b/src/TdbIO.Scene/TdbSceneReader.LegacyReferencePorts.cs @@ -0,0 +1,44 @@ +using System.Globalization; +using IOScene; + +namespace TdbIO.Scene; + +public static partial class TdbSceneReader +{ + private static void AddLegacyPortRelations(SceneDocument scene, Dictionary objectIndices, + IEnumerable relations) + { + const string key = "tekla:reference-port"; + var sets = new Dictionary(); + foreach (var relation in relations) + { + var from = scene.Elements[objectIndices[relation.FromObjectId] + 1]; + var to = scene.Elements[objectIndices[relation.ToObjectId] + 1]; + if (relation.Kind == LegacyReferencePortRelationKind.ElementAttachment) + Add(to, from, relation.Id, "element", "Owning element IFC GlobalId"); + else + { + Add(from, to, relation.Id, "related-port", "Related port IFC GlobalId"); + Add(to, from, relation.Id, "relating-port", "Relating port IFC GlobalId"); + } + } + + void Add(SceneElement port, SceneElement peer, uint relationId, string role, string name) + { + if (peer.IfcGuid is not string guid) return; + if (!sets.TryGetValue(port.Id, out var set)) + { + set = new ScenePropertySet { Id = scene.PropertySets.Count + 1, Key = key, Name = "IFC port relationships" }; + scene.PropertySets.Add(set); + port.PropertySetIds.Add(set.Id); + sets.Add(port.Id, set); + } + set.Properties.Add(new SceneProperty + { + Name = name, + Key = string.Create(CultureInfo.InvariantCulture, $"{key}:{role}:{relationId}"), + Value = SceneValue.FromText(guid), + }); + } + } +} diff --git a/src/TdbIO.Scene/TdbSceneReader.LegacyReferences.cs b/src/TdbIO.Scene/TdbSceneReader.LegacyReferences.cs index 0792f79..8e31e49 100644 --- a/src/TdbIO.Scene/TdbSceneReader.LegacyReferences.cs +++ b/src/TdbIO.Scene/TdbSceneReader.LegacyReferences.cs @@ -36,8 +36,9 @@ private static TrimBimSceneResult ReadLegacyReference(string directory, string n var foreignObjects = ReadOptional("foreignobjects.tsfodat", "legacy-reference-identity", "object identities"); var objects = foreignObjects?.Objects.ToDictionary(item => item.Id) ?? []; - var savedRelations = ReadOptional("hierarchy.tsfodat", - "legacy-reference-hierarchy", "object relationships")?.Relations ?? []; + var hierarchy = ReadOptional("hierarchy.tsfodat", + "legacy-reference-hierarchy", "object relationships"); + var savedRelations = hierarchy?.Relations ?? []; var attributes = ReadOptional("attributes.tsfodat", "legacy-reference-attributes", "object attributes"); var instancesByObject = instances.ToLookup(instance => instance.ObjectId); @@ -122,6 +123,8 @@ private static TrimBimSceneResult ReadLegacyReference(string directory, string n TrimBimSceneReader.AddSavedPropertySet(source, set.Name, set.Properties, units) is int setId) source.Elements[index + 1].PropertySetIds.Add(setId); } + if (foreignObjects != null && hierarchy != null) + AddLegacyPortRelations(source, objectIndices, hierarchy.ReadPortRelations(foreignObjects)); if (generateGeometry) { diff --git a/src/TdbIO/LegacyReferenceCacheDocuments.cs b/src/TdbIO/LegacyReferenceCacheDocuments.cs index 0398bb3..51a1cfd 100644 --- a/src/TdbIO/LegacyReferenceCacheDocuments.cs +++ b/src/TdbIO/LegacyReferenceCacheDocuments.cs @@ -50,15 +50,61 @@ internal LegacyReferenceHierarchyDocument(IReadOnlyList /// The relationship records, including unrecognised relationship codes. public IReadOnlyList Relations { get; } + + /// Reads recognized distribution port attachments and connections in saved record order. + /// The foreign objects table from the same cache. + /// Records with missing endpoints, unknown classes or a self-connection remain available in . + public IEnumerable ReadPortRelations(LegacyReferenceObjectsDocument objects) + { + ArgumentNullException.ThrowIfNull(objects); + Dictionary? byId = null; + foreach (var relation in Relations) + { + if (relation.KindCode != 0 || relation.ParentObjectId == relation.ChildObjectId) continue; + byId ??= objects.Objects.ToDictionary(item => item.Id); + if (!byId.TryGetValue(relation.ParentObjectId, out var first) || + !byId.TryGetValue(relation.ChildObjectId, out var second) || + second.IfcTypeName != "IFCDISTRIBUTIONPORT") + continue; + + // The cache stores RelatedPort before RelatingPort for IfcRelConnectsPorts. + if (first.IfcTypeName == "IFCDISTRIBUTIONPORT") + yield return new LegacyReferencePortRelation(relation.Id, second.Id, first.Id, LegacyReferencePortRelationKind.PortConnection); + else if (IsIfcElement(first.IfcTypeName)) + yield return new LegacyReferencePortRelation(relation.Id, first.Id, second.Id, LegacyReferencePortRelationKind.ElementAttachment); + } + } + + private static bool IsIfcElement(string? typeName) => typeName is "IFCBEAM" or "IFCBUILDINGELEMENTPROXY" or "IFCCOLUMN" + or "IFCCURTAINWALL" or "IFCDOOR" or "IFCELEMENTASSEMBLY" or "IFCENERGYCONVERSIONDEVICE" or "IFCFLOWFITTING" + or "IFCFLOWSEGMENT" or "IFCFLOWTERMINAL" or "IFCFURNISHINGELEMENT" or "IFCMEMBER" or "IFCPLATE" + or "IFCSLAB" or "IFCSTAIR" or "IFCTRANSPORTELEMENT" or "IFCWALL" or "IFCWINDOW"; } /// A saved relationship between two foreign objects in an older reference cache. /// The key of the relationship record. -/// The foreign object key of the parent or group. -/// The foreign object key of the child or group member. +/// The first foreign object key in the saved record. +/// The second foreign object key in the saved record. /// The raw saved relationship code. public readonly record struct LegacyReferenceRelation(uint Id, uint ParentObjectId, uint ChildObjectId, uint KindCode); +/// An IFC distribution port relationship decoded from an older reference cache. +/// The key of the saved relationship record. +/// The owning element for an attachment, or the IFC RelatingPort for a connection. +/// The attached port for an attachment, or the IFC RelatedPort for a connection. +/// The meaning of the relationship. +public readonly record struct LegacyReferencePortRelation(uint Id, uint FromObjectId, uint ToObjectId, LegacyReferencePortRelationKind Kind); + +/// The supported kinds of distribution port relationship. +public enum LegacyReferencePortRelationKind +{ + /// A port attached to an element. + ElementAttachment, + + /// A connection between two ports, in IFC relationship order. + PortConnection, +} + /// The saved object labels, material names and property sets from a legacy reference attribute table. public sealed class LegacyReferenceAttributesDocument : TdbDocument { diff --git a/tests/TdbIO.Scene.Tests/TdbSceneReader.ReferenceTests.cs b/tests/TdbIO.Scene.Tests/TdbSceneReader.ReferenceTests.cs index a0f9da4..7bfcd9e 100644 --- a/tests/TdbIO.Scene.Tests/TdbSceneReader.ReferenceTests.cs +++ b/tests/TdbIO.Scene.Tests/TdbSceneReader.ReferenceTests.cs @@ -494,6 +494,63 @@ public void RestoresStoreysAndCategoriesFromOlderCachesInEachPlacement(bool tilt } } + [Theory] + [InlineData(false)] + [InlineData(true)] + public void ShowsPortConnectionsOnBothPortsAndKeepsTheirSpatialParents(bool geometry) + { + const string elementGuid = "0000000000000000000025"; + const string relatedGuid = "0000000000000000000028"; + const string relatingGuid = "0000000000000000000029"; + const string storeyGuid = "0000000000000000000031"; + string path = CreateInput(writeCurrent: false); + string cache = CreateLegacyCache( + Synthetic.LegacyTypedReferenceObjectRecord(25, elementGuid, 41), + Synthetic.LegacyTypedReferenceObjectRecord(28, relatedGuid, 65), + Synthetic.LegacyTypedReferenceObjectRecord(29, relatingGuid, 65), + Synthetic.LegacyTypedReferenceObjectRecord(31, storeyGuid, 69, 7)); + WriteLegacyHierarchy(cache, + Synthetic.LegacyReferenceRelationRecord(4, 0, 25, 28), + Synthetic.LegacyReferenceRelationRecord(8, 0, 28, 29), + Synthetic.LegacyReferenceRelationRecord(9, 0, 28, 28), + Synthetic.LegacyReferenceRelationRecord(10, 2, 31, 28), + Synthetic.LegacyReferenceRelationRecord(11, 2, 31, 29)); + + var result = TdbSceneReader.Read(path, new() { IncludeReferenceModels = true, GenerateGeometry = geometry }); + Assert.Empty(result.Diagnostics); + var scene = result.Document; + const string setKey = "tekla:reference-port"; + foreach (var model in scene.Models.Skip(1)) + { + var nodes = scene.Elements.Where(item => item.ModelId == model.Id && item.IfcGuid != null) + .ToDictionary(item => item.IfcGuid!); + var related = nodes[relatedGuid]; + var relating = nodes[relatingGuid]; + var storey = nodes[storeyGuid]; + Assert.Equal(storey.Id, related.ParentId); + Assert.Equal(storey.LevelId, related.LevelId); + Assert.Equal(storey.Id, relating.ParentId); + Assert.Equal(storey.LevelId, relating.LevelId); + Assert.DoesNotContain(scene.PropertySets, set => nodes[elementGuid].PropertySetIds.Contains(set.Id) && set.Key == setKey); + var relatedSet = Assert.Single(scene.PropertySets, set => related.PropertySetIds.Contains(set.Id) && set.Key == setKey); + var relatingSet = Assert.Single(scene.PropertySets, set => relating.PropertySetIds.Contains(set.Id) && set.Key == setKey); + Assert.Collection(relatedSet.Properties, + property => + { + Assert.Equal($"{setKey}:element:4", property.Key); + Assert.Equal(SceneValue.FromText(elementGuid), property.Value); + }, + property => + { + Assert.Equal($"{setKey}:relating-port:8", property.Key); + Assert.Equal(SceneValue.FromText(relatingGuid), property.Value); + }); + var relatedProperty = Assert.Single(relatingSet.Properties); + Assert.Equal($"{setKey}:related-port:8", relatedProperty.Key); + Assert.Equal(SceneValue.FromText(relatedGuid), relatedProperty.Value); + } + } + [Fact] public void ReportsMissingCurrentCachesWithoutReadingAnEarlierRevision() { diff --git a/tests/TdbIO.Tests/LegacyReferenceCacheTests.cs b/tests/TdbIO.Tests/LegacyReferenceCacheTests.cs index cc57db5..98f1842 100644 --- a/tests/TdbIO.Tests/LegacyReferenceCacheTests.cs +++ b/tests/TdbIO.Tests/LegacyReferenceCacheTests.cs @@ -113,6 +113,40 @@ public void ReadsStoredHierarchyKeysEndpointsAndRawCodesInFileOrder() Assert.Empty(Assert.IsType(TdbFile.Open(empty, "hierarchy.tsfodat")).Relations); } + [Fact] + public void ReadsPortRelationsInIfcOrderAndKeepsUnresolvedRecords() + { + using var objectsFile = new MemoryStream(Gzip(Concat( + LegacyTypedReferenceObjectRecord(11, "0000000000000000000011", 41), + LegacyTypedReferenceObjectRecord(12, "0000000000000000000012", 65), + LegacyTypedReferenceObjectRecord(13, "0000000000000000000013", 65), + LegacyTypedReferenceObjectRecord(14, "0000000000000000000014", 68), + LegacyTypedReferenceObjectRecord(15, "0000000000000000000015", 999), + LegacyTypedReferenceObjectRecord(16, null, 65)))); + using var hierarchyFile = new MemoryStream(Gzip(Concat( + LegacyReferenceRelationRecord(7, 0, 11, 12), + LegacyReferenceRelationRecord(2, 0, 12, 13), + LegacyReferenceRelationRecord(3, 0, 12, 13), + LegacyReferenceRelationRecord(4, 0, 12, 12), + LegacyReferenceRelationRecord(5, 0, 14, 12), + LegacyReferenceRelationRecord(6, 0, 15, 12), + LegacyReferenceRelationRecord(8, 0, 11, 16), + LegacyReferenceRelationRecord(9, 0, 99, 12), + LegacyReferenceRelationRecord(10, 0, 12, 11), + LegacyReferenceRelationRecord(11, 2, 11, 12)))); + var objects = Assert.IsType(TdbFile.Open(objectsFile, "foreignobjects.tsfodat")); + var hierarchy = Assert.IsType(TdbFile.Open(hierarchyFile, "hierarchy.tsfodat")); + + Assert.Equal(new[] + { + new LegacyReferencePortRelation(7, 11, 12, LegacyReferencePortRelationKind.ElementAttachment), + new LegacyReferencePortRelation(2, 13, 12, LegacyReferencePortRelationKind.PortConnection), + new LegacyReferencePortRelation(3, 13, 12, LegacyReferencePortRelationKind.PortConnection), + }, hierarchy.ReadPortRelations(objects)); + Assert.Equal(10, hierarchy.Relations.Count); + Assert.Equal(new LegacyReferenceRelation(2, 12, 13, 0), hierarchy.Relations[1]); + } + [Fact] public void RejectsWrongHierarchyRecordLengthsAndRepeatedRecordKeys() {