From f3685ef25b073a5268ef9f4dd0e8878271cb18c5 Mon Sep 17 00:00:00 2001 From: mahach666 <79989386+mahach666@users.noreply.github.com> Date: Sun, 6 Dec 2026 16:58:49 +0300 Subject: [PATCH] Export polygon meshes from older reference caches --- CHANGELOG.md | 1 + README.md | 2 +- docs/public-api.md | 24 ++- src/TdbIO.Cli/Cli.cs | 14 +- src/TdbIO.Scene/TdbSceneOptions.cs | 2 +- .../TdbSceneReader.LegacyReferences.cs | 160 ++++++++++++++++++ src/TdbIO.Scene/TdbSceneReader.References.cs | 26 ++- src/TdbIO.Scene/TdbSceneReader.cs | 4 +- src/TdbIO.Scene/TdbSceneResult.cs | 3 + src/TdbIO.Scene/TrimBimMeshTriangulation.cs | 69 +++++++- src/TdbIO.Scene/TrimBimSceneReader.cs | 65 +------ .../Container/LegacyReferenceCacheReader.cs | 10 +- .../LegacyReferenceGeometryReader.cs | 113 +++++++++++++ src/TdbIO/LegacyReferenceCacheDocuments.cs | 6 +- src/TdbIO/LegacyReferenceGeometry.cs | 52 ++++++ src/TdbIO/TdbFile.cs | 2 + src/TdbIO/TdbFileKind.cs | 6 + tests/TdbIO.Tests/CliTests.cs | 38 +++++ .../TdbIO.Tests/LegacyReferenceCacheTests.cs | 40 ++++- .../TdbIO.Tests/Synthetic.LegacyReference.cs | 47 +++++ 20 files changed, 605 insertions(+), 79 deletions(-) create mode 100644 src/TdbIO.Scene/TdbSceneReader.LegacyReferences.cs create mode 100644 src/TdbIO/Internal/Container/LegacyReferenceGeometryReader.cs create mode 100644 src/TdbIO/LegacyReferenceGeometry.cs create mode 100644 tests/TdbIO.Tests/Synthetic.LegacyReference.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index 6d3b2e65..6d6835f4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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. diff --git a/README.md b/README.md index e5851e4a..b00c0516 100644 --- a/README.md +++ b/README.md @@ -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 | diff --git a/docs/public-api.md b/docs/public-api.md index 4ed1ac4c..7a75a57b 100644 --- a/docs/public-api.md +++ b/docs/public-api.md @@ -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 | @@ -803,9 +805,9 @@ 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 @@ -813,6 +815,22 @@ 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. diff --git a/src/TdbIO.Cli/Cli.cs b/src/TdbIO.Cli/Cli.cs index 155a8917..21a1b668 100644 --- a/src/TdbIO.Cli/Cli.cs +++ b/src/TdbIO.Cli/Cli.cs @@ -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); @@ -816,7 +823,7 @@ private static IReadOnlyList 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 @@ -1022,14 +1029,15 @@ private static ILookup LocalAttributes(string modelPath, string .ToLookup(file => Path.GetFileNameWithoutExtension(file), StringComparer.Ordinal); } - private static IReadOnlyList? ReferenceInputs(TeklaModel model, Command cmd) + private static IReadOnlyList? ReferenceInputs(TeklaModel model, Command cmd, IReadOnlyList 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().Select(path => Path.Combine(directory, path)).Distinct(StringComparer.OrdinalIgnoreCase).ToList(); + .OfType().Select(path => Path.Combine(directory, path)) + .Concat(readCacheFiles).Distinct(StringComparer.OrdinalIgnoreCase).ToList(); if (cmd.ReferenceVisibilityPath is { } visibility) inputs.Add(visibility); return inputs; } diff --git a/src/TdbIO.Scene/TdbSceneOptions.cs b/src/TdbIO.Scene/TdbSceneOptions.cs index a893f646..05230214 100644 --- a/src/TdbIO.Scene/TdbSceneOptions.cs +++ b/src/TdbIO.Scene/TdbSceneOptions.cs @@ -46,7 +46,7 @@ public sealed class TdbSceneOptions /// public bool GenerateGeometry { get; set; } = true; - /// Includes external reference models from their saved TrimBIM caches. Default is false. + /// Includes external reference models from their saved TrimBIM or older reference caches. Default is false. public bool IncludeReferenceModels { get; set; } /// Includes saved construction planning tasks and their scene elements. Default is false. diff --git a/src/TdbIO.Scene/TdbSceneReader.LegacyReferences.cs b/src/TdbIO.Scene/TdbSceneReader.LegacyReferences.cs new file mode 100644 index 00000000..27eeb00b --- /dev/null +++ b/src/TdbIO.Scene/TdbSceneReader.LegacyReferences.cs @@ -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 cacheFiles) + { + var source = new SceneDocument { Title = name }; + var diagnostics = new List(); + 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("instances.tsfodat").Instances; + var layers = Open("layers.tsfodat").Layers.ToDictionary(layer => layer.Id); + var layerProperties = new Dictionary(); + var objectIds = new Dictionary(); + 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("definitions.tsfodat"); + var materials = Open("materials.tsfodat").Materials + .ToDictionary(material => material.Id); + var textures = new Dictionary(); + var textureTable = new Lazy>(ReadTextureTable); + var geometries = new Dictionary(); + 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)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(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 ReadTextureTable() + { + try + { + return Open("textures.tsfodat").Textures.ToDictionary(texture => texture.Id); + } + catch (FileNotFoundException) + { + return []; + } + } + } +} diff --git a/src/TdbIO.Scene/TdbSceneReader.References.cs b/src/TdbIO.Scene/TdbSceneReader.References.cs index c9c44f0a..3406ad51 100644 --- a/src/TdbIO.Scene/TdbSceneReader.References.cs +++ b/src/TdbIO.Scene/TdbSceneReader.References.cs @@ -9,7 +9,8 @@ private sealed record ReferenceScene(SceneDocument Source, Dictionary Dictionary PropertySets, HashSet UniqueIfcGuids); private static void AddReferenceModels(SceneDocument scene, TeklaModel model, string modelDirectory, - TdbSceneOptions options, List diagnostics, List<(int ObjectId, long ElementId)>? taskElements) + TdbSceneOptions options, List diagnostics, List<(int ObjectId, long ElementId)>? taskElements, + HashSet cacheFiles) { var caches = new Dictionary(StringComparer.OrdinalIgnoreCase); var keys = scene.Models.Select(m => m.Key).ToHashSet(StringComparer.Ordinal); @@ -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)) @@ -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? ReadReferenceObjects(int referenceId) { if (!identityReaderAvailable) return null; diff --git a/src/TdbIO.Scene/TdbSceneReader.cs b/src/TdbIO.Scene/TdbSceneReader.cs index 5f6d52db..780d7823 100644 --- a/src/TdbIO.Scene/TdbSceneReader.cs +++ b/src/TdbIO.Scene/TdbSceneReader.cs @@ -1160,8 +1160,9 @@ void AddLineGeometry(long elementId, List vertices, RgbaColor? color = var referenceTaskElements = scheduleTasks.Count > 0 && options.IncludeReferenceModels ? new List<(int ObjectId, long ElementId)>() : null; + var referenceCacheFiles = new HashSet(StringComparer.OrdinalIgnoreCase); if (options.IncludeReferenceModels) - AddReferenceModels(scene, model, referenceDirectory!, options, diagnostics, referenceTaskElements); + AddReferenceModels(scene, model, referenceDirectory!, options, diagnostics, referenceTaskElements, referenceCacheFiles); if (scheduleTasks.Count > 0) AddTaskSchedules(scene, model, scheduleTasks, sceneObjects!, asmElementMap, referenceTaskElements, diagnostics); AddGridAxes(scene, options.GridPlanes); @@ -1175,6 +1176,7 @@ void AddLineGeometry(long elementId, List vertices, RgbaColor? color = { ViewpointBounds = viewpointBounds, ViewpointHiddenElements = viewpointHiddenElements, + ReferenceCacheFiles = referenceCacheFiles.ToArray(), }; } diff --git a/src/TdbIO.Scene/TdbSceneResult.cs b/src/TdbIO.Scene/TdbSceneResult.cs index e5cc623c..9d8cdc50 100644 --- a/src/TdbIO.Scene/TdbSceneResult.cs +++ b/src/TdbIO.Scene/TdbSceneResult.cs @@ -71,6 +71,9 @@ internal TdbSceneResult( /// Findings of the conversion. public IReadOnlyList Diagnostics { get; } + /// Paths to the external cache files read or checked during conversion. + public IReadOnlyList ReferenceCacheFiles { get; internal init; } = []; + /// Findings about the geometry of the parts: the proxy boxes with default dimensions and the parts that got /// no mesh. public IReadOnlyList GeometryDiagnostics { get; } diff --git a/src/TdbIO.Scene/TrimBimMeshTriangulation.cs b/src/TdbIO.Scene/TrimBimMeshTriangulation.cs index 996cd27c..04d5b4ac 100644 --- a/src/TdbIO.Scene/TrimBimMeshTriangulation.cs +++ b/src/TdbIO.Scene/TrimBimMeshTriangulation.cs @@ -6,7 +6,66 @@ namespace TdbIO.Scene; internal static class TrimBimMeshTriangulation { - internal static int[]? Triangulate(Vector3d[] vertices, ushort[] outer, IReadOnlyList? holes) + internal static List TriangulateMesh(Vector3d[] vertices, Vector3d[]? normals, + IEnumerable<(IEnumerable Indices, int? Parent)> polygons, out int faces, out int skipped) + { + var outer = new List(); + var holes = new Dictionary>(); + foreach (var (indices, parent) in polygons) + { + var contour = ContourIndices(indices, vertices); + if (parent is not int index) outer.Add(contour); + else + { + if (!holes.TryGetValue(index, out var rings)) holes.Add(index, rings = []); + rings.Add(contour); + } + } + + var triangles = new List(); + faces = outer.Count; + skipped = 0; + for (int i = 0; i < outer.Count; i++) + { + holes.TryGetValue(i, out var rings); + if (Triangulate(vertices, outer[i], rings) is { } face) + { + if (normals != null) OrientFace(face, vertices, normals, outer[i]); + triangles.AddRange(face); + } + else skipped++; + } + return triangles; + } + + private static int[] ContourIndices(IEnumerable source, Vector3d[] vertices) + { + var indices = new List(); + foreach (int index in source) + { + if (indices.Count == 0 || vertices[indices[^1]] != vertices[index]) indices.Add(index); + } + if (indices.Count > 1 && vertices[indices[^1]] == vertices[indices[0]]) + indices.RemoveAt(indices.Count - 1); + return indices.ToArray(); + } + + private static void OrientFace(int[] face, Vector3d[] vertices, Vector3d[] normals, int[] contour) + { + var expected = Vector3d.Zero; + foreach (int i in contour) expected += normals[i]; + var actual = Vector3d.Zero; + for (int i = 0; i < face.Length; i += 3) + { + Vector3d origin = vertices[face[i]]; + actual += Vector3d.Cross(vertices[face[i + 1]] - origin, vertices[face[i + 2]] - origin); + } + if (Vector3d.Dot(actual, expected) >= 0) return; + for (int i = 0; i < face.Length; i += 3) + (face[i + 1], face[i + 2]) = (face[i + 2], face[i + 1]); + } + + private static int[]? Triangulate(Vector3d[] vertices, int[] outer, IReadOnlyList? holes) { if (outer.Length < 3 || holes?.Any(ring => ring.Length < 3) == true) return null; var boundary = outer.Select(index => vertices[index]).ToArray(); @@ -19,7 +78,7 @@ internal static class TrimBimMeshTriangulation if (holes == null) { int[]? triangles = PlateBoundaryTriangulation.Triangulate(boundary, normal, out int winding); - return winding == 1 && triangles != null ? triangles.Select(index => (int)outer[index]).ToArray() : null; + return winding == 1 && triangles != null ? triangles.Select(index => outer[index]).ToArray() : null; } var sourceRings = new[] { outer }.Concat(holes).ToArray(); @@ -29,11 +88,11 @@ internal static class TrimBimMeshTriangulation if (!double.IsFinite(span) || span == 0) return null; const double gridSpan = 1e11; var gridRings = new Paths64(sourceRings.Length); - var sourceIndices = new Dictionary(); + var sourceIndices = new Dictionary(); int offset = 0; for (int ring = 0; ring < sourceRings.Length; ring++) { - ushort[] indices = sourceRings[ring]; + int[] indices = sourceRings[ring]; var path = new Path64(indices.Length); for (int i = 0; i < indices.Length; i++) { @@ -61,7 +120,7 @@ internal static class TrimBimMeshTriangulation gridRings = trimmed; } if (cap == null) return null; - var meshIndices = gridRings.SelectMany(ring => ring).Select(node => (int)sourceIndices[node]).ToArray(); + var meshIndices = gridRings.SelectMany(ring => ring).Select(node => sourceIndices[node]).ToArray(); return cap.Select(index => meshIndices[index]).ToArray(); } } diff --git a/src/TdbIO.Scene/TrimBimSceneReader.cs b/src/TdbIO.Scene/TrimBimSceneReader.cs index f50fddcc..569458a9 100644 --- a/src/TdbIO.Scene/TrimBimSceneReader.cs +++ b/src/TdbIO.Scene/TrimBimSceneReader.cs @@ -109,35 +109,13 @@ private static TrimBimSceneResult Convert(TrimBimDocument document, string key, { var vertices = mesh.Vertices.Select(Vector).ToArray(); var normals = mesh.Normals?.Select(Vector).ToArray(); - var outer = new List(); - var holes = new Dictionary>(); - foreach (var contour in mesh.Polygons) - { - ushort[] indices = ContourIndices(contour, vertices); - if (contour.OuterContourIndex is not int parent) outer.Add(indices); - else - { - if (!holes.TryGetValue(parent, out var rings)) holes.Add(parent, rings = []); - rings.Add(indices); - } - } - var triangles = new List(); - int skipped = 0; - for (int i = 0; i < outer.Count; i++) - { - holes.TryGetValue(i, out var rings); - if (TrimBimMeshTriangulation.Triangulate(vertices, outer[i], rings) is { } face) - { - if (normals != null) OrientFace(face, vertices, normals, outer[i]); - triangles.AddRange(face); - } - else - skipped++; - } + var polygons = mesh.Polygons.Select(contour => (contour.VertexIndices.Select(index => (int)index), + contour.OuterContourIndex)); + var triangles = TrimBimMeshTriangulation.TriangulateMesh(vertices, normals, polygons, out int faces, out int skipped); if (skipped > 0) { diagnostics.Add(new(SceneSeverity.Warning, "trimbim-untriangulated", - string.Create(CultureInfo.InvariantCulture, $"TrimBIM mesh {mesh.MeshIndex} omitted {skipped} of {outer.Count} faces that could not be triangulated."))); + string.Create(CultureInfo.InvariantCulture, $"TrimBIM mesh {mesh.MeshIndex} omitted {skipped} of {faces} faces that could not be triangulated."))); } if (triangles.Count == 0) continue; int id = mesh.MeshIndex + 1; @@ -176,38 +154,9 @@ private static TrimBimSceneResult Convert(TrimBimDocument document, string key, return new TrimBimSceneResult(scene, diagnostics); } - private static ushort[] ContourIndices(TrimBimPolygon contour, Vector3d[] vertices) - { - var indices = new List(contour.VertexCount); - foreach (ushort index in contour.VertexIndices) - { - if (indices.Count == 0 || vertices[indices[^1]] != vertices[index]) indices.Add(index); - } - if (indices.Count > 1 && vertices[indices[^1]] == vertices[indices[0]]) - indices.RemoveAt(indices.Count - 1); - return indices.ToArray(); - } - - private static void OrientFace(int[] face, Vector3d[] vertices, Vector3d[] normals, ushort[] contour) - { - var expected = Vector3d.Zero; - foreach (ushort i in contour) expected += normals[i]; - var actual = Vector3d.Zero; - for (int i = 0; i < face.Length; i += 3) - { - Vector3d origin = vertices[face[i]]; - actual += Vector3d.Cross(vertices[face[i + 1]] - origin, vertices[face[i + 2]] - origin); - } - if (Vector3d.Dot(actual, expected) >= 0) return; - for (int i = 0; i < face.Length; i += 3) - (face[i + 1], face[i + 2]) = (face[i + 2], face[i + 1]); - } - private static int? AddTextureMaterial(SceneDocument scene, TrimBimTexture texture, List diagnostics) { - ReadOnlySpan bytes = texture.ImageBytes.Span; - string? mime = bytes.StartsWith(new byte[] { 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A }) ? "image/png" - : bytes.StartsWith(new byte[] { 0xFF, 0xD8, 0xFF }) ? "image/jpeg" : null; + string? mime = TextureMimeType(texture.ImageBytes.Span); if (mime == null) { diagnostics.Add(new(SceneSeverity.Warning, "trimbim-texture-format", @@ -223,6 +172,10 @@ private static void OrientFace(int[] face, Vector3d[] vertices, Vector3d[] norma return id; } + internal static string? TextureMimeType(ReadOnlySpan bytes) + => bytes.StartsWith(new byte[] { 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A }) ? "image/png" + : bytes.StartsWith(new byte[] { 0xFF, 0xD8, 0xFF }) ? "image/jpeg" : null; + private static int[] ReadParents(IReadOnlyList relations, int count, List diagnostics, out int[] spatialParents) { diff --git a/src/TdbIO/Internal/Container/LegacyReferenceCacheReader.cs b/src/TdbIO/Internal/Container/LegacyReferenceCacheReader.cs index 59cf090b..92e9f8fb 100644 --- a/src/TdbIO/Internal/Container/LegacyReferenceCacheReader.cs +++ b/src/TdbIO/Internal/Container/LegacyReferenceCacheReader.cs @@ -2,7 +2,7 @@ namespace TdbIO.Internal; -internal static class LegacyReferenceCacheReader +internal static partial class LegacyReferenceCacheReader { private const int RecordHeaderSize = 8; private const int LayerFixedSize = 8; @@ -16,6 +16,8 @@ public static TdbFileKind KindFromName(string? 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; + if (string.Equals(name, "definitions.tsfodat", StringComparison.OrdinalIgnoreCase)) return TdbFileKind.LegacyReferenceDefinitions; + if (string.Equals(name, "textures.tsfodat", StringComparison.OrdinalIgnoreCase)) return TdbFileKind.LegacyReferenceTextures; return TdbFileKind.Unknown; } @@ -30,6 +32,8 @@ public static bool HasRecordHeader(ReadOnlySpan head, TdbFileKind kind) && size == LayerFixedSize + 2L * Bytes.U32(head, RecordHeaderSize), TdbFileKind.LegacyReferenceMaterials => size == MaterialSize, TdbFileKind.LegacyReferenceInstances => size == InstanceSize, + TdbFileKind.LegacyReferenceDefinitions => head.Length >= 16 && size >= 8 && Bytes.U32(head, 12) <= size - 8, + TdbFileKind.LegacyReferenceTextures => head.Length >= 16 && size >= 8 && Bytes.U32(head, 12) == size - 8, _ => false, }; } @@ -57,8 +61,10 @@ public static LegacyReferenceMaterialsDocument ReadMaterials(byte[] 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); + int texture = Bytes.I32(data, body + 13); + if (texture < -1) throw FormatError.At("Invalid reference cache material texture ID", body + 13); materials.Add(new LegacyReferenceMaterial(id, new TrimBimColor(data[body], data[body + 1], - data[body + 2], data[body + 3]))); + data[body + 2], data[body + 3])) { TextureId = texture == -1 ? null : (uint)texture }); } return new LegacyReferenceMaterialsDocument(materials.AsReadOnly()); } diff --git a/src/TdbIO/Internal/Container/LegacyReferenceGeometryReader.cs b/src/TdbIO/Internal/Container/LegacyReferenceGeometryReader.cs new file mode 100644 index 00000000..616c4c57 --- /dev/null +++ b/src/TdbIO/Internal/Container/LegacyReferenceGeometryReader.cs @@ -0,0 +1,113 @@ +namespace TdbIO.Internal; + +internal static partial class LegacyReferenceCacheReader +{ + public static LegacyReferenceDefinitionsDocument ReadDefinitions(byte[] data) + { + var meshes = new List(); + var ids = new HashSet(); + int unsupported = 0; + foreach (var (id, body, size) in ReadRecords(data)) + { + if (size < 8) throw FormatError.At("Missing reference geometry definition header", body); + if (!ids.Add(id)) throw FormatError.At("Duplicate reference geometry definition ID", body - RecordHeaderSize); + uint type = Bytes.U32(data, body), baseSize = Bytes.U32(data, body + 4); + if (baseSize > size - 8) throw FormatError.At("Invalid reference geometry definition length", body + 4); + if (type is 1 or 4 or 5) meshes.Add(ReadMesh(data, id, type, body, body + 8 + (int)baseSize, body + size)); + else unsupported++; + } + return new LegacyReferenceDefinitionsDocument(meshes.AsReadOnly(), unsupported); + } + + public static LegacyReferenceTexturesDocument ReadTextures(byte[] data) + { + var textures = new List(); + var ids = new HashSet(); + foreach (var (id, body, size) in ReadRecords(data)) + { + if (size < 8 || Bytes.U32(data, body + 4) != size - 8) + throw FormatError.At("Invalid reference cache image length", body); + if (!ids.Add(id)) throw FormatError.At("Duplicate reference cache image ID", body - RecordHeaderSize); + textures.Add(new LegacyReferenceTexture(id, data.AsMemory(body + 8, size - 8))); + } + return new LegacyReferenceTexturesDocument(textures.AsReadOnly()); + } + + private static LegacyReferenceMesh ReadMesh(byte[] data, uint id, uint type, int body, int baseEnd, int end) + { + const int vectorSize = 3 * sizeof(double); + Bytes.Need(body, 16, baseEnd, "Reference mesh header"); + uint count = Bytes.U32(data, body + 8); + int offset = body + 16; + Bytes.Need(offset, (long)count * vectorSize, baseEnd, "Reference mesh vertices"); + var vertices = ReadVectors(data, offset, (int)count); + offset += vertices.Length * vectorSize; + + var polygons = new List(); + int outerCount = ReadContours(data, ref offset, baseEnd, vertices.Length, polygons, null); + Bytes.Need(offset, 8, baseEnd, "Reference mesh hole groups"); + uint groups = Bytes.U32(data, offset); + offset += 8; + for (int group = 0; group < groups; group++) + { + Bytes.Need(offset, 16, baseEnd, "Reference mesh hole group"); + uint parent = Bytes.U32(data, offset); + if (parent >= outerCount) throw FormatError.At("Reference mesh hole has an invalid outer contour index", offset); + offset += 8; + ReadContours(data, ref offset, baseEnd, vertices.Length, polygons, (int)parent); + } + if (offset != baseEnd) throw FormatError.At("Extra data in reference mesh contours", offset); + + var mesh = new LegacyReferenceMesh(id, Array.AsReadOnly(vertices), polygons.AsReadOnly()); + int extraStride = type == 4 ? 8 : type == 5 ? vectorSize : 0; + if (end - baseEnd != (long)count * extraStride) + throw FormatError.At("Invalid reference mesh vertex attribute length", baseEnd); + if (type == 4) + { + var coordinates = new TrimBimTextureCoordinate[vertices.Length]; + for (int i = 0; i < coordinates.Length; i++) + { + int position = baseEnd + i * extraStride; + float u = Bytes.F32(data, position), v = Bytes.F32(data, position + sizeof(float)); + if (!float.IsFinite(u) || !float.IsFinite(v)) + throw FormatError.At("Non-finite reference mesh texture coordinates", position); + coordinates[i] = new TrimBimTextureCoordinate(u, v); + } + return mesh with { TextureCoordinates = Array.AsReadOnly(coordinates) }; + } + return type == 5 ? mesh with { Normals = Array.AsReadOnly(ReadVectors(data, baseEnd, vertices.Length)) } : mesh; + } + + private static ModelVector3D[] ReadVectors(byte[] data, int offset, int count) + { + var values = new ModelVector3D[count]; + for (int i = 0; i < count; i++) + values[i] = ReadVector(data, offset + i * 3 * sizeof(double)); + return values; + } + + private static int ReadContours(byte[] data, ref int offset, int limit, int vertices, + List polygons, int? parent) + { + Bytes.Need(offset, 8, limit, "Reference mesh contour list"); + uint count = Bytes.U32(data, offset); + offset += 8; + for (int i = 0; i < count; i++) + { + Bytes.Need(offset, 8, limit, "Reference mesh contour"); + uint size = Bytes.U32(data, offset); + offset += 8; + Bytes.Need(offset, (long)size * sizeof(uint), limit, "Reference mesh contour indices"); + var indices = new int[size]; + for (int index = 0; index < indices.Length; index++) + { + uint value = Bytes.U32(data, offset); + if (value >= vertices) throw FormatError.At("Reference mesh vertex index is outside the vertex list", offset); + indices[index] = (int)value; + offset += sizeof(uint); + } + polygons.Add(new LegacyReferencePolygon(Array.AsReadOnly(indices), parent)); + } + return (int)count; + } +} diff --git a/src/TdbIO/LegacyReferenceCacheDocuments.cs b/src/TdbIO/LegacyReferenceCacheDocuments.cs index e0a7303b..f2441469 100644 --- a/src/TdbIO/LegacyReferenceCacheDocuments.cs +++ b/src/TdbIO/LegacyReferenceCacheDocuments.cs @@ -39,7 +39,11 @@ internal LegacyReferenceInstancesDocument(IReadOnlyList /// 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); +public readonly record struct LegacyReferenceMaterial(uint Id, TrimBimColor Color) +{ + /// The saved image key in the same cache, or null for an untextured material. + public uint? TextureId { get; init; } +} /// An older reference cache instance, placed in cache coordinates. /// The saved geometry definition key. diff --git a/src/TdbIO/LegacyReferenceGeometry.cs b/src/TdbIO/LegacyReferenceGeometry.cs new file mode 100644 index 00000000..c10e60be --- /dev/null +++ b/src/TdbIO/LegacyReferenceGeometry.cs @@ -0,0 +1,52 @@ +namespace TdbIO; + +/// The supported geometry definitions in an older reference cache. +public sealed class LegacyReferenceDefinitionsDocument : TdbDocument +{ + internal LegacyReferenceDefinitionsDocument(IReadOnlyList meshes, int unsupportedDefinitionCount) + : base(TdbFileKind.LegacyReferenceDefinitions, []) + { + Meshes = meshes; + UnsupportedDefinitionCount = unsupportedDefinitionCount; + } + + /// The saved polygon meshes, in file order. + public IReadOnlyList Meshes { get; } + + /// The number of saved definitions with an unsupported geometry type. + public int UnsupportedDefinitionCount { get; } +} + +/// A saved polygon mesh in an older reference cache. +/// The geometry definition key referenced by instances in the same cache. +/// Mesh-local XYZ coordinates in index order. +/// The outer contours followed by the hole contours. +public readonly record struct LegacyReferenceMesh(uint Id, IReadOnlyList Vertices, + IReadOnlyList Polygons) +{ + /// Stored vertex normals in index order, when present. + public IReadOnlyList? Normals { get; init; } + + /// Stored texture coordinates in index order, when present. + public IReadOnlyList? TextureCoordinates { get; init; } +} + +/// A saved polygon or hole contour in an older reference cache mesh. +/// Zero-based indices into the mesh vertices, in saved order. +/// The zero-based outer contour index for a hole, or null for an outer contour. +public readonly record struct LegacyReferencePolygon(IReadOnlyList VertexIndices, int? OuterContourIndex); + +/// The saved images in an older reference cache, in file order. +public sealed class LegacyReferenceTexturesDocument : TdbDocument +{ + internal LegacyReferenceTexturesDocument(IReadOnlyList textures) + : base(TdbFileKind.LegacyReferenceTextures, []) => Textures = textures; + + /// The images identified by their saved keys. + public IReadOnlyList Textures { get; } +} + +/// An encoded image in an older reference cache. +/// The image key referenced by materials in the same cache. +/// The original encoded image. +public readonly record struct LegacyReferenceTexture(uint Id, ReadOnlyMemory ImageBytes); diff --git a/src/TdbIO/TdbFile.cs b/src/TdbIO/TdbFile.cs index bf21a049..ed218230 100644 --- a/src/TdbIO/TdbFile.cs +++ b/src/TdbIO/TdbFile.cs @@ -113,6 +113,8 @@ private static TdbDocument Read(Stream stream, string? fileName, TdbReadOptions TdbFileKind.LegacyReferenceLayers => LegacyReferenceCacheReader.ReadLayers(payload), TdbFileKind.LegacyReferenceMaterials => LegacyReferenceCacheReader.ReadMaterials(payload), TdbFileKind.LegacyReferenceInstances => LegacyReferenceCacheReader.ReadInstances(payload), + TdbFileKind.LegacyReferenceDefinitions => LegacyReferenceCacheReader.ReadDefinitions(payload), + TdbFileKind.LegacyReferenceTextures => LegacyReferenceCacheReader.ReadTextures(payload), _ => throw NotRecognised(), }; } diff --git a/src/TdbIO/TdbFileKind.cs b/src/TdbIO/TdbFileKind.cs index f85938f7..4af3615d 100644 --- a/src/TdbIO/TdbFileKind.cs +++ b/src/TdbIO/TdbFileKind.cs @@ -81,4 +81,10 @@ public enum TdbFileKind /// A gzip-compressed geometry instance table named instances.tsfodat. LegacyReferenceInstances, + + /// A gzip-compressed geometry definition table named definitions.tsfodat. + LegacyReferenceDefinitions, + + /// A gzip-compressed image table named textures.tsfodat. + LegacyReferenceTextures, } diff --git a/tests/TdbIO.Tests/CliTests.cs b/tests/TdbIO.Tests/CliTests.cs index 14794ecc..f7cf91a4 100644 --- a/tests/TdbIO.Tests/CliTests.cs +++ b/tests/TdbIO.Tests/CliTests.cs @@ -169,6 +169,44 @@ public void ExportsOnlyReferencesVisibleInTheSelectedFileAndProtectsTheirCache() Assert.Equal(trb, System.IO.File.ReadAllBytes(cache)); } + [Fact] + public void ExportsAndProtectsAnOlderReferenceCacheWhenTrimBimIsMissing() + { + string db = File("host.db1", ReferenceScenePayload()); + string cache = Path.Combine("RefCacheFolders", $"7_{ReferenceSceneHash}"); + Directory.CreateDirectory(Path.Combine(_folder, cache)); + File(Path.Combine(cache, "definitions.tsfodat"), Gzip(LegacyReferenceMeshRecord(18, type: 4))); + File(Path.Combine(cache, "layers.tsfodat"), Gzip(LegacyReferenceLayerRecord(3, "Outline", 1))); + File(Path.Combine(cache, "materials.tsfodat"), Gzip(LegacyReferenceMaterialRecord(5, [255, 255, 255, 180], texture: 6))); + File(Path.Combine(cache, "textures.tsfodat"), Gzip(LegacyReferenceImageRecord(6, + [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]))); + byte[] saved = Gzip(LegacyReferenceInstanceRecord(18, 5, 3, 25)); + string instances = File(Path.Combine(cache, "instances.tsfodat"), saved); + + var export = Run("export", db, "--scene-json", "--reference-models"); + Assert.Equal(Cli.ExitOk, export.Exit); + Assert.Empty(export.Err); + using var json = JsonDocument.Parse(export.Out); + var root = json.RootElement; + Assert.Equal(3, root.GetProperty("Models").GetArrayLength()); + Assert.Equal(2, root.GetProperty("Instances").GetArrayLength()); + var geometry = Assert.Single(root.GetProperty("Geometries").EnumerateArray()); + Assert.Equal(24, geometry.GetProperty("Indices").GetArrayLength()); + Assert.Equal(16, geometry.GetProperty("UVs").GetArrayLength()); + Assert.Single(root.GetProperty("Textures").EnumerateArray()); + Assert.Single(root.GetProperty("Materials").EnumerateArray()); + Assert.Contains("Outline", export.Out); + + var overwrite = Run("export", db, instances, "--scene-json", "--reference-models"); + Assert.Equal(Cli.ExitUsage, overwrite.Exit); + Assert.Contains("reference cache", overwrite.Err); + Assert.Equal(saved, System.IO.File.ReadAllBytes(instances)); + + Directory.CreateDirectory(Path.Combine(_folder, "RefCacheFolders", $"8_{ReferenceSceneHash}")); + var ambiguous = Run("export", db, "--scene-json", "--reference-models"); + Assert.Contains("Several older cache folders", ambiguous.Err); + } + [Fact] public void AppliesSavedReferenceVisibilityToHtmlViewpoints() { diff --git a/tests/TdbIO.Tests/LegacyReferenceCacheTests.cs b/tests/TdbIO.Tests/LegacyReferenceCacheTests.cs index de2ca2a0..e43f9486 100644 --- a/tests/TdbIO.Tests/LegacyReferenceCacheTests.cs +++ b/tests/TdbIO.Tests/LegacyReferenceCacheTests.cs @@ -11,7 +11,7 @@ public sealed class LegacyReferenceCacheTests 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 materialsFile = new MemoryStream(Gzip(LegacyReferenceMaterialRecord(5, [17, 89, 166, 240]))); using var instancesFile = new MemoryStream(Gzip(Concat(Instance(8), Instance(3)))); Assert.Equal(TdbFileKind.LegacyReferenceLayers, TdbFile.DetectKind(layersFile, "LAYERS.TSFODAT")); @@ -29,6 +29,44 @@ public void ReadsSavedLayersMaterialsAndInstancesByTheirKeys() Assert.Equal(instances.Instances[0] with { LayerId = 3 }, instances.Instances[1]); } + [Fact] + public void ReadsMeshContoursImagesAndOptionalVertexFields() + { + byte[] image = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]; + using var definitions = new MemoryStream(Gzip(Concat( + LegacyReferenceMeshRecord(18, type: 4), LegacyReferenceMeshRecord(90, type: 5), + LegacyReferenceRecord(8, Concat(Le32(3), Le32(0)))))); + using var textures = new MemoryStream(Gzip(LegacyReferenceImageRecord(11, image))); + using var materials = new MemoryStream(Gzip(LegacyReferenceMaterialRecord(4, [1, 2, 3, 4], texture: 11))); + + Assert.Equal(TdbFileKind.LegacyReferenceDefinitions, TdbFile.DetectKind(definitions, "definitions.tsfodat")); + Assert.Equal(TdbFileKind.LegacyReferenceTextures, TdbFile.DetectKind(textures, "textures.tsfodat")); + var meshes = Assert.IsType(TdbFile.Open(definitions, "definitions.tsfodat")); + Assert.Equal(1, meshes.UnsupportedDefinitionCount); + var textured = meshes.Meshes[0]; + Assert.Equal(18u, textured.Id); + Assert.Equal(new ModelVector3D(4, 1, 0), textured.Vertices[7]); + Assert.Equal(new[] { 0, 1, 2, 3 }, textured.Polygons[0].VertexIndices); + Assert.Null(textured.Polygons[0].OuterContourIndex); + Assert.Equal(new[] { 4, 5, 6, 7 }, textured.Polygons[1].VertexIndices); + Assert.Equal(0, textured.Polygons[1].OuterContourIndex); + Assert.Equal(new TrimBimTextureCoordinate(.4f, .125f), textured.TextureCoordinates![7]); + Assert.Equal(new ModelVector3D(0, 0, -1), meshes.Meshes[1].Normals![7]); + var material = Assert.Single(Assert.IsType(TdbFile.Open(materials, "materials.tsfodat")).Materials); + var texture = Assert.Single(Assert.IsType(TdbFile.Open(textures, "textures.tsfodat")).Textures); + Assert.Equal(texture.Id, material.TextureId); + Assert.Equal(image, texture.ImageBytes.ToArray()); + } + + [Theory] + [InlineData(1, 7, "outer contour index")] + [InlineData(0, 8, "vertex index")] + public void RejectsBadMeshContourReferences(int parent, int vertex, string errorText) + { + using var input = new MemoryStream(Gzip(LegacyReferenceMeshRecord(1, parent: parent, lastVertex: vertex))); + Assert.Contains(errorText, Assert.Throws(() => TdbFile.Open(input, "definitions.tsfodat")).Message); + } + [Fact] public void AcceptsAnEmptyNamedCacheTableAndRequiresTheExactBasename() { diff --git a/tests/TdbIO.Tests/Synthetic.LegacyReference.cs b/tests/TdbIO.Tests/Synthetic.LegacyReference.cs new file mode 100644 index 00000000..25c18887 --- /dev/null +++ b/tests/TdbIO.Tests/Synthetic.LegacyReference.cs @@ -0,0 +1,47 @@ +using System.Buffers.Binary; +using System.Text; + +namespace TdbIO.Tests; + +internal static partial class Synthetic +{ + internal static byte[] LegacyReferenceMeshRecord(uint id, int type = 1, int parent = 0, int lastVertex = 7) + { + byte[] basis = Concat(Le32(8), Le32(0), + LegacyDoubles(0, 0, 0, 10, 0, 0, 10, 8, 0, 0, 8, 0, 2, 1, 0, 2, 3, 0, 4, 3, 0, 4, 1, 0), + Le32(1), Le32(0), Le32(4), Le32(0), Le32(0), Le32(1), Le32(2), Le32(3), + Le32(1), Le32(0), Le32(parent), Le32(0), Le32(1), Le32(0), + Le32(4), Le32(0), Le32(4), Le32(5), Le32(6), Le32(lastVertex)); + byte[] extras = type switch + { + 4 => Floats(0, 0, 1, 0, 1, 1, 0, 1, .2f, .125f, .2f, .375f, .4f, .375f, .4f, .125f), + 5 => LegacyDoubles(0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, + 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1), + _ => [], + }; + return LegacyReferenceRecord(id, Concat(Le32(type), Le32(basis.Length), basis, extras)); + } + + internal static byte[] LegacyReferenceLayerRecord(uint id, string name, uint state) + => LegacyReferenceRecord(id, Concat(Le32(name.Length), Encoding.Unicode.GetBytes(name), Le32(state))); + + internal static byte[] LegacyReferenceMaterialRecord(uint id, byte[] rgba, int texture = -1) => + LegacyReferenceRecord(id, Concat(rgba, new byte[9], Le32(texture), new byte[12])); + + internal static byte[] LegacyReferenceImageRecord(uint id, byte[] data) + => LegacyReferenceRecord(id, Concat(Le32(1), Le32(data.Length), data)); + + internal static byte[] LegacyReferenceInstanceRecord(uint definition, uint materialId, uint layerId, uint objectId) + => LegacyReferenceRecord(definition, Concat(Le32(materialId), Le32(layerId), Le32(objectId), + LegacyDoubles(1.25, -7.5, 13, 0, 1, 0, -1, 0, 0, 0, 0, 1), new byte[12])); + + internal static byte[] LegacyReferenceRecord(uint id, byte[] body) => Concat(Le32(id), Le32(body.Length), body); + + private static byte[] LegacyDoubles(params double[] coordinates) + { + var bytes = new byte[coordinates.Length * sizeof(double)]; + for (int i = 0; i < coordinates.Length; i++) + BinaryPrimitives.WriteDoubleLittleEndian(bytes.AsSpan(i * sizeof(double)), coordinates[i]); + return bytes; + } +}