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 @@ -6,6 +6,7 @@ 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).
- Expose the original IFC element identifier as `NwcNode.SourceIfcGlobalId` and `sourceIfcGlobalId` in scene-tree JSON (#291).

### Fixed
Expand Down
8 changes: 5 additions & 3 deletions docs/format-notes.md
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ Once inflated, streams serve dedicated roles identified by their signature prefi
- **Location**: the DbCache entry whose final segment is `LcOpNwdLogicalHierarchy` (one zlib stream). Older notes called it the scene tree and scanned it for tags 52/53; that scan misses every node that is only back-referenced. Files without a DbCache directory still use that lenient scan (see §2.2.2).
- **Writer tree records**: `NwcWriter` writes flat tag-53 name and tag-52 identity pairs. A tag-53 record may carry a parent marker `[int32 -2][int32 parentNodeId]` after the name (`0` is the model root), which makes the lenient builder attach the following node exactly; real Navisworks streams do not contain it.
- **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.
- **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.
- **Classes**:
Expand All @@ -78,7 +78,7 @@ Once inflated, streams serve dedicated roles identified by their signature prefi
ENTRY LcOaPartitionProps : flags 1, (a, b) = (4, b)
SEGMENT := [int32 0] ZSTREAM{k} ZTOC contiguous zlib streams from offset+4 to offset+length; b = compressed length of ZTOC
ZTOC := [int32 k] [k x int32 compressed length of ZSTREAM i] zero pad to 8 (length roundup8(4 + 4k))
HIERARCHY HEADER := [int32 k >= 1] [k x int32 n_i] n_i = number of roots in ZSTREAM i
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
66 := [str name = null] [ptr 52 key] [i32 flags] PAD8 [i64 value]
Expand Down Expand Up @@ -153,7 +153,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. 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 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.
- **`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.
Expand All @@ -175,6 +175,8 @@ UVBODY := [p1][fc][fc x f32] TOKENS(p1, fc/2)? (raw; tokens iff fc/2 != p
- **UVBODY**: the raw form stores interleaved `f32` U/V pairs. The quantised form stores `[U0 bits][V0 bits][U1 bits][V1 bits]…` using `PACKED`. The widths are `bu = w & 0xFF` and `bv = (w >> 8) & 0xFF`. A nonzero-width code `q` represents `min + q/(2^bits - 1) × (max - min)`; width zero takes that axis's minimum. Both widths may be zero for a constant pair. The token stream maps each of the `p1` render vertices to a stored pair, independently of the position map. U/V use the lower-left origin, as confirmed by converting a synthetic OBJ with asymmetric coordinates in Navisworks.
- **Text** (class 103): `[100][103][str text][6 x f32][6 x f32 bounds (min then max)][i32 style index][pad8]`. The reader preserves the text, style index, bounds and fragment placement. The glyph triangles counted by the fragment are absent from the geometry record.

- **Parametric disks and cylinder sides**: Class 104 is `[100][104][3][center xyz][u xyz][v xyz][radius][pad8]`. Class 105 is `[100][105][0x00030003][start xyz][end xyz][u xyz][v xyz][radius]`. The coordinates, cross-section basis vectors and radius are `f32`. The reader checks the basis and radius and emits the 32 triangles per disk or 64 triangles per side counted by the fragment. Cylinder caps are separate class-104 records. Parametric fragment boxes can be conservative, so the reader checks that they enclose the decoded surface within single-precision rounding.

- **Writer records**: `NwcWriter` emits its own simplified record, `[id][94][0][60][p1][p2][p2 x f32 xyz]`, followed by the trailer `["NWCI"][indexCount][indexCount x i32][Id i32][nameLength][UTF-8 name][pad4]`. The fallback mesh parser (§2.5) restores the exact triangle indices, `Id` and `Name` from the trailer; records without it keep the rebuilt strip and the synthesized `Mesh_{index}` identity. The trailer is writer-specific: it is not part of the documented Navisworks grammar.

### 2.7 DB Cache Directory (`DbCache` / `LcOpDBCache`)
Expand Down
120 changes: 115 additions & 5 deletions src/NwcIO/Internal/Parsing/GeometryRecordParser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,12 @@

namespace NwcIO.Internal.Parsing;

/// <summary>A decoded geometry record: triangles (class 94), lines (class 95) or points (class 96).</summary>
/// <summary>A decoded triangle, line, point, text or parametric geometry record.</summary>
internal sealed class GeometryRecord
{
public required bool IsLines { get; init; }
public bool IsPoints { get; init; }
public bool IsParametric { get; init; }
public string? Text { get; init; }
public int? TextStyleIndex { get; init; }

Expand All @@ -35,7 +36,7 @@ internal sealed class GeometryRecord
/// <summary>One colour per point when stored.</summary>
public RgbaColor[]? PointColors { get; init; }

/// <summary>Axis-aligned bounds of the stored positions.</summary>
/// <summary>Axis-aligned bounds in local geometry coordinates.</summary>
public required BoundingBox3d Bounds { get; init; }

public int PrimitiveCount => IsPoints ? Vertices.Length : IsLines ? LineIndices.Length / 2 : Indices.Length / 3;
Expand Down Expand Up @@ -69,9 +70,14 @@ public static GeometryRecord Parse(ReadOnlySpan<byte> record, int normalBits)
return ReadText(record, pos);
}

if (cls is 104 or 105)
{
return ReadParametric(record, pos, hasSide: cls == 105);
}

if (cls is not (94 or 95 or 96))
{
throw Fail($"class {cls} is not 94, 95, 96 or 103", at);
throw Fail($"class {cls} is not 94, 95, 96, 103, 104 or 105", at);
}

bool lines = cls == 95;
Expand Down Expand Up @@ -398,6 +404,107 @@ public static GeometryRecord Parse(ReadOnlySpan<byte> record, int normalBits)
};
}

private static GeometryRecord ReadParametric(ReadOnlySpan<byte> record, int pos, bool hasSide)
{
Expect(record, ref pos, hasSide ? 0x00030003 : 3, "unsupported parametric geometry flags");
Vector3d start = ReadParametricVector(record, ref pos);
Vector3d end = hasSide ? ReadParametricVector(record, ref pos) : start;
int basisOffset = pos;
Vector3d u = ReadParametricVector(record, ref pos);
Vector3d v = ReadParametricVector(record, ref pos);
int radiusOffset = pos;
double radius = ReadFiniteSingle(record, ref pos, "parametric radius is not finite");
if (radius <= 0)
{
throw Fail("parametric radius is not positive", radiusOffset);
}

CheckEnd(record, ref pos);
const double basisTolerance = 1e-4;
if (Math.Abs(u.LengthSquared - 1) > basisTolerance || Math.Abs(v.LengthSquared - 1) > basisTolerance ||
Math.Abs(Vector3d.Dot(u, v)) > basisTolerance)
{
throw Fail("parametric basis is not orthonormal", basisOffset);
}

var normal = Vector3d.Cross(u, v).Normalize();
if (hasSide)
{
var axis = end - start;
double alignment = Vector3d.Dot(normal, axis) / axis.Length;
if (!double.IsFinite(alignment) || Math.Abs(alignment) < 1 - basisTolerance)
{
throw Fail("cylinder axis is not perpendicular to its cross section", basisOffset);
}

if (alignment < 0)
{
v = -v;
}
}

// The fragment counts for these records are 32 triangles for a disk and 64 for a cylinder side.
const int segments = 32;
var vertices = new Vector3d[segments + (hasSide ? segments : 1)];
var normals = new Vector3d[vertices.Length];
var indices = new int[segments * (hasSide ? 6 : 3)];
for (int i = 0; i < segments; i++)
{
var (sin, cos) = Math.SinCos(Math.Tau * i / segments);
var radial = u * cos + v * sin;
var offset = radial * radius;
vertices[i] = start + offset;
int next = (i + 1) % segments;
if (hasSide)
{
vertices[i + segments] = end + offset;
normals[i] = normals[i + segments] = radial.Normalize();
int corner = 6 * i;
indices[corner] = i;
indices[corner + 1] = next;
indices[corner + 2] = i + segments;
indices[corner + 3] = next;
indices[corner + 4] = next + segments;
indices[corner + 5] = i + segments;
}
else
{
normals[i] = normal;
indices[3 * i] = segments;
indices[3 * i + 1] = i;
indices[3 * i + 2] = next;
}
}

if (!hasSide)
{
vertices[segments] = start;
normals[segments] = normal;
}

var radiusBounds = radius * new Vector3d(Math.Sqrt(u.X * u.X + v.X * v.X), Math.Sqrt(u.Y * u.Y + v.Y * v.Y),
Math.Sqrt(u.Z * u.Z + v.Z * v.Z));
var min = new Vector3d(Math.Min(start.X, end.X), Math.Min(start.Y, end.Y), Math.Min(start.Z, end.Z)) - radiusBounds;
var max = new Vector3d(Math.Max(start.X, end.X), Math.Max(start.Y, end.Y), Math.Max(start.Z, end.Z)) + radiusBounds;
return new GeometryRecord
{
IsLines = false,
IsParametric = true,
Vertices = vertices,
Normals = normals,
Indices = indices,
LineIndices = [],
Bounds = new BoundingBox3d(min, max),
};
}

private static Vector3d ReadParametricVector(ReadOnlySpan<byte> record, ref int pos)
{
const string nonFinite = "parametric geometry value is not finite";
return new(ReadFiniteSingle(record, ref pos, nonFinite), ReadFiniteSingle(record, ref pos, nonFinite),
ReadFiniteSingle(record, ref pos, nonFinite));
}

private static GeometryRecord ReadText(ReadOnlySpan<byte> record, int pos)
{
int lengthOffset = pos;
Expand Down Expand Up @@ -444,10 +551,13 @@ private static GeometryRecord ReadText(ReadOnlySpan<byte> record, int pos)
};
}

private static float ReadTextNumber(ReadOnlySpan<byte> record, ref int pos)
private static float ReadTextNumber(ReadOnlySpan<byte> record, ref int pos) =>
ReadFiniteSingle(record, ref pos, "text geometry value is not finite");

private static float ReadFiniteSingle(ReadOnlySpan<byte> record, ref int pos, string error)
{
float value = BitConverter.Int32BitsToSingle(ReadInt32(record, ref pos));
return float.IsFinite(value) ? value : throw Fail("text geometry value is not finite", pos - 4);
return float.IsFinite(value) ? value : throw Fail(error, pos - 4);
}

private static void CheckEnd(ReadOnlySpan<byte> record, ref int pos)
Expand Down
9 changes: 3 additions & 6 deletions src/NwcIO/Internal/Parsing/HierarchyParser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@ internal static class HierarchyParser
// Slot families as observed (docs/format-notes.md §2.2).
private static ReadOnlySpan<int> TopLevelClasses => [53, 32];

private static ReadOnlySpan<int> TopLevelClassesWithoutPropertyStreams => [22, 53, 32];

private static ReadOnlySpan<int> ChildClasses => [22, 53];

private static ReadOnlySpan<int> UsernameClasses => [52];
Expand Down Expand Up @@ -301,11 +303,6 @@ public Parser(LcObjectReader reader, int guidCount, Func<IReadOnlyList<byte[]>?>
public (Node[] Top, long Total) ReadStream()
{
int k = _reader.ReadCount(4);
if (k < 1)
{
throw _reader.Fail("header count k is below 1");
}

var rootCounts = new int[k];
for (int i = 0; i < k; i++)
{
Expand All @@ -314,7 +311,7 @@ public Parser(LcObjectReader reader, int guidCount, Func<IReadOnlyList<byte[]>?>

_roots = new PartitionRoots(_reader, rootCounts, _partitionProps!);
_reader.ReadImplicitRoot();
var top = ReadNodes(TopLevelClasses);
var top = ReadNodes(k == 0 ? TopLevelClassesWithoutPropertyStreams : TopLevelClasses);
var (total, _, _) = Measure(top, 0);
if (_reader.ReadInt32() != 1)
{
Expand Down
11 changes: 10 additions & 1 deletion src/NwcIO/Internal/Parsing/ModelGraphReader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -478,7 +478,7 @@ private static void CheckLinks(Fragment[] fragments, GeometryRecord[] records, I
}

var record = records[fragment.Record - 1];
if (fragment.Bounds != record.Bounds)
if (fragment.Bounds != record.Bounds && !(record.IsParametric && EnclosesParametricBounds(fragment.Bounds, record.Bounds)))
{
throw Link(k, "bounding box differs from the record's");
}
Expand All @@ -491,6 +491,15 @@ private static void CheckLinks(Fragment[] fragments, GeometryRecord[] records, I
}
}

// Parametric primitives may have conservative fragment boxes stored with single-precision rounding.
private static bool EnclosesParametricBounds(BoundingBox3d stored, BoundingBox3d actual)
{
double rounding = Math.Max(actual.Min.Length, actual.Max.Length) * 1e-6;
var tolerance = new Vector3d(rounding, rounding, rounding);
var enclosing = new BoundingBox3d(stored.Min - tolerance, stored.Max + tolerance);
return enclosing.Contains(actual.Min) && enclosing.Contains(actual.Max);
}

private static InvalidDataException Entry(string segment, NwcDbCacheEntry entry, string rule) =>
new($"{segment} DbCache entry at file byte {entry.Offset}: {rule}");

Expand Down
12 changes: 11 additions & 1 deletion tests/NwcIO.Tests/GeometryRecordParserTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,16 @@ public class GeometryRecordParserTests
{
private static readonly RgbaColor Red = new(1, 0, 0, 1), Green = new(0, 1, 0, 1);

[Fact]
public void Parse_ParametricCylinderWithZeroRadius_RejectsTheRecord()
{
var record = new LcGraphWriter().Int(100).Int(105).Int(0x00030003)
.Float(0).Float(0).Float(0).Float(0).Float(0).Float(1)
.Float(1).Float(0).Float(0).Float(0).Float(1).Float(0)
.Float(0).ToArray();
AssertRule("parametric radius is not positive", record);
}

[Fact]
public void Parse_LinePalette_IsAbgr()
{
Expand Down Expand Up @@ -244,7 +254,7 @@ public void Parse_R5EightBitPalette_DecodesDiagonalNormal()
[InlineData("R1", 92, "C0", "lead byte is undefined")] // undefined NTOK lead
[InlineData("R1", 112, "01000040", "unused packed bit is set")] // unused packed bit
[InlineData("R1", 76, "67000000", "slot id is out of order")] // N id 103: id order
[InlineData("R1", 4, "61000000", "class 97 is not 94, 95, 96 or 103")] // unknown class 97
[InlineData("R1", 4, "61000000", "class 97 is not 94, 95, 96, 103, 104 or 105")] // unknown class 97
[InlineData("R1", -1, "0000000000000000", "record does not end at its TOC length")] // -1 = append: end != TOC length
[InlineData("R2", 122, "01", "pad byte is not zero")] // non-zero pad4
[InlineData("R2", 84, "D5", "lead byte is undefined")] // axis code outside N
Expand Down
2 changes: 0 additions & 2 deletions tests/NwcIO.Tests/HierarchyParserTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -288,7 +288,6 @@ 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("kZero", "header count k is below 1")] // header k = 0
[InlineData("extra200Null", "null pointer in a slot that needs an object")] // class 200 with a null extra
public void Read_SlotFamilyDefect_Throws(string defect, string rule) => AssertRule(rule, Defective(defect));

Expand Down Expand Up @@ -832,7 +831,6 @@ private static void Extra(LcGraphWriter w, int itemFlag = 1, int payload = 0x000
w.Int(99).Int(0);
}),
"topLevelLeaf" => End(LeafAtTopLevel()),
"kZero" => GroupWithLeaf(0, _ => { }, k: 0),
"extra200Null" => GroupWithLeaf(1, w =>
{
w.New(200);
Expand Down
Loading
Loading