From a0914d586dd399350b27f2a1e16ebabbdb48e188 Mon Sep 17 00:00:00 2001 From: mahach666 <79989386+mahach666@users.noreply.github.com> Date: Sun, 6 Dec 2026 16:41:57 +0300 Subject: [PATCH] Read older reference cache layers, materials and instances --- CHANGELOG.md | 1 + README.md | 1 + docs/public-api.md | 18 +++- src/TdbIO.Cli/Cli.cs | 10 ++ src/TdbIO/Internal/Container/KindDetector.cs | 21 +++- .../Container/LegacyReferenceCacheReader.cs | 100 ++++++++++++++++++ src/TdbIO/LegacyReferenceCacheDocuments.cs | 54 ++++++++++ src/TdbIO/TdbFile.cs | 15 ++- src/TdbIO/TdbFileKind.cs | 11 +- tests/TdbIO.Tests/CliTests.cs | 14 +++ .../TdbIO.Tests/LegacyReferenceCacheTests.cs | 86 +++++++++++++++ 11 files changed, 322 insertions(+), 9 deletions(-) create mode 100644 src/TdbIO/Internal/Container/LegacyReferenceCacheReader.cs create mode 100644 src/TdbIO/LegacyReferenceCacheDocuments.cs create mode 100644 tests/TdbIO.Tests/LegacyReferenceCacheTests.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index 2964c92..6d3b2e6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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. diff --git a/README.md b/README.md index e3e1539..e5851e4 100644 --- a/README.md +++ b/README.md @@ -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 | diff --git a/docs/public-api.md b/docs/public-api.md index 41262b0..4ed1ac4 100644 --- a/docs/public-api.md +++ b/docs/public-api.md @@ -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`. | @@ -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 | @@ -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. diff --git a/src/TdbIO.Cli/Cli.cs b/src/TdbIO.Cli/Cli.cs index 9bc2bcb..155a891 100644 --- a/src/TdbIO.Cli/Cli.cs +++ b/src/TdbIO.Cli/Cli.cs @@ -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); diff --git a/src/TdbIO/Internal/Container/KindDetector.cs b/src/TdbIO/Internal/Container/KindDetector.cs index 68284e3..814b68e 100644 --- a/src/TdbIO/Internal/Container/KindDetector.cs +++ b/src/TdbIO/Internal/Container/KindDetector.cs @@ -28,7 +28,7 @@ public static TdbFileKind FromUnpacked(ReadOnlySpan head) } /// 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. + /// Reports, grid presets and older reference cache files also require a file name. public static TdbFileKind FromRaw(ReadOnlySpan head, string? fileName) { TdbFileKind kind; @@ -37,6 +37,13 @@ public static TdbFileKind FromRaw(ReadOnlySpan head, string? fileName) Span 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; @@ -62,6 +69,18 @@ public static TdbFileKind FromRaw(ReadOnlySpan head, string? fileName) return kind; } + private static bool IsEmptyGzip(ReadOnlySpan head) + { + try + { + return Gzip.Unpack(head.ToArray(), maxUnpacked: 0).Length == 0; + } + catch (InvalidDataException) + { + return false; + } + } + private static ReadOnlySpan Utf8Bom => [0xEF, 0xBB, 0xBF]; private static TdbFileKind ShapeXmlKind(ReadOnlySpan head) diff --git a/src/TdbIO/Internal/Container/LegacyReferenceCacheReader.cs b/src/TdbIO/Internal/Container/LegacyReferenceCacheReader.cs new file mode 100644 index 0000000..59cf090 --- /dev/null +++ b/src/TdbIO/Internal/Container/LegacyReferenceCacheReader.cs @@ -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 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(); + var ids = new HashSet(); + 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(); + var ids = new HashSet(); + 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(); + 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); + } +} diff --git a/src/TdbIO/LegacyReferenceCacheDocuments.cs b/src/TdbIO/LegacyReferenceCacheDocuments.cs new file mode 100644 index 0000000..e0a7303 --- /dev/null +++ b/src/TdbIO/LegacyReferenceCacheDocuments.cs @@ -0,0 +1,54 @@ +namespace TdbIO; + +/// The saved layer table of an older reference cache, in file order. +public sealed class LegacyReferenceLayersDocument : TdbDocument +{ + internal LegacyReferenceLayersDocument(IReadOnlyList layers) + : base(TdbFileKind.LegacyReferenceLayers, []) => Layers = layers; + + /// The layer records, identified by their saved keys. + public IReadOnlyList Layers { get; } +} + +/// The saved material palette of an older reference cache, in file order. +public sealed class LegacyReferenceMaterialsDocument : TdbDocument +{ + internal LegacyReferenceMaterialsDocument(IReadOnlyList materials) + : base(TdbFileKind.LegacyReferenceMaterials, []) => Materials = materials; + + /// The material records, identified by their saved keys. + public IReadOnlyList Materials { get; } +} + +/// The saved geometry instances of an older reference cache, in file order. +public sealed class LegacyReferenceInstancesDocument : TdbDocument +{ + internal LegacyReferenceInstancesDocument(IReadOnlyList instances) + : base(TdbFileKind.LegacyReferenceInstances, []) => Instances = instances; + + /// The saved instances, including repeated uses of the same geometry. + public IReadOnlyList Instances { get; } +} + +/// A named layer in an older reference cache. +/// The key referenced by geometry instances from the same cache. +/// The saved layer name. +/// The raw saved layer state code. +public readonly record struct LegacyReferenceLayer(uint Id, string Name, uint StateCode); + +/// A saved material in an older reference cache. +/// The key referenced by geometry instances from the same cache. +/// The saved RGBA channels. +public readonly record struct LegacyReferenceMaterial(uint Id, TrimBimColor Color); + +/// An older reference cache instance, placed in cache coordinates. +/// The saved geometry definition key. +/// The key in the same cache's material table. +/// The key in the same cache's layer table. +/// The saved foreign object key in this reference cache. +/// The instance origin in the reference cache's coordinates. +/// The instance X direction. +/// The instance Y direction. +/// The instance Z direction. +public readonly record struct LegacyReferenceInstance(uint DefinitionId, uint MaterialId, uint LayerId, uint ObjectId, + ModelVector3D Origin, ModelVector3D AxisX, ModelVector3D AxisY, ModelVector3D AxisZ); diff --git a/src/TdbIO/TdbFile.cs b/src/TdbIO/TdbFile.cs index 7af2303..bf21a04 100644 --- a/src/TdbIO/TdbFile.cs +++ b/src/TdbIO/TdbFile.cs @@ -11,7 +11,7 @@ public static class TdbFile // The size limit for the uncompressed text readers. internal const int TextMaxLength = 16 * 1024 * 1024; - /// Tells the kind of a file from its first bytes (at most 64 KiB) and, for reports and grid presets, + /// 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 . /// The file to examine. @@ -28,11 +28,11 @@ public static TdbFileKind DetectKind(string path) } /// 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 . /// A readable stream. - /// The file name, used to recognise reports and distinguish grid preset types. + /// The file name, used for reports, grid presets and older reference cache files. /// The kind of the data. /// is null. /// is not readable. @@ -68,7 +68,7 @@ public static TdbDocument Open(string path, TdbReadOptions? options = null) /// 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. /// A readable stream. - /// The file name, used to recognise reports and distinguish grid preset types. + /// The file name, used for reports, grid presets and older reference cache files. /// Read options; null for the defaults. /// The document; its type depends on . /// is null. @@ -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), @@ -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(), }; } diff --git a/src/TdbIO/TdbFileKind.cs b/src/TdbIO/TdbFileKind.cs index 7b7d061..f85938f 100644 --- a/src/TdbIO/TdbFileKind.cs +++ b/src/TdbIO/TdbFileKind.cs @@ -1,6 +1,6 @@ namespace TdbIO; -/// The kind of a file, found from its content (and, for reports only, from its file name). +/// The kind of a file, found from its content and, for some formats, its file name. public enum TdbFileKind { /// Not a recognised file. @@ -72,4 +72,13 @@ public enum TdbFileKind /// A saved property file for an individual model grid line (.grdp). GridLinePreset, + + /// A gzip-compressed layer table named layers.tsfodat. + LegacyReferenceLayers, + + /// A gzip-compressed material table named materials.tsfodat. + LegacyReferenceMaterials, + + /// A gzip-compressed geometry instance table named instances.tsfodat. + LegacyReferenceInstances, } diff --git a/tests/TdbIO.Tests/CliTests.cs b/tests/TdbIO.Tests/CliTests.cs index 0613289..14794ec 100644 --- a/tests/TdbIO.Tests/CliTests.cs +++ b/tests/TdbIO.Tests/CliTests.cs @@ -62,6 +62,20 @@ public void InfoShowsTrimBimObjectGuidCount() Assert.False(json.RootElement.TryGetProperty("geometryLayers", out _)); } + [Fact] + public void InfoShowsSavedLegacyReferenceLayerNames() + { + string file = File("layers.tsfodat", Gzip(Concat(Le32(1), Le32(22), + Le32(7), Encoding.Unicode.GetBytes("Outline"), Le32(1)))); + var (exit, stdout, stderr) = Run("info", file, "--json"); + Assert.Equal(Cli.ExitOk, exit); + Assert.Empty(stderr); + using var json = JsonDocument.Parse(stdout); + Assert.Equal("LegacyReferenceLayers", json.RootElement.GetProperty("kind").GetString()); + Assert.Equal(1, json.RootElement.GetProperty("layers").GetInt32()); + Assert.Equal("Outline", json.RootElement.GetProperty("geometryLayers")[0].GetString()); + } + [Fact] public void InfoShowsSavedTrimBimGeometryLayersInOrder() { diff --git a/tests/TdbIO.Tests/LegacyReferenceCacheTests.cs b/tests/TdbIO.Tests/LegacyReferenceCacheTests.cs new file mode 100644 index 0000000..de2ca2a --- /dev/null +++ b/tests/TdbIO.Tests/LegacyReferenceCacheTests.cs @@ -0,0 +1,86 @@ +using System.Buffers.Binary; +using System.Text; +using Xunit; +using static TdbIO.Tests.Synthetic; + +namespace TdbIO.Tests; + +public sealed class LegacyReferenceCacheTests +{ + [Fact] + public void ReadsSavedLayersMaterialsAndInstancesByTheirKeys() + { + using var layersFile = new MemoryStream(Gzip(Concat(Layer(8, "Outline", 1), Layer(3, "Слой 🟦", 2)))); + using var materialsFile = new MemoryStream(Gzip(Record(5, Concat([17, 89, 166, 240], new byte[25])))); + using var instancesFile = new MemoryStream(Gzip(Concat(Instance(8), Instance(3)))); + + Assert.Equal(TdbFileKind.LegacyReferenceLayers, TdbFile.DetectKind(layersFile, "LAYERS.TSFODAT")); + Assert.Equal(TdbFileKind.LegacyReferenceMaterials, TdbFile.DetectKind(materialsFile, "materials.tsfodat")); + Assert.Equal(TdbFileKind.LegacyReferenceInstances, TdbFile.DetectKind(instancesFile, "instances.tsfodat")); + var layers = Assert.IsType(TdbFile.Open(layersFile, "layers.tsfodat")); + var materials = Assert.IsType(TdbFile.Open(materialsFile, "materials.tsfodat")); + var instances = Assert.IsType(TdbFile.Open(instancesFile, "instances.tsfodat")); + + Assert.Equal(new LegacyReferenceLayer(8, "Outline", 1), layers.Layers[0]); + Assert.Equal(new LegacyReferenceLayer(3, "Слой 🟦", 2), layers.Layers[1]); + Assert.Equal(new LegacyReferenceMaterial(5, new TrimBimColor(17, 89, 166, 240)), Assert.Single(materials.Materials)); + Assert.Equal(new LegacyReferenceInstance(0, 5, 8, 25, new(1.25, -7.5, 13), new(0, 1, 0), + new(-1, 0, 0), new(0, 0, 1)), instances.Instances[0]); + Assert.Equal(instances.Instances[0] with { LayerId = 3 }, instances.Instances[1]); + } + + [Fact] + public void AcceptsAnEmptyNamedCacheTableAndRequiresTheExactBasename() + { + using var file = new MemoryStream(Gzip([])); + Assert.Equal(TdbFileKind.Unknown, TdbFile.DetectKind(file, "defs.tsfodat")); + Assert.Equal(TdbFileKind.LegacyReferenceLayers, TdbFile.DetectKind(file, "layers.tsfodat")); + Assert.Empty(Assert.IsType(TdbFile.Open(file, "layers.tsfodat")).Layers); + } + + [Fact] + public void DoesNotStealExistingGzipSignatures() + { + using var file = new MemoryStream(Gzip(Ascii("!Guid mapping for "))); + Assert.Equal(TdbFileKind.GuidMapper, TdbFile.DetectKind(file, "layers.tsfodat")); + } + + [Fact] + public void RejectsBadLayerLengthsAndDuplicateLayerIds() + { + using var malformed = new MemoryStream(Gzip(Record(1, Concat(Le32(int.MaxValue), Le32(1))))); + using var duplicate = new MemoryStream(Gzip(Concat(Layer(1, "Upper", 1), Layer(1, "Lower", 1)))); + Assert.Equal(TdbFileKind.Unknown, TdbFile.DetectKind(malformed, "layers.tsfodat")); + Assert.Contains("layer name length", Assert.Throws(() => TdbFile.Open(malformed, "layers.tsfodat")).Message); + Assert.Contains("Duplicate", Assert.Throws(() => TdbFile.Open(duplicate, "layers.tsfodat")).Message); + } + + [Fact] + public void RejectsCutInstancesAndNonFiniteAxes() + { + byte[] invalid = Instance(8); + BinaryPrimitives.WriteDoubleLittleEndian(invalid.AsSpan(8 + 36), double.NaN); + using var malformed = new MemoryStream(Gzip(invalid)); + using var cut = new MemoryStream(Gzip(Instance(8)[..^1])); + Assert.Equal(TdbFileKind.Unknown, TdbFile.DetectKind(cut, "instances.tsfodat")); + var error = Assert.Throws(() => TdbFile.Open(malformed, "instances.tsfodat")); + Assert.Equal(44L, error.Data["Offset"]); + Assert.Contains("record runs past the end", Assert.Throws(() => TdbFile.Open(cut, "instances.tsfodat")).Message); + } + + private static byte[] Layer(uint id, string name, uint state) + => Record(id, Concat(Le32(name.Length), Encoding.Unicode.GetBytes(name), Le32(state))); + + private static byte[] Instance(uint layerId) + { + var body = new byte[120]; + Concat(Le32(5), Le32(layerId), Le32(25)).CopyTo(body, 0); + double[] xyzAndAxes = [1.25, -7.5, 13, 0, 1, 0, -1, 0, 0, 0, 0, 1]; + for (int i = 0; i < xyzAndAxes.Length; i++) + BinaryPrimitives.WriteDoubleLittleEndian(body.AsSpan(12 + i * 8), xyzAndAxes[i]); + return Record(0, body); + } + + private static byte[] Record(uint id, byte[] body) + => Concat(Le32(id), Le32(body.Length), body); +}