From af3c253b60841d2f1c2b658defa0d65f02ae8984 Mon Sep 17 00:00:00 2001 From: mahach666 <79989386+mahach666@users.noreply.github.com> Date: Mon, 23 Nov 2026 11:17:44 +0300 Subject: [PATCH] Make expanded property reference limit configurable --- CHANGELOG.md | 4 ++ docs/getting-started.md | 8 ++++ docs/public-api.md | 4 ++ src/NwcIO.Cli/Program.cs | 21 ++++++++- src/NwcIO/Internal/Parsing/HierarchyParser.cs | 20 ++++++--- .../Internal/Parsing/ModelGraphReader.cs | 10 +++-- src/NwcIO/NwcReaderOptions.cs | 18 ++++++++ .../NwcIO.Tests/CliArgumentValidationTests.cs | 22 ++++++++++ tests/NwcIO.Tests/CliExitCodeTests.cs | 44 +++++++++++++++++++ tests/NwcIO.Tests/ModelGraphReaderTests.cs | 42 ++++++++++++++++++ 10 files changed, 181 insertions(+), 12 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 40e0b77..77306b9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,10 @@ All notable changes to the `NwcIO` library, the CLI and the `NwcIO.Scene` adapte ## [Unreleased] +### Added + +- `--max-property-refs` and `NwcReaderOptions.MaxExpandedPropertyReferences` let callers raise the expanded scene tree property reference limit for large models (#288). + ### Fixed - `NwcAssembly.ToDocument()` preserves explicit node visibility when copying the assembly tree. diff --git a/docs/getting-started.md b/docs/getting-started.md index 2cf0cb0..e76561c 100644 --- a/docs/getting-started.md +++ b/docs/getting-started.md @@ -137,6 +137,14 @@ doc.SaveHtmlViewer("interactive_site.html", new NwcHtmlViewerOptions ## CLI Usage +The DbCache scene tree reader allows 134,217,728 property and property tab references by default. +Each occurrence of a shared node contributes its references to the total. Use `--max-property-refs` with a positive +32-bit integer to change the limit for a run. A higher limit can increase memory use. + +```bash +nwcio model.nwd model.json --no-meshes --no-materials --no-transforms --max-property-refs 268435456 --report +``` + Run standard coordination and export tasks from your terminal or CI/CD pipelines. Except `--report`, the commands below use frozen features (bug fixes only): ```bash diff --git a/docs/public-api.md b/docs/public-api.md index c84e535..79ebd23 100644 --- a/docs/public-api.md +++ b/docs/public-api.md @@ -33,6 +33,10 @@ The supported surface is the `NwcIO` and `NwcIO.Model.*` namespaces listed here `NwcDocument.GetLoadedPath()` returns the full path of a document opened by filename. It returns `null` for documents opened from a stream or created in memory. `NwcFileInfo.SourcePath` is the source path stored in the file. +`NwcReaderOptions.MaxExpandedPropertyReferences` caps the total references to property records and tabs across +all node occurrences in a DbCache scene tree. The default is 134,217,728. Set a positive `int` to change the limit. +Exceeding it throws `InvalidDataException` before the reader expands the tree. A higher limit can increase memory use. + `NwcDocument.Open` overloads for paths and streams accept an `IProgress` and `CancellationToken`. Cancellation is checked during container scanning and between parsing phases. A non-seekable input uses a temporary file. With `KeepStreamCatalog = false`, stream payloads diff --git a/src/NwcIO.Cli/Program.cs b/src/NwcIO.Cli/Program.cs index f7b1385..182a010 100644 --- a/src/NwcIO.Cli/Program.cs +++ b/src/NwcIO.Cli/Program.cs @@ -75,6 +75,7 @@ Matrix tolerances are in document units --catalog Include raw container stream catalog (offsets, sizes, kinds) --no-transforms Exclude 3D transform matrices from JSON export --no-tree Skip reading the scene tree and exclude it from JSON export + --max-property-refs Cap expanded scene tree property and tab references (default: 134217728) --no-indent Write compact JSON instead of pretty-printed indented JSON --bvh-stats Include Bounding Volume Hierarchy (BVH) spatial index statistics --raycast Perform 3D raycast test: "originX,originY,originZ,dirX,dirY,dirZ" @@ -168,6 +169,7 @@ internal static int Run( bool includeCatalog = false; bool includeTransforms = true; bool includeTree = true; + int? maxExpandedPropertyReferences = null; bool indent = true; bool printReport = false; @@ -212,6 +214,15 @@ internal static int Run( case "--no-tree": includeTree = false; break; + case "--max-property-refs": + if (!TryConsumeValue(args, ref i, arg, out string maxRefsValue, @err)) return 1; + if (!int.TryParse(maxRefsValue, NumberStyles.Integer, CultureInfo.InvariantCulture, out int maxRefs) || maxRefs <= 0) + { + @err.WriteLine($"Error: Invalid value '{maxRefsValue}' for {arg}. Expected an integer from 1 to 2147483647."); + return 1; + } + maxExpandedPropertyReferences = maxRefs; + break; case "--no-meshes": readMeshes = false; break; @@ -540,6 +551,10 @@ internal static int Run( BuildSceneTree = includeTree, KeepStreamCatalog = includeCatalog, }; + if (maxExpandedPropertyReferences is int limit) + { + readerOptions.MaxExpandedPropertyReferences = limit; + } if (!multipleInputs && !isDirectory && !isNwf && !isManifest) { @@ -1052,7 +1067,11 @@ int ProcessLoadedAssembly(NwcAssembly preloaded, string displayPath, string? out @err.WriteLine($"Error: Baseline file '{explicitDiffBaseline}' not found."); return 2; } - var baseDoc = NwcDocument.Open(explicitDiffBaseline, new NwcReaderOptions { BuildSceneTree = includeTree }); + var baseDoc = NwcDocument.Open(explicitDiffBaseline, new NwcReaderOptions + { + BuildSceneTree = includeTree, + MaxExpandedPropertyReferences = readerOptions.MaxExpandedPropertyReferences, + }); var diffReport = baseDoc.Compare(doc, new Model.Diff.NwcDiffOptions { GeometricTolerance = diffTolerance }); if (!string.IsNullOrEmpty(explicitDiffJsonPath)) diff --git a/src/NwcIO/Internal/Parsing/HierarchyParser.cs b/src/NwcIO/Internal/Parsing/HierarchyParser.cs index b5a57c2..d712c0f 100644 --- a/src/NwcIO/Internal/Parsing/HierarchyParser.cs +++ b/src/NwcIO/Internal/Parsing/HierarchyParser.cs @@ -13,8 +13,8 @@ internal static class HierarchyParser // shortcut: fixed cap on expanded node occurrences against crafted DAGs (real files stay near 1M); raise it if a real model needs more public const int MaxExpandedNodes = 1 << 23; - // shortcut: fixed cap on property and property-tab references copied into expanded nodes (every occurrence copies its node's lists, about 1 GiB at the cap), against crafted DAGs; raise it if a real model needs more - public const int MaxExpandedProperties = 1 << 27; + // Every occurrence copies its node's property and tab references, about 1 GiB at the default cap. + public const int DefaultMaxExpandedPropertyReferences = 1 << 27; private const string Segment = "LcOpNwdLogicalHierarchy"; private const string PropsSegment = "LcOaPartitionProps"; @@ -43,16 +43,19 @@ internal static class HierarchyParser /// Gives the LcOaPartitionProps root streams, its table of contents excluded; called once, at the first null attribute slot or /// after the hierarchy tail. It returns null, or is null, when the file has no such segment; an empty list is a segment without streams. /// + /// Caps the sum of property records and tabs across all node occurrences. /// The nodes in preorder; [0] is the synthetic root (Id 0, Name , Class "Model", Tag 0). public static IReadOnlyList Read( byte[] data, string rootName, bool includeProperties = true, IReadOnlyList? guids = null, - Func?>? partitionProps = null) + Func?>? partitionProps = null, + int maxExpandedPropertyReferences = DefaultMaxExpandedPropertyReferences) { guids ??= []; - var (top, total) = new Parser(new LcObjectReader(data, Segment), guids.Count, partitionProps ?? (() => null)).ReadStream(); + var (top, total) = new Parser(new LcObjectReader(data, Segment), guids.Count, partitionProps ?? (() => null), + maxExpandedPropertyReferences).ReadStream(); return Expand(top, rootName, total, includeProperties, guids); } @@ -238,6 +241,7 @@ private sealed class Parser { private readonly LcObjectReader _reader; private readonly int _guidCount; + private readonly int _maxExpandedPropertyReferences; // Null in a parser of one LcOaPartitionProps stream, which holds roots and no nodes. private readonly Func?>? _partitionProps; @@ -246,10 +250,12 @@ private sealed class Parser // The roots the null attribute slots take; ReadStream sets it from the header. private PartitionRoots? _roots; - public Parser(LcObjectReader reader, int guidCount, Func?>? partitionProps) + public Parser(LcObjectReader reader, int guidCount, Func?>? partitionProps, + int maxExpandedPropertyReferences = DefaultMaxExpandedPropertyReferences) { _reader = reader; _guidCount = guidCount; + _maxExpandedPropertyReferences = maxExpandedPropertyReferences; _partitionProps = partitionProps; _readBody = ReadBody; } @@ -431,9 +437,9 @@ private void SkipDoubles(int count) } // Each occurrence copies its node's tab references and records, so a small DAG over a property-heavy leaf multiplies them. - if (propertyReferences > MaxExpandedProperties) + if (propertyReferences > _maxExpandedPropertyReferences) { - throw _reader.Fail($"expanded tree exceeds {MaxExpandedProperties} property references"); + throw _reader.Fail($"expanded tree exceeds {_maxExpandedPropertyReferences} property references"); } if (height > LcObjectReader.MaxNestingDepth) diff --git a/src/NwcIO/Internal/Parsing/ModelGraphReader.cs b/src/NwcIO/Internal/Parsing/ModelGraphReader.cs index 4484f44..a0ff703 100644 --- a/src/NwcIO/Internal/Parsing/ModelGraphReader.cs +++ b/src/NwcIO/Internal/Parsing/ModelGraphReader.cs @@ -135,7 +135,8 @@ public static async ValueTask ReadAsync(ModelSegments segments, NwcR { preorder = segments.Hierarchy is null ? [new NwcNode { Id = 0, Name = rootName, Class = "Model", Tag = 0 }] - : await ReadHierarchy(segments.Hierarchy, rootName, options.ReadPropertyRecords, guids, segments.PartitionProps).ConfigureAwait(false); + : await ReadHierarchy(segments.Hierarchy, rootName, options.ReadPropertyRecords, guids, segments.PartitionProps, + options.MaxExpandedPropertyReferences).ConfigureAwait(false); } var meshes = new List(); @@ -272,12 +273,13 @@ private static Guid[] ReadGuidStore(byte[] data) private static async ValueTask> ReadHierarchy( LcRawStream hierarchy, string rootName, bool includeProperties, Guid[] guids, - Func?>> partitionProps) + Func?>> partitionProps, int maxExpandedPropertyReferences) { byte[] data = await hierarchy.GetDataAsync().ConfigureAwait(false); if (!hierarchy.RequiresAsyncRead) { - return HierarchyParser.Read(data, rootName, includeProperties, guids, () => partitionProps().GetSynchronousResult()); + return HierarchyParser.Read(data, rootName, includeProperties, guids, + () => partitionProps().GetSynchronousResult(), maxExpandedPropertyReferences); } // The hierarchy always checks the roots on a successful parse. Defer validation failures to that same point. @@ -296,7 +298,7 @@ private static async ValueTask> ReadHierarchy( { failure?.Throw(); return roots; - }); + }, maxExpandedPropertyReferences); } // The LcOaPartitionProps root streams, once the last stream, the table of contents [i32 k][k x i32 compressed length] zero-padded diff --git a/src/NwcIO/NwcReaderOptions.cs b/src/NwcIO/NwcReaderOptions.cs index ff8757e..b44a5cb 100644 --- a/src/NwcIO/NwcReaderOptions.cs +++ b/src/NwcIO/NwcReaderOptions.cs @@ -3,6 +3,8 @@ namespace NwcIO; /// Options controlling what reads and keeps. public sealed class NwcReaderOptions { + private int _maxExpandedPropertyReferences = Internal.Parsing.HierarchyParser.DefaultMaxExpandedPropertyReferences; + public static NwcReaderOptions Default { get; } = new(); /// Parse the scene-tree/property streams (default: true). @@ -58,6 +60,22 @@ public sealed class NwcReaderOptions /// public long MaxTotalDecompressedBytes { get; set; } = Internal.Container.NwcContainerReader.DefaultMaxTotalDecompressedBytes; + /// + /// Positive cap on the total property records and property tabs referenced by nodes in the expanded DbCache + /// scene tree (default: 134,217,728). Exceeding it throws before expansion. + /// Raising the cap can increase memory use. + /// + /// The assigned value is zero or negative. + public int MaxExpandedPropertyReferences + { + get => _maxExpandedPropertyReferences; + set + { + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(value); + _maxExpandedPropertyReferences = value; + } + } + /// /// Cap on the vertices of one geometry record on the lenient reader path (default: 200,000). Larger records are skipped. /// Model files read through their DbCache directory use the strict geometry parser and its own bounds. diff --git a/tests/NwcIO.Tests/CliArgumentValidationTests.cs b/tests/NwcIO.Tests/CliArgumentValidationTests.cs index 85a35e4..6ff57fa 100644 --- a/tests/NwcIO.Tests/CliArgumentValidationTests.cs +++ b/tests/NwcIO.Tests/CliArgumentValidationTests.cs @@ -64,6 +64,28 @@ public void VersionOption_PrintsVersionAndExits0() Assert.StartsWith("nwcio", out2.Trim()); } + [Theory] + [InlineData("0")] + [InlineData("-1")] + [InlineData("2147483648")] + [InlineData("1.5")] + [InlineData("abc")] + public void MaxPropertyRefs_InvalidValue_Exits1(string value) + { + var (exit, _, error) = Run("--max-property-refs", value); + Assert.Equal(1, exit); + Assert.Contains("for --max-property-refs", error); + Assert.Contains("Expected an integer", error); + } + + [Fact] + public void MaxPropertyRefs_MissingValue_Exits1() + { + var (exit, _, error) = Run("--max-property-refs", "--report"); + Assert.Equal(1, exit); + Assert.Contains("Missing argument for --max-property-refs", error); + } + [Fact] public void ValueOption_ConsumingFlagOrOption_Exits1WithError() { diff --git a/tests/NwcIO.Tests/CliExitCodeTests.cs b/tests/NwcIO.Tests/CliExitCodeTests.cs index a4f992f..05c85dc 100644 --- a/tests/NwcIO.Tests/CliExitCodeTests.cs +++ b/tests/NwcIO.Tests/CliExitCodeTests.cs @@ -70,6 +70,50 @@ public void PartitionHierarchyNwc_OpensWithAndWithoutTree() } } + [Theory] + [InlineData(false)] + [InlineData(true)] + public void MaxPropertyRefs_AppliesToInputAndDiffBaseline(bool useBaseline) + { + string root = TempRoot(); + Directory.CreateDirectory(root); + try + { + string path = Path.Combine(root, "input.nwd"); + string output = Path.Combine(root, "out.json"); + string baseline = Path.Combine(root, "baseline.nwd"); + string diff = Path.Combine(root, "diff.json"); + byte[] file = SyntheticNwcFile.Build(HierarchyParserTests.PropertyLeafHierarchy(), null, [], []); + string[] args = [path, output, "--no-meshes", "--no-materials", "--no-transforms", "--report"]; + if (useBaseline) + { + var (empty, _) = SyntheticTree.Write(1); + File.WriteAllBytes(path, SyntheticNwcFile.Build(empty, null, [], [])); + File.WriteAllBytes(baseline, file); + args = [.. args, "--diff", baseline, "--diff-json", diff]; + } + else + { + File.WriteAllBytes(path, file); + } + + string expectedOutput = useBaseline ? diff : output; + using var error = new StringWriter(); + Assert.Equal(3, NwcIO.Cli.Program.Run([.. args, "--max-property-refs", "3"], errorWriter: error)); + Assert.Contains("expanded tree exceeds 3 property references", error.ToString()); + Assert.False(File.Exists(expectedOutput)); + + using var retryError = new StringWriter(); + int exit = NwcIO.Cli.Program.Run([.. args, "--max-property-refs", "4"], errorWriter: retryError); + Assert.True(exit == 0, retryError.ToString()); + Assert.True(File.Exists(expectedOutput)); + } + finally + { + Directory.Delete(root, true); + } + } + [Fact] public void PartitionHierarchyFolder_OpensWithAndWithoutTree() { diff --git a/tests/NwcIO.Tests/ModelGraphReaderTests.cs b/tests/NwcIO.Tests/ModelGraphReaderTests.cs index 4d69f6b..4d5ec95 100644 --- a/tests/NwcIO.Tests/ModelGraphReaderTests.cs +++ b/tests/NwcIO.Tests/ModelGraphReaderTests.cs @@ -247,6 +247,48 @@ public void Open_ReadPropertyRecords_ControlsLeafProperties(bool readProperties, Assert.Equal(expected == 0 ? 0 : 1, leaf.PropertyTabs.Count); } + [Fact] + public async Task Open_ExpandedPropertyLimitCountsEachOccurrence_SyncAndAsync() + { + var shared = new TreeNode("Leaf", "Leaf", Slots: + [new HTab(new Tab("Data", "Data", "data", new Prop("Id", "id", 2, 1)))]); + var (hierarchy, _) = SyntheticTree.Write(1, new TreeNode("Group", "Group", Children: [shared, shared])); + byte[] file = SyntheticNwcFile.Build(hierarchy, null, [], []); + var options = new NwcReaderOptions { MaxExpandedPropertyReferences = 3, KeepStreamCatalog = false }; + using var input = new MemoryStream(file); + + var syncError = Assert.Throws(() => NwcDocument.Open(input, options)); + input.Position = 0; + var asyncError = await Assert.ThrowsAsync(() => NwcDocument.OpenAsync(input, options)); + Assert.Contains("expanded tree exceeds 3 property references", syncError.Message); + Assert.Equal(syncError.Message, asyncError.Message); + + options.MaxExpandedPropertyReferences = 4; + input.Position = 0; + var synchronous = NwcDocument.Open(input, options); + input.Position = 0; + var asynchronous = await NwcDocument.OpenAsync(input, options); + foreach (var document in new[] { synchronous, asynchronous }) + { + var group = Assert.Single(document.RootNode!.Children); + Assert.Equal(2, group.Children.Count); + Assert.All(group.Children, leaf => + { + Assert.Single(leaf.Properties); + Assert.Single(leaf.PropertyTabs); + }); + } + } + + [Theory] + [InlineData(0)] + [InlineData(-1)] + public void ExpandedPropertyLimitRejectsNonPositiveValues(int limit) + { + var options = new NwcReaderOptions(); + Assert.Throws(() => options.MaxExpandedPropertyReferences = limit); + } + [Fact] public void Save_StrictlyReadMeshesAndTransforms_ReopenWithSamePlacement() {