From 03539118e0e1f888dc4998f4df72fedb6e8a1721 Mon Sep 17 00:00:00 2001 From: sim <79989386+mahach666@users.noreply.github.com> Date: Sat, 5 Dec 2026 13:09:40 +0300 Subject: [PATCH] Read remaining layouts from the issue 291 retest Co-authored-by: SergeyPriem <97326127+SergeyPriem@users.noreply.github.com> --- CHANGELOG.md | 1 + docs/format-notes.md | 8 +- src/NwcIO/Internal/Parsing/FragmentParser.cs | 4 +- src/NwcIO/Internal/Parsing/HierarchyParser.cs | 16 ++-- src/NwcIO/Internal/Parsing/LcObjectReader.cs | 26 +++--- tests/NwcIO.Tests/FragmentParserTests.cs | 35 ++++++-- tests/NwcIO.Tests/HierarchyParserTests.cs | 83 +++++++++++++++++-- 7 files changed, 133 insertions(+), 40 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3fdf7bb..7df5588 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,7 @@ All notable changes to the `NwcIO` library, the CLI and the `NwcIO.Scene` adapte - Read line normals, class-76 text properties, short asset lights and additional fragment appearance records. Replace encoded surrogate code units in material names (#291). - Open DWG caches whose implicit ByLayer material has an empty asset slot. +- Read named material selectors and additional fragment appearance trailers. Replace encoded surrogate code units throughout object-graph strings (#291). - Read IFC string properties and class-96 point geometry in Navisworks model files. The scene adapter preserves point geometry (#291). - Read the scene tree of NWD files that store lights or references to earlier lights in the partition trailer. - Open mixed IFC/DWG NWD files with named materials, shared assets, 64-bit properties and CAD text geometry. Preserve CAD annotation text, bounds and placement in the read model. diff --git a/docs/format-notes.md b/docs/format-notes.md index b0ef547..40a314b 100644 --- a/docs/format-notes.md +++ b/docs/format-notes.md @@ -58,7 +58,7 @@ Once inflated, streams serve dedicated roles identified by their signature prefi - **Linked writer cache**: the partition header option `IOExtend.NwcWriter.Scene/1` identifies a writer cache with metre coordinates. A node's tag-52 record with class `IOExtend.NwcWriter.Link`, name `Mesh ID` and a type-2 int32 value links the mesh with that ID from the `NWCI` trailer to the node. Mesh IDs must be unique and each link must name an existing mesh once. Other node properties become tabs grouped by record class. This metadata is for writer caches without a DbCache directory. - **Stream framing**: `[int32 k][k x int32] [int32 100] [int32 n] n x pointer [int32 1]`, zero-padded to a multiple of 8. `k` is the number of `LcOaPartitionProps` root streams; the `k` ints are their root counts (§2.2.1). Id 100 is the implicit root and has no class or body. RVM-derived models with no partition property streams use `k = 0` and can have a class-22 leaf directly under the implicit root. - **Pointer rule**: a pointer is `0` (null), `[1][id]` (back-reference to an object whose body is complete) or `[nextId][classId][body]` (new object). `nextId` starts at 100; an object takes its id before its body is read, so nested new objects take the following ids in depth-first order. Any other first value, an unknown class, or a back-reference to an unfinished object is invalid. Ids are per stream: equal ids in different streams mean nothing. -- **Primitives**: strings are `[int32 len][UTF-8][zero pad to 4]` with `-1` for null; `f64` and `i64` values are aligned to 8 bytes from the stream start, with one zero `int32` of padding when needed. +- **Primitives**: strings are `[int32 len][UTF-8][zero pad to 4]` with `-1` for null. Three-byte encodings of UTF-16 surrogate code units become U+FFFD. The remaining bytes must be valid UTF-8. `f64` and `i64` values are aligned to 8 bytes from the stream start, with one zero `int32` of padding when needed. - **Classes**: - `53` group: `[str name][ptr 52 username][i32 flags][i32 X][i32 Y][Y x attribute ptr][i32 c][c x child ptr]`. Children are class 22 or 53 and are never null. - `22` leaf: the same layout without `c` and children. @@ -67,8 +67,8 @@ Once inflated, streams serve dedicated roles identified by their signature prefi - `27` partition light: `[i32 1][i32 selector (0 or 1), new ptr185 or shared asset index][13 x f64]`. A short asset light has 12 doubles followed by a new class-27 object with a new class-185 asset. The class-185 asset uses the same layout as material JSON. Lights are read and skipped. - `52` display/internal name pair: `[str name][str internal]`. It is the node username, the property tab username and every property key. - **Attributes** (slots may be null): `86` property tab `[str name][ptr 52][i32 flags][i32 n] n x ([ptr 52 key][i32 type][value])` with value by type `0` none, `1,6,7,10,11` `f64`, `5,15` `i64` (Unix seconds and signed integer, respectively), `2,3` `i32`, `4` and `9` string (type 9 was never seen; it is read as a string), `8` class-52 pointer, `12,13` three or two `f64` coordinates; `31` material; `40` translation; `41` translation and quaternion (`x -> R(q)x + t`); `39` 3x3 column-major matrix and translation; `79` hyperlinks; `200` wraps an inline or shared class-185 material asset (§2.4). -- **Class 31 material**: `[str name][15 x f64]`. The DWG variant is `[str name][ptr 52 username][i32 zero][14 x f64]`. Its username can be a new object or a back-reference. Three-byte encodings of UTF-16 surrogate code units in the material name become U+FFFD. -- **Class 200 implicit material**: DWG caches can store `[str "ByLayer"][i32 0][i32 0][null asset pointer]`. +- **Class 31 material**: `[str name][15 x f64]`. The DWG variant is `[str name][ptr 52 username][i32 zero][14 x f64]`. Its username can be a new object or a back-reference. +- **Class 200 material**: `[str name][i32 X][i32 Y]` followed by an inline or shared asset. When X and Y are zero, the asset slot can instead hold a single word 0. The observed selector 1 is followed by a zero belonging to the enclosing object. A class-185 asset back-reference starts with 1 and uses an earlier nonzero id. - **Imported IFC element IDs**: The class-86 tab with internal name `lcatfconsumer_Element_tab` can hold `lcatfconsumer_parameter_GlobalId` and `lcatfconsumer_parameter_IfcGUID`. The reader exposes their valid 22-character IFC ID as `NwcNode.SourceIfcGlobalId` when all valid values agree. The ID belongs to the node carrying the tab. - **Shared subtrees**: a child pointer may back-reference an earlier node, so the hierarchy is a directed acyclic graph. A node reached through several parents appears once per path when the tree is expanded. - **Preorder index (`seq`)**: walk from the implicit root in stored order, counting groups, with a shared subtree walked again at every place it occurs. The root has index 0. Every fragment's `seq` indexes this expanded sequence and lands on a leaf; `seq` never decreases along the fragments stream, and a leaf owns one contiguous run of fragments. @@ -118,7 +118,7 @@ The nesting is therefore independent of the exporter UI language for the marker - `15` pose: `[3 x f64 t][4 x f64 q]`, `q = (x, y, z, w)` a unit quaternion. - `16` pose with scale: class 15 plus `[f64 s]`. The scale is a uniform factor and can be negative. - `17` affine pose: three basis rows `[3 x f32][f32 zero]`, then `[f32 one]` and `[3 x f64 t]` aligned to 8. The rows are the images of the local X, Y and Z axes. DWG block insertions with different scale factors per axis can use this pose. - - `55` appearance: `[i32 flags][ptr 54]`, plus a material-asset slot when `flags & 32`. The slot is null, a class-185 object pointer, or a single shared index (2 or higher) into `LcOpSharedNodes`. The shared stream starts with a count followed by zero-based indexed pointers to class-185 assets or class-102 fonts. A class-102 font stores `[str name][f64][4 x i32]`. A valid new class-185 pointer takes precedence over a shared index with the same lead word. Flag `0x71` has a trailing zero word after the material-asset slot. Flag `0x61` can have the same zero word. A new inline asset can also be followed by a zero word immediately before a new class-93 geometry pointer. + - `55` appearance: `[i32 flags][ptr 54]`, plus a material-asset slot when `flags & 32`. The slot is null, a class-185 object pointer, or a single shared index (2 or higher) into `LcOpSharedNodes`. The shared stream starts with a count followed by zero-based indexed pointers to class-185 assets or class-102 fonts. A class-102 font stores `[str name][f64][4 x i32]`. A valid new class-185 pointer takes precedence over a shared index with the same lead word. Flag `0x71` has a trailing zero word after the material-asset slot. Flag `0x61` can have the same zero word or a 1 immediately before a new class-93 geometry pointer. A new inline asset can also be followed by a zero word immediately before a new class-93 geometry pointer. - `185` material asset: `[str JSON][str metadata][i32 count]`, then `count` items `[str name][i32 embedded][str path]`; an embedded item adds `[str name][i64 length][payload padded to 4]`. For the Generic diffuse image, `userassets` identifies the root key in `materials`. Its enabled `properties.colors.generic_diffuse.connections` identifies the `UnifiedBitmap` entry. `properties.uris.unifiedbitmap_Bitmap.values` supplies the path. The reader looks up that path in the XRef table and prefers the matching record's `RemappedPath` when present. Thumbnail URIs and unrelated bitmap nodes are ignored. - `54` material: 14 `f32`: ambient 0–2, diffuse 3–5, specular 6–8 (always 0), emissive 9–11 (always 0), shininess 12 (Revit Shininess / 128), transparency 13 (Revit Transparency / 100, values below 0.1 stored as 0). Channels are quantised to bytes. `31` (hierarchy) uses `f64` fields and names the material (§2.2). - `93` geometry reference: `[6 x f32 bbox][3 x f64 c][f32][i32 key][i32 rec]`. `rec` is the 1-based index of a geometry record (§2.5). The box equals the bounding box of the record's positions, and `c` is the offset of those positions: for a posed fragment it is the pose translation in the partition's frame, and it places a fragment without a pose. diff --git a/src/NwcIO/Internal/Parsing/FragmentParser.cs b/src/NwcIO/Internal/Parsing/FragmentParser.cs index 8393c88..50e0cf5 100644 --- a/src/NwcIO/Internal/Parsing/FragmentParser.cs +++ b/src/NwcIO/Internal/Parsing/FragmentParser.cs @@ -193,8 +193,8 @@ private FragmentLook ReadAppearance() throw _reader.Fail("appearance flag 0x71 has a nonzero trailing word"); } - // Flag 0x61 can include a trailing zero. An inline asset can have one before a new geometry pointer. - if ((flags == 0x61 && _reader.PeekInt32() == 0) || + // For flag 0x61, a 1 before a new geometry is a trailer. A geometry back-reference uses an earlier id. + if ((flags == 0x61 && (_reader.PeekInt32() == 0 || _reader.NextWordsAre([1, _reader.Next, 93]))) || (newInlineAsset && _reader.NextWordsAre([0, _reader.Next, 93]))) { _reader.ReadInt32(); diff --git a/src/NwcIO/Internal/Parsing/HierarchyParser.cs b/src/NwcIO/Internal/Parsing/HierarchyParser.cs index 6c0793c..d88206e 100644 --- a/src/NwcIO/Internal/Parsing/HierarchyParser.cs +++ b/src/NwcIO/Internal/Parsing/HierarchyParser.cs @@ -647,7 +647,7 @@ private static NwcPropertyTab SingleProperty(Username key, int valueType, string // The DWG form inserts a username and a zero word before its fourteen doubles. private Material ReadMaterial() { - var material = new Material(_reader.ReadString(replaceEncodedSurrogates: true)); + var material = new Material(_reader.ReadString()); if (_reader.NextIsPointer(52)) { ReadUsername(); @@ -838,16 +838,20 @@ private List ReadHyperlinks() return list; } - // Class 200: [str name][i32 X][i32 Y] followed by an inline or shared class-185 asset. + // Class 200: [str name][i32 X][i32 Y] followed by an inline or shared asset, or a selector. private object ReadExtra() { - string? name = _reader.ReadString(); + _reader.ReadString(); int x = _reader.ReadInt32(); int y = _reader.ReadInt32(); - if (_sharedNodes?.TryReadMaterial(_reader, out _) != true) + // The selector 1 is followed by a zero in the observed layout. Asset back-references use a nonzero id. + if (x == 0 && y == 0 && (_reader.PeekInt32() == 0 || _reader.NextWordsAre([1, 0]))) + { + _reader.ReadInt32(); + } + else if (_sharedNodes?.TryReadMaterial(_reader, out _) != true) { - // A DWG cache can leave the implicit ByLayer material's asset empty. - _reader.ReadPointer(ExtraClasses, _readBody, allowNull: name == "ByLayer" && x == 0 && y == 0); + _reader.ReadPointer(ExtraClasses, _readBody, allowNull: false); } return Dropped; diff --git a/src/NwcIO/Internal/Parsing/LcObjectReader.cs b/src/NwcIO/Internal/Parsing/LcObjectReader.cs index a6312bc..186a4a3 100644 --- a/src/NwcIO/Internal/Parsing/LcObjectReader.cs +++ b/src/NwcIO/Internal/Parsing/LcObjectReader.cs @@ -98,7 +98,7 @@ public long ReadInt64() } /// [len][UTF-8 bytes][zero pad to 4]; a length of -1 is null. - public string? ReadString(bool replaceEncodedSurrogates = false) + public string? ReadString() { int length = ReadInt32(); if (length == -1) @@ -114,23 +114,21 @@ public long ReadInt64() return Encoding.UTF8.GetString(bytes); } - if (replaceEncodedSurrogates) + // Some writers store UTF-16 surrogate code units as three-byte sequences in UTF-8 strings. + byte[]? repaired = null; + for (int i = 0; i < bytes.Length - 2; i++) { - // Some material names contain UTF-16 surrogate code units encoded as three bytes. - byte[] repaired = bytes.ToArray(); - for (int i = 0; i < repaired.Length - 2; i++) + if (bytes[i] == 0xED && bytes[i + 1] is >= 0xA0 and <= 0xBF && bytes[i + 2] is >= 0x80 and <= 0xBF) { - if (repaired[i] == 0xED && repaired[i + 1] is >= 0xA0 and <= 0xBF && repaired[i + 2] is >= 0x80 and <= 0xBF) - { - "\uFFFD"u8.CopyTo(repaired.AsSpan(i)); - i += 2; - } + repaired ??= bytes.ToArray(); + "\uFFFD"u8.CopyTo(repaired.AsSpan(i)); + i += 2; } + } - if (Utf8.IsValid(repaired)) - { - return Encoding.UTF8.GetString(repaired); - } + if (repaired is not null && Utf8.IsValid(repaired)) + { + return Encoding.UTF8.GetString(repaired); } throw Fail("string is not valid UTF-8"); diff --git a/tests/NwcIO.Tests/FragmentParserTests.cs b/tests/NwcIO.Tests/FragmentParserTests.cs index c80030f..bc1902f 100644 --- a/tests/NwcIO.Tests/FragmentParserTests.cs +++ b/tests/NwcIO.Tests/FragmentParserTests.cs @@ -122,10 +122,11 @@ public void Read_AppearanceWithExtraSlot_ReadsLikeF1(string variant) => Assert.Equal(FragmentParser.Read(FormatVectors.F1), FragmentParser.Read(BuildF1(variant))); [Theory] - [InlineData(0x61, true)] - [InlineData(0x61, false)] - [InlineData(0x71, true)] - public void Read_AppearanceWithMaterialAsset_ConsumesTrailingWord(int flags, bool useSharedAsset) + [InlineData(0x61, true, 0)] + [InlineData(0x61, false, 0)] + [InlineData(0x61, false, 1)] + [InlineData(0x71, true, 0)] + public void Read_AppearanceWithMaterialAsset_ConsumesTrailingWord(int flags, bool useSharedAsset, int trailer) { var shared = new LcGraphWriter().Int(3).Null().Null(); shared.New(185); @@ -133,7 +134,7 @@ public void Read_AppearanceWithMaterialAsset_ConsumesTrailingWord(int flags, boo var table = new SharedNodeTable(shared.ToArray(), readTextures: false); string variant = useSharedAsset ? "sharedAsset" : "extra185"; - Assert.Equal(FragmentParser.Read(FormatVectors.F1), FragmentParser.Read(BuildF1(variant, flags), table)); + Assert.Equal(FragmentParser.Read(FormatVectors.F1), FragmentParser.Read(BuildF1(variant, flags, trailer), table)); Assert.Throws(() => FragmentParser.Read(BuildF1(variant, flags, appearanceTrailer: 2), table)); } @@ -144,6 +145,13 @@ public void Read_Appearance61WithoutTrailingWord_PreservesFragments() FragmentParser.Read(BuildF1("extra185", appearanceFlags: 0x61, appearanceTrailer: null))); } + [Fact] + public void Read_Appearance61BeforeGeometryBackReference_PreservesFragments() + { + Assert.Equal(FragmentParser.Read(FormatVectors.F1), + FragmentParser.Read(BuildF1("extra185", appearanceFlags: 0x61, appearanceTrailer: null, newSecondAppearance: true))); + } + [Fact] public void Read_InlineAssetWithZeroBeforeNewGeometry_PreservesFragments() { @@ -159,7 +167,8 @@ private static void AssertRule(string rule, byte[] bytes) } // The F1 layout documented in FormatVectors; a variant changes the shared class 55 or fragment 1 as its row says. - private static byte[] BuildF1(string? variant = null, int? appearanceFlags = null, int? appearanceTrailer = 0, bool inlineGeometryMarker = false) + private static byte[] BuildF1(string? variant = null, int? appearanceFlags = null, int? appearanceTrailer = 0, + bool inlineGeometryMarker = false, bool newSecondAppearance = false) { var w = new LcGraphWriter(); w.Int(2); @@ -169,7 +178,14 @@ private static byte[] BuildF1(string? variant = null, int? appearanceFlags = nul w.Double(10).Double(0).Double(0); w.Double(0).Double(0).Double(0).Double(1); int appearance = w.New(55); - Appearance(w, variant, appearanceFlags, appearanceTrailer); + if (newSecondAppearance) + { + Appearance(w, null, null, null); + } + else + { + Appearance(w, variant, appearanceFlags, appearanceTrailer); + } if (inlineGeometryMarker) { w.Int(0); @@ -202,6 +218,11 @@ private static byte[] BuildF1(string? variant = null, int? appearanceFlags = nul { w.Null(); } + else if (newSecondAppearance) + { + w.New(55); + Appearance(w, variant, appearanceFlags, appearanceTrailer); + } else { w.Ref(appearance); diff --git a/tests/NwcIO.Tests/HierarchyParserTests.cs b/tests/NwcIO.Tests/HierarchyParserTests.cs index 31f7a24..e5a597b 100644 --- a/tests/NwcIO.Tests/HierarchyParserTests.cs +++ b/tests/NwcIO.Tests/HierarchyParserTests.cs @@ -199,14 +199,15 @@ public void Read_DwgMaterialUsernameBackReference_ConsumesMarkerAndKeepsNextAttr } [Theory] - [InlineData(0x80, true)] - [InlineData(0x00, false)] - public void Read_MaterialNameWithSurrogate_ReplacesOnlyTheSurrogate(int lastByte, bool validSurrogate) + [InlineData(0x80, 'B', true)] + [InlineData(0x00, 'B', false)] + [InlineData(0x80, '\u00FF', false)] + public void Read_MaterialNameWithSurrogate_ReplacesOnlyTheSurrogate(int lastByte, char suffixByte, bool validSurrogate) { byte[] hierarchy = GroupWithLeaf(2, w => { w.New(31); - w.Int(5).Int(0xB0ED41 | (lastByte << 24)).Int('B'); + w.Int(5).Int(0xB0ED41 | (lastByte << 24)).Int(suffixByte); Doubles(w, 15); PropertyTab(w, 1); }); @@ -256,6 +257,68 @@ public void Read_ByLayerWithoutMaterialAsset_KeepsFollowingProperty() Assert.Single(nodes[2].Properties); } + [Theory] + [InlineData(0)] + [InlineData(1)] + public void Read_Class200Selector_PreservesFollowingPartitionProperty(int selector) + { + var hierarchy = Begin(roots: [1]); + Partition(hierarchy, "P", 1, w => Leaf(w, 3, leaf => + { + leaf.New(200); + leaf.Str("Finish").Int(0).Int(0).Int(selector); + leaf.Null(); + PropertyTab(leaf, 2); + })); + var props = new LcGraphWriter(); + PropertyTab(props, 1); + + var nodes = HierarchyParser.Read(End(hierarchy), "Model", partitionProps: () => [props.ToArray()]); + + Assert.Equal([1, 2], nodes[2].PropertyTabs.Select(tab => tab.Properties.Count)); + } + + [Fact] + public void Read_Class200WithAssetBackReference_PreservesFollowingProperty() + { + byte[] hierarchy = GroupWithLeaf(3, w => + { + w.New(200); + w.Str("Finish").Int(0).Int(0); + int asset = w.New(185); + w.Str("{}").Str(null).Int(0); + w.New(200); + w.Str("Alternate finish").Int(0).Int(0).Ref(asset); + PropertyTab(w, 1); + }); + + Assert.Single(HierarchyParser.Read(hierarchy, "Model")[2].Properties); + } + + [Fact] + public void Read_EncodedSurrogates_InNodeAndPartitionProperty() + { + var hierarchy = Begin(roots: [1]); + Group(hierarchy, 1); + hierarchy.New(22); + hierarchy.Int(5).Int(unchecked((int)0x80B0ED41)).Int('B'); + Username(hierarchy, "Leaf", "LcTestLeaf"); + hierarchy.Int(0).Int(0).Int(1).Null(); + + var props = new LcGraphWriter(); + props.New(86); + props.Str("Details"); + int key = Username(props, "Note", "LcNote"); + props.Int(0).Int(2); + props.Ref(key).Int(4).Int(6).Int(unchecked((int)0x80B0ED41)).Int(0xA9C3); // A, encoded low surrogate, é + props.Ref(key).Int(4).Str("Following value"); + + var leaf = HierarchyParser.Read(End(hierarchy), "Model", partitionProps: () => [props.ToArray()])[2]; + + Assert.Equal("A\uFFFDB", leaf.Name); + Assert.Equal(["A\uFFFDé", "Following value"], leaf.Properties.Select(p => p.Value)); + } + [Fact] public void Read_ValueType5_IsDateTimeFromUnixSeconds() { @@ -327,7 +390,8 @@ public void Read_EveryAttributeClass_ParsesAndKeepsOnlyProperties() [Theory] [InlineData("topLevelLeaf", "class 22, which this slot does not allow")] // root's top-level slot holds a new 22 (observed: 53 or 32 only) - [InlineData("extra200Null", "null pointer in a slot that needs an object")] // class 200 with a null extra + [InlineData("extra200NullWithFlags", "null pointer in a slot that needs an object")] + [InlineData("extra200UnknownAsset", "back-reference to unknown id 999")] public void Read_SlotFamilyDefect_Throws(string defect, string rule) => AssertRule(rule, Defective(defect)); [Fact] @@ -887,10 +951,15 @@ private static void Extra(LcGraphWriter w, int itemFlag = 1, int payload = 0x000 w.Int(99).Int(0); }), "topLevelLeaf" => End(LeafAtTopLevel()), - "extra200Null" => GroupWithLeaf(1, w => + "extra200NullWithFlags" => GroupWithLeaf(1, w => + { + w.New(200); + w.Str("j").Int(1).Int(0).Null(); + }), + "extra200UnknownAsset" => GroupWithLeaf(1, w => { w.New(200); - w.Str("j").Int(0).Int(0).Null(); + w.Str("j").Int(0).Int(0).Ref(999); }), _ => throw new ArgumentOutOfRangeException(nameof(defect)), };