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 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.
- 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.
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, labels and material names, 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, 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 |
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 @@ -537,6 +537,7 @@ private static Command Parse(string[] args)
case LegacyReferenceAttributesDocument attributes:
Add("objectLabels", attributes.Labels.Count);
Add("materialNames", attributes.MaterialNames.Count);
Add("propertySets", attributes.PropertySets.Count);
break;
case LegacyReferenceDefinitionsDocument definitions:
Add("polygonMeshes", definitions.Meshes.Count);
Expand Down
19 changes: 15 additions & 4 deletions src/TdbIO.Scene/TdbSceneReader.LegacyReferences.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,9 @@ private static TrimBimSceneResult ReadLegacyReference(string directory, string n
source.Elements.Add(new SceneElement { Id = 1, ModelId = 1, Kind = SceneNodeKind.Model, Name = name });
var instances = Open<LegacyReferenceInstancesDocument>("instances.tsfodat").Instances;
var layers = Open<LegacyReferenceLayersDocument>("layers.tsfodat").Layers.ToDictionary(layer => layer.Id);
var identities = ReadOptional<LegacyReferenceObjectsDocument>("foreignobjects.tsfodat",
"legacy-reference-identity", "object identities")?.Objects.ToDictionary(item => item.Id, item => item.IfcGlobalId) ?? [];
var foreignObjects = ReadOptional<LegacyReferenceObjectsDocument>("foreignobjects.tsfodat",
"legacy-reference-identity", "object identities");
var identities = foreignObjects?.Objects.ToDictionary(item => item.Id, item => item.IfcGlobalId) ?? [];
var savedRelations = ReadOptional<LegacyReferenceHierarchyDocument>("hierarchy.tsfodat",
"legacy-reference-hierarchy", "object relationships")?.Relations ?? [];
var attributes = ReadOptional<LegacyReferenceAttributesDocument>("attributes.tsfodat",
Expand All @@ -57,9 +58,11 @@ private static TrimBimSceneResult ReadLegacyReference(string directory, string n
diagnostics.Add(new(SceneSeverity.Warning, "legacy-reference-hierarchy",
string.Create(CultureInfo.InvariantCulture, $"The older cache omitted {invalidRelations} relationships with invalid endpoints.")));

// Keep the instance objects in their original order, then add related objects without instances.
// Keep instance objects in their original order, then add objects reached by relations or properties.
var propertySets = attributes?.PropertySets ?? [];
uint[] objectKeys = instances.Select(instance => instance.ObjectId)
.Union(usableRelations.SelectMany(relation => new[] { relation.ParentObjectId, relation.ChildObjectId })).ToArray();
.Union(usableRelations.SelectMany(relation => new[] { relation.ParentObjectId, relation.ChildObjectId }))
.Union(propertySets.Where(set => HasObject(set.ObjectId)).Select(set => set.ObjectId)).ToArray();
var objectIndices = objectKeys.Select((key, index) => (key, index)).ToDictionary(pair => pair.key, pair => pair.index);
var relations = usableRelations.Select(relation => new TrimBimObjectRelation(objectIndices[relation.ParentObjectId],
objectIndices[relation.ChildObjectId], (int)relation.KindCode)).ToArray();
Expand Down Expand Up @@ -105,6 +108,14 @@ private static TrimBimSceneResult ReadLegacyReference(string directory, string n
source.Elements.Add(element);
}
TrimBimSceneReader.AddGroupMemberships(source, groupMembers);
var units = (attributes != null && foreignObjects != null ? attributes.ReadPropertyUnits(foreignObjects) : [])
.ToDictionary(unit => unit.Kind);
foreach (var set in propertySets)
{
if (objectIndices.TryGetValue(set.ObjectId, out int index) &&
TrimBimSceneReader.AddSavedPropertySet(source, set.Name, set.Properties, units) is int setId)
source.Elements[index + 1].PropertySetIds.Add(setId);
}

if (generateGeometry)
{
Expand Down
37 changes: 22 additions & 15 deletions src/TdbIO.Scene/TrimBimSceneReader.Properties.cs
Original file line number Diff line number Diff line change
Expand Up @@ -79,25 +79,32 @@ private static void AddPropertySets(SceneDocument scene, TrimBimDocument documen
foreach (var source in document.ReadPropertySets())
{
if (source.ObjectIndices.Count == 0) continue;
var set = new ScenePropertySet
{
Id = scene.PropertySets.Count + 1, Name = source.Name,
Key = $"trimbim:property-set:{Uri.EscapeDataString(source.Name)}",
};
var occurrences = new Dictionary<string, int>(StringComparer.Ordinal);
foreach (var property in source.Properties)
{
if (ConvertProperty(property, units) is not SceneValue value) continue;
string key = PropertyKey(set.Key, property.Name, occurrences);
set.Properties.Add(new SceneProperty { Name = property.Name, Key = key, Value = value });
}
if (set.Properties.Count == 0) continue;
scene.PropertySets.Add(set);
if (AddSavedPropertySet(scene, source.Name, source.Properties, units) is not int setId) continue;
foreach (int index in source.ObjectIndices.Distinct())
scene.Elements[index + 1].PropertySetIds.Add(set.Id);
scene.Elements[index + 1].PropertySetIds.Add(setId);
}
}

internal static int? AddSavedPropertySet(SceneDocument scene, string name, IReadOnlyList<TrimBimProperty> properties,
IReadOnlyDictionary<TrimBimPropertyKind, TrimBimPropertyUnit> units)
{
var set = new ScenePropertySet
{
Id = scene.PropertySets.Count + 1, Name = name,
Key = $"trimbim:property-set:{Uri.EscapeDataString(name)}",
};
var occurrences = new Dictionary<string, int>(StringComparer.Ordinal);
foreach (var property in properties)
{
if (ConvertProperty(property, units) is not SceneValue value) continue;
string key = PropertyKey(set.Key, property.Name, occurrences);
set.Properties.Add(new SceneProperty { Name = property.Name, Key = key, Value = value });
}
if (set.Properties.Count == 0) return null;
scene.PropertySets.Add(set);
return set.Id;
}

private static string PropertyKey(string scope, string name, Dictionary<string, int> occurrences)
{
int occurrence = occurrences.GetValueOrDefault(name) + 1;
Expand Down
85 changes: 83 additions & 2 deletions src/TdbIO/Internal/Container/LegacyReferenceAttributeReader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@ internal static partial class LegacyReferenceCacheReader
{
private const int AttributeHeaderSize = 8;
private const uint ObjectNameAttribute = 29;
private const uint PropertySetAttribute = 30;
private const int PropertySetHeaderSize = 22;
private const int MinimumScalarPropertySize = 17;
private const uint ObjectMetadataAttribute = 31;
private const uint ObjectMaterialAttribute = 33;
private const int ObjectMaterialTailSize = 5;
Expand All @@ -18,11 +21,20 @@ 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))
var propertySets = new List<LegacyReferencePropertySet>();
var propertySetIds = new HashSet<uint>();
foreach (var (id, 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 == PropertySetAttribute)
{
if (!propertySetIds.Add(id)) throw FormatError.At("Duplicate reference cache property set ID", body);
propertySets.Add(ReadPropertySet(data, id, objectId, body + AttributeHeaderSize, body + size));
continue;
}

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"
Expand Down Expand Up @@ -58,7 +70,76 @@ public static LegacyReferenceAttributesDocument ReadAttributes(byte[] data)
labels[objectId] = label;
}
return new LegacyReferenceAttributesDocument(new ReadOnlyDictionary<uint, LegacyReferenceObjectLabel>(labels),
new ReadOnlyDictionary<uint, string>(materialNames));
new ReadOnlyDictionary<uint, string>(materialNames), propertySets.AsReadOnly());
}

private static LegacyReferencePropertySet ReadPropertySet(byte[] data, uint id, uint objectId, int offset, int end)
{
Bytes.Need(offset, PropertySetHeaderSize, end, "Reference cache property set header");
offset += PropertySetHeaderSize;
string name = ReadAttributeText(data, ref offset, end) ?? string.Empty;
string? description = ReadAttributeText(data, ref offset, end);
Bytes.Need(offset, sizeof(uint), end, "Reference cache property count");
uint count = Bytes.U32(data, offset);
offset += sizeof(uint);
Bytes.Need(offset, MinimumScalarPropertySize * (long)count, end, "Reference cache properties");
var properties = new TrimBimProperty[count];
for (int i = 0; i < properties.Length; i++)
{
Bytes.Need(offset, sizeof(uint), end, "Reference cache property layout");
if (Bytes.U32(data, offset) != 1)
throw FormatError.At("Unsupported reference cache property layout", offset);
offset += sizeof(uint);
string propertyName = ReadAttributeText(data, ref offset, end) ?? string.Empty;
string? propertyDescription = ReadAttributeText(data, ref offset, end);
Bytes.Need(offset, sizeof(uint), end, "Reference cache property kind");
TrimBimPropertyKind kind = Bytes.U32(data, offset) switch
{
1 => TrimBimPropertyKind.Text,
2 => TrimBimPropertyKind.Boolean,
3 => TrimBimPropertyKind.Integer,
4 => TrimBimPropertyKind.Number,
5 => TrimBimPropertyKind.Length,
6 => TrimBimPropertyKind.Volume,
7 => TrimBimPropertyKind.Mass,
8 => TrimBimPropertyKind.Area,
9 => TrimBimPropertyKind.Angle,
_ => throw FormatError.At("Unsupported reference cache property kind", offset),
};
offset += sizeof(uint);
properties[i] = new TrimBimProperty(propertyName, kind, ReadLegacyPropertyValue(data, kind, ref offset, end))
{
Description = propertyDescription,
};
}

if (offset != end) throw FormatError.At("Invalid reference cache property set record length", offset);
return new LegacyReferencePropertySet(id, objectId, name, description, Array.AsReadOnly(properties));
}

private static object ReadLegacyPropertyValue(byte[] data, TrimBimPropertyKind kind, ref int offset, int end)
{
if (kind == TrimBimPropertyKind.Text) return ReadAttributeText(data, ref offset, end) ?? string.Empty;
int width = kind switch
{
TrimBimPropertyKind.Boolean => sizeof(byte),
TrimBimPropertyKind.Integer => sizeof(int),
_ => sizeof(double),
};
int start = offset;
Bytes.Need(start, width, end, "Reference cache property value");
offset += width;
if (kind == TrimBimPropertyKind.Boolean)
return data[start] switch
{
0 => false,
1 => true,
_ => throw FormatError.At("Invalid reference cache boolean property", start),
};
if (kind == TrimBimPropertyKind.Integer) return Bytes.I32(data, start);
double value = Bytes.F64(data, start);
if (!double.IsFinite(value)) throw FormatError.At("Non-finite reference cache property value", start);
return value;
}

private static string? ReadAttributeText(byte[] data, ref int offset, int end)
Expand Down
6 changes: 5 additions & 1 deletion src/TdbIO/Internal/Container/LegacyReferenceCacheReader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,11 @@ public static LegacyReferenceObjectsDocument ReadObjects(byte[] data)
long identity = (long)body + ObjectFixedSize + sizeof(uint) * (long)Bytes.U32(data, countOffset);
int end = body + size;
if (identity > end) throw FormatError.At("Invalid reference cache object geometry key count", countOffset);
objects.Add(new LegacyReferenceObject(id, ReadObjectIfcGlobalId(data, (int)identity, end)));
string? ifcGlobalId = ReadObjectIfcGlobalId(data, (int)identity, end);
objects.Add(new LegacyReferenceObject(id, ifcGlobalId)
{
IsIfcProject = ifcGlobalId != null && Bytes.U32(data, body + 52) == 2 && Bytes.U32(data, body + 56) == 91,
});
}
return new LegacyReferenceObjectsDocument(objects.AsReadOnly());
}
Expand Down
32 changes: 32 additions & 0 deletions src/TdbIO/Internal/TrimBimPropertyUnitReader.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
namespace TdbIO.Internal;

internal static class TrimBimPropertyUnitReader
{
private static readonly (TrimBimPropertyKind Kind, string Name, string Factor, double ToSi)[] PropertyUnitFields =
[
(TrimBimPropertyKind.Length, "LENGTHUNIT.Name", "LENGTHUNIT.ScaleFactor", 0.001),
(TrimBimPropertyKind.Area, "AREAUNIT.Name", "AREAUNIT.ScaleFactor", 1),
(TrimBimPropertyKind.Volume, "VOLUMEUNIT.Name", "VOLUMEUNIT.ScaleFactor", 1),
(TrimBimPropertyKind.Mass, "MASSUNIT.Name", "MASSUNIT.ScaleFactor", 1),
(TrimBimPropertyKind.Angle, "PLANEANGLEUNIT.Name", "PLANEANGLEUNIT.Conversion", Math.PI / 180),
];

internal static IEnumerable<TrimBimPropertyUnit> Read(IReadOnlyList<TrimBimProperty> properties)
{
var fields = properties.ToLookup(property => property.Name, property => property.Value, StringComparer.Ordinal);
foreach (var (kind, name, factor, toSi) in PropertyUnitFields)
{
string? unitName = ReadUniqueField(fields[name]) as string;
if (!string.IsNullOrWhiteSpace(unitName) && ReadUniqueField(fields[factor]) is double scale && scale > 0)
yield return new TrimBimPropertyUnit(kind, unitName, scale, toSi);
}
}

private static object? ReadUniqueField(IEnumerable<object> fields)
{
using var entries = fields.GetEnumerator();
if (!entries.MoveNext()) return null;
var value = entries.Current;
return entries.MoveNext() ? null : value;
}
}
Loading
Loading