diff --git a/CHANGELOG.md b/CHANGELOG.md index 17150fb..4390afb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,7 @@ API between minor releases. ### Added +- Show saved object names, descriptions and object type text from older reference caches. - Restore the saved object hierarchy and group memberships when exporting references from older caches. - Read saved IFC GlobalIds from older reference caches and link each insertion to its own Tekla object identities. - Read saved double-precision curve sets from older reference caches and export their curve-only lines, points and arcs. diff --git a/README.md b/README.md index d3687c5..6ae1fe3 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`, `definitions.tsfodat`, `textures.tsfodat`) | Legacy reference cache documents | Geometry instances, IFC GlobalIds, object relationships, 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, object relationships and labels, 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.Cli/Cli.cs b/src/TdbIO.Cli/Cli.cs index 4e7e226..9e75d5a 100644 --- a/src/TdbIO.Cli/Cli.cs +++ b/src/TdbIO.Cli/Cli.cs @@ -534,6 +534,9 @@ private static Command Parse(string[] args) case LegacyReferenceHierarchyDocument hierarchy: Add("relationships", hierarchy.Relations.Count); break; + case LegacyReferenceAttributesDocument attributes: + Add("objectLabels", attributes.Labels.Count); + break; case LegacyReferenceDefinitionsDocument definitions: Add("polygonMeshes", definitions.Meshes.Count); Add("curveSets", definitions.CurveSets.Count); diff --git a/src/TdbIO.Scene/TdbSceneReader.LegacyReferences.cs b/src/TdbIO.Scene/TdbSceneReader.LegacyReferences.cs index 1621993..d52e7f1 100644 --- a/src/TdbIO.Scene/TdbSceneReader.LegacyReferences.cs +++ b/src/TdbIO.Scene/TdbSceneReader.LegacyReferences.cs @@ -37,6 +37,8 @@ private static TrimBimSceneResult ReadLegacyReference(string directory, string n "legacy-reference-identity", "object identities")?.Objects.ToDictionary(item => item.Id, item => item.IfcGlobalId) ?? []; var savedRelations = ReadOptional("hierarchy.tsfodat", "legacy-reference-hierarchy", "object relationships")?.Relations ?? []; + var labels = ReadOptional("attributes.tsfodat", + "legacy-reference-labels", "object labels")?.Labels; var instancesByObject = instances.ToLookup(instance => instance.ObjectId); var usableRelations = new List(); int invalidRelations = 0; @@ -73,11 +75,13 @@ private static TrimBimSceneResult ReadLegacyReference(string directory, string n uint objectKey = objectKeys[index]; string id = objectKey.ToString(CultureInfo.InvariantCulture); identities.TryGetValue(objectKey, out string? ifcGlobalId); + var label = labels?.GetValueOrDefault(objectKey) ?? default; var element = new SceneElement { Id = ElementId(index), ModelId = 1, ParentId = parents[index] < 0 ? 1 : ElementId(parents[index]), SourceId = ifcGlobalId ?? id, IfcGuid = ifcGlobalId, - Kind = groupMembers.Contains(index) ? SceneNodeKind.Group : SceneNodeKind.Element, Name = $"Object {id}", + Kind = groupMembers.Contains(index) ? SceneNodeKind.Group : SceneNodeKind.Element, + Name = label.Name ?? $"Object {id}", }; foreach (uint layerId in instancesByObject[objectKey].Select(instance => instance.LayerId).Distinct()) { @@ -96,6 +100,7 @@ private static TrimBimSceneResult ReadLegacyReference(string directory, string n } element.PropertySetIds.Add(propertySetId); } + TrimBimSceneReader.AddObjectMetadata(source, element, label.Description, label.ObjectType); source.Elements.Add(element); } TrimBimSceneReader.AddGroupMemberships(source, groupMembers); diff --git a/src/TdbIO.Scene/TrimBimSceneReader.Properties.cs b/src/TdbIO.Scene/TrimBimSceneReader.Properties.cs index bba3c58..2b85cac 100644 --- a/src/TdbIO.Scene/TrimBimSceneReader.Properties.cs +++ b/src/TdbIO.Scene/TrimBimSceneReader.Properties.cs @@ -31,6 +31,20 @@ private static void AddImportMetadata(SceneDocument scene, TrimBimDocument docum scene.Elements[0].PropertySetIds.Add(set.Id); } + internal static void AddObjectMetadata(SceneDocument scene, SceneElement element, string? description, string? objectType = null) + { + if (description == null && objectType == null) return; + + const string key = "trimbim:object"; + var set = new ScenePropertySet { Id = scene.PropertySets.Count + 1, Name = "TrimBIM", Key = key }; + if (description != null) + set.Properties.Add(new SceneProperty { Name = "Description", Key = $"{key}:description", Value = SceneValue.FromText(description) }); + if (objectType != null) + set.Properties.Add(new SceneProperty { Name = "Object type", Key = $"{key}:object-type", Value = SceneValue.FromText(objectType) }); + scene.PropertySets.Add(set); + element.PropertySetIds.Add(set.Id); + } + internal static void AddGroupMemberships(SceneDocument scene, ILookup groupMembers) { foreach (var members in groupMembers) diff --git a/src/TdbIO.Scene/TrimBimSceneReader.cs b/src/TdbIO.Scene/TrimBimSceneReader.cs index 22a6bee..aa586ec 100644 --- a/src/TdbIO.Scene/TrimBimSceneReader.cs +++ b/src/TdbIO.Scene/TrimBimSceneReader.cs @@ -80,19 +80,7 @@ private static TrimBimSceneResult Convert(TrimBimDocument document, string key, Name = label.Name ?? globalId ?? string.Create(CultureInfo.InvariantCulture, $"Object {index + 1}"), Category = label.TypeName ?? string.Empty, }; - if (label.Description is { } description) - { - var properties = new ScenePropertySet - { - Id = scene.PropertySets.Count + 1, Name = "TrimBIM", Key = "trimbim:object", - Properties = [new SceneProperty - { - Name = "Description", Key = "trimbim:object:description", Value = SceneValue.FromText(description), - }], - }; - scene.PropertySets.Add(properties); - element.PropertySetIds.Add(properties.Id); - } + AddObjectMetadata(scene, element, label.Description); scene.Elements.Add(element); } AddLevels(scene, placements, parents, spatialParents, metresPerUnit); diff --git a/src/TdbIO/Internal/Container/LegacyReferenceAttributeReader.cs b/src/TdbIO/Internal/Container/LegacyReferenceAttributeReader.cs new file mode 100644 index 0000000..067a283 --- /dev/null +++ b/src/TdbIO/Internal/Container/LegacyReferenceAttributeReader.cs @@ -0,0 +1,64 @@ +using System.Collections.ObjectModel; + +namespace TdbIO.Internal; + +internal static partial class LegacyReferenceCacheReader +{ + private const int AttributeHeaderSize = 8; + private const uint ObjectNameAttribute = 29; + private const uint ObjectMetadataAttribute = 31; + private const int ObjectNameTailSize = 96; + private const int ObjectHistoryTextCount = 13; + private const int ObjectHistoryFixedSize = 21; + + public static LegacyReferenceAttributesDocument ReadAttributes(byte[] data) + { + var labels = new Dictionary(); + var seen = new HashSet<(uint ObjectId, uint Kind)>(); + foreach (var (_, body, size) in ReadRecords(data)) + { + if (size < AttributeHeaderSize) throw FormatError.At("Invalid reference cache attribute size", body - 4); + uint objectId = Bytes.U32(data, body); + uint kind = Bytes.U32(data, body + sizeof(uint)); + if (kind is not (ObjectNameAttribute or ObjectMetadataAttribute)) continue; + if (!seen.Add((objectId, kind))) throw FormatError.At("Duplicate reference cache object label attribute", body); + + int offset = body + AttributeHeaderSize; + int end = body + size; + if (kind == ObjectNameAttribute) + { + string? name = ReadAttributeText(data, ref offset, end); + if (end - offset != ObjectNameTailSize) throw FormatError.At("Invalid reference cache object name record length", offset); + labels.TryAdd(objectId, new LegacyReferenceObjectLabel(name, null, null)); + continue; + } + + // The three label fields follow the saved history strings and its fixed-width fields. + for (int i = 0; i < ObjectHistoryTextCount; i++) + offset += sizeof(uint) + ReadAttributeTextLength(data, offset, end); + Bytes.Need(offset, ObjectHistoryFixedSize, end, "Reference cache object history"); + offset += ObjectHistoryFixedSize; + var label = new LegacyReferenceObjectLabel(ReadAttributeText(data, ref offset, end), + ReadAttributeText(data, ref offset, end), ReadAttributeText(data, ref offset, end)); + if (offset != end) throw FormatError.At("Invalid reference cache object label record length", offset); + labels[objectId] = label; + } + return new LegacyReferenceAttributesDocument(new ReadOnlyDictionary(labels)); + } + + private static string? ReadAttributeText(byte[] data, ref int offset, int end) + { + int length = ReadAttributeTextLength(data, offset, end); + int start = offset + sizeof(uint); + offset = start + length; + return length == 0 ? null : Bytes.LengthDelimitedText(data, start, length, Utf16Encoding); + } + + private static int ReadAttributeTextLength(byte[] data, int offset, int end) + { + Bytes.Need(offset, sizeof(uint), end, "Reference cache text length"); + long length = 2L * Bytes.U32(data, offset); + Bytes.Need(offset + sizeof(uint), length, end, "Reference cache text"); + return (int)length; + } +} diff --git a/src/TdbIO/Internal/Container/LegacyReferenceCacheReader.cs b/src/TdbIO/Internal/Container/LegacyReferenceCacheReader.cs index 8a4b373..7eec67c 100644 --- a/src/TdbIO/Internal/Container/LegacyReferenceCacheReader.cs +++ b/src/TdbIO/Internal/Container/LegacyReferenceCacheReader.cs @@ -13,7 +13,7 @@ internal static partial class LegacyReferenceCacheReader private const int ObjectFixedSize = ObjectGeometryKeyCountOffset + sizeof(uint); private const int IfcIdentitySize = 96; private const int IdentityTagSize = 3 * sizeof(uint); - private static readonly Encoding LayerEncoding = new UnicodeEncoding(false, false, true); + private static readonly Encoding Utf16Encoding = new UnicodeEncoding(false, false, true); public static TdbFileKind KindFromName(string? fileName) { @@ -25,6 +25,7 @@ public static TdbFileKind KindFromName(string? fileName) if (string.Equals(name, "textures.tsfodat", StringComparison.OrdinalIgnoreCase)) return TdbFileKind.LegacyReferenceTextures; if (string.Equals(name, "foreignobjects.tsfodat", StringComparison.OrdinalIgnoreCase)) return TdbFileKind.LegacyReferenceObjects; if (string.Equals(name, "hierarchy.tsfodat", StringComparison.OrdinalIgnoreCase)) return TdbFileKind.LegacyReferenceHierarchy; + if (string.Equals(name, "attributes.tsfodat", StringComparison.OrdinalIgnoreCase)) return TdbFileKind.LegacyReferenceAttributes; return TdbFileKind.Unknown; } @@ -44,6 +45,7 @@ public static bool HasRecordHeader(ReadOnlySpan head, TdbFileKind kind) TdbFileKind.LegacyReferenceObjects => head.Length >= RecordHeaderSize + ObjectFixedSize && ObjectFixedSize + sizeof(uint) * (long)Bytes.U32(head, RecordHeaderSize + ObjectGeometryKeyCountOffset) <= size, TdbFileKind.LegacyReferenceHierarchy => size == RelationSize, + TdbFileKind.LegacyReferenceAttributes => size >= AttributeHeaderSize, _ => false, }; } @@ -57,7 +59,7 @@ public static LegacyReferenceLayersDocument ReadLayers(byte[] data) if (size < LayerFixedSize || size != LayerFixedSize + 2L * Bytes.U32(data, body)) throw FormatError.At("Invalid reference cache layer name length", body); if (!ids.Add(id)) throw FormatError.At("Duplicate reference cache layer ID", body - RecordHeaderSize); - string name = Bytes.LengthDelimitedText(data, body + 4, size - LayerFixedSize, LayerEncoding); + string name = Bytes.LengthDelimitedText(data, body + 4, size - LayerFixedSize, Utf16Encoding); layers.Add(new LegacyReferenceLayer(id, name, Bytes.U32(data, body + size - 4))); } return new LegacyReferenceLayersDocument(layers.AsReadOnly()); diff --git a/src/TdbIO/LegacyReferenceCacheDocuments.cs b/src/TdbIO/LegacyReferenceCacheDocuments.cs index 2862ba0..6928aef 100644 --- a/src/TdbIO/LegacyReferenceCacheDocuments.cs +++ b/src/TdbIO/LegacyReferenceCacheDocuments.cs @@ -57,6 +57,22 @@ internal LegacyReferenceHierarchyDocument(IReadOnlyList /// The raw saved relationship code. public readonly record struct LegacyReferenceRelation(uint Id, uint ParentObjectId, uint ChildObjectId, uint KindCode); +/// The saved object labels from a legacy reference attribute table. +public sealed class LegacyReferenceAttributesDocument : TdbDocument +{ + internal LegacyReferenceAttributesDocument(IReadOnlyDictionary labels) + : base(TdbFileKind.LegacyReferenceAttributes, []) => Labels = labels; + + /// Labels by saved foreign object key. Full metadata takes precedence over name-only attributes. + public IReadOnlyDictionary Labels { get; } +} + +/// The saved descriptive fields of a foreign object in an older reference cache. +/// The saved object name, when present. +/// The saved object description, when present. +/// The saved object type text, when present. +public readonly record struct LegacyReferenceObjectLabel(string? Name, string? Description, string? ObjectType); + /// A saved foreign object in an older reference cache. /// The key referenced by geometry instances from the same cache. /// The saved IFC GlobalId when present in a known identity record, otherwise null. diff --git a/src/TdbIO/TdbFile.cs b/src/TdbIO/TdbFile.cs index 620f61d..eee56b1 100644 --- a/src/TdbIO/TdbFile.cs +++ b/src/TdbIO/TdbFile.cs @@ -117,6 +117,7 @@ private static TdbDocument Read(Stream stream, string? fileName, TdbReadOptions TdbFileKind.LegacyReferenceTextures => LegacyReferenceCacheReader.ReadTextures(payload), TdbFileKind.LegacyReferenceObjects => LegacyReferenceCacheReader.ReadObjects(payload), TdbFileKind.LegacyReferenceHierarchy => LegacyReferenceCacheReader.ReadHierarchy(payload), + TdbFileKind.LegacyReferenceAttributes => LegacyReferenceCacheReader.ReadAttributes(payload), _ => throw NotRecognised(), }; } diff --git a/src/TdbIO/TdbFileKind.cs b/src/TdbIO/TdbFileKind.cs index b550167..a9aed2e 100644 --- a/src/TdbIO/TdbFileKind.cs +++ b/src/TdbIO/TdbFileKind.cs @@ -93,4 +93,7 @@ public enum TdbFileKind /// A gzip-compressed reference object relationship table named hierarchy.tsfodat. LegacyReferenceHierarchy, + + /// A gzip-compressed reference object attribute table named attributes.tsfodat. + LegacyReferenceAttributes, } diff --git a/tests/TdbIO.Scene.Tests/TdbSceneReader.ReferenceTests.cs b/tests/TdbIO.Scene.Tests/TdbSceneReader.ReferenceTests.cs index 1dd2aa4..3f2b0fa 100644 --- a/tests/TdbIO.Scene.Tests/TdbSceneReader.ReferenceTests.cs +++ b/tests/TdbIO.Scene.Tests/TdbSceneReader.ReferenceTests.cs @@ -263,6 +263,48 @@ public void KeepsOlderReferenceGeometryWhenTheHierarchyTableIsMalformed() Assert.Equal(2, result.Document.Elements.Count(element => element.IfcGuid == "0000000000000000000025")); } + [Fact] + public void UsesSavedObjectLabelsAndGroupNamesInBothPlacementsOfAnOlderCache() + { + const string ifcId = "0000000000000000000025"; + string path = CreateInput(writeCurrent: false); + string cache = CreateLegacyCache(Synthetic.LegacyReferenceObjectRecord(25, ifcId), + Synthetic.LegacyReferenceObjectRecord(29, "0000000000000000000029")); + WriteLegacyHierarchy(cache, Synthetic.LegacyReferenceRelationRecord(1, 6, 29, 25)); + WriteLegacyAttributes(cache, Synthetic.LegacyReferenceLabelRecord(1, 25, "Стойка", "Входной узел", "Column type"), + Synthetic.LegacyReferenceNameRecord(2, 29, "Контур 🟦")); + + var result = TdbSceneReader.Read(path, new() { IncludeReferenceModels = true, GenerateGeometry = false }); + Assert.Empty(result.Diagnostics); + var scene = result.Document; + var parts = scene.Elements.Where(element => element.IfcGuid == ifcId).ToArray(); + Assert.Equal(2, parts.Length); + Assert.All(parts, element => + { + Assert.Equal("Стойка", element.Name); + var properties = scene.PropertySets.Where(set => element.PropertySetIds.Contains(set.Id)) + .SelectMany(set => set.Properties); + Assert.Equal("Входной узел", Assert.Single(properties, item => item.Name == "Description").Value.Text); + Assert.Equal("Column type", Assert.Single(properties, item => item.Name == "Object type").Value.Text); + Assert.Equal("Контур 🟦", Assert.Single(properties, item => item.Name == "Group").Value.Text); + }); + Assert.Equal(2, scene.Elements.Count(element => element.Kind == SceneNodeKind.Group && element.Name == "Контур 🟦")); + Assert.Equal(2, scene.Elements.Count(element => element.Name == "Object 26")); + } + + [Fact] + public void KeepsOlderReferenceGeometryWhenTheLabelTableIsMalformed() + { + string path = CreateInput(writeCurrent: false); + string cache = CreateLegacyCache(Synthetic.LegacyReferenceObjectRecord(25, "0000000000000000000025")); + WriteLegacyAttributes(cache, Synthetic.LegacyReferenceRecord(1, + Synthetic.Concat(Synthetic.Le32(25), Synthetic.Le32(31), Synthetic.Le32(1000)))); + var result = TdbSceneReader.Read(path, new() { IncludeReferenceModels = true }); + Assert.Contains("The older cache object labels could not be read.", Assert.Single(result.Diagnostics).Message); + Assert.Equal(4, result.Document.Instances.Count); + Assert.Equal(2, result.Document.Elements.Count(element => element.Name == "Object 25")); + } + private static IEnumerable TeklaIds(SceneDocument scene, SceneElement element) => scene.PropertySets.Where(set => element.PropertySetIds.Contains(set.Id)) .SelectMany(set => set.Properties) @@ -390,6 +432,9 @@ public void AssignsAReferenceObjectOnlyToItsSavedInsertion(bool legacy) private static void WriteLegacyHierarchy(string cache, params byte[][] relations) => File.WriteAllBytes(Path.Combine(cache, "hierarchy.tsfodat"), Synthetic.Gzip(Synthetic.Concat(relations))); + private static void WriteLegacyAttributes(string cache, params byte[][] attributes) => + File.WriteAllBytes(Path.Combine(cache, "attributes.tsfodat"), Synthetic.Gzip(Synthetic.Concat(attributes))); + private string CreateLegacyCache(params byte[][] objects) { string cache = Path.Combine(_directory, "RefCacheFolders", $"7_{Synthetic.ReferenceSceneHash}"); diff --git a/tests/TdbIO.Tests/CliTests.cs b/tests/TdbIO.Tests/CliTests.cs index a5eb893..f45ea30 100644 --- a/tests/TdbIO.Tests/CliTests.cs +++ b/tests/TdbIO.Tests/CliTests.cs @@ -103,6 +103,19 @@ public void InfoCountsOlderReferenceRelationships() Assert.Equal(2, json.RootElement.GetProperty("relationships").GetInt32()); } + [Fact] + public void InfoCountsOlderReferenceObjectLabels() + { + string file = File("attributes.tsfodat", Gzip(Concat(LegacyReferenceNameRecord(1, 25, "Post"), + LegacyReferenceLabelRecord(2, 25, "Post", "Steel post", "Post type")))); + var (exit, stdout, stderr) = Run("info", file, "--json"); + Assert.Equal(Cli.ExitOk, exit); + Assert.Empty(stderr); + using var json = JsonDocument.Parse(stdout); + Assert.Equal("LegacyReferenceAttributes", json.RootElement.GetProperty("kind").GetString()); + Assert.Equal(1, json.RootElement.GetProperty("objectLabels").GetInt32()); + } + [Fact] public void InfoShowsSavedTrimBimGeometryLayersInOrder() { @@ -213,6 +226,8 @@ public void ExportsAndProtectsAnOlderReferenceCacheWhenTrimBimIsMissing() string objects = File(Path.Combine(cache, "foreignobjects.tsfodat"), foreignObjects); byte[] relations = Gzip([]); string hierarchy = File(Path.Combine(cache, "hierarchy.tsfodat"), relations); + byte[] labels = Gzip(LegacyReferenceNameRecord(1, 25, "Named reference member")); + string attributes = File(Path.Combine(cache, "attributes.tsfodat"), labels); var export = Run("export", db, "--scene-json", "--reference-models"); Assert.Equal(Cli.ExitOk, export.Exit); @@ -243,6 +258,11 @@ public void ExportsAndProtectsAnOlderReferenceCacheWhenTrimBimIsMissing() Assert.Contains("reference cache", overwrite.Err); Assert.Equal(relations, System.IO.File.ReadAllBytes(hierarchy)); + var overwriteLabels = Run("export", db, attributes, "--scene-json", "--reference-models"); + Assert.Equal(Cli.ExitUsage, overwriteLabels.Exit); + Assert.Contains("reference cache", overwriteLabels.Err); + Assert.Equal(labels, System.IO.File.ReadAllBytes(attributes)); + Directory.CreateDirectory(Path.Combine(_folder, "RefCacheFolders", $"8_{ReferenceSceneHash}")); var ambiguous = Run("export", db, "--scene-json", "--reference-models"); Assert.Contains("Several older cache folders", ambiguous.Err); diff --git a/tests/TdbIO.Tests/LegacyReferenceCacheTests.cs b/tests/TdbIO.Tests/LegacyReferenceCacheTests.cs index 9bd7492..58183a4 100644 --- a/tests/TdbIO.Tests/LegacyReferenceCacheTests.cs +++ b/tests/TdbIO.Tests/LegacyReferenceCacheTests.cs @@ -94,6 +94,43 @@ public void RejectsWrongHierarchyRecordLengthsAndRepeatedRecordKeys() () => TdbFile.Open(duplicate, "hierarchy.tsfodat")).Message); } + [Theory] + [InlineData(false)] + [InlineData(true)] + public void ReadsSavedLabelsAndPrefersTheFullMetadataRegardlessOfOrder(bool reverse) + { + byte[] nameOnly = LegacyReferenceNameRecord(2, 25, "Fallback"); + byte[] full = LegacyReferenceLabelRecord(1, 25, "Балка 🟦", "北側", "Beam type"); + using var file = new MemoryStream(Gzip(Concat(reverse ? full : nameOnly, reverse ? nameOnly : full, + LegacyReferenceNameRecord(3, 8, "Only name"), LegacyReferenceLabelRecord(4, 9, "", "", ""), + LegacyReferenceRecord(5, Concat(Le32(25), Le32(700)))))); + Assert.Equal(TdbFileKind.Unknown, TdbFile.DetectKind(file, "labels.tsfodat")); + Assert.Equal(TdbFileKind.LegacyReferenceAttributes, TdbFile.DetectKind(file, "ATTRIBUTES.TSFODAT")); + var document = Assert.IsType(TdbFile.Open(file, "attributes.tsfodat")); + Assert.Equal(3, document.Labels.Count); + Assert.Equal(new LegacyReferenceObjectLabel("Балка 🟦", "北側", "Beam type"), document.Labels[25]); + Assert.Equal(new LegacyReferenceObjectLabel("Only name", null, null), document.Labels[8]); + Assert.Equal(default, document.Labels[9]); + } + + [Fact] + public void RejectsAnAttributeLengthThatWouldReadIntoTheNextRecord() + { + byte[] shortName = LegacyReferenceRecord(1, Concat(Le32(25), Le32(29), Le32(uint.MaxValue))); + using var file = new MemoryStream(Gzip(Concat(shortName, LegacyReferenceNameRecord(2, 26, "Safe")))); + Assert.Contains("Reference cache text runs past the end", Assert.Throws( + () => TdbFile.Open(file, "attributes.tsfodat")).Message); + } + + [Fact] + public void RejectsRepeatedObjectLabelsOfTheSameKind() + { + using var file = new MemoryStream(Gzip(Concat(LegacyReferenceNameRecord(1, 25, "One"), + LegacyReferenceNameRecord(2, 25, "Two")))); + Assert.Contains("Duplicate reference cache object label attribute", Assert.Throws( + () => TdbFile.Open(file, "attributes.tsfodat")).Message); + } + [Fact] public void ReadsMeshContoursImagesAndOptionalVertexFields() { diff --git a/tests/TdbIO.Tests/Synthetic.LegacyReference.cs b/tests/TdbIO.Tests/Synthetic.LegacyReference.cs index 6e922b0..526510d 100644 --- a/tests/TdbIO.Tests/Synthetic.LegacyReference.cs +++ b/tests/TdbIO.Tests/Synthetic.LegacyReference.cs @@ -57,6 +57,15 @@ internal static byte[] LegacyReferenceObjectRecord(uint id, string? ifcGlobalId, Concat(geometryKeys.Select(Le32).ToArray()), identity)); } + internal static byte[] LegacyReferenceNameRecord(uint id, uint objectId, string name) + => LegacyReferenceRecord(id, Concat(Le32(objectId), Le32(29), LegacyAttributeText(name), new byte[96])); + + internal static byte[] LegacyReferenceLabelRecord(uint id, uint objectId, string name, string description, string objectType) + => LegacyReferenceRecord(id, Concat(Le32(objectId), Le32(31), LegacyAttributeText("Author 🟦"), + new byte[12 * sizeof(uint) + 21], LegacyAttributeText(name), LegacyAttributeText(description), LegacyAttributeText(objectType))); + + private static byte[] LegacyAttributeText(string value) => Concat(Le32(value.Length), Encoding.Unicode.GetBytes(value)); + internal static byte[] LegacyReferenceRelationRecord(uint id, uint kind, uint parent, uint child) => LegacyReferenceRecord(id, Concat(Le32(kind), Le32(parent), Le32(child)));