diff --git a/docs/public-api.md b/docs/public-api.md index 9102699..c859228 100644 --- a/docs/public-api.md +++ b/docs/public-api.md @@ -124,7 +124,7 @@ High-level connected object model produced by `Db1Document.ReadModel()`: | Type | Use | | --- | --- | -| `TeklaModel` | Decoded object graph: `Document`, `ModelGuid`, `Assemblies`, `Parts`, `Bolts`, `Welds`, `Objects`. Fast lookup methods: `FindObject(id/guid)`, `FindPart(id)`, `FindAssembly(id)`, `FindBolt(id)`, `FindWeld(id)`. | +| `TeklaModel` | Decoded object graph: `Document`, `ModelGuid`, `Assemblies`, `Parts`, `Bolts`, `Welds`, `Objects`. Fast lookup methods: `FindObject(id/guid)`, `FindPart(id)`, `FindAssembly(id)`, `FindBolt(id)`, `FindWeld(id)`. JSON serialization: `ToJson(indented)` and `WriteJson(stream/writer, indented)`. | | `ModelObject` | Base entity: `Id`, `Guid` (RFC 4122), `Type`, `Subtype`, `Phase`, `ParentId`, `AssemblyId`, `StringAttributes`, `NumericAttributes`, `GetStringAttribute(name)`, `GetNumericAttribute(name)`. | | `ModelAssembly` | Assembly / cast unit: `Name`, `Prefix`, `StartNumber`, `PositionNumber`, `AssemblyType`, `Class`, `MainPart`, `Secondaries`, `Parts`, `Bolts`, `Welds`. | | `ModelPart` | Structural part: `Name`, `Profile` (resolved with parameter strings), `Material`, `Prefix`, `StartNumber`, `PositionNumber`, `Class`, `Finish`, `Assembly`, `IsMainPart`, `StartPoint`, `EndPoint`, `Length`, `CoordinateSystem`, `Bolts`, `Welds`. | diff --git a/src/TdbIO.Cli/Cli.cs b/src/TdbIO.Cli/Cli.cs index 35e5ef5..2dda55f 100644 --- a/src/TdbIO.Cli/Cli.cs +++ b/src/TdbIO.Cli/Cli.cs @@ -15,15 +15,18 @@ internal static class Cli Usage: tdbio info [--json] [--encoding ascii|utf-8|cp1251|cp1252] tdbio tables [--json] tdbio text [--json] + tdbio export [--indent] tdbio --help | -h | --version Commands: info The kind of the file and its main values. tables The table sections of a model database (.db1) or a DBV@ file, one line each. text The text chains of a model database (.db1), one line each. Save stamps show only their date. + export Decodes the object model of a model database (.db1) and writes it as JSON. Options: --json Write one JSON object instead of text. + --indent Format the JSON output with indentation (export only). --encoding The encoding of a template or report, instead of detecting it (info only). Warnings go to stderr and do not change the exit code. @@ -34,7 +37,7 @@ text The text chains of a model database (.db1), one line each. Save stamps private static readonly string[] TextColumns = ["section", "headId", "rows", "length", "stamp", "savedAt", "text"]; private static readonly string[] OrphanColumns = ["section", "id"]; - private sealed record Command(string Name, string Path, bool Json, Encoding? Encoding); + private sealed record Command(string Name, string Path, bool Json, bool Indent, Encoding? Encoding); // A usage error found while parsing or after the kind is known. private sealed class UsageException(string message) : Exception(message); @@ -74,6 +77,7 @@ internal static int Run(string[] args, TextWriter stdout, TextWriter stderr) { case "info": error = Info(output, doc, command.Json); break; case "tables": Tables(output, doc, command.Json); break; + case "export": Export(output, doc, command.Indent); break; default: Text(output, doc, command.Json); break; } stdout.Write(output.ToString()); @@ -103,11 +107,12 @@ private static Command Parse(string[] args) { if (args.Length == 0) throw new UsageException("No command given."); string name = args[0]; - if (name is not ("info" or "tables" or "text")) throw new UsageException($"Unknown command '{name}'."); + if (name is not ("info" or "tables" or "text" or "export")) throw new UsageException($"Unknown command '{name}'."); string? path = null; string? encodingName = null; bool json = false; + bool indent = false; for (int i = 1; i < args.Length; i++) { string arg = args[i]; @@ -116,6 +121,11 @@ private static Command Parse(string[] args) if (json) throw new UsageException("Option '--json' is repeated."); json = true; } + else if (arg == "--indent" && name == "export") + { + if (indent) throw new UsageException("Option '--indent' is repeated."); + indent = true; + } else if (arg == "--encoding" && name == "info") { if (encodingName != null) throw new UsageException("Option '--encoding' is repeated."); @@ -128,7 +138,7 @@ private static Command Parse(string[] args) else path = arg; } if (path == null) throw new UsageException("No file given."); - return new Command(name, path, json, encodingName == null ? null : EncodingOf(encodingName)); + return new Command(name, path, json, indent, encodingName == null ? null : EncodingOf(encodingName)); } // Strict encodings: a byte the encoding does not define is an input error, never replaced. @@ -290,6 +300,13 @@ private static void Text(TextWriter w, TdbDocument doc, bool json) } } + private static void Export(TextWriter w, TdbDocument doc, bool indent) + { + if (doc is not Db1Document db1) throw new WrongKindException($"'export' needs a model database (.db1), not {doc.Kind}."); + var model = db1.ReadModel(); + w.WriteLine(model.ToJson(indent)); + } + // The number of blocks below the root and the deepest level (the root is level 0). private static (int Blocks, int Depth) Measure(TemplateBlock block) { diff --git a/src/TdbIO/Internal/ModelBuilder.cs b/src/TdbIO/Internal/ModelBuilder.cs index c59fe0a..f0b0db8 100644 --- a/src/TdbIO/Internal/ModelBuilder.cs +++ b/src/TdbIO/Internal/ModelBuilder.cs @@ -20,23 +20,23 @@ internal static TeklaModel BuildFromSections(Db1Document doc, IReadOnlyList r.AsObject()); var assRows = GetActiveRows(FindSection(sections, AssemblyRow.TableKey, AssemblyRow.ExpectedRowSize), AssemblyRow.ExpectedRowSize, r => r.AsAssembly()); - var partRows = GetActiveRows(FindSection(sections, PartRow.TableKey, PartRow.ExpectedRowSize), PartRow.ExpectedRowSize, r => r.AsPart()); + var partRows = GetActiveRows(FindSection(sections, PartRow.TableKey, PartRow.ExpectedRowSize), PartRow.ExpectedRowSize, r => (Row: r.AsPart(), Offset: r.Offset + 1)); var boltRows = GetActiveRows(FindSection(sections, BoltRow.TableKey, BoltRow.ExpectedRowSize), BoltRow.ExpectedRowSize, r => r.AsBolt()); var weldRows = GetActiveRows(FindSection(sections, WeldingRow.TableKey, WeldingRow.ExpectedRowSize), WeldingRow.ExpectedRowSize, r => r.AsWelding()); - var ptRows = GetActiveRows(FindSection(sections, PointRow.TableKey, PointRow.ExpectedRowSize), PointRow.ExpectedRowSize, r => r.AsPoint()); - var csysRows = GetActiveRows(FindSection(sections, CoordsysRow.TableKey, CoordsysRow.ExpectedRowSize), CoordsysRow.ExpectedRowSize, r => r.AsCoordsys()); + var ptRows = GetActiveRows(FindSection(sections, PointRow.TableKey, PointRow.ExpectedRowSize), PointRow.ExpectedRowSize, r => (Row: r.AsPoint(), Offset: r.Offset + 1)); + var csysRows = GetActiveRows(FindSection(sections, CoordsysRow.TableKey, CoordsysRow.ExpectedRowSize), CoordsysRow.ExpectedRowSize, r => (Row: r.AsCoordsys(), Offset: r.Offset + 1)); var paRows = GetActiveRows(FindSection(sections, PartAttrRow.TableKey, PartAttrRow.ExpectedRowSize), PartAttrRow.ExpectedRowSize, r => r.AsPartAttr()); var strPoolRows = GetActiveRows(FindSection(sections, StringPoolRow.TableKey, StringPoolRow.ExpectedRowSize), StringPoolRow.ExpectedRowSize, r => r.AsStringPool()); var numAttrRows = GetActiveRows(FindSection(sections, NumAttrRow.TableKey, NumAttrRow.ExpectedRowSize), NumAttrRow.ExpectedRowSize, r => r.AsNumAttr()); var strAttrRows = GetActiveRows(FindSection(sections, StrAttrRow.TableKey, StrAttrRow.ExpectedRowSize), StrAttrRow.ExpectedRowSize, r => r.AsStrAttr()); - var numDefRows = GetActiveRows(FindSection(sections, NumAttrAttrRow.TableKey, NumAttrAttrRow.ExpectedRowSize), NumAttrAttrRow.ExpectedRowSize, r => r.AsNumAttrAttr()); + var numDefRows = GetActiveRows(FindSection(sections, NumAttrAttrRow.TableKey, NumAttrAttrRow.ExpectedRowSize), NumAttrAttrRow.ExpectedRowSize, r => (Row: r.AsNumAttrAttr(), Offset: r.Offset + 1)); var strDefRows = GetActiveRows(FindSection(sections, StrAttrAttrRow.TableKey, StrAttrAttrRow.ExpectedRowSize), StrAttrAttrRow.ExpectedRowSize, r => r.AsStrAttrAttr()); var phaseRows = GetActiveRows(FindSection(sections, ObjectPhaseRow.TableKey, ObjectPhaseRow.ExpectedRowSize), ObjectPhaseRow.ExpectedRowSize, r => r.AsObjectPhase()); var partNumRows = GetActiveRows(FindSection(sections, PartNumberingRow.TableKey, PartNumberingRow.ExpectedRowSize), PartNumberingRow.ExpectedRowSize, r => r.AsPartNumbering()); var assNumRows = GetActiveRows(FindSection(sections, AssemblyNumberingRow.TableKey, AssemblyNumberingRow.ExpectedRowSize), AssemblyNumberingRow.ExpectedRowSize, r => r.AsAssemblyNumbering()); var objNumRows = GetActiveRows(FindSection(sections, ObjectNumberingRow.TableKey, ObjectNumberingRow.ExpectedRowSize), ObjectNumberingRow.ExpectedRowSize, r => r.AsObjectNumbering()); - var holeRows = GetActiveRows(FindSection(sections, BoltHoleRow.TableKey, BoltHoleRow.ExpectedRowSize), BoltHoleRow.ExpectedRowSize, r => r.AsBoltHole()); - var boltPtRows = GetActiveRows(FindSection(sections, BoltHolePointsRow.TableKey, BoltHolePointsRow.ExpectedRowSize), BoltHolePointsRow.ExpectedRowSize, r => r.AsBoltHolePoints()); + var holeRows = GetActiveRows(FindSection(sections, BoltHoleRow.TableKey, BoltHoleRow.ExpectedRowSize), BoltHoleRow.ExpectedRowSize, r => (Row: r.AsBoltHole(), Offset: r.Offset + 1)); + var boltPtRows = GetActiveRows(FindSection(sections, BoltHolePointsRow.TableKey, BoltHolePointsRow.ExpectedRowSize), BoltHolePointsRow.ExpectedRowSize, r => (Row: r.AsBoltHolePoints(), Offset: r.Offset + 1)); // 2. Primary lookups var objects = new Dictionary(objRows.Count); @@ -114,10 +114,10 @@ void TraverseChain(StringPoolRow head) } var points = new Dictionary(ptRows.Count); - foreach (var pt in ptRows) points[pt.Id] = new ModelPoint(pt.Id, pt.X, pt.Y, pt.Z); + foreach (var (pt, offset) in ptRows) points[pt.Id] = new ModelPoint(pt.Id, pt.X, pt.Y, pt.Z) { Offset = offset }; var coords = new Dictionary(csysRows.Count); - foreach (var cs in csysRows) coords[cs.Id] = new ModelCoordsys(cs.Id, cs.X, cs.Y, cs.Z, cs.Length); + foreach (var (cs, offset) in csysRows) coords[cs.Id] = new ModelCoordsys(cs.Id, cs.X, cs.Y, cs.Z, cs.Length) { Offset = offset }; var partAttrs = new Dictionary(paRows.Count); foreach (var pa in paRows) partAttrs[pa.Id] = pa; @@ -135,10 +135,10 @@ void TraverseChain(StringPoolRow head) foreach (var on in objNumRows) objNumberIds[on.Id] = on.NumberId; // 3. User & System Attributes - var numDefs = new Dictionary(numDefRows.Count); - foreach (var nd in numDefRows) + var numDefs = new Dictionary(numDefRows.Count); + foreach (var (nd, offset) in numDefRows) if (!string.IsNullOrEmpty(nd.Name)) - numDefs[nd.Id] = (nd.Name, nd.Value); + numDefs[nd.Id] = (nd.Name, nd.Value, offset + 8); var strDefs = new Dictionary(strDefRows.Count); foreach (var sd in strDefRows) @@ -151,6 +151,7 @@ void TraverseChain(StringPoolRow head) } var numAttrsByObj = new Dictionary>(); + var numAttrOffsetsByObj = new Dictionary>(); foreach (var na in numAttrRows) { if (numDefs.TryGetValue(na.AttrId, out var def)) @@ -158,6 +159,10 @@ void TraverseChain(StringPoolRow head) if (!numAttrsByObj.TryGetValue(na.FatherId, out var dict)) numAttrsByObj[na.FatherId] = dict = new Dictionary(StringComparer.OrdinalIgnoreCase); dict[def.Name] = def.Value; + + if (!numAttrOffsetsByObj.TryGetValue(na.FatherId, out var offDict)) + numAttrOffsetsByObj[na.FatherId] = offDict = new Dictionary(StringComparer.OrdinalIgnoreCase); + offDict[def.Name] = def.Offset; } } @@ -198,7 +203,10 @@ void TraverseChain(StringPoolRow head) a.Type, a.Class, strAttrs, - numAttrs); + numAttrs) + { + NumericAttributeOffsets = numAttrOffsetsByObj.GetValueOrDefault(a.Id) + }; assemblies.Add(assembly); assembliesById[a.Id] = assembly; @@ -207,7 +215,7 @@ void TraverseChain(StringPoolRow head) // 5. Build Parts var parts = new List(partRows.Count); var partsById = new Dictionary(partRows.Count); - foreach (var p in partRows) + foreach (var (p, pBodyOffset) in partRows) { var obj = objects.GetValueOrDefault(p.Id); int phase = phases.GetValueOrDefault(p.Id); @@ -256,7 +264,11 @@ void TraverseChain(StringPoolRow head) p.Length, csys, strAttrs, - numAttrs); + numAttrs, + lengthOffset: pBodyOffset + 56) + { + NumericAttributeOffsets = numAttrOffsetsByObj.GetValueOrDefault(p.Id) + }; parts.Add(part); partsById[p.Id] = part; @@ -264,7 +276,7 @@ void TraverseChain(StringPoolRow head) // 6. Build Bolts and Bolt Holes var holesByBolt = new Dictionary>(); - foreach (var h in holeRows) + foreach (var (h, offset) in holeRows) { if (!holesByBolt.TryGetValue(h.BoltId, out var list)) holesByBolt[h.BoltId] = list = new List(); @@ -278,16 +290,19 @@ void TraverseChain(StringPoolRow head) h.Length, h.LongHoleDir, h.LongHoleType, - h.ShorteningLength)); + h.ShorteningLength) + { + Offset = offset + }); } var patternPtsByBolt = new Dictionary>(); - foreach (var bp in boltPtRows) + foreach (var (bp, offset) in boltPtRows) { if (!patternPtsByBolt.TryGetValue(bp.BoltId, out var list)) patternPtsByBolt[bp.BoltId] = list = new List(); - list.Add(new ModelPoint(0, bp.IntPoint1X, bp.IntPoint1Y, bp.IntPoint1Z)); - list.Add(new ModelPoint(0, bp.IntPoint2X, bp.IntPoint2Y, bp.IntPoint2Z)); + list.Add(new ModelPoint(0, bp.IntPoint1X, bp.IntPoint1Y, bp.IntPoint1Z) { Offset = offset }); + list.Add(new ModelPoint(0, bp.IntPoint2X, bp.IntPoint2Y, bp.IntPoint2Z) { Offset = offset + 24 }); } var bolts = new List(boltRows.Count); @@ -316,7 +331,10 @@ void TraverseChain(StringPoolRow head) holes, positions, strAttrs, - numAttrs); + numAttrs) + { + NumericAttributeOffsets = numAttrOffsetsByObj.GetValueOrDefault(b.Id) + }; var connectedParts = new List(); foreach (var h in holes) @@ -350,7 +368,10 @@ void TraverseChain(StringPoolRow head) obj.AssemblyId > 0 ? obj.AssemblyId : null, w.CommonAttrId, strAttrs, - numAttrs); + numAttrs) + { + NumericAttributeOffsets = numAttrOffsetsByObj.GetValueOrDefault(w.Id) + }; welds.Add(weld); weldsById[w.Id] = weld; @@ -446,7 +467,10 @@ void TraverseChain(StringPoolRow head) o.ParentId > 0 ? o.ParentId : null, o.AssemblyId > 0 ? o.AssemblyId : null, strAttrs, - numAttrs); + numAttrs) + { + NumericAttributeOffsets = numAttrOffsetsByObj.GetValueOrDefault(o.Id) + }; genericObjectsById[o.Id] = genObj; } } diff --git a/src/TdbIO/Internal/ModelJsonWriter.cs b/src/TdbIO/Internal/ModelJsonWriter.cs new file mode 100644 index 0000000..d156767 --- /dev/null +++ b/src/TdbIO/Internal/ModelJsonWriter.cs @@ -0,0 +1,266 @@ +using System.Globalization; +using System.Text; +using System.Text.Json; + +namespace TdbIO.Internal; + +internal static class ModelJsonWriter +{ + public static string ToJson(TeklaModel model, bool indented) + { + using var stream = new MemoryStream(); + Write(model, stream, indented); + return Encoding.UTF8.GetString(stream.GetBuffer(), 0, (int)stream.Length); + } + + public static void Write(TeklaModel model, Stream stream, bool indented) + { + ArgumentNullException.ThrowIfNull(model); + ArgumentNullException.ThrowIfNull(stream); + + using var writer = new Utf8JsonWriter(stream, new JsonWriterOptions { Indented = indented }); + Write(model, writer); + } + + public static void Write(TeklaModel model, Utf8JsonWriter writer) + { + ArgumentNullException.ThrowIfNull(model); + ArgumentNullException.ThrowIfNull(writer); + + writer.WriteStartObject(); + + writer.WriteString("modelGuid", model.ModelGuid.ToString("D")); + writer.WriteString("version", model.Document.Version); + + writer.WriteStartObject("counts"); + writer.WriteNumber("assemblies", model.Assemblies.Count); + writer.WriteNumber("parts", model.Parts.Count); + writer.WriteNumber("bolts", model.Bolts.Count); + writer.WriteNumber("welds", model.Welds.Count); + writer.WriteNumber("objects", model.Objects.Count); + writer.WriteEndObject(); + + // Assemblies + writer.WriteStartArray("assemblies"); + foreach (var a in model.Assemblies) + { + writer.WriteStartObject(); + writer.WriteNumber("id", a.Id); + writer.WriteString("guid", a.Guid.ToString("D")); + writer.WriteString("name", a.Name); + writer.WriteString("mark", $"{a.Prefix}{a.PositionNumber}"); + writer.WriteString("prefix", a.Prefix); + writer.WriteNumber("startNumber", a.StartNumber); + writer.WriteNumber("positionNumber", a.PositionNumber); + writer.WriteNumber("assemblyType", a.AssemblyType); + writer.WriteNumber("class", a.Class); + writer.WriteNumber("phase", a.Phase); + + if (a.MainPart != null) writer.WriteNumber("mainPartId", a.MainPart.Id); + else writer.WriteNull("mainPartId"); + + writer.WriteStartArray("secondaryPartIds"); + foreach (var s in a.Secondaries) writer.WriteNumberValue(s.Id); + writer.WriteEndArray(); + + writer.WriteStartArray("partIds"); + foreach (var p in a.Parts) writer.WriteNumberValue(p.Id); + writer.WriteEndArray(); + + writer.WriteStartArray("boltIds"); + foreach (var b in a.Bolts) writer.WriteNumberValue(b.Id); + writer.WriteEndArray(); + + writer.WriteStartArray("weldIds"); + foreach (var w in a.Welds) writer.WriteNumberValue(w.Id); + writer.WriteEndArray(); + + WriteAttributes(writer, a); + + writer.WriteEndObject(); + } + writer.WriteEndArray(); + + // Parts + writer.WriteStartArray("parts"); + foreach (var p in model.Parts) + { + writer.WriteStartObject(); + writer.WriteNumber("id", p.Id); + writer.WriteString("guid", p.Guid.ToString("D")); + writer.WriteString("name", p.Name); + writer.WriteString("profile", p.Profile); + writer.WriteString("material", p.Material); + writer.WriteString("mark", $"{p.Prefix}{p.PositionNumber}"); + writer.WriteString("prefix", p.Prefix); + writer.WriteNumber("startNumber", p.StartNumber); + writer.WriteNumber("positionNumber", p.PositionNumber); + writer.WriteNumber("class", p.Class); + writer.WriteString("finish", p.Finish); + WriteFiniteNumber(writer, "length", p.Length, p.LengthOffset); + writer.WriteNumber("phase", p.Phase); + + if (p.AssemblyId.HasValue) writer.WriteNumber("assemblyId", p.AssemblyId.Value); + else writer.WriteNull("assemblyId"); + + writer.WriteBoolean("isMainPart", p.IsMainPart); + + if (p.StartPoint.HasValue) WritePoint(writer, "startPoint", p.StartPoint.Value); + else writer.WriteNull("startPoint"); + + if (p.EndPoint.HasValue) WritePoint(writer, "endPoint", p.EndPoint.Value); + else writer.WriteNull("endPoint"); + + if (p.CoordinateSystem.HasValue) + { + var cs = p.CoordinateSystem.Value; + writer.WriteStartObject("coordinateSystem"); + writer.WriteNumber("id", cs.Id); + long csOff = cs.Offset; + WriteFiniteNumber(writer, "x", cs.X, csOff > 0 ? csOff + 8 : 0); + WriteFiniteNumber(writer, "y", cs.Y, csOff > 0 ? csOff + 16 : 0); + WriteFiniteNumber(writer, "z", cs.Z, csOff > 0 ? csOff + 24 : 0); + WriteFiniteNumber(writer, "length", cs.Length, csOff > 0 ? csOff + 32 : 0); + writer.WriteEndObject(); + } + else writer.WriteNull("coordinateSystem"); + + writer.WriteStartArray("boltIds"); + foreach (var b in p.Bolts) writer.WriteNumberValue(b.Id); + writer.WriteEndArray(); + + writer.WriteStartArray("weldIds"); + foreach (var w in p.Welds) writer.WriteNumberValue(w.Id); + writer.WriteEndArray(); + + WriteAttributes(writer, p); + + writer.WriteEndObject(); + } + writer.WriteEndArray(); + + // Bolts + writer.WriteStartArray("bolts"); + foreach (var b in model.Bolts) + { + writer.WriteStartObject(); + writer.WriteNumber("id", b.Id); + writer.WriteString("guid", b.Guid.ToString("D")); + writer.WriteNumber("phase", b.Phase); + + if (b.AssemblyId.HasValue) writer.WriteNumber("assemblyId", b.AssemblyId.Value); + else writer.WriteNull("assemblyId"); + + if (b.FirstPoint.HasValue) WritePoint(writer, "firstPoint", b.FirstPoint.Value); + else writer.WriteNull("firstPoint"); + + if (b.SecondPoint.HasValue) WritePoint(writer, "secondPoint", b.SecondPoint.Value); + else writer.WriteNull("secondPoint"); + + writer.WriteStartArray("connectedPartIds"); + foreach (var cp in b.ConnectedParts) writer.WriteNumberValue(cp.Id); + writer.WriteEndArray(); + + writer.WriteStartArray("holes"); + foreach (var h in b.Holes) + { + writer.WriteStartObject(); + writer.WriteNumber("no", h.No); + writer.WriteNumber("partId", h.PartId); + long hOff = h.Offset; + WriteFiniteNumber(writer, "pointZ", h.PointZ, hOff > 0 ? hOff + 16 : 0); + WriteFiniteNumber(writer, "length", h.Length, hOff > 0 ? hOff + 24 : 0); + writer.WriteNumber("longHoleDir", h.LongHoleDir); + writer.WriteNumber("longHoleType", h.LongHoleType); + WriteFiniteNumber(writer, "shorteningLength", h.ShorteningLength, hOff > 0 ? hOff + 40 : 0); + writer.WriteEndObject(); + } + writer.WriteEndArray(); + + writer.WriteStartArray("positions"); + foreach (var pos in b.Positions) + { + writer.WriteStartObject(); + long posOff = pos.Offset; + WriteFiniteNumber(writer, "x", pos.X, posOff > 0 ? posOff + 8 : 0); + WriteFiniteNumber(writer, "y", pos.Y, posOff > 0 ? posOff + 16 : 0); + WriteFiniteNumber(writer, "z", pos.Z, posOff > 0 ? posOff + 24 : 0); + writer.WriteEndObject(); + } + writer.WriteEndArray(); + + WriteAttributes(writer, b); + + writer.WriteEndObject(); + } + writer.WriteEndArray(); + + // Welds + writer.WriteStartArray("welds"); + foreach (var w in model.Welds) + { + writer.WriteStartObject(); + writer.WriteNumber("id", w.Id); + writer.WriteString("guid", w.Guid.ToString("D")); + writer.WriteNumber("phase", w.Phase); + writer.WriteNumber("commonAttrId", w.CommonAttrId); + + if (w.AssemblyId.HasValue) writer.WriteNumber("assemblyId", w.AssemblyId.Value); + else writer.WriteNull("assemblyId"); + + if (w.ParentId.HasValue) writer.WriteNumber("parentId", w.ParentId.Value); + else writer.WriteNull("parentId"); + + writer.WriteStartArray("connectedPartIds"); + foreach (var cp in w.ConnectedParts) writer.WriteNumberValue(cp.Id); + writer.WriteEndArray(); + + WriteAttributes(writer, w); + + writer.WriteEndObject(); + } + writer.WriteEndArray(); + + writer.WriteEndObject(); + } + + private static void WriteFiniteNumber(Utf8JsonWriter writer, string propertyName, double value, long offset = 0) + { + if (!double.IsFinite(value)) + throw FormatError.At(string.Create(CultureInfo.InvariantCulture, $"Non-finite number {value} in '{propertyName}'"), offset); + writer.WriteNumber(propertyName, value); + } + + private static void WritePoint(Utf8JsonWriter writer, string propertyName, ModelPoint pt) + { + writer.WriteStartObject(propertyName); + writer.WriteNumber("id", pt.Id); + long ptOff = pt.Offset; + WriteFiniteNumber(writer, "x", pt.X, ptOff > 0 ? ptOff + 8 : 0); + WriteFiniteNumber(writer, "y", pt.Y, ptOff > 0 ? ptOff + 16 : 0); + WriteFiniteNumber(writer, "z", pt.Z, ptOff > 0 ? ptOff + 24 : 0); + writer.WriteEndObject(); + } + + private static void WriteAttributes(Utf8JsonWriter writer, ModelObject obj) + { + if (obj.StringAttributes.Count > 0) + { + writer.WriteStartObject("stringAttributes"); + foreach (var (k, v) in obj.StringAttributes) + writer.WriteString(k, v); + writer.WriteEndObject(); + } + + if (obj.NumericAttributes.Count > 0) + { + writer.WriteStartObject("numericAttributes"); + foreach (var (k, v) in obj.NumericAttributes) + { + long offset = obj.NumericAttributeOffsets != null && obj.NumericAttributeOffsets.TryGetValue(k, out long off) ? off : 0; + WriteFiniteNumber(writer, k, v, offset); + } + writer.WriteEndObject(); + } + } +} diff --git a/src/TdbIO/TeklaModel.cs b/src/TdbIO/TeklaModel.cs index 0682c38..d75d5ea 100644 --- a/src/TdbIO/TeklaModel.cs +++ b/src/TdbIO/TeklaModel.cs @@ -87,6 +87,20 @@ internal TeklaModel( /// Finds a weld by its integer identifier, or returns null if not found. public ModelWeld? FindWeld(int id) => _weldsById.GetValueOrDefault(id); + + /// Serializes the decoded model to a JSON string. + /// Whether to format the JSON with indentation. + /// A JSON string representation of the model. + public string ToJson(bool indented = false) => Internal.ModelJsonWriter.ToJson(this, indented); + + /// Writes the decoded model as JSON to a stream. + /// The output stream. + /// Whether to format the JSON with indentation. + public void WriteJson(Stream stream, bool indented = false) => Internal.ModelJsonWriter.Write(this, stream, indented); + + /// Writes the decoded model as JSON using a . + /// The UTF-8 JSON writer. + public void WriteJson(System.Text.Json.Utf8JsonWriter writer) => Internal.ModelJsonWriter.Write(this, writer); } /// Base class for all entities in a Tekla Structures model. @@ -115,6 +129,8 @@ public ModelObject( NumericAttributes = numericAttributes ?? new Dictionary(); } + internal IReadOnlyDictionary? NumericAttributeOffsets { get; init; } + /// The unique integer identifier of the object (primary key in the database). public int Id { get; } @@ -247,7 +263,8 @@ internal ModelPart( double length, ModelCoordsys? coordinateSystem, IReadOnlyDictionary? stringAttributes = null, - IReadOnlyDictionary? numericAttributes = null) + IReadOnlyDictionary? numericAttributes = null, + long lengthOffset = 0) : base(id, guid, type, subtype, phase, parentId, assemblyId, stringAttributes, numericAttributes) { Name = name ?? string.Empty; @@ -262,10 +279,13 @@ internal ModelPart( EndPoint = endPoint; Length = length; CoordinateSystem = coordinateSystem; + LengthOffset = lengthOffset; Bolts = Array.Empty(); Welds = Array.Empty(); } + internal long LengthOffset { get; init; } + /// The part name (e.g. "BEAM", "COLUMN", "PLATE"). public string Name { get; } @@ -409,6 +429,8 @@ internal ModelWeld( /// The Z coordinate in millimeters. public readonly record struct ModelPoint(int Id, double X, double Y, double Z) { + internal long Offset { get; init; } + /// public override string ToString() => $"({X:F2}, {Y:F2}, {Z:F2})"; } @@ -421,6 +443,8 @@ public readonly record struct ModelPoint(int Id, double X, double Y, double Z) /// Length or scale factor. public readonly record struct ModelCoordsys(int Id, double X, double Y, double Z, double Length) { + internal long Offset { get; init; } + /// public override string ToString() => $"Origin=({X:F2}, {Y:F2}, {Z:F2}), Length={Length:F2}"; } @@ -444,6 +468,8 @@ public readonly record struct ModelBoltHole( int LongHoleType, double ShorteningLength) { + internal long Offset { get; init; } + /// public override string ToString() => $"Hole #{No} in Part #{PartId} Grip={Length:F1}"; } diff --git a/tests/TdbIO.Tests/CliTests.cs b/tests/TdbIO.Tests/CliTests.cs index 7033dda..c9935dc 100644 --- a/tests/TdbIO.Tests/CliTests.cs +++ b/tests/TdbIO.Tests/CliTests.cs @@ -1,3 +1,4 @@ +using System.Buffers.Binary; using System.Text.Json; using TdbIO.CommandLine; using Xunit; @@ -61,6 +62,9 @@ private string Db1WithTables() => File("t.db1", Gzip(Db1TablesPayload( [InlineData("info", "a", "--encoding", "utf-16")] [InlineData("info", "a", "--encoding", "ascii", "--encoding", "ascii")] [InlineData("tables", "a", "--encoding", "ascii")] + [InlineData("export")] + [InlineData("export", "a", "--indent", "--indent")] + [InlineData("export", "a", "--encoding", "ascii")] [InlineData("text", "-h")] [InlineData("--help", "x")] public void UsageErrorsExitOneWithTwoLines(params string[] args) @@ -357,6 +361,58 @@ public void BrokenTextSectionInJsonInfoPrintsHeaderAndReportsError() Assert.StartsWith("tdbio: ", Assert.Single(Lines(stderr))); } + [Fact] + public void ExportOnDbvIsAnInputError() => AssertInputError("export", Dbv()); + + [Fact] + public void ExportOutputsJsonForDb1() + { + var (exit, stdout, stderr) = Run("export", Db1WithTables(), "--indent"); + Assert.Equal(Cli.ExitOk, exit); + Assert.Equal("", stderr); + using var json = JsonDocument.Parse(stdout); + var root = json.RootElement; + Assert.True(root.TryGetProperty("modelGuid", out _)); + Assert.True(root.TryGetProperty("assemblies", out _)); + Assert.True(root.TryGetProperty("parts", out _)); + Assert.True(root.TryGetProperty("counts", out _)); + } + + [Fact] + public void ExportOnModelWithNonFiniteNumberReturnsExitInput() + { + var partBytes = new byte[PartRow.ExpectedRowSize]; + BinaryPrimitives.WriteInt32LittleEndian(partBytes.AsSpan(0), 101); + BinaryPrimitives.WriteDoubleLittleEndian(partBytes.AsSpan(56), double.NaN); + + var objBytes = new byte[ObjectRow.ExpectedRowSize]; + BinaryPrimitives.WriteInt32LittleEndian(objBytes.AsSpan(0), 101); + BinaryPrimitives.WriteInt32LittleEndian(objBytes.AsSpan(28), 1); // Type = 1 (Part) + + byte[] unkeyedSec = Db1Section(null, 4, [1], (0x04, Counting(4), 1, 2)); + byte[] objSec = Db1Section(ObjectRow.TableKey, ObjectRow.ExpectedRowSize, [1], (0x04, objBytes, 1, 2)); + byte[] partSec = Db1Section(PartRow.TableKey, PartRow.ExpectedRowSize, [1], (0x04, partBytes, 1, 2)); + + string nanFile = File("nan.db1", Gzip(Db1TablesPayload(unkeyedSec, objSec, partSec))); + + var (exit, stdout, stderr) = Run("export", nanFile); + Assert.Equal(Cli.ExitInput, exit); + Assert.Contains("Non-finite number NaN in 'length'", stderr); + Assert.Contains("0x152", stderr); + + // Finite counterpart succeeds + var finitePartBytes = (byte[])partBytes.Clone(); + BinaryPrimitives.WriteDoubleLittleEndian(finitePartBytes.AsSpan(56), 1000.0); + byte[] finitePartSec = Db1Section(PartRow.TableKey, PartRow.ExpectedRowSize, [1], (0x04, finitePartBytes, 1, 2)); + string okFile = File("ok.db1", Gzip(Db1TablesPayload(unkeyedSec, objSec, finitePartSec))); + + var (okExit, okStdout, okStderr) = Run("export", okFile); + Assert.Equal(Cli.ExitOk, okExit); + Assert.Empty(okStderr); + using var json = JsonDocument.Parse(okStdout); + Assert.Equal(1000.0, json.RootElement.GetProperty("parts")[0].GetProperty("length").GetDouble()); + } + private static void AssertInputError(params string[] args) { var (exit, stdout, stderr) = Run(args); diff --git a/tests/TdbIO.Tests/JsonExportTests.cs b/tests/TdbIO.Tests/JsonExportTests.cs new file mode 100644 index 0000000..4456d6f --- /dev/null +++ b/tests/TdbIO.Tests/JsonExportTests.cs @@ -0,0 +1,111 @@ +using System.Text.Json; +using Xunit; + +namespace TdbIO.Tests; + +public class JsonExportTests +{ + [Fact] + public void WriteJsonThrowsOnNull() + { + var doc = Db1Document.Create(Synthetic.Db1TablesPayload( + Synthetic.Db1Section(null, 4, [1], (0x04, Synthetic.Counting(4), 1, 2)))); + var model = doc.ReadModel(); + Assert.Throws(() => model.WriteJson((Stream)null!)); + Assert.Throws(() => model.WriteJson((Utf8JsonWriter)null!)); + } + + [SkippableFact] + public void RealModelsExportToValidJson() + { + var files = TestFiles.FindAll(".db1", ".bak").Where(f => TdbFile.DetectKind(f) == TdbFileKind.Db1).ToList(); + if (files.Count == 0) throw TestFiles.Missing("model database files"); + + foreach (string file in files) + { + var doc = (Db1Document)TdbFile.Open(file); + var model = doc.ReadModel(); + + string compactJson = model.ToJson(indented: false); + Assert.False(string.IsNullOrEmpty(compactJson)); + Assert.DoesNotContain("\n", compactJson); + + string indentedJson = model.ToJson(indented: true); + Assert.Contains("\n", indentedJson); + + // Stream write matches string export + using var ms = new MemoryStream(); + model.WriteJson(ms, indented: true); + string streamJson = System.Text.Encoding.UTF8.GetString(ms.ToArray()); + Assert.Equal(indentedJson, streamJson); + + // Parse and validate structure + using var json = JsonDocument.Parse(compactJson); + var root = json.RootElement; + + Assert.Equal(model.ModelGuid.ToString("D"), root.GetProperty("modelGuid").GetString()); + Assert.Equal(doc.Version, root.GetProperty("version").GetString()); + + var counts = root.GetProperty("counts"); + Assert.Equal(model.Assemblies.Count, counts.GetProperty("assemblies").GetInt32()); + Assert.Equal(model.Parts.Count, counts.GetProperty("parts").GetInt32()); + Assert.Equal(model.Bolts.Count, counts.GetProperty("bolts").GetInt32()); + Assert.Equal(model.Welds.Count, counts.GetProperty("welds").GetInt32()); + Assert.Equal(model.Objects.Count, counts.GetProperty("objects").GetInt32()); + + var assemblies = root.GetProperty("assemblies"); + Assert.Equal(model.Assemblies.Count, assemblies.GetArrayLength()); + + var parts = root.GetProperty("parts"); + Assert.Equal(model.Parts.Count, parts.GetArrayLength()); + + var bolts = root.GetProperty("bolts"); + Assert.Equal(model.Bolts.Count, bolts.GetArrayLength()); + + var welds = root.GetProperty("welds"); + Assert.Equal(model.Welds.Count, welds.GetArrayLength()); + } + } + + [Fact] + public void NonFiniteLengthThrowsInvalidDataException() + { + var doc = Db1Document.Create(Synthetic.Db1Payload([])); + var part = new ModelPart(1, Guid.NewGuid(), 1, 0, 1, null, null, "BEAM", "HEA300", "S355", "B", 1, 1, 1, "", null, null, double.NaN, null, lengthOffset: 0x12A); + var model = new TeklaModel(doc, doc.ModelGuid, [], [part], [], [], [part]); + + var ex = Assert.Throws(() => model.ToJson()); + Assert.Equal(0x12A, (long)ex.Data["Offset"]!); + Assert.Contains("0x12A", ex.Message); + } + + [Fact] + public void NonFiniteCoordinatesThrowInvalidDataException() + { + var doc = Db1Document.Create(Synthetic.Db1Payload([])); + var pt = new ModelPoint(1, double.PositiveInfinity, 0, 0) { Offset = 0x100 }; + var part = new ModelPart(1, Guid.NewGuid(), 1, 0, 1, null, null, "BEAM", "HEA300", "S355", "B", 1, 1, 1, "", pt, null, 1000.0, null); + var model = new TeklaModel(doc, doc.ModelGuid, [], [part], [], [], [part]); + + var ex = Assert.Throws(() => model.ToJson()); + Assert.Equal(0x108, (long)ex.Data["Offset"]!); + Assert.Contains("0x108", ex.Message); + } + + [Fact] + public void NonFiniteNumericAttributeThrowsInvalidDataException() + { + var doc = Db1Document.Create(Synthetic.Db1Payload([])); + var attrs = new Dictionary { ["WEIGHT"] = double.NaN }; + var offsets = new Dictionary { ["WEIGHT"] = 0x200 }; + var part = new ModelPart(1, Guid.NewGuid(), 1, 0, 1, null, null, "BEAM", "HEA300", "S355", "B", 1, 1, 1, "", null, null, 1000.0, null, null, attrs) + { + NumericAttributeOffsets = offsets + }; + var model = new TeklaModel(doc, doc.ModelGuid, [], [part], [], [], [part]); + + var ex = Assert.Throws(() => model.ToJson()); + Assert.Equal(0x200, (long)ex.Data["Offset"]!); + Assert.Contains("0x200", ex.Message); + } +}