Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ API between minor releases.

### Added

- Read saved object material names from older reference caches and show them in scene metadata.
- 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.
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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, object relationships and labels, 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, labels and material names, 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 |
Expand Down
1 change: 1 addition & 0 deletions src/TdbIO.Cli/Cli.cs
Original file line number Diff line number Diff line change
Expand Up @@ -536,6 +536,7 @@ private static Command Parse(string[] args)
break;
case LegacyReferenceAttributesDocument attributes:
Add("objectLabels", attributes.Labels.Count);
Add("materialNames", attributes.MaterialNames.Count);
break;
case LegacyReferenceDefinitionsDocument definitions:
Add("polygonMeshes", definitions.Meshes.Count);
Expand Down
9 changes: 5 additions & 4 deletions src/TdbIO.Scene/TdbSceneReader.LegacyReferences.cs
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +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<LegacyReferenceHierarchyDocument>("hierarchy.tsfodat",
"legacy-reference-hierarchy", "object relationships")?.Relations ?? [];
var labels = ReadOptional<LegacyReferenceAttributesDocument>("attributes.tsfodat",
"legacy-reference-labels", "object labels")?.Labels;
var attributes = ReadOptional<LegacyReferenceAttributesDocument>("attributes.tsfodat",
"legacy-reference-attributes", "object attributes");
var instancesByObject = instances.ToLookup(instance => instance.ObjectId);
var usableRelations = new List<LegacyReferenceRelation>();
int invalidRelations = 0;
Expand Down Expand Up @@ -75,7 +75,7 @@ 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 label = attributes?.Labels.GetValueOrDefault(objectKey) ?? default;
var element = new SceneElement
{
Id = ElementId(index), ModelId = 1, ParentId = parents[index] < 0 ? 1 : ElementId(parents[index]),
Expand All @@ -100,7 +100,8 @@ private static TrimBimSceneResult ReadLegacyReference(string directory, string n
}
element.PropertySetIds.Add(propertySetId);
}
TrimBimSceneReader.AddObjectMetadata(source, element, label.Description, label.ObjectType);
TrimBimSceneReader.AddObjectMetadata(source, element, label.Description, label.ObjectType,
attributes?.MaterialNames.GetValueOrDefault(objectKey));
source.Elements.Add(element);
}
TrimBimSceneReader.AddGroupMemberships(source, groupMembers);
Expand Down
7 changes: 5 additions & 2 deletions src/TdbIO.Scene/TrimBimSceneReader.Properties.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,16 +31,19 @@ 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)
internal static void AddObjectMetadata(SceneDocument scene, SceneElement element, string? description,
string? objectType = null, string? materialName = null)
{
if (description == null && objectType == null) return;
if (description == null && objectType == null && materialName == 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) });
if (materialName != null)
set.Properties.Add(new SceneProperty { Name = "Material", Key = $"{key}:material", Value = SceneValue.FromText(materialName) });
scene.PropertySets.Add(set);
element.PropertySetIds.Add(set.Id);
}
Expand Down
21 changes: 18 additions & 3 deletions src/TdbIO/Internal/Container/LegacyReferenceAttributeReader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,21 +7,26 @@ internal static partial class LegacyReferenceCacheReader
private const int AttributeHeaderSize = 8;
private const uint ObjectNameAttribute = 29;
private const uint ObjectMetadataAttribute = 31;
private const uint ObjectMaterialAttribute = 33;
private const int ObjectMaterialTailSize = 5;
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<uint, LegacyReferenceObjectLabel>();
var materialNames = new Dictionary<uint, string>();
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);
if (kind is not (ObjectNameAttribute or ObjectMetadataAttribute or ObjectMaterialAttribute)) continue;
if (!seen.Add((objectId, kind)))
throw FormatError.At(kind == ObjectMaterialAttribute ? "Duplicate reference cache object material attribute"
: "Duplicate reference cache object label attribute", body);

int offset = body + AttributeHeaderSize;
int end = body + size;
Expand All @@ -33,6 +38,15 @@ public static LegacyReferenceAttributesDocument ReadAttributes(byte[] data)
continue;
}

if (kind == ObjectMaterialAttribute)
{
string? name = ReadAttributeText(data, ref offset, end);
if (end - offset != ObjectMaterialTailSize)
throw FormatError.At("Invalid reference cache object material record length", offset);
if (name != null) materialNames.Add(objectId, name);
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);
Expand All @@ -43,7 +57,8 @@ public static LegacyReferenceAttributesDocument ReadAttributes(byte[] data)
if (offset != end) throw FormatError.At("Invalid reference cache object label record length", offset);
labels[objectId] = label;
}
return new LegacyReferenceAttributesDocument(new ReadOnlyDictionary<uint, LegacyReferenceObjectLabel>(labels));
return new LegacyReferenceAttributesDocument(new ReadOnlyDictionary<uint, LegacyReferenceObjectLabel>(labels),
new ReadOnlyDictionary<uint, string>(materialNames));
}

private static string? ReadAttributeText(byte[] data, ref int offset, int end)
Expand Down
14 changes: 11 additions & 3 deletions src/TdbIO/LegacyReferenceCacheDocuments.cs
Original file line number Diff line number Diff line change
Expand Up @@ -57,14 +57,22 @@ internal LegacyReferenceHierarchyDocument(IReadOnlyList<LegacyReferenceRelation>
/// <param name="KindCode">The raw saved relationship code.</param>
public readonly record struct LegacyReferenceRelation(uint Id, uint ParentObjectId, uint ChildObjectId, uint KindCode);

/// <summary>The saved object labels from a legacy reference attribute table.</summary>
/// <summary>The saved object labels and material names from a legacy reference attribute table.</summary>
public sealed class LegacyReferenceAttributesDocument : TdbDocument
{
internal LegacyReferenceAttributesDocument(IReadOnlyDictionary<uint, LegacyReferenceObjectLabel> labels)
: base(TdbFileKind.LegacyReferenceAttributes, []) => Labels = labels;
internal LegacyReferenceAttributesDocument(IReadOnlyDictionary<uint, LegacyReferenceObjectLabel> labels,
IReadOnlyDictionary<uint, string> materialNames)
: base(TdbFileKind.LegacyReferenceAttributes, [])
{
Labels = labels;
MaterialNames = materialNames;
}

/// <summary>Labels by saved foreign object key. Full metadata takes precedence over name-only attributes.</summary>
public IReadOnlyDictionary<uint, LegacyReferenceObjectLabel> Labels { get; }

/// <summary>Nonempty saved material names by foreign object key.</summary>
public IReadOnlyDictionary<uint, string> MaterialNames { get; }
}

/// <summary>The saved descriptive fields of a foreign object in an older reference cache.</summary>
Expand Down
26 changes: 19 additions & 7 deletions tests/TdbIO.Scene.Tests/TdbSceneReader.ReferenceTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -263,18 +263,22 @@ public void KeepsOlderReferenceGeometryWhenTheHierarchyTableIsMalformed()
Assert.Equal(2, result.Document.Elements.Count(element => element.IfcGuid == "0000000000000000000025"));
}

[Fact]
public void UsesSavedObjectLabelsAndGroupNamesInBothPlacementsOfAnOlderCache()
[Theory]
[InlineData(false)]
[InlineData(true)]
public void UsesSavedObjectLabelsAndMaterialsInBothPlacementsOfAnOlderCache(bool generateGeometry)
{
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, "Контур 🟦"));
Synthetic.LegacyReferenceNameRecord(2, 29, "Контур 🟦"),
Synthetic.LegacyReferenceObjectMaterialRecord(3, 25, "Сталь"),
Synthetic.LegacyReferenceObjectMaterialRecord(4, 26, "Бетон"));

var result = TdbSceneReader.Read(path, new() { IncludeReferenceModels = true, GenerateGeometry = false });
var result = TdbSceneReader.Read(path, new() { IncludeReferenceModels = true, GenerateGeometry = generateGeometry });
Assert.Empty(result.Diagnostics);
var scene = result.Document;
var parts = scene.Elements.Where(element => element.IfcGuid == ifcId).ToArray();
Expand All @@ -287,20 +291,28 @@ public void UsesSavedObjectLabelsAndGroupNamesInBothPlacementsOfAnOlderCache()
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("Сталь", Assert.Single(properties, item => item.Key == "trimbim:object:material").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"));
var fallbackObjects = scene.Elements.Where(element => element.Name == "Object 26").ToArray();
Assert.Equal(2, fallbackObjects.Length);
Assert.All(fallbackObjects, element => Assert.Contains(scene.PropertySets, set =>
element.PropertySetIds.Contains(set.Id) && set.Properties.Any(property =>
property.Key == "trimbim:object:material" && property.Value.Text == "Бетон")));
Assert.Equal(generateGeometry ? 4 : 0, scene.Instances.Count);
Assert.All(scene.Instances, instance => Assert.Equal(new RgbaColor(3, 17, 31, 190), instance.Color));
Assert.Empty(scene.Materials);
}

[Fact]
public void KeepsOlderReferenceGeometryWhenTheLabelTableIsMalformed()
public void KeepsOlderReferenceGeometryWhenTheAttributeTableIsMalformed()
{
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.Contains("The older cache object attributes 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"));
}
Expand Down
6 changes: 4 additions & 2 deletions tests/TdbIO.Tests/CliTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -104,16 +104,18 @@ public void InfoCountsOlderReferenceRelationships()
}

[Fact]
public void InfoCountsOlderReferenceObjectLabels()
public void InfoCountsOlderReferenceObjectLabelsAndMaterialNames()
{
string file = File("attributes.tsfodat", Gzip(Concat(LegacyReferenceNameRecord(1, 25, "Post"),
LegacyReferenceLabelRecord(2, 25, "Post", "Steel post", "Post type"))));
LegacyReferenceLabelRecord(2, 25, "Post", "Steel post", "Post type"),
LegacyReferenceObjectMaterialRecord(3, 25, "Steel"), LegacyReferenceObjectMaterialRecord(4, 26, "Concrete"))));
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());
Assert.Equal(2, json.RootElement.GetProperty("materialNames").GetInt32());
}

[Fact]
Expand Down
25 changes: 25 additions & 0 deletions tests/TdbIO.Tests/LegacyReferenceCacheTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,31 @@ public void ReadsSavedLabelsAndPrefersTheFullMetadataRegardlessOfOrder(bool reve
Assert.Equal(default, document.Labels[9]);
}

[Fact]
public void ReadsMaterialNamesByObjectKeyIndependentlyOfObjectLabels()
{
using var file = new MemoryStream(Gzip(Concat(LegacyReferenceObjectMaterialRecord(1, 25, "Сталь 🟦"),
LegacyReferenceNameRecord(2, 25, "Member"), LegacyReferenceObjectMaterialRecord(3, 26, "Concrete"),
LegacyReferenceObjectMaterialRecord(4, 27, ""))));
var document = Assert.IsType<LegacyReferenceAttributesDocument>(TdbFile.Open(file, "attributes.tsfodat"));
Assert.Equal("Member", Assert.Single(document.Labels).Value.Name);
Assert.Equal(2, document.MaterialNames.Count);
Assert.Equal("Сталь 🟦", document.MaterialNames[25]);
Assert.Equal("Concrete", document.MaterialNames[26]);
}

[Fact]
public void RejectsTruncatedOrDuplicateMaterialNameRecords()
{
byte[] material = LegacyReferenceObjectMaterialRecord(1, 25, "Steel");
using var truncated = new MemoryStream(Gzip(LegacyReferenceRecord(1, material[8..^1])));
using var duplicate = new MemoryStream(Gzip(Concat(material, LegacyReferenceObjectMaterialRecord(2, 25, "Concrete"))));
Assert.Contains("object material record length", Assert.Throws<InvalidDataException>(
() => TdbFile.Open(truncated, "attributes.tsfodat")).Message);
Assert.Contains("Duplicate reference cache object material", Assert.Throws<InvalidDataException>(
() => TdbFile.Open(duplicate, "attributes.tsfodat")).Message);
}

[Fact]
public void RejectsAnAttributeLengthThatWouldReadIntoTheNextRecord()
{
Expand Down
3 changes: 3 additions & 0 deletions tests/TdbIO.Tests/Synthetic.LegacyReference.cs
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,9 @@ internal static byte[] LegacyReferenceLabelRecord(uint id, uint objectId, string
=> LegacyReferenceRecord(id, Concat(Le32(objectId), Le32(31), LegacyAttributeText("Author 🟦"),
new byte[12 * sizeof(uint) + 21], LegacyAttributeText(name), LegacyAttributeText(description), LegacyAttributeText(objectType)));

internal static byte[] LegacyReferenceObjectMaterialRecord(uint id, uint objectId, string name)
=> LegacyReferenceRecord(id, Concat(Le32(objectId), Le32(33), LegacyAttributeText(name), [0], Le32(-1)));

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)
Expand Down
Loading