diff --git a/CHANGELOG.md b/CHANGELOG.md index 6d6835f..855bd64 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,7 @@ API between minor releases. ### Added +- Read saved double-precision curve sets from older reference caches and export their curve-only lines, points and arcs. - 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`. diff --git a/docs/public-api.md b/docs/public-api.md index 7a75a57..50de98f 100644 --- a/docs/public-api.md +++ b/docs/public-api.md @@ -818,8 +818,12 @@ 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 +are float pairs. `CurveSets` exposes saved lines, points and circular arcs +in double precision, including the envelope radius when stored. The scene +adapter renders curve-only definitions. It reports omitted geometry for +definitions whose body is unsupported. `UnsupportedDefinitionCount` +counts unhandled definitions in the native reader. +A material's `TextureId` identifies the encoded image in `LegacyReferenceTexturesDocument`. With reference exports enabled, the scene reader uses an older reference @@ -827,7 +831,7 @@ 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. +mesh and curve instances, transforms, colors, layer names and supported images. Scene diagnostics report omitted geometry. `TdbSceneResult.ReferenceCacheFiles` lists the cache paths consulted during conversion. diff --git a/src/TdbIO.Cli/Cli.cs b/src/TdbIO.Cli/Cli.cs index 21a1b66..54fb961 100644 --- a/src/TdbIO.Cli/Cli.cs +++ b/src/TdbIO.Cli/Cli.cs @@ -529,6 +529,7 @@ private static Command Parse(string[] args) break; case LegacyReferenceDefinitionsDocument definitions: Add("polygonMeshes", definitions.Meshes.Count); + Add("curveSets", definitions.CurveSets.Count); Add("unsupportedDefinitions", definitions.UnsupportedDefinitionCount); break; case LegacyReferenceTexturesDocument textures: diff --git a/src/TdbIO.Scene/TdbSceneReader.LegacyReferences.cs b/src/TdbIO.Scene/TdbSceneReader.LegacyReferences.cs index 27eeb00..cf78b9e 100644 --- a/src/TdbIO.Scene/TdbSceneReader.LegacyReferences.cs +++ b/src/TdbIO.Scene/TdbSceneReader.LegacyReferences.cs @@ -71,7 +71,7 @@ private static TrimBimSceneResult ReadLegacyReference(string directory, string n .ToDictionary(material => material.Id); var textures = new Dictionary(); var textureTable = new Lazy>(ReadTextureTable); - var geometries = new Dictionary(); + var geometries = new Dictionary(); int skippedFaces = 0; foreach (var mesh in definitions.Meshes) { @@ -82,17 +82,24 @@ private static TrimBimSceneResult ReadLegacyReference(string directory, string n skippedFaces += skipped; if (indices.Count == 0) continue; int id = source.Geometries.Count + 1; - geometries.Add(mesh.Id, id); + geometries.Add(mesh.Id, (id, null, null)); 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(), }); } + foreach (var curves in definitions.CurveSets) + { + if (curves.EnvelopeRadius != null) continue; + var arcs = curves.Arcs.Select(arc => (arc.Center, arc.Normal, arc.StartDirection, arc.Radius, arc.SweepRadians)); + var (lines, points) = TrimBimSceneReader.AddCurveGeometry(source, curves.Segments, arcs, metresPerUnit: 1); + if (lines != null || points != null) geometries.Add(curves.Id, (null, lines, points)); + } int skippedInstances = 0; foreach (var instance in instances) { - if (!geometries.TryGetValue(instance.DefinitionId, out int geometry)) + if (!geometries.TryGetValue(instance.DefinitionId, out var geometry)) { skippedInstances++; continue; @@ -102,18 +109,23 @@ private static TrimBimSceneResult ReadLegacyReference(string directory, string n 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 + if (geometry.Mesh is int mesh) + AddInstance(mesh, material.TextureId is uint texture ? AddLegacyTexture(texture) : null); + if (geometry.Lines is int lines) AddInstance(lines, null); + if (geometry.Points is int points) AddInstance(points, null); + + void AddInstance(int id, int? materialId) => source.Instances.Add(new SceneInstance { - ElementId = objectIds[instance.ObjectId], GeometryId = geometry, + ElementId = objectIds[instance.ObjectId], GeometryId = id, 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, + MaterialId = materialId, }); } 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."))); + $"The older cache omitted {skippedInstances} instances without supported renderable geometry and {skippedFaces} faces that could not be triangulated."))); int? AddLegacyTexture(uint textureId) { diff --git a/src/TdbIO.Scene/TrimBimSceneReader.Curves.cs b/src/TdbIO.Scene/TrimBimSceneReader.Curves.cs index 4d799b0..cfc913b 100644 --- a/src/TdbIO.Scene/TrimBimSceneReader.Curves.cs +++ b/src/TdbIO.Scene/TrimBimSceneReader.Curves.cs @@ -7,27 +7,11 @@ public static partial class TrimBimSceneReader private static void AddCurves(SceneDocument scene, TrimBimDocument document, TrimBimObjectPlacement[] placements, double metresPerUnit) { - int nextId = (scene.Geometries.LastOrDefault()?.Id ?? 0) + 1; var ids = new Dictionary(); foreach (var curves in document.ReadCurveSets()) - { - var lines = new List(); - var points = new List(); - foreach (var segment in curves.Segments) - { - Vector3d p = Vector(segment.Start) * metresPerUnit; - if (segment.Start == segment.End) points.Add(p); - else - { - lines.Add(p); - lines.Add(Vector(segment.End) * metresPerUnit); - } - } - foreach (var arc in curves.Arcs) - AddArc(arc, metresPerUnit, lines, points); - - ids.Add(curves.CurveSetIndex, (AddGeometry(SceneTopology.Lines, lines), AddGeometry(SceneTopology.Points, points))); - } + ids.Add(curves.CurveSetIndex, AddCurveGeometry(scene, curves.Segments, + curves.Arcs.Select(arc => (arc.Center, arc.Normal, arc.StartDirection, + (double)arc.Radius, (double)arc.SweepRadians)), metresPerUnit)); foreach (var instance in document.ReadCurveSetInstances()) { @@ -36,20 +20,44 @@ private static void AddCurves(SceneDocument scene, TrimBimDocument document, if (points is int pointId) AddInstance(pointId, instance); } + void AddInstance(int id, TrimBimCurveSetInstance instance) + => scene.Instances.Add(CreateInstance(id, placements[instance.ObjectIndex], instance.Origin, + instance.AxisX, instance.AxisY, instance.Color, metresPerUnit)); + } + + internal static (int? Lines, int? Points) AddCurveGeometry(SceneDocument scene, IEnumerable segments, + IEnumerable<(ModelVector3D Center, ModelVector3D Normal, ModelVector3D StartDirection, double Radius, double SweepRadians)> arcs, + double metresPerUnit) + { + var lines = new List(); + var points = new List(); + foreach (var segment in segments) + { + Vector3d p = Vector(segment.Start) * metresPerUnit; + if (segment.Start == segment.End) points.Add(p); + else + { + lines.Add(p); + lines.Add(Vector(segment.End) * metresPerUnit); + } + } + foreach (var arc in arcs) + AddArc(arc, metresPerUnit, lines, points); + + return (AddGeometry(SceneTopology.Lines, lines), AddGeometry(SceneTopology.Points, points)); + int? AddGeometry(SceneTopology topology, List vertices) { if (vertices.Count == 0) return null; - int id = nextId++; + int id = (scene.Geometries.LastOrDefault()?.Id ?? 0) + 1; scene.Geometries.Add(new SceneGeometry { Id = id, Topology = topology, Vertices = vertices }); return id; } - - void AddInstance(int id, TrimBimCurveSetInstance instance) - => scene.Instances.Add(CreateInstance(id, placements[instance.ObjectIndex], instance.Origin, - instance.AxisX, instance.AxisY, instance.Color, metresPerUnit)); } - private static void AddArc(TrimBimCircularArc arc, double metresPerUnit, List lines, List points) + private static void AddArc( + (ModelVector3D Center, ModelVector3D Normal, ModelVector3D StartDirection, double Radius, double SweepRadians) arc, + double metresPerUnit, List lines, List points) { Vector3d center = Vector(arc.Center) * metresPerUnit; Vector3d axisX = Vector(arc.StartDirection) * (arc.Radius * metresPerUnit); @@ -64,11 +72,11 @@ private static void AddArc(TrimBimCircularArc arc, double metresPerUnit, List(); + var arcs = new List(); + for (int group = 0; group < groupCount; group++) + { + if (hasEnvelope) + { + Bytes.Need(offset, sizeof(uint), tail, "Reference curve group type"); + if (Bytes.U32(data, offset) != 1) return null; + offset += sizeof(uint); + } + Bytes.Need(offset, sizeof(uint), tail, "Reference curve group length"); + uint length = Bytes.U32(data, offset); + offset += sizeof(uint); + Bytes.Need(offset, length, tail, "Reference curve group"); + int groupEnd = offset + (int)length; + while (offset < groupEnd) + { + Bytes.Need(offset, 8, groupEnd, "Reference curve primitive header"); + uint kind = Bytes.U32(data, offset), width = Bytes.U32(data, offset + 4); + offset += 8; + Bytes.Need(offset, width, groupEnd, "Reference curve primitive"); + switch (kind) + { + case 2: + if (width != 48) throw FormatError.At("Invalid reference curve segment length", offset - 4); + segments.Add(new TrimBimLineSegment(ReadVector(data, offset), ReadVector(data, offset + 24))); + break; + case 4: + if (width != 88) throw FormatError.At("Invalid reference circular arc length", offset - 4); + double radius = Bytes.F64(data, offset + 24), sweep = Bytes.F64(data, offset + 80); + if (!double.IsFinite(radius) || radius < 0) + throw FormatError.At("Invalid reference circular arc radius", offset + 24); + if (!double.IsFinite(sweep)) + throw FormatError.At("Invalid reference circular arc sweep", offset + 80); + arcs.Add(new LegacyReferenceCircularArc(ReadVector(data, offset), ReadVector(data, offset + 32), + ReadVector(data, offset + 56), radius, sweep)); + break; + default: + return null; + } + offset += (int)width; + } + } + if (offset != tail) throw FormatError.At("Extra data in reference curve groups", offset); + if (!hasEnvelope && Bytes.U32(data, tail) != 0) return null; + var set = new LegacyReferenceCurveSet(id, segments.AsReadOnly(), arcs.AsReadOnly()); + if (!hasEnvelope) return set; + + double envelopeRadius = Bytes.F64(data, tail); + if (!double.IsFinite(envelopeRadius) || envelopeRadius < 0) + throw FormatError.At("Invalid reference curve envelope radius", tail); + return set with { EnvelopeRadius = envelopeRadius }; + } +} diff --git a/src/TdbIO/Internal/Container/LegacyReferenceGeometryReader.cs b/src/TdbIO/Internal/Container/LegacyReferenceGeometryReader.cs index 616c4c5..d2d6e92 100644 --- a/src/TdbIO/Internal/Container/LegacyReferenceGeometryReader.cs +++ b/src/TdbIO/Internal/Container/LegacyReferenceGeometryReader.cs @@ -5,6 +5,7 @@ internal static partial class LegacyReferenceCacheReader public static LegacyReferenceDefinitionsDocument ReadDefinitions(byte[] data) { var meshes = new List(); + var curves = new List(); var ids = new HashSet(); int unsupported = 0; foreach (var (id, body, size) in ReadRecords(data)) @@ -14,9 +15,11 @@ public static LegacyReferenceDefinitionsDocument ReadDefinitions(byte[] data) 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 if (type is 2 or 3 && ReadCurveSet(data, id, type == 3, body, body + size, baseSize) is { } curveSet) + curves.Add(curveSet); else unsupported++; } - return new LegacyReferenceDefinitionsDocument(meshes.AsReadOnly(), unsupported); + return new LegacyReferenceDefinitionsDocument(meshes.AsReadOnly(), curves.AsReadOnly(), unsupported); } public static LegacyReferenceTexturesDocument ReadTextures(byte[] data) diff --git a/src/TdbIO/LegacyReferenceGeometry.cs b/src/TdbIO/LegacyReferenceGeometry.cs index c10e60b..155ba0f 100644 --- a/src/TdbIO/LegacyReferenceGeometry.cs +++ b/src/TdbIO/LegacyReferenceGeometry.cs @@ -3,16 +3,21 @@ namespace TdbIO; /// The supported geometry definitions in an older reference cache. public sealed class LegacyReferenceDefinitionsDocument : TdbDocument { - internal LegacyReferenceDefinitionsDocument(IReadOnlyList meshes, int unsupportedDefinitionCount) + internal LegacyReferenceDefinitionsDocument(IReadOnlyList meshes, + IReadOnlyList curveSets, int unsupportedDefinitionCount) : base(TdbFileKind.LegacyReferenceDefinitions, []) { Meshes = meshes; + CurveSets = curveSets; UnsupportedDefinitionCount = unsupportedDefinitionCount; } /// The saved polygon meshes, in file order. public IReadOnlyList Meshes { get; } + /// The saved sets of line segments and circular arcs, in file order. + public IReadOnlyList CurveSets { get; } + /// The number of saved definitions with an unsupported geometry type. public int UnsupportedDefinitionCount { get; } } @@ -36,6 +41,26 @@ public readonly record struct LegacyReferenceMesh(uint Id, IReadOnlyListThe zero-based outer contour index for a hole, or null for an outer contour. public readonly record struct LegacyReferencePolygon(IReadOnlyList VertexIndices, int? OuterContourIndex); +/// A saved set of analytic curves in an older reference cache. +/// The geometry definition key referenced by instances in the same cache. +/// The saved line segments, including points with coincident endpoints. +/// The saved circular arcs. +public readonly record struct LegacyReferenceCurveSet(uint Id, IReadOnlyList Segments, + IReadOnlyList Arcs) +{ + /// The saved radius that expands the bounds of a radius-bearing path, or null for a curve-only definition. + public double? EnvelopeRadius { get; init; } +} + +/// A saved circular arc using double precision in an older reference cache. +/// The local center of the circle. +/// The stored normal of the circle. +/// The stored direction from the center to the start. +/// The stored arc radius. +/// The signed sweep angle in radians. +public readonly record struct LegacyReferenceCircularArc(ModelVector3D Center, ModelVector3D Normal, + ModelVector3D StartDirection, double Radius, double SweepRadians); + /// The saved images in an older reference cache, in file order. public sealed class LegacyReferenceTexturesDocument : TdbDocument { diff --git a/tests/TdbIO.Tests/CliTests.cs b/tests/TdbIO.Tests/CliTests.cs index f7cf91a..cf6ec1a 100644 --- a/tests/TdbIO.Tests/CliTests.cs +++ b/tests/TdbIO.Tests/CliTests.cs @@ -207,6 +207,38 @@ public void ExportsAndProtectsAnOlderReferenceCacheWhenTrimBimIsMissing() Assert.Contains("Several older cache folders", ambiguous.Err); } + [Fact] + public void ExportsLegacyLinesAndPointsWithoutSubstitutingAPathForRadiusBearingGeometry() + { + 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(Concat(LegacyReferenceCurvesRecord(18), LegacyReferenceCurvesRecord(19, envelope: 0.1)))); + File(Path.Combine(cache, "layers.tsfodat"), Gzip(LegacyReferenceLayerRecord(3, "Outline", 1))); + File(Path.Combine(cache, "materials.tsfodat"), Gzip(LegacyReferenceMaterialRecord(5, [3, 17, 31, 190]))); + File(Path.Combine(cache, "instances.tsfodat"), Gzip(Concat( + LegacyReferenceInstanceRecord(18, 5, 3, 25), LegacyReferenceInstanceRecord(19, 5, 3, 26)))); + + var export = Run("export", db, "--scene-json", "--reference-models"); + Assert.Equal(Cli.ExitOk, export.Exit); + Assert.Contains("omitted 1 instances", export.Err); + using var json = JsonDocument.Parse(export.Out); + var root = json.RootElement; + Assert.Equal(4, root.GetProperty("Instances").GetArrayLength()); + Assert.Collection(root.GetProperty("Geometries").EnumerateArray(), + lines => + { + Assert.Equal((int)IOScene.SceneTopology.Lines, lines.GetProperty("Topology").GetInt32()); + Assert.Equal(114, lines.GetProperty("Vertices").GetArrayLength()); + }, + point => + { + Assert.Equal((int)IOScene.SceneTopology.Points, point.GetProperty("Topology").GetInt32()); + Assert.Equal(new[] { 3d, 4d, 5d }, point.GetProperty("Vertices").EnumerateArray().Select(v => v.GetDouble())); + }); + } + [Fact] public void AppliesSavedReferenceVisibilityToHtmlViewpoints() { diff --git a/tests/TdbIO.Tests/LegacyReferenceCacheTests.cs b/tests/TdbIO.Tests/LegacyReferenceCacheTests.cs index e43f948..f1ece3f 100644 --- a/tests/TdbIO.Tests/LegacyReferenceCacheTests.cs +++ b/tests/TdbIO.Tests/LegacyReferenceCacheTests.cs @@ -35,7 +35,7 @@ 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)))))); + LegacyReferenceRecord(8, Concat(Le32(99), 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))); @@ -58,6 +58,33 @@ public void ReadsMeshContoursImagesAndOptionalVertexFields() Assert.Equal(image, texture.ImageBytes.ToArray()); } + [Theory] + [InlineData(null)] + [InlineData(0.0028575)] + public void RetainsSavedDoublePrecisionCurvesAndTheEnvelope(double? envelope) + { + using var file = new MemoryStream(Gzip(LegacyReferenceCurvesRecord(25, envelope))); + var definitions = Assert.IsType(TdbFile.Open(file, "definitions.tsfodat")); + var set = Assert.Single(definitions.CurveSets); + Assert.Equal(25u, set.Id); + Assert.Equal(envelope, set.EnvelopeRadius); + Assert.Equal(new ModelVector3D(1.234567890123, 0, 0), set.Segments[0].End); + Assert.Equal(set.Segments[1].Start, set.Segments[1].End); + var arc = Assert.Single(set.Arcs); + Assert.Equal(2.34567890123, arc.Radius); + Assert.Equal(-Math.PI / 2, arc.SweepRadians); + Assert.Equal(new ModelVector3D(0, 0, 1), arc.Normal); + Assert.Equal(0, definitions.UnsupportedDefinitionCount); + } + + [Fact] + public void RejectsAnInvalidLegacyArcLength() + { + using var file = new MemoryStream(Gzip(LegacyReferenceCurvesRecord(25, arcSize: 80))); + var error = Assert.Throws(() => TdbFile.Open(file, "definitions.tsfodat")); + Assert.Contains("Invalid reference circular arc length", error.Message); + } + [Theory] [InlineData(1, 7, "outer contour index")] [InlineData(0, 8, "vertex index")] diff --git a/tests/TdbIO.Tests/Synthetic.LegacyReference.cs b/tests/TdbIO.Tests/Synthetic.LegacyReference.cs index 25c1888..cd04386 100644 --- a/tests/TdbIO.Tests/Synthetic.LegacyReference.cs +++ b/tests/TdbIO.Tests/Synthetic.LegacyReference.cs @@ -25,6 +25,18 @@ internal static byte[] LegacyReferenceMeshRecord(uint id, int type = 1, int pare 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[] LegacyReferenceCurvesRecord(uint id, double? envelope = null, int arcSize = 88) + { + byte[] primitives = Concat( + Le32(2), Le32(48), LegacyDoubles(0, 0, 0, 1.234567890123, 0, 0), + Le32(2), Le32(48), LegacyDoubles(3, 4, 5, 3, 4, 5), + Le32(4), Le32(arcSize), LegacyDoubles(0, 0, 0, 2.34567890123, 0, 0, 1, 1, 0, 0, -Math.PI / 2)); + byte[] payload = envelope is double radius + ? Concat(Le32(1), Le32(1), Le32(primitives.Length), primitives, LegacyDoubles(radius)) + : Concat(Le32(1), Le32(primitives.Length), primitives, Le32(0)); + return LegacyReferenceRecord(id, Concat(Le32(envelope.HasValue ? 3 : 2), Le32(payload.Length), payload)); + } + internal static byte[] LegacyReferenceMaterialRecord(uint id, byte[] rgba, int texture = -1) => LegacyReferenceRecord(id, Concat(rgba, new byte[9], Le32(texture), new byte[12]));