Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
8 changes: 4 additions & 4 deletions docs/format-notes.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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.
Expand Down Expand Up @@ -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.
Expand Down
4 changes: 2 additions & 2 deletions src/NwcIO/Internal/Parsing/FragmentParser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down
16 changes: 10 additions & 6 deletions src/NwcIO/Internal/Parsing/HierarchyParser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down Expand Up @@ -838,16 +838,20 @@ private List<NwcHyperlink> 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;
Expand Down
26 changes: 12 additions & 14 deletions src/NwcIO/Internal/Parsing/LcObjectReader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ public long ReadInt64()
}

/// <summary>[len][UTF-8 bytes][zero pad to 4]; a length of -1 is null.</summary>
public string? ReadString(bool replaceEncodedSurrogates = false)
public string? ReadString()
{
int length = ReadInt32();
if (length == -1)
Expand All @@ -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");
Expand Down
35 changes: 28 additions & 7 deletions tests/NwcIO.Tests/FragmentParserTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -122,18 +122,19 @@ 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);
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.Equal(FragmentParser.Read(FormatVectors.F1), FragmentParser.Read(BuildF1(variant, flags, trailer), table));
Assert.Throws<InvalidDataException>(() => FragmentParser.Read(BuildF1(variant, flags, appearanceTrailer: 2), table));
}

Expand All @@ -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()
{
Expand All @@ -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);
Expand All @@ -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);
Expand Down Expand Up @@ -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);
Expand Down
Loading
Loading