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

- Reconstruct polygon meshes with holes, UVs, normals and embedded images from older reference caches when a current TRB8 cache is absent.
- Read older reference cache layer names, material colors and geometry instance placements from `.tsfodat` files.
- Read named TrimBIM layers on polygon mesh and curve set instances and list stored layer names in `tdbio info`.
- Show saved Tekla object GUIDs on linked IFC elements when the identity matches within one insertion.
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`) | `LegacyReferenceLayers`, `LegacyReferenceMaterials`, `LegacyReferenceInstances` | Layer names, material RGBA, instance placements and saved keys | Saved layer state code |
| Older reference cache tables (`layers.tsfodat`, `materials.tsfodat`, `instances.tsfodat`, `definitions.tsfodat`, `textures.tsfodat`) | Legacy reference cache documents | Geometry instances, 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
24 changes: 21 additions & 3 deletions docs/public-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,8 @@ The kind of each document:
| `LegacyReferenceLayers` | `LegacyReferenceLayersDocument` | a gzip cache layer table named `layers.tsfodat` |
| `LegacyReferenceMaterials` | `LegacyReferenceMaterialsDocument` | a gzip cache material table named `materials.tsfodat` |
| `LegacyReferenceInstances` | `LegacyReferenceInstancesDocument` | a gzip cache instance table named `instances.tsfodat` |
| `LegacyReferenceDefinitions` | `LegacyReferenceDefinitionsDocument` | a gzip geometry definition table named `definitions.tsfodat` |
| `LegacyReferenceTextures` | `LegacyReferenceTexturesDocument` | a gzip image table named `textures.tsfodat` |
| `Dbv` | `DbvDocument` | gzip data that unpacks to `DBV@` (uncompressed `DBV@` data is `Unknown`) |
| `History` | `HistoryDocument` | an uncompressed SQLite 3 header |
| `Nc1` | `Nc1Document` | uncompressed text starting with `ST`, optionally preceded by `**` comment lines in the 64 KiB detection prefix |
Expand Down Expand Up @@ -803,16 +805,32 @@ layer index against this vector. Instances that share geometry can belong
to different layers. When the vector is absent or empty, `LayerName` is null.
`tdbio info` reports the nonempty vector as `geometryLayers`.

Older reference caches in `RefCacheFolders` store layers, materials and
geometry instances in separate gzip files. Open the three tables using their
saved file names. Match `LegacyReferenceInstance.LayerId` and `MaterialId`
Older reference caches in `RefCacheFolders` store layers, materials,
geometry instances, definitions and images in separate gzip files. Open
the tables using their saved file names. Match `LegacyReferenceInstance.LayerId` and `MaterialId`
to the corresponding `Id` values in the same cache directory. Material
colors are stored as RGBA. Layer names retain their saved text and
`StateCode` retains the raw saved number. Instance positions and directions
are in cache coordinates. An instance also exposes the saved geometry
definition and foreign object keys. `tdbio info` reports the table row count
and lists the layer names for a layer table.

`LegacyReferenceDefinitionsDocument.Meshes` returns stored polygon meshes
with 32-bit vertex indices, including hole contours and their outer contour
indices. Mesh vertices and normal vectors are read as saved doubles. UVs
are float pairs. `UnsupportedDefinitionCount` counts unhandled geometry
definitions. A material's `TextureId` identifies the encoded image in
`LegacyReferenceTexturesDocument`.

With reference exports enabled, the scene reader uses an older reference
cache when the current TRB8 file is absent. It looks in `RefCacheFolders`
under the model directory and then its parent. A cache directory name has
a numeric prefix followed by an underscore and the current revision hash.
The reader requires a unique match in the selected location. It preserves
mesh instances, transforms, colors, layer names and supported images.
Scene diagnostics report omitted geometry. `TdbSceneResult.ReferenceCacheFiles`
lists the cache paths consulted during conversion.

`ReadCurveSets()` enumerates the saved line segments and circular arcs.
Arc parameters are stored in local coordinates with a sweep in radians.
`ReadCurveSetInstances()` links a curve set to its object, local placement and color.
Expand Down
14 changes: 11 additions & 3 deletions src/TdbIO.Cli/Cli.cs
Original file line number Diff line number Diff line change
Expand Up @@ -527,6 +527,13 @@ private static Command Parse(string[] args)
case LegacyReferenceInstancesDocument instances:
Add("instances", instances.Instances.Count);
break;
case LegacyReferenceDefinitionsDocument definitions:
Add("polygonMeshes", definitions.Meshes.Count);
Add("unsupportedDefinitions", definitions.UnsupportedDefinitionCount);
break;
case LegacyReferenceTexturesDocument textures:
Add("textures", textures.Textures.Count);
break;
case IdRangeDocument ranges:
Add("next", ranges.Next);
Add("ranges", ranges.Ranges.Count);
Expand Down Expand Up @@ -816,7 +823,7 @@ private static IReadOnlyList<string> Export(TextWriter w, TdbDocument doc, Comma
d.Code.StartsWith("task-schedule-", StringComparison.Ordinal) ||
d.Code is "view-filter-unsupported" or "representation-unsupported"))
.Select(d => d.Message));
WriteScene(w, sceneResult.Document, sceneResult.Diagnostics, cmd, ReferenceInputs(model, cmd),
WriteScene(w, sceneResult.Document, sceneResult.Diagnostics, cmd, ReferenceInputs(model, cmd, sceneResult.ReferenceCacheFiles),
sceneResult.ViewpointBounds, sceneResult.ViewpointHiddenElements, viewAttributeInputs);
}
else
Expand Down Expand Up @@ -1022,14 +1029,15 @@ private static ILookup<string, string> LocalAttributes(string modelPath, string
.ToLookup(file => Path.GetFileNameWithoutExtension(file), StringComparer.Ordinal);
}

private static IReadOnlyList<string>? ReferenceInputs(TeklaModel model, Command cmd)
private static IReadOnlyList<string>? ReferenceInputs(TeklaModel model, Command cmd, IReadOnlyList<string> readCacheFiles)
{
if (!cmd.IncludeReferenceModels || cmd.OutputPath == null) return null;
string directory = Path.GetDirectoryName(Path.GetFullPath(cmd.Path))!;
var inputs = model.ReferenceModels.SelectMany(reference => model.GetReferenceModelRevisions(reference.Id))
.Where(revision => revision.IsCurrentRevision)
.Select(revision => revision.CachedTrimBimRelativePath)
.OfType<string>().Select(path => Path.Combine(directory, path)).Distinct(StringComparer.OrdinalIgnoreCase).ToList();
.OfType<string>().Select(path => Path.Combine(directory, path))
.Concat(readCacheFiles).Distinct(StringComparer.OrdinalIgnoreCase).ToList();
if (cmd.ReferenceVisibilityPath is { } visibility) inputs.Add(visibility);
return inputs;
}
Expand Down
2 changes: 1 addition & 1 deletion src/TdbIO.Scene/TdbSceneOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ public sealed class TdbSceneOptions
/// </summary>
public bool GenerateGeometry { get; set; } = true;

/// <summary>Includes external reference models from their saved TrimBIM caches. Default is false.</summary>
/// <summary>Includes external reference models from their saved TrimBIM or older reference caches. Default is false.</summary>
public bool IncludeReferenceModels { get; set; }

/// <summary>Includes saved construction planning tasks and their scene elements. Default is false.</summary>
Expand Down
160 changes: 160 additions & 0 deletions src/TdbIO.Scene/TdbSceneReader.LegacyReferences.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,160 @@
using System.Globalization;
using IOScene;

namespace TdbIO.Scene;

public static partial class TdbSceneReader
{
private static string? FindLegacyReferenceCache(string modelDirectory, string hash)
{
foreach (string? parent in new[] { modelDirectory, Path.GetDirectoryName(modelDirectory) })
{
if (parent == null) continue;
string root = Path.Combine(parent, "RefCacheFolders");
var matches = Directory.Exists(root) ? Directory.EnumerateDirectories(root).Where(path =>
{
string name = Path.GetFileName(path);
int separator = name.IndexOf('_');
return separator > 0 && name.AsSpan(0, separator).IndexOfAnyExceptInRange('0', '9') < 0 &&
name.AsSpan(separator + 1).Equals(hash, StringComparison.OrdinalIgnoreCase);
}).Take(2).ToArray() : [];
if (matches.Length > 1) throw new InvalidDataException("Several older cache folders match the current revision.");
if (matches.Length == 1) return matches[0];
}
return null;
}

private static TrimBimSceneResult ReadLegacyReference(string directory, string name, bool generateGeometry,
HashSet<string> cacheFiles)
{
var source = new SceneDocument { Title = name };
var diagnostics = new List<SceneDiagnostic>();
source.Models.Add(new SceneModel { Id = 1, Key = name, Name = name, SourceFormat = "tsfodat" });
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 layerProperties = new Dictionary<uint, int>();
var objectIds = new Dictionary<uint, long>();
foreach (var group in instances.GroupBy(instance => instance.ObjectId))
{
string id = group.Key.ToString(CultureInfo.InvariantCulture);
var element = new SceneElement
{
Id = source.Elements.Count + 1, ModelId = 1, ParentId = 1, SourceId = id,
Kind = SceneNodeKind.Element, Name = $"Object {id}",
};
foreach (uint layerId in group.Select(instance => instance.LayerId).Distinct())
{
if (!layerProperties.TryGetValue(layerId, out int propertySetId))
{
if (!layers.TryGetValue(layerId, out var layer))
throw new InvalidDataException("An older cache instance references a missing layer.");
propertySetId = source.PropertySets.Count + 1;
string key = string.Create(CultureInfo.InvariantCulture, $"tekla:reference-layer:{layerId}");
source.PropertySets.Add(new ScenePropertySet
{
Id = propertySetId, Key = key, Name = "Geometry layer",
Properties = [new SceneProperty { Key = $"{key}:name", Name = "Name", Value = SceneValue.FromText(layer.Name) }],
});
layerProperties.Add(layerId, propertySetId);
}
element.PropertySetIds.Add(propertySetId);
}
objectIds.Add(group.Key, element.Id);
source.Elements.Add(element);
}

if (generateGeometry)
{
var definitions = Open<LegacyReferenceDefinitionsDocument>("definitions.tsfodat");
var materials = Open<LegacyReferenceMaterialsDocument>("materials.tsfodat").Materials
.ToDictionary(material => material.Id);
var textures = new Dictionary<uint, int?>();
var textureTable = new Lazy<Dictionary<uint, LegacyReferenceTexture>>(ReadTextureTable);
var geometries = new Dictionary<uint, int>();
int skippedFaces = 0;
foreach (var mesh in definitions.Meshes)
{
var vertices = mesh.Vertices.Select(ToSceneVector).ToArray();
var normals = mesh.Normals?.Select(ToSceneVector).ToArray();
var contours = mesh.Polygons.Select(polygon => ((IEnumerable<int>)polygon.VertexIndices, polygon.OuterContourIndex));
var indices = TrimBimMeshTriangulation.TriangulateMesh(vertices, normals, contours, out _, out int skipped);
skippedFaces += skipped;
if (indices.Count == 0) continue;
int id = source.Geometries.Count + 1;
geometries.Add(mesh.Id, id);
source.Geometries.Add(new SceneGeometry
{
Id = id, Topology = SceneTopology.Triangles, Vertices = vertices, Indices = indices, Normals = normals,
UVs = mesh.TextureCoordinates?.Select(uv => new Vector2d(uv.U, uv.V)).ToArray(),
});
}
int skippedInstances = 0;
foreach (var instance in instances)
{
if (!geometries.TryGetValue(instance.DefinitionId, out int geometry))
{
skippedInstances++;
continue;
}
if (!materials.TryGetValue(instance.MaterialId, out var material))
throw new InvalidDataException("An older cache instance references a missing material.");
var rgba = material.Color;
var transform = new Transform3d(ToSceneVector(instance.AxisX), ToSceneVector(instance.AxisY),
ToSceneVector(instance.AxisZ), ToSceneVector(instance.Origin));
source.Instances.Add(new SceneInstance
{
ElementId = objectIds[instance.ObjectId], GeometryId = geometry,
Color = new RgbaColor(rgba.Red, rgba.Green, rgba.Blue, rgba.Alpha),
Transform = transform == Transform3d.Identity ? null : transform,
MaterialId = material.TextureId is uint texture ? AddLegacyTexture(texture) : null,
});
}
if (skippedInstances > 0 || skippedFaces > 0)
diagnostics.Add(new SceneDiagnostic(SceneSeverity.Warning, "legacy-reference-incomplete",
string.Create(CultureInfo.InvariantCulture,
$"The older cache omitted {skippedInstances} instances with no supported mesh and {skippedFaces} faces that could not be triangulated.")));

int? AddLegacyTexture(uint textureId)
{
if (textures.TryGetValue(textureId, out int? id)) return id;
if (textureTable.Value.TryGetValue(textureId, out var texture) &&
TrimBimSceneReader.TextureMimeType(texture.ImageBytes.Span) is string mime)
{
id = source.Textures.Count + 1;
source.Textures.Add(new SceneTexture { Id = id.Value, MimeType = mime, Data = texture.ImageBytes.ToArray() });
source.Materials.Add(new SceneMaterial { Id = id.Value, TextureId = id, Color = new RgbaColor(255, 255, 255, 255) });
}
else
{
diagnostics.Add(new SceneDiagnostic(SceneSeverity.Warning, "legacy-reference-texture",
string.Create(CultureInfo.InvariantCulture, $"Image {textureId} is missing or has an unsupported format.")));
}
textures.Add(textureId, id);
return id;
}
}

diagnostics.AddRange(source.Validate());
return new TrimBimSceneResult(source, diagnostics);

T Open<T>(string fileName) where T : TdbDocument
{
string path = Path.Combine(directory, fileName);
cacheFiles.Add(path);
return TdbFile.Open(path) as T ?? throw new InvalidDataException($"Invalid older cache file '{fileName}'.");
}

Dictionary<uint, LegacyReferenceTexture> ReadTextureTable()
{
try
{
return Open<LegacyReferenceTexturesDocument>("textures.tsfodat").Textures.ToDictionary(texture => texture.Id);
}
catch (FileNotFoundException)
{
return [];
}
}
}
}
26 changes: 21 additions & 5 deletions src/TdbIO.Scene/TdbSceneReader.References.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@ private sealed record ReferenceScene(SceneDocument Source, Dictionary<int, int>
Dictionary<int, int> PropertySets, HashSet<string> UniqueIfcGuids);

private static void AddReferenceModels(SceneDocument scene, TeklaModel model, string modelDirectory,
TdbSceneOptions options, List<SceneDiagnostic> diagnostics, List<(int ObjectId, long ElementId)>? taskElements)
TdbSceneOptions options, List<SceneDiagnostic> diagnostics, List<(int ObjectId, long ElementId)>? taskElements,
HashSet<string> cacheFiles)
{
var caches = new Dictionary<string, ReferenceScene>(StringComparer.OrdinalIgnoreCase);
var keys = scene.Models.Select(m => m.Key).ToHashSet(StringComparer.Ordinal);
Expand Down Expand Up @@ -49,10 +50,7 @@ private static void AddReferenceModels(SceneDocument scene, TeklaModel model, st
{
try
{
string cachePath = Path.Combine(modelDirectory, relativePath);
if (TdbFile.Open(cachePath) is not TrimBimDocument trimBim)
throw new InvalidDataException("The saved cache is not a TRB8 file.");
var result = TrimBimSceneReader.ReadReference(trimBim, name, options.GenerateGeometry);
var result = ReadCache(relativePath, revision.Hash, name);
if (result.Diagnostics.FirstOrDefault(d => d.Severity == SceneSeverity.Error) is { } error)
throw new InvalidDataException(error.Message);
foreach (var diagnostic in result.Diagnostics.Where(d => d.Severity == SceneSeverity.Warning))
Expand Down Expand Up @@ -160,6 +158,24 @@ private static void AddReferenceModels(SceneDocument scene, TeklaModel model, st
void Warn(string name, string code, string message)
=> diagnostics.Add(new(SceneSeverity.Warning, code, $"{name}: {message}"));

TrimBimSceneResult ReadCache(string relativePath, string hash, string name)
{
string path = Path.Combine(modelDirectory, relativePath);
try
{
var cache = TdbFile.Open(path) as TrimBimDocument
?? throw new InvalidDataException("The saved cache is not a TRB8 file.");
cacheFiles.Add(path);
return TrimBimSceneReader.ReadReference(cache, name, options.GenerateGeometry);
}
catch (Exception error) when (error is FileNotFoundException or DirectoryNotFoundException)
{
string? legacy = FindLegacyReferenceCache(modelDirectory, hash);
if (legacy == null) throw;
return ReadLegacyReference(legacy, name, options.GenerateGeometry, cacheFiles);
}
}

Dictionary<string, Db1ReferenceModelObjectIdentity>? ReadReferenceObjects(int referenceId)
{
if (!identityReaderAvailable) return null;
Expand Down
Loading
Loading