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 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.
- Resolve reference model journal links to stored child identities and child events.
Expand Down
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -223,6 +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 |
| `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
18 changes: 16 additions & 2 deletions docs/public-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@ from several threads.

| Type | Use |
| --- | --- |
| `TdbFile` | `DetectKind(path)` and `DetectKind(stream, fileName)` tell the kind of a file from its first bytes (at most 64 KiB) without reading it whole; they never throw for the content and give `Unknown` for data that is short, cut or not recognised. `Open(path, options)` and `Open(stream, fileName, options)` read the file into the document of its kind. The stream need not be seekable and is not disposed; `fileName` is used only to recognise reports. |
| `TdbFileKind` | `Unknown`, `Db1`, `Db2`, `Drawing`, `IdRanges`, `GuidMapper`, `Dbv`, `History`, `Nc1`, `Template`, `Report`, `DrawingLayout`, `DrawingSnapshot`, `ProfileCatalog`, `ShapeDefinition`, `ShapeGeometry`, `TrimBim`, `ObjectGroup`, `ObjectRepresentation`. |
| `TdbFile` | `DetectKind(path)` and `DetectKind(stream, fileName)` inspect at most the first 64 KiB. They give `Unknown` for an incomplete or unrecognised signature. `Open(path, options)` and `Open(stream, fileName, options)` read the file into the document of its kind. The stream need not be seekable and is not disposed. The file name is used for reports, grid presets and older reference cache tables. |
| `TdbFileKind` | `Unknown` or one of the file kinds listed below. |
| `TdbReadOptions` | `MaxUnpackedLength`: the most bytes read into memory, the unpacked size of gzip data or the size of an uncompressed file (default 1 GiB, valid range 1 to `Array.MaxLength`). `TextEncoding`: the encoding of templates and reports and of the text values in table rows, or null to choose it from the bytes. `Default` gives a new instance with the defaults. |
| `TdbDocument` | The base class of every document: `Kind` and `Warnings`. |

Expand All @@ -33,6 +33,9 @@ The kind of each document:
| `IdRanges` | `IdRangeDocument` | gzip data that unpacks to `IdRangeMapper` |
| `GuidMapper` | `GuidMapperDocument` | gzip data that unpacks to `!Guid mapping for ` |
| `TrimBim` | `TrimBimDocument` | an uncompressed file with the `TRB8` identifier at byte 4 |
| `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` |
| `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 @@ -799,6 +802,17 @@ The `LayerName` of a polygon mesh or curve set instance resolves its own
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`
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.

`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
10 changes: 10 additions & 0 deletions src/TdbIO.Cli/Cli.cs
Original file line number Diff line number Diff line change
Expand Up @@ -517,6 +517,16 @@ private static Command Parse(string[] args)
error = e.Message;
}
break;
case LegacyReferenceLayersDocument layers:
Add("layers", layers.Layers.Count);
Add("geometryLayers", layers.Layers.Select(layer => layer.Name));
break;
case LegacyReferenceMaterialsDocument materials:
Add("materials", materials.Materials.Count);
break;
case LegacyReferenceInstancesDocument instances:
Add("instances", instances.Instances.Count);
break;
case IdRangeDocument ranges:
Add("next", ranges.Next);
Add("ranges", ranges.Ranges.Count);
Expand Down
21 changes: 20 additions & 1 deletion src/TdbIO/Internal/Container/KindDetector.cs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ public static TdbFileKind FromUnpacked(ReadOnlySpan<byte> head)
}

/// <summary>The kind of a file from its first bytes as stored. Gzip data is classified by its unpacked head.
/// Reports and grid presets also require a file name.</summary>
/// Reports, grid presets and older reference cache files also require a file name.</summary>
public static TdbFileKind FromRaw(ReadOnlySpan<byte> head, string? fileName)
{
TdbFileKind kind;
Expand All @@ -37,6 +37,13 @@ public static TdbFileKind FromRaw(ReadOnlySpan<byte> head, string? fileName)
Span<byte> unpacked = stackalloc byte[PeekLength];
int n = Gzip.Peek(head, unpacked);
kind = FromUnpacked(unpacked[..n]);
if (kind == TdbFileKind.Unknown)
{
var cacheKind = LegacyReferenceCacheReader.KindFromName(fileName);
if (cacheKind != TdbFileKind.Unknown && (n == 0 ? IsEmptyGzip(head)
: LegacyReferenceCacheReader.HasRecordHeader(unpacked[..n], cacheKind)))
return cacheKind;
}
}
else if (DrawingLayoutHeader.TryRead(head, out _, out _)) kind = TdbFileKind.DrawingLayout;
else if (DrawingSnapshotDocument.HasHeader(head)) kind = TdbFileKind.DrawingSnapshot;
Expand All @@ -62,6 +69,18 @@ public static TdbFileKind FromRaw(ReadOnlySpan<byte> head, string? fileName)
return kind;
}

private static bool IsEmptyGzip(ReadOnlySpan<byte> head)
{
try
{
return Gzip.Unpack(head.ToArray(), maxUnpacked: 0).Length == 0;
}
catch (InvalidDataException)
{
return false;
}
}

private static ReadOnlySpan<byte> Utf8Bom => [0xEF, 0xBB, 0xBF];

private static TdbFileKind ShapeXmlKind(ReadOnlySpan<byte> head)
Expand Down
100 changes: 100 additions & 0 deletions src/TdbIO/Internal/Container/LegacyReferenceCacheReader.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
using System.Text;

namespace TdbIO.Internal;

internal static class LegacyReferenceCacheReader
{
private const int RecordHeaderSize = 8;
private const int LayerFixedSize = 8;
private const int MaterialSize = 29;
private const int InstanceSize = 120;
private static readonly Encoding LayerEncoding = new UnicodeEncoding(false, false, true);

public static TdbFileKind KindFromName(string? fileName)
{
string? name = Path.GetFileName(fileName);
if (string.Equals(name, "layers.tsfodat", StringComparison.OrdinalIgnoreCase)) return TdbFileKind.LegacyReferenceLayers;
if (string.Equals(name, "materials.tsfodat", StringComparison.OrdinalIgnoreCase)) return TdbFileKind.LegacyReferenceMaterials;
if (string.Equals(name, "instances.tsfodat", StringComparison.OrdinalIgnoreCase)) return TdbFileKind.LegacyReferenceInstances;
return TdbFileKind.Unknown;
}

public static bool HasRecordHeader(ReadOnlySpan<byte> head, TdbFileKind kind)
{
if (head.Length < RecordHeaderSize) return false;
uint size = Bytes.U32(head, 4);
if (head.Length < KindDetector.PeekLength && size > head.Length - RecordHeaderSize) return false;
return kind switch
{
TdbFileKind.LegacyReferenceLayers => head.Length >= RecordHeaderSize + sizeof(uint)
&& size == LayerFixedSize + 2L * Bytes.U32(head, RecordHeaderSize),
TdbFileKind.LegacyReferenceMaterials => size == MaterialSize,
TdbFileKind.LegacyReferenceInstances => size == InstanceSize,
_ => false,
};
}

public static LegacyReferenceLayersDocument ReadLayers(byte[] data)
{
var layers = new List<LegacyReferenceLayer>();
var ids = new HashSet<uint>();
foreach (var (id, body, size) in ReadRecords(data))
{
if (size < LayerFixedSize || size != LayerFixedSize + 2L * Bytes.U32(data, body))
throw FormatError.At("Invalid reference cache layer name length", body);
if (!ids.Add(id)) throw FormatError.At("Duplicate reference cache layer ID", body - RecordHeaderSize);
string name = Bytes.LengthDelimitedText(data, body + 4, size - LayerFixedSize, LayerEncoding);
layers.Add(new LegacyReferenceLayer(id, name, Bytes.U32(data, body + size - 4)));
}
return new LegacyReferenceLayersDocument(layers.AsReadOnly());
}

public static LegacyReferenceMaterialsDocument ReadMaterials(byte[] data)
{
var materials = new List<LegacyReferenceMaterial>();
var ids = new HashSet<uint>();
foreach (var (id, body, size) in ReadRecords(data))
{
if (size != MaterialSize) throw FormatError.At("Invalid reference cache material size", body - 4);
if (!ids.Add(id)) throw FormatError.At("Duplicate reference cache material ID", body - RecordHeaderSize);
materials.Add(new LegacyReferenceMaterial(id, new TrimBimColor(data[body], data[body + 1],
data[body + 2], data[body + 3])));
}
return new LegacyReferenceMaterialsDocument(materials.AsReadOnly());
}

public static LegacyReferenceInstancesDocument ReadInstances(byte[] data)
{
var instances = new List<LegacyReferenceInstance>();
foreach (var (definition, body, size) in ReadRecords(data))
{
if (size != InstanceSize) throw FormatError.At("Invalid reference cache instance size", body - 4);
instances.Add(new LegacyReferenceInstance(definition, Bytes.U32(data, body), Bytes.U32(data, body + 4),
Bytes.U32(data, body + 8), ReadVector(data, body + 12), ReadVector(data, body + 36),
ReadVector(data, body + 60), ReadVector(data, body + 84)));
}
return new LegacyReferenceInstancesDocument(instances.AsReadOnly());
}

private static IEnumerable<(uint Id, int Body, int Size)> ReadRecords(byte[] data)
{
int offset = 0;
while (offset < data.Length)
{
Bytes.Need(offset, RecordHeaderSize, data.Length, "Reference cache record header");
uint id = Bytes.U32(data, offset), size = Bytes.U32(data, offset + 4);
int body = offset + RecordHeaderSize;
Bytes.Need(body, size, data.Length, "Reference cache record");
yield return (id, body, (int)size);
offset = body + (int)size;
}
}

private static ModelVector3D ReadVector(byte[] data, int offset)
{
double x = Bytes.F64(data, offset), y = Bytes.F64(data, offset + 8), z = Bytes.F64(data, offset + 16);
if (!double.IsFinite(x) || !double.IsFinite(y) || !double.IsFinite(z))
throw FormatError.At("Non-finite reference cache coordinate", offset);
return new ModelVector3D(x, y, z);
}
}
54 changes: 54 additions & 0 deletions src/TdbIO/LegacyReferenceCacheDocuments.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
namespace TdbIO;

/// <summary>The saved layer table of an older reference cache, in file order.</summary>
public sealed class LegacyReferenceLayersDocument : TdbDocument
{
internal LegacyReferenceLayersDocument(IReadOnlyList<LegacyReferenceLayer> layers)
: base(TdbFileKind.LegacyReferenceLayers, []) => Layers = layers;

/// <summary>The layer records, identified by their saved keys.</summary>
public IReadOnlyList<LegacyReferenceLayer> Layers { get; }
}

/// <summary>The saved material palette of an older reference cache, in file order.</summary>
public sealed class LegacyReferenceMaterialsDocument : TdbDocument
{
internal LegacyReferenceMaterialsDocument(IReadOnlyList<LegacyReferenceMaterial> materials)
: base(TdbFileKind.LegacyReferenceMaterials, []) => Materials = materials;

/// <summary>The material records, identified by their saved keys.</summary>
public IReadOnlyList<LegacyReferenceMaterial> Materials { get; }
}

/// <summary>The saved geometry instances of an older reference cache, in file order.</summary>
public sealed class LegacyReferenceInstancesDocument : TdbDocument
{
internal LegacyReferenceInstancesDocument(IReadOnlyList<LegacyReferenceInstance> instances)
: base(TdbFileKind.LegacyReferenceInstances, []) => Instances = instances;

/// <summary>The saved instances, including repeated uses of the same geometry.</summary>
public IReadOnlyList<LegacyReferenceInstance> Instances { get; }
}

/// <summary>A named layer in an older reference cache.</summary>
/// <param name="Id">The key referenced by geometry instances from the same cache.</param>
/// <param name="Name">The saved layer name.</param>
/// <param name="StateCode">The raw saved layer state code.</param>
public readonly record struct LegacyReferenceLayer(uint Id, string Name, uint StateCode);

/// <summary>A saved material in an older reference cache.</summary>
/// <param name="Id">The key referenced by geometry instances from the same cache.</param>
/// <param name="Color">The saved RGBA channels.</param>
public readonly record struct LegacyReferenceMaterial(uint Id, TrimBimColor Color);

/// <summary>An older reference cache instance, placed in cache coordinates.</summary>
/// <param name="DefinitionId">The saved geometry definition key.</param>
/// <param name="MaterialId">The key in the same cache's material table.</param>
/// <param name="LayerId">The key in the same cache's layer table.</param>
/// <param name="ObjectId">The saved foreign object key in this reference cache.</param>
/// <param name="Origin">The instance origin in the reference cache's coordinates.</param>
/// <param name="AxisX">The instance X direction.</param>
/// <param name="AxisY">The instance Y direction.</param>
/// <param name="AxisZ">The instance Z direction.</param>
public readonly record struct LegacyReferenceInstance(uint DefinitionId, uint MaterialId, uint LayerId, uint ObjectId,
ModelVector3D Origin, ModelVector3D AxisX, ModelVector3D AxisY, ModelVector3D AxisZ);
15 changes: 10 additions & 5 deletions src/TdbIO/TdbFile.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ public static class TdbFile
// The size limit for the uncompressed text readers.
internal const int TextMaxLength = 16 * 1024 * 1024;

/// <summary>Tells the kind of a file from its first bytes (at most 64 KiB) and, for reports and grid presets,
/// <summary>Tells the kind of a file from its first bytes (at most 64 KiB) and, for some formats,
/// its file name. Never throws
/// for the content: data that is short, cut or not recognised gives <see cref="TdbFileKind.Unknown"/>.</summary>
/// <param name="path">The file to examine.</param>
Expand All @@ -28,11 +28,11 @@ public static TdbFileKind DetectKind(string path)
}

/// <summary>Tells the kind of the data from its first bytes (at most 64 KiB, read from the current position) and, for
/// reports and grid presets, the file name. A seekable stream is moved back to where it was; the stream
/// some formats, the file name. A seekable stream is moved back to where it was; the stream
/// is not disposed. Never throws for
/// the content: data that is short, cut or not recognised gives <see cref="TdbFileKind.Unknown"/>.</summary>
/// <param name="stream">A readable stream.</param>
/// <param name="fileName">The file name, used to recognise reports and distinguish grid preset types.</param>
/// <param name="fileName">The file name, used for reports, grid presets and older reference cache files.</param>
/// <returns>The kind of the data.</returns>
/// <exception cref="ArgumentNullException"><paramref name="stream"/> is null.</exception>
/// <exception cref="ArgumentException"><paramref name="stream"/> is not readable.</exception>
Expand Down Expand Up @@ -68,7 +68,7 @@ public static TdbDocument Open(string path, TdbReadOptions? options = null)
/// <summary>Reads the data from the current position to the end into the document of its kind. The stream need not be
/// seekable and is not disposed.</summary>
/// <param name="stream">A readable stream.</param>
/// <param name="fileName">The file name, used to recognise reports and distinguish grid preset types.</param>
/// <param name="fileName">The file name, used for reports, grid presets and older reference cache files.</param>
/// <param name="options">Read options; null for the defaults.</param>
/// <returns>The document; its type depends on <see cref="TdbDocument.Kind"/>.</returns>
/// <exception cref="ArgumentNullException"><paramref name="stream"/> is null.</exception>
Expand Down Expand Up @@ -97,7 +97,9 @@ private static TdbDocument Read(Stream stream, string? fileName, TdbReadOptions
? Math.Min(cap, TextMaxLength)
: cap;
byte[] payload = Gzip.Unpack(InputReader.ReadAll(stream, cap, head, "MaxUnpackedLength"), unpackedCap);
return KindDetector.FromUnpacked(payload) switch
var unpackedKind = KindDetector.FromUnpacked(payload);
if (unpackedKind == TdbFileKind.Unknown) unpackedKind = LegacyReferenceCacheReader.KindFromName(fileName);
return unpackedKind switch
{
TdbFileKind.Db1 => Db1Document.Create(payload, options.TextEncoding, options.RoundBarProfileAliases),
TdbFileKind.Db2 => Db2Document.Create(payload),
Expand All @@ -108,6 +110,9 @@ private static TdbDocument Read(Stream stream, string? fileName, TdbReadOptions
TdbFileKind.ProfileCatalog => ProfileCatalogDocument.Create(payload, options.TextEncoding),
TdbFileKind.ShapeDefinition => ShapeDefinitionDocument.Create(payload),
TdbFileKind.ShapeGeometry => ShapeGeometryDocument.Create(payload),
TdbFileKind.LegacyReferenceLayers => LegacyReferenceCacheReader.ReadLayers(payload),
TdbFileKind.LegacyReferenceMaterials => LegacyReferenceCacheReader.ReadMaterials(payload),
TdbFileKind.LegacyReferenceInstances => LegacyReferenceCacheReader.ReadInstances(payload),
_ => throw NotRecognised(),
};
}
Expand Down
Loading
Loading