diff --git a/CHANGELOG.md b/CHANGELOG.md index fa81466..860df49 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,7 +6,8 @@ All notable changes to the `NwcIO` library, the CLI and the `NwcIO.Scene` adapte ### Fixed -- Path-based Wavefront OBJ export writes a sibling `.mtl` with diffuse colors and opacity from mesh materials (#93). Texture coordinates and texture maps are pending. +- Path-based Wavefront OBJ export writes a sibling `.mtl` with diffuse colors and opacity from mesh materials (#93). +- Read raw and quantised mesh UVs and Generic diffuse image references with XRef remapping. OBJ/MTL and GLB exports preserve the UVs and link to external diffuse images (#93). ## [0.16.0] - 2026-11-19 diff --git a/docs/format-notes.md b/docs/format-notes.md index 6f5b111..b8b189d 100644 --- a/docs/format-notes.md +++ b/docs/format-notes.md @@ -101,7 +101,7 @@ The nesting is therefore independent of the exporter UI language for the marker - **Other containers**: files not read through a DbCache directory are scanned for streams `[int32 ?][int32 count]` where `(streamLength - 8) == count * 16`, followed by the 16-byte GUIDs. ### 2.4 Fragments (`LcOpNwdFragments`) -- **Location**: the DbCache entry whose final segment is `LcOpNwdFragments` (one zlib stream). Framing: `[int32 n] n x pointer`, zero-padded to a multiple of 8. Pointers follow the rule in §2.2; every root pointer is a new class-13 object. +- **Location**: the DbCache entry whose final segment is `LcOpNwdFragments` (one zlib stream). Framing: `[int32 n] n x pointer`, zero-padded to a multiple of 8. Some writers insert one zero word between `n` and the first `[100][13]`. Pointers follow the rule in §2.2; every root pointer is a new class-13 object. - **Classes**: - `13` fragment: `[f64 D][i32 a][i32 b][i32 c][i32 seq][ptr pose][ptr appearance][ptr geometry]`. - `seq`: preorder index of the owning leaf (§2.2). @@ -111,7 +111,8 @@ 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 `[ptr 185]` when `flags & 32`. + - `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..99`) into `LcOpSharedNodes`. The shared stream starts with a count followed by indexed pointers. An appearance with flags `0x71` has one trailing zero word in a Navisworks 2027 file saved after editing the diffuse image. + - `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) repeats the fields as `f64` and names the material (null for rooms). - `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. @@ -143,7 +144,8 @@ CSLOT := 0 | [id][58][5634][-p1][pal][pal x 4 bytes] CTOK? (CTOK iff pal != p1 P := [n][bits][n][ceil(n*bits/32) words] (strip or polyline lengths L) SFIELD := [S] TOKENS(S, p1)? (class 94 only; tokens iff S > 0) UVBODY := [p1][fc][fc x f32] TOKENS(p1, fc/2)? (raw; tokens iff fc/2 != p1) - | [-p1][4 x f32][w][m][ceil(m*(bu+bv)/32) words] TOKENS(p1, m)? (quantised; tokens iff m != p1) + | [-p1][f32 minU][f32 minV][f32 maxU][f32 maxV][w][m] + [ceil(m*(bu+bv)/32) words] TOKENS(p1, m)? (quantised; tokens iff m != p1) ``` - **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. @@ -165,8 +167,7 @@ UVBODY := [p1][fc][fc x f32] TOKENS(p1, fc/2)? (raw; tokens iff fc/2 != p - **Normals** (class 94): a palette entry is three two's-complement values of width `B`, divided by `2^(B-1)-1` and normalised; a zero vector means no normal. `B` is not stored in the record: it is the width under which every record of the file parses (16 for `.nwc`, 8 for `.nwd`). Render vertex `r` takes `palette[NIdx[r]]`, or an axis vector for an axis code (`D0` +X, `D1` -X, `D2` +Y, `D3` -Y, `D4` +Z, `D5` -Z). - **Triangles** (class 94): corners are `0..p1-1` when `S = 0`, otherwise `TOKENS(S, p1)`. They are split by `L` into consecutive strips; in each strip, triangle `i` is `(c[i], c[i+1], c[i+2])` for even `i` and `(c[i+1], c[i], c[i+2])` for odd `i`. Parity restarts in every strip. The triangle count is the sum of `L-2`. Front faces are counter-clockwise. - **Polylines** (class 95): render vertices `0..p1-1` are split by `L` into open polylines; the segment count is the sum of `L-1`. There is no implicit closing segment. -- **UVBODY**: the raw form has a non-negative first int `p1` and `fc` floats (two per UV pair, `fc/2` pairs). The quantised form has `-p1`, four floats, then `w`, `m` and the packed words; `bu = w & 0xFF` and `bv = (w >> 8) & 0xFF` are the bit widths of the two coordinates, so the packed block is `ceil(m*(bu+bv)/32)` words. One width may be 0, a coordinate constant over the record (seen in `.nwd` files saved by Navisworks 2026); both cannot. The token stream maps each of the `p1` render vertices to one of the `fc/2` or `m` stored pairs. -- **Not decoded**: UV values and colour channels. Only their lengths and maps are read, to find the next field. +- **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. - **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`) diff --git a/docs/public-api.md b/docs/public-api.md index b3837b2..af71fc0 100644 --- a/docs/public-api.md +++ b/docs/public-api.md @@ -21,7 +21,7 @@ The supported surface is the `NwcIO` and `NwcIO.Model.*` namespaces listed here | `NwcPropertyRecord` | Property record (`Class`, `Name`, `Value`, `ValueType`, `Tag`, `FirstInt`; typed `IntValue`, `DoubleValue`, `ReferenceId`, `ReferenceTag`, `ReferenceClass`). On node properties of the strict path, `Class` is the property tab name (category, for example `Element`), `Name` the property name and `FirstInt` the key object id. Records scanned from property streams (`NwcDocument.PropertyRecords`, and node properties of other files) keep their internal class names. `TabInternalName` and `InternalName` are the internal names of the tab and the key on strict-path node properties, null on scanned records. | | `NwcPropertyTab` | One property tab of a strict-path node (`NwcNode.PropertyTabs`, in stored slot order): display `Name`, `InternalName`, `Properties`. A tab object shared by several nodes is one instance. | | `NwcMesh` | Triangle mesh with vertices, indices, `Normals` aligned with vertices, `LineIndices` for polylines, world-space transform, bounding box, and material. Model files hold one mesh per placed fragment; `Id` is the fragment index. Meshes of fragments that share a geometry record share their `Vertices`, `Indices`, `Normals`, `LineIndices` and `LineColors` arrays; do not mutate them. `GeometryIndex` (the geometry record; −1 outside model files) and `LineColors` (per vertex, line meshes of model files). | -| `NwcMaterial` | Colour and PBR material. On the strict path, with meshes and the scene tree, each mesh's material is decoded from the file: `Name` is the name of the nearest class-31 material on its leaf or an ancestor (`Default` when there is none or it is empty), `Color` is the diffuse colour of its appearance with alpha `1 - transparency`, each channel rounded to a byte (halves away from zero), and `Roughness` and `Metallic` keep their defaults (the file's shininess is not mapped); one material per distinct name and colour bytes, `Id` in order of first use, and `NwcDocument.Materials` lists them; `NwcNode.Material` stays null. Without the scene tree there are no materials. Elsewhere nothing is decoded from material data in the file: names come from material references in property records and the colour from a `revit_Color` record that follows the definition. A material without that record gets a neutral grey and `IsInferred = true`; no colour is guessed from the name. Meshes are not matched to materials by name or size: every mesh without a material shares one neutral `Default Material` with `IsInferred = true` (a new instance per document, listed in `NwcDocument.Materials`). `IsInferred` is `true` for a colour or material that is not read from the file. | +| `NwcMaterial` | Colour and PBR material. On the strict path, `Name` comes from the nearest class-31 material on the mesh's leaf or an ancestor (`Default` when absent or empty), `Color` comes from the fragment's diffuse appearance with alpha `1 - transparency`, and `DiffuseTexture` comes from its Generic diffuse map. Each colour channel is rounded to a byte (halves away from zero). `Roughness` and `Metallic` keep their defaults. `NwcDocument.Materials` lists distinct name, RGBA and texture combinations in order of first use. With `BuildSceneTree = false`, appearances with a diffuse image still supply a material named `Default`. Elsewhere names come from material references in property records and the colour from a `revit_Color` record that follows the definition. A material without that record gets a neutral grey and `IsInferred = true`. Meshes without a material share one neutral `Default Material` per document with `IsInferred = true`. | | `NwcTransform` | Parsed pose/transform records with quaternion rotation, uniform `Scale` (negative for a mirrored placement) and affine 4×4 matrix conversion. Model files hold one transform per fragment, with the same `Id` as its mesh. | | `NwcFileInfo` | Source path, loader plugin, export timestamp from partition header, format version, text encoding, and chunk marker from section headers. | | `NwcDbCacheDirectory` & `NwcDbCacheEntry` | The `LcOpDBCache` directory (`NwcDocument.DbCache`, null when the file has none or it cannot be parsed). `DatabaseName` is the name of the `LcOpDBCache` entry or `""`; `Entries` lists every entry in file order and `Find` looks one up by segment name (exact or suffix, case-insensitive). Each entry has `Name`, `Flags`, `Offset` (an absolute file offset), `Length` and `Extra` (`a + b*2^32` of its two trailing 32-bit fields). | @@ -137,8 +137,14 @@ Space to activate them. With focus on the 3D model view, the arrow keys orbit, + Home resets the camera. Escape clears the current measurement while Measure is active. OBJ saves to a path, including `SaveObjAsync`, write a sibling `.mtl` when exported geometry -has materials. The library stores diffuse RGB (`Kd`) and opacity (`d`). OBJ saves to a stream or -`TextWriter` export geometry only. Texture coordinates and texture maps are currently unsupported. +has materials. `NwcMesh.TexCoords` holds optional per-vertex UVs with a lower-left origin. OBJ +writes `vt` and indexes it from faces, including when writing to a stream or `TextWriter`. +The material library stores diffuse RGB (`Kd`), opacity (`d`), and `map_Kd` for a diffuse image. +GLB writes `TEXCOORD_0` with a top-left origin, and `baseColorTexture` for external PNG or JPEG images. +`NwcMaterial.DiffuseTexture` holds the image reference, including any XRef remapping. Exporters +emit references to local paths. Keep the referenced images available at those paths. Relative +references are interpreted relative to the exported asset. Embedded image payloads and other +material channels remain outside this support. An OBJ save with materials requires a sibling filename that can be used in an `mtllib` directive. The export rejects a symbolic link at the material library path. diff --git a/src/NwcIO/Compatibility/Export/GlbExporter.cs b/src/NwcIO/Compatibility/Export/GlbExporter.cs index 2031409..c9ab015 100644 --- a/src/NwcIO/Compatibility/Export/GlbExporter.cs +++ b/src/NwcIO/Compatibility/Export/GlbExporter.cs @@ -71,6 +71,10 @@ public static void Write( // Copies of a source material made for line primitives that export COLOR_0, one per source material and blend flag. var materialsWithBlend = new HashSet(); var lineMaterialMap = new Dictionary<(int? Source, bool Blend), int>(); + var imageUris = new Dictionary(StringComparer.Ordinal); + var images = new List(); + var texturedVariants = new Dictionary(); + var materialTextures = new Dictionary(); for (int m = 0; m < meshes.Count; m++) { @@ -247,6 +251,29 @@ public static void Write( null)); } + int? uvAccessor = null; + if (indices.Count > 0 && TextureExport.GetCoordinates(mesh, vCount, cancellationToken) is { } uv) + { + long uvLength = (long)vCount * 8; + long offset = bin.BeginView(uvLength); + for (int v = 0; v < vCount;) + { + cancellationToken.ThrowIfCancellationRequested(); + var batch = bin.ReserveRecords(vCount - v, 8, out int count); + for (int i = 0; i < count; i++, v++) + { + var coordinate = uv[v]; + BinaryPrimitives.WriteSingleLittleEndian(batch[(8 * i)..], coordinate.X); + // glTF's texture origin is the upper left. NWC and OBJ use the lower left. + BinaryPrimitives.WriteSingleLittleEndian(batch[(8 * i + 4)..], 1f - coordinate.Y); + } + } + + uvAccessor = accessors.Count; + accessors.Add(new AccessorDef(bufferViews.Count, 0, ComponentTypeFloat, vCount, "VEC2", null, null)); + bufferViews.Add(new BufferViewDef(offset, uvLength, TargetArrayBuffer)); + } + int? triIdxAccessor = WriteIndexAccessor(bin, indices, vCount, bufferViews, accessors); int? lineIdxAccessor = WriteIndexAccessor(bin, lineIndices, vCount, bufferViews, accessors); @@ -301,12 +328,31 @@ public static void Write( var primitives = new List(); if (triIdxAccessor.HasValue && normAccessorIdx.HasValue) { + int? triangleMaterial = matIdx; + if (uvAccessor.HasValue && matIdx is { } baseIndex && TextureExport.GetImageUri(mesh.Material!.DiffuseTexture) is { } uri) + { + if (!texturedVariants.TryGetValue(baseIndex, out int variant)) + { + if (!imageUris.TryGetValue(uri, out int image)) + { + image = images.Count; + images.Add(uri); + imageUris.Add(uri, image); + } + variant = materialTable.Count; + materialTable.Add(mesh.Material); + texturedVariants.Add(baseIndex, variant); + materialTextures.Add(variant, image); + } + triangleMaterial = variant; + } primitives.Add(new PrimitiveDef( posAccessorIdx, normAccessorIdx.Value, null, + uvAccessor, triIdxAccessor.Value, - matIdx, + triangleMaterial, 4)); // TRIANGLES } @@ -316,6 +362,7 @@ public static void Write( posAccessorIdx, null, colAccessorIdx, + null, lineIdxAccessor.Value, lineMatIdx, 1)); // LINES @@ -334,6 +381,8 @@ public static void Write( generatorName ?? "NwcIO glTF 2.0 Exporter", viewpoints, materialsWithBlend, + images, + materialTextures, cancellationToken); WriteContainer(output, jsonData.Span, binFile); @@ -393,6 +442,8 @@ private static ReadOnlyMemory BuildJsonChunk( string generator, IReadOnlyList? viewpoints, HashSet? materialsWithBlend, + List images, + Dictionary materialTextures, CancellationToken cancellationToken) { var json = new ArrayBufferWriter(); @@ -530,6 +581,7 @@ private static ReadOnlyMemory BuildJsonChunk( { writer.WriteNumber("COLOR_0", colAcc); } + if (p.UvAccessor is { } uvAcc) writer.WriteNumber("TEXCOORD_0", uvAcc); writer.WriteEndObject(); writer.WriteNumber("indices", p.IndicesAccessor); @@ -569,6 +621,12 @@ private static ReadOnlyMemory BuildJsonChunk( WriteSafeFloatValue(writer, mat.Color.B); WriteSafeFloatValue(writer, mat.Color.A); writer.WriteEndArray(); + if (materialTextures.TryGetValue(i, out int texture)) + { + writer.WriteStartObject("baseColorTexture"); + writer.WriteNumber("index", texture); + writer.WriteEndObject(); + } WriteSafeFloat(writer, "metallicFactor", mat.Metallic); WriteSafeFloat(writer, "roughnessFactor", mat.Roughness); writer.WriteEndObject(); @@ -578,6 +636,27 @@ private static ReadOnlyMemory BuildJsonChunk( if (materials.Count > 0) writer.WriteEndArray(); + if (images.Count > 0) + { + writer.WriteStartArray("images"); + foreach (string uri in images) + { + writer.WriteStartObject(); + writer.WriteString("uri", uri); + writer.WriteEndObject(); + } + writer.WriteEndArray(); + + writer.WriteStartArray("textures"); + for (int i = 0; i < images.Count; i++) + { + writer.WriteStartObject(); + writer.WriteNumber("source", i); + writer.WriteEndObject(); + } + writer.WriteEndArray(); + } + // accessors if (accessors.Count > 0) writer.WriteStartArray("accessors"); for (int i = 0; i < accessors.Count; i++) @@ -851,6 +930,7 @@ private readonly record struct PrimitiveDef( int PositionAccessor, int? NormalAccessor, int? ColorAccessor, + int? UvAccessor, int IndicesAccessor, int? MaterialIndex, int Mode); diff --git a/src/NwcIO/Compatibility/Export/ObjExporter.cs b/src/NwcIO/Compatibility/Export/ObjExporter.cs index 78253d4..d117085 100644 --- a/src/NwcIO/Compatibility/Export/ObjExporter.cs +++ b/src/NwcIO/Compatibility/Export/ObjExporter.cs @@ -35,7 +35,7 @@ private static async ValueTask WriteFileCore(IReadOnlyList meshes, stri ArgumentNullException.ThrowIfNull(path); cancellationToken.ThrowIfCancellationRequested(); - var materials = new Dictionary(); + var materials = new Dictionary<(NwcMaterial Material, string? Map), string>(); bool hasUnassigned = false; foreach (var mesh in meshes) { @@ -43,9 +43,12 @@ private static async ValueTask WriteFileCore(IReadOnlyList meshes, stri if (mesh.Vertices.Count == 0 || !HasPrimitives(mesh)) continue; if (mesh.Material is { } material) { - if (!materials.ContainsKey(material)) + bool hasTexturedFaces = material.DiffuseTexture is not null && mesh.Indices.Count >= 3 && + TextureExport.GetCoordinates(mesh, mesh.Vertices.Count, cancellationToken) is not null; + var key = (material, GetMap(mesh, hasTexturedFaces)); + if (!materials.ContainsKey(key)) { - materials.Add(material, FormattableString.Invariant($"nwc_{materials.Count + 1}")); + materials.Add(key, FormattableString.Invariant($"nwc_{materials.Count + 1}")); } } else @@ -98,7 +101,7 @@ public static void Write( private static void WriteCore(IReadOnlyList meshes, TextWriter writer, bool worldCoordinates, string? sourceDocument, Func? objectNamePrefix, - string? materialFileName, Dictionary? materials, CancellationToken cancellationToken) + string? materialFileName, Dictionary<(NwcMaterial Material, string? Map), string>? materials, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(meshes); ArgumentNullException.ThrowIfNull(writer); @@ -115,6 +118,7 @@ private static void WriteCore(IReadOnlyList meshes, TextWriter writer, writer.WriteLine(); int baseVertexIndex = 1; + int baseUvIndex = 1; for (int m = 0; m < meshes.Count; m++) { @@ -147,9 +151,18 @@ private static void WriteCore(IReadOnlyList meshes, TextWriter writer, writer.WriteLine(FormattableString.Invariant($"v {pt.X:F4} {pt.Y:F4} {pt.Z:F4}")); } + var uv = mesh.Indices.Count >= 3 ? TextureExport.GetCoordinates(mesh, vertices.Count, cancellationToken) : null; + if (uv is not null) + { + foreach (var coordinate in uv) + { + writer.WriteLine(FormattableString.Invariant($"vt {coordinate.X:R} {coordinate.Y:R}")); + } + } + if (materials is not null && HasPrimitives(mesh)) { - string materialName = mesh.Material is { } material ? materials[material] : DefaultMaterial; + string materialName = mesh.Material is { } material ? materials[(material, GetMap(mesh, uv is not null))] : DefaultMaterial; writer.WriteLine($"usemtl {materialName}"); } @@ -162,7 +175,14 @@ private static void WriteCore(IReadOnlyList meshes, TextWriter writer, int i0 = baseVertexIndex + faces[i]; int i1 = baseVertexIndex + faces[i + 1]; int i2 = baseVertexIndex + faces[i + 2]; - writer.WriteLine(FormattableString.Invariant($"f {i0} {i1} {i2}")); + if (uv is null) + { + writer.WriteLine(FormattableString.Invariant($"f {i0} {i1} {i2}")); + } + else + { + writer.WriteLine(FormattableString.Invariant($"f {i0}/{baseUvIndex + faces[i]} {i1}/{baseUvIndex + faces[i + 1]} {i2}/{baseUvIndex + faces[i + 2]}")); + } } } @@ -178,27 +198,36 @@ private static void WriteCore(IReadOnlyList meshes, TextWriter writer, } baseVertexIndex += vertices.Count; + baseUvIndex += uv?.Count ?? 0; writer.WriteLine(); } } private static bool HasPrimitives(NwcMesh mesh) => mesh.Indices.Count >= 3 || mesh.LineIndices.Count >= 2; - private static void WriteMaterials(TextWriter writer, Dictionary materials, bool hasUnassigned, + private static string? GetMap(NwcMesh mesh, bool hasUv) + { + if (!hasUv || mesh.Indices.Count < 3 || TextureExport.GetLocalPath(mesh.Material?.DiffuseTexture) is not { } path || + path.Contains('#')) return null; + return path[0] == '-' ? "./" + path : path; + } + + private static void WriteMaterials(TextWriter writer, Dictionary<(NwcMaterial Material, string? Map), string> materials, bool hasUnassigned, CancellationToken cancellationToken) { - foreach (var (material, name) in materials) + foreach (var (entry, name) in materials) { cancellationToken.ThrowIfCancellationRequested(); - WriteMaterial(name, material.Color); + WriteMaterial(name, entry.Material.Color, entry.Map); } - if (hasUnassigned) WriteMaterial(DefaultMaterial, RgbaColor.White); + if (hasUnassigned) WriteMaterial(DefaultMaterial, RgbaColor.White, null); - void WriteMaterial(string name, RgbaColor color) + void WriteMaterial(string name, RgbaColor color, string? map) { writer.WriteLine($"newmtl {name}"); writer.WriteLine(FormattableString.Invariant($"Kd {Component(color.R):R} {Component(color.G):R} {Component(color.B):R}")); writer.WriteLine(FormattableString.Invariant($"d {Component(color.A):R}")); + if (map is not null) writer.WriteLine($"map_Kd {map}"); writer.WriteLine(); } diff --git a/src/NwcIO/Compatibility/Export/TextureExport.cs b/src/NwcIO/Compatibility/Export/TextureExport.cs new file mode 100644 index 0000000..77d82ef --- /dev/null +++ b/src/NwcIO/Compatibility/Export/TextureExport.cs @@ -0,0 +1,48 @@ +using System.Numerics; +using NwcIO.Model; + +namespace NwcIO.Internal.Export; + +internal static class TextureExport +{ + public static IReadOnlyList? GetCoordinates(NwcMesh mesh, int vertexCount, CancellationToken cancellationToken) + { + if (mesh.TexCoords is not { } coordinates || coordinates.Count != vertexCount) return null; + + for (int i = 0; i < coordinates.Count; i++) + { + if ((i & 4095) == 0) cancellationToken.ThrowIfCancellationRequested(); + var uv = coordinates[i]; + if (!float.IsFinite(uv.X) || !float.IsFinite(uv.Y)) return null; + } + return coordinates; + } + + // Export a reference only. A model-supplied path must not cause the exporter to open a file or fetch a URL. + public static string? GetLocalPath(NwcXRef? texture) + { + string? path = texture?.EffectivePath.Replace('\\', '/'); + if (string.IsNullOrWhiteSpace(path) || path != path.Trim() || path.StartsWith("//", StringComparison.Ordinal) || + path.Any(c => char.IsControl(c) || c is '\u2028' or '\u2029')) return null; + + int colon = path.IndexOf(':', IsDrivePath(path) ? 2 : 0); + return colon < 0 ? path : null; + } + + public static string? GetImageUri(NwcXRef? texture) + { + if (GetLocalPath(texture) is not { } path) return null; + string extension = Path.GetExtension(path); + if (!string.Equals(extension, ".png", StringComparison.OrdinalIgnoreCase) && + !string.Equals(extension, ".jpeg", StringComparison.OrdinalIgnoreCase) && + !string.Equals(extension, ".jpg", StringComparison.OrdinalIgnoreCase)) return null; + + if (IsDrivePath(path)) return $"file:///{path[..2]}{EscapePath(path[2..])}"; + if (path[0] == '/') return "file://" + EscapePath(path); + return EscapePath(path); + } + + private static bool IsDrivePath(string path) => path.Length >= 3 && char.IsAsciiLetter(path[0]) && path[1] == ':' && path[2] == '/'; + + private static string EscapePath(string path) => string.Join('/', path.Split('/').Select(Uri.EscapeDataString)); +} diff --git a/src/NwcIO/Internal/Parsing/FragmentParser.cs b/src/NwcIO/Internal/Parsing/FragmentParser.cs index 7bd7c73..4faab43 100644 --- a/src/NwcIO/Internal/Parsing/FragmentParser.cs +++ b/src/NwcIO/Internal/Parsing/FragmentParser.cs @@ -1,3 +1,4 @@ +using System.Buffers.Binary; using NwcIO.Model; namespace NwcIO.Internal.Parsing; @@ -18,7 +19,7 @@ internal readonly record struct Fragment( FragmentLook Look); /// 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); +internal readonly record struct FragmentLook(float R, float G, float B, float Transparency, string? DiffuseTexturePath = null); /// Strict reader of the LcOpNwdFragments object graph (docs/format-notes.md §2.2, §2.4). internal static class FragmentParser @@ -38,7 +39,12 @@ internal static class FragmentParser private static ReadOnlySpan GeometryClasses => [93]; - public static Fragment[] Read(byte[] data) => new Parser(new LcObjectReader(data, Segment)).ReadStream(); + public static Fragment[] Read(byte[] data, byte[]? sharedNodes = null, bool readTextures = false) + { + bool paddedCount = data.Length >= 16 && BinaryPrimitives.ReadInt32LittleEndian(data.AsSpan(4)) == 0 && + BinaryPrimitives.ReadInt32LittleEndian(data.AsSpan(8)) == 100 && BinaryPrimitives.ReadInt32LittleEndian(data.AsSpan(12)) == 13; + return new Parser(new LcObjectReader(data, Segment), sharedNodes, readTextures).ReadStream(paddedCount); + } private sealed record Pose(Vector3d Translation, Quaterniond Rotation, double Scale); @@ -51,17 +57,23 @@ private sealed class Parser private readonly LcObjectReader _reader; private readonly Func _readBody; + private readonly byte[]? _sharedNodes; + private readonly bool _readTextures; + private string?[]? _sharedTextures; - public Parser(LcObjectReader reader) + public Parser(LcObjectReader reader, byte[]? sharedNodes, bool readTextures) { _reader = reader; _readBody = ReadBody; + _sharedNodes = sharedNodes; + _readTextures = readTextures; } // [n] PTR{n}, each a new class 13, then the zero pad to 8 (docs/format-notes.md §2.4). - public Fragment[] ReadStream() + public Fragment[] ReadStream(bool paddedCount) { var fragments = new Fragment[_reader.ReadCount(MinFragmentBytes)]; + if (paddedCount) _reader.ReadInt32(); for (int i = 0; i < fragments.Length; i++) { fragments[i] = (Fragment)_reader.ReadPointer(FragmentClasses, _readBody, allowNull: false, allowBackReference: false)!; @@ -80,7 +92,7 @@ public Fragment[] ReadStream() 55 => ReadAppearance(), 54 => ReadMaterial(), 93 => ReadGeometry(), - 185 => HierarchyParser.ReadMaterialJson(_reader), + 185 => HierarchyParser.ReadMaterialJson(_reader, _readTextures), _ => throw new InvalidOperationException($"class {classId} has no body reader"), }; @@ -123,17 +135,43 @@ private double ReadFinite() return double.IsFinite(value) ? value : throw _reader.Fail("pose value is not finite"); } - // Class 55: [flags][ptr 54], then [ptr 185 or null] when flags & 32; the look is its material's, the extra is dropped. + // Class 55: [flags][ptr 54], then [ptr 185, a shared index, or null] when flags & 32. private FragmentLook ReadAppearance() { int flags = _reader.ReadInt32(); var look = (FragmentLook)_reader.ReadPointer(MaterialClasses, _readBody, allowNull: false)!; - if ((flags & 32) != 0) + if ((flags & 32) == 0) return look; + + string? texturePath; + if (_sharedNodes is not null && _reader.TryReadSharedIndex(out int index)) + { + _sharedTextures ??= ReadSharedTextures(_sharedNodes, _readTextures); + if (index >= _sharedTextures.Length) throw _reader.Fail("appearance shared index is outside LcOpSharedNodes"); + texturePath = _sharedTextures[index]; + } + else + { + 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) { - _reader.ReadPointer(ExtraClasses, _readBody); + throw _reader.Fail("appearance flag 0x71 has a nonzero trailing word"); } + return look with { DiffuseTexturePath = texturePath }; + } - return look; + private static string?[] ReadSharedTextures(byte[] data, bool readTextures) + { + var reader = new LcObjectReader(data, "LcOpSharedNodes"); + var textures = new string?[reader.ReadCount(8)]; + for (int i = 0; i < textures.Length; i++) + { + textures[i] = reader.ReadPointer(ExtraClasses, _ => HierarchyParser.ReadMaterialJson(reader, readTextures)) as string; + } + reader.ReadEnd(); + return textures; } // Class 54: 14 x f32: ambient 0-2, diffuse 3-5, specular 6-8, emissive 9-11, shininess 12, transparency 13. diff --git a/src/NwcIO/Internal/Parsing/GeometryRecordParser.cs b/src/NwcIO/Internal/Parsing/GeometryRecordParser.cs index 741869d..2812071 100644 --- a/src/NwcIO/Internal/Parsing/GeometryRecordParser.cs +++ b/src/NwcIO/Internal/Parsing/GeometryRecordParser.cs @@ -1,4 +1,5 @@ using System.Buffers.Binary; +using System.Numerics; using NwcIO.Model; namespace NwcIO.Internal.Parsing; @@ -20,6 +21,9 @@ internal sealed class GeometryRecord /// One unit normal per render vertex, for none; null for lines. public required Vector3d[]? Normals { get; init; } + /// One texture coordinate per render vertex, when present. + public Vector2[]? TexCoords { get; init; } + /// One colour per render vertex for lines; null for triangles. public RgbaColor[]? LineColors { get; init; } @@ -110,6 +114,7 @@ public static GeometryRecord Parse(ReadOnlySpan record, int normalBits) at = pos; int id = ReadInt32(record, ref pos); bool hasUv = id != 0; + Vector2[]? texCoords = null; if (hasUv) { ExpectId(id, ref nextId, at); @@ -125,20 +130,29 @@ public static GeometryRecord Parse(ReadOnlySpan record, int normalBits) throw Fail("UV float count is not positive and even", at); } + int pairsOffset = pos; Skip(record, ref pos, 4L * fc, "UV floats pass the end"); - if (fc / 2 != p1) + var pairs = new Vector2[fc / 2]; + for (int i = 0; i < pairs.Length; i++) { - Tokens(record, ref pos, p1, fc / 2, false); + pairs[i] = ReadUv(record, pairsOffset + 8 * i); } + texCoords = MapUv(record, ref pos, p1, pairs); } else if (n == -p1) { + int range = pos; Skip(record, ref pos, 16, "UV range passes the end"); + var minimum = ReadUv(record, range); + var maximum = ReadUv(record, range + 8); + if (maximum.X < minimum.X || maximum.Y < minimum.Y) + { + throw Fail("UV range maximum is below its minimum", range); + } at = pos; int w = ReadInt32(record, ref pos); int bu = w & 0xFF, bv = w >> 8; - // One width may be 0: that coordinate is constant over the record (seen in .nwd files saved by Navisworks 2026). - if (w >> 16 != 0 || (bu == 0 && bv == 0)) + if (w >> 16 != 0 || (bu == 0 && bv == 0 && minimum != maximum)) { throw Fail("UV bit widths are not two bytes with one non-zero", at); } @@ -150,12 +164,19 @@ public static GeometryRecord Parse(ReadOnlySpan record, int normalBits) throw Fail("UV value count is not in 1..p1", at); } - // UV values are not decoded: read for length only. + int packedOffset = pos; SkipPacked(record, ref pos, m, bu + bv); - if (m != p1) + var packed = record[packedOffset..pos]; + var pairs = new Vector2[m]; + long bit = 0; + for (int i = 0; i < m; i++) { - Tokens(record, ref pos, p1, m, false); + double u = ReadPackedUnit(packed, ref bit, bu); + double v = ReadPackedUnit(packed, ref bit, bv); + pairs[i] = new Vector2((float)(minimum.X + u * ((double)maximum.X - minimum.X)), + (float)(minimum.Y + v * ((double)maximum.Y - minimum.Y))); } + texCoords = MapUv(record, ref pos, p1, pairs); } else { @@ -344,11 +365,41 @@ public static GeometryRecord Parse(ReadOnlySpan record, int normalBits) Indices = indices, LineIndices = lineIndices, Normals = normals, + TexCoords = texCoords, LineColors = lines ? lineColors : null, Bounds = bounds, }; } + private static Vector2 ReadUv(ReadOnlySpan data, int offset) + { + var uv = new Vector2(BinaryPrimitives.ReadSingleLittleEndian(data[offset..]), + BinaryPrimitives.ReadSingleLittleEndian(data[(offset + 4)..])); + if (!float.IsFinite(uv.X) || !float.IsFinite(uv.Y)) throw Fail("UV is not finite", offset); + return uv; + } + + private static Vector2[] MapUv(ReadOnlySpan record, ref int pos, int count, Vector2[] pairs) => + pairs.Length == count ? pairs : Array.ConvertAll(Tokens(record, ref pos, count, pairs.Length, false), i => pairs[i]); + + private static double ReadPackedUnit(ReadOnlySpan packed, ref long bit, int width) + { + if (width == 0) return 0; + + double value = 0; + for (int remaining = width; remaining > 0;) + { + int available = 32 - (int)(bit & 31); + int take = Math.Min(remaining, available); + uint word = BinaryPrimitives.ReadUInt32LittleEndian(packed[(4 * (int)(bit >> 5))..]); + uint chunk = (word >> (available - take)) & (uint.MaxValue >> (32 - take)); + value = Math.ScaleB(value, take) + chunk; + remaining -= take; + bit += take; + } + return value / (Math.ScaleB(1, width) - 1); + } + /// /// TOKENS(count, fresh, axis), without the pad4 that follows it in a record. /// Runs introduce 0..fresh-1 once each, in order; axis codes decode to -1..-6. diff --git a/src/NwcIO/Internal/Parsing/HierarchyParser.cs b/src/NwcIO/Internal/Parsing/HierarchyParser.cs index 7e2333c..1a4e25b 100644 --- a/src/NwcIO/Internal/Parsing/HierarchyParser.cs +++ b/src/NwcIO/Internal/Parsing/HierarchyParser.cs @@ -57,9 +57,9 @@ public static IReadOnlyList Read( } /// Reads a class-185 body (material JSON with embedded files, docs/format-notes.md §2.2), which the fragments stream holds too. - internal static object ReadMaterialJson(LcObjectReader reader) + internal static object ReadMaterialJson(LcObjectReader reader, bool readTexture = false) { - reader.ReadString(); + string? json = reader.ReadString(); reader.ReadString(); int count = reader.ReadCount(12); for (int i = 0; i < count; i++) @@ -79,7 +79,7 @@ internal static object ReadMaterialJson(LcObjectReader reader) } } - return Dropped; + return readTexture && MaterialTextureParser.ReadDiffusePath(json) is { } path ? path : Dropped; } // IFC_GUID (-1019000) of the element's own tab, when it has the IFC form: 22 characters of the IFC alphabet, the first 0-3 (128 bits). diff --git a/src/NwcIO/Internal/Parsing/LcObjectReader.cs b/src/NwcIO/Internal/Parsing/LcObjectReader.cs index 219f1ea..c08605b 100644 --- a/src/NwcIO/Internal/Parsing/LcObjectReader.cs +++ b/src/NwcIO/Internal/Parsing/LcObjectReader.cs @@ -35,6 +35,16 @@ public LcObjectReader(byte[] data, string segment) public int ReadInt32() => BinaryPrimitives.ReadInt32LittleEndian(Take(4, "i32")); + public bool TryReadSharedIndex(out int index) + { + if (BinaryPrimitives.TryReadInt32LittleEndian(_data.AsSpan(Position), out index) && index is >= 2 and < FirstId) + { + Position += 4; + return true; + } + return false; + } + public float ReadSingle() => BinaryPrimitives.ReadSingleLittleEndian(Take(4, "f32")); public double ReadDouble() diff --git a/src/NwcIO/Internal/Parsing/MaterialTextureParser.cs b/src/NwcIO/Internal/Parsing/MaterialTextureParser.cs new file mode 100644 index 0000000..e69f10f --- /dev/null +++ b/src/NwcIO/Internal/Parsing/MaterialTextureParser.cs @@ -0,0 +1,79 @@ +using System.Text.Json; +using NwcIO.Model; + +namespace NwcIO.Internal.Parsing; + +internal static class MaterialTextureParser +{ + public static string? ReadDiffusePath(string? json) + { + if (string.IsNullOrEmpty(json)) return null; + + try + { + using var document = JsonDocument.Parse(json); + var root = document.RootElement; + string? rootId = SingleString(Property(root, "userassets")); + var materials = Property(root, "materials"); + if (rootId is null) return null; + + var material = Property(materials, rootId); + var diffuse = Property(Property(Property(material, "properties"), "colors"), "generic_diffuse"); + if (Property(diffuse, "IsConnectionEnabled").ValueKind != JsonValueKind.True) return null; + string? bitmapId = SingleString(Property(diffuse, "connections")); + if (bitmapId is null) return null; + + var bitmap = Property(materials, bitmapId); + var definition = Property(bitmap, "definition"); + if (definition.ValueKind != JsonValueKind.String || !definition.ValueEquals("UnifiedBitmap")) return null; + var uris = Property(Property(bitmap, "properties"), "uris"); + string? path = SingleString(Property(Property(uris, "unifiedbitmap_Bitmap"), "values")); + if (string.IsNullOrWhiteSpace(path)) return null; + + if (path.StartsWith("file:", StringComparison.OrdinalIgnoreCase) && + Uri.TryCreate(path, UriKind.Absolute, out var file) && file.IsFile && file.Host.Length == 0) + { + return file.LocalPath; + } + return path; + } + catch (JsonException) + { + // Appearance JSON is optional and the base diffuse colour is stored separately. + return null; + } + } + + public static Dictionary Index(NwcXRefTable? table) + { + var index = new Dictionary(StringComparer.Ordinal); + if (table is not null) + { + foreach (var reference in table.References) + { + if (reference.OriginalPath.Length > 0) index.TryAdd(Key(reference.OriginalPath), reference); + } + foreach (var reference in table.References) + { + if (reference.RemappedPath.Length > 0) index.TryAdd(Key(reference.RemappedPath), reference); + } + } + return index; + } + + public static NwcXRef? Resolve(string? path, Dictionary references) => + path is null ? null : references.TryGetValue(Key(path), out var reference) ? reference : new NwcXRef(path, ""); + + private static string Key(string path) + { + string key = path.Replace('\\', '/'); + return key.StartsWith("//", StringComparison.Ordinal) || key.Length >= 2 && key[1] == ':' ? key.ToUpperInvariant() : key; + } + + private static JsonElement Property(JsonElement element, string property) => + element.ValueKind == JsonValueKind.Object && element.TryGetProperty(property, out var val) ? val : default; + + private static string? SingleString(JsonElement element) => + element.ValueKind == JsonValueKind.Array && element.GetArrayLength() == 1 && element[0].ValueKind == JsonValueKind.String + ? element[0].GetString() : null; +} diff --git a/src/NwcIO/Internal/Parsing/ModelGraphReader.cs b/src/NwcIO/Internal/Parsing/ModelGraphReader.cs index 48f4071..4484f44 100644 --- a/src/NwcIO/Internal/Parsing/ModelGraphReader.cs +++ b/src/NwcIO/Internal/Parsing/ModelGraphReader.cs @@ -16,6 +16,7 @@ internal sealed record ModelSegments( IReadOnlyList GeometryChunks, LcRawStream? Toc, LcRawStream? GuidStore, + LcRawStream? SharedNodes, Func?>> PartitionProps); /// @@ -39,6 +40,7 @@ internal static class ModelGraphReader private const string FragmentsSegment = "LcOpNwdFragments"; private const string GeometrySegment = "LcOpNwdGeometry"; private const string GuidStoreSegment = "LcOpGuidStore"; + private const string SharedNodesSegment = "LcOpSharedNodes"; private const string PartitionPropsSegment = "LcOaPartitionProps"; /// The segments, or null when the container is not a model file (it then keeps the lenient path). @@ -53,7 +55,7 @@ internal static class ModelGraphReader return null; } - NwcDbCacheEntry? hierarchy = null, fragments = null, geometry = null, guidStore = null; + NwcDbCacheEntry? hierarchy = null, fragments = null, geometry = null, guidStore = null, sharedNodes = null; var props = new List(); foreach (var entry in directory.Entries) { @@ -71,6 +73,9 @@ internal static class ModelGraphReader case GuidStoreSegment: guidStore = Once(guidStore, entry, GuidStoreSegment); break; + case SharedNodesSegment: + sharedNodes = Once(sharedNodes, entry, SharedNodesSegment); + break; case PartitionPropsSegment: // Only recorded: the tree reader checks them when it needs them (docs/format-notes.md §2.2.1). props.Add(entry); @@ -87,6 +92,7 @@ internal static class ModelGraphReader var hierarchyStream = hierarchy is null ? null : SingleStream(streams, hierarchy, HierarchySegment); var fragmentsStream = fragments is null ? null : SingleStream(streams, fragments, FragmentsSegment); var guidStoreStream = guidStore is null ? null : SingleStream(streams, guidStore, GuidStoreSegment); + var sharedNodesStream = sharedNodes is null ? null : SingleStream(streams, sharedNodes, SharedNodesSegment); LcRawStream[] chunks = []; LcRawStream? toc = null; if (geometry is not null) @@ -111,12 +117,14 @@ internal static class ModelGraphReader toc.Kind = NwcStreamKind.Toc; } - return new ModelSegments(directory, hierarchyStream, fragmentsStream, chunks, toc, guidStoreStream, () => PartitionRootStreams(streams, props)); + return new ModelSegments(directory, hierarchyStream, fragmentsStream, chunks, toc, guidStoreStream, + sharedNodesStream, () => PartitionRootStreams(streams, props)); } /// The tree first, so a tree that cannot be read fails before any geometry work; then geometry, fragments and links. /// A segment breaks its grammar or a fragment breaks a link rule. - public static async ValueTask ReadAsync(ModelSegments segments, NwcReaderOptions options, string rootName, CancellationToken cancellationToken) + public static async ValueTask ReadAsync(ModelSegments segments, NwcReaderOptions options, string rootName, + NwcXRefTable? xRefs, CancellationToken cancellationToken) { // The tree needs the table for element GUIDs whatever ReadGuids says. Guid[] guids = segments.GuidStore is not null && (options.ReadGuids || (options.BuildSceneTree && segments.Hierarchy is not null)) @@ -133,7 +141,8 @@ public static async ValueTask ReadAsync(ModelSegments segments, NwcR var meshes = new List(); var transforms = new List(); var materials = new List(); - var materialsByKey = new Dictionary<(string, byte, byte, byte, byte), NwcMaterial>(); + var materialsByKey = new Dictionary<(string, byte, byte, byte, byte, NwcXRef?), NwcMaterial>(); + var references = MaterialTextureParser.Index(xRefs); if ((options.ReadMeshes || options.ReadTransforms) && (segments.Toc is not null || segments.Fragments is not null)) { if (segments.Toc is null) @@ -142,7 +151,9 @@ public static async ValueTask ReadAsync(ModelSegments segments, NwcR } var records = await GeometrySegmentReader.ReadAsync(segments.GeometryChunks, segments.Toc, cancellationToken).ConfigureAwait(false); - Fragment[] fragments = segments.Fragments is null ? [] : FragmentParser.Read(await segments.Fragments.GetDataAsync().ConfigureAwait(false)); + byte[]? sharedNodes = segments.SharedNodes is null ? null : await segments.SharedNodes.GetDataAsync().ConfigureAwait(false); + Fragment[] fragments = segments.Fragments is null ? [] : FragmentParser.Read(await segments.Fragments.GetDataAsync().ConfigureAwait(false), + sharedNodes, readTextures: options.ReadMeshes && options.ReadMaterials); CheckLinks(fragments, records, preorder); object? elementKey = null; for (int k = 0; k < fragments.Length; k++) @@ -177,6 +188,7 @@ public static async ValueTask ReadAsync(ModelSegments segments, NwcR Vertices = record.Vertices, Indices = record.Indices, Normals = record.Normals, + TexCoords = record.TexCoords, LineIndices = record.LineIndices, LineColors = record.LineColors, GeometryIndex = fragment.Record - 1, @@ -185,8 +197,8 @@ public static async ValueTask ReadAsync(ModelSegments segments, NwcR Node = leaf, ElementKey = elementKey, - // Names come from the tree, so there are no materials without it. - Material = leaf is not null && options.ReadMaterials ? MaterialOf(leaf.MaterialName, fragment.Look, materialsByKey, materials) : null, + Material = options.ReadMaterials && (leaf is not null || fragment.Look.DiffuseTexturePath is not null) + ? MaterialOf(leaf?.MaterialName, fragment.Look, references, materialsByKey, materials) : null, }; meshes.Add(mesh); if (leaf is not null) @@ -201,16 +213,24 @@ public static async ValueTask ReadAsync(ModelSegments segments, NwcR return new ModelGraph(preorder?[0], meshes, transforms, guids, materials); } - // One material per distinct (name, RGBA bytes), its id the order of first use (docs/format-notes.md §2.9). Shininess has no defined + // One material per distinct (name, RGBA bytes, texture), its id the order of first use. Shininess has no defined // PBR equivalent, so Roughness and Metallic keep their defaults. private static NwcMaterial MaterialOf( - string? name, FragmentLook look, Dictionary<(string, byte, byte, byte, byte), NwcMaterial> byKey, List materials) + string? name, FragmentLook look, Dictionary references, + Dictionary<(string, byte, byte, byte, byte, NwcXRef?), NwcMaterial> byKey, List materials) { - (string Name, byte R, byte G, byte B, byte A) key = - (string.IsNullOrEmpty(name) ? "Default" : name, Byte(look.R), Byte(look.G), Byte(look.B), Byte(1.0 - look.Transparency)); + (string Name, byte R, byte G, byte B, byte A, NwcXRef? Texture) key = + (string.IsNullOrEmpty(name) ? "Default" : name, Byte(look.R), Byte(look.G), Byte(look.B), Byte(1.0 - look.Transparency), + MaterialTextureParser.Resolve(look.DiffuseTexturePath, references)); if (!byKey.TryGetValue(key, out var material)) { - material = new NwcMaterial { Id = materials.Count, Name = key.Name, Color = new RgbaColor(key.R / 255f, key.G / 255f, key.B / 255f, key.A / 255f) }; + material = new NwcMaterial + { + Id = materials.Count, + Name = key.Name, + Color = new RgbaColor(key.R / 255f, key.G / 255f, key.B / 255f, key.A / 255f), + DiffuseTexture = key.Texture, + }; byKey.Add(key, material); materials.Add(material); } diff --git a/src/NwcIO/Internal/Parsing/XRefTableParser.cs b/src/NwcIO/Internal/Parsing/XRefTableParser.cs index f6de719..d1cfcfe 100644 --- a/src/NwcIO/Internal/Parsing/XRefTableParser.cs +++ b/src/NwcIO/Internal/Parsing/XRefTableParser.cs @@ -66,18 +66,21 @@ internal static class XRefTableParser using var doc = document; var root = doc.RootElement; + if (root.ValueKind != JsonValueKind.Object) return null; - string type = root.TryGetProperty("Type", out var typeProp) ? typeProp.GetString() ?? "" : ""; - int version = root.TryGetProperty("Version", out var verProp) && verProp.TryGetInt32(out int v) ? v : 1; - string savedFilename = root.TryGetProperty("SavedFilename", out var fileProp) ? fileProp.GetString() ?? "" : ""; + string type = GetString(root, "Type"); + int version = root.TryGetProperty("Version", out var verProp) && verProp.ValueKind == JsonValueKind.Number && + verProp.TryGetInt32(out int v) ? v : 1; + string savedFilename = GetString(root, "SavedFilename"); var references = new List(); if (root.TryGetProperty("Table", out var tableProp) && tableProp.ValueKind == JsonValueKind.Array) { foreach (var item in tableProp.EnumerateArray()) { - string orig = item.TryGetProperty("OriginalPath", out var origProp) ? origProp.GetString() ?? "" : ""; - string remap = item.TryGetProperty("RemappedPath", out var remapProp) ? remapProp.GetString() ?? "" : ""; + if (item.ValueKind != JsonValueKind.Object) continue; + string orig = GetString(item, "OriginalPath"); + string remap = GetString(item, "RemappedPath"); if (!string.IsNullOrEmpty(orig) || !string.IsNullOrEmpty(remap)) { references.Add(new NwcXRef(orig, remap)); @@ -92,4 +95,7 @@ internal static class XRefTableParser return null; } } + + private static string GetString(JsonElement element, string name) => + element.TryGetProperty(name, out var value) && value.ValueKind == JsonValueKind.String ? value.GetString() ?? "" : ""; } diff --git a/src/NwcIO/Model/NwcMaterial.cs b/src/NwcIO/Model/NwcMaterial.cs index 95306cc..65000b1 100644 --- a/src/NwcIO/Model/NwcMaterial.cs +++ b/src/NwcIO/Model/NwcMaterial.cs @@ -12,6 +12,9 @@ public sealed class NwcMaterial /// Base diffuse / albedo RGBA color. public RgbaColor Color { get; set; } = RgbaColor.White; + /// Optional diffuse image reference. The remapped path takes precedence over the original. + public NwcXRef? DiffuseTexture { get; set; } + /// PBR metallic factor [0.0 .. 1.0]. public float Metallic { get; set; } = 0.1f; diff --git a/src/NwcIO/Model/NwcMesh.cs b/src/NwcIO/Model/NwcMesh.cs index 9d89a4c..adce588 100644 --- a/src/NwcIO/Model/NwcMesh.cs +++ b/src/NwcIO/Model/NwcMesh.cs @@ -1,3 +1,5 @@ +using System.Numerics; + namespace NwcIO.Model; /// @@ -25,6 +27,9 @@ public sealed class NwcMesh /// public IReadOnlyList? Normals { get; init; } + /// One texture coordinate per vertex, when stored in the geometry record. + public IReadOnlyList? TexCoords { get; init; } + /// /// Segment index pairs into ; a closed polyline repeats its first vertex; /// empty for triangle meshes. diff --git a/src/NwcIO/NwcDocument.cs b/src/NwcIO/NwcDocument.cs index 5507587..fe228bb 100644 --- a/src/NwcIO/NwcDocument.cs +++ b/src/NwcIO/NwcDocument.cs @@ -232,6 +232,13 @@ private static async ValueTask ParseContainer( } } + NwcXRefTable? xRefs = null; + var xrefStream = container.Streams.FirstOrDefault(s => s.Kind == NwcStreamKind.XRefJson); + if (xrefStream is not null) + { + xRefs = XRefTableParser.Parse(await xrefStream.LoadAsync().ConfigureAwait(false)); + } + var transforms = new List(); var meshes = new List(); int skippedMeshRecords = 0; @@ -240,7 +247,7 @@ private static async ValueTask ParseContainer( cancellationToken.ThrowIfCancellationRequested(); if (segments is not null) { - var graph = await ModelGraphReader.ReadAsync(segments, options, rootName, cancellationToken).ConfigureAwait(false); + var graph = await ModelGraphReader.ReadAsync(segments, options, rootName, xRefs, cancellationToken).ConfigureAwait(false); transforms.AddRange(graph.Transforms); meshes.AddRange(graph.Meshes); materials.AddRange(graph.Materials); @@ -291,13 +298,6 @@ private static async ValueTask ParseContainer( materials.AddRange(MaterialParser.Parse(records, meshes, rootNode)); } - NwcXRefTable? xRefs = null; - var xrefStream = container.Streams.FirstOrDefault(s => s.Kind == NwcStreamKind.XRefJson); - if (xrefStream is not null) - { - xRefs = XRefTableParser.Parse(await xrefStream.LoadAsync().ConfigureAwait(false)); - } - var dbCache = segments?.Directory; var dbCacheStream = container.Streams.FirstOrDefault(s => s.Kind == NwcStreamKind.DbCache); if (dbCache is null && dbCacheStream is not null) diff --git a/tests/NwcIO.Tests/Fixtures/SyntheticFragments.cs b/tests/NwcIO.Tests/Fixtures/SyntheticFragments.cs index c04592b..702e3a7 100644 --- a/tests/NwcIO.Tests/Fixtures/SyntheticFragments.cs +++ b/tests/NwcIO.Tests/Fixtures/SyntheticFragments.cs @@ -3,7 +3,8 @@ namespace NwcIO.Tests; /// Class 55 [i32 1][new 54: ambient R,G,B, diffuse R,G,B, specular 0,0,0, emissive 0,0,0, Shininess, Transparency] as 14 f32. -internal sealed record Look(float R, float G, float B, float Shininess, float Transparency); +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 /// to fragment SharesGeometryOf's. SharesPoseOf back-references an earlier pose. Look writes a new appearance; @@ -55,12 +56,22 @@ public static byte[] Build(params Frag[] fragments) else { appearance[k] = w.New(55); - w.Int(1); + w.Int(look.EditedMaterial ? 0x71 : look.MaterialJson is not null || look.SharedMaterial.HasValue ? 33 : 1); w.New(54); foreach (float v in (float[])[look.R, look.G, look.B, look.R, look.G, look.B, 0, 0, 0, 0, 0, 0, look.Shininess, look.Transparency]) { w.Float(v); } + if (look.SharedMaterial is { } index) + { + w.Int(index); + } + else if (look.MaterialJson is { } json) + { + w.New(185); + w.Str(json).Str(null).Int(0); + } + if (look.EditedMaterial) w.Int(0); } if (f.SharesGeometryOf >= 0) diff --git a/tests/NwcIO.Tests/GeometryRecordParserTests.cs b/tests/NwcIO.Tests/GeometryRecordParserTests.cs index fa13420..079a603 100644 --- a/tests/NwcIO.Tests/GeometryRecordParserTests.cs +++ b/tests/NwcIO.Tests/GeometryRecordParserTests.cs @@ -1,4 +1,5 @@ using System.Buffers.Binary; +using System.Numerics; using NwcIO.Internal.Parsing; using NwcIO.Model; using Xunit; @@ -176,11 +177,28 @@ public void Parse_R3ClosedPolyline_DecodesSegments() public void Parse_R4RawUvSlot_ShiftsNormalIdAndDecodesAsR1() { Assert.Equal(160, FormatVectors.R4.Length); - AssertR1(GeometryRecordParser.Parse(FormatVectors.R4, 16)); + var geometry = GeometryRecordParser.Parse(FormatVectors.R4, 16); + AssertR1(geometry); + Assert.Equal([Vector2.Zero, Vector2.One, Vector2.One, Vector2.Zero], geometry.TexCoords!); } [Fact] - public void Parse_QuantisedUvSlot_DecodesAsR1() => AssertR1(GeometryRecordParser.Parse(BuildR1q(), 16)); + public void Parse_QuantisedUvSlot_DecodesAsR1() + { + var geometry = GeometryRecordParser.Parse(BuildR1q(), 16); + AssertR1(geometry); + Assert.Equal([Vector2.Zero, Vector2.One, Vector2.One, Vector2.Zero], geometry.TexCoords!); + } + + [Fact] + public void Parse_QuantisedUv_InterleavesUnequalWidthsAcrossWords() + { + byte[] record = [.. BuildR1q()[..84], .. Words([0x3E000000, 0x3E800000, 0x3F600000, 0x3F200000, 0x0108, 4]), + .. Convert.FromHexString("7F957F00000000F0"), .. BuildR1q()[120..164]]; + var geometry = GeometryRecordParser.Parse(record, 16); + AssertR1(geometry); + Assert.Equal([new Vector2(0.125f, 0.25f), new(0.875f, 0.25f), new(0.375f, 0.625f), new(0.875f, 0.625f)], geometry.TexCoords!); + } // R1q header: w at +100, m at +104 (quantised UV, docs/format-notes.md §2.6) [Theory] diff --git a/tests/NwcIO.Tests/TextureExportTests.cs b/tests/NwcIO.Tests/TextureExportTests.cs new file mode 100644 index 0000000..4ec16c4 --- /dev/null +++ b/tests/NwcIO.Tests/TextureExportTests.cs @@ -0,0 +1,97 @@ +using System.Buffers.Binary; +using System.Numerics; +using System.Text; +using System.Text.Json; +using NwcIO.Model; +using Xunit; + +namespace NwcIO.Tests; + +public class TextureExportTests +{ + private const string Appearance = """ + {"version":2,"userassets":["surface"],"materials":{ + "surface":{"definition":"Generic","properties":{"colors":{"generic_diffuse":{ + "IsConnectionEnabled":true,"connections":["bitmap"]}}}}, + "unrelated":{"definition":"UnifiedBitmap","properties":{"uris":{"unifiedbitmap_Bitmap":{"values":["wrong.png"]}}}}, + "bitmap":{"definition":"UnifiedBitmap","properties":{"uris":{"unifiedbitmap_Bitmap":{"values":["old/paint.png"]}}}} + }} + """; + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task OpenAndExport_ReadsUvAndRemappedDiffuseTexture(bool sharedAppearance) + { + var extra = new List<(string, byte[])> + { + ("LcOpXRefTable", Encoding.UTF8.GetBytes(""" + {"Type":"XRefTable","Table":[{"OriginalPath":"wrong.png","RemappedPath":"wrong-2.png"}, + {"OriginalPath":"old\\paint.png","RemappedPath":"maps/paint color.png"}]} + """)), + }; + var look = new Look(1, 1, 1, 0, 0, MaterialJson: Appearance); + if (sharedAppearance) + { + var shared = new LcGraphWriter().Int(3); + for (int i = 0; i < 3; i++) + { + shared.New(185); + shared.Str(i == 2 ? Appearance : null).Str(null).Int(0); + } + extra.Add(("LcOpSharedNodes", shared.ToArray())); + look = look with { MaterialJson = null, SharedMaterial = 2, EditedMaterial = true }; + } + + var fragments = SyntheticFragments.Build(new Frag(2, Vector3d.Zero, 1, 2, 4, Rec: 1, Look: look), + new Frag(7, Vector3d.Zero, 1, 2, 4, Rec: 2, Look: look)); + byte[] data = SyntheticNwcFile.Build(FormatVectors.H1, fragments, [[.. FormatVectors.R4, .. FormatVectors.R1]], + [FormatVectors.R4.Length, FormatVectors.R1.Length], extraStreams: extra); + var doc = NwcDocument.Open(new MemoryStream(data)); + Assert.Equal([Vector2.Zero, Vector2.One, Vector2.One, Vector2.Zero], doc.Meshes[0].TexCoords); + Assert.Null(doc.Meshes[1].TexCoords); + Assert.Same(doc.XRefs!.References[1], doc.Meshes[0].Material!.DiffuseTexture); + + var directory = Directory.CreateTempSubdirectory("nwcio-textures-"); + try + { + string obj = Path.Combine(directory.FullName, "model.obj"); + await doc.SaveObjAsync(obj); + var lines = File.ReadAllLines(obj); + Assert.Contains("vt 0 0", lines); + Assert.Contains("f 1/1 2/2 3/3", lines); + Assert.Contains("f 5 6 7", lines); + Assert.Contains("map_Kd maps/paint color.png", File.ReadAllLines(Path.ChangeExtension(obj, ".mtl"))); + + using var output = new MemoryStream(); + await doc.SaveGlbAsync(output); + byte[] glb = output.ToArray(); + int jsonLength = BinaryPrimitives.ReadInt32LittleEndian(glb.AsSpan(12)); + using var json = JsonDocument.Parse(glb.AsMemory(20, jsonLength)); + var root = json.RootElement; + var textured = root.GetProperty("meshes")[0].GetProperty("primitives")[0]; + var untextured = root.GetProperty("meshes")[1].GetProperty("primitives")[0]; + int accessorIndex = textured.GetProperty("attributes").GetProperty("TEXCOORD_0").GetInt32(); + Assert.False(untextured.GetProperty("attributes").TryGetProperty("TEXCOORD_0", out _)); + var accessor = root.GetProperty("accessors")[accessorIndex]; + Assert.Equal("VEC2", accessor.GetProperty("type").GetString()); + Assert.Equal(4, accessor.GetProperty("count").GetInt32()); + var view = root.GetProperty("bufferViews")[accessor.GetProperty("bufferView").GetInt32()]; + int binOffset = 28 + jsonLength + view.GetProperty("byteOffset").GetInt32(); + Assert.Equal(0, BinaryPrimitives.ReadSingleLittleEndian(glb.AsSpan(binOffset))); + Assert.Equal(1, BinaryPrimitives.ReadSingleLittleEndian(glb.AsSpan(binOffset + 4))); + Assert.Equal(1, BinaryPrimitives.ReadSingleLittleEndian(glb.AsSpan(binOffset + 8))); + Assert.Equal(0, BinaryPrimitives.ReadSingleLittleEndian(glb.AsSpan(binOffset + 12))); + var materials = root.GetProperty("materials"); + Assert.False(materials[untextured.GetProperty("material").GetInt32()].GetProperty("pbrMetallicRoughness").TryGetProperty("baseColorTexture", out _)); + int texIndex = materials[textured.GetProperty("material").GetInt32()].GetProperty("pbrMetallicRoughness") + .GetProperty("baseColorTexture").GetProperty("index").GetInt32(); + int imageIndex = root.GetProperty("textures")[texIndex].GetProperty("source").GetInt32(); + Assert.Equal("maps/paint%20color.png", root.GetProperty("images")[imageIndex].GetProperty("uri").GetString()); + } + finally + { + directory.Delete(recursive: true); + } + } +}