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

- 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.
- Show saved object names, descriptions and object type text 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, 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, 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
2 changes: 2 additions & 0 deletions src/TdbIO.Cli/Cli.cs
Original file line number Diff line number Diff line change
Expand Up @@ -530,6 +530,8 @@ private static Command Parse(string[] args)
case LegacyReferenceObjectsDocument objects:
Add("objects", objects.Objects.Count);
Add("ifcGlobalIds", objects.Objects.Count(item => item.IfcGlobalId is not null));
Add("ifcTypes", objects.Objects.Count(item => item.IfcTypeName is not null));
Add("storeys", objects.Objects.Count(item => item.IfcTypeName == "IFCBUILDINGSTOREY"));
break;
case LegacyReferenceHierarchyDocument hierarchy:
Add("relationships", hierarchy.Relations.Count);
Expand Down
20 changes: 13 additions & 7 deletions src/TdbIO.Scene/TdbSceneReader.LegacyReferences.cs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ private static TrimBimSceneResult ReadLegacyReference(string directory, string n
var layers = Open<LegacyReferenceLayersDocument>("layers.tsfodat").Layers.ToDictionary(layer => layer.Id);
var foreignObjects = ReadOptional<LegacyReferenceObjectsDocument>("foreignobjects.tsfodat",
"legacy-reference-identity", "object identities");
var identities = foreignObjects?.Objects.ToDictionary(item => item.Id, item => item.IfcGlobalId) ?? [];
var objects = foreignObjects?.Objects.ToDictionary(item => item.Id) ?? [];
var savedRelations = ReadOptional<LegacyReferenceHierarchyDocument>("hierarchy.tsfodat",
"legacy-reference-hierarchy", "object relationships")?.Relations ?? [];
var attributes = ReadOptional<LegacyReferenceAttributesDocument>("attributes.tsfodat",
Expand All @@ -58,15 +58,16 @@ 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 instance objects in their original order, then add objects reached by relations or properties.
// Keep instance objects in their original order, then add non-geometric objects with saved metadata.
var propertySets = attributes?.PropertySets ?? [];
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)).ToArray();
.Union(propertySets.Where(set => HasObject(set.ObjectId)).Select(set => set.ObjectId))
.Union(objects.Values.Where(item => item.IfcTypeName != null).Select(item => item.Id)).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();
int[] parents = TrimBimSceneReader.ReadParents(relations, objectKeys.Length, out _, out int discardedParents);
int[] parents = TrimBimSceneReader.ReadParents(relations, objectKeys.Length, out var spatialParents, out int discardedParents);
if (discardedParents > 0)
diagnostics.Add(new(SceneSeverity.Warning, "legacy-reference-parent",
string.Create(CultureInfo.InvariantCulture, $"The older cache left {discardedParents} objects at the scene root after encountering conflicting or cyclic parents.")));
Expand All @@ -77,14 +78,17 @@ 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 savedObject = objects.GetValueOrDefault(objectKey);
string? ifcGlobalId = savedObject.IfcGlobalId;
var label = attributes?.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,
Kind = groupMembers.Contains(index) || TrimBimSceneReader.IsIfcGroup(savedObject.IfcTypeName)
? SceneNodeKind.Group : SceneNodeKind.Element,
Name = label.Name ?? $"Object {id}",
Category = savedObject.IfcTypeName ?? string.Empty,
};
foreach (uint layerId in instancesByObject[objectKey].Select(instance => instance.LayerId).Distinct())
{
Expand All @@ -107,6 +111,8 @@ private static TrimBimSceneResult ReadLegacyReference(string directory, string n
attributes?.MaterialNames.GetValueOrDefault(objectKey));
source.Elements.Add(element);
}
TrimBimSceneReader.AddLevels(source, parents, spatialParents,
index => objects.GetValueOrDefault(objectKeys[index]).StoreyElevation);
TrimBimSceneReader.AddGroupMemberships(source, groupMembers);
var units = (attributes != null && foreignObjects != null ? attributes.ReadPropertyUnits(foreignObjects) : [])
.ToDictionary(unit => unit.Kind);
Expand Down Expand Up @@ -210,7 +216,7 @@ T Open<T>(string fileName) where T : TdbDocument
return TdbFile.Open(path) as T ?? throw new InvalidDataException($"Invalid older cache file '{fileName}'.");
}

bool HasObject(uint key) => instancesByObject.Contains(key) || identities.ContainsKey(key);
bool HasObject(uint key) => instancesByObject.Contains(key) || objects.ContainsKey(key);

static long ElementId(int index) => index + 2L;

Expand Down
9 changes: 4 additions & 5 deletions src/TdbIO.Scene/TrimBimSceneReader.Levels.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,19 +4,18 @@ namespace TdbIO.Scene;

public static partial class TrimBimSceneReader
{
private static void AddLevels(SceneDocument scene, IReadOnlyList<TrimBimObjectPlacement> placements,
int[] parents, int[] spatialParents, double metresPerUnit)
internal static void AddLevels(SceneDocument scene, int[] parents, int[] spatialParents, Func<int, double?> readElevation)
{
var levels = new int[placements.Count];
for (int i = 0; i < placements.Count; i++)
var levels = new int[parents.Length];
for (int i = 0; i < levels.Length; i++)
{
var element = scene.Elements[i + 1];
if (element.Category != "IFCBUILDINGSTOREY") continue;
int id = scene.Levels.Count + 1;
scene.Levels.Add(new SceneLevel
{
Id = id, ModelId = element.ModelId, Name = element.Name,
Elevation = ReadLevelElevation(placements[i], metresPerUnit),
Elevation = readElevation(i),
});
element.Kind = SceneNodeKind.Level;
levels[i] = id;
Expand Down
8 changes: 5 additions & 3 deletions src/TdbIO.Scene/TrimBimSceneReader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -74,16 +74,15 @@ private static TrimBimSceneResult Convert(TrimBimDocument document, string key,
{
Id = ElementId(index), ModelId = modelId, ParentId = parents[index] < 0 ? rootId : ElementId(parents[index]),
SourceId = globalId, IfcGuid = globalId,
Kind = groupMembers.Contains(index) || label.TypeName is "IFCGROUP" or "IFCSYSTEM" or "IFCBUILDINGSYSTEM"
or "IFCDISTRIBUTIONSYSTEM" or "IFCDISTRIBUTIONCIRCUIT" or "IFCZONE"
Kind = groupMembers.Contains(index) || IsIfcGroup(label.TypeName)
? SceneNodeKind.Group : SceneNodeKind.Element,
Name = label.Name ?? globalId ?? string.Create(CultureInfo.InvariantCulture, $"Object {index + 1}"),
Category = label.TypeName ?? string.Empty,
};
AddObjectMetadata(scene, element, label.Description);
scene.Elements.Add(element);
}
AddLevels(scene, placements, parents, spatialParents, metresPerUnit);
AddLevels(scene, parents, spatialParents, index => ReadLevelElevation(placements[index], metresPerUnit));
AddPropertySets(scene, document);
AddGroupMemberships(scene, groupMembers);
AddCoordinateReferences(scene, document);
Expand Down Expand Up @@ -217,6 +216,9 @@ internal static int[] ReadParents(IReadOnlyList<TrimBimObjectRelation> relations
}

private static long ElementId(int index) => index + 2L;
internal static bool IsIfcGroup(string? typeName) => typeName is "IFCGROUP" or "IFCSYSTEM" or "IFCBUILDINGSYSTEM"
or "IFCDISTRIBUTIONSYSTEM" or "IFCDISTRIBUTIONCIRCUIT" or "IFCZONE";

private static Vector3d Vector(ModelVector3D v) => new(v.X, v.Y, v.Z);

private static SceneInstance CreateInstance(int geometryId, TrimBimObjectPlacement placement,
Expand Down
56 changes: 54 additions & 2 deletions src/TdbIO/Internal/Container/LegacyReferenceCacheReader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -107,10 +107,15 @@ 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);
string? ifcGlobalId = ReadObjectIfcGlobalId(data, (int)identity, end);
int identityOffset = (int)identity;
string? ifcGlobalId = ReadObjectIfcGlobalId(data, identityOffset, end);
string? ifcTypeName = ifcGlobalId != null && Bytes.U32(data, body + 52) == 2
? ReadIfcTypeName(Bytes.U32(data, body + 56)) : null;
objects.Add(new LegacyReferenceObject(id, ifcGlobalId)
{
IsIfcProject = ifcGlobalId != null && Bytes.U32(data, body + 52) == 2 && Bytes.U32(data, body + 56) == 91,
IfcTypeName = ifcTypeName,
IsIfcProject = ifcTypeName == "IFCPROJECT",
StoreyElevation = ifcTypeName == "IFCBUILDINGSTOREY" ? ReadStoreyElevation(data, identityOffset, end) : null,
});
}
return new LegacyReferenceObjectsDocument(objects.AsReadOnly());
Expand Down Expand Up @@ -144,6 +149,53 @@ public static LegacyReferenceHierarchyDocument ReadHierarchy(byte[] data)
return Encoding.ASCII.GetString(encoded);
}

private static double? ReadStoreyElevation(byte[] data, int identity, int end)
{
const int storeyPlacementSize = 132;
int placement = identity + IfcIdentitySize;
if (end - placement != storeyPlacementSize) return null;

// The saved origin is already in metres. An identity frame is also used for a missing placement.
var origin = ReadVector(data, placement + 8);
var axisX = ReadVector(data, placement + 32);
var axisZ = ReadVector(data, placement + 56);
return origin == default && axisX == new ModelVector3D(1, 0, 0) && axisZ == new ModelVector3D(0, 0, 1)
? null : origin.Z;
}

private static string? ReadIfcTypeName(uint code) => code switch
{
2 => "IFCANNOTATION",
5 => "IFCBEAM",
13 => "IFCBUILDINGELEMENTPROXY",
14 => "IFCCOLUMN",
16 => "IFCCURTAINWALL",
17 => "IFCDOOR",
19 => "IFCMEMBER",
21 => "IFCPLATE",
26 => "IFCSLAB",
27 => "IFCSTAIR",
29 => "IFCWALL",
31 => "IFCWINDOW",
36 => "IFCENERGYCONVERSIONDEVICE",
39 => "IFCFLOWFITTING",
41 => "IFCFLOWSEGMENT",
43 => "IFCFLOWTERMINAL",
46 => "IFCELEMENTASSEMBLY",
60 => "IFCFURNISHINGELEMENT",
61 => "IFCTRANSPORTELEMENT",
65 => "IFCDISTRIBUTIONPORT",
68 => "IFCBUILDING",
69 => "IFCBUILDINGSTOREY",
70 => "IFCSITE",
71 => "IFCSPACE",
91 => "IFCPROJECT",
92 => "IFCGROUP",
93 => "IFCSYSTEM",
190 => "IFCBUILDINGSYSTEM",
_ => null,
};

private static IEnumerable<(uint Id, int Body, int Size)> ReadRecords(byte[] data)
{
int offset = 0;
Expand Down
6 changes: 6 additions & 0 deletions src/TdbIO/LegacyReferenceCacheDocuments.cs
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,12 @@ public readonly record struct LegacyReferenceObject(uint Id, string? IfcGlobalId
{
/// <summary>Whether the cache identifies the object as an IFC project.</summary>
public bool IsIfcProject { get; init; }

/// <summary>The recognized IFC entity name in uppercase, or null for an unknown type.</summary>
public string? IfcTypeName { get; init; }

/// <summary>The saved storey origin's elevation in metres, when a distinct placement is available.</summary>
public double? StoreyElevation { get; init; }
}

/// <summary>A named layer in an older reference cache.</summary>
Expand Down
42 changes: 42 additions & 0 deletions tests/TdbIO.Scene.Tests/TdbSceneReader.ReferenceTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -452,6 +452,48 @@ public void KeepsStoreyAssignmentsWhenALinkIsTilted()
e => Assert.Contains(levels, level => level.Id == e.LevelId));
}

[Theory]
[InlineData(false)]
[InlineData(true)]
public void RestoresStoreysAndCategoriesFromOlderCachesInEachPlacement(bool tiltSecond)
{
string path = CreateInput(writeCurrent: false,
host: Synthetic.ReferenceScenePayload(tiltSecond: tiltSecond, firstZ: 5000, secondZ: -3000));
string cache = CreateLegacyCache(
Synthetic.LegacyTypedReferenceObjectRecord(25, "0000000000000000000025", 29),
Synthetic.LegacyTypedReferenceObjectRecord(29, "0000000000000000000029", 46),
Synthetic.LegacyTypedReferenceObjectRecord(31, "0000000000000000000031", 69, 10),
Synthetic.LegacyTypedReferenceObjectRecord(32, "0000000000000000000032", 69, 0),
Synthetic.LegacyTypedReferenceObjectRecord(33, "0000000000000000000033", 92));
WriteLegacyHierarchy(cache, Synthetic.LegacyReferenceRelationRecord(1, 4, 29, 25),
Synthetic.LegacyReferenceRelationRecord(2, 2, 31, 25), Synthetic.LegacyReferenceRelationRecord(3, 2, 32, 29));
WriteLegacyAttributes(cache, Synthetic.LegacyReferenceNameRecord(1, 31, "Upper"),
Synthetic.LegacyReferenceNameRecord(2, 32, "Unknown elevation"));

var result = TdbSceneReader.Read(path, new() { IncludeReferenceModels = true, GenerateGeometry = false });
Assert.Empty(result.Diagnostics);
var scene = result.Document;
Assert.Equal(4, scene.Levels.Count);
foreach (var model in scene.Models.Skip(1))
{
var elements = scene.Elements.Where(element => element.ModelId == model.Id).ToArray();
var wall = Assert.Single(elements, element => element.Category == "IFCWALL");
var assembly = Assert.Single(elements, element => element.Category == "IFCELEMENTASSEMBLY");
var group = Assert.Single(elements, element => element.Category == "IFCGROUP");
Assert.Equal(SceneNodeKind.Group, group.Kind);
var upper = Assert.Single(scene.Levels, level => level.ModelId == model.Id && level.Name == "Upper");
var other = Assert.Single(scene.Levels, level => level.ModelId == model.Id && level.Name == "Unknown elevation");
double? expected = model.Id == scene.Models[1].Id ? 25 : tiltSecond ? null : 2;
Assert.Equal(expected, upper.Elevation);
Assert.Null(other.Elevation);
Assert.Equal(assembly.Id, wall.ParentId);
Assert.Equal(upper.Id, wall.LevelId);
Assert.Equal(other.Id, assembly.LevelId);
Assert.All(elements.Where(element => element.Kind == SceneNodeKind.Level),
element => Assert.Equal(model.Id, scene.Levels.Single(level => level.Id == element.LevelId).ModelId));
}
}

[Fact]
public void ReportsMissingCurrentCachesWithoutReadingAnEarlierRevision()
{
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 @@ -77,17 +77,19 @@ public void InfoShowsSavedLegacyReferenceLayerNames()
}

[Fact]
public void InfoCountsOlderReferenceObjectsAndSavedIfcGlobalIds()
public void InfoCountsOlderReferenceObjectsIdentitiesAndStoreys()
{
string file = File("foreignobjects.tsfodat", Gzip(Concat(
LegacyReferenceObjectRecord(8, "0000000000000000000001"), LegacyReferenceObjectRecord(9, null))));
LegacyTypedReferenceObjectRecord(8, "0000000000000000000001", 69, 10), LegacyReferenceObjectRecord(9, null))));
var (exit, stdout, stderr) = Run("info", file, "--json");
Assert.Equal(Cli.ExitOk, exit);
Assert.Empty(stderr);
using var json = JsonDocument.Parse(stdout);
Assert.Equal("LegacyReferenceObjects", json.RootElement.GetProperty("kind").GetString());
Assert.Equal(2, json.RootElement.GetProperty("objects").GetInt32());
Assert.Equal(1, json.RootElement.GetProperty("ifcGlobalIds").GetInt32());
Assert.Equal(1, json.RootElement.GetProperty("ifcTypes").GetInt32());
Assert.Equal(1, json.RootElement.GetProperty("storeys").GetInt32());
}

[Fact]
Expand Down
Loading
Loading