diff --git a/docs/public-api.md b/docs/public-api.md index ccd5a9f5..2465be2d 100644 --- a/docs/public-api.md +++ b/docs/public-api.md @@ -10,7 +10,7 @@ projects through `InternalsVisibleTo`. |---|---| | `RvtDocument` | Opens a file (`Open`) or a readable, seekable stream (`OpenStream`), saves a verified lossless copy (`SaveAs`), and gives the elements, project information, file metadata and category lookups. A document opened from a stream has no `SourcePath`: `SaveAs` throws `InvalidOperationException`, and printing cannot read the images it takes from the file (the title block logo and the picture of a rendering view). | | `RvtFileReader` | Lower level read that returns the `RevitFileInfo` behind a document. `Read` takes a path and `ReadStream` reads from the beginning of a readable, seekable stream, whatever its position. The stream is only read: it is never written to, shortened or closed, also when it is writable. A failure of the stream itself is thrown as the stream threw it. | -| `RvtReaderOptions` | Options of a read, including `DiagnosticOutput`, `Progress` (see below), `ResolveCurrentCopies` (keeps only the current copy of an element that several partition streams hold; default true, set it to false to decode every copy), `RaiseLimits` and `Diagnostics`. `RevitLocalizationDirectory` is `[Obsolete]` and ignored: the texts are built in. | +| `RvtReaderOptions` | Options of a read, including `DiagnosticOutput`, `Progress`, `CreatePartitionScratch`, `ResolveCurrentCopies` (keeps only the current copy of an element that several partition streams hold; default true, set it to false to decode every copy), `RaiseLimits` and `Diagnostics`. `RevitLocalizationDirectory` is `[Obsolete]` and ignored: the texts are built in. | | `RvtReadDiagnostics`, `StreamRecord`, `ReaderLimitHit` | What a read collects when `RvtReaderOptions.Diagnostics` is set: the partition and metadata streams read (stored and inflated byte sizes and member decode counts) and the streams cut by a limit. | | `RvtReadProgress` | File-reading updates delivered through `RvtReaderOptions.Progress`. | | `ExportReport`, `SkipLog`, `GeometryQualityClass`, `ElementGeometryQuality` | The machine-readable report of a run (`ToJson`), the per-element geometry quality classification and totals, and the elements an export left out; see [the export report](export-report.md). | @@ -19,6 +19,23 @@ projects through `InternalsVisibleTo`. | `BuildingStoreyCatalog`, `BuildingStorey` | `RvtDocument.GetBuildingStoreyCatalog()` lists native project building storeys in order of elevation and Revit ID. Each storey carries its ID, name and resolved elevation in internal feet. `GetStoreyId(elementId)` uses the current IFC storey rules and returns null for an unknown element or one assigned to the building itself. Obtain a new catalog after editing levels. | | `GridAxis` | `RvtDocument.GetGridAxes()` lists decoded project axes in Revit ID order. A circular or multi-segment axis has ordered analytic segments. `GridAxis.Tessellate(maxErrorFeet)` returns path points in internal feet. | +`RvtReaderOptions.CreatePartitionScratch` can return a new, empty stream for the current read. The stream must support reading, +writing and seeking. RvtIO writes inflated partition segments to it, reads them back in windows and disposes it before the read +returns or throws. Use private temporary storage outside managed memory to reduce the reader's working set. With a null factory, +segments are kept in memory. + +Exact framing is validated in both modes. Layout translation reads the partition by item and writes completed chunks to scratch +when configured. Raw element record bodies and geometry blocks are read back from their byte ranges in those chunks, including +ranges that cross chunk boundaries. A bounded whole-chunk cache serves full scans and supplies any ranges it already holds. The parser +stores decoded parameter records individually in scratch and reads them by element ID. Paged scene reads also keep the +resolved value maps used to build elements in scratch. Recovery of damaged framing and bytes +outside the layout grammar can still require a whole partition in memory. The returned document and its geometry are built in +memory. + +With a scratch factory, `ReadStream` can validate and decode an exactly framed partition stream larger than one array. +The reader also stores decoded element-record references and field vectors on pages in that stream during a scratch-backed read. +The array-size limit still applies to other streams and to compressed partitions that require the recovery scanner. + `RvtReaderOptions.Progress` observes one `RvtFileReader.Read` or `ReadStream`. The reader calls `IProgress.Report` synchronously on the thread that calls `Read` or `ReadStream`, one call at a time and in phase order, and does not catch an exception the observer throws: it ends the read and reaches the caller as it was thrown, so an observer can cancel by throwing. @@ -33,8 +50,14 @@ reports them in this order and never returns to an earlier phase. A file can ski `wide-model` (no counts) only when `PreserveWideLayout` also parses the model of the wide layout first. `class-schema` covers reading the file's own class schema, its element table records and the episode table; `r22-layout` is the rewrite that follows, which can take as long as the phases around it. -`Completed` and `Total` count partition streams (`partitions`), the streams the rewrite reads (`r22-layout`), block scan -passes (`element-blocks`) or decoded stream bytes (`parameter-stream`). `Completed` does not decrease within a phase. +`Completed` and `Total` count partition streams (`partitions`), the streams the rewrite reads (`r22-layout`), data chunks scanned +for records or names (`element-records`, `element-properties`), block scan and recovery passes +(`element-blocks`, `recover-geometry`), decoded stream bytes +(`parameter-stream`), element candidates processed (`build-model`) or completed resolution passes (`finalize-model`). +`Completed` does not decrease within a phase. +`GeometryBlocks` optionally gives the processed and queued geometry blocks within the current block pass. Such updates +repeat the pass number while the block count advances. Geometry recovery passes cover decoding blocks from the main +walk, locating additional blocks, decoding those blocks, and recovering planar wall bodies. A zero total means the reader has no work count for that update. Counts describe units within one phase. `complete` (1 of 1) is the last update of a read. diff --git a/docs/scene.md b/docs/scene.md index a44b83a9..e8128fc8 100644 --- a/docs/scene.md +++ b/docs/scene.md @@ -40,7 +40,25 @@ closed one is an `ArgumentException`. Set `RvtSceneOptions.ReadProgress` to observe the reader phases and work counts during `Read(path)`; it is the `RvtReaderOptions.Progress` of that read (see [the public API](public-api.md)), including its guarantees on order and thread. Pass an `IProgress` of your own when order matters, as `Progress` can deliver updates late and out of order. -The final reader update, `complete`, marks the end of the file read. Mesh extraction and scene mapping follow it and report nothing. +The final reader update, `complete`, marks the end of the file read. Set `RvtSceneOptions.MeshProgress` to receive completed +and total drawable element counts during mesh extraction. Updates are reported on the calling thread. An empty drawable set +reports `(0, 0)` once. Scene mapping follows mesh extraction. + +`RvtSceneOptions.CreatePartitionScratch` passes a scratch stream factory to the file reader for path and stream reads. Use it to +read inflated partitions through private temporary storage as described in the [public API](public-api.md). + +Use `ReadStream(stream, options, triangleScratch)` to keep expanded body faces, large element reference lists, resolved parameters, intermediate triangle meshes and +the scene's triangle buffers in another temporary stream. Pass an empty, readable, writable, seekable stream; the caller owns it and +keeps it open until it has finished using the returned scene. It must be separate from the input and partition scratch. +Parameter edits reuse their reserved slots in this stream. A slot moves to a larger allocation when its contents grow beyond its capacity. +Derived curve, sheet, room and instance properties are written back as each element is updated, keeping the edited parameter lists out of the managed heap between updates. +The partition scratch also holds provisional native field edits until category resolution determines which edits apply. +The archived lists also retain the first type references, the kinds of zero-ID references, the first positive creation phase, and whether a host quantity placeholder needs removal. +Geometry block indexes carry the available detail alternatives alongside symbol links. Quantity checks inspect the index before decoding geometry. +During this read, analytic mesh nodes retain the facts needed for element measurements. Shell quantities and scene tessellation read the archived polygons through the same paged face lists. +The temporary scene document keeps the resolved parameter values and omits the provenance indexes used by the compact API and IFC export. +Element records allocate storage for optional MEP, room, validated type-reference, curve driver, and instance placement facts when those facts are present. +Revit UniqueIds from creation history are formatted when their elements are mapped to the scene. Set `RvtSceneOptions.IncludeModelLinesAndReinforcement` to include straight model lines as line primitives and reinforcement with decoded bar paths as triangles. The native RVT-to-NWC tool enables this option. diff --git a/src/RvtIO.Scene/RvtSceneOptions.cs b/src/RvtIO.Scene/RvtSceneOptions.cs index ca64db1b..72d6f9a9 100644 --- a/src/RvtIO.Scene/RvtSceneOptions.cs +++ b/src/RvtIO.Scene/RvtSceneOptions.cs @@ -13,6 +13,14 @@ public sealed class RvtSceneOptions /// order and thread; the last update, complete, ends the file read, and the meshes and the scene are built after it. public IProgress? ReadProgress { get; set; } + /// Receives completed and total drawable element counts during mesh extraction, on the calling thread. + /// Starts at zero and ends when the drawable elements are processed, before mapping them into the scene. + public IProgress<(int Completed, int Total)>? MeshProgress { get; set; } + + /// Opens scratch storage for inflated partitions when the scene reader opens a file. + /// The factory follows the contract of . + public Func? CreatePartitionScratch { get; set; } + /// Includes straight model lines and reinforcement described by its centre lines. public bool IncludeModelLinesAndReinforcement { get; set; } diff --git a/src/RvtIO.Scene/RvtSceneReader.cs b/src/RvtIO.Scene/RvtSceneReader.cs index 11969605..fe599f91 100644 --- a/src/RvtIO.Scene/RvtSceneReader.cs +++ b/src/RvtIO.Scene/RvtSceneReader.cs @@ -52,7 +52,8 @@ public static RvtSceneResult Read(string path, RvtSceneOptions? options = null) if (key.Length == 0) throw new ArgumentException("The model key is empty.", nameof(options)); var readDiagnostics = new RvtReadDiagnostics(); var document = RvtDocument.Open(path, ReaderOptions(readDiagnostics, options)); - return Map(document, ElementMeshes.Extract(document, MeshOptions(options)), key, ReadDiagnostics(readDiagnostics)); + var meshes = ElementMeshes.ExtractCore(document, MeshOptions(options), null, options?.MeshProgress); + return Map(document, meshes, key, ReadDiagnostics(readDiagnostics)); } /// Reads a scene and its diagnostics from a readable, seekable RVT stream with the same @@ -66,15 +67,51 @@ public static RvtSceneResult Read(string path, RvtSceneOptions? options = null) /// is not readable or not seekable, or is closed, or /// is null or empty. /// The stream is empty, is not a compound file, or is cut or damaged. - /// A stream is longer than one array can hold, or a file with no project - /// partitions contains a source element ID above the range of document-local keys. - public static RvtSceneResult ReadStream(Stream stream, RvtSceneOptions options) + /// A stream that requires an array is longer than one array can hold, or a file + /// with no project partitions contains a source element ID above the range of document-local keys. + public static RvtSceneResult ReadStream(Stream stream, RvtSceneOptions options) => + ReadStreamCore(stream, options, null); + + /// Reads a scene and keeps its triangle buffers, intermediate faces and element parameters in a separate temporary stream. + /// The caller owns that stream and keeps it open until the scene is no longer needed. + /// The readable, seekable RVT input. + /// The options of the read, including the required model key. + /// An empty, readable, writable, seekable stream distinct from the input + /// and any partition scratch stream. Its contents are written during conversion and read while rendering or exporting the scene. + /// The triangle scratch stream is not empty or separate, or does not support + /// reading, writing and seeking. + public static RvtSceneResult ReadStream(Stream stream, RvtSceneOptions options, Stream triangleScratch) + { + ArgumentNullException.ThrowIfNull(triangleScratch); + if (ReferenceEquals(stream, triangleScratch) || !triangleScratch.CanRead || !triangleScratch.CanWrite + || !triangleScratch.CanSeek || triangleScratch.Length != 0) + throw new ArgumentException("Use a separate, empty, readable, writable, seekable triangle scratch stream.", nameof(triangleScratch)); + return ReadStreamCore(stream, options, triangleScratch); + } + + private static RvtSceneResult ReadStreamCore(Stream stream, RvtSceneOptions options, Stream? triangleScratch) { ArgumentNullException.ThrowIfNull(options); string key = RequiredKey(options); var readDiagnostics = new RvtReadDiagnostics(); - var document = RvtDocument.OpenStream(stream, ReaderOptions(readDiagnostics, options)); - return Map(document, ElementMeshes.Extract(document, MeshOptions(options)), key, ReadDiagnostics(readDiagnostics)); + var readerOptions = ReaderOptions(readDiagnostics, options); + if (triangleScratch != null && readerOptions.CreatePartitionScratch is { } createPartitionScratch) + readerOptions.CreatePartitionScratch = () => + { + var partitionScratch = createPartitionScratch(); + if (ReferenceEquals(partitionScratch, triangleScratch)) + throw new ArgumentException("Partition scratch must be separate from triangle scratch.", nameof(options)); + return partitionScratch; + }; + var scratch = triangleScratch == null ? null : new SceneMeshScratch(triangleScratch); + if (scratch != null) + { + readerOptions.ArchiveSceneGeometry = scratch.ArchiveGeometry; + readerOptions.ArchiveSceneParameters = scratch.ArchiveParameters; + } + var document = RvtDocument.OpenStream(stream, readerOptions); + var meshes = ElementMeshes.ExtractCore(document, MeshOptions(options), scratch == null ? null : scratch.Store, options.MeshProgress); + return Map(document, meshes, key, ReadDiagnostics(readDiagnostics), scratch); } private static RvtReaderOptions ReaderOptions(RvtReadDiagnostics diagnostics, RvtSceneOptions? options) @@ -85,6 +122,7 @@ private static RvtReaderOptions ReaderOptions(RvtReadDiagnostics diagnostics, Rv SeparateFacesWithDistinctOpenings = true, Diagnostics = diagnostics, Progress = options?.ReadProgress, + CreatePartitionScratch = options?.CreatePartitionScratch, }; /// The scene diagnostics of a read: read-cut for each stream a reader limit cut, then for each stream read, in @@ -124,7 +162,8 @@ internal static IEnumerable ReadDiagnostics(RvtReadDiagnostics public static RvtSceneResult Read(RvtDocument document, RvtSceneOptions? options) { ArgumentNullException.ThrowIfNull(document); - return Map(document, ElementMeshes.Extract(document, MeshOptions(options)), RequiredKey(options)); + var meshes = ElementMeshes.ExtractCore(document, MeshOptions(options), null, options?.MeshProgress); + return Map(document, meshes, RequiredKey(options)); } /// Turns an opened document into a scene with meshes the caller extracted from it, for example with @@ -155,7 +194,8 @@ private static string RequiredKey(RvtSceneOptions? options) => options?.ModelKey : throw new ArgumentException("A document has no file name: give the model key in RvtSceneOptions.ModelKey.", nameof(options)); /// The scene of the meshes of ; the element facts come from the document. - private static RvtSceneResult Map(RvtDocument document, MeshSet meshes, string modelKey, IEnumerable? diagnostics = null) + internal static RvtSceneResult Map(RvtDocument document, MeshSet meshes, string modelKey, + IEnumerable? diagnostics = null, SceneMeshScratch? scratch = null) { var scene = new SceneDocument { Title = modelKey }; scene.Models.Add(new SceneModel @@ -187,7 +227,7 @@ private static RvtSceneResult Map(RvtDocument document, MeshSet meshes, string m var symbols = new Dictionary>(); foreach (var (symbolId, symbolMeshes) in meshes.Symbols.OrderBy(symbol => symbol.Key)) - symbols[symbolId] = symbolMeshes.Select(mesh => (AddGeometry(scene, mesh, default), MaterialOf(mesh.MaterialId))).ToList(); + symbols[symbolId] = symbolMeshes.Select(mesh => (AddGeometry(scene, mesh, default, scratch), MaterialOf(mesh.MaterialId))).ToList(); var typeSets = new Dictionary(); var coverage = new Dictionary(); @@ -195,13 +235,14 @@ private static RvtSceneResult Map(RvtDocument document, MeshSet meshes, string m foreach (var mesh in meshes.Elements) { var element = document.GetElement(mesh.ElementId); + string? uniqueId = element?.UniqueId; var sceneElement = new SceneElement { Id = mesh.ElementId, ModelId = ModelId, LevelId = mesh.IsDatum ? null : storeys.GetStoreyId(mesh.ElementId), - SourceId = element?.UniqueId, - IfcGuid = element != null ? IfcGuidOf(element) : null, + SourceId = uniqueId, + IfcGuid = element != null ? IfcGuidOf(element, uniqueId) : null, Kind = SceneNodeKind.Element, Name = (mesh.Line != null || mesh.Arc != null) && string.IsNullOrWhiteSpace(element?.Name) ? "Model Lines" : element?.Name ?? string.Empty, Category = CategoryName(element), @@ -210,12 +251,12 @@ private static RvtSceneResult Map(RvtDocument document, MeshSet meshes, string m if (sceneElement.SourceId == null) withoutUniqueId++; if (element != null) { - if (AddPropertySet(scene, "Instance", "revit:instance", element.Parameters, element) is int instanceSet) + if (AddPropertySet(scene, "Instance", "revit:instance", element.ReadParameters, element) is int instanceSet) sceneElement.PropertySetIds.Add(instanceSet); if (document.GetTypeElement(element) is { } type) { if (!typeSets.TryGetValue(type.Id, out int? typeSet)) - typeSets[type.Id] = typeSet = AddPropertySet(scene, "Type", "revit:type", type.Parameters); + typeSets[type.Id] = typeSet = AddPropertySet(scene, "Type", "revit:type", type.ReadParameters); if (typeSet is int set) sceneElement.PropertySetIds.Add(set); } } @@ -277,7 +318,7 @@ private static RvtSceneResult Map(RvtDocument document, MeshSet meshes, string m foreach (var own in mesh.Meshes) scene.Instances.Add(new SceneInstance { - ElementId = mesh.ElementId, GeometryId = AddGeometry(scene, own, origin), Transform = transform, MaterialId = MaterialOf(own.MaterialId), + ElementId = mesh.ElementId, GeometryId = AddGeometry(scene, own, origin, scratch), Transform = transform, MaterialId = MaterialOf(own.MaterialId), }); } if (scene.Instances.Count > instancesBefore) withGeometry++; @@ -381,7 +422,7 @@ private static string CategoryName(Element? element) => if (DisplayText(parameter) is not { } text) continue; properties.Add(new SceneProperty { - Name = parameter.Definition?.Name ?? parameter.Id.ToString(CultureInfo.InvariantCulture), + Name = parameter.DefinitionName ?? parameter.Id.ToString(CultureInfo.InvariantCulture), Key = parameter.Id < 0 ? "revit:bip:" + parameter.Id.ToString(CultureInfo.InvariantCulture) : null, Value = SceneValue.FromText(text), }); @@ -430,13 +471,13 @@ StorageType.Double when parameter.Value is double value && parameter.SpecType is /// The IFC GlobalId Revit's IFC export gives the element: the value of its built-in IfcGUID parameter (IFC_GUID) /// when it is a valid GlobalId, else the export id of its UniqueId (the episode GUID with its last 64 bits XORed with the /// element id the UniqueId ends with) in the IFC base-64 form; null without either. - private static string? IfcGuidOf(Element element) + private static string? IfcGuidOf(Element element, string? uniqueId) { - if (element.Parameters.Where(parameter => parameter.Id == (int)BuiltInParameter.IFC_GUID) + if (element.ReadParameters.Where(parameter => parameter.Id == (int)BuiltInParameter.IFC_GUID) .Select(parameter => parameter.Value as string).FirstOrDefault(IsIfcGuid) is { } stored) return stored; // The original element id has a minimum width of eight hex digits. - if (element.UniqueId is not { Length: >= 45 and <= 53 } uniqueId || uniqueId[36] != '-' + if (uniqueId is not { Length: >= 45 and <= 53 } || uniqueId[36] != '-' || !Guid.TryParseExact(uniqueId.AsSpan(0, 36), "D", out var episode) || !long.TryParse(uniqueId.AsSpan(37), NumberStyles.AllowHexSpecifier, CultureInfo.InvariantCulture, out long originalId) || originalId < 0) @@ -465,7 +506,7 @@ private static SceneMaterial Material(RvtDocument document, int id) } /// Adds the mesh as a geometry in metres, its vertices relative to (feet). - private static int AddGeometry(SceneDocument scene, TriangleMesh mesh, MeshVector origin) + private static int AddGeometry(SceneDocument scene, TriangleMesh mesh, MeshVector origin, SceneMeshScratch? scratch) { var vertices = new Vector3d[mesh.Positions.Length / 3]; for (int vertex = 0; vertex < vertices.Length; vertex++) @@ -477,7 +518,13 @@ private static int AddGeometry(SceneDocument scene, TriangleMesh mesh, MeshVecto for (int vertex = 0; vertex < normals.Length; vertex++) normals[vertex] = new Vector3d(mesh.Normals[3 * vertex], mesh.Normals[3 * vertex + 1], mesh.Normals[3 * vertex + 2]); int id = scene.Geometries.Count + 1; - scene.Geometries.Add(new SceneGeometry { Id = id, Topology = SceneTopology.Triangles, Vertices = vertices, Indices = mesh.Indices, Normals = normals }); + scene.Geometries.Add(new SceneGeometry + { + Id = id, Topology = SceneTopology.Triangles, + Vertices = scratch == null ? vertices : scratch.Store(vertices), + Indices = scratch == null ? mesh.Indices : scratch.Store(mesh.Indices), + Normals = scratch == null ? normals : scratch.Store(normals), + }); return id; } diff --git a/src/RvtIO.Scene/SceneMeshScratch.cs b/src/RvtIO.Scene/SceneMeshScratch.cs new file mode 100644 index 00000000..d36b63ad --- /dev/null +++ b/src/RvtIO.Scene/SceneMeshScratch.cs @@ -0,0 +1,113 @@ +using System.Collections; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using RvtIO.Meshes; +using RvtIO.Model; +using RvtIO.Parsing; + +namespace RvtIO.Scene; + +/// Stores scene working data in seekable scratch while preserving the list contracts. +internal sealed class SceneMeshScratch +{ + private readonly PartitionChunks.Backing storage; + private readonly GeometryFaceStore faces; + private readonly SceneParameterScratch parameters; + private readonly Func> storeReferences; + + internal SceneMeshScratch(Stream stream) + { + storage = new(stream); + faces = new(storage); + parameters = new(storage); + storeReferences = Store; + } + + internal void ArchiveGeometry(Element element) + { + faces.Archive(element); + element.ArchiveReferences(storeReferences); + } + + internal void ArchiveParameters(Element element) => parameters.Archive(element); + + internal IReadOnlyList Store(IReadOnlyList meshes) + { + var stored = new StoredMesh[meshes.Count]; + for (int i = 0; i < meshes.Count; i++) + { + var mesh = meshes[i]; + stored[i] = new(mesh.MaterialId, Store(mesh.Positions), Store(mesh.Normals), Store(mesh.Indices)); + } + return new MeshList(stored); + } + + internal StoredArray Store(T[] values) where T : unmanaged + { + int pageSize = (64 * 1024) / Unsafe.SizeOf(); + var pages = new List(); + for (int start = 0; start < values.Length;) + { + int length = Math.Min(values.Length - start, pageSize); + pages.Add(storage.Add(MemoryMarshal.AsBytes(values.AsSpan(start, length)))); + start += length; + } + return new StoredArray(storage, pages.ToArray(), values.Length, pageSize); + } + + internal sealed class StoredArray(PartitionChunks.Backing backing, PartitionChunks.Chunk[] pages, + int count, int pageSize) : IReadOnlyList where T : unmanaged + { + public int Count => count; + + public T this[int index] + { + get + { + if ((uint)index >= (uint)Count) throw new ArgumentOutOfRangeException(nameof(index)); + return MemoryMarshal.Cast(backing.Read(pages[index / pageSize]))[index % pageSize]; + } + } + + internal T[] ReadAll() + { + var result = new T[Count]; + for (int page = 0; page < pages.Length; page++) + MemoryMarshal.Cast(backing.Read(pages[page])).CopyTo(result.AsSpan(page * pageSize)); + return result; + } + + public IEnumerator GetEnumerator() + { + foreach (var page in pages) + { + byte[] bytes = backing.Read(page); + int length = bytes.Length / Unsafe.SizeOf(); + for (int index = 0; index < length; index++) + yield return MemoryMarshal.Cast(bytes)[index]; + } + } + + IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); + } + + private readonly record struct StoredMesh(int Material, StoredArray Positions, StoredArray Normals, + StoredArray Indices) + { + internal TriangleMesh Read() => new() + { + MaterialId = Material, + Positions = Positions.ReadAll(), + Normals = Normals.ReadAll(), + Indices = Indices.ReadAll(), + }; + } + + private sealed class MeshList(StoredMesh[] meshes) : IReadOnlyList + { + public int Count => meshes.Length; + public TriangleMesh this[int index] => meshes[index].Read(); + public IEnumerator GetEnumerator() => meshes.Select(mesh => mesh.Read()).GetEnumerator(); + IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); + } +} diff --git a/src/RvtIO.Scene/SceneParameterScratch.cs b/src/RvtIO.Scene/SceneParameterScratch.cs new file mode 100644 index 00000000..3966a222 --- /dev/null +++ b/src/RvtIO.Scene/SceneParameterScratch.cs @@ -0,0 +1,238 @@ +using System.Collections; +using System.Numerics; +using System.Runtime.InteropServices; +using System.Text; +using RvtIO.Model; +using RvtIO.Parsing; + +namespace RvtIO.Scene; + +/// Keeps element parameters in scratch between construction, resolution and tessellation passes. +internal sealed class SceneParameterScratch(PartitionChunks.Backing storage) +{ + private const int DefinitionLimit = 4096; + + private enum ValueKind : byte { None, Integer, Double, Text, Boolean } + + [Flags] + private enum ParameterFlags : byte + { + ReadOnly = 1, Approximate = 2, Missing = 4, ResolvedZero = 8, Native = 16, Metadata = 32, + } + + private readonly MemoryStream output = new(64 * 1024); + private readonly PartitionChunks.Backing backing = storage; + private readonly object readLock = new(); + private readonly Dictionary<(int Id, string? Name, string? BuiltIn), int> definitionIds = new(); + private readonly List definitions = new(); + private PartitionChunks.Chunk? cached; + private Parameter[]? cachedParameters; + + internal void Archive(Element element) => element.ArchiveParameters(Store); + + private IReadOnlyList? Store(List parameters, IReadOnlyList? previous) + { + if (parameters.Any(parameter => parameter.Value is not (null or int or double or string or bool))) + return null; + + using var writer = new BinaryWriter(output, Encoding.UTF8, leaveOpen: true); + Span guidBytes = stackalloc byte[16]; + var zeroReferences = Parameter.ZeroReferenceKinds.None; + int firstPhase = -1; + bool quantityPlaceholder = false; + foreach (var parameter in parameters) + { + zeroReferences |= parameter.ClassifyZeroReference(); + if (firstPhase < 0 && parameter.Id == -1012100 && parameter.Value is int phase && phase > 0) + firstPhase = phase; + quantityPlaceholder |= Parameter.IsHostQuantityPlaceholder(parameter); + writer.Write(parameter.Id); + writer.Write7BitEncodedInt((int)parameter.StorageType); + ParameterFlags flags = 0; + if (parameter.IsReadOnly) flags |= ParameterFlags.ReadOnly; + if (parameter.IsApproximate) flags |= ParameterFlags.Approximate; + if (parameter.HasNoRevitValue) flags |= ParameterFlags.Missing; + if (parameter.HasResolvedZeroElementId) flags |= ParameterFlags.ResolvedZero; + if (parameter.FromNativeFields) flags |= ParameterFlags.Native; + if (parameter.HasSupplementalMetadata) flags |= ParameterFlags.Metadata; + writer.Write((byte)flags); + WriteValue(writer, parameter.Value); + WriteDefinition(writer, parameter.DefinitionFields); + if (!parameter.HasSupplementalMetadata) continue; + writer.Write(parameter.Guid.HasValue); + if (parameter.Guid is Guid guid) + { + guid.TryWriteBytes(guidBytes); + writer.Write(guidBytes); + } + WriteText(writer, parameter.ForgeId); + WriteText(writer, parameter.SpecType); + WriteText(writer, parameter.UnitSymbol); + writer.Write(parameter.ConversionFactor.HasValue); + if (parameter.ConversionFactor is double factor) writer.Write(factor); + writer.Write(parameter.NativeElementId.HasValue); + if (parameter.NativeElementId is long id) writer.Write(id); + } + var encoded = output.GetBuffer().AsSpan(0, checked((int)output.Length)); + var archived = previous is ParameterList prior && ReferenceEquals(prior.Owner, this) + ? prior : new ParameterList(this); + archived.Save(encoded, parameters, zeroReferences, firstPhase, quantityPlaceholder); + output.SetLength(0); + if (output.Capacity > 128 * 1024) output.Capacity = 64 * 1024; + return archived; + } + + private Parameter[] Read(PartitionChunks.Chunk block, int count) + { + lock (readLock) + { + if (ReferenceEquals(cached, block)) return cachedParameters!; + using var reader = new BinaryReader(new MemoryStream(backing.Read(block), writable: false)); + var parameters = new Parameter[count]; + Span guidBytes = stackalloc byte[16]; + for (int i = 0; i < parameters.Length; i++) + { + int id = reader.ReadInt32(); + StorageType storageType = (StorageType)reader.Read7BitEncodedInt(); + var flags = (ParameterFlags)reader.ReadByte(); + object? value = ReadValue(reader); + var parameter = ReadParameter(reader); + parameter.Id = id; + parameter.StorageType = storageType; + parameter.IsReadOnly = (flags & ParameterFlags.ReadOnly) != 0; + parameter.IsApproximate = (flags & ParameterFlags.Approximate) != 0; + parameter.Value = value; + parameter.HasNoRevitValue = (flags & ParameterFlags.Missing) != 0; + parameter.HasResolvedZeroElementId = (flags & ParameterFlags.ResolvedZero) != 0; + parameter.FromNativeFields = (flags & ParameterFlags.Native) != 0; + parameters[i] = parameter; + if ((flags & ParameterFlags.Metadata) == 0) continue; + if (reader.ReadBoolean()) + { + reader.BaseStream.ReadExactly(guidBytes); + parameter.Guid = new Guid(guidBytes); + } + parameter.ForgeId = ReadText(reader); + parameter.SpecType = ReadText(reader); + parameter.UnitSymbol = ReadText(reader); + if (reader.ReadBoolean()) parameter.ConversionFactor = reader.ReadDouble(); + if (reader.ReadBoolean()) parameter.NativeElementId = reader.ReadInt64(); + } + cached = block; + return cachedParameters = parameters; + } + } + + private void WriteDefinition(BinaryWriter writer, (int Id, string? Name, string? BuiltIn)? fields) + { + if (fields is not { } definition) + { + writer.Write7BitEncodedInt(0); + return; + } + if (definitionIds.TryGetValue(definition, out int index)) + { + writer.Write7BitEncodedInt(index + 2); + return; + } + if (definitions.Count < DefinitionLimit + && (definition.Name?.Length ?? 0) + (definition.BuiltIn?.Length ?? 0) <= 512) + { + writer.Write7BitEncodedInt(definitions.Count + 2); + definitionIds.Add(definition, definitions.Count); + definitions.Add(new Parameter.DefinitionTemplate(definition.Id, definition.Name, definition.BuiltIn)); + return; + } + writer.Write7BitEncodedInt(1); + writer.Write(definition.Id); + WriteText(writer, definition.Name); + WriteText(writer, definition.BuiltIn); + } + + private Parameter ReadParameter(BinaryReader reader) + { + int tag = reader.Read7BitEncodedInt(); + return tag switch + { + 0 => new Parameter((Parameter.DefinitionTemplate?)null), + 1 => new Parameter(new Definition { Id = reader.ReadInt32(), Name = ReadText(reader), BuiltInParameter = ReadText(reader) }), + _ => new Parameter(definitions[tag - 2]), + }; + } + + private sealed class ParameterList(SceneParameterScratch store) : Element.IArchivedParameters + { + private PartitionChunks.Chunk? block; + private int capacity; + internal SceneParameterScratch Owner => store; + public int Count { get; private set; } + public int FamilyTypeId { get; private set; } + public int FamilyAndTypeReferenceId { get; private set; } + public Parameter.ZeroReferenceKinds ZeroReferences { get; private set; } + public int FirstPositiveCreatedPhase { get; private set; } + public bool HasHostQuantityPlaceholder { get; private set; } + public Parameter this[int index] => store.Read(block!, Count)[index]; + public IEnumerator GetEnumerator() => ((IEnumerable)store.Read(block!, Count)).GetEnumerator(); + IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); + + internal void Save(ReadOnlySpan data, List parameters, Parameter.ZeroReferenceKinds zeroReferences, + int firstPhase, bool quantityPlaceholder) + { + if (block != null && data.Length <= capacity) + { + // An unchanged edit keeps its previous block and decoded cache entry. + if (Count == parameters.Count && data.SequenceEqual(store.backing.Read(block))) return; + block = store.backing.Overwrite(block, data, capacity); + } + else + { + // Grow geometrically so repeated edits keep one slot while they fit. + int nextCapacity = (int)Math.Min((uint)int.MaxValue, BitOperations.RoundUpToPowerOf2((uint)Math.Max(256, data.Length))); + block = store.backing.Add(data, nextCapacity); + capacity = nextCapacity; + } + Count = parameters.Count; + FamilyTypeId = Element.FindTypeReferenceId(parameters, includeFamilyAndType: false); + FamilyAndTypeReferenceId = Element.FindTypeReferenceId(parameters, includeFamilyAndType: true); + ZeroReferences = zeroReferences; + FirstPositiveCreatedPhase = firstPhase; + HasHostQuantityPlaceholder = quantityPlaceholder; + } + } + + private static void WriteValue(BinaryWriter writer, object? value) + { + switch (value) + { + case null: writer.Write((byte)ValueKind.None); break; + case int number: writer.Write((byte)ValueKind.Integer); writer.Write(number); break; + case double number: writer.Write((byte)ValueKind.Double); writer.Write(number); break; + case string text: writer.Write((byte)ValueKind.Text); WriteText(writer, text); break; + case bool flag: writer.Write((byte)ValueKind.Boolean); writer.Write(flag); break; + default: throw new InvalidDataException("Unsupported archived parameter value."); + } + } + + private static object? ReadValue(BinaryReader reader) => (ValueKind)reader.ReadByte() switch + { + ValueKind.None => null, + ValueKind.Integer => reader.ReadInt32(), + ValueKind.Double => reader.ReadDouble(), + ValueKind.Text => ReadText(reader), + ValueKind.Boolean => reader.ReadBoolean(), + _ => throw new InvalidDataException("Unknown archived parameter value."), + }; + + private static void WriteText(BinaryWriter writer, string? value) + { + writer.Write(value?.Length ?? -1); + if (value != null) writer.Write(MemoryMarshal.AsBytes(value.AsSpan())); + } + + private static string? ReadText(BinaryReader reader) + { + int length = reader.ReadInt32(); + return length == -1 ? null : string.Create(length, reader.BaseStream, + static (chars, stream) => stream.ReadExactly(MemoryMarshal.AsBytes(chars))); + } +} diff --git a/src/RvtIO/Diagnostics/RvtContainerCheck.cs b/src/RvtIO/Diagnostics/RvtContainerCheck.cs index 71a8a4f7..dcb2870a 100644 --- a/src/RvtIO/Diagnostics/RvtContainerCheck.cs +++ b/src/RvtIO/Diagnostics/RvtContainerCheck.cs @@ -28,7 +28,8 @@ public static void Verify(string path) using var root = OpenVerified(file, info.Name, out _, surfaceStreamFailures: false); } - internal static RootStorage OpenVerified(Stream stream, string name, out ReadOnlyStreamView view, bool surfaceStreamFailures = true) + internal static RootStorage OpenVerified(Stream stream, string name, out ReadOnlyStreamView view, + bool surfaceStreamFailures = true, bool streamPartitions = false) { ArgumentNullException.ThrowIfNull(stream); if (!stream.CanRead || !stream.CanSeek) @@ -53,7 +54,7 @@ internal static RootStorage OpenVerified(Stream stream, string name, out ReadOnl { var buffer = new byte[1 << 20]; int visited = 0; - Walk(root, "", buffer, ref visited); + Walk(root, "", buffer, ref visited, streamPartitions); return root; } catch (Exception ex) @@ -72,18 +73,26 @@ internal static RootStorage OpenVerified(Stream stream, string name, out ReadOnl // Bounds the total work when a damaged directory points several entries at the same children. private const int MaxEntries = 200_000; - private static void Walk(Storage storage, string prefix, byte[] buffer, ref int visited, int depth = 0) + internal static RvtLimitException ArrayLengthLimit(string name, long length) => + new(new ReaderLimitHit(name, "array-length", Array.MaxLength, Raisable: false, + $"stream '{name}' is {length.ToString("N0", CultureInfo.InvariantCulture)} bytes, more than the {Array.MaxLength.ToString("N0", CultureInfo.InvariantCulture)} bytes the platform holds in one array")); + + private static void Walk(Storage storage, string prefix, byte[] buffer, ref int visited, bool streamPartitions, int depth = 0) { if (depth > MaxDepth) throw new InvalidDataException($"storage nesting deeper than {MaxDepth} levels at '{prefix}'"); foreach (var entry in storage.EnumerateEntries()) { if (++visited > MaxEntries) throw new InvalidDataException($"more than {MaxEntries} directory entries"); string name = prefix + entry.Name; - if (entry.Type == EntryType.Storage) { Walk(storage.OpenStorage(entry.Name), name + "/", buffer, ref visited, depth + 1); continue; } + if (entry.Type == EntryType.Storage) + { + Walk(storage.OpenStorage(entry.Name), name + "/", buffer, ref visited, streamPartitions, depth + 1); + continue; + } if (entry.Type != EntryType.Stream) continue; - if (entry.Length > Array.MaxLength) - throw new RvtLimitException(new ReaderLimitHit(name, "array-length", Array.MaxLength, Raisable: false, - $"stream '{name}' is {entry.Length.ToString("N0", CultureInfo.InvariantCulture)} bytes, more than the {Array.MaxLength.ToString("N0", CultureInfo.InvariantCulture)} bytes the platform holds in one array")); + if (entry.Length > Array.MaxLength + && !(streamPartitions && depth == 1 && prefix.Equals("Partitions/", StringComparison.OrdinalIgnoreCase))) + throw ArrayLengthLimit(name, entry.Length); using var stream = storage.OpenStream(entry.Name); long total = 0; int read; diff --git a/src/RvtIO/Diagnostics/RvtReadProgress.cs b/src/RvtIO/Diagnostics/RvtReadProgress.cs index 45bb4743..54efe6fb 100644 --- a/src/RvtIO/Diagnostics/RvtReadProgress.cs +++ b/src/RvtIO/Diagnostics/RvtReadProgress.cs @@ -4,4 +4,8 @@ namespace RvtIO; /// The machine-readable name of the current reader phase. /// Completed units of work within the phase. /// Units of work in that phase, or zero when no count is available. -public readonly record struct RvtReadProgress(string Phase, long Completed = 0, long Total = 0); +public readonly record struct RvtReadProgress(string Phase, long Completed = 0, long Total = 0) +{ + /// The number of geometry blocks processed and queued in the current pass, when available. + public (int Completed, int Total)? GeometryBlocks { get; init; } +} diff --git a/src/RvtIO/Geometry/BrepMeasures.cs b/src/RvtIO/Geometry/BrepMeasures.cs index 398c3c2f..e755d94f 100644 --- a/src/RvtIO/Geometry/BrepMeasures.cs +++ b/src/RvtIO/Geometry/BrepMeasures.cs @@ -89,9 +89,10 @@ internal static List ShellsOfCurrent(GeometryData? geometry, HashSet<(long X, long Y, long Z)>? splitVertices = null) { var result = new List(); - if (geometry?.Faces is not { Count: > 0 } faces) return result; - IEnumerable<(List Faces, bool Closed)> shells = geometry.BrepSolids is { Count: > 0 } solids - ? solids.Select(solid => (solid.FaceIndices.Where(i => (uint)i < (uint)faces.Count).Select(i => faces[i]).ToList(), solid.IsClosed)) + if (geometry?.ReadFaces is not { Count: > 0 } faces) return result; + IEnumerable<(IReadOnlyList Faces, bool Closed)> shells = geometry.BrepSolids is { Count: > 0 } solids + ? solids.Select(solid => ((IReadOnlyList)solid.FaceIndices.Where(i => (uint)i < (uint)faces.Count) + .Select(i => faces[i]).ToList(), solid.IsClosed)) : [(faces, false)]; foreach (var (shellFaces, closed) in shells) { @@ -112,9 +113,8 @@ internal static List ShellsOfCurrent(GeometryData? geometry, bool sourceMeasured = false; if (closed && shellFaces.Select(face => face.GeometryNode).Distinct().ToList() is [var nodeId] && geometry.NodeMeasures?.Any(measure => measure.Node == nodeId && measure.Volume < 0) != true // a cutting node has no solid to measure - && geometry.MeshNodes?.FirstOrDefault(node => node.Node == nodeId) is { SourceMeasures: { } measures } source - && shellFaces.Select(face => face.SourceFace != 0 ? face.SourceFace : face.MeshMarker).ToHashSet() - .SetEquals(source.Faces.Select(face => (uint)face.Marker))) + && geometry.TryGetMeshNodeMeasures(nodeId, + shellFaces.Select(face => face.SourceFace != 0 ? face.SourceFace : face.MeshMarker), out var measures)) { area = measures.Area; volume = measures.Volume; @@ -132,9 +132,9 @@ internal static List ShellsOfCurrent(GeometryData? geometry, if (geometry is not { UntriangulatedFaces: 0, BrepSolids: [{ IsClosed: true } solid], NodeMeasures: [{ Node: > 0, Volume: > 0 } measure] } || !double.IsFinite(measure.Volume) - || solid.FaceIndices.Count != geometry.Faces.Count - || geometry.Faces.Any(face => face.CurvedSurface || face.GeometryNode != measure.Node) - || !FacetedShell.TryOrientExactFacetedShell(geometry.Faces, solid.FaceIndices, + || solid.FaceIndices.Count != geometry.ReadFaces.Count + || geometry.ReadFaces.Any(face => face.CurvedSurface || face.GeometryNode != measure.Node) + || !FacetedShell.TryOrientExactFacetedShell(geometry.ReadFaces, solid.FaceIndices, out var faces, out geometricVolume, triangulateNonPlanarFaces: false)) return null; return new ShellInfo(faces, Closed: true, measure.Volume, measure.Area); @@ -216,10 +216,10 @@ internal static (ShellPrism Prism, double Volume)? MeasuredPlanarPrism(GeometryD /// (a cutting node, whose measure has a negative volume, is not taken). Null unless every node of the geometry has its integrals. internal static (double Volume, double Area)? NodeSolidTotalsCurrent(GeometryData? geometry) { - if (geometry?.NodeMeasures is not { Count: > 0 } measures || geometry.Faces.Count == 0) return null; + if (geometry?.NodeMeasures is not { Count: > 0 } measures || geometry.ReadFaces.Count == 0) return null; var byNode = new Dictionary(); foreach (var measure in measures) byNode.TryAdd(measure.Node, measure); - if (geometry.Faces.Any(face => face.GeometryNode > 0 && !byNode.ContainsKey(face.GeometryNode))) return null; + if (geometry.ReadFaces.Any(face => face.GeometryNode > 0 && !byNode.ContainsKey(face.GeometryNode))) return null; var taken = byNode.Values.Where(measure => measure.Volume > 0).ToList(); if (taken.Count == 0) return null; return (taken.Sum(measure => measure.Volume) * CubicFeetToCubicMetres, taken.Sum(measure => measure.Area) * SquareFeetToSquareMetres); diff --git a/src/RvtIO/Geometry/WallExtrusion.cs b/src/RvtIO/Geometry/WallExtrusion.cs index f259818f..95e38c54 100644 --- a/src/RvtIO/Geometry/WallExtrusion.cs +++ b/src/RvtIO/Geometry/WallExtrusion.cs @@ -38,7 +38,7 @@ internal static partial class WallExtrusion internal static bool? IsStandardCaseBody(GeometryData? geometry, Parsing.TfBlockDeserializer.OwnWallHelperInput? helper = null, double? trimmedAxisLength = null) { - if (geometry?.Faces is not { Count: > 0 } faces || faces.Any(face => face.OuterVertices is not { Count: >= 3 })) return null; + if (geometry?.ReadFaces is not { Count: > 0 } faces || faces.Any(face => face.OuterVertices is not { Count: >= 3 })) return null; var solids = geometry.BrepSolids; var first = solids is { Count: > 0 } ? solids[0].FaceIndices.Where(index => (uint)index < (uint)faces.Count).Select(index => faces[index]).ToList() @@ -63,7 +63,7 @@ internal static partial class WallExtrusion if (TryFindVerticalExtrusion(first, out string reason, exactCylinders: true, edgeBounds)) return true; // (a Geometry node the face meshes cover is complete as well: every Face of it is decoded, the round ones that the dense // shell lacks included) - bool closedShell = solids is { Count: 1 } && solids[0].IsClosed || geometry.MeshNodes is { Count: 1 }; + bool closedShell = solids is { Count: 1 } && solids[0].IsClosed || geometry.MeshNodeCount == 1; return reason == "tilted-or-opening" && !closedShell; } diff --git a/src/RvtIO/Internal/BuildingStoreyResolver.cs b/src/RvtIO/Internal/BuildingStoreyResolver.cs index 9c32f50e..97b4fe22 100644 --- a/src/RvtIO/Internal/BuildingStoreyResolver.cs +++ b/src/RvtIO/Internal/BuildingStoreyResolver.cs @@ -49,7 +49,7 @@ internal int Resolve(Element elem, out bool hasOffStoreyLevel, double[]? outline // that level, in the building where no storey is that low. Element? offStoreyLevel = null; foreach (int parameterId in baseLevelParameters) - if (parameterSource.Parameters.FirstOrDefault(parameter => parameter.Id == parameterId)?.Value is int levelId) + if (parameterSource.ReadParameters.FirstOrDefault(parameter => parameter.Id == parameterId)?.Value is int levelId) { if (_storeyIds.TryGetValue(levelId, out int storeyId)) return storeyId; if (_currentProfile && offStoreyLevel == null @@ -67,7 +67,7 @@ internal int Resolve(Element elem, out bool hasOffStoreyLevel, double[]? outline // A column whose base level is a Level that is not a project storey stands in the highest storey at or // below that level, and in the building where no storey is that low. if (_currentProfile && elem.CategoryId is -2001330 or -2000100 - && parameterSource.Parameters.FirstOrDefault(parameter => parameter.Id == -1001350)?.Value is int columnBaseLevelId + && parameterSource.ReadParameters.FirstOrDefault(parameter => parameter.Id == -1001350)?.Value is int columnBaseLevelId && _elemById.TryGetValue(columnBaseLevelId, out var columnBaseLevel) && columnBaseLevel.CategoryId == -2000240) return _storeyIds.TryGetValue(columnBaseLevelId, out int baseStoreyId) ? baseStoreyId @@ -81,7 +81,7 @@ internal int Resolve(Element elem, out bool hasOffStoreyLevel, double[]? outline foreach (int parameterId in elem.CategoryId is -2000035 or -2000120 ? new[] { -1001952, -1002062, -1114000, -1001350, -1001365, -1001383, -1002063, -1001352 } : new[] { -1001952, -1002062, -1114000, -1001350, -1001365, -1001383, -1002063 }) - if (elem.Parameters.FirstOrDefault(parameter => parameter.Id == parameterId)?.Value is int assocLevelId) + if (elem.ReadParameters.FirstOrDefault(parameter => parameter.Id == parameterId)?.Value is int assocLevelId) { if (_storeyIds.TryGetValue(assocLevelId, out int assocStoreyId)) return assocStoreyId; if (offStoreyLevel == null @@ -95,7 +95,7 @@ internal int Resolve(Element elem, out bool hasOffStoreyLevel, double[]? outline } } // Try to find LEVEL_PARAM or BASE_LEVEL_PARAM in element's parameters - else foreach (var p in elem.Parameters) + else foreach (var p in elem.ReadParameters) { if (p.StorageType == StorageType.ElementId && p.Value is int refId && refId > 0) { @@ -223,11 +223,11 @@ internal static List GetBuildingStoreyLevels(IEnumerable eleme var candidates = elements .Where(element => IsProjectLevel(element) && !string.IsNullOrWhiteSpace(element.Name) - && element.Parameters.Any(parameter => parameter.Id == -1007102 + && element.ReadParameters.Any(parameter => parameter.Id == -1007102 && parameter.StorageType == StorageType.Double && parameter.Value is double elevation && double.IsFinite(elevation)) - && element.Parameters.Any(parameter => parameter.Id == -1007111 + && element.ReadParameters.Any(parameter => parameter.Id == -1007111 && parameter.StorageType == StorageType.Integer && parameter.Value is int isBuildingStory && isBuildingStory == 1)) @@ -242,7 +242,7 @@ internal static List GetBuildingStoreyLevels(IEnumerable eleme internal static double GetElevation(Element level) { // Look for LEVEL_ELEV parameter - foreach (var p in level.Parameters) + foreach (var p in level.ReadParameters) { string? pName = p.Definition?.Name; if (pName != null && pName.Contains("LEVEL_ELEV") && p.StorageType == StorageType.Double && p.Value is double d) diff --git a/src/RvtIO/Internal/ElementRecord.cs b/src/RvtIO/Internal/ElementRecord.cs index 78867434..f4558120 100644 --- a/src/RvtIO/Internal/ElementRecord.cs +++ b/src/RvtIO/Internal/ElementRecord.cs @@ -1,20 +1,64 @@ +using RvtIO.Parsing; + namespace RvtIO.Internal; internal record BipEntry(int BipId, string? BipName, int FieldType, int? Value); internal record ElementRecord { + private byte[]? _body; + private PartitionChunks.Block? _storedBody; + private ParsedFields? _fields; + private ElementRecordFieldStore? _fieldStore; + private ElementRecordFieldStore.Slice _storedFields; + + internal sealed class ParsedFields + { + internal List References = new(); + internal List BipParams = new(); + internal HashSet WritableParamIds = new(); + internal List EntryValues = new(); + } + + private ParsedFields? Fields => _fieldStore?.Read(_storedFields) ?? _fields; + + internal ParsedFields EditFields() => _fieldStore == null + ? _fields ??= new() + : throw new InvalidOperationException("Archived record fields are read-only."); + + internal void ArchiveFields(ElementRecordFieldStore store) + { + if (_fields == null) return; + _storedFields = store.Add(_fields); + _fieldStore = store; + _fields = null; + } + public uint ElemId { get; set; } - public byte[] Body { get; set; } = Array.Empty(); - public List References { get; set; } = new(); - public List BipParams { get; set; } = new(); + public byte[] Body + { + get => _body ?? _storedBody?.Read().Data ?? Array.Empty(); + set { _body = value; _storedBody = null; } + } + + internal void RetainBodyInScratch(PartitionChunks.Block stored) + { + _storedBody = stored; + _body = null; + } + public IReadOnlyList References => Fields?.References ?? (IReadOnlyList)Array.Empty(); + public IReadOnlyList BipParams + { + get => Fields?.BipParams ?? (IReadOnlyList)Array.Empty(); + init => EditFields().BipParams = value.ToList(); + } public double[]? Geometry { get; set; } public int? CategoryId { get; set; } public ushort Subclass { get; set; } - public HashSet WritableParamIds { get; set; } = new(); + internal bool IsWritable(int parameterId) => Fields?.WritableParamIds.Contains(parameterId) == true; /// All schema entry values (int32) in order. Index = field position in class hierarchy. - public List EntryValues { get; set; } = new(); + public IReadOnlyList EntryValues => Fields?.EntryValues ?? (IReadOnlyList)Array.Empty(); } internal record BaseElementFields diff --git a/src/RvtIO/Internal/ElementRecordFieldStore.cs b/src/RvtIO/Internal/ElementRecordFieldStore.cs new file mode 100644 index 00000000..e7897ab7 --- /dev/null +++ b/src/RvtIO/Internal/ElementRecordFieldStore.cs @@ -0,0 +1,88 @@ +using System.Text; +using RvtIO.Parsing; + +namespace RvtIO.Internal; + +/// Pages the decoded fields that record consumers read after the initial parse. +internal sealed class ElementRecordFieldStore(PartitionChunks.Backing backing) +{ + private const int PageBytes = 64 * 1024; + private readonly MemoryStream output = new(PageBytes); + private readonly object readLock = new(); + private Page current = new(); + private Slice last; + private ElementRecord.ParsedFields? lastFields; + + internal sealed class Page + { + internal PartitionChunks.Chunk? Chunk; + } + + internal readonly record struct Slice(Page Page, int Start); + + // The record parser is the only writer. Records already parsed can be read before it seals the page. + internal Slice Add(ElementRecord.ParsedFields fields) + { + var slice = new Slice(current, checked((int)output.Position)); + using var writer = new BinaryWriter(output, Encoding.UTF8, leaveOpen: true); + writer.Write(fields.References.Count); + foreach (uint reference in fields.References) writer.Write(reference); + writer.Write(fields.BipParams.Count); + foreach (var parameter in fields.BipParams) + { + writer.Write(parameter.BipId); + writer.Write(parameter.BipName != null); + if (parameter.BipName != null) writer.Write(parameter.BipName); + writer.Write(parameter.FieldType); + writer.Write(parameter.Value.HasValue); + if (parameter.Value is int value) writer.Write(value); + } + writer.Write(fields.WritableParamIds.Count); + foreach (int id in fields.WritableParamIds) writer.Write(id); + writer.Write(fields.EntryValues.Count); + foreach (int value in fields.EntryValues) writer.Write(value); + if (output.Length >= PageBytes) Seal(); + return slice; + } + + internal void Seal() + { + if (output.Length == 0) return; + current.Chunk = backing.Add(output.GetBuffer().AsSpan(0, checked((int)output.Length))); + current = new Page(); + output.SetLength(0); + if (output.Capacity > 2 * PageBytes) output.Capacity = PageBytes; + } + + internal ElementRecord.ParsedFields Read(Slice slice) + { + lock (readLock) + { + if (lastFields != null && last == slice) return lastFields; + byte[] bytes = slice.Page.Chunk is { } stored ? backing.Read(stored) : output.GetBuffer(); + using var reader = new BinaryReader(new MemoryStream(bytes, slice.Start, bytes.Length - slice.Start, writable: false)); + var fields = new ElementRecord.ParsedFields(); + int references = reader.ReadInt32(); + fields.References.EnsureCapacity(references); + for (int i = 0; i < references; i++) fields.References.Add(reader.ReadUInt32()); + int parameters = reader.ReadInt32(); + fields.BipParams.EnsureCapacity(parameters); + for (int i = 0; i < parameters; i++) + { + int id = reader.ReadInt32(); + string? name = reader.ReadBoolean() ? reader.ReadString() : null; + int type = reader.ReadInt32(); + int? value = reader.ReadBoolean() ? reader.ReadInt32() : null; + fields.BipParams.Add(new BipEntry(id, name, type, value)); + } + int writable = reader.ReadInt32(); + fields.WritableParamIds.EnsureCapacity(writable); + for (int i = 0; i < writable; i++) fields.WritableParamIds.Add(reader.ReadInt32()); + int entries = reader.ReadInt32(); + fields.EntryValues.EnsureCapacity(entries); + for (int i = 0; i < entries; i++) fields.EntryValues.Add(reader.ReadInt32()); + last = slice; + return lastFields = fields; + } + } +} diff --git a/src/RvtIO/Internal/ElementValueStore.cs b/src/RvtIO/Internal/ElementValueStore.cs new file mode 100644 index 00000000..9f3a61c9 --- /dev/null +++ b/src/RvtIO/Internal/ElementValueStore.cs @@ -0,0 +1,73 @@ +using System.Diagnostics.CodeAnalysis; +using System.Text; +using RvtIO.Parsing; + +namespace RvtIO.Internal; + +/// Preserves resolved value maps in source order while the elements are assembled. +internal sealed class ElementValueStore where TKey : notnull +{ + private const int PageBytes = 64 * 1024; + private readonly PartitionChunks.Backing backing; + private readonly Dictionary offsets; + private readonly List pages = []; + private readonly Func readKey; + private readonly Func readValue; + private uint lastOwner; + private Dictionary? lastValues; + + internal ElementValueStore(PartitionChunks.Backing storage, Dictionary> source, + Action writeKey, Action writeValue, + Func readKey, Func readValue) + { + backing = storage; + this.readKey = readKey; + this.readValue = readValue; + offsets = new(source.Count); + using var buffer = new MemoryStream(PageBytes); + using var writer = new BinaryWriter(buffer, Encoding.UTF8, leaveOpen: true); + foreach (var (owner, values) in source) + { + offsets.Add(owner, (pages.Count, checked((int)buffer.Position))); + writer.Write(values.Count); + foreach (var (key, value) in values) + { + writeKey(writer, key); + writeValue(writer, value); + } + if (buffer.Length >= PageBytes) FlushPage(); + // Removing the current entry does not invalidate Dictionary enumeration. + source.Remove(owner); + } + if (buffer.Length > 0) FlushPage(); + + void FlushPage() + { + pages.Add(backing.Add(buffer.GetBuffer().AsSpan(0, checked((int)buffer.Length)))); + buffer.SetLength(0); + if (buffer.Capacity > 2 * PageBytes) buffer.Capacity = PageBytes; + } + } + + internal bool TryGetValue(uint owner, [NotNullWhen(true)] out Dictionary? values) + { + if (lastValues != null && owner == lastOwner) + { + values = lastValues; + return true; + } + if (!offsets.TryGetValue(owner, out var offset)) + { + values = null; + return false; + } + byte[] bytes = backing.Read(pages[offset.Page]); + using var reader = new BinaryReader(new MemoryStream(bytes, offset.Offset, bytes.Length - offset.Offset, writable: false)); + int count = reader.ReadInt32(); + values = new(count); + for (int i = 0; i < count; i++) values.Add(readKey(reader), readValue(reader)); + lastOwner = owner; + lastValues = values; + return true; + } +} diff --git a/src/RvtIO/Internal/GRepBlockStore.cs b/src/RvtIO/Internal/GRepBlockStore.cs new file mode 100644 index 00000000..ad06ea84 --- /dev/null +++ b/src/RvtIO/Internal/GRepBlockStore.cs @@ -0,0 +1,153 @@ +using System.Collections; +using System.Diagnostics.CodeAnalysis; +using RvtIO.Parsing; + +namespace RvtIO.Internal; + +/// Keeps decoded geometry for resident reads and exact block references for scratch-backed reads. +internal sealed class GRepBlockStore : IEnumerable> +{ + [Flags] + internal enum DetailAlternatives : byte + { + Coarse = 1, Medium = 2, CoarseQuantities = 4, + } + + private readonly Dictionary entries = []; + + private readonly record struct Entry(GRepData? Resident, Replay? Stored) + { + internal List Instances => Resident?.Instances ?? Stored!.Instances; + internal int FaceCount => Resident?.Faces.Count ?? Stored!.FaceCount; + internal Rank Rank => Resident is { } geometry ? Rank.From(geometry) : Stored!.Rank; + internal DetailAlternatives Alternatives => Resident is { } geometry ? GetAlternatives(geometry) : Stored!.Alternatives; + internal GRepData Read() => Resident ?? Stored!.Read(); + } + + private sealed class Replay(PartitionChunks.Block block, uint size, GRepData decoded, bool nativeWallBody = false) + { + internal readonly Rank Rank = Rank.From(decoded); + internal readonly int FaceCount = decoded.Faces.Count; + internal readonly List Instances = decoded.Instances; + internal readonly DetailAlternatives Alternatives = GetAlternatives(decoded); + private int symbol = decoded.SymbolElemId; + private double[]? transform = decoded.InstanceTransform; + private WeakReference? cached; + + internal void MergeInstances(List source) + { + BlockParser.MergeGRepInstances(Instances, source); + if (Instances.Count == 0) return; + symbol = Instances[0].SymbolElemId; + transform = Instances[0].Transform; + Volatile.Write(ref cached, null); + } + + internal GRepData Read() + { + if (Volatile.Read(ref cached)?.TryGetTarget(out var recent) == true) return recent; + var (data, start) = block.Read(); + // This block has already contributed its diagnostics on the initial decode. + using var silenceReplay = DiagnosticSink.Use(TextWriter.Null); + var geometry = GRepParserV2.Parse(data, start, size, nativeWallBody: nativeWallBody) + ?? throw new InvalidOperationException("A previously decoded geometry block could not be read from scratch."); + geometry.Instances = Instances; + geometry.SymbolElemId = symbol; + geometry.InstanceTransform = transform; + // Repeated lookups can reuse the decoded graph while it remains reachable. + Volatile.Write(ref cached, new WeakReference(geometry)); + return geometry; + } + } + + internal readonly record struct Rank(int VertexCount, int FaceCount, bool Transformed, bool Angled, bool Mapped) + { + internal static Rank From(GRepData geometry) => new( + geometry.Faces.Sum(face => face.Vertices?.Count ?? 0), + geometry.Faces.Count, + geometry.Transform != null, + geometry.Faces.Any(face => Math.Abs(face.XVector[0]) > 0.01 && Math.Abs(face.XVector[1]) > 0.01), + geometry.Instances.Count != 0); + } + + internal GRepData this[uint id] + { + get => entries[id].Read(); + set => Set(id, value); + } + + internal int Count => entries.Count; + internal IEnumerable Keys => entries.Keys; + internal IEnumerable Values => entries.Values.Select(entry => entry.Read()); + internal bool ContainsKey(uint id) => entries.ContainsKey(id); + internal IReadOnlyList Instances(uint id) => entries[id].Instances; + internal void Clear() => entries.Clear(); + + internal void Set(uint id, GRepData value, PartitionChunks.Block? block = null, uint size = 0, + bool nativeWallBody = false) => + entries[id] = block is { } stored ? new(null, new Replay(stored, size, value, nativeWallBody)) : new(value, null); + + internal bool TryAdd(uint id, GRepData value, PartitionChunks.Block? block, uint size) => + entries.TryAdd(id, block is { } stored ? new(null, new Replay(stored, size, value)) : new(value, null)); + + internal bool TryGetValue(uint id, [NotNullWhen(true)] out GRepData? value) + { + value = entries.TryGetValue(id, out var entry) ? entry.Read() : null; + return value != null; + } + + internal bool TryGetRank(uint id, out Rank rank) + { + bool found = entries.TryGetValue(id, out var entry); + rank = found ? entry.Rank : default; + return found; + } + + private static DetailAlternatives GetAlternatives(GRepData geometry) + { + DetailAlternatives alternatives = 0; + if (geometry.Coarse != null) alternatives |= DetailAlternatives.Coarse; + if (geometry.Medium != null) alternatives |= DetailAlternatives.Medium; + if (geometry.CoarseQuantities != null) alternatives |= DetailAlternatives.CoarseQuantities; + return alternatives; + } + + /// Checks the retained detail flags and links before replaying the geometry of an element or symbol. + internal bool HasDetailAlternative(uint id, DetailAlternatives alternatives, HashSet visited) + { + if (!entries.TryGetValue(id, out var entry)) return false; + if ((entry.Alternatives & alternatives) != 0) return true; + foreach (var instance in entry.Instances) + if (instance.SymbolElemId > 0 && visited.Add((uint)instance.SymbolElemId) + && HasDetailAlternative((uint)instance.SymbolElemId, alternatives, visited)) + return true; + return false; + } + + internal void MergeInstances(uint id, List source) + { + var entry = entries[id]; + if (entry.Resident is { } resident) BlockParser.MergeGRepInstances(resident, source); + else entry.Stored!.MergeInstances(source); + } + + internal IEnumerable ReferencedSymbols() + { + foreach (var entry in entries.Values) + foreach (var instance in entry.Instances) + if (instance.SymbolElemId > 0) yield return (uint)instance.SymbolElemId; + } + + internal IEnumerable BlockOnlyCandidates(HashSet referencedSymbols) + { + foreach (var (id, entry) in entries) + if (entry.FaceCount >= 4 || referencedSymbols.Contains(id)) yield return id; + } + + public IEnumerator> GetEnumerator() + { + foreach (var (id, entry) in entries) yield return new(id, entry.Read()); + } + + IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); +} diff --git a/src/RvtIO/Internal/NativeParameterStore.cs b/src/RvtIO/Internal/NativeParameterStore.cs new file mode 100644 index 00000000..289582b9 --- /dev/null +++ b/src/RvtIO/Internal/NativeParameterStore.cs @@ -0,0 +1,186 @@ +using System.Collections; +using System.Diagnostics.CodeAnalysis; +using System.Runtime.InteropServices; +using System.Text; +using RvtIO.Model; +using RvtIO.Parsing; +using NativeParams = RvtIO.Parsing.TfBlockDeserializer.NativeParams; +using NamedParam = RvtIO.Parsing.TfBlockDeserializer.NamedParamRecord; + +namespace RvtIO.Internal; + +/// Stores decoded parameter records individually in the partition scratch stream when available. +internal sealed class NativeParameterStore : IReadOnlyDictionary +{ + private readonly Dictionary entries = []; + private readonly PartitionChunks.Backing? backing; + private readonly MemoryStream? writeBuffer; + private readonly BinaryWriter? bufferWriter; + + internal NativeParameterStore(PartitionChunks.Backing? backing) + { + this.backing = backing; + if (backing == null) return; + writeBuffer = new MemoryStream(1024); + bufferWriter = new BinaryWriter(writeBuffer, Encoding.UTF8, leaveOpen: true); + } + + private readonly record struct Entry(NativeParams? Resident, PartitionChunks.Chunk? Stored, + IReadOnlyList? Entities); + + public NativeParams this[uint id] + { + get => Read(entries[id]); + set => entries[id] = Store(value); + } + + public int Count => entries.Count; + public IEnumerable Keys => entries.Keys; + public IEnumerable Values => entries.Values.Select(Read); + public bool ContainsKey(uint id) => entries.ContainsKey(id); + internal void Clear() => entries.Clear(); + + public bool TryGetValue(uint id, [NotNullWhen(true)] out NativeParams? value) + { + value = entries.TryGetValue(id, out var entry) ? Read(entry) : null; + return value != null; + } + + public IEnumerator> GetEnumerator() + { + foreach (var (id, entry) in entries) yield return new(id, Read(entry)); + } + + IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); + + private Entry Store(NativeParams value) + { + if (backing == null) return new(value, null, null); + var bytes = writeBuffer!; + lock (bytes) + { + bytes.SetLength(0); + WriteRecord(bufferWriter!, value); + var chunk = backing.Add(bytes.GetBuffer().AsSpan(0, checked((int)bytes.Length))); + if (bytes.Capacity > 128 * 1024) + { + bytes.SetLength(0); + bytes.Capacity = 64 * 1024; + } + return new(null, chunk, value.ExtensibleStorage); + } + } + + private static void WriteRecord(BinaryWriter writer, NativeParams value) + { + writer.Write(value.RootParameterStoresComplete); + writer.Write(value.TailWalkComplete); + WriteNullableInts(writer, value.CellClasses); + WriteNullableInts(writer, value.RoofExtrusionFaceTags); + WritePairs(writer, value.Doubles, static (w, v) => w.Write(v)); + WritePairs(writer, value.Ints, static (w, v) => w.Write(v)); + WritePairs(writer, value.Strings, WriteString); + WritePairs(writer, value.ElementIds, static (w, v) => w.Write(v)); + WriteFields(writer, value.Fields, static (w, v) => w.Write(v)); + WriteFields(writer, value.DoubleFields, static (w, v) => w.Write(v)); + WriteFields(writer, value.StringFields, WriteString); + writer.Write(value.NamedParams.Count); + foreach (var entry in value.NamedParams) + { + writer.Write(entry.ParamId); + writer.Write(entry.Str != null); + if (entry.Str != null) WriteString(writer, entry.Str); + writer.Write(entry.Value); + writer.Write(entry.ElemId); + writer.Write(entry.Int); + writer.Write(entry.Instance); + writer.Write(entry.Reporting); + } + } + + private NativeParams Read(Entry entry) + { + if (entry.Resident is { } resident) return resident; + using var reader = new BinaryReader(new MemoryStream(backing!.Read(entry.Stored!), writable: false)); + var parameters = new NativeParams + { + RootParameterStoresComplete = reader.ReadBoolean(), + TailWalkComplete = reader.ReadBoolean(), + CellClasses = ReadNullableInts(reader), + ExtensibleStorage = entry.Entities, + }; + if (ReadNullableInts(reader) is { } tags) parameters.RoofExtrusionFaceTags = tags.ToHashSet(); + ReadPairs(reader, parameters.Doubles, static r => r.ReadDouble()); + ReadPairs(reader, parameters.Ints, static r => r.ReadInt32()); + ReadPairs(reader, parameters.Strings, ReadString); + ReadPairs(reader, parameters.ElementIds, static r => r.ReadInt32()); + ReadFields(reader, parameters.Fields, static r => r.ReadInt32()); + ReadFields(reader, parameters.DoubleFields, static r => r.ReadDouble()); + ReadFields(reader, parameters.StringFields, ReadString); + int count = reader.ReadInt32(); + for (int i = 0; i < count; i++) + parameters.NamedParams.Add(new NamedParam(reader.ReadInt32(), reader.ReadBoolean() ? ReadString(reader) : null, + reader.ReadDouble(), reader.ReadInt32(), reader.ReadInt32(), reader.ReadBoolean(), reader.ReadBoolean())); + return parameters; + } + + private static void WriteNullableInts(BinaryWriter writer, IReadOnlyCollection? values) + { + writer.Write(values?.Count ?? -1); + if (values == null) return; + foreach (int value in values) writer.Write(value); + } + + private static List? ReadNullableInts(BinaryReader reader) + { + int count = reader.ReadInt32(); + if (count == -1) return null; + var values = new List(count); + for (int i = 0; i < count; i++) values.Add(reader.ReadInt32()); + return values; + } + + private static void WritePairs(BinaryWriter writer, List<(int ParamId, T Value)> values, Action writeValue) + { + writer.Write(values.Count); + foreach (var (id, value) in values) + { + writer.Write(id); + writeValue(writer, value); + } + } + + private static void ReadPairs(BinaryReader reader, List<(int ParamId, T Value)> values, Func readValue) + { + int count = reader.ReadInt32(); + values.EnsureCapacity(count); + for (int i = 0; i < count; i++) values.Add((reader.ReadInt32(), readValue(reader))); + } + + private static void WriteFields(BinaryWriter writer, Dictionary fields, Action writeValue) + { + writer.Write(fields.Count); + foreach (var (name, value) in fields) + { + WriteString(writer, name); + writeValue(writer, value); + } + } + + private static void ReadFields(BinaryReader reader, Dictionary fields, Func readValue) + { + int count = reader.ReadInt32(); + fields.EnsureCapacity(count); + for (int i = 0; i < count; i++) fields.Add(ReadString(reader), readValue(reader)); + } + + internal static void WriteString(BinaryWriter writer, string value) + { + writer.Write(value.Length); + // Preserve UTF-16 code units exactly, including unpaired surrogates. + writer.Write(MemoryMarshal.AsBytes(value.AsSpan())); + } + + internal static string ReadString(BinaryReader reader) => string.Create(reader.ReadInt32(), reader.BaseStream, + static (chars, stream) => stream.ReadExactly(MemoryMarshal.AsBytes(chars))); +} diff --git a/src/RvtIO/Internal/NativeTableEffectsScratch.cs b/src/RvtIO/Internal/NativeTableEffectsScratch.cs new file mode 100644 index 00000000..90753f39 --- /dev/null +++ b/src/RvtIO/Internal/NativeTableEffectsScratch.cs @@ -0,0 +1,134 @@ +using System.Text; +using RvtIO.Model; +using RvtIO.Parsing; + +namespace RvtIO.Internal; + +/// Retains native field-table edits until categories are resolved and their domains can be checked. +internal sealed class NativeTableEffectsScratch(PartitionChunks.Backing backing) +{ + private const int PageSize = 64 * 1024; + private readonly MemoryStream output = new(PageSize); + private readonly Dictionary slices = new(ReferenceEqualityComparer.Instance); + private readonly Dictionary domainIds = new(ReferenceEqualityComparer.Instance); + private readonly List domains = []; + private Page current = new(); + + private sealed class Page + { + internal PartitionChunks.Chunk? Chunk; + } + + private readonly record struct Slice(Page Page, int Start); + private enum ValueKind : byte { None, Integer, Double, Text, Boolean } + + internal void Archive(Element element) + { + if (element.NativeTableAddedParams is not { Count: > 0 } added + || element.NativeTablePrevious?.Values.Any(value => value.Value is not (null or int or double or string or bool)) == true) + return; + var slice = new Slice(current, checked((int)output.Position)); + using var writer = new BinaryWriter(output, Encoding.UTF8, leaveOpen: true); + writer.Write(added.Count); + foreach (var row in added) + { + if (!domainIds.TryGetValue(row.Domains, out int domainId)) + { + domainId = domains.Count; + domains.Add(row.Domains); + domainIds.Add(row.Domains, domainId); + } + writer.Write(row.ParamId); + writer.Write(domainId); + writer.Write((int)row.Storage); + WriteValue(writer, row.Value); + writer.Write(row.HasNoRevitValue); + } + + writer.Write(element.NativeTableCreatedParams?.Count ?? 0); + if (element.NativeTableCreatedParams is { } created) + foreach (int id in created) writer.Write(id); + writer.Write(element.NativeTablePrevious?.Count ?? 0); + if (element.NativeTablePrevious is { } previous) + { + foreach (var (id, value) in previous) + { + writer.Write(id); + WriteValue(writer, value.Value); + writer.Write((int)value.Storage); + writer.Write(value.HasNoRevitValue); + } + } + slices.Add(element, slice); + element.NativeTableAddedParams = null; + element.NativeTableCreatedParams = null; + element.NativeTablePrevious = null; + if (output.Length >= PageSize) Seal(); + } + + internal void Seal() + { + if (output.Length == 0) return; + current.Chunk = backing.Add(output.GetBuffer().AsSpan(0, checked((int)output.Length))); + current = new Page(); + output.SetLength(0); + if (output.Capacity > 2 * PageSize) output.Capacity = PageSize; + } + + internal void Restore(Element element) + { + if (!slices.Remove(element, out var slice)) return; + byte[] bytes = backing.Read(slice.Page.Chunk!); + using var reader = new BinaryReader(new MemoryStream(bytes, slice.Start, bytes.Length - slice.Start, writable: false)); + int count = reader.ReadInt32(); + var added = new List<(int ParamId, string[] Domains, StorageType Storage, object Value, bool HasNoRevitValue)>(count); + for (int index = 0; index < count; index++) + { + int id = reader.ReadInt32(); + var domain = domains[reader.ReadInt32()]; + var storage = (StorageType)reader.ReadInt32(); + object value = ReadValue(reader) ?? throw new InvalidDataException("A native field edit has no value."); + added.Add((id, domain, storage, value, reader.ReadBoolean())); + } + element.NativeTableAddedParams = added; + + count = reader.ReadInt32(); + if (count > 0) + { + var created = new HashSet(count); + for (int index = 0; index < count; index++) created.Add(reader.ReadInt32()); + element.NativeTableCreatedParams = created; + } + count = reader.ReadInt32(); + if (count > 0) + { + var previous = new Dictionary(count); + for (int index = 0; index < count; index++) + previous.Add(reader.ReadInt32(), (ReadValue(reader), (StorageType)reader.ReadInt32(), reader.ReadBoolean())); + element.NativeTablePrevious = previous; + } + } + + private static void WriteValue(BinaryWriter writer, object? value) + { + switch (value) + { + case null: writer.Write((byte)ValueKind.None); break; + case int number: writer.Write((byte)ValueKind.Integer); writer.Write(number); break; + case double number: writer.Write((byte)ValueKind.Double); writer.Write(number); break; + case string text: writer.Write((byte)ValueKind.Text); NativeParameterStore.WriteString(writer, text); break; + case bool flag: writer.Write((byte)ValueKind.Boolean); writer.Write(flag); break; + default: throw new InvalidDataException("Unsupported native field edit value."); + } + } + + private static object? ReadValue(BinaryReader reader) => (ValueKind)reader.ReadByte() switch + { + ValueKind.None => null, + ValueKind.Integer => reader.ReadInt32(), + ValueKind.Double => reader.ReadDouble(), + ValueKind.Text => NativeParameterStore.ReadString(reader), + ValueKind.Boolean => reader.ReadBoolean(), + _ => throw new InvalidDataException("Unknown native field edit value."), + }; +} diff --git a/src/RvtIO/Internal/ParsingState.cs b/src/RvtIO/Internal/ParsingState.cs index c03c2917..5bccec90 100644 --- a/src/RvtIO/Internal/ParsingState.cs +++ b/src/RvtIO/Internal/ParsingState.cs @@ -1,9 +1,12 @@ +using System.Diagnostics.CodeAnalysis; using RvtIO.Parsing; namespace RvtIO.Internal; internal class ParsingState { + internal bool KeepExportProvenance { get; init; } = true; + internal Action? ArchiveSceneParameters { get; init; } public Dictionary? OwnPartitionWallParts { get; set; } public Dictionary OwnWallSide0Ids { get; } = new(); /// Face-history table of the first BaseWallGStep of the current own wall root (see @@ -89,17 +92,22 @@ public TfBlockDeserializer.UnitsElemOptions? OwnDocumentUnitOptions /// ElementHeader.m_categroryId of the element records the continuous walk accepted (see ); /// a null value marks an id whose records disagree or whose header could not be read. - public Dictionary HeaderCategories { get; } = new(); + public Dictionary HeaderCategories { get; private set; } = new(); // Categories proved by the current project's own framed header and a compatible root. internal Dictionary CurrentFramedCategories { get; } = new(); /// ElementHeader.m_designOptionId per element id (files with 64-bit ids; null: the records of the id disagree). - public Dictionary HeaderDesignOptions { get; } = new(); + public Dictionary HeaderDesignOptions { get; private set; } = new(); /// The axis-aligned outline the ElementHeader of the element's records stores (see ): /// a verdict when the records agree it is there or agree there is none, null when they disagree or no record was read. - public Dictionary HeaderBoundingBoxes { get; } = new(); + public Dictionary HeaderBoundingBoxes { get; private set; } = new(); + + internal void ReleaseSceneHeaderBoundingBoxes() + { + if (!KeepExportProvenance) HeaderBoundingBoxes = new(); + } /// The file's own class schema when its element ids are 64-bit (Revit 2025 layout, see ); /// null for the 32-bit layouts, which keep the shipped Revit 2022 tables. @@ -150,12 +158,55 @@ public TfBlockDeserializer.UnitsElemOptions? OwnDocumentUnitOptions public HashSet AllKnownIds { get; set; } = new(); public Dictionary> ElemStrings { get; set; } = new(); public Dictionary> ElemScanStrings { get; set; } = new(); + internal Dictionary? SceneFallbackNames { get; set; } + internal Dictionary? SceneParameterNames { get; set; } public Dictionary> ElemDoubles { get; set; } = new(); public Dictionary> ElemBipDoubles { get; set; } = new(); public Dictionary> ElemParamStrings { get; set; } = new(); public Dictionary> ElemBipInts { get; set; } = new(); + private ElementValueStore? storedBipDoubles; + private ElementValueStore? storedBipInts; + private ElementValueStore? storedParamStrings; + + internal void ArchiveElementValues() + { + if (KeepExportProvenance || PartitionScratch is not { } scratch) return; + storedBipDoubles = new(scratch, ElemBipDoubles, static (w, v) => w.Write(v), static (w, v) => w.Write(v), + static r => r.ReadInt32(), static r => r.ReadDouble()); + ElemBipDoubles = new(); + storedBipInts = new(scratch, ElemBipInts, static (w, v) => w.Write(v), static (w, v) => w.Write(v), + static r => r.ReadInt32(), static r => r.ReadInt32()); + ElemBipInts = new(); + storedParamStrings = new(scratch, ElemParamStrings, static (w, v) => w.Write(v), NativeParameterStore.WriteString, + static r => r.ReadUInt32(), NativeParameterStore.ReadString); + ElemParamStrings = new(); + } + + internal bool TryReadBipDoubles(uint owner, [NotNullWhen(true)] out Dictionary? values) => + storedBipDoubles != null ? storedBipDoubles.TryGetValue(owner, out values) : ElemBipDoubles.TryGetValue(owner, out values); + + internal bool TryReadBipInts(uint owner, [NotNullWhen(true)] out Dictionary? values) => + storedBipInts != null ? storedBipInts.TryGetValue(owner, out values) : ElemBipInts.TryGetValue(owner, out values); + + internal bool TryReadParamStrings(uint owner, [NotNullWhen(true)] out Dictionary? values) => + storedParamStrings != null ? storedParamStrings.TryGetValue(owner, out values) : ElemParamStrings.TryGetValue(owner, out values); + + internal void ReleaseElementBuildInputs() + { + SceneFallbackNames = null; + HeaderCategories = new(); + HeaderDesignOptions = new(); + ElemBaseFields = new(); + storedBipDoubles = null; + storedBipInts = null; + storedParamStrings = null; + ElemBipDoubles = new(); + ElemBipInts = new(); + ElemParamStrings = new(); + } + public Dictionary ElemBaseFields { get; set; } = new(); - public Dictionary GrepBlocks { get; set; } = new(); + public GRepBlockStore GrepBlocks { get; set; } = new(); internal Dictionary RailingQuantityInputs { get; } = new(); /// While set, the symbols placed from are taken at the Coarse detail level. @@ -168,7 +219,7 @@ public TfBlockDeserializer.UnitsElemOptions? OwnDocumentUnitOptions /// FamilySymbol.m_complexCutGeoms decoded as an exact family-local BRep. /// Kept separate from the symbol's visible GRep because it is a void operand. - public Dictionary FamilyCutGreps { get; } = new(); + public GRepBlockStore FamilyCutGreps { get; } = new(); /// FamilySymbol InsertableObj cut profiles decoded from m_pCutLoops, /// m_cutDirs and m_cutIndices. These are distinct from m_complexCutGeoms. public Dictionary> FamilyCutLoops { get; } = new(); @@ -200,9 +251,10 @@ public TfBlockDeserializer.UnitsElemOptions? OwnDocumentUnitOptions public HashSet HostCutOutStepsFromLayoutSearch { get; } = new(); public HashSet BlockOnlyIds { get; set; } = new(); public Dictionary ForgeParamDefs { get; set; } = new(); - public List Chunks { get; set; } = new(); - public List RecordChunks { get; set; } = new(); - public List NonRecordChunks { get; set; } = new(); + public IReadOnlyList Chunks { get; set; } = []; + public IReadOnlyList RecordChunks { get; set; } = []; + public IReadOnlyList NonRecordChunks { get; set; } = []; + internal PartitionChunks.Backing? PartitionScratch => (Chunks as PartitionChunks)?.Store; public Dictionary WallTypeWidths { get; set; } = new(); /// Wall function enum extracted from classIdx=0x00012100 blocks at offset 0x18. @@ -414,7 +466,7 @@ public TfBlockDeserializer.UnitsElemOptions? OwnDocumentUnitOptions /// Native parameter stores per element, deserialized from the Element base /// class m_pParamValueSet* containers (schema-driven). - public Dictionary NativeParams { get; set; } = new(); + public NativeParameterStore NativeParams { get; init; } = new(null); /// Elements whose NativeParams came from a block of their own ElemTable class (the element root). public HashSet NativeParamsFromRootClass { get; } = new(); diff --git a/src/RvtIO/Meshes/ElementMeshes.cs b/src/RvtIO/Meshes/ElementMeshes.cs index b4c9aab4..37d5c170 100644 --- a/src/RvtIO/Meshes/ElementMeshes.cs +++ b/src/RvtIO/Meshes/ElementMeshes.cs @@ -41,7 +41,12 @@ public static class ElementMeshes /// The meshes of the drawable elements of . /// is null. - public static MeshSet Extract(RvtDocument document, ElementMeshOptions? options = null) + public static MeshSet Extract(RvtDocument document, ElementMeshOptions? options = null) => + ExtractCore(document, options, null); + + internal static MeshSet ExtractCore(RvtDocument document, ElementMeshOptions? options, + Func, IReadOnlyList>? store, + IProgress<(int Completed, int Total)>? progress = null) { ArgumentNullException.ThrowIfNull(document); options ??= new ElementMeshOptions(); @@ -51,6 +56,9 @@ public static MeshSet Extract(RvtDocument document, ElementMeshOptions? options var symbolCache = new Dictionary(); var placedSymbols = new Dictionary>(); + IReadOnlyList Keep(IReadOnlyList meshes) => + store != null && meshes.Count > 0 ? store(meshes) : meshes; + bool IsMaterial(int id) => document.GetElement(id)?.CategoryId == MaterialsCategoryId; int MaterialOf(GeoFace face) { @@ -71,10 +79,10 @@ int MaterialOf(GeoFace face) if (document.GetElement(symbolId)?.Geometry is { PlacedSymbolClipped: false, PlacedSymbolBox: false } geometry) { bool ghosts = geometry.GhostNodes is { Count: > 0 }; - var (meshes, failed) = Triangulate(geometry.Faces, MaterialOf, ghosts); + var (meshes, failed) = Triangulate(geometry.ReadFaces, MaterialOf, ghosts); if (meshes.Count > 0) - symbol = new SymbolMeshes(meshes, failed + geometry.UntriangulatedFaces, geometry.UntriangulatedFaces, - DropsUntakenNodes(geometry.Faces, ghosts), geometry.Faces.Any(face => face.GeometryNode < 0), ghosts); + symbol = new SymbolMeshes(Keep(meshes), failed + geometry.UntriangulatedFaces, geometry.UntriangulatedFaces, + DropsUntakenNodes(geometry.ReadFaces, ghosts), geometry.ReadFaces.Any(face => face.GeometryNode < 0), ghosts); } symbolCache[symbolId] = symbol; return symbol; @@ -85,7 +93,7 @@ int MaterialOf(GeoFace face) { if (geometry.ExactMappedInstances is not { Count: > 0 } mapped || geometry.PlacedSymbolClipped || geometry.PlacedSymbolBox) return null; - bool dropsUntaken = DropsUntakenNodes(geometry.Faces, geometry.GhostNodes is { Count: > 0 }); + bool dropsUntaken = DropsUntakenNodes(geometry.ReadFaces, geometry.GhostNodes is { Count: > 0 }); var placements = new List(mapped.Count); int failed = 0; int untriangulatedInSymbols = 0; @@ -108,8 +116,15 @@ int MaterialOf(GeoFace face) } var elements = new List(); + var clock = progress == null ? null : System.Diagnostics.Stopwatch.StartNew(); + progress?.Report((0, drawable.Count)); foreach (var (element, body) in drawable) { + if (clock?.ElapsedMilliseconds >= 500 && elements.Count > 0) + { + progress!.Report((elements.Count, drawable.Count)); + clock.Restart(); + } if (options.IncludeModelLinesAndReinforcement && IsStairContainer(element, body, drawableIds)) { elements.Add(new ElementMesh @@ -136,7 +151,7 @@ int MaterialOf(GeoFace face) Line = line, Arc = arc, LinePairs = linePairs, - Meshes = rebar == null ? [] : [rebar], + Meshes = rebar == null ? [] : Keep([rebar]), Coverage = line != null || arc != null || linePairs != null || rebar != null ? MeshCoverage.Complete : info.WideLayoutNotRewritten ? MeshCoverage.Undecoded : MeshCoverage.NoGeometry, }); @@ -157,17 +172,18 @@ int MaterialOf(GeoFace face) }); continue; } - var (meshes, failed) = Triangulate(body.Faces, MaterialOf, body.GhostNodes is { Count: > 0 }); + var (meshes, failed) = Triangulate(body.ReadFaces, MaterialOf, body.GhostNodes is { Count: > 0 }); // A face left out of the reader's triangulation of its trim loops (see GeometryData.UntriangulatedFaces). failed += body.UntriangulatedFaces; elements.Add(new ElementMesh { ElementId = element.Id, - Meshes = meshes, + Meshes = Keep(meshes), Coverage = CoverageOf(meshes.Count > 0, body, failed, false), UntriangulatedFaces = failed, }); } + if (drawable.Count > 0) progress?.Report((drawable.Count, drawable.Count)); if (options.IncludeDatumGeometry) { var existing = elements.Select(element => element.ElementId).ToHashSet(); @@ -285,7 +301,7 @@ private static bool IsStairContainer(Element element, GeometryData? body, HashSe if (element.CategoryId is not ((int)BuiltInCategory.OST_Lines or (int)BuiltInCategory.OST_RoomSeparationLines or (int)BuiltInCategory.OST_MEPSpaceSeparationLines) || element.OwnerViewId != null || !element.RootClassIs("CurveElem") - || !element.Parameters.Any(p => p.Id == (int)BuiltInParameter.CURVE_IS_DETAIL && p.Value is 0)) + || !element.ReadParameters.Any(p => p.Id == (int)BuiltInParameter.CURVE_IS_DETAIL && p.Value is 0)) return null; return element.NativeModelArc ?? (element.Location is { CurveType: "Line" } line ? line : null); } @@ -305,7 +321,7 @@ private static bool IsStairContainer(Element element, GeometryData? body, HashSe if (!(length > 0 && double.IsFinite(length))) return null; var normal = direction / length; var origin = Pt3.From(plane.Origin); - var faces = host.Faces.Where(face => face.OuterVertices is { Count: >= 3 } loop && + var faces = host.ReadFaces.Where(face => face.OuterVertices is { Count: >= 3 } loop && loop.All(point => point.Length == 3 && Math.Abs(normal.Dot(Pt3.From(point) - origin)) <= tolerance)) .Take(2).ToArray(); if (faces.Length != 1) return null; diff --git a/src/RvtIO/Model/Element.cs b/src/RvtIO/Model/Element.cs index 082e6fe1..22211801 100644 --- a/src/RvtIO/Model/Element.cs +++ b/src/RvtIO/Model/Element.cs @@ -14,8 +14,204 @@ internal sealed record GridPlaneData(double[] Envelope, double[] Origin, double[ /// A Revit element: an instance or a type, with its identity, parameters and geometry. public class Element { - /// A copy that shares all members with this element; the caller replaces what it changes. - internal Element ShallowCopy() => (Element)MemberwiseClone(); + // Specialized tuples are absent on most elements. Boxing the present values + // keeps the empty fields reference-sized while preserving shallow-copy semantics. + private object? _mediumSolidTotals; + private object? _columnAttachment; + private object? _ownSingleFamilyCutout; + private object? _serializedAreaScheme; + + // Most parsed records carry neither drawing fields nor stair or railing data. + private DrawingData? _drawing; + + private sealed class DrawingData + { + internal string? Text; + internal double[]? TextPosition; + internal double? TextFontSizePoints; + internal int? ViewportScale; + internal int? ImageWidth; + internal int? ImageHeight; + internal double[]? ViewOrigin; + internal double[]? ViewHorizontalDirection; + internal double[]? ViewVerticalDirection; + internal double[]? ViewDirection; + internal int? ViewportViewId; + internal double[]? ViewportOffset; + + internal DrawingData ShallowCopy() => (DrawingData)MemberwiseClone(); + } + + private StairAndRailingData? _stairAndRailing; + + private sealed class StairAndRailingData + { + internal int? SerializedBaseRailingSymbolId; + internal int? SerializedStairsRailingAttrId; + internal double? SerializedRailingTopHeightFeet; + internal int? SerializedStairTypeId; + internal int? SerializedStairBaseLevelId; + internal bool SerializedStairTypeLinkIsResolved; + internal ushort? SerializedStairsTypeClassId; + internal Internal.StairComponentSource.CoreComponent[]? SerializedStairCore; + internal int[]? SerializedStairCopyLevelIds; + internal Parsing.TfBlockDeserializer.StairRunInput? SerializedStairRunInput; + internal string? ValidatedStairOccurrenceName; + internal List? SerializedStairNameParameters; + internal int? SerializedRailingStairHostId; + internal double? SerializedStairsTypeMinInsideTreadFeet; + internal double? SerializedStairRunTypeNosingFeet; + internal int? SerializedActualNumberOfRisers; + internal double? SerializedActualRiserHeightFeet; + internal double? SerializedActualTreadDepthFeet; + internal string? ValidatedStairComponentTypeName; + + internal StairAndRailingData ShallowCopy() => (StairAndRailingData)MemberwiseClone(); + } + + private WallData? _wall; + + private sealed class WallData + { + internal IReadOnlyList? OwnWallCutoutInstanceIds; + internal IReadOnlyList? OwnWallCutoutSteps; + internal double[][]? OwnWallAxisLine; + internal double[][]? OwnWallTrimmedAxis; + internal int? OwnWallCrossSection; + internal Parsing.TfBlockDeserializer.OwnWallHelperInput? OwnWallHelper; + internal double? ValidatedWallTypeThicknessFeet; + internal GeometryData? OwnPrimaryPlanarBody; + internal double[]? OwnWallSide0NormalCurrent; + internal GeometryData? OwnCurrentCutPairBodyCurrent; + internal bool? SerializedWallFlipped; + internal bool? SerializedWallJoinedToTop; + internal IReadOnlyList? SerializedWallEndJoins; + internal int? SerializedCurtainWallFunction; + internal string? SerializedCurtainWallTypeName; + internal string? SerializedBasicWallTypeName; + internal bool IsSerializedStackedWallType; + internal int? SerializedBasicWallTypeFunction; + internal int? SerializedCurtainHostId; + internal int[]? SerializedCurtainPanelOrder; + + internal WallData ShallowCopy() => (WallData)MemberwiseClone(); + } + + private MepData? _mep; + + private sealed class MepData + { + internal IReadOnlyList<(int Index, int Direction, int SystemType)>? SerializedMepConnectors; + internal IReadOnlyList<(int Index, int Direction, IReadOnlyList<(int Id, int Index, int Type)> Refs)>? SerializedConnectorGraph; + internal IReadOnlyList? SerializedConnectorSystems; + internal IReadOnlyList? SerializedConnectorModes; + internal (string Name, int TypeId)? SerializedMepSystem; + internal int? SerializedCurveSystemTypeId; + internal int? SerializedCircuitBaseEquipmentId; + internal string? ValidatedDuctTypeName; + internal string? ValidatedMepTypeName; + internal string? ValidatedMepFamilyName; + internal int? SerializedMepCurveTypeId; + + internal MepData ShallowCopy() => (MepData)MemberwiseClone(); + } + + private SpaceData? _space; + + private sealed class SpaceData + { + internal GeometryData? SerializedSpaceBoundary; + internal GeometryData? SerializedCurvedSpaceBoundary; + internal GeometryData? SerializedLiteralSpaceBoundary; + internal IReadOnlyList<(double X, double Y)>? SerializedPlanBoundary; + internal int? SerializedRoomPhaseId; + internal double? SerializedRoomPlanAreaSquareFeet; + internal int? SerializedRoomId; + internal bool? SerializedRoomIsLocationless; + internal bool? SerializedZoneIsDefault; + internal int? SerializedSpaceZoneId; + internal Dictionary? NativeRoomFields; + internal int? EnergyBuildingTypeId; + + internal SpaceData ShallowCopy() => (SpaceData)MemberwiseClone(); + } + + private TypeReferenceData? _typeReferences; + + private sealed class TypeReferenceData + { + internal int? SerializedSystemTypeId; + internal ushort? SerializedSystemTypeClassId; + internal string? ValidatedFloorTypeReferenceName; + internal string? ValidatedFloorOwnTypeName; + internal bool ValidatedFloorTypeReferenceIsExplicit; + internal bool ValidatedFloorTypeReferenceIsBlocked; + internal int? SerializedCeilingTypeId; + internal string? ValidatedCeilingTypeReferenceName; + internal bool ValidatedCeilingTypeReferenceIsExplicit; + internal bool ValidatedCeilingTypeReferenceIsBlocked; + internal string? ValidatedWindowTypeReferenceName; + internal bool ValidatedWindowTypeReferenceIsExplicit; + internal bool ValidatedWindowTypeReferenceIsBlocked; + internal string? ValidatedProxyTypeReferenceName; + internal bool ValidatedProxyTypeReferenceIsExplicit; + internal bool ValidatedProxyTypeReferenceIsBlocked; + internal string? ValidatedDistributionTypeReferenceName; + internal bool ValidatedDistributionTypeReferenceIsExplicit; + internal bool ValidatedDistributionTypeReferenceIsBlocked; + internal string? ValidatedRoofOrRailingTypeReferenceName; + internal bool ValidatedRoofOrRailingTypeReferenceIsExplicit; + internal bool ValidatedRoofOrRailingTypeReferenceIsBlocked; + internal string? ValidatedSystemFamilyName; + internal string? ValidatedCorniceTypeName; + + internal TypeReferenceData ShallowCopy() => (TypeReferenceData)MemberwiseClone(); + } + + private CurveDriverData? _curveDriver; + + private sealed class CurveDriverData + { + internal LocationCurve? NativeModelArc; + internal (double StartZ, double EndZ)? CurveDriverLineZ; + internal (double X, double Y, double Z)? CurveDriverLineDirection; + internal double? CurveDriverLineLength; + internal int? CurveDriverRefLevelId; + internal double? CurveDriverRotation; + + internal CurveDriverData ShallowCopy() => (CurveDriverData)MemberwiseClone(); + } + + private FamilyPlacementData? _familyPlacement; + + private sealed class FamilyPlacementData + { + internal (double X, double Y)? InstanceOriginXY; + internal double? InstanceOriginZ; + internal bool? InstanceUsesOffsetPosition; + internal bool? InstanceIsVertical; + internal int? NativeStructuralType; + internal (int BaseLevel, double BaseOffset, int TopLevel, double TopOffset)? FamilyLevelRefs; + internal double? FramingCopingDistance; + internal double? SymbolFramingLength; + + internal FamilyPlacementData ShallowCopy() => (FamilyPlacementData)MemberwiseClone(); + } + + /// A copy that shares member values with this element; the caller replaces what it changes. + internal Element ShallowCopy() + { + var copy = (Element)MemberwiseClone(); + copy._drawing = _drawing?.ShallowCopy(); + copy._stairAndRailing = _stairAndRailing?.ShallowCopy(); + copy._wall = _wall?.ShallowCopy(); + copy._mep = _mep?.ShallowCopy(); + copy._space = _space?.ShallowCopy(); + copy._typeReferences = _typeReferences?.ShallowCopy(); + copy._curveDriver = _curveDriver?.ShallowCopy(); + copy._familyPlacement = _familyPlacement?.ShallowCopy(); + return copy; + } /// The document-local element key used by the existing 32-bit APIs. Use /// for the ID as stored in the RVT. @@ -81,26 +277,68 @@ public class Element /// Start/end z of the FamInstCurveDriver drive curve (CurveDriver.m_pCrv GLine), project coordinates (feet). [JsonIgnore] - internal (double StartZ, double EndZ)? CurveDriverLineZ { get; set; } + internal (double StartZ, double EndZ)? CurveDriverLineZ + { + get => _curveDriver?.CurveDriverLineZ; + set + { + if (value != null || _curveDriver != null) (_curveDriver ??= new()).CurveDriverLineZ = value; + } + } /// The circular drive curve owned by this curve element, in internal coordinates. - internal LocationCurve? NativeModelArc { get; set; } + internal LocationCurve? NativeModelArc + { + get => _curveDriver?.NativeModelArc; + set + { + if (value != null || _curveDriver != null) (_curveDriver ??= new()).NativeModelArc = value; + } + } /// Unit direction of the straight drive curve (CurveDriver.m_pCrv GLine dirVec); absent for an arc driver. [JsonIgnore] - internal (double X, double Y, double Z)? CurveDriverLineDirection { get; set; } + internal (double X, double Y, double Z)? CurveDriverLineDirection + { + get => _curveDriver?.CurveDriverLineDirection; + set + { + if (value != null || _curveDriver != null) (_curveDriver ??= new()).CurveDriverLineDirection = value; + } + } /// Length of the straight drive curve (CurveDriver.m_pCrv GLine: the end-parameter span times the stored direction vector), feet. [JsonIgnore] - internal double? CurveDriverLineLength { get; set; } + internal double? CurveDriverLineLength + { + get => _curveDriver?.CurveDriverLineLength; + set + { + if (value != null || _curveDriver != null) (_curveDriver ??= new()).CurveDriverLineLength = value; + } + } /// StructuralUserData.m_copingDistance as stored (-1 when the member has no coped end). [JsonIgnore] - internal double? FramingCopingDistance { get; set; } + internal double? FramingCopingDistance + { + get => _familyPlacement?.FramingCopingDistance; + set + { + if (value != null || _familyPlacement != null) (_familyPlacement ??= new()).FramingCopingDistance = value; + } + } /// FamInstCurveDriver.m_refLevelId as stored (-1 when the driver has no reference level of its own). [JsonIgnore] - internal int? CurveDriverRefLevelId { get; set; } + internal int? CurveDriverRefLevelId + { + get => _curveDriver?.CurveDriverRefLevelId; + set + { + if (value != null || _curveDriver != null) (_curveDriver ??= new()).CurveDriverRefLevelId = value; + } + } /// Material whose appearance came from a shading (0x09B6) payload or its shading holder. [JsonIgnore] @@ -108,11 +346,25 @@ public class Element /// FamilyInstance.m_instOrigin z as stored (the placement height relative to the instance's host/level). [JsonIgnore] - internal double? InstanceOriginZ { get; set; } + internal double? InstanceOriginZ + { + get => _familyPlacement?.InstanceOriginZ; + set + { + if (value != null || _familyPlacement != null) (_familyPlacement ??= new()).InstanceOriginZ = value; + } + } /// FamilyInstance.m_refs FamilyLevelRef pair as stored: base (first) and top (second) level and offset. [JsonIgnore] - internal (int BaseLevel, double BaseOffset, int TopLevel, double TopOffset)? FamilyLevelRefs { get; set; } + internal (int BaseLevel, double BaseOffset, int TopLevel, double TopOffset)? FamilyLevelRefs + { + get => _familyPlacement?.FamilyLevelRefs; + set + { + if (value != null || _familyPlacement != null) (_familyPlacement ??= new()).FamilyLevelRefs = value; + } + } /// Parameters set by the NativeFieldParameters table with their validated presence domains, the /// parameter's state before the table set it (null: it did not exist) and the value the table left. @@ -129,7 +381,14 @@ public class Element /// StructCurveDriverBase.m_rotation as stored. [JsonIgnore] - internal double? CurveDriverRotation { get; set; } + internal double? CurveDriverRotation + { + get => _curveDriver?.CurveDriverRotation; + set + { + if (value != null || _curveDriver != null) (_curveDriver ??= new()).CurveDriverRotation = value; + } + } /// Element.m_createdPhaseId / m_demolishedPhaseId as stored. [JsonIgnore] @@ -159,11 +418,22 @@ public class Element /// The volume (cubic metres) and surface (square metres) of the taken solids of a column at the Medium level when it /// differs from the Fine one; null when the element has no alternatives or its Medium solids have no surface integrals. [JsonIgnore] - internal (double Volume, double Area)? MediumSolidTotals { get; set; } + internal (double Volume, double Area)? MediumSolidTotals + { + get => ((double Volume, double Area)?)_mediumSolidTotals; + set => _mediumSolidTotals = value; + } /// EnergyDataSettings.m_buildingTypeId as stored (the project's HVAC load building type). [JsonIgnore] - internal int? EnergyBuildingTypeId { get; set; } + internal int? EnergyBuildingTypeId + { + get => _space?.EnergyBuildingTypeId; + set + { + if (value != null || _space != null) (_space ??= new()).EnergyBuildingTypeId = value; + } + } /// The instance's own geometry symbol (InstanceInfo m_symbolId) as stored. [JsonIgnore] @@ -171,23 +441,55 @@ public class Element /// Framing length regenerated into an instance symbol: StructSetbackSymFamRef.m_Length, equal at both ends. [JsonIgnore] - internal double? SymbolFramingLength { get; set; } + internal double? SymbolFramingLength + { + get => _familyPlacement?.SymbolFramingLength; + set + { + if (value != null || _familyPlacement != null) (_familyPlacement ??= new()).SymbolFramingLength = value; + } + } /// The attachment record of a column end (AttachInfo 699): IsTop is m_baseOrTop = 1. [JsonIgnore] - internal (bool IsTop, double Offset, int Justification)? ColumnAttachment { get; set; } + internal (bool IsTop, double Offset, int Justification)? ColumnAttachment + { + get => ((bool IsTop, double Offset, int Justification)?)_columnAttachment; + set => _columnAttachment = value; + } /// FamilyInstance.m_useOffsetPos as stored: whether the instance keeps its offset when its grid moves. [JsonIgnore] - internal bool? InstanceUsesOffsetPosition { get; set; } + internal bool? InstanceUsesOffsetPosition + { + get => _familyPlacement?.InstanceUsesOffsetPosition; + set + { + if (value != null || _familyPlacement != null) (_familyPlacement ??= new()).InstanceUsesOffsetPosition = value; + } + } /// FamilyInstance.m_instOrigin x and y as stored (project coordinates, feet). [JsonIgnore] - internal (double X, double Y)? InstanceOriginXY { get; set; } + internal (double X, double Y)? InstanceOriginXY + { + get => _familyPlacement?.InstanceOriginXY; + set + { + if (value != null || _familyPlacement != null) (_familyPlacement ??= new()).InstanceOriginXY = value; + } + } /// FamilyInstance.m_bVertical as stored. [JsonIgnore] - internal bool? InstanceIsVertical { get; set; } + internal bool? InstanceIsVertical + { + get => _familyPlacement?.InstanceIsVertical; + set + { + if (value != null || _familyPlacement != null) (_familyPlacement ??= new()).InstanceIsVertical = value; + } + } /// FamilyInstance.m_assocSketchPlaneId as stored. [JsonIgnore] @@ -217,32 +519,74 @@ public class Element /// Complete planar boundary cache of this unique OST_Rooms owner, in /// project coordinates (feet). Kept out of physical geometry and public JSON. [JsonIgnore] - internal GeometryData? SerializedSpaceBoundary { get; set; } + internal GeometryData? SerializedSpaceBoundary + { + get => _space?.SerializedSpaceBoundary; + set + { + if (value != null || _space != null) (_space ??= new()).SerializedSpaceBoundary = value; + } + } /// The cache of a room whose boundary also holds analytic cylinders (a round wall): the current profile body of the room is /// written from the face meshes of its Geometry node. Kept apart from (planar boundaries /// only), which the legacy profile target and the room area read. - internal GeometryData? SerializedCurvedSpaceBoundary { get; set; } + internal GeometryData? SerializedCurvedSpaceBoundary + { + get => _space?.SerializedCurvedSpaceBoundary; + set + { + if (value != null || _space != null) (_space ??= new()).SerializedCurvedSpaceBoundary = value; + } + } /// The planar cache of a room read literally (loops of the coedges as they are, no welding, no closed-shell validation): the /// body of a room whose welded cache is refused or is no manifold shell. See GRepParserV2.ParseLiteralPlanarSpaceBoundary. - internal GeometryData? SerializedLiteralSpaceBoundary { get; set; } + internal GeometryData? SerializedLiteralSpaceBoundary + { + get => _space?.SerializedLiteralSpaceBoundary; + set + { + if (value != null || _space != null) (_space ??= new()).SerializedLiteralSpaceBoundary = value; + } + } /// The outline (feet, plan coordinates) of a room or area that has no geometry block, from its circuit in the level room plan: the profile /// The current profile extrudes for it. Null when there is none or the circuit cannot be read exactly (see Parsing.RoomPlanBoundary). - internal IReadOnlyList<(double X, double Y)>? SerializedPlanBoundary { get; set; } + internal IReadOnlyList<(double X, double Y)>? SerializedPlanBoundary + { + get => _space?.SerializedPlanBoundary; + set + { + if (value != null || _space != null) (_space ??= new()).SerializedPlanBoundary = value; + } + } /// The planar boundary of a room, else its curved one: what the current profile export reads. internal GeometryData? SerializedSpaceBoundaryCurrent => SerializedSpaceBoundary ?? SerializedCurvedSpaceBoundary; /// RoomElem.m_phaseId from a unique, validated room owner root. [JsonIgnore] - internal int? SerializedRoomPhaseId { get; set; } + internal int? SerializedRoomPhaseId + { + get => _space?.SerializedRoomPhaseId; + set + { + if (value != null || _space != null) (_space ??= new()).SerializedRoomPhaseId = value; + } + } /// The area (square feet) of the circuit RoomElem.m_cachedCircuitId names in the single level room plan /// that holds this room, less its islands. [JsonIgnore] - internal double? SerializedRoomPlanAreaSquareFeet { get; set; } + internal double? SerializedRoomPlanAreaSquareFeet + { + get => _space?.SerializedRoomPlanAreaSquareFeet; + set + { + if (value != null || _space != null) (_space ??= new()).SerializedRoomPlanAreaSquareFeet = value; + } + } /// Exact serialized Element.m_docAccess handle. [JsonIgnore] @@ -277,58 +621,149 @@ public class Element /// The plain text of a text note, decoded from the RTF string Revit stores for it; null for every other /// element and for a text note whose block was not decoded. [JsonIgnore] - public string? Text { get; set; } + public string? Text + { + get => _drawing?.Text; + set + { + if (value != null || _drawing != null) (_drawing ??= new()).Text = value; + } + } /// The position of a text note in the coordinates of its view (feet), [x, y, z]; null when not /// decoded. [JsonIgnore] - public double[]? TextPosition { get; set; } + public double[]? TextPosition + { + get => _drawing?.TextPosition; + set + { + if (value != null || _drawing != null) (_drawing ??= new()).TextPosition = value; + } + } /// The font size of the text note in points, when the stored RTF declares one. [JsonIgnore] - public double? TextFontSizePoints { get; set; } + public double? TextFontSizePoints + { + get => _drawing?.TextFontSizePoints; + set + { + if (value != null || _drawing != null) (_drawing ??= new()).TextFontSizePoints = value; + } + } /// The view scale of a viewport (the denominator), decoded from the viewport record; null when the /// reader did not decode it. [JsonIgnore] - public int? ViewportScale { get; set; } + public int? ViewportScale + { + get => _drawing?.ViewportScale; + set + { + if (value != null || _drawing != null) (_drawing ??= new()).ViewportScale = value; + } + } /// The pixel width of an image symbol, when the reader decoded it. [JsonIgnore] - public int? ImageWidth { get; set; } + public int? ImageWidth + { + get => _drawing?.ImageWidth; + set + { + if (value != null || _drawing != null) (_drawing ??= new()).ImageWidth = value; + } + } /// The pixel height of an image symbol, when the reader decoded it. [JsonIgnore] - public int? ImageHeight { get; set; } + public int? ImageHeight + { + get => _drawing?.ImageHeight; + set + { + if (value != null || _drawing != null) (_drawing ??= new()).ImageHeight = value; + } + } /// The origin of a view's plane (feet), [x, y, z]; null when the reader did not decode it. [JsonIgnore] - public double[]? ViewOrigin { get; set; } + public double[]? ViewOrigin + { + get => _drawing?.ViewOrigin; + set + { + if (value != null || _drawing != null) (_drawing ??= new()).ViewOrigin = value; + } + } /// The horizontal axis of a view's plane, a unit vector; null when not decoded. [JsonIgnore] - public double[]? ViewHorizontalDirection { get; set; } + public double[]? ViewHorizontalDirection + { + get => _drawing?.ViewHorizontalDirection; + set + { + if (value != null || _drawing != null) (_drawing ??= new()).ViewHorizontalDirection = value; + } + } /// The vertical axis of a view's plane, a unit vector; null when not decoded. [JsonIgnore] - public double[]? ViewVerticalDirection { get; set; } + public double[]? ViewVerticalDirection + { + get => _drawing?.ViewVerticalDirection; + set + { + if (value != null || _drawing != null) (_drawing ??= new()).ViewVerticalDirection = value; + } + } /// The direction a view looks at, a unit vector; null when not decoded. [JsonIgnore] - public double[]? ViewDirection { get; set; } + public double[]? ViewDirection + { + get => _drawing?.ViewDirection; + set + { + if (value != null || _drawing != null) (_drawing ??= new()).ViewDirection = value; + } + } /// For a viewport: the element id of the view it displays; null when the reader did not decode it. [JsonIgnore] - public int? ViewportViewId { get; set; } + public int? ViewportViewId + { + get => _drawing?.ViewportViewId; + set + { + if (value != null || _drawing != null) (_drawing ??= new()).ViewportViewId = value; + } + } /// For a viewport: the offset of the displayed view on the sheet (feet), [x, y, z]; null when not /// decoded. [JsonIgnore] - public double[]? ViewportOffset { get; set; } + public double[]? ViewportOffset + { + get => _drawing?.ViewportOffset; + set + { + if (value != null || _drawing != null) (_drawing ??= new()).ViewportOffset = value; + } + } /// Exact BaseRailing.m_baseRailingSymbolId stored by this occurrence. [JsonIgnore] - internal int? SerializedBaseRailingSymbolId { get; set; } + internal int? SerializedBaseRailingSymbolId + { + get => _stairAndRailing?.SerializedBaseRailingSymbolId; + set + { + if (value != null || _stairAndRailing != null) (_stairAndRailing ??= new()).SerializedBaseRailingSymbolId = value; + } + } /// Own unique InstanceInfo.m_symbolId resolving to a FamilySymbol /// with known semantic kind/owner prefix. The original symbol, @@ -344,57 +779,145 @@ public class Element /// One active own computed-symbol cut with paired InstanceInfo transform; /// only a unique, non-inplace family with no nested instances is admitted. [JsonIgnore] - internal (int SymbolId, int HostId, double[] Transform, FamilyCutLoopData Loop)? OwnSingleFamilyCutout { get; set; } + internal (int SymbolId, int HostId, double[] Transform, FamilyCutLoopData Loop)? OwnSingleFamilyCutout + { + get => ((int SymbolId, int HostId, double[] Transform, FamilyCutLoopData Loop)?)_ownSingleFamilyCutout; + set => _ownSingleFamilyCutout = value; + } /// Own phase-4 cutout instance IDs in source order, not inferred inverse hosts. [JsonIgnore] - internal IReadOnlyList? OwnWallCutoutInstanceIds { get; set; } + internal IReadOnlyList? OwnWallCutoutInstanceIds + { + get => _wall?.OwnWallCutoutInstanceIds; + set + { + if (value != null || _wall != null) (_wall ??= new()).OwnWallCutoutInstanceIds = value; + } + } [JsonIgnore] - internal IReadOnlyList? OwnWallCutoutSteps { get; set; } + internal IReadOnlyList? OwnWallCutoutSteps + { + get => _wall?.OwnWallCutoutSteps; + set + { + if (value != null || _wall != null) (_wall ??= new()).OwnWallCutoutSteps = value; + } + } [JsonIgnore] - internal double[][]? OwnWallAxisLine { get; set; } + internal double[][]? OwnWallAxisLine + { + get => _wall?.OwnWallAxisLine; + set + { + if (value != null || _wall != null) (_wall ??= new()).OwnWallAxisLine = value; + } + } /// The location line of a straight own wall, bounded by its trimmed curve: start and end /// point, feet. Null when the side faces of the wall are not both known. [JsonIgnore] - internal double[][]? OwnWallTrimmedAxis { get; set; } + internal double[][]? OwnWallTrimmedAxis + { + get => _wall?.OwnWallTrimmedAxis; + set + { + if (value != null || _wall != null) (_wall ??= new()).OwnWallTrimmedAxis = value; + } + } [JsonIgnore] - internal int? OwnWallCrossSection { get; set; } + internal int? OwnWallCrossSection + { + get => _wall?.OwnWallCrossSection; + set + { + if (value != null || _wall != null) (_wall ??= new()).OwnWallCrossSection = value; + } + } /// Profile helper of the own wall root; null when the root is not readable or not unique. [JsonIgnore] - internal Parsing.TfBlockDeserializer.OwnWallHelperInput? OwnWallHelper { get; set; } + internal Parsing.TfBlockDeserializer.OwnWallHelperInput? OwnWallHelper + { + get => _wall?.OwnWallHelper; + set + { + if (value != null || _wall != null) (_wall ??= new()).OwnWallHelper = value; + } + } /// Exact BaseRailing.m_stairsRailingAttrId stored by this occurrence. [JsonIgnore] - internal int? SerializedStairsRailingAttrId { get; set; } + internal int? SerializedStairsRailingAttrId + { + get => _stairAndRailing?.SerializedStairsRailingAttrId; + set + { + if (value != null || _stairAndRailing != null) (_stairAndRailing ??= new()).SerializedStairsRailingAttrId = value; + } + } /// Exact BaseRailingAttr.m_topRailHeight reached through /// , in Revit internal feet. [JsonIgnore] - internal double? SerializedRailingTopHeightFeet { get; set; } + internal double? SerializedRailingTopHeightFeet + { + get => _stairAndRailing?.SerializedRailingTopHeightFeet; + set + { + if (value != null || _stairAndRailing != null) (_stairAndRailing ??= new()).SerializedRailingTopHeightFeet = value; + } + } /// Exact StairsElement.m_typeId from this occurrence's unique complete /// class-3681 root, after resolving one unique class-3742 StairsType target. [JsonIgnore] - internal int? SerializedStairTypeId { get; set; } + internal int? SerializedStairTypeId + { + get => _stairAndRailing?.SerializedStairTypeId; + set + { + if (value != null || _stairAndRailing != null) (_stairAndRailing ??= new()).SerializedStairTypeId = value; + } + } /// Exact StairsElement.m_baseLevelId of the same class-3681 root (STAIRS_BASE_LEVEL_PARAM). [JsonIgnore] - internal int? SerializedStairBaseLevelId { get; set; } + internal int? SerializedStairBaseLevelId + { + get => _stairAndRailing?.SerializedStairBaseLevelId; + set + { + if (value != null || _stairAndRailing != null) (_stairAndRailing ??= new()).SerializedStairBaseLevelId = value; + } + } /// True only while resolves to the /// unique materialized stair type validated by its own exact class-3742 root. [JsonIgnore] - internal bool SerializedStairTypeLinkIsResolved { get; set; } + internal bool SerializedStairTypeLinkIsResolved + { + get => _stairAndRailing?.SerializedStairTypeLinkIsResolved ?? false; + set + { + if (value || _stairAndRailing != null) (_stairAndRailing ??= new()).SerializedStairTypeLinkIsResolved = value; + } + } /// Exact raw Tf class of this materialized StairsType target. Kept after /// public TypeId normalization so the exporter can revalidate the raw boundary. [JsonIgnore] - internal ushort? SerializedStairsTypeClassId { get; set; } + internal ushort? SerializedStairsTypeClassId + { + get => _stairAndRailing?.SerializedStairsTypeClassId; + set + { + if (value != null || _stairAndRailing != null) (_stairAndRailing ??= new()).SerializedStairsTypeClassId = value; + } + } /// Own semantic class from a single validated Element base prefix; /// not the first geometry frame or the public normalized TypeId. @@ -416,7 +939,14 @@ public class Element /// FamilyInstance.m_structType as stored (StructuralType: 0 non-structural, 1 beam, 2 brace, 3 column, 4 footing, 5 unknown /// framing); null when the walk did not read it. [JsonIgnore] - internal int? NativeStructuralType { get; set; } + internal int? NativeStructuralType + { + get => _familyPlacement?.NativeStructuralType; + set + { + if (value != null || _familyPlacement != null) (_familyPlacement ??= new()).NativeStructuralType = value; + } + } /// ElementHeader.m_designOptionId of a file with 64-bit ids; null when not decoded. [JsonIgnore] @@ -486,30 +1016,72 @@ internal bool RootClassIs(string className) => NativeRootClassName != null /// Own helper core, reciprocally owned and equal to the native typed /// inverse ownership set. Ordering is not an API naming ordinal. [JsonIgnore] - internal Internal.StairComponentSource.CoreComponent[]? SerializedStairCore { get; set; } + internal Internal.StairComponentSource.CoreComponent[]? SerializedStairCore + { + get => _stairAndRailing?.SerializedStairCore; + set + { + if (value != null || _stairAndRailing != null) (_stairAndRailing ??= new()).SerializedStairCore = value; + } + } /// Levels a multistory stair is repeated on, in stored order. [JsonIgnore] - internal int[]? SerializedStairCopyLevelIds { get; set; } + internal int[]? SerializedStairCopyLevelIds + { + get => _stairAndRailing?.SerializedStairCopyLevelIds; + set + { + if (value != null || _stairAndRailing != null) (_stairAndRailing ??= new()).SerializedStairCopyLevelIds = value; + } + } /// Single complete own run graph's native style and cached API path /// directions, with independent semantic class and reciprocal ElemRec owner. [JsonIgnore] - internal Parsing.TfBlockDeserializer.StairRunInput? SerializedStairRunInput { get; set; } + internal Parsing.TfBlockDeserializer.StairRunInput? SerializedStairRunInput + { + get => _stairAndRailing?.SerializedStairRunInput; + set + { + if (value != null || _stairAndRailing != null) (_stairAndRailing ??= new()).SerializedStairRunInput = value; + } + } /// Native IDS_STAIR instance name from the saved locale's resource, /// admitted only for a complete own native stair/type/core. Not the type Name. [JsonIgnore] - internal string? ValidatedStairOccurrenceName { get; set; } + internal string? ValidatedStairOccurrenceName + { + get => _stairAndRailing?.ValidatedStairOccurrenceName; + set + { + if (value != null || _stairAndRailing != null) (_stairAndRailing ??= new()).ValidatedStairOccurrenceName = value; + } + } /// Own complete parameter-store scope for native instance naming; /// null is unvalidated, an empty list is validated absence. Never public heuristics. [JsonIgnore] - internal List? SerializedStairNameParameters { get; set; } + internal List? SerializedStairNameParameters + { + get => _stairAndRailing?.SerializedStairNameParameters; + set + { + if (value != null || _stairAndRailing != null) (_stairAndRailing ??= new()).SerializedStairNameParameters = value; + } + } /// Own single class-485 BaseRailing.m_stairsId, separately from /// ElemRec ownership, registered lists, and the adjustment start component. [JsonIgnore] - internal int? SerializedRailingStairHostId { get; set; } + internal int? SerializedRailingStairHostId + { + get => _stairAndRailing?.SerializedRailingStairHostId; + set + { + if (value != null || _stairAndRailing != null) (_stairAndRailing ??= new()).SerializedRailingStairHostId = value; + } + } /// Material.m_name from this material's own single MaterialElem root. [JsonIgnore] @@ -543,21 +1115,56 @@ internal bool RootClassIs(string className) => NativeRootClassName != null /// Own basic-wall type getter, bound through the exact occurrence type link. /// Separate from legacy Layers and propagated parameters; internal feet. [JsonIgnore] - internal double? ValidatedWallTypeThicknessFeet { get; set; } + internal double? ValidatedWallTypeThicknessFeet + { + get => _wall?.ValidatedWallTypeThicknessFeet; + set + { + if (value != null || _wall != null) (_wall ??= new()).ValidatedWallTypeThicknessFeet = value; + } + } // Kept separate until the writer has completed the host/void contract. [JsonIgnore] - internal GeometryData? OwnPrimaryPlanarBody { get; set; } + internal GeometryData? OwnPrimaryPlanarBody + { + get => _wall?.OwnPrimaryPlanarBody; + set + { + if (value != null || _wall != null) (_wall ??= new()).OwnPrimaryPlanarBody = value; + } + } [System.Text.Json.Serialization.JsonIgnore] - internal double[]? OwnWallSide0NormalCurrent { get; set; } + internal double[]? OwnWallSide0NormalCurrent + { + get => _wall?.OwnWallSide0NormalCurrent; + set + { + if (value != null || _wall != null) (_wall ??= new()).OwnWallSide0NormalCurrent = value; + } + } [System.Text.Json.Serialization.JsonIgnore] - internal GeometryData? OwnCurrentCutPairBodyCurrent { get; set; } + internal GeometryData? OwnCurrentCutPairBodyCurrent + { + get => _wall?.OwnCurrentCutPairBodyCurrent; + set + { + if (value != null || _wall != null) (_wall ??= new()).OwnCurrentCutPairBodyCurrent = value; + } + } /// VWall.m_isFlipped read from the wall's own native record; null when not decoded. [JsonIgnore] - internal bool? SerializedWallFlipped { get; set; } + internal bool? SerializedWallFlipped + { + get => _wall?.SerializedWallFlipped; + set + { + if (value != null || _wall != null) (_wall ??= new()).SerializedWallFlipped = value; + } + } /// GroupMembership.m_groupId of the element: the model group instance it belongs to. [JsonIgnore] @@ -565,15 +1172,33 @@ internal bool RootClassIs(string className) => NativeRootClassName != null /// FamInstDesignPropertyManager.m_idRoom of a family instance: the room it is in. [JsonIgnore] - internal int? SerializedRoomId { get; set; } + internal int? SerializedRoomId + { + get => _space?.SerializedRoomId; + set + { + if (value != null || _space != null) (_space ??= new()).SerializedRoomId = value; + } + } /// AreaMeasureElem.m_areaElemName and m_areaElemDescription of an area scheme. [JsonIgnore] - internal (string Name, string Description)? SerializedAreaScheme { get; set; } + internal (string Name, string Description)? SerializedAreaScheme + { + get => ((string Name, string Description)?)_serializedAreaScheme; + set => _serializedAreaScheme = value; + } /// RoomElem.m_bIsLocationless: the room or area is not placed in a plan. [JsonIgnore] - internal bool? SerializedRoomIsLocationless { get; set; } + internal bool? SerializedRoomIsLocationless + { + get => _space?.SerializedRoomIsLocationless; + set + { + if (value != null || _space != null) (_space ??= new()).SerializedRoomIsLocationless = value; + } + } /// True for the defining (template) instance of a group type and for its members: they are stored /// in the file but are not elements of the model. @@ -591,34 +1216,76 @@ internal bool RootClassIs(string className) => NativeRootClassName != null /// StairsType.m_minTreadWidthOnInsideBoundary in feet (own stairs type root). [JsonIgnore] - internal double? SerializedStairsTypeMinInsideTreadFeet { get; set; } + internal double? SerializedStairsTypeMinInsideTreadFeet + { + get => _stairAndRailing?.SerializedStairsTypeMinInsideTreadFeet; + set + { + if (value != null || _stairAndRailing != null) (_stairAndRailing ??= new()).SerializedStairsTypeMinInsideTreadFeet = value; + } + } /// StairsRunType.m_nosingLength in feet (own stairs run type root). [JsonIgnore] - internal double? SerializedStairRunTypeNosingFeet { get; set; } + internal double? SerializedStairRunTypeNosingFeet + { + get => _stairAndRailing?.SerializedStairRunTypeNosingFeet; + set + { + if (value != null || _stairAndRailing != null) (_stairAndRailing ??= new()).SerializedStairRunTypeNosingFeet = value; + } + } /// Family instance connectors in stored order: Connector.m_nIndex, the stored hvac (2381) or /// piping (2382) connector calculation direction and its system type (null when the domains are mixed /// or the connector objects do not match the calculations one to one). [JsonIgnore] - internal IReadOnlyList<(int Index, int Direction, int SystemType)>? SerializedMepConnectors { get; set; } + internal IReadOnlyList<(int Index, int Direction, int SystemType)>? SerializedMepConnectors + { + get => _mep?.SerializedMepConnectors; + set + { + if (value != null || _mep != null) (_mep ??= new()).SerializedMepConnectors = value; + } + } /// Every connector of the element in stored order: Connector.m_nIndex, the stored flow direction /// (SegmentConnectorCalculation.m_eDirection, 0 when none) and Connector.m_arrRefs, the connected /// (element id, connector index, connection type) entries. The element's own other connectors are among them. [JsonIgnore] - internal IReadOnlyList<(int Index, int Direction, IReadOnlyList<(int Id, int Index, int Type)> Refs)>? SerializedConnectorGraph { get; set; } + internal IReadOnlyList<(int Index, int Direction, IReadOnlyList<(int Id, int Index, int Type)> Refs)>? SerializedConnectorGraph + { + get => _mep?.SerializedConnectorGraph; + set + { + if (value != null || _mep != null) (_mep ??= new()).SerializedConnectorGraph = value; + } + } /// The MEP system element each connector of belongs to, in the /// same order (the connector's m_idSystem from the segment calculation of a curve or the hvac/piping /// calculation of a family instance; 0 or negative for none). [JsonIgnore] - internal IReadOnlyList? SerializedConnectorSystems { get; set; } + internal IReadOnlyList? SerializedConnectorSystems + { + get => _mep?.SerializedConnectorSystems; + set + { + if (value != null || _mep != null) (_mep ??= new()).SerializedConnectorSystems = value; + } + } /// The mode of each connector of , in the same order; null when the walk of /// the file does not know the mode (Revit 2022 layout). [JsonIgnore] - internal IReadOnlyList? SerializedConnectorModes { get; set; } + internal IReadOnlyList? SerializedConnectorModes + { + get => _mep?.SerializedConnectorModes; + set + { + if (value != null || _mep != null) (_mep ??= new()).SerializedConnectorModes = value; + } + } /// The vertical extent (feet) of a Grid's finite surface: the interval of levels the grid belongs to. /// Null for a grid whose surface was not decoded. @@ -632,23 +1299,58 @@ internal bool RootClassIs(string className) => NativeRootClassName != null /// MEPCurve.m_idSystemType, the system type an MEP curve (duct, flex duct, pipe) stores itself, also when it /// belongs to no system (its System Type parameter is then -1); null when the element stores none. [JsonIgnore] - internal int? SerializedCurveSystemTypeId { get; set; } + internal int? SerializedCurveSystemTypeId + { + get => _mep?.SerializedCurveSystemTypeId; + set + { + if (value != null || _mep != null) (_mep ??= new()).SerializedCurveSystemTypeId = value; + } + } /// ZoneElement.m_bDefault of an HVAC zone (whether it is the default zone); null for other elements. [JsonIgnore] - internal bool? SerializedZoneIsDefault { get; set; } + internal bool? SerializedZoneIsDefault + { + get => _space?.SerializedZoneIsDefault; + set + { + if (value != null || _space != null) (_space ??= new()).SerializedZoneIsDefault = value; + } + } /// RoomElem.m_zoneElementId of a space: the HVAC zone it belongs to; null when it belongs to none. [JsonIgnore] - internal int? SerializedSpaceZoneId { get; set; } + internal int? SerializedSpaceZoneId + { + get => _space?.SerializedSpaceZoneId; + set + { + if (value != null || _space != null) (_space ??= new()).SerializedSpaceZoneId = value; + } + } /// RbsSystem.m_strName and m_typeId of an MEP system element (piping or duct system); null for other elements. [JsonIgnore] - internal (string Name, int TypeId)? SerializedMepSystem { get; set; } + internal (string Name, int TypeId)? SerializedMepSystem + { + get => _mep?.SerializedMepSystem; + set + { + if (value != null || _mep != null) (_mep ??= new()).SerializedMepSystem = value; + } + } /// The base equipment (panel) of an electrical circuit, from its connector manager; null for other elements and for a circuit with none. [JsonIgnore] - internal int? SerializedCircuitBaseEquipmentId { get; set; } + internal int? SerializedCircuitBaseEquipmentId + { + get => _mep?.SerializedCircuitBaseEquipmentId; + set + { + if (value != null || _mep != null) (_mep ??= new()).SerializedCircuitBaseEquipmentId = value; + } + } /// Own SymbolInfo type name with the original localized system family, /// used for LayerSet metadata and IFC floor/ceiling Type.Name; the name remains @@ -659,7 +1361,14 @@ internal bool RootClassIs(string className) => NativeRootClassName != null /// Whether the wall's own root carries a top attachment /// (JoinToRoofGStep with m_baseOrTop = 1); null when unvalidated. [JsonIgnore] - internal bool? SerializedWallJoinedToTop { get; set; } + internal bool? SerializedWallJoinedToTop + { + get => _wall?.SerializedWallJoinedToTop; + set + { + if (value != null || _wall != null) (_wall ??= new()).SerializedWallJoinedToTop = value; + } + } /// The export id of the element: its episode GUID with the last /// 32 bits XORed with the original element id (Global/History and Global/ElemTable); @@ -675,34 +1384,83 @@ internal bool RootClassIs(string className) => NativeRootClassName != null /// Own wall/floor/ceiling type link, validated against one unique /// materialized type's exact root and category. Never a public type guess. [JsonIgnore] - internal int? SerializedSystemTypeId { get; set; } + internal int? SerializedSystemTypeId + { + get => _typeReferences?.SerializedSystemTypeId; + set + { + if (value != null || _typeReferences != null) (_typeReferences ??= new()).SerializedSystemTypeId = value; + } + } /// Exact own native root class of that wall/floor/ceiling type. /// Kept independently of localization and the public TypeId normalization. [JsonIgnore] - internal ushort? SerializedSystemTypeClassId { get; set; } + internal ushort? SerializedSystemTypeClassId + { + get => _typeReferences?.SerializedSystemTypeClassId; + set + { + if (value != null || _typeReferences != null) (_typeReferences ??= new()).SerializedSystemTypeClassId = value; + } + } /// Control joins of the wall's own driver: per end (0 start, 1 end) the joined /// element and its joined end; null when the wall block is not read exactly. [JsonIgnore] - internal IReadOnlyList? SerializedWallEndJoins { get; set; } + internal IReadOnlyList? SerializedWallEndJoins + { + get => _wall?.SerializedWallEndJoins; + set + { + if (value != null || _wall != null) (_wall ??= new()).SerializedWallEndJoins = value; + } + } /// Exact StairsElement.m_actualNumberOfRisers occurrence value. [JsonIgnore] - internal int? SerializedActualNumberOfRisers { get; set; } + internal int? SerializedActualNumberOfRisers + { + get => _stairAndRailing?.SerializedActualNumberOfRisers; + set + { + if (value != null || _stairAndRailing != null) (_stairAndRailing ??= new()).SerializedActualNumberOfRisers = value; + } + } /// Exact StairsElement.m_actualRiserHeight in Revit internal feet. [JsonIgnore] - internal double? SerializedActualRiserHeightFeet { get; set; } + internal double? SerializedActualRiserHeightFeet + { + get => _stairAndRailing?.SerializedActualRiserHeightFeet; + set + { + if (value != null || _stairAndRailing != null) (_stairAndRailing ??= new()).SerializedActualRiserHeightFeet = value; + } + } /// Exact StairsElement.m_actualTreadDepth in Revit internal feet. [JsonIgnore] - internal double? SerializedActualTreadDepthFeet { get; set; } + internal double? SerializedActualTreadDepthFeet + { + get => _stairAndRailing?.SerializedActualTreadDepthFeet; + set + { + if (value != null || _stairAndRailing != null) (_stairAndRailing ??= new()).SerializedActualTreadDepthFeet = value; + } + } /// Exact WallType.m_function serialized by this element's own /// NewCurtainWallType root block (0=Interior, 1=Exterior, ...). [JsonIgnore] - internal int? SerializedCurtainWallFunction { get; set; } + internal int? SerializedCurtainWallFunction + { + get => _wall?.SerializedCurtainWallFunction; + set + { + if (value != null || _wall != null) (_wall ??= new()).SerializedCurtainWallFunction = value; + } + } /// FUNCTION_PARAM stored by this FamilySymbol's own FamilyParams prefix (the first /// matching NamedParam, its separate integer member), accepted only for a unique root block @@ -747,7 +1505,14 @@ internal bool RootClassIs(string className) => NativeRootClassName != null /// Values of the schema fields the room of a family instance is found from /// (), keyed Declaring:Name; a field the record did not hold is /// absent. - internal Dictionary? NativeRoomFields { get; set; } + internal Dictionary? NativeRoomFields + { + get => _space?.NativeRoomFields; + set + { + if (value != null || _space != null) (_space ??= new()).NativeRoomFields = value; + } + } /// Tf class tag of the element's record (the class the record is an instance of, by its schema name); null when the /// record was not walked. @@ -762,16 +1527,37 @@ internal bool RootClassIs(string className) => NativeRootClassName != null /// Own unique NewCurtainWallType SymbolInfo name, not a mark or an /// occurrence-name fallback. Kept separate from public identity/name fields. [JsonIgnore] - internal string? SerializedCurtainWallTypeName { get; set; } + internal string? SerializedCurtainWallTypeName + { + get => _wall?.SerializedCurtainWallTypeName; + set + { + if (value != null || _wall != null) (_wall ??= new()).SerializedCurtainWallTypeName = value; + } + } /// Own unique BasicWallType SymbolInfo name, independent of public name fallbacks. [JsonIgnore] - internal string? SerializedBasicWallTypeName { get; set; } + internal string? SerializedBasicWallTypeName + { + get => _wall?.SerializedBasicWallTypeName; + set + { + if (value != null || _wall != null) (_wall ??= new()).SerializedBasicWallTypeName = value; + } + } /// Own unique StackedWallType root. Such a type's placed parent wall is /// a container, not a separate IFC wall product; its component walls remain sources. [JsonIgnore] - internal bool IsSerializedStackedWallType { get; set; } + internal bool IsSerializedStackedWallType + { + get => _wall?.IsSerializedStackedWallType ?? false; + set + { + if (value || _wall != null) (_wall ??= new()).IsSerializedStackedWallType = value; + } + } /// Element name (first useful string found near this element in the binary stream). public string? Name { get; set; } @@ -782,49 +1568,105 @@ internal bool RootClassIs(string className) => NativeRootClassName != null /// block. This is isolated from : it may override only floor/slab- /// opening Reference properties, never IFC identity fields. [JsonIgnore] - internal string? ValidatedFloorTypeReferenceName { get; set; } + internal string? ValidatedFloorTypeReferenceName + { + get => _typeReferences?.ValidatedFloorTypeReferenceName; + set + { + if (value != null || _typeReferences != null) (_typeReferences ??= new()).ValidatedFloorTypeReferenceName = value; + } + } /// The own name of the floor type (its unique HostObjAttr root, validated), set when no Reference parameter /// decides the floor Reference. The current IFC profile prefers it to , which /// ends in a text parameter of a type that carries some. [JsonIgnore] - internal string? ValidatedFloorOwnTypeName { get; set; } + internal string? ValidatedFloorOwnTypeName + { + get => _typeReferences?.ValidatedFloorOwnTypeName; + set + { + if (value != null || _typeReferences != null) (_typeReferences ??= new()).ValidatedFloorOwnTypeName = value; + } + } /// True when came from an /// explicit instance/type Reference parameter rather than the terminal type name. /// Such a value can create the main product Pset even when the parsed element name /// is missing. [JsonIgnore] - internal bool ValidatedFloorTypeReferenceIsExplicit { get; set; } + internal bool ValidatedFloorTypeReferenceIsExplicit + { + get => _typeReferences?.ValidatedFloorTypeReferenceIsExplicit ?? false; + set + { + if (value || _typeReferences != null) (_typeReferences ??= new()).ValidatedFloorTypeReferenceIsExplicit = value; + } + } /// An exact floor/type relationship was validated, but a higher-priority /// Reference parameter could not be reproduced deterministically. Lower-priority /// name source must not leak past that parameter. [JsonIgnore] - internal bool ValidatedFloorTypeReferenceIsBlocked { get; set; } + internal bool ValidatedFloorTypeReferenceIsBlocked + { + get => _typeReferences?.ValidatedFloorTypeReferenceIsBlocked ?? false; + set + { + if (value || _typeReferences != null) (_typeReferences ??= new()).ValidatedFloorTypeReferenceIsBlocked = value; + } + } /// Exact Ceiling.m_ceilingAttributesId carried from this occurrence's /// own class-642 root block after owner, class, uniqueness and category validation. /// It is isolated from the public type graph and must never rewrite /// or type-related parameters. [JsonIgnore] - internal int? SerializedCeilingTypeId { get; set; } + internal int? SerializedCeilingTypeId + { + get => _typeReferences?.SerializedCeilingTypeId; + set + { + if (value != null || _typeReferences != null) (_typeReferences ??= new()).SerializedCeilingTypeId = value; + } + } /// Exact ceiling QTO Reference source reached through /// . It is isolated from product identity, /// public names, the structural type graph and material resolution. [JsonIgnore] - internal string? ValidatedCeilingTypeReferenceName { get; set; } + internal string? ValidatedCeilingTypeReferenceName + { + get => _typeReferences?.ValidatedCeilingTypeReferenceName; + set + { + if (value != null || _typeReferences != null) (_typeReferences ??= new()).ValidatedCeilingTypeReferenceName = value; + } + } /// True when the validated ceiling Reference came from an explicit /// instance/serialized-type parameter rather than terminal type-name source. [JsonIgnore] - internal bool ValidatedCeilingTypeReferenceIsExplicit { get; set; } + internal bool ValidatedCeilingTypeReferenceIsExplicit + { + get => _typeReferences?.ValidatedCeilingTypeReferenceIsExplicit ?? false; + set + { + if (value || _typeReferences != null) (_typeReferences ??= new()).ValidatedCeilingTypeReferenceIsExplicit = value; + } + } /// The exact ceiling relationship was validated, but a higher-priority /// Reference parameter could not be reproduced deterministically. [JsonIgnore] - internal bool ValidatedCeilingTypeReferenceIsBlocked { get; set; } + internal bool ValidatedCeilingTypeReferenceIsBlocked + { + get => _typeReferences?.ValidatedCeilingTypeReferenceIsBlocked ?? false; + set + { + if (value || _typeReferences != null) (_typeReferences ??= new()).ValidatedCeilingTypeReferenceIsBlocked = value; + } + } /// Exact window Reference source reached through the instance's own /// directly-decoded FamilyInstance.m_masterSymbolId (never the general TypeId/ @@ -835,19 +1677,40 @@ internal bool RootClassIs(string className) => NativeRootClassName != null /// from : it may override only Pset_QuantityTakeOff/Pset_WindowCommon /// Reference, never IFC identity fields. [JsonIgnore] - internal string? ValidatedWindowTypeReferenceName { get; set; } + internal string? ValidatedWindowTypeReferenceName + { + get => _typeReferences?.ValidatedWindowTypeReferenceName; + set + { + if (value != null || _typeReferences != null) (_typeReferences ??= new()).ValidatedWindowTypeReferenceName = value; + } + } /// True when came from an /// explicit instance/type Reference parameter rather than the resolved symbol's /// name-table terminal name. [JsonIgnore] - internal bool ValidatedWindowTypeReferenceIsExplicit { get; set; } + internal bool ValidatedWindowTypeReferenceIsExplicit + { + get => _typeReferences?.ValidatedWindowTypeReferenceIsExplicit ?? false; + set + { + if (value || _typeReferences != null) (_typeReferences ??= new()).ValidatedWindowTypeReferenceIsExplicit = value; + } + } /// An exact window/symbol relationship was validated, but a higher-priority /// Reference parameter could not be reproduced deterministically. Lower-priority /// name-table source must not leak past that parameter. [JsonIgnore] - internal bool ValidatedWindowTypeReferenceIsBlocked { get; set; } + internal bool ValidatedWindowTypeReferenceIsBlocked + { + get => _typeReferences?.ValidatedWindowTypeReferenceIsBlocked ?? false; + set + { + if (value || _typeReferences != null) (_typeReferences ??= new()).ValidatedWindowTypeReferenceIsBlocked = value; + } + } /// Exact IfcBuildingElementProxy Reference source, same mechanism and /// precedence as - the instance's own @@ -860,74 +1723,186 @@ internal bool RootClassIs(string className) => NativeRootClassName != null /// Isolated from : it may override only Pset_QuantityTakeOff/ /// Pset_BuildingElementProxyCommon Reference, never IFC identity fields. [JsonIgnore] - internal string? ValidatedProxyTypeReferenceName { get; set; } + internal string? ValidatedProxyTypeReferenceName + { + get => _typeReferences?.ValidatedProxyTypeReferenceName; + set + { + if (value != null || _typeReferences != null) (_typeReferences ??= new()).ValidatedProxyTypeReferenceName = value; + } + } /// True when came from an /// explicit instance/type Reference parameter rather than the resolved symbol's /// name-table terminal name. [JsonIgnore] - internal bool ValidatedProxyTypeReferenceIsExplicit { get; set; } + internal bool ValidatedProxyTypeReferenceIsExplicit + { + get => _typeReferences?.ValidatedProxyTypeReferenceIsExplicit ?? false; + set + { + if (value || _typeReferences != null) (_typeReferences ??= new()).ValidatedProxyTypeReferenceIsExplicit = value; + } + } /// An exact proxy/symbol relationship was validated, but a higher-priority /// Reference parameter could not be reproduced deterministically. Lower-priority /// name-table source must not leak past that parameter. [JsonIgnore] - internal bool ValidatedProxyTypeReferenceIsBlocked { get; set; } + internal bool ValidatedProxyTypeReferenceIsBlocked + { + get => _typeReferences?.ValidatedProxyTypeReferenceIsBlocked ?? false; + set + { + if (value || _typeReferences != null) (_typeReferences ??= new()).ValidatedProxyTypeReferenceIsBlocked = value; + } + } /// Own FamilyInstance -> FamilySymbol -> SymbolInfo validation, confined to /// distribution-flow QTO/Common Reference. Never changes product/type identity. [JsonIgnore] - internal string? ValidatedDistributionTypeReferenceName { get; set; } + internal string? ValidatedDistributionTypeReferenceName + { + get => _typeReferences?.ValidatedDistributionTypeReferenceName; + set + { + if (value != null || _typeReferences != null) (_typeReferences ??= new()).ValidatedDistributionTypeReferenceName = value; + } + } [JsonIgnore] - internal bool ValidatedDistributionTypeReferenceIsExplicit { get; set; } + internal bool ValidatedDistributionTypeReferenceIsExplicit + { + get => _typeReferences?.ValidatedDistributionTypeReferenceIsExplicit ?? false; + set + { + if (value || _typeReferences != null) (_typeReferences ??= new()).ValidatedDistributionTypeReferenceIsExplicit = value; + } + } [JsonIgnore] - internal bool ValidatedDistributionTypeReferenceIsBlocked { get; set; } + internal bool ValidatedDistributionTypeReferenceIsBlocked + { + get => _typeReferences?.ValidatedDistributionTypeReferenceIsBlocked ?? false; + set + { + if (value || _typeReferences != null) (_typeReferences ??= new()).ValidatedDistributionTypeReferenceIsBlocked = value; + } + } /// Own RoofAttributes/StairsRailingAttr name for QTO Reference only. [JsonIgnore] - internal string? ValidatedRoofOrRailingTypeReferenceName { get; set; } + internal string? ValidatedRoofOrRailingTypeReferenceName + { + get => _typeReferences?.ValidatedRoofOrRailingTypeReferenceName; + set + { + if (value != null || _typeReferences != null) (_typeReferences ??= new()).ValidatedRoofOrRailingTypeReferenceName = value; + } + } [JsonIgnore] - internal bool ValidatedRoofOrRailingTypeReferenceIsExplicit { get; set; } + internal bool ValidatedRoofOrRailingTypeReferenceIsExplicit + { + get => _typeReferences?.ValidatedRoofOrRailingTypeReferenceIsExplicit ?? false; + set + { + if (value || _typeReferences != null) (_typeReferences ??= new()).ValidatedRoofOrRailingTypeReferenceIsExplicit = value; + } + } [JsonIgnore] - internal bool ValidatedRoofOrRailingTypeReferenceIsBlocked { get; set; } + internal bool ValidatedRoofOrRailingTypeReferenceIsBlocked + { + get => _typeReferences?.ValidatedRoofOrRailingTypeReferenceIsBlocked ?? false; + set + { + if (value || _typeReferences != null) (_typeReferences ??= new()).ValidatedRoofOrRailingTypeReferenceIsBlocked = value; + } + } /// Localized system family name of THIS type element (Revit's own resource /// string for its exact root class). Set only on type elements; occurrences read it /// through their type link. Never derived from names or marks. [JsonIgnore] - internal string? ValidatedSystemFamilyName { get; set; } + internal string? ValidatedSystemFamilyName + { + get => _typeReferences?.ValidatedSystemFamilyName; + set + { + if (value != null || _typeReferences != null) (_typeReferences ??= new()).ValidatedSystemFamilyName = value; + } + } /// THIS stair component type's own SymbolInfo name, independent of /// the public Name/TypeId propagation. Never a borrowed level or occurrence name. [JsonIgnore] - internal string? ValidatedStairComponentTypeName { get; set; } + internal string? ValidatedStairComponentTypeName + { + get => _stairAndRailing?.ValidatedStairComponentTypeName; + set + { + if (value != null || _stairAndRailing != null) (_stairAndRailing ??= new()).ValidatedStairComponentTypeName = value; + } + } /// THIS CorniceAttr type's own SymbolInfo name. Never a borrowed /// public Name; used only with its original system family for IFC type naming. [JsonIgnore] - internal string? ValidatedCorniceTypeName { get; set; } + internal string? ValidatedCorniceTypeName + { + get => _typeReferences?.ValidatedCorniceTypeName; + set + { + if (value != null || _typeReferences != null) (_typeReferences ??= new()).ValidatedCorniceTypeName = value; + } + } /// THIS circular duct type's own SymbolInfo name, independent of /// general Name propagation; used only for IFC type-object naming. [JsonIgnore] - internal string? ValidatedDuctTypeName { get; set; } + internal string? ValidatedDuctTypeName + { + get => _mep?.ValidatedDuctTypeName; + set + { + if (value != null || _mep != null) (_mep ??= new()).ValidatedDuctTypeName = value; + } + } /// THIS pipe, flex pipe, pipe insulation or cable tray type's own SymbolInfo name; the name table can hold a /// different string for these types. [JsonIgnore] - internal string? ValidatedMepTypeName { get; set; } + internal string? ValidatedMepTypeName + { + get => _mep?.ValidatedMepTypeName; + set + { + if (value != null || _mep != null) (_mep ??= new()).ValidatedMepTypeName = value; + } + } /// Localized system family name of THIS pipe, flex pipe, pipe insulation or cable tray type. Kept apart /// from : only the current profile naming reads it (the legacy profile has no such /// products). [JsonIgnore] - internal string? ValidatedMepFamilyName { get; set; } + internal string? ValidatedMepFamilyName + { + get => _mep?.ValidatedMepFamilyName; + set + { + if (value != null || _mep != null) (_mep ??= new()).ValidatedMepFamilyName = value; + } + } /// The type of THIS MEP curve occurrence (pipe, flex pipe, pipe insulation, duct, cable tray) read /// from its own RbsCurve.m_idType and checked against the type's exact root class. The general /// FamilyTypeId can name another element's symbol for these occurrences. [JsonIgnore] - internal int? SerializedMepCurveTypeId { get; set; } + internal int? SerializedMepCurveTypeId + { + get => _mep?.SerializedMepCurveTypeId; + set + { + if (value != null || _mep != null) (_mep ??= new()).SerializedMepCurveTypeId = value; + } + } /// Exact FamilyInstance.m_masterSymbolId decoded for THIS occurrence /// (schema field presence, not an identity/name value). Set only when the native @@ -945,13 +1920,14 @@ internal bool RootClassIs(string className) => NativeRootClassName != null internal bool TypeFromNativePointer { get; set; } /// Closed-shell quantities of the solids at the Coarse, Medium and Fine detail levels (index 0, 1, 2); null at a level whose - /// solids are not all closed shells of plane faces. See ElementBuilder.ApplyInstanceQuantities. + /// solids are not all closed shells of plane faces. Null until quantities are collected. + /// See ElementBuilder.ApplyInstanceQuantities. [JsonIgnore] - internal Parsing.SolidQuantities.Shell?[] LevelShells { get; set; } = new Parsing.SolidQuantities.Shell?[3]; + internal Parsing.SolidQuantities.Shell?[]? LevelShells { get; set; } - /// Number of solids at Coarse, Medium and Fine. + /// Number of solids at Coarse, Medium and Fine. Null until quantities are collected. [JsonIgnore] - internal int[] LevelSolidCounts { get; set; } = new int[3]; + internal int[]? LevelSolidCounts { get; set; } /// Revit BuiltInCategory ID (e.g. -2000011 = OST_Walls). public int? CategoryId { get; set; } @@ -959,8 +1935,66 @@ internal bool RootClassIs(string className) => NativeRootClassName != null /// BuiltInCategory name (e.g. "OST_Walls"). public string? Category { get; set; } + private List? _parameters = new(); + private IReadOnlyList? _storedParameters; + /// The parameters of the element. - public List Parameters { get; set; } = new(); + public List Parameters + { + get + { + if (_parameters == null && _storedParameters != null) + _parameters = _storedParameters.ToList(); + return _parameters!; + } + set + { + _parameters = value; + _storedParameters = null; + } + } + + internal IReadOnlyList ReadParameters => _parameters ?? _storedParameters!; + + internal interface IArchivedParameters : IReadOnlyList + { + int FamilyTypeId { get; } + int FamilyAndTypeReferenceId { get; } + Parameter.ZeroReferenceKinds ZeroReferences { get; } + int FirstPositiveCreatedPhase { get; } + bool HasHostQuantityPlaceholder { get; } + } + + internal int FirstPositiveCreatedPhase + { + get + { + if (_parameters == null && _storedParameters is IArchivedParameters archived) + return archived.FirstPositiveCreatedPhase; + foreach (var parameter in ReadParameters) + if (parameter.Id == -1012100 && parameter.Value is int phase && phase > 0) return phase; + return -1; + } + } + + internal bool HasHostQuantityPlaceholder => + _parameters == null && _storedParameters is IArchivedParameters archived + ? archived.HasHostQuantityPlaceholder + : ReadParameters.Any(Parameter.IsHostQuantityPlaceholder); + + internal Parameter.ZeroReferenceKinds? ArchivedZeroReferences => + _parameters == null && _storedParameters is IArchivedParameters archived ? archived.ZeroReferences : null; + + internal void ArchiveParameters(Func, IReadOnlyList?, IReadOnlyList?> store) + { + if (_parameters == null) return; + var archived = _parameters.Count == 0 ? Array.Empty() : store(_parameters, _storedParameters); + _storedParameters = archived; + if (archived != null) + { + _parameters = null; + } + } /// The axis-aligned outline the element header stores: [minX, minY, minZ, maxX, maxY, maxZ] in Revit internal /// units (feet, project coordinates) - the box the application reports. Null when the header stores no outline; the @@ -978,13 +2012,32 @@ internal bool RootClassIs(string className) => NativeRootClassName != null /// reports an outline for a roof that only holds curtain panels). Everything that reads the box of an element in the IFC export reads this one. internal double[]? DecodedBox => BoundingBoxIsHeaderOutline ? Geometry?.BoundingBox : BoundingBox; + private string? _uniqueId; + private bool _uniqueIdFromExportId; + /// /// Revit UniqueId: the creation episode GUID followed by the original element ID in hexadecimal (at least eight /// digits). Both are read from the element's history in the document's element table. Null when the /// file holds no history for the element (for example an element found only in a stream), since its UniqueId cannot /// be known then. /// - public string? UniqueId { get; set; } + public string? UniqueId + { + get => _uniqueIdFromExportId + ? Parsing.ElementExportIds.UniqueIdFromExportId(SerializedExportId!.Value, (ulong)OriginalElementId!.Value) + : _uniqueId; + set + { + _uniqueIdFromExportId = false; + _uniqueId = value; + } + } + + internal void DeferUniqueId() + { + _uniqueId = null; + _uniqueIdFromExportId = true; + } /// Fully decoded public Extensible Storage entities owned by this element, when available. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] @@ -1007,10 +2060,39 @@ internal bool RootClassIs(string className) => NativeRootClassName != null /// WallType.m_function from a unique validated own BasicWallType root. [JsonIgnore] - internal int? SerializedBasicWallTypeFunction { get; set; } + internal int? SerializedBasicWallTypeFunction + { + get => _wall?.SerializedBasicWallTypeFunction; + set + { + if (value != null || _wall != null) (_wall ??= new()).SerializedBasicWallTypeFunction = value; + } + } /// IDs of directly referenced elements. - public List? References { get; set; } + public List? References + { + get + { + if (_references != null && _references is not List) + _references = _references.ToList(); + return (List?)_references; + } + set => _references = value; + } + + private IReadOnlyList? _references; + internal IReadOnlyList? ReadReferences => _references; + + internal void SetReferences(IEnumerable references, bool editable) => + _references = editable ? references.ToList() : references.ToArray(); + + internal void ArchiveReferences(Func> store) + { + // Short arrays already take less space than an index into scratch. + if (_references is int[] { Length: > 32 } values) + _references = store(values); + } /// Strings found near referenced elements, grouped by their TypeId. public Dictionary>? RefStrings { get; set; } @@ -1100,7 +2182,14 @@ internal bool RootClassIs(string className) => NativeRootClassName != null /// Own direct CurtainCellFamRef/MullionFamRef membership, distinct from /// the host which this instance can cut. Attached only from a unique native root. [JsonIgnore] - internal int? SerializedCurtainHostId { get; set; } + internal int? SerializedCurtainHostId + { + get => _wall?.SerializedCurtainHostId; + set + { + if (value != null || _wall != null) (_wall ??= new()).SerializedCurtainHostId = value; + } + } /// The geometry of an instance whose own Faces are all unfilled (a void or cut helper, see /// ) while its computed symbol has filled ones: the symbol's geometry placed by the @@ -1113,7 +2202,14 @@ internal bool RootClassIs(string className) => NativeRootClassName != null /// drivers one after the other): the order they are exported in. Null for any other element and for a wall whose /// root did not decode exactly. [JsonIgnore] - internal int[]? SerializedCurtainPanelOrder { get; set; } + internal int[]? SerializedCurtainPanelOrder + { + get => _wall?.SerializedCurtainPanelOrder; + set + { + if (value != null || _wall != null) (_wall ??= new()).SerializedCurtainPanelOrder = value; + } + } /// Exact host-of-host m_hostId reached through this element's own /// serialized m_hostId and the raw NativeParams record of that direct host. @@ -1143,8 +2239,8 @@ internal bool RootClassIs(string className) => NativeRootClassName != null /// public Parameter? LookupParameter(string name) { - foreach (var p in Parameters) - if (p.Definition?.Name == name) return p; + foreach (var p in ReadParameters) + if (p.DefinitionName == name) return p; return null; } @@ -1154,8 +2250,8 @@ internal bool RootClassIs(string className) => NativeRootClassName != null public Parameter? LookupParameter(BuiltIns.BuiltInParameter bip) { int bipId = (int)bip; - foreach (var p in Parameters) - if (p.Definition?.Id == bipId) return p; + foreach (var p in ReadParameters) + if (p.DefinitionFields?.Id == bipId) return p; return null; } @@ -1165,8 +2261,8 @@ internal bool RootClassIs(string className) => NativeRootClassName != null public IReadOnlyList GetParameters(string name) { var result = new List(); - foreach (var p in Parameters) - if (p.Definition?.Name == name) result.Add(p); + foreach (var p in ReadParameters) + if (p.DefinitionName == name) result.Add(p); return result; } @@ -1175,17 +2271,22 @@ public IReadOnlyList GetParameters(string name) /// Returns -1 if no type reference found. /// [JsonIgnore] - public int FamilyTypeId + public int FamilyTypeId => GetTypeReferenceId(includeFamilyAndType: false); + + internal int GetTypeReferenceId(bool includeFamilyAndType) { - get - { - foreach (var p in Parameters) - { - if (p.Definition?.Name is "ELEM_TYPE_PARAM" && p.Value is int id && id > 0) - return id; - } - return -1; - } + if (_parameters == null && _storedParameters is IArchivedParameters archived) + return includeFamilyAndType ? archived.FamilyAndTypeReferenceId : archived.FamilyTypeId; + return FindTypeReferenceId(ReadParameters, includeFamilyAndType); + } + + internal static int FindTypeReferenceId(IReadOnlyList parameters, bool includeFamilyAndType) + { + foreach (var parameter in parameters) + if (parameter.Value is int id && id > 0 && (parameter.DefinitionName is "ELEM_TYPE_PARAM" + || includeFamilyAndType && parameter.DefinitionName is "ELEM_FAMILY_AND_TYPE_PARAM")) + return id; + return -1; } /// diff --git a/src/RvtIO/Model/ExactIfcStringParameterResolver.cs b/src/RvtIO/Model/ExactIfcStringParameterResolver.cs index 9038d6f0..a7882d17 100644 --- a/src/RvtIO/Model/ExactIfcStringParameterResolver.cs +++ b/src/RvtIO/Model/ExactIfcStringParameterResolver.cs @@ -36,8 +36,8 @@ internal static ExactIfcStringParameterResult Resolve( Element element, string propertyName) { string cleanPropertyName = RemoveAsciiSpaces(propertyName); - var candidates = element.Parameters.Where(parameter => - parameter.Definition?.Name is string name + var candidates = element.ReadParameters.Where(parameter => + parameter.DefinitionName is string name && string.Equals( RemoveAsciiSpaces(name), cleanPropertyName, StringComparison.InvariantCultureIgnoreCase)).ToList(); diff --git a/src/RvtIO/Model/Geometry.cs b/src/RvtIO/Model/Geometry.cs index 00b9395b..6a5bf6c3 100644 --- a/src/RvtIO/Model/Geometry.cs +++ b/src/RvtIO/Model/Geometry.cs @@ -18,8 +18,36 @@ public class GeometryData /// The m_bbox of the root representation (feet, in the frame of the geometry), which may exceed the tight box. internal double[]? RootBoundingBox { get; set; } + private List? residentFaces = new(); + private IReadOnlyList? storedFaces; + /// List of geometry nodes (GGroups containing faces/edges). - public List Faces { get; set; } = new(); + public List Faces + { + get + { + if (storedFaces != null) + { + residentFaces = storedFaces.ToList(); + storedFaces = null; + } + return residentFaces!; + } + set + { + residentFaces = value; + storedFaces = null; + } + } + + internal IReadOnlyList ReadFaces => storedFaces ?? residentFaces!; + + internal void ArchiveFaces(Func, IReadOnlyList> store) + { + if (residentFaces is not { Count: > 0 } faces) return; + storedFaces = store(faces); + residentFaces = null; + } /// Classifier-only faces: no boundary and no rendered geometry. internal List? InactiveFaces { get; set; } @@ -27,13 +55,57 @@ public class GeometryData /// The Geometry nodes written as triangle sets, in the frame of (see GRepParserV2.BuildNodes). internal List? MeshNodes { get; set; } + private MeshNodeSummary[]? sceneMeshNodes; + + private readonly record struct MeshNodeSummary(int Node, bool Curved, + (double Area, double Volume)? Measures, uint[]? Markers); + + internal int MeshNodeCount => MeshNodes?.Count ?? sceneMeshNodes?.Length ?? 0; + + // The scene tessellates the polygons. Keep the analytic node facts used to compute element properties. + internal void KeepSceneMeshNodeFacts() + { + if (MeshNodes is not { Count: > 0 } nodes) return; + sceneMeshNodes = nodes.Select(node => new MeshNodeSummary(node.Node, + node.Faces.Any(face => face.SurfaceKind != RvtIO.Geometry.Meshing.SurfaceKind.Plane), + node.SourceMeasures, node.SourceMeasures.HasValue ? node.Faces.Select(face => (uint)face.Marker).ToArray() : null)).ToArray(); + MeshNodes = null; + } + + internal bool TryGetMeshNodeMeasures(int node, IEnumerable markers, out (double Area, double Volume) measures) + { + if (sceneMeshNodes != null) + { + foreach (var summary in sceneMeshNodes) + { + if (summary.Node != node) continue; + if (summary.Measures is { } source && markers.ToHashSet().SetEquals(summary.Markers!)) + { + measures = source; + return true; + } + break; + } + } + else if (MeshNodes?.FirstOrDefault(item => item.Node == node) is { SourceMeasures: { } source } original + && markers.ToHashSet().SetEquals(original.Faces.Select(face => (uint)face.Marker))) + { + measures = source; + return true; + } + measures = default; + return false; + } + /// The surface integrals of the Geometry nodes (see GRepData.NodeMeasures), under the node ids of . internal List? NodeMeasures { get; set; } /// A Geometry node written as a triangle set has a face that is not a plane (a round end, a hole): the body is the face meshes, /// whatever the dense polygons of the planar faces close into. - internal bool HasCurvedFace(IReadOnlyCollection? nodes = null) => MeshNodes?.Any(node => (nodes == null || nodes.Contains(node.Node)) - && node.Faces.Any(face => face.SurfaceKind != RvtIO.Geometry.Meshing.SurfaceKind.Plane)) == true; + internal bool HasCurvedFace(IReadOnlyCollection? nodes = null) => sceneMeshNodes != null + ? sceneMeshNodes.Any(node => node.Curved && (nodes == null || nodes.Contains(node.Node))) + : MeshNodes?.Any(node => (nodes == null || nodes.Contains(node.Node)) + && node.Faces.Any(face => face.SurfaceKind != RvtIO.Geometry.Meshing.SurfaceKind.Plane)) == true; /// List of edges with 3D coordinates. public List? Edges { get; set; } @@ -116,21 +188,32 @@ public class GeoInstance /// A planar face defined by origin + two direction vectors. public class GeoFace { + /// Creates a face with zero-initialized frame vectors. + public GeoFace() : this(new double[3], new double[3], new double[3], new double[3]) { } + + internal GeoFace(double[] origin, double[] xVector, double[] yVector, double[] normal) + { + Origin = origin; + XVector = xVector; + YVector = yVector; + Normal = normal; + } + /// GFace.m_renderStyleId: the material element id of the face (internal; not serialized). [System.Text.Json.Serialization.JsonIgnore] internal int? RenderStyleId { get; set; } /// Plane origin [x, y, z] in feet. - public double[] Origin { get; set; } = new double[3]; + public double[] Origin { get; set; } /// Plane X direction vector [x, y, z]. - public double[] XVector { get; set; } = new double[3]; + public double[] XVector { get; set; } /// Plane Y direction vector [x, y, z]. - public double[] YVector { get; set; } = new double[3]; + public double[] YVector { get; set; } /// Normal = XVector x YVector (computed). - public double[] Normal { get; set; } = new double[3]; + public double[] Normal { get; set; } /// 2D envelope of the face in parametric space [minU, minV, maxU, maxV]. public double[]? Envelope { get; set; } diff --git a/src/RvtIO/Model/Parameter.cs b/src/RvtIO/Model/Parameter.cs index e54226ca..4c7ac77d 100644 --- a/src/RvtIO/Model/Parameter.cs +++ b/src/RvtIO/Model/Parameter.cs @@ -13,6 +13,8 @@ public class Parameter internal Parameter ShallowCopy(object? value) { var copy = (Parameter)MemberwiseClone(); + copy._definition = Definition; + copy._metadata = _metadata?.Copy(); if (!Equals(copy._value, value)) copy.HasResolvedZeroElementId = false; copy._value = value; @@ -20,11 +22,46 @@ internal Parameter ShallowCopy(object? value) } private object? _value; + private object? _definition; + private Metadata? _metadata; + + internal bool HasSupplementalMetadata => _metadata != null; + + private sealed class Metadata + { + internal Guid? Guid; + internal string? ForgeId; + internal string? SpecType; + internal string? UnitSymbol; + internal double? ConversionFactor; + internal long? NativeElementId; + + internal Metadata Copy() => (Metadata)MemberwiseClone(); + } + + internal sealed record DefinitionTemplate(int Id, string? Name, string? BuiltIn) + { + internal DefinitionTemplate(int id, string name) : this(id, name, name) { } + } + + /// Creates an empty parameter with its own mutable definition. + public Parameter() => _definition = new Definition(); + + internal Parameter(DefinitionTemplate? definition) => _definition = definition; + + internal Parameter(Definition definition) => _definition = definition; /// GUID of shared/external parameters (parsed from ForgeId). Null for built-in params. /// Invariant per definition id - serialized once in the document's ParameterDefinitions table. [JsonIgnore] - public Guid? Guid { get; set; } + public Guid? Guid + { + get => _metadata?.Guid; + set + { + if (value != null || _metadata != null) (_metadata ??= new()).Guid = value; + } + } /// /// For built-in params: the BIP enum int value (same as Definition.Id, negative). @@ -36,7 +73,25 @@ internal Parameter ShallowCopy(object? value) /// Definition (name/BIP). Invariant per ; hoisted into the /// document-level ParameterDefinitions table for JSON, so it is not serialized inline. [JsonIgnore] - public Definition Definition { get; set; } = new(); + public Definition Definition + { + get => _definition is DefinitionTemplate template + ? (Definition)(_definition = new Definition { Id = template.Id, Name = template.Name, BuiltInParameter = template.BuiltIn }) + : (Definition)_definition!; + set => _definition = value; + } + + internal string? DefinitionName => _definition is DefinitionTemplate template ? template.Name : ((Definition?)_definition)?.Name; + + internal static bool IsHostQuantityPlaceholder(Parameter parameter) => parameter.Id is -1012805 or -1012806 or -1012807 + && ((parameter.Value is double number && number <= 0) || (parameter.Value is int integer && integer <= 0)); + + internal (int Id, string? Name, string? BuiltIn)? DefinitionFields => _definition switch + { + DefinitionTemplate template => (template.Id, template.Name, template.BuiltIn), + Definition definition => (definition.Id, definition.Name, definition.BuiltInParameter), + _ => null, + }; /// Storage type. Invariant per definition id - lives in ParameterDefinitions. [JsonIgnore] @@ -66,23 +121,51 @@ public object? Value /// Forge TypeId string for user-defined/shared params (e.g. "autodesk.parameter.aec.revit.external.-1:GUID-1.0.0"). /// Invariant per definition id - lives in ParameterDefinitions. [JsonIgnore] - public string? ForgeId { get; set; } + public string? ForgeId + { + get => _metadata?.ForgeId; + set + { + if (value != null || _metadata != null) (_metadata ??= new()).ForgeId = value; + } + } /// Measurement spec type (e.g. "autodesk.spec.aec:length-2.0.0"). /// Resolved from ForgeId via 0x0B3A blocks, or from BIP name heuristics. [JsonIgnore] - public string? SpecType { get; set; } + public string? SpecType + { + get => _metadata?.SpecType; + set + { + if (value != null || _metadata != null) (_metadata ??= new()).SpecType = value; + } + } /// Display unit symbol (e.g. "mm", "m^2", "degC"). /// Resolved from SpecType via 0x0FBD ForgeTypeId spec registry. /// Invariant per definition id - lives in ParameterDefinitions. [JsonIgnore] - public string? UnitSymbol { get; set; } + public string? UnitSymbol + { + get => _metadata?.UnitSymbol; + set + { + if (value != null || _metadata != null) (_metadata ??= new()).UnitSymbol = value; + } + } /// Conversion factor from Revit internal units to display units. /// E.g. for length: feet -> mm = 304.8. [JsonIgnore] - public double? ConversionFactor { get; set; } + public double? ConversionFactor + { + get => _metadata?.ConversionFactor; + set + { + if (value != null || _metadata != null) (_metadata ??= new()).ConversionFactor = value; + } + } /// True when this parameter's value came from an approximate fallback /// (e.g. dominant bounding-box dimension) rather than an exact decoded source (e.g. @@ -185,10 +268,30 @@ internal static bool IsValidZeroElementIdTarget( return false; } + [Flags] + internal enum ZeroReferenceKinds : byte + { + None = 0, + Resolved = 1, + Phase = 2, + DimensionStyle = 4, + } + + internal ZeroReferenceKinds ClassifyZeroReference() + { + var kinds = HasResolvedZeroElementId ? ZeroReferenceKinds.Resolved : ZeroReferenceKinds.None; + if (StorageType != StorageType.ElementId || Value is not int id || id != 0) return kinds; + if (IsPhaseElementIdParameter(Id)) kinds |= ZeroReferenceKinds.Phase; + if (IsTypeElementIdParameter(Id)) kinds |= ZeroReferenceKinds.DimensionStyle; + return kinds; + } + /// Marks on each parameter whose 0 element-id /// value resolves to a real target element with id 0 in its domain. - internal static void ResolveZeroElementIds(RevitFileInfo info, RvtIO.Internal.ParsingState? state = null) + internal static void ResolveZeroElementIds(RevitFileInfo info, RvtIO.Internal.ParsingState? state = null, + Action? archiveParameters = null) { + archiveParameters ??= state?.ArchiveSceneParameters; bool hasZeroPhase = HasZeroProjectPhase(info, state); bool hasZeroDimStyle = HasZeroDimensionStyle(info, state); if (state != null) @@ -196,20 +299,22 @@ internal static void ResolveZeroElementIds(RevitFileInfo info, RvtIO.Internal.Pa info.SerializedHasZeroProjectPhase = hasZeroPhase; info.SerializedHasZeroDimensionStyle = hasZeroDimStyle; } + var relevant = ZeroReferenceKinds.Resolved; + if (hasZeroPhase) relevant |= ZeroReferenceKinds.Phase; + if (hasZeroDimStyle) relevant |= ZeroReferenceKinds.DimensionStyle; foreach (var element in info.Elements) { - foreach (var parameter in element.Parameters) + if (element.ArchivedZeroReferences is { } kinds && (kinds & relevant) == 0) continue; + int index = -1; + foreach (var parameter in element.ReadParameters) { - if (parameter.StorageType == StorageType.ElementId && parameter.Value is int eid && eid == 0) - { - parameter.HasResolvedZeroElementId = - IsValidZeroElementIdTarget(element, parameter.Id, hasZeroPhase, hasZeroDimStyle); - } - else if (parameter.HasResolvedZeroElementId) - { - parameter.HasResolvedZeroElementId = false; - } + index++; + bool resolves = parameter.StorageType == StorageType.ElementId && parameter.Value is int eid && eid == 0 + && IsValidZeroElementIdTarget(element, parameter.Id, hasZeroPhase, hasZeroDimStyle); + if (parameter.HasResolvedZeroElementId != resolves) + element.Parameters[index].HasResolvedZeroElementId = resolves; } + archiveParameters?.Invoke(element); } } @@ -301,7 +406,14 @@ public long AsElementId64() => [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public string? SourceElementId => NativeElementId?.ToString(CultureInfo.InvariantCulture); - internal long? NativeElementId { get; set; } + internal long? NativeElementId + { + get => _metadata?.NativeElementId; + set + { + if (value != null || _metadata != null) (_metadata ??= new()).NativeElementId = value; + } + } /// /// Get a formatted display string for the value. diff --git a/src/RvtIO/Model/ProductRules.cs b/src/RvtIO/Model/ProductRules.cs index 09b2cdbc..98e1aa4b 100644 --- a/src/RvtIO/Model/ProductRules.cs +++ b/src/RvtIO/Model/ProductRules.cs @@ -17,17 +17,17 @@ internal static class ProductRules /// an instance whose own geometry is null is not exported (for example the floor-hosted family /// "Assignment - Rectangular opening (floor)"). Faces whose flags are not known (placed from a nested symbol) count as filled. internal static bool HasOnlyUnfilledFaces(Element element) => - element.Geometry?.Faces is { Count: > 0 } faces + element.Geometry?.ReadFaces is { Count: > 0 } faces && faces.All(face => face.GInfoFlags is uint flags && (flags & FaceFillFlag) == 0); /// Whether the element names its created phase (PHASE_CREATED) in its own record graph. Preview and type records /// inherit the parameter during parameter propagation without referencing that phase. internal static bool HasProjectPhaseReference(Element e) { - int? phase = e.Parameters.FirstOrDefault(p => p.Id == -1012100)?.Value is int n ? n : null; // PHASE_CREATED + int? phase = e.ReadParameters.FirstOrDefault(p => p.Id == -1012100)?.Value is int n ? n : null; // PHASE_CREATED // Id 0 is a phase of Revit 2023 and later (the first project phase, a row of its // element table); the earlier layouts number phases from 1. - return phase is > 0 && (e.References?.Contains(phase.Value) == true || e.SerializedCreatedPhaseId == phase.Value) + return phase is > 0 && (e.ReadReferences?.Contains(phase.Value) == true || e.SerializedCreatedPhaseId == phase.Value) || phase == 0 && e.SerializedCreatedPhaseId == 0; } @@ -36,7 +36,7 @@ internal static HashSet TypeElementIds(IEnumerable elements) { var typeElementIds = new HashSet(); foreach (var e in elements) - foreach (var p in e.Parameters) + foreach (var p in e.ReadParameters) if (p.Id is -1002050 or -1002052 && p.Value is int typeId && typeId > 0) typeElementIds.Add(typeId); return typeElementIds; diff --git a/src/RvtIO/Model/RevitFileInfo.cs b/src/RvtIO/Model/RevitFileInfo.cs index a2e1d512..4d187158 100644 --- a/src/RvtIO/Model/RevitFileInfo.cs +++ b/src/RvtIO/Model/RevitFileInfo.cs @@ -42,7 +42,7 @@ public partial class RevitFileInfo [System.Text.Json.Serialization.JsonIgnore(Condition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull)] public IReadOnlyDictionary? SourceElementIds => ElementIds?.SourceIdsAsText(); - internal void AttachSourceElementIds() + internal void AttachSourceElementIds(Action? archiveParameters = null) { if (ElementIds is not { } ids) return; long? WhenRemapped(int key) @@ -55,9 +55,18 @@ internal void AttachSourceElementIds() element.NativeId = WhenRemapped(element.Id); element.NativeTypeId = WhenRemapped(element.TypeId); element.NativeHostId = element.HostId is int host ? WhenRemapped(host) : null; - foreach (var parameter in element.Parameters) + int index = -1; + foreach (var parameter in element.ReadParameters) + { + index++; if (parameter.StorageType == StorageType.ElementId && parameter.Value is int key) - parameter.NativeElementId = WhenRemapped(key); + { + long? sourceId = WhenRemapped(key); + if (parameter.NativeElementId != sourceId) + element.Parameters[index].NativeElementId = sourceId; + } + } + archiveParameters?.Invoke(element); } } diff --git a/src/RvtIO/Parsing/BipHelpers.cs b/src/RvtIO/Parsing/BipHelpers.cs index 91c4c4c4..f6348176 100644 --- a/src/RvtIO/Parsing/BipHelpers.cs +++ b/src/RvtIO/Parsing/BipHelpers.cs @@ -5,15 +5,26 @@ namespace RvtIO.Parsing; internal static class BipHelpers { - public static Parameter MakeBipParam(int bipId, string bipName, StorageType storageType, object value, bool hasNoRevitValue = false) => new() + private static class BuiltInDefinitions { - Id = bipId, - StorageType = storageType, - Value = value, - HasNoRevitValue = hasNoRevitValue, - IsReadOnly = IsBipReadOnly(bipName), - Definition = new Definition { Id = bipId, BuiltInParameter = bipName, Name = bipName }, - }; + internal static readonly Dictionary ById = BipNames.Lookup.ToDictionary( + entry => entry.Key, entry => new Parameter.DefinitionTemplate(entry.Key, entry.Value)); + } + + public static Parameter MakeBipParam(int bipId, string? bipName, StorageType storageType, object? value, + bool hasNoRevitValue = false) + { + var parameter = bipName != null && BuiltInDefinitions.ById.TryGetValue(bipId, out var template) + && bipName == template.Name + ? new Parameter(template) + : new Parameter(new Definition { Id = bipId, BuiltInParameter = bipName, Name = bipName }); + parameter.Id = bipId; + parameter.StorageType = storageType; + parameter.Value = value; + parameter.HasNoRevitValue = hasNoRevitValue; + parameter.IsReadOnly = IsBipReadOnly(bipName); + return parameter; + } public static StorageType BipStorageType(string? bipName) { diff --git a/src/RvtIO/Parsing/BlockParser.cs b/src/RvtIO/Parsing/BlockParser.cs index 01d292e8..7fd91054 100644 --- a/src/RvtIO/Parsing/BlockParser.cs +++ b/src/RvtIO/Parsing/BlockParser.cs @@ -11,50 +11,73 @@ internal static class BlockParser private static readonly string? DumpGrepEnvironment = Environment.GetEnvironmentVariable("RVTIO_DUMP_GREP"); /// A GRep block collected for decoding after the walk of one or several chunks. - internal readonly record struct PendingGRep(byte[] Chunk, uint Eid, int Start, uint Size, bool IsFamilyCut); + internal readonly record struct PendingGRep(byte[] Chunk, uint Eid, int Start, uint Size, bool IsFamilyCut) + { + internal PartitionChunks.Block? Stored { get; init; } + } /// Decodes the collected GRep blocks and applies them in collection order (the merge rules depend on /// arrival order). - internal static void ApplyPendingGReps(ParsingState state, List pending) + internal static void ApplyPendingGReps(ParsingState state, List pending, Action? progress = null) { - if (pending.Count == 0) return; DecodeGRepBlocksInOrder(pending.Count, index => { var job = pending[index]; - return GRepParserV2.Parse(job.Chunk, job.Start, job.Size); + var (data, start) = job.Stored?.Read() ?? (job.Chunk, job.Start); + return GRepParserV2.Parse(data, start, job.Size); }, - (index, geometry) => ApplyPendingGRep(state, pending[index], geometry)); + (index, geometry) => ApplyPendingGRep(state, pending[index], geometry), progress); } /// Applies one decoded block of a pass: a family cutter is kept when it is the first authored one of its /// element, any other block is merged into the element's geometry. internal static void ApplyPendingGRep(ParsingState state, PendingGRep job, GRepData? geometry) { + if (geometry == null) return; + var stored = job.Stored; + if (stored == null && state.PartitionScratch is { } backing) + stored = new PartitionChunks.Block(job.Chunk, job.Start, checked((int)job.Size + 16), backing); if (job.IsFamilyCut) { - if (!state.FamilyCutGreps.ContainsKey(job.Eid) - && geometry is { } familyCut && IsAuthoredFamilyComplexCutter(familyCut)) - state.FamilyCutGreps[job.Eid] = familyCut; + if (!state.FamilyCutGreps.ContainsKey(job.Eid) && IsAuthoredFamilyComplexCutter(geometry)) + state.FamilyCutGreps.Set(job.Eid, geometry, stored, job.Size); } - else ApplyGRepBlock(state, job.Eid, geometry); + else ApplyGRepBlock(state.GrepBlocks, job.Eid, geometry, stored, job.Size); } /// Decodes blocks and applies each result on the calling thread in index order. /// A browser decodes and applies one block at a time; elsewhere the blocks are decoded in parallel. - internal static void DecodeGRepBlocksInOrder(int count, Func decode, Action apply) => - DecodeGRepBlocksInOrder(count, decode, apply, OperatingSystem.IsBrowser()); + internal static void DecodeGRepBlocksInOrder(int count, Func decode, Action apply, + Action? progress = null) => + DecodeGRepBlocksInOrder(count, decode, apply, OperatingSystem.IsBrowser(), progress); /// The seam of the overload above: selects the one-block-at-a-time path of a /// browser. internal static void DecodeGRepBlocksInOrder( - int count, Func decode, Action apply, bool sequential) + int count, Func decode, Action apply, bool sequential, + Action? progress = null) { + if (count == 0) return; + var clock = progress == null ? null : System.Diagnostics.Stopwatch.StartNew(); + progress?.Invoke(0, count); + + void Apply(int index, GRepData? geometry) + { + apply(index, geometry); + int completed = index + 1; + if (clock != null && (completed == count || clock.ElapsedMilliseconds >= 500)) + { + progress!(completed, count); + clock.Restart(); + } + } + if (sequential) { // A browser has a bounded WebAssembly heap: release each unused result before decoding the next block. for (int index = 0; index < count; index++) - apply(index, decode(index)); + Apply(index, decode(index)); return; } @@ -64,7 +87,7 @@ internal static void DecodeGRepBlocksInOrder( Parallel.For(0, count, index => decoded[index] = decode(index)); for (int index = 0; index < count; index++) { - apply(index, decoded[index]); + Apply(index, decoded[index]); decoded[index] = null; } } @@ -247,7 +270,8 @@ internal static bool ParseBlock(byte[] chunk, int pos, uint eid, uint dataSize, { ExtractBlockStrings(chunk, dataStart, dataEnd, eid, state.ElemStrings); - ExtractBlockDoubles(chunk, dataStart, dataEnd, eid, state.ElemDoubles); + if (state.KeepExportProvenance) + ExtractBlockDoubles(chunk, dataStart, dataEnd, eid, state.ElemDoubles); // Blocks with high classIdx word = 0xFFFF contain BIP key->double pairs at stride 12 if ((classIdx >> 16) == 0xFFFF) @@ -429,65 +453,33 @@ internal static bool ParseBlock(byte[] chunk, int pos, uint eid, uint dataSize, } /// Merges one decoded GRep block into the element's geometry (arrival-order rules). - private static void ApplyGRepBlock(ParsingState state, uint eid, Internal.GRepData? gdV2) + private static void ApplyGRepBlock(GRepBlockStore blocks, uint eid, GRepData candidate, + PartitionChunks.Block? stored, uint size) { - - // Edge UV pairs are mapped to world via the face Planes (scanned from - // the block tail): a real tessellated BRep. Use it whenever it produced - // >=2 world faces; else keep the pattern scan. - var gd = gdV2; - // GInstance reference (family instances): carry the symbol id + placement - // regardless of which decoder supplied the faces - the element's real - // geometry is the SYMBOL's, transformed (IfcMappedItem architecture). - if (gdV2 is { Instances.Count: > 0 }) - { - gd ??= new Internal.GRepData(); - MergeGRepInstances(gd, gdV2); - } - if (gd != null) - { - if (!state.GrepBlocks.TryGetValue(eid, out var existing)) - { - state.GrepBlocks[eid] = gd; - } - else - { - // Separate GRep blocks may store the resolved display mesh beside an - // explicit GInstance mapped representation. They are alternatives, not - // additive geometry: combining their faces duplicates all or part of - // the symbol body. The serialized GInstance is authoritative because it - // identifies both the source symbol and its exact placement transform. - bool? preferCandidateMapped = PreferExplicitMappedRepresentation(existing, gd); - if (preferCandidateMapped.HasValue) - { - if (preferCandidateMapped.Value) state.GrepBlocks[eid] = gd; - return; - } - - // Tiebreakers (in priority order): - // 1. Upgrade if existing has no faces and new one does - // 2. Prefer world-coordinate transform - // 3. Prefer non-axis-aligned faces (world-oriented) - // Don't naively pick "more faces" - different blocks describe different - // aspects (e.g. an analytical model vs the actual wall) and the larger - // block may not be the structural geometry. - bool replace = false; - int VertCount(Internal.GRepData g) => - g.Faces.Sum(fc => fc.Vertices?.Count ?? 0); - int gv = VertCount(gd), ev = VertCount(existing); - // Real tessellated geometry (more actual polygon vertices) always wins. - if (gv > ev + 2) replace = true; - else if (existing.Faces.Count == 0 && gd.Faces.Count > 0) replace = true; - else if (gd.Transform != null && existing.Transform == null) replace = true; - else if (HasNonAxisAlignedFaces(gd) && !HasNonAxisAlignedFaces(existing)) replace = true; - if (replace) - { - MergeGRepInstances(gd, existing); - state.GrepBlocks[eid] = gd; - } - else MergeGRepInstances(existing, gd); - } - } + MergeGRepInstances(candidate, candidate.Instances); + if (!blocks.TryGetRank(eid, out var existing)) + { + blocks.Set(eid, candidate, stored, size); + return; + } + + var rank = GRepBlockStore.Rank.From(candidate); + // An explicit mapped representation is authoritative over a resolved display mesh. + if (existing.Mapped != rank.Mapped) + { + if (rank.Mapped) blocks.Set(eid, candidate, stored, size); + return; + } + + if (rank.VertexCount > existing.VertexCount + 2 + || existing.FaceCount == 0 && rank.FaceCount > 0 + || rank.Transformed && !existing.Transformed + || rank.Angled && !existing.Angled) + { + MergeGRepInstances(candidate, blocks.Instances(eid)); + blocks.Set(eid, candidate, stored, size); + } + else blocks.MergeInstances(eid, candidate.Instances); } /// A partial family cutter needs its serialized dummy-host closure plane. @@ -501,49 +493,25 @@ internal static bool IsAuthoredFamilyComplexCutter(GRepData geometry) return hasClosurePlane || geometry.Solids.Any(solid => solid.IsClosed); } - /// - /// Returns which of two separate GRep blocks to keep when exactly one is an explicit - /// mapped representation. A null result means both blocks have the same representation - /// kind and the ordinary geometry-quality comparison must decide between them. - /// - internal static bool? PreferExplicitMappedRepresentation(GRepData existing, GRepData candidate) + internal static void MergeGRepInstances(GRepData target, IReadOnlyList source) { - bool existingMapped = existing.Instances.Count > 0; - bool candidateMapped = candidate.Instances.Count > 0; - return existingMapped == candidateMapped ? null : candidateMapped; + MergeGRepInstances(target.Instances, source); + if (target.Instances.Count == 0) return; + target.SymbolElemId = target.Instances[0].SymbolElemId; + target.InstanceTransform = target.Instances[0].Transform; } - private static void MergeGRepInstances(GRepData target, GRepData source) + internal static void MergeGRepInstances(List target, IReadOnlyList source) { - foreach (var instance in source.Instances) - if (!target.Instances.Any(x => x.SymbolElemId == instance.SymbolElemId + if (ReferenceEquals(target, source)) return; + foreach (var instance in source) + if (!target.Any(x => x.SymbolElemId == instance.SymbolElemId && x.Transform.SequenceEqual(instance.Transform))) - target.Instances.Add(new GRepInstance + target.Add(new GRepInstance { SymbolElemId = instance.SymbolElemId, Transform = (double[])instance.Transform.Clone(), }); - var primary = target.Instances.FirstOrDefault(); - if (primary != null) - { - target.SymbolElemId = primary.SymbolElemId; - target.InstanceTransform = primary.Transform; - } - } - - /// - /// Check if any face in the GRep data has non-axis-aligned direction vectors, - /// which indicates the geometry is in world coordinates (not wall-local). - /// - private static bool HasNonAxisAlignedFaces(GRepData gd) - { - foreach (var face in gd.Faces) - { - double ax = Math.Abs(face.XVector[0]), ay = Math.Abs(face.XVector[1]); - if (ax > 0.01 && ay > 0.01) - return true; - } - return false; } public static void ExtractBlockStrings(byte[] d, int start, int end, uint eid, Dictionary> elemStrings) diff --git a/src/RvtIO/Parsing/ElementBuilder.CoarseSurface.cs b/src/RvtIO/Parsing/ElementBuilder.CoarseSurface.cs index 770b67b6..5a30e1c8 100644 --- a/src/RvtIO/Parsing/ElementBuilder.CoarseSurface.cs +++ b/src/RvtIO/Parsing/ElementBuilder.CoarseSurface.cs @@ -21,14 +21,16 @@ internal static void ApplyCoarseDoorWindowSurfaces(RevitFileInfo info, ParsingSt } if (element.CategoryId is not (DoorsCategoryId or WindowsCategoryId)) continue; uint id = (uint)element.Id; - state.GrepBlocks.TryGetValue(id, out var grep); state.FamilyInstanceTransforms.TryGetValue(id, out var transformOnly); var visited = new HashSet(); - if (!HasQuantityAlternative(grep, state, visited) - && !(transformOnly != null && state.GrepBlocks.TryGetValue((uint)Math.Max(transformOnly.SymbolId, 0), out var symbol) - && HasQuantityAlternative(symbol, state, visited))) + const GRepBlockStore.DetailAlternatives alternatives = + GRepBlockStore.DetailAlternatives.Coarse | GRepBlockStore.DetailAlternatives.CoarseQuantities; + if (!state.GrepBlocks.HasDetailAlternative(id, alternatives, visited) + && !(transformOnly != null + && state.GrepBlocks.HasDetailAlternative((uint)Math.Max(transformOnly.SymbolId, 0), alternatives, visited))) continue; + state.GrepBlocks.TryGetValue(id, out var grep); state.CoarseView = true; state.IncludeNonVisibleQuantities = true; try @@ -56,13 +58,14 @@ internal static void ApplyCoarseDoorWindowSurfaces(RevitFileInfo info, ParsingSt private static void ApplyMediumLevelVolume(Element element, ParsingState state) { uint id = (uint)element.Id; - state.GrepBlocks.TryGetValue(id, out var grep); state.FamilyInstanceTransforms.TryGetValue(id, out var transformOnly); var visited = new HashSet(); - if (!HasAlternative(grep, state, visited, 2) - && !(transformOnly != null && state.GrepBlocks.TryGetValue((uint)Math.Max(transformOnly.SymbolId, 0), out var symbol) - && HasAlternative(symbol, state, visited, 2))) + const GRepBlockStore.DetailAlternatives alternativeLevel = GRepBlockStore.DetailAlternatives.Medium; + if (!state.GrepBlocks.HasDetailAlternative(id, alternativeLevel, visited) + && !(transformOnly != null + && state.GrepBlocks.HasDetailAlternative((uint)Math.Max(transformOnly.SymbolId, 0), alternativeLevel, visited))) return; + state.GrepBlocks.TryGetValue(id, out var grep); element.HasMediumAlternatives = true; state.DetailView = 2; try @@ -79,17 +82,4 @@ private static void ApplyMediumLevelVolume(Element element, ParsingState state) } finally { state.DetailView = 0; } } - - /// True when the block or a nested symbol has a separate Coarse or non-visible quantity view. - private static bool HasQuantityAlternative(GRepData? block, ParsingState state, HashSet visited) - { - if (block == null) return false; - if (block.Coarse != null || block.CoarseQuantities != null) return true; - foreach (var instance in block.Instances) - if (instance.SymbolElemId > 0 && visited.Add((uint)instance.SymbolElemId) - && state.GrepBlocks.TryGetValue((uint)instance.SymbolElemId, out var symbol) - && HasQuantityAlternative(symbol, state, visited)) - return true; - return false; - } } diff --git a/src/RvtIO/Parsing/ElementBuilder.FramingCutLength.cs b/src/RvtIO/Parsing/ElementBuilder.FramingCutLength.cs index 5014d7e1..bef37acf 100644 --- a/src/RvtIO/Parsing/ElementBuilder.FramingCutLength.cs +++ b/src/RvtIO/Parsing/ElementBuilder.FramingCutLength.cs @@ -20,7 +20,7 @@ internal static void ApplyFramingCutLength(RevitFileInfo info) { if (e.CategoryId != -2001320 || e.NativeMasterSymbolId == null || e.CurveDriverLineDirection is not { } direction || e.FramingCopingDistance != -1 - || e.Geometry?.Faces is not { Count: > 0 } faces + || e.Geometry?.ReadFaces is not { Count: > 0 } faces || e.Parameters.FirstOrDefault(p => p.Id == IndependentJustificationParamId)?.Value is not (null or 0)) continue; double min = double.MaxValue, max = double.MinValue; diff --git a/src/RvtIO/Parsing/ElementBuilder.InstanceQuantities.cs b/src/RvtIO/Parsing/ElementBuilder.InstanceQuantities.cs index 496d535c..a4f18896 100644 --- a/src/RvtIO/Parsing/ElementBuilder.InstanceQuantities.cs +++ b/src/RvtIO/Parsing/ElementBuilder.InstanceQuantities.cs @@ -44,8 +44,9 @@ internal static void ApplyInstanceQuantities(RevitFileInfo info, IReadOnlyDictio if (e.NativeMasterSymbolId != null && (!classByElement.TryGetValue((uint)e.Id, out var rootClass) || rootClass != FamilyInstanceRootClassId)) continue; if (ProductRules.HasOnlyUnfilledFaces(e)) continue; if (category == -2001320 && e.FramingCopingDistance is not < 0) continue; - int level = Array.FindIndex(e.LevelSolidCounts, count => count > 0); - if (level < 0 || e.LevelShells[level] is not { } shell) continue; + if (e.LevelSolidCounts is not { } counts || e.LevelShells is not { } shells) continue; + int level = Array.FindIndex(counts, count => count > 0); + if (level < 0 || shells[level] is not { } shell) continue; if (volume) SetParam(e, -1012806, "HOST_VOLUME_COMPUTED", StorageType.Double, shell.Volume); if (area) SetParam(e, -1012805, "HOST_AREA_COMPUTED", StorageType.Double, shell.SurfaceArea / 2); } diff --git a/src/RvtIO/Parsing/ElementBuilder.MullionLength.cs b/src/RvtIO/Parsing/ElementBuilder.MullionLength.cs index 4308cfe3..5ec1cc09 100644 --- a/src/RvtIO/Parsing/ElementBuilder.MullionLength.cs +++ b/src/RvtIO/Parsing/ElementBuilder.MullionLength.cs @@ -6,7 +6,8 @@ internal static partial class ElementBuilder { // shortcut: curved axes retain the geometry fallback until their own symbol curve metrics are decoded. internal static void ApplyMullionSymbolLength( - IReadOnlyList elements, IReadOnlyDictionary nativeParams) + IReadOnlyList elements, IReadOnlyDictionary nativeParams, + Action? archiveParameters = null) { foreach (var element in elements) { @@ -28,6 +29,7 @@ internal static void ApplyMullionSymbolLength( if (!complete || !double.IsFinite(length) || length <= 0) continue; SetParam(element, -1004005, "CURVE_ELEM_LENGTH", StorageType.Double, length); element.Parameters.First(parameter => parameter.Id == -1004005).IsApproximate = false; + archiveParameters?.Invoke(element); } } } diff --git a/src/RvtIO/Parsing/ElementBuilder.OwnFamilyCutout.cs b/src/RvtIO/Parsing/ElementBuilder.OwnFamilyCutout.cs index 90263d35..76550eb0 100644 --- a/src/RvtIO/Parsing/ElementBuilder.OwnFamilyCutout.cs +++ b/src/RvtIO/Parsing/ElementBuilder.OwnFamilyCutout.cs @@ -70,7 +70,7 @@ internal static void ApplySolidTrimmedAxis(IReadOnlyList elements) if (element.OwnWallTrimmedAxis != null || element.CategoryId != -2000011 || element.Location is not { CurveType: "Line", DriverOrigin: { Length: 3 } o, DriverDirection: { Length: 3 } d, DriverEndParams: { Length: 2 } endParams } - || element.Geometry?.Faces is not { Count: > 0 } faces) continue; + || element.Geometry?.ReadFaces is not { Count: > 0 } faces) continue; var solidFaces = element.Geometry.BrepSolids is { Count: > 0 } solids ? solids[0].FaceIndices.Where(i => (uint)i < (uint)faces.Count).Select(i => faces[i]) : faces; if (SolidTrimmedRange(solidFaces, o, d, endParams) is not var (lo, hi)) continue; diff --git a/src/RvtIO/Parsing/ElementBuilder.SolidQuantities.cs b/src/RvtIO/Parsing/ElementBuilder.SolidQuantities.cs index 5fbbcd0a..1b298901 100644 --- a/src/RvtIO/Parsing/ElementBuilder.SolidQuantities.cs +++ b/src/RvtIO/Parsing/ElementBuilder.SolidQuantities.cs @@ -13,13 +13,15 @@ internal static void ApplyShellQuantities(RevitFileInfo info, ParsingState state { foreach (var element in info.Elements) { - element.LevelShells = new SolidQuantities.Shell?[3]; - element.LevelSolidCounts = new int[3]; + var shells = new SolidQuantities.Shell?[3]; + var counts = new int[3]; LevelGeometries(element, state, (slot, geometry) => { - element.LevelShells[slot] = SolidQuantities.OfAllSolids(geometry); - element.LevelSolidCounts[slot] = geometry?.BrepSolids?.Count ?? 0; + shells[slot] = SolidQuantities.OfAllSolids(geometry); + counts[slot] = geometry?.BrepSolids?.Count ?? 0; }); + element.LevelShells = shells; + element.LevelSolidCounts = counts; } } @@ -38,16 +40,18 @@ internal static void LevelGeometries(Element element, ParsingState state, Action return; } uint id = (uint)element.Id; - state.GrepBlocks.TryGetValue(id, out var grep); + GRepData? grep = null; state.FamilyInstanceTransforms.TryGetValue(id, out var transformOnly); for (int level = 1; level <= 2; level++) { var visited = new HashSet(); - bool has = HasAlternative(grep, state, visited, level) - || (transformOnly != null && state.GrepBlocks.TryGetValue((uint)Math.Max(transformOnly.SymbolId, 0), out var symbol) - && HasAlternative(symbol, state, visited, level)); + var alternative = level == 1 ? GRepBlockStore.DetailAlternatives.Coarse : GRepBlockStore.DetailAlternatives.Medium; + bool has = state.GrepBlocks.HasDetailAlternative(id, alternative, visited) + || (transformOnly != null + && state.GrepBlocks.HasDetailAlternative((uint)Math.Max(transformOnly.SymbolId, 0), alternative, visited)); int slot = level == 1 ? 0 : 1; if (!has) { visit(slot, element.Geometry); continue; } + if (grep == null) state.GrepBlocks.TryGetValue(id, out grep); state.CoarseView = level == 1; state.DetailView = level; try { @@ -64,16 +68,4 @@ internal static void LevelGeometries(Element element, ParsingState state, Action finally { state.CoarseView = false; state.DetailView = 0; } } } - - private static bool HasAlternative(GRepData? block, ParsingState state, HashSet visited, int level) - { - if (block == null) return false; - if ((level == 1 ? block.Coarse : block.Medium) != null) return true; - foreach (var instance in block.Instances) - if (instance.SymbolElemId > 0 && visited.Add((uint)instance.SymbolElemId) - && state.GrepBlocks.TryGetValue((uint)instance.SymbolElemId, out var symbol) - && HasAlternative(symbol, state, visited, level)) - return true; - return false; - } } diff --git a/src/RvtIO/Parsing/ElementBuilder.cs b/src/RvtIO/Parsing/ElementBuilder.cs index 40859c49..5b3bf284 100644 --- a/src/RvtIO/Parsing/ElementBuilder.cs +++ b/src/RvtIO/Parsing/ElementBuilder.cs @@ -771,10 +771,9 @@ List EnvelopeToCorners(double[] env, double[] origin, double[] xv, dou grepFaceToGeoFace[grepFaceIndex] = existing; continue; } - var gf = new GeoFace + // V2 stashes the polygon normal in XVector. + var gf = new GeoFace(fp.Origin, new double[3], new double[3], fp.XVector) { - Origin = fp.Origin, - Normal = fp.XVector, // V2 stashes the polygon normal here OuterVertices = poly, InnerVertices = fp.InnerVertices, AlternativeOuterVertices = fp.AlternativeOuterVertices, @@ -824,12 +823,8 @@ List EnvelopeToCorners(double[] env, double[] origin, double[] xv, dou fp.XVector[2] * fp.YVector[0] - fp.XVector[0] * fp.YVector[2], fp.XVector[0] * fp.YVector[1] - fp.XVector[1] * fp.YVector[0], }; - var geoFace = new GeoFace + var geoFace = new GeoFace(fp.Origin, fp.XVector, fp.YVector, normal) { - Origin = fp.Origin, - XVector = fp.XVector, - YVector = fp.YVector, - Normal = normal, Envelope = fp.Envelope, RenderStyleId = fp.RenderStyleId, GeometryNode = fp.GeometryNode, @@ -1159,6 +1154,7 @@ private static bool TryResolveFamilyNameViaTable( return nativeName; if (state.WideNames.TryGetValue(eid, out var wideName) && !string.IsNullOrWhiteSpace(wideName)) return wideName; + if (state.SceneFallbackNames is { } sceneNames) return sceneNames.GetValueOrDefault(eid); string? foundName = null; if (state.ElemStrings.TryGetValue(eid, out var blkStrs)) foundName = blkStrs.FirstOrDefault(StringScanner.IsValidElementName); @@ -1167,6 +1163,45 @@ private static bool TryResolveFamilyNameViaTable( return foundName; } + internal static void CompactSceneNameCandidates(ParsingState state) + { + if (state.KeepExportProvenance) return; + + // Parameter captions still need the block strings even when an authoritative element name exists. + state.SceneParameterNames = CollectParameterDefinitionNames(state); + var names = new Dictionary(); + // Removing the current entry preserves enumeration and releases candidates as they are consumed. + foreach (var (id, strings) in state.ElemStrings) + { + if (strings.FirstOrDefault(StringScanner.IsValidElementName) is { } name) + names.Add(id, name); + state.ElemStrings.Remove(id); + } + state.ElemStrings = new(); + foreach (var (id, strings) in state.ElemScanStrings) + { + if (!names.ContainsKey(id) && strings.FirstOrDefault(StringScanner.IsValidParamName) is { } name) + names.Add(id, name); + state.ElemScanStrings.Remove(id); + } + state.ElemScanStrings = new(); + state.SceneFallbackNames = names; + } + + internal static Dictionary CollectParameterDefinitionNames(ParsingState state) + { + if (state.SceneParameterNames is { } sceneNames) return sceneNames; + + // Use ForgeParamDefs or an &-prefixed string from the block, never an element's scan name. + var names = new Dictionary(); + foreach (var (id, definition) in state.ForgeParamDefs) + if (definition.DisplayName is { } name) names[(int)id] = name; + foreach (var (id, strings) in state.ElemStrings) + if (!names.ContainsKey((int)id) && strings.FirstOrDefault(s => s.StartsWith('&') && s.Length > 1) is { } name) + names[(int)id] = name[1..]; + return names; + } + public static void BuildElemTableElement( uint elemId, uint typeId, ParsingState state, RevitFileInfo rvtInfo) { @@ -1230,21 +1265,24 @@ public static void BuildElemTableElement( if (rec.References.Count > 0) { - elem.References = rec.References.Select(r => (int)r).ToList(); - var refStrings = new Dictionary>(); - foreach (var refId in rec.References) + elem.SetReferences(rec.References.Select(r => (int)r), state.KeepExportProvenance); + if (state.KeepExportProvenance) { - if (refId == elemId) continue; - if (!state.ElemTable.ContainsKey(refId)) continue; - if (state.ElemStrings.TryGetValue(refId, out var refStrs) && refStrs.Count > 0) + var refStrings = new Dictionary>(); + foreach (var refId in rec.References) { - string label = state.ElemClassIdx.TryGetValue(refId, out var refClassId) - ? $"Ref_T{refClassId}" : $"Ref_E{refId}"; - if (!refStrings.ContainsKey(label)) - refStrings[label] = refStrs.Take(5).ToList(); + if (refId == elemId) continue; + if (!state.ElemTable.ContainsKey(refId)) continue; + if (state.ElemStrings.TryGetValue(refId, out var refStrs) && refStrs.Count > 0) + { + string label = state.ElemClassIdx.TryGetValue(refId, out var refClassId) + ? $"Ref_T{refClassId}" : $"Ref_E{refId}"; + if (!refStrings.ContainsKey(label)) + refStrings[label] = refStrs.Take(5).ToList(); + } } + if (refStrings.Count > 0) elem.RefStrings = refStrings; } - if (refStrings.Count > 0) elem.RefStrings = refStrings; } AddBodyBipParams(elem, rec, elemId, state); @@ -1331,7 +1369,7 @@ private static void AttachSketchCurve(Element elem, uint id, ParsingState state) /// private static int TypeParamOf(Element e) { - foreach (var p in e.Parameters) + foreach (var p in e.ReadParameters) if (p.Id is -1002050 or -1002052 or -1002000 && p.Value is int v && v > 1000) return v; return -1; @@ -1341,17 +1379,15 @@ private static int TypeParamOf(Element e) /// Resolve ELEM_TYPE_PARAM / ELEM_FAMILY_AND_TYPE_PARAM / SYMBOL_ID_PARAM to the real type /// element id for instances whose binary body didn't carry it. /// - private static void ResolveTypeParams(RevitFileInfo info) + private static void ResolveTypeParams(RevitFileInfo info, IReadOnlyDictionary byId, + Action? archiveParameters) { - var byId = new Dictionary(); - foreach (var e in info.Elements) byId[e.Id] = e; - // Weak (automatic) dimensions reference their dim style FIRST - a small built-in element id // (e.g. 277), below the >1000 cutoff of the voting heuristic underneath. - foreach (var e in info.Elements) + foreach (var e in ElementsWithParameterEdits(info.Elements, archiveParameters)) { - if (e.CategoryId != -2000261 || e.References is not { Count: > 0 }) continue; - int t = e.References[0]; + if (e.CategoryId != -2000261 || e.ReadReferences is not { Count: > 0 }) continue; + int t = e.ReadReferences[0]; if (t <= 0 || TypeParamOf(e) > 0) continue; AddBipIfMissing(e, -1002050, "ELEM_TYPE_PARAM", t); AddBipIfMissing(e, -1002052, "ELEM_FAMILY_AND_TYPE_PARAM", t); @@ -1369,49 +1405,48 @@ private static void ResolveTypeParams(RevitFileInfo info) // For each candidate id, how many distinct elements of each category reference it. A type // element is referenced predominantly by its instances (one category). - var refCat = new Dictionary>(); + var categoryVotes = new Dictionary<(int Reference, int Category), int>(); + var referenceVotes = new Dictionary(); + var seenRefs = new HashSet(); foreach (var e in info.Elements) { - if (e.References == null || !e.CategoryId.HasValue) continue; + if (e.ReadReferences == null || !e.CategoryId.HasValue) continue; int c = e.CategoryId.Value; - var seenRefs = new HashSet(); - foreach (var r in e.References) + seenRefs.Clear(); + foreach (var r in e.ReadReferences) { if (r <= 1000 || !seenRefs.Add(r)) continue; - if (!refCat.TryGetValue(r, out var cc)) refCat[r] = cc = new Dictionary(); - cc.TryGetValue(c, out int n); cc[c] = n + 1; + var key = (r, c); + categoryVotes[key] = categoryVotes.GetValueOrDefault(key) + 1; + referenceVotes[r] = referenceVotes.GetValueOrDefault(r) + 1; } } - foreach (var e in info.Elements) + foreach (var e in ElementsWithParameterEdits(info.Elements, archiveParameters)) { - if (e.References == null || e.References.Count == 0 || TypeParamOf(e) > 0) continue; + if (e.ReadReferences == null || e.ReadReferences.Count == 0 || TypeParamOf(e) > 0) continue; int chosen = -1; if (!e.CategoryId.HasValue) { // No category to disambiguate by - only trust a referenced known type. - foreach (var r in e.References) + foreach (var r in e.ReadReferences) if (r > 1000 && r != e.Id && seed.Contains(r)) { chosen = r; break; } } else { int C = e.CategoryId.Value; int bestScore = -1; - var seen = new HashSet(); - foreach (var r in e.References) + seenRefs.Clear(); + foreach (var r in e.ReadReferences) { - if (r <= 1000 || r == e.Id || !seen.Add(r)) continue; + if (r <= 1000 || r == e.Id || !seenRefs.Add(r)) continue; // candidate's own category must be compatible (null or same) - excludes // levels/phases. if (byId.TryGetValue(r, out var re) && re.CategoryId.HasValue && re.CategoryId != C) continue; - int n = 0, tot = 0; - if (refCat.TryGetValue(r, out var cc)) - { - cc.TryGetValue(C, out n); - foreach (var v in cc.Values) tot += v; - } + int n = categoryVotes.GetValueOrDefault((r, C)); + int tot = referenceVotes.GetValueOrDefault(r); double frac = tot > 0 ? (double)n / tot : 0; bool qualifies = (n >= 2 && frac >= 0.6) || seed.Contains(r); if (!qualifies) continue; @@ -1432,12 +1467,12 @@ private static void ResolveTypeParams(RevitFileInfo info) /// "Design Option" (DESIGN_OPTION_PARAM, string) is "Main Model" for an element outside any /// design option (DESIGN_OPTION_ID -1, or -4 on Material elements). /// - private static void ApplyDerivedDesignOptionName(RevitFileInfo info) + private static void ApplyDerivedDesignOptionName(RevitFileInfo info, Action? archiveParameters) { - foreach (var e in info.Elements) + foreach (var e in ElementsWithParameterEdits(info.Elements, archiveParameters)) { - if (e.Parameters.Any(p => p.Id == -1013200)) continue; - var option = e.Parameters.FirstOrDefault(p => p.Id == -1013201); + if (e.ReadParameters.Any(p => p.Id == -1013200)) continue; + var option = e.ReadParameters.FirstOrDefault(p => p.Id == -1013201); if (option?.Value is int id && id is -1 or -4) e.Parameters.Add(BipHelpers.MakeBipParam(-1013200, "DESIGN_OPTION_PARAM", StorageType.String, "Main Model")); } @@ -1532,11 +1567,12 @@ static void SetDouble(Element e, int id, string name, double value) /// HOST_ID_PARAM of a family instance from the stored InsertableInst.m_hostId: curtain cells /// and mullions report their curtain host, beams their beam system or truss. /// - internal static void ApplyHostIdParam(RevitFileInfo info, IReadOnlyDictionary? classByElement) + internal static void ApplyHostIdParam(RevitFileInfo info, IReadOnlyDictionary? classByElement, + Action? archiveParameters = null) { var byId = new Dictionary(); foreach (var e in info.Elements) byId.TryAdd(e.Id, e); - foreach (var e in info.Elements) + foreach (var e in ElementsWithParameterEdits(info.Elements, archiveParameters)) { if (e.SerializedHostId is not int host || host <= 0) continue; int? value = null; @@ -1563,9 +1599,9 @@ internal static void ApplyHostIdParam(RevitFileInfo info, IReadOnlyDictionary - internal static void ApplyInstanceOriginOffsets(RevitFileInfo info) + internal static void ApplyInstanceOriginOffsets(RevitFileInfo info, Action? archiveParameters = null) { - foreach (var e in info.Elements) + foreach (var e in ElementsWithParameterEdits(info.Elements, archiveParameters)) { if (e.InstanceOriginZ is not double z || e.NativeMasterSymbolId == null) continue; if (e.CategoryId == -2001300) // OST_StructuralFoundation @@ -1587,11 +1623,11 @@ internal static void ApplyInstanceOriginOffsets(RevitFileInfo info) /// Offset (SCHEDULE_BASE_LEVEL_OFFSET_PARAM and FAMILY_BASE_LEVEL_OFFSET_PARAM) is the base /// offset. /// - internal static void ApplyStructuralColumnParams(RevitFileInfo info) + internal static void ApplyStructuralColumnParams(RevitFileInfo info, Action? archiveParameters = null) { var byId = new Dictionary(); foreach (var e in info.Elements) byId.TryAdd(e.Id, e); - foreach (var e in info.Elements) + foreach (var e in ElementsWithParameterEdits(info.Elements, archiveParameters)) { if (e.CategoryId is not (-2001330 or -2000100) || e.NativeMasterSymbolId == null || e.FamilyLevelRefs is not { } refs) continue; SetParam(e, -1002065, "SCHEDULE_BASE_LEVEL_OFFSET_PARAM", StorageType.Double, refs.BaseOffset); @@ -1609,7 +1645,7 @@ internal static void ApplyStructuralColumnParams(RevitFileInfo info) ? elevation : null; } - internal static void ApplyFramingSymbolLength(RevitFileInfo info) + internal static void ApplyFramingSymbolLength(RevitFileInfo info, Action? archiveParameters = null) { var byId = new Dictionary(); foreach (var e in info.Elements) byId.TryAdd(e.Id, e); @@ -1618,23 +1654,27 @@ internal static void ApplyFramingSymbolLength(RevitFileInfo info) if (e.CategoryId != -2001320 || e.NativeMasterSymbolId == null || e.InstanceSymbolId is not int symbolId || !byId.TryGetValue(symbolId, out var symbol) || symbol.SymbolFramingLength is not double length) continue; SetParam(e, -1001375, "INSTANCE_LENGTH_PARAM", StorageType.Double, length); + archiveParameters?.Invoke(e); } } - internal static void ApplyHeadHeight(RevitFileInfo info) + internal static void ApplyHeadHeight(RevitFileInfo info, Action? archiveParameters = null) { var byId = new Dictionary(); foreach (var e in info.Elements) byId.TryAdd(e.Id, e); foreach (var e in info.Elements) { if (e.CategoryId is not (-2000014 or -2000023) || e.NativeMasterSymbolId is not int typeId) continue; - if (e.Parameters.FirstOrDefault(p => p.Id == -1001361)?.Value is not double sill) continue; + if (e.ReadParameters.FirstOrDefault(p => p.Id == -1001361)?.Value is not double sill) continue; bool estimated = e.BoundingBoxDimensionParamIds?.Contains(-1001300) == true; - object? height = (estimated ? null : e.Parameters.FirstOrDefault(p => p.Id == -1001300)?.Value) + object? height = (estimated ? null : e.ReadParameters.FirstOrDefault(p => p.Id == -1001300)?.Value) ?? (byId.TryGetValue(typeId, out var type) && type.BoundingBoxDimensionParamIds?.Contains(-1001300) != true ? type.Parameters.FirstOrDefault(p => p.Id == -1001300)?.Value : null); if (height is double h) + { SetParam(e, -1001362, "INSTANCE_HEAD_HEIGHT_PARAM", StorageType.Double, sill + h); + archiveParameters?.Invoke(e); + } } } @@ -1644,7 +1684,7 @@ internal static void ApplyHeadHeight(RevitFileInfo info) /// topography surface/subregion. /// internal static void ApplyHostLabels(RevitFileInfo info, Lookup.RevitSystemFamilyNames? names, - IReadOnlyDictionary? classByElement) + IReadOnlyDictionary? classByElement, Action? archiveParameters = null) { if (names == null) return; foreach (var group in info.Elements) @@ -1655,15 +1695,17 @@ internal static void ApplyHostLabels(RevitFileInfo info, Lookup.RevitSystemFamil } var byId = new Dictionary(); foreach (var e in info.Elements) byId.TryAdd(e.Id, e); - foreach (var e in info.Elements) + foreach (var e in ElementsWithParameterEdits(info.Elements, archiveParameters)) { - var host = e.Parameters.FirstOrDefault(p => p.Id == -1001363); - if (host == null) + Parameter host; + if (e.ReadParameters.Any(p => p.Id == -1001363)) + host = e.Parameters.First(p => p.Id == -1001363); + else { // An instance placed on the face of an element (Host Id -1, the host stored) shows // that element as its Host. if (e.CategoryId is -2001330 or -2001320 or -2000100 || e.NativeMasterSymbolId == null || e.SerializedHostId is not > 0 - || e.Parameters.FirstOrDefault(p => p.Id == -1002108)?.Value is not -1) + || e.ReadParameters.FirstOrDefault(p => p.Id == -1002108)?.Value is not -1) continue; host = BipHelpers.MakeBipParam(-1001363, "INSTANCE_FREE_HOST_PARAM", StorageType.String, ""); e.Parameters.Add(host); @@ -1679,7 +1721,7 @@ internal static void ApplyHostLabels(RevitFileInfo info, Lookup.RevitSystemFamil ? Lookup.RevitUiText.Subregion : Lookup.RevitUiText.TopographySurface); else if (byId.TryGetValue(hostId, out hostElement) && hostElement.CategoryId == -2005301) // OST_BoundaryConditions label = names.Get(Lookup.RevitUiText.BoundaryConditions); - else if (e.Parameters.FirstOrDefault(p => p.Id == -1002108)?.Value is -1 && hostElement != null) + else if (e.ReadParameters.FirstOrDefault(p => p.Id == -1002108)?.Value is -1 && hostElement != null) { // On a work plane the host is the element whose face the plane lies on (GeomRef // of the plane reference); a plane on a level or a reference plane has none. @@ -1691,9 +1733,9 @@ internal static void ApplyHostLabels(RevitFileInfo info, Lookup.RevitSystemFamil } } else if (e.NativeMasterSymbolId != null - && e.Parameters.FirstOrDefault(p => p.Id == -1001352)?.Value is int levelId && levelId > 0 + && e.ReadParameters.FirstOrDefault(p => p.Id == -1001352)?.Value is int levelId && levelId > 0 && byId.TryGetValue(levelId, out var level) && level.IsNativeLevel - && level.Parameters.FirstOrDefault(p => p.Id == -1007101)?.Value is string levelName && levelName.Length > 0 + && level.ReadParameters.FirstOrDefault(p => p.Id == -1007101)?.Value is string levelName && levelName.Length > 0 && names.Get(Lookup.RevitUiText.LevelFamily) is string levelFamily) label = levelFamily + " : " + levelName; if (label != null) { host.Value = label; host.StorageType = StorageType.String; } @@ -1705,7 +1747,8 @@ internal static void ApplyHostLabels(RevitFileInfo info, Lookup.RevitSystemFamil /// "Work Plane" text (SKETCH_PLANE_PARAM) of an instance placed on a datum: its sketch plane /// lies on a level, or the reference plane is its stored host. /// - internal static void ApplyWorkPlaneLabels(RevitFileInfo info, Lookup.RevitSystemFamilyNames? names) + internal static void ApplyWorkPlaneLabels(RevitFileInfo info, Lookup.RevitSystemFamilyNames? names, + Action? archiveParameters = null) { if (names == null) return; var byId = new Dictionary(); @@ -1713,12 +1756,12 @@ internal static void ApplyWorkPlaneLabels(RevitFileInfo info, Lookup.RevitSystem string? DatumLabel(Element datum) { if (datum.IsNativeLevel) - return datum.Parameters.FirstOrDefault(p => p.Id == -1007101)?.Value is string { Length: > 0 } levelName + return datum.ReadParameters.FirstOrDefault(p => p.Id == -1007101)?.Value is string { Length: > 0 } levelName && names.Get(Lookup.RevitUiText.LevelFamily) is string levelFamily ? levelFamily + " : " + levelName : null; return datum.CategoryId == ReferencePlaneCategoryId && !string.IsNullOrEmpty(datum.Name) && names.Get(Lookup.RevitUiText.ReferencePlane) is string planeFamily ? planeFamily + " : " + datum.Name : null; } - foreach (var e in info.Elements) + foreach (var e in ElementsWithParameterEdits(info.Elements, archiveParameters)) { string? label = null; if (e.AssocSketchPlaneId is > 0 && byId.TryGetValue(e.AssocSketchPlaneId.Value, out var sketchPlane) @@ -1750,15 +1793,15 @@ internal static void ApplyWorkPlaneLabels(RevitFileInfo info, Lookup.RevitSystem // The name of an electrical panel is its Panel Name (RBS_ELEC_PANEL_NAME, the element name // of electrical equipment), not the name of its type; the name of any other element is not // read here (the stored element name is not reliable for floors). - string? ownName = NonEmpty(type.Parameters.FirstOrDefault(p => p.Id == -1002001)?.Value as string) ?? NonEmpty(type.Name); - string? panelName = NonEmpty(element.Parameters.FirstOrDefault(p => p.Id == -1140078)?.Value as string) + string? ownName = NonEmpty(type.ReadParameters.FirstOrDefault(p => p.Id == -1002001)?.Value as string) ?? NonEmpty(type.Name); + string? panelName = NonEmpty(element.ReadParameters.FirstOrDefault(p => p.Id == -1140078)?.Value as string) ?? (element.CategoryId == -2001040 && NonEmpty(element.Name) is { } instanceName && instanceName != ownName ? instanceName : null); // Electrical equipment is named by its panel name; where the file gives none that is known // here, the type name would be wrong. if (panelName == null && element.CategoryId == -2001040) return null; string? typeName = panelName ?? ownName; string? family = NonEmpty(type.ValidatedSystemFamilyName) - ?? NonEmpty(type.Parameters.FirstOrDefault(p => p.Id == -1002002)?.Value as string) + ?? NonEmpty(type.ReadParameters.FirstOrDefault(p => p.Id == -1002002)?.Value as string) ?? NonEmpty(type.FamilyName) ?? NonEmpty(element.FamilyName); return typeName == null || family == null ? null : family + " : " + typeName; } @@ -1792,7 +1835,7 @@ internal static void ApplyWorkPlaneLabels(RevitFileInfo info, Lookup.RevitSystem /// MEP system membership of ducts (3148) and pipes (3210). internal static void ApplyMepSystemParams(RevitFileInfo info, ParsingState state, Lookup.RevitSystemFamilyNames? names) { - foreach (var e in info.Elements) + foreach (var e in ElementsWithParameterEdits(info.Elements, state.ArchiveSceneParameters)) { if (!state.NativeParams.TryGetValue((uint)e.Id, out var np)) continue; if (np.Fields.TryGetValue("3190:m_basicSystemType", out int basicType)) @@ -2048,11 +2091,14 @@ private static void TraceElement(RevitFileInfo info, string stage) } /// Runs after categories are final. - internal static void PruneNativeFieldTableOutsideDomains(RevitFileInfo info, IReadOnlyDictionary? classByElement) + internal static void PruneNativeFieldTableOutsideDomains(RevitFileInfo info, IReadOnlyDictionary? classByElement, + Action? archiveParameters = null, NativeTableEffectsScratch? effectsScratch = null) { if (classByElement == null) return; + effectsScratch?.Seal(); foreach (var e in info.Elements) { + effectsScratch?.Restore(e); if (e.NativeTableAddedParams is not { Count: > 0 } added) continue; string rootClass = classByElement.TryGetValue((uint)e.Id, out var cls) ? cls.ToString(System.Globalization.CultureInfo.InvariantCulture) : "None"; string domain = rootClass + "/" + (e.CategoryId?.ToString(System.Globalization.CultureInfo.InvariantCulture) ?? "None"); @@ -2098,6 +2144,7 @@ internal static void PruneNativeFieldTableOutsideDomains(RevitFileInfo info, IRe e.NativeTableAddedParams = null; e.NativeTableCreatedParams = null; e.NativeTablePrevious = null; + archiveParameters?.Invoke(e); } } @@ -2224,7 +2271,8 @@ double Speed(double t) /// "Detail Line" (CURVE_IS_DETAIL) of a curve element is 1 exactly when the curve is owned by a /// view (Element.m_ownerDBViewId set). /// - internal static void ApplyDetailCurveFlag(RevitFileInfo info, IReadOnlyDictionary? classByElement) + internal static void ApplyDetailCurveFlag(RevitFileInfo info, IReadOnlyDictionary? classByElement, + Action? archiveParameters = null) { if (classByElement == null) return; foreach (var e in info.Elements) @@ -2232,10 +2280,11 @@ internal static void ApplyDetailCurveFlag(RevitFileInfo info, IReadOnlyDictionar if (e.SerializedOwnerDbViewId is not int ownerView || !classByElement.TryGetValue((uint)e.Id, out var cls) || cls != 838) continue; // CurveElem SetParam(e, -1004011, "CURVE_IS_DETAIL", StorageType.Integer, ownerView > 0 ? 1 : 0); + archiveParameters?.Invoke(e); } } - internal static void ApplyCrossSectionRotation(RevitFileInfo info) + internal static void ApplyCrossSectionRotation(RevitFileInfo info, Action? archiveParameters = null) { var byId = new Dictionary(); foreach (var e in info.Elements) byId.TryAdd(e.Id, e); @@ -2246,6 +2295,7 @@ internal static void ApplyCrossSectionRotation(RevitFileInfo info) && byId.TryGetValue(host, out var hostElement) && hostElement.Category == "OST_StructuralTruss"; if (trussMember) e.Parameters.RemoveAll(p => p.Id == -1001586); else SetParam(e, -1001586, "STRUCTURAL_BEND_DIR_ANGLE", StorageType.Double, rotation); + archiveParameters?.Invoke(e); } } @@ -2254,19 +2304,19 @@ internal static void ApplyCrossSectionRotation(RevitFileInfo info) /// element, including id 0 (phases of older files keep low ids such as 0 and 2). /// internal static void ApplyStoredPhases(RevitFileInfo info, IReadOnlyDictionary? classByElement, - IReadOnlyCollection? projectPhaseOrder = null) + IReadOnlyCollection? projectPhaseOrder = null, Action? archiveParameters = null) { if (classByElement == null) return; // A phase is a ProjectPhase element or an entry of the project's single phase-order record. bool IsPhase(int id) => id >= 0 && ((classByElement.TryGetValue((uint)id, out var cls) && cls == 3065) || projectPhaseOrder?.Contains(id) == true); - foreach (var e in info.Elements) + foreach (var e in ElementsWithParameterEdits(info.Elements, archiveParameters)) { if (e.SerializedCreatedPhaseId is int created && IsPhase(created) - && e.Parameters.Any(p => p.Id == -1012100)) + && e.ReadParameters.Any(p => p.Id == -1012100)) SetParam(e, -1012100, "PHASE_CREATED", StorageType.ElementId, created); if (e.SerializedDemolishedPhaseId is int demolished && (demolished == -1 || IsPhase(demolished)) - && e.Parameters.Any(p => p.Id == -1012101)) + && e.ReadParameters.Any(p => p.Id == -1012101)) SetParam(e, -1012101, "PHASE_DEMOLISHED", StorageType.ElementId, demolished); } } @@ -2276,7 +2326,7 @@ bool IsPhase(int id) => id >= 0 && ((classByElement.TryGetValue((uint)id, out va /// Connection) exist when the family's Symbolic Representation is 1 (from project settings) and /// carry the stored m_connectionType ids. /// - internal static void ApplyStructuralConnectionParams(RevitFileInfo info) + internal static void ApplyStructuralConnectionParams(RevitFileInfo info, Action? archiveParameters = null) { var byId = new Dictionary(); foreach (var e in info.Elements) byId.TryAdd(e.Id, e); @@ -2297,6 +2347,7 @@ internal static void ApplyStructuralConnectionParams(RevitFileInfo info) SetParam(e, -1018804, "STRUCT_CONNECTION_COLUMN_BASE", StorageType.ElementId, connections.First); SetParam(e, -1018803, "STRUCT_CONNECTION_COLUMN_TOP", StorageType.ElementId, connections.Second); } + archiveParameters?.Invoke(e); } } @@ -2310,7 +2361,7 @@ internal static void ApplyStructuralConnectionParams(RevitFileInfo info) -1150188, // ROOM_PLENUM_LIGHTING_PARAM ]; - internal static void ApplyRoomBuildingTypeLoads(RevitFileInfo info) + internal static void ApplyRoomBuildingTypeLoads(RevitFileInfo info, Action? archiveParameters = null) { var settings = info.Elements.Where(e => e.EnergyBuildingTypeId != null).ToList(); if (settings.Count != 1) return; @@ -2329,22 +2380,24 @@ internal static void ApplyRoomBuildingTypeLoads(RevitFileInfo info) } if (values.TryGetValue(-1114239, out double sensible) && values.TryGetValue(-1114189, out double latent)) SetParam(room, -1114188, "ROOM_PEOPLE_TOTAL_HEAT_GAIN_PER_PERSON_PARAM", StorageType.Double, sensible + latent); + archiveParameters?.Invoke(room); } } - internal static void ApplyRoomLevelParams(RevitFileInfo info) + internal static void ApplyRoomLevelParams(RevitFileInfo info, Action? archiveParameters = null) { var byId = new Dictionary(); foreach (var e in info.Elements) byId.TryAdd(e.Id, e); foreach (var e in info.Elements) { if (e.CategoryId is not (-2000160 or -2003200)) continue; // OST_Rooms, OST_Areas - if (e.Parameters.FirstOrDefault(p => p.Id == -1006916)?.Value is not int levelId || levelId <= 0 + if (e.ReadParameters.FirstOrDefault(p => p.Id == -1006916)?.Value is not int levelId || levelId <= 0 || !byId.TryGetValue(levelId, out var level) || !level.IsNativeLevel) continue; if (level.Parameters.FirstOrDefault(p => p.Id == -1007101)?.Value is string levelName && levelName.Length > 0) SetParam(e, -1007101, "LEVEL_NAME", StorageType.String, levelName); if (level.Parameters.FirstOrDefault(p => p.Id == -1006939)?.Value is double computationHeight) SetParam(e, -1006928, "ROOM_COMPUTATION_HEIGHT", StorageType.Double, computationHeight); + archiveParameters?.Invoke(e); } } @@ -2357,11 +2410,11 @@ private static void SetParam(Element e, int id, string name, StorageType storage } /// Which instances carry the parameter is left to the existing passes. - internal static void ApplyInstanceElevationFromLevel(RevitFileInfo info) + internal static void ApplyInstanceElevationFromLevel(RevitFileInfo info, Action? archiveParameters = null) { var byId = new Dictionary(); foreach (var e in info.Elements) byId.TryAdd(e.Id, e); - foreach (var e in info.Elements) + foreach (var e in ElementsWithParameterEdits(info.Elements, archiveParameters)) { if (e.NativeMasterSymbolId == null || e.Transform?.Origin is not { Length: 3 } origin) continue; var elevationParam = e.Parameters.FirstOrDefault(p => p.Id == -1001360); @@ -2369,7 +2422,7 @@ internal static void ApplyInstanceElevationFromLevel(RevitFileInfo info) if (e.Parameters.FirstOrDefault(p => p.Id == -1002108)?.Value is not int host || host != -1) continue; if (e.Parameters.FirstOrDefault(p => p.Id == -1001352)?.Value is not int level || level <= 0 || !byId.TryGetValue(level, out var levelElement) - || levelElement.Parameters.FirstOrDefault(p => p.Id == -1007102)?.Value is not double levelElevation) + || levelElement.ReadParameters.FirstOrDefault(p => p.Id == -1007102)?.Value is not double levelElevation) continue; elevationParam.Value = origin[2] - levelElevation; elevationParam.StorageType = StorageType.Double; @@ -2378,10 +2431,25 @@ internal static void ApplyInstanceElevationFromLevel(RevitFileInfo info) private static void AddBipIfMissing(Element e, int id, string name, int value) { - foreach (var p in e.Parameters) if (p.Id == id) return; + foreach (var p in e.ReadParameters) if (p.Id == id) return; e.Parameters.Add(BipHelpers.MakeBipParam(id, name, StorageType.ElementId, value)); } + private static IEnumerable ElementsWithParameterEdits(List elements, Action? archive) + { + return archive == null ? elements : StoreEach(elements, archive); + + static IEnumerable StoreEach(List elements, Action store) + { + foreach (var element in elements) + { + // The caller's loop edits this element before requesting the next one. + yield return element; + store(element); + } + } + } + /// /// System/annotation categories assigned via the empirical block-class registry whose elements /// report unhosted defaults (HOST_ID=-1, INSTANCE_OFFSET_POS=0) in the Revit API - same @@ -2436,13 +2504,13 @@ private static void AddBipIfMissing(Element e, int id, string name, int value) /// NO category get ELEM_CATEGORY_PARAM(-1140362)/_MT(-1140363) = -1 - this is exactly what the /// Revit API returns for uncategorized (internal) elements. /// - private static void AddCategoryAndFamilyParams(RevitFileInfo info) + private static void AddCategoryAndFamilyParams(RevitFileInfo info, Action? archiveParameters) { foreach (var e in info.Elements) { bool hasCat = false, hasCatMt = false, hasFam = false; int typeVal = -1; - foreach (var p in e.Parameters) + foreach (var p in e.ReadParameters) { switch (p.Id) { @@ -2459,7 +2527,7 @@ private static void AddCategoryAndFamilyParams(RevitFileInfo info) // empirical block registry: the export reports unhosted defaults for them (they // used to take this branch before the registry categorized them). AddBipIfMissing(e, -1002108, "HOST_ID_PARAM", -1); - if (e.Parameters.All(p => p.Id != -1001370)) + if (e.ReadParameters.All(p => p.Id != -1001370)) e.Parameters.Add(BipHelpers.MakeBipParam(-1001370, "INSTANCE_OFFSET_POS_PARAM", StorageType.Integer, 0, hasNoRevitValue: true)); } @@ -2480,6 +2548,7 @@ private static void AddCategoryAndFamilyParams(RevitFileInfo info) if (!hasFam && typeVal > 0) e.Parameters.Add(BipHelpers.MakeBipParam(-1002051, "ELEM_FAMILY_PARAM", StorageType.ElementId, typeVal)); + archiveParameters?.Invoke(e); } } @@ -2537,7 +2606,7 @@ void Add(int id, string name, StorageType st, object val) // comes from the native record or the holder vote below) keeps that transparency. foreach (var (finishId, finish) in state.MaterialFinishes) if (!state.MaterialAppearances.ContainsKey(finishId) && byId.TryGetValue((int)finishId, out var finished) - && finished.CategoryId == -2000700 && !finished.Parameters.Any(parameter => parameter.Id == -1002551)) + && finished.CategoryId == -2000700 && !finished.ReadParameters.Any(parameter => parameter.Id == -1002551)) finished.Parameters.Add(BipHelpers.MakeBipParam(-1002551, "MATERIAL_PARAM_TRANSPARENCY", StorageType.Integer, finish.Transparency)); // Fallback for OST_Materials elements without a decoded appearance: link through the record @@ -2552,19 +2621,19 @@ void Add(int id, string name, StorageType st, object val) var holderRefCount = new Dictionary(); foreach (var e in info.Elements) { - if (e.CategoryId != -2000700 || e.References == null) continue; + if (e.CategoryId != -2000700 || e.ReadReferences == null) continue; var seen = new HashSet(); - foreach (var r in e.References) + foreach (var r in e.ReadReferences) if (seen.Add(r) && state.ShadingEntries.ContainsKey((uint)r)) { holderRefCount.TryGetValue(r, out int n); holderRefCount[r] = n + 1; } } foreach (var e in materials) { - if (e.References == null) continue; + if (e.ReadReferences == null) continue; var holders = new List(); var seen = new HashSet(); - foreach (var r in e.References) + foreach (var r in e.ReadReferences) if (seen.Add(r) && state.ShadingEntries.ContainsKey((uint)r)) holders.Add(r); if (holders.Count == 0) continue; @@ -2741,17 +2810,22 @@ internal static void ApplySerializedRoomNames( /// Synthesize room identity/relationship parameters from already decoded data. Exact ROOM_NAME /// is applied before this pass; geometric quantities remain omitted. /// - internal static void ApplyRoomParams(RevitFileInfo info) + internal static void ApplyRoomParams(RevitFileInfo info, Action? archiveParameters = null, + IReadOnlyDictionary? elementIndex = null) { - var byId = new Dictionary(); - foreach (var e in info.Elements) byId[e.Id] = e; + if (elementIndex == null) + { + var byId = new Dictionary(); + foreach (var e in info.Elements) byId[e.Id] = e; + elementIndex = byId; + } foreach (var e in info.Elements) { if (e.CategoryId != -2000160) continue; // OST_Rooms var existing = new HashSet(); int phase = -1; - foreach (var p in e.Parameters) + foreach (var p in e.ReadParameters) { existing.Add(p.Id); if (p.Id == -1012100 && p.Value is int ph) phase = ph; // PHASE_CREATED (if present) @@ -2768,14 +2842,14 @@ void Add(int id, string name, StorageType st, object val) // Level (OST_Levels) and phase (OST_Phases) from the room's references. int levelId = -1; - if (e.References != null) - foreach (var r in e.References) + if (e.ReadReferences != null) + foreach (var r in e.ReadReferences) { - if (!byId.TryGetValue(r, out var re)) continue; + if (!elementIndex.TryGetValue(r, out var re)) continue; if (levelId < 0 && re.CategoryId == -2000240) levelId = r; if (phase < 0 && re.CategoryId == -2000112) phase = r; } - if (levelId <= 0 && e.Parameters.FirstOrDefault(p => p.Id is -1001952 or -1002062 && p.Value is int id && id > 0)?.Value is int paramLevelId) + if (levelId <= 0 && e.ReadParameters.FirstOrDefault(p => p.Id is -1001952 or -1002062 && p.Value is int id && id > 0)?.Value is int paramLevelId) levelId = paramLevelId; if (levelId > 0) { @@ -2792,6 +2866,7 @@ void Add(int id, string name, StorageType st, object val) Add(-1012113, "ROOM_PHASE", StorageType.ElementId, roomPhase); Add(-1012112, "ROOM_PHASE_ID", StorageType.ElementId, roomPhase); } + archiveParameters?.Invoke(e); // ROOM_VOLUME / ROOM_PERIMETER / ROOM_HEIGHT are deliberately not emitted: // volume/perimeter/height are computed by Revit at runtime and are not persisted // anywhere in the file. @@ -2809,15 +2884,14 @@ void Add(int id, string name, StorageType st, object val) /// Sheet / placement parameters. Sheets (OST_Sheets, -2003100) with decoded 0x03E3 info get /// SHEET_NUMBER + SHEET_ISSUE_DATE. /// - private static void ApplySheetParams(RevitFileInfo info, ParsingState? state) + private static void ApplySheetParams(RevitFileInfo info, ParsingState? state, IReadOnlyDictionary byId) { if (state == null) return; - var byId = new Dictionary(); - foreach (var e in info.Elements) byId[e.Id] = e; + var archiveParameters = state.ArchiveSceneParameters; void Add(Element e, int id, string name, object val) { - foreach (var p in e.Parameters) if (p.Id == id) return; + if (e.ReadParameters.Any(parameter => parameter.Id == id)) return; e.Parameters.Add(BipHelpers.MakeBipParam(id, name, StorageType.String, val)); } @@ -2831,38 +2905,51 @@ void Add(Element e, int id, string name, object val) if (!string.IsNullOrEmpty(si.IssueDate)) Add(e, -1006322, "SHEET_ISSUE_DATE", si.IssueDate); Add(e, -1006601, "VIEWER_SHEET_NUMBER", si.Number); + archiveParameters?.Invoke(e); } // 2. Views referenced directly BY a sheet are placed on it (e.g. ImageViews). var placed = new HashSet(); foreach (var e in info.Elements) { - if (e.CategoryId != -2003100 || e.References == null) continue; + if (e.CategoryId != -2003100 || e.ReadReferences == null) continue; sheetNumbers.TryGetValue(e.Id, out var num); - foreach (var r in e.References) + foreach (var r in e.ReadReferences) if (r != e.Id && byId.TryGetValue(r, out var re) && re.CategoryId is int rc && ViewCategories.Contains(rc) && rc != -2003100) { placed.Add(r); - if (num != null) Add(re, -1006601, "VIEWER_SHEET_NUMBER", num); + if (num != null) + { + Add(re, -1006601, "VIEWER_SHEET_NUMBER", num); + archiveParameters?.Invoke(re); + } } } // 3. Viewports -> sheet number; views shown by the viewport inherit it. foreach (var e in info.Elements) { - if (e.CategoryId != -2000515 || e.References == null) continue; // OST_Viewports + if (e.CategoryId != -2000515 || e.ReadReferences == null) continue; // OST_Viewports string? num = null; - foreach (var r in e.References) + foreach (var r in e.ReadReferences) if (sheetNumbers.TryGetValue(r, out var n)) { num = n; break; } - foreach (var r in e.References) + foreach (var r in e.ReadReferences) if (r != e.Id && byId.TryGetValue(r, out var re) && re.CategoryId is int rc && ViewCategories.Contains(rc) && rc != -2003100) { placed.Add(r); - if (num != null) Add(re, -1006601, "VIEWER_SHEET_NUMBER", num); + if (num != null) + { + Add(re, -1006601, "VIEWER_SHEET_NUMBER", num); + archiveParameters?.Invoke(re); + } } - if (num != null) Add(e, -1006601, "VIEWER_SHEET_NUMBER", num); + if (num != null) + { + Add(e, -1006601, "VIEWER_SHEET_NUMBER", num); + archiveParameters?.Invoke(e); + } placed.Add(e.Id); } @@ -2873,6 +2960,7 @@ void Add(Element e, int id, string name, object val) if (c is -2003100 or -2000515 || placed.Contains(e.Id)) continue; Add(e, -1006601, "VIEWER_SHEET_NUMBER", "---"); Add(e, -1006602, "VIEWER_DETAIL_NUMBER", "-"); + archiveParameters?.Invoke(e); } // 5. VIEW_NAME from the name-field signature in the view's own block; viewports report the @@ -2882,9 +2970,9 @@ void Add(Element e, int id, string name, object val) if (e.CategoryId is not int c || !ViewCategories.Contains(c)) continue; string? nm = null; if (state.ViewNames.TryGetValue((uint)e.Id, out var own)) nm = own; - else if (c == -2000515 && e.References != null) + else if (c == -2000515 && e.ReadReferences != null) { - foreach (var r in e.References) + foreach (var r in e.ReadReferences) if (state.ViewNames.TryGetValue((uint)r, out var shown) && byId.TryGetValue(r, out var re) && re.CategoryId is int rc && ViewCategories.Contains(rc) && rc != -2003100) // not the sheet itself @@ -2893,6 +2981,7 @@ void Add(Element e, int id, string name, object val) if (nm == null) continue; Add(e, -1005112, "VIEW_NAME", nm); if (string.IsNullOrEmpty(e.Name) || e.Name != nm) e.Name = nm; + archiveParameters?.Invoke(e); } } @@ -2959,20 +3048,18 @@ private static void ApplyTextNotes(RevitFileInfo info, ParsingState? state) } /// Computed area/volume for curtain-wall members. - private static void AddCurtainQuantities(RevitFileInfo info) + private static void AddCurtainQuantities(RevitFileInfo info, Action? archiveParameters) { - foreach (var e in info.Elements) + foreach (var e in ElementsWithParameterEdits(info.Elements, archiveParameters)) { if (e.CategoryId is not (-2000170 or -2000171)) continue; bool panel = e.CategoryId == -2000170; var shell = SolidQuantities.OfSingleClosedShell(e.Geometry); if (shell is null && GeometryBox(e) is not { Length: 6 }) continue; - var existing = new HashSet(); - foreach (var p in e.Parameters) existing.Add(p.Id); void Add(int id, string name, double val) { - if (!existing.Contains(id) && val > 1e-9) + if (val > 1e-9 && !e.ReadParameters.Any(p => p.Id == id)) e.Parameters.Add(BipHelpers.MakeBipParam(id, name, StorageType.Double, val)); } @@ -3035,7 +3122,7 @@ private static void ApplyDetailLines(RevitFileInfo info, ParsingState? state) e.CategoryId = curveCat; e.Category = BuiltInCategoryNames.Lookup.TryGetValue(curveCat, out var ccn) ? ccn : "OST_Lines"; - var existing = new HashSet(e.Parameters.Select(p => p.Id)); + var existing = new HashSet(e.ReadParameters.Select(p => p.Id)); void Add(int id, string name, StorageType st, object val) { if (!existing.Contains(id)) e.Parameters.Add(BipHelpers.MakeBipParam(id, name, st, val)); @@ -3080,7 +3167,7 @@ private static void ApplyBlockSignatureCategories(RevitFileInfo info, ParsingSta if (!state.AnalyticalNodeOwners.Contains((uint)e.Id)) continue; e.CategoryId = -2009645; e.Category = "OST_AnalyticalNodes"; - var existing = new HashSet(e.Parameters.Select(p => p.Id)); + var existing = new HashSet(e.ReadParameters.Select(p => p.Id)); if (!existing.Contains(-1140362)) e.Parameters.Add(BipHelpers.MakeBipParam(-1140362, "ELEM_CATEGORY_PARAM", StorageType.ElementId, -2009645)); if (!existing.Contains(-1140363)) @@ -3093,7 +3180,7 @@ private static void ApplyWorksets(RevitFileInfo info, ParsingState? state) { if (state == null || state.ElemWorksets.Count == 0) return; bool nonWorkshared2027 = state.WideSchema?.Release == 2027 && info.SerializedIsWorkshared == false; - foreach (var e in info.Elements) + foreach (var e in ElementsWithParameterEdits(info.Elements, state.ArchiveSceneParameters)) { var existing = e.Parameters.FirstOrDefault(p => p.Id == -1002053); if (state.ElemWorksets.TryGetValue((uint)e.Id, out uint ws)) @@ -3128,11 +3215,45 @@ private static void ApplyWorksets(RevitFileInfo info, ParsingState? state) internal static int? StoredGroupMembership(ushort rootClass, TfBlockDeserializer.NativeParams np) => rootClass != 1322 && np.Fields.TryGetValue("422:m_groupId", out int groupId) && groupId > 0 ? groupId : null; - /// - /// Apply the native parameter stores (schema-deserialized Element m_pParamValueSet* containers) - /// - the file's authoritative stored params. - /// - internal static void ApplyNativeParams(RevitFileInfo info, ParsingState? state) + // These facts are used by the compact API and IFC export. Scene properties use the resolved Parameter values. + private static void ApplyNativeExportFacts(Element e, TfBlockDeserializer.NativeParams np) + { + var storedIds = new HashSet(); + foreach (var (pid, _) in np.Doubles) storedIds.Add(pid); + foreach (var (pid, _) in np.Ints) storedIds.Add(pid); + foreach (var (pid, _) in np.Strings) storedIds.Add(pid); + foreach (var (pid, _) in np.ElementIds) storedIds.Add(pid); + foreach (var named in np.NamedParams) + if (named.ParamId < 0) storedIds.Add(named.ParamId); + if (storedIds.Count > 0) e.NativeStoredParameterIds = storedIds; + var storeIds = new HashSet(); + foreach (var (pid, _) in np.Doubles) storeIds.Add(pid); + foreach (var (pid, _) in np.Ints) storeIds.Add(pid); + foreach (var (pid, _) in np.Strings) storeIds.Add(pid); + foreach (var (pid, _) in np.ElementIds) storeIds.Add(pid); + e.NativeParameterStoreIds = storeIds; + e.NativeParameterStoresComplete = np.RootParameterStoresComplete; + e.NativeCellListTag = np.Fields.TryGetValue("37:m_cellList", out int cellListTag) ? cellListTag : null; + e.NativeCellClasses = np.CellClasses?.ToArray(); + e.NativeTailWalkComplete = np.TailWalkComplete; + if (np.NamedParams.Count > 0) + e.NativeNamedParameters = np.NamedParams.Where(named => named.ParamId < 0).Select(named => (named.ParamId, named.Instance)).ToArray(); + // the two element-base keys are only kept for family instances (they exist in every + // record) + bool familyInstanceRecord = np.Fields.ContainsKey("1794:m_masterSymbolId"); + foreach (string key in TfBlockDeserializer.ListFactFieldKeys) + if (np.Fields.TryGetValue(key, out int listFieldValue) && (familyInstanceRecord || !key.StartsWith("37:", StringComparison.Ordinal))) + (e.NativeListFields ??= new())[key] = listFieldValue; + foreach (string key in TfBlockDeserializer.RoomRuleFieldKeys) + { + if (np.Fields.TryGetValue(key, out int roomRuleInt)) (e.NativeRoomFields ??= new())[key] = roomRuleInt; + else if (np.DoubleFields.TryGetValue(key, out double roomRuleReal) && double.IsFinite(roomRuleReal)) + (e.NativeRoomFields ??= new())[key] = roomRuleReal; + } + } + + /// Applies the file's authoritative native parameter stores. + internal static void ApplyNativeParams(RevitFileInfo info, ParsingState? state, NativeTableEffectsScratch? effectsScratch = null) { if (state == null || (state.NativeParams.Count == 0 @@ -3154,6 +3275,7 @@ internal static void ApplyNativeParams(RevitFileInfo info, ParsingState? state) } bool hasZeroPhase = Parameter.HasZeroProjectPhase(info, state); bool hasZeroDimStyle = Parameter.HasZeroDimensionStyle(info, state); + var byId = new Dictionary(); foreach (var e in info.Elements) { e.SerializedCurtainWallFunction = null; @@ -3200,41 +3322,10 @@ internal static void ApplyNativeParams(RevitFileInfo info, ParsingState? state) e.SerializedStairRunTypeNosingFeet = nosing; if (e.CategoryId == -2000011 && np.Fields.TryGetValue("362:m_isFlipped", out int wallFlipped)) e.SerializedWallFlipped = wallFlipped != 0; - var byId = new Dictionary(); + byId.Clear(); foreach (var p in e.Parameters) byId.TryAdd(p.Id, p); - var storedIds = new HashSet(); - foreach (var (pid, _) in np.Doubles) storedIds.Add(pid); - foreach (var (pid, _) in np.Ints) storedIds.Add(pid); - foreach (var (pid, _) in np.Strings) storedIds.Add(pid); - foreach (var (pid, _) in np.ElementIds) storedIds.Add(pid); - foreach (var named in np.NamedParams) - if (named.ParamId < 0) storedIds.Add(named.ParamId); - if (storedIds.Count > 0) e.NativeStoredParameterIds = storedIds; - var storeIds = new HashSet(); - foreach (var (pid, _) in np.Doubles) storeIds.Add(pid); - foreach (var (pid, _) in np.Ints) storeIds.Add(pid); - foreach (var (pid, _) in np.Strings) storeIds.Add(pid); - foreach (var (pid, _) in np.ElementIds) storeIds.Add(pid); - e.NativeParameterStoreIds = storeIds; - e.NativeParameterStoresComplete = np.RootParameterStoresComplete; - e.NativeCellListTag = np.Fields.TryGetValue("37:m_cellList", out int cellListTag) ? cellListTag : null; - e.NativeCellClasses = np.CellClasses?.ToArray(); - e.NativeTailWalkComplete = np.TailWalkComplete; e.ExtensibleStorage = np.ExtensibleStorage; - if (np.NamedParams.Count > 0) - e.NativeNamedParameters = np.NamedParams.Where(named => named.ParamId < 0).Select(named => (named.ParamId, named.Instance)).ToArray(); - // the two element-base keys are only kept for family instances (they exist in every - // record) - bool familyInstanceRecord = np.Fields.ContainsKey("1794:m_masterSymbolId"); - foreach (string key in TfBlockDeserializer.ListFactFieldKeys) - if (np.Fields.TryGetValue(key, out int listFieldValue) && (familyInstanceRecord || !key.StartsWith("37:", StringComparison.Ordinal))) - (e.NativeListFields ??= new())[key] = listFieldValue; - foreach (string key in TfBlockDeserializer.RoomRuleFieldKeys) - { - if (np.Fields.TryGetValue(key, out int roomRuleInt)) (e.NativeRoomFields ??= new())[key] = roomRuleInt; - else if (np.DoubleFields.TryGetValue(key, out double roomRuleReal) && double.IsFinite(roomRuleReal)) - (e.NativeRoomFields ??= new())[key] = roomRuleReal; - } + if (state.KeepExportProvenance) ApplyNativeExportFacts(e, np); if (TfBlockDeserializer.CaptureAllFields) { e.DebugNativeFields = new Dictionary(); @@ -3674,6 +3765,8 @@ void ApplyType(int typeId) Apply(-1005147, StorageType.ElementId, fsp); // VIEW_FIXED_SKETCH_PLANE if (np.Fields.TryGetValue("m_bUseTrueNorth", out int tn)) Apply(-1005168, StorageType.Integer, tn); // PLAN_VIEW_NORTH + effectsScratch?.Archive(e); + state.ArchiveSceneParameters?.Invoke(e); } Parameter.ResolveZeroElementIds(info, state); } @@ -3941,7 +4034,7 @@ internal static void ApplySerializedStairData( private static void ApplyBipKeyedStrings(RevitFileInfo info, ParsingState? state) { if (state == null || state.BipKeyedStrings.Count == 0) return; - foreach (var e in info.Elements) + foreach (var e in ElementsWithParameterEdits(info.Elements, state.ArchiveSceneParameters)) { if (!state.BipKeyedStrings.TryGetValue((uint)e.Id, out var map)) continue; var byBip = new Dictionary(); @@ -3969,9 +4062,6 @@ private static void ApplyBipKeyedStrings(RevitFileInfo info, ParsingState? state private static void ApplyComputedHeights(RevitFileInfo info, ParsingState? state) { - var byId = new Dictionary(); - foreach (var e in info.Elements) byId[e.Id] = e; - // (1) level elevations - three sources in priority order: a) an already-decoded LEVEL_ELEV // parameter; b) the [elev][-0.0][-1.0] block-signature candidate; c) wall votes: for a wall // based on level L, bboxMinZ - baseOffset == elev(L). @@ -3980,7 +4070,7 @@ private static void ApplyComputedHeights(RevitFileInfo info, ParsingState? state { if (e.CategoryId != -2000011 || GeometryBox(e) is not { Length: 6 } wb) continue; int baseId = -1; double bo = 0; - foreach (var p in e.Parameters) + foreach (var p in e.ReadParameters) { if (p.Id == -1001107 && p.Value is int b && b > 0) baseId = b; else if (p.Id == -1001108 && p.Value is double o1) bo = o1; @@ -3991,7 +4081,7 @@ private static void ApplyComputedHeights(RevitFileInfo info, ParsingState? state } var levelElev = new Dictionary(); - foreach (var e in info.Elements) + foreach (var e in ElementsWithParameterEdits(info.Elements, state?.ArchiveSceneParameters)) { if (e.CategoryId != -2000240) continue; var p = e.Parameters.FirstOrDefault(p => p.Id == -1007102); @@ -4012,10 +4102,12 @@ private static void ApplyComputedHeights(RevitFileInfo info, ParsingState? state } } - foreach (var e in info.Elements) + var existing = new HashSet(); + foreach (var e in ElementsWithParameterEdits(info.Elements, state?.ArchiveSceneParameters)) { - var existing = new HashSet(); - foreach (var p in e.Parameters) existing.Add(p.Id); + if (e.CategoryId is not (-2000011 or -2000170 or -2000032 or -2001320 or -2001330 or -2001300)) continue; + existing.Clear(); + foreach (var p in e.ReadParameters) existing.Add(p.Id); void Add(int id, string name, double val) { if (!existing.Contains(id)) @@ -4083,10 +4175,9 @@ void Add(int id, string name, double val) // Sanitize computed-quantity placeholders: Revit never reports non-positive // HOST_AREA/VOLUME/PERIMETER; a - here is a binary placeholder, not a value. - foreach (var e in info.Elements) - e.Parameters.RemoveAll(p => - p.Id is -1012805 or -1012806 or -1012807 && - ((p.Value is double dv && dv <= 0) || (p.Value is int iv && iv <= 0))); + foreach (var e in ElementsWithParameterEdits(info.Elements, state?.ArchiveSceneParameters)) + if (e.HasHostQuantityPlaceholder) + e.Parameters.RemoveAll(Parameter.IsHostQuantityPlaceholder); } /// @@ -4130,33 +4221,50 @@ private static GeometryData BuildBoxGeometry(double[] bb) return geo; } + private static int DominantCreatedPhase(List elements) + { + var votes = new Dictionary(); + foreach (var e in elements) + { + int phase = e.FirstPositiveCreatedPhase; + if (phase > 0) votes[phase] = votes.GetValueOrDefault(phase) + 1; + } + int dominant = -1, count = 0; + foreach (var (phase, votesForPhase) in votes) + if (votesForPhase > count) + { + dominant = phase; + count = votesForPhase; + } + return dominant; + } + /// /// Constant/default parameters the Revit API reports on views, datums and dimensions, each /// constant for the whole file. /// - private static void AddViewAndDatumDefaults(RevitFileInfo info) + private static void AddViewAndDatumDefaults(RevitFileInfo info, Action? archiveParameters) { // VIEW_PHASE: views report the model's dominant phase - derive it as the most common // PHASE_CREATED value across all elements. - var phaseVotes = new Dictionary(); - foreach (var e in info.Elements) - foreach (var p in e.Parameters) - if (p.Id == -1012100 && p.Value is int ph && ph > 0) - { phaseVotes.TryGetValue(ph, out int n); phaseVotes[ph] = n + 1; break; } - int domPhase = -1, domN = 0; - foreach (var (ph, n) in phaseVotes) if (n > domN) { domPhase = ph; domN = n; } + int domPhase = DominantCreatedPhase(info.Elements); - foreach (var e in info.Elements) + var existing = new HashSet(); + foreach (var e in ElementsWithParameterEdits(info.Elements, archiveParameters)) { if (e.CategoryId is not int c) continue; - var existing = new HashSet(); - foreach (var p in e.Parameters) existing.Add(p.Id); + bool view = ViewCategories.Contains(c); + bool datum = c is -2000530 or -2000220 or -2000240; + bool dimension = c is -2000260 or -2000261 or -2000262 || e.Dimension != null; + if (!view && !datum && !dimension && c is not (-2009645 or -2000045)) continue; + existing.Clear(); + foreach (var p in e.ReadParameters) existing.Add(p.Id); void Add(int id, string name, StorageType st, object val) { if (!existing.Contains(id)) e.Parameters.Add(BipHelpers.MakeBipParam(id, name, st, val)); } - if (ViewCategories.Contains(c)) + if (view) { Add(-1005176, "VIEW_TEMPLATE", StorageType.ElementId, -1); Add(-1005199, "VIEW_TEMPLATE_FOR_SCHEDULE", StorageType.ElementId, -1); @@ -4169,9 +4277,9 @@ void Add(int id, string name, StorageType st, object val) if (domPhase > 0) Add(-1012102, "VIEW_PHASE", StorageType.ElementId, domPhase); } - if (c is -2000530 or -2000220 or -2000240) // ref planes / grids / levels + if (datum) // ref planes / grids / levels Add(-1012201, "DATUM_VOLUME_OF_INTEREST", StorageType.ElementId, -1); - if (c is -2000260 or -2000261 or -2000262 || e.Dimension != null) + if (dimension) { Add(-1006477, "BASELINE_DIM_OFFSET", StorageType.Double, 0.0); Add(-1004515, "DIM_LEADER", StorageType.Integer, 1); @@ -4241,7 +4349,7 @@ void AddRef(int bip, string name, int val) /// Emit CURVE_ELEM_LENGTH from the element's decoded location curve length (walls, model/sketch /// lines) when the binary body didn't already provide it. /// - internal static void AddCurveLengths(RevitFileInfo info) + internal static void AddCurveLengths(RevitFileInfo info, Action? archiveParameters = null) { foreach (var e in info.Elements) { @@ -4255,16 +4363,12 @@ internal static void AddCurveLengths(RevitFileInfo info) len = Math.Max(bb[3] - bb[0], Math.Max(bb[4] - bb[1], bb[5] - bb[2])); approximate = true; } - if (len <= 1e-9) continue; + if (len <= 1e-9 || e.ReadParameters.Any(parameter => parameter.Id == -1004005)) continue; - bool has = false; - foreach (var p in e.Parameters) if (p.Id == -1004005) { has = true; break; } - if (!has) - { - var param = BipHelpers.MakeBipParam(-1004005, "CURVE_ELEM_LENGTH", StorageType.Double, len); - param.IsApproximate = approximate; - e.Parameters.Add(param); - } + var param = BipHelpers.MakeBipParam(-1004005, "CURVE_ELEM_LENGTH", StorageType.Double, len); + param.IsApproximate = approximate; + e.Parameters.Add(param); + archiveParameters?.Invoke(e); } } @@ -4294,24 +4398,18 @@ public static void BuildDiscoveredElement(uint eid, ParsingState state, RevitFil } if (rec.References.Count > 0) - elem.References = rec.References.Select(r => (int)r).ToList(); + elem.SetReferences(rec.References.Select(r => (int)r), state.KeepExportProvenance); // Body BIP entries foreach (var b in rec.BipParams) { if (b.BipId == 0 && !b.Value.HasValue) continue; BipNames.Lookup.TryGetValue(b.BipId, out string? bipName); - var param = new Parameter - { - Id = b.BipId, - StorageType = BipHelpers.BipStorageType(bipName), - IsReadOnly = BipHelpers.IsBipReadOnly(bipName), - Definition = new Definition { Id = b.BipId, BuiltInParameter = bipName, Name = bipName }, - }; - if (param.StorageType == StorageType.Double && state.ElemBipDoubles.TryGetValue(eid, out var dblMap) && dblMap.TryGetValue(b.BipId, out double dv)) + var param = BipHelpers.MakeBipParam(b.BipId, bipName, BipHelpers.BipStorageType(bipName), null); + if (param.StorageType == StorageType.Double && state.TryReadBipDoubles(eid, out var dblMap) && dblMap.TryGetValue(b.BipId, out double dv)) param.Value = dv; else if ((param.StorageType == StorageType.Integer || param.StorageType == StorageType.ElementId) - && state.ElemBipInts.TryGetValue(eid, out var intMap) && intMap.TryGetValue(b.BipId, out int iv)) + && state.TryReadBipInts(eid, out var intMap) && intMap.TryGetValue(b.BipId, out int iv)) param.Value = iv; else param.Value = b.Value.HasValue ? (object)b.Value.Value : null; @@ -4375,7 +4473,9 @@ public static void BuildBlockOnlyElement(uint bid, ParsingState state, RevitFile /// internal static void AttachFamilyCutGeometry(Element elem, uint elementId, ParsingState state) { - if (state.FamilyCutGreps.TryGetValue(elementId, out var familyCut)) + // The scene uses the already resolved visible faces. The cutting operand itself + // is needed by IFC, which constructs its own host representation. + if (state.KeepExportProvenance && state.FamilyCutGreps.TryGetValue(elementId, out var familyCut)) { elem.FamilyCutGeometry = BuildGeometryData(familyCut, state.SeparateFacesWithDistinctOpenings); elem.FamilyCutClosurePlaneOrigin = familyCut.FamilyClosurePlaneOrigin; @@ -4389,7 +4489,7 @@ internal static void AttachFamilyCutGeometry(Element elem, uint elementId, Parsi elem.CuttingElementIds = cuttingElementIds.Select(id => (int)id).ToList(); if (state.HostCutOutSteps.TryGetValue(elementId, out var cutOutSteps) && (!state.HostCutOutStepsFromLayoutSearch.Contains(elementId) - || elem.References is { } hostReferences && cutOutSteps.All(step => hostReferences.Contains(step.ElementId)))) + || elem.ReadReferences is { } hostReferences && cutOutSteps.All(step => hostReferences.Contains(step.ElementId)))) elem.CutOutSteps = cutOutSteps; } @@ -4974,6 +5074,8 @@ internal static (int Elements, int ReplacedUniqueIds) ApplyExportIds( int applied = 0, replaced = 0; foreach (Element element in elements) { + string? previousUniqueId = element.UniqueId; + element.UniqueId = previousUniqueId; element.SerializedExportId = null; element.SerializedHandleExportId = null; // Id 0 is a valid ElemTable row (ProjectPhase / DimensionStyle) across wide and native R22 tables. @@ -4989,9 +5091,14 @@ internal static (int Elements, int ReplacedUniqueIds) ApplyExportIds( element.SerializedExportId = ElementExportIds.ExportId(episode, originalId); if (element.ElementId >= 0) element.SerializedHandleExportId = ElementExportIds.ExportId(episode, (ulong)element.ElementId); - string uniqueId = ElementExportIds.UniqueId(episode, originalId); - if (element.UniqueId != null && element.UniqueId != uniqueId) replaced++; - element.UniqueId = uniqueId; + if (state.KeepExportProvenance || previousUniqueId != null) + { + string uniqueId = ElementExportIds.UniqueId(episode, originalId); + if (previousUniqueId != null && previousUniqueId != uniqueId) replaced++; + element.UniqueId = uniqueId; + } + // Only the elements included in the scene need the formatted string. + if (!state.KeepExportProvenance) element.DeferUniqueId(); applied++; } return (applied, replaced); @@ -5756,8 +5863,10 @@ internal static void RepairBasicWallTypeFunctionBodyFallbacks( } } - public static void PostProcess(RevitFileInfo rvtInfo, ParsingState? state = null, TextWriter? diag = null) + public static void PostProcess(RevitFileInfo rvtInfo, ParsingState? state = null, TextWriter? diag = null, + Action? passCompleted = null) { + var archiveParameters = state?.ArchiveSceneParameters; ApplyGridDatums(rvtInfo, state); rvtInfo.GraphicsStyles = state?.GraphicsStyles .Where(pair => pair.Value is { BlockCount: 1, MaterialId: not null }) @@ -5767,14 +5876,23 @@ public static void PostProcess(RevitFileInfo rvtInfo, ParsingState? state = null .ToDictionary(pair => (int)pair.Key, pair => pair.Value.Name!); var idToName = new Dictionary(); - var idToElem = new Dictionary(); + var idToElem = new Dictionary(rvtInfo.Elements.Count); + bool duplicateIds = false; foreach (var e in rvtInfo.Elements) { if (!string.IsNullOrEmpty(e.Name)) idToName[e.Id] = e.Name; - idToElem[e.Id] = e; + if (!idToElem.TryAdd(e.Id, e)) + { + duplicateIds = true; + idToElem[e.Id] = e; + } } + Element? FirstElement(int id) => duplicateIds + ? rvtInfo.Elements.FirstOrDefault(element => element.Id == id) + : idToElem.GetValueOrDefault(id); + // Inherit category from type element or references Phase 1: TypeId and ELEM_TYPE_PARAM // (safe, direct type->instance) var idToCategory = new Dictionary(); @@ -5796,7 +5914,7 @@ public static void PostProcess(RevitFileInfo rvtInfo, ParsingState? state = null } // ELEM_TYPE_PARAM from record body - var typeParam = e.Parameters.FirstOrDefault(p => p.Id == -1002050); + var typeParam = e.ReadParameters.FirstOrDefault(p => p.Id == -1002050); if (typeParam?.Value is int tpId && idToCategory.TryGetValue(tpId, out var tpCat)) { e.CategoryId = tpCat.catId; @@ -5817,8 +5935,8 @@ public static void PostProcess(RevitFileInfo rvtInfo, ParsingState? state = null int added = 0; foreach (var e in rvtInfo.Elements) { - if (e.CategoryId.HasValue || e.References == null) continue; - foreach (var refId in e.References) + if (e.CategoryId.HasValue || e.ReadReferences == null) continue; + foreach (var refId in e.ReadReferences) { if (refId == e.Id) continue; if (idToCategory.TryGetValue(refId, out var refCat) @@ -5845,9 +5963,9 @@ public static void PostProcess(RevitFileInfo rvtInfo, ParsingState? state = null var levelNameFromView = new Dictionary(); foreach (var e in rvtInfo.Elements) { - if (e.Category != "OST_Views" || string.IsNullOrEmpty(e.Name) || e.References == null) continue; + if (e.Category != "OST_Views" || string.IsNullOrEmpty(e.Name) || e.ReadReferences == null) continue; var levelRefs = new List(); - foreach (var r in e.References) + foreach (var r in e.ReadReferences) if (levelIds.Contains(r)) levelRefs.Add(r); if (levelRefs.Count != 1) continue; int lid = levelRefs[0]; @@ -5889,14 +6007,14 @@ public static void PostProcess(RevitFileInfo rvtInfo, ParsingState? state = null // Material name: first record body reference that has a name and isn't self/preview string? materialName = null; - if (e.References != null) + if (e.ReadReferences != null) { - foreach (var refId in e.References) + foreach (var refId in e.ReadReferences) { if (refId == e.Id) continue; if (idToName.TryGetValue(refId, out var rn) && !string.IsNullOrEmpty(rn)) { - var refElem = rvtInfo.Elements.FirstOrDefault(x => x.Id == refId); + var refElem = FirstElement(refId); if (refElem?.Category is "OST_PreviewLegendComponents" or "OST_Materials") continue; materialName = rn; break; @@ -5905,7 +6023,7 @@ public static void PostProcess(RevitFileInfo rvtInfo, ParsingState? state = null } // Width from WALL_ATTR_WIDTH_PARAM (in feet -> mm) - var widthParam = e.Parameters.FirstOrDefault(p => p.Id == -1001000); + var widthParam = e.ReadParameters.FirstOrDefault(p => p.Id == -1001000); double widthFt = widthParam?.Value is double dw ? dw : 0; int widthMm = (int)Math.Round(widthFt * 304.8); @@ -5918,11 +6036,11 @@ public static void PostProcess(RevitFileInfo rvtInfo, ParsingState? state = null } // Attach CompoundStructure layers to wall type elements - if (state?.CompoundLayers.Count > 0) + if (state is { KeepExportProvenance: true } && state.CompoundLayers.Count > 0) { foreach (var (eid, layers) in state.CompoundLayers) { - var elem = rvtInfo.Elements.FirstOrDefault(e => e.Id == (int)eid); + var elem = FirstElement((int)eid); if (elem == null) continue; elem.Layers = layers.Select(l => new Model.MaterialLayer { @@ -5944,7 +6062,7 @@ public static void PostProcess(RevitFileInfo rvtInfo, ParsingState? state = null { if (e.Layers != null && e.Layers.Count > 0) continue; if (e.Category != null && !layerHostCats.Contains(e.Category)) continue; - var tp = e.Parameters.FirstOrDefault(p => p.Id == -1002050); + var tp = e.ReadParameters.FirstOrDefault(p => p.Id == -1002050); if (tp?.Value is int typeId && layersByElemId.TryGetValue(typeId, out var typeLayers)) { e.Layers = typeLayers; continue; } // An element whose own record names its type takes the layers of that type only: its References also @@ -5955,8 +6073,8 @@ public static void PostProcess(RevitFileInfo rvtInfo, ParsingState? state = null continue; } // Try References (for walls without ELEM_TYPE_PARAM) - if (e.References == null) continue; - foreach (var refId in e.References) + if (e.ReadReferences == null) continue; + foreach (var refId in e.ReadReferences) { if (layersByElemId.TryGetValue(refId, out var refLayers)) { e.Layers = refLayers; break; } @@ -5969,32 +6087,33 @@ public static void PostProcess(RevitFileInfo rvtInfo, ParsingState? state = null // Resolve TypeId independently: ElemTable contains no type element id. Resolution priority: // 1. ELEM_TYPE_PARAM value if it references a real element of the same category 2. // SYMBOL_ID_PARAM value (same check) 3. - var allElemIds = new HashSet(rvtInfo.Elements.Select(e => e.Id)); - var elemByIdLookup = rvtInfo.Elements.ToDictionary(e => e.Id); + // Preserve the duplicate-key check of the type lookup. + if (duplicateIds) _ = rvtInfo.Elements.ToDictionary(e => e.Id); + int[] typeParameterIds = [-1002050, -1002000, -1002052]; foreach (var e in rvtInfo.Elements) { // Trust current TypeId only if it resolves to an element of the SAME category. // Otherwise it's likely a Tf-class index or a leaked phase/sentinel value. - bool currentValid = e.TypeId > 0 && elemByIdLookup.TryGetValue(e.TypeId, out var curType) + bool currentValid = e.TypeId > 0 && idToElem.TryGetValue(e.TypeId, out var curType) && (curType.CategoryId == e.CategoryId || !e.CategoryId.HasValue); if (currentValid) continue; int? resolved = null; - foreach (int paramId in new[] { -1002050, -1002000, -1002052 }) + foreach (int paramId in typeParameterIds) { - var p = e.Parameters.FirstOrDefault(pp => pp.Id == paramId); - if (p?.Value is int v && v > 0 && elemByIdLookup.TryGetValue(v, out var paramTarget) + var p = e.ReadParameters.FirstOrDefault(pp => pp.Id == paramId); + if (p?.Value is int v && v > 0 && idToElem.TryGetValue(v, out var paramTarget) && (paramTarget.CategoryId == e.CategoryId || !e.CategoryId.HasValue)) { resolved = v; break; } } // Room separation lines reference other boundaries, but have no Revit type. - if (resolved == null && e.References != null && e.CategoryId.HasValue + if (resolved == null && e.ReadReferences != null && e.CategoryId.HasValue && e.CategoryId != (int)BuiltIns.BuiltInCategory.OST_RoomSeparationLines) { - foreach (var refId in e.References) + foreach (var refId in e.ReadReferences) { if (refId == e.Id) continue; - if (!elemByIdLookup.TryGetValue(refId, out var refElem)) continue; + if (!idToElem.TryGetValue(refId, out var refElem)) continue; if (refElem.CategoryId == e.CategoryId) { // Prefer the lowest-ID candidate (types are typically created before @@ -6007,15 +6126,15 @@ public static void PostProcess(RevitFileInfo rvtInfo, ParsingState? state = null } // Also overwrite ELEM_TYPE_PARAM / SYMBOL_ID_PARAM / ELEM_FAMILY_AND_TYPE_PARAM values when // the resolved TypeId differs from the stored garbage (e.g. 528 Tf-class index) - foreach (var e in rvtInfo.Elements) + foreach (var e in ElementsWithParameterEdits(rvtInfo.Elements, archiveParameters)) { - if (e.TypeId <= 0 || !allElemIds.Contains(e.TypeId)) continue; - foreach (int paramId in new[] { -1002050, -1002000, -1002052 }) + if (e.TypeId <= 0 || !idToElem.ContainsKey(e.TypeId)) continue; + foreach (int paramId in typeParameterIds) { - var p = e.Parameters.FirstOrDefault(pp => pp.Id == paramId); + var p = e.ReadParameters.FirstOrDefault(pp => pp.Id == paramId); if (p == null) continue; - if (p.Value is int v && v > 0 && allElemIds.Contains(v)) continue; // already valid - p.Value = e.TypeId; + if (p.Value is int v && v > 0 && idToElem.ContainsKey(v)) continue; // already valid + e.Parameters.First(pp => pp.Id == paramId).Value = e.TypeId; } } // Rebuild idToName after TypeId fix @@ -6039,14 +6158,13 @@ public static void PostProcess(RevitFileInfo rvtInfo, ParsingState? state = null } else if (string.IsNullOrEmpty(e.Name)) { - var typeParam = e.Parameters.FirstOrDefault(p => p.Id == -1002050); + var typeParam = e.ReadParameters.FirstOrDefault(p => p.Id == -1002050); if (typeParam?.Value is int tpId && idToName.TryGetValue(tpId, out var tpName)) e.Name = tpName; } } // Compatibility fallback for versions where InsertableInst.m_hostId was not decoded. - var elemById = rvtInfo.Elements.ToDictionary(e => e.Id); var hostCategories = new HashSet { "OST_Walls", "OST_Floors", "OST_Ceilings", "OST_Roofs" }; var insertCategories = new HashSet { "OST_Doors", "OST_Windows", "OST_MechanicalEquipment", "OST_GenericModel", "OST_StructuralColumns", "OST_CurtainWallPanels" }; @@ -6054,10 +6172,10 @@ public static void PostProcess(RevitFileInfo rvtInfo, ParsingState? state = null { if (e.SerializedHostId.HasValue) continue; if (e.Category == null || !insertCategories.Contains(e.Category)) continue; - if (e.References == null) continue; - foreach (var refId in e.References) + if (e.ReadReferences == null) continue; + foreach (var refId in e.ReadReferences) { - if (elemById.TryGetValue(refId, out var refElem) && refElem.Category != null + if (idToElem.TryGetValue(refId, out var refElem) && refElem.Category != null && hostCategories.Contains(refElem.Category)) { e.HostId = refId; @@ -6068,17 +6186,17 @@ public static void PostProcess(RevitFileInfo rvtInfo, ParsingState? state = null // Fix computed WALL_USER_HEIGHT_PARAM: stored value in 0xFFFF blocks is the type default // which often equals wall width. - foreach (var e in rvtInfo.Elements) + foreach (var e in ElementsWithParameterEdits(rvtInfo.Elements, archiveParameters)) { if (e.Category != "OST_Walls" || GeometryBox(e) is not { Length: 6 }) continue; - var hp = e.Parameters.FirstOrDefault(p => p.Id == -1001105); // WALL_USER_HEIGHT_PARAM - var wp = e.Parameters.FirstOrDefault(p => p.Id == -1001000); // WALL_ATTR_WIDTH_PARAM + var hp = e.ReadParameters.FirstOrDefault(p => p.Id == -1001105); // WALL_USER_HEIGHT_PARAM + var wp = e.ReadParameters.FirstOrDefault(p => p.Id == -1001000); // WALL_ATTR_WIDTH_PARAM if (hp?.Value is double storedH && wp?.Value is double storedW && storedW > 0) { double dz = GeometryBox(e)![5] - GeometryBox(e)![2]; // Only fix if stored height equals stored width (type default leak) AND dz differs if (Math.Abs(storedH - storedW) < 0.001 && dz > 0.01 && Math.Abs(dz - storedH) > 0.01) - hp.Value = dz; + e.Parameters.First(p => p.Id == -1001105).Value = dz; } } @@ -6114,7 +6232,7 @@ public static void PostProcess(RevitFileInfo rvtInfo, ParsingState? state = null if (isReal) realTotal++; // Symbol id: the element's own id if IT has a name entry with a parent, otherwise its // ELEM_TYPE_PARAM target. - var typeParam = e.Parameters.FirstOrDefault(p => p.Id == -1002050); + var typeParam = e.ReadParameters.FirstOrDefault(p => p.Id == -1002050); bool hasTypeParam = typeParam?.Value is int htp && htp > 0; int symbolId = typeParam?.Value is int tid && tid > 0 ? tid : e.Id; if (isReal && hasTypeParam) realHasTypeParam++; @@ -6163,7 +6281,7 @@ public static void PostProcess(RevitFileInfo rvtInfo, ParsingState? state = null continue; } - var famParam = e.Parameters.FirstOrDefault(p => p.Id == -1002051); + var famParam = e.ReadParameters.FirstOrDefault(p => p.Id == -1002051); if (famParam?.Value is int famId && famId > 0) { if (state.ElementNameTable.TryGetValue((uint)famId, out var tblName)) @@ -6182,7 +6300,7 @@ public static void PostProcess(RevitFileInfo rvtInfo, ParsingState? state = null // Fallback: look at type element's ELEM_FAMILY_PARAM if (typeParam?.Value is int typeId && typeId > 0 && idToElem.TryGetValue(typeId, out var typeElem)) { - var typeFam = typeElem.Parameters.FirstOrDefault(p => p.Id == -1002051); + var typeFam = typeElem.ReadParameters.FirstOrDefault(p => p.Id == -1002051); if (typeFam?.Value is int typeFamId && typeFamId > 0 && idToName.TryGetValue(typeFamId, out var typeFamName)) { e.FamilyName = typeFamName; viaTypeElement++; @@ -6275,7 +6393,7 @@ void ReportDistinctMissing(string label, Dictionary counts) { if (e.CategoryId == -2000220) continue; if (state.ElementNameTable.ContainsKey((uint)e.Id)) continue; // has own name - var tp = e.Parameters.FirstOrDefault(p => p.Id == -1002050); + var tp = e.ReadParameters.FirstOrDefault(p => p.Id == -1002050); if (tp?.Value is int tid && tid > 0 && tid != e.Id && state.ElementNameTable.TryGetValue((uint)tid, out var typeName)) e.Name = typeName; @@ -6283,53 +6401,45 @@ void ReportDistinctMissing(string label, Dictionary counts) // The compatibility ELEM_TYPE_PARAM value above can be a real element id of the wrong // category even after TypeId was canonically resolved. ApplyValidatedWallTypeNames( - rvtInfo.Elements, elemByIdLookup, + rvtInfo.Elements, idToElem, state.CompoundStructureTypeNameSource, state.NativeParams); ApplyValidatedCeilingTypeNames( - rvtInfo.Elements, elemByIdLookup, + rvtInfo.Elements, idToElem, state.CeilingTypeNameSource); - // User param name resolution: use ForgeParamDefs (reliable) or ElemStrings &-prefix DO NOT - // use idToName for ParamElem elements - their Name comes from unreliable ScanStr - var paramDefNames = new Dictionary(); - foreach (var (pid, def) in state.ForgeParamDefs) - { - if (def.DisplayName != null) - paramDefNames[(int)pid] = def.DisplayName; - } - // Also try extracting names from &-prefixed strings in ElemStrings for elements not yet in - // paramDefNames - foreach (var (pid, strs) in state.ElemStrings) - { - if (paramDefNames.ContainsKey((int)pid)) continue; - var ampName = strs.FirstOrDefault(s => s.StartsWith('&') && s.Length > 1); - if (ampName != null) - paramDefNames[(int)pid] = ampName[1..]; - } + var paramDefNames = CollectParameterDefinitionNames(state); + state.SceneParameterNames = null; foreach (var e in rvtInfo.Elements) { - foreach (var p in e.Parameters) + int index = -1; + foreach (var p in e.ReadParameters) { - if (p.Id > 0 && string.IsNullOrEmpty(p.Definition?.Name) + index++; + if (p.Id > 0 && string.IsNullOrEmpty(p.DefinitionName) && paramDefNames.TryGetValue(p.Id, out var paramName)) { - p.Definition ??= new Definition(); - p.Definition.Id = p.Id; - p.Definition.Name = paramName; + var editable = e.Parameters[index]; + editable.Definition ??= new Definition(); + editable.Definition.Id = p.Id; + editable.Definition.Name = paramName; } } + state.ArchiveSceneParameters?.Invoke(e); } // Fix SYMBOL_ID_PARAM: record body stores it as -1 (null) for instances; SYMBOL_ID_PARAM // should always equal ELEM_TYPE_PARAM for FamilyInstances. foreach (var e in rvtInfo.Elements) { - var symParam = e.Parameters.FirstOrDefault(p => p.Id == -1002000); + var symParam = e.ReadParameters.FirstOrDefault(p => p.Id == -1002000); if (symParam?.Value is not int sv || sv > 0) continue; // already valid - var typeParam = e.Parameters.FirstOrDefault(p => p.Id == -1002050); + var typeParam = e.ReadParameters.FirstOrDefault(p => p.Id == -1002050); if (typeParam?.Value is int tv && tv > 0) - symParam.Value = tv; + { + e.Parameters.First(p => p.Id == -1002000).Value = tv; + state.ArchiveSceneParameters?.Invoke(e); + } } // Infer Level element elevations (LEVEL_ELEV = -1007102) via cross-reference: Elements on a @@ -6340,7 +6450,7 @@ void ReportDistinctMissing(string label, Dictionary counts) const int OST_LEVELS = -2000240; var levelElemIdSet = new HashSet(rvtInfo.Elements - .Where(e => e.Parameters.Any(p => p.Id == BIP_ELEM_CATEGORY && p.Value is int c && c == OST_LEVELS)) + .Where(e => e.ReadParameters.Any(p => p.Id == BIP_ELEM_CATEGORY && p.Value is int c && c == OST_LEVELS)) .Select(e => e.Id)); if (levelElemIdSet.Count > 0) @@ -6349,11 +6459,11 @@ void ReportDistinctMissing(string label, Dictionary counts) foreach (var e in rvtInfo.Elements) { - var le = e.Parameters.FirstOrDefault(p => p.Id == BIP_LEVEL_ELEV); + var le = e.ReadParameters.FirstOrDefault(p => p.Id == BIP_LEVEL_ELEV); if (le?.Value is not double elev) continue; - if (e.References == null) continue; + if (e.ReadReferences == null) continue; - foreach (var refId in e.References) + foreach (var refId in e.ReadReferences) { if (!levelElemIdSet.Contains(refId)) continue; // Wins (all samples for the same level should agree) @@ -6366,9 +6476,9 @@ void ReportDistinctMissing(string label, Dictionary counts) foreach (var levelId in levelElemIdSet) { if (!inferredLevelElevs.TryGetValue(levelId, out double elev)) continue; - var levelElem = rvtInfo.Elements.FirstOrDefault(e => e.Id == levelId); + var levelElem = idToElem.GetValueOrDefault(levelId); if (levelElem == null) continue; - if (levelElem.Parameters.Any(p => p.Id == BIP_LEVEL_ELEV)) continue; // already set + if (levelElem.ReadParameters.Any(p => p.Id == BIP_LEVEL_ELEV)) continue; // already set BipNames.Lookup.TryGetValue(BIP_LEVEL_ELEV, out string? bipName); levelElem.Parameters.Add(new Parameter @@ -6379,6 +6489,7 @@ void ReportDistinctMissing(string label, Dictionary counts) IsReadOnly = BipHelpers.IsBipReadOnly(bipName), Definition = new Definition { Id = BIP_LEVEL_ELEV, BuiltInParameter = bipName, Name = bipName } }); + archiveParameters?.Invoke(levelElem); } } } @@ -6391,19 +6502,19 @@ void ReportDistinctMissing(string label, Dictionary counts) const int BIP_INST_ELEV = -1001360; BipNames.Lookup.TryGetValue(BIP_INST_ELEV, out string? instElevName); - foreach (var e in rvtInfo.Elements) + foreach (var e in ElementsWithParameterEdits(rvtInfo.Elements, archiveParameters)) { - var existing = e.Parameters.FirstOrDefault(p => p.Id == BIP_INST_ELEV); + var existing = e.ReadParameters.FirstOrDefault(p => p.Id == BIP_INST_ELEV); if (existing?.Value is double) continue; // already a real double value - var le = e.Parameters.FirstOrDefault(p => p.Id == BIP_LEVEL_ELEV2); + var le = e.ReadParameters.FirstOrDefault(p => p.Id == BIP_LEVEL_ELEV2); if (le?.Value is not double levelElev) continue; if (GeometryBox(e) is not double[] bb || bb.Length < 6) continue; double instElev = bb[2] - levelElev; // MinZ - level elevation if (existing != null) - existing.Value = instElev; // update the null entry + e.Parameters.First(p => p.Id == BIP_INST_ELEV).Value = instElev; // update the null entry else e.Parameters.Add(new Parameter { @@ -6434,12 +6545,15 @@ void ReportDistinctMissing(string label, Dictionary counts) } } - ResolveTypeParams(rvtInfo); + ResolveTypeParams(rvtInfo, idToElem, archiveParameters); ApplyDetailLines(rvtInfo, state); ApplyBlockSignatureCategories(rvtInfo, state); + passCompleted?.Invoke(); // Native (schema-deserialized) params land BEFORE the default-emitting passes so // authoritative stored values are not blocked by add-if-missing defaults. - ApplyNativeParams(rvtInfo, state); + var nativeTableScratch = archiveParameters != null && state?.PartitionScratch is { } nativeBacking + ? new NativeTableEffectsScratch(nativeBacking) : null; + ApplyNativeParams(rvtInfo, state, nativeTableScratch); TraceElement(rvtInfo, "after-native"); if (state != null) { @@ -6448,9 +6562,10 @@ void ReportDistinctMissing(string label, Dictionary counts) rvtInfo.Elements, state.NativeParams, state.ElemClassIdx); } FixCategoryFromClassIdx(rvtInfo, state); - PropagateInstanceCategoryFromType(rvtInfo); + PropagateInstanceCategoryFromType(rvtInfo, state?.ArchiveSceneParameters); TraceElement(rvtInfo, "before-prune"); - PruneNativeFieldTableOutsideDomains(rvtInfo, state?.ElemClassIdx); + PruneNativeFieldTableOutsideDomains(rvtInfo, state?.ElemClassIdx, archiveParameters, nativeTableScratch); + nativeTableScratch = null; TraceElement(rvtInfo, "after-prune"); if (state != null) { @@ -6468,12 +6583,13 @@ void ReportDistinctMissing(string label, Dictionary counts) if (state != null) { ApplyValidatedMemberTypeNames( - rvtInfo.Elements, elemByIdLookup, + rvtInfo.Elements, idToElem, state.NativeParams, state.ElementNameTable, state.NativeElementNames); } - AddCategoryAndFamilyParams(rvtInfo); - AddCurveLengths(rvtInfo); + AddCategoryAndFamilyParams(rvtInfo, state?.ArchiveSceneParameters); + passCompleted?.Invoke(); + AddCurveLengths(rvtInfo, archiveParameters); ApplyMaterialAppearance(rvtInfo, state); ApplyHvacSpaceTypeParams(rvtInfo, state); if (state != null) ApplySerializedRoomNames(rvtInfo.Elements, state.RoomNameSource); @@ -6483,15 +6599,15 @@ void ReportDistinctMissing(string label, Dictionary counts) if (state != null) ApplySerializedSpaceBoundaries( rvtInfo.Elements, state.RoomNameSource, state.SpaceBoundarySource, state.SpaceLiteralBoundaries, state.SeparateFacesWithDistinctOpenings); - ApplyRoomParams(rvtInfo); - ApplySheetParams(rvtInfo, state); + ApplyRoomParams(rvtInfo, archiveParameters, idToElem); + ApplySheetParams(rvtInfo, state, idToElem); ApplyTextNotes(rvtInfo, state); ApplyViewports(rvtInfo, state); ApplyViewPlanes(rvtInfo, state); ApplyImageSizes(rvtInfo, state); ApplyViewportScales(rvtInfo, state); - AddViewAndDatumDefaults(rvtInfo); - AddCurtainQuantities(rvtInfo); + AddViewAndDatumDefaults(rvtInfo, state?.ArchiveSceneParameters); + AddCurtainQuantities(rvtInfo, state?.ArchiveSceneParameters); EnrichTypeLevelBips(rvtInfo, state); PropagateChainPlaceholders(rvtInfo, state); PropagateTypeElementIdParams(rvtInfo, state); @@ -6500,34 +6616,36 @@ void ReportDistinctMissing(string label, Dictionary counts) PropagateFamilySymbolBlockInts(rvtInfo, state); PropagateFamilyElementIdParams(rvtInfo, state); CoerceParamStorageByForge(rvtInfo, state); - ApplyDerivedDesignOptionName(rvtInfo); + ApplyDerivedDesignOptionName(rvtInfo, state?.ArchiveSceneParameters); ApplyCurveDriverLevelParams(rvtInfo); - ApplyHostIdParam(rvtInfo, state?.ElemClassIdx); - ApplyInstanceOriginOffsets(rvtInfo); - ApplyInstanceElevationFromLevel(rvtInfo); - ApplyStructuralColumnParams(rvtInfo); - ApplyRoomLevelParams(rvtInfo); - ApplyFramingSymbolLength(rvtInfo); - if (state != null) ApplyMullionSymbolLength(rvtInfo.Elements, state.NativeParams); - ApplyRoomBuildingTypeLoads(rvtInfo); - ApplyHeadHeight(rvtInfo); - ApplyStructuralConnectionParams(rvtInfo); - ApplyCrossSectionRotation(rvtInfo); - ApplyDetailCurveFlag(rvtInfo, state?.ElemClassIdx); + ApplyHostIdParam(rvtInfo, state?.ElemClassIdx, state?.ArchiveSceneParameters); + ApplyInstanceOriginOffsets(rvtInfo, state?.ArchiveSceneParameters); + ApplyInstanceElevationFromLevel(rvtInfo, state?.ArchiveSceneParameters); + ApplyStructuralColumnParams(rvtInfo, archiveParameters); + ApplyRoomLevelParams(rvtInfo, archiveParameters); + ApplyFramingSymbolLength(rvtInfo, archiveParameters); + if (state != null) ApplyMullionSymbolLength(rvtInfo.Elements, state.NativeParams, archiveParameters); + ApplyRoomBuildingTypeLoads(rvtInfo, archiveParameters); + ApplyHeadHeight(rvtInfo, archiveParameters); + ApplyStructuralConnectionParams(rvtInfo, archiveParameters); + ApplyCrossSectionRotation(rvtInfo, archiveParameters); + ApplyDetailCurveFlag(rvtInfo, state?.ElemClassIdx, archiveParameters); + passCompleted?.Invoke(); ApplyStoredPhases(rvtInfo, state?.ElemClassIdx, - state?.ProjectPhaseOrderSource is { BlockCount: 1, PhaseIds: { } phaseOrder } ? phaseOrder : null); + state?.ProjectPhaseOrderSource is { BlockCount: 1, PhaseIds: { } phaseOrder } ? phaseOrder : null, + state?.ArchiveSceneParameters); TraceElement(rvtInfo, "after-phases"); BuildSketchTopology(rvtInfo, state); // Runs LAST: needs WALL_BASE_CONSTRAINT / WALL_HEIGHT_TYPE emitted by the passes above. ApplyComputedHeights(rvtInfo, state); ApplyBipKeyedStrings(rvtInfo, state); - if (state != null) Revit2027ApiValues.Apply(rvtInfo, state, elemByIdLookup); + if (state != null) Revit2027ApiValues.Apply(rvtInfo, state, idToElem); ApplyWorksets(rvtInfo, state); TraceElement(rvtInfo, "before-fixphase"); - FixUnresolvedPhaseCreated(rvtInfo); + FixUnresolvedPhaseCreated(rvtInfo, state?.ArchiveSceneParameters); TraceElement(rvtInfo, "after-fixphase"); - FixWallStructuralUsage(rvtInfo); - FixWallBaseConstraint(rvtInfo); + FixWallStructuralUsage(rvtInfo, state?.ArchiveSceneParameters); + FixWallBaseConstraint(rvtInfo, state?.ArchiveSceneParameters); FixNodeConnectionStatus(rvtInfo, state); AddCategoryConstantParams(rvtInfo, state); // Wall centrelines the pattern scan missed: synthesize from face geometry (needs the width @@ -6547,17 +6665,17 @@ void ReportDistinctMissing(string label, Dictionary counts) if (state != null) { ApplyValidatedFloorTypeReferenceNames( - rvtInfo.Elements, elemByIdLookup, + rvtInfo.Elements, idToElem, state.FloorTypeNameSource, state.NativeParams, state); ApplyValidatedCeilingTypeReferenceNames( rvtInfo.Elements, state.CeilingTypeNameSource, state.NativeParams, state.ElemClassIdx); ApplyValidatedWindowTypeReferenceNames( - rvtInfo.Elements, elemByIdLookup, + rvtInfo.Elements, idToElem, state.NativeParams, state.ElementNameTable); ApplyValidatedProxyTypeReferenceNames( - rvtInfo.Elements, elemByIdLookup, + rvtInfo.Elements, idToElem, state.NativeParams, state.ElementNameTable); ApplyValidatedWallSweepTypeReferenceNames(rvtInfo.Elements, state); ApplyValidatedDistributionTypeReferenceNames(rvtInfo.Elements, state); @@ -6574,10 +6692,10 @@ void ReportDistinctMissing(string label, Dictionary counts) ApplyCurtainPanelOrders(rvtInfo.Elements, state); RepairBasicWallTypeFunctionBodyFallbacks(rvtInfo.Elements, state); } - foreach (var e in rvtInfo.Elements) + foreach (var e in ElementsWithParameterEdits(rvtInfo.Elements, state?.ArchiveSceneParameters)) { Parameter? lv = null; bool hasSched = false; - foreach (var p in e.Parameters) + foreach (var p in e.ReadParameters) { if (p.Id == -1001952) lv = p; else if (p.Id == -1002062) { hasSched = true; break; } @@ -6587,10 +6705,10 @@ void ReportDistinctMissing(string label, Dictionary counts) } // Curtain panel GENERIC_HEIGHT and CURTAIN_WALL_PANELS_HEIGHT are the same value; fill // whichever is missing from the other. - foreach (var e in rvtInfo.Elements) + foreach (var e in ElementsWithParameterEdits(rvtInfo.Elements, state?.ArchiveSceneParameters)) { Parameter? gen = null, pan = null; - foreach (var p in e.Parameters) + foreach (var p in e.ReadParameters) { if (p.Id == -1001300) gen = p; else if (p.Id == -1010300) pan = p; @@ -6610,7 +6728,7 @@ void ReportDistinctMissing(string label, Dictionary counts) // Same pair for the width: GENERIC_WIDTH equals CURTAIN_WALL_PANELS_WIDTH on every // element that has the panel width. Parameter? genWidth = null, panWidth = null; - foreach (var p in e.Parameters) + foreach (var p in e.ReadParameters) { if (p.Id == -1001301) genWidth = p; else if (p.Id == -1010301) panWidth = p; @@ -6657,6 +6775,7 @@ internal static void ApplyHeaderBoundingBoxes(RevitFileInfo rvtInfo, ParsingStat e.BoundingBox = box.Present ? box.Box : null; e.BoundingBoxIsHeaderOutline = box.Present; } + state.ReleaseSceneHeaderBoundingBoxes(); } /// The order key of the GInstance node the source geometry is the symbol of: the source's nodes then sort at that node's place among the nodes of the target (Revit walks a GInstance's symbol where the GInstance stands); null keeps the keys of the source as they are. @@ -6778,21 +6897,27 @@ face.AnalyticCylinderReferenceDirection is null /// sentinel (EnrichTypeLevelBips): curtain-wall sub-elements - mullions, panels, grid lines - /// plus ElemTable-covered instances that carry no phase reference in their block. /// - private static void FixUnresolvedPhaseCreated(RevitFileInfo info) + private static void FixUnresolvedPhaseCreated(RevitFileInfo info, Action? archiveParameters) { - var phaseVotes = new Dictionary(); - foreach (var e in info.Elements) - foreach (var p in e.Parameters) - if (p.Id == -1012100 && p.Value is int ph && ph > 0) - { phaseVotes.TryGetValue(ph, out int n); phaseVotes[ph] = n + 1; break; } - int domPhase = -1, domN = 0; - foreach (var (ph, n) in phaseVotes) if (n > domN) { domPhase = ph; domN = n; } + int domPhase = DominantCreatedPhase(info.Elements); if (domPhase <= 0) return; foreach (var e in info.Elements) - foreach (var p in e.Parameters) + { + int index = -1; + foreach (var p in e.ReadParameters) + { + index++; if (p.Id == -1012100 && p.Value is int pv && pv < 0) - { p.Value = domPhase; p.StorageType = StorageType.ElementId; break; } + { + var editable = e.Parameters[index]; + editable.Value = domPhase; + editable.StorageType = StorageType.ElementId; + archiveParameters?.Invoke(e); + break; + } + } + } } /// @@ -6800,18 +6925,26 @@ private static void FixUnresolvedPhaseCreated(RevitFileInfo info) /// (~always 1) - it is NOT the structural-usage enum. So derive WALL_STRUCTURAL_USAGE from the /// significant flag we already emit. /// - internal static void FixWallStructuralUsage(RevitFileInfo info) + internal static void FixWallStructuralUsage(RevitFileInfo info, Action? archiveParameters = null) { foreach (var e in info.Elements) { - int? sig = null; Parameter? usage = null; - foreach (var p in e.Parameters) + int? sig = null; + var parameters = e.ReadParameters; + int usageIndex = -1, index = -1; + foreach (var p in parameters) { + index++; if (p.Id == -1001596 && p.Value is int sv && (sv == 0 || sv == 1)) sig = sv; - else if (p.Id == -1001119) usage = p; + else if (p.Id == -1001119) usageIndex = index; + } + if (sig is int s && usageIndex >= 0 && parameters[usageIndex].Value is not > 1) + { + var usage = e.Parameters[usageIndex]; + usage.Value = s; + usage.StorageType = StorageType.Integer; + archiveParameters?.Invoke(e); } - if (sig is int s && usage != null && usage.Value is not > 1) - { usage.Value = s; usage.StorageType = StorageType.Integer; } } } @@ -6837,7 +6970,7 @@ private static void FixCategoryFromClassIdx(RevitFileInfo info, ParsingState? st else if (useHeader && e.NativeHeaderCategoryId is int header && header != -1) cat = header; else if (!state.ElemClassIdx.TryGetValue((uint)e.Id, out var cls) || !TfClassRegistry.HighPurityClassCategory.TryGetValue(cls, out cat)) continue; - if (e.CategoryId == cat && (e.Id != 0 || e.Parameters.Any(p => p.Id == -1140362))) continue; + if (e.CategoryId == cat && (e.Id != 0 || e.ReadParameters.Any(p => p.Id == -1140362))) continue; e.CategoryId = cat; if (nameByCat.TryGetValue(cat, out var nm) || BuiltInCategoryNames.Lookup.TryGetValue(cat, out nm)) e.Category = nm; var cp = e.Parameters.FirstOrDefault(p => p.Id == -1140362); @@ -6846,11 +6979,12 @@ private static void FixCategoryFromClassIdx(RevitFileInfo info, ParsingState? st var cpm = e.Parameters.FirstOrDefault(p => p.Id == -1140363); if (cpm != null) { cpm.Value = cat; cpm.StorageType = StorageType.ElementId; } else e.Parameters.Add(BipHelpers.MakeBipParam(-1140363, "ELEM_CATEGORY_PARAM_MT", StorageType.ElementId, cat)); + state.ArchiveSceneParameters?.Invoke(e); } } /// An instance's category equals its type's category. - private static void PropagateInstanceCategoryFromType(RevitFileInfo info) + private static void PropagateInstanceCategoryFromType(RevitFileInfo info, Action? archiveParameters) { var catById = new Dictionary(); foreach (var e in info.Elements) @@ -6872,6 +7006,7 @@ private static void PropagateInstanceCategoryFromType(RevitFileInfo info) var cpm = e.Parameters.FirstOrDefault(p => p.Id == -1140363); if (cpm != null) { cpm.Value = tc.cat; cpm.StorageType = StorageType.ElementId; } else e.Parameters.Add(BipHelpers.MakeBipParam(-1140363, "ELEM_CATEGORY_PARAM_MT", StorageType.ElementId, tc.cat)); + archiveParameters?.Invoke(e); added++; } if (added == 0) break; @@ -6891,13 +7026,13 @@ private static void ComputeSketchQuantities(RevitFileInfo info, ParsingState? st { if (e.CategoryId is not (-2000032 or -2000038 or -2000035)) continue; var sk = e.SketchLoops; - if (sk == null && e.References != null) - foreach (var r in e.References) + if (sk == null && e.ReadReferences != null) + foreach (var r in e.ReadReferences) if (byId.TryGetValue(r, out var re) && re.SketchLoops != null) { sk = re.SketchLoops; break; } if (sk == null || sk.Count == 0) { if (state is { StaleCopiesRemoved: true } - && e.References?.Any(r => r > 0 + && e.ReadReferences?.Any(r => r > 0 && state.WalkedElementClassRoots.GetValueOrDefault((uint)r) is { BlockCount: 1, ClassId: 4065 }) == true) ApplyUnsketchedFloorArea(e); continue; @@ -6930,9 +7065,9 @@ private static void ComputeSketchQuantities(RevitFileInfo info, ParsingState? st if (foot > 1e-6 && (net < 0.3 * foot || net > 1.05 * foot)) continue; } - if (e.Parameters.All(p => p.Id != -1012805)) + if (e.ReadParameters.All(p => p.Id != -1012805)) e.Parameters.Add(BipHelpers.MakeBipParam(-1012805, "HOST_AREA_COMPUTED", StorageType.Double, net)); - if (outerP > 0 && e.Parameters.All(p => p.Id != -1001953)) + if (outerP > 0 && e.ReadParameters.All(p => p.Id != -1001953)) e.Parameters.Add(BipHelpers.MakeBipParam(-1001953, "HOST_PERIMETER_COMPUTED", StorageType.Double, outerP)); // Volume = net x type thickness (sum of compound layers of the type). @@ -6940,7 +7075,7 @@ private static void ComputeSketchQuantities(RevitFileInfo info, ParsingState? st && state.CompoundLayers.TryGetValue((uint)e.TypeId, out var layers) && layers.Count > 0) { double thick = layers.Sum(l => l.ThicknessFt); - if (thick > 0 && e.Parameters.All(p => p.Id != -1012806)) + if (thick > 0 && e.ReadParameters.All(p => p.Id != -1012806)) e.Parameters.Add(BipHelpers.MakeBipParam(-1012806, "HOST_VOLUME_COMPUTED", StorageType.Double, net * thick)); } } @@ -6951,7 +7086,7 @@ internal static void ApplyUnsketchedFloorArea(Element floor) if (floor is not { CategoryId: -2000032, RootClassName: "Floor", SerializedSystemTypeId: > 0 } || floor.CuttingElementIds is { Count: > 0 } || floor.CutOutSteps?.Any(step => step.Cutout) == true - || floor.Parameters.Any(p => p.Id == -1012805) + || floor.ReadParameters.Any(p => p.Id == -1012805) || BrepMeasures.MeasuredPlanarPrism(floor.Geometry) is not ({ InnerPerimeter: 0 } prism, _)) return; floor.Parameters.Add(BipHelpers.MakeBipParam(-1012805, "HOST_AREA_COMPUTED", StorageType.Double, prism.ProfileArea)); @@ -6963,9 +7098,9 @@ internal static void ApplyCutFloorQuantities(Element floor) || BrepMeasures.MeasuredPlanarPrism(floor.Geometry) is not ({ InnerPerimeter: > 0 } prism, var volume)) return; // The closed body includes the inserted opening that the host sketch omits. - if (floor.Parameters.All(p => p.Id != -1012805)) + if (floor.ReadParameters.All(p => p.Id != -1012805)) floor.Parameters.Add(BipHelpers.MakeBipParam(-1012805, "HOST_AREA_COMPUTED", StorageType.Double, prism.ProfileArea)); - if (floor.Parameters.All(p => p.Id != -1012806)) + if (floor.ReadParameters.All(p => p.Id != -1012806)) floor.Parameters.Add(BipHelpers.MakeBipParam(-1012806, "HOST_VOLUME_COMPUTED", StorageType.Double, volume)); } @@ -6987,23 +7122,23 @@ internal static void ApplyCutFloorQuantities(Element floor) /// categories the user edited report the LOCAL USERNAME (they were borrowed on edit); /// annotation/view categories report empty. /// - private static void ApplyEditedByCategoryRules(RevitFileInfo info, ParsingState? state) + internal static void ApplyEditedByCategoryRules(RevitFileInfo info, ParsingState? state) { string? user = state?.LocalUsername; if (string.IsNullOrEmpty(user)) return; - foreach (var e in info.Elements) + foreach (var e in ElementsWithParameterEdits(info.Elements, state?.ArchiveSceneParameters)) { // Key the rule on the EMITTED category param (what the export/comparison sees), not // e.CategoryId - late passes assign CategoryId without updating the param, and those // are exactly the internal elements. int c = -1; - foreach (var p in e.Parameters) + foreach (var p in e.ReadParameters) if (p.Id == -1140362) { if (p.Value is int cv) c = cv; break; } if (c == -1) continue; string? val = EditedByUserCats.Contains(c) ? user : EditedByEmptyCats.Contains(c) ? "" : null; if (val == null) continue; - if (e.Parameters.All(p => p.Id != -1002067)) + if (e.ReadParameters.All(p => p.Id != -1002067)) e.Parameters.Add(BipHelpers.MakeBipParam(-1002067, "EDITED_BY", StorageType.String, val)); } } @@ -7012,7 +7147,7 @@ private static void ApplyEditedByCategoryRules(RevitFileInfo info, ParsingState? private static void ApplyCapturedCurveStyles(RevitFileInfo info, ParsingState? state) { if (state == null) return; - foreach (var e in info.Elements) + foreach (var e in ElementsWithParameterEdits(info.Elements, state.ArchiveSceneParameters)) { if (e.Id <= 0) continue; uint eid = (uint)e.Id; @@ -7020,12 +7155,12 @@ private static void ApplyCapturedCurveStyles(RevitFileInfo info, ParsingState? s if (state.DetailCurveStyles.TryGetValue(eid, out int d) && d > 0) sty = d; else if (state.CurveGeometry.TryGetValue(eid, out var g) && g.GStyle > 0) sty = g.GStyle; if (state.CurveGeometry.TryGetValue(eid, out var cgl) && cgl.Length > 1e-9 - && e.Parameters.All(p => p.Id != -1004005)) + && e.ReadParameters.All(p => p.Id != -1004005)) e.Parameters.Add(BipHelpers.MakeBipParam(-1004005, "CURVE_ELEM_LENGTH", StorageType.Double, cgl.Length)); if (sty <= 0) continue; - if (e.Parameters.All(p => p.Id != -1006210)) + if (e.ReadParameters.All(p => p.Id != -1006210)) e.Parameters.Add(BipHelpers.MakeBipParam(-1006210, "BUILDING_CURVE_GSTYLE", StorageType.ElementId, sty)); - if (e.Parameters.All(p => p.Id != -1006211)) + if (e.ReadParameters.All(p => p.Id != -1006211)) e.Parameters.Add(BipHelpers.MakeBipParam(-1006211, "BUILDING_CURVE_GSTYLE_PLUS_INVISIBLE", StorageType.ElementId, sty)); } } @@ -7038,10 +7173,10 @@ private static void AddCategoryConstantParams(RevitFileInfo info, ParsingState? var analyticalCats = new HashSet { -2009640, -2009641, -2009642, -2009643, -2009644, -2009646, -2009649 }; void AddIfMissing(Element e, int id, string name, int val) { - if (e.Parameters.All(p => p.Id != id)) + if (e.ReadParameters.All(p => p.Id != id)) e.Parameters.Add(BipHelpers.MakeBipParam(id, name, StorageType.Integer, val)); } - foreach (var e in info.Elements) + foreach (var e in ElementsWithParameterEdits(info.Elements, state?.ArchiveSceneParameters)) { bool curveOwner = state != null && e.Id > 0 && (state.CurveBlockOwners.Contains((uint)e.Id) || state.CurveGeometry.ContainsKey((uint)e.Id)); @@ -7060,13 +7195,13 @@ void AddIfMissing(Element e, int id, string name, int val) AddIfMissing(e, -1152343, "ANALYTICAL_MODEL_MANUALLY_ADJUSTED", 0); AddIfMissing(e, -1009523, "ANALYTICAL_MODEL_SKETCH_PROJECTION", -6); AddIfMissing(e, -1009522, "ANALYTICAL_MODEL_SKETCH_ALIGNMENT_METHOD", 0); - if (e.Parameters.All(p => p.Id != -1006008)) + if (e.ReadParameters.All(p => p.Id != -1006008)) e.Parameters.Add(BipHelpers.MakeBipParam(-1006008, "CURVE_HEIGHT_OFFSET", StorageType.Double, 0.0)); - if (e.Parameters.All(p => p.Id != -1006015)) + if (e.ReadParameters.All(p => p.Id != -1006015)) e.Parameters.Add(BipHelpers.MakeBipParam(-1006015, "CURVE_PARAM_STEEL_CANTILEVER", StorageType.Double, 0.0)); - if (e.Parameters.All(p => p.Id != -1006014)) + if (e.ReadParameters.All(p => p.Id != -1006014)) e.Parameters.Add(BipHelpers.MakeBipParam(-1006014, "CURVE_PARAM_CONCRETE_CANTILEVER", StorageType.Double, 0.0)); - if (e.Parameters.All(p => p.Id != -1006016)) + if (e.ReadParameters.All(p => p.Id != -1006016)) e.Parameters.Add(BipHelpers.MakeBipParam(-1006016, "ROOF_SLOPE", StorageType.Double, 1.0 / 12.0)); } continue; @@ -7083,7 +7218,7 @@ void AddIfMissing(Element e, int id, string name, int val) AddIfMissing(e, -1006441, "SPOT_ELEV_RELATIVE_BASE", -1); void AddStr(int id, string name) { - if (e.Parameters.All(p => p.Id != id)) + if (e.ReadParameters.All(p => p.Id != id)) e.Parameters.Add(BipHelpers.MakeBipParam(id, name, StorageType.String, "", hasNoRevitValue: true)); } AddStr(-1006479, "SPOT_ELEV_SINGLE_OR_UPPER_SUFFIX"); @@ -7100,7 +7235,7 @@ void AddStr(int id, string name) if (p.Id is -1002050 or -1002000 or -1002051 or -1002052) { p.Value = 1412; p.StorageType = StorageType.ElementId; } foreach (int pid in new[] { -1002050, -1002000, -1002051, -1002052 }) - if (e.Parameters.All(p => p.Id != pid)) + if (e.ReadParameters.All(p => p.Id != pid)) e.Parameters.Add(BipHelpers.MakeBipParam(pid, "", StorageType.ElementId, 1412)); e.TypeId = 1412; } @@ -7114,9 +7249,9 @@ void AddStr(int id, string name) AddIfMissing(e, -1001713, "RELATED_TO_MASS", 0); AddIfMissing(e, -1019100, "WALL_CROSS_SECTION", 1); AddIfMissing(e, -1001007, "WALL_ATTR_ROOM_BOUNDING", 1); - if (e.Parameters.All(p => p.Id != -1012828)) + if (e.ReadParameters.All(p => p.Id != -1012828)) e.Parameters.Add(BipHelpers.MakeBipParam(-1012828, "WALL_TOP_EXTENSION_DIST_PARAM", StorageType.Double, 0.0)); - if (e.Parameters.All(p => p.Id != -1012829)) + if (e.ReadParameters.All(p => p.Id != -1012829)) e.Parameters.Add(BipHelpers.MakeBipParam(-1012829, "WALL_BOTTOM_EXTENSION_DIST_PARAM", StorageType.Double, 0.0)); } else if (c == -2000032 || c == -2000035) @@ -7137,16 +7272,16 @@ private static void FixNodeConnectionStatus(RevitFileInfo info, ParsingState? st var incoming = new Dictionary(); foreach (var e in info.Elements) { - if (e.References == null) continue; - foreach (var r in e.References) + if (e.ReadReferences == null) continue; + foreach (var r in e.ReadReferences) { incoming.TryGetValue(r, out int c); incoming[r] = c + 1; } } foreach (var e in info.Elements) { if (e.CategoryId != -2009645 || e.Id <= 0) continue; if (!state.ElemClassIdx.TryGetValue((uint)e.Id, out var cls)) continue; - if (e.Parameters.Any(p => p.Id == -1001597)) continue; - int outd = e.References?.Count ?? 0; + if (e.ReadParameters.Any(p => p.Id == -1001597)) continue; + int outd = e.ReadReferences?.Count ?? 0; incoming.TryGetValue(e.Id, out int ind); int? status = null; if (cls == 0x0884) // Hub @@ -7174,13 +7309,7 @@ private static void CreateElemTablePlaceholders(RevitFileInfo info, ParsingState foreach (var e in info.Elements) existing.Add(e.Id); // Model dominant phase (same derivation as FixUnresolvedPhaseCreated) for PHASE_CREATED. - var phaseVotes = new Dictionary(); - foreach (var e in info.Elements) - foreach (var p in e.Parameters) - if (p.Id == -1012100 && p.Value is int ph && ph > 0) - { phaseVotes.TryGetValue(ph, out int n); phaseVotes[ph] = n + 1; break; } - int domPhase = -1, domN = 0; - foreach (var (ph, n) in phaseVotes) if (n > domN) { domPhase = ph; domN = n; } + int domPhase = DominantCreatedPhase(info.Elements); var src = new HashSet(state.ElemTable.Keys); foreach (var k in state.ElemWorksets.Keys) src.Add(k); @@ -7193,13 +7322,14 @@ private static void CreateElemTablePlaceholders(RevitFileInfo info, ParsingState el.Parameters.Add(BipHelpers.MakeBipParam(-1012101, "PHASE_DEMOLISHED", StorageType.ElementId, -1, hasNoRevitValue: true)); if (domPhase > 0) el.Parameters.Add(BipHelpers.MakeBipParam(-1012100, "PHASE_CREATED", StorageType.ElementId, domPhase)); + state.ArchiveSceneParameters?.Invoke(el); info.Elements.Add(el); } } - private static void FixWallBaseConstraint(RevitFileInfo info) + private static void FixWallBaseConstraint(RevitFileInfo info, Action? archiveParameters) { - foreach (var e in info.Elements) + foreach (var e in ElementsWithParameterEdits(info.Elements, archiveParameters)) { if (e.CategoryId != -2000011) continue; // OST_Walls int lvl = 0; Parameter? baseParam = null; @@ -7241,9 +7371,9 @@ private static void BuildSketchTopology(RevitFileInfo info, ParsingState? state) var ownerLines = new Dictionary>(); foreach (var e in info.Elements) { - if (e.References == null || sketchLineIds.Contains(e.Id)) continue; + if (e.ReadReferences == null || sketchLineIds.Contains(e.Id)) continue; HashSet? set = null; - foreach (var r in e.References) + foreach (var r in e.ReadReferences) if (sketchLineIds.Contains(r)) (set ??= new HashSet()).Add(r); if (set != null && set.Count >= 3) ownerLines[e.Id] = set; } @@ -7292,15 +7422,15 @@ private static void BuildSketchTopology(RevitFileInfo info, ParsingState? state) if (int.TryParse(Environment.GetEnvironmentVariable("RVTIO_DBG_SKETCH"), out int dbgEid) && dbgEid != 0) { byId.TryGetValue(dbgEid, out var de); - var refs = de?.References; + var refs = de?.ReadReferences; int inSketch = refs?.Count(r => sketchLineIds.Contains(r)) ?? -1; DiagnosticSink.WriteLine($" [sketch-dbg] {dbgEid}: found={de != null} refs={refs?.Count ?? -1} refsInSketchLines={inSketch} isOwner={ownerLines.ContainsKey(dbgEid)} loops={(de?.SketchLoops?.Count ?? 0)}"); if (refs != null) foreach (var r in refs.Take(12)) { byId.TryGetValue(r, out var re); - int r2 = re?.References?.Count(x => sketchLineIds.Contains(x)) ?? -1; - DiagnosticSink.WriteLine($" [sketch-dbg] ref {r}: cat={re?.CategoryId} ownRefs={re?.References?.Count ?? -1} refsInSketchLines={r2} isOwner={ownerLines.ContainsKey(r)}"); + int r2 = re?.ReadReferences?.Count(x => sketchLineIds.Contains(x)) ?? -1; + DiagnosticSink.WriteLine($" [sketch-dbg] ref {r}: cat={re?.CategoryId} ownRefs={re?.ReadReferences?.Count ?? -1} refsInSketchLines={r2} isOwner={ownerLines.ContainsKey(r)}"); } } } @@ -7451,14 +7581,14 @@ private static void PropagateFamilyElementIdParams(RevitFileInfo rvtInfo, Parsin } if (symToVals.Count == 0) return; - foreach (var e in rvtInfo.Elements) + foreach (var e in ElementsWithParameterEdits(rvtInfo.Elements, state.ArchiveSceneParameters)) { uint typeCandidate = e.TypeId > 0 ? (uint)e.TypeId : 0u; var candidates = new List(); - if (e.References != null) + if (e.ReadReferences != null) { var seen = new HashSet { typeCandidate }; - foreach (var rid in e.References) + foreach (var rid in e.ReadReferences) { if (rid <= 0 || rid == e.Id) continue; uint urid = (uint)rid; @@ -7496,11 +7626,15 @@ private static void CoerceParamStorageByForge(RevitFileInfo rvtInfo, ParsingStat { foreach (var e in rvtInfo.Elements) { - foreach (var p in e.Parameters) + int index = -1; + foreach (var original in e.ReadParameters) { - if (string.IsNullOrEmpty(p.ForgeId) && p.Id > 0 && state != null - && state.ForgeParamDefs.TryGetValue((uint)p.Id, out var def)) + index++; + var p = original; + if (string.IsNullOrEmpty(original.ForgeId) && original.Id > 0 && state != null + && state.ForgeParamDefs.TryGetValue((uint)original.Id, out var def)) { + p = e.Parameters[index]; p.ForgeId = def.ForgeId; if (string.IsNullOrEmpty(p.Definition?.Name) && !string.IsNullOrEmpty(def.DisplayName)) { @@ -7528,39 +7662,43 @@ private static void CoerceParamStorageByForge(RevitFileInfo rvtInfo, ParsingStat || (p.Value is int piv && piv == -1); if (isStringSpec && p.StorageType != StorageType.String) { + p = e.Parameters[index]; p.StorageType = StorageType.String; p.Value = ""; if (wasNoRevitValue) p.HasNoRevitValue = true; } else if (isBoolSpec && p.StorageType != StorageType.Integer) { + p = e.Parameters[index]; p.StorageType = StorageType.Integer; p.Value = 0; if (wasNoRevitValue) p.HasNoRevitValue = true; } else if (isNumericSpec && p.StorageType == StorageType.String) { + p = e.Parameters[index]; p.StorageType = StorageType.Double; p.Value = 0.0; if (wasNoRevitValue) p.HasNoRevitValue = true; } } + state?.ArchiveSceneParameters?.Invoke(e); } } private static void PropagateFamilySymbolBlockDoubles(RevitFileInfo rvtInfo, ParsingState? state) { if (state == null || state.FamilySymbolBlockDoubles.Count == 0) return; - foreach (var e in rvtInfo.Elements) + foreach (var e in ElementsWithParameterEdits(rvtInfo.Elements, state.ArchiveSceneParameters)) { // Iterate ALL candidate symbol blocks for this element (TypeId + shadow refs). Shadow // blocks are visited AFTER the type so instance-specific values override type defaults. var typeCandidate = e.TypeId > 0 ? (uint)e.TypeId : 0u; var shadowCandidates = new List(); - if (e.References != null) + if (e.ReadReferences != null) { var seen = new HashSet { typeCandidate }; - foreach (var rid in e.References) + foreach (var rid in e.ReadReferences) { if (rid <= 0 || rid == e.Id) continue; uint urid = (uint)rid; @@ -7633,16 +7771,16 @@ private static void PropagateFamilySymbolBlockDoubles(RevitFileInfo rvtInfo, Par private static void PropagateFamilySymbolBlockInts(RevitFileInfo rvtInfo, ParsingState? state) { if (state == null || state.FamilySymbolBlockInts.Count == 0) return; - foreach (var e in rvtInfo.Elements) + foreach (var e in ElementsWithParameterEdits(rvtInfo.Elements, state.ArchiveSceneParameters)) { uint typeCandidate = e.TypeId > 0 ? (uint)e.TypeId : 0u; var candidates = new List(); if (typeCandidate != 0 && state.FamilySymbolBlockInts.ContainsKey(typeCandidate)) candidates.Add(typeCandidate); - if (e.References != null) + if (e.ReadReferences != null) { var seen = new HashSet { typeCandidate }; - foreach (var rid in e.References) + foreach (var rid in e.ReadReferences) { if (rid <= 0 || rid == e.Id) continue; uint urid = (uint)rid; @@ -7680,16 +7818,16 @@ private static void PropagateFamilySymbolBlockInts(RevitFileInfo rvtInfo, Parsin private static void PropagateFamilySymbolBlockStrings(RevitFileInfo rvtInfo, ParsingState? state) { if (state == null || state.FamilySymbolBlockStrings.Count == 0) return; - foreach (var e in rvtInfo.Elements) + foreach (var e in ElementsWithParameterEdits(rvtInfo.Elements, state.ArchiveSceneParameters)) { var candidates = new List(); uint typeCandidate = e.TypeId > 0 ? (uint)e.TypeId : 0u; if (typeCandidate != 0 && state.FamilySymbolBlockStrings.ContainsKey(typeCandidate)) candidates.Add(typeCandidate); - if (e.References != null) + if (e.ReadReferences != null) { var seen = new HashSet { typeCandidate }; - foreach (var rid in e.References) + foreach (var rid in e.ReadReferences) { if (rid <= 0 || rid == e.Id) continue; uint urid = (uint)rid; @@ -7765,12 +7903,12 @@ private static void PropagateTypeElementIdParams(RevitFileInfo rvtInfo, ParsingS { if (state == null) return; var elemById = rvtInfo.Elements.ToDictionary(e => e.Id); - foreach (var e in rvtInfo.Elements) + foreach (var e in ElementsWithParameterEdits(rvtInfo.Elements, state.ArchiveSceneParameters)) { if (e.TypeId <= 0 || !elemById.TryGetValue(e.TypeId, out var typeElem)) continue; - if (typeElem.References == null) continue; - var existing = new HashSet(e.Parameters.Select(p => p.Id)); - foreach (var defId in typeElem.References) + if (typeElem.ReadReferences == null) continue; + var existing = new HashSet(e.ReadParameters.Select(p => p.Id)); + foreach (var defId in typeElem.ReadReferences) { if (defId <= 0 || existing.Contains(defId) || !state.IsParameterElement((uint)defId)) continue; if (!elemById.TryGetValue(defId, out var defElem)) continue; @@ -7980,6 +8118,32 @@ private struct RefScan public int FirstLevelId; } + private static readonly (Parameter.DefinitionTemplate Definition, StorageType Type, object Value, bool ReadOnly)[] CommonBipDefaults = + [ + CommonBipDefault(-1010103, "ALL_MODEL_DESCRIPTION", StorageType.String, ""), + CommonBipDefault(-1010104, "ALL_MODEL_URL", StorageType.String, ""), + CommonBipDefault(-1010105, "ALL_MODEL_TYPE_COMMENTS", StorageType.String, ""), + CommonBipDefault(-1010106, "ALL_MODEL_INSTANCE_COMMENTS", StorageType.String, ""), + CommonBipDefault(-1010108, "ALL_MODEL_MANUFACTURER", StorageType.String, ""), + CommonBipDefault(-1010109, "ALL_MODEL_MODEL", StorageType.String, ""), + CommonBipDefault(-1001203, "ALL_MODEL_MARK", StorageType.String, ""), + CommonBipDefault(-1140422, "KEYNOTE_PARAM", StorageType.String, ""), + CommonBipDefault(-1002500, "UNIFORMAT_CODE", StorageType.String, ""), + CommonBipDefault(-1002501, "UNIFORMAT_DESCRIPTION", StorageType.String, ""), + CommonBipDefault(-1002502, "OMNICLASS_CODE", StorageType.String, ""), + CommonBipDefault(-1002503, "OMNICLASS_DESCRIPTION", StorageType.String, ""), + CommonBipDefault(-1152384, "ALL_MODEL_TYPE_IMAGE", StorageType.ElementId, -1), + CommonBipDefault(-1002002, "ALL_MODEL_FAMILY_NAME", StorageType.String, ""), + CommonBipDefault(-1002001, "SYMBOL_NAME_PARAM", StorageType.String, ""), + CommonBipDefault(-1001405, "WINDOW_TYPE_ID", StorageType.String, ""), + CommonBipDefault(-1001206, "FIRE_RATING", StorageType.String, ""), + CommonBipDefault(-1005556, "STRUCTURAL_FAMILY_CODE_NAME", StorageType.String, ""), + CommonBipDefault(-1001205, "ALL_MODEL_COST", StorageType.Double, 0.0), + ]; + + private static (Parameter.DefinitionTemplate Definition, StorageType Type, object Value, bool ReadOnly) CommonBipDefault( + int id, string name, StorageType type, object value) => (new(id, name), type, value, BipHelpers.IsBipReadOnly(name)); + private static void EnrichTypeLevelBips(RevitFileInfo rvtInfo, ParsingState? state) { if (state == null) return; @@ -7988,13 +8152,26 @@ private static void EnrichTypeLevelBips(RevitFileInfo rvtInfo, ParsingState? sta // Per-instance: scan refs + type's refs together to find type-level params. IEnumerable CollectRefs(Element e) { - if (e.TypeId > 0 && elemById.TryGetValue(e.TypeId, out var t) && t.References != null) - foreach (var r in t.References) yield return r; - if (e.References != null) foreach (var r in e.References) yield return r; + if (e.TypeId > 0 && elemById.TryGetValue(e.TypeId, out var t) && t.ReadReferences != null) + foreach (var r in t.ReadReferences) yield return r; + if (e.ReadReferences != null) foreach (var r in e.ReadReferences) yield return r; } var typePhases = new Dictionary(); - var typeRefSets = new Dictionary>(); + var referencedByOwnType = new HashSet(); var typeScans = new Dictionary<(int TypeId, bool IsWall), RefScan>(); + var levelElevations = new Dictionary(); + var present = new HashSet(); + + double? LevelElevation(int levelId) + { + if (levelElevations.TryGetValue(levelId, out var elevation)) return elevation; + // This pass derives offsets and leaves stored level elevations alone. + elevation = elemById.GetValueOrDefault(levelId)?.ReadParameters + .FirstOrDefault(parameter => parameter.Id == -1007102)?.Value as double?; + levelElevations.Add(levelId, elevation); + return elevation; + } + void Accumulate(ref RefScan scan, int rid, int ownerId, bool isWall) { if (rid == ownerId || rid <= 0) return; @@ -8021,21 +8198,24 @@ void Accumulate(ref RefScan scan, int rid, int ownerId, bool isWall) RefScan ScanRefs(Element e, bool isWall) { var scan = new RefScan { FirstLevelId = -1 }; - if (e.TypeId > 0 && elemById.TryGetValue(e.TypeId, out var t) && t.References != null) + if (e.TypeId > 0 && elemById.TryGetValue(e.TypeId, out var t) && t.ReadReferences != null) { if (!typeScans.TryGetValue((e.TypeId, isWall), out var typeScan)) { typeScan = new RefScan { FirstLevelId = -1 }; - foreach (var r in t.References) Accumulate(ref typeScan, r, int.MinValue, isWall); + foreach (var r in t.ReadReferences) + { + Accumulate(ref typeScan, r, int.MinValue, isWall); + // Only an instance referenced by its own type needs a scan that skips itself. + if (elemById.TryGetValue(r, out var instance) && instance.TypeId == e.TypeId) + referencedByOwnType.Add(r); + } typeScans[(e.TypeId, isWall)] = typeScan; } - // A type reference equal to the instance's own id is skipped in the full scan. - if (!typeRefSets.TryGetValue(e.TypeId, out var typeRefSet)) - typeRefSets[e.TypeId] = typeRefSet = new HashSet(t.References); - if (typeRefSet.Contains(e.Id)) typeScan = RescanSkipping(t.References, e.Id, isWall); + if (referencedByOwnType.Contains(e.Id)) typeScan = RescanSkipping(t.ReadReferences, e.Id, isWall); scan = typeScan; } - if (e.References != null) foreach (var r in e.References) Accumulate(ref scan, r, e.Id, isWall); + if (e.ReadReferences != null) foreach (var r in e.ReadReferences) Accumulate(ref scan, r, e.Id, isWall); return scan; } RefScan RescanSkipping(IEnumerable refs, int skipId, bool isWall) @@ -8047,7 +8227,7 @@ RefScan RescanSkipping(IEnumerable refs, int skipId, bool isWall) void EnsureBip(Element e, int id, string name, StorageType st, object value, bool isApproximate = false, bool hasNoRevitValue = false) { - if (e.Parameters.Any(p => p.Id == id)) return; + if (e.ReadParameters.Any(p => p.Id == id)) return; var parameter = BipHelpers.MakeBipParam(id, name, st, value, hasNoRevitValue: hasNoRevitValue); parameter.IsApproximate = isApproximate; e.Parameters.Add(parameter); @@ -8147,7 +8327,7 @@ void EnsureBipOrFixNull(Element e, int id, string name, StorageType st, int valu // STRUCTURAL_ANALYTICAL_MODEL (-1001552): walls default to 1 when structural // significant var samParam = e.Parameters.FirstOrDefault(p => p.Id == -1001552); - bool isStructural = e.Parameters.Any(p => p.Id == -1001596 && p.Value is int i && i == 1); + bool isStructural = e.ReadParameters.Any(p => p.Id == -1001596 && p.Value is int i && i == 1); if (samParam == null) EnsureBip(e, -1001552, "STRUCTURAL_ANALYTICAL_MODEL", StorageType.Integer, isStructural ? 1 : 0); else if (samParam.Value is int iv && iv == 0 && isStructural) samParam.Value = 1; @@ -8176,19 +8356,19 @@ void EnsureBipOrFixNull(Element e, int id, string name, StorageType st, int valu // PHASE_CREATED / PHASE_DEMOLISHED: phase IDs from references (OST_Phases = -2000112) int? phaseCreatedId = null; - if (e.TypeId > 0 && elemById.TryGetValue(e.TypeId, out var phaseType) && phaseType.References != null) + if (e.TypeId > 0 && elemById.TryGetValue(e.TypeId, out var phaseType) && phaseType.ReadReferences != null) { if (!typePhases.TryGetValue(e.TypeId, out var typePhase)) { typePhase = null; - foreach (var rid in phaseType.References) + foreach (var rid in phaseType.ReadReferences) if (elemById.TryGetValue(rid, out var refElem) && refElem.CategoryId == -2000112) { typePhase = rid; break; } typePhases[e.TypeId] = typePhase; } phaseCreatedId = typePhase; } - if (phaseCreatedId == null && e.References != null) - foreach (var rid in e.References) + if (phaseCreatedId == null && e.ReadReferences != null) + foreach (var rid in e.ReadReferences) if (elemById.TryGetValue(rid, out var refElem) && refElem.CategoryId == -2000112) { phaseCreatedId = rid; break; } if (phaseCreatedId.HasValue) EnsureBipOrFixNull(e, -1012100, "PHASE_CREATED", StorageType.ElementId, phaseCreatedId.Value, -2000112); @@ -8213,9 +8393,7 @@ void EnsureBipOrFixNull(Element e, int id, string name, StorageType st, int valu // INSTANCE_ELEVATION_PARAM: instance elevation relative to its level. bbox.MinZ - // level.elev. (LEVEL_ELEV is propagated through ElemBipDoubles as BIP -1007102.) // Override existing -1 sentinel. - if (GeometryBox(e) is { Length: 6 } && firstLevelId > 0 - && elemById.TryGetValue(firstLevelId, out var lvlEl) - && lvlEl.Parameters.FirstOrDefault(p => p.Id == -1007102)?.Value is double lvlElev) + if (GeometryBox(e) is { Length: 6 } && firstLevelId > 0 && LevelElevation(firstLevelId) is double lvlElev) { // Only when the level's elevation actually resolved - assuming 0 for an unresolved // level produced garbage elevations (= raw bbox z). @@ -8248,12 +8426,7 @@ void EnsureBipOrFixNull(Element e, int id, string name, StorageType st, int valu // (extracted in BlockParser) is authoritative. if (e.Transform?.Origin is { Length: 3 } org) { - double lvlElev2 = 0; - if (firstLevelId > 0 && elemById.TryGetValue(firstLevelId, out var lvlForSill)) - { - var lp2 = lvlForSill.Parameters.FirstOrDefault(p => p.Id == -1007102); - if (lp2?.Value is double lv2) lvlElev2 = lv2; - } + double lvlElev2 = firstLevelId > 0 ? LevelElevation(firstLevelId) ?? 0 : 0; double computedSill = Math.Round(org[2] - lvlElev2, 12); var sillExisting = e.Parameters.FirstOrDefault(p => p.Id == -1001361); if (sillExisting == null) @@ -8262,60 +8435,35 @@ void EnsureBipOrFixNull(Element e, int id, string name, StorageType st, int valu sillExisting.Value = computedSill; // free instance: stored value is a 0 placeholder } - // Wall- and instance-common ANALYTICAL_* BIPs propagated from the structural material. - // For walls, ANALYTICAL_THERMAL_RESISTANCE = thickness / - // ANALYTICAL_HEAT_TRANSFER_COEFFICIENT. - if (materialId.HasValue && elemById.TryGetValue(materialId.Value, out var matElem)) + // Legacy thermal estimates for walls with a structural material. + if (isWall && materialId is int structuralMaterial && elemById.ContainsKey(structuralMaterial)) { - // Propagate well-known material doubles to instance as ANALYTICAL_* BIPs. Most - // materials have these as PHY_MATERIAL_PARAM_* via reference propagation; we just - // copy them here under the canonical ANALYTICAL_* names. - double? thermalMass = null, thickness = null; - foreach (var mp in matElem.Parameters) - { - if (mp.Value is not double mv) continue; - if (mp.Id == -1140309) thermalMass = mv * 1e6; // unit weight scaled - approximation - } - if (isWall) - { - var widthP = e.Parameters.FirstOrDefault(p => p.Id == -1001000); - if (widthP?.Value is double w) thickness = w; - } - // Legacy thermal estimates: retain their values for compatibility, but do not label - // them as exact own RVT parameters. - if (isWall) - { - EnsureBip(e, -1005430, "ANALYTICAL_HEAT_TRANSFER_COEFFICIENT", StorageType.Double, 3.4866666666666668, isApproximate: true); - EnsureBip(e, -1005436, "ANALYTICAL_ROUGHNESS", StorageType.Integer, 3, isApproximate: true); - EnsureBip(e, -1005435, "ANALYTICAL_ABSORPTANCE", StorageType.Double, 0.7, isApproximate: true); - EnsureBip(e, -1005434, "ANALYTICAL_THERMAL_MASS", StorageType.Double, 453330.0, isApproximate: true); - if (thickness.HasValue) - EnsureBip(e, -1005431, "ANALYTICAL_THERMAL_RESISTANCE", StorageType.Double, - thickness.Value / 3.4866666666666668, isApproximate: true); - } + EnsureBip(e, -1005430, "ANALYTICAL_HEAT_TRANSFER_COEFFICIENT", StorageType.Double, 3.4866666666666668, isApproximate: true); + EnsureBip(e, -1005436, "ANALYTICAL_ROUGHNESS", StorageType.Integer, 3, isApproximate: true); + EnsureBip(e, -1005435, "ANALYTICAL_ABSORPTANCE", StorageType.Double, 0.7, isApproximate: true); + EnsureBip(e, -1005434, "ANALYTICAL_THERMAL_MASS", StorageType.Double, 453330.0, isApproximate: true); + if (e.ReadParameters.FirstOrDefault(parameter => parameter.Id == -1001000)?.Value is double thickness) + EnsureBip(e, -1005431, "ANALYTICAL_THERMAL_RESISTANCE", StorageType.Double, + thickness / 3.4866666666666668, isApproximate: true); } - // Common string/scalar defaults Revit always returns. Unset String params read back - // from Revit as an empty string "" (has_value=true), NOT a -1 sentinel. - EnsureBip(e, -1010103, "ALL_MODEL_DESCRIPTION", StorageType.String, "", hasNoRevitValue: true); - EnsureBip(e, -1010104, "ALL_MODEL_URL", StorageType.String, "", hasNoRevitValue: true); - EnsureBip(e, -1010105, "ALL_MODEL_TYPE_COMMENTS", StorageType.String, "", hasNoRevitValue: true); - EnsureBip(e, -1010106, "ALL_MODEL_INSTANCE_COMMENTS", StorageType.String, "", hasNoRevitValue: true); - EnsureBip(e, -1010108, "ALL_MODEL_MANUFACTURER", StorageType.String, "", hasNoRevitValue: true); - EnsureBip(e, -1010109, "ALL_MODEL_MODEL", StorageType.String, "", hasNoRevitValue: true); - EnsureBip(e, -1001203, "ALL_MODEL_MARK", StorageType.String, "", hasNoRevitValue: true); - EnsureBip(e, -1140422, "KEYNOTE_PARAM", StorageType.String, "", hasNoRevitValue: true); - EnsureBip(e, -1002500, "UNIFORMAT_CODE", StorageType.String, "", hasNoRevitValue: true); - EnsureBip(e, -1002501, "UNIFORMAT_DESCRIPTION", StorageType.String, "", hasNoRevitValue: true); - EnsureBip(e, -1002502, "OMNICLASS_CODE", StorageType.String, "", hasNoRevitValue: true); - EnsureBip(e, -1002503, "OMNICLASS_DESCRIPTION", StorageType.String, "", hasNoRevitValue: true); - EnsureBip(e, -1152384, "ALL_MODEL_TYPE_IMAGE", StorageType.ElementId, -1, hasNoRevitValue: true); - EnsureBip(e, -1002002, "ALL_MODEL_FAMILY_NAME", StorageType.String, "", hasNoRevitValue: true); - EnsureBip(e, -1002001, "SYMBOL_NAME_PARAM", StorageType.String, "", hasNoRevitValue: true); - EnsureBip(e, -1001405, "WINDOW_TYPE_ID", StorageType.String, "", hasNoRevitValue: true); - EnsureBip(e, -1001206, "FIRE_RATING", StorageType.String, "", hasNoRevitValue: true); - EnsureBip(e, -1005556, "STRUCTURAL_FAMILY_CODE_NAME", StorageType.String, "", hasNoRevitValue: true); - EnsureBip(e, -1001205, "ALL_MODEL_COST", StorageType.Double, 0.0, hasNoRevitValue: true); // (a.k.a. legacy DOOR_COST) + // Each slot remains available to the later passes that fill in stored values. + // The scene only needs its mutable definition when a pass or the adapter reads it. + present.Clear(); + foreach (var parameter in e.Parameters) present.Add(parameter.Id); + foreach (var (definition, storage, value, isReadOnly) in CommonBipDefaults) + { + if (present.Contains(definition.Id)) continue; + var parameter = state.KeepExportProvenance + ? BipHelpers.MakeBipParam(definition.Id, definition.Name, storage, value, hasNoRevitValue: true) + : new Parameter(definition) + { + Id = definition.Id, StorageType = storage, Value = value, + IsReadOnly = isReadOnly, HasNoRevitValue = true, + }; + e.Parameters.Add(parameter); + } + state.ArchiveSceneParameters?.Invoke(e); } } @@ -8328,7 +8476,7 @@ private static void PropagateChainPlaceholders(RevitFileInfo rvtInfo, ParsingSta { if (state == null || state.FamilyParamMaps.Count == 0) return; var elemById = rvtInfo.Elements.ToDictionary(e => e.Id); - foreach (var e in rvtInfo.Elements) + foreach (var e in ElementsWithParameterEdits(rvtInfo.Elements, state.ArchiveSceneParameters)) { if (e.TypeId <= 0 || !state.FamilyParamMaps.TryGetValue((uint)e.TypeId, out var map)) continue; @@ -8449,9 +8597,9 @@ private static void ComputeWallSolids(List elements) double wallLength = wallAlongX ? dx : dy; double wallWidth = wallAlongX ? dy : dx; - foreach (var p in elem.Parameters) + foreach (var p in elem.ReadParameters) { - if (p.Definition?.Name == "WALL_ATTR_WIDTH_PARAM" + if (p.DefinitionName == "WALL_ATTR_WIDTH_PARAM" && p.StorageType == StorageType.Double && p.Value is double wFt) { if (wFt > 0.001 && wFt < wallLength) @@ -8470,12 +8618,12 @@ private static void ComputeWallSolids(List elements) // Universal approach: extract direction and position from world-coordinate faces. The // GRep block with world-coordinate faces has XVectors that show the actual wall // direction in world space (not axis-aligned). - if (elem.Geometry?.Faces != null) + if (elem.Geometry?.ReadFaces != null) { GeoFace? bestFace = null; double bestArea = 0; - foreach (var face in elem.Geometry.Faces) + foreach (var face in elem.Geometry.ReadFaces) { if (Math.Abs(face.Normal[2]) > 0.5) continue; if (face.Envelope == null || face.Envelope.Length < 4) continue; @@ -8557,7 +8705,7 @@ private static void ComputeWallSolids(List elements) // center, we need to find where the face center maps to in world. GeoFace? largestFace = null; double largestArea = 0; - foreach (var face in elem.Geometry.Faces) + foreach (var face in elem.Geometry.ReadFaces) { if (Math.Abs(face.Normal[2]) > 0.5) continue; if (face.Envelope == null) continue; @@ -8616,10 +8764,10 @@ private static void ComputeWallSolids(List elements) ExtrusionHeight = dz, }; - if (elem.Geometry?.Faces != null) + if (elem.Geometry?.ReadFaces != null) { var openings = new List(); - foreach (var face in elem.Geometry.Faces) + foreach (var face in elem.Geometry.ReadFaces) { if (face.InnerVertices == null || face.InnerVertices.Count == 0) continue; @@ -8719,27 +8867,23 @@ private static void AddBodyBipParams(Element elem, ElementRecord rec, uint elemI foreach (var b in rec.BipParams) { if (b.BipId == 0 || !seenIds.Add(b.BipId)) continue; - var param = new Parameter - { - Id = b.BipId, - StorageType = b.BipId < 0 ? BipHelpers.BipStorageType(b.BipName) : StorageType.None, - }; + var param = b.BipId < 0 + ? BipHelpers.MakeBipParam(b.BipId, b.BipName, BipHelpers.BipStorageType(b.BipName), null) + : new Parameter { Id = b.BipId, StorageType = StorageType.None }; if (b.BipId < 0) { - param.Definition = new Definition { Id = b.BipId, BuiltInParameter = b.BipName, Name = b.BipName }; - param.IsReadOnly = BipHelpers.IsBipReadOnly(b.BipName); bool resolvedStored = false; if (param.StorageType == StorageType.Double - && state.ElemBipDoubles.TryGetValue(elemId, out var bipDoubleVals) + && state.TryReadBipDoubles(elemId, out var bipDoubleVals) && bipDoubleVals.TryGetValue(b.BipId, out double dv)) { param.Value = dv; resolvedStored = true; } else if ((param.StorageType == StorageType.ElementId || param.StorageType == StorageType.Integer) - && state.ElemBipInts.TryGetValue(elemId, out var bipIntVals) + && state.TryReadBipInts(elemId, out var bipIntVals) && bipIntVals.TryGetValue(b.BipId, out int iv)) { param.Value = iv; resolvedStored = true; } else if (param.StorageType == StorageType.None - && state.ElemBipDoubles.TryGetValue(elemId, out var bipDblFallback) + && state.TryReadBipDoubles(elemId, out var bipDblFallback) && bipDblFallback.TryGetValue(b.BipId, out double dvFallback)) { param.StorageType = StorageType.Double; @@ -8754,7 +8898,7 @@ private static void AddBodyBipParams(Element elem, ElementRecord rec, uint elemI foreach (var refId in rec.References) { if (refId == elemId) continue; - if (state.ElemBipDoubles.TryGetValue(refId, out var refBipDbls) + if (state.TryReadBipDoubles(refId, out var refBipDbls) && refBipDbls.TryGetValue(b.BipId, out double refDv)) { if (param.StorageType == StorageType.None) param.StorageType = StorageType.Double; @@ -8770,7 +8914,7 @@ private static void AddBodyBipParams(Element elem, ElementRecord rec, uint elemI foreach (var refId in rec.References) { if (refId == elemId) continue; - if (state.ElemBipInts.TryGetValue(refId, out var refBipInts) + if (state.TryReadBipInts(refId, out var refBipInts) && refBipInts.TryGetValue(b.BipId, out int refIv)) { param.Value = refIv; @@ -8801,11 +8945,11 @@ private static void AddBodyBipParams(Element elem, ElementRecord rec, uint elemI param.ForgeId = forgeId; param.Guid = paramGuid; param.Definition = new Definition { Id = b.BipId, Name = displayName }; - param.IsReadOnly = !rec.WritableParamIds.Contains(b.BipId); - if (state.ElemBipDoubles.TryGetValue(elemId, out var userDblVals) + param.IsReadOnly = !rec.IsWritable(b.BipId); + if (state.TryReadBipDoubles(elemId, out var userDblVals) && userDblVals.TryGetValue(b.BipId, out double userDbl)) { param.StorageType = StorageType.Double; param.Value = userDbl; } - else if (state.ElemParamStrings.TryGetValue(elemId, out var paramStrMap) + else if (state.TryReadParamStrings(elemId, out var paramStrMap) && paramStrMap.TryGetValue((uint)b.BipId, out string? strVal)) { param.StorageType = StorageType.String; param.Value = strVal; } else @@ -8821,7 +8965,7 @@ private static void AddBodyBipParams(Element elem, ElementRecord rec, uint elemI private static void AddUserParams(Element elem, ElementRecord rec, uint elemId, ParsingState state) { - if (!state.ElemParamStrings.TryGetValue(elemId, out var paramStrMap)) return; + if (!state.TryReadParamStrings(elemId, out var paramStrMap)) return; var existingIds = new HashSet(elem.Parameters.Select(p => p.Id)); foreach (var (paramDefId, strVal) in paramStrMap) { @@ -8839,7 +8983,7 @@ private static void AddUserParams(Element elem, ElementRecord rec, uint elemId, Id = (int)paramDefId, StorageType = StorageType.String, Value = strVal, - IsReadOnly = !rec.WritableParamIds.Contains((int)paramDefId), + IsReadOnly = !rec.IsWritable((int)paramDefId), ForgeId = forgeId, Guid = paramGuid, Definition = new Definition { Id = (int)paramDefId, Name = displayName }, @@ -8849,7 +8993,7 @@ private static void AddUserParams(Element elem, ElementRecord rec, uint elemId, private static void AddBipDoubles(Element elem, uint elemId, ParsingState state) { - if (!state.ElemBipDoubles.TryGetValue(elemId, out var bipDblMap)) return; + if (!state.TryReadBipDoubles(elemId, out var bipDblMap)) return; var existing = new HashSet(elem.Parameters.Select(p => p.Id)); foreach (var (bipKey, bipVal) in bipDblMap) { @@ -8857,12 +9001,7 @@ private static void AddBipDoubles(Element elem, uint elemId, ParsingState state) if (bipKey < 0) { BipNames.Lookup.TryGetValue(bipKey, out string? bipName); - elem.Parameters.Add(new Parameter - { - Id = bipKey, StorageType = StorageType.Double, Value = bipVal, - IsReadOnly = BipHelpers.IsBipReadOnly(bipName), - Definition = new Definition { Id = bipKey, BuiltInParameter = bipName, Name = bipName }, - }); + elem.Parameters.Add(BipHelpers.MakeBipParam(bipKey, bipName, StorageType.Double, bipVal)); } else { @@ -8886,7 +9025,7 @@ private static void AddBipDoubles(Element elem, uint elemId, ParsingState state) private static void AddBipInts(Element elem, uint elemId, ParsingState state) { - if (!state.ElemBipInts.TryGetValue(elemId, out var bipIntMap)) return; + if (!state.TryReadBipInts(elemId, out var bipIntMap)) return; var existing = new HashSet(elem.Parameters.Select(p => p.Id)); foreach (var (bipKey, bipVal) in bipIntMap) { @@ -8894,12 +9033,7 @@ private static void AddBipInts(Element elem, uint elemId, ParsingState state) if (bipKey < 0) { BipNames.Lookup.TryGetValue(bipKey, out string? bipName); - elem.Parameters.Add(new Parameter - { - Id = bipKey, StorageType = BipHelpers.BipStorageType(bipName), Value = bipVal, - IsReadOnly = BipHelpers.IsBipReadOnly(bipName), - Definition = new Definition { Id = bipKey, BuiltInParameter = bipName, Name = bipName }, - }); + elem.Parameters.Add(BipHelpers.MakeBipParam(bipKey, bipName, BipHelpers.BipStorageType(bipName), bipVal)); } else { @@ -8929,7 +9063,7 @@ private static void AddPropagatedBipDoubles(Element elem, uint elemId, ParsingSt foreach (var refId in rec.References) { if (refId == elemId) continue; - if (!state.ElemBipDoubles.TryGetValue(refId, out var refBipDbls)) continue; + if (!state.TryReadBipDoubles(refId, out var refBipDbls)) continue; foreach (var (bipKey, bipVal) in refBipDbls) { if (existing.Contains(bipKey)) continue; @@ -8937,12 +9071,7 @@ private static void AddPropagatedBipDoubles(Element elem, uint elemId, ParsingSt if (bipKey < 0) { BipNames.Lookup.TryGetValue(bipKey, out string? bipName); - elem.Parameters.Add(new Parameter - { - Id = bipKey, StorageType = StorageType.Double, Value = bipVal, - IsReadOnly = BipHelpers.IsBipReadOnly(bipName), - Definition = new Definition { Id = bipKey, BuiltInParameter = bipName, Name = bipName }, - }); + elem.Parameters.Add(BipHelpers.MakeBipParam(bipKey, bipName, StorageType.Double, bipVal)); } else { @@ -9031,7 +9160,7 @@ private static void BuildLocationFromTailLine(Element elem, uint elemId, Parsing // Walls only, and only when the wall has extracted face geometry: synthesize the centreline // from the LARGEST VERTICAL face (world coords): direction = the face's in-plane axis, // extent = outer vertices projected on it. - if (elem.CategoryId != -2000011 || elem.Geometry?.Faces is not { Count: > 0 } faces) return; + if (elem.CategoryId != -2000011 || elem.Geometry?.ReadFaces is not { Count: > 0 } faces) return; double widFt = 0; foreach (var p in elem.Parameters) diff --git a/src/RvtIO/Parsing/ElementExportIds.cs b/src/RvtIO/Parsing/ElementExportIds.cs index 720a7903..c59f9cbe 100644 --- a/src/RvtIO/Parsing/ElementExportIds.cs +++ b/src/RvtIO/Parsing/ElementExportIds.cs @@ -91,6 +91,9 @@ private static bool SchemaDeclaresElemRecLayout() internal static string UniqueId(Guid episode, ulong originalElementId) => $"{episode:D}-{originalElementId:x8}"; + internal static string UniqueIdFromExportId(Guid exportId, ulong originalElementId) => + UniqueId(XorTail(exportId, originalElementId), originalElementId); + /// /// The export-id rule: the episode GUID with the original element id XORed into its last 64 bits. /// diff --git a/src/RvtIO/Parsing/ElementHeaderCategory.cs b/src/RvtIO/Parsing/ElementHeaderCategory.cs index 8df77f1e..e7818a95 100644 --- a/src/RvtIO/Parsing/ElementHeaderCategory.cs +++ b/src/RvtIO/Parsing/ElementHeaderCategory.cs @@ -26,6 +26,7 @@ internal static class ElementHeaderCategory // releases into it), whose class tags are those of the embedded format schema. private static readonly Lazy OutlineTag = new(() => (ushort)TagOfShippedSchema("Outline")); private static readonly Lazy ParentsTag = new(() => (ushort)TagOfShippedSchema("ElementParents")); + private static readonly ElementHeaderBox AbsentOutline = new(false, null); private static int TagOfShippedSchema(string name) { @@ -107,7 +108,7 @@ private static int TagOfShippedSchema(string name) return null; at += 6; - if (!present) return new ElementHeaderBox(false, null); + if (!present) return AbsentOutline; if (at + OutlineLength > recordEnd) return null; var box = new double[6]; for (int d = 0; d < 6; d++) box[d] = BitConverter.ToDouble(buffer, (int)at + sizeof(double) * d); diff --git a/src/RvtIO/Parsing/GRepParserV2.cs b/src/RvtIO/Parsing/GRepParserV2.cs index a580d5df..3404ee8d 100644 --- a/src/RvtIO/Parsing/GRepParserV2.cs +++ b/src/RvtIO/Parsing/GRepParserV2.cs @@ -176,9 +176,35 @@ public double[] Weld(double[] point) public Dictionary FaceHasFirstLoop = new(); public HashSet LastLoops = new(); - public int U32() { if (Pos + 4 > End) throw Stop; int v = BitConverter.ToInt32(D, Pos); Pos += 4; return v; } - public double F64() { if (Pos + 8 > End) throw Stop; double v = BitConverter.ToDouble(D, Pos); Pos += 8; return v; } - public void Take(int n) { if (Pos + n > End) throw Stop; Pos += n; } + public int U32() => TryU32(out int value) ? value : throw Stop; + + public bool TryU32(out int value) + { + value = 0; + if (End - Pos < sizeof(int)) return false; + value = BitConverter.ToInt32(D, Pos); + Pos += sizeof(int); + return true; + } + public double F64() => TryF64(out double value) ? value : throw Stop; + + public bool TryF64(out double value) + { + value = 0; + if (End - Pos < sizeof(double)) return false; + value = BitConverter.ToDouble(D, Pos); + Pos += sizeof(double); + return true; + } + + public void Take(int n) { if (!TryTake(n)) throw Stop; } + + public bool TryTake(int n) + { + if (n > End - Pos) return false; + Pos += n; + return true; + } public bool CanRead(int n) => Pos + n <= End; } @@ -1263,13 +1289,18 @@ bool TryReadCount(out uint count) } private static void WalkQueueItem(Cur c, int qi) + { + if (!TryWalkQueueItem(c, qi)) throw Stop; + } + + private static bool TryWalkQueueItem(Cur c, int qi) { var (cls, v) = c.Queue[qi]; c.CurrentQueueIndex = qi; c.CurrentObjectHandle = v; c.CurrentObjectClass = cls; var qf = TfBlockDeserializer.SerializationFields(cls); - if (qf == null) throw Stop; + if (qf == null) return false; // Blob-headed items: refresh the class's tag base (tag = base + ordinal). if (qf.Count > 0 && qf[0].Name == "m_GInfo" && c.CanRead(16)) { @@ -1317,6 +1348,10 @@ private static void WalkQueueItem(Cur c, int qi) { // Layout: [Envelope 4xf64 uv][orient u8] then Plane: [O,X,Y] (105 total) / // CylSurf|ConeSurf: [O,X,Y,Z][R] (137). + // Check the length first: a block replayed from scratch is an exact-size buffer, so the + // envelope reads below must not run past it before the guard can raise Stop. + int need = cls == 522 ? 105 : 137; + if (!c.CanRead(need)) throw Stop; var env = new double[4]; for (int k = 0; k < 4; k++) env[k] = BitConverter.ToDouble(c.D, c.Pos + 8 * k); int fp = c.Pos + 33; @@ -1325,8 +1360,6 @@ private static void WalkQueueItem(Cur c, int qi) Kind = cls == 522 ? SurfKind.Plane : cls == 983 ? SurfKind.Cylinder : SurfKind.Cone, Env = env, Orient = c.D[c.Pos + 32], }; - int need = cls == 522 ? 105 : 137; - if (!c.CanRead(need)) throw Stop; for (int k = 0; k < 3; k++) { sr.O[k] = BitConverter.ToDouble(c.D, fp + 8 * k); @@ -1517,7 +1550,7 @@ double[] ReadParameters() HermiteNodes = new List(), }; uint count = BitConverter.ToUInt32(c.D, c.Pos + 33); - if (count == 0xFFFFFFFF) { c.Take(37); return; } + if (count == 0xFFFFFFFF) { c.Take(37); return true; } if (count > 1_000_000 || !c.CanRead(37 + 56 * (int)count)) throw Stop; int nodePos = c.Pos + 37; bool valid = true; @@ -1658,8 +1691,10 @@ double[] ReadParameters() } else { - foreach (var sf in qf) ReadField(c, sf, 1); + foreach (var sf in qf) + if (!TryReadField(c, sf, 1)) return false; } + return true; } /// @@ -1894,7 +1929,11 @@ bool DryRun(int off, int qj) c.Pos = off; bool ok = true; int want = Math.Min(10, c.Queue.Count - qj); - try { for (int k = 0; k < want; k++) WalkQueueItem(c, qj + k); } + try + { + for (int k = 0; k < want; k++) + if (!TryWalkQueueItem(c, qj + k)) { ok = false; break; } + } catch (DecodeStop) { ok = false; } // Roll the dry run back - the caller's loop re-walks for real. c.Pos = snap.Pos; @@ -1968,6 +2007,13 @@ bool DryRun(int off, int qj) private static void ReadField(Cur c, TfBlockDeserializer.TfField f, int depth) + { + if (!TryReadField(c, f, depth)) throw Stop; + } + + // Resync tests many false candidates. Reject malformed headers and array counts without an exception + // while advancing the real walk to the same failing byte as the ordinary scalar reads. + private static bool TryReadField(Cur c, TfBlockDeserializer.TfField f, int depth) { if (depth > 48) throw Stop; @@ -1975,14 +2021,12 @@ private static void ReadField(Cur c, TfBlockDeserializer.TfField f, int depth) { // GInfo is a declared four-field value object, not opaque padding: tag, control // command, category ElementId, flags. - int tag = c.U32(); - int control = c.U32(); - int categoryId = c.U32(); - uint flags = (uint)c.U32(); - if (categoryId < -3_000_000) throw Stop; + if (!c.TryU32(out int tag) || !c.TryU32(out int control) || !c.TryU32(out int categoryId) + || !c.TryU32(out int rawFlags) || categoryId < -3_000_000) return false; + uint flags = (uint)rawFlags; if (c.CurrentObjectHandle != 0) c.ObjectGInfo[c.CurrentObjectHandle] = (tag, control, categoryId, flags); - return; + return true; } // GRep.m_bBox / m_tightbBox are two inline XYZ points. Capture them only on the root @@ -1999,22 +2043,22 @@ private static void ReadField(Cur c, TfBlockDeserializer.TfField f, int depth) if (f.Name == "m_tightbBox") c.RootTightBoundingBox = box; else c.RootBoundingBox = box; } - return; + return true; } // Surface(523).m_Envelope has NO ref in the schema but is serialized INLINE as Envelope = 2 // uv corners x 16 bytes = 32. - if (f.Name == "m_Envelope" && f.Declaring == 523) { c.Take(32); return; } + if (f.Name == "m_Envelope" && f.Declaring == 523) { c.Take(32); return true; } // FamilyDB serializes these POD entries as int[2], as in the exact Tf reader. if (c.RootClass == 1829 && f is { Declaring: 1829, Name: "m_dummyHostInsertionFaceTags", Type: 13, Mods: 80, Ref: null, Cnt: null }) { uint count = (uint)c.U32(); - if (count == uint.MaxValue) return; + if (count == uint.MaxValue) return true; if (count > 1_000_000 || count > (c.End - c.Pos) / 8) throw Stop; c.Take((int)count * 8); - return; + return true; } if (c.RootClass == 1829 && f is { Declaring: 1763, Name: "second", Type: 14, Mods: 0, Ref: 1763 }) { @@ -2026,59 +2070,59 @@ private static void ReadField(Cur c, TfBlockDeserializer.TfField f, int depth) // FamilySymbol's embedded complex-cut BRep reaches the geometry walker through // FamSymHandleMgr. - if (f.Declaring == 140 && f.Name == "m_foreignElemIdRef") { c.Take(4); return; } + if (f.Declaring == 140 && f.Name == "m_foreignElemIdRef") { c.Take(4); return true; } if (f.Declaring == 1729 && f.Name == "m_handleMap") { uint count = (uint)c.U32(); - if (count == 0xFFFFFFFF) return; + if (count == 0xFFFFFFFF) return true; if (count > 100_000) throw Stop; var fields = TfBlockDeserializer.SerializationFields(1730) ?? throw Stop; for (uint index = 0; index < count; index++) foreach (var field in fields) ReadField(c, field, depth + 1); - return; + return true; } if (f.Declaring == 1730 && f.Name == "second") { var fields = TfBlockDeserializer.SerializationFields(1727) ?? throw Stop; foreach (var field in fields) ReadField(c, field, depth + 1); - return; + return true; } - if (f.Declaring == 1758 && f.Name == "m_flags") { c.Take(3); return; } - if (f.Declaring == 322 && f.Name == "second") { c.Take(4); return; } + if (f.Declaring == 1758 && f.Name == "m_flags") { c.Take(3); return true; } + if (f.Declaring == 322 && f.Name == "second") { c.Take(4); return true; } if (f.Declaring == 714 && f.Name == "m_params") { ReadInlineContainer(c, 715, depth); - return; + return true; } if (f.Declaring == 714 && f.Name == "m_geomRefHandles") { ReadInlineStruct(c, 716, depth); - return; + return true; } if (f.Declaring == 716 && f.Name == "m_offsetGeomMap") { ReadInlineContainer(c, 717, depth); - return; + return true; } if (f.Declaring == 496 && f.Name == "m_PatternPositionMap") { ReadInlineContainer(c, 497, depth); - return; + return true; } if (f.Declaring == 496 && f.Name == "m_substituteFaceMap") { ReadInlineContainer(c, 498, depth); - return; + return true; } if (f.Declaring == 497 && f.Name == "second") { ReadInlineStruct(c, 78, depth); - return; + return true; } if (f.Declaring == 498 && f.Name == "second") { ReadInlineStruct(c, 91, depth); - return; + return true; } // GHermiteSpline stores its nodes inline. One node is a 3D point, a 3D tangent and a curve @@ -2086,11 +2130,12 @@ private static void ReadField(Cur c, TfBlockDeserializer.TfField f, int depth) // does not carry an item-class reference. if (f.Declaring == 2020 && f.Name == "m_NodeArray") { - uint n = (uint)c.U32(); - if (n == 0xFFFFFFFF) return; - if (n > 1_000_000) throw Stop; + if (!c.TryU32(out int count)) return false; + uint n = (uint)count; + if (n == 0xFFFFFFFF) return true; + if (n > 1_000_000) return false; c.Take(56 * (int)n); - return; + return true; } // GeomGenerator history entries have class-declared fixed widths: FaceHistEntry=16, @@ -2099,7 +2144,7 @@ private static void ReadField(Cur c, TfBlockDeserializer.TfField f, int depth) or "m_edgeHistTable" or "m_edgeHistTableReverse") { uint n = (uint)c.U32(); - if (n == 0xFFFFFFFF) return; + if (n == 0xFFFFFFFF) return true; if (n > 100000) throw Stop; int recordSize = f.Name switch { @@ -2108,7 +2153,7 @@ private static void ReadField(Cur c, TfBlockDeserializer.TfField f, int depth) _ => 20, }; c.Take(recordSize * (int)n); - return; + return true; } // Exact spatial fallback also needs the sentinel's own face/first/last/open contract, not // only the back-references found on adjacent Edge objects. @@ -2126,31 +2171,31 @@ private static void ReadField(Cur c, TfBlockDeserializer.TfField f, int depth) if (!c.CanRead(1)) throw Stop; loop.Open = c.D[c.Pos++]; break; } - return; + return true; } // Edge back-references to its two adjacent faces (2xu32 fixed array). if (f.Name == "m_pFace" && c.CapEdge != null) { uint a = (uint)c.U32(), b = (uint)c.U32(); c.CapEdge.FaceA = a; c.CapEdge.FaceB = b; - return; + return true; } if (f.Name == "m_next" && c.CapEdge != null) { c.CapEdge.NextA = (uint)c.U32(); c.CapEdge.NextB = (uint)c.U32(); - return; + return true; } if (f.Name == "m_prev" && c.CapEdge != null) { c.CapEdge.PrevA = (uint)c.U32(); c.CapEdge.PrevB = (uint)c.U32(); - return; + return true; } if (f.Name == "m_interiorEdgePnts") { uint n = (uint)c.U32(); - if (n == 0xFFFFFFFF) return; + if (n == 0xFFFFFFFF) return true; if (n > 100000) throw Stop; // Each EdgePnt contains the UV coordinates in both adjacent faces. Every sample is part // of the serialized trim polyline; dropping them collapses a closed circular edge to a @@ -2160,39 +2205,42 @@ private static void ReadField(Cur c, TfBlockDeserializer.TfField f, int depth) var point = ReadUV(c); c.CapEdge?.Interior.Add(point); } - return; + return true; } if (f.Name == "m_firstAndLastEdgePnts") { var s = ReadUV(c); var e = ReadUV(c); if (c.CapEdge != null) { c.CapEdge.Start = s; c.CapEdge.EndP = e; c.CapEdge.HasEndpoints = true; } - return; + return true; } if (f.Name == "m_flags" && c.CapEdge != null) { if (!c.CanRead(1)) throw Stop; c.CapEdge.Flags = c.D[c.Pos++]; - return; + return true; } int hi = f.Mods >> 4; - if (hi == 6) { ReadString(c); return; } + if (hi == 6) return TryReadString(c); if (hi == 1) { int n = f.Cnt ?? 0; - for (int i = 0; i < n; i++) ReadScalar(c, f, depth); - return; + for (int i = 0; i < n; i++) + if (!TryReadScalar(c, f, depth)) return false; + return true; } if (hi == 5) { - uint n = (uint)c.U32(); - if (n == 0xFFFFFFFF) return; - if (n > 1_000_000) throw Stop; - for (uint i = 0; i < n; i++) ReadScalar(c, f, depth); - return; + if (!c.TryU32(out int count)) return false; + uint n = (uint)count; + if (n == 0xFFFFFFFF) return true; + if (n > 1_000_000) return false; + for (uint i = 0; i < n; i++) + if (!TryReadScalar(c, f, depth)) return false; + return true; } - ReadScalar(c, f, depth); + return TryReadScalar(c, f, depth); } private static void ReadInlineContainer(Cur c, int classId, int depth) @@ -2210,13 +2258,13 @@ private static void ReadInlineStruct(Cur c, int classId, int depth) foreach (var field in fields) ReadField(c, field, depth + 1); } - private static void ReadScalar(Cur c, TfBlockDeserializer.TfField f, int depth) + private static bool TryReadScalar(Cur c, TfBlockDeserializer.TfField f, int depth) { switch (f.Type) { case 0x01: case 0x02: case 0x03: { - if (!c.CanRead(1)) throw Stop; + if (!c.CanRead(1)) return false; byte value = c.D[c.Pos++]; bool captureConditionCut = c.CurrentObjectClass is 1995 or 1996 && f.Name == "m_negateDirCondition"; @@ -2230,11 +2278,11 @@ private static void ReadScalar(Cur c, TfBlockDeserializer.TfField f, int depth) values[f.Name] = fieldValues = new(); fieldValues.Add(value); } - return; + return true; } case 0x04: { - int value = c.U32(); + if (!c.TryU32(out int value)) return false; bool captureModelCondition = c.CurrentObjectClass is 1999 or 2002; if (c.CurrentQueueIndex >= 0 && ((c.Debug && c.CurrentObjectClass is >= 1992 and <= 2015) @@ -2244,12 +2292,12 @@ private static void ReadScalar(Cur c, TfBlockDeserializer.TfField f, int depth) c.QueueInts[c.CurrentQueueIndex] = values = new(); values[f.Name] = value; } - return; + return true; } - case 0x05: case 0x06: c.Take(4); return; + case 0x05: case 0x06: return c.TryTake(4); case 0x07: { - double value = c.F64(); + if (!c.TryF64(out double value)) return false; if (c.Debug && c.CurrentQueueIndex >= 0 && c.CurrentObjectClass is >= 1992 and <= 2003) { if (!c.QueueDoubles.TryGetValue(c.CurrentQueueIndex, out var values)) @@ -2258,19 +2306,19 @@ private static void ReadScalar(Cur c, TfBlockDeserializer.TfField f, int depth) values[f.Name] = fieldValues = new(); fieldValues.Add(value); } - return; + return true; } - case 0x0A: c.Take(8); return; - case 0x08: ReadString(c); return; - case 0x09: c.Take(16); return; + case 0x0A: return c.TryTake(8); + case 0x08: return TryReadString(c); + case 0x09: return c.TryTake(16); // POD array item: ref 524(Envelope)/1248(EdgePnt) = 2xf64 UV (16b); else 3xf64 point // (24b). field already loops cnt times for fixed arrays (hi==1). - case 0x0D: c.Take((f.Mods >> 4) == 1 ? (f.Ref is 524 or 1248 ? 16 : 24) : 8 * (f.Cnt ?? 3)); return; + case 0x0D: return c.TryTake((f.Mods >> 4) == 1 ? (f.Ref is 524 or 1248 ? 16 : 24) : 8 * (f.Cnt ?? 3)); case 0x0E: { int lo = f.Mods & 0x0F; - if (lo == 3) { c.Take(4); return; } - if (lo is 1 or 2) { ReadPtr(c, f.Name); return; } + if (lo == 3) return c.TryTake(4); + if (lo is 1 or 2) return TryReadPtr(c, f.Name); if (f.Ref == 20) { // GPolyMesh.m_materialID: the material of the mesh (the mesh has no faces to @@ -2281,53 +2329,49 @@ private static void ReadScalar(Cur c, TfBlockDeserializer.TfField f, int depth) c.QueueInts[c.CurrentQueueIndex] = meshValues = new(); meshValues[f.Name] = BitConverter.ToInt32(c.D, c.Pos); } - c.Take(4); - return; + return c.TryTake(4); } if (f.Ref.HasValue) { - var sub = TfBlockDeserializer.SerializationFields(f.Ref.Value) ?? throw Stop; - foreach (var sf in sub) ReadField(c, sf, depth + 1); - return; + var sub = TfBlockDeserializer.SerializationFields(f.Ref.Value); + if (sub == null) return false; + foreach (var sf in sub) + if (!TryReadField(c, sf, depth + 1)) return false; + return true; } - ReadPoly(c, f.Name); - return; + return TryReadPoly(c, f.Name); } - default: throw Stop; + default: return false; } } - private static void ReadString(Cur c) + private static bool TryReadString(Cur c) { - uint n = (uint)c.U32(); - if (n > 100000) throw Stop; - c.Take(2 * (int)n); + return c.TryU32(out int count) && (uint)count <= 100000 && c.TryTake(2 * count); } - private static void ReadPtr(Cur c, string? field = null) + private static bool TryReadPtr(Cur c, string field) { - int v = c.U32(); + if (!c.TryU32(out int v)) return false; if (field == "m_pFirstLoop" && c.CurrentObjectClass == 1589) c.FaceHasFirstLoop[(uint)c.CurrentObjectHandle] = v != 0; else if (field == "m_nextLoop" && v == 0 && c.CurrentObjectClass is 1254 or 1257 && c.CurrentQueueIndex >= 0) c.LastLoops.Add(c.CurrentQueueIndex); - if (v == 0) return; - if (!c.CanRead(2)) throw Stop; - ushort cls = BitConverter.ToUInt16(c.D, c.Pos); c.Pos += 2; - if (cls == 4) { ReadGInfoTail(c); return; } - if (!TfBlockDeserializer.Schemas.ContainsKey(cls)) throw Stop; - Enqueue(c, cls, v, field ?? ""); + if (v == 0) return true; + return TryReadReference(c, v, field); } - private static void ReadPoly(Cur c, string field) + private static bool TryReadPoly(Cur c, string field) + => c.TryU32(out int v) && (v != -1 || TryReadReference(c, v, field)); + + private static bool TryReadReference(Cur c, int handle, string field) { - uint v = (uint)c.U32(); - if (v == 0 || v != 0xFFFFFFFF) return; // null or plain handle - if (!c.CanRead(2)) throw Stop; + if (!c.CanRead(2)) return false; ushort cls = BitConverter.ToUInt16(c.D, c.Pos); c.Pos += 2; - if (cls == 4) { ReadGInfoTail(c); return; } - if (!TfBlockDeserializer.Schemas.ContainsKey(cls)) throw Stop; - Enqueue(c, cls, (int)v, field); + if (cls == 4) return TryReadGInfoTail(c); + if (!TfBlockDeserializer.Schemas.ContainsKey(cls)) return false; + Enqueue(c, cls, handle, field); + return true; } private static void Enqueue(Cur c, ushort cls, int handle, string field) @@ -2343,15 +2387,13 @@ private static void Enqueue(Cur c, ushort cls, int handle, string field) } } - private static void ReadGInfoTail(Cur c) + private static bool TryReadGInfoTail(Cur c) { - if (!c.CanRead(2)) throw Stop; + if (!c.CanRead(2)) return false; ushort tk = BitConverter.ToUInt16(c.D, c.Pos); c.Pos += 2; - if ((tk & 0xFF) != 8) throw Stop; + if ((tk & 0xFF) != 8) return false; int kind = tk >> 8; - if (kind == 0) return; - if (kind == 1) { c.Take(6 * 8 + 2 * 4); return; } - throw Stop; + return kind == 0 || kind == 1 && c.TryTake(6 * 8 + 2 * 4); } private static EdgeUV ReadUV(Cur c) diff --git a/src/RvtIO/Parsing/GeometryFaceStore.cs b/src/RvtIO/Parsing/GeometryFaceStore.cs new file mode 100644 index 00000000..3693b5f8 --- /dev/null +++ b/src/RvtIO/Parsing/GeometryFaceStore.cs @@ -0,0 +1,258 @@ +using System.Collections; +using System.Runtime.InteropServices; +using RvtIO.Internal; +using RvtIO.Model; + +namespace RvtIO.Parsing; + +/// Stores the expanded face lists of a scene read in the caller's geometry scratch stream. +internal sealed class GeometryFaceStore(PartitionChunks.Backing storage) +{ + private const int PageBytes = 64 * 1024; + private readonly MemoryStream output = new(PageBytes); + private readonly object pageLock = new(); + private Page? cachedPage; + private GeoFace[]? cachedFaces; + + internal void Archive(Element element) + { + ArchiveBody(element.Geometry); + ArchiveBody(element.SerializedComputedSymbolGeometry); + } + + private void ArchiveBody(GeometryData? body) + { + if (body == null) return; + body.ArchiveFaces(Store); + body.KeepSceneMeshNodeFacts(); + } + + private IReadOnlyList Store(List faces) + { + using var writer = new BinaryWriter(output, System.Text.Encoding.UTF8, leaveOpen: true); + var pages = new List(); + int first = 0; + for (int i = 0; i < faces.Count; i++) + { + WriteFace(writer, faces[i]); + if (output.Length < PageBytes && i + 1 < faces.Count) continue; + var block = storage.Add(output.GetBuffer().AsSpan(0, checked((int)output.Length))); + pages.Add(new Page(first, i + 1, block)); + first = i + 1; + output.SetLength(0); + if (output.Capacity > 2 * PageBytes) output.Capacity = PageBytes; + } + return new FaceList(this, pages.ToArray(), faces.Count); + } + + private GeoFace[] ReadPage(Page page) + { + lock (pageLock) + { + if (ReferenceEquals(cachedPage, page)) return cachedFaces!; + using var reader = new BinaryReader(new MemoryStream(storage.Read(page.Block), writable: false)); + var faces = new GeoFace[page.End - page.First]; + for (int i = 0; i < faces.Length; i++) faces[i] = ReadFace(reader); + if (page.Block.Length <= 2 * PageBytes) + { + cachedPage = page; + cachedFaces = faces; + } + return faces; + } + } + + private sealed record Page(int First, int End, PartitionChunks.Chunk Block); + + private sealed class FaceList(GeometryFaceStore store, Page[] pages, int count) : IReadOnlyList + { + public int Count => count; + public GeoFace this[int index] + { + get + { + if ((uint)index >= (uint)Count) throw new ArgumentOutOfRangeException(nameof(index)); + int lo = 0, hi = pages.Length - 1; + while (lo < hi) + { + int mid = lo + (hi - lo) / 2; + if (index < pages[mid].End) hi = mid; + else lo = mid + 1; + } + return store.ReadPage(pages[lo])[index - pages[lo].First]; + } + } + + public IEnumerator GetEnumerator() + { + foreach (var page in pages) + foreach (var face in store.ReadPage(page)) + yield return face; + } + + IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); + } + + private static void WriteFace(BinaryWriter writer, GeoFace face) + { + WriteOptional(writer, face.RenderStyleId, static (output, value) => output.Write(value)); + WriteArray(writer, face.Origin); + WriteArray(writer, face.XVector); + WriteArray(writer, face.YVector); + WriteArray(writer, face.Normal); + WriteArray(writer, face.Envelope); + WriteOptional(writer, face.Area, static (output, value) => output.Write(value)); + WriteRing(writer, face.InnerLoops); + WriteRing(writer, face.OuterVertices); + WriteRings(writer, face.InnerVertices); + WriteRing(writer, face.AlternativeOuterVertices); + WriteArray(writer, face.AnalyticCylinderOrigin); + WriteArray(writer, face.AnalyticCylinderAxis); + WriteArray(writer, face.AnalyticCylinderReferenceDirection); + writer.Write(face.AnalyticCylinderRadius); + WriteArray(writer, face.MeshEdgeBounds); + WriteArray(writer, face.MeshPlaneEnvelopeCorners); + WriteArcs(writer, face.MeshArcs); + WriteOptional(writer, face.QuadratureArea, static (output, value) => output.Write(value)); + writer.Write(face.CurvedSurface); + writer.Write(face.PlaneSurface); + WriteArray(writer, face.PlaneXAxis); + WriteArray(writer, face.PlaneYAxis); + writer.Write(face.SourceFace); + writer.Write(face.MeshMarker); + WriteRing(writer, face.FirstSourceLoop); + WriteRings(writer, face.SourceLoops); + writer.Write(face.GeometryNode); + writer.Write(face.NodeOrder); + writer.Write(face.GeometryStyle); + WriteOptional(writer, face.GInfoFlags, static (output, value) => output.Write(value)); + WriteOptional(writer, face.NestedRenderStyleId, static (output, value) => output.Write(value)); + WriteArray(writer, face.EdgeIndices); + } + + private static GeoFace ReadFace(BinaryReader reader) + { + int? renderStyleId = ReadOptional(reader, static input => input.ReadInt32()); + return new(ReadArray(reader)!, ReadArray(reader)!, ReadArray(reader)!, ReadArray(reader)!) + { + RenderStyleId = renderStyleId, + Envelope = ReadArray(reader), + Area = ReadOptional(reader, static input => input.ReadDouble()), + InnerLoops = ReadRing(reader), + OuterVertices = ReadRing(reader), + InnerVertices = ReadRings(reader), + AlternativeOuterVertices = ReadRing(reader), + AnalyticCylinderOrigin = ReadArray(reader), + AnalyticCylinderAxis = ReadArray(reader), + AnalyticCylinderReferenceDirection = ReadArray(reader), + AnalyticCylinderRadius = reader.ReadDouble(), + MeshEdgeBounds = ReadArray(reader), + MeshPlaneEnvelopeCorners = ReadArray(reader), + MeshArcs = ReadArcs(reader), + QuadratureArea = ReadOptional(reader, static input => input.ReadDouble()), + CurvedSurface = reader.ReadBoolean(), + PlaneSurface = reader.ReadBoolean(), + PlaneXAxis = ReadArray(reader), + PlaneYAxis = ReadArray(reader), + SourceFace = reader.ReadUInt32(), + MeshMarker = reader.ReadUInt32(), + FirstSourceLoop = ReadRing(reader), + SourceLoops = ReadRings(reader), + GeometryNode = reader.ReadInt32(), + NodeOrder = reader.ReadInt64(), + GeometryStyle = reader.ReadInt32(), + GInfoFlags = ReadOptional(reader, static input => input.ReadUInt32()), + NestedRenderStyleId = ReadOptional(reader, static input => input.ReadInt32()), + EdgeIndices = ReadArray(reader)?.ToList(), + }; + } + + private static void WriteOptional(BinaryWriter writer, T? value, Action write) where T : struct + { + writer.Write(value.HasValue); + if (value is T item) write(writer, item); + } + + private static T? ReadOptional(BinaryReader reader, Func read) where T : struct => + reader.ReadBoolean() ? read(reader) : null; + + private static void WriteArray(BinaryWriter writer, T[]? values) where T : unmanaged + { + writer.Write(values?.Length ?? -1); + if (values != null) writer.Write(MemoryMarshal.AsBytes(values.AsSpan())); + } + + private static T[]? ReadArray(BinaryReader reader) where T : unmanaged + { + int count = reader.ReadInt32(); + if (count == -1) return null; + var values = new T[count]; + reader.BaseStream.ReadExactly(MemoryMarshal.AsBytes(values.AsSpan())); + return values; + } + + private static void WriteRing(BinaryWriter writer, IReadOnlyList? ring) + { + writer.Write(ring?.Count ?? -1); + if (ring != null) + foreach (var point in ring) WriteArray(writer, point); + } + + private static List? ReadRing(BinaryReader reader) + { + int count = reader.ReadInt32(); + if (count == -1) return null; + var points = new List(count); + for (int i = 0; i < count; i++) points.Add(ReadArray(reader)!); + return points; + } + + private static void WriteRings(BinaryWriter writer, IReadOnlyList>? rings) + { + writer.Write(rings?.Count ?? -1); + if (rings != null) + foreach (var ring in rings) WriteRing(writer, ring); + } + + private static List>? ReadRings(BinaryReader reader) + { + int count = reader.ReadInt32(); + if (count == -1) return null; + var rings = new List>(count); + for (int i = 0; i < count; i++) rings.Add(ReadRing(reader)!); + return rings; + } + + private static void WriteArcs(BinaryWriter writer, IReadOnlyList? arcs) + { + writer.Write(arcs?.Count ?? -1); + if (arcs == null) return; + foreach (var arc in arcs) + { + WriteArray(writer, arc.Centre); + WriteArray(writer, arc.X); + WriteArray(writer, arc.Y); + writer.Write(arc.Radius); + writer.Write(arc.First); + writer.Write(arc.Last); + writer.Write(arc.Edge); + } + } + + private static List? ReadArcs(BinaryReader reader) + { + int count = reader.ReadInt32(); + if (count == -1) return null; + var arcs = new List(count); + for (int i = 0; i < count; i++) + arcs.Add(new Arc(ReadArray(reader)!, ReadArray(reader)!, ReadArray(reader)!, + reader.ReadDouble(), reader.ReadDouble(), reader.ReadDouble(), reader.ReadUInt32())); + return arcs; + } + + private static void WriteArray(BinaryWriter writer, List? values) + { + writer.Write(values?.Count ?? -1); + if (values != null) writer.Write(MemoryMarshal.AsBytes(CollectionsMarshal.AsSpan(values))); + } +} diff --git a/src/RvtIO/Parsing/OwnPartitionParts.cs b/src/RvtIO/Parsing/OwnPartitionParts.cs index c92cc254..fc633cbe 100644 --- a/src/RvtIO/Parsing/OwnPartitionParts.cs +++ b/src/RvtIO/Parsing/OwnPartitionParts.cs @@ -31,13 +31,19 @@ internal sealed record Classes(PartitionFraming.Tags Tags, int[] NodeKinds, int internal static Dictionary? Read(byte[] raw, out string? failure) => Read(raw, Revit2022, 4, out failure); internal static Dictionary? Read(byte[] raw, Classes classes, int idWidth, out string? failure) + => Read(raw, null, classes, idWidth, out failure); + + internal static Dictionary? Read(Stream raw, Classes classes, int idWidth, out string? failure) + => Read(null, raw, classes, idWidth, out failure); + + private static Dictionary? Read(byte[]? raw, Stream? stream, Classes classes, int idWidth, out string? failure) { var nodes = new Dictionary(); var geometry = new Dictionary(); var ambiguous = new HashSet(); try { - bool walked = PartitionFraming.Walk(raw, classes.Tags, idWidth, record => + void Collect(PartitionFraming.Record record) { ulong terminator = idWidth == 8 ? ulong.MaxValue : uint.MaxValue; if (record.Owner == terminator) return; @@ -57,7 +63,10 @@ internal sealed record Classes(PartitionFraming.Tags Tags, int[] NodeKinds, int // A repeated deposit replaces the previous one, including a different root class. if (wanted) selected[owner] = SHA256.HashData(record.Item.Span); else selected.Remove(owner); - }, out failure, out _); + } + bool walked = stream == null + ? PartitionFraming.Walk(raw!, classes.Tags, idWidth, Collect, out failure, out _) + : PartitionFraming.WalkStream(stream, classes.Tags, idWidth, Collect, out failure, out _); if (!walked) return null; } catch (InvalidDataException exception) diff --git a/src/RvtIO/Parsing/PartitionChunks.cs b/src/RvtIO/Parsing/PartitionChunks.cs new file mode 100644 index 00000000..3c216f70 --- /dev/null +++ b/src/RvtIO/Parsing/PartitionChunks.cs @@ -0,0 +1,257 @@ +using System.Collections; + +namespace RvtIO.Parsing; + +/// Ordered references to inflated partition chunks. A filtered list shares the same references. +internal sealed class PartitionChunks(PartitionChunks.Backing? backing = null) : IReadOnlyList +{ + internal sealed record Chunk(int Length, byte[]? Memory, long Offset); + + internal sealed class Backing(Stream stream) + { + private const int CachedChunks = 16; + private const int CacheLimit = 8 * 1024 * 1024; + private static readonly byte[] SmallPadding = new byte[64 * 1024]; + private readonly Dictionary cache = new(ReferenceEqualityComparer.Instance); + private readonly Queue cacheOrder = new(CachedChunks); + private int cacheBytes; + private long end; + + internal Chunk Add(ReadOnlySpan data) => Add(data, data.Length); + + internal Chunk Add(ReadOnlySpan data, int reservedLength) + { + ArgumentOutOfRangeException.ThrowIfLessThan(reservedLength, data.Length); + lock (stream) + { + long offset = end; + long next = checked(offset + reservedLength); + WriteAt(offset, data); + int padding = reservedLength - data.Length; + // Keep small reserved slots contiguous so stream buffering can batch writes. + if (padding > 0 && padding <= SmallPadding.Length) + WriteAt(offset + data.Length, SmallPadding.AsSpan(0, padding)); + end = next; + return new Chunk(data.Length, null, offset); + } + } + + internal Chunk Overwrite(Chunk chunk, ReadOnlySpan data, int reservedLength) + { + ArgumentOutOfRangeException.ThrowIfLessThan(reservedLength, data.Length); + lock (stream) + { + WriteAt(chunk.Offset, data); + // A new chunk identity keeps reads distinct from previously cached bytes. + return new Chunk(data.Length, null, chunk.Offset); + } + } + + private void WriteAt(long offset, ReadOnlySpan data) + { + try + { + if (stream.Position != offset) stream.Position = offset; + stream.Write(data); + } + catch (Exception failure) when (MalformedInput.Is(failure)) + { + throw new StorageFailure("Could not write the partition scratch stream.", failure); + } + } + + internal byte[] Read(Chunk chunk) + { + if (chunk.Length == 0) return []; + lock (stream) + { + if (cache.TryGetValue(chunk, out var data)) return data; + data = new byte[chunk.Length]; + ReadAt(chunk.Offset, data); + if (data.Length <= CacheLimit) + { + while (cache.Count == CachedChunks || cacheBytes + data.Length > CacheLimit) + { + var oldest = cacheOrder.Dequeue(); + cacheBytes -= cache[oldest].Length; + cache.Remove(oldest); + } + cache.Add(chunk, data); + cacheOrder.Enqueue(chunk); + cacheBytes += data.Length; + } + return data; + } + } + + internal void ReadSlice(Chunk chunk, int start, Span destination) + { + ArgumentOutOfRangeException.ThrowIfNegative(start); + ArgumentOutOfRangeException.ThrowIfGreaterThan(destination.Length, chunk.Length - start); + if (destination.IsEmpty) return; + lock (stream) + { + if (cache.TryGetValue(chunk, out var data)) + data.AsSpan(start, destination.Length).CopyTo(destination); + else + ReadAt(checked(chunk.Offset + start), destination); + } + } + + private void ReadAt(long offset, Span destination) + { + try + { + if (stream.Position != offset) stream.Position = offset; + stream.ReadExactly(destination); + } + catch (Exception failure) when (MalformedInput.Is(failure)) + { + throw new StorageFailure("Could not read the partition scratch stream.", failure); + } + } + } + + // A storage error must never be treated as a malformed record and skipped. + private sealed class StorageFailure(string message, Exception cause) : Exception(message, cause); + + internal readonly struct Block + { + private readonly object? source; + private readonly Chunk? stored; + private readonly long start; + private readonly int length; + + internal Block(byte[] data, int start, int length, Backing? backing) + { + if (backing == null) + { + source = data; + this.start = start; + } + else + { + source = backing; + stored = backing.Add(data.AsSpan(start, length)); + } + } + + internal Block(Backing backing, Chunk stored, int start, int length) + { + source = backing; + this.stored = stored; + this.start = start; + this.length = length; + } + + internal Block(WindowSource source, long start, int length) + { + this.source = source; + this.start = start; + this.length = length; + } + + internal (byte[] Data, int Start) Read() + { + if (source is byte[] resident) return (resident, (int)start); + if (source is WindowSource window) return (window.Read(start, length), 0); + var backing = (Backing)source!; + if (length == 0) return (backing.Read(stored!), 0); + var bytes = new byte[length]; + backing.ReadSlice(stored!, (int)start, bytes); + return (bytes, 0); + } + } + + /// A bounded view over the concatenation of the original inflated chunks. + internal sealed class WindowSource + { + private readonly PartitionChunks chunks; + private readonly long[] starts; + + internal WindowSource(PartitionChunks chunks) + { + this.chunks = chunks; + starts = new long[chunks.Count + 1]; + for (int i = 0; i < chunks.Count; i++) starts[i + 1] = starts[i] + PartitionChunks.LengthAt(chunks, i); + } + + internal long Length => starts[^1]; + + // Use the same logical segment and overlap boundaries as the in-memory scanner. + internal IEnumerable<(long Start, int Length, int Limit)> Segments(long target, int overlap) + { + int index = 0; + long start = 0; + while (index < chunks.Count) + { + int first = index; + while (index < chunks.Count && starts[index + 1] - start <= target) index++; + if (index == first) index++; + int length = checked((int)(starts[index] - start)); + int limit = index == chunks.Count ? length : Math.Max(0, length - overlap); + yield return (start, length, limit); + start += limit; + } + } + + internal byte[] Read(long offset, int count) + { + var result = new byte[count]; + int index = Array.BinarySearch(starts, offset); + if (index < 0) index = ~index - 1; + int written = 0; + while (written < count) + { + var chunk = chunks.entries[index]; + int from = (int)(offset - starts[index]); + int copy = Math.Min(count - written, chunk.Length - from); + var target = result.AsSpan(written, copy); + if (chunk.Memory is { } resident) + resident.AsSpan(from, copy).CopyTo(target); + else + chunks.Store!.ReadSlice(chunk, from, target); + offset += copy; + written += copy; + index++; + } + return result; + } + } + + private readonly List entries = []; + internal Backing? Store => backing; + internal Chunk Reference(int index) => entries[index]; + internal Block? StoredBlock(int index, int start, int length) + => backing != null && entries[index].Memory == null ? new Block(backing, entries[index], start, length) : null; + internal void Add(Chunk chunk) => entries.Add(chunk); + internal void Add(byte[] data) => Add(backing?.Add(data) ?? new Chunk(data.Length, data, 0)); + internal void AddRange(PartitionChunks chunks) => entries.AddRange(chunks.entries); + + internal PartitionChunks Select(IEnumerable indices) + { + var result = new PartitionChunks(backing); + foreach (int index in indices) result.Add(entries[index]); + return result; + } + + public int Count => entries.Count; + public byte[] this[int index] + { + get + { + var chunk = entries[index]; + return chunk.Memory ?? backing!.Read(chunk); + } + } + + public IEnumerator GetEnumerator() + { + for (int i = 0; i < entries.Count; i++) yield return this[i]; + } + + IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); + + internal static int LengthAt(IReadOnlyList chunks, int index) + => chunks is PartitionChunks partition ? partition.entries[index].Length : chunks[index].Length; +} diff --git a/src/RvtIO/Parsing/PartitionFraming.cs b/src/RvtIO/Parsing/PartitionFraming.cs index b49784f2..57e2fd3e 100644 --- a/src/RvtIO/Parsing/PartitionFraming.cs +++ b/src/RvtIO/Parsing/PartitionFraming.cs @@ -51,23 +51,32 @@ internal sealed record Framed(IReadOnlyList Segments, List /// Where the bytes of the item are: in its segment when it lies in one, else in a copy (an item can run into the next segment /// of its chain); Copied tells which. internal (byte[] Data, int Start, bool Copied) Bytes(ProjectItem item) + => Bytes(item, out _); + + internal (byte[] Data, int Start, bool Copied) Bytes(ProjectItem item, out PartitionChunks.Block? stored) { + stored = null; if (starts == null) { var at = new long[Segments.Count]; - for (int i = 1; i < at.Length; i++) at[i] = at[i - 1] + Segments[i - 1].Length; + for (int i = 1; i < at.Length; i++) at[i] = at[i - 1] + PartitionChunks.LengthAt(Segments, i - 1); starts = at; } int s = Array.BinarySearch(starts, item.Offset); if (s < 0) s = ~s - 1; - while (s < starts.Length - 1 && starts[s + 1] <= item.Offset && Segments[s].Length == 0) s++; + while (s < starts.Length - 1 && starts[s + 1] <= item.Offset && PartitionChunks.LengthAt(Segments, s) == 0) s++; int from = (int)(item.Offset - starts[s]); - if (from + (long)item.Length <= Segments[s].Length) return (Segments[s], from, false); + if (from + (long)item.Length <= PartitionChunks.LengthAt(Segments, s)) + { + stored = (Segments as PartitionChunks)?.StoredBlock(s, from, item.Length); + return (Segments[s], from, false); + } var copy = new byte[item.Length]; for (int done = 0; done < item.Length; s++, from = 0) { - int n = Math.Min(item.Length - done, Segments[s].Length - from); - Buffer.BlockCopy(Segments[s], from, copy, done, n); + var segment = Segments[s]; + int n = Math.Min(item.Length - done, segment.Length - from); + Buffer.BlockCopy(segment, from, copy, done, n); done += n; } return (copy, 0, true); @@ -86,15 +95,24 @@ internal sealed record Framed(IReadOnlyList Segments, List /// with the reason in when the framing does not hold. is 4 or 8. internal static bool Walk(byte[] raw, Tags tags, int idWidth, Action onRecord, out string? failure, out int blocks, List? segmentLengths = null, List? segmentBytes = null) + => WalkCore(() => new Cursor(raw, paged: true), tags, idWidth, onRecord, out failure, out blocks, + segmentLengths, segmentBytes is null ? null : segmentBytes.Add, incremental: false); + + internal static bool WalkStream(Stream raw, Tags tags, int idWidth, Action onRecord, out string? failure, out int blocks, + List? segmentLengths = null, Action? onSegment = null) + => WalkCore(() => new Cursor(raw), tags, idWidth, onRecord, out failure, out blocks, segmentLengths, onSegment, incremental: true); + + private static bool WalkCore(Func open, Tags tags, int idWidth, Action onRecord, + out string? failure, out int blocks, List? segmentLengths, Action? onSegment, bool incremental) { failure = null; blocks = 0; try { - var input = new Cursor(raw, paged: true); + var input = open(); Require(input.U32() == 9 && input.U32() == 0, "format"); var keys = new HashSet(); - long inflated = 0; // output of all finished chains + long inflated = 0; // bytes of records already emitted while (true) { Require(input.U16() == tags.ContentMarker, "content-marker"); @@ -113,7 +131,7 @@ internal static bool Walk(byte[] raw, Tags tags, int idWidth, Action onR HashSet[] owners = [new(), new(), new()]; using var chain = new MemoryStream(); uint? chainIndex = null; - long countSum = 0, sizeSum = 0; + long countSum = 0, sizeSum = 0, actualCount = 0, actualSize = 0; while (true) { Require(input.U16() == tags.SegmentMarker, "segment-marker"); @@ -136,22 +154,24 @@ internal static bool Walk(byte[] raw, Tags tags, int idWidth, Action onR int before = (int)chain.Length; Inflate(payload, chain); segmentLengths?.Add((int)chain.Length - before); - segmentBytes?.Add(chain.GetBuffer().AsSpan(before, (int)chain.Length - before).ToArray()); + onSegment?.Invoke(chain.GetBuffer().AsSpan(before, (int)chain.Length - before).ToArray()); countSum += count; sizeSum += unc; - if (mode is not (0 or 1)) continue; - + bool final = mode is 0 or 1; + if (!final && !incremental) continue; var memory = chain.GetBuffer().AsMemory(0, checked((int)chain.Length)); var records = new Cursor(memory); - long actualCount = 0, actualSize = 0; + int committed = 0; + int headerSize = idWidth + (index == 101 ? 4 : 8); while (records.Remaining > 0) { - int begin = records.Position; + if (!final && records.Remaining < headerSize) break; ulong owner = idWidth == 8 ? records.U64() : records.U32(); uint extra = index != 101 ? records.U32() : 0; uint bodySize = records.U32(); Require(bodySize <= int.MaxValue, "record-length"); - int bodyAt = records.Position; + if (!final && records.Remaining < (long)bodySize + 4) break; + int bodyAt = (int)records.Position; records.Bytes((int)bodySize); Require(records.U32() == bodySize, "record-footer"); actualCount++; @@ -159,14 +179,20 @@ internal static bool Walk(byte[] raw, Tags tags, int idWidth, Action onR // the channel census only counts real owners; the id -1 record is the chain terminator of the block bool terminator = owner == (idWidth == 8 ? ulong.MaxValue : uint.MaxValue); if (!terminator) owners[index - 101].Add(owner); - onRecord(new Record(blocks, key, (int)index, owner, extra, memory.Slice(bodyAt, (int)bodySize), memory.Slice(begin, records.Position - begin), inflated + begin)); + int finish = (int)records.Position; + onRecord(new Record(blocks, key, (int)index, owner, extra, memory.Slice(bodyAt, (int)bodySize), + memory.Slice(committed, finish - committed), inflated + committed)); + committed = finish; } + inflated += committed; + // A record may straddle many members; retain only its unfinished suffix between members. + memory.Span[committed..].CopyTo(chain.GetBuffer()); + chain.SetLength(memory.Length - committed); + chain.Position = chain.Length; + if (!final) continue; Require(actualCount == countSum && actualSize == sizeSum, "chain-counts"); - inflated += chain.Length; - chain.SetLength(0); - chain.Position = 0; chainIndex = null; - countSum = sizeSum = 0; + countSum = sizeSum = actualCount = actualSize = 0; } Require(owners[0].Count == expectedOwners && owners[0].SetEquals(owners[1]) && owners[0].SetEquals(owners[2]), "owner-census"); Require(input.U16() == tags.SignatureMarker, "signature-marker"); @@ -230,34 +256,86 @@ private static void Require(bool condition, string reason) if (!condition) throw new InvalidDataException(reason); } - private sealed class Cursor(ReadOnlyMemory bytes, bool paged = false) + private sealed class Cursor { - private readonly int length = paged ? PayloadLength(bytes.Span) : bytes.Length; + private readonly ReadOnlyMemory bytes; + private readonly bool paged; + private readonly long length; + private readonly Stream? stream; + private readonly byte[]? page; + private readonly byte[] scalar = new byte[16]; + private long pageStart = -1; + + internal Cursor(ReadOnlyMemory bytes, bool paged = false) + { + this.bytes = bytes; + this.paged = paged; + length = paged ? PayloadLength(bytes.Span) : bytes.Length; + } + + internal Cursor(Stream stream) + { + this.stream = stream; + paged = true; + page = new byte[PagedGzipStream.PageDataLength]; + long rawLength = stream.Length; + long tails = 0; + Span tag = stackalloc byte[2]; + for (long offset = PagedGzipStream.PageDataLength; offset < rawLength;) + { + long remaining = rawLength - offset; + Require(remaining >= PagedGzipStream.SegmentLength, "page-framing"); + if (remaining > PagedGzipStream.SegmentLength) + { + stream.Position = offset; + stream.ReadExactly(tag); + Require(tag[0] == 0 && (tag[1] & 0x0f) == 0, "page-framing"); + } + tails++; + if (remaining <= PagedGzipStream.PageStride) break; + offset += PagedGzipStream.PageStride; + } + length = rawLength - tails * PagedGzipStream.SegmentLength; + } - internal int Position { get; private set; } - internal int Remaining => length - Position; - internal ReadOnlySpan Bytes(int count) => Take(count).Span; + internal long Position { get; private set; } + internal long Remaining => length - Position; + internal ReadOnlySpan Bytes(int count) + { + if (stream == null) return Take(count).Span; + Require(count >= 0 && count <= Remaining && count <= scalar.Length, "bounds"); + var target = scalar.AsSpan(0, count); + ReadPaged(Position, target); + Position += count; + return target; + } /// The next bytes: a view of the stream where they lie, a copy only when a page tail runs through them. internal ReadOnlyMemory Take(int count) { Require(count >= 0 && count <= Remaining, "bounds"); - int start = Position; + long start = Position; Position += count; if (count == 0) return default; - if (!paged) return bytes.Slice(start, count); + if (stream != null) + { + var result = new byte[count]; + ReadPaged(start, result); + return result; + } + if (!paged) return bytes.Slice((int)start, count); - int inPage = start % PagedGzipStream.PageDataLength; + int inPage = (int)(start % PagedGzipStream.PageDataLength); int available = PagedGzipStream.PageDataLength - inPage; - if (count <= available) return bytes.Slice(PhysicalOffset(start), count); + if (count <= available) return bytes.Slice((int)PhysicalOffset(start), count); // The inflater needs one contiguous gzip member. Only values spanning a page tail need a copy. var value = new byte[count]; for (int copied = 0; copied < count;) { - int offset = start + copied; - int take = Math.Min(count - copied, PagedGzipStream.PageDataLength - offset % PagedGzipStream.PageDataLength); - bytes.Span.Slice(PhysicalOffset(offset), take).CopyTo(value.AsSpan(copied)); + long offset = start + copied; + int take = Math.Min(count - copied, PagedGzipStream.PageDataLength - (int)(offset % PagedGzipStream.PageDataLength)); + bytes.Span.Slice((int)PhysicalOffset(offset), take).CopyTo(value.AsSpan(copied)); copied += take; } return value; @@ -268,12 +346,31 @@ internal ReadOnlyMemory Take(int count) internal void Skip(long count) { Require(count >= 0 && count <= Remaining, "signature-bounds"); - Position += (int)count; + Position += count; } - private static int PhysicalOffset(int logicalOffset) => logicalOffset + private static long PhysicalOffset(long logicalOffset) => logicalOffset + logicalOffset / PagedGzipStream.PageDataLength * PagedGzipStream.SegmentLength; + private void ReadPaged(long offset, Span target) + { + while (!target.IsEmpty) + { + int inside = (int)(offset % PagedGzipStream.PageDataLength); + long start = offset - inside; + if (pageStart != start) + { + stream!.Position = PhysicalOffset(start); + stream.ReadExactly(page.AsSpan(0, (int)Math.Min(page!.Length, length - start))); + pageStart = start; + } + int count = Math.Min(target.Length, page!.Length - inside); + page.AsSpan(inside, count).CopyTo(target); + target = target[count..]; + offset += count; + } + } + private static int PayloadLength(ReadOnlySpan raw) { int tails = 0; diff --git a/src/RvtIO/Parsing/R22Transcoder.cs b/src/RvtIO/Parsing/R22Transcoder.cs index ea65d1e4..5ce06cc2 100644 --- a/src/RvtIO/Parsing/R22Transcoder.cs +++ b/src/RvtIO/Parsing/R22Transcoder.cs @@ -55,67 +55,80 @@ internal R22Transcoder(SchemaDocument source, SchemaDocument target, int sourceI /// The chunks of one partition stream in the 2022 layout, cut at item boundaries; the input is the same stream /// concatenated. Bytes outside the section grammar are copied as they are. - internal List Stream(IReadOnlyList chunks, out Stats stats) + internal PartitionChunks Stream(IReadOnlyList chunks, out Stats stats, PartitionChunks.Backing? backing = null) { - long total = 0; - foreach (var c in chunks) total += c.Length; - var buf = new byte[total]; - long off = 0; - foreach (var c in chunks) { Buffer.BlockCopy(c, 0, buf, (int)off, c.Length); off += c.Length; } - var result = new List(); - var output = new MemoryStream(); + var source = new ChunkInput(chunks); + var result = new PartitionChunks(backing); + using var output = new MemoryStream(); stats = new Stats(); int w = _sourceWidth; - int n = buf.Length, p = 0; + long n = source.Length, p = 0; void Flush(bool force) { - if (output.Length > 0 && (force || output.Length >= 1 << 20)) { result.Add(output.ToArray()); output.SetLength(0); } + if (output.Length == 0 || (!force && output.Length < 1 << 20)) return; + result.Add(output.ToArray()); + output.SetLength(0); } void Separator(int length, bool counted) { // ff*W [u32 k]? 00*8 in the source width, ff*4 ... in the target width - var sep = new byte[(counted ? 4 : 0) + 4 + 8]; - sep.AsSpan(0, 4).Fill(0xFF); - if (counted) BinaryPrimitives.WriteUInt32LittleEndian(sep.AsSpan(4), BitConverter.ToUInt32(buf, p + w)); - output.Write(sep); + Span sep = stackalloc byte[16]; + sep.Clear(); + sep[..4].Fill(0xFF); + if (counted) BinaryPrimitives.WriteUInt32LittleEndian(sep[4..], source.UInt32(p + w)); + output.Write(sep[..(counted ? 16 : 12)]); p += length; } - bool IsSeparator(int at) => at + w <= n && buf.AsSpan(at, w).IndexOfAnyExcept((byte)0xFF) < 0; - bool HasRecordlessSectionAhead(int at) + bool IsSeparator(long at) => at + w <= n && source.Span(at, w).IndexOfAnyExcept((byte)0xFF) < 0; + bool TryItem(long at, bool block, out int length) + { + length = 0; + int head = w + (block ? 8 : 4); + if (at + head + 4 > n) return false; + uint size = source.UInt32(at + head - 4); + if (size < 2 || size > (block ? 64_000_000u : 8_000_000u) || at + head + 4 + size > n + || source.UInt32(at + head + size) != size) return false; + length = head + (int)size + 4; + return true; + } + bool HasRecordlessSectionAhead(long at) { - if (at + w + 8 > n || !IsSeparator(at) || buf.AsSpan(at + w, 8).IndexOfAnyExcept((byte)0) >= 0) return false; - int q = at + w + 8; - while (q + w + 12 <= n && !IsSeparator(q) && TryBlock(buf, q, w, out int len)) q += len; - if (q + w + 12 > n || !IsSeparator(q) || buf.AsSpan(q + w + 4, 8).IndexOfAnyExcept((byte)0) >= 0) return false; + if (at + w + 8 > n || !IsSeparator(at) || source.Span(at + w, 8).IndexOfAnyExcept((byte)0) >= 0) return false; + long q = at + w + 8; + while (!IsSeparator(q) && TryItem(q, true, out int len)) q += len; + if (q + w + 12 > n || !IsSeparator(q) || source.Span(q + w + 4, 8).IndexOfAnyExcept((byte)0) >= 0) return false; q += w + 12; - while (q + w + 12 <= n && !IsSeparator(q) && TryBlock(buf, q, w, out int len)) q += len; - return q + w + 12 <= n && IsSeparator(q) && buf.AsSpan(q + w + 4, 8).IndexOfAnyExcept((byte)0) < 0; + while (!IsSeparator(q) && TryItem(q, true, out int len)) q += len; + return q + w + 12 <= n && IsSeparator(q) && source.Span(q + w + 4, 8).IndexOfAnyExcept((byte)0) < 0; } while (p < n) { // section: records - int recordsAt = p; - while (p + w + 8 <= n && !IsSeparator(p) && TryRecord(buf, p, w, out int length)) + long recordsAt = p; + while (!IsSeparator(p) && TryItem(p, false, out int length)) { - WriteRecord(buf, p, output, stats); + var (data, start) = source.Bytes(p, length); + WriteRecord(data, start, output, stats); p += length; Flush(false); } if (!IsSeparator(p) || p + w + 8 > n || (p == recordsAt && !HasRecordlessSectionAhead(p))) break; Separator(w + 8, false); // root blocks - while (p + w + 12 <= n && !IsSeparator(p) && TryBlock(buf, p, w, out int length)) + while (!IsSeparator(p) && TryItem(p, true, out int length)) { - WriteBlock(buf, p, output, stats, root: true); + var (data, start) = source.Bytes(p, length); + WriteBlock(data, start, output, stats, root: true); p += length; Flush(false); } if (!IsSeparator(p) || p + w + 12 > n) break; Separator(w + 12, true); // second blocks (one per record: placeholders and geometry) - while (p + w + 12 <= n && !IsSeparator(p) && TryBlock(buf, p, w, out int length)) + while (!IsSeparator(p) && TryItem(p, true, out int length)) { - WriteBlock(buf, p, output, stats, root: false); + var (data, start) = source.Bytes(p, length); + WriteBlock(data, start, output, stats, root: false); p += length; Flush(false); } @@ -123,22 +136,91 @@ bool HasRecordlessSectionAhead(int at) Separator(w + 12, true); Flush(true); } - if (p < n) output.Write(buf, p, n - p); + if (p < n) + { + // Preserve the original unparsed tail as one chunk for the legacy scanners. + source.CopyTail(p, output); + stats.StoppedBytes = Convert.ToHexString(source.Span(p, (int)Math.Min(48, n - p))); + } Flush(true); stats.UnparsedBytes = n - p; stats.StoppedAt = p; - if (p < n) stats.StoppedBytes = Convert.ToHexString(buf, p, Math.Min(48, n - p)); return result; } + private sealed class ChunkInput + { + private readonly IReadOnlyList _chunks; + private readonly long[] _starts; + private int _current = -1; + private byte[] _data = []; + + internal ChunkInput(IReadOnlyList chunks) + { + _chunks = chunks; + _starts = new long[chunks.Count + 1]; + for (int index = 0; index < chunks.Count; index++) + _starts[index + 1] = _starts[index] + PartitionChunks.LengthAt(chunks, index); + } + + internal long Length => _starts[^1]; + + private int Locate(long at) + { + if (_current < 0 || at < _starts[_current] || at >= _starts[_current + 1]) + { + int index = Array.BinarySearch(_starts, at); + if (index < 0) index = ~index - 1; + while (at == _starts[index + 1]) index++; + _data = _chunks[index]; + _current = index; + } + return (int)(at - _starts[_current]); + } + + internal (byte[] Data, int Offset) Bytes(long at, int count) + { + int offset = Locate(at); + if (count <= _data.Length - offset) return (_data, offset); + var buffer = new byte[count]; + for (int copied = 0; copied < count;) + { + offset = Locate(at + copied); + int length = Math.Min(count - copied, _data.Length - offset); + _data.AsSpan(offset, length).CopyTo(buffer.AsSpan(copied)); + copied += length; + } + return (buffer, 0); + } + + internal ReadOnlySpan Span(long at, int count) + { + var (data, offset) = Bytes(at, count); + return data.AsSpan(offset, count); + } + + internal uint UInt32(long at) => BinaryPrimitives.ReadUInt32LittleEndian(Span(at, 4)); + + internal void CopyTail(long at, Stream output) + { + while (at < Length) + { + int offset = Locate(at); + int length = _data.Length - offset; + output.Write(_data, offset, length); + at += length; + } + } + } + /// The channel-102 and 103 records of the project's own block of one framed stream in the 2022 layout, each rewritten as /// rewrites a block and none running into the next segment; channel 101 is left out. Null when the frame's id /// width is not the one of the file's schema. - internal PartitionFraming.Framed? Framed(PartitionFraming.Framed source, out Stats stats) + internal PartitionFraming.Framed? Framed(PartitionFraming.Framed source, out Stats stats, PartitionChunks.Backing? backing = null) { stats = new Stats(); if (source.IdWidth != _sourceWidth) return null; - var segments = new List(); + var segments = new PartitionChunks(backing); var items = new List(); var output = new MemoryStream(); long flushed = 0; @@ -165,26 +247,6 @@ internal sealed class Stats public readonly Dictionary Failures = new(); } - private static bool TryRecord(byte[] b, int p, int w, out int length) - { - length = 0; - if (p + w + 8 > b.Length) return false; - uint size = BitConverter.ToUInt32(b, p + w); - if (size < 2 || size > 8_000_000 || p + (long)w + 8 + size > b.Length || BitConverter.ToUInt32(b, p + w + 4 + (int)size) != size) return false; - length = w + 8 + (int)size; - return true; - } - - private static bool TryBlock(byte[] b, int p, int w, out int length) - { - length = 0; - if (p + w + 12 > b.Length) return false; - uint size = BitConverter.ToUInt32(b, p + w + 4); - if (size < 2 || size > 64_000_000 || p + (long)w + 12 + size > b.Length || BitConverter.ToUInt32(b, p + w + 8 + (int)size) != size) return false; - length = w + 12 + (int)size; - return true; - } - private void WriteId(byte[] b, int p, MemoryStream output) { Span id = stackalloc byte[4]; diff --git a/src/RvtIO/Parsing/RecordParser.cs b/src/RvtIO/Parsing/RecordParser.cs index 900a203f..a0a98990 100644 --- a/src/RvtIO/Parsing/RecordParser.cs +++ b/src/RvtIO/Parsing/RecordParser.cs @@ -38,7 +38,8 @@ internal static bool ContainsAnchoredR25Record(byte[] chunk, IReadOnlySet return false; } - public static void ParseChunk(byte[] chunk, ParsingState state) + public static void ParseChunk(byte[] chunk, ParsingState state, PartitionChunks? source = null, int segment = 0, + ElementRecordFieldStore? fieldStore = null) { int pos = 0; bool aligned = false; @@ -68,10 +69,14 @@ public static void ParseChunk(byte[] chunk, ParsingState state) ExtractReferences(rec); ExtractBodyParams(rec); BlockParser.ExtractBlockStrings(body, 0, body.Length, elemId, state.ElemStrings); - BlockParser.ExtractBlockDoubles(body, 0, body.Length, elemId, state.ElemDoubles); + if (state.KeepExportProvenance) + BlockParser.ExtractBlockDoubles(body, 0, body.Length, elemId, state.ElemDoubles); state.Records[elemId] = rec; // Extract after storing record (needs references for SymbolId validation) BlockParser.ExtractFamilyInstanceTransform(body, 0, body.Length, elemId, state.FamilyInstanceTransforms, state.Records); + if (source?.StoredBlock(segment, pos + 12, body.Length) is { } stored) + rec.RetainBodyInScratch(stored); + if (fieldStore != null) rec.ArchiveFields(fieldStore); } pos = next; aligned = true; @@ -83,7 +88,8 @@ public static void ParseChunk(byte[] chunk, ParsingState state) } /// Parse R25 records: [elemId:4][zero:4][hash:4][bodySize:4][body][bodySize:4] - public static void ParseChunkR25(byte[] chunk, ParsingState state) + public static void ParseChunkR25(byte[] chunk, ParsingState state, PartitionChunks? source = null, int segment = 0, + ElementRecordFieldStore? fieldStore = null) { int pos = 0; bool aligned = false; @@ -108,8 +114,12 @@ public static void ParseChunkR25(byte[] chunk, ParsingState state) ExtractR25Body(rec); BlockParser.ExtractBlockStrings(body, 0, body.Length, elemId, state.ElemStrings); - BlockParser.ExtractBlockDoubles(body, 0, body.Length, elemId, state.ElemDoubles); + if (state.KeepExportProvenance) + BlockParser.ExtractBlockDoubles(body, 0, body.Length, elemId, state.ElemDoubles); state.Records[elemId] = rec; + if (source?.StoredBlock(segment, pos + 16, body.Length) is { } stored) + rec.RetainBodyInScratch(stored); + if (fieldStore != null) rec.ArchiveFields(fieldStore); } pos = next; aligned = true; @@ -221,7 +231,7 @@ private static void ExtractR25Body(ElementRecord rec) if (ElementIdEncoding.IsSupported(refId) && refId != 0xFFFFFFFF && pad == 0 && refId != rec.ElemId) { if (!rec.References.Contains(refId)) - rec.References.Add(refId); + rec.EditFields().References.Add(refId); } off += 8; } @@ -236,7 +246,7 @@ private static void ExtractR25Body(ElementRecord rec) if (ElementIdEncoding.IsSupported(refId) && pad == 0 && refId != rec.ElemId && refId != 0xFFFFFFFF) { if (!rec.References.Contains(refId)) - rec.References.Add(refId); + rec.EditFields().References.Add(refId); } } @@ -312,7 +322,7 @@ public static void ExtractReferences(ElementRecord rec) for (int i = 0; i < count; i++) { uint refId = BitConverter.ToUInt32(body, refStart + i * 4); - if (refId > 0 && refId < 0xFFFFFF00) rec.References.Add(refId); + if (refId > 0 && refId < 0xFFFFFF00) rec.EditFields().References.Add(refId); } refStart += count * 4; if (refStart + 4 > body.Length) break; @@ -372,13 +382,14 @@ public static void ExtractBodyParams(ElementRecord rec) break; } - rec.EntryValues.Add(rawValue); + var fields = rec.EditFields(); + fields.EntryValues.Add(rawValue); if (paramKey == -1) { if (rawValue != -1 && (fieldType == 3 || fieldType == 4)) { - rec.BipParams.Add(new BipEntry(0, null, fieldType, rawValue)); + fields.BipParams.Add(new BipEntry(0, null, fieldType, rawValue)); } continue; } @@ -395,8 +406,8 @@ public static void ExtractBodyParams(ElementRecord rec) int? intVal = rawValue; // ft=205 entries mark user params as writable (non-readonly) if (fieldType == 205 && paramKey > 0) - rec.WritableParamIds.Add(paramKey); - rec.BipParams.Add(new BipEntry(paramKey, bipName, fieldType, intVal)); + fields.WritableParamIds.Add(paramKey); + fields.BipParams.Add(new BipEntry(paramKey, bipName, fieldType, intVal)); } // Do not infer geometry from bytes following class id 0x0548 diff --git a/src/RvtIO/Parsing/RecordRouting.cs b/src/RvtIO/Parsing/RecordRouting.cs index c5e02d7b..e7445259 100644 --- a/src/RvtIO/Parsing/RecordRouting.cs +++ b/src/RvtIO/Parsing/RecordRouting.cs @@ -28,7 +28,7 @@ internal sealed class Census /// SHA-256 over all items (the three channels in file order) of one element in one partition stream. internal Dictionary<(ulong Owner, int Partition), byte[]> Digests { get; } = []; /// Stored length of each partition stream: the reader decompresses the longest first. - internal Dictionary StreamLengths { get; } = []; + internal Dictionary StreamLengths { get; } = []; internal List Items { get; } = []; internal Dictionary> SegmentLengths { get; } = []; internal int KeyedRecords { get; set; } @@ -46,6 +46,12 @@ internal sealed class Census /// Walks one partition stream into the census; false (with the reason) when its framing does not hold. internal static bool Collect(Census census, int partition, byte[] raw, out string? failure) + => CollectCore(census, partition, raw, null, out failure); + + internal static bool CollectStream(Census census, int partition, Stream stream, out string? failure) + => CollectCore(census, partition, null, stream, out failure); + + private static bool CollectCore(Census census, int partition, byte[]? raw, Stream? stream, out string? failure) { var lengths = new List(); var holders = new List<(ulong Owner, long Offset, int Length)>(); @@ -54,7 +60,7 @@ internal static bool Collect(Census census, int partition, byte[] raw, out strin bool ok; try { - ok = PartitionFraming.Walk(raw, census.Tags, census.IdWidth, r => + void CollectRecord(PartitionFraming.Record r) { if (r.Owner == (census.IdWidth == 8 ? ulong.MaxValue : uint.MaxValue)) return; if (r.Block != 0) { if (r.Channel == 101) keyed++; return; } @@ -62,7 +68,9 @@ internal static bool Collect(Census census, int partition, byte[] raw, out strin if (!hashers.TryGetValue(r.Owner, out var hasher)) hashers[r.Owner] = hasher = System.Security.Cryptography.IncrementalHash.CreateHash(System.Security.Cryptography.HashAlgorithmName.SHA256); hasher.AppendData(r.Item.Span); - }, out failure, out _, lengths); + } + ok = stream == null ? PartitionFraming.Walk(raw!, census.Tags, census.IdWidth, CollectRecord, out failure, out _, lengths) + : PartitionFraming.WalkStream(stream, census.Tags, census.IdWidth, CollectRecord, out failure, out _, lengths); if (!ok) return false; foreach (var (owner, hasher) in hashers) census.Digests[(owner, partition)] = hasher.GetHashAndReset(); } @@ -70,7 +78,7 @@ internal static bool Collect(Census census, int partition, byte[] raw, out strin { foreach (var hasher in hashers.Values) hasher.Dispose(); } - census.StreamLengths[partition] = raw.Length; + census.StreamLengths[partition] = raw?.LongLength ?? stream!.Length; census.SegmentLengths[partition] = lengths; census.KeyedRecords += keyed; foreach (var (owner, offset, length) in holders) @@ -131,24 +139,33 @@ internal static void Drop(List items, IReadOnlyLis /// The chunks of one partition stream without the given byte ranges of its inflated stream. Null when the chunks are /// not the segments of the framing (same count, same lengths), so a range could not be placed exactly. internal static List? Prune(IReadOnlyList chunks, IReadOnlyList segmentLengths, IReadOnlyList<(long Start, int Length)> ranges) + => PruneCore(chunks, segmentLengths, ranges)?.ToList(); + + internal static PartitionChunks? PrunePartition(PartitionChunks chunks, IReadOnlyList segmentLengths, IReadOnlyList<(long Start, int Length)> ranges) + => PruneCore(chunks, segmentLengths, ranges); + + private static PartitionChunks? PruneCore(IReadOnlyList chunks, IReadOnlyList segmentLengths, IReadOnlyList<(long Start, int Length)> ranges) { if (chunks.Count != segmentLengths.Count) return null; for (int i = 0; i < chunks.Count; i++) - if (chunks[i].Length != segmentLengths[i]) return null; - var result = new List(chunks.Count); + if (PartitionChunks.LengthAt(chunks, i) != segmentLengths[i]) return null; + var stored = chunks as PartitionChunks; + var result = new PartitionChunks(stored?.Store); long chunkStart = 0; int next = 0; - foreach (var chunk in chunks) + for (int i = 0; i < chunks.Count; i++) { - long chunkEnd = chunkStart + chunk.Length; + long chunkEnd = chunkStart + segmentLengths[i]; // a chunk no range reaches is kept as it is (the framing of the stream holds on to it as well) if (next >= ranges.Count || ranges[next].Start >= chunkEnd) { - result.Add(chunk); + if (stored == null) result.Add(chunks[i]); + else result.Add(stored.Reference(i)); chunkStart = chunkEnd; continue; } - var kept = new MemoryStream(chunk.Length); + var chunk = chunks[i]; + using var kept = new MemoryStream(chunk.Length); long position = chunkStart; while (next < ranges.Count && ranges[next].Start < chunkEnd) { diff --git a/src/RvtIO/Parsing/SolidQuantities.cs b/src/RvtIO/Parsing/SolidQuantities.cs index df9aa760..bc80a924 100644 --- a/src/RvtIO/Parsing/SolidQuantities.cs +++ b/src/RvtIO/Parsing/SolidQuantities.cs @@ -19,35 +19,36 @@ internal static class SolidQuantities /// volumes and surfaces add up, the largest face is the largest of any solid. Null otherwise. internal static Shell? OfAllSolids(GeometryData? geometry) { - if (geometry?.BrepSolids is not { Count: > 0 } solids || geometry.Faces.Count == 0) return null; + if (geometry?.BrepSolids is not { Count: > 0 } solids || geometry.ReadFaces is not { Count: > 0 } faces) return null; var covered = new HashSet(); double volume = 0, surface = 0, largest = 0; foreach (var solid in solids) { - if (!solid.IsClosed || solid.FaceIndices.Any(i => i < 0 || i >= geometry.Faces.Count || !geometry.Faces[i].PlaneSurface)) + if (!solid.IsClosed || OfClosedShell(faces, solid.FaceIndices, planarOnly: true) is not { } shell) return null; - var one = new GeometryData - { - Faces = solid.FaceIndices.Select(i => geometry.Faces[i]).ToList(), - BrepSolids = [new GeoBrepSolid { FaceIndices = Enumerable.Range(0, solid.FaceIndices.Count).ToList(), IsClosed = true }], - }; - if (OfSingleClosedShell(one) is not { } shell) return null; volume += shell.Volume; surface += shell.SurfaceArea; largest = Math.Max(largest, shell.LargestFaceArea); covered.UnionWith(solid.FaceIndices); } - return covered.Count == geometry.Faces.Count ? new Shell(volume, surface, largest) : null; + return covered.Count == faces.Count ? new Shell(volume, surface, largest) : null; } internal static Shell? OfSingleClosedShell(GeometryData? geometry) { if (geometry?.BrepSolids is not { Count: 1 } solids || !solids[0].IsClosed) return null; + return OfClosedShell(geometry.ReadFaces, solids[0].FaceIndices, planarOnly: false); + } + + private static Shell? OfClosedShell(IReadOnlyList source, List indices, bool planarOnly) + { var faces = new List>>(); // face -> loops (outer first) -> points - foreach (int index in solids[0].FaceIndices) + foreach (int index in indices) { - if (index < 0 || index >= geometry.Faces.Count || geometry.Faces[index].OuterVertices is not { Count: >= 3 } outer) return null; + if ((uint)index >= (uint)source.Count) return null; + var face = source[index]; + if ((planarOnly && !face.PlaneSurface) || face.OuterVertices is not { Count: >= 3 } outer) return null; var loops = new List> { outer }; double[] outerArea = VectorArea(outer); - foreach (var inner in geometry.Faces[index].InnerVertices ?? []) + foreach (var inner in face.InnerVertices ?? []) { if (inner.Count < 3) return null; // holes run against the outer boundary @@ -117,7 +118,7 @@ internal static class SolidQuantities /// floor steps. internal static double? RoomPlanArea(GeometryData? boundary) { - if (boundary?.Faces is not { Count: > 0 } faces) return null; + if (boundary?.ReadFaces is not { Count: > 0 } faces) return null; double projected = 0; foreach (var face in faces) { diff --git a/src/RvtIO/Parsing/StringScanner.cs b/src/RvtIO/Parsing/StringScanner.cs index bd45ca84..b6ce5809 100644 --- a/src/RvtIO/Parsing/StringScanner.cs +++ b/src/RvtIO/Parsing/StringScanner.cs @@ -57,12 +57,13 @@ public static bool IsValidParamName(string s) } /// Scan a chunk for element name strings near element IDs. - public static void ScanChunk(byte[] d, HashSet elemSet, Dictionary> elemStrings) + public static void ScanChunk(byte[] d, HashSet elemSet, Dictionary> elemStrings, + bool firstNameOnly = false) { // Each string is found once in a linear pass and attributed to the known ids at i in (j-600, j+100], // the positions whose window [i-100, i+600) contains the string at j. Scanning a window per id would // revalidate the same bytes many times, because id arrays pack known ids back to back. - var seenPerEid = new Dictionary>(); + var seenPerEid = firstNameOnly ? null : new Dictionary>(); for (int j = 0; j + 6 <= d.Length; j++) { uint sLen = BitConverter.ToUInt32(d, j); @@ -101,6 +102,11 @@ public static void ScanChunk(byte[] d, HashSet elemSet, Dictionary(); + if (seenPerEid == null) + { + if (list.Count == 0) list.Add(s); + continue; + } if (!seenPerEid.TryGetValue(eid, out var seen)) seenPerEid[eid] = seen = new HashSet(); if (seen.Add(s)) list.Add(s); diff --git a/src/RvtIO/Parsing/TfStreamWalker.Windows.cs b/src/RvtIO/Parsing/TfStreamWalker.Windows.cs new file mode 100644 index 00000000..efdb1dda --- /dev/null +++ b/src/RvtIO/Parsing/TfStreamWalker.Windows.cs @@ -0,0 +1,52 @@ +namespace RvtIO.Parsing; + +internal static partial class TfStreamWalker +{ + private const int WindowStep = 16 * 1024 * 1024; + + private static void WalkWindows(PartitionChunks chunks, HashSet knownIds, LocatedBlockVisitor visit, + RecordVisitor? visitRecord, Action? progress, long segmentTarget) + { + var source = new PartitionChunks.WindowSource(chunks); + progress?.Invoke(0, source.Length); + foreach (var (start, length, limit) in source.Segments(segmentTarget, MaxBlock)) + { + bool aligned = false; + int position = 0; + while (position < limit && position + 12L <= length) + { + int stop = (int)Math.Min((long)position + WindowStep, limit); + int end = (int)Math.Min((long)stop + 2 * MaxBlock, length); + int from = Math.Max(0, position - 16); + long windowStart = start + from; + var bytes = source.Read(windowStart, end - from); + Action? report = progress == null ? null : offset => progress(windowStart + offset, source.Length); + position = from + WalkWindow(bytes, position - from, ref aligned, knownIds, + (data, offset, size, cls, eid) => visit(data, offset, size, cls, eid, + new(source, windowStart + offset, checked((int)size + 16))), + stop - from, visitRecord, report); + } + } + if (source.Length > 0) progress?.Invoke(source.Length, source.Length); + } + + private static void ScanWindows(PartitionChunks chunks, HashSet targetIds, LocatedBlockVisitor visit, + long segmentTarget, int maxBlock) + { + var source = new PartitionChunks.WindowSource(chunks); + // Preserve the marker order of the concatenated segment, also when it spans several windows. + foreach (var (start, length, limit) in source.Segments(segmentTarget, maxBlock)) + foreach (byte marker in new byte[] { 0xD7, 0xD6, 0x46 }) + for (int position = 0; position < limit;) + { + int stop = (int)Math.Min((long)position + WindowStep, limit); + int end = (int)Math.Min((long)stop + maxBlock + 16, length); + long windowStart = start + position; + var bytes = source.Read(windowStart, end - position); + ScanWindow(bytes, 0, stop - position, marker, maxBlock, targetIds, + (data, offset, size, cls, eid) => visit(data, offset, size, cls, eid, + new(source, windowStart + offset, checked((int)size + 16)))); + position = stop; + } + } +} diff --git a/src/RvtIO/Parsing/TfStreamWalker.cs b/src/RvtIO/Parsing/TfStreamWalker.cs index 0e52d322..71dc15e3 100644 --- a/src/RvtIO/Parsing/TfStreamWalker.cs +++ b/src/RvtIO/Parsing/TfStreamWalker.cs @@ -11,18 +11,38 @@ internal static partial class TfStreamWalker { public delegate void BlockVisitor(byte[] segment, int blockStart, uint dataSize, ushort classId, uint eid); + internal delegate void LocatedBlockVisitor(byte[] segment, int blockStart, uint dataSize, ushort classId, uint eid, + PartitionChunks.Block block); + /// Called for every record ([eid][bodySize][0x053C or 0x04F8][body]) the walk accepts, with the segment and the record start. public delegate void RecordVisitor(byte[] segment, int recordStart, uint eid); private const int MaxBlock = 1_100_000; // > any real block/record size we accept + private const long DefaultSegmentTarget = 1_400_000_000; /// Walks the concatenated chunks in segments of at most bytes (tests pass a small one to /// reach the second segment). gets the offset in the concatenated stream and its length. public static void Walk(IReadOnlyList chunks, HashSet knownIds, BlockVisitor visit, - RecordVisitor? visitRecord = null, Action? progress = null, long segTarget = 1_400_000_000) + RecordVisitor? visitRecord = null, Action? progress = null, long segTarget = DefaultSegmentTarget) + => WalkLocated(chunks, knownIds, (data, start, size, cls, eid, _) => visit(data, start, size, cls, eid), + visitRecord, progress, segTarget); + + internal static void WalkLocated(IReadOnlyList chunks, HashSet knownIds, LocatedBlockVisitor visit, + RecordVisitor? visitRecord = null, Action? progress = null, long segTarget = DefaultSegmentTarget) { - // As in WalkStreaming: the carried overlap and two maximum-sized items must fit in a segment. + // The carried overlap and two maximum-sized items must fit in a segment. if (segTarget <= 3 * MaxBlock) throw new ArgumentOutOfRangeException(nameof(segTarget)); + if (chunks is PartitionChunks { Store: not null } stored) + WalkWindows(stored, knownIds, visit, visitRecord, progress, segTarget); + else + WalkResident(chunks, knownIds, (data, start, size, cls, eid) => + visit(data, start, size, cls, eid, new(data, start, checked((int)size + 16), null)), + visitRecord, progress, segTarget); + } + + private static void WalkResident(IReadOnlyList chunks, HashSet knownIds, BlockVisitor visit, + RecordVisitor? visitRecord, Action? progress, long segTarget) + { long total = 0; foreach (var c in chunks) total += c.Length; progress?.Invoke(0, total); @@ -68,12 +88,17 @@ public static void Walk(IReadOnlyList chunks, HashSet knownIds, Bl private static void WalkSegment(byte[] buf, HashSet knownIds, BlockVisitor visit, int visitLimit, RecordVisitor? visitRecord = null, Action? reportPosition = null) { - int n = buf.Length; - int pos = 0; bool aligned = false; + WalkWindow(buf, 0, ref aligned, knownIds, visit, visitLimit, visitRecord, reportPosition); + } + + private static int WalkWindow(byte[] buf, int pos, ref bool aligned, HashSet knownIds, BlockVisitor visit, + int visitLimit, RecordVisitor? visitRecord, Action? reportPosition) + { + int n = buf.Length; const int reportInterval = 1 << 20; - long nextReport = reportPosition is null ? long.MaxValue : reportInterval; - while (pos + 12 <= n) + long nextReport = reportPosition is null ? long.MaxValue : pos + (long)reportInterval; + while (pos < visitLimit && pos + 12 <= n) { if (pos >= nextReport && pos < visitLimit) { @@ -93,13 +118,14 @@ private static void WalkSegment(byte[] buf, HashSet knownIds, BlockVisitor continue; } var (isBlock, size, eid, cls, dataSize) = it.Value; - if (isBlock && pos < visitLimit) + if (isBlock) visit(buf, pos, dataSize, cls, eid); - else if (!isBlock && pos < visitLimit) + else visitRecord?.Invoke(buf, pos, eid); pos += size; aligned = true; } + return pos; } /// Targeted scan for GRep blocks (classIdx 0x07D7/0x07D6) of SPECIFIC element @@ -107,20 +133,33 @@ private static void WalkSegment(byte[] buf, HashSet knownIds, BlockVisitor /// ids never anchor. Vectorized: hunt the classIdx byte, then validate [eid in targets] /// [dataSize plausible] at the implied block start. The visitor's parser is the final /// validator (returns null on a false positive). - public static void ScanBlocks(IReadOnlyList chunks, HashSet targetIds, BlockVisitor visit) + public static void ScanBlocks(IReadOnlyList chunks, HashSet targetIds, BlockVisitor visit) => + ScanLocated(chunks, targetIds, (data, start, size, cls, eid, _) => visit(data, start, size, cls, eid)); + + // Freeform family symbols (imported meshes) reach multi-MB blocks, far above the + // anchored walk's MaxBlock. The id+classIdx match already gates false positives. + private const int MaxTargetBlock = 8_000_000; + + internal static void ScanLocated(IReadOnlyList chunks, HashSet targetIds, LocatedBlockVisitor visit) { if (targetIds.Count == 0) return; - const long segTarget = 1_400_000_000; - // Freeform family symbols (imported meshes) reach multi-MB blocks, far above the - // anchored walk's MaxBlock. The id+classIdx match already gates false positives. - const int maxTargetBlock = 8_000_000; + if (chunks is PartitionChunks { Store: not null } stored) + ScanWindows(stored, targetIds, visit, DefaultSegmentTarget, MaxTargetBlock); + else + ScanResident(chunks, targetIds, (data, start, size, cls, eid) => + visit(data, start, size, cls, eid, new(data, start, checked((int)size + 16), null))); + } + + private static void ScanResident(IReadOnlyList chunks, HashSet targetIds, BlockVisitor visit) + { + const int maxTargetBlock = MaxTargetBlock; int i = 0; var carry = Array.Empty(); while (i < chunks.Count) { long size = carry.Length; int start = i; - while (i < chunks.Count && size + chunks[i].Length <= segTarget) { size += chunks[i].Length; i++; } + while (i < chunks.Count && size + chunks[i].Length <= DefaultSegmentTarget) { size += chunks[i].Length; i++; } if (start == i && i < chunks.Count) { size += chunks[i].Length; i++; } var seg = new byte[size]; int off = carry.Length; @@ -130,29 +169,7 @@ public static void ScanBlocks(IReadOnlyList chunks, HashSet target int scanLimit = last ? seg.Length : Math.Max(0, seg.Length - maxTargetBlock); foreach (byte marker in (ReadOnlySpan)[0xD7, 0xD6, 0x46]) - { - byte hi = marker == 0x46 ? (byte)0x03 : (byte)0x07; // 0x0346 sketch curves / 0x07D7-6 GRep - var span = new ReadOnlySpan(seg); - int p = 12; // classIdx low byte sits at blockStart+12 - while (p < scanLimit + 12 && p < seg.Length - 1) - { - int rel = span[p..].IndexOf(marker); - if (rel < 0) break; - p += rel; - int bs = p - 12; - if (seg[p + 1] == hi && bs >= 0 && bs < scanLimit) - { - uint eid = BitConverter.ToUInt32(seg, bs); - if (targetIds.Contains(eid)) - { - uint ds = BitConverter.ToUInt32(seg, bs + 8); - if (ds >= 20 && ds < maxTargetBlock && bs + 16 + ds <= seg.Length) - visit(seg, bs, ds, BitConverter.ToUInt16(seg, bs + 12), eid); - } - } - p++; - } - } + ScanWindow(seg, 0, scanLimit, marker, maxTargetBlock, targetIds, visit); if (!last) { int tail = Math.Min(maxTargetBlock, seg.Length); @@ -162,6 +179,27 @@ public static void ScanBlocks(IReadOnlyList chunks, HashSet target } } + private static void ScanWindow(byte[] bytes, int start, int stop, byte marker, int maxBlock, + HashSet targetIds, BlockVisitor visit) + { + byte hi = marker == 0x46 ? (byte)0x03 : (byte)0x07; + int end = Math.Min(stop, bytes.Length - 13) + 12; + var span = bytes.AsSpan(); + for (int p = start + 12; p < end; p++) + { + int rel = span[p..end].IndexOf(marker); + if (rel < 0) break; + p += rel; + int bs = p - 12; + if (span[p + 1] != hi) continue; + uint eid = BitConverter.ToUInt32(span[bs..]); + if (!targetIds.Contains(eid)) continue; + uint ds = BitConverter.ToUInt32(span[(bs + 8)..]); + if (ds >= 20 && ds < maxBlock && bs + 16L + ds <= bytes.Length) + visit(bytes, bs, ds, BitConverter.ToUInt16(span[p..]), eid); + } + } + private static (bool IsBlock, int Size, uint Eid, ushort Cls, uint DataSize)? ParseItem( byte[] buf, int pos, int n, HashSet knownIds) { diff --git a/src/RvtIO/RvtDocument.cs b/src/RvtIO/RvtDocument.cs index 7ba80e60..ba917445 100644 --- a/src/RvtIO/RvtDocument.cs +++ b/src/RvtIO/RvtDocument.cs @@ -80,7 +80,7 @@ private ProjectInfo FillProjectInformation(ProjectInfo info) /// Number of elements in the document. public int ElementCount => _info.Elements.Count; - private RvtDocument(RevitFileInfo info, string? sourcePath = null) + private RvtDocument(RevitFileInfo info, string? sourcePath = null, Action? archiveParameters = null) { _info = info; _sourcePath = sourcePath; @@ -97,25 +97,18 @@ private RvtDocument(RevitFileInfo info, string? sourcePath = null) _typeElementIds = new HashSet(); foreach (var e in info.Elements) { - foreach (var p in e.Parameters) - { - if (p.Definition?.Name is "ELEM_TYPE_PARAM" or "ELEM_FAMILY_AND_TYPE_PARAM" - && p.Value is int typeId && typeId > 0) - { - _typeElementIds.Add(typeId); - break; - } - } + int typeId = e.GetTypeReferenceId(includeFamilyAndType: true); + if (typeId > 0) _typeElementIds.Add(typeId); } - SynthesizeMissingParams(); - info.AttachSourceElementIds(); - Parameter.ResolveZeroElementIds(_info); + SynthesizeMissingParams(archiveParameters); + info.AttachSourceElementIds(archiveParameters); + Parameter.ResolveZeroElementIds(_info, archiveParameters: archiveParameters); ResolveElementNames(); - // Build UniqueId index (only if UniqueIds are present) - if (info.Elements.Any(e => e.UniqueId != null)) + // Paged scenes look up elements by numeric key and defer textual UniqueIds. + if (archiveParameters == null && info.Elements.Any(e => e.UniqueId != null)) { _elemByUniqueId = new Dictionary(StringComparer.OrdinalIgnoreCase); foreach (var e in info.Elements) @@ -130,7 +123,7 @@ private RvtDocument(RevitFileInfo info, string? sourcePath = null) /// Synthesize standard Revit BIPs that the binary parser may not have extracted. /// Runs once during construction to ensure API compatibility with Revit. /// - private void SynthesizeMissingParams() + private void SynthesizeMissingParams(Action? archiveParameters) { foreach (var elem in _info.Elements) { @@ -154,13 +147,13 @@ private void SynthesizeMissingParams() // ELEM_TYPE_PARAM for elements that don't have it but reference a type element: // walls often don't get it from the binary, but their References include the type ID. - if (elem.FamilyTypeId <= 0 && elem.References != null && elem.References.Count > 0) + if (elem.FamilyTypeId <= 0 && elem.ReadReferences != null && elem.ReadReferences.Count > 0) { // Look for a referenced element with same category that: // a) is already known as a type (in _typeElementIds), OR // b) has the same CategoryId and no geometry/bbox (likely a type definition) int? candidateTypeId = null; - foreach (var refId in elem.References) + foreach (var refId in elem.ReadReferences) { if (refId <= 0 || refId == elem.Id) continue; if (!_elemById.TryGetValue(refId, out var refElem)) continue; @@ -207,6 +200,7 @@ private void SynthesizeMissingParams() FixEmptyElementIdParam(elem, "SYMBOL_ID_PARAM", (int)BuiltInParameter.SYMBOL_ID_PARAM, familyTypeId); FixEmptyElementIdParam(elem, "ELEM_FAMILY_PARAM", (int)BuiltInParameter.ELEM_FAMILY_PARAM, familyTypeId); } + archiveParameters?.Invoke(elem); } } @@ -309,8 +303,9 @@ private static void FixEmptyElementIdParam(Element elem, string paramName, int b var p = elem.LookupParameter(paramName); if (p != null && !p.HasValue) { - p.Value = value; - p.StorageType = StorageType.ElementId; + var editable = elem.Parameters.First(parameter => parameter.DefinitionName == paramName); + editable.Value = value; + editable.StorageType = StorageType.ElementId; } else if (p == null) { @@ -342,10 +337,10 @@ public static RvtDocument Open(string rvtPath, RvtReaderOptions? options = null) /// is null. /// is not readable or not seekable, or is closed. /// The stream is empty, is not a compound file, or is cut or damaged. - /// A stream is longer than one array can hold, or a file with no project - /// partitions contains a source element ID above the range of document-local keys. + /// A stream that requires an array is longer than one array can hold, or a file + /// with no project partitions contains a source element ID above the range of document-local keys. public static RvtDocument OpenStream(Stream stream, RvtReaderOptions? options = null) - => new(new RvtFileReader(options).ReadStream(stream)); + => new(new RvtFileReader(options).ReadStream(stream), archiveParameters: options?.ArchiveSceneParameters); /// /// Wrap an existing RevitFileInfo as a queryable Document. diff --git a/src/RvtIO/RvtFileReader.OwnWallPlanarBodies.cs b/src/RvtIO/RvtFileReader.OwnWallPlanarBodies.cs index 87507d97..0fa3377d 100644 --- a/src/RvtIO/RvtFileReader.OwnWallPlanarBodies.cs +++ b/src/RvtIO/RvtFileReader.OwnWallPlanarBodies.cs @@ -6,7 +6,10 @@ namespace RvtIO; public partial class RvtFileReader { - private static void ReadOwnWallPlanarBodies(ParsingState state) + private readonly record struct OwnWallGRep(PartitionChunks.Block Block, uint Size, ushort Cls, uint Owner); + + private static void ReadOwnWallPlanarBodies(ParsingState state, List? collected, + Action? progress) { var owners = state.OwnedElementClassRoots.Where(entry => entry.Value.BlockCount == 1 && entry.Value.ClassId is 3524 or 361).Select(entry => entry.Key).ToHashSet(); @@ -15,50 +18,84 @@ private static void ReadOwnWallPlanarBodies(ParsingState state) state.OwnWallTrimmedRanges.Clear(); state.OwnCurrentWallFaceGroups.Clear(); if (owners.Count == 0) return; - // Class roots are complete now; a second anchored walk avoids stream-order admission. The walk only collects the - // owner blocks; the per-block geometry decode is independent, so it runs in parallel and the results are applied in - // walk order. - var jobs = new List<(byte[] Data, int Start, uint Size, ushort Cls, uint Owner)>(); - TfStreamWalker.Walk(state.Chunks, state.AllKnownIds, (data, start, size, cls, owner) => - { - if (cls is 2007 or 2006 && owners.Contains(owner)) jobs.Add((data, start, size, cls, owner)); - }); - var decoded = new (GRepData? Body, string? Failure)[jobs.Count]; + // Filter only after class roots are complete. In-memory reads rediscover the + // ranges here to avoid keeping their resident segment buffers across recovery. + var jobs = collected ?? new List(); + if (collected != null) + jobs.RemoveAll(job => !owners.Contains(job.Owner)); + else + TfStreamWalker.WalkLocated(state.Chunks, state.AllKnownIds, (_, _, size, cls, owner, block) => + { + if (cls is 2007 or 2006 && owners.Contains(owner)) + jobs.Add(new(block, size, cls, owner)); + }); + if (jobs.Count == 0) return; + progress?.Invoke(0, jobs.Count); + // Retain replacement wall geometry and the trimmed ranges on both paths. + // Only IFC needs the separate planar body and its grouping provenance. + var decoded = state.KeepExportProvenance ? new (GRepData? Body, string? Failure)[jobs.Count] : null; var grepCounts = jobs.GroupBy(job => job.Owner).ToDictionary(group => group.Key, group => group.Count()); var nativeBodies = new GRepData?[jobs.Count]; - var normals = new (uint SourceFace, double[] Normal)?[jobs.Count]; - var groups = new IReadOnlyDictionary?[jobs.Count]; + var normals = decoded == null ? null : new (uint SourceFace, double[] Normal)?[jobs.Count]; + var groups = decoded == null ? null : new IReadOnlyDictionary?[jobs.Count]; var trimmed = new (double Lo, double Hi)?[jobs.Count]; - Parallel.For(0, jobs.Count, index => + void Decode(int index) { - var (data, start, size, cls, owner) = jobs[index]; - decoded[index] = DecodeOwnWallPlanarBody(data, start, size, cls, owner, out var graph); - if (graph != null && grepCounts[owner] == 1 && decoded[index].Body != null + var (block, size, cls, owner) = jobs[index]; + if (decoded == null && (cls != 2007 || grepCounts[owner] != 1)) return; + var (data, start) = block.Read(); + var bodyResult = DecodeOwnWallPlanarBody(data, start, size, cls, owner, out var graph); + if (decoded != null) decoded[index] = bodyResult; + if (state.KeepExportProvenance && graph != null && grepCounts[owner] == 1 && bodyResult.Body != null && state.OwnCurrentWallRoots.Contains(owner) && state.OwnPartitionWallParts?.TryGetValue(owner, out var current) == true && OwnPartitionParts.MatchesFrame(data, start, size, current.GeometrySha256)) { if (state.OwnWallSide0Ids.TryGetValue(owner, out int sideId)) - normals[index] = TfBlockDeserializer.SelectOwnWallSide0Normal(graph, sideId); - groups[index] = TfBlockDeserializer.SelectOwnPostCutFaceGroups(graph, - decoded[index].Body!.Faces.Select(face => face.SourceFace).ToArray()); + normals![index] = TfBlockDeserializer.SelectOwnWallSide0Normal(graph, sideId); + groups![index] = TfBlockDeserializer.SelectOwnPostCutFaceGroups(graph, + bodyResult.Body.Faces.Select(face => face.SourceFace).ToArray()); } - if (graph != null && grepCounts[owner] == 1 && decoded[index].Body is { } trimmedBody + if (graph != null && grepCounts[owner] == 1 && bodyResult.Body is { } trimmedBody && state.OwnWallBaseFaces.TryGetValue(owner, out var baseFaces) && state.OwnWallCutoutSteps.TryGetValue(owner, out var location) && location.BlockCount == 1 && location.Axis is { } locationAxis) trimmed[index] = TfBlockDeserializer.SelectOwnWallTrimmedRange(graph, baseFaces, trimmedBody, locationAxis); - if (decoded[index].Body == null) + if (bodyResult.Body == null) nativeBodies[index] = DecodeOwnNativeWallBody(state, data, start, size, cls, owner, grepCounts[owner]); - }); + } + if (OperatingSystem.IsBrowser()) + { + var clock = progress == null ? null : System.Diagnostics.Stopwatch.StartNew(); + for (int index = 0; index < jobs.Count; index++) + { + Decode(index); + if (clock?.ElapsedMilliseconds >= 500 && index + 1 < jobs.Count) + { + progress!(index + 1, jobs.Count); + clock.Restart(); + } + } + } + else + Parallel.For(0, jobs.Count, Decode); for (int index = 0; index < jobs.Count; index++) { - ApplyOwnWallPlanarBody(state, jobs[index].Owner, decoded[index]); - if (normals[index] is { } normal) state.OwnWallSide0Normals[jobs[index].Owner] = normal; + if (decoded != null) + { + ApplyOwnWallPlanarBody(state, jobs[index].Owner, decoded[index]); + if (normals![index] is { } normal) state.OwnWallSide0Normals[jobs[index].Owner] = normal; + if (groups![index] is { } faces) state.OwnCurrentWallFaceGroups[jobs[index].Owner] = faces; + } if (trimmed[index] is { } range) state.OwnWallTrimmedRanges[jobs[index].Owner] = range; - if (groups[index] is { } faces) state.OwnCurrentWallFaceGroups[jobs[index].Owner] = faces; - if (nativeBodies[index] is { } native) state.GrepBlocks[jobs[index].Owner] = native; + if (nativeBodies[index] is { } native) + { + var job = jobs[index]; + state.GrepBlocks.Set(job.Owner, native, state.PartitionScratch != null ? job.Block : null, + job.Size, nativeWallBody: true); + } } + progress?.Invoke(jobs.Count, jobs.Count); } internal static GRepData? DecodeOwnNativeWallBody(ParsingState state, byte[] data, int start, diff --git a/src/RvtIO/RvtFileReader.R22Layout.cs b/src/RvtIO/RvtFileReader.R22Layout.cs index 03af5e52..8519fe5b 100644 --- a/src/RvtIO/RvtFileReader.R22Layout.cs +++ b/src/RvtIO/RvtFileReader.R22Layout.cs @@ -9,8 +9,8 @@ public partial class RvtFileReader /// Revit 2022 layout (see ); the chunks after the partition streams are kept. Also the number of rewritten /// partition chunks and the framed streams with their records of the project's own block in that layout (null for a stream without /// a framing or with another id width). Null when the file's schema table does not parse a second time or its id width is not 4 or 8 bytes. - private static (List Chunks, int PartitionChunkCount, List Framed)? RewriteToR22Layout(RootStorage root, - FileSchema schema, List chunks, IReadOnlyList> partitionStreams, + private static (PartitionChunks Chunks, int PartitionChunkCount, List Framed)? RewriteToR22Layout(RootStorage root, + FileSchema schema, PartitionChunks chunks, IReadOnlyList> partitionStreams, IReadOnlyList framedStreams, TextWriter? diag, ElementIdMap? ids, IProgress? progress = null) { @@ -23,14 +23,15 @@ private static (List Chunks, int PartitionChunkCount, List(chunks.Count); + var rewritten = new PartitionChunks(chunks.Store); // The unit of work is a stream: each partition stream and each framed stream the rewrite reads. int streamCount = partitionStreams.Count + framedStreams.Count(frame => frame != null); int streamsDone = 0; progress?.Report(new("r22-layout", 0, streamCount)); foreach (var stream in partitionStreams) { - rewritten.AddRange(transcoder.Stream(stream, out var stats)); + var segments = transcoder.Stream(stream, out var stats, chunks.Store); + rewritten.AddRange(segments); diag?.WriteLine($"Revit 2022 layout: {stats.Records} records ({stats.RecordsRewritten} rewritten), " + $"{stats.RootBlocks} root blocks ({stats.RootBlocksRewritten}), {stats.OtherBlocks} other blocks ({stats.OtherBlocksRewritten}), " + $"{stats.UnparsedBytes} bytes outside the section grammar"); @@ -41,12 +42,13 @@ private static (List Chunks, int PartitionChunkCount, List s.Count))); + int sourcePartitionCount = partitionStreams.Sum(s => s.Count); + rewritten.AddRange(chunks.Select(Enumerable.Range(sourcePartitionCount, chunks.Count - sourcePartitionCount))); var framed = new List(framedStreams.Count); foreach (var frame in framedStreams) { if (frame == null) { framed.Add(null); continue; } - var rewrittenFrame = transcoder.Framed(frame, out var stats); + var rewrittenFrame = transcoder.Framed(frame, out var stats, chunks.Store); framed.Add(rewrittenFrame); if (rewrittenFrame != null) diag?.WriteLine($"Revit 2022 layout of the project block: {stats.RootBlocks} root blocks ({stats.RootBlocksRewritten} rewritten), " diff --git a/src/RvtIO/RvtFileReader.cs b/src/RvtIO/RvtFileReader.cs index 2a2282a6..1afc4d03 100644 --- a/src/RvtIO/RvtFileReader.cs +++ b/src/RvtIO/RvtFileReader.cs @@ -53,19 +53,28 @@ public RevitFileInfo Read(string rvtPath) /// is null. /// is not readable or not seekable, or is closed. /// The stream is empty, is not a compound file, or is cut or damaged. - /// A stream is longer than one array can hold, or a file with no project - /// partitions contains a source element ID above the range of document-local keys. + /// A stream that requires an array is longer than one array can hold, or a file + /// with no project partitions contains a source element ID above the range of document-local keys. public RevitFileInfo ReadStream(Stream stream) { - using var root = RvtContainerCheck.OpenVerified(stream, "Revit input stream", out var view); - var info = ReadCore(root); + using var root = RvtContainerCheck.OpenVerified(stream, "Revit input stream", out var view, + streamPartitions: _options.CreatePartitionScratch != null); + var info = ReadCore(root, stream); // The decoders absorb a read that fails and go on with less data; such a result is not returned. view.ThrowStreamFailure(); return info; } - private RevitFileInfo ReadCore(RootStorage root) + private RevitFileInfo ReadCore(RootStorage root, Stream? input = null) { + var createScratch = _options.CreatePartitionScratch; + var storage = createScratch?.Invoke(); + if (storage != null && ReferenceEquals(storage, input)) + throw new ArgumentException("Partition scratch storage must be separate from the input stream."); + using var scratch = storage; + if (createScratch != null && (scratch == null || !scratch.CanRead || !scratch.CanWrite || !scratch.CanSeek || scratch.Length != 0)) + throw new ArgumentException("Partition scratch storage must be a readable, writable, seekable, empty stream."); + var backing = scratch == null ? null : new PartitionChunks.Backing(scratch); var progress = _options.Progress; progress?.Report(new("metadata")); var diag = _options.DiagnosticOutput; @@ -93,11 +102,11 @@ private RevitFileInfo ReadCore(RootStorage root) Dictionary? tfSchemas = null; LogPhase("Decompressing partitions..."); - var chunks = DecompressPartitions(root, diag, out var ownPartitionWallParts, out var partitionStreams, out var framedStreams, out bool staleCopiesRemoved, out var routing, collectFamilyStorage: true, progress); + var chunks = DecompressPartitions(root, diag, out var ownPartitionWallParts, out var partitionStreams, out var framedStreams, out bool staleCopiesRemoved, out var routing, collectFamilyStorage: true, progress, backing); var fmtChunks = DecompressStorage(root, "Formats", diag); if (fmtChunks.Count > 0) { - chunks.AddRange(fmtChunks); + foreach (var chunk in fmtChunks) chunks.Add(chunk); // Parse Formats/Latest class schema table (stored temporarily, assigned to state below) try { @@ -108,7 +117,7 @@ private RevitFileInfo ReadCore(RootStorage root) catch (Exception ex) when (MalformedInput.Is(ex)) { } } var globalChunks = DecompressStorage(root, "Global", diag); - if (globalChunks.Count > 0) chunks.AddRange(globalChunks); + foreach (var chunk in globalChunks) chunks.Add(chunk); progress?.Report(new("class-schema")); // Episode GUID table: nested stream Global/History (there is no top-level "History" storage). @@ -124,7 +133,7 @@ private RevitFileInfo ReadCore(RootStorage root) projectInfo, transmissionData, episodeTable, elemRecHistories, elemRecOwners, tfSchemas, ownPartitionWallParts, staleCopiesRemoved, routing, elemTableIsExact, previewBase64, previewMime, diag, LogPhase, ids); WideModel = wideInfo; - WideState = wideState; + WideState = backing == null ? wideState : null; } bool r22View = false; @@ -145,14 +154,14 @@ private RevitFileInfo ReadCore(RootStorage root) projectInfo, transmissionData, episodeTable, elemRecHistories, elemRecOwners, tfSchemas, ownPartitionWallParts, staleCopiesRemoved, routing, elemTableIsExact, previewBase64, previewMime, diag, LogPhase, ids, progress); ExtensibleStorageReader.Apply(root, rvtInfo, framedStreams); - LastParsingState = state; + LastParsingState = backing == null ? state : null; progress?.Report(new("complete", 1, 1)); return rvtInfo; } private (RevitFileInfo Info, ParsingState State) ParseModel( RootStorage root, - List chunks, + PartitionChunks chunks, IReadOnlyList readFrames, int partitionChunkCount, bool r22View, @@ -182,7 +191,7 @@ private RevitFileInfo ReadCore(RootStorage root) if (ids != null && !r22View) { // The native index reads these partitions. A legacy scan could attach a wide owner's low bits to another element. - chunks = chunks.Skip(partitionChunkCount).ToList(); + chunks = chunks.Select(Enumerable.Range(partitionChunkCount, chunks.Count - partitionChunkCount)); partitionChunkCount = 0; } var state = new ParsingState @@ -193,6 +202,9 @@ private RevitFileInfo ReadCore(RootStorage root) ElemWorksets = elemWorksets, AllKnownIds = new HashSet(elemTable.Keys), Chunks = chunks, + NativeParams = new(chunks.Store), + KeepExportProvenance = _options.ArchiveSceneGeometry == null, + ArchiveSceneParameters = _options.ArchiveSceneParameters, OwnPartitionWallParts = ownPartitionWallParts, TfClassSchemas = tfSchemas ?? new(), LocalUsername = fileMetadata.GetValueOrDefault("Username"), @@ -211,7 +223,7 @@ private RevitFileInfo ReadCore(RootStorage root) progress?.Report(new("element-records")); ReadWideElementIndex(root, state, partitionStreams, framedStreams, wideSchema, diag); ReadRebarBars(root, state, partitionStreams, framedStreams, wideSchema); - ClassifyAndParseRecords(chunks, state, diag); + ClassifyAndParseRecords(chunks, state, diag, progress); LogPhase("Records parsed"); ParseBlocks(state, diag, progress); @@ -228,16 +240,7 @@ private RevitFileInfo ReadCore(RootStorage root) diag?.WriteLine($"Grid datums: {state.GridDatums.Count}"); progress?.Report(new("element-properties")); - // Scan all chunks for element name strings in parallel. Store each result at its - // source chunk index so task completion order cannot change first-match name resolution. - var partialResults = new Dictionary>?[chunks.Count]; - Parallel.For(0, chunks.Count, chunkIndex => - { - var localStrings = new Dictionary>(); - StringScanner.ScanChunk(chunks[chunkIndex], state.AllKnownIds, localStrings); - if (localStrings.Count > 0) partialResults[chunkIndex] = localStrings; - }); - MergeElemScanStringsInChunkOrder(partialResults, state.ElemScanStrings); + ScanElementStrings(chunks, state, progress); LogPhase("Strings scanned"); diag?.WriteLine($"Elements with BIP doubles: {state.ElemBipDoubles.Count}"); @@ -750,37 +753,32 @@ private RevitFileInfo ReadCore(RootStorage root) // Pre-propagate BIP doubles through reference chains PrePropagateBipDoubles(state, diag); + state.ArchiveElementValues(); + ElementBuilder.CompactSceneNameCandidates(state); LogPhase("Parameter keys remapped"); + // Scan the original chunks before the element records occupy the heap. + ExtractWallFunctions(state); + // a file with 64-bit ids lists the elements of its element table only (the record and stream heuristics also find ids of the // loaded families' own documents) var extraRecordIds = state.WideSchema != null ? new List() : state.Records.Keys .Where(k => !state.ElemTable.ContainsKey(k)) .OrderBy(k => k).ToList(); - foreach (var (elemId, typeId) in state.ElemTable.OrderBy(x => x.Key)) - ElementBuilder.BuildElemTableElement(elemId, typeId, state, rvtInfo); - - LogPhase("Elements built"); - foreach (var eid in extraRecordIds) - ElementBuilder.BuildDiscoveredElement(eid, state, rvtInfo); - LogPhase("Discovered elements built"); - // GRep blocks discovered by the stream walk / targeted scan that no index knows: // real geometry whose Record/ElemTable entries sit in unrecoverable stream members // (e.g. heavy slabs with thousands of reference triangles were entirely absent). // Referenced family symbols are retained as block-only definition elements. They // are not exported as standalone IFC products, but callers need their geometry to // resolve GeometryData.Instances without reaching into parser internals. - var referencedSyms = new HashSet(); - foreach (var g in state.GrepBlocks.Values) - foreach (var instance in g.Instances) - if (instance.SymbolElemId > 0) referencedSyms.Add((uint)instance.SymbolElemId); - foreach (var kv in state.GrepBlocks) - if ((state.WideSchema == null || state.R22View) && (kv.Value.Faces.Count >= 4 || referencedSyms.Contains(kv.Key)) - && !state.ElemTable.ContainsKey(kv.Key) - && !state.Records.ContainsKey(kv.Key)) - state.BlockOnlyIds.Add(kv.Key); + if (state.WideSchema == null || state.R22View) + { + var referencedSyms = state.GrepBlocks.ReferencedSymbols().ToHashSet(); + foreach (uint id in state.GrepBlocks.BlockOnlyCandidates(referencedSyms)) + if (!state.ElemTable.ContainsKey(id) && !state.Records.ContainsKey(id)) + state.BlockOnlyIds.Add(id); + } // FamilySymbol.m_complexCutGeoms can be the only decoded block for a definition. // Keep that definition in the model so an instance's exact serialized SymbolId can // resolve the cutter without relying on category/name/reference inference. @@ -793,11 +791,50 @@ private RevitFileInfo ReadCore(RootStorage root) && !state.Records.ContainsKey(familySymbolId)) state.BlockOnlyIds.Add(familySymbolId); + long elementJobs = (long)state.ElemTable.Count + extraRecordIds.Count + state.BlockOnlyIds.Count; + long elementsBuilt = 0; + int archivedElements = 0; + var archiveGeometry = _options.ArchiveSceneGeometry; + var archiveParameters = _options.ArchiveSceneParameters; + var buildClock = progress == null ? null : System.Diagnostics.Stopwatch.StartNew(); + if (elementJobs > 0) progress?.Report(new("build-model", 0, elementJobs)); + + void ElementBuilt() + { + if (archiveGeometry != null || archiveParameters != null) + while (archivedElements < rvtInfo.Elements.Count) + { + var element = rvtInfo.Elements[archivedElements++]; + archiveGeometry?.Invoke(element); + archiveParameters?.Invoke(element); + } + if (buildClock == null) return; + if (++elementsBuilt == elementJobs || buildClock.ElapsedMilliseconds >= 500) + { + progress!.Report(new("build-model", elementsBuilt, elementJobs)); + buildClock.Restart(); + } + } + + foreach (uint elemId in state.ElemTable.Keys.Order()) + { + ElementBuilder.BuildElemTableElement(elemId, state.ElemTable[elemId], state, rvtInfo); + ElementBuilt(); + } + LogPhase("Elements built"); + foreach (var eid in extraRecordIds) + { + ElementBuilder.BuildDiscoveredElement(eid, state, rvtInfo); + ElementBuilt(); + } + LogPhase("Discovered elements built"); + foreach (var bid in state.BlockOnlyIds) + { ElementBuilder.BuildBlockOnlyElement(bid, state, rvtInfo); + ElementBuilt(); + } - // Wall function extraction: scan all chunks for classIdx=0x00012100 blocks - ExtractWallFunctions(state); diag?.WriteLine($"Wall type functions: {state.WallTypeFunctions.Count} entries"); LogPhase("Block-only elements built"); @@ -808,13 +845,27 @@ private RevitFileInfo ReadCore(RootStorage root) "Local" or "Central" => true, _ => null, }; - ElementBuilder.PostProcess(rvtInfo, state, diag); + if (archiveGeometry != null) + state.ReleaseElementBuildInputs(); + const int finalizationPasses = 7; + int completedFinalizationPasses = 0; + progress?.Report(new("finalize-model", completedFinalizationPasses, finalizationPasses)); + Action? finalizationProgress = progress == null ? null : () => + progress.Report(new("finalize-model", ++completedFinalizationPasses, finalizationPasses)); + ElementBuilder.PostProcess(rvtInfo, state, diag, finalizationProgress); + finalizationProgress?.Invoke(); + if (state.PartitionScratch != null) + { + // Geometry and its cutters have been resolved into the elements. A scratch-backed + // read does not retain ParsingState for diagnostics after it returns. + state.GrepBlocks.Clear(); + state.FamilyCutGreps.Clear(); + } if (state.GridAxes is { } axes) { rvtInfo.CurvedGridAxes = axes.Paths; rvtInfo.GridChainMemberIds = axes.Members; } - progress?.Report(new("finalize-model")); LogPhase("Post-processed"); ElementBuilder.ApplyValidatedStairComponentTypeNames(rvtInfo.Elements, state); ElementBuilder.ApplyValidatedCorniceTypeNames(rvtInfo.Elements, state); @@ -835,12 +886,13 @@ private RevitFileInfo ReadCore(RootStorage root) int systemFamilyTypes = ElementBuilder.ApplyValidatedSystemFamilyNames(rvtInfo.Elements, state, familyNames); ReadCompactLookupText(rvtInfo); ElementBuilder.ApplyValidatedStairOccurrenceNames(rvtInfo.Elements, familyNames); - ElementBuilder.ApplyHostLabels(rvtInfo, systemFamilyNames, state.ElemClassIdx); - ElementBuilder.ApplyWorkPlaneLabels(rvtInfo, systemFamilyNames); + ElementBuilder.ApplyHostLabels(rvtInfo, systemFamilyNames, state.ElemClassIdx, archiveParameters); + ElementBuilder.ApplyWorkPlaneLabels(rvtInfo, systemFamilyNames, archiveParameters); ElementBuilder.ApplyColumnLocationMarks(rvtInfo, state.OwnDocumentUnitOptions?.Value, state.ElemClassIdx); ElementBuilder.ApplyMepSystemParams(rvtInfo, state, systemFamilyNames); ElementBuilder.ApplyConnectorGraph(rvtInfo, state); ElementBuilder.ApplyStairNameParameterScopes(rvtInfo.Elements, state); + finalizationProgress?.Invoke(); diag?.WriteLine($"System family names: locale={rvtInfo.Metadata.SavedLocale ?? "?"}, " + $"resources={(systemFamilyNames != null ? "loaded" : "unavailable")}, types={systemFamilyTypes}"); LogPhase("Names and parameters applied"); @@ -883,7 +935,7 @@ private RevitFileInfo ReadCore(RootStorage root) diag?.WriteLine($"Framed type references: {typeLinks} corrected"); } rvtInfo.ElementIds = ids; - rvtInfo.AttachSourceElementIds(); + rvtInfo.AttachSourceElementIds(archiveParameters); var (exportIds, replacedUniqueIds) = ElementBuilder.ApplyExportIds(rvtInfo.Elements, state); diag?.WriteLine($"Element export ids: episodes={state.HistoryEpisodeGuids.Count}/{state.EpisodeTableX?.ToString() ?? "?"}, " + $"records={state.ElemRecHistories?.Count.ToString() ?? "unavailable"}, elements={exportIds}, " @@ -891,6 +943,7 @@ private RevitFileInfo ReadCore(RootStorage root) diag?.WriteLine($"Wall height overrides: {ElementBuilder.WallHeightOverrides}, skipped-no-elev: {ElementBuilder.WallHeightSkippedNoElev}; level-elev candidates: {state.LevelElevCandidates.Count}"); LogPhase("Export ids applied"); + finalizationProgress?.Invoke(); ResolveParameterUnits(rvtInfo, state); Parameter.ResolveZeroElementIds(rvtInfo, state); @@ -914,24 +967,63 @@ private RevitFileInfo ReadCore(RootStorage root) LogPhase("Done"); diag?.WriteLine($"Output: {rvtInfo.Elements.Count} elements, " + - $"{rvtInfo.Elements.Count(e => e.Parameters.Count > 0)} with params, " + + $"{rvtInfo.Elements.Count(e => e.ReadParameters.Count > 0)} with params, " + $"{rvtInfo.Elements.Count(e => e.Geometry != null)} with geometry"); int sketchOwners = rvtInfo.Elements.Count(e => e.SketchLoops != null); if (sketchOwners > 0) diag?.WriteLine($"Sketch topology: {sketchOwners} owners, " + $"{rvtInfo.Elements.Where(e => e.SketchLoops != null).Sum(e => e.SketchLoops!.Count)} loops"); - rvtInfo.UserParameters = UserParameterCatalog.Build(state); + // Paged scenes take their properties from the resolved element parameters. + // The catalog serves compact export and sheets, and duplicates decoded values. + if (state.KeepExportProvenance) + rvtInfo.UserParameters = UserParameterCatalog.Build(state); + finalizationProgress?.Invoke(); return (rvtInfo, state); } + private static void ScanElementStrings(PartitionChunks chunks, ParsingState state, IProgress? progress) + { + if (chunks.Count == 0) return; + const int batchSize = 16; + // ScanChunk emits only valid names and rejects Autodesk identifiers. The scene parser + // uses the first valid scan name for element names and missing parameter captions. + bool firstNameOnly = !state.KeepExportProvenance; + var partialResults = new Dictionary>?[Math.Min(batchSize, chunks.Count)]; + var seen = firstNameOnly ? null : new Dictionary>(); + var clock = progress == null ? null : System.Diagnostics.Stopwatch.StartNew(); + progress?.Report(new("element-properties", 0, chunks.Count)); + for (int start = 0; start < chunks.Count;) + { + int first = start; + int count = Math.Min(partialResults.Length, chunks.Count - first); + // Keep both memory use and merge order independent of task completion order. + Parallel.For(0, count, index => + { + var localStrings = new Dictionary>(); + StringScanner.ScanChunk(chunks[first + index], state.AllKnownIds, localStrings, firstNameOnly); + if (localStrings.Count > 0) partialResults[index] = localStrings; + }); + MergeElemScanStringsInChunkOrder(partialResults, state.ElemScanStrings, seen, firstNameOnly); + Array.Clear(partialResults); + start += count; + if (clock != null && (start == chunks.Count || clock.ElapsedMilliseconds >= 500)) + { + progress!.Report(new("element-properties", start, chunks.Count)); + clock.Restart(); + } + } + } + internal static void MergeElemScanStringsInChunkOrder( IReadOnlyList>?> partialResults, - Dictionary> elemScanStrings) + Dictionary> elemScanStrings, + Dictionary>? mergeSeen = null, + bool firstNameOnly = false) { // HashSet-backed dedupe: rebar-heavy models attribute thousands of strings per // element, and List.Contains per insert made this merge quadratic. - var mergeSeen = new Dictionary>(); + if (!firstNameOnly) mergeSeen ??= new(); for (int chunkIndex = 0; chunkIndex < partialResults.Count; chunkIndex++) { var partial = partialResults[chunkIndex]; @@ -939,9 +1031,14 @@ internal static void MergeElemScanStringsInChunkOrder( foreach (var (eid, strings) in partial) { + if (firstNameOnly) + { + elemScanStrings.TryAdd(eid, strings); + continue; + } if (!elemScanStrings.TryGetValue(eid, out var list)) elemScanStrings[eid] = list = new List(); - if (!mergeSeen.TryGetValue(eid, out var seen)) + if (!mergeSeen!.TryGetValue(eid, out var seen)) mergeSeen[eid] = seen = new HashSet(list); foreach (var s in strings) if (seen.Add(s)) list.Add(s); @@ -985,7 +1082,7 @@ internal static void MergeElemScanStringsInChunkOrder( } if (ids != null && !r22View) { - chunks = chunks.Skip(partitionChunkCount).ToList(); + chunks = chunks.Select(Enumerable.Range(partitionChunkCount, chunks.Count - partitionChunkCount)); partitionChunkCount = 0; } @@ -1341,12 +1438,12 @@ void Fail(string reason) diag?.WriteLine($"Wide document units: UnitsElem {document.UnitsElemId}, {options.Options.Length} format options, unit schemas {document.Units.Entries.Length}"); } - private List DecompressPartitions(RootStorage root, TextWriter? diag, + private PartitionChunks DecompressPartitions(RootStorage root, TextWriter? diag, out Dictionary? ownPartitionWallParts, out List> partitionStreams, out List framedStreams, out bool staleCopiesRemoved, out (IReadOnlyDictionary? Current, IReadOnlyDictionary? UnroutedTypePartitions) routes, - bool collectFamilyStorage = false, IProgress? progress = null) + bool collectFamilyStorage = false, IProgress? progress = null, PartitionChunks.Backing? backing = null) { staleCopiesRemoved = false; var partStor = root.OpenStorage("Partitions"); @@ -1358,13 +1455,13 @@ private List DecompressPartitions(RootStorage root, TextWriter? diag, progress?.Report(new("partitions", 0, partEntries.Count)); var decompressor = new ChunkDecompressor(); - var allChunks = new List(); + var allChunks = new PartitionChunks(backing); partitionStreams = new List>(); framedStreams = []; ownPartitionWallParts = null; var routing = partEntries.Count > 1 ? PlanRecordRouting(root, partStor, partEntries.Select(e => e.Name).ToList(), _options.ResolveCurrentCopies ? diag : null, - recoverTypeIds: collectFamilyStorage) + recoverTypeIds: collectFamilyStorage, streamInput: backing != null) : null; routes = (routing?.Current, routing?.UnroutedTypePartitions); // the exact framing of the partition streams (PartitionFraming), when the class table names its marker classes and the id width is known @@ -1380,8 +1477,7 @@ private List DecompressPartitions(RootStorage root, TextWriter? diag, { diag?.WriteLine($"Partitions stream: '{partEntry.Name}' ({partEntry.Length:N0} bytes)"); using var partStream = partStor.OpenStream(partEntry.Name); - var raw = new byte[partStream.Length]; - partStream.ReadExactly(raw); + var raw = backing == null ? ReadRawPartition(partStream) : null; // shortcut: saved format9 with one partition stream; multi-stream scope needs its own load validation. if (partEntries.Count == 1 && partEntry.Name == "0") @@ -1390,23 +1486,25 @@ private List DecompressPartitions(RootStorage root, TextWriter? diag, var wallClasses = framingSchema == null ? null : OwnPartitionParts.ClassesOf(framingSchema); string? failure; ownPartitionWallParts = wallClasses != null && ElemTableLayout.IdWidth(framingSchema!) is int framingWidth - ? OwnPartitionParts.Read(raw, wallClasses, framingWidth, out failure) + ? raw == null ? OwnPartitionParts.Read(partStream, wallClasses, framingWidth, out failure) + : OwnPartitionParts.Read(raw, wallClasses, framingWidth, out failure) : Fail("the schema lacks the framing or wall classes", out failure); diag?.WriteLine($" Own partition wall parts: {ownPartitionWallParts?.Count.ToString() ?? "unavailable"} ({failure ?? "exact"})"); } - var chunks = CutPartition(raw, framing, decompressor, out var stats, out string? framingFailure, out var framed, entityCellTag); + var chunks = CutPartitionCore(raw, partStream, framing, decompressor, out var stats, out string? framingFailure, + out var framed, entityCellTag, backing, partEntry.Name); int? partitionNumber = int.TryParse(partEntry.Name, out int parsedPartition) ? parsedPartition : null; if (framed != null && partitionNumber is int partNum) framed = framed with { Partition = partNum }; - RecordStream("Partitions/" + partEntry.Name, raw.Length, stats.Members, stats.Decoded, stats.Failed, stats.Recovered, stats.Unverified, - chunks.Sum(chunk => (long)chunk.Length)); + RecordStream("Partitions/" + partEntry.Name, partStream.Length, stats.Members, stats.Decoded, stats.Failed, stats.Recovered, stats.Unverified, + Enumerable.Range(0, chunks.Count).Sum(index => (long)PartitionChunks.LengthAt(chunks, index))); diag?.WriteLine(framingFailure == null ? $" Chunks: {chunks.Count} segments of the exact framing" : $" Chunks: {chunks.Count} decompressed by a search for gzip members (framing: {framingFailure})"); if (_options.ResolveCurrentCopies && routing != null && partitionNumber is int pruningPartition && RecordRouting.Stale(routing.Census, routing.Current, pruningPartition) is { Count: > 0 } stale) { - if (RecordRouting.Prune(chunks, routing.Census.SegmentLengths[pruningPartition], stale) is { } pruned) + if (RecordRouting.PrunePartition(chunks, routing.Census.SegmentLengths[pruningPartition], stale) is { } pruned) { chunks = pruned; staleCopiesRemoved = true; @@ -1428,21 +1526,37 @@ private List DecompressPartitions(RootStorage root, TextWriter? diag, private static Dictionary? Fail(string reason, out string? failure) { failure = reason; return null; } + private static byte[] ReadRawPartition(Stream stream) + { + stream.Position = 0; + var raw = new byte[stream.Length]; + stream.ReadExactly(raw); + return raw; + } + /// The chunks of a partition stream: when its framing holds (), the output of each segment, every one a /// gzip member checked by its CRC and length, and null; otherwise the members a search for gzip headers /// finds, with the recovery of damaged ones (), and the reason the framing does not hold. - internal static List CutPartition(byte[] raw, (PartitionFraming.Tags Tags, int IdWidth)? framing, ChunkDecompressor decompressor, + internal static IReadOnlyList CutPartition(byte[] raw, (PartitionFraming.Tags Tags, int IdWidth)? framing, ChunkDecompressor decompressor, out (int Members, int Decoded, int Failed, int Recovered, int Unverified) stats, out string? framingFailure, out PartitionFraming.Framed? framed, ushort? familyEntityCellTag = null) + => CutPartitionCore(raw, null, framing, decompressor, out stats, out framingFailure, out framed, familyEntityCellTag, null); + + private static PartitionChunks CutPartitionCore(byte[]? raw, Stream? stream, (PartitionFraming.Tags Tags, int IdWidth)? framing, + ChunkDecompressor decompressor, out (int Members, int Decoded, int Failed, int Recovered, int Unverified) stats, + out string? framingFailure, out PartitionFraming.Framed? framed, ushort? familyEntityCellTag, PartitionChunks.Backing? backing, + string? partition = null) { - var segments = new List(); + var segments = new PartitionChunks(backing); var items = new List(); var familyItems = new List(); var familyKeys = familyEntityCellTag.HasValue ? new HashSet(StringComparer.Ordinal) : null; byte[]? cellTagBytes = familyEntityCellTag is ushort tag ? BitConverter.GetBytes(tag) : null; framed = null; framingFailure = "the class table names no framing classes or the id width is not known"; - if (framing is var (tags, idWidth) && PartitionFraming.Walk(raw, tags, idWidth, r => + if (framing is var (tags, idWidth)) + { + void Collect(PartitionFraming.Record r) { if (r.Block == 0 && r.Owner != (idWidth == 8 ? ulong.MaxValue : uint.MaxValue)) items.Add(new(r.Channel, r.Owner, r.Offset, r.Item.Length)); @@ -1452,15 +1566,31 @@ internal static List CutPartition(byte[] raw, (PartitionFraming.Tags Tag if (r.Body.Span.IndexOf(cellTagBytes!) >= 0) familyItems.Add(new(r.Key, new(r.Channel, r.Owner, r.Offset, r.Item.Length))); } - }, out framingFailure, out _, null, segments)) - { - stats = (segments.Count, segments.Count, 0, 0, 0); - framed = new PartitionFraming.Framed(segments, items, idWidth) { FamilyEntityCandidates = familyItems, FamilyKeys = familyKeys }; - return segments; + } + bool exact; + if (raw == null) + exact = PartitionFraming.WalkStream(stream!, tags, idWidth, Collect, out framingFailure, out _, onSegment: segments.Add); + else + { + var resident = new List(); + exact = PartitionFraming.Walk(raw, tags, idWidth, Collect, out framingFailure, out _, segmentBytes: resident); + if (exact) foreach (var segment in resident) segments.Add(segment); + } + if (exact) + { + stats = (segments.Count, segments.Count, 0, 0, 0); + framed = new PartitionFraming.Framed(segments, items, idWidth) { FamilyEntityCandidates = familyItems, FamilyKeys = familyKeys }; + return segments; + } } - var chunks = decompressor.DecompressAll(raw); + // The gzip recovery scanner still requires one contiguous compressed partition. + if (raw == null && stream!.Length > Array.MaxLength) + throw RvtContainerCheck.ArrayLengthLimit("Partitions/" + partition, stream.Length); + var chunks = decompressor.DecompressAll(raw ?? ReadRawPartition(stream!)); stats = decompressor.LastStats; - return chunks; + var recovered = new PartitionChunks(backing); + foreach (var chunk in chunks) recovered.Add(chunk); + return recovered; } private sealed record RoutingPlan(RecordRouting.Census Census, Dictionary Current, @@ -1469,7 +1599,7 @@ private sealed record RoutingPlan(RecordRouting.Census Census, DictionaryThe current copy of every element that several partition streams hold (), or null with the /// reason in the diagnostics when the framing, the element table or the increment table does not decode. private static RoutingPlan? PlanRecordRouting(RootStorage root, Storage partStor, IReadOnlyList names, TextWriter? diag, - bool recoverTypeIds) + bool recoverTypeIds, bool streamInput) { var schema = FormatsSchema.TryRead(root); var census = RecordRouting.Begin(schema, out var failure); @@ -1483,9 +1613,9 @@ private sealed record RoutingPlan(RecordRouting.Census Census, Dictionary return new EpisodeTableParseResult { Guids = result, X = x, DetachGuid = detachGuid }; } - private static void ClassifyAndParseRecords(List chunks, ParsingState state, TextWriter? diag) + private static void ClassifyAndParseRecords(PartitionChunks chunks, ParsingState state, TextWriter? diag, + IProgress? progress = null) { - foreach (var chunk in chunks) + var records = new PartitionChunks(chunks.Store); + var other = new PartitionChunks(chunks.Store); + var fields = chunks.Store is { } backing ? new ElementRecordFieldStore(backing) : null; + var clock = progress == null ? null : System.Diagnostics.Stopwatch.StartNew(); + if (chunks.Count > 0) progress?.Report(new("element-records", 0, chunks.Count)); + for (int i = 0; i < chunks.Count; i++) { + var chunk = chunks[i]; bool hasRecords = RecordParser.ContainsAnchoredR22Record( chunk, state.AllKnownIds); bool isR25 = !hasRecords && RecordParser.ContainsAnchoredR25Record( @@ -1777,18 +1914,26 @@ private static void ClassifyAndParseRecords(List chunks, ParsingState st hasRecords |= isR25; if (hasRecords) { - state.RecordChunks.Add(chunk); + records.Add(chunks.Reference(i)); if (isR25) - RecordParser.ParseChunkR25(chunk, state); + RecordParser.ParseChunkR25(chunk, state, chunks, i, fields); else - RecordParser.ParseChunk(chunk, state); + RecordParser.ParseChunk(chunk, state, chunks, i, fields); } else { - state.NonRecordChunks.Add(chunk); + other.Add(chunks.Reference(i)); + } + if (clock != null && (i + 1 == chunks.Count || clock.ElapsedMilliseconds >= 500)) + { + progress!.Report(new("element-records", i + 1, chunks.Count)); + clock.Restart(); } } + fields?.Seal(); + state.RecordChunks = records; + state.NonRecordChunks = other; var extraCount = state.Records.Keys.Count(k => !state.ElemTable.ContainsKey(k)); diag?.WriteLine($"Records: {state.Records.Count} ({state.Records.Count - extraCount} in ElemTable + {extraCount} discovered)"); @@ -2392,11 +2537,13 @@ internal static void RecordCurtainPanelOrder( /// The drive curve of a family instance in a file with its own schema: the field walk of the root block names no pointer /// target, so its GLine (CurveDriver.m_pCrv: origin, direction, end parameters) is read by the Revit 2022 tail walk over the /// rewritten block (the rewrite keeps the bytes of that object). Only the keys the field walk cannot give are added. - internal static void AddDriveCurveFromRewrittenBlock(TfBlockDeserializer.NativeParams target, TfBlockDeserializer.NativeParams? tail) + internal static bool AddDriveCurveFromRewrittenBlock(TfBlockDeserializer.NativeParams target, TfBlockDeserializer.NativeParams? tail) { - if (tail == null) return; + if (tail == null) return false; + bool changed = false; foreach (var (key, value) in tail.DoubleFields) - if (key.StartsWith("87:m_pCrv.", StringComparison.Ordinal)) target.DoubleFields.TryAdd(key, value); + if (key.StartsWith("87:m_pCrv.", StringComparison.Ordinal)) changed |= target.DoubleFields.TryAdd(key, value); + return changed; } /// Hands the channel-102 records of the project's own block, one root object per @@ -2404,9 +2551,9 @@ internal static void AddDriveCurveFromRewrittenBlock(TfBlockDeserializer.NativeP /// of loaded families and byte runs inside other items, and each one counted as a second root of the element. The location line of a /// wall () is read from its root record once every root is counted. internal static void RecordFramedRoots(ParsingState state, - List<(byte[] Data, int Start, uint Size, ushort Class, uint Owner)>? unanchoredTypeRoots = null) + List<(PartitionFraming.Framed Frame, PartitionFraming.ProjectItem Item, ushort Class, uint Owner)>? unanchoredTypeRoots = null) { - var roots = new List<(byte[] Data, int Start, uint Size, ushort Class, uint Owner, int? Partition)>(); + var roots = new List<(PartitionFraming.Framed Frame, PartitionFraming.ProjectItem Item, ushort Class, uint Owner)>(); foreach (var frame in state.FramedPartitions!) foreach (var record in frame!.Items) { @@ -2414,25 +2561,28 @@ internal static void RecordFramedRoots(ParsingState state, uint owner = (uint)record.Owner; if (owner == 0 && !state.AllKnownIds.Contains(0)) continue; // the item [owner:4][checksum:4][size:4][class:2 ...][size:4] is the block layout the walk hands over - var (data, start, _) = frame.Bytes(record); + var (data, start, _) = frame.Bytes(record with { Length = 14 }); ushort classId = BitConverter.ToUInt16(data, start + 12); if (!state.ElemClassIdx.ContainsKey(owner)) state.ElemClassIdx[owner] = classId; - roots.Add((data, start, (uint)(record.Length - 16), classId, owner, frame.Partition)); + roots.Add((frame, record, classId, owner)); } // a file with its own class schema has the roots of its element index seeded already (ReadWideElementIndex): the record replaces // the seed where it is counted; a root the count leaves out, such as one whose rewrite failed (unknown tag), keeps it if (state.WideSchema != null) - foreach (var (_, _, _, classId, owner, _) in roots) + foreach (var (_, _, classId, owner) in roots) if (StairComponentSource.CountsClassRoot(state, classId, owner)) state.OwnedElementClassRoots.Remove(owner); - foreach (var (data, start, size, classId, owner, partition) in roots) + foreach (var (frame, record, classId, owner) in roots) { + var (data, start, _) = frame.Bytes(record); + uint size = (uint)(record.Length - 16); + int? partition = frame.Partition; StairComponentSource.Record(state, data, start, size, classId, owner); if (classId == 1012 && state.WideSchema == null || state.StaleCopiesRemoved && (classId is 2335 or 3971 || classId is 1005 or 3524 && partition is int partWithType && (state.IncrementRoutedPartitions?.TryGetValue(owner, out int currentTypePartition) != true || partWithType == currentTypePartition))) - unanchoredTypeRoots?.Add((data, start, size, classId, owner)); + unanchoredTypeRoots?.Add((frame, record, classId, owner)); if (classId == 3471) { RecordRoomNameSource(state, data, start, size, classId, owner); @@ -2454,8 +2604,12 @@ internal static void RecordFramedRoots(ParsingState state, || part == currentPartition)) RecordProjectPhaseOrderSource(state, data, start, size, classId, owner); } - foreach (var (data, start, size, classId, owner, _) in roots) - if (classId is 3524 or 361) RecordWallLocationLine(state, data, start, size, classId, owner); + foreach (var (frame, record, classId, owner) in roots) + if (classId is 3524 or 361) + { + var (data, start, _) = frame.Bytes(record); + RecordWallLocationLine(state, data, start, (uint)(record.Length - 16), classId, owner); + } if (!state.StaleCopiesRemoved) return; foreach (var frame in state.FramedPartitions) @@ -2478,11 +2632,11 @@ internal static void RecordFramedRoots(ParsingState state, state.CurrentFramedCategories[owner] = null; } if (unanchoredTypeRoots != null) - foreach (var (data, start, size, classId, owner, partition) in roots) + foreach (var (frame, record, classId, owner) in roots) if (classId == 1794 && state.CurrentFramedCategories.GetValueOrDefault(owner) == -2000150 && (state.IncrementRoutedPartitions?.TryGetValue(owner, out int currentPartition) != true - || partition == currentPartition)) - unanchoredTypeRoots.Add((data, start, size, classId, owner)); + || frame.Partition == currentPartition)) + unanchoredTypeRoots.Add((frame, record, classId, owner)); } /// Hands the channel-102 and 103 records of the project's own block (the root objects and the @@ -2495,7 +2649,7 @@ internal static void ParseFramedBlocks(ParsingState state, bool collectBlockOnly foreach (var record in frame!.Items) { if (record.Channel == 101 || record.Length < 18 || record.Owner > uint.MaxValue || record.Owner == 0 && !state.AllKnownIds.Contains(0)) continue; - var (data, start, copied) = frame.Bytes(record); + var (data, start, copied) = frame.Bytes(record, out var storedRecord); uint eid = (uint)record.Owner; int queued = pending.Count; BlockParser.ParseBlock(data, start, eid, (uint)(record.Length - 16), state.AllKnownIds.Contains(eid), state, collectBlockOnlyIds, pending); @@ -2504,10 +2658,17 @@ internal static void ParseFramedBlocks(ParsingState state, bool collectBlockOnly // records of one model, none of which changed the output); decode it once the geometry decoder is linear in the block size. if ((copied || record.Length - 16 > BlockParser.MaxBlockSize) && pending.Count > queued) pending.RemoveRange(queued, pending.Count - queued); + else if (state.PartitionScratch is { } backing) + for (int i = queued; i < pending.Count; i++) + { + var job = pending[i]; + var stored = storedRecord ?? new PartitionChunks.Block(job.Chunk, job.Start, (int)job.Size + 16, backing); + pending[i] = job with { Chunk = [], Stored = stored }; + } } } private static void RecoverFramedScheduleTypes(ParsingState state, - List<(byte[] Data, int Start, uint Size, ushort Class, uint Owner)> roots) + List<(PartitionFraming.Framed Frame, PartitionFraming.ProjectItem Item, ushort Class, uint Owner)> roots) { const string typeField = "m_dbViewTypeId"; foreach (var schedule in roots.Where(root => root.Class == 1012).GroupBy(root => root.Owner)) @@ -2521,8 +2682,10 @@ private static void RecoverFramedScheduleTypes(ParsingState state, // Without pruning, the remaining project copies must agree on the stored reference. int typeId = 0; - foreach (var (data, start, size, classId, _) in schedule) + foreach (var (frame, item, classId, _) in schedule) { + var (data, start, _) = frame.Bytes(item); + uint size = (uint)(item.Length - 16); if (!TfBlockDeserializer.TryExtractOwnElementClass(data, start, size, classId, out int ownId) || ownId != owner || TfBlockDeserializer.ExtractParams(data, start, size, classId) is not { } fields @@ -2537,8 +2700,9 @@ private static void RecoverFramedScheduleTypes(ParsingState state, if (typeId <= 0 || state.WalkedElementClassRoots.GetValueOrDefault((uint)typeId) is not { BlockCount: 1, ClassId: 1020 }) continue; - if (native == null) state.NativeParams.Add(owner, native = new()); + native ??= new(); native.Fields[typeField] = typeId; + state.NativeParams[owner] = native; } } @@ -2555,13 +2719,16 @@ internal static void RunTfStreamWalk(ParsingState state, IProgress(); + var walkGReps = new List<(PartitionChunks.Block Block, uint Size, uint Eid)>(); + // Scratch-backed blocks retain only their ranges. Keep candidates until the walk + // has counted their owners' roots, avoiding a second pass over the partition. + List? wallGReps = state.Chunks is PartitionChunks { Store: not null } ? [] : null; // the roots the class and stair sources count: the records of the project's block when every stream is read by its framing bool framedRoots = state.ReadsFramedRecords; - List<(byte[] Data, int Start, uint Size, ushort Class, uint Owner)>? unanchoredTypeRoots = + List<(PartitionFraming.Framed Frame, PartitionFraming.ProjectItem Item, ushort Class, uint Owner)>? unanchoredTypeRoots = framedRoots ? [] : null; if (framedRoots) RecordFramedRoots(state, unanchoredTypeRoots); - TfStreamWalker.Walk(state.Chunks, state.AllKnownIds, (seg, bs, ds, cls, eid) => + TfStreamWalker.WalkLocated(state.Chunks, state.AllKnownIds, (seg, bs, ds, cls, eid, block) => { uint fullClassIdx = BitConverter.ToUInt32(seg, bs + 12); if (fullClassIdx is 0xFFFF0200 or 0xFFFF077B or 0xFFFF0286) @@ -2663,8 +2830,10 @@ internal static void RunTfStreamWalk(ParsingState state, IProgress ElementHeaderCategory.Record(state, seg, recordStart, eid), progress is null ? null : (completed, total) => progress.Report(new("parameter-stream", completed, total))); - progress?.Report(new("recover-geometry")); + const int recoveryPasses = 4; + int completedRecoveryPasses = 0; + progress?.Report(new("recover-geometry", completedRecoveryPasses, recoveryPasses)); + Action? recoveryProgress = progress == null ? null : (completed, total) => + progress.Report(new("recover-geometry", completedRecoveryPasses, recoveryPasses) + { GeometryBlocks = (completed, total) }); if (unanchoredTypeRoots != null) { RecoverFramedScheduleTypes(state, unanchoredTypeRoots); // Pruning can leave an element's own record where the sequential scan cannot anchor. - foreach (var (data, start, size, classId, owner) in unanchoredTypeRoots) + foreach (var (frame, item, classId, owner) in unanchoredTypeRoots) { if (classId == 1012 || state.NativeParamsFromRootClass.Contains(owner) || !state.WalkedElementClassRoots.TryGetValue(owner, out var root) - || root.BlockCount != 1 || root.ClassId != classId - || TfBlockDeserializer.ExtractParams(data, start, size, classId) is not { } parameters + || root.BlockCount != 1 || root.ClassId != classId) + continue; + var (data, start, _) = frame.Bytes(item); + uint size = (uint)(item.Length - 16); + if (TfBlockDeserializer.ExtractParams(data, start, size, classId) is not { } parameters || NativeTypePointers.Of(classId, parameters) is not int typeId || !state.AllKnownIds.Contains((uint)typeId)) continue; if (classId == 3524) @@ -2757,7 +2935,9 @@ internal static void RunTfStreamWalk(ParsingState state, IProgress 0 && !state.GrepBlocks.ContainsKey((uint)instance.SymbolElemId)) - missingIds.Add((uint)instance.SymbolElemId); + foreach (uint symbol in state.GrepBlocks.ReferencedSymbols()) + if (!state.GrepBlocks.ContainsKey(symbol)) missingIds.Add(symbol); foreach (var id in state.AllKnownIds) if (!state.GrepBlocks.ContainsKey(id)) missingIds.Add(id); foreach (var id in state.Records.Keys) @@ -2783,11 +2961,11 @@ internal static void RunTfStreamWalk(ParsingState state, IProgress 0 && !state.GrepBlocks.ContainsKey((uint)r)) missingIds.Add((uint)r); + int foundSketch = 0; + var scanGReps = new List<(PartitionChunks.Block Block, uint Size, uint Eid)>(); if (missingIds.Count > 0) { - int foundSketch = 0; - var scanGReps = new List<(byte[] Segment, int Start, uint Size, uint Eid)>(); - TfStreamWalker.ScanBlocks(state.Chunks, missingIds, (seg, bs, ds, cls, eid) => + TfStreamWalker.ScanLocated(state.Chunks, missingIds, (seg, bs, ds, cls, eid, block) => { if (dumpGrepEids.Count > 0 && dumpGrepEids.Contains(eid)) { @@ -2824,18 +3002,25 @@ internal static void RunTfStreamWalk(ParsingState state, IProgress 0) + { + int found = ApplyFirstDecodableGReps(state, scanGReps, recoveryProgress); DiagnosticSink.WriteLine($" [gscan] targeted scan recovered {found} G-blocks + {foundSketch} sketch curves for {missingIds.Count} candidate ids"); } - ReadOwnWallPlanarBodies(state); + scanGReps.Clear(); + progress?.Report(new("recover-geometry", ++completedRecoveryPasses, recoveryPasses)); + ReadOwnWallPlanarBodies(state, wallGReps, recoveryProgress); + progress?.Report(new("recover-geometry", ++completedRecoveryPasses, recoveryPasses)); } /// Decodes collected GRep blocks in parallel and stores, in collection order, the first decodable block of /// each element that has none yet. Returns the number stored. private static int ApplyFirstDecodableGReps( - ParsingState state, List<(byte[] Segment, int Start, uint Size, uint Eid)> jobs) + ParsingState state, List<(PartitionChunks.Block Block, uint Size, uint Eid)> jobs, Action? progress) { if (jobs.Count == 0) return 0; bool slowDiag = Environment.GetEnvironmentVariable("RVTIO_GREP_SLOW") is { Length: > 0 }; @@ -2845,21 +3030,24 @@ private static int ApplyFirstDecodableGReps( { var job = jobs[index]; var clock = slowDiag ? System.Diagnostics.Stopwatch.StartNew() : null; - var geometry = GRepParserV2.Parse(job.Segment, job.Start, job.Size); + var (data, start) = job.Block.Read(); + var geometry = GRepParserV2.Parse(data, start, job.Size); if (clock != null && (clock.ElapsedMilliseconds > 2000 || geometry?.Faces.Count > 100000)) DiagnosticSink.WriteLine($"slow GRep eid={job.Eid} ms={clock.ElapsedMilliseconds} faces={geometry?.Faces.Count}"); return geometry; }, (index, geometry) => { - if (StoreFirstDecodableGRep(state, jobs[index].Eid, geometry)) stored++; - }); + var job = jobs[index]; + if (StoreFirstDecodableGRep(state, job.Eid, geometry, job.Block, job.Size)) stored++; + }, progress); return stored; } /// Stores a decoded block for an element that has none yet; the first decodable block of an element wins. - internal static bool StoreFirstDecodableGRep(ParsingState state, uint eid, GRepData? geometry) => - geometry != null && state.GrepBlocks.TryAdd(eid, geometry); + internal static bool StoreFirstDecodableGRep(ParsingState state, uint eid, GRepData? geometry, + PartitionChunks.Block? block = null, uint size = 0) => + geometry != null && state.GrepBlocks.TryAdd(eid, geometry, state.PartitionScratch != null ? block : null, size); internal static void ParseBlocks(ParsingState state, TextWriter? diag, IProgress? progress = null) { @@ -2873,6 +3061,8 @@ void Lap(string name) lap.Restart(); progress?.Report(new("element-blocks", ++completedPasses, passCount)); } + Action? geometryProgress = progress == null ? null : (completed, total) => + progress.Report(new("element-blocks", completedPasses, passCount) { GeometryBlocks = (completed, total) }); // Expand known IDs with discovered record IDs foreach (var eid in state.Records.Keys) state.AllKnownIds.Add(eid); @@ -2932,29 +3122,37 @@ void Lap(string name) BlockParser.CollectViewPlanes(chunk, state); // The blocks of some views (a detail section, a wall section) sit in chunks that are neither a record nor a // data chunk of the classified lists: every remaining chunk is scanned too, so their planes are found. - var planeChunks = new HashSet(ReferenceEqualityComparer.Instance); - foreach (var chunk in state.NonRecordChunks) planeChunks.Add(chunk); - foreach (var chunk in state.RecordChunks) planeChunks.Add(chunk); - foreach (var chunk in state.Chunks) - if (planeChunks.Add(chunk)) - BlockParser.CollectViewPlanes(chunk, state); + if (state.Chunks is not PartitionChunks { Store: not null }) + { + var planeChunks = new HashSet(ReferenceEqualityComparer.Instance); + foreach (var chunk in state.NonRecordChunks) planeChunks.Add(chunk); + foreach (var chunk in state.RecordChunks) planeChunks.Add(chunk); + foreach (var chunk in state.Chunks) + if (planeChunks.Add(chunk)) + BlockParser.CollectViewPlanes(chunk, state); + } Lap("view planes"); // a file read by its framing or an unrewritten 64-bit file: skip the legacy 32-bit partition chunk scan bool framedBlocks = state.ReadsFramedRecords; bool skipPartitionScan = framedBlocks || (!state.R22View && state.WideSchema != null && WideElementRecords.IdWidth(state.WideSchema) == 8); - var partitionChunks = skipPartitionScan - ? state.Chunks.Take(state.PartitionChunkCount).ToHashSet(ReferenceEqualityComparer.Instance) : null; - bool Scanned(byte[] chunk) => partitionChunks?.Contains(chunk) != true; - // First pass: parse blocks, collect block-only IDs - var firstPassGReps = new List(); - if (framedBlocks) ParseFramedBlocks(state, collectBlockOnlyIds: true, firstPassGReps); - foreach (var chunk in state.NonRecordChunks.Where(Scanned)) - BlockParser.ParseChunk(chunk, state, collectBlockOnlyIds: true, deferred: firstPassGReps); - foreach (var chunk in state.RecordChunks.Where(Scanned)) - BlockParser.ParseChunk(chunk, state, collectBlockOnlyIds: true, deferred: firstPassGReps); - BlockParser.ApplyPendingGReps(state, firstPassGReps); + IReadOnlyList ScanChunks(IReadOnlyList list) + { + if (!skipPartitionScan) return list; + if (state.Chunks is PartitionChunks { Store: not null } stored && list is PartitionChunks selected) + { + var excluded = Enumerable.Range(0, state.PartitionChunkCount).Select(stored.Reference) + .ToHashSet(ReferenceEqualityComparer.Instance); + return selected.Select(Enumerable.Range(0, selected.Count).Where(i => !excluded.Contains(selected.Reference(i)))); + } + var partitionChunks = state.Chunks.Take(state.PartitionChunkCount).ToHashSet(ReferenceEqualityComparer.Instance); + return list.Where(chunk => !partitionChunks.Contains(chunk)).ToArray(); + } + var nonRecordScan = ScanChunks(state.NonRecordChunks); + var recordScan = ScanChunks(state.RecordChunks); + + ApplyPass(collectBlockOnlyIds: true); diag?.WriteLine($"Block-only elements: {state.BlockOnlyIds.Count}"); Lap("first parse pass"); @@ -2963,13 +3161,7 @@ void Lap(string name) { foreach (var bid in state.BlockOnlyIds) state.AllKnownIds.Add(bid); - var secondPassGReps = new List(); - if (framedBlocks) ParseFramedBlocks(state, collectBlockOnlyIds: false, secondPassGReps); - foreach (var chunk in state.NonRecordChunks.Where(Scanned)) - BlockParser.ParseChunk(chunk, state, deferred: secondPassGReps); - foreach (var chunk in state.RecordChunks.Where(Scanned)) - BlockParser.ParseChunk(chunk, state, deferred: secondPassGReps); - BlockParser.ApplyPendingGReps(state, secondPassGReps); + ApplyPass(collectBlockOnlyIds: false); } Lap("second parse pass"); diag?.WriteLine($"GRep blocks: {state.GrepBlocks.Count} elements"); @@ -2983,6 +3175,31 @@ void Lap(string name) if (state.ForgeParamSpecs.Count > 0) diag?.WriteLine($"ForgeId to spec mappings: {state.ForgeParamSpecs.Count} params"); + void ApplyPass(bool collectBlockOnlyIds) + { + var pending = new List(); + if (framedBlocks) ParseFramedBlocks(state, collectBlockOnlyIds, pending); + Scan(nonRecordScan); + Scan(recordScan); + BlockParser.ApplyPendingGReps(state, pending, geometryProgress); + + void Scan(IReadOnlyList chunks) + { + var segments = chunks as PartitionChunks; + for (int i = 0; i < chunks.Count; i++) + { + int first = pending.Count; + BlockParser.ParseChunk(chunks[i], state, collectBlockOnlyIds, pending); + if (segments?.Store == null) continue; + for (int j = first; j < pending.Count; j++) + { + var job = pending[j]; + if (segments.StoredBlock(i, job.Start, (int)job.Size + 16) is { } stored) + pending[j] = job with { Chunk = [], Stored = stored }; + } + } + } + } } /// @@ -3511,11 +3728,12 @@ internal sealed record ActiveProjectLocation( private static void ResolveParameterUnits(RevitFileInfo rvtInfo, ParsingState state) { - int resolved = 0; foreach (var elem in rvtInfo.Elements) { - foreach (var param in elem.Parameters) + int index = -1; + foreach (var param in elem.ReadParameters) { + index++; if (param.StorageType != StorageType.Double) continue; string? specType = null; @@ -3526,17 +3744,20 @@ private static void ResolveParameterUnits(RevitFileInfo rvtInfo, ParsingState st // 2. Resolve unit category from spec type or BIP name string? unitCat = specType != null ? GetUnitCategory(specType) : null; - if (unitCat == null && param.Definition?.Name != null) - unitCat = GetUnitCategoryFromBipName(param.Definition.Name); + if (unitCat == null && param.DefinitionName is { } name) + unitCat = GetUnitCategoryFromBipName(name); if (unitCat == null) continue; - param.SpecType = specType; var (symbol, factor) = GetUnitDisplay(unitCat); - param.UnitSymbol = symbol; - param.ConversionFactor = factor; - resolved++; + if (param.SpecType == specType && param.UnitSymbol == symbol && param.ConversionFactor == factor) + continue; + var editable = elem.Parameters[index]; + editable.SpecType = specType; + editable.UnitSymbol = symbol; + editable.ConversionFactor = factor; } + state.ArchiveSceneParameters?.Invoke(elem); } } diff --git a/src/RvtIO/RvtIO.csproj b/src/RvtIO/RvtIO.csproj index 25e3091f..b8322fc7 100644 --- a/src/RvtIO/RvtIO.csproj +++ b/src/RvtIO/RvtIO.csproj @@ -21,6 +21,7 @@ + diff --git a/src/RvtIO/RvtReaderOptions.cs b/src/RvtIO/RvtReaderOptions.cs index f4ccd07b..bc54e974 100644 --- a/src/RvtIO/RvtReaderOptions.cs +++ b/src/RvtIO/RvtReaderOptions.cs @@ -48,6 +48,14 @@ public class RvtReaderOptions /// Collects the streams read, how much of each decoded, and the limits that cut a stream. Null to collect nothing. public RvtReadDiagnostics? Diagnostics { get; set; } + /// Opens a private, empty, readable, writable and seekable scratch stream for inflated partition segments. + /// The reader owns the stream and disposes it when the read ends. Use storage outside managed memory to reduce the + /// working set. Null keeps the segments in memory. + public Func? CreatePartitionScratch { get; set; } + + internal Action? ArchiveSceneGeometry { get; set; } + internal Action? ArchiveSceneParameters { get; set; } + /// Receives phase and work-count updates from in the order the phases run. /// The reader calls synchronously on the thread that calls Read, one call at a time, and /// does not catch an exception the observer throws: it ends the read. instead posts each update to the diff --git a/src/RvtIO/Sheets/SheetCatalog.cs b/src/RvtIO/Sheets/SheetCatalog.cs index 5107b981..b5918e0c 100644 --- a/src/RvtIO/Sheets/SheetCatalog.cs +++ b/src/RvtIO/Sheets/SheetCatalog.cs @@ -119,7 +119,7 @@ public static SheetCatalog Extract(RevitFileInfo info) { if (!Compact.CompactUniverse.IsTableRow(element, info.ElemTableIsExact)) continue; if (element.LookupParameter(BuiltInParameter.VIEWPORT_DETAIL_NUMBER) == null) continue; - if (element.References is not { Count: > 0 } references) continue; + if (element.ReadReferences is not { Count: > 0 } references) continue; int sheetId = 0; foreach (int reference in references) { diff --git a/tests/RvtIO.Tests/AnalyticSolidMeasureTests.cs b/tests/RvtIO.Tests/AnalyticSolidMeasureTests.cs index 1e93d041..2ccba755 100644 --- a/tests/RvtIO.Tests/AnalyticSolidMeasureTests.cs +++ b/tests/RvtIO.Tests/AnalyticSolidMeasureTests.cs @@ -221,17 +221,29 @@ public void ShellMeasures_RequireAClosedShellAndEverySourceFace(bool complete, b }).ToList(), BrepSolids = [new GeoBrepSolid { IsClosed = closed, FaceIndices = [0, 1, 2, 3] }], MeshNodes = [new GeometryNode(7, 0, - Enumerable.Range(1, complete ? 4 : 5).Select(i => new BrFace { Marker = i, SurfaceKind = SurfaceKind.Plane, Loops = [] }).ToList(), 1) + Enumerable.Range(1, complete ? 4 : 5).Select(i => new BrFace + { Marker = i, SurfaceKind = i == 1 ? SurfaceKind.Cylinder : SurfaceKind.Plane, Loops = [] }).ToList(), 1) { SourceMeasures = (12, 5) }], }; - var shell = Assert.Single(BrepMeasures.ShellsOfCurrent(geometry)); - Assert.Equal(expected, shell.SourceMeasured); - Assert.Equal(expected ? 12 : 4, shell.Area, 12); - if (expected) + AssertMeasures(); + geometry.KeepSceneMeshNodeFacts(); + Assert.Null(geometry.MeshNodes); + Assert.Equal(1, geometry.MeshNodeCount); + Assert.True(geometry.HasCurvedFace([7])); + Assert.False(geometry.HasCurvedFace([8])); + AssertMeasures(); + + void AssertMeasures() { - Assert.Equal(5, shell.Volume, 12); - Assert.Equal(12, BrepMeasures.SurfaceAreaCurrent(geometry), 12); + var shell = Assert.Single(BrepMeasures.ShellsOfCurrent(geometry)); + Assert.Equal(expected, shell.SourceMeasured); + Assert.Equal(expected ? 12 : 4, shell.Area, 12); + if (expected) + { + Assert.Equal(5, shell.Volume, 12); + Assert.Equal(12, BrepMeasures.SurfaceAreaCurrent(geometry), 12); + } } } diff --git a/tests/RvtIO.Tests/BasicWallTypeSerializationTests.cs b/tests/RvtIO.Tests/BasicWallTypeSerializationTests.cs index 8e5d151c..5df0ebd4 100644 --- a/tests/RvtIO.Tests/BasicWallTypeSerializationTests.cs +++ b/tests/RvtIO.Tests/BasicWallTypeSerializationTests.cs @@ -128,7 +128,7 @@ public void BodyFunctionSentinel_UnvalidatedOrStoredConflictsAreNotRewritten(str var (element, state) = BodyFallback(1); var p = element.Parameters[0]; var native = state.NativeParams[100]; - var body = state.Records[100].BipParams; + var body = state.Records[100].EditFields().BipParams; switch (mutation) { case "duplicate_root": state.BasicWallTypeFunctions[100] = (2, 1); break; diff --git a/tests/RvtIO.Tests/BipParameterTests.cs b/tests/RvtIO.Tests/BipParameterTests.cs new file mode 100644 index 00000000..35ae476e --- /dev/null +++ b/tests/RvtIO.Tests/BipParameterTests.cs @@ -0,0 +1,32 @@ +using RvtIO.BuiltIns; +using RvtIO.Model; +using RvtIO.Parsing; +using Xunit; + +namespace RvtIO.Tests; + +public class BipParameterTests +{ + [Theory] + [InlineData("ALL_MODEL_MARK")] + [InlineData("Custom Mark")] + [InlineData(null)] + public void BuiltInParametersRetainTheirNamesAndHaveIndependentDefinitions(string? name) + { + const int id = (int)BuiltInParameter.ALL_MODEL_MARK; + var first = BipHelpers.MakeBipParam(id, name, StorageType.String, "first"); + var second = BipHelpers.MakeBipParam(id, name, StorageType.String, ""); + + Assert.Equal((id, name, name), first.DefinitionFields!.Value); + Assert.Equal((id, name, name), second.DefinitionFields!.Value); + Assert.Equal("first", first.Value); + Assert.Equal("", second.Value); + + first.Definition.Name = "Edited"; + + Assert.Equal("Edited", first.DefinitionName); + Assert.Equal(name, second.DefinitionName); + Assert.Equal((id, name, name), + BipHelpers.MakeBipParam(id, name, StorageType.String, null).DefinitionFields!.Value); + } +} diff --git a/tests/RvtIO.Tests/BlockDiagnosticTests.cs b/tests/RvtIO.Tests/BlockDiagnosticTests.cs index ed9ca8a0..f0acd805 100644 --- a/tests/RvtIO.Tests/BlockDiagnosticTests.cs +++ b/tests/RvtIO.Tests/BlockDiagnosticTests.cs @@ -52,7 +52,7 @@ public void BlocksFor100907() _output.WriteLine($"Output written to {TestFiles.Scratch("blocks_100907.txt")}"); } - private static int ScanChunksForBlocks(List chunks, uint targetElemId, StringBuilder sb, string label) + private static int ScanChunksForBlocks(IReadOnlyList chunks, uint targetElemId, StringBuilder sb, string label) { int blockCount = 0; @@ -753,7 +753,7 @@ public void InvestigateMissingRecords() sb.AppendLine(); sb.AppendLine($" --- Byte scan for {eid} (bytes: {BitConverter.ToString(eidBytes)}) ---"); - void ScanChunkList(List chunks, string label) + void ScanChunkList(IReadOnlyList chunks, string label) { int totalHits = 0; for (int ci = 0; ci < chunks.Count; ci++) diff --git a/tests/RvtIO.Tests/DerivedInstanceParamsTests.cs b/tests/RvtIO.Tests/DerivedInstanceParamsTests.cs index 705a052d..655a2ea6 100644 --- a/tests/RvtIO.Tests/DerivedInstanceParamsTests.cs +++ b/tests/RvtIO.Tests/DerivedInstanceParamsTests.cs @@ -604,9 +604,10 @@ public void DiagnosticInstanceQuantities_TakeTheFirstDetailLevelWithSolids() }; var uncertified = new Element { Id = 5, CategoryId = -2001330, NativeMasterSymbolId = 5, LevelSolidCounts = [1, 1, 1], LevelShells = new SolidQuantities.Shell?[3] }; var door = new Element { Id = 6, CategoryId = -2000023, NativeMasterSymbolId = 5, LevelSolidCounts = [1, 1, 1], LevelShells = shells }; - var classes = new Dictionary { [1] = 1794, [2] = 1794, [3] = 1829, [4] = 1794, [5] = 1794, [6] = 1794 }; + var unmeasured = new Element { Id = 7, CategoryId = -2001330, NativeMasterSymbolId = 5 }; + var classes = new Dictionary { [1] = 1794, [2] = 1794, [3] = 1829, [4] = 1794, [5] = 1794, [6] = 1794, [7] = 1794 }; - ElementBuilder.ApplyInstanceQuantities(new RevitFileInfo { Elements = [column, fixture, symbol, coped, uncertified, door] }, classes); + ElementBuilder.ApplyInstanceQuantities(new RevitFileInfo { Elements = [column, fixture, symbol, coped, uncertified, door, unmeasured] }, classes); Assert.Equal(2.0, Value(column, -1012806)); Assert.Null(Value(column, -1012805)); @@ -616,6 +617,9 @@ public void DiagnosticInstanceQuantities_TakeTheFirstDetailLevelWithSolids() Assert.Null(Value(coped, -1012806)); Assert.Null(Value(uncertified, -1012806)); Assert.Null(Value(door, -1012806)); + Assert.Null(unmeasured.LevelSolidCounts); + Assert.Null(unmeasured.LevelShells); + Assert.Null(Value(unmeasured, -1012806)); } [Fact] diff --git a/tests/RvtIO.Tests/ElemScanStringsMergeTests.cs b/tests/RvtIO.Tests/ElemScanStringsMergeTests.cs index 501da3a5..ea964e89 100644 --- a/tests/RvtIO.Tests/ElemScanStringsMergeTests.cs +++ b/tests/RvtIO.Tests/ElemScanStringsMergeTests.cs @@ -1,3 +1,4 @@ +using System.Text; using RvtIO.Internal; using RvtIO.Parsing; using Xunit; @@ -33,6 +34,49 @@ public void ResolveElementName_AfterReverseCompletion_PicksFirstSourceChunkCandi Assert.Equal(B, ElementBuilder.ResolveElementName(ElementId, state)); } + [Fact] + public void FirstNameOnly_PreservesTheFirstValidNameAcrossChunks() + { + byte[][] chunks = + [ + NameChunk("autodesk.parameter.invalid", B, Same), + NameChunk(A, Same, C), + ]; + var all = Scan(firstNameOnly: false); + var firstOnly = Scan(firstNameOnly: true); + Assert.Equal([B, Same, A, C], all[ElementId]); + Assert.Equal([B], firstOnly[ElementId]); + + Dictionary> Scan(bool firstNameOnly) + { + var partials = new Dictionary>[chunks.Length]; + for (int i = chunks.Length - 1; i >= 0; i--) + { + partials[i] = new(); + StringScanner.ScanChunk(chunks[i], [ElementId], partials[i], firstNameOnly); + } + + var names = new Dictionary>(); + foreach (var partial in partials) + RvtFileReader.MergeElemScanStringsInChunkOrder([partial], names, firstNameOnly: firstNameOnly); + return names; + } + + static byte[] NameChunk(params string[] names) + { + var bytes = new byte[256]; + using var stream = new MemoryStream(bytes); + using var writer = new BinaryWriter(stream, Encoding.Unicode); + writer.Write(ElementId); + foreach (string name in names) + { + writer.Write(name.Length); + writer.Write(Encoding.Unicode.GetBytes(name)); + } + return bytes; + } + } + private static Dictionary>?[] ReverseCompletedResults() { var partialResults = new Dictionary>?[2]; diff --git a/tests/RvtIO.Tests/ElementExportIdTests.cs b/tests/RvtIO.Tests/ElementExportIdTests.cs index 71b13074..9ac15f1a 100644 --- a/tests/RvtIO.Tests/ElementExportIdTests.cs +++ b/tests/RvtIO.Tests/ElementExportIdTests.cs @@ -86,26 +86,29 @@ public void BuildUniqueId_TakesTheEpisodeAnExternalDumpGivesTheElement() Assert.Null(ElementBuilder.BuildUniqueId(8, state)); // index beyond the dump's list } - [Fact] - public void ApplyExportIds_GivesTheUniqueIdOfTheElementHistoryAndNoneWithout() + [Theory] + [InlineData(true)] + [InlineData(false)] + public void ApplyExportIds_GivesTheUniqueIdOfTheElementHistoryAndNoneWithout(bool keepExportProvenance) { var episodes = new[] { Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid() }; var state = new ParsingState { + KeepExportProvenance = keepExportProvenance, HistoryEpisodeGuids = episodes.Select(g => g.ToString("D")).ToList(), EpisodeTableX = 3, // 5: created in the last episode; 6: renumbered from 4 in the first; 9: a creation date beyond the list. ElemRecHistories = new() { [5] = new(5, 0), [6] = new(4, 2), [9] = new(9, 3), [13] = new(-1, 0) }, }; var created = new Element { Id = 5 }; - var renumbered = new Element { Id = 6 }; + var renumbered = new Element { Id = 6, UniqueId = $"{episodes[0]:D}-00000006" }; var outsideList = new Element { Id = 9 }; var withoutRow = new Element { Id = 12 }; var invalidOriginal = new Element { Id = 13 }; var (applied, replaced) = ElementBuilder.ApplyExportIds([created, renumbered, outsideList, withoutRow, invalidOriginal], state); - Assert.Equal((2, 0), (applied, replaced)); + Assert.Equal((2, 1), (applied, replaced)); Assert.Equal($"{episodes[2]:D}-00000005", created.UniqueId); Assert.Equal(ElementExportIds.ExportId(episodes[2], 5), created.SerializedExportId); Assert.Equal($"{episodes[0]:D}-00000004", renumbered.UniqueId); @@ -119,14 +122,17 @@ public void ApplyExportIds_GivesTheUniqueIdOfTheElementHistoryAndNoneWithout() Assert.Null(invalidOriginal.SerializedExportId); } - [Fact] - public void ApplyExportIds_MatchesRevit2027ForAWallAboveUInt32() + [Theory] + [InlineData(true)] + [InlineData(false)] + public void ApplyExportIds_MatchesRevit2027ForAWallAboveUInt32(bool keepExportProvenance) { // A generated two-wall model reopened in Revit 2027.2 and exported to IFC2x3. const long elementId = 4_295_967_297; const int key = int.MaxValue; var state = new ParsingState { + KeepExportProvenance = keepExportProvenance, HistoryEpisodeGuids = ["95db5b0a-a7bf-4747-af03-b1f5fe59fca1"], EpisodeTableX = 1, ElemRecHistories = new() { [key] = new(elementId, 0) }, @@ -140,6 +146,13 @@ public void ApplyExportIds_MatchesRevit2027ForAWallAboveUInt32() Assert.Equal(Guid.Parse("95db5b0a-a7bf-4747-af03-b1f4fe56bee0"), wall.SerializedExportId); Assert.Equal(wall.SerializedExportId, wall.SerializedHandleExportId); Assert.Equal("2LsriAfxz7Hwy3iVJ_LhxW", IfcExporter.ResolveExactElementGlobalId(wall, new HashSet())); + + state.ElemRecHistories!.Clear(); + Assert.Equal((0, 0), ElementBuilder.ApplyExportIds([wall], state)); + Assert.Null(wall.SerializedExportId); + Assert.Equal("95db5b0a-a7bf-4747-af03-b1f5fe59fca1-1000f4241", wall.UniqueId); + wall.UniqueId = "explicit identity"; + Assert.Equal("explicit identity", wall.UniqueId); } [Fact] diff --git a/tests/RvtIO.Tests/ElementHeaderBoundingBoxTests.cs b/tests/RvtIO.Tests/ElementHeaderBoundingBoxTests.cs index 6e07c8f1..e492777a 100644 --- a/tests/RvtIO.Tests/ElementHeaderBoundingBoxTests.cs +++ b/tests/RvtIO.Tests/ElementHeaderBoundingBoxTests.cs @@ -84,6 +84,7 @@ public void Reader_AcceptsTheStoredAbsenceOfAnOutline() Assert.NotNull(verdict); Assert.False(verdict.Present); Assert.Null(verdict.Box); + Assert.Same(verdict, ElementHeaderCategory.ReadBoundingBox(Record(AbsentBody()), 0)); } [Theory] @@ -195,11 +196,13 @@ public void Recorder_FollowsTheRecordsAndStaysUnknownOnDisagreement() ElementHeaderCategory.Record(state, Record(AbsentBody()), 0, 101); Assert.False(Assert.IsType(state.HeaderBoundingBoxes[101]).Present); } - [Fact] - public void Applier_PutsTheStoredOutlineOnTheElementAndClearsTheUnstoredOne() + [Theory] + [InlineData(true)] + [InlineData(false)] + public void Applier_PutsTheStoredOutlineOnTheElementAndClearsTheUnstoredOne(bool keepExportProvenance) { double[] box = [-1.0, -1.0, 0.0, 1.0, 1.0, 2.0]; - var state = new ParsingState(); + var state = new ParsingState { KeepExportProvenance = keepExportProvenance }; state.HeaderBoundingBoxes[100] = new ElementHeaderBox(true, box); state.HeaderBoundingBoxes[101] = new ElementHeaderBox(false, null); state.HeaderBoundingBoxes[102] = null; // the records disagree @@ -217,7 +220,8 @@ public void Applier_PutsTheStoredOutlineOnTheElementAndClearsTheUnstoredOne() Assert.False(disagreeing.BoundingBoxIsHeaderOutline); Assert.Equal([9, 9, 9, 9, 9, 9], disagreeing.BoundingBox); Assert.Equal([9, 9, 9, 9, 9, 9], unrecorded.BoundingBox); - Assert.Same(box, state.HeaderBoundingBoxes[103]!.Box); + if (keepExportProvenance) Assert.Same(box, state.HeaderBoundingBoxes[103]!.Box); + else Assert.Empty(state.HeaderBoundingBoxes); } [Fact] diff --git a/tests/RvtIO.Tests/ElementRecordFieldStoreTests.cs b/tests/RvtIO.Tests/ElementRecordFieldStoreTests.cs new file mode 100644 index 00000000..f73b2b22 --- /dev/null +++ b/tests/RvtIO.Tests/ElementRecordFieldStoreTests.cs @@ -0,0 +1,39 @@ +using RvtIO.Internal; +using RvtIO.Parsing; +using Xunit; + +namespace RvtIO.Tests; + +public class ElementRecordFieldStoreTests +{ + [Fact] + public void ArchivedFieldsCanBeReadBeforeAndAfterPageSeal() + { + using var scratch = new MemoryStream(); + var store = new ElementRecordFieldStore(new PartitionChunks.Backing(scratch)); + var record = new ElementRecord { ElemId = 1, Body = [1, 2, 3] }; + var fields = record.EditFields(); + fields.References.AddRange([23, 11, 23]); + fields.BipParams.AddRange([new(-1001203, "ALL_MODEL_MARK", 3, -1), new(50, null, 205, null)]); + fields.WritableParamIds.Add(50); + fields.EntryValues.AddRange([-1, 11, 0]); + record.ArchiveFields(store); + + Assert.Equal(fields.References, record.References); + Assert.Throws(() => record.EditFields()); + + var other = new ElementRecord { ElemId = 2 }; + other.EditFields().References.AddRange(Enumerable.Repeat(123u, 20_000)); + other.ArchiveFields(store); + store.Seal(); + Assert.True(scratch.Length > 64 * 1024); + Assert.Equal(20_000, other.References.Count); + + Assert.Equal(fields.References, record.References); + Assert.Equal(fields.BipParams, record.BipParams); + Assert.True(record.IsWritable(50)); + Assert.False(record.IsWritable(-1001203)); + Assert.Equal(fields.EntryValues, record.EntryValues); + Assert.Equal(new byte[] { 1, 2, 3 }, record.Body); + } +} diff --git a/tests/RvtIO.Tests/ElementValueStoreTests.cs b/tests/RvtIO.Tests/ElementValueStoreTests.cs new file mode 100644 index 00000000..caf44a05 --- /dev/null +++ b/tests/RvtIO.Tests/ElementValueStoreTests.cs @@ -0,0 +1,53 @@ +using RvtIO.Internal; +using RvtIO.Parsing; +using Xunit; + +namespace RvtIO.Tests; + +public class ElementValueStoreTests +{ + [Fact] + public void PagedBuildMapsKeepTypesOrderingAndTextAcrossPages() + { + using var scratch = new MemoryStream(); + var state = new ParsingState + { + KeepExportProvenance = false, + Chunks = new PartitionChunks(new PartitionChunks.Backing(scratch)), + }; + int[] signedKeys = [-1001203, int.MinValue, 19]; + state.ElemBipInts[0] = new() { [signedKeys[0]] = -1, [signedKeys[1]] = 42, [signedKeys[2]] = 0 }; + state.ElemBipInts[123] = new(); + state.ElemBipDoubles[13] = new() { [-1001100] = -0.0, [19] = double.PositiveInfinity }; + const uint unsignedKey = uint.MaxValue; + const string text = "Text\uD800"; + state.ElemParamStrings[1] = new() { [1] = new string('x', 70_000) }; + state.ElemParamStrings[2] = new() { [unsignedKey] = text, [2] = "" }; + + state.ArchiveElementValues(); + + Assert.Empty(state.ElemBipInts); + Assert.Empty(state.ElemBipDoubles); + Assert.Empty(state.ElemParamStrings); + Assert.True(scratch.Length > 64 * 1024); + Assert.True(state.TryReadBipInts(0, out var integers)); + Assert.Equal(signedKeys, integers.Keys); + Assert.Equal([-1, 42, 0], integers.Values); + Assert.True(state.TryReadBipInts(123, out var empty)); + Assert.Empty(empty); + Assert.False(state.TryReadBipInts(31, out _)); + Assert.True(state.TryReadBipDoubles(13, out var doubles)); + Assert.Equal(BitConverter.DoubleToInt64Bits(-0.0), BitConverter.DoubleToInt64Bits(doubles[-1001100])); + Assert.Equal(double.PositiveInfinity, doubles[19]); + Assert.True(state.TryReadParamStrings(2, out var strings)); + Assert.Equal([unsignedKey, 2u], strings.Keys); + Assert.Equal([text, ""], strings.Values); + Assert.True(state.TryReadParamStrings(1, out var large)); + Assert.Equal(70_000, large[1].Length); + Assert.True(state.TryReadParamStrings(2, out strings)); + Assert.Equal(text, strings[unsignedKey]); + + state.ReleaseElementBuildInputs(); + Assert.False(state.TryReadParamStrings(2, out _)); + } +} diff --git a/tests/RvtIO.Tests/ExactIfcStringParameterResolverTests.cs b/tests/RvtIO.Tests/ExactIfcStringParameterResolverTests.cs index ffae0f70..fc83511c 100644 --- a/tests/RvtIO.Tests/ExactIfcStringParameterResolverTests.cs +++ b/tests/RvtIO.Tests/ExactIfcStringParameterResolverTests.cs @@ -1,4 +1,5 @@ using RvtIO.Model; +using RvtIO.Scene; using Xunit; namespace RvtIO.Tests; @@ -31,6 +32,26 @@ public void ResolveReference_EmptyInstanceFallsThroughToTypeThenTypeSuffix() Assert.Equal("Type suffix", result.Value); } + [Fact] + public void ResolveReference_LeavesInstanceAndTypeParametersInScratch() + { + using var stream = new MemoryStream(); + var scratch = new SceneMeshScratch(stream); + var instance = ElementWithParameter("Reference", StorageType.String, ""); + var type = ElementWithParameter("reference [type]", StorageType.String, "Type suffix"); + scratch.ArchiveParameters(instance); + scratch.ArchiveParameters(type); + var storedInstance = instance.ReadParameters; + var storedType = type.ReadParameters; + + var result = ExactIfcStringParameterResolver.ResolveReference(instance, type); + + Assert.Equal(ExactIfcStringParameterState.Value, result.State); + Assert.Equal("Type suffix", result.Value); + Assert.Same(storedInstance, instance.ReadParameters); + Assert.Same(storedType, type.ReadParameters); + } + [Theory] [InlineData(StorageType.Double, 12.5)] [InlineData(StorageType.Integer, 12)] diff --git a/tests/RvtIO.Tests/GRepBlockDecodeTests.cs b/tests/RvtIO.Tests/GRepBlockDecodeTests.cs index 83714cac..840456a6 100644 --- a/tests/RvtIO.Tests/GRepBlockDecodeTests.cs +++ b/tests/RvtIO.Tests/GRepBlockDecodeTests.cs @@ -84,6 +84,7 @@ public void DecodeGRepBlocks_InABrowserDecodesAndAppliesOneBlockAtATime() var applied = new List(); int caller = Environment.CurrentManagedThreadId; int retained = 0; + var updates = new List(); BlockParser.DecodeGRepBlocksInOrder(count, index => @@ -99,10 +100,20 @@ public void DecodeGRepBlocks_InABrowserDecodesAndAppliesOneBlockAtATime() retained--; applied.Add(index); }, - sequential: true); + sequential: true, + progress: (completed, total) => + { + Assert.Equal(caller, Environment.CurrentManagedThreadId); + Assert.Equal(count, total); + Assert.Equal(applied.Count, completed); + updates.Add(completed); + }); Assert.Equal(0, retained); Assert.Equal(Enumerable.Range(0, count), applied); + Assert.Equal(0, updates[0]); + Assert.Equal(count, updates[^1]); + Assert.Equal(updates.Distinct().Order(), updates); } [Fact] @@ -140,6 +151,25 @@ public void DecodeGRepBlocks_AFailedDecodeInABrowserPassesThroughAfterTheEarlier Solids = [new GRepSolid { IsClosed = true, FaceIndices = [0] }], }; + [Fact] + public void ApplyPendingGReps_ReportsStartAndCompletionOfItsPass() + { + var state = new ParsingState(); + var updates = new List<(int Completed, int Total)>(); + var pending = new List + { + new(new byte[16], 7, 0, 0, IsFamilyCut: false), + new(new byte[16], 8, 0, 0, IsFamilyCut: false), + }; + + BlockParser.ApplyPendingGReps(state, pending, (completed, total) => updates.Add((completed, total))); + + Assert.Equal((0, 2), updates[0]); + Assert.Equal((2, 2), updates[^1]); + Assert.All(updates, update => Assert.Equal(2, update.Total)); + Assert.Empty(state.GrepBlocks); + } + [Fact] public void ApplyPendingGRep_KeepsTheFirstAuthoredFamilyCutterOfAnElement() { diff --git a/tests/RvtIO.Tests/GRepParserV2Tests.cs b/tests/RvtIO.Tests/GRepParserV2Tests.cs index f6675564..0b6f5c04 100644 --- a/tests/RvtIO.Tests/GRepParserV2Tests.cs +++ b/tests/RvtIO.Tests/GRepParserV2Tests.cs @@ -69,9 +69,15 @@ public void ExplicitMappedRepresentation_WinsWithoutMixingSeparateResolvedFaces( Transform = [1, 0, 0, 0, 1, 0, 0, 0, 1, 10, 20, 30], }); - Assert.True(BlockParser.PreferExplicitMappedRepresentation(resolved, mapped)); - Assert.False(BlockParser.PreferExplicitMappedRepresentation(mapped, resolved)); - Assert.Null(BlockParser.PreferExplicitMappedRepresentation(mapped, mapped)); + foreach (bool mappedFirst in new[] { false, true }) + { + var state = new ParsingState(); + var job = new BlockParser.PendingGRep([], 7, 0, 0, IsFamilyCut: false); + BlockParser.ApplyPendingGRep(state, job, mappedFirst ? mapped : resolved); + BlockParser.ApplyPendingGRep(state, job, mappedFirst ? resolved : mapped); + Assert.Same(mapped, state.GrepBlocks[7]); + Assert.Empty(state.GrepBlocks[7].Faces); + } } [Theory] diff --git a/tests/RvtIO.Tests/HighElementIdParsingTests.cs b/tests/RvtIO.Tests/HighElementIdParsingTests.cs index 136ade80..16852dfb 100644 --- a/tests/RvtIO.Tests/HighElementIdParsingTests.cs +++ b/tests/RvtIO.Tests/HighElementIdParsingTests.cs @@ -22,6 +22,39 @@ public void RecordParser_AcceptsRepresentableElementIdAboveLegacyCeiling() Assert.True(state.Records.ContainsKey(ElementId)); } + [Theory] + [InlineData(false)] + [InlineData(true)] + public void RecordParser_RetainsTheExactBodyInItsAlreadyStoredSegment(bool r25) + { + byte[] body = [0xAD, 0x14, 0x02, 0xF8]; + int start = r25 ? 16 : 12; + byte[] chunk = new byte[start + body.Length + (r25 ? 4 : 0)]; + if (r25) + { + BitConverter.GetBytes(ElementId).CopyTo(chunk, 0); + BitConverter.GetBytes(body.Length).CopyTo(chunk, 12); + BitConverter.GetBytes(body.Length).CopyTo(chunk, start + body.Length); + } + else WriteRecord(chunk, 0, ElementId); + body.CopyTo(chunk, start); + + using var scratch = new MemoryStream(); + var chunks = new PartitionChunks(new PartitionChunks.Backing(scratch)); + chunks.Add(chunk); + var state = new ParsingState(); + state.AllKnownIds.Add(ElementId); + + if (r25) RecordParser.ParseChunkR25(chunk, state, chunks); + else RecordParser.ParseChunk(chunk, state, chunks); + + var record = state.Records[ElementId]; + byte[] first = record.Body; + Assert.Equal(body, first); + Assert.NotSame(first, record.Body); + Assert.Equal(chunk.Length, scratch.Length); + } + [Fact] public void RecordParser_AcceptsStructurallyAdjacentUnknownHighIds() { diff --git a/tests/RvtIO.Tests/MultiOutputExportTests.cs b/tests/RvtIO.Tests/MultiOutputExportTests.cs index 80f2498c..d4b2207c 100644 --- a/tests/RvtIO.Tests/MultiOutputExportTests.cs +++ b/tests/RvtIO.Tests/MultiOutputExportTests.cs @@ -213,6 +213,138 @@ public void MultiOutput_MissingPathOption_ExitsWithCode1(string option) } } + [Fact] + public void CopiedElementCanReplaceDrawingStairAndWallFactsIndependently() + { + var original = new RvtIO.Model.Element + { + Text = "Original", + ViewOrigin = [1, 2, 3], + SerializedStairTypeId = 42, + SerializedStairTypeLinkIsResolved = true, + SerializedStairCopyLevelIds = [10, 20], + OwnWallCutoutInstanceIds = [30, 40], + SerializedWallFlipped = false, + IsSerializedStackedWallType = true, + }; + var copy = original.ShallowCopy(); + + Assert.Same(original.ViewOrigin, copy.ViewOrigin); + Assert.Same(original.SerializedStairCopyLevelIds, copy.SerializedStairCopyLevelIds); + Assert.Same(original.OwnWallCutoutInstanceIds, copy.OwnWallCutoutInstanceIds); + copy.Text = null; + copy.ViewOrigin = null; + copy.SerializedStairTypeId = 17; + copy.SerializedStairTypeLinkIsResolved = false; + copy.OwnWallCutoutInstanceIds = null; + copy.SerializedWallFlipped = true; + copy.IsSerializedStackedWallType = false; + + Assert.Equal("Original", original.Text); + Assert.Equal([1d, 2d, 3d], original.ViewOrigin); + Assert.Equal(42, original.SerializedStairTypeId); + Assert.True(original.SerializedStairTypeLinkIsResolved); + Assert.Equal([30, 40], original.OwnWallCutoutInstanceIds); + Assert.False(original.SerializedWallFlipped); + Assert.True(original.IsSerializedStackedWallType); + Assert.Null(copy.Text); + Assert.Null(copy.ViewOrigin); + Assert.Equal(17, copy.SerializedStairTypeId); + Assert.False(copy.SerializedStairTypeLinkIsResolved); + Assert.Null(copy.OwnWallCutoutInstanceIds); + Assert.True(copy.SerializedWallFlipped); + Assert.False(copy.IsSerializedStackedWallType); + } + + [Fact] + public void CopiedElementCanReplaceMepRoomAndTypeFactsIndependently() + { + var original = new RvtIO.Model.Element + { + SerializedConnectorSystems = [0, 9], + SerializedMepSystem = ("Supply", 0), + SerializedPlanBoundary = [(1, 2), (3, 4)], + SerializedRoomIsLocationless = false, + SerializedRoomPlanAreaSquareFeet = 0, + SerializedSystemTypeId = 0, + ValidatedWindowTypeReferenceName = "Window type", + ValidatedWindowTypeReferenceIsExplicit = true, + }; + var copy = original.ShallowCopy(); + + Assert.Same(original.SerializedConnectorSystems, copy.SerializedConnectorSystems); + Assert.Same(original.SerializedPlanBoundary, copy.SerializedPlanBoundary); + Assert.Equal(("Supply", 0), copy.SerializedMepSystem); + Assert.False(copy.SerializedRoomIsLocationless); + Assert.Equal(0, copy.SerializedRoomPlanAreaSquareFeet); + Assert.Equal(0, copy.SerializedSystemTypeId); + + copy.SerializedConnectorSystems = null; + copy.SerializedMepSystem = null; + copy.SerializedPlanBoundary = null; + copy.SerializedRoomIsLocationless = true; + copy.SerializedSystemTypeId = null; + copy.ValidatedWindowTypeReferenceName = null; + copy.ValidatedWindowTypeReferenceIsExplicit = false; + + Assert.Equal([0, 9], original.SerializedConnectorSystems); + Assert.Equal(("Supply", 0), original.SerializedMepSystem); + Assert.Equal([(1d, 2d), (3d, 4d)], original.SerializedPlanBoundary); + Assert.False(original.SerializedRoomIsLocationless); + Assert.Equal(0, original.SerializedSystemTypeId); + Assert.Equal("Window type", original.ValidatedWindowTypeReferenceName); + Assert.True(original.ValidatedWindowTypeReferenceIsExplicit); + Assert.Null(copy.SerializedConnectorSystems); + Assert.Null(copy.SerializedMepSystem); + Assert.Null(copy.SerializedPlanBoundary); + Assert.True(copy.SerializedRoomIsLocationless); + Assert.Null(copy.SerializedSystemTypeId); + Assert.Null(copy.ValidatedWindowTypeReferenceName); + Assert.False(copy.ValidatedWindowTypeReferenceIsExplicit); + } + + [Fact] + public void CopiedElementCanReplaceCurveDriverAndPlacementFactsIndependently() + { + var original = new RvtIO.Model.Element + { + CurveDriverLineZ = (0, 3), + CurveDriverLineLength = 0, + InstanceOriginXY = (0, 0), + InstanceUsesOffsetPosition = false, + NativeStructuralType = 0, + FamilyLevelRefs = (4, 0, 5, 2), + }; + var copy = original.ShallowCopy(); + + Assert.Equal((0d, 3d), copy.CurveDriverLineZ); + Assert.Equal(0d, copy.CurveDriverLineLength); + Assert.Equal((0d, 0d), copy.InstanceOriginXY); + Assert.False(copy.InstanceUsesOffsetPosition); + Assert.Equal(0, copy.NativeStructuralType); + Assert.Equal((4, 0d, 5, 2d), copy.FamilyLevelRefs); + + copy.CurveDriverLineZ = null; + copy.CurveDriverLineLength = 10; + copy.InstanceOriginXY = (7, 9); + copy.InstanceUsesOffsetPosition = true; + copy.NativeStructuralType = null; + copy.FamilyLevelRefs = null; + + Assert.Equal((0d, 3d), original.CurveDriverLineZ); + Assert.Equal(0d, original.CurveDriverLineLength); + Assert.Equal((0d, 0d), original.InstanceOriginXY); + Assert.False(original.InstanceUsesOffsetPosition); + Assert.Equal(0, original.NativeStructuralType); + Assert.Equal((4, 0d, 5, 2d), original.FamilyLevelRefs); + Assert.Null(copy.CurveDriverLineZ); + Assert.Equal(10d, copy.CurveDriverLineLength); + Assert.Equal((7d, 9d), copy.InstanceOriginXY); + Assert.True(copy.InstanceUsesOffsetPosition); + Assert.Null(copy.NativeStructuralType); + Assert.Null(copy.FamilyLevelRefs); + } + [Fact] public void MultiOutput_RvtDocumentFromInfo_DoesNotMutateSourceInfo() { diff --git a/tests/RvtIO.Tests/NativeFieldDomainTests.cs b/tests/RvtIO.Tests/NativeFieldDomainTests.cs index 1373a63a..971e67dd 100644 --- a/tests/RvtIO.Tests/NativeFieldDomainTests.cs +++ b/tests/RvtIO.Tests/NativeFieldDomainTests.cs @@ -2,6 +2,7 @@ using RvtIO.Internal; using RvtIO.Model; using RvtIO.Parsing; +using RvtIO.Scene; using Xunit; namespace RvtIO.Tests; @@ -13,8 +14,27 @@ public class NativeFieldDomainTests private static Dictionary Classes(params (uint Id, ushort Class)[] items) => items.ToDictionary(i => i.Id, i => i.Class); - [Fact] - public void ParameterCreatedByTheTable_IsRemovedOutsideItsDomains_AndKeptInsideThem() + private static void Prune(RevitFileInfo info, IReadOnlyDictionary classes, bool paged) + { + using var stream = new MemoryStream(); + var effects = paged ? new NativeTableEffectsScratch(new PartitionChunks.Backing(stream)) : null; + if (effects != null) + { + foreach (var element in info.Elements) + { + effects.Archive(element); + Assert.Null(element.NativeTableAddedParams); + Assert.Null(element.NativeTableCreatedParams); + Assert.Null(element.NativeTablePrevious); + } + } + ElementBuilder.PruneNativeFieldTableOutsideDomains(info, classes, effectsScratch: effects); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void ParameterCreatedByTheTable_IsRemovedOutsideItsDomains_AndKeptInsideThem(bool paged) { var inside = new Element { Id = 1, CategoryId = -2000011 }; inside.Parameters.Add(P(-1006000, StorageType.Integer, 5)); @@ -30,7 +50,7 @@ public void ParameterCreatedByTheTable_IsRemovedOutsideItsDomains_AndKeptInsideT classWide.NativeTableCreatedParams = [-1006000]; var info = new RevitFileInfo { Elements = [inside, wrongCategory, classWide] }; - ElementBuilder.PruneNativeFieldTableOutsideDomains(info, Classes((1, 10), (2, 10), (3, 10))); + Prune(info, Classes((1, 10), (2, 10), (3, 10)), paged); Assert.Equal(5, Value(inside, -1006000)); Assert.Null(Value(wrongCategory, -1006000)); @@ -38,34 +58,41 @@ public void ParameterCreatedByTheTable_IsRemovedOutsideItsDomains_AndKeptInsideT Assert.Null(inside.NativeTableAddedParams); } - [Fact] - public void OverwrittenValue_IsGivenBack_WhenNoRowAppliesToTheFinalDomain() + [Theory] + [InlineData(false)] + [InlineData(true)] + public void OverwrittenValue_IsGivenBack_WhenNoRowAppliesToTheFinalDomain(bool paged) { var element = new Element { Id = 1, CategoryId = -2000023 }; element.Parameters.Add(P(-1006001, StorageType.String, "wrong")); element.NativeTableAddedParams = [(-1006001, ["10/-2000011"], StorageType.String, "wrong", false)]; - element.NativeTablePrevious = new() { [-1006001] = ("original", StorageType.String, false) }; + string original = new string('x', 40_000) + '\ud800'; + element.NativeTablePrevious = new() { [-1006001] = (original, StorageType.String, false) }; - ElementBuilder.PruneNativeFieldTableOutsideDomains(new RevitFileInfo { Elements = [element] }, Classes((1, 10))); + Prune(new RevitFileInfo { Elements = [element] }, Classes((1, 10)), paged); - Assert.Equal("original", Value(element, -1006001)); + Assert.Equal(original, Value(element, -1006001)); } - [Fact] - public void LaterPassValue_IsNotTouched() + [Theory] + [InlineData(false)] + [InlineData(true)] + public void LaterPassValue_IsNotTouched(bool paged) { var element = new Element { Id = 1, CategoryId = -2000023 }; element.Parameters.Add(P(-1006001, StorageType.String, "decided later")); element.NativeTableAddedParams = [(-1006001, ["10/-2000011"], StorageType.String, "table", false)]; element.NativeTablePrevious = new() { [-1006001] = ("original", StorageType.String, false) }; - ElementBuilder.PruneNativeFieldTableOutsideDomains(new RevitFileInfo { Elements = [element] }, Classes((1, 10))); + Prune(new RevitFileInfo { Elements = [element] }, Classes((1, 10)), paged); Assert.Equal("decided later", Value(element, -1006001)); } - [Fact] - public void InDomainRow_WinsOverALaterOutOfDomainRow() + [Theory] + [InlineData(false)] + [InlineData(true)] + public void InDomainRow_WinsOverALaterOutOfDomainRow(bool paged) { var element = new Element { Id = 1, CategoryId = -2000011 }; element.Parameters.Add(P(-1006002, StorageType.String, "")); @@ -75,13 +102,15 @@ public void InDomainRow_WinsOverALaterOutOfDomainRow() (-1006002, ["10/-2000016"], StorageType.String, "", false), ]; - ElementBuilder.PruneNativeFieldTableOutsideDomains(new RevitFileInfo { Elements = [element] }, Classes((1, 10))); + Prune(new RevitFileInfo { Elements = [element] }, Classes((1, 10)), paged); Assert.Equal("450x200", Value(element, -1006002)); } - [Fact] - public void NegativeElementIdOptionInNativeFieldTable_IsKeptInDomain_AndPrunedOutsideDomain() + [Theory] + [InlineData(false)] + [InlineData(true)] + public void NegativeElementIdOptionInNativeFieldTable_IsKeptInDomain_AndPrunedOutsideDomain(bool paged) { var inDomain = new Element { Id = 10, CategoryId = -2000150 }; var outOfDomain = new Element { Id = 11, CategoryId = -2000575 }; @@ -90,7 +119,15 @@ public void NegativeElementIdOptionInNativeFieldTable_IsKeptInDomain_AndPrunedOu var npOut = new TfBlockDeserializer.NativeParams(); npOut.Fields["174:m_centerlineTickMarkStyleId"] = -2; - var state = new ParsingState(); + using var partitionStream = new MemoryStream(); + using var sceneStream = new MemoryStream(); + var scratch = new SceneMeshScratch(sceneStream); + var state = new ParsingState + { + KeepExportProvenance = !paged, + Chunks = paged ? new PartitionChunks(new PartitionChunks.Backing(partitionStream)) : [], + ArchiveSceneParameters = paged ? scratch.ArchiveParameters : null, + }; state.ElemClassIdx[10] = 174; state.ElemClassIdx[11] = 174; state.NativeParams[10] = npIn; @@ -98,6 +135,7 @@ public void NegativeElementIdOptionInNativeFieldTable_IsKeptInDomain_AndPrunedOu var info = new RevitFileInfo { Elements = [inDomain, outOfDomain] }; ElementBuilder.PostProcess(info, state); + if (paged) Assert.True(partitionStream.Length > 0); var keptParam = Assert.Single(inDomain.Parameters, p => p.Id == -1006445); Assert.Equal(-2, keptParam.Value); diff --git a/tests/RvtIO.Tests/NativeParameterStoreTests.cs b/tests/RvtIO.Tests/NativeParameterStoreTests.cs new file mode 100644 index 00000000..e86f4d1d --- /dev/null +++ b/tests/RvtIO.Tests/NativeParameterStoreTests.cs @@ -0,0 +1,90 @@ +using RvtIO.Internal; +using RvtIO.Model; +using RvtIO.Parsing; +using Xunit; + +namespace RvtIO.Tests; + +public class NativeParameterStoreTests +{ + [Fact] + public void ScratchRoundTripPreservesOrderedValuesFlagsAndTypedEntities() + { + using var scratch = new MemoryStream(); + var store = new NativeParameterStore(new PartitionChunks.Backing(scratch)); + const string unpairedSurrogate = "\uD800"; + var parameter = new TfBlockDeserializer.NativeParams + { + RootParameterStoresComplete = true, + TailWalkComplete = true, + CellClasses = [17, 17, 42], + RoofExtrusionFaceTags = [], + ExtensibleStorage = [new ExtensibleStorageEntity(Guid.Empty, "schema", new Dictionary + { ["value"] = 7 })], + Doubles = { (1, -0.0), (1, double.NaN) }, + Ints = { (2, int.MinValue) }, + Strings = { (2, unpairedSurrogate), (2, "") }, + ElementIds = { (3, -1) }, + Fields = { ["count"] = 6 }, + DoubleFields = { ["length"] = double.PositiveInfinity }, + StringFields = { ["name"] = "Клапан" }, + NamedParams = { new(1, null, 1.5, -1, 3, true, false), new(2, "", -3, 2, 1, false, true) }, + }; + store[5] = parameter; + store[7] = new TfBlockDeserializer.NativeParams(); + + Assert.True(store.TryGetValue(5, out var restored)); + Assert.NotSame(parameter, restored); + Assert.True(restored.RootParameterStoresComplete); + Assert.True(restored.TailWalkComplete); + Assert.Equal(parameter.CellClasses, restored.CellClasses); + Assert.Empty(restored.RoofExtrusionFaceTags!); + Assert.Same(parameter.ExtensibleStorage, restored.ExtensibleStorage); + Assert.Equal(parameter.Doubles, restored.Doubles); + Assert.Equal(BitConverter.DoubleToInt64Bits(-0.0), BitConverter.DoubleToInt64Bits(restored.Doubles[0].Value)); + Assert.Equal(parameter.Ints, restored.Ints); + Assert.Equal(parameter.Strings, restored.Strings); + Assert.Equal(parameter.ElementIds, restored.ElementIds); + Assert.Equal(parameter.Fields, restored.Fields); + Assert.Equal(parameter.DoubleFields, restored.DoubleFields); + Assert.Equal(parameter.StringFields, restored.StringFields); + Assert.Equal(parameter.NamedParams, restored.NamedParams); + Assert.Equal(new uint[] { 5, 7 }, store.Select(entry => entry.Key)); + Assert.Null(store[7].CellClasses); + Assert.Null(store[7].RoofExtrusionFaceTags); + Assert.False(store.TryGetValue(9, out _)); + } + + [Fact] + public void ScratchUpdateReplacesTheRecordWithoutChangingItsOrder() + { + using var scratch = new MemoryStream(); + var store = new NativeParameterStore(new PartitionChunks.Backing(scratch)); + store[3] = new TfBlockDeserializer.NativeParams(); + store[5] = new TfBlockDeserializer.NativeParams(); + + var record = store[3]; + record.Fields["m_dbViewTypeId"] = 7; + store[3] = record; + + Assert.Equal(new uint[] { 3, 5 }, store.Keys); + Assert.Equal(7, store[3].Fields["m_dbViewTypeId"]); + } + + [Fact] + public void ReusingBufferKeepsSmallRecordsShortAfterALargeRecord() + { + using var scratch = new MemoryStream(); + var store = new NativeParameterStore(new PartitionChunks.Backing(scratch)); + store[1] = new TfBlockDeserializer.NativeParams(); + long emptySize = scratch.Length; + string largeValue = new('а', 100_000); + store[2] = new TfBlockDeserializer.NativeParams { Strings = { (10, largeValue) } }; + long largeEnd = scratch.Length; + store[3] = new TfBlockDeserializer.NativeParams(); + + Assert.Equal(emptySize, scratch.Length - largeEnd); + Assert.Equal(largeValue, Assert.Single(store[2].Strings).Value); + Assert.Empty(store[3].Strings); + } +} diff --git a/tests/RvtIO.Tests/NonVisibleQuantityGeometryTests.cs b/tests/RvtIO.Tests/NonVisibleQuantityGeometryTests.cs index 69a4874c..20eaed01 100644 --- a/tests/RvtIO.Tests/NonVisibleQuantityGeometryTests.cs +++ b/tests/RvtIO.Tests/NonVisibleQuantityGeometryTests.cs @@ -81,6 +81,27 @@ public void DoorArea_UsesQuantityViewForOwnOrNestedBodiesAndKeepsVisibleGeometry Assert.False(state.IncludeNonVisibleQuantities); } + [Fact] + public void ScratchDetailFlagsFollowNestedSymbolsWithoutReplayingGeometry() + { + using var stream = new MemoryStream(); + var backing = new PartitionChunks.Backing(stream); + // Only the decoded summary is meaningful here; replaying the bytes would fail. + var block = new PartitionChunks.Block([0], 0, 1, backing); + var blocks = new GRepBlockStore(); + blocks.Set(10, new GRepData { Instances = [new GRepInstance { SymbolElemId = 20 }] }, block, 1); + blocks.Set(20, new GRepData + { + Instances = [new GRepInstance { SymbolElemId = 10 }], + CoarseQuantities = new GRepData(), + Medium = new GRepData(), + }, block, 1); + + Assert.True(blocks.HasDetailAlternative(10, GRepBlockStore.DetailAlternatives.CoarseQuantities, [])); + Assert.True(blocks.HasDetailAlternative(10, GRepBlockStore.DetailAlternatives.Medium, [])); + Assert.False(blocks.HasDetailAlternative(10, GRepBlockStore.DetailAlternatives.Coarse, [])); + } + [Fact] public void SurfaceArea_CountsSourceSurfaceOnceAcrossFacetsAndSeparatelyAcrossNodes() { diff --git a/tests/RvtIO.Tests/OwnElementClassTests.cs b/tests/RvtIO.Tests/OwnElementClassTests.cs index 3b7c8ea0..32216c14 100644 --- a/tests/RvtIO.Tests/OwnElementClassTests.cs +++ b/tests/RvtIO.Tests/OwnElementClassTests.cs @@ -228,8 +228,57 @@ public void ParseBlocks_InTheRevit2022View_ReadsTheBlockBehindAHeaderLikeRunOfAn Assert.DoesNotContain(999u, state.BlockOnlyIds); } + [Theory] + [InlineData(false)] + [InlineData(true)] + public void ParseBlocks_KeepsTheLegacyScanOrderWithScratchSegments(bool storeSegments) + { + byte[] known = Frame(0x07D7), discovered = Frame(0x07D7); + BitConverter.GetBytes(456u).CopyTo(discovered, 0); + using var scratch = new MemoryStream(); + var segments = new PartitionChunks(storeSegments ? new PartitionChunks.Backing(scratch) : null); + segments.Add(known); + segments.Add(discovered); + var state = new ParsingState + { + AllKnownIds = [123], + Chunks = segments, + NonRecordChunks = segments, + }; + + RvtFileReader.ParseBlocks(state, null); + + Assert.Equal([456u], state.BlockOnlyIds); + Assert.Equal(4, state.BlockClassInventory[0x07D7].Count); + Assert.Equal(storeSegments ? known.Length + discovered.Length : 0, scratch.Length); + } + [Fact] - public void TheGeometryOfARecordThatRunsIntoTheNextSegmentOrIsOverTheSizeLimit_IsNotDecoded() + public void FramedScheduleRecoveryKeepsTheSourceRecordLocation() + { + byte[] schedule = Frame(1012); + using var scratch = new MemoryStream(); + var segments = new PartitionChunks(new PartitionChunks.Backing(scratch)); + segments.Add(schedule[..15]); + segments.Add(schedule[15..]); + var item = new PartitionFraming.ProjectItem(102, 123, 0, schedule.Length); + var frame = new PartitionFraming.Framed(segments, [item], 4); + var state = new ParsingState { AllKnownIds = [123], FramedPartitions = [frame] }; + var deferred = new List<(PartitionFraming.Framed Frame, PartitionFraming.ProjectItem Item, ushort Class, uint Owner)>(); + + RvtFileReader.RecordFramedRoots(state, deferred); + + var source = Assert.Single(deferred); + Assert.Same(frame, source.Frame); + Assert.Equal(item, source.Item); + Assert.Equal((1012, 123u), ((int)source.Class, source.Owner)); + Assert.Equal(schedule.Length, scratch.Length); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void TheGeometryOfARecordThatRunsIntoTheNextSegmentOrIsOverTheSizeLimit_IsNotDecoded(bool storeSegments) { byte[] crossing = Frame(0x07D7), whole = Frame(0x07D7); BitConverter.GetBytes(456u).CopyTo(whole, 0); @@ -241,10 +290,15 @@ public void TheGeometryOfARecordThatRunsIntoTheNextSegmentOrIsOverTheSizeLimit_I BitConverter.GetBytes((ushort)0x07D7).CopyTo(large, 12); BitConverter.GetBytes(size).CopyTo(large, 16 + (int)size - 4); byte[] stream = [.. crossing, .. whole, .. large]; + using var scratch = new MemoryStream(); + var segments = new PartitionChunks(storeSegments ? new PartitionChunks.Backing(scratch) : null); + segments.Add(stream[..10]); + segments.Add(stream[10..]); var state = new ParsingState { AllKnownIds = [123, 456, 789], - FramedPartitions = [new PartitionFraming.Framed([stream[..10], stream[10..]], + Chunks = segments, + FramedPartitions = [new PartitionFraming.Framed(segments, [new(103, 123, 0, crossing.Length), new(103, 456, crossing.Length, whole.Length), new(103, 789, crossing.Length + whole.Length, large.Length)], 4)], }; @@ -254,6 +308,15 @@ public void TheGeometryOfARecordThatRunsIntoTheNextSegmentOrIsOverTheSizeLimit_I Assert.Equal(3, state.BlockClassInventory[0x07D7].Count); Assert.Equal([456u], pending.Select(p => p.Eid)); + if (storeSegments) + { + Assert.Equal(stream.Length, scratch.Length); + var job = Assert.Single(pending); + Assert.Empty(job.Chunk); + var (data, start) = job.Stored!.Value.Read(); + Assert.Equal(0, start); + Assert.Equal(whole, data); + } } // TESTFILE.rvt is saved in five increments; reading it with and without the removal of the superseded copies changes the records around diff --git a/tests/RvtIO.Tests/ParameterValueFormattingTests.cs b/tests/RvtIO.Tests/ParameterValueFormattingTests.cs index 970c138d..c655245c 100644 --- a/tests/RvtIO.Tests/ParameterValueFormattingTests.cs +++ b/tests/RvtIO.Tests/ParameterValueFormattingTests.cs @@ -5,6 +5,58 @@ namespace RvtIO.Tests; public class ParameterValueFormattingTests { + [Fact] + public void DeferredBuiltInDefinitionRetainsIndependentMutabilityAndCloneSemantics() + { + var definition = new Parameter.DefinitionTemplate(-1001203, "ALL_MODEL_MARK"); + var first = new Parameter(definition) { Id = definition.Id, StorageType = StorageType.String, Value = "", HasNoRevitValue = true }; + var second = new Parameter(definition) { Id = definition.Id, StorageType = StorageType.String, Value = "", HasNoRevitValue = true }; + var clone = first.ShallowCopy("A-01"); + + Assert.Same(first.Definition, clone.Definition); + Assert.False(first.HasRevitValue); + second.Value = ""; + Assert.True(second.HasRevitValue); + first.Definition.Name = "Marker"; + Assert.Equal("Marker", clone.Definition.Name); + Assert.Equal("ALL_MODEL_MARK", second.Definition.Name); + Assert.Equal("ALL_MODEL_MARK", second.Definition.BuiltInParameter); + Assert.Equal(definition.Id, second.Definition.Id); + } + + [Fact] + public void OptionalMetadataRemainsIndependentAfterCopying() + { + var original = new Parameter + { + Guid = Guid.Empty, ForgeId = "forge", SpecType = "length", + UnitSymbol = "mm", ConversionFactor = 304.8, + StorageType = StorageType.ElementId, Value = 15, NativeElementId = 4294967311, + }; + var copy = original.ShallowCopy(original.Value); + + Assert.Equal(original.Guid, copy.Guid); + Assert.Equal(original.ForgeId, copy.ForgeId); + Assert.Equal(original.SpecType, copy.SpecType); + Assert.Equal(original.UnitSymbol, copy.UnitSymbol); + Assert.Equal(original.ConversionFactor, copy.ConversionFactor); + Assert.Equal(original.AsElementId64(), copy.AsElementId64()); + + copy.Guid = null; + copy.ForgeId = null; + copy.SpecType = "area"; + copy.UnitSymbol = "m²"; + copy.ConversionFactor = null; + copy.NativeElementId = null; + + Assert.Equal(Guid.Empty, original.Guid); + Assert.Equal("forge", original.ForgeId); + Assert.Equal("length", original.SpecType); + Assert.Equal("mm", original.UnitSymbol); + Assert.Equal(304.8, original.ConversionFactor); + Assert.Equal(4294967311, original.AsElementId64()); + } + [Fact] public void Parameter_AsValueString_CaseInsensitiveAndBipFallback() { diff --git a/tests/RvtIO.Tests/PartitionFramingFuzzTests.cs b/tests/RvtIO.Tests/PartitionFramingFuzzTests.cs index 742840b0..6f36263c 100644 --- a/tests/RvtIO.Tests/PartitionFramingFuzzTests.cs +++ b/tests/RvtIO.Tests/PartitionFramingFuzzTests.cs @@ -1,6 +1,7 @@ using System.Buffers.Binary; using OpenMcdf; using RvtIO.Parsing; +using RvtIO.Writing; using Xunit; namespace RvtIO.Tests; @@ -125,6 +126,167 @@ public void Walk_ChecksTheTagOfEveryPageTailBeforeItReadsARecord() } } + [Fact] + public void StreamWalkMatchesInflatedSegmentsAndChecksTrailingPageTails() + { + byte[] raw = PaddedLargeStream(); + var reference = new List(); + Assert.True(PartitionFraming.Walk(raw, FramingTags(), 4, _ => { }, out var failure, out _, segmentBytes: reference), failure); + using var input = new MemoryStream(raw, writable: false); + input.Position = input.Length; + var streamed = new List(); + Assert.True(PartitionFraming.WalkStream(input, FramingTags(), 4, _ => { }, out failure, out _, onSegment: streamed.Add), failure); + Assert.Equal(reference.Count, streamed.Count); + for (int i = 0; i < reference.Count; i++) Assert.Equal(reference[i], streamed[i]); + + raw[TailOffsets(raw.Length)[^1]] = 1; + Assert.False(PartitionFraming.WalkStream(input, FramingTags(), 4, _ => Assert.Fail("Unexpected record"), + out failure, out _, onSegment: _ => Assert.Fail("Unexpected segment"))); + Assert.Equal("page-framing", failure); + } + + [Fact] + public void StreamWalkSpansMemberBoundariesInsideTheRecordHeaderAndFooter() + { + var tags = FramingTags(); + using var raw = new MemoryStream(); + using var writer = new BinaryWriter(raw); + writer.Write(9UL); + writer.Write(tags.ContentMarker); + writer.Write(0U); + writer.Write(1U); + byte[] body = [12, 34, 56, 78, 90]; + for (uint channel = 101; channel <= 103; channel++) + { + using var item = new MemoryStream(); + using var itemWriter = new BinaryWriter(item); + itemWriter.Write(123U); + if (channel != 101) itemWriter.Write(456U); + itemWriter.Write(body.Length); + itemWriter.Write(body); + itemWriter.Write(body.Length); + byte[] bytes = item.ToArray(); + Member(bytes[..3], 2, false); + Member(bytes[3..^3], 3, false); + Member(bytes[^3..], 1, true); + + void Member(byte[] fragment, uint flags, bool last) + { + byte[] gzip = GzipMember.Write(fragment); + int size = gzip.Length + 8; + writer.Write(tags.SegmentMarker); + writer.Write(flags); + writer.Write(last ? 1 : 0); + writer.Write(size); + writer.Write(last ? body.Length : 0); + writer.Write(channel); + writer.Write(0U); + writer.Write(gzip); + writer.Write(tags.SegmentCheckback); + writer.Write(size); + } + } + writer.Write(tags.SegmentMarker); + writer.Write(new byte[16]); + writer.Write(tags.SignatureMarker); + writer.Write(0UL); + writer.Write(tags.ContentMarker); + writer.Write(0U); + writer.Write(uint.MaxValue); + + var reference = new List<(int Channel, long Offset, ulong Owner, byte[] Body)>(); + var streamed = new List<(int Channel, long Offset, ulong Owner, byte[] Body)>(); + Assert.True(PartitionFraming.Walk(raw.ToArray(), tags, 4, r => reference.Add((r.Channel, r.Offset, r.Owner, r.Body.ToArray())), + out var failure, out _), failure); + Assert.True(PartitionFraming.WalkStream(raw, tags, 4, r => streamed.Add((r.Channel, r.Offset, r.Owner, r.Body.ToArray())), + out failure, out _), failure); + Assert.Equal(3, streamed.Count); + for (int i = 0; i < streamed.Count; i++) + { + Assert.Equal((reference[i].Channel, reference[i].Offset, reference[i].Owner), + (streamed[i].Channel, streamed[i].Offset, streamed[i].Owner)); + Assert.Equal(reference[i].Body, streamed[i].Body); + } + } + + [Fact] + public void StreamWalkCanSeekToAPartitionBlockBeyondTenGiB() + { + var tags = FramingTags(); + const uint signatureBytes = 3_000_000_000; + const uint secondaryCount = 3_900_000_000; + using var head = new MemoryStream(); + using var writer = new BinaryWriter(head); + writer.Write(9UL); + writer.Write(tags.ContentMarker); + writer.Write(0UL); + writer.Write(tags.SegmentMarker); + writer.Write(new byte[16]); + writer.Write(tags.SignatureMarker); + writer.Write(signatureBytes); + long secondaryAt = head.Length + signatureBytes; + long nextBlock = secondaryAt + sizeof(uint) + 2L * secondaryCount; + Assert.True(nextBlock > 10L * 1024 * 1024 * 1024); + + using var trailer = new MemoryStream(); + using var tail = new BinaryWriter(trailer); + tail.Write(tags.ContentMarker); + tail.Write(uint.MaxValue); + tail.Write(tags.ContentKey); + tail.Write(0U); + tail.Write(new byte[16]); + tail.Write(tags.SegmentMarker); + tail.Write(new byte[16]); + tail.Write(tags.SignatureMarker); + tail.Write(0UL); + tail.Write(tags.ContentMarker); + tail.Write(0U); + tail.Write(uint.MaxValue); + + long end = nextBlock + trailer.Length; + using var input = new SparsePartitionStream(Physical(end - 1) + 1); + input.Set(0, head.ToArray()); + input.Set(secondaryAt, BitConverter.GetBytes(secondaryCount)); + input.Set(nextBlock, trailer.ToArray()); + Assert.True(PartitionFraming.WalkStream(input, tags, 4, _ => Assert.Fail("Unexpected record"), out var failure, out int blocks), failure); + Assert.Equal(2, blocks); + Assert.InRange(input.LargestRead, 1, PagedGzipStream.PageDataLength); + } + + private static long Physical(long logical) + => logical + logical / PagedGzipStream.PageDataLength * PagedGzipStream.SegmentLength; + + private sealed class SparsePartitionStream(long length) : Stream + { + private readonly Dictionary contents = []; + public override long Length => length; + public override long Position { get; set; } + public override bool CanRead => true; + public override bool CanSeek => true; + public override bool CanWrite => false; + internal int LargestRead { get; private set; } + + internal void Set(long offset, byte[] bytes) + { + for (int i = 0; i < bytes.Length; i++) contents[Physical(offset + i)] = bytes[i]; + } + + public override int Read(Span buffer) + { + int count = (int)Math.Min(buffer.Length, Length - Position); + LargestRead = Math.Max(LargestRead, count); + for (int i = 0; i < count; i++) buffer[i] = contents.GetValueOrDefault(Position + i); + Position += count; + return count; + } + + public override int Read(byte[] buffer, int offset, int count) => Read(buffer.AsSpan(offset, count)); + public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); + public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException(); + public override void Flush() { } + public override void SetLength(long value) => throw new NotSupportedException(); + } + [Fact] public void Walk_RejectsAStreamThatEndsInsideAPageTail() { diff --git a/tests/RvtIO.Tests/R22TranscoderTests.cs b/tests/RvtIO.Tests/R22TranscoderTests.cs index 69e957aa..dde63528 100644 --- a/tests/RvtIO.Tests/R22TranscoderTests.cs +++ b/tests/RvtIO.Tests/R22TranscoderTests.cs @@ -116,8 +116,10 @@ public void Payload_IdBeyond32BitsIsNotRewritten() Assert.Null(new R22Transcoder(Source(), Target(), 8).Payload(block, 0, block.Length)); } - [Fact] - public void Framed_RewritesTheBlocksOfTheProjectBlock_EachWholeInOneSegment_AndLeavesOutTheHeaders() + [Theory] + [InlineData(false)] + [InlineData(true)] + public void Framed_RewritesTheBlocksOfTheProjectBlock_EachWholeInOneSegment_AndLeavesOutTheHeaders(bool storeSegments) { var payload = Bytes(w => { w.Write((ushort)6); w.Write(1); w.Write(2); w.Write(77L); }); var unknown = Bytes(w => { w.Write((ushort)4); w.Write(1); }); @@ -135,7 +137,9 @@ byte[] Item(ulong owner, bool header, byte[] body) => Bytes(w => [new(101, 123, 0, header.Length), new(102, 123, header.Length, root.Length), new(103, 456, header.Length + root.Length, geometry.Length)], 8); var transcoder = new R22Transcoder(Source(), Target(), 8); - var framed = transcoder.Framed(source, out var stats)!; + using var scratch = new MemoryStream(); + var backing = storeSegments ? new PartitionChunks.Backing(scratch) : null; + var framed = transcoder.Framed(source, out var stats, backing)!; Assert.Equal(4, framed.IdWidth); Assert.Equal([(102, 123UL), (103, 456UL)], framed.Items.Select(i => (i.Channel, i.Owner))); @@ -154,6 +158,7 @@ byte[] Block(uint owner, byte[] body) => Bytes(w => Assert.False(copied); Assert.Equal(expected[i], data.AsSpan(start, framed.Items[i].Length).ToArray()); } + Assert.Equal(storeSegments ? expected.Sum(block => block.Length) : 0, scratch.Length); // a frame of another id width than the file's schema is not rewritten Assert.Null(transcoder.Framed(source with { IdWidth = 4 }, out _)); } @@ -236,13 +241,26 @@ public void Stream_SkipsAllPrunedRecordlessSectionAndRewritesFollowingSection() w.Write(0L); }); + byte[] suffix = [0xBC, 0xAD, 0xDE, 0x0A]; + byte[] input = [.. stream, .. suffix]; var transcoder = new R22Transcoder(Source(), Target(), 8); - _ = transcoder.Stream([stream], out var stats); + var expected = transcoder.Stream([input], out var contiguous); + using var scratch = new MemoryStream(); + var backing = new PartitionChunks.Backing(scratch); + var split = new PartitionChunks(backing); + // Every scalar, payload and separator crosses input segment boundaries. + foreach (byte value in input) { split.Add([]); split.Add([value]); } + var actual = transcoder.Stream(split, out var stats, backing); - Assert.Equal(0, stats.UnparsedBytes); + Assert.Equal(suffix.Length, stats.UnparsedBytes); Assert.Equal(stream.Length, stats.StoppedAt); + Assert.Equal("BCADDE0A", stats.StoppedBytes); + Assert.Equal(contiguous.StoppedAt, stats.StoppedAt); Assert.Equal(1, stats.Records); Assert.Equal(1, stats.RecordsRewritten); Assert.Empty(stats.Failures); + Assert.Equal(expected.Count, actual.Count); + for (int i = 0; i < expected.Count; i++) Assert.Equal(expected[i], actual[i]); + Assert.Equal(suffix, actual[^1]); } } diff --git a/tests/RvtIO.Tests/ReadProgressTests.cs b/tests/RvtIO.Tests/ReadProgressTests.cs index 8afede66..e4801342 100644 --- a/tests/RvtIO.Tests/ReadProgressTests.cs +++ b/tests/RvtIO.Tests/ReadProgressTests.cs @@ -85,6 +85,21 @@ public void ProjectFile_ReportsEveryPhaseOnceInOrderAndTheStreamBytes() Assert.Equal(new RvtReadProgress("parameter-stream"), stream[0]); Assert.True(stream.Length >= 3 && stream[^1].Total > 0 && stream[^1].Completed == stream[^1].Total); Assert.Equal(new RvtReadProgress("parameter-stream", 0, stream[^1].Total), stream[1]); + foreach (string phase in new[] { "element-records", "element-properties" }) + { + var scan = progress.Updates.Where(update => update.Phase == phase).ToArray(); + Assert.True(scan[^1].Total > 0); + Assert.Contains(new RvtReadProgress(phase, 0, scan[^1].Total), scan); + Assert.Equal(new RvtReadProgress(phase, scan[^1].Total, scan[^1].Total), scan[^1]); + } + var build = progress.Updates.Where(update => update.Phase == "build-model").ToArray(); + Assert.Equal(new RvtReadProgress("build-model"), build[0]); + Assert.Equal(new RvtReadProgress("build-model", 0, 1), build[1]); + Assert.Equal(new RvtReadProgress("build-model", 1, 1), build[^1]); + Assert.Equal(Enumerable.Range(0, 5).Select(pass => new RvtReadProgress("recover-geometry", pass, 4)), + progress.Updates.Where(update => update.Phase == "recover-geometry" && update.GeometryBlocks == null)); + Assert.Equal(Enumerable.Range(0, 8).Select(pass => new RvtReadProgress("finalize-model", pass, 7)), + progress.Updates.Where(update => update.Phase == "finalize-model")); } [Fact] diff --git a/tests/RvtIO.Tests/RvtSceneReaderTests.cs b/tests/RvtIO.Tests/RvtSceneReaderTests.cs index 33936f92..fd5581ac 100644 --- a/tests/RvtIO.Tests/RvtSceneReaderTests.cs +++ b/tests/RvtIO.Tests/RvtSceneReaderTests.cs @@ -1,8 +1,10 @@ using System.Globalization; +using System.Reflection; using IOScene; using RvtIO.BuiltIns; using RvtIO.Meshes; using RvtIO.Model; +using RvtIO.Parsing; using RvtIO.Scene; using Xunit; @@ -13,6 +15,328 @@ namespace RvtIO.Tests; /// incomplete geometry and those of a damaged read. public class RvtSceneReaderTests { + [Theory] + [InlineData(true)] + [InlineData(false)] + public void SceneNameCandidatesKeepElementAndParameterNamePriorities(bool keepExportProvenance) + { + var state = new RvtIO.Internal.ParsingState { KeepExportProvenance = keepExportProvenance }; + state.ElementNameTable[1] = "Table name"; + state.NativeElementNames[1] = "Native name"; + state.NativeElementNames[2] = "Native name"; + state.WideNames[2] = "Wide name"; + state.WideNames[3] = "Wide name"; + state.WideNames[4] = " "; + state.ElemStrings[1] = ["Block name", "&Block caption"]; + state.ElemStrings[4] = ["1234", "First block name", "Later block name"]; + state.ElemStrings[5] = ["1234", "autodesk.parameter.key"]; + state.ElemStrings[6] = ["&First caption", "&Later caption"]; + state.ElemScanStrings[4] = ["Scan name"]; + state.ElemScanStrings[5] = ["1234", "First scan name", "Later scan name"]; + state.ElemScanStrings[7] = ["&Scan caption"]; + state.ForgeParamDefs[1] = ("autodesk.parameter.key", "Forge caption"); + state.ForgeParamDefs[6] = ("autodesk.parameter.other", null); + + ElementBuilder.CompactSceneNameCandidates(state); + + Assert.Equal("Table name", ElementBuilder.ResolveElementName(1, state)); + Assert.Equal("Native name", ElementBuilder.ResolveElementName(2, state)); + Assert.Equal("Wide name", ElementBuilder.ResolveElementName(3, state)); + Assert.Equal("First block name", ElementBuilder.ResolveElementName(4, state)); + Assert.Equal("First scan name", ElementBuilder.ResolveElementName(5, state)); + Assert.Null(ElementBuilder.ResolveElementName(8, state)); + var captions = ElementBuilder.CollectParameterDefinitionNames(state); + Assert.Equal(2, captions.Count); + Assert.Equal("Forge caption", captions[1]); + Assert.Equal("First caption", captions[6]); + Assert.Equal(keepExportProvenance ? 4 : 0, state.ElemStrings.Count); + Assert.Equal(keepExportProvenance ? 3 : 0, state.ElemScanStrings.Count); + } + + [Fact] + public void EmptyPagedParametersRemainEditableWithoutWritingScratch() + { + using var stream = new MemoryStream(); + var scratch = new SceneMeshScratch(stream); + var first = new Element(); + var second = new Element(); + + scratch.ArchiveParameters(first); + scratch.ArchiveParameters(second); + + Assert.Same(Array.Empty(), first.ReadParameters); + Assert.Same(first.ReadParameters, second.ReadParameters); + Assert.Equal(0L, stream.Length); + + first.Parameters.Add(new Parameter { Id = 5, Value = 12, StorageType = StorageType.Integer }); + Assert.Empty(second.ReadParameters); + scratch.ArchiveParameters(first); + Assert.Equal(12, Assert.Single(first.ReadParameters).Value); + + first.Parameters.Clear(); + scratch.ArchiveParameters(first); + Assert.Same(second.ReadParameters, first.ReadParameters); + Assert.NotSame(first.Parameters, second.Parameters); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void TypeReferenceScanSkipsOnlyTheInstanceBeingResolved(bool paged) + { + var levelA = new Element { Id = 10, TypeId = 400, CategoryId = -2000240 }; + var levelB = new Element { Id = 11, TypeId = 400, CategoryId = -2000240 }; + levelA.Parameters.Add(new Parameter { Id = -1007102, Value = 4d, StorageType = StorageType.Double }); + var wall = new Element { Id = 12, TypeId = 400, CategoryId = -2000011, BoundingBox = [0, 0, 9, 1, 1, 12] }; + var nextWall = new Element { Id = 13, TypeId = 400, CategoryId = -2000011, BoundingBox = [0, 0, 10, 1, 1, 12] }; + var type = new Element { Id = 400 }; + type.SetReferences(Enumerable.Range(1000, 64).Prepend(levelB.Id).Prepend(levelA.Id), editable: !paged); + var info = new RevitFileInfo { Elements = [levelA, levelB, wall, nextWall, type] }; + using var stream = new MemoryStream(); + var scratch = new SceneMeshScratch(stream); + if (paged) + { + scratch.ArchiveGeometry(type); + scratch.ArchiveParameters(levelA); + } + var state = new RvtIO.Internal.ParsingState + { + KeepExportProvenance = !paged, + ArchiveSceneParameters = paged ? scratch.ArchiveParameters : null, + }; + + typeof(ElementBuilder).GetMethod("EnrichTypeLevelBips", BindingFlags.Static | BindingFlags.NonPublic)! + .Invoke(null, [info, state]); + + Assert.Equal(levelB.Id, FamilyLevel(levelA)); + Assert.Equal(levelA.Id, FamilyLevel(levelB)); + Assert.Equal(levelA.Id, FamilyLevel(wall)); + Assert.Equal(5d, Elevation(wall)); + Assert.Equal(6d, Elevation(nextWall)); + + static int FamilyLevel(Element element) => + Assert.IsType(Assert.Single(element.ReadParameters, parameter => parameter.Id == -1001352).Value); + static double Elevation(Element element) => + Assert.IsType(Assert.Single(element.ReadParameters, parameter => parameter.Id == -1001360).Value); + } + + [Fact] + public void CurveLengthsKeepStoredAndDerivedValuesOnParameterPages() + { + using var stream = new MemoryStream(); + var scratch = new SceneMeshScratch(stream); + var derived = new Element { Id = 1, Location = new LocationCurve { Length = 3 } }; + var stored = new Element + { + Id = 2, + Location = new LocationCurve { Length = 3 }, + Parameters = + [ + new Parameter { Id = -1004005, StorageType = StorageType.Double, Value = 5d }, + ], + }; + scratch.ArchiveParameters(derived); + scratch.ArchiveParameters(stored); + + ElementBuilder.AddCurveLengths(new RevitFileInfo { Elements = [derived, stored] }, scratch.ArchiveParameters); + + static double Length(Element element) + { + Assert.IsNotType>(element.ReadParameters); + return Assert.IsType(Assert.Single(element.ReadParameters, parameter => parameter.Id == -1004005).Value); + } + Assert.Equal(3d, Length(derived)); + Assert.Equal(5d, Length(stored)); + } + + [Fact] + public void RoomAndSheetPassesArchiveTheirEditsBeforeTheNextPass() + { + using var stream = new MemoryStream(); + var scratch = new SceneMeshScratch(stream); + var room = new Element { Id = 1, CategoryId = -2000160, Name = "Office", SerializedRoomPhaseId = 0 }; + var sheet = new Element { Id = 2, CategoryId = -2003100, References = [3] }; + var view = new Element { Id = 3, CategoryId = -2000279 }; + var info = new RevitFileInfo { Elements = [room, sheet, view] }; + var index = info.Elements.ToDictionary(element => element.Id); + var state = new RvtIO.Internal.ParsingState + { + ArchiveSceneParameters = scratch.ArchiveParameters, + SheetInfo = { [2] = ("A-01", "2026-11-24") }, + ViewNames = { [3] = "Plan" }, + }; + + ElementBuilder.ApplyRoomParams(info, scratch.ArchiveParameters, index); + typeof(ElementBuilder).GetMethod("ApplySheetParams", BindingFlags.Static | BindingFlags.NonPublic)! + .Invoke(null, [info, state, index]); + + Assert.Equal("Office", Value(room, -1006900)); + Assert.Equal(0, Value(room, -1012112)); + Assert.Equal("A-01", Value(sheet, -1007401)); + Assert.Equal("A-01", Value(view, -1006601)); + Assert.Equal("Plan", Value(view, -1005112)); + + static object? Value(Element element, int id) + { + Assert.IsNotType>(element.ReadParameters); + return Assert.Single(element.ReadParameters, parameter => parameter.Id == id).Value; + } + } + + [Fact] + public void DetailCurveFlagsAreUpdatedOnParameterPages() + { + using var stream = new MemoryStream(); + var scratch = new SceneMeshScratch(stream); + var modelCurve = new Element { Id = 1, SerializedOwnerDbViewId = 0 }; + var detailCurve = new Element + { + Id = 2, + SerializedOwnerDbViewId = 42, + Parameters = [new Parameter { Id = -1004011, StorageType = StorageType.Integer, Value = 0 }], + }; + var other = new Element { Id = 3, SerializedOwnerDbViewId = 42 }; + var data = new RevitFileInfo { Elements = [modelCurve, detailCurve, other] }; + scratch.ArchiveParameters(detailCurve); + + ElementBuilder.ApplyDetailCurveFlag(data, new Dictionary { [1] = 838, [2] = 838, [3] = 839 }, + scratch.ArchiveParameters); + + Assert.Equal(0, Flag(modelCurve)); + Assert.Equal(1, Flag(detailCurve)); + Assert.Empty(other.ReadParameters); + + static int Flag(Element element) + { + Assert.IsNotType>(element.ReadParameters); + return Assert.IsType(Assert.Single(element.ReadParameters, parameter => parameter.Id == -1004011).Value); + } + } + + [Fact] + public void ArchivedTypeReferencesUseTheFirstValidParameterAndTrackEdits() + { + using var stream = new MemoryStream(); + var scratch = new SceneMeshScratch(stream); + var element = new Element + { + Parameters = + [ + TypeParameter("ELEM_TYPE_PARAM", -1), + TypeParameter("ELEM_FAMILY_AND_TYPE_PARAM", 7), + TypeParameter("ELEM_TYPE_PARAM", 10), + TypeParameter("ELEM_TYPE_PARAM", 12), + ], + }; + + scratch.ArchiveParameters(element); + Assert.Equal(10, element.FamilyTypeId); + Assert.Equal(7, element.GetTypeReferenceId(includeFamilyAndType: true)); + + element.Parameters[1].Value = 0; + element.Parameters[2].Definition!.Name = "Unrelated"; + Assert.Equal(12, element.FamilyTypeId); + Assert.Equal(12, element.GetTypeReferenceId(includeFamilyAndType: true)); + + scratch.ArchiveParameters(element); + Assert.Equal(12, element.FamilyTypeId); + Assert.Equal(12, element.GetTypeReferenceId(includeFamilyAndType: true)); + Assert.IsNotType>(element.ReadParameters); + + static Parameter TypeParameter(string name, int value) => new() + { + Definition = new Definition { Name = name }, + StorageType = StorageType.ElementId, + Value = value, + }; + } + + [Fact] + public void ArchivedPhaseVoteAndQuantityPlaceholderFollowParameterEdits() + { + using var stream = new MemoryStream(); + var scratch = new SceneMeshScratch(stream); + var element = new Element + { + Parameters = + [ + new Parameter { Id = -1012100, StorageType = StorageType.ElementId, Value = -1 }, + new Parameter { Id = -1012100, StorageType = StorageType.ElementId, Value = 0 }, + new Parameter { Id = -1012100, StorageType = StorageType.ElementId, Value = 12 }, + new Parameter { Id = -1012100, StorageType = StorageType.ElementId, Value = 13 }, + new Parameter { Id = -1012805, StorageType = StorageType.Double, Value = 0d }, + new Parameter { Id = -1012807, StorageType = StorageType.String, Value = "0" }, + ], + }; + + scratch.ArchiveParameters(element); + var stored = element.ReadParameters; + Assert.Equal(12, element.FirstPositiveCreatedPhase); + Assert.True(element.HasHostQuantityPlaceholder); + Assert.Same(stored, element.ReadParameters); + + element.Parameters[2].Value = -1; + element.Parameters[4].Value = 1d; + Assert.Equal(13, element.FirstPositiveCreatedPhase); + Assert.False(element.HasHostQuantityPlaceholder); + + scratch.ArchiveParameters(element); + Assert.Equal(13, element.FirstPositiveCreatedPhase); + Assert.False(element.HasHostQuantityPlaceholder); + Assert.IsNotType>(element.ReadParameters); + } + + [Fact] + public void ArchivedZeroReferencesAreResolvedAndClearedAsTargetsChange() + { + using var stream = new MemoryStream(); + var scratch = new SceneMeshScratch(stream); + var element = new Element + { + Parameters = + [ + new Parameter { Id = (int)BuiltInParameter.PHASE_CREATED, StorageType = StorageType.ElementId, Value = 0 }, + new Parameter { Id = 99, StorageType = StorageType.ElementId, Value = 0, HasResolvedZeroElementId = true }, + ], + }; + var info = new RevitFileInfo { Elements = [element], SerializedHasZeroProjectPhase = true }; + scratch.ArchiveParameters(element); + + Parameter.ResolveZeroElementIds(info, archiveParameters: scratch.ArchiveParameters); + + Assert.True(element.ReadParameters[0].HasResolvedZeroElementId); + Assert.False(element.ReadParameters[1].HasResolvedZeroElementId); + Assert.IsNotType>(element.ReadParameters); + + info.SerializedHasZeroProjectPhase = false; + Parameter.ResolveZeroElementIds(info, archiveParameters: scratch.ArchiveParameters); + + Assert.All(element.ReadParameters, parameter => Assert.False(parameter.HasResolvedZeroElementId)); + Assert.Equal(Parameter.ZeroReferenceKinds.Phase, element.ArchivedZeroReferences); + Assert.IsNotType>(element.ReadParameters); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public void NativeFactsAreOptionalWithoutChangingSceneParameterValues(bool keepExportProvenance) + { + const int parameterId = -1001105; + var state = new RvtIO.Internal.ParsingState { KeepExportProvenance = keepExportProvenance }; + var native = new RvtIO.Parsing.TfBlockDeserializer.NativeParams { RootParameterStoresComplete = true }; + native.Doubles.Add((parameterId, 17.25)); + state.NativeParams[1] = native; + var element = new Element { Id = 1 }; + var data = new RevitFileInfo { Elements = [element] }; + + RvtIO.Parsing.ElementBuilder.ApplyNativeParams(data, state); + + var value = Assert.Single(element.Parameters, parameter => parameter.Id == parameterId); + Assert.Equal(17.25, value.Value); + Assert.Equal(keepExportProvenance, element.NativeStoredParameterIds?.Contains(parameterId) == true); + Assert.Equal(keepExportProvenance, element.NativeParameterStoreIds?.Contains(parameterId) == true); + } + private const double Foot = 0.3048; private const int Wall = 100, Door = 101, Empty = 102, Broken = 103, Type = 200, Symbol = 300, Concrete = 500; @@ -102,6 +426,328 @@ private static RvtDocument Document() => RvtDocument.FromInfo(new RevitFileInfo private static RvtSceneResult Map() => RvtSceneReader.Read(Document(), Meshes(), new RvtSceneOptions { ModelKey = "model.rvt" }); + [Fact] + public void PagedReferencesPreserveOrderAndRestoreTheEditableList() + { + using var stream = new MemoryStream(); + var scratch = new SceneMeshScratch(stream); + var element = new Element(); + var source = Enumerable.Range(0, 17_000).Select(i => i % 1037).ToArray(); + element.SetReferences(source, editable: false); + scratch.ArchiveGeometry(element); + + var stored = element.ReadReferences; + Assert.NotNull(stored); + Assert.IsNotType(stored); + Assert.Equal(source, stored); + Assert.Equal(source[16_384], stored[16_384]); + var editable = element.References; + Assert.NotNull(editable); + editable[16_384] = 42; + editable.RemoveAt(0); + Assert.Same(editable, element.References); + Assert.Equal(16_999, element.ReadReferences!.Count); + Assert.Equal(42, element.ReadReferences[16_383]); + Assert.Equal(source[16_384], stored[16_384]); + } + + [Fact] + public void ScratchScenePreservesGeometryPropertiesPlacementsAndDiagnostics() + { + using var stream = new MemoryStream(); + var scratch = new SceneMeshScratch(stream); + var meshes = Meshes(); + var stored = new MeshSet + { + Symbols = meshes.Symbols.ToDictionary(pair => pair.Key, pair => scratch.Store(pair.Value)), + Elements = meshes.Elements.Select(element => new ElementMesh + { + ElementId = element.ElementId, + Meshes = scratch.Store(element.Meshes), + Placements = element.Placements, + Coverage = element.Coverage, + UntriangulatedFaces = element.UntriangulatedFaces, + }).ToArray(), + }; + + var expected = Map(); + var actual = RvtSceneReader.Map(Document(), stored, "model.rvt", scratch: scratch); + + Assert.True(stream.Length > 0); + Assert.Equal(SceneJson.Write(expected.Document), SceneJson.Write(actual.Document)); + Assert.Equal(expected.Diagnostics, actual.Diagnostics); + } + + [Fact] + public void ScratchSceneArrayReadsAcrossPageBoundariesAndWithInterleavedWrites() + { + using var stream = new MemoryStream(); + var scratch = new SceneMeshScratch(stream); + var values = Enumerable.Range(0, 8000).Select(i => new Vector3d(i, -i, i * .5)).ToArray(); + var stored = scratch.Store(values); + var later = scratch.Store(new[] { 5, 7 }); + + Assert.Equal(values, stored); + Assert.Equal(values, stored.ReadAll()); + Assert.Equal(values[2730], stored[2730]); + Assert.Equal(7, later[1]); + Assert.Equal(values[^1], stored[^1]); + Assert.Throws(() => stored[values.Length]); + } + + [Fact] + public void ResolvedParameterPagesPreserveOrderFlagsAndPropertyValues() + { + using var stream = new MemoryStream(); + var scratch = new SceneMeshScratch(stream); + var reference = new Parameter + { + Id = -1012100, Definition = new Definition { Id = -1012100, Name = "Phase", BuiltInParameter = "PHASE_CREATED" }, + Value = 0, StorageType = StorageType.ElementId, NativeElementId = 4294967311, HasResolvedZeroElementId = true, + FromNativeFields = true, IsReadOnly = true, + }; + var text = new Parameter + { + Id = 1200, Value = "\ud800", StorageType = StorageType.String, Guid = Guid.Empty, + Definition = new Definition { Id = 1200, Name = "Exact text" }, + }; + var distance = new Parameter + { + Id = 1201, Value = 2.25, StorageType = StorageType.Double, ForgeId = "length", + SpecType = "autodesk.spec.aec:length-2.0.0", UnitSymbol = "mm", ConversionFactor = 304.8, + IsApproximate = true, + }; + var missing = new Parameter { Id = 1202, Value = false, StorageType = StorageType.Integer, HasNoRevitValue = true }; + var first = new Element { Parameters = [reference, text, distance, missing], SerializedCreatedPhaseId = 0 }; + var second = new Element { Parameters = [new Parameter { Id = -1002050, Value = 7 }] }; + var original = first.Parameters; + scratch.ArchiveParameters(first); + scratch.ArchiveParameters(second); + + var archived = first.ReadParameters; + Assert.NotSame(original, archived); + Assert.Equal(original.Select(p => p.Id), archived.Select(p => p.Id)); + Assert.Equal(7, second.ReadParameters[0].Value); + Assert.Equal(reference.SourceElementId, archived[0].SourceElementId); + Assert.True(archived[0].HasRevitValue); + Assert.True(archived[0].FromNativeFields); + Assert.True(archived[0].IsReadOnly); + Assert.Equal(reference.Definition.BuiltInParameter, archived[0].Definition.BuiltInParameter); + Assert.Equal(text.Value, first.LookupParameter("Exact text")!.Value); + Assert.Equal(Guid.Empty, archived[1].Guid); + Assert.Equal(distance.AsValueString(), archived[2].AsValueString()); + Assert.Equal(distance.SpecType, archived[2].SpecType); + Assert.True(archived[2].IsApproximate); + Assert.False(archived[3].HasRevitValue); + Assert.Equal(false, archived[3].Value); + Assert.Contains(7, ProductRules.TypeElementIds([first, second])); + Assert.True(ProductRules.HasProjectPhaseReference(first)); + Assert.Same(archived, first.ReadParameters); + + long persisted = stream.Length; + Assert.Equal(4, first.Parameters.Count); + scratch.ArchiveParameters(first); + Assert.Equal(persisted, stream.Length); + Assert.Same(archived, first.ReadParameters); + + first.Parameters.RemoveAt(3); + Assert.Same(first.Parameters, first.ReadParameters); + first.Parameters[1].Value = "Resolved later"; + scratch.ArchiveParameters(first); + Assert.Equal(persisted, stream.Length); + Assert.Equal(3, first.ReadParameters.Count); + Assert.Equal("Resolved later", first.ReadParameters[1].Value); + Assert.Equal(7, second.ReadParameters[0].Value); + + first.Parameters[1].Value = new string('a', 1024); + scratch.ArchiveParameters(first); + long grown = stream.Length; + Assert.True(grown > persisted); + string replacement = new('b', 1024); + first.Parameters[1].Value = replacement; + scratch.ArchiveParameters(first); + Assert.Equal(grown, stream.Length); + Assert.Equal(replacement, first.ReadParameters[1].Value); + Assert.Equal(7, second.ReadParameters[0].Value); + } + + [Fact] + public void ParameterPagesRestoreIndependentDefinitions() + { + using var stream = new MemoryStream(); + var scratch = new SceneMeshScratch(stream); + string inlineName = new('x', 513); + var first = new Element { Parameters = [WithName("Caption"), WithName(inlineName), new() { Definition = null! }] }; + var second = new Element { Parameters = [WithName("Caption")] }; + scratch.ArchiveParameters(first); + scratch.ArchiveParameters(second); + + var definition = first.Parameters[0].Definition; + definition.Name = "Edited"; + scratch.ArchiveParameters(first); + Assert.Equal("Edited", first.ReadParameters[0].DefinitionName); + Assert.Equal("Caption", second.ReadParameters[0].DefinitionName); + Assert.Equal("BUILT_IN", second.ReadParameters[0].Definition.BuiltInParameter); + Assert.Equal(inlineName, first.ReadParameters[1].DefinitionName); + Assert.Null(first.ReadParameters[2].Definition); + + static Parameter WithName(string name) => + new() { Id = -7, Definition = new Definition { Id = -7, Name = name, BuiltInParameter = "BUILT_IN" } }; + } + + [Fact] + public void FirstModelResolutionPassKeepsTypesAndElevationsOnParameterPages() + { + using var stream = new MemoryStream(); + var scratch = new SceneMeshScratch(stream); + var type = new Element { Id = 5001, Name = "Type", CategoryId = -2000011, Category = "OST_Walls" }; + var instance = new Element + { + Id = 5002, CategoryId = -2000011, Category = "OST_Walls", BoundingBox = [0, 0, 12, 1, 1, 13], + Parameters = + [ + new() { Id = -1002050, StorageType = StorageType.ElementId, Value = type.Id }, + new() { Id = -1007102, StorageType = StorageType.Double, Value = 10.0 }, + ], + }; + scratch.ArchiveParameters(instance); + var info = new RevitFileInfo { Elements = [type, instance] }; + int passes = 0; + + ElementBuilder.PostProcess(info, new RvtIO.Internal.ParsingState + { + ArchiveSceneParameters = scratch.ArchiveParameters, + }, passCompleted: () => + { + if (++passes != 1) return; + Assert.Equal(type.Id, instance.TypeId); + Assert.IsNotType>(instance.ReadParameters); + Assert.Equal(2.0, instance.ReadParameters.First(p => p.Id == -1001360).Value); + }); + + Assert.True(passes > 0); + } + + [Fact] + public void WorksharingOwnersUseTheEmittedCategoryWithoutRetainingParameterLists() + { + using var stream = new MemoryStream(); + var scratch = new SceneMeshScratch(stream); + var info = new RevitFileInfo + { + Elements = + [ + new() { CategoryId = -2000260, Parameters = [Category(-2000011)] }, + new() { Parameters = [Category(-2000260)] }, + new() { Parameters = [Category(7)] }, + new() { Parameters = [Category(-2000011), new() { Id = -1002067, Value = "Stored owner" }] }, + ], + }; + foreach (var element in info.Elements) scratch.ArchiveParameters(element); + + ElementBuilder.ApplyEditedByCategoryRules(info, new RvtIO.Internal.ParsingState + { + LocalUsername = "Local owner", + ArchiveSceneParameters = scratch.ArchiveParameters, + }); + + Assert.Equal("Local owner", Owner(info.Elements[0])); + Assert.Equal("", Owner(info.Elements[1])); + Assert.Null(Owner(info.Elements[2])); + Assert.Equal("Stored owner", Owner(info.Elements[3])); + Assert.All(info.Elements, element => Assert.IsNotType>(element.ReadParameters)); + + static Parameter Category(int value) => new() { Id = -1140362, Value = value }; + static object? Owner(Element element) => element.ReadParameters.FirstOrDefault(p => p.Id == -1002067)?.Value; + } + + [Fact] + public void StoredPhasesAreUpdatedAndRearchivedOneElementAtATime() + { + using var stream = new MemoryStream(); + var scratch = new SceneMeshScratch(stream); + var info = new RevitFileInfo + { + Elements = + [ + new() { Id = 1, SerializedCreatedPhaseId = 7, Parameters = [ExistingPhase(-1)] }, + new() { Id = 2, SerializedCreatedPhaseId = 8, Parameters = [ExistingPhase(3)] }, + ], + }; + foreach (var element in info.Elements) scratch.ArchiveParameters(element); + + var edited = new List(); + ElementBuilder.ApplyStoredPhases(info, new Dictionary { [7] = 3065 }, + archiveParameters: element => + { + scratch.ArchiveParameters(element); + edited.Add(element.Id); + }); + + Assert.Equal([1, 2], edited); + Assert.Equal(7, info.Elements[0].ReadParameters[0].Value); + Assert.Equal(3, info.Elements[1].ReadParameters[0].Value); + Assert.All(info.Elements, element => Assert.IsNotType>(element.ReadParameters)); + + static Parameter ExistingPhase(int value) => + new() { Id = -1012100, StorageType = StorageType.ElementId, Value = value }; + } + + [Fact] + public void ExpandedFacePagesPreserveFaceOrderAndRestoreMutableLists() + { + using var stream = new MemoryStream(); + var scratch = new SceneMeshScratch(stream); + var faces = Enumerable.Range(0, 1024).Select(i => new GeoFace + { + Origin = [i, 0, 0], + XVector = [1, 0, 0], + YVector = [0, 1, 0], + OuterVertices = [[i, 0, 0], [i + 1, 0, 0], [i, 1, 0]], + InnerVertices = i == 1 ? [[[1.1, .1, 0], [1.2, .1, 0], [1.1, .2, 0]]] : null, + Normal = [0, 0, 1], + GeometryNode = i % 2 == 0 ? 4 : -7, + RenderStyleId = i, + MeshArcs = i == 1 ? [new([1, 2, 3], [1, 0, 0], [0, 1, 0], .5, .25, .75, 6)] : null, + GInfoFlags = i == 0 ? 0x200u : null, + EdgeIndices = i == 0 ? [0, 2, 1] : null, + }).ToList(); + var geometry = new GeometryData { Faces = faces }; + scratch.ArchiveGeometry(new Element { Geometry = geometry }); + + Assert.True(stream.Length > 64 * 1024); + Assert.NotSame(faces, geometry.ReadFaces); + Assert.Equal(faces.Select(face => face.RenderStyleId), geometry.ReadFaces.Select(face => face.RenderStyleId)); + var restoredFrame = geometry.ReadFaces[1000]; + Assert.Equal(faces[1000].Origin, restoredFrame.Origin); + Assert.Equal(faces[1000].XVector, restoredFrame.XVector); + Assert.Equal(faces[1000].YVector, restoredFrame.YVector); + Assert.Equal(faces[1000].Normal, restoredFrame.Normal); + Assert.Equal(faces[1000].OuterVertices![2], geometry.ReadFaces[1000].OuterVertices![2]); + Assert.Equal(faces[1].InnerVertices![0][1], geometry.ReadFaces[1].InnerVertices![0][1]); + Assert.Equal(6u, Assert.Single(geometry.ReadFaces[1].MeshArcs!).Edge); + Assert.Equal(0x200u, geometry.ReadFaces[0].GInfoFlags); + Assert.Equal(faces[0].EdgeIndices, geometry.ReadFaces[0].EdgeIndices); + + var restored = geometry.Faces; + restored[0].GeometryNode = 42; + restored.RemoveAt(restored.Count - 1); + Assert.Same(restored, geometry.Faces); + Assert.Equal(1023, geometry.ReadFaces.Count); + Assert.Equal(42, geometry.ReadFaces[0].GeometryNode); + } + + [Fact] + public void SceneReaderRequiresSeparateTriangleScratch() + { + using var stream = new MemoryStream(); + var options = new RvtSceneOptions { ModelKey = "model.rvt" }; + Assert.Throws(() => RvtSceneReader.ReadStream(stream, options, stream)); + using var nonempty = new MemoryStream([7]); + Assert.Throws(() => RvtSceneReader.ReadStream(stream, options, nonempty)); + Assert.Empty(stream.ToArray()); + } + /// The scene of one drawable element. private static SceneDocument MapOne(Element element) => RvtSceneReader.Read(RvtDocument.FromInfo(new RevitFileInfo { Elements = [element] }), new MeshSet { Elements = [new ElementMesh { ElementId = element.Id, Meshes = [Triangle(0, 0, 0)] }] }, new RvtSceneOptions { ModelKey = "m" }).Document; @@ -591,7 +1237,7 @@ private static RvtSceneResult ReadSyntheticFile(byte[]? extraPartition = null, R public void PathReaderForwardsProgressAndCountsWithoutChangingScene() { byte[] extraPartition = [1, 2, 3]; - var progress = new ReadProgressLog(); + var progress = new ProgressLog(); var baseline = ReadSyntheticFile(extraPartition, new RvtSceneOptions { ModelKey = "model" }); var result = ReadSyntheticFile(extraPartition, new RvtSceneOptions { ModelKey = "model", ReadProgress = progress }); @@ -599,7 +1245,7 @@ public void PathReaderForwardsProgressAndCountsWithoutChangingScene() Assert.Equal(new RvtReadProgress("complete", 1, 1), progress.Updates[^1]); Assert.Equal([0L, 1L, 2L], progress.Updates.Where(update => update.Phase == "partitions").Select(update => update.Completed)); Assert.All(progress.Updates.Where(update => update.Phase == "partitions"), update => Assert.Equal(2, update.Total)); - var blocks = progress.Updates.Where(update => update.Phase == "element-blocks").ToArray(); + var blocks = progress.Updates.Where(update => update.Phase == "element-blocks" && update.GeometryBlocks == null).ToArray(); Assert.Equal(Enumerable.Range(0, blocks.Length).Select(index => (long)index), blocks.Select(update => update.Completed)); Assert.Equal(blocks[^1].Total, blocks[^1].Completed); ReadProgressTests.AssertWellFormed(progress.Updates, ReadProgressTests.ProjectPhases); @@ -637,10 +1283,10 @@ public void StreamReadForwardsProgressInTheOrderOfAPathRead() try { CliExitCodeTests.WriteSyntheticRvt(path, [1, 2, 3]); - var fromPath = new ReadProgressLog(); + var fromPath = new ProgressLog(); RvtSceneReader.Read(path, new RvtSceneOptions { ModelKey = "model", ReadProgress = fromPath }); - var fromStream = new ReadProgressLog(); + var fromStream = new ProgressLog(); using var stream = File.OpenRead(path); RvtSceneReader.ReadStream(stream, new RvtSceneOptions { ModelKey = "model", ReadProgress = fromStream }); @@ -651,6 +1297,60 @@ public void StreamReadForwardsProgressInTheOrderOfAPathRead() finally { File.Delete(path); } } + [Fact] + public void ScratchReadKeepsTheSceneAndRecoveryDiagnosticsAndClosesScratch() + { + var baseline = ReadSyntheticFile([1, 2, 3], new RvtSceneOptions { ModelKey = "model" }); + using var scratch = new MemoryStream(); + var result = ReadSyntheticFile([1, 2, 3], new RvtSceneOptions + { + ModelKey = "model", + CreatePartitionScratch = () => scratch, + }); + + Assert.Equal(SceneJson.Write(baseline.Document), SceneJson.Write(result.Document)); + Assert.Equal(baseline.Diagnostics, result.Diagnostics); + Assert.False(scratch.CanRead); + } + + [SkippableTheory] + [InlineData("Test_2022.rvt", true)] + [InlineData("Test_2025.rvt", false)] + [InlineData("Test_2025.rvt", true)] + public void ScratchReadMatchesSceneAndDiagnosticsOfARealModel(string fileName, bool archiveScene) + { + string path = TestFiles.Find(fileName); + var baseline = RvtSceneReader.Read(path); + string temporary = Path.Combine(Path.GetTempPath(), "rvtio-scratch-" + Guid.NewGuid().ToString("N")); + using var input = File.OpenRead(path); + var meshProgress = new ProgressLog<(int Completed, int Total)>(); + var options = new RvtSceneOptions + { + ModelKey = Path.GetFileName(path), + MeshProgress = meshProgress, + CreatePartitionScratch = () => new FileStream(temporary, FileMode.CreateNew, FileAccess.ReadWrite, FileShare.None, + bufferSize: 64 * 1024, FileOptions.DeleteOnClose), + }; + using var sceneScratch = archiveScene + ? new FileStream(temporary + ".scene", FileMode.CreateNew, FileAccess.ReadWrite, FileShare.None, + bufferSize: 64 * 1024, FileOptions.DeleteOnClose) + : null; + var result = sceneScratch == null + ? RvtSceneReader.ReadStream(input, options) + : RvtSceneReader.ReadStream(input, options, sceneScratch); + + Assert.NotEmpty(baseline.Document.Instances); + Assert.Equal(baseline.Diagnostics, result.Diagnostics); + Assert.Equal(SceneJson.Write(baseline.Document), SceneJson.Write(result.Document)); + int total = meshProgress.Updates[0].Total; + Assert.True(total > 0); + Assert.Equal((0, total), meshProgress.Updates[0]); + Assert.Equal((total, total), meshProgress.Updates[^1]); + Assert.All(meshProgress.Updates, update => Assert.Equal(total, update.Total)); + Assert.False(File.Exists(temporary)); + Assert.True(input.CanRead); + } + [Fact] public void InvalidCompoundStreamKeepsItsTypedErrorAndRemainsOpen() { @@ -663,10 +1363,23 @@ public void InvalidCompoundStreamKeepsItsTypedErrorAndRemainsOpen() Assert.Equal(1, stream.ReadByte()); } - private sealed class ReadProgressLog : IProgress + [Fact] + public void EmptySceneReportsZeroDrawableElements() + { + var meshProgress = new ProgressLog<(int Completed, int Total)>(); + RvtSceneReader.Read(RvtDocument.FromInfo(new RevitFileInfo()), new RvtSceneOptions + { + ModelKey = "empty", + MeshProgress = meshProgress, + }); + + Assert.Equal((0, 0), Assert.Single(meshProgress.Updates)); + } + + private sealed class ProgressLog : IProgress { - public List Updates { get; } = []; - public void Report(RvtReadProgress value) => Updates.Add(value); + public List Updates { get; } = []; + public void Report(T value) => Updates.Add(value); } [Fact] diff --git a/tests/RvtIO.Tests/ScaledInstanceComponentTests.cs b/tests/RvtIO.Tests/ScaledInstanceComponentTests.cs index a5d1307a..ade61bc1 100644 --- a/tests/RvtIO.Tests/ScaledInstanceComponentTests.cs +++ b/tests/RvtIO.Tests/ScaledInstanceComponentTests.cs @@ -57,6 +57,33 @@ public void HiddenInstanceVariant_NeedsAllThreeVisibilityBits(uint flags, bool e Assert.Equal(expected, GRepParserV2.IsHiddenInstanceVariant(flags)); } + [Fact] + public void ScratchGRep_ReplaysTheWinningBlockWithItsMergedInstances() + { + const uint owner = 9516707; + var bytes = SymbolBlock(); + uint size = BitConverter.ToUInt32(bytes, 8); + var backing = new PartitionChunks.Backing(new MemoryStream()); + var scratch = new PartitionChunks(backing); + var stored = new PartitionChunks.Block(bytes, 0, bytes.Length, backing); + var state = new ParsingState { Chunks = scratch }; + var job = new BlockParser.PendingGRep([], owner, 0, size, IsFamilyCut: false) { Stored = stored }; + var decoded = Assert.IsType(GRepParserV2.Parse(bytes, 0, size)); + BlockParser.ApplyPendingGRep(state, job, decoded); + BlockParser.ApplyPendingGRep(state, job, new GRepData + { + Instances = [new GRepInstance { SymbolElemId = 42 }], + }); + + var restored = state.GrepBlocks[owner]; + Assert.NotSame(decoded, restored); + Assert.Equal(decoded.BoundingBox, restored.BoundingBox); + Assert.Equal(9988502, restored.SymbolElemId); + Assert.Equal(decoded.InstanceTransform, restored.InstanceTransform); + Assert.Equal(new uint[] { 9988502, 42 }, state.GrepBlocks.ReferencedSymbols()); + Assert.Equal(new[] { 9988502, 42 }, restored.Instances.Select(instance => instance.SymbolElemId)); + } + [Theory] [InlineData(new double[] { 1, 0, 0, 0, 1, 0, 0, 0, 1 }, true)] [InlineData(new double[] { 0, -1, 0, 1, 0, 0, 0, 0, 1 }, true)] diff --git a/tests/RvtIO.Tests/SolidQuantitiesTests.cs b/tests/RvtIO.Tests/SolidQuantitiesTests.cs index db2d1e14..45a5000e 100644 --- a/tests/RvtIO.Tests/SolidQuantitiesTests.cs +++ b/tests/RvtIO.Tests/SolidQuantitiesTests.cs @@ -42,6 +42,24 @@ public void BoxGivesItsExactQuantitiesWhateverTheWindingOfItsFaces(params int[] Assert.Equal(4.0, shell.Value.LargestFaceArea, 9); } + [Fact] + public void QuantityCalculationsLeaveArchivedFacesInScratch() + { + var box = Box(0, 0, 0, 2, 3, 4, 1, 4); + foreach (var face in box.Faces) face.PlaneSurface = true; + var expected = SolidQuantities.OfSingleClosedShell(box); + Assert.NotNull(expected); + using var scratch = new MemoryStream(); + new GeometryFaceStore(new PartitionChunks.Backing(scratch)).Archive(new Element { Geometry = box }); + var archived = box.ReadFaces; + Assert.True(scratch.Length > 0); + + Assert.Equal(expected, SolidQuantities.OfSingleClosedShell(box)); + Assert.Equal(expected, SolidQuantities.OfAllSolids(box)); + Assert.Equal(6, SolidQuantities.RoomPlanArea(box)!.Value, 9); + Assert.Same(archived, box.ReadFaces); + } + [Fact] public void HoleThroughAFacePairIsSubtracted() { diff --git a/tests/RvtIO.Tests/StreamInputTests.cs b/tests/RvtIO.Tests/StreamInputTests.cs index 17929b45..9b31fbee 100644 --- a/tests/RvtIO.Tests/StreamInputTests.cs +++ b/tests/RvtIO.Tests/StreamInputTests.cs @@ -1,5 +1,7 @@ +using System.Buffers.Binary; using System.Runtime.CompilerServices; using IOScene; +using OpenMcdf; using RvtIO.Meshes; using RvtIO.Scene; using Xunit; @@ -493,6 +495,31 @@ public void AStreamIsReadFromItsBeginningWhateverItsPosition() } } + [Theory] + [InlineData("Partitions", true)] + [InlineData("Partitions", false)] + [InlineData("Global", true)] + public void WideCompoundStreamSizesAreAllowedOnlyForStreamedPartitions(string storage, bool useScratch) + { + using var file = new MemoryStream(); + using (var container = RootStorage.Create(file, OpenMcdf.Version.V4, StorageModeFlags.LeaveOpen)) + using (var payload = container.CreateStorage(storage).CreateStream("0")) + payload.Write(new byte[4096]); + + var bytes = file.ToArray(); + int directory = (BinaryPrimitives.ReadInt32LittleEndian(bytes.AsSpan(48)) + 1) * 4096; + int entry = directory + 2 * 128; // root and storage precede the single stream entry + BinaryPrimitives.WriteInt64LittleEndian(bytes.AsSpan(entry + 120), (long)Array.MaxLength + 4096); + using var changed = new MemoryStream(bytes); + var reader = new RvtFileReader(new RvtReaderOptions { CreatePartitionScratch = useScratch ? () => new MemoryStream() : null }); + + // No data was added to the container. Streaming must still verify the declared end of the stream. + if (storage == "Partitions" && useScratch) + Assert.Equal("truncated-or-damaged", Assert.Throws(() => reader.ReadStream(changed)).Kind); + else + Assert.Equal("array-length", Assert.Throws(() => reader.ReadStream(changed)).Hit.Limit); + } + [Fact] public void ThePathCheckKeepsReportingAFailingReadAsAnInputError() { diff --git a/tests/RvtIO.Tests/TfStreamWalkerStreamingTests.cs b/tests/RvtIO.Tests/TfStreamWalkerStreamingTests.cs index bed7264e..c7741ebb 100644 --- a/tests/RvtIO.Tests/TfStreamWalkerStreamingTests.cs +++ b/tests/RvtIO.Tests/TfStreamWalkerStreamingTests.cs @@ -50,6 +50,101 @@ IEnumerable Chunks() } } + [Fact] + public void BackedWindowsPreserveAnchorsRecordsAndTargetedVisitOrder() + { + uint[] ids = Enumerable.Range(101, 24).Select(id => (uint)id).ToArray(); + byte[] bytes = Blocks(ids); + // Cross the 16 MiB boundary with different targeted classes and keep their visit order. + const int length = 800_016; + for (int i = 0; i < ids.Length; i++) + BitConverter.GetBytes((ushort)(i % 2 == 0 ? 2006 : 2007)).CopyTo(bytes, i * length + 12); + byte[][] chunks = bytes.Chunk(189_911).ToArray(); + using var scratch = new MemoryStream(); + var backed = new PartitionChunks(new PartitionChunks.Backing(scratch)); + foreach (var chunk in chunks) backed.Add(chunk); + + Assert.Equal(Visits(chunks, false), Visits(backed, false)); + Assert.Equal(Visits(chunks, true), Visits(backed, true)); + Assert.Equal(ids.Length, Visits(backed, true).Count); + + var anchored = new List(); + var scanned = new List(); + TfStreamWalker.WalkLocated(backed, [], (_, _, _, _, _, block) => anchored.Add(block)); + TfStreamWalker.ScanLocated(backed, ids.ToHashSet(), (_, _, _, _, _, block) => scanned.Add(block)); + Assert.Equal(bytes.Length, scratch.Length); + Assert.Equal(ids, anchored.Select(CheckBlock)); + Assert.Equal(Visits(chunks, true).Select(visit => visit.Owner), scanned.Select(CheckBlock)); + + uint CheckBlock(PartitionChunks.Block block) + { + var (source, start) = block.Read(); + uint owner = BitConverter.ToUInt32(source, start); + int index = Array.IndexOf(ids, owner); + Assert.True(index >= 0 && bytes.AsSpan(index * length, length).SequenceEqual(source.AsSpan(start, length))); + return owner; + } + + List<(uint Owner, uint Size, ushort Class)> Visits(IReadOnlyList source, bool targeted) + { + var result = new List<(uint, uint, ushort)>(); + void Visit(byte[] data, int start, uint size, ushort kind, uint owner) + { + Assert.Equal(size, BitConverter.ToUInt32(data, start + 12 + (int)size)); + result.Add((owner, size, kind)); + } + if (targeted) TfStreamWalker.ScanBlocks(source, ids.ToHashSet(), Visit); + else TfStreamWalker.Walk(source, [], Visit); + return result; + } + } + + [Fact] + public void LocatedBlocksUseLongOffsetsInTheConcatenatedChunks() + { + using var scratch = new MemoryStream(); + var chunks = new PartitionChunks(new PartitionChunks.Backing(scratch)); + // Only the final chunk is read. The virtual length of the preceding chunks tests + // the address without allocating a multi-gigabyte array. + const int largeChunk = 1_000_000_000; + for (int i = 0; i < 10; i++) chunks.Add(new PartitionChunks.Chunk(largeChunk, null, 0)); + byte[] payload = [1, 2, 3, 4, 5, 6]; + chunks.Add(payload[..3]); + chunks.Add(payload[3..]); + var range = new PartitionChunks.Block(new PartitionChunks.WindowSource(chunks), 10L * largeChunk + 1, 4); + + var (data, start) = range.Read(); + + Assert.Equal(0, start); + Assert.Equal(payload[1..5], data); + } + + [Fact] + public void ScratchBlockReadsFetchOnlyTheirRangeOutsideTheChunkCache() + { + using var scratch = new TrackingScratch(); + var chunks = new PartitionChunks(new PartitionChunks.Backing(scratch)); + var first = new byte[256 * 1024]; + var second = new byte[256 * 1024]; + first[^2] = 1; + first[^1] = 2; + second[0] = 3; + second[1] = 4; + chunks.Add(first); + chunks.Add(second); + var record = chunks.StoredBlock(0, first.Length - 2, 2)!.Value; + var acrossChunks = new PartitionChunks.Block(new PartitionChunks.WindowSource(chunks), first.Length - 2, 4); + + Assert.Equal(new byte[] { 1, 2 }, record.Read().Data); + Assert.Equal(2, scratch.ReadBytes); + Assert.Equal(new byte[] { 1, 2, 3, 4 }, acrossChunks.Read().Data); + Assert.Equal(6, scratch.ReadBytes); + + _ = chunks[0]; + Assert.Equal(new byte[] { 1, 2 }, record.Read().Data); + Assert.Equal(first.Length + 6, scratch.ReadBytes); + } + [Fact] public void EmptyAndEmptyChunkStreamsHaveNoVisits() { @@ -93,4 +188,16 @@ private static byte[] Blocks(uint[] ids) } return result; } + + private sealed class TrackingScratch : MemoryStream + { + internal int ReadBytes { get; private set; } + + public override int Read(Span buffer) + { + int count = base.Read(buffer); + ReadBytes += count; + return count; + } + } }