From c4bbae456ba19575ab486865b06d1c7b94676d8e Mon Sep 17 00:00:00 2001
From: sim <79989386+mahach666@users.noreply.github.com>
Date: Sat, 5 Dec 2026 03:07:22 +0300
Subject: [PATCH] Read Navisworks variants from the issue 291 retest
---
CHANGELOG.md | 3 +
docs/format-notes.md | 21 +++---
src/NwcIO/Internal/Parsing/FragmentParser.cs | 61 +++++++++++++++--
.../Internal/Parsing/GeometryRecordParser.cs | 8 ++-
src/NwcIO/Internal/Parsing/HierarchyParser.cs | 49 ++++++++++----
src/NwcIO/Internal/Parsing/LcObjectReader.cs | 48 ++++++++++++--
.../Internal/Parsing/ModelGraphReader.cs | 1 +
src/NwcIO/Model/NwcMesh.cs | 2 +-
src/NwcIO/Model/NwcTransform.cs | 3 +-
.../Fixtures/SyntheticFragments.cs | 14 +++-
tests/NwcIO.Tests/FragmentParserTests.cs | 65 +++++++++++++++++--
.../NwcIO.Tests/GeometryRecordParserTests.cs | 18 ++++-
tests/NwcIO.Tests/HierarchyParserTests.cs | 60 ++++++++++++++++-
tests/NwcIO.Tests/ModelGraphReaderTests.cs | 25 +++++++
tests/NwcIO.Tests/PartitionPropsTests.cs | 21 ++++++
15 files changed, 353 insertions(+), 46 deletions(-)
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 0e515de..3fdf7bb 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,10 +7,13 @@ All notable changes to the `NwcIO` library, the CLI and the `NwcIO.Scene` adapte
### Added
- Read class-104 parametric disks and class-105 cylinder sides as triangle geometry (#291).
+- Read class-17 affine fragment poses, including non-uniform scaling and mirrored placements (#291).
- Expose the original IFC element identifier as `NwcNode.SourceIfcGlobalId` and `sourceIfcGlobalId` in scene-tree JSON (#291).
### Fixed
+- 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 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 e207a33..b0ef547 100644
--- a/docs/format-notes.md
+++ b/docs/format-notes.md
@@ -64,10 +64,11 @@ Once inflated, streams serve dedicated roles identified by their signature prefi
- `22` leaf: the same layout without `c` and children.
- `X` (element index): 0 on every node that is not a Revit element; on an element node, `X - 1` indexes the GUID table (§2.3). The exporter writes some elements (for example grids) as two sibling nodes with the same `X`, not always adjacent; NwcIO makes the first the element and points the second to it. Such a pair takes two equal GUID table entries (`X - 1` and `X`), so the table size is the number of stored nodes with `X > 0` and the next element's index is `X + 2`. The same `X` under different parents, including a node and its descendant, is a linked placement: NwcIO keeps it with `NwcNode.IsLinkPlacement`, points `Element` at the first placement, and `NwcIO.Scene` writes it as its own `SceneModel`.
- `32` (`LcOaPartition`): `[str]` (empty in every file seen), a class-53 body whose name is the partition's source file name, then a trailer. Class 32 nodes are the top-level children of a `.nwd`; class 53 nodes are the top-level children of a `.nwc`. The cache's separate `LcOpNwdPartition` stream starts directly with a class-32 pointer and omits the children's count and slots. Its trailer starts with the light count and light objects, followed by source metadata. Its grammar is `[i32 2][i32 n] n x ptr27 3 x f64 [i32][str loader plugin][i32 format version][i32][i32] 6 x f64 [i32][str][i32][str source path] 3 x f64 4 x f64 [i32][i32]`. A light pointer can define a new class-27 object or refer to a previously read class-27 object. The last four doubles describe a plan box.
- - `27` partition light: `[i32 1][i32 selector (0 or 1), new ptr185 or shared asset index][13 x f64]`. The class-185 asset uses the same layout as material JSON. Lights are read and skipped.
+ - `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.
+- **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]`.
- **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.
@@ -80,13 +81,14 @@ SEGMENT := [int32 0] ZSTREAM{k} ZTOC contiguous zlib streams from off
ZTOC := [int32 k] [k x int32 compressed length of ZSTREAM i] zero pad to 8 (length roundup8(4 + 4k))
HIERARCHY HEADER := [int32 k >= 0] [k x int32 n_i] n_i = number of roots in ZSTREAM i
ZSTREAM i := ROOT{n_i} zero pad to 8 ids from 100 per stream, no implicit root
-ROOT := a new object (never null, never a back-reference) of class 86, 79, 66 or 70; nested objects are class 52
+ROOT := a new object (never null, never a back-reference) of class 86, 79, 66, 70 or 76; nested objects are class 52
66 := [str name = null] [ptr 52 key] [i32 flags] PAD8 [i64 value]
70 := [str value] [ptr 52 key] [i32 flags]
+76 := [str label] [ptr 52 key] [i32 flags] [str value]
LINK := the n-th null attribute slot of a hierarchy node, in byte order, takes the n-th root of ZSTREAM 0 ‖ ZSTREAM 1 ‖ ...
```
-The roots are the tabs a node uses once (element, parameter, type, material and room tabs) and its element id; tabs shared by two or more nodes stay in the hierarchy. A class-66 root becomes a one-property tab named by its key. Revit IDs use flags `0x01000000` or `0x00020000` and values in `1..2^31-1`. DWG handles (`LcOpDwgEntityAttrib`) accept flags `0`, `0x02000000` and `0x03000000` as well and retain their 64-bit value. Handles already accepted under the legacy flags and range keep their existing type-2 representation. The per-node order the exporter writes (`86* 79? 66?`, the 66 last) is not enforced.
+The roots are the tabs a node uses once (element, parameter, type, material and room tabs) and its element id; tabs shared by two or more nodes stay in the hierarchy. A class-66 root becomes a one-property tab named by its key. A class-76 root becomes one text property, using the key's display name when no label is stored. Revit IDs use flags `0x01000000` or `0x00020000` and values in `1..2^31-1`. DWG handles (`LcOpDwgEntityAttrib`) accept flags `0`, `0x02000000` and `0x03000000` as well and retain their 64-bit value. Handles already accepted under the legacy flags and range keep their existing type-2 representation. The per-node order the exporter writes (`86* 79? 66?`, the 66 last) is not enforced.
### 2.2.2 Lenient fallback scene tree
@@ -115,13 +117,14 @@ The nesting is therefore independent of the exporter UI language for the marker
- `14` pose: `[3 x f64 t]`, a translation (identity rotation, scale 1). The Revit NWC exporter writes it for unrotated poses.
- `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.
- - `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. An appearance with flags `0x71` has one trailing zero word in a Navisworks 2027 file saved after editing the diffuse image.
+ - `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.
- `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.
-- **Placement**: the fragment pose is the full world transform of the record's positions: `world = s·R(q)·v + t`, with `s = 1` for classes 14 and 15 and `R(q)` the identity for class 14. `R(q)` is the usual rotation matrix of the normalised quaternion. No unit conversion is applied.
-- **Mirroring**: a pose with `s < 0` mirrors the geometry, so triangle winding must be reversed to keep faces outward in world space. Local vertices and indices are not changed.
-- **Sharing**: several fragments may reference one geometry record, directly or through back-referenced class 93 objects. A pose slot may reference an earlier class-14, class-15 or class-16 pose in the stream.
+- **Placement**: for classes 14–16 the fragment pose places positions as `world = s·R(q)·v + t`, with `s = 1` for classes 14 and 15 and `R(q)` the identity for class 14. `R(q)` is the rotation matrix of the normalised quaternion. For class 17, multiply each basis row by the corresponding local coordinate and add the three results to the translation. No unit conversion is applied.
+- **Mirroring**: a negative uniform scale or a negative determinant of the linear basis reverses triangle winding in world-space output.
+- **Sharing**: several fragments may reference one geometry record, directly or through back-referenced class 93 objects. A pose slot may reference an earlier class-14, class-15, class-16 or class-17 pose in the stream.
#### Spatial hierarchy (`LcOpNwdSpatialHierarchy`)
@@ -153,7 +156,7 @@ UVBODY := [p1][fc][fc x f32] TOKENS(p1, fc/2)? (raw; tokens iff fc/2 != p
```
- **Colour palette**: entries are `[A=0xFF][B][G][R]` (a little-endian `uint32` `0xRRGGBBAA`). Evidence: a level's line colour equals its type's colour parameter (a Revit colour int, red in the low byte) in 218 of 218 level lines that are not black; the 95 whose colour tells the orders apart all match this order. A line record can carry several colours, per vertex.
-- **Class**: `94` triangles, `95` lines, `96` points, `103` text, `104` disks, `105` cylinder sides. Class 94 always has a normal slot; classes 95 and 96 never have a UV or normal slot. The colour slot is optional (`.nwd` files saved by Navisworks 2026 have triangle records with one and line records without one): a triangle record's colours are read for length and dropped, and a line record without colours falls back to its material colour. Object ids run 100, 101, then 102, 103 over the slots present.
+- **Class**: `94` triangles, `95` lines, `96` points, `103` text, `104` disks, `105` cylinder sides. Class 94 requires normals and allows UVs. Class 95 allows normals. Class 96 requires both slots to be null. The colour slot is optional (`.nwd` files saved by Navisworks 2026 have triangle records with one and line records without one): a triangle record's colours are read for length and dropped, and a line record without colours falls back to its material colour. Object ids run 100, 101, then 102, 103 over the slots present.
- **`p1` is the render-vertex count**, not the position count. `p2/3` positions are stored; `VMAP` maps each render vertex to a position and is the identity when absent. Quantised positions (negative `p1`) are not supported.
- **PACKED(count, w)**: bit `j` of the stream is bit `31 - j%32` of little-endian word `j/32`; value `k` occupies bits `k*w` to `k*w+w-1`, most significant first.
- **TOKENS(count, fresh)**: one byte code for every map. State: `out = []`, `next = 0`; read lead bytes until `count` values exist.
diff --git a/src/NwcIO/Internal/Parsing/FragmentParser.cs b/src/NwcIO/Internal/Parsing/FragmentParser.cs
index 4069efe..8393c88 100644
--- a/src/NwcIO/Internal/Parsing/FragmentParser.cs
+++ b/src/NwcIO/Internal/Parsing/FragmentParser.cs
@@ -6,7 +6,7 @@ namespace NwcIO.Internal.Parsing;
///
/// One class-13 fragment (docs/format-notes.md §2.4): is its leaf's expanded preorder index,
/// the 1-based geometry record (class-93 rec), the fragment int a,
-/// the colour of its appearance, and the pose places the record's positions as Scale * R(Rotation) * v + Translation.
+/// the colour of its appearance. The pose uses when present, otherwise Scale * R(Rotation) * v + Translation.
///
internal readonly record struct Fragment(
int Seq,
@@ -16,7 +16,8 @@ internal readonly record struct Fragment(
Quaterniond Rotation,
double Scale,
BoundingBox3d Bounds,
- FragmentLook Look);
+ FragmentLook Look,
+ double[]? Matrix = null);
/// The class-54 diffuse colour (floats 3, 4, 5) and transparency (float 13) of a fragment's appearance (docs/format-notes.md §2.4).
internal readonly record struct FragmentLook(float R, float G, float B, float Transparency, string? DiffuseTexturePath = null);
@@ -29,7 +30,7 @@ internal static class FragmentParser
// Slot families as observed (docs/format-notes.md §2.4).
private static ReadOnlySpan FragmentClasses => [13];
- private static ReadOnlySpan PoseClasses => [14, 15, 16];
+ private static ReadOnlySpan PoseClasses => [14, 15, 16, 17];
private static ReadOnlySpan AppearanceClasses => [55];
@@ -46,7 +47,7 @@ public static Fragment[] Read(byte[] data, SharedNodeTable? sharedNodes = null,
return new Parser(new LcObjectReader(data, Segment), sharedNodes, readTextures).ReadStream(paddedCount);
}
- private sealed record Pose(Vector3d Translation, Quaterniond Rotation, double Scale);
+ private sealed record Pose(Vector3d Translation, Quaterniond Rotation, double Scale, double[]? Matrix = null);
private sealed record GeometryReference(BoundingBox3d Bounds, int Record, Vector3d Centre);
@@ -88,6 +89,7 @@ public Fragment[] ReadStream(bool paddedCount)
14 => new Pose(ReadTranslation(), Quaterniond.Identity, 1.0),
15 => ReadPose(scaled: false),
16 => ReadPose(scaled: true),
+ 17 => ReadMatrixPose(),
55 => ReadAppearance(),
54 => ReadMaterial(),
93 => ReadGeometry(),
@@ -108,7 +110,7 @@ private Fragment ReadFragment()
var look = (FragmentLook)_reader.ReadPointer(AppearanceClasses, _readBody, allowNull: false)!;
var geometry = (GeometryReference)_reader.ReadPointer(GeometryClasses, _readBody, allowNull: false)!;
pose ??= new Pose(geometry.Centre, Quaterniond.Identity, 1.0);
- return new Fragment(seq, geometry.Record, primitiveCount, pose.Translation, pose.Rotation, pose.Scale, geometry.Bounds, look);
+ return new Fragment(seq, geometry.Record, primitiveCount, pose.Translation, pose.Rotation, pose.Scale, geometry.Bounds, look, pose.Matrix);
}
// Class 14: [3 f64 t], a translation.
@@ -128,6 +130,44 @@ private Pose ReadPose(bool scaled)
return new Pose(translation, rotation, scale);
}
+ // Class 17: three padded f32 basis rows, f32 homogeneous coordinate, aligned f64 translation.
+ private Pose ReadMatrixPose()
+ {
+ var x = ReadMatrixRow();
+ var y = ReadMatrixRow();
+ var z = ReadMatrixRow();
+ if (_reader.ReadSingle() != 1)
+ {
+ throw _reader.Fail("class-17 homogeneous coordinate is not 1");
+ }
+
+ var translation = ReadTranslation();
+ double orientation = Vector3d.Dot(x, Vector3d.Cross(y, z)) < 0 ? -1.0 : 1.0;
+ return new Pose(translation, Quaterniond.Identity, orientation,
+ [
+ x.X, x.Y, x.Z, 0.0,
+ y.X, y.Y, y.Z, 0.0,
+ z.X, z.Y, z.Z, 0.0,
+ translation.X, translation.Y, translation.Z, 1.0,
+ ]);
+ }
+
+ private Vector3d ReadMatrixRow()
+ {
+ var row = new Vector3d(_reader.ReadSingle(), _reader.ReadSingle(), _reader.ReadSingle());
+ if (!double.IsFinite(row.X) || !double.IsFinite(row.Y) || !double.IsFinite(row.Z))
+ {
+ throw _reader.Fail("pose value is not finite");
+ }
+
+ if (_reader.ReadSingle() != 0)
+ {
+ throw _reader.Fail("class-17 matrix row padding is not zero");
+ }
+
+ return row;
+ }
+
private double ReadFinite()
{
double value = _reader.ReadDouble();
@@ -141,16 +181,25 @@ private FragmentLook ReadAppearance()
var look = (FragmentLook)_reader.ReadPointer(MaterialClasses, _readBody, allowNull: false)!;
if ((flags & 32) == 0) return look;
+ bool newInlineAsset = false;
if (_sharedNodes?.TryReadMaterial(_reader, out string? texturePath) != true)
{
+ newInlineAsset = _reader.PeekInt32() == _reader.Next;
texturePath = _reader.ReadPointer(ExtraClasses, _readBody) as string;
}
- // Navisworks 2027 writes one more zero word for an appearance whose image was assigned in the material editor.
if (flags == 0x71 && _reader.ReadInt32() != 0)
{
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) ||
+ (newInlineAsset && _reader.NextWordsAre([0, _reader.Next, 93])))
+ {
+ _reader.ReadInt32();
+ }
+
return look with { DiffuseTexturePath = texturePath };
}
diff --git a/src/NwcIO/Internal/Parsing/GeometryRecordParser.cs b/src/NwcIO/Internal/Parsing/GeometryRecordParser.cs
index da6d2a4..e837489 100644
--- a/src/NwcIO/Internal/Parsing/GeometryRecordParser.cs
+++ b/src/NwcIO/Internal/Parsing/GeometryRecordParser.cs
@@ -264,7 +264,13 @@ public static GeometryRecord Parse(ReadOnlySpan record, int normalBits)
: Array.ConvertAll(Tokens(record, ref pos, p1, cpal, false), k => palette[k]);
}
- if (cls == 94 ? normals is null : hasUv || normals is not null)
+ bool invalidSlots = cls switch
+ {
+ 94 => normals is null,
+ 95 => hasUv,
+ _ => hasUv || normals is not null,
+ };
+ if (invalidSlots)
{
throw Fail("slot set does not match the class", pos);
}
diff --git a/src/NwcIO/Internal/Parsing/HierarchyParser.cs b/src/NwcIO/Internal/Parsing/HierarchyParser.cs
index 0335f0e..6c0793c 100644
--- a/src/NwcIO/Internal/Parsing/HierarchyParser.cs
+++ b/src/NwcIO/Internal/Parsing/HierarchyParser.cs
@@ -36,7 +36,7 @@ internal static class HierarchyParser
private static ReadOnlySpan ExtraClasses => [185];
private static ReadOnlySpan PartitionLightClasses => [27];
- private static ReadOnlySpan PartitionRootClasses => [86, 79, 66, 70];
+ private static ReadOnlySpan PartitionRootClasses => [86, 79, 66, 70, 76];
private static ReadOnlySpan KnownClasses => [53, 22, 32, 52, 86, 31, 40, 41, 39, 79, 200, 185];
@@ -334,7 +334,6 @@ public Parser(LcObjectReader reader, int guidCount, Func?>
52 => ReadUsernameBody(),
86 => ReadPropertyTab(),
31 => ReadMaterial(),
- 27 => ReadPartitionLight(),
40 => ReadTransform(doubles: 3),
41 => ReadTransform(doubles: 7),
39 => ReadMatrix(),
@@ -343,6 +342,7 @@ public Parser(LcObjectReader reader, int guidCount, Func?>
185 => ReadMaterialJson(_reader),
66 => ReadElementId(),
70 => ReadStringProperty(),
+ 76 => ReadTextProperty(),
_ => throw new InvalidOperationException($"class {classId} has no body reader"),
};
@@ -430,9 +430,12 @@ private void ReadPartitionTrailer()
// A shared light takes only the two words of its back-reference.
int lightCount = _reader.ReadCount(8);
- for (int i = 0; i < lightCount; i++)
+ int light = 0;
+ object ReadLight(int _) => ReadPartitionLight(hasFollowingLight: light + 1 < lightCount);
+ Func readLight = ReadLight;
+ for (; light < lightCount; light++)
{
- _reader.ReadPointer(PartitionLightClasses, _readBody, allowNull: false);
+ _reader.ReadPointer(PartitionLightClasses, readLight, allowNull: false);
}
SkipDoubles(3);
@@ -451,7 +454,7 @@ private void ReadPartitionTrailer()
_reader.ReadInt32();
}
- private object ReadPartitionLight()
+ private object ReadPartitionLight(bool hasFollowingLight)
{
if (_reader.ReadInt32() != 1)
{
@@ -459,7 +462,8 @@ private object ReadPartitionLight()
}
// A built-in light has a selector. A light with an asset has a class-185 object in its place.
- if (_reader.PeekInt32() is 0 or 1)
+ bool hasAsset = _reader.PeekInt32() is not (0 or 1);
+ if (!hasAsset)
{
_reader.ReadInt32();
}
@@ -468,7 +472,14 @@ private object ReadPartitionLight()
_reader.ReadPointer(ExtraClasses, _readBody, allowNull: false, allowBackReference: false);
}
- SkipDoubles(13);
+ SkipDoubles(12);
+ // The short form is identified by the next new light's header and its new asset pointer.
+ int next = _reader.Next;
+ if (!hasAsset || !hasFollowingLight || !_reader.NextWordsAre([next, 27, 1, next + 1, 185]))
+ {
+ _reader.ReadDouble();
+ }
+
return Dropped;
}
@@ -606,9 +617,18 @@ private NwcPropertyTab ReadStringProperty()
return SingleProperty(key, 4, value);
}
- private static NwcPropertyTab SingleProperty(Username key, int valueType, string? value, long? intValue = null)
+ // Class 76 keeps its optional label and its text value in separate strings.
+ private NwcPropertyTab ReadTextProperty()
+ {
+ string? label = _reader.ReadString();
+ var key = ReadUsername();
+ _reader.ReadInt32();
+ return SingleProperty(key, 4, _reader.ReadString(), label: label);
+ }
+
+ private static NwcPropertyTab SingleProperty(Username key, int valueType, string? value, long? intValue = null, string? label = null)
{
- string name = key.Display ?? "";
+ string name = label ?? key.Display ?? "";
var record = new NwcPropertyRecord
{
FirstInt = key.Id,
@@ -627,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());
+ var material = new Material(_reader.ReadString(replaceEncodedSurrogates: true));
if (_reader.NextIsPointer(52))
{
ReadUsername();
@@ -821,12 +841,13 @@ private List ReadHyperlinks()
// Class 200: [str name][i32 X][i32 Y] followed by an inline or shared class-185 asset.
private object ReadExtra()
{
- _reader.ReadString();
- _reader.ReadInt32();
- _reader.ReadInt32();
+ string? name = _reader.ReadString();
+ int x = _reader.ReadInt32();
+ int y = _reader.ReadInt32();
if (_sharedNodes?.TryReadMaterial(_reader, out _) != true)
{
- _reader.ReadPointer(ExtraClasses, _readBody, allowNull: false);
+ // A DWG cache can leave the implicit ByLayer material's asset empty.
+ _reader.ReadPointer(ExtraClasses, _readBody, allowNull: name == "ByLayer" && x == 0 && y == 0);
}
return Dropped;
diff --git a/src/NwcIO/Internal/Parsing/LcObjectReader.cs b/src/NwcIO/Internal/Parsing/LcObjectReader.cs
index 4c679f5..a6312bc 100644
--- a/src/NwcIO/Internal/Parsing/LcObjectReader.cs
+++ b/src/NwcIO/Internal/Parsing/LcObjectReader.cs
@@ -60,6 +60,27 @@ public bool NextIsPointer(int classId)
return reference.Body is not null && reference.ClassId == classId;
}
+ public bool NextWordsAre(ReadOnlySpan words)
+ {
+ var remaining = _data.AsSpan(Position);
+ if (words.Length > remaining.Length / sizeof(int))
+ {
+ return false;
+ }
+
+ foreach (int word in words)
+ {
+ if (BinaryPrimitives.ReadInt32LittleEndian(remaining) != word)
+ {
+ return false;
+ }
+
+ remaining = remaining[sizeof(int)..];
+ }
+
+ return true;
+ }
+
public int ReadInt32() => BinaryPrimitives.ReadInt32LittleEndian(Take(4, "i32"));
public float ReadSingle() => BinaryPrimitives.ReadSingleLittleEndian(Take(4, "f32"));
@@ -77,7 +98,7 @@ public long ReadInt64()
}
/// [len][UTF-8 bytes][zero pad to 4]; a length of -1 is null.
- public string? ReadString()
+ public string? ReadString(bool replaceEncodedSurrogates = false)
{
int length = ReadInt32();
if (length == -1)
@@ -88,12 +109,31 @@ public long ReadInt64()
int start = Position;
SkipPadded(length);
var bytes = _data.AsSpan(start, length);
- if (!Utf8.IsValid(bytes))
+ if (Utf8.IsValid(bytes))
+ {
+ return Encoding.UTF8.GetString(bytes);
+ }
+
+ if (replaceEncodedSurrogates)
{
- throw Fail("string is not valid UTF-8");
+ // 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 (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;
+ }
+ }
+
+ if (Utf8.IsValid(repaired))
+ {
+ return Encoding.UTF8.GetString(repaired);
+ }
}
- return Encoding.UTF8.GetString(bytes);
+ throw Fail("string is not valid UTF-8");
}
/// Skips bytes and the zero pad after them to a multiple of 4.
diff --git a/src/NwcIO/Internal/Parsing/ModelGraphReader.cs b/src/NwcIO/Internal/Parsing/ModelGraphReader.cs
index 02c2d54..d6453a8 100644
--- a/src/NwcIO/Internal/Parsing/ModelGraphReader.cs
+++ b/src/NwcIO/Internal/Parsing/ModelGraphReader.cs
@@ -174,6 +174,7 @@ public static async ValueTask ReadAsync(ModelSegments segments, NwcR
Translation = fragment.Translation,
Rotation = fragment.Rotation,
Scale = fragment.Scale,
+ Matrix = fragment.Matrix,
BoundingBox = fragment.Bounds,
};
transforms.Add(transform);
diff --git a/src/NwcIO/Model/NwcMesh.cs b/src/NwcIO/Model/NwcMesh.cs
index e48c88f..0502e9a 100644
--- a/src/NwcIO/Model/NwcMesh.cs
+++ b/src/NwcIO/Model/NwcMesh.cs
@@ -22,7 +22,7 @@ public sealed class NwcMesh
///
/// Unit normal per entry of , local space; null when none stored;
- /// = no normal; world normal = normalize(sign(Scale)·R·n).
+ /// = no normal. For an invertible world transform, transform normals by the inverse transpose of its linear part and renormalize.
///
public IReadOnlyList? Normals { get; init; }
diff --git a/src/NwcIO/Model/NwcTransform.cs b/src/NwcIO/Model/NwcTransform.cs
index 0c0d51f..79ef0f3 100644
--- a/src/NwcIO/Model/NwcTransform.cs
+++ b/src/NwcIO/Model/NwcTransform.cs
@@ -20,7 +20,8 @@ public sealed class NwcTransform
///
/// Uniform scale applied before the rotation: world = Scale·R(Rotation)·v + Translation.
/// A negative value mirrors; world-space consumers must reverse triangle winding.
- /// For non-uniform or general transforms, see and .
+ /// For a parsed general affine transform, this value carries the orientation sign. Use
+ /// or for the full transform.
///
public double Scale { get; init; } = 1.0;
diff --git a/tests/NwcIO.Tests/Fixtures/SyntheticFragments.cs b/tests/NwcIO.Tests/Fixtures/SyntheticFragments.cs
index 702e3a7..82d5df4 100644
--- a/tests/NwcIO.Tests/Fixtures/SyntheticFragments.cs
+++ b/tests/NwcIO.Tests/Fixtures/SyntheticFragments.cs
@@ -6,12 +6,12 @@ namespace NwcIO.Tests;
internal sealed record Look(float R, float G, float B, float Shininess, float Transparency,
string? MaterialJson = null, int? SharedMaterial = null, bool EditedMaterial = false);
-/// One fragment: TranslationOnly writes a class-14 pose (T only, S ignored), else S 1 a class-15 pose, else class 16; a new class 93 with bbox (0,0,0)-(MaxX,MaxY,MaxZ), or a back-reference
+/// One fragment: LinearPose writes the nine linear coefficients of a class-17 pose; TranslationOnly writes class 14, else S 1 writes class 15, else class 16. A new class 93 with bbox (0,0,0)-(MaxX,MaxY,MaxZ), or a back-reference
/// to fragment SharesGeometryOf's. SharesPoseOf back-references an earlier pose. Look writes a new appearance;
/// null back-references fragment SharesLookOf's (fragment 0 writes Look(0,0,0,0,0)).
internal sealed record Frag(int Seq, Vector3d T, double S, int A, int B, int Rec = 0, float MaxZ = 0, int SharesGeometryOf = -1,
float MaxX = 1, float MaxY = 1, Look? Look = null, int SharesLookOf = 0, bool TranslationOnly = false,
- int SharesPoseOf = -1);
+ int SharesPoseOf = -1, float[]? LinearPose = null);
/// Writes LcOpNwdFragments streams in the F1 layout (docs/format-notes.md §2.4).
internal static class SyntheticFragments
@@ -33,6 +33,16 @@ public static byte[] Build(params Frag[] fragments)
poses[k] = poses[f.SharesPoseOf];
w.Ref(poses[k]);
}
+ else if (f.LinearPose is { } linear)
+ {
+ poses[k] = w.New(17);
+ for (int i = 0; i < linear.Length; i += 3)
+ {
+ w.Float(linear[i]).Float(linear[i + 1]).Float(linear[i + 2]).Float(0);
+ }
+
+ w.Float(1).Double(f.T.X).Double(f.T.Y).Double(f.T.Z);
+ }
else
{
poses[k] = w.New(f.TranslationOnly ? 14 : f.S == 1 ? 15 : 16);
diff --git a/tests/NwcIO.Tests/FragmentParserTests.cs b/tests/NwcIO.Tests/FragmentParserTests.cs
index 8ebd5f2..c80030f 100644
--- a/tests/NwcIO.Tests/FragmentParserTests.cs
+++ b/tests/NwcIO.Tests/FragmentParserTests.cs
@@ -46,6 +46,17 @@ public void Read_InvalidPoseValue_Throws(int offset, double value, string rule)
public void Read_NonFiniteTranslationOnlyPose_Throws(double x, double y, double z)
=> AssertRule("pose value is not finite", SyntheticFragments.Build(new Frag(2, new(x, y, z), 1, 2, 4, Rec: 1, TranslationOnly: true)));
+ [Theory]
+ [InlineData(48, float.NaN, "pose value is not finite")]
+ [InlineData(60, 1, "class-17 matrix row padding is not zero")]
+ [InlineData(96, 0, "class-17 homogeneous coordinate is not 1")]
+ [InlineData(100, 1, "f64 alignment pad is not zero")]
+ public void Read_InvalidMatrixPose_Throws(int offset, float value, string rule)
+ {
+ var bytes = SyntheticFragments.Build(new Frag(2, Vector3d.Zero, 1, 2, 4, Rec: 1, LinearPose: [2, 0, 0, 0, 3, 0, 0, 0, 4]));
+ AssertRule(rule, FormatVectors.Patched(bytes, offset, BitConverter.GetBytes(value)));
+ }
+
// Fragment 0 ends at byte 220 and fragment 1 (with its f64 pad) at 304; each later one is 80 bytes: [id][13], D, four ints,
// a new class-14 pose and two back-references. 150 fragments leave 12,140 bytes after the count: enough for 150 x 80, not 150 x 81.
[Fact]
@@ -110,6 +121,36 @@ public void Read_NullPose_PlacesTheRecordAtItsCentre()
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)
+ {
+ var shared = new LcGraphWriter().Int(3).Null().Null();
+ shared.New(185);
+ shared.Str(null).Str(null).Int(0);
+ 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.Throws(() => FragmentParser.Read(BuildF1(variant, flags, appearanceTrailer: 2), table));
+ }
+
+ [Fact]
+ public void Read_Appearance61WithoutTrailingWord_PreservesFragments()
+ {
+ Assert.Equal(FragmentParser.Read(FormatVectors.F1),
+ FragmentParser.Read(BuildF1("extra185", appearanceFlags: 0x61, appearanceTrailer: null)));
+ }
+
+ [Fact]
+ public void Read_InlineAssetWithZeroBeforeNewGeometry_PreservesFragments()
+ {
+ Assert.Equal(FragmentParser.Read(FormatVectors.F1),
+ FragmentParser.Read(BuildF1("extra185", appearanceFlags: 0x21, inlineGeometryMarker: true)));
+ }
+
private static void AssertRule(string rule, byte[] bytes)
{
var ex = Assert.Throws(() => FragmentParser.Read(bytes));
@@ -118,7 +159,7 @@ 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)
+ private static byte[] BuildF1(string? variant = null, int? appearanceFlags = null, int? appearanceTrailer = 0, bool inlineGeometryMarker = false)
{
var w = new LcGraphWriter();
w.Int(2);
@@ -128,7 +169,12 @@ private static byte[] BuildF1(string? variant = null)
w.Double(10).Double(0).Double(0);
w.Double(0).Double(0).Double(0).Double(1);
int appearance = w.New(55);
- Appearance(w, variant);
+ Appearance(w, variant, appearanceFlags, appearanceTrailer);
+ if (inlineGeometryMarker)
+ {
+ w.Int(0);
+ }
+
int geometry = w.New(93);
w.Float(0).Float(0).Float(0).Float(1).Float(1).Float(0);
w.Double(0.5).Double(0.5).Double(0);
@@ -166,9 +212,9 @@ private static byte[] BuildF1(string? variant = null)
}
// Class-55 body: [flags][ptr 54], then [ptr 185 or null] when flags & 32.
- private static void Appearance(LcGraphWriter w, string? variant)
+ private static void Appearance(LcGraphWriter w, string? variant, int? appearanceFlags, int? appearanceTrailer)
{
- w.Int(variant is "extra185" or "extraNull" ? 33 : 1);
+ w.Int(appearanceFlags ?? (variant is "extra185" or "extraNull" ? 33 : 1));
if (variant == "materialNull")
{
w.Null();
@@ -181,7 +227,11 @@ private static void Appearance(LcGraphWriter w, string? variant)
w.Int(0);
}
- if (variant == "extra185")
+ if (variant == "sharedAsset")
+ {
+ w.Int(2);
+ }
+ else if (variant == "extra185")
{
w.New(185);
w.Str("j").Str("i").Int(0);
@@ -190,5 +240,10 @@ private static void Appearance(LcGraphWriter w, string? variant)
{
w.Null();
}
+
+ if (appearanceFlags is 0x61 or 0x71 && appearanceTrailer is int trailer)
+ {
+ w.Int(trailer);
+ }
}
}
diff --git a/tests/NwcIO.Tests/GeometryRecordParserTests.cs b/tests/NwcIO.Tests/GeometryRecordParserTests.cs
index acbde6c..4a514bd 100644
--- a/tests/NwcIO.Tests/GeometryRecordParserTests.cs
+++ b/tests/NwcIO.Tests/GeometryRecordParserTests.cs
@@ -289,7 +289,7 @@ public void Parse_Mutation_Throws(string vector, int offset, string bytes, strin
[InlineData("R1", 108, "02000000", "second primitive count differs")] // second P count differs
[InlineData("R1", 104, "00000000", "primitive length width is not in 1..31")] // P bits = 0
[InlineData("R1", 116, "FFFFFFFF", "corner count is negative")] // S < 0
- [InlineData("R1", 4, "5F000000", "slot set does not match the class")] // class 95 with an N slot: slot set
+ [InlineData("R1", 4, "60000000", "slot set does not match the class")] // class 96 with an N slot: slot set
[InlineData("R4", 80, "05000000", "UV count is neither p1 nor -p1")] // UV count neither p1 nor -p1
[InlineData("R3", 92, "00000000", "colour palette size is not positive")] // colour palette size 0
public void Parse_GrammarViolation_Throws(string vector, int offset, string bytes, string rule)
@@ -319,6 +319,22 @@ public void Parse_LinesWithoutColour_DecodesAsR3WithoutColours()
Assert.Null(g.LineColors);
}
+ [Fact]
+ public void Parse_LinesWithNormals_PreservesNormalsAndSegments()
+ {
+ byte[] r3 = FormatVectors.R3;
+ // Six normals share the eight-bit (0, 0, 127) palette entry. Tokens select it for all six vertices.
+ byte[] record = [.. r3[..72], .. Words([102, 100, unchecked((uint)-6), 1, 0x00007F00, 0x00008400, 0]), .. r3[104..], 0, 0, 0, 0];
+
+ var geometry = GeometryRecordParser.Parse(record, 8);
+
+ Assert.True(geometry.IsLines);
+ Assert.Equal(GeometryRecordParser.Parse(r3, 16).LineIndices, geometry.LineIndices);
+ Assert.Equal(Enumerable.Repeat(new Vector3d(0, 0, 1), 6), geometry.Normals);
+ Assert.Null(geometry.TexCoords);
+ Assert.Null(geometry.LineColors);
+ }
+
[Fact]
public void Parse_IdentityNormalPalette_DecodesAsR1() => AssertR1(GeometryRecordParser.Parse(BuildR1IdentityNormals(), 16));
diff --git a/tests/NwcIO.Tests/HierarchyParserTests.cs b/tests/NwcIO.Tests/HierarchyParserTests.cs
index b55c8f8..31f7a24 100644
--- a/tests/NwcIO.Tests/HierarchyParserTests.cs
+++ b/tests/NwcIO.Tests/HierarchyParserTests.cs
@@ -198,6 +198,30 @@ public void Read_DwgMaterialUsernameBackReference_ConsumesMarkerAndKeepsNextAttr
Assert.Single(nodes[3].Properties);
}
+ [Theory]
+ [InlineData(0x80, true)]
+ [InlineData(0x00, false)]
+ public void Read_MaterialNameWithSurrogate_ReplacesOnlyTheSurrogate(int lastByte, bool validSurrogate)
+ {
+ byte[] hierarchy = GroupWithLeaf(2, w =>
+ {
+ w.New(31);
+ w.Int(5).Int(0xB0ED41 | (lastByte << 24)).Int('B');
+ Doubles(w, 15);
+ PropertyTab(w, 1);
+ });
+
+ if (!validSurrogate)
+ {
+ AssertRule("string is not valid UTF-8", hierarchy);
+ return;
+ }
+
+ var leaf = HierarchyParser.Read(hierarchy, "Model")[2];
+ Assert.Equal("A\uFFFDB", leaf.MaterialName);
+ Assert.Single(leaf.Properties);
+ }
+
[Fact]
public void Read_ExtraWithSharedMaterial_KeepsFollowingProperty()
{
@@ -217,6 +241,21 @@ public void Read_ExtraWithSharedMaterial_KeepsFollowingProperty()
Assert.Single(nodes[2].Properties);
}
+ [Fact]
+ public void Read_ByLayerWithoutMaterialAsset_KeepsFollowingProperty()
+ {
+ byte[] hierarchy = GroupWithLeaf(2, w =>
+ {
+ w.New(200);
+ w.Str("ByLayer").Int(0).Int(0).Null();
+ PropertyTab(w, 1);
+ });
+
+ var nodes = HierarchyParser.Read(hierarchy, "Model");
+
+ Assert.Single(nodes[2].Properties);
+ }
+
[Fact]
public void Read_ValueType5_IsDateTimeFromUnixSeconds()
{
@@ -444,6 +483,23 @@ public void Read_PartitionLights_PreserveTheFollowingPartition()
Assert.Equal(["Model", "A", "L", "B"], nodes.Select(node => node.Name));
}
+ [Fact]
+ public void Read_ShortAssetLightFollowedByNewLight_PreservesPartitionBoundaries()
+ {
+ var w = Begin(n: 2);
+ Partition(w, "A", 0, _ => { }, lights:
+ [
+ p => PartitionLight(p, assetClass: 185, tailDoubles: 12),
+ p => PartitionLight(p, assetClass: 185),
+ ]);
+ Partition(w, "B", 1, p => Leaf(p, 0, _ => { }));
+
+ var nodes = HierarchyParser.Read(End(w), "Model");
+
+ Assert.Equal(["A", "B"], nodes[0].Children.Select(n => n.Name));
+ Assert.Single(nodes[2].Children);
+ }
+
[Theory]
[InlineData(1)]
[InlineData(8)]
@@ -674,7 +730,7 @@ internal static LcGraphWriter Partition(LcGraphWriter w, string name, int childC
return w.Int(1).Int(0);
}
- private static void PartitionLight(LcGraphWriter w, int marker = 1, int selector = 0, int? assetClass = null)
+ private static void PartitionLight(LcGraphWriter w, int marker = 1, int selector = 0, int? assetClass = null, int tailDoubles = 13)
{
w.New(27);
w.Int(marker);
@@ -688,7 +744,7 @@ private static void PartitionLight(LcGraphWriter w, int marker = 1, int selector
w.Int(selector);
}
- Doubles(w, 13);
+ Doubles(w, tailDoubles);
}
// A group whose one leaf holds a three-item class-86 tab.
diff --git a/tests/NwcIO.Tests/ModelGraphReaderTests.cs b/tests/NwcIO.Tests/ModelGraphReaderTests.cs
index 802af75..0c88130 100644
--- a/tests/NwcIO.Tests/ModelGraphReaderTests.cs
+++ b/tests/NwcIO.Tests/ModelGraphReaderTests.cs
@@ -33,6 +33,31 @@ public void Open_F1File_LinksFragmentsToLeavesAndPoses()
Assert.Equal(3, doc.DbCache!.Entries.Count);
}
+ [Theory]
+ [InlineData(true)]
+ [InlineData(false)]
+ public void Open_Class17Pose_PreservesAffineWorldPlacementAndWinding(bool tree)
+ {
+ var translation = new Vector3d(10, 20, 30);
+ byte[] fragments = SyntheticFragments.Build(
+ new Frag(2, translation, 1, 2, 4, Rec: 1, LinearPose: [0, -2, 0, -3, 0, 1, 0, 0, 4]),
+ new Frag(7, Vector3d.Zero, 1, 2, 4, Rec: 1, SharesGeometryOf: 0, SharesPoseOf: 0));
+ using var stream = new MemoryStream(SyntheticNwcFile.Build(FormatVectors.H1, fragments, [FormatVectors.R1], [120]));
+
+ var document = NwcDocument.Open(stream, new NwcReaderOptions { BuildSceneTree = tree });
+
+ Assert.Equal(2, document.Meshes.Count);
+ Assert.Equal(document.Transforms[0].Matrix, document.Transforms[1].Matrix);
+ Assert.All(document.Meshes, mesh =>
+ {
+ Assert.Equal(tree, mesh.Node is not null);
+ Assert.False(mesh.Transform!.IsUniform);
+ Assert.Equal(translation, mesh.Transform.Translation);
+ Assert.Equal([translation, new(10, 18, 30), new(7, 20, 31), new(7, 18, 31)], mesh.GetWorldVertices());
+ Assert.Equal([0, 2, 1, 2, 3, 1], mesh.GetWorldIndices());
+ });
+ }
+
[Theory]
[InlineData(true, 0)]
[InlineData(false, 0)]
diff --git a/tests/NwcIO.Tests/PartitionPropsTests.cs b/tests/NwcIO.Tests/PartitionPropsTests.cs
index cba7012..c2d9f49 100644
--- a/tests/NwcIO.Tests/PartitionPropsTests.cs
+++ b/tests/NwcIO.Tests/PartitionPropsTests.cs
@@ -69,6 +69,27 @@ public void Read_Class79Root_IsDropped()
Assert.Equal("1002", Assert.Single(nodes[3].PropertyTabs).Properties[0].Value);
}
+ [Theory]
+ [InlineData(null, 0)]
+ [InlineData("Custom label", 0x00020000)]
+ public void Read_Class76Root_PreservesTextAndFollowingProperty(string? label, int flags)
+ {
+ var hierarchy = HierarchyParserTests.Begin(roots: [2]);
+ HierarchyParserTests.Partition(hierarchy, "P", 1, w => HierarchyParserTests.Leaf(w, 2, leaf => leaf.Null().Null()));
+ var props = new LcGraphWriter();
+ props.New(76);
+ props.Str(label);
+ HierarchyParserTests.Username(props, "Description", "LcText");
+ props.Int(flags).Str("Some text");
+ HierarchyParserTests.PropertyTab(props, 1);
+
+ var leaf = Read(HierarchyParserTests.End(hierarchy), [props.ToArray()])[2];
+ Assert.Equal(2, leaf.PropertyTabs.Count);
+ var text = Assert.Single(leaf.PropertyTabs[0].Properties);
+ Assert.Equal((label ?? "Description", "LcText", 4, "Some text"), (text.Name, text.InternalName, text.ValueType, text.Value));
+ Assert.Single(leaf.PropertyTabs[1].Properties);
+ }
+
[Fact]
public void Read_SharedStoredNode_TakesItsRootsOnce()
{