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 circular hollow extrusion placements and profile dimensions from older reference caches and show them in scene properties.
- Read stored surface area, volume, center of gravity and solid status from older reference caches and export them with scene properties.
- 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.
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, recognized IFC classes and storeys, object relationships including distribution port connections, labels, materials, property sets and stored geometry measurements, 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, property sets, geometry measurements and circular hollow extrusions, 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 @@ -541,6 +541,7 @@ private static Command Parse(string[] args)
Add("materialNames", attributes.MaterialNames.Count);
Add("propertySets", attributes.PropertySets.Count);
Add("calculatedGeometryValues", attributes.CalculatedGeometryValues.Count);
Add("circularHollowExtrusions", attributes.CircularHollowExtrusions.Count);
break;
case LegacyReferenceDefinitionsDocument definitions:
Add("polygonMeshes", definitions.Meshes.Count);
Expand Down
38 changes: 36 additions & 2 deletions src/TdbIO.Scene/TdbSceneReader.LegacyReferenceMeasurements.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ namespace TdbIO.Scene;

public static partial class TdbSceneReader
{
private static readonly Dictionary<TrimBimPropertyKind, TrimBimPropertyUnit> LegacyCalculatedGeometryUnits = new()
private static readonly Dictionary<TrimBimPropertyKind, TrimBimPropertyUnit> LegacyGeometryPropertyUnits = new()
{
[TrimBimPropertyKind.Volume] = new(TrimBimPropertyKind.Volume, "CUBIC_METRE", 1, 1),
[TrimBimPropertyKind.Area] = new(TrimBimPropertyKind.Area, "SQUARE_METRE", 1, 1),
Expand All @@ -28,8 +28,42 @@ private static void AddLegacyCalculatedGeometry(SceneDocument scene, Dictionary<
new("IsSolid", TrimBimPropertyKind.Boolean, measurements.IsSolid),
];
if (TrimBimSceneReader.AddSavedPropertySet(scene, "CalculatedGeometryValues", properties,
LegacyCalculatedGeometryUnits) is int setId)
LegacyGeometryPropertyUnits) is int setId)
scene.Elements[index + 1].PropertySetIds.Add(setId);
}
}

private static void AddLegacyCircularHollowExtrusions(SceneDocument scene, Dictionary<uint, int> objectIndices,
IReadOnlyDictionary<uint, LegacyReferenceCircularHollowExtrusion> extrusions)
{
foreach (var (objectId, extrusion) in extrusions)
{
if (!objectIndices.TryGetValue(objectId, out int index)) continue;
var element = scene.Elements[index + 1];
var origin = extrusion.Origin;
var axisX = extrusion.AxisX;
var displacement = extrusion.Displacement;
TrimBimProperty[] placement =
[
new("OriginX", TrimBimPropertyKind.Length, origin.X),
new("OriginY", TrimBimPropertyKind.Length, origin.Y),
new("OriginZ", TrimBimPropertyKind.Length, origin.Z),
new("XDirX", TrimBimPropertyKind.Number, axisX.X),
new("XDirY", TrimBimPropertyKind.Number, axisX.Y),
new("XDirZ", TrimBimPropertyKind.Number, axisX.Z),
new("ExtrusionX", TrimBimPropertyKind.Length, displacement.X),
new("ExtrusionY", TrimBimPropertyKind.Length, displacement.Y),
new("ExtrusionZ", TrimBimPropertyKind.Length, displacement.Z),
];
var profile = new List<TrimBimProperty>(3);
if (extrusion.ProfileName is string name)
profile.Add(new("ProfileName", TrimBimPropertyKind.Text, name));
profile.Add(new("Radius", TrimBimPropertyKind.Length, extrusion.Radius));
profile.Add(new("WallThickness", TrimBimPropertyKind.Length, extrusion.WallThickness));
if (TrimBimSceneReader.AddSavedPropertySet(scene, "Extrusion", placement, LegacyGeometryPropertyUnits) is int placementId)
element.PropertySetIds.Add(placementId);
if (TrimBimSceneReader.AddSavedPropertySet(scene, "IfcCircleHollowProfile", profile, LegacyGeometryPropertyUnits) is int profileId)
element.PropertySetIds.Add(profileId);
}
}
}
6 changes: 5 additions & 1 deletion src/TdbIO.Scene/TdbSceneReader.LegacyReferences.cs
Original file line number Diff line number Diff line change
Expand Up @@ -62,11 +62,13 @@ private static TrimBimSceneResult ReadLegacyReference(string directory, string n
// Keep instance objects in their original order, then add non-geometric objects with saved metadata.
var propertySets = attributes?.PropertySets ?? [];
var calculatedGeometry = attributes?.CalculatedGeometryValues;
var circularHollowExtrusions = attributes?.CircularHollowExtrusions;
uint[] objectKeys = instances.Select(instance => instance.ObjectId)
.Union(usableRelations.SelectMany(relation => new[] { relation.ParentObjectId, relation.ChildObjectId }))
.Union(propertySets.Where(set => HasObject(set.ObjectId)).Select(set => set.ObjectId))
.Union(objects.Values.Where(item => item.IfcTypeName != null).Select(item => item.Id))
.Union(calculatedGeometry?.Keys.Where(HasObject) ?? []).ToArray();
.Union(calculatedGeometry?.Keys.Where(HasObject) ?? [])
.Union(circularHollowExtrusions?.Keys.Where(HasObject) ?? []).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 @@ -127,6 +129,8 @@ private static TrimBimSceneResult ReadLegacyReference(string directory, string n
}
if (calculatedGeometry != null)
AddLegacyCalculatedGeometry(source, objectIndices, calculatedGeometry);
if (circularHollowExtrusions != null)
AddLegacyCircularHollowExtrusions(source, objectIndices, circularHollowExtrusions);
if (foreignObjects != null && hierarchy != null)
AddLegacyPortRelations(source, objectIndices, hierarchy.ReadPortRelations(foreignObjects));

Expand Down
36 changes: 35 additions & 1 deletion src/TdbIO/Internal/Container/LegacyReferenceAttributeReader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,10 @@ namespace TdbIO.Internal;
internal static partial class LegacyReferenceCacheReader
{
private const int AttributeHeaderSize = 8;
private const uint ExtrusionAttribute = 4;
private const int ExtrusionFrameSize = 9 * sizeof(double);
private const int CircularHollowDimensionsSize = 2 * sizeof(double);
private const int MinimumCircularHollowExtrusionSize = ExtrusionFrameSize + sizeof(uint) + CircularHollowDimensionsSize;
private const uint ObjectNameAttribute = 29;
private const uint PropertySetAttribute = 30;
private const int PropertySetHeaderSize = 22;
Expand All @@ -23,6 +27,7 @@ public static LegacyReferenceAttributesDocument ReadAttributes(byte[] data)
var labels = new Dictionary<uint, LegacyReferenceObjectLabel>();
var materialNames = new Dictionary<uint, string>();
var calculatedGeometry = new Dictionary<uint, LegacyReferenceGeometryValues>();
var circularHollowExtrusions = new Dictionary<uint, LegacyReferenceCircularHollowExtrusion>();
var seen = new HashSet<(uint ObjectId, uint Kind)>();
var propertySets = new List<LegacyReferencePropertySet>();
var propertySetIds = new HashSet<uint>();
Expand All @@ -31,6 +36,13 @@ public static LegacyReferenceAttributesDocument ReadAttributes(byte[] 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 == ExtrusionAttribute)
{
var extrusion = ReadCircularHollowExtrusion(data, body + AttributeHeaderSize, size - AttributeHeaderSize);
if (!circularHollowExtrusions.TryAdd(objectId, extrusion))
throw FormatError.At("Duplicate reference cache circular hollow extrusion attribute", body);
continue;
}
if (kind == PropertySetAttribute)
{
if (!propertySetIds.Add(id)) throw FormatError.At("Duplicate reference cache property set ID", body);
Expand Down Expand Up @@ -81,7 +93,29 @@ public static LegacyReferenceAttributesDocument ReadAttributes(byte[] data)
}
return new LegacyReferenceAttributesDocument(new ReadOnlyDictionary<uint, LegacyReferenceObjectLabel>(labels),
new ReadOnlyDictionary<uint, string>(materialNames), propertySets.AsReadOnly(),
new ReadOnlyDictionary<uint, LegacyReferenceGeometryValues>(calculatedGeometry));
new ReadOnlyDictionary<uint, LegacyReferenceGeometryValues>(calculatedGeometry),
new ReadOnlyDictionary<uint, LegacyReferenceCircularHollowExtrusion>(circularHollowExtrusions));
}

private static LegacyReferenceCircularHollowExtrusion ReadCircularHollowExtrusion(byte[] data, int offset, int size)
{
if (size < MinimumCircularHollowExtrusionSize)
throw FormatError.At("Invalid reference cache circular hollow extrusion length", offset);
var origin = ReadVector(data, offset);
var axisX = ReadVector(data, offset + 3 * sizeof(double));
var displacement = ReadVector(data, offset + 6 * sizeof(double));
if (axisX == default || displacement == default)
throw FormatError.At("Invalid reference cache extrusion frame", offset);
int radiusOffset = offset + ExtrusionFrameSize;
int end = offset + size;
string? profileName = ReadAttributeText(data, ref radiusOffset, end);
if (end - radiusOffset != CircularHollowDimensionsSize)
throw FormatError.At("Invalid reference cache circular hollow extrusion length", radiusOffset);
double radius = Bytes.F64(data, radiusOffset);
double thickness = Bytes.F64(data, radiusOffset + sizeof(double));
if (!double.IsFinite(radius) || !double.IsFinite(thickness) || thickness <= 0 || thickness >= radius)
throw FormatError.At("Invalid reference cache circular hollow profile dimensions", radiusOffset);
return new LegacyReferenceCircularHollowExtrusion(origin, axisX, displacement, radius, thickness, profileName);
}

private static LegacyReferenceGeometryValues ReadCalculatedGeometry(byte[] data, int offset, int size)
Expand Down
19 changes: 17 additions & 2 deletions src/TdbIO/LegacyReferenceCacheDocuments.cs
Original file line number Diff line number Diff line change
Expand Up @@ -105,18 +105,20 @@ public enum LegacyReferencePortRelationKind
PortConnection,
}

/// <summary>The saved object metadata, property sets and calculated geometry from a legacy reference attribute table.</summary>
/// <summary>The saved object metadata, property sets and geometry attributes from a legacy reference attribute table.</summary>
public sealed class LegacyReferenceAttributesDocument : TdbDocument
{
internal LegacyReferenceAttributesDocument(IReadOnlyDictionary<uint, LegacyReferenceObjectLabel> labels,
IReadOnlyDictionary<uint, string> materialNames, IReadOnlyList<LegacyReferencePropertySet> propertySets,
IReadOnlyDictionary<uint, LegacyReferenceGeometryValues> calculatedGeometryValues)
IReadOnlyDictionary<uint, LegacyReferenceGeometryValues> calculatedGeometryValues,
IReadOnlyDictionary<uint, LegacyReferenceCircularHollowExtrusion> circularHollowExtrusions)
: base(TdbFileKind.LegacyReferenceAttributes, [])
{
Labels = labels;
MaterialNames = materialNames;
PropertySets = propertySets;
CalculatedGeometryValues = calculatedGeometryValues;
CircularHollowExtrusions = circularHollowExtrusions;
}

/// <summary>Labels by saved foreign object key. Full metadata takes precedence over name-only attributes.</summary>
Expand All @@ -131,6 +133,9 @@ internal LegacyReferenceAttributesDocument(IReadOnlyDictionary<uint, LegacyRefer
/// <summary>Geometry measurements written by the importer, keyed by foreign object.</summary>
public IReadOnlyDictionary<uint, LegacyReferenceGeometryValues> CalculatedGeometryValues { get; }

/// <summary>Recognized circular hollow extrusions, keyed by foreign object.</summary>
public IReadOnlyDictionary<uint, LegacyReferenceCircularHollowExtrusion> CircularHollowExtrusions { get; }

/// <summary>Reads declared property units for the single IFC project in the same reference cache.</summary>
public IEnumerable<TrimBimPropertyUnit> ReadPropertyUnits(LegacyReferenceObjectsDocument objects)
{
Expand Down Expand Up @@ -158,6 +163,16 @@ public sealed record LegacyReferencePropertySet(uint Id, uint ObjectId, string N
/// <param name="IsSolid">The importer's saved solid classification.</param>
public readonly record struct LegacyReferenceGeometryValues(double Volume, double Area, ModelVector3D CenterOfGravity, bool IsSolid);

/// <summary>The stored placement and section of a circular hollow extrusion in an older reference cache.</summary>
/// <param name="Origin">Center of the starting profile in cache coordinates, in millimetres.</param>
/// <param name="AxisX">The stored local X direction of the profile.</param>
/// <param name="Displacement">The vector from the start to the end of the extrusion, in millimetres.</param>
/// <param name="Radius">The outer profile radius in millimetres.</param>
/// <param name="WallThickness">The profile wall thickness in millimetres.</param>
/// <param name="ProfileName">The saved profile name, when present.</param>
public readonly record struct LegacyReferenceCircularHollowExtrusion(ModelVector3D Origin, ModelVector3D AxisX,
ModelVector3D Displacement, double Radius, double WallThickness, string? ProfileName = null);

/// <summary>The saved descriptive fields of a foreign object in an older reference cache.</summary>
/// <param name="Name">The saved object name, when present.</param>
/// <param name="Description">The saved object description, when present.</param>
Expand Down
36 changes: 36 additions & 0 deletions tests/TdbIO.Scene.Tests/TdbSceneReader.ReferenceTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -395,6 +395,42 @@ public void ExposesLegacyCalculatedGeometryInSourceUnitsConvertedToSi(bool gener
Assert.DoesNotContain(scene.Elements, element => element.SourceId == "35");
}

[Theory]
[InlineData(false)]
[InlineData(true)]
public void ExposesCircularHollowExtrusionPropertiesAndKeepsSavedMeshInstances(bool generateGeometry)
{
const string guid = "0000000000000000000025";
string path = CreateInput(writeCurrent: false);
string cache = CreateLegacyCache(Synthetic.LegacyReferenceObjectRecord(25, guid));
WriteLegacyAttributes(cache, Synthetic.LegacyReferenceCircularHollowExtrusionRecord(1, 25, profileName: "Duct 250"),
Synthetic.LegacyReferenceCircularHollowExtrusionRecord(2, 99));

var result = TdbSceneReader.Read(path, new() { IncludeReferenceModels = true, GenerateGeometry = generateGeometry });
Assert.Empty(result.Diagnostics);
var scene = result.Document;
Assert.Equal(generateGeometry ? 4 : 0, scene.Instances.Count);
var placement = Assert.Single(scene.PropertySets, item => item.Name == "Extrusion");
var profile = Assert.Single(scene.PropertySets, item => item.Name == "IfcCircleHollowProfile");
var elements = scene.Elements.Where(element => element.IfcGuid == guid).ToArray();
Assert.Equal(2, elements.Length);
Assert.All(elements, element => Assert.Contains(placement.Id, element.PropertySetIds));
Assert.All(elements, element => Assert.Contains(profile.Id, element.PropertySetIds));
var placementValues = placement.Properties.ToDictionary(property => property.Name, property => property.Value);
Assert.Equal(9, placementValues.Count);
Assert.Equal(SceneValue.FromNumber(1.25, SceneUnits.Metre, "1.25 m"), placementValues["OriginX"]);
Assert.Equal(SceneValue.FromNumber(-0.5, SceneUnits.Metre, "-0.5 m"), placementValues["OriginY"]);
Assert.Equal(SceneValue.FromNumber(1, null, "1"), placementValues["XDirY"]);
Assert.Equal(SceneValue.FromNumber(6, SceneUnits.Metre, "6 m"), placementValues["ExtrusionX"]);
Assert.Equal(SceneValue.FromNumber(-8, SceneUnits.Metre, "-8 m"), placementValues["ExtrusionZ"]);
var profileValues = profile.Properties.ToDictionary(property => property.Name, property => property.Value);
Assert.Equal(3, profileValues.Count);
Assert.Equal(SceneValue.FromText("Duct 250"), profileValues["ProfileName"]);
Assert.Equal(SceneValue.FromNumber(0.125, SceneUnits.Metre, "0.125 m"), profileValues["Radius"]);
Assert.Equal(SceneValue.FromNumber(0.002, SceneUnits.Metre, "0.002 m"), profileValues["WallThickness"]);
Assert.DoesNotContain(scene.Elements, element => element.SourceId == "99");
}

private static IEnumerable<SceneProperty> TeklaIds(SceneDocument scene, SceneElement element) =>
scene.PropertySets.Where(set => element.PropertySetIds.Contains(set.Id))
.SelectMany(set => set.Properties)
Expand Down
4 changes: 3 additions & 1 deletion tests/TdbIO.Tests/CliTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,8 @@ public void InfoCountsOlderReferenceObjectAttributes()
LegacyReferenceLabelRecord(2, 25, "Post", "Steel post", "Post type"),
LegacyReferenceObjectMaterialRecord(3, 25, "Steel"), LegacyReferenceObjectMaterialRecord(4, 26, "Concrete"),
LegacyReferencePropertySetRecord(5, 25, "Properties"),
LegacyReferenceCalculatedGeometryRecord(6, 25, 3, 10, 1250, 0, 0, 1))));
LegacyReferenceCalculatedGeometryRecord(6, 25, 3, 10, 1250, 0, 0, 1),
LegacyReferenceCircularHollowExtrusionRecord(7, 25))));
var (exit, stdout, stderr) = Run("info", file, "--json");
Assert.Equal(Cli.ExitOk, exit);
Assert.Empty(stderr);
Expand All @@ -122,6 +123,7 @@ public void InfoCountsOlderReferenceObjectAttributes()
Assert.Equal(2, json.RootElement.GetProperty("materialNames").GetInt32());
Assert.Equal(1, json.RootElement.GetProperty("propertySets").GetInt32());
Assert.Equal(1, json.RootElement.GetProperty("calculatedGeometryValues").GetInt32());
Assert.Equal(1, json.RootElement.GetProperty("circularHollowExtrusions").GetInt32());
}

[Fact]
Expand Down
Loading
Loading