diff --git a/CHANGELOG.md b/CHANGELOG.md index 6ab2eb1a..6037be84 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -28,6 +28,12 @@ API between minor releases. ### Changed +- Reading reuses local family symbol geometry, builds independent elements in parallel, and reduces parameter and geometry + allocations during decoding and post-processing. Compact JSON prepares properties in bounded batches and writes them + in element ID order. +- The reader inflates validated partition members in parallel, reuses a single partition walk for wall records, and skips + repeated geometry work during block recovery. Native parameter decoding keeps the original order of records for each owner. + - `SaveAs` and `Rewrite` to another directory also check the saved paths of the linked images of a project, as they already did for linked models and point clouds. They refuse with `relative-reference-relocation` when a relative image path would resolve to a different file or the layout of a link cannot be verified. See the [writing guide](docs/writing.md). ### Fixed diff --git a/docs/public-api.md b/docs/public-api.md index ccd5a9f5..296e5736 100644 --- a/docs/public-api.md +++ b/docs/public-api.md @@ -40,7 +40,12 @@ A zero total means the reader has no work count for that update. Counts describe `CompactJsonExporter.Export` passes `Progress` to its first read only. A file of a wide layout is then read a second time for solid quantities; that read reports the single update `quantities` after the first read's `complete`, and the JSON -writing that follows reports nothing. +writing that follows reports nothing. Large Compact JSON exports can prepare row properties in bounded parallel batches. +Rows are written in element ID order. + +The reader reuses a family's local symbol geometry across its placements. Each placement retains its own transformed +coordinates. Parameters can share immutable definition metadata internally and materialize their own mutable +`Definition` on access. ## Model diff --git a/src/RvtIO.Cli/ExportCommand.cs b/src/RvtIO.Cli/ExportCommand.cs index 9260fa61..4c3f2413 100644 --- a/src/RvtIO.Cli/ExportCommand.cs +++ b/src/RvtIO.Cli/ExportCommand.cs @@ -204,8 +204,9 @@ private static int Export(ExportArguments arguments) if (compactJsonPath != null) { // The compact export reads Element.Name only where it is validated (the IFC branch above keeps the fallback names). - RvtIO.Export.ValidatedElementNames.Apply(jsonModel, jsonState); - var compactIdentity = new CompactIdentity(CompactUniverse.Select(jsonModel)); + var names = new CompactElementNames(jsonModel, jsonState); + names.ApplyValidatedNames(jsonModel, jsonState); + var compactIdentity = new CompactIdentity(CompactUniverse.Enumerate(jsonModel)); // --dev-candidates : measurement run without the value gate; writes (id, parameter, stored text, derived text, class) of every // listed parameter for the value gate. --dev-trace : writes (id, class, parameter, reason) of every listed parameter // (reason empty: written) and of every element whose list is unknown (parameter 0). --dev-facts : writes the facts that decide @@ -226,7 +227,8 @@ private static int Export(ExportArguments arguments) // or from the in-memory R22 model when available. var compactGate = RvtIO.Compact.CompactValueGate.ForLayout(jsonModel.GeometryUndecoded); CompactSolidQuantities? compactQuantities = null; - if (ifcState.R22View || !ifcModel.GeometryUndecoded) + // Only wide-layout property rules and the explicit solids dump consume this index. + if ((jsonModel.GeometryUndecoded || solidsPath != null) && (ifcState.R22View || !ifcModel.GeometryUndecoded)) { compactQuantities = CompactSolidQuantities.From(ifcModel, ifcState, compactGate.HasSolidRules); } @@ -247,7 +249,8 @@ private static int Export(ExportArguments arguments) } // A project (.rvt) is a document without an owner family; an .rfa is not decided. var compactSource = CompactPropertySources.Create(jsonModel, jsonState, - rvtPath.EndsWith(".rvt", StringComparison.OrdinalIgnoreCase) ? true : null, gated: candidatesPath == null, identity: compactIdentity, quantities: compactQuantities); + rvtPath.EndsWith(".rvt", StringComparison.OrdinalIgnoreCase) ? true : null, + gated: candidatesPath == null, identity: compactIdentity, quantities: compactQuantities, names: names); using var candidatesWriter = candidatesPath == null ? null : new StreamWriter(candidatesPath, false, new System.Text.UTF8Encoding(false)); using var traceWriter = tracePath == null ? null : new StreamWriter(tracePath, false, new System.Text.UTF8Encoding(false)); using var factsWriter = factsPath == null ? null : new StreamWriter(factsPath, false, new System.Text.UTF8Encoding(false)); diff --git a/src/RvtIO.Cli/InspectBatchDump.cs b/src/RvtIO.Cli/InspectBatchDump.cs index 70f84a9e..f3374b1e 100644 --- a/src/RvtIO.Cli/InspectBatchDump.cs +++ b/src/RvtIO.Cli/InspectBatchDump.cs @@ -316,7 +316,7 @@ public static void Run(RevitFileInfo info, string idsPath, string outPath, Parsi /// IfcExporter's private ParameterNameEquals convention - duplicated here deliberately so /// this diagnostic-only tool has no dependency on IfcExporter internals. private static bool NameMatches(RvtIO.Model.Parameter parameter, string name) => - parameter.Definition?.Name is string parameterName + parameter.DefinitionName is string parameterName && string.Equals( parameterName.Replace(" ", null), name.Replace(" ", null), StringComparison.InvariantCultureIgnoreCase); diff --git a/src/RvtIO.Cli/ListCategoryDump.cs b/src/RvtIO.Cli/ListCategoryDump.cs index c4b89de9..24a3689d 100644 --- a/src/RvtIO.Cli/ListCategoryDump.cs +++ b/src/RvtIO.Cli/ListCategoryDump.cs @@ -79,7 +79,7 @@ public static void Run(RevitFileInfo info, int categoryId, string outPath) private static string? NamedStringParam(Element e, string name) { foreach (var p in e.Parameters) - if (p.Definition?.Name is string n + if (p.DefinitionName is string n && string.Equals(n.Replace(" ", null), name.Replace(" ", null), StringComparison.InvariantCultureIgnoreCase) && p.Value is string v) diff --git a/src/RvtIO.Cli/ReadCommands.cs b/src/RvtIO.Cli/ReadCommands.cs index 2742f24c..6e5a10aa 100644 --- a/src/RvtIO.Cli/ReadCommands.cs +++ b/src/RvtIO.Cli/ReadCommands.cs @@ -113,14 +113,14 @@ private static int Inspect(string rvtPath, string? externalDumpPath, string? ext // RVTIO_INSPECT_ALL=1 lists every parameter, not the first twenty. int listedParameters = Environment.GetEnvironmentVariable("RVTIO_INSPECT_ALL") == "1" ? int.MaxValue : 20; foreach (var p in elem.Parameters.Take(listedParameters)) - Console.WriteLine($" [{p.Id}] {p.Definition?.Name ?? "?"} = {p.Value} ({p.StorageType})"); + Console.WriteLine($" [{p.Id}] {p.DefinitionName ?? "?"} = {p.Value} ({p.StorageType})"); if (elem.Parameters.Count > listedParameters) Console.WriteLine($" ... +{elem.Parameters.Count - listedParameters} more"); foreach (var p in elem.Parameters.Skip(listedParameters).Where(parameter => - parameter.Definition?.Name?.Contains("WIDTH", StringComparison.OrdinalIgnoreCase) == true - || parameter.Definition?.Name?.Contains("HEIGHT", StringComparison.OrdinalIgnoreCase) == true - || parameter.Definition?.Name?.Contains("ROUGH", StringComparison.OrdinalIgnoreCase) == true)) - Console.WriteLine($" size [{p.Id}] {p.Definition?.Name ?? "?"} = {p.Value} ({p.StorageType})"); + parameter.DefinitionName?.Contains("WIDTH", StringComparison.OrdinalIgnoreCase) == true + || parameter.DefinitionName?.Contains("HEIGHT", StringComparison.OrdinalIgnoreCase) == true + || parameter.DefinitionName?.Contains("ROUGH", StringComparison.OrdinalIgnoreCase) == true)) + Console.WriteLine($" size [{p.Id}] {p.DefinitionName ?? "?"} = {p.Value} ({p.StorageType})"); if (elem.References != null) Console.WriteLine($" References ({elem.References.Count}): {string.Join(", ", elem.References)}"); if (elem.Dimension != null) diff --git a/src/RvtIO.Cli/RvtIO.Cli.csproj b/src/RvtIO.Cli/RvtIO.Cli.csproj index b0b946a5..e639b11a 100644 --- a/src/RvtIO.Cli/RvtIO.Cli.csproj +++ b/src/RvtIO.Cli/RvtIO.Cli.csproj @@ -9,7 +9,7 @@ net8.0;net10.0 true - false + true diff --git a/src/RvtIO/Compact/CompactBuiltinParameters.cs b/src/RvtIO/Compact/CompactBuiltinParameters.cs index 43d24edb..a37f0642 100644 --- a/src/RvtIO/Compact/CompactBuiltinParameters.cs +++ b/src/RvtIO/Compact/CompactBuiltinParameters.cs @@ -1,3 +1,4 @@ +using System.Collections.Frozen; using RvtIO.Internal; using RvtIO.Model; using RvtIO.Parsing; @@ -20,6 +21,8 @@ internal sealed class CompactBuiltinParameters /// The built-in entries of an element (ascending id) and the (group, label) pairs left without a validated value. internal readonly record struct CompactBuiltinResult( IReadOnlyList<(int Id, CompactProperty Property)> Entries, IReadOnlySet<(string Group, string Label)> Unvalidated); + private static readonly IReadOnlySet<(string Group, string Label)> EmptyUnvalidated = + FrozenSet<(string Group, string Label)>.Empty; /// ELEM_DESIGN_OPTION_ID ("Design Option"). Without design option sets no element is in an option, so the /// parameter is the null id and prints "None". @@ -34,9 +37,11 @@ internal readonly record struct CompactBuiltinResult( } private readonly CompactElementNames _names; + private readonly Func _findElement; private readonly CompactFormatSettings? _format; private readonly CompactListFileFacts _file; private readonly Func _headerCategory; + private readonly bool _usesDefaultHeaderCategory; private readonly CompactValueGate? _gate; private readonly ParsingState? _state; private readonly CompactSolidQuantities? _quantities; @@ -44,6 +49,7 @@ internal readonly record struct CompactBuiltinResult( private readonly string? _lookupNoneText; private readonly Dictionary _held = []; private readonly HashSet _conflicting = []; + private readonly HashSet<(string Group, string Label)> _seen = []; private readonly Dictionary _skipped = new(StringComparer.Ordinal); /// Which value sources are trusted per parameter; null writes the derived value for every parameter and @@ -61,8 +67,10 @@ public CompactBuiltinParameters(CompactElementNames names, CompactFormatSettings _state = state; _surveyOffsetFeet = surveyOffsetFeet; _names = names; + _findElement = names.Find; _format = format; _file = file; + _usesDefaultHeaderCategory = headerCategory == null; _headerCategory = headerCategory ?? CompactHeaderCategory.Of; _gate = gate; } @@ -93,6 +101,26 @@ public CompactBuiltinParameters(CompactElementNames names, CompactFormatSettings public int Elements { get; private set; } + internal bool CanFork => _usesDefaultHeaderCategory + && Trace == null && FactsTrace == null && Candidates == null && IdListOverride == null; + + internal CompactBuiltinParameters Fork() => + new(_names, _format, _file, gate: _gate, state: _state, surveyOffsetFeet: _surveyOffsetFeet, + lookupNoneText: _lookupNoneText, quantities: _quantities); + + internal void CollectReport(CompactBuiltinParameters worker) + { + if (worker.Elements == 0) return; + Elements += worker.Elements; + Written += worker.Written; + ElementsWithList += worker.ElementsWithList; + LastIds = worker.LastIds; + foreach (var (reason, count) in worker._skipped) + _skipped[reason] = _skipped.GetValueOrDefault(reason) + count; + worker.Elements = worker.Written = worker.ElementsWithList = 0; + worker._skipped.Clear(); + } + /// The entries in ascending id order, and the (group, label) pairs that are listed but whose value is not written: a later /// parameter with the same pair must not be written either, because the writer keeps the first value of a repeated pair. /// Ids owned by another source () are not looked at. @@ -101,7 +129,7 @@ public CompactBuiltinResult GetEntries(Element element, Func? isOwned Elements++; int? header = _headerCategory(element); string recordClass = ElementListFacts.RecordClassName(element) ?? ""; - var facts = new ElementListFacts(element, header, _file, id => _names.Find(id)); + var facts = new ElementListFacts(element, header, _file, _findElement); FactsTrace?.Invoke(element, facts); var list = IdListOverride?.Invoke(element) is { } forced ? new CompactListResult(forced, null) @@ -109,15 +137,16 @@ public CompactBuiltinResult GetEntries(Element element, Func? isOwned LastIds = list.Ids; if (list.Ids is not { } ids) { - Skip("list: " + list.Unknown); - Trace?.Invoke(element, 0, "list: " + list.Unknown); - return new([], new HashSet<(string, string)>()); + string reason = "list: " + list.Unknown; + Skip(reason); + Trace?.Invoke(element, 0, reason); + return new([], EmptyUnvalidated); } ElementsWithList++; Prepare(element); var result = new List<(int, CompactProperty)>(ids.Length); - var unvalidated = new HashSet<(string, string)>(); - var seen = new HashSet<(string, string)>(); + HashSet<(string Group, string Label)>? unvalidated = null; + _seen.Clear(); foreach (int id in ids) { if (isOwned?.Invoke(id) == true) continue; @@ -135,8 +164,8 @@ public CompactBuiltinResult GetEntries(Element element, Func? isOwned } string? text = ValueText(element, id, header, out string? reason); // a repeated (group, label): the first id is the one kept, whatever the writer is given later - bool first = seen.Add((group, label)); - if (!first && text != null && unvalidated.Contains((group, label))) + bool first = _seen.Add((group, label)); + if (!first && text != null && unvalidated?.Contains((group, label)) == true) { text = null; reason = "label shared with an earlier parameter whose value is not written"; @@ -145,14 +174,14 @@ public CompactBuiltinResult GetEntries(Element element, Func? isOwned { Skip(reason!); Trace?.Invoke(element, id, reason); - if (first) unvalidated.Add((group, label)); + if (first) (unvalidated ??= new()).Add((group, label)); continue; } Trace?.Invoke(element, id, null); result.Add((id, new CompactProperty(group, label, text))); Written++; } - return new(result, unvalidated); + return new(result, unvalidated ?? EmptyUnvalidated); } private void Prepare(Element element) diff --git a/src/RvtIO/Compact/CompactElementNames.cs b/src/RvtIO/Compact/CompactElementNames.cs index 21453f1a..70463d57 100644 --- a/src/RvtIO/Compact/CompactElementNames.cs +++ b/src/RvtIO/Compact/CompactElementNames.cs @@ -1,3 +1,4 @@ +using System.Collections.Concurrent; using RvtIO.Export; using RvtIO.Internal; using RvtIO.Model; @@ -14,15 +15,17 @@ namespace RvtIO.Compact; /// internal sealed class CompactElementNames { - private readonly Dictionary _byId = []; - private readonly Dictionary _counts = []; + private readonly Dictionary _byId; + private readonly Dictionary _counts; private readonly ParsingState? _state; - private readonly Dictionary _cache = []; + private readonly ConcurrentDictionary _cache = new(); public CompactElementNames(RevitFileInfo info, ParsingState? state) { ArgumentNullException.ThrowIfNull(info); _state = state; + _byId = new(info.Elements.Count); + _counts = new(info.Elements.Count); foreach (Element element in info.Elements) { _byId.TryAdd(element.Id, element); @@ -30,20 +33,22 @@ public CompactElementNames(RevitFileInfo info, ParsingState? state) } } + internal void ApplyValidatedNames(RevitFileInfo info, ParsingState state) => + ValidatedElementNames.Apply(info, state, _byId, _counts); + /// The element with the id, null when the file has none. public Element? Find(int id) => _byId.GetValueOrDefault(id); /// The validated name of the element with the id; null when there is none. - public string? NameOf(int id) + public string? NameOf(int id) => _cache.GetOrAdd(id, static (key, names) => names.ResolveName(key), this); + + private string? ResolveName(int id) { - if (_cache.TryGetValue(id, out string? known)) return known; string? name = null; if (_byId.TryGetValue(id, out Element? element)) name = _state != null ? ValidatedElementNames.Resolve(element, _byId, _counts, _state)?.Name : element.RuleClassName == "MaterialElem" ? element.SerializedMaterialName : null; - if (string.IsNullOrWhiteSpace(name)) name = null; - _cache[id] = name; - return name; + return string.IsNullOrWhiteSpace(name) ? null : name; } } diff --git a/src/RvtIO/Compact/CompactIdentity.cs b/src/RvtIO/Compact/CompactIdentity.cs index 54aa86e6..e2f03cba 100644 --- a/src/RvtIO/Compact/CompactIdentity.cs +++ b/src/RvtIO/Compact/CompactIdentity.cs @@ -61,6 +61,7 @@ private readonly record struct ClassRule( private readonly Dictionary _rows = []; private readonly Func _headerCategory; private readonly Func _elementName; + internal bool UsesDefaultResolvers { get; } /// The elements of the element table (); a type is looked up among them. /// The header category of an element, null when unknown (default ). @@ -70,6 +71,7 @@ public CompactIdentity(IEnumerable rows, Func? headerCat { ArgumentNullException.ThrowIfNull(rows); foreach (var element in rows) _rows.TryAdd(element.Id, element); + UsesDefaultResolvers = headerCategory == null && elementName == null; _headerCategory = headerCategory ?? CompactHeaderCategory.Of; _elementName = elementName ?? (element => element.Name); } diff --git a/src/RvtIO/Compact/CompactJsonExporter.cs b/src/RvtIO/Compact/CompactJsonExporter.cs index 090b587b..12ae73df 100644 --- a/src/RvtIO/Compact/CompactJsonExporter.cs +++ b/src/RvtIO/Compact/CompactJsonExporter.cs @@ -1,4 +1,5 @@ using System.Globalization; +using System.Runtime.ExceptionServices; using RvtIO.Model; namespace RvtIO.Compact; @@ -14,6 +15,7 @@ namespace RvtIO.Compact; /// (none by default), written by one node at a time. public static class CompactJsonExporter { + private const int PropertyBatchSize = 2048; private static readonly IReadOnlyList NoProperties = []; /// Reads a Revit file and writes its compact JSON properties collection to . @@ -33,14 +35,16 @@ public static void Export(string rvtPath, string outputPath, RvtReaderOptions? r var info = reader.Read(rvtPath); var state = reader.LastParsingState ?? throw new InvalidOperationException("The reader kept no parsing state."); // The compact export reads Element.Name only where it is validated. - RvtIO.Export.ValidatedElementNames.Apply(info, state); - var identity = new CompactIdentity(CompactUniverse.Select(info)); + var names = new CompactElementNames(info, state); + names.ApplyValidatedNames(info, state); + var identity = new CompactIdentity(CompactUniverse.Enumerate(info)); // A wide layout does not decode geometry or curves: their quantities come from a second read in the Revit 2022 layout. var gate = CompactValueGate.ForLayout(info.GeometryUndecoded); var quantities = info.GeometryUndecoded ? CompactSolidQuantities.Read(rvtPath, readerOptions, gate.HasSolidRules) : null; // A project (.rvt) is a document without an owner family; an .rfa is not decided. var source = CompactPropertySources.Create(info, state, - rvtPath.EndsWith(".rvt", StringComparison.OrdinalIgnoreCase) ? true : null, gated: true, identity: identity, quantities: quantities); + rvtPath.EndsWith(".rvt", StringComparison.OrdinalIgnoreCase) ? true : null, + gated: true, identity: identity, quantities: quantities, names: names); Export(info, outputPath, source, diagnostics, identity, options); if (diagnostics != null) source.Builtin.WriteReport(diagnostics); } @@ -64,25 +68,66 @@ internal static CompactExportStats Export(RevitFileInfo info, Stream output, ICo using var diagnosticScope = DiagnosticSink.Use(diagnostics); var rows = CompactUniverse.Select(info); var builder = new CompactNodeBuilder(identity ?? new CompactIdentity(rows)); - int nodes = 0; long bytes; using (var writer = new CompactJsonWriter(output, options?.JsonClassNamePrefix ?? "")) { - foreach (var element in rows) - { - var properties = source == null ? NoProperties - : source.GetProperties(element) ?? throw new InvalidDataException($"The property source returned no list for element {element.Id}."); - writer.WriteNode(builder.Build(element, properties)); - nodes++; - } + int workers = Math.Min(8, Environment.ProcessorCount); + if (rows.Count >= PropertyBatchSize && workers > 1 && source is CompactPropertySources { CanFork: true } compact) + WriteBatches(rows, compact, builder, writer, workers); + else + foreach (var element in rows) + { + var properties = source == null ? NoProperties + : source.GetProperties(element) ?? throw new InvalidDataException($"The property source returned no list for element {element.Id}."); + writer.WriteNode(builder.Build(element, properties)); + } writer.Complete(); bytes = writer.BytesWritten; } - var stats = new CompactExportStats(nodes, bytes, builder.UnresolvedClassNameCount); + var stats = new CompactExportStats(rows.Count, bytes, builder.UnresolvedClassNameCount); if (diagnostics != null) WriteDiagnostics(diagnostics, stats, builder); return stats; } + private static void WriteBatches(List rows, CompactPropertySources source, CompactNodeBuilder builder, + CompactJsonWriter writer, int workerCount) + { + // Each worker has its own per-element scratch state. Keep a bounded set of properties in flight + // and write both rows and reports in the same order as the serial export. + var workers = new CompactPropertySources[workerCount]; + for (int i = 0; i < workers.Length; i++) workers[i] = source.Fork(); + var properties = new IReadOnlyList?[PropertyBatchSize]; + var failures = new ExceptionDispatchInfo?[workerCount]; + var parallel = new ParallelOptions { MaxDegreeOfParallelism = workerCount }; + for (int offset = 0; offset < rows.Count; offset += PropertyBatchSize) + { + int count = Math.Min(PropertyBatchSize, rows.Count - offset); + Parallel.For(0, workerCount, parallel, worker => + { + try + { + for (int i = count * worker / workerCount; i < count * (worker + 1) / workerCount; i++) + properties[i] = workers[worker].GetProperties(rows[offset + i]); + } + catch (Exception error) + { + failures[worker] = ExceptionDispatchInfo.Capture(error); + } + }); + for (int worker = 0; worker < workerCount; worker++) + { + for (int i = count * worker / workerCount; i < count * (worker + 1) / workerCount; i++) + { + var entries = properties[i]; + if (entries == null) failures[worker]!.Throw(); + writer.WriteNode(builder.Build(rows[offset + i], entries)); + properties[i] = null; + } + source.Builtin.CollectReport(workers[worker].Builtin); + } + } + } + private static void WriteDiagnostics(TextWriter diagnostics, CompactExportStats stats, CompactNodeBuilder builder) { diagnostics.WriteLine(string.Create(CultureInfo.InvariantCulture, $"Compact JSON: {stats.Nodes} nodes, {stats.Bytes} bytes")); diff --git a/src/RvtIO/Compact/CompactPropertySources.cs b/src/RvtIO/Compact/CompactPropertySources.cs index 46885b5a..f5796fb5 100644 --- a/src/RvtIO/Compact/CompactPropertySources.cs +++ b/src/RvtIO/Compact/CompactPropertySources.cs @@ -5,16 +5,26 @@ namespace RvtIO.Compact; internal sealed class CompactPropertySources : ICompactPropertySource { + private static readonly Func IsIfcId = CompactIfcParameters.OwnedIds.Contains; + private static readonly Comparison<(int Id, int Index, CompactProperty Property)> CompareEntryIds = static (a, b) => + a.Id == b.Id ? a.Index.CompareTo(b.Index) : a.Id.CompareTo(b.Id); + private readonly CompactBuiltinParameters _builtin; private readonly CompactIfcParameters _ifc; private readonly CompactUserParameters _user; private readonly CompactIdentityProperties? _identity; + private readonly CompactIdentity? _identityRules; + private readonly bool _ownsSources; + private readonly List<(int Id, int Index, CompactProperty Property)> _orderedEntries = []; - internal CompactPropertySources(CompactBuiltinParameters builtin, CompactIfcParameters ifc, CompactUserParameters user, CompactIdentity? identity = null) + internal CompactPropertySources(CompactBuiltinParameters builtin, CompactIfcParameters ifc, CompactUserParameters user, + CompactIdentity? identity = null, bool ownsSources = false) { _builtin = builtin; _ifc = ifc; _user = user; + _identityRules = identity; + _ownsSources = ownsSources; // the type entries of the identity block are listed by the same id list as the built-in entries _identity = identity == null ? null : new CompactIdentityProperties(identity, _ => _builtin.LastIds); } @@ -23,12 +33,18 @@ internal CompactPropertySources(CompactBuiltinParameters builtin, CompactIfcPara internal Action? UserTrace { set => _user.Trace = value; } internal CompactBuiltinParameters Builtin => _builtin; + internal bool CanFork => _ownsSources && _builtin.CanFork && Collision == null + && _user.Trace == null && _identityRules?.UsesDefaultResolvers != false; + + internal CompactPropertySources Fork() => new(_builtin.Fork(), _ifc, _user, _identityRules); + /// The composite of a file. internal static CompactPropertySources Create(RevitFileInfo info, ParsingState? state, bool? isProjectDocument, - Func? headerCategory = null, bool gated = true, CompactIdentity? identity = null, CompactSolidQuantities? quantities = null) + Func? headerCategory = null, bool gated = true, CompactIdentity? identity = null, + CompactSolidQuantities? quantities = null, CompactElementNames? names = null) { ArgumentNullException.ThrowIfNull(info); - var names = new CompactElementNames(info, state); + names ??= new CompactElementNames(info, state); var file = new CompactListFileFacts(info.SerializedIsWorkshared, isProjectDocument, info.Elements.Any(element => CompactIfcParameters.ClassName(element) == "DesignOptionSet"), DesignOptions.Of(info.Elements)); double? surveyOffset = info.SharedTransformIsActiveLocation && info.SharedTransform is { Length: 12 } transform ? transform[11] : null; @@ -37,25 +53,30 @@ internal static CompactPropertySources Create(RevitFileInfo info, ParsingState? var settings = info.SerializedFormatSettings; var user = new CompactUserParameters(info, settings == null ? null : (spec, raw) => CompactValueFormatter.Format(raw, spec, settings), - names.NameOf); - return new CompactPropertySources(builtin, new CompactIfcParameters(info), user, identity); + names.NameOf, names.Find); + return new CompactPropertySources(builtin, new CompactIfcParameters(info), user, identity, ownsSources: true); } public IReadOnlyList GetProperties(Element element) { - var builtin = _builtin.GetEntries(element, CompactIfcParameters.OwnedIds.Contains); - var entries = new List<(int Id, CompactProperty Property)>(builtin.Entries); - entries.AddRange(_ifc.GetEntries(element)); - if (_identity != null) entries.AddRange(_identity.GetEntries(element)); - var result = new List(entries.Count + 8); - // a stable sort: equal ids cannot occur (the two sources own disjoint ids), but the order must not depend on it - foreach (var entry in entries.OrderBy(entry => entry.Id)) result.Add(entry.Property); + var builtin = _builtin.GetEntries(element, IsIfcId); + _orderedEntries.Clear(); + AppendEntries(builtin.Entries); + AppendEntries(_ifc.GetEntries(element)); + if (_identity != null) AppendEntries(_identity.GetEntries(element)); + _orderedEntries.Sort(CompareEntryIds); + var result = new List(_orderedEntries.Count + 8); + foreach (var entry in _orderedEntries) result.Add(entry.Property); + _orderedEntries.Clear(); + int builtinCount = result.Count; foreach (var (user, family) in _user.GetPropertiesWithKind(element)) { if (!family && builtin.Unvalidated.Contains((user.Group, user.Label))) continue; - int earlier = result.FindIndex(p => p.Group == user.Group && p.Label == user.Label); - if (earlier >= 0) + int earlier = 0; + while (earlier < result.Count && (result[earlier].Group != user.Group || result[earlier].Label != user.Label)) + earlier++; + if (earlier < result.Count) { Collision?.Invoke(element, result[earlier], user); // a parameter the family defines comes before the built-in parameters @@ -65,4 +86,13 @@ public IReadOnlyList GetProperties(Element element) } return result; } + + private void AppendEntries(IReadOnlyList<(int Id, CompactProperty Property)> entries) + { + for (int i = 0; i < entries.Count; i++) + { + var (id, property) = entries[i]; + _orderedEntries.Add((id, _orderedEntries.Count, property)); + } + } } diff --git a/src/RvtIO/Compact/CompactSolidQuantities.cs b/src/RvtIO/Compact/CompactSolidQuantities.cs index 28d68b6b..524b1722 100644 --- a/src/RvtIO/Compact/CompactSolidQuantities.cs +++ b/src/RvtIO/Compact/CompactSolidQuantities.cs @@ -52,13 +52,19 @@ internal static CompactSolidQuantities Read(string path, RvtReaderOptions option internal static CompactSolidQuantities From(RevitFileInfo info, ParsingState state, Func? wantsSolids) { var result = new CompactSolidQuantities(); - foreach (var element in info.Elements) + var previousCache = state.SymbolPlacementGeometry; + state.SymbolPlacementGeometry ??= new(ReferenceEqualityComparer.Instance); + try { - if (element.Parameters.FirstOrDefault(p => p.Id == CurveElemLengthParameter) is { Value: double length }) - result._curveLength.TryAdd(element.Id, length); - if (element.CategoryId is int category && (wantsSolids?.Invoke(category) ?? true)) - result._solids.TryAdd(element.Id, Measure(element, state) with { Category = category }); + foreach (var element in info.Elements) + { + if (element.Parameters.FirstOrDefault(p => p.Id == CurveElemLengthParameter) is { Value: double length }) + result._curveLength.TryAdd(element.Id, length); + if (element.CategoryId is int category && (wantsSolids?.Invoke(category) ?? true)) + result._solids.TryAdd(element.Id, Measure(element, state) with { Category = category }); + } } + finally { state.SymbolPlacementGeometry = previousCache; } return result; } @@ -73,11 +79,12 @@ internal static CompactSolidQuantities From(RevitFileInfo info, ParsingState sta internal static Solids Measure(Element element, ParsingState state) { - var levels = new GeometryData?[3]; - ElementBuilder.LevelGeometries(element, state, (slot, geometry) => levels[slot] = geometry); - int chosen = Array.FindIndex(levels, geometry => geometry?.BrepSolids is { Count: > 0 }); - if (chosen < 0) return new Solids("none", 2, 0, 0, 0, 0, null); - return Measure(levels[chosen]!, chosen); + for (int level = 1; level <= 2; level++) + if (ElementBuilder.GeometryAtDetailLevel(element, state, level) is { BrepSolids.Count: > 0 } geometry) + return Measure(geometry, level - 1); + return element.Geometry is { BrepSolids.Count: > 0 } fine + ? Measure(fine, 2) + : new Solids("none", 2, 0, 0, 0, 0, null); } internal static Solids Measure(GeometryData geometry, int level) diff --git a/src/RvtIO/Compact/CompactUserParameters.cs b/src/RvtIO/Compact/CompactUserParameters.cs index c70876e3..f80156e0 100644 --- a/src/RvtIO/Compact/CompactUserParameters.cs +++ b/src/RvtIO/Compact/CompactUserParameters.cs @@ -12,13 +12,20 @@ internal sealed class CompactUserParameters : ICompactPropertySource private readonly UserParameterCatalog? _catalog; private readonly Func? _formatNumber; private readonly Func _elementName; - private readonly Dictionary _byId; + private readonly Func _findElement; - public CompactUserParameters(RevitFileInfo info, Func? formatNumber = null, Func? elementName = null) + public CompactUserParameters(RevitFileInfo info, Func? formatNumber = null, + Func? elementName = null, Func? findElement = null) { _catalog = info.UserParameters; - _byId = info.Elements.GroupBy(e => e.Id).ToDictionary(g => g.Key, g => g.First()); _formatNumber = formatNumber; + if (findElement == null) + { + var elements = new Dictionary(info.Elements.Count); + foreach (var element in info.Elements) elements.TryAdd(element.Id, element); + findElement = id => elements.GetValueOrDefault(id); + } + _findElement = findElement; if (elementName == null) { var names = new Dictionary(); @@ -33,10 +40,12 @@ public CompactUserParameters(RevitFileInfo info, Func? public IReadOnlyList GetEntries(Element element) { if (_catalog == null) return []; - var result = new List(); var source = CompactIfcParameters.CenterLineClasses.Contains(ElementListFacts.RecordClassName(element) ?? "") - && element.SerializedOwningElementId is int owner && _byId.TryGetValue(owner, out var ownerElement) ? ownerElement : element; - foreach (var entry in _catalog.EntriesOf(source)) + && element.SerializedOwningElementId is int owner && _findElement(owner) is { } ownerElement ? ownerElement : element; + var entries = _catalog.EntriesOf(source); + if (entries.Count == 0) return []; + var result = new List(); + foreach (var entry in entries) { var d = entry.Definition; if (UserParameterCatalog.GroupLabelOf(d) is not { } group) continue; @@ -75,8 +84,10 @@ public IReadOnlyList GetEntries(Element element) /// The printed properties with the kind of their parameter (true: defined by the family). internal IReadOnlyList<(CompactProperty Property, bool Family)> GetPropertiesWithKind(Element element) { + var entries = GetEntries(element); + if (entries.Count == 0) return []; var result = new List<(CompactProperty, bool)>(); - foreach (var e in GetEntries(element)) + foreach (var e in entries) { string? text = e.Text ?? (e.Raw is double raw && e.Spec != null ? _formatNumber?.Invoke(e.Spec, raw) : null); if (text != null) result.Add((new CompactProperty(e.Group, e.Label, text), e.Family)); diff --git a/src/RvtIO/Export/ValidatedElementNames.cs b/src/RvtIO/Export/ValidatedElementNames.cs index 8c6cd437..bdef3ee4 100644 --- a/src/RvtIO/Export/ValidatedElementNames.cs +++ b/src/RvtIO/Export/ValidatedElementNames.cs @@ -39,17 +39,23 @@ internal static class ValidatedElementNames /// internal static int Apply(RevitFileInfo info, ParsingState state) { - var byId = new Dictionary(); - var counts = new Dictionary(); + var byId = new Dictionary(info.Elements.Count); + var counts = new Dictionary(info.Elements.Count); foreach (Element element in info.Elements) { byId.TryAdd(element.Id, element); counts[element.Id] = counts.GetValueOrDefault(element.Id) + 1; } + return Apply(info, state, byId, counts); + } + + internal static int Apply(RevitFileInfo info, ParsingState state, + IReadOnlyDictionary byId, IReadOnlyDictionary counts) + { // Resolve everything before assigning: no resolution may read another element's replaced Name. var names = new string?[info.Elements.Count]; - for (int index = 0; index < names.Length; index++) - names[index] = Resolve(info.Elements[index], byId, counts, state)?.Name; + Parallel.For(0, names.Length, + index => names[index] = Resolve(info.Elements[index], byId, counts, state)?.Name); int named = 0; for (int index = 0; index < names.Length; index++) { diff --git a/src/RvtIO/FilteredElementCollector.cs b/src/RvtIO/FilteredElementCollector.cs index 49826351..98863bb9 100644 --- a/src/RvtIO/FilteredElementCollector.cs +++ b/src/RvtIO/FilteredElementCollector.cs @@ -58,7 +58,7 @@ public FilteredElementCollector WhereElementIsNotElementType() // Fallback: keep only elements that have ELEM_TYPE_PARAM (family instances) _source = _source.Where(e => e.Parameters.Any(p => - p.Definition?.Name is "ELEM_TYPE_PARAM" or "ELEM_FAMILY_AND_TYPE_PARAM")); + p.DefinitionName is "ELEM_TYPE_PARAM" or "ELEM_FAMILY_AND_TYPE_PARAM")); } return this; } @@ -77,7 +77,7 @@ public FilteredElementCollector WhereElementIsElementType() { _source = _source.Where(e => !e.Parameters.Any(p => - p.Definition?.Name is "ELEM_TYPE_PARAM" or "ELEM_FAMILY_AND_TYPE_PARAM")); + p.DefinitionName is "ELEM_TYPE_PARAM" or "ELEM_FAMILY_AND_TYPE_PARAM")); } return this; } @@ -116,7 +116,7 @@ public FilteredElementCollector WhereHasParameters() public FilteredElementCollector WhereHasParameter(string paramName) { _source = _source.Where(e => - e.Parameters.Any(p => p.Definition?.Name == paramName)); + e.Parameters.Any(p => p.DefinitionName == paramName)); return this; } @@ -125,7 +125,7 @@ public FilteredElementCollector WhereHasParameter(BuiltInParameter bip) { int bipId = (int)bip; _source = _source.Where(e => - e.Parameters.Any(p => p.Definition?.Id == bipId)); + e.Parameters.Any(p => p.DefinitionId == bipId)); return this; } diff --git a/src/RvtIO/Geometry/FacetedShell.cs b/src/RvtIO/Geometry/FacetedShell.cs index 69f277ca..e20f717c 100644 --- a/src/RvtIO/Geometry/FacetedShell.cs +++ b/src/RvtIO/Geometry/FacetedShell.cs @@ -77,17 +77,18 @@ internal static bool TryOrientExactFacetedShell(IReadOnlyList faces, long edgeUseCount = 0; foreach (int faceIndex in indices) { - var normalized = CloneFace(faces[faceIndex]); - if (normalized.OuterVertices is not { Count: >= 3 } outer + var source = faces[faceIndex]; + if (source.OuterVertices is not { Count: >= 3 } outer || outer.Any(point => point.Length < 3 || !double.IsFinite(point[0]) || !double.IsFinite(point[1]) || !double.IsFinite(point[2]))) return false; + var normalized = CloneFaceMetadata(source); normalized.OuterVertices = CleanPrecisionLoop(outer); if (normalized.OuterVertices.Count < 3 || FaceCollapsesAtIfcPrecision(normalized)) return false; - normalized.InnerVertices = normalized.InnerVertices? + normalized.InnerVertices = source.InnerVertices? .Where(ring => ring.Count >= 3 && ring.All(point => point.Length >= 3 && double.IsFinite(point[0]) && double.IsFinite(point[1]) && double.IsFinite(point[2]))) @@ -320,19 +321,17 @@ static List CleanPrecisionLoop(List ring) { var first = IfcPrecisionKeyFeet(ring[0]); var last = first; - int count = 1; + var clean = new List(ring.Count) { (double[])ring[0].Clone() }; for (int index = 1; index < ring.Count; index++) { var point = ring[index]; var key = IfcPrecisionKeyFeet(point); if (last == key) continue; - if (count != index) ring[count] = point; - count++; + clean.Add((double[])point.Clone()); last = key; } - if (count > 1 && first == last) count--; - ring.RemoveRange(count, ring.Count - count); - return ring; + if (clean.Count > 1 && first == last) clean.RemoveAt(clean.Count - 1); + return clean; } static void ReverseFace(GeoFace face, bool detachVertices) @@ -355,27 +354,18 @@ void ReverseRing(List ring) } } - static GeoFace CloneFace(GeoFace source) - { - static List CopyRing(List ring) => - ring.Select(point => (double[])point.Clone()).ToList(); - - return new GeoFace + static GeoFace CloneFaceMetadata(GeoFace source) => + new((double[])source.Origin.Clone(), (double[])source.Normal.Clone(), includePlaneAxes: false) { - Origin = (double[])source.Origin.Clone(), XVector = (double[])source.XVector.Clone(), YVector = (double[])source.YVector.Clone(), - Normal = (double[])source.Normal.Clone(), Envelope = source.Envelope is null ? null : (double[])source.Envelope.Clone(), Area = source.Area, InnerLoops = source.InnerLoops?.Select(loop => (double[])loop.Clone()).ToList(), - OuterVertices = source.OuterVertices is null ? null : CopyRing(source.OuterVertices), - InnerVertices = source.InnerVertices?.Select(CopyRing).ToList(), AlternativeOuterVertices = source.AlternativeOuterVertices is null ? null : source.AlternativeOuterVertices.Select(point => (double[])point.Clone()).ToList(), EdgeIndices = source.EdgeIndices?.ToList(), }; - } } /// diff --git a/src/RvtIO/Ifc/IfcExporter.OwnFamilyCutout.cs b/src/RvtIO/Ifc/IfcExporter.OwnFamilyCutout.cs index 0f5b62f6..e3c17c79 100644 --- a/src/RvtIO/Ifc/IfcExporter.OwnFamilyCutout.cs +++ b/src/RvtIO/Ifc/IfcExporter.OwnFamilyCutout.cs @@ -193,7 +193,7 @@ private static bool HostedFillingProductCanBeEmitted(Element cutter, || cutter.Geometry is not { Faces.Count: > 0 } geometry || !geometry.Faces.Any(face => face.OuterVertices is { Count: >= 3 }) || FacetedGeometryCannotCreateProductShapeAtIfcPrecision(geometry)) return false; - var levels = cutter.Parameters.Where(parameter => parameter.Definition?.Name is + var levels = cutter.Parameters.Where(parameter => parameter.DefinitionName is "LEVEL_PARAM" or "FAMILY_LEVEL_PARAM" or "SCHEDULE_LEVEL_PARAM" or "INSTANCE_REFERENCE_LEVEL_PARAM") .Select(parameter => parameter.Value).OfType() .Where(id => id > 0 && elements.TryGetValue(id, out var level) && level.CategoryId == -2000240).ToArray(); diff --git a/src/RvtIO/Ifc/IfcExporter.QuantitiesCurrent.cs b/src/RvtIO/Ifc/IfcExporter.QuantitiesCurrent.cs index 7dc2a241..e00200d1 100644 --- a/src/RvtIO/Ifc/IfcExporter.QuantitiesCurrent.cs +++ b/src/RvtIO/Ifc/IfcExporter.QuantitiesCurrent.cs @@ -896,7 +896,7 @@ private List QuantitiesOfProductCurrent(QuantityContextCurrent co foreach (Element? owner in new[] { instance, type }) if (owner != null) foreach (var parameter in owner.Parameters) - if (parameter.Definition?.Name == name && !parameter.HasNoRevitValue && !parameter.IsApproximate + if (parameter.DefinitionName == name && !parameter.HasNoRevitValue && !parameter.IsApproximate && parameter.Value is double named && (!double.IsFinite(named) || Math.Abs(named) < 1e29) && named > 0 && owner.BoundingBoxDimensionParamIds?.Contains(parameter.Id) != true) return named; diff --git a/src/RvtIO/Ifc/IfcExporter.RampCurrent.cs b/src/RvtIO/Ifc/IfcExporter.RampCurrent.cs index f09e5a2d..9bdefc97 100644 --- a/src/RvtIO/Ifc/IfcExporter.RampCurrent.cs +++ b/src/RvtIO/Ifc/IfcExporter.RampCurrent.cs @@ -61,7 +61,7 @@ private static List RelinkRampTypes(List elements) if (relink) { var parameters = ramp.Parameters.ToList(); - int index = parameters.FindIndex(p => p.Definition?.Name is "ELEM_TYPE_PARAM" && p.Value is int); + int index = parameters.FindIndex(p => p.DefinitionName is "ELEM_TYPE_PARAM" && p.Value is int); if (index >= 0) parameters[index] = parameters[index].ShallowCopy(typeId); else parameters.Add(new Parameter { diff --git a/src/RvtIO/Ifc/IfcExporter.cs b/src/RvtIO/Ifc/IfcExporter.cs index f2a8d64c..a711e6d5 100644 --- a/src/RvtIO/Ifc/IfcExporter.cs +++ b/src/RvtIO/Ifc/IfcExporter.cs @@ -1546,7 +1546,7 @@ bool RejectStandaloneWriterPath(string stage) } var explicitLevelIds = opening.Parameters - .Where(parameter => parameter.Definition?.Name is + .Where(parameter => parameter.DefinitionName is "LEVEL_PARAM" or "FAMILY_LEVEL_PARAM" or "SCHEDULE_LEVEL_PARAM" or "INSTANCE_REFERENCE_LEVEL_PARAM") .Select(parameter => parameter.Value) @@ -1750,7 +1750,7 @@ bool HasCompetingExactHostedWriterAuthority( // A placed family instance must reference a project level when its serialized level // parameters point to Level elements. var explicitLevelIds = elem.Parameters - .Where(parameter => parameter.Definition?.Name is + .Where(parameter => parameter.DefinitionName is "LEVEL_PARAM" or "FAMILY_LEVEL_PARAM" or "SCHEDULE_LEVEL_PARAM" or "INSTANCE_REFERENCE_LEVEL_PARAM") .Select(parameter => parameter.Value) @@ -1914,7 +1914,7 @@ bool HasCompetingExactHostedWriterAuthority( (elem.DecodedBox ?? elem.Geometry?.BoundingBox) is { Length: >= 6 } diagBox ? diagBox[2].ToString("R", CultureInfo.InvariantCulture) : "-", storeyIds.FirstOrDefault(pair => pair.Value == elemStoreyId).Key, string.Join(',', elem.Parameters.Where(p => p.StorageType == StorageType.ElementId && p.Value is int) - .Select(p => $"{p.Id}:{p.Definition?.Name}={p.Value}"))) + "\n"); + .Select(p => $"{p.Id}:{p.DefinitionName}={p.Value}"))) + "\n"); if (ifcType == "IFCCURTAINWALL" && exactCurtainChildren.ContainsKey(elem.Id)) { @@ -5820,14 +5820,14 @@ int EnsureSurfaceStyle(int materialElementId, string materialName) } else if (elemById.TryGetValue(materialElementId, out var materialElement) && materialElement.Parameters.FirstOrDefault(parameter => - parameter.Definition?.Name == "MATERIAL_PARAM_COLOR")?.Value is int packedColor) + parameter.DefinitionName == "MATERIAL_PARAM_COLOR")?.Value is int packedColor) { var (red, green, blue) = DecodePackedMaterialColor(packedColor); int transparencyPercent = materialElement.Parameters.FirstOrDefault(parameter => - parameter.Definition?.Name == "MATERIAL_PARAM_TRANSPARENCY")?.Value is int transparency + parameter.DefinitionName == "MATERIAL_PARAM_TRANSPARENCY")?.Value is int transparency ? Math.Clamp(transparency, 0, 100) : 0; int shininess = materialElement.Parameters.FirstOrDefault(parameter => - parameter.Definition?.Name == "MATERIAL_PARAM_SHININESS")?.Value is int shine + parameter.DefinitionName == "MATERIAL_PARAM_SHININESS")?.Value is int shine ? Math.Max(0, shine) : 0; // The current profile writes the transparency the file stores (a float: 0.975 where @@ -6137,7 +6137,7 @@ int EnsureUnnamedMaterial() => if (source.Geometry?.GStyleElemId is > 0) candidateIds.Add(source.Geometry.GStyleElemId); candidateIds.AddRange(source.Parameters - .Where(parameter => parameter.Definition?.Name?.Contains( + .Where(parameter => parameter.DefinitionName?.Contains( "MATERIAL", StringComparison.OrdinalIgnoreCase) == true) .Select(parameter => parameter.Value).OfType()); candidateIds.AddRange(source.References ?? Enumerable.Empty()); @@ -6431,10 +6431,10 @@ bool IsSerializedMaterial(Element candidate) => candidate.CategoryId == -2000700 && (candidate.HasShadingAppearance && candidate.Parameters.Any(parameter => - parameter.Definition?.Name == "MATERIAL_PARAM_COLOR" + parameter.DefinitionName == "MATERIAL_PARAM_COLOR" && parameter.Value is int) && candidate.Parameters.Any(parameter => - parameter.Definition?.Name == "MATERIAL_PARAM_SHININESS" + parameter.DefinitionName == "MATERIAL_PARAM_SHININESS" && parameter.Value is int) || CurrentProfile && candidate.SerializedMaterialName is { Length: > 0 }); @@ -6995,7 +6995,7 @@ static bool IsUsableName([System.Diagnostics.CodeAnalysis.NotNullWhen(true)] str // The tagged MATERIAL_NAME field is the authored material display name when it is present. string? serializedName = material.Parameters.FirstOrDefault(parameter => - parameter.Definition?.Name == "MATERIAL_NAME")?.Value as string; + parameter.DefinitionName == "MATERIAL_NAME")?.Value as string; if (IsUsableName(serializedName)) return serializedName!; if (IsUsableName(material.Name)) @@ -31410,7 +31410,7 @@ static bool TryGetUniqueSerializedDimension( out int nameMatches, out int exactMatches) { var named = element.Parameters.Where(parameter => - parameter.Definition?.Name == name) + parameter.DefinitionName == name) .ToList(); var matches = named.Where(parameter => { @@ -31434,7 +31434,7 @@ static bool TryGetUniqueSerializedDimension( StringComparison.OrdinalIgnoreCase) == true || exactSharedDefinition && parameter.SpecType == null; - return parameter.Definition?.Name == name + return parameter.DefinitionName == name && parameter.Id > 0 && parameter.StorageType == StorageType.Double && (exactFamilyDefinition || exactSharedDefinition) @@ -31452,7 +31452,7 @@ static bool TryGetUniqueSerializedDimension( } static string DescribeNamedParameters(Element element, string name) => string.Join("|", element.Parameters - .Where(parameter => parameter.Definition?.Name == name) + .Where(parameter => parameter.DefinitionName == name) .Select(parameter => $"id={parameter.Id},guid={parameter.Guid?.ToString() ?? "null"}," + $"storage={parameter.StorageType},forge={parameter.ForgeId ?? "null"}," @@ -57390,7 +57390,7 @@ is not (-2000151 or -2000023))) foreach (Element cutter in genericCutters) { var familyTypeParameters = cutter.Parameters.Where(parameter => - parameter.Definition?.Name == "ELEM_TYPE_PARAM") + parameter.DefinitionName == "ELEM_TYPE_PARAM") .ToList(); if (familyTypeParameters is not [{ Id: -1002050, StorageType: StorageType.ElementId, @@ -58038,7 +58038,7 @@ double NormalFeet(double[] point) => return Reject("instance-host-set"); var familyTypeParameters = hostedElement.Parameters - .Where(parameter => parameter.Definition?.Name == "ELEM_TYPE_PARAM") + .Where(parameter => parameter.DefinitionName == "ELEM_TYPE_PARAM") .ToList(); if (familyTypeParameters is not [{ Id: -1002050, StorageType: StorageType.ElementId, @@ -58820,7 +58820,7 @@ bool TryGetExactInstanceFamilyLength( string name, out double value) { var parameters = hostedElement.Parameters - .Where(parameter => parameter.Definition?.Name == name + .Where(parameter => parameter.DefinitionName == name && parameter.Id > 0 && parameter.Guid == null && parameter.ForgeId?.StartsWith( @@ -59141,7 +59141,7 @@ static bool TryGetUniqueExternalLength( bool TryGetUniqueFamilyLength(string name, out double value) { var matches = hostedElement.Parameters.Where(parameter => - parameter.Definition?.Name == name + parameter.DefinitionName == name && parameter.Id > 0 && parameter.Guid == null && parameter.StorageType == StorageType.Double @@ -59453,7 +59453,7 @@ static bool TryGetUniqueExternalLength( bool TryGetUniqueFamilyLength(string name, out double value) { var matches = hostedElement.Parameters.Where(parameter => - parameter.Definition?.Name == name + parameter.DefinitionName == name && parameter.Id > 0 && parameter.Guid == null && parameter.StorageType == StorageType.Double @@ -59888,7 +59888,7 @@ bool TryGetExactInstanceFamilyLength( string name, out double value) { var parameters = hostedElement.Parameters - .Where(parameter => parameter.Definition?.Name == name + .Where(parameter => parameter.DefinitionName == name && parameter.Id > 0 && parameter.Guid == null && parameter.ForgeId?.StartsWith( @@ -60272,7 +60272,7 @@ bool TryGetExactInstanceFamilyLength( string name, bool requireWritable, out double value) { var parameters = hostedElement.Parameters - .Where(parameter => parameter.Definition?.Name == name + .Where(parameter => parameter.DefinitionName == name && parameter.Id > 0 && parameter.Guid == null && (!requireWritable || !parameter.IsReadOnly) @@ -61354,7 +61354,7 @@ bool TryGetExactInstanceFamilyLength( string name, bool requireWritable, out double value) { var parameters = hostedElement.Parameters - .Where(parameter => parameter.Definition?.Name == name + .Where(parameter => parameter.DefinitionName == name && parameter.Id > 0 && parameter.Guid == null && (!requireWritable || !parameter.IsReadOnly) @@ -62269,7 +62269,7 @@ bool InSegment((double CentreAlong, double Width, double BaseZ, "Четверть Сверху"; var directedDepthParameters = hostedElement.Parameters .Where(parameter => - parameter.Definition?.Name is + parameter.DefinitionName is InnerAdditionalDepthName or OuterAdditionalDepthName) .ToList(); @@ -62278,7 +62278,7 @@ bool TryGetUniqueFamilyLength( { var matches = hostedElement.Parameters .Where(parameter => - parameter.Definition?.Name == name + parameter.DefinitionName == name && parameter.Id > 0 && parameter.Guid == null && parameter.ForgeId?.StartsWith( @@ -63963,7 +63963,7 @@ private static ExactIsExternalParameterResult ResolveExactWallStructuralUsagePar Element element, int parameterId = WallStructuralUsageParamId) { List matches = element.Parameters - .Where(parameter => parameter.Definition?.Id == parameterId) + .Where(parameter => parameter.DefinitionId == parameterId) .ToList(); if (matches.Count == 0) return new(ExactIsExternalParameterState.Absent); @@ -64137,9 +64137,9 @@ internal static bool HasProjectLevelGuidParameter(RevitFileInfo info) => info.Elements.Any(element => element.Parameters.Any(parameter => parameter.Id is (int)BuiltIns.BuiltInParameter.IFC_PROJECT_GUID or (int)BuiltIns.BuiltInParameter.IFC_BUILDING_GUID or (int)BuiltIns.BuiltInParameter.IFC_SITE_GUID - || parameter.Definition?.Id is (int)BuiltIns.BuiltInParameter.IFC_PROJECT_GUID + || parameter.DefinitionId is (int)BuiltIns.BuiltInParameter.IFC_PROJECT_GUID or (int)BuiltIns.BuiltInParameter.IFC_BUILDING_GUID or (int)BuiltIns.BuiltInParameter.IFC_SITE_GUID - || parameter.Definition?.Name is "IfcProject GUID" or "IfcBuilding GUID" or "IfcSite GUID" or "IfcSiteGUID")); + || parameter.DefinitionName is "IfcProject GUID" or "IfcBuilding GUID" or "IfcSite GUID" or "IfcSiteGUID")); private static readonly Regex SingleObjectPropertyRelation = new( @"^'[0-9A-Za-z_$]{22}',#\d+,\$,\$,\(#(\d+)\),#(\d+)$", RegexOptions.Compiled); @@ -64883,7 +64883,7 @@ private static bool IsIfcGuidParameterId(int? id) => id is (int)BuiltIns.BuiltInParameter.IFC_GUID or (int)BuiltIns.BuiltInParameter.IFC_TYPE_GUID; private static bool HasIfcGuidOverride(IEnumerable parameters, bool currentProfile) => !currentProfile && parameters.Any(parameter => - (IsIfcGuidParameterId(parameter.Id) || IsIfcGuidParameterId(parameter.Definition?.Id)) + (IsIfcGuidParameterId(parameter.Id) || IsIfcGuidParameterId(parameter.DefinitionId)) && parameter.StorageType == StorageType.String && parameter.Value is string { Length: > 0 }); /// Pset_WallCommon.ExtendToStructure. @@ -64926,7 +64926,7 @@ private static ExactIsExternalParameterResult ResolveExactFloorParamIsStructural return new(ExactIsExternalParameterState.Absent); List matches = element.Parameters - .Where(parameter => parameter.Definition?.Id == FloorParamIsStructuralId) + .Where(parameter => parameter.DefinitionId == FloorParamIsStructuralId) .ToList(); if (matches.Count == 0) return new(ExactIsExternalParameterState.Absent); @@ -65864,7 +65864,7 @@ private static bool TryGetSyntheticRuntimeInstanceLengthMarker( } private static bool ParameterNameEquals(Parameter parameter, string name) => - parameter.Definition?.Name is string parameterName + parameter.DefinitionName is string parameterName && string.Equals( parameterName.Replace(" ", null), name.Replace(" ", null), StringComparison.InvariantCultureIgnoreCase); @@ -66302,7 +66302,7 @@ private void ExportPropertySets(StepWriter w, Element elem, int elemEntityId, in continue; } - string paramName = p.Definition?.Name ?? $"Param_{p.Id}"; + string paramName = p.DefinitionName ?? $"Param_{p.Id}"; string groupName = "Other"; if (RevitParameterGroups && Parsing.ApiParameterDefinitions.TryGet( p.Id, out string apiName, out int apiGroupId, out string apiDataType)) @@ -66422,7 +66422,7 @@ static double NamedDimension(Element e, Element? type, string token) { foreach (var p in e.Parameters.Concat(type?.Parameters ?? Enumerable.Empty())) if (p.Value is double d && d > 0.03 && d < 100 - && p.Definition?.Name?.Contains(token, StringComparison.OrdinalIgnoreCase) == true) + && p.DefinitionName?.Contains(token, StringComparison.OrdinalIgnoreCase) == true) return d; return 0; } @@ -68628,7 +68628,7 @@ private static void AppendWallDiag(string path, Element wall) && ids.Split(',').Contains(wall.Id.ToString())) { var detail = new System.Text.StringBuilder().Append("# wall ").Append(wall.Id).Append(" name=").Append(wall.Name).Append(" cat=").Append(wall.CategoryId).Append('\n'); - foreach (var p in wall.Parameters) detail.Append(" p ").Append(p.Id).Append(' ').Append(p.Definition?.Name).Append(" = ").Append(p.Value).Append('\n'); + foreach (var p in wall.Parameters) detail.Append(" p ").Append(p.Id).Append(' ').Append(p.DefinitionName).Append(" = ").Append(p.Value).Append('\n'); for (int fi = 0; fi < faces.Count; fi++) { var f = faces[fi]; diff --git a/src/RvtIO/Internal/ElementRecord.cs b/src/RvtIO/Internal/ElementRecord.cs index 78867434..5fe3a794 100644 --- a/src/RvtIO/Internal/ElementRecord.cs +++ b/src/RvtIO/Internal/ElementRecord.cs @@ -1,20 +1,17 @@ namespace RvtIO.Internal; -internal record BipEntry(int BipId, string? BipName, int FieldType, int? Value); +internal readonly record struct BipEntry(int BipId, string? BipName, int FieldType, int? Value); internal record ElementRecord { public uint ElemId { get; set; } - public byte[] Body { get; set; } = Array.Empty(); + public ReadOnlyMemory Body { get; set; } public List References { get; set; } = new(); public List BipParams { get; set; } = new(); public double[]? Geometry { get; set; } public int? CategoryId { get; set; } public ushort Subclass { get; set; } - public HashSet WritableParamIds { get; set; } = new(); - - /// All schema entry values (int32) in order. Index = field position in class hierarchy. - public List EntryValues { get; set; } = new(); + public HashSet? WritableParamIds { get; set; } } internal record BaseElementFields diff --git a/src/RvtIO/Internal/GRepData.cs b/src/RvtIO/Internal/GRepData.cs index 9416a8aa..a2fab57f 100644 --- a/src/RvtIO/Internal/GRepData.cs +++ b/src/RvtIO/Internal/GRepData.cs @@ -81,6 +81,7 @@ internal record GRepData /// m_complexCutGeoms field and selected faces below that exact branch. public bool IsFamilyComplexCut { get; set; } + public (int Faces, int Edges, int Solids)? QueueSummary { get; set; } public Dictionary? QueueClassCounts { get; set; } /// True when the serialized graph of this block holds detail-level alternatives (a GConditionInt on the detail diff --git a/src/RvtIO/Internal/ParsingState.cs b/src/RvtIO/Internal/ParsingState.cs index c03c2917..68cb265d 100644 --- a/src/RvtIO/Internal/ParsingState.cs +++ b/src/RvtIO/Internal/ParsingState.cs @@ -150,20 +150,16 @@ public TfBlockDeserializer.UnitsElemOptions? OwnDocumentUnitOptions public HashSet AllKnownIds { get; set; } = new(); public Dictionary> ElemStrings { get; set; } = new(); public Dictionary> ElemScanStrings { get; set; } = new(); - public Dictionary> ElemDoubles { get; set; } = new(); + // PrePropagateBipDoubles can share inherited maps. After that pass they are read-only. public Dictionary> ElemBipDoubles { get; set; } = new(); public Dictionary> ElemParamStrings { get; set; } = new(); public Dictionary> ElemBipInts { get; set; } = new(); public Dictionary ElemBaseFields { get; set; } = new(); public Dictionary GrepBlocks { get; set; } = new(); + // Symbol-local faces are read-only to the placement pass. The cache is scoped to model building. + internal Dictionary? SymbolPlacementGeometry { get; set; } internal Dictionary RailingQuantityInputs { get; } = new(); - /// While set, the symbols placed from are taken at the Coarse detail level. - public bool CoarseView { get; set; } - public bool IncludeNonVisibleQuantities { get; set; } - - /// The detail level the geometry is placed at: 0 Fine, 1 Coarse, 2 Medium. - public int DetailView { get; set; } public Dictionary OwnWallPlanarBodies { get; } = new(); /// FamilySymbol.m_complexCutGeoms decoded as an exact family-local BRep. @@ -597,6 +593,7 @@ internal bool IsParameterElement(uint id) => OwnedElementClassRoots.TryGetValue( /// Block classIdx inventory: classIdx -> (count, totalBytes, sampleElemIds, sampleData). public Dictionary BlockClassInventory { get; set; } = new(); + internal bool CollectBlockClassInventory { get; init; } = true; /// ForgeTypeId Spec Registry extracted from 0x0FBD blocks. /// Maps spec URN -> (symbolURN, unitURN, conversionFactor). diff --git a/src/RvtIO/Internal/StairComponentSource.cs b/src/RvtIO/Internal/StairComponentSource.cs index 481fd167..07f4e45d 100644 --- a/src/RvtIO/Internal/StairComponentSource.cs +++ b/src/RvtIO/Internal/StairComponentSource.cs @@ -66,7 +66,8 @@ internal static bool CountsClassRoot(ParsingState state, ushort classId, uint ow TfBlockDeserializer.IsSubclassOf(classId, 37) && (classId == 3681 || (state.ElemRecOwningElementIds?.ContainsKey(owner) ?? false)); - internal static void Apply(IReadOnlyList elements, ParsingState state) + internal static void Apply(IReadOnlyList elements, ParsingState state, + IReadOnlyDictionary? unique = null) { foreach (var element in elements) { @@ -79,7 +80,7 @@ internal static void Apply(IReadOnlyList elements, ParsingState state) element.SerializedStairRunInput = null; } if (state.ElemRecOwningElementIds == null) return; - var unique = elements.GroupBy(element => element.Id) + unique ??= elements.GroupBy(element => element.Id) .Where(group => group.Count() == 1).ToDictionary(group => group.Key, group => group.Single()); foreach (var element in unique.Values) { diff --git a/src/RvtIO/Model/Element.cs b/src/RvtIO/Model/Element.cs index 082e6fe1..22b99494 100644 --- a/src/RvtIO/Model/Element.cs +++ b/src/RvtIO/Model/Element.cs @@ -716,12 +716,12 @@ internal bool RootClassIs(string className) => NativeRootClassName != null /// these parameters of an element are listed, so a stored parameter with an empty text value is /// still "held" for a property that reads it by name. [JsonIgnore] - internal HashSet? NativeStoredParameterIds { get; set; } + internal IReadOnlyCollection? NativeStoredParameterIds { get; set; } /// Ids of the parameters stored in the element's four root parameter stores (double, integer, /// string, element id value sets); null when the element's native record was not decoded. /// tells whether every store of the record was read. - internal HashSet? NativeParameterStoreIds { get; set; } + internal IReadOnlyCollection? NativeParameterStoreIds { get; set; } internal bool NativeParameterStoresComplete { get; set; } @@ -1144,7 +1144,7 @@ internal bool RootClassIs(string className) => NativeRootClassName != null public Parameter? LookupParameter(string name) { foreach (var p in Parameters) - if (p.Definition?.Name == name) return p; + if (p.DefinitionName == name) return p; return null; } @@ -1155,7 +1155,7 @@ internal bool RootClassIs(string className) => NativeRootClassName != null { int bipId = (int)bip; foreach (var p in Parameters) - if (p.Definition?.Id == bipId) return p; + if (p.DefinitionId == bipId) return p; return null; } @@ -1166,7 +1166,7 @@ public IReadOnlyList GetParameters(string name) { var result = new List(); foreach (var p in Parameters) - if (p.Definition?.Name == name) result.Add(p); + if (p.DefinitionName == name) result.Add(p); return result; } @@ -1181,7 +1181,7 @@ public int FamilyTypeId { foreach (var p in Parameters) { - if (p.Definition?.Name is "ELEM_TYPE_PARAM" && p.Value is int id && id > 0) + if (p.DefinitionName is "ELEM_TYPE_PARAM" && p.Value is int id && id > 0) return id; } return -1; diff --git a/src/RvtIO/Model/ExactIfcStringParameterResolver.cs b/src/RvtIO/Model/ExactIfcStringParameterResolver.cs index 9038d6f0..9c70f49d 100644 --- a/src/RvtIO/Model/ExactIfcStringParameterResolver.cs +++ b/src/RvtIO/Model/ExactIfcStringParameterResolver.cs @@ -37,7 +37,7 @@ internal static ExactIfcStringParameterResult Resolve( { string cleanPropertyName = RemoveAsciiSpaces(propertyName); var candidates = element.Parameters.Where(parameter => - parameter.Definition?.Name is string name + 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..1652a0f2 100644 --- a/src/RvtIO/Model/Geometry.cs +++ b/src/RvtIO/Model/Geometry.cs @@ -116,21 +116,32 @@ public class GeoInstance /// A planar face defined by origin + two direction vectors. public class GeoFace { + /// Creates a face with zeroed plane vectors. + public GeoFace() : this(new double[3], new double[3]) { } + + internal GeoFace(double[] origin, double[] normal, bool includePlaneAxes = true) + { + Origin = origin; + Normal = normal; + XVector = includePlaneAxes ? new double[3] : []; + YVector = includePlaneAxes ? new double[3] : []; + } + /// 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..b4d22333 100644 --- a/src/RvtIO/Model/Parameter.cs +++ b/src/RvtIO/Model/Parameter.cs @@ -1,4 +1,5 @@ using System.Globalization; +using System.Runtime.CompilerServices; using System.Text.Json.Serialization; namespace RvtIO.Model @@ -9,9 +10,40 @@ namespace RvtIO.Model /// public class Parameter { + internal sealed class DefinitionData(int id, string? name, string? builtInParameter = null, Guid? guid = null) + { + internal int Id { get; } = id; + internal string? Name { get; } = name; + internal string? BuiltInParameter { get; } = builtInParameter; + internal object? BoxedGuid { get; } = guid; + + internal Definition ToDefinition() => new() { Id = Id, Name = Name, BuiltInParameter = BuiltInParameter }; + } + // Readers share resolved units. The public setters replace the record on the edited parameter. + internal sealed record DisplayUnits(string? SpecType, string? Symbol, double? Factor); + + private static readonly DisplayUnits NoDisplayUnits = new(null, null, null); + private object? _definition; + private DisplayUnits? _displayUnits; + + /// Creates a parameter with its own empty definition. + public Parameter() => _definition = new Definition(); + + internal Parameter(Definition definition) => _definition = definition; + internal Parameter(DefinitionData definition) + { + _definition = definition; + _guid = definition.BoxedGuid; + } + + internal void SetDefinitionData(DefinitionData definition) => Volatile.Write(ref _definition, definition); + + internal void UseGuidIfMissing(DefinitionData definition) => _guid ??= definition.BoxedGuid; + /// A copy of this parameter with another value. internal Parameter ShallowCopy(object? value) { + _ = Definition; // Shallow copies share the same mutable definition. var copy = (Parameter)MemberwiseClone(); if (!Equals(copy._value, value)) copy.HasResolvedZeroElementId = false; @@ -20,11 +52,43 @@ internal Parameter ShallowCopy(object? value) } private object? _value; + private static readonly object[] SmallIntegers = [-1, 0, 1, 2, 3]; + private static readonly object DoubleZero = 0.0; + private static readonly object DoubleOne = 1.0; + + // The reader produces many identical scalar values. Pool only the exact numeric types and bits. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static object? BoxParsedValue(T value) + { + if (typeof(T) == typeof(int)) + { + int number = Unsafe.As(ref value); + return number is >= -1 and <= 3 ? SmallIntegers[number + 1] : number; + } + if (typeof(T) == typeof(double)) + { + double number = Unsafe.As(ref value); + return BitConverter.DoubleToInt64Bits(number) switch + { + 0 => DoubleZero, + 0x3ff0_0000_0000_0000L => DoubleOne, + _ => number, + }; + } + return value; + } + + // Built-in parameters have no GUID. Store a boxed Guid only when one is present. + private object? _guid; /// 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 => (Guid?)_guid; + set => _guid = value; + } /// /// For built-in params: the BIP enum int value (same as Definition.Id, negative). @@ -36,7 +100,43 @@ 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 + { + var state = Volatile.Read(ref _definition); + while (state is DefinitionData stored) + { + var definition = stored.ToDefinition(); + var previous = Interlocked.CompareExchange(ref _definition, definition, stored); + if (ReferenceEquals(previous, stored)) return definition; + state = previous; + } + return (Definition)state!; + } + set => Volatile.Write(ref _definition, value); + } + + internal string? DefinitionName => Volatile.Read(ref _definition) switch + { + DefinitionData stored => stored.Name, + Definition definition => definition.Name, + _ => null, + }; + + internal string? DefinitionBuiltIn => Volatile.Read(ref _definition) switch + { + DefinitionData stored => stored.BuiltInParameter, + Definition definition => definition.BuiltInParameter, + _ => null, + }; + + internal int? DefinitionId => Volatile.Read(ref _definition) switch + { + DefinitionData stored => stored.Id, + Definition definition => definition.Id, + _ => null, + }; /// Storage type. Invariant per definition id - lives in ParameterDefinitions. [JsonIgnore] @@ -71,18 +171,32 @@ public object? 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 => _displayUnits?.SpecType; + set => _displayUnits = (_displayUnits ?? NoDisplayUnits) with { 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 => _displayUnits?.Symbol; + set => _displayUnits = (_displayUnits ?? NoDisplayUnits) with { Symbol = 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 => _displayUnits?.Factor; + set => _displayUnits = (_displayUnits ?? NoDisplayUnits) with { Factor = value }; + } + + internal void SetDisplayUnits(DisplayUnits units) => _displayUnits = units; /// 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. @@ -188,6 +302,15 @@ internal static bool IsValidZeroElementIdTarget( /// 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) + { + var (hasZeroPhase, hasZeroDimStyle) = ResolveZeroElementIdDomains(info, state); + foreach (var element in info.Elements) + foreach (var parameter in element.Parameters) + parameter.ResolveZeroElementId(element, hasZeroPhase, hasZeroDimStyle); + } + + internal static (bool Phase, bool DimensionStyle) ResolveZeroElementIdDomains( + RevitFileInfo info, RvtIO.Internal.ParsingState? state) { bool hasZeroPhase = HasZeroProjectPhase(info, state); bool hasZeroDimStyle = HasZeroDimensionStyle(info, state); @@ -196,21 +319,15 @@ internal static void ResolveZeroElementIds(RevitFileInfo info, RvtIO.Internal.Pa info.SerializedHasZeroProjectPhase = hasZeroPhase; info.SerializedHasZeroDimensionStyle = hasZeroDimStyle; } - foreach (var element in info.Elements) - { - foreach (var parameter in element.Parameters) - { - 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; - } - } - } + return (hasZeroPhase, hasZeroDimStyle); + } + + internal void ResolveZeroElementId(Element owner, bool hasZeroPhase, bool hasZeroDimStyle) + { + if (StorageType == StorageType.ElementId && Value is int eid && eid == 0) + HasResolvedZeroElementId = IsValidZeroElementIdTarget(owner, Id, hasZeroPhase, hasZeroDimStyle); + else if (HasResolvedZeroElementId) + HasResolvedZeroElementId = false; } private static bool IsProjectPhaseElement(Element element) => @@ -363,8 +480,8 @@ public long AsElementId64() => } // Fallback: heuristic based on parameter or BIP name tokens - string? name = Definition?.Name; - string? bip = Definition?.BuiltInParameter; + string? name = DefinitionName; + string? bip = DefinitionBuiltIn; // Dimensionless coefficients, scales, ratios, and factors must not be inferred as dimensional lengths/areas/volumes if (HasWordToken(name, bip, ScalarKeywords)) diff --git a/src/RvtIO/Model/RevitFileInfo.cs b/src/RvtIO/Model/RevitFileInfo.cs index a2e1d512..5123a92d 100644 --- a/src/RvtIO/Model/RevitFileInfo.cs +++ b/src/RvtIO/Model/RevitFileInfo.cs @@ -169,8 +169,8 @@ public void BuildParameterDefinitionTable() { table[p.Id] = new ParameterDefinition { - Name = p.Definition?.Name, - BuiltInParameter = p.Definition?.BuiltInParameter, + Name = p.DefinitionName, + BuiltInParameter = p.DefinitionBuiltIn, StorageType = p.StorageType, IsReadOnly = p.IsReadOnly, ForgeId = p.ForgeId, @@ -181,8 +181,8 @@ public void BuildParameterDefinitionTable() else { // Fill nullable fields that a later instance resolved but an earlier one missed. - def.Name ??= p.Definition?.Name; - def.BuiltInParameter ??= p.Definition?.BuiltInParameter; + def.Name ??= p.DefinitionName; + def.BuiltInParameter ??= p.DefinitionBuiltIn; def.ForgeId ??= p.ForgeId; def.UnitSymbol ??= p.UnitSymbol; def.Guid ??= p.Guid; diff --git a/src/RvtIO/Parsing/BipHelpers.cs b/src/RvtIO/Parsing/BipHelpers.cs index 91c4c4c4..f3978688 100644 --- a/src/RvtIO/Parsing/BipHelpers.cs +++ b/src/RvtIO/Parsing/BipHelpers.cs @@ -5,15 +5,40 @@ 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 readonly Dictionary Definitions = + BipNames.Lookup.ToDictionary(pair => pair.Key, + pair => (new Parameter.DefinitionData(pair.Key, pair.Value, pair.Value), + IsBipReadOnly(pair.Value), BipStorageType(pair.Value))); + + internal static Parameter MakeBipParam(int bipId, string? bipName, StorageType? storageType, T value, bool hasNoRevitValue = false) => + MakeBipParam(bipId, bipName, storageType, Parameter.BoxParsedValue(value), hasNoRevitValue); + + public static Parameter MakeBipParam(int bipId, string? bipName, StorageType? storageType, object? value, bool hasNoRevitValue = false) { - Id = bipId, - StorageType = storageType, - Value = value, - HasNoRevitValue = hasNoRevitValue, - IsReadOnly = IsBipReadOnly(bipName), - Definition = new Definition { Id = bipId, BuiltInParameter = bipName, Name = bipName }, - }; + Parameter parameter; + if (Definitions.TryGetValue(bipId, out var cached) && cached.Definition.Name == bipName) + parameter = new Parameter(cached.Definition) + { IsReadOnly = cached.IsReadOnly, StorageType = storageType ?? cached.Storage }; + else + parameter = new Parameter(new Definition { Id = bipId, BuiltInParameter = bipName, Name = bipName }) + { IsReadOnly = IsBipReadOnly(bipName), StorageType = storageType ?? BipStorageType(bipName) }; + parameter.Id = bipId; + parameter.Value = value; + parameter.HasNoRevitValue = hasNoRevitValue; + return parameter; + } + + internal static Parameter MakeStoredBipParam(int id, StorageType storage, object? value, bool hasNoRevitValue) + { + if (!Definitions.TryGetValue(id, out var cached)) + return MakeBipParam(id, id.ToString(), storage, value, hasNoRevitValue); + + return new Parameter(cached.Definition) + { + Id = id, IsReadOnly = cached.IsReadOnly, StorageType = storage, + Value = value, HasNoRevitValue = hasNoRevitValue, + }; + } public static StorageType BipStorageType(string? bipName) { @@ -60,11 +85,6 @@ public static bool IsBipReadOnly(string? bipName) || n.Contains("_URL") || n.Contains("_KEYNOTE") || n.Contains("_MODEL") || n.Contains("_MANUFACTURER") || n.Contains("_COST")) return false; - if (n.Contains("_COMPUTED") || n.Contains("_VOLUME") || n.Contains("_AREA") - || n.Contains("ELEM_TYPE_PARAM") || n.Contains("ELEM_FAMILY_PARAM") - || n.Contains("SYMBOL_ID_PARAM") || n.Contains("ELEM_FAMILY_AND_TYPE") - || n.Contains("ELEM_TYPE_LABEL") || n.Contains("_CUT_LENGTH")) - return true; return true; } @@ -75,8 +95,8 @@ public static bool IsBipReadOnly(string? bipName) if (colonIdx < 0) return null; int start = colonIdx + 4; if (start >= forgeId.Length) return null; - if (start + 36 <= forgeId.Length && Guid.TryParse(forgeId.Substring(start, 36), out var g36)) return g36; - if (start + 32 <= forgeId.Length && Guid.TryParse(forgeId.Substring(start, 32), out var g32)) return g32; + if (start + 36 <= forgeId.Length && Guid.TryParse(forgeId.AsSpan(start, 36), out var g36)) return g36; + if (start + 32 <= forgeId.Length && Guid.TryParse(forgeId.AsSpan(start, 32), out var g32)) return g32; return null; } } diff --git a/src/RvtIO/Parsing/BlockParser.cs b/src/RvtIO/Parsing/BlockParser.cs index 01d292e8..404586f0 100644 --- a/src/RvtIO/Parsing/BlockParser.cs +++ b/src/RvtIO/Parsing/BlockParser.cs @@ -1,3 +1,7 @@ +using System.Globalization; +using System.Numerics; +using System.Runtime.InteropServices; +using System.Runtime.Intrinsics; using System.Text; using RvtIO.Internal; using RvtIO.Lookup; @@ -12,29 +16,67 @@ internal static class BlockParser /// 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 GRepRange(byte[] Chunk, int Start, uint Size); - /// 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 const int PendingGRepBatchSize = 8192; + + internal static void SkipRepeatedFirstGReps(List firstPass, List secondPass) + { + var soleBlockByOwner = new Dictionary(); + foreach (var job in firstPass) + if (!job.IsFamilyCut && !soleBlockByOwner.TryAdd(job.Eid, job)) + soleBlockByOwner[job.Eid] = default; + + // Reapplying an owner's sole block is idempotent before any other block for that + // owner. Keep all later candidates, since their merge can depend on arrival order. + secondPass.RemoveAll(job => !job.IsFamilyCut + && soleBlockByOwner.Remove(job.Eid, out var first) && job == first); + } + + /// Decodes the collected GRep blocks in parallel and applies them in collection order (the merge + /// rules depend on arrival order). + internal static void ApplyPendingGReps(ParsingState state, List pending, HashSet? unreadable = null) { if (pending.Count == 0) return; - DecodeGRepBlocksInOrder(pending.Count, - index => + if (OperatingSystem.IsBrowser()) + { + foreach (var job in pending) { - var job = pending[index]; - return GRepParserV2.Parse(job.Chunk, job.Start, job.Size); - }, - (index, geometry) => ApplyPendingGRep(state, pending[index], geometry)); + var geometry = GRepParserV2.Parse(job.Chunk, job.Start, job.Size); + if (geometry == null) unreadable?.Add(new(job.Chunk, job.Start, job.Size)); + ApplyPendingGRep(state, job, geometry); + } + return; + } + var decoded = new GRepData?[Math.Min(pending.Count, PendingGRepBatchSize)]; + int offset = 0; + while (offset < pending.Count) + { + int count = Math.Min(decoded.Length, pending.Count - offset); + Parallel.For(0, count, index => + { + var job = pending[offset + index]; + if (unreadable?.Contains(new GRepRange(job.Chunk, job.Start, job.Size)) != true) + decoded[index] = GRepParserV2.Parse(job.Chunk, job.Start, job.Size); + }); + for (int index = 0; index < count; index++) + { + var job = pending[offset + index]; + var geometry = decoded[index]; + decoded[index] = null; + if (geometry == null) unreadable?.Add(new GRepRange(job.Chunk, job.Start, job.Size)); + ApplyPendingGRep(state, job, geometry); + } + offset += count; + } } - /// 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 (job.IsFamilyCut) { - if (!state.FamilyCutGreps.ContainsKey(job.Eid) - && geometry is { } familyCut && IsAuthoredFamilyComplexCutter(familyCut)) + if (geometry is { } familyCut && !state.FamilyCutGreps.ContainsKey(job.Eid) + && IsAuthoredFamilyComplexCutter(familyCut)) state.FamilyCutGreps[job.Eid] = familyCut; } else ApplyGRepBlock(state, job.Eid, geometry); @@ -162,7 +204,7 @@ internal static bool ParseBlock(byte[] chunk, int pos, uint eid, uint dataSize, uint classKey = classIdx & 0xFFFF; // classKey=0 is never a valid class - these are false positives from scanner misalignment if (classKey == 0) return false; - if (ElementIdEncoding.IsSupported(eid)) + if (state.CollectBlockClassInventory && ElementIdEncoding.IsSupported(eid)) { if (!state.BlockClassInventory.TryGetValue(classKey, out var bcs)) state.BlockClassInventory[classKey] = bcs = new BlockClassStats(); @@ -247,8 +289,6 @@ 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); - // Blocks with high classIdx word = 0xFFFF contain BIP key->double pairs at stride 12 if ((classIdx >> 16) == 0xFFFF) { @@ -546,41 +586,79 @@ private static bool HasNonAxisAlignedFaces(GRepData gd) return false; } + private const int MaxBlockStrings = 20; + private const int MaxBlockStringLength = 500; + public static void ExtractBlockStrings(byte[] d, int start, int end, uint eid, Dictionary> elemStrings) { - for (int j = start; j + 6 <= end; j++) + elemStrings.TryGetValue(eid, out var strings); + if (strings?.Count >= MaxBlockStrings || end - start < 8) return; + Span chars = stackalloc char[MaxBlockStringLength]; + int position = start, limit = end - 7; + if (start >= 0 && end <= d.Length && BitConverter.IsLittleEndian && Vector256.IsHardwareAccelerated) + { + ref byte data = ref MemoryMarshal.GetArrayDataReference(d); + int width = Vector256.Count; + for (; position <= limit - width; position += width) + { + // The 32-bit length is 2..500. Skip bytes that cannot start that length. + var low = Vector256.LoadUnsafe(ref data, (nuint)position); + var second = Vector256.LoadUnsafe(ref data, (nuint)(position + 1)); + var high = Vector256.LoadUnsafe(ref data, (nuint)(position + 2)) + | Vector256.LoadUnsafe(ref data, (nuint)(position + 3)); + var shortLengths = Vector256.Equals(second, Vector256.Zero) + & Vector256.GreaterThan(low, Vector256.Create((byte)1)); + var longLengths = Vector256.Equals(second, Vector256.Create((byte)1)) + & Vector256.LessThanOrEqual(low, Vector256.Create((byte)(MaxBlockStringLength - 256))); + uint candidates = ((shortLengths | longLengths) & Vector256.Equals(high, Vector256.Zero)) + .ExtractMostSignificantBits(); + while (candidates != 0) + { + int offset = position + BitOperations.TrailingZeroCount(candidates); + int length = BlockStringLength(d, offset, end); + if (length != 0 && AppendBlockString(d, offset + 4, length, eid, elemStrings, chars, ref strings)) return; + candidates &= candidates - 1; + } + } + } + for (; position < limit; position++) { - uint sLen = BitConverter.ToUInt32(d, j); - if (sLen < 2 || sLen > 500 || j + 4 + sLen * 2 > end) continue; + int length = BlockStringLength(d, position, end); + if (length != 0 && AppendBlockString(d, position + 4, length, eid, elemStrings, chars, ref strings)) return; + } + } - bool valid = true; - int printable = 0; - for (int k = 0; k < (int)sLen && valid; k++) - { - byte lo = d[j + 4 + k * 2], hi = d[j + 4 + k * 2 + 1]; - // Accept: ASCII (hi=0x00), Cyrillic (hi=0x04), known Deflate64 artifacts (hi=0xF7/0x1B), - // or any hi when lo is printable ASCII (handles Deflate64 hi-byte corruption in Cyrillic+ASCII strings) - if (hi != 0x00 && hi != 0x04 && hi != 0xF7 && hi != 0x1B && (lo < 0x20 || lo > 0x7E)) - { valid = false; break; } - char c = DecodeUtf16Char(lo, hi); - if (c < 0x20 && c != '\t' && c != '\n' && c != '\r') { valid = false; break; } - if (char.IsLetterOrDigit(c) || char.IsPunctuation(c) || char.IsSymbol(c)) printable++; - } - if (!valid || printable < sLen * 0.6) continue; + private static int BlockStringLength(byte[] data, int offset, int end) + { + uint length = BitConverter.ToUInt32(data, offset); + return length >= 2 && length <= MaxBlockStringLength && offset + 4 + length * 2 <= end ? (int)length : 0; + } - var sb = new StringBuilder(); - for (int k = 0; k < (int)sLen; k++) - { - char c = DecodeUtf16Char(d[j + 4 + k * 2], d[j + 4 + k * 2 + 1]); - if (c < 0x20 && c != '\t' && c != '\n' && c != '\r') { sb.Clear(); break; } - sb.Append(c); - } - string str = sb.ToString().Trim(); - if (str.Length < 2) continue; - if (!elemStrings.ContainsKey(eid)) elemStrings[eid] = new List(); - if (!elemStrings[eid].Contains(str) && elemStrings[eid].Count < 20) - elemStrings[eid].Add(str); - } + private static bool AppendBlockString(byte[] data, int payload, int length, uint eid, + Dictionary> elemStrings, Span chars, ref List? strings) + { + int printable = 0; + for (int index = 0; index < length; index++) + { + byte lo = data[payload + index * 2], hi = data[payload + index * 2 + 1]; + // A damaged high byte can still carry printable ASCII. + if (hi != 0x00 && hi != 0x04 && hi != 0xF7 && hi != 0x1B && (lo < 0x20 || lo > 0x7E)) return false; + char c = DecodeUtf16Char(lo, hi); + if (c < 0x20 && c != '\t' && c != '\n' && c != '\r') return false; + chars[index] = c; + UnicodeCategory category = char.GetUnicodeCategory(c); + if (category is <= UnicodeCategory.OtherLetter or UnicodeCategory.DecimalDigitNumber + or >= UnicodeCategory.ConnectorPunctuation and <= UnicodeCategory.OtherSymbol) printable++; + } + if (printable < length * 0.6) return false; + + ReadOnlySpan value = chars[..length].Trim(); + if (value.Length < 2) return false; + if (strings == null) elemStrings[eid] = strings = new List(); + foreach (string previous in strings) + if (value.SequenceEqual(previous.AsSpan())) return false; + strings.Add(value.ToString()); + return strings.Count == MaxBlockStrings; } /// @@ -591,9 +669,8 @@ public static void ExtractBlockStrings(byte[] d, int start, int end, uint eid, D private static void ExtractInsertSillFrom0702Block(byte[] d, int start, int end, uint eid, Dictionary> elemBipDoubles) { - for (int i = start; i + 30 <= end; i++) + for (int i = start; (i = FindParamSentinel(d, i, end - 30)) >= 0; i++) { - if (d[i] != 0xFF || d[i + 1] != 0xFF || d[i + 2] != 0xFF || d[i + 3] != 0xFF) continue; if (d[i + 4] != 0xBE || d[i + 5] != 0x08) continue; if (d[i + 6] != 0 || d[i + 7] != 0 || d[i + 8] != 0 || d[i + 9] != 0) continue; double sill = BitConverter.ToDouble(d, i + 10); @@ -755,13 +832,13 @@ public static void ExtractFamilyInstanceTransform(byte[] d, int start, int end, // Use 2-byte alignment (variable-length fields can cause misalignment). int lastStart = end - TRF_BYTES - 4; lastStart -= (lastStart - start) % 2; + Span trf = stackalloc double[12]; for (int i = lastStart; i >= start; i -= 2) { // Quick pre-check: first double of Col0 should be a reasonable rotation value [-1..1] double r00 = BitConverter.ToDouble(d, i); if (double.IsNaN(r00) || Math.Abs(r00) > 1.01) continue; - var trf = new double[12]; trf[0] = r00; bool valid = true; for (int k = 1; k < 12; k++) @@ -792,7 +869,7 @@ public static void ExtractFamilyInstanceTransform(byte[] d, int start, int end, // Layout A (column-major 3x4): SymbolId is int32 right after 12 doubles (96 bytes) // Layout B (row-major 4x4): 4th row [0,0,0,1] after 12 doubles, then SymbolId after 16 doubles (128 bytes) int symbolId = -1; - double[] finalTrf = trf; + bool rowMajor = false; // Check Layout B first: see if doubles 12-15 are [0, 0, 0, 1] if (i + 128 + 4 <= end) @@ -803,18 +880,12 @@ public static void ExtractFamilyInstanceTransform(byte[] d, int start, int end, double r33 = BitConverter.ToDouble(d, i + 120); if (Math.Abs(r30) < 1e-10 && Math.Abs(r31) < 1e-10 && Math.Abs(r32) < 1e-10 && Math.Abs(r33 - 1.0) < 1e-10) { - // Row-major 4x4: [r00,r01,r02,tx, r10,r11,r12,ty, r20,r21,r22,tz, 0,0,0,1] - // Convert to column-major 3x4: [r00,r10,r20, r01,r11,r21, r02,r12,r22, tx,ty,tz] - finalTrf = new double[] - { - trf[0], trf[4], trf[8], // Col0 - trf[1], trf[5], trf[9], // Col1 - trf[2], trf[6], trf[10], // Col2 - trf[3], trf[7], trf[11], // Translation - }; int sid = BitConverter.ToInt32(d, i + 128); if (sid > 0) + { symbolId = sid; + rowMajor = true; + } } } @@ -822,10 +893,7 @@ public static void ExtractFamilyInstanceTransform(byte[] d, int start, int end, { int sid = BitConverter.ToInt32(d, i + TRF_BYTES); if (sid > 0) - { symbolId = sid; - finalTrf = trf; - } } if (symbolId <= 0) continue; @@ -841,7 +909,11 @@ public static void ExtractFamilyInstanceTransform(byte[] d, int start, int end, familyInstanceTransforms[eid] = new FamilyInstanceData { - Trf = finalTrf, + // Convert row-major 4x4 to column-major 3x4 only for the accepted candidate. + Trf = rowMajor + ? [trf[0], trf[4], trf[8], trf[1], trf[5], trf[9], + trf[2], trf[6], trf[10], trf[3], trf[7], trf[11]] + : trf.ToArray(), SymbolId = symbolId, }; return; @@ -990,9 +1062,8 @@ private static void ExtractNameFrom0725Block(byte[] d, int start, int end, uint private static void ExtractFamilySymbolDoubles(byte[] d, int start, int end, uint eid, Dictionary> resultByEid) { - for (int i = start; i + 8 <= end; i++) + for (int i = start; (i = FindParamSentinel(d, i, end - 8)) >= 0; i++) { - if (d[i] != 0xFF || d[i+1] != 0xFF || d[i+2] != 0xFF || d[i+3] != 0xFF) continue; uint paramKey = BitConverter.ToUInt32(d, i + 4); // Plausible project param def ID range if (paramKey < 200 || paramKey > int.MaxValue) continue; @@ -1004,8 +1075,6 @@ private static void ExtractFamilySymbolDoubles(byte[] d, int start, int end, uin double ad = Math.Abs(dv); if (ad != 0 && (ad < 1e-12 || ad > 1e9)) continue; // Skip values that look like packed int data - high u32 must be a reasonable double sign/exponent - uint hi = BitConverter.ToUInt32(d, i - 4); - // Reject if hi bytes look like an unrelated int (e.g. another element id) if (ad == 0) { // For zero values, require explicit "all zeros" preceding 8 bytes @@ -1017,7 +1086,7 @@ private static void ExtractFamilySymbolDoubles(byte[] d, int start, int end, uin if (!resultByEid.TryGetValue(eid, out var map)) resultByEid[eid] = map = new Dictionary(); // Prefer first occurrence per (eid, paramKey) - if (!map.ContainsKey(paramKey)) map[paramKey] = dv; + map.TryAdd(paramKey, dv); } } @@ -1033,9 +1102,7 @@ private static void ExtractFamilySymbolElemIdPairs(byte[] d, int start, int end, // a project elem-id, preceded by >=8 zero bytes and followed by >=12 zero bytes + FFFFFFFF. for (int i = start + 8; i + 24 <= end; i += 2) { - bool zerosBefore = true; - for (int z = 1; z <= 8; z++) if (d[i - z] != 0) { zerosBefore = false; break; } - if (!zerosBefore) continue; + if (BitConverter.ToUInt64(d, i - 8) != 0) continue; int v1 = BitConverter.ToInt32(d, i); int v2 = BitConverter.ToInt32(d, i + 4); @@ -1043,20 +1110,12 @@ private static void ExtractFamilySymbolElemIdPairs(byte[] d, int start, int end, if (v2 < 200) continue; if (v2 < 100_000) continue; - bool zerosAfter = true; - for (int z = 8; z < 16; z++) if (d[i + z] != 0) { zerosAfter = false; break; } - if (!zerosAfter) continue; - bool foundSentinel = false; - for (int z = 16; z < 28 && i + z + 4 <= end; z++) - { - if (d[i + z] == 0xFF && d[i + z + 1] == 0xFF && d[i + z + 2] == 0xFF && d[i + z + 3] == 0xFF) - { foundSentinel = true; break; } - } - if (!foundSentinel) continue; + if (BitConverter.ToUInt64(d, i + 8) != 0 + || FindParamSentinel(d, i + 16, Math.Min(i + 27, end - 4)) < 0) continue; if (!resultByEid.TryGetValue(eid, out var map)) resultByEid[eid] = map = new Dictionary(); - if (!map.ContainsKey(v2)) map[v2] = v1; + map.TryAdd(v2, v1); } } @@ -1067,9 +1126,8 @@ private static void ExtractFamilySymbolElemIdPairs(byte[] d, int start, int end, private static void ExtractFamilySymbolInts(byte[] d, int start, int end, uint eid, Dictionary> resultByEid) { - for (int i = start; i + 18 <= end; i++) + for (int i = start; (i = FindParamSentinel(d, i, end - 18)) >= 0; i++) { - if (d[i] != 0xFF || d[i+1] != 0xFF || d[i+2] != 0xFF || d[i+3] != 0xFF) continue; int paramKey = BitConverter.ToInt32(d, i + 4); // Require LARGER threshold than for strings/doubles to avoid matching the inner sentinel // of string entries (where i+4 is the "typeMarker" like 0x0EB6 = 3766). @@ -1087,7 +1145,7 @@ private static void ExtractFamilySymbolInts(byte[] d, int start, int end, uint e if (!resultByEid.TryGetValue(eid, out var map)) resultByEid[eid] = map = new Dictionary(); - if (!map.ContainsKey(paramKey)) map[paramKey] = value; + map.TryAdd(paramKey, value); } } @@ -1100,9 +1158,8 @@ private static void ExtractFamilySymbolInts(byte[] d, int start, int end, uint e private static void ExtractFamilySymbolStrings(byte[] d, int start, int end, uint eid, Dictionary> resultByEid) { - for (int i = start; i + 8 <= end; i++) + for (int i = start; (i = FindParamSentinel(d, i, end - 8)) >= 0; i++) { - if (d[i] != 0xFF || d[i+1] != 0xFF || d[i+2] != 0xFF || d[i+3] != 0xFF) continue; int paramKey = BitConverter.ToInt32(d, i + 4); // Plausible param key: positive user param or BIP (-1000000..-1200000 range) bool isPositive = paramKey > 200; @@ -1111,12 +1168,7 @@ private static void ExtractFamilySymbolStrings(byte[] d, int start, int end, uin // Walk back looking for the inner FFFFFFFF that separates the string from the outer // sentinel. Search within 30 bytes back (typical type-marker + zeros = 14 bytes). - int innerSentinel = -1; - for (int b = Math.Max(start, i - 30); b + 4 <= i; b++) - { - if (d[b] == 0xFF && d[b+1] == 0xFF && d[b+2] == 0xFF && d[b+3] == 0xFF) - { innerSentinel = b; break; } - } + int innerSentinel = FindParamSentinel(d, Math.Max(start, i - 30), i - 4); if (innerSentinel < 0) continue; int strEnd = innerSentinel; // Try slen values; require slen u32 at (strEnd - slen*2 - 4) @@ -1145,7 +1197,7 @@ private static void ExtractFamilySymbolStrings(byte[] d, int start, int end, uin string s = sb.ToString(); if (!resultByEid.TryGetValue(eid, out var map)) resultByEid[eid] = map = new Dictionary(); - if (!map.ContainsKey(paramKey)) map[paramKey] = s; + map.TryAdd(paramKey, s); break; } } @@ -1172,9 +1224,8 @@ private static (Dictionary map, Dictionary typeValues) var allEntries = new List<(int offset, int entryLen, uint binKey, ushort marker, ushort slen, string? str)>(); int pos = start; - while (pos + 18 <= end) + while ((pos = FindParamSentinel(d, pos, end - 18)) >= 0) { - if (BitConverter.ToUInt32(d, pos) != 0xFFFFFFFF) { pos++; continue; } // Validate basic shape: 4 zeros at +8-11 bool zerosOk = true; for (int z = 0; z < 4 && zerosOk; z++) if (d[pos + 8 + z] != 0) zerosOk = false; @@ -1372,21 +1423,6 @@ private static void ExtractBipDoublesFromBlock(byte[] d, int start, int end, uin } } - public static void ExtractBlockDoubles(byte[] d, int start, int end, uint eid, Dictionary> elemDoubles) - { - for (int j = start; j + 8 <= end; j += 4) - { - double dv = BitConverter.ToDouble(d, j); - if (dv != 0 && !double.IsNaN(dv) && !double.IsInfinity(dv) - && Math.Abs(dv) < 1e12 && Math.Abs(dv) > 1e-20) - { - if (!elemDoubles.ContainsKey(eid)) elemDoubles[eid] = new List(); - if (!elemDoubles[eid].Contains(dv) && elemDoubles[eid].Count < 30) - elemDoubles[eid].Add(dv); - } - } - } - // 0x702 block: user param values (strings + doubles) // Mixed entry types, all preceded by [FF FF FF FF:4][paramDefId:4]: // String: [FF FF FF FF:4][paramDefId:4][zeros:6][slen:2][zeros:2][string:slen*2 UTF-16LE] @@ -1402,9 +1438,8 @@ private static void ExtractParamValuesFrom0702Block(byte[] d, int start, int end // The 8 bytes just BEFORE an entry's sentinel are the trailing double value for THAT // entry (slen=0 case). I.e. the entry's "tail" doubles are stored at the boundary // overlapping with the previous entry's padding. - for (int i = start; i + 18 <= end; i++) + for (int i = start; (i = FindParamSentinel(d, i, end - 18)) >= 0; i++) { - if (BitConverter.ToUInt32(d, i) != 0xFFFFFFFF) continue; uint paramDefId = BitConverter.ToUInt32(d, i + 4); // Structural validation: paramKey followed by 6 zeros, then 2-byte slen, then padding. // (The 0x702 block does NOT carry the 0x725-style marker byte - these 6 bytes are zero.) @@ -1454,6 +1489,13 @@ private static void ExtractParamValuesFrom0702Block(byte[] d, int start, int end } } + private static int FindParamSentinel(byte[] data, int start, int lastStart) + { + if (start > lastStart) return -1; + int offset = data.AsSpan(start, lastStart - start + 4).IndexOf((ReadOnlySpan)[0xFF, 0xFF, 0xFF, 0xFF]); + return offset < 0 ? -1 : start + offset; + } + // Extract BIP ElementId values from 0x702 block's BIP section. // The BIP section precedes user param entries. It contains sentinel-delimited entries. // Key patterns: @@ -1465,18 +1507,17 @@ private static void ExtractBipIntsFrom0702Block(byte[] d, int start, int end, ui Dictionary records) { if (!records.TryGetValue(eid, out var rec)) return; - var body = rec.Body; - int mp = -1; - for (int ii = 0; ii < body.Length - 1; ii++) - if (BitConverter.ToUInt16(body, ii) == 0x0548) { mp = ii; break; } + var body = rec.Body.Span; + ReadOnlySpan bodyMarker = BitConverter.IsLittleEndian ? [0x48, 0x05] : [0x05, 0x48]; + int mp = body.IndexOf(bodyMarker); if (mp < 0) return; // Collect ElementId BIP keys from body entries (ft=4, negative key, ElementId storage type) var elementIdBips = new List(); for (int p = 2; p + 14 <= mp; p += 14) { - int k = BitConverter.ToInt32(body, p + 4); - ushort ft = BitConverter.ToUInt16(body, p + 8); + int k = BitConverter.ToInt32(body.Slice(p + 4)); + ushort ft = BitConverter.ToUInt16(body.Slice(p + 8)); if (ft != 4 || k >= -1 || k < -2_000_000) continue; if (!BipNames.Lookup.TryGetValue(k, out string? nm)) continue; if (BipHelpers.BipStorageType(nm) == StorageType.ElementId) @@ -1484,26 +1525,24 @@ private static void ExtractBipIntsFrom0702Block(byte[] d, int start, int end, ui } if (elementIdBips.Count == 0) return; - int blockLen = end - start; if (!elemBipInts.TryGetValue(eid, out var intDict)) elemBipInts[eid] = intDict = new Dictionary(); // Extract sentinel values from BIP section (scan until long FF gap = ELEM_TYPE_PARAM) // Sentinel pattern: [FFFFFFFF+][value:4] -- the value after each FF run var sentinelValues = new List<(int val, bool inElemSet)>(); - for (int i = 0; i < blockLen - 8; i++) + for (int i = start; (i = FindParamSentinel(d, i, end - 9)) >= 0; i++) { - if (BitConverter.ToUInt32(d, start + i) != 0xFFFFFFFF) continue; int ffEnd = i + 4; - while (ffEnd < blockLen && d[start + ffEnd] == 0xFF) ffEnd++; - if (ffEnd + 4 > blockLen) break; - uint val = BitConverter.ToUInt32(d, start + ffEnd); + while (ffEnd < end && d[ffEnd] == 0xFF) ffEnd++; + if (ffEnd + 4 > end) break; + uint val = BitConverter.ToUInt32(d, ffEnd); if (val > 0) { int afterVal = ffEnd + 4; int ffCount = 0; - while (afterVal + ffCount < blockLen && d[start + afterVal + ffCount] == 0xFF) + while (afterVal + ffCount < end && d[afterVal + ffCount] == 0xFF) ffCount++; if (ffCount >= 20 && elemSet.Contains(val)) { @@ -2010,9 +2049,13 @@ private static bool IsCleanMaterialName(string? nm) internal static void CollectShadingEntries(byte[] d, Dictionary> entries) { - for (int j = 0; j + 28 <= d.Length; j++) + ReadOnlySpan signature = [0xFF, 0xFF, 0xFF, 0xFF, 0, 0, 0, 0]; + int lastStart = d.Length - 28; + for (int j = 0; j <= lastStart; j++) { - if (BitConverter.ToUInt32(d, j) != 0xFFFFFFFF || BitConverter.ToUInt32(d, j + 4) != 0) continue; + int next = d.AsSpan(j, lastStart - j + signature.Length).IndexOf(signature); + if (next < 0) break; + j += next; uint c = BitConverter.ToUInt32(d, j + 8); uint s = BitConverter.ToUInt32(d, j + 12); uint hid = BitConverter.ToUInt32(d, j + 16); @@ -2066,39 +2109,13 @@ private static void ExtractSheetInfo(byte[] d, int start, int end, uint eid, } } - /// Scans the blocks of a chunk for image-symbol blocks (class 0x089A) and records the pixel size of each - /// image. - internal static void CollectImageSizes(byte[] chunk, ParsingState state) - { - int pos = 0; - while (pos + 16 <= chunk.Length) - { - uint eid = BitConverter.ToUInt32(chunk, pos); - int size = BitConverter.ToInt32(chunk, pos + 8); - uint classIdx = BitConverter.ToUInt32(chunk, pos + 12); - if (eid == 0 || eid > 50_000_000 || size <= 0 || size > MaxBlockSize || pos + 16 + size > chunk.Length) - { - pos++; - continue; - } - if ((classIdx & 0xFFFF) == 0x089A && size >= 0x88 && !state.ImageSizes.ContainsKey(eid)) - { - int width = BitConverter.ToInt32(chunk, pos + 16 + 0x80); - int height = BitConverter.ToInt32(chunk, pos + 16 + 0x84); - if (width is > 0 and < 20000 && height is > 0 and < 20000) - state.ImageSizes[eid] = (width, height); - } - pos += 16 + size; - } - } - /// /// Scans the blocks of a chunk for the plane of a view: the schema stores m_horzDir (a horizontal unit vector), the /// view origin, the view scale, m_vertDir (a vertical unit vector) and m_viewDir (a horizontal unit vector) as /// thirteen consecutive doubles. The block walk of the project's own data does not always reach them, so they are /// found by signature and kept under the element id of the block. /// - internal static void CollectViewPlanes(byte[] chunk, ParsingState state) + internal static void CollectViewPlanes(byte[] chunk, ParsingState state, bool includeImages = false) { int pos = 0; while (pos + 16 <= chunk.Length) @@ -2111,6 +2128,13 @@ internal static void CollectViewPlanes(byte[] chunk, ParsingState state) pos++; continue; } + if (includeImages && (classIdx & 0xFFFF) == 0x089A && size >= 0x88 && !state.ImageSizes.ContainsKey(eid)) + { + int width = BitConverter.ToInt32(chunk, pos + 16 + 0x80); + int height = BitConverter.ToInt32(chunk, pos + 16 + 0x84); + if (width is > 0 and < 20000 && height is > 0 and < 20000) + state.ImageSizes[eid] = (width, height); + } // The view's own block (class 0x3F8) stores the plane as its origin, the view scale, the vertical and the // camera direction; the older signature below is kept for the blocks that store it as thirteen consecutive // doubles. The block layout wins: a wrong signature candidate must not hide the view's own plane. @@ -2164,8 +2188,15 @@ private static bool AxisAlignedUnit(double x, double y, double z) private static void TryFindViewPlane(byte[] d, int start, int end, uint eid, ParsingState state) { - for (int i = start; i + 13 * 8 <= end; i++) - { + // With |vx| and |vy| at most 0.01, the unit-length tolerance requires + // |vz| in [0.998, 1.001]. Its IEEE 754 exponent can only have these bytes. + int limit = end - 103; + for (int i = start; i < limit; i++) + { + int next = d.AsSpan(i + 78, limit - i).IndexOfAny((byte)0xEF, (byte)0xF0); + if (next < 0) break; + i += next; + if ((d[i + 79] & 0x7F) != 0x3F) continue; double hx = BitConverter.ToDouble(d, i), hy = BitConverter.ToDouble(d, i + 8); double hz = BitConverter.ToDouble(d, i + 16); if (!double.IsFinite(hx) || !double.IsFinite(hy) || !double.IsFinite(hz)) continue; @@ -2283,11 +2314,13 @@ private static void ExtractTextNote(byte[] d, int start, int end, uint eid, Pars private static void ExtractViewName(byte[] d, int start, int end, uint eid, Dictionary names) { - for (int j = start; j + 30 <= end; j++) + ReadOnlySpan signature = [0xFF, 0xFF, 0xFF, 0xFF, 0xB5, 0x0B, 1, 0, 0, 0]; + int lastStart = end - 30; + for (int j = start; j <= lastStart; j++) { - if (BitConverter.ToUInt32(d, j) != 0xFFFFFFFF) continue; - if (BitConverter.ToUInt16(d, j + 4) != 0x0BB5) continue; - if (BitConverter.ToUInt32(d, j + 6) != 1) continue; + int next = d.AsSpan(j, lastStart - j + signature.Length).IndexOf(signature); + if (next < 0) break; + j += next; if (BitConverter.ToUInt32(d, j + 14) != 0) continue; uint ln = BitConverter.ToUInt32(d, j + 18); if (ln < 1 || ln > 100 || j + 22 + (int)ln * 2 > end) return; @@ -2383,8 +2416,14 @@ internal static void CollectBipStrings(byte[] d, ParsingState state) if (ElementIdEncoding.IsSupported(eid)) { int ds = pos + 16, de = ds + (int)dataSize; - for (int j = ds; j + 10 <= de; j++) + int limit = de - 9; + for (int j = ds; j < limit; j++) { + // -1,200,000 through -1,000,000 have 0xED..0xF0 in byte two. + int next = d.AsSpan(j + 2, limit - j).IndexOfAnyInRange((byte)0xED, (byte)0xF0); + if (next < 0) break; + j += next; + if (d[j + 3] != 0xFF) continue; int bip = BitConverter.ToInt32(d, j); if (bip > -1_000_000 || bip < -1_200_000) continue; uint ln = BitConverter.ToUInt32(d, j + 4); @@ -2420,7 +2459,7 @@ internal static void CollectBipStrings(byte[] d, ParsingState state) internal static void CollectLevelElevations(byte[] d, ParsingState state) { // marker: -0.0 followed by -1.0 - byte[] mark = [0, 0, 0, 0, 0, 0, 0, 0x80, 0, 0, 0, 0, 0, 0, 0xF0, 0xBF]; + ReadOnlySpan mark = [0, 0, 0, 0, 0, 0, 0, 0x80, 0, 0, 0, 0, 0, 0, 0xF0, 0xBF]; int pos = 0; while (pos + 16 <= d.Length) { @@ -2440,18 +2479,15 @@ internal static void CollectLevelElevations(byte[] d, ParsingState state) if (dataSize == 0) { pos++; continue; } if (pos + 16 + (int)dataSize > d.Length) break; - if (ElementIdEncoding.IsSupported(eid) && !state.LevelElevCandidates.ContainsKey(eid)) + if (dataSize >= 24 && ElementIdEncoding.IsSupported(eid) && !state.LevelElevCandidates.ContainsKey(eid)) { - int ds = pos + 16, de = ds + (int)dataSize; - for (int j = ds + 8; j + 16 <= de; j++) + int ds = pos + 16; + int marker = d.AsSpan(ds + 8, (int)dataSize - 8).IndexOf(mark); + if (marker >= 0) { - bool m = true; - for (int k = 0; k < 16 && m; k++) if (d[j + k] != mark[k]) m = false; - if (!m) continue; - double elev = BitConverter.ToDouble(d, j - 8); + double elev = BitConverter.ToDouble(d, ds + marker); if (!double.IsNaN(elev) && Math.Abs(elev) < 1e5) state.LevelElevCandidates[eid] = elev; - break; } } pos += 16 + (int)dataSize; @@ -2470,13 +2506,20 @@ internal static void CollectHvacTables(byte[] d, HashSet knownIds, Dictionary> hvac, Dictionary schedules) { - for (int o = 0; o + 0xCF <= d.Length; o++) - { - uint eid = BitConverter.ToUInt32(d, o + 0x24); - if (eid == 0 || !knownIds.Contains(eid) || hvac.ContainsKey(eid)) continue; + if (d.Length < 0xCF) return; + // Both Kelvin values must have 0x40 as the high byte of the double. + int limit = d.Length - 0xCF + 1; + for (int o = 0; o < limit; o++) + { + int next = d.AsSpan(o + 0x5E, limit - o).IndexOf((byte)0x40); + if (next < 0) break; + o += next; + if (d[o + 0xB6] != 0x40) continue; double cool = BitConverter.ToDouble(d, o + 0x57); double heat = BitConverter.ToDouble(d, o + 0xAF); if (!(cool > 250 && cool < 330 && heat > 250 && heat < 330)) continue; + uint eid = BitConverter.ToUInt32(d, o + 0x24); + if (eid == 0 || !knownIds.Contains(eid) || hvac.ContainsKey(eid)) continue; double ll = BitConverter.ToDouble(d, o + 0x47); double dh = BitConverter.ToDouble(d, o + 0xA7); if (double.IsNaN(ll) || ll < 0 || ll >= 1e4 || double.IsNaN(dh) || dh < 0 || dh > 1) continue; diff --git a/src/RvtIO/Parsing/CompactUniverse.cs b/src/RvtIO/Parsing/CompactUniverse.cs index 4cae89ee..ccf2e08a 100644 --- a/src/RvtIO/Parsing/CompactUniverse.cs +++ b/src/RvtIO/Parsing/CompactUniverse.cs @@ -12,10 +12,14 @@ internal static bool IsTableRow(Element element, bool elemTableIsExact) => !element.IsBlockOnly && !(elemTableIsExact && element.IsDiscovered); /// The table rows of ordered by ElementId; elements with the same id keep their order. - internal static List Select(RevitFileInfo info) + internal static List Select(RevitFileInfo info) => + Enumerate(info).OrderBy(element => element.Id).ToList(); + + /// The table rows in their original model order. + internal static IEnumerable Enumerate(RevitFileInfo info) { ArgumentNullException.ThrowIfNull(info); bool exact = info.ElemTableIsExact; - return info.Elements.Where(element => IsTableRow(element, exact)).OrderBy(element => element.Id).ToList(); + return info.Elements.Where(element => IsTableRow(element, exact)); } } diff --git a/src/RvtIO/Parsing/ElementBuilder.CoarseSurface.cs b/src/RvtIO/Parsing/ElementBuilder.CoarseSurface.cs index 770b67b6..2f201a5f 100644 --- a/src/RvtIO/Parsing/ElementBuilder.CoarseSurface.cs +++ b/src/RvtIO/Parsing/ElementBuilder.CoarseSurface.cs @@ -12,14 +12,28 @@ internal static partial class ElementBuilder /// This separate view is placed like the visible body and never replaces the element's geometry. internal static void ApplyCoarseDoorWindowSurfaces(RevitFileInfo info, ParsingState state) { + var candidates = new List(); foreach (var element in info.Elements) + if (element.CategoryId is DoorsCategoryId or WindowsCategoryId or StructuralColumnsCategoryId) + candidates.Add(element); + + // The temporary decoded bodies are large. Bound the number built at the same time. + if (SymbolDiagPath != null || Environment.GetEnvironmentVariable("RVTIO_GREPV2_DBG") == "1" + || Environment.GetEnvironmentVariable("RVTIO_GREPV2_DBG_ID") is { Length: > 0 } + || Environment.GetEnvironmentVariable("RVTIO_TOPO") is { Length: > 0 } + || Environment.GetEnvironmentVariable("RVTIO_MESH_DIAG") is { Length: > 0 }) + { + foreach (var element in candidates) Apply(element); + } + else Parallel.ForEach(candidates, new ParallelOptions { MaxDegreeOfParallelism = 2 }, Apply); + + void Apply(Element element) { if (element.CategoryId == StructuralColumnsCategoryId) { ApplyMediumLevelVolume(element, state); - continue; + return; } - 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); @@ -27,27 +41,10 @@ internal static void ApplyCoarseDoorWindowSurfaces(RevitFileInfo info, ParsingSt if (!HasQuantityAlternative(grep, state, visited) && !(transformOnly != null && state.GrepBlocks.TryGetValue((uint)Math.Max(transformOnly.SymbolId, 0), out var symbol) && HasQuantityAlternative(symbol, state, visited))) - continue; + return; - state.CoarseView = true; - state.IncludeNonVisibleQuantities = true; - try - { - var coarse = new Element { Id = element.Id, TypeId = element.TypeId, BoundingBox = element.Geometry?.BoundingBox }; - var own = grep?.CoarseQuantities ?? grep?.Coarse ?? grep; - if (own != null) - { - coarse.Geometry = BuildGeometryData(own, state.SeparateFacesWithDistinctOpenings); - ExpandInstanceGeometry(coarse, own, element.TypeId, state); - } - ExpandTransformOnlyInstanceGeometry(coarse, id, element.TypeId, state); - element.CoarseSurfaceArea = BrepMeasures.SurfaceAreaCurrent(coarse.Geometry); - } - finally - { - state.CoarseView = false; - state.IncludeNonVisibleQuantities = false; - } + var coarse = BuildQuantityGeometry(element.Id, grep, state, GeometryDetail.CoarseQuantities); + element.CoarseSurfaceArea = BrepMeasures.SurfaceAreaCurrent(coarse); } } @@ -64,20 +61,8 @@ private static void ApplyMediumLevelVolume(Element element, ParsingState state) && HasAlternative(symbol, state, visited, 2))) return; element.HasMediumAlternatives = true; - state.DetailView = 2; - try - { - var alternative = new Element { Id = element.Id, TypeId = element.TypeId, BoundingBox = element.Geometry?.BoundingBox }; - var block = grep?.Medium ?? grep; - if (block != null) - { - alternative.Geometry = BuildGeometryData(block, state.SeparateFacesWithDistinctOpenings); - ExpandInstanceGeometry(alternative, block, element.TypeId, state); - } - ExpandTransformOnlyInstanceGeometry(alternative, id, element.TypeId, state); - element.MediumSolidTotals = BrepMeasures.NodeSolidTotalsCurrent(alternative.Geometry); - } - finally { state.DetailView = 0; } + var medium = BuildQuantityGeometry(element.Id, grep, state, GeometryDetail.Medium); + element.MediumSolidTotals = BrepMeasures.NodeSolidTotalsCurrent(medium); } /// True when the block or a nested symbol has a separate Coarse or non-visible quantity view. diff --git a/src/RvtIO/Parsing/ElementBuilder.OwnFamilyCutout.cs b/src/RvtIO/Parsing/ElementBuilder.OwnFamilyCutout.cs index 90263d35..9d00cc4e 100644 --- a/src/RvtIO/Parsing/ElementBuilder.OwnFamilyCutout.cs +++ b/src/RvtIO/Parsing/ElementBuilder.OwnFamilyCutout.cs @@ -5,9 +5,13 @@ namespace RvtIO.Parsing; internal static partial class ElementBuilder { - internal static void ApplyOwnFamilyCutoutInputs(IReadOnlyList elements, ParsingState state) + internal static void ApplyOwnFamilyCutoutInputs(IReadOnlyList elements, ParsingState state, + IReadOnlyDictionary? unique = null) { - var counts = elements.GroupBy(element => element.Id).ToDictionary(group => group.Key, group => group.Count()); + var counts = unique == null + ? elements.GroupBy(element => element.Id).ToDictionary(group => group.Key, group => group.Count()) + : null; + bool IsUnique(int id) => unique?.ContainsKey(id) ?? counts!.GetValueOrDefault(id) == 1; foreach (var element in elements) { element.OwnSingleFamilyCutout = null; @@ -17,7 +21,7 @@ internal static void ApplyOwnFamilyCutoutInputs(IReadOnlyList elements, element.OwnWallTrimmedAxis = null; element.OwnWallCrossSection = null; element.OwnWallHelper = null; - if (element.Id <= 0 || counts[element.Id] != 1 + if (element.Id <= 0 || !IsUnique(element.Id) || !state.ComputedSymbolTargetClasses.TryGetValue((uint)element.Id, out var root) || root.BlockCount != 1) continue; if (root.ClassId is 3524 or 361 @@ -43,7 +47,7 @@ internal static void ApplyOwnFamilyCutoutInputs(IReadOnlyList elements, HostId: > 0, InsertOrientation: 0 } source } || source.HostId != element.SerializedHostId || source.SymbolId != symbolId || !IsUniqueRoot(symbolId, 1829) - || !counts.TryGetValue(symbolId, out int symbolCount) || symbolCount != 1 + || !IsUnique(symbolId) || !state.OwnFamilyCutSymbols.TryGetValue((uint)symbolId, out var computed) || computed is not { BlockCount: 1, Symbol: { Active: true }, Loops.Count: 1 } || !state.FamilyInstanceSymbolIds.TryGetValue((uint)element.Id, out var type) diff --git a/src/RvtIO/Parsing/ElementBuilder.SolidQuantities.cs b/src/RvtIO/Parsing/ElementBuilder.SolidQuantities.cs index 5fbbcd0a..23b30085 100644 --- a/src/RvtIO/Parsing/ElementBuilder.SolidQuantities.cs +++ b/src/RvtIO/Parsing/ElementBuilder.SolidQuantities.cs @@ -15,54 +15,50 @@ internal static void ApplyShellQuantities(RevitFileInfo info, ParsingState state { element.LevelShells = new SolidQuantities.Shell?[3]; element.LevelSolidCounts = new int[3]; - LevelGeometries(element, state, (slot, geometry) => + for (int slot = 0; slot < 3; slot++) { + var geometry = slot == 2 ? element.Geometry : GeometryAtDetailLevel(element, state, slot + 1); element.LevelShells[slot] = SolidQuantities.OfAllSolids(geometry); element.LevelSolidCounts[slot] = geometry?.BrepSolids?.Count ?? 0; - }); + } } } - /// - /// Hands the geometry of an element at Coarse (slot 0), Medium (slot 1) and Fine (slot 2) to - /// , Fine first. A level the element's blocks have no alternative for - /// is the Fine geometry. - /// - internal static void LevelGeometries(Element element, ParsingState state, Action visit) + /// Geometry for measuring solids at Coarse (1) or Medium (2), falling back to Fine when the level has no alternative. + internal static GeometryData? GeometryAtDetailLevel(Element element, ParsingState state, int level) { - visit(2, element.Geometry); - if (element.Id <= 0) - { - visit(0, element.Geometry); - visit(1, element.Geometry); - return; - } + if (element.Id <= 0) return element.Geometry; uint id = (uint)element.Id; state.GrepBlocks.TryGetValue(id, out var grep); 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)); + if (!has) return element.Geometry; + + return BuildQuantityGeometry(element.Id, grep, state, level == 1 ? GeometryDetail.Coarse : GeometryDetail.Medium); + } + + private static GRepData? SelectDetailGeometry(GRepData? block, GeometryDetail detail) => detail switch + { + GeometryDetail.CoarseQuantities => block?.CoarseQuantities ?? block?.Coarse ?? block, + GeometryDetail.Coarse => block?.Coarse ?? block, + GeometryDetail.Medium => block?.Medium ?? block, + _ => block, + }; + + private static GeometryData? BuildQuantityGeometry(int elementId, GRepData? grep, ParsingState state, + GeometryDetail detail) + { + var alternative = new Element { Id = elementId }; + if (SelectDetailGeometry(grep, detail) is { } block) { - 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)); - int slot = level == 1 ? 0 : 1; - if (!has) { visit(slot, element.Geometry); continue; } - state.CoarseView = level == 1; state.DetailView = level; - try - { - var alt = new Element { Id = element.Id, TypeId = element.TypeId, BoundingBox = element.Geometry?.BoundingBox }; - var own = level == 1 ? grep?.Coarse ?? grep : grep?.Medium ?? grep; - if (own != null) - { - alt.Geometry = BuildGeometryData(own, state.SeparateFacesWithDistinctOpenings); - ExpandInstanceGeometry(alt, own, element.TypeId, state); - } - ExpandTransformOnlyInstanceGeometry(alt, id, element.TypeId, state); - visit(slot, alt.Geometry); - } - finally { state.CoarseView = false; state.DetailView = 0; } + alternative.Geometry = BuildGeometryData(block, state.SeparateFacesWithDistinctOpenings, includeEdgesAndInstances: false); + ExpandInstanceGeometry(alternative, block, state, detail); } + ExpandTransformOnlyInstanceGeometry(alternative, (uint)elementId, state, detail); + return alternative.Geometry; } private static bool HasAlternative(GRepData? block, ParsingState state, HashSet visited, int level) diff --git a/src/RvtIO/Parsing/ElementBuilder.cs b/src/RvtIO/Parsing/ElementBuilder.cs index 40859c49..491ac648 100644 --- a/src/RvtIO/Parsing/ElementBuilder.cs +++ b/src/RvtIO/Parsing/ElementBuilder.cs @@ -8,12 +8,15 @@ namespace RvtIO.Parsing; internal static partial class ElementBuilder { + internal enum GeometryDetail { Fine, Coarse, Medium, CoarseQuantities } + /// /// Family instance (GInstance GRep): replace the element's placeholder geometry with the /// SYMBOL's mesh placed by the instance transform (IfcMappedItem architecture); symbols may /// nest (compose transforms up to 4 levels). /// - private static void ExpandInstanceGeometry(Element elem, GRepData grep, int typeId, ParsingState state) + private static void ExpandInstanceGeometry(Element elem, GRepData grep, ParsingState state, + GeometryDetail detail = GeometryDetail.Fine) { if (grep.Instances.Count == 0) return; elem.Geometry ??= new GeometryData(); @@ -25,20 +28,20 @@ private static void ExpandInstanceGeometry(Element elem, GRepData grep, int type { var placed = BuildPlacedSymbolGeometry( instance.SymbolElemId, instance.Transform, state, new HashSet(), placedBox: placedBox, - unresolvedNested: unresolvedNested); + unresolvedNested: unresolvedNested, detail: detail); if (placed == null) { elem.Geometry.UnresolvedSymbol = true; LogUnresolvedSymbol(elem, instance.SymbolElemId, "no-geometry", state); continue; } - if (!state.IncludeNonVisibleQuantities) + if (detail != GeometryDetail.CoarseQuantities) { - placed = ClipGeometryToBounds(placed, grep.BoundingBox, out bool clipped); + placed = ClipGeometryToBounds(placed, grep.BoundingBox, out bool clipped, ownsSource: true); if (clipped) elem.Geometry.PlacedSymbolClipped = true; } if (placed == null) { LogUnresolvedSymbol(elem, instance.SymbolElemId, "clipped-away", state); continue; } - AppendGeometry(elem.Geometry, placed, instance.NodeOrder); + AppendPlacedGeometry(elem.Geometry, placed, instance.NodeOrder); expandedTopLevel.Add(new GeoInstance { SymbolId = instance.SymbolElemId, @@ -57,7 +60,7 @@ private static void ExpandInstanceGeometry(Element elem, GRepData grep, int type /// that layout the mesh is owned directly by SymbolId/typeId. /// private static void ExpandTransformOnlyInstanceGeometry( - Element elem, uint elemId, int typeId, ParsingState state) + Element elem, uint elemId, ParsingState state, GeometryDetail detail = GeometryDetail.Fine) { if ((elem.Geometry?.Faces?.Count ?? 0) >= 3) return; if (!state.FamilyInstanceTransforms.TryGetValue(elemId, out var fi)) return; @@ -65,7 +68,7 @@ private static void ExpandTransformOnlyInstanceGeometry( var placedBox = new StrongBox(); var unresolvedNested = new StrongBox(); var placed = BuildPlacedSymbolGeometry(fi.SymbolId, fi.Trf, state, new HashSet(), placedBox: placedBox, - unresolvedNested: unresolvedNested); + unresolvedNested: unresolvedNested, detail: detail); if (placed == null) { if (elem.Geometry != null) elem.Geometry.UnresolvedSymbol = true; @@ -74,7 +77,7 @@ private static void ExpandTransformOnlyInstanceGeometry( } elem.Geometry ??= new GeometryData(); bool hadOwnFaces = elem.Geometry.Faces.Count > 0; - AppendGeometry(elem.Geometry, placed); + AppendPlacedGeometry(elem.Geometry, placed); if (placedBox.Value) elem.Geometry.PlacedSymbolBox = true; if (unresolvedNested.Value) elem.Geometry.UnresolvedSymbol = true; elem.Geometry.Instances ??= new List(); @@ -187,7 +190,7 @@ double[] Corner(int x, int y, int z) => TransformGeometryPoint( var geometry = new GeometryData { Faces = new List() }; foreach (var quad in quads) { - var ring = quad.Select(index => corners[index]).ToList(); + var ring = quad.Select(index => (double[])corners[index].Clone()).ToList(); if (mirrored) ring.Reverse(); double[] u = [ring[1][0] - ring[0][0], ring[1][1] - ring[0][1], ring[1][2] - ring[0][2]]; double[] v = [ring[3][0] - ring[0][0], ring[3][1] - ring[0][1], ring[3][2] - ring[0][2]]; @@ -198,7 +201,7 @@ double[] Corner(int x, int y, int z) => TransformGeometryPoint( geometry.Faces.Add(new GeoFace { OuterVertices = ring, - Origin = ring[0], XVector = xAxis, YVector = yAxis, + Origin = (double[])ring[0].Clone(), XVector = xAxis, YVector = yAxis, Normal = [ xAxis[1] * yAxis[2] - xAxis[2] * yAxis[1], @@ -228,15 +231,13 @@ private static double[] TransformGeometryPoint(double[] point, double[] t) => internal static GeometryData? BuildPlacedSymbolGeometry( int symbolId, double[] transform, ParsingState state, HashSet path, int scaledComponentFaceBudget = ScaledComponentFaceBudget, StrongBox? placedBox = null, - StrongBox? unresolvedNested = null) + StrongBox? unresolvedNested = null, GeometryDetail detail = GeometryDetail.Fine) { if (symbolId <= 0 || transform.Length < 12 || !path.Add(symbolId)) return null; try { if (!state.GrepBlocks.TryGetValue((uint)symbolId, out var symbol)) return null; - if (state.IncludeNonVisibleQuantities && symbol.CoarseQuantities != null) symbol = symbol.CoarseQuantities; - else if (state.CoarseView && symbol.Coarse != null) symbol = symbol.Coarse; - else if (state.DetailView == 2 && symbol.Medium != null) symbol = symbol.Medium; + symbol = SelectDetailGeometry(symbol, detail)!; if (symbol.Faces.Count > scaledComponentFaceBudget && IsRescaledPlacement(transform)) { // The most frequent face material and graphics style of the replaced component (the @@ -251,26 +252,41 @@ static int MostFrequent(IEnumerable values) => values.GroupBy(value => valu } var result = new GeometryData(); - var own = BuildGeometryData(symbol, state.SeparateFacesWithDistinctOpenings); + var cache = state.SymbolPlacementGeometry; + GeometryData? own; + if (cache == null) own = BuildLocalFaces(); + else + { + // Concurrent placements share the same local faces. Transforms run outside the lock. + lock (cache) + if (!cache.TryGetValue(symbol, out own)) + { + own = BuildLocalFaces(); + cache.Add(symbol, own); + } + } if (own?.Faces is { Count: > 0 }) { - own.Instances = null; - var placedOwn = TransformGeometry(own, transform); - if (placedOwn != null) AppendGeometry(result, placedOwn); + var placedOwn = TransformGeometry(own, transform, areaOnly: detail == GeometryDetail.CoarseQuantities); + if (placedOwn != null) AppendPlacedGeometry(result, placedOwn); } foreach (var child in symbol.Instances) { var childTransform = ComposeTransforms(transform, child.Transform); var placedChild = BuildPlacedSymbolGeometry( - child.SymbolElemId, childTransform, state, path, scaledComponentFaceBudget, placedBox, unresolvedNested); - if (placedChild != null) AppendGeometry(result, placedChild, child.NodeOrder); + child.SymbolElemId, childTransform, state, path, scaledComponentFaceBudget, placedBox, unresolvedNested, detail); + if (placedChild != null) AppendPlacedGeometry(result, placedChild, child.NodeOrder); else if (unresolvedNested != null) unresolvedNested.Value = true; } if (result.Faces.Count == 0) return null; - SetGeometryBoundsFromFaces(result); + if (detail != GeometryDetail.CoarseQuantities) SetGeometryBoundsFromFaces(result); return result; + + GeometryData? BuildLocalFaces() => symbol.Faces.Count > 0 + ? BuildGeometryData(symbol, state.SeparateFacesWithDistinctOpenings, includeEdgesAndInstances: false) + : null; } finally { @@ -307,18 +323,18 @@ internal static void DeduplicateExactFaces(GeometryData geometry) { if (geometry.Faces.Count < 2) return; - var faceByKey = new Dictionary(StringComparer.Ordinal); + var faceByKey = new Dictionary(ExactFaceComparer.Instance); var oldToNew = new int[geometry.Faces.Count]; var uniqueFaces = new List(geometry.Faces.Count); for (int oldIndex = 0; oldIndex < geometry.Faces.Count; oldIndex++) { var face = geometry.Faces[oldIndex]; - string key = ExactFaceKey(face); - if (!faceByKey.TryGetValue(key, out int newIndex)) + ref int newIndex = ref System.Runtime.InteropServices.CollectionsMarshal.GetValueRefOrAddDefault( + faceByKey, face, out bool exists); + if (!exists) { newIndex = uniqueFaces.Count; uniqueFaces.Add(face); - faceByKey[key] = newIndex; } oldToNew[oldIndex] = newIndex; } @@ -341,6 +357,108 @@ internal static void DeduplicateExactFaces(GeometryData geometry) geometry.BrepSolids = uniqueSolids.Count > 0 ? uniqueSolids : null; } + private sealed class ExactFaceComparer : IEqualityComparer + { + internal static readonly ExactFaceComparer Instance = new(); + + public bool Equals(GeoFace? left, GeoFace? right) + { + if (ReferenceEquals(left, right)) return true; + if (left == null || right == null) return false; + if (left.OuterVertices is { Count: > 0 } outer) + { + if (right.OuterVertices is not { Count: > 0 } other || !SameRing(outer, other)) return false; + } + else + { + if (right.OuterVertices is { Count: > 0 } || PointBits(left.Origin) != PointBits(right.Origin) + || PointBits(left.XVector) != PointBits(right.XVector) || PointBits(left.YVector) != PointBits(right.YVector)) + return false; + var envelope = left.Envelope ?? []; + var other = right.Envelope ?? []; + if (envelope.Length != other.Length) return false; + for (int i = 0; i < envelope.Length; i++) + if (BitConverter.DoubleToInt64Bits(envelope[i]) != BitConverter.DoubleToInt64Bits(other[i])) return false; + } + + var holes = left.InnerVertices; + var otherHoles = right.InnerVertices; + int count = HoleCount(holes); + if (count != HoleCount(otherHoles)) return false; + for (int i = 0; i < count; i++) + if (!SameRing(holes![i], otherHoles![i])) + return count > 1 && ExactFaceKey(left) == ExactFaceKey(right); + return true; + } + + private static int HoleCount(List>? holes) => + holes is { Count: 1 } && holes[0].Count == 0 ? 0 : holes?.Count ?? 0; + + private static (long X, long Y, long Z) PointBits(double[] point) => ( + point.Length > 0 ? BitConverter.DoubleToInt64Bits(point[0]) : 0, + point.Length > 1 ? BitConverter.DoubleToInt64Bits(point[1]) : 0, + point.Length > 2 ? BitConverter.DoubleToInt64Bits(point[2]) : 0); + + private static bool SameRing(List left, List right) + { + int count = left.Count; + if (count != right.Count) return false; + int equalInOrder = 0; + while (equalInOrder < count && PointBits(left[equalInOrder]) == PointBits(right[equalInOrder])) + equalInOrder++; + if (equalInOrder == count) return true; + + // Each common prefix point cancels from the two multisets. + int remaining = count - equalInOrder; + Span<(long, long, long)> a = remaining <= 64 ? stackalloc (long, long, long)[remaining] : new (long, long, long)[remaining]; + Span<(long, long, long)> b = remaining <= 64 ? stackalloc (long, long, long)[remaining] : new (long, long, long)[remaining]; + for (int i = 0; i < remaining; i++) + { + a[i] = PointBits(left[equalInOrder + i]); + b[i] = PointBits(right[equalInOrder + i]); + } + a.Sort(); + b.Sort(); + return a.SequenceEqual(b); + } + + public int GetHashCode(GeoFace face) + { + static int PointHash(double[] point) + { + var (x, y, z) = PointBits(point); + return HashCode.Combine(x, y, z); + } + + static int RingHash(List ring) + { + int sum = 0; + foreach (var point in ring) sum = unchecked(sum + PointHash(point)); + return HashCode.Combine(sum, ring.Count); + } + + var hash = new HashCode(); + if (face.OuterVertices is { Count: > 0 } outer) + hash.Add(RingHash(outer)); + else + { + hash.Add(PointHash(face.Origin)); + hash.Add(PointHash(face.XVector)); + hash.Add(PointHash(face.YVector)); + if (face.Envelope != null) + foreach (double value in face.Envelope) hash.Add(BitConverter.DoubleToInt64Bits(value)); + } + if (face.InnerVertices is { Count: > 0 } rings && (rings.Count > 1 || rings[0].Count > 0)) + { + int sum = 0; + foreach (var ring in rings) sum = unchecked(sum + RingHash(ring)); + hash.Add(sum); + hash.Add(rings.Count); + } + return hash.ToHashCode(); + } + } + internal static string ExactFaceKey(GeoFace face) { static string PointKey(double[] point) @@ -403,23 +521,21 @@ internal static bool IsRigidPlacement(double[] t) /// Apply a GInstance placement (rows: basisX, basisY, basisZ, origin - 12 doubles) to a /// symbol's geometry, producing world-space faces for the instance. /// - private static GeometryData? TransformGeometry(GeometryData sym, double[] t) + private static GeometryData? TransformGeometry(GeometryData sym, double[] t, bool areaOnly) { if (t.Length < 12) return null; - double[] Map(double[] p) - { - double x = p[0], y = p[1], z = p.Length > 2 ? p[2] : 0; - return new[] + double[] MapCoordinates(double x, double y, double z) => + new[] { t[9] + x * t[0] + y * t[1] + z * t[2], t[10] + x * t[3] + y * t[4] + z * t[5], t[11] + x * t[6] + y * t[7] + z * t[8], }; - } - var outGeo = new GeometryData { Faces = new List() }; - var faceMap = new Dictionary(); - double minx = double.MaxValue, miny = double.MaxValue, minz = double.MaxValue; - double maxx = double.MinValue, maxy = double.MinValue, maxz = double.MinValue; + double[] Map(double[] p) => MapCoordinates(p[0], p[1], p.Length > 2 ? p[2] : 0); + var mappedOrigin = areaOnly ? [] : MapCoordinates(0, 0, 0); + bool rigid = IsRigidPlacement(t); + var outGeo = new GeometryData(); + var faceMap = sym.BrepSolids is { Count: > 0 } ? new int[sym.Faces.Count] : null; for (int sourceFaceIndex = 0; sourceFaceIndex < sym.Faces.Count; sourceFaceIndex++) { var f = sym.Faces[sourceFaceIndex]; @@ -430,26 +546,25 @@ double[] Map(double[] p) var w = Map(v); if (!double.IsFinite(w[0]) || !double.IsFinite(w[1]) || !double.IsFinite(w[2])) { verts = null; break; } verts.Add(w); - minx = Math.Min(minx, w[0]); maxx = Math.Max(maxx, w[0]); - miny = Math.Min(miny, w[1]); maxy = Math.Max(maxy, w[1]); - minz = Math.Min(minz, w[2]); maxz = Math.Max(maxz, w[2]); } if (verts == null) continue; - var n = Map(new[] { f.Normal[0], f.Normal[1], f.Normal[2] }); - var n0 = Map(new[] { 0.0, 0.0, 0.0 }); - var nd = new[] { n[0] - n0[0], n[1] - n0[1], n[2] - n0[2] }; + double[] normal = []; + double[] origin = []; + if (!areaOnly) + { + normal = MapCoordinates(f.Normal[0], f.Normal[1], f.Normal[2]); + for (int i = 0; i < 3; i++) normal[i] -= mappedOrigin[i]; + origin = (double[])verts[0].Clone(); + } List>? inner = null; if (f.InnerVertices is { Count: > 0 }) inner = f.InnerVertices .Select(loop => loop.Select(Map).ToList()) .Where(loop => loop.Count >= 3).ToList(); - int targetFaceIndex = outGeo.Faces.Count; - outGeo.Faces.Add(new GeoFace + outGeo.Faces.Add(new GeoFace(origin, normal, includePlaneAxes: !areaOnly) { OuterVertices = verts, InnerVertices = inner is { Count: > 0 } ? inner : null, - Normal = nd, - Origin = verts[0], Area = f.Area, PlaneSurface = f.PlaneSurface, NestedRenderStyleId = f.NestedRenderStyleId ?? f.RenderStyleId, @@ -457,41 +572,34 @@ double[] Map(double[] p) NodeOrder = f.NodeOrder, GeometryStyle = f.GeometryStyle, MeshMarker = f.SourceFace != 0 ? f.SourceFace : f.MeshMarker, - QuadratureArea = IsRigidPlacement(t) ? f.QuadratureArea : null, + QuadratureArea = rigid ? f.QuadratureArea : null, }); - faceMap[sourceFaceIndex] = targetFaceIndex; + if (faceMap != null) faceMap[sourceFaceIndex] = outGeo.Faces.Count; } - if (sym.Instances is { Count: > 0 }) - outGeo.Instances = sym.Instances.Select(instance => new GeoInstance - { - SymbolId = instance.SymbolId, - Transform = ComposeTransforms(t, instance.Transform), - NodeOrder = instance.NodeOrder, - }).ToList(); - if (outGeo.Faces.Count == 0 && outGeo.Instances is not { Count: > 0 }) return null; + if (outGeo.Faces.Count == 0) return null; // the Revit face meshes of the nodes are made in the frame of the symbol and placed // with the transform of the instance (a rotation or a mirror image; a scaled instance keeps // the polygons) - if (sym.MeshNodes is { Count: > 0 } && !IsRigidPlacement(t) && Environment.GetEnvironmentVariable("RVTIO_MESH_LOG") == "1") + if (sym.MeshNodes is { Count: > 0 } && !rigid && Environment.GetEnvironmentVariable("RVTIO_MESH_LOG") == "1") DiagnosticSink.WriteLine($"[meshmesh] {sym.MeshNodes.Count} nodes not placed: the transform is scaled ({string.Join(",", t.Select(v => v.ToString("G4")))})"); - if (sym.MeshNodes is { Count: > 0 } && IsRigidPlacement(t)) - outGeo.MeshNodes = sym.MeshNodes.Select(node => node with { Placement = node.Placement == null ? (double[])t.Clone() : ComposeTransforms(t, node.Placement) }).ToList(); + if (sym.MeshNodes is { Count: > 0 } && rigid) + outGeo.MeshNodes = areaOnly ? sym.MeshNodes : sym.MeshNodes.Select(node => node with + { Placement = node.Placement == null ? (double[])t.Clone() : ComposeTransforms(t, node.Placement) }).ToList(); // area and volume are the same in a rigidly placed frame; a scaled one has none - if (sym.NodeMeasures is { Count: > 0 } && IsRigidPlacement(t)) outGeo.NodeMeasures = sym.NodeMeasures; - if (sym.BrepSolids is { Count: > 0 }) + if (sym.NodeMeasures is { Count: > 0 } && rigid) outGeo.NodeMeasures = sym.NodeMeasures; + if (faceMap != null && sym.BrepSolids is { } solids) { outGeo.BrepSolids = new(); - foreach (var solid in sym.BrepSolids) + foreach (var solid in solids) { var mapped = solid.FaceIndices - .Where(faceMap.ContainsKey).Select(i => faceMap[i]).Distinct().ToList(); + .Where(i => (uint)i < (uint)faceMap.Length && faceMap[i] > 0) + .Select(i => faceMap[i] - 1).Distinct().ToList(); if (mapped.Count >= 4) outGeo.BrepSolids.Add(new GeoBrepSolid { FaceIndices = mapped, IsClosed = solid.IsClosed }); } if (outGeo.BrepSolids.Count == 0) outGeo.BrepSolids = null; } - if (outGeo.Faces.Count > 0) - outGeo.BoundingBox = new[] { minx, miny, minz, maxx, maxy, maxz }; outGeo.UntriangulatedFaces = sym.UntriangulatedFaces; return outGeo; } @@ -506,7 +614,11 @@ double[] Map(double[] p) /// True when the result is not the faces of as they are: a face was cut /// or left out, or nothing is left (null). - internal static GeometryData? ClipGeometryToBounds(GeometryData source, double[]? bounds, out bool changed) + internal static GeometryData? ClipGeometryToBounds(GeometryData source, double[]? bounds, out bool changed) => + ClipGeometryToBounds(source, bounds, out changed, ownsSource: false); + + private static GeometryData? ClipGeometryToBounds( + GeometryData source, double[]? bounds, out bool changed, bool ownsSource) { changed = false; if (bounds is not { Length: 6 } @@ -526,6 +638,13 @@ static bool Inside(double[] point, double[] box) .Any(point => !Inside(point, bounds))) return source; + static void RemoveAdjacentDuplicates(List polygon) + { + for (int index = polygon.Count - 1; index > 0; index--) + if (polygon[index].SequenceEqual(polygon[index - 1])) polygon.RemoveAt(index); + if (polygon.Count > 1 && polygon[0].SequenceEqual(polygon[^1])) polygon.RemoveAt(polygon.Count - 1); + } + static List ClipPlane( List polygon, int axis, double limit, bool keepGreater, ref bool changed) { @@ -564,9 +683,7 @@ double[] Intersect(double[] a, double[] b) previous = current; previousInside = currentInside; } - for (int index = output.Count - 1; index > 0; index--) - if (output[index].SequenceEqual(output[index - 1])) output.RemoveAt(index); - if (output.Count > 1 && output[0].SequenceEqual(output[^1])) output.RemoveAt(output.Count - 1); + RemoveAdjacentDuplicates(output); return output; } @@ -589,34 +706,56 @@ double[] Intersect(double[] a, double[] b) var face = source.Faces[oldIndex]; if (face.OuterVertices is not { Count: >= 3 } outer) { changed = true; continue; } bool faceChanged = false; - var polygon = outer.Select(point => (double[])point.Clone()).ToList(); - polygon = ClipPlane(polygon, 0, bounds[0], keepGreater: true, ref faceChanged); - polygon = ClipPlane(polygon, 0, bounds[3], keepGreater: false, ref faceChanged); - polygon = ClipPlane(polygon, 1, bounds[1], keepGreater: true, ref faceChanged); - polygon = ClipPlane(polygon, 1, bounds[4], keepGreater: false, ref faceChanged); - polygon = ClipPlane(polygon, 2, bounds[2], keepGreater: true, ref faceChanged); - polygon = ClipPlane(polygon, 2, bounds[5], keepGreater: false, ref faceChanged); + bool inside = true; + foreach (var point in outer) + inside &= Inside(point, bounds); + var originalCorner = outer[0]; + var polygon = ownsSource ? outer : outer.Select(point => (double[])point.Clone()).ToList(); + if (inside) + RemoveAdjacentDuplicates(polygon); + else + { + polygon = ClipPlane(polygon, 0, bounds[0], keepGreater: true, ref faceChanged); + polygon = ClipPlane(polygon, 0, bounds[3], keepGreater: false, ref faceChanged); + polygon = ClipPlane(polygon, 1, bounds[1], keepGreater: true, ref faceChanged); + polygon = ClipPlane(polygon, 1, bounds[4], keepGreater: false, ref faceChanged); + polygon = ClipPlane(polygon, 2, bounds[2], keepGreater: true, ref faceChanged); + polygon = ClipPlane(polygon, 2, bounds[5], keepGreater: false, ref faceChanged); + } if (faceChanged) changed = true; if (polygon.Count < 3) continue; int newIndex = result.Faces.Count; - result.Faces.Add(new GeoFace - { - Origin = polygon[0], - XVector = (double[])face.XVector.Clone(), - YVector = (double[])face.YVector.Clone(), - Normal = (double[])face.Normal.Clone(), - OuterVertices = polygon, - InnerVertices = face.InnerVertices?.Select(ring => - ring.Select(point => (double[])point.Clone()).ToList()).ToList(), - Area = face.Area, - PlaneSurface = face.PlaneSurface, - NestedRenderStyleId = face.NestedRenderStyleId ?? face.RenderStyleId, - GeometryNode = face.GeometryNode, - NodeOrder = face.NodeOrder, - GeometryStyle = face.GeometryStyle, - MeshMarker = face.SourceFace != 0 ? face.SourceFace : face.MeshMarker, - }); + if (ownsSource) + { + // Placed faces already own their arrays. Clipping retains the polygon + // and planar data, but discards the source envelope and quadrature area. + if (!ReferenceEquals(originalCorner, polygon[0])) face.Origin = (double[])polygon[0].Clone(); + face.OuterVertices = polygon; + face.Envelope = null; + face.QuadratureArea = null; + result.Faces.Add(face); + } + else + { + result.Faces.Add(new GeoFace + { + Origin = polygon[0], + XVector = (double[])face.XVector.Clone(), + YVector = (double[])face.YVector.Clone(), + Normal = (double[])face.Normal.Clone(), + OuterVertices = polygon, + InnerVertices = face.InnerVertices?.Select(ring => + ring.Select(point => (double[])point.Clone()).ToList()).ToList(), + Area = face.Area, + PlaneSurface = face.PlaneSurface, + NestedRenderStyleId = face.NestedRenderStyleId ?? face.RenderStyleId, + GeometryNode = face.GeometryNode, + NodeOrder = face.NodeOrder, + GeometryStyle = face.GeometryStyle, + MeshMarker = face.SourceFace != 0 ? face.SourceFace : face.MeshMarker, + }); + } oldToNew[oldIndex] = newIndex; if (faceChanged) clippedFaces.Add(oldIndex); } @@ -652,12 +791,6 @@ double[] Intersect(double[] a, double[] b) return result; } - /// - /// Whether the per-class object counts of a GRep block outlive the parse (RVTIO_TYPEKEY_DIAG, - /// IfcExporter.TypeKeysCurrent.cs). - /// - private static readonly bool KeepStoredClassCounts = Environment.GetEnvironmentVariable("RVTIO_TYPEKEY_DIAG") is { Length: > 0 }; - /// /// RVTIO_X_GHOSTNODE=0 leaves the curved nodes that have no polygon (a duplicate of another /// node, display surfaces) out of the triangle sets. @@ -675,7 +808,11 @@ internal static string FaceCornerKey(List cs) return string.Join(";", parts); } - public static GeometryData? BuildGeometryData(GRepData grep, bool separateFacesWithDistinctOpenings = false) + public static GeometryData? BuildGeometryData(GRepData grep, bool separateFacesWithDistinctOpenings = false) => + BuildGeometryData(grep, separateFacesWithDistinctOpenings, includeEdgesAndInstances: true); + + private static GeometryData? BuildGeometryData( + GRepData grep, bool separateFacesWithDistinctOpenings, bool includeEdgesAndInstances) { // Skip empty GRep records - no faces and no bounding box = no actual geometry to report. if (grep.Faces.Count == 0 && grep.BoundingBox == null && grep.Instances.Count == 0) return null; @@ -695,7 +832,7 @@ internal static string FaceCornerKey(List cs) UntriangulatedFaces = grep.UntriangulatedFaces, NodeMeasures = grep.NodeMeasures, Transform = grep.Transform, - Instances = grep.Instances.Count > 0 + Instances = includeEdgesAndInstances && grep.Instances.Count > 0 ? grep.Instances.Select(instance => new GeoInstance { SymbolId = instance.SymbolElemId, @@ -703,13 +840,13 @@ internal static string FaceCornerKey(List cs) NodeOrder = instance.NodeOrder, }).ToList() : null, - Vertices = new(), - Edges = new(), - StoredNodeSummary = grep.QueueClassCounts is { } classCounts - ? (classCounts.GetValueOrDefault(GRepParserV2.GFaceClass), classCounts.GetValueOrDefault(GRepParserV2.EdgeClass)) + Vertices = includeEdgesAndInstances ? new() : null, + Edges = includeEdgesAndInstances ? new() : null, + StoredNodeSummary = grep.QueueSummary is { } summary + ? (summary.Faces, summary.Edges) : null, - StoredSolids = grep.QueueClassCounts?.GetValueOrDefault(GRepParserV2.SolidClass), - StoredClassCounts = KeepStoredClassCounts ? grep.QueueClassCounts : null, + StoredSolids = grep.QueueSummary?.Solids, + StoredClassCounts = grep.QueueClassCounts, }; // Dedup vertices by rounding to 1e-6 precision @@ -718,7 +855,7 @@ int GetOrAddVertex(double x, double y, double z) { var key = ((long)Math.Round(x * 1e6), (long)Math.Round(y * 1e6), (long)Math.Round(z * 1e6)); if (vertexMap.TryGetValue(key, out int idx)) return idx; - idx = geo.Vertices.Count; + idx = geo.Vertices!.Count; geo.Vertices.Add(new[] { x, y, z }); vertexMap[key] = idx; return idx; @@ -726,15 +863,24 @@ int GetOrAddVertex(double x, double y, double z) int AddEdge(int v0, int v1) { - int idx = geo.Edges.Count; + int idx = geo.Edges!.Count; geo.Edges.Add(new GeoEdge { - Start = geo.Vertices[v0], + Start = geo.Vertices![v0], End = geo.Vertices[v1], }); return idx; } + void AddPolygonEdges(List corners, List edges) + { + Span vertices = stackalloc int[4]; + for (int i = 0; i < vertices.Length; i++) + vertices[i] = GetOrAddVertex(corners[i][0], corners[i][1], corners[i][2]); + for (int i = 0; i < vertices.Length; i++) + edges.Add(AddEdge(vertices[i], vertices[(i + 1) % vertices.Length])); + } + List EnvelopeToCorners(double[] env, double[] origin, double[] xv, double[] yv) { double minU = env[0], minV = env[1], maxU = env[2], maxV = env[3]; @@ -751,7 +897,9 @@ List EnvelopeToCorners(double[] env, double[] origin, double[] xv, dou // rescans) under different plane parameterizations. Deduplicate by the face's canonical 3D // corners: same 4 corner positions = same face. var seenFaces = new Dictionary(); - var grepFaceToGeoFace = new Dictionary(); + var grepFaceToGeoFace = new int[grep.Faces.Count]; + bool indexSourcePolygons = !grep.PreserveSourceFaceIdentity + || grep.Faces.Any(face => face.Vertices is not { Count: >= 3 } && face.Envelope is { Length: 4 }); static string CornerKey(List cs) => FaceCornerKey(cs); for (int grepFaceIndex = 0; grepFaceIndex < grep.Faces.Count; grepFaceIndex++) @@ -764,12 +912,16 @@ List EnvelopeToCorners(double[] env, double[] origin, double[] xv, dou // Two faces that share their outline but not their holes are two faces (the cap of // a window frame and the cap of the glazing bar behind it are the same rectangle // with different openings). - var ck2 = CornerKey(poly) + (separateFacesWithDistinctOpenings && fp.InnerVertices is { Count: > 0 } innerRings - ? "#" + string.Join("|", innerRings.Select(CornerKey).Order(StringComparer.Ordinal)) : ""); - if (!grep.PreserveSourceFaceIdentity && seenFaces.TryGetValue(ck2, out int existing)) + if (indexSourcePolygons) { - grepFaceToGeoFace[grepFaceIndex] = existing; - continue; + var key = CornerKey(poly) + (separateFacesWithDistinctOpenings && fp.InnerVertices is { Count: > 0 } innerRings + ? "#" + string.Join("|", innerRings.Select(CornerKey).Order(StringComparer.Ordinal)) : ""); + if (!grep.PreserveSourceFaceIdentity && seenFaces.TryGetValue(key, out int existing)) + { + grepFaceToGeoFace[grepFaceIndex] = existing; + continue; + } + seenFaces[key] = geo.Faces.Count; } var gf = new GeoFace { @@ -802,14 +954,15 @@ List EnvelopeToCorners(double[] env, double[] origin, double[] xv, dou }; int added = geo.Faces.Count; geo.Faces.Add(gf); - seenFaces[ck2] = added; grepFaceToGeoFace[grepFaceIndex] = added; continue; } + List? corners = null; if (fp.Envelope is { Length: 4 } envK) { - var ck = CornerKey(EnvelopeToCorners(envK, fp.Origin, fp.XVector, fp.YVector)); + corners = EnvelopeToCorners(envK, fp.Origin, fp.XVector, fp.YVector); + var ck = CornerKey(corners); if (seenFaces.TryGetValue(ck, out int existing)) { grepFaceToGeoFace[grepFaceIndex] = existing; @@ -846,17 +999,12 @@ List EnvelopeToCorners(double[] env, double[] origin, double[] xv, dou geoFace.Area = Math.Max(0, a); } - if (fp.Envelope is { Length: 4 }) + if (corners != null) { - var corners = EnvelopeToCorners(fp.Envelope, fp.Origin, fp.XVector, fp.YVector); geoFace.OuterVertices = corners; - var edgeIndices = new List(); - var vi = new int[4]; - for (int i = 0; i < 4; i++) - vi[i] = GetOrAddVertex(corners[i][0], corners[i][1], corners[i][2]); - for (int i = 0; i < 4; i++) - edgeIndices.Add(AddEdge(vi[i], vi[(i + 1) % 4])); + var edgeIndices = includeEdgesAndInstances ? new List() : null; + if (edgeIndices != null) AddPolygonEdges(corners, edgeIndices); if (fp.InnerLoops.Count > 0) { @@ -867,11 +1015,7 @@ List EnvelopeToCorners(double[] env, double[] origin, double[] xv, dou var innerCorners = EnvelopeToCorners(il, fp.Origin, fp.XVector, fp.YVector); geoFace.InnerVertices.Add(innerCorners); - var ivi = new int[4]; - for (int i = 0; i < 4; i++) - ivi[i] = GetOrAddVertex(innerCorners[i][0], innerCorners[i][1], innerCorners[i][2]); - for (int i = 0; i < 4; i++) - edgeIndices.Add(AddEdge(ivi[i], ivi[(i + 1) % 4])); + if (edgeIndices != null) AddPolygonEdges(innerCorners, edgeIndices); } } @@ -910,7 +1054,7 @@ List EnvelopeToCorners(double[] env, double[] origin, double[] xv, dou foreach (var solid in grep.Solids) { var mapped = solid.FaceIndices - .Where(grepFaceToGeoFace.ContainsKey) + .Where(i => (uint)i < (uint)grepFaceToGeoFace.Length) .Select(i => grepFaceToGeoFace[i]).Distinct().ToList(); if (mapped.Count >= 4) geo.BrepSolids.Add(new GeoBrepSolid { FaceIndices = mapped, IsClosed = solid.IsClosed }); @@ -922,8 +1066,8 @@ List EnvelopeToCorners(double[] env, double[] origin, double[] xv, dou RemoveInteriorLayerFaces(geo.Faces); // Set to null if empty to avoid JSON bloat - if (geo.Vertices.Count == 0) geo.Vertices = null; - if (geo.Edges.Count == 0) geo.Edges = null; + if (geo.Vertices is { Count: 0 }) geo.Vertices = null; + if (geo.Edges is { Count: 0 }) geo.Edges = null; return geo; } @@ -1168,7 +1312,11 @@ private static bool TryResolveFamilyNameViaTable( } public static void BuildElemTableElement( - uint elemId, uint typeId, ParsingState state, RevitFileInfo rvtInfo) + uint elemId, uint typeId, ParsingState state, RevitFileInfo rvtInfo, HashSet? parameterIds = null) + => rvtInfo.Elements.Add(CreateElemTableElement(elemId, typeId, state, parameterIds ?? new())); + + internal static Element CreateElemTableElement( + uint elemId, uint typeId, ParsingState state, HashSet parameterIds) { var elem = new Element { Id = (int)elemId, TypeId = -1 }; elem.NativeHeaderCategoryId = state.HeaderCategories.GetValueOrDefault(elemId); @@ -1212,11 +1360,11 @@ public static void BuildElemTableElement( elem.Parameters.Add(BipHelpers.MakeBipParam(-1140363, "ELEM_CATEGORY_PARAM_MT", StorageType.ElementId, resolvedHeader)); } } - rvtInfo.Elements.Add(elem); - return; + return elem; } elem.Name = ResolveElementName(elemId, state); + parameterIds.Clear(); GRepData? grepDataForElem = null; if (state.Records.TryGetValue(elemId, out var rec)) @@ -1247,8 +1395,8 @@ public static void BuildElemTableElement( if (refStrings.Count > 0) elem.RefStrings = refStrings; } - AddBodyBipParams(elem, rec, elemId, state); - AddUserParams(elem, rec, elemId, state); + AddBodyBipParams(elem, rec, elemId, state, parameterIds); + AddUserParams(elem, rec, elemId, state, parameterIds); } if (!elem.CategoryId.HasValue && wideHeaderCategory is int wideCat) @@ -1263,14 +1411,14 @@ public static void BuildElemTableElement( // The tight box of the record stays on the geometry; the element box comes from the // header outline (ApplyHeaderBoundingBoxes). elem.Geometry = BuildGeometryData(grepDataForElem, state.SeparateFacesWithDistinctOpenings); - ExpandInstanceGeometry(elem, grepDataForElem, (int)typeId, state); + ExpandInstanceGeometry(elem, grepDataForElem, state); } - AddBipDoubles(elem, elemId, state); - AddBipInts(elem, elemId, state); - AddPropagatedBipDoubles(elem, elemId, state); - AddBaseFields(elem, elemId, state); - AddComputedElementParams(elem, elemId, typeId, state); + AddBipDoubles(elem, elemId, state, parameterIds); + AddBipInts(elem, elemId, state, parameterIds); + AddPropagatedBipDoubles(elem, elemId, state, parameterIds); + AddBaseFields(elem, elemId, state, parameterIds); + AddComputedElementParams(elem, parameterIds); AttachFamilyCutGeometry(elem, elemId, state); @@ -1280,13 +1428,13 @@ public static void BuildElemTableElement( AddBboxDimensionsIfMissing(elem, state); BuildLocationCurve(elem, elemId, state); BuildInstanceTransform(elem, elemId, state); - ExpandTransformOnlyInstanceGeometry(elem, elemId, (int)typeId, state); + ExpandTransformOnlyInstanceGeometry(elem, elemId, state); AttachComputedSymbolGeometry(elem, elemId, state); AttachDimension(elem, elemId, state); AttachSketchCurve(elem, elemId, state); ApplyOwnWallPlanarBody(elem, state); - rvtInfo.Elements.Add(elem); + return elem; } /// @@ -1341,11 +1489,8 @@ 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) + internal static void ResolveTypeParams(RevitFileInfo info, IReadOnlyDictionary byId) { - 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) @@ -1361,62 +1506,59 @@ private static void ResolveTypeParams(RevitFileInfo info) // Seed: type element ids that some element already carries (from the binary body). var seed = new HashSet(); - foreach (var e in info.Elements) - { - int t = TypeParamOf(e); - if (t > 0) seed.Add(t); - } - // 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 unresolved = new List(); + var refCat = new Dictionary(); + var otherCategories = new Dictionary<(int Reference, int Category), int>(); + var seenRefs = new HashSet(); foreach (var e in info.Elements) { - if (e.References == null || !e.CategoryId.HasValue) continue; - int c = e.CategoryId.Value; - var seenRefs = new HashSet(); + int t = TypeParamOf(e); + if (t > 0) seed.Add(t); + if (e.References is not { Count: > 0 }) continue; + if (t <= 0) unresolved.Add(e); + if (e.CategoryId is not int c) continue; + seenRefs.Clear(); foreach (var r in e.References) { 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; + ref var votes = ref System.Runtime.InteropServices.CollectionsMarshal.GetValueRefOrAddDefault(refCat, r, out bool exists); + if (!exists) votes.Category = c; + votes.Total++; + if (votes.Category == c) votes.Count++; + else + System.Runtime.InteropServices.CollectionsMarshal.GetValueRefOrAddDefault(otherCategories, (r, c), out _)++; } } - foreach (var e in info.Elements) + foreach (var e in unresolved) { - if (e.References == null || e.References.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.References!) 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) + foreach (var r in e.References!) { - if (r <= 1000 || r == e.Id || !seen.Add(r)) continue; + if (r <= 1000 || r == e.Id) 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; - } - double frac = tot > 0 ? (double)n / tot : 0; - bool qualifies = (n >= 2 && frac >= 0.6) || seed.Contains(r); + refCat.TryGetValue(r, out var votes); + int n = votes.Category == C ? votes.Count : otherCategories.GetValueOrDefault((r, C)); + bool knownType = seed.Contains(r); + bool qualifies = (n >= 2 && votes.Total > 0 && (double)n / votes.Total >= 0.6) || knownType; if (!qualifies) continue; - int score = n + (seed.Contains(r) ? 100 : 0); + int score = n + (knownType ? 100 : 0); if (score > bestScore) { bestScore = score; chosen = r; } } } @@ -1489,10 +1631,9 @@ private static bool TryCurveDriverLineZ(TfBlockDeserializer.NativeParams np, out /// (INSTANCE_REFERENCE_LEVEL_PARAM) is the driver's stored m_refLevelId, else the Level the /// instance's sketch plane lies on (SketchPlane OnDatumPlaneRef.m_datumPlaneId). /// - internal static void ApplyCurveDriverLevelParams(RevitFileInfo info) + internal static void ApplyCurveDriverLevelParams(RevitFileInfo info, IReadOnlyDictionary? byId = null) { - var byId = new Dictionary(); - foreach (var e in info.Elements) byId.TryAdd(e.Id, e); + byId ??= IndexElements(info.Elements); foreach (var e in info.Elements) { if (e.CurveDriverRefLevelId is not int stored) continue; @@ -1532,10 +1673,10 @@ 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, + IReadOnlyDictionary? byId = null) { - var byId = new Dictionary(); - foreach (var e in info.Elements) byId.TryAdd(e.Id, e); + byId ??= IndexElements(info.Elements); foreach (var e in info.Elements) { if (e.SerializedHostId is not int host || host <= 0) continue; @@ -1587,10 +1728,9 @@ 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, IReadOnlyDictionary? byId = null) { - var byId = new Dictionary(); - foreach (var e in info.Elements) byId.TryAdd(e.Id, e); + byId ??= IndexElements(info.Elements); foreach (var e in info.Elements) { if (e.CategoryId is not (-2001330 or -2000100) || e.NativeMasterSymbolId == null || e.FamilyLevelRefs is not { } refs) continue; @@ -1609,10 +1749,9 @@ internal static void ApplyStructuralColumnParams(RevitFileInfo info) ? elevation : null; } - internal static void ApplyFramingSymbolLength(RevitFileInfo info) + internal static void ApplyFramingSymbolLength(RevitFileInfo info, IReadOnlyDictionary? byId = null) { - var byId = new Dictionary(); - foreach (var e in info.Elements) byId.TryAdd(e.Id, e); + byId ??= IndexElements(info.Elements); foreach (var e in info.Elements) { if (e.CategoryId != -2001320 || e.NativeMasterSymbolId == null || e.InstanceSymbolId is not int symbolId @@ -1621,10 +1760,9 @@ internal static void ApplyFramingSymbolLength(RevitFileInfo info) } } - internal static void ApplyHeadHeight(RevitFileInfo info) + internal static void ApplyHeadHeight(RevitFileInfo info, IReadOnlyDictionary? byId = null) { - var byId = new Dictionary(); - foreach (var e in info.Elements) byId.TryAdd(e.Id, e); + byId ??= IndexElements(info.Elements); foreach (var e in info.Elements) { if (e.CategoryId is not (-2000014 or -2000023) || e.NativeMasterSymbolId is not int typeId) continue; @@ -1644,7 +1782,7 @@ internal static void ApplyHeadHeight(RevitFileInfo info) /// topography surface/subregion. /// internal static void ApplyHostLabels(RevitFileInfo info, Lookup.RevitSystemFamilyNames? names, - IReadOnlyDictionary? classByElement) + IReadOnlyDictionary? classByElement, IReadOnlyDictionary? byId = null) { if (names == null) return; foreach (var group in info.Elements) @@ -1653,8 +1791,7 @@ internal static void ApplyHostLabels(RevitFileInfo info, Lookup.RevitSystemFamil else if (group.IsNativeLevel) group.SerializedUiFamilyLabel = names.Get(Lookup.RevitUiText.LevelFamily); else if (group.CategoryId == -2001340) group.SerializedUiFamilyLabel = names.Get(Lookup.RevitUiText.TopographySurface); } - var byId = new Dictionary(); - foreach (var e in info.Elements) byId.TryAdd(e.Id, e); + byId ??= IndexElements(info.Elements); foreach (var e in info.Elements) { var host = e.Parameters.FirstOrDefault(p => p.Id == -1001363); @@ -1705,11 +1842,11 @@ 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, + IReadOnlyDictionary? byId = null) { if (names == null) return; - var byId = new Dictionary(); - foreach (var e in info.Elements) byId.TryAdd(e.Id, e); + byId ??= IndexElements(info.Elements); string? DatumLabel(Element datum) { if (datum.IsNativeLevel) @@ -1743,7 +1880,7 @@ internal static void ApplyWorkPlaneLabels(RevitFileInfo info, Lookup.RevitSystem /// name Revit supplies for the type's root class, else the family of the type; null when the /// type or a name is unknown. /// - private static string? FamilyAndTypeLabel(Element element, Dictionary byId) + private static string? FamilyAndTypeLabel(Element element, IReadOnlyDictionary byId) { if (element.TypeId <= 0 || !byId.TryGetValue(element.TypeId, out var type)) return null; static string? NonEmpty(string? text) => string.IsNullOrEmpty(text) ? null : text; @@ -2051,22 +2188,41 @@ private static void TraceElement(RevitFileInfo info, string stage) internal static void PruneNativeFieldTableOutsideDomains(RevitFileInfo info, IReadOnlyDictionary? classByElement) { if (classByElement == null) return; + var byParameter = new Dictionary(); + var domainNames = new Dictionary<(ushort? Class, int? Category), (string Root, string Domain)>(); foreach (var e in info.Elements) { 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"); - bool InDomain(string[] domains) => Array.IndexOf(domains, domain) >= 0 || Array.IndexOf(domains, rootClass) >= 0; - foreach (var group in added.GroupBy(row => row.ParamId)) - { - var rows = group.ToList(); - int paramId = group.Key; + var domainKey = (Class: classByElement.TryGetValue((uint)e.Id, out var cls) ? (ushort?)cls : null, Category: e.CategoryId); + if (!domainNames.TryGetValue(domainKey, out var names)) + { + string root = domainKey.Class?.ToString(System.Globalization.CultureInfo.InvariantCulture) ?? "None"; + string category = domainKey.Category?.ToString(System.Globalization.CultureInfo.InvariantCulture) ?? "None"; + names = (root, root + "/" + category); + domainNames.Add(domainKey, names); + } + byParameter.Clear(); + for (int i = 0; i < added.Count; i++) + { + var row = added[i]; + ref var indices = ref System.Runtime.InteropServices.CollectionsMarshal.GetValueRefOrAddDefault( + byParameter, row.ParamId, out bool exists); + if (!exists) indices = (i, i, -1); + indices.Last = i; // PHASE_CREATED is what the IFC exporter takes as a placed element without a // category (a project phase reference): a class-wide table row must not hand it to // elements the legacy phase pass left without. - var matching = paramId == -1012100 && e.CategoryId == null - ? default : rows.LastOrDefault(row => InDomain(row.Domains)); - if (matching.Domains == null) + if ((row.ParamId != -1012100 || e.CategoryId != null) + && (Array.IndexOf(row.Domains, names.Domain) >= 0 || Array.IndexOf(row.Domains, names.Root) >= 0)) + indices.Matching = i; + } + for (int i = 0; i < added.Count; i++) + { + int paramId = added[i].ParamId; + var indices = byParameter[paramId]; + if (indices.First != i) continue; + var last = added[indices.Last]; + if (indices.Matching < 0) { // No row of the table applies to this element: drop what the table created, // give back what it overwrote (unless a later pass already replaced the table's @@ -2074,8 +2230,8 @@ internal static void PruneNativeFieldTableOutsideDomains(RevitFileInfo info, IRe if (e.NativeTableCreatedParams?.Contains(paramId) == true) e.Parameters.RemoveAll(p => p.Id == paramId); else if (e.NativeTablePrevious != null && e.NativeTablePrevious.TryGetValue(paramId, out var previous)) { - var overwritten = e.Parameters.FirstOrDefault(p => p.Id == paramId); - if (overwritten != null && Equals(overwritten.Value, rows[^1].Value)) + var overwritten = FindParameterById(e.Parameters, paramId); + if (overwritten != null && Equals(overwritten.Value, last.Value)) { overwritten.Value = previous.Value; overwritten.StorageType = previous.Storage; @@ -2086,10 +2242,10 @@ internal static void PruneNativeFieldTableOutsideDomains(RevitFileInfo info, IRe } // Rows are applied in table order, an out-of-domain row may have overwritten the // in-domain value. - var last = rows[^1]; - var parameter = e.Parameters.FirstOrDefault(p => p.Id == paramId); - if (!InDomain(last.Domains) && parameter != null && Equals(parameter.Value, last.Value)) + if (indices.Matching != indices.Last + && FindParameterById(e.Parameters, paramId) is { } parameter && Equals(parameter.Value, last.Value)) { + var matching = added[indices.Matching]; parameter.Value = matching.Value; parameter.StorageType = matching.Storage; parameter.HasNoRevitValue = matching.HasNoRevitValue; @@ -2235,10 +2391,9 @@ internal static void ApplyDetailCurveFlag(RevitFileInfo info, IReadOnlyDictionar } } - internal static void ApplyCrossSectionRotation(RevitFileInfo info) + internal static void ApplyCrossSectionRotation(RevitFileInfo info, IReadOnlyDictionary? byId = null) { - var byId = new Dictionary(); - foreach (var e in info.Elements) byId.TryAdd(e.Id, e); + byId ??= IndexElements(info.Elements); foreach (var e in info.Elements) { if (e.CurveDriverRotation is not double rotation) continue; @@ -2262,12 +2417,29 @@ bool IsPhase(int id) => id >= 0 && ((classByElement.TryGetValue((uint)id, out va || projectPhaseOrder?.Contains(id) == true); foreach (var e in info.Elements) { - if (e.SerializedCreatedPhaseId is int created && IsPhase(created) - && e.Parameters.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)) - SetParam(e, -1012101, "PHASE_DEMOLISHED", StorageType.ElementId, demolished); + int? created = e.SerializedCreatedPhaseId; + int? demolished = e.SerializedDemolishedPhaseId; + bool setCreated = created is int cp && IsPhase(cp); + bool setDemolished = demolished is int dp && (dp == -1 || IsPhase(dp)); + if (!setCreated && !setDemolished) continue; + foreach (var parameter in e.Parameters) + { + if (parameter.Id == -1012100 && setCreated) + { + parameter.Value = created!.Value; + setCreated = false; + } + else if (parameter.Id == -1012101 && setDemolished) + { + parameter.Value = demolished!.Value; + setDemolished = false; + } + else continue; + + parameter.StorageType = StorageType.ElementId; + e.BoundingBoxDimensionParamIds?.Remove(parameter.Id); + if (!setCreated && !setDemolished) break; + } } } @@ -2276,10 +2448,9 @@ 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, IReadOnlyDictionary? byId = null) { - var byId = new Dictionary(); - foreach (var e in info.Elements) byId.TryAdd(e.Id, e); + byId ??= IndexElements(info.Elements); foreach (var e in info.Elements) { if (e.StructuralConnectionTypes is not { } connections || e.NativeMasterSymbolId is not int symbolId @@ -2332,10 +2503,9 @@ internal static void ApplyRoomBuildingTypeLoads(RevitFileInfo info) } } - internal static void ApplyRoomLevelParams(RevitFileInfo info) + internal static void ApplyRoomLevelParams(RevitFileInfo info, IReadOnlyDictionary? byId = null) { - var byId = new Dictionary(); - foreach (var e in info.Elements) byId.TryAdd(e.Id, e); + byId ??= IndexElements(info.Elements); foreach (var e in info.Elements) { if (e.CategoryId is not (-2000160 or -2003200)) continue; // OST_Rooms, OST_Areas @@ -2348,6 +2518,17 @@ internal static void ApplyRoomLevelParams(RevitFileInfo info) } } + private static Dictionary IndexElements(List elements, bool keepLast = false) + { + var byId = new Dictionary(elements.Count); + foreach (var element in elements) + { + if (keepLast) byId[element.Id] = element; + else byId.TryAdd(element.Id, element); + } + return byId; + } + private static void SetParam(Element e, int id, string name, StorageType storage, object value) { var existing = e.Parameters.FirstOrDefault(p => p.Id == id); @@ -2357,10 +2538,9 @@ 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, IReadOnlyDictionary? byId = null) { - var byId = new Dictionary(); - foreach (var e in info.Elements) byId.TryAdd(e.Id, e); + byId ??= IndexElements(info.Elements); foreach (var e in info.Elements) { if (e.NativeMasterSymbolId == null || e.Transform?.Origin is not { Length: 3 } origin) continue; @@ -2441,6 +2621,7 @@ private static void AddCategoryAndFamilyParams(RevitFileInfo info) foreach (var e in info.Elements) { bool hasCat = false, hasCatMt = false, hasFam = false; + bool hasHost = false, hasOffset = false, hasDesignOption = false, hasPhaseDemolished = false; int typeVal = -1; foreach (var p in e.Parameters) { @@ -2450,6 +2631,10 @@ private static void AddCategoryAndFamilyParams(RevitFileInfo info) case -1140363: hasCatMt = true; break; case -1002051: hasFam = true; break; case -1002050: if (p.Value is int tv && tv > 1000) typeVal = tv; break; + case -1002108: hasHost = true; break; + case -1001370: hasOffset = true; break; + case -1013201: hasDesignOption = true; break; + case -1012101: hasPhaseDemolished = true; break; } } @@ -2458,14 +2643,17 @@ private static void AddCategoryAndFamilyParams(RevitFileInfo info) // Uncategorized elements and system/annotation classes categorized via the // 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 (!hasHost) + e.Parameters.Add(BipHelpers.MakeBipParam(-1002108, "HOST_ID_PARAM", StorageType.ElementId, -1)); + if (!hasOffset) e.Parameters.Add(BipHelpers.MakeBipParam(-1001370, "INSTANCE_OFFSET_POS_PARAM", StorageType.Integer, 0, hasNoRevitValue: true)); } - AddBipIfMissing(e, -1013201, "DESIGN_OPTION_ID", -1); + if (!hasDesignOption) + e.Parameters.Add(BipHelpers.MakeBipParam(-1013201, "DESIGN_OPTION_ID", StorageType.ElementId, -1)); // PHASE_DEMOLISHED: -1 ("None") is the only value seen. - AddBipIfMissing(e, -1012101, "PHASE_DEMOLISHED", -1); + if (!hasPhaseDemolished) + e.Parameters.Add(BipHelpers.MakeBipParam(-1012101, "PHASE_DEMOLISHED", StorageType.ElementId, -1)); int catVal = int.MinValue; if (!e.CategoryId.HasValue) catVal = -1; @@ -2487,11 +2675,15 @@ private static void AddCategoryAndFamilyParams(RevitFileInfo info) /// Apply decoded 0x09B6 material shading appearance (color/shininess/transparency/ glow) as /// parameters on the owning OST_Materials element. /// - internal static void ApplyMaterialAppearance(RevitFileInfo info, ParsingState? state) + internal static void ApplyMaterialAppearance(RevitFileInfo info, ParsingState? state, + Dictionary? byId = null) { if (state == null) return; - var byId = new Dictionary(); - foreach (var e in info.Elements) byId[e.Id] = e; + if (byId == null) + { + byId = new Dictionary(); + foreach (var e in info.Elements) byId[e.Id] = e; + } var colored = new HashSet(); foreach (var (eid, m) in state.MaterialAppearances) @@ -2741,10 +2933,9 @@ 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, IReadOnlyDictionary? byId = null) { - var byId = new Dictionary(); - foreach (var e in info.Elements) byId[e.Id] = e; + byId ??= IndexElements(info.Elements, keepLast: true); foreach (var e in info.Elements) { @@ -2809,11 +3000,9 @@ 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; void Add(Element e, int id, string name, object val) { @@ -3132,7 +3321,10 @@ private static void ApplyWorksets(RevitFileInfo info, ParsingState? state) /// 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) + private static readonly string[] NativeTypeAttributeFields = ["m_floorAttributesId", "m_roofAttributesId", "m_attrId"]; + + internal static void ApplyNativeParams(RevitFileInfo info, ParsingState? state, + IReadOnlyDictionary? unique = null) { if (state == null || (state.NativeParams.Count == 0 @@ -3140,7 +3332,7 @@ internal static void ApplyNativeParams(RevitFileInfo info, ParsingState? state) && state.FamilySymbolFunctions.Count == 0)) return; ApplySerializedCeilingTypeLinks( - info.Elements, state.NativeParams, state.ElemClassIdx); + info.Elements, state.NativeParams, state.ElemClassIdx, unique); var groupOfMember = new Dictionary(); foreach (var (group, members) in state.GroupMembers.OrderBy(pair => pair.Key)) foreach (int member in members) groupOfMember.TryAdd(member, (int)group); @@ -3154,7 +3346,23 @@ internal static void ApplyNativeParams(RevitFileInfo info, ParsingState? state) } bool hasZeroPhase = Parameter.HasZeroProjectPhase(info, state); bool hasZeroDimStyle = Parameter.HasZeroDimensionStyle(info, state); - foreach (var e in info.Elements) + if (info.Elements.Count > 0) + Parallel.ForEach(System.Collections.Concurrent.Partitioner.Create(0, info.Elements.Count), + range => ApplyRange(range.Item1, range.Item2)); + Parameter.ResolveZeroElementIds(info, state); + + void ApplyRange(int start, int end) + { + var byId = new Dictionary(); + var nativeFieldRows = new List(); + var nativeFieldValues = new object?[NativeFieldParameters.All.Length]; + var storeIds = new HashSet(); + for (int index = start; index < end; index++) + ApplyElement(info.Elements[index], byId, nativeFieldRows, nativeFieldValues, storeIds); + } + + void ApplyElement(Element e, Dictionary byId, List nativeFieldRows, + object?[] nativeFieldValues, HashSet storeIds) { e.SerializedCurtainWallFunction = null; if (e.Id > 0 && state.NewCurtainWallTypeFunctions.TryGetValue( @@ -3177,7 +3385,7 @@ internal static void ApplyNativeParams(RevitFileInfo info, ParsingState? state) e.NativeDesignOptionName = null; e.SerializedGroupId = groupOfMember.TryGetValue(e.Id, out int owningGroup) ? owningGroup : null; e.NativeRecordClass = state.ElemClassIdx.TryGetValue((uint)e.Id, out ushort recordClass) ? recordClass : null; - if (!state.NativeParams.TryGetValue((uint)e.Id, out var np)) continue; + if (!state.NativeParams.TryGetValue((uint)e.Id, out var np)) return; if (np.Fields.TryGetValue("3471:m_bIsLocationless", out int locationless)) e.SerializedRoomIsLocationless = locationless != 0; if (np.StringFields.TryGetValue("388:m_areaElemName", out string? areaSchemeName) @@ -3200,25 +3408,23 @@ 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(); + storeIds.Clear(); 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; + var storeSnapshot = storeIds.ToArray(); + e.NativeParameterStoreIds = storeSnapshot; + // Both properties describe stored provenance. Only named-only IDs need a second snapshot. + foreach (var named in np.NamedParams) + if (named.ParamId < 0) storeIds.Add(named.ParamId); + e.NativeStoredParameterIds = storeIds.Count == 0 ? null + : storeIds.Count == storeSnapshot.Length ? storeSnapshot : storeIds.ToArray(); e.NativeParameterStoresComplete = np.RootParameterStoresComplete; e.NativeCellListTag = np.Fields.TryGetValue("37:m_cellList", out int cellListTag) ? cellListTag : null; - e.NativeCellClasses = np.CellClasses?.ToArray(); + e.NativeCellClasses = np.CellClasses; e.NativeTailWalkComplete = np.TailWalkComplete; e.ExtensibleStorage = np.ExtensibleStorage; if (np.NamedParams.Count > 0) @@ -3252,7 +3458,7 @@ internal static void ApplyNativeParams(RevitFileInfo info, ParsingState? state) foreach (var (pid, value) in np.ElementIds) e.DebugNativeFields["store.E:" + pid] = value; foreach (var (pid, value) in np.Strings) e.DebugNativeFields["store.S:" + pid] = value; } - void Apply(int pid, StorageType st, object val, bool force = false, bool fromTable = false, bool noRevitValue = false) + void Apply(int pid, StorageType st, T val, bool force = false, bool fromTable = false, bool noRevitValue = false) { // An explicit rule that sets the parameter takes it over from the field table's // domain bookkeeping. @@ -3270,7 +3476,7 @@ void Apply(int pid, StorageType st, object val, bool force = false, bool fromTab // heuristic. if (hollow || force) { - existing.Value = val; + existing.Value = Parameter.BoxParsedValue(val); existing.StorageType = st; existing.FromNativeFields = true; existing.HasNoRevitValue = noRevitValue; @@ -3278,8 +3484,7 @@ void Apply(int pid, StorageType st, object val, bool force = false, bool fromTab } return; } - BipNames.Lookup.TryGetValue(pid, out string? name); - var par = BipHelpers.MakeBipParam(pid, name ?? pid.ToString(), st, val, hasNoRevitValue: noRevitValue); + var par = BipHelpers.MakeStoredBipParam(pid, st, Parameter.BoxParsedValue(val), noRevitValue); par.FromNativeFields = true; e.Parameters.Add(par); byId[pid] = par; @@ -3342,8 +3547,8 @@ void ApplyType(int typeId) e.HostId = serializedHostId > 0 ? serializedHostId : null; Apply(-1002108, StorageType.ElementId, serializedHostId, force: true, noRevitValue: serializedHostId <= 0); // HOST_ID_PARAM } - e.ExtraHostIds = CapturedElementIds("m_extraHostIds"); - e.ExplicitHostIds = CapturedElementIds("m_explicitHostIds"); + e.ExtraHostIds = CapturedElementIds("m_extraHostIds@"); + e.ExplicitHostIds = CapturedElementIds("m_explicitHostIds@"); if (np.Fields.TryGetValue("m_superInstanceId", out int superInstanceId) && superInstanceId > 0) e.SuperInstanceId = superInstanceId; @@ -3374,7 +3579,7 @@ void ApplyType(int typeId) if (np.Fields.TryGetValue("m_wallCrossSection", out int wcs)) Apply(-1019100, StorageType.Integer, wcs); // WALL_CROSS_SECTION // Floor / Roof / Level(Datum) type-attribute ids -> type params. - foreach (var attrName in new[] { "m_floorAttributesId", "m_roofAttributesId", "m_attrId" }) + foreach (var attrName in NativeTypeAttributeFields) { if (np.Fields.TryGetValue(attrName, out int at) && at > 0) { @@ -3413,7 +3618,7 @@ void ApplyType(int typeId) foreach (var named in np.NamedParams) { if (named.ParamId <= 0) continue; - var existing = e.Parameters.FirstOrDefault(p => p.Id == named.ParamId); + byId.TryGetValue(named.ParamId, out var existing); var namedStorage = FamilyParamStorageFromSpec(state, named.ParamId); if (namedStorage == StorageType.None && existing is { StorageType: not StorageType.None }) namedStorage = existing.StorageType; @@ -3458,21 +3663,19 @@ void ApplyType(int typeId) byId[named.ParamId] = e.Parameters[^1]; } // Parameters stored verbatim in a schema field. - foreach (var entry in NativeFieldParameters.All) - { - object? tableValue = null; - bool tableSet = false; - switch (entry.Storage) - { - case StorageType.Double when np.DoubleFields.TryGetValue(entry.Key, out double fieldDouble): - tableValue = fieldDouble; tableSet = double.IsFinite(fieldDouble) && Math.Abs(fieldDouble) < 1e29; break; - case StorageType.Integer or StorageType.ElementId when np.Fields.TryGetValue(entry.Key, out int fieldInt): - tableValue = fieldInt; tableSet = entry.Storage != StorageType.ElementId || fieldInt != -1; break; - case StorageType.String when np.StringFields.TryGetValue(entry.Key, out string? fieldString): - tableValue = fieldString; tableSet = true; break; - } - if (tableValue == null) continue; - if (NativeFieldParameters.NotWithCompleteStores.Contains((entry.ParamId, entry.Key)) && np.RootParameterStoresComplete) continue; + NativeFieldParameters.CollectPresentRows(np, nativeFieldRows, nativeFieldValues); + foreach (int row in nativeFieldRows) + { + var entry = NativeFieldParameters.All[row]; + var tableValue = nativeFieldValues[row]; + nativeFieldValues[row] = null; + if (tableValue == null || (np.RootParameterStoresComplete && entry.RequiresIncompleteStores)) continue; + bool tableSet = entry.Storage switch + { + StorageType.Double => double.IsFinite((double)tableValue) && Math.Abs((double)tableValue) < 1e29, + StorageType.ElementId => (int)tableValue != -1, + _ => true, + }; bool hasRevitValue = tableSet && (entry.Storage != StorageType.ElementId || Parameter.IsSetElementId(entry.ParamId, (int)tableValue, Parameter.IsValidZeroElementIdTarget(e, entry.ParamId, hasZeroPhase, hasZeroDimStyle))); // Presence domains: where the field is not the raw -1 / >= 1e29 sentinel, those of the row (even when parameter-specific @@ -3494,7 +3697,8 @@ void ApplyType(int typeId) } if (state.ElemClassIdx.TryGetValue((uint)e.Id, out var mepCurveClass) && mepCurveClass is 3148 or 3210 or 3134 or 598) ApplyMepCurveGeometry(np, mepCurveClass, (pid, st, val, force) => Apply(pid, st, val, force)); - else ApplyFlexCurveGeometry(np, mepCurveClass, (pid, st, val, force) => Apply(pid, st, val, force)); + else if (mepCurveClass is 3177 or 3180) + ApplyFlexCurveGeometry(np, mepCurveClass, (pid, st, val, force) => Apply(pid, st, val, force)); if (np.DoubleFields.TryGetValue("1709:m_rotation", out double curveDriverRotation) && double.IsFinite(curveDriverRotation)) e.CurveDriverRotation = curveDriverRotation; if (np.Fields.TryGetValue("1708:m_refLevelId", out int curveDriverLevel)) @@ -3533,10 +3737,12 @@ void ApplyType(int typeId) Apply(origin, StorageType.Double, gridOrigin, force: true); } } - foreach (string userData in new[] { "3789", "3775" }) - if (np.Fields.TryGetValue(userData + ":m_connectionType@0", out int firstConnection) - && np.Fields.TryGetValue(userData + ":m_connectionType@1", out int secondConnection)) - e.StructuralConnectionTypes = (firstConnection, secondConnection); + if (np.Fields.TryGetValue("3789:m_connectionType@0", out int firstConnection) + && np.Fields.TryGetValue("3789:m_connectionType@1", out int secondConnection)) + e.StructuralConnectionTypes = (firstConnection, secondConnection); + if (np.Fields.TryGetValue("3775:m_connectionType@0", out firstConnection) + && np.Fields.TryGetValue("3775:m_connectionType@1", out secondConnection)) + e.StructuralConnectionTypes = (firstConnection, secondConnection); if (np.Fields.TryGetValue("1419:m_buildingTypeId", out int buildingType) && buildingType > 0) e.EnergyBuildingTypeId = buildingType; if (np.Fields.TryGetValue("2237:m_symbolId", out int instanceSymbol) && instanceSymbol > 0) @@ -3619,15 +3825,14 @@ void ApplyType(int typeId) } } - List? CapturedElementIds(string fieldName) + List? CapturedElementIds(string prefix) { - var values = np.Fields - .Where(pair => pair.Key.StartsWith(fieldName + "@", StringComparison.Ordinal)) - .OrderBy(pair => int.Parse(pair.Key[(fieldName.Length + 1)..], - System.Globalization.CultureInfo.InvariantCulture)) - .Select(pair => pair.Value) - .ToList(); - return values.Count > 0 ? values : null; + List>? matches = null; + foreach (var field in np.Fields) + if (field.Key.StartsWith(prefix, StringComparison.Ordinal)) + (matches ??= new()).Add(field); + return matches?.OrderBy(pair => int.Parse(pair.Key.AsSpan(prefix.Length), + System.Globalization.CultureInfo.InvariantCulture)).Select(pair => pair.Value).ToList(); } if (np.Fields.TryGetValue("m_useEqualityFormula", out int ueq)) Apply(-1004514, StorageType.Integer, ueq); // DIM_DISPLAY_EQ @@ -3675,7 +3880,6 @@ void ApplyType(int typeId) if (np.Fields.TryGetValue("m_bUseTrueNorth", out int tn)) Apply(-1005168, StorageType.Integer, tn); // PLAN_VIEW_NORTH } - Parameter.ResolveZeroElementIds(info, state); } /// @@ -3683,7 +3887,7 @@ void ApplyType(int typeId) /// duplicated id is omitted: choosing either owner/target would make native link selection /// depend on materialization order. /// - private static Dictionary BuildUniqueElementIndexForNativeCeilingLinks( + private static Dictionary BuildUniqueElementIndex( IReadOnlyList elements) { var uniqueElementsById = new Dictionary(); @@ -3708,10 +3912,10 @@ private static Dictionary BuildUniqueElementIndexForNativeCeilingL internal static void ApplySerializedCeilingTypeLinks( IReadOnlyList elements, IReadOnlyDictionary nativeParams, - IReadOnlyDictionary classIds) + IReadOnlyDictionary classIds, + IReadOnlyDictionary? uniqueElementsById = null) { - Dictionary uniqueElementsById = - BuildUniqueElementIndexForNativeCeilingLinks(elements); + uniqueElementsById ??= BuildUniqueElementIndex(elements); foreach (Element occurrence in elements) { occurrence.SerializedCeilingTypeId = null; @@ -3941,10 +4145,11 @@ internal static void ApplySerializedStairData( private static void ApplyBipKeyedStrings(RevitFileInfo info, ParsingState? state) { if (state == null || state.BipKeyedStrings.Count == 0) return; + var byBip = new Dictionary(); foreach (var e in info.Elements) { if (!state.BipKeyedStrings.TryGetValue((uint)e.Id, out var map)) continue; - var byBip = new Dictionary(); + byBip.Clear(); foreach (var p in e.Parameters) byBip.TryAdd(p.Id, p); foreach (var (bip, val) in map) { @@ -3969,9 +4174,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). @@ -4014,11 +4216,10 @@ private static void ApplyComputedHeights(RevitFileInfo info, ParsingState? state foreach (var e in info.Elements) { - 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; void Add(int id, string name, double val) { - if (!existing.Contains(id)) + if (FindParameterById(e.Parameters, id) == null) e.Parameters.Add(BipHelpers.MakeBipParam(id, name, StorageType.Double, val)); } @@ -4138,25 +4339,24 @@ private static void AddViewAndDatumDefaults(RevitFileInfo info) { // 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 = null; + var existing = new HashSet(); foreach (var e in info.Elements) { if (e.CategoryId is not int c) continue; - var existing = new HashSet(); + 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.Parameters) 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); @@ -4166,12 +4366,13 @@ void Add(int id, string name, StorageType st, object val) Add(-1005333, "VIEW_GRAPH_SUN_PATH", StorageType.Integer, 0); Add(-1012202, "VIEWER_VOLUME_OF_INTEREST_CROP", StorageType.ElementId, -1); Add(-1005254, "VIEWPORT_ATTR_ORIENTATION_ON_SHEET", StorageType.Integer, 0); + domPhase ??= DominantCreatedPhase(info.Elements); if (domPhase > 0) - Add(-1012102, "VIEW_PHASE", StorageType.ElementId, domPhase); + Add(-1012102, "VIEW_PHASE", StorageType.ElementId, domPhase.Value); } - 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); @@ -4200,11 +4401,9 @@ void Add(int id, string name, StorageType st, object val) /// Apply decoded 0x085A HVACLoadSpaceType energy-load parameters as Double parameters on the /// owning space-type element. /// - private static void ApplyHvacSpaceTypeParams(RevitFileInfo info, ParsingState? state) + private static void ApplyHvacSpaceTypeParams(ParsingState? state, IReadOnlyDictionary byId) { if (state == null || state.HvacSpaceTypeParams.Count == 0) return; - var byId = new Dictionary(); - foreach (var e in info.Elements) byId[e.Id] = e; foreach (var (eid, vals) in state.HvacSpaceTypeParams) { @@ -4268,7 +4467,11 @@ internal static void AddCurveLengths(RevitFileInfo info) } } - public static void BuildDiscoveredElement(uint eid, ParsingState state, RevitFileInfo rvtInfo) + public static void BuildDiscoveredElement(uint eid, ParsingState state, RevitFileInfo rvtInfo, + HashSet? parameterIds = null) + => rvtInfo.Elements.Add(CreateDiscoveredElement(eid, state, parameterIds ?? new())); + + internal static Element CreateDiscoveredElement(uint eid, ParsingState state, HashSet parameterIds) { var rec = state.Records[eid]; var elem = new Element { Id = (int)eid, TypeId = -1, IsDiscovered = true }; @@ -4290,38 +4493,34 @@ public static void BuildDiscoveredElement(uint eid, ParsingState state, RevitFil // The tight box of the record stays on the geometry; the element box comes from the // header outline (ApplyHeaderBoundingBoxes). elem.Geometry = BuildGeometryData(grepData, state.SeparateFacesWithDistinctOpenings); - ExpandInstanceGeometry(elem, grepData, elem.TypeId, state); + ExpandInstanceGeometry(elem, grepData, state); } if (rec.References.Count > 0) elem.References = rec.References.Select(r => (int)r).ToList(); + parameterIds.Clear(); // 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 }, - }; + var param = BipHelpers.MakeBipParam(b.BipId, bipName, null, null); if (param.StorageType == StorageType.Double && state.ElemBipDoubles.TryGetValue(eid, out var dblMap) && dblMap.TryGetValue(b.BipId, out double dv)) - param.Value = dv; + param.Value = Parameter.BoxParsedValue(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)) - param.Value = iv; + param.Value = Parameter.BoxParsedValue(iv); else - param.Value = b.Value.HasValue ? (object)b.Value.Value : null; + param.Value = b.Value is int value ? Parameter.BoxParsedValue(value) : null; elem.Parameters.Add(param); + parameterIds.Add(param.Id); } - AddBipDoubles(elem, eid, state); - AddBipInts(elem, eid, state); - AddPropagatedBipDoubles(elem, eid, state); - AddBaseFields(elem, eid, state); + AddBipDoubles(elem, eid, state, parameterIds); + AddBipInts(elem, eid, state, parameterIds); + AddPropagatedBipDoubles(elem, eid, state, parameterIds); + AddBaseFields(elem, eid, state, parameterIds); AttachFamilyCutGeometry(elem, eid, state); if (grepData != null) @@ -4330,15 +4529,16 @@ public static void BuildDiscoveredElement(uint eid, ParsingState state, RevitFil AddBboxDimensionsIfMissing(elem, state); BuildLocationCurve(elem, eid, state); BuildInstanceTransform(elem, eid, state); - ExpandTransformOnlyInstanceGeometry(elem, eid, elem.TypeId, state); + ExpandTransformOnlyInstanceGeometry(elem, eid, state); AttachDimension(elem, eid, state); AttachSketchCurve(elem, eid, state); ApplyOwnWallPlanarBody(elem, state); - rvtInfo.Elements.Add(elem); + return elem; } - public static void BuildBlockOnlyElement(uint bid, ParsingState state, RevitFileInfo rvtInfo) + public static void BuildBlockOnlyElement(uint bid, ParsingState state, RevitFileInfo rvtInfo, + HashSet? parameterIds = null) { var elem = new Element { Id = (int)bid, TypeId = -1, IsBlockOnly = true }; elem.UniqueId = BuildUniqueId(bid, state); @@ -4351,11 +4551,13 @@ public static void BuildBlockOnlyElement(uint bid, ParsingState state, RevitFile // The tight box of the record stays on the geometry; the element box comes from the // header outline (ApplyHeaderBoundingBoxes). elem.Geometry = BuildGeometryData(grepData, state.SeparateFacesWithDistinctOpenings); - ExpandInstanceGeometry(elem, grepData, elem.TypeId, state); + ExpandInstanceGeometry(elem, grepData, state); } - AddBipDoubles(elem, bid, state); - AddBaseFields(elem, bid, state); + parameterIds ??= new HashSet(); + parameterIds.Clear(); + AddBipDoubles(elem, bid, state, parameterIds); + AddBaseFields(elem, bid, state, parameterIds); AttachFamilyCutGeometry(elem, bid, state); if (grepData != null) @@ -4611,9 +4813,10 @@ internal static void ApplyValidatedMemberTypeNames( } // Late native type canonicalization must not leave an earlier type's name on a door. - internal static void ApplyValidatedDoorTypeNames(IReadOnlyList elements, ParsingState state) + internal static void ApplyValidatedDoorTypeNames(IReadOnlyList elements, ParsingState state, + IReadOnlyDictionary? unique = null) { - var unique = BuildUniqueElementIndexForNativeCeilingLinks(elements); + unique ??= BuildUniqueElementIndex(elements); foreach (var instance in elements) { if (instance.CategoryId != -2000023 || instance.Id <= 0 @@ -4672,11 +4875,11 @@ internal static void ApplyValidatedCeilingTypeReferenceNames( IReadOnlyList elements, IReadOnlyDictionary source, IReadOnlyDictionary nativeParams, - IReadOnlyDictionary classIds) + IReadOnlyDictionary classIds, + IReadOnlyDictionary? uniqueElementsById = null) { const int CeilingsCategoryId = -2000038; - Dictionary uniqueElementsById = - BuildUniqueElementIndexForNativeCeilingLinks(elements); + uniqueElementsById ??= BuildUniqueElementIndex(elements); foreach (Element element in elements) { element.ValidatedCeilingTypeReferenceName = null; @@ -5099,20 +5302,20 @@ internal static int ApplyHostTypeCompoundStructures(IReadOnlyList eleme return applied; } - internal static int ApplyBasicWallTypeThickness(IReadOnlyList elements, ParsingState state) + internal static int ApplyBasicWallTypeThickness(IReadOnlyList elements, ParsingState state, + IReadOnlyDictionary? unique = null) { - var counts = new Dictionary(); + unique ??= BuildUniqueElementIndex(elements); foreach (var element in elements) { element.ValidatedWallTypeThicknessFeet = null; - counts[element.Id] = counts.GetValueOrDefault(element.Id) + 1; } int applied = 0; foreach (var element in elements) { - if (element.Id <= 0 || counts[element.Id] != 1 || element.IsBlockOnly + if (element.Id <= 0 || !unique.ContainsKey(element.Id) || element.IsBlockOnly || element.CategoryId != -2000011 || element.SerializedSystemTypeId is not int typeId - || !counts.TryGetValue(typeId, out int typeCount) || typeCount != 1 + || !unique.ContainsKey(typeId) || !state.SystemTypeRoots.TryGetValue((uint)typeId, out var root) || root.BlockCount != 1 || root.ClassId != 512 || !state.HostTypeCompoundStructures.TryGetValue((uint)typeId, out var host) @@ -5125,18 +5328,18 @@ internal static int ApplyBasicWallTypeThickness(IReadOnlyList elements, return applied; } - internal static int ApplyCompoundCeilingTypeThickness(IReadOnlyList elements, ParsingState state) + internal static int ApplyCompoundCeilingTypeThickness(IReadOnlyList elements, ParsingState state, + IReadOnlyDictionary? unique = null) { - var counts = new Dictionary(); + unique ??= BuildUniqueElementIndex(elements); foreach (var element in elements) { element.ValidatedCeilingTypeThicknessFeet = null; - counts[element.Id] = counts.GetValueOrDefault(element.Id) + 1; } int applied = 0; foreach (var element in elements) { - if (element.Id <= 0 || counts[element.Id] != 1 || element.IsBlockOnly || element.CategoryId != -2000038 + if (element.Id <= 0 || !unique.ContainsKey(element.Id) || element.IsBlockOnly || element.CategoryId != -2000038 || !state.SystemTypeRoots.TryGetValue((uint)element.Id, out var root) || root.BlockCount != 1 || root.ClassId != 646 || !state.HostTypeCompoundStructures.TryGetValue((uint)element.Id, out var host) @@ -5150,16 +5353,16 @@ internal static int ApplyCompoundCeilingTypeThickness(IReadOnlyList ele } internal static int ApplyValidatedSystemFamilyNames( - IReadOnlyList elements, ParsingState state, Lookup.RevitSystemFamilyNames? names) + IReadOnlyList elements, ParsingState state, Lookup.RevitSystemFamilyNames? names, + IReadOnlyDictionary? unique = null) { foreach (var element in elements) { element.ValidatedSystemFamilyName = null; element.ValidatedMepFamilyName = null; } if (names == null) return 0; - var counts = new Dictionary(); - foreach (var element in elements) counts[element.Id] = counts.GetValueOrDefault(element.Id) + 1; + unique ??= BuildUniqueElementIndex(elements); int assigned = 0; foreach (var element in elements) { - if (element.Id <= 0 || counts[element.Id] != 1 + if (element.Id <= 0 || !unique.ContainsKey(element.Id) || !state.SystemTypeRoots.TryGetValue((uint)element.Id, out var root) || root.BlockCount != 1 || root.ClassId == 0 || Lookup.RevitSystemFamilyNames.KindOf(root.ClassId, root.Discriminator, element.CategoryId) @@ -5178,14 +5381,14 @@ or Lookup.SystemFamilyKind.CableTrayWithoutFittings or Lookup.SystemFamilyKind.C } internal static void ApplyValidatedStairOccurrenceNames(IReadOnlyList elements, - Lookup.RevitSystemFamilyNames? names) + Lookup.RevitSystemFamilyNames? names, IReadOnlyDictionary? unique = null) { foreach (var element in elements) element.ValidatedStairOccurrenceName = null; if (names?.StairOccurrenceName is not { Length: > 0 } name) return; - var counts = elements.GroupBy(element => element.Id).ToDictionary(group => group.Key, group => group.Count()); - var unique = elements.Where(element => counts[element.Id] == 1).ToDictionary(element => element.Id); - foreach (var element in unique.Values) + unique ??= BuildUniqueElementIndex(elements); + foreach (var element in elements) { + if (element.CategoryId != -2000120 || !unique.ContainsKey(element.Id)) continue; if (element.Id > 0 && !element.IsBlockOnly && element.CategoryId == -2000120 && element.RootClassName == "Stairs") { element.ValidatedStairOccurrenceName = name; @@ -5202,14 +5405,17 @@ internal static void ApplyValidatedStairOccurrenceNames(IReadOnlyList e } } - internal static void ApplyStairNameParameterScopes(IReadOnlyList elements, ParsingState state) + internal static void ApplyStairNameParameterScopes(IReadOnlyList elements, ParsingState state, + IReadOnlyDictionary? unique = null) { foreach (var element in elements) element.SerializedStairNameParameters = null; - var counts = elements.GroupBy(element => element.Id).ToDictionary(group => group.Key, group => group.Count()); + if (state.StairNameParameterRoots.Count == 0) return; + unique ??= BuildUniqueElementIndex(elements); foreach (var element in elements) { - if (element.Id <= 0 || element.IsBlockOnly || counts[element.Id] != 1 + if (element.Id <= 0 || element.IsBlockOnly || element.SerializedOwnElementClassId is not (3681 or 3708 or 3686 or 3727) + || !unique.ContainsKey(element.Id) || !state.StairNameParameterRoots.TryGetValue((uint)element.Id, out var root) || root is not { BlockCount: 1, Input: { } input } || input.OwnerId != element.Id || !input.Values.RootParameterStoresComplete) continue; @@ -5233,17 +5439,17 @@ internal static void ApplyStairNameParameterScopes(IReadOnlyList elemen } } - internal static void ApplyValidatedStairComponentTypeNames(IReadOnlyList elements, ParsingState state) + internal static void ApplyValidatedStairComponentTypeNames(IReadOnlyList elements, ParsingState state, + IReadOnlyDictionary? unique = null) { - var counts = new Dictionary(); + unique ??= BuildUniqueElementIndex(elements); foreach (var element in elements) { element.ValidatedStairComponentTypeName = null; - counts[element.Id] = counts.GetValueOrDefault(element.Id) + 1; } foreach (var element in elements) { - if (element.Id <= 0 || counts[element.Id] != 1 || element.IsBlockOnly + if (element.Id <= 0 || !unique.ContainsKey(element.Id) || element.IsBlockOnly || !state.SystemTypeRoots.TryGetValue((uint)element.Id, out var root) || root.BlockCount != 1 || !state.StairComponentTypeNames.TryGetValue((uint)element.Id, out var validation) @@ -5256,17 +5462,17 @@ internal static void ApplyValidatedStairComponentTypeNames(IReadOnlyList elements, ParsingState state) + internal static void ApplyValidatedDuctTypeNames(IReadOnlyList elements, ParsingState state, + IReadOnlyDictionary? unique = null) { - var counts = new Dictionary(); + unique ??= BuildUniqueElementIndex(elements); foreach (var element in elements) { element.ValidatedDuctTypeName = null; - counts[element.Id] = counts.GetValueOrDefault(element.Id) + 1; } foreach (var element in elements) { - if (element.Id <= 0 || counts[element.Id] != 1 || element.IsBlockOnly + if (element.Id <= 0 || !unique.ContainsKey(element.Id) || element.IsBlockOnly || element.CategoryId != -2008000 || !state.SystemTypeRoots.TryGetValue((uint)element.Id, out var root) || root is not { BlockCount: 1, ClassId: 110, Discriminator: 124 or 126 or 127 } @@ -5281,17 +5487,17 @@ internal static void ApplyValidatedDuctTypeNames(IReadOnlyList elements /// must be one unique materialized type whose single exact root has the class of the name /// block. /// - internal static void ApplyValidatedMepTypeNames(IReadOnlyList elements, ParsingState state) + internal static void ApplyValidatedMepTypeNames(IReadOnlyList elements, ParsingState state, + IReadOnlyDictionary? unique = null) { - var counts = new Dictionary(); + unique ??= BuildUniqueElementIndex(elements); foreach (var element in elements) { element.ValidatedMepTypeName = null; - counts[element.Id] = counts.GetValueOrDefault(element.Id) + 1; } foreach (var element in elements) { - if (element.Id <= 0 || counts[element.Id] != 1 || element.IsBlockOnly + if (element.Id <= 0 || !unique.ContainsKey(element.Id) || element.IsBlockOnly || !state.SystemTypeRoots.TryGetValue((uint)element.Id, out var root) || root.BlockCount != 1 || root.ClassId == 0 || !state.MepTypeNames.TryGetValue((uint)element.Id, out var validation) @@ -5304,21 +5510,21 @@ internal static void ApplyValidatedMepTypeNames(IReadOnlyList elements, /// Type of a pipe, flex pipe, pipe insulation, duct or cable tray occurrence from its own /// RbsCurve.m_idType. /// - internal static void ApplyMepCurveTypeLinks(IReadOnlyList elements, ParsingState state) + internal static void ApplyMepCurveTypeLinks(IReadOnlyList elements, ParsingState state, + IReadOnlyDictionary? unique = null) { - var counts = new Dictionary(); + unique ??= BuildUniqueElementIndex(elements); foreach (var element in elements) { element.SerializedMepCurveTypeId = null; - counts[element.Id] = counts.GetValueOrDefault(element.Id) + 1; } foreach (var element in elements) { - if (element.Id <= 0 || counts[element.Id] != 1 || element.IsBlockOnly + if (element.Id <= 0 || !unique.ContainsKey(element.Id) || element.IsBlockOnly || !state.SystemOccurrenceTypeIds.TryGetValue((uint)element.Id, out var occurrence) || occurrence.BlockCount != 1 || occurrence.TypeId is not > 0 || occurrence.TypeId == element.Id || !MepCurveTypeClass(occurrence.ClassId, out ushort typeClass) - || counts.GetValueOrDefault(occurrence.TypeId.Value) != 1 + || !unique.ContainsKey(occurrence.TypeId.Value) || !state.SystemTypeRoots.TryGetValue((uint)occurrence.TypeId.Value, out var root) || root.BlockCount != 1 || root.ClassId != typeClass) continue; element.SerializedMepCurveTypeId = occurrence.TypeId; @@ -5341,17 +5547,17 @@ private static bool MepCurveTypeClass(ushort occurrenceClass, out ushort typeCla return typeClass != 0; } - internal static void ApplyValidatedCorniceTypeNames(IReadOnlyList elements, ParsingState state) + internal static void ApplyValidatedCorniceTypeNames(IReadOnlyList elements, ParsingState state, + IReadOnlyDictionary? unique = null) { - var counts = new Dictionary(); + unique ??= BuildUniqueElementIndex(elements); foreach (var element in elements) { element.ValidatedCorniceTypeName = null; - counts[element.Id] = counts.GetValueOrDefault(element.Id) + 1; } foreach (var element in elements) { - if (element.Id <= 0 || counts[element.Id] != 1 || element.IsBlockOnly + if (element.Id <= 0 || !unique.ContainsKey(element.Id) || element.IsBlockOnly || element.CategoryId != -2000181 || !state.SystemTypeRoots.TryGetValue((uint)element.Id, out var root) || root is not { BlockCount: 1, ClassId: 873 } @@ -5365,25 +5571,23 @@ internal static void ApplyValidatedCorniceTypeNames(IReadOnlyList eleme /// Preserve exact system-type identity separately from public type guesses. Both occurrence and /// type must have unique, compatible own roots. /// - internal static void ApplySerializedSystemTypeIdentity(IReadOnlyList elements, ParsingState state) + internal static void ApplySerializedSystemTypeIdentity(IReadOnlyList elements, ParsingState state, + IReadOnlyDictionary? unique = null) { - var counts = new Dictionary(); foreach (var element in elements) { element.SerializedSystemTypeId = null; element.SerializedSystemTypeClassId = null; - counts[element.Id] = counts.GetValueOrDefault(element.Id) + 1; } - var needed = state.SystemOccurrenceTypeIds.Values.Where(value => value.TypeId is > 0) - .Select(value => value.TypeId!.Value).ToHashSet(); - var types = elements.Where(element => needed.Contains(element.Id) && counts[element.Id] == 1) - .ToDictionary(element => element.Id); + if (state.SystemOccurrenceTypeIds.Count == 0) return; + unique ??= BuildUniqueElementIndex(elements); foreach (var element in elements) { - if (element.Id <= 0 || counts[element.Id] != 1 || element.IsBlockOnly + if (element.Id <= 0 || element.IsBlockOnly || !state.SystemOccurrenceTypeIds.TryGetValue((uint)element.Id, out var occurrence) || occurrence.BlockCount != 1 || occurrence.TypeId is not > 0 - || !types.TryGetValue(occurrence.TypeId.Value, out var type) || type.IsBlockOnly + || !unique.ContainsKey(element.Id) + || !unique.TryGetValue(occurrence.TypeId.Value, out var type) || type.IsBlockOnly || type.Id == element.Id // a Floor occurrence is filed under OST_Floors even when its foundation slab type // is not @@ -5412,28 +5616,21 @@ internal static void ApplySerializedSystemTypeIdentity(IReadOnlyList el /// roots/materialization and non-FamilySymbol targets stay unvalidated. Generated block-only /// symbols are valid targets, just as in the original API. /// - internal static void ApplyValidatedOriginalFamilySymbols(IReadOnlyList elements, ParsingState state) + internal static void ApplyValidatedOriginalFamilySymbols(IReadOnlyList elements, ParsingState state, + IReadOnlyDictionary? unique = null) { - var counts = new Dictionary(); + unique ??= BuildUniqueElementIndex(elements); foreach (var element in elements) { element.ValidatedOriginalFamilySymbolId = null; - counts[element.Id] = counts.GetValueOrDefault(element.Id) + 1; - } - var needed = state.ComputedFamilySymbols.Values.Where(value => value.Symbol != null) - .Select(value => value.Symbol!.SymbolId).ToHashSet(); - var symbols = elements.Where(element => needed.Contains(element.Id) && counts[element.Id] == 1) - .ToDictionary(element => element.Id); - foreach (var element in elements) - { - element.SerializedFlippedSymbol = element.Id > 0 && counts[element.Id] == 1 - && state.ComputedFamilySymbols.TryGetValue((uint)element.Id, out var root) - && root is { BlockCount: 1, Symbol: { FlippedX: bool flippedX, FlippedY: bool flippedY } } - ? flippedX != flippedY : null; - if (element.Id <= 0 || counts[element.Id] != 1 + element.SerializedFlippedSymbol = null; + if (element.Id <= 0 || !state.ComputedFamilySymbols.TryGetValue((uint)element.Id, out var own) - || own.BlockCount != 1 || own.Symbol is not { SymbolId: > 0 } source - || source.SymbolId == element.Id || !symbols.ContainsKey(source.SymbolId) + || own.BlockCount != 1 || own.Symbol is not { } source + || !unique.ContainsKey(element.Id)) continue; + if (source is { FlippedX: bool flippedX, FlippedY: bool flippedY }) + element.SerializedFlippedSymbol = flippedX != flippedY; + if (source.SymbolId <= 0 || source.SymbolId == element.Id || !unique.ContainsKey(source.SymbolId) || !state.ComputedSymbolTargetClasses.TryGetValue((uint)source.SymbolId, out var target) || target is not { BlockCount: 1, ClassId: 1829 }) continue; @@ -5445,9 +5642,10 @@ internal static void ApplyValidatedOriginalFamilySymbols(IReadOnlyList /// Ceiling.getTypeId_ reads its own m_ceilingAttributesId. Replace the earlier /// voted type only after both unique compatible roots have established that link. /// - internal static void ApplyValidatedCeilingCanonicalTypes(IReadOnlyList elements, ParsingState state) + internal static void ApplyValidatedCeilingCanonicalTypes(IReadOnlyList elements, ParsingState state, + IReadOnlyDictionary? uniqueElements = null) { - var uniqueElements = BuildUniqueElementIndexForNativeCeilingLinks(elements); + uniqueElements ??= BuildUniqueElementIndex(elements); foreach (var element in elements) { if (element.CategoryId != -2000038 || element.IsBlockOnly @@ -5756,7 +5954,7 @@ internal static void RepairBasicWallTypeFunctionBodyFallbacks( } } - public static void PostProcess(RevitFileInfo rvtInfo, ParsingState? state = null, TextWriter? diag = null) + public static IReadOnlyDictionary PostProcess(RevitFileInfo rvtInfo, ParsingState? state = null, TextWriter? diag = null) { ApplyGridDatums(rvtInfo, state); rvtInfo.GraphicsStyles = state?.GraphicsStyles @@ -5767,12 +5965,11 @@ 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 elemByIdLookup = rvtInfo.Elements.ToDictionary(e => e.Id); foreach (var e in rvtInfo.Elements) { if (!string.IsNullOrEmpty(e.Name)) idToName[e.Id] = e.Name; - idToElem[e.Id] = e; } // Inherit category from type element or references Phase 1: TypeId and ELEM_TYPE_PARAM @@ -5896,7 +6093,7 @@ public static void PostProcess(RevitFileInfo rvtInfo, ParsingState? state = null 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 = elemByIdLookup.GetValueOrDefault(refId); if (refElem?.Category is "OST_PreviewLegendComponents" or "OST_Materials") continue; materialName = rn; break; @@ -5922,8 +6119,7 @@ public static void PostProcess(RevitFileInfo rvtInfo, ParsingState? state = null { foreach (var (eid, layers) in state.CompoundLayers) { - var elem = rvtInfo.Elements.FirstOrDefault(e => e.Id == (int)eid); - if (elem == null) continue; + if (!elemByIdLookup.TryGetValue((int)eid, out var elem)) continue; elem.Layers = layers.Select(l => new Model.MaterialLayer { ThicknessMm = Math.Round(l.ThicknessFt * 304.8, 2), @@ -5969,8 +6165,7 @@ 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); + ReadOnlySpan typeParamIds = [-1002050, -1002000, -1002052]; foreach (var e in rvtInfo.Elements) { // Trust current TypeId only if it resolves to an element of the SAME category. @@ -5980,9 +6175,9 @@ public static void PostProcess(RevitFileInfo rvtInfo, ParsingState? state = null if (currentValid) continue; int? resolved = null; - foreach (int paramId in new[] { -1002050, -1002000, -1002052 }) + foreach (int paramId in typeParamIds) { - var p = e.Parameters.FirstOrDefault(pp => pp.Id == paramId); + var p = FindParameterById(e.Parameters, paramId); if (p?.Value is int v && v > 0 && elemByIdLookup.TryGetValue(v, out var paramTarget) && (paramTarget.CategoryId == e.CategoryId || !e.CategoryId.HasValue)) { resolved = v; break; } @@ -6009,12 +6204,12 @@ public static void PostProcess(RevitFileInfo rvtInfo, ParsingState? state = null // the resolved TypeId differs from the stored garbage (e.g. 528 Tf-class index) foreach (var e in rvtInfo.Elements) { - if (e.TypeId <= 0 || !allElemIds.Contains(e.TypeId)) continue; - foreach (int paramId in new[] { -1002050, -1002000, -1002052 }) + if (e.TypeId <= 0 || !elemByIdLookup.ContainsKey(e.TypeId)) continue; + foreach (int paramId in typeParamIds) { - var p = e.Parameters.FirstOrDefault(pp => pp.Id == paramId); + var p = FindParameterById(e.Parameters, paramId); if (p == null) continue; - if (p.Value is int v && v > 0 && allElemIds.Contains(v)) continue; // already valid + if (p.Value is int v && v > 0 && elemByIdLookup.ContainsKey(v)) continue; // already valid p.Value = e.TypeId; } } @@ -6046,7 +6241,6 @@ public static void PostProcess(RevitFileInfo rvtInfo, ParsingState? state = null } // 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" }; @@ -6057,7 +6251,7 @@ public static void PostProcess(RevitFileInfo rvtInfo, ParsingState? state = null if (e.References == null) continue; foreach (var refId in e.References) { - if (elemById.TryGetValue(refId, out var refElem) && refElem.Category != null + if (elemByIdLookup.TryGetValue(refId, out var refElem) && refElem.Category != null && hostCategories.Contains(refElem.Category)) { e.HostId = refId; @@ -6180,7 +6374,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)) + if (typeParam?.Value is int typeId && typeId > 0 && elemByIdLookup.TryGetValue(typeId, out var typeElem)) { var typeFam = typeElem.Parameters.FirstOrDefault(p => p.Id == -1002051); if (typeFam?.Value is int typeFamId && typeFamId > 0 && idToName.TryGetValue(typeFamId, out var typeFamName)) @@ -6311,7 +6505,7 @@ void ReportDistinctMissing(string label, Dictionary counts) { foreach (var p in e.Parameters) { - if (p.Id > 0 && string.IsNullOrEmpty(p.Definition?.Name) + if (p.Id > 0 && string.IsNullOrEmpty(p.DefinitionName) && paramDefNames.TryGetValue(p.Id, out var paramName)) { p.Definition ??= new Definition(); @@ -6366,8 +6560,7 @@ 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); - if (levelElem == null) continue; + if (!elemByIdLookup.TryGetValue(levelId, out var levelElem)) continue; if (levelElem.Parameters.Any(p => p.Id == BIP_LEVEL_ELEV)) continue; // already set BipNames.Lookup.TryGetValue(BIP_LEVEL_ELEV, out string? bipName); @@ -6434,12 +6627,12 @@ void ReportDistinctMissing(string label, Dictionary counts) } } - ResolveTypeParams(rvtInfo); + ResolveTypeParams(rvtInfo, elemByIdLookup); ApplyDetailLines(rvtInfo, state); ApplyBlockSignatureCategories(rvtInfo, state); // 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); + ApplyNativeParams(rvtInfo, state, elemByIdLookup); TraceElement(rvtInfo, "after-native"); if (state != null) { @@ -6454,16 +6647,16 @@ void ReportDistinctMissing(string label, Dictionary counts) TraceElement(rvtInfo, "after-prune"); if (state != null) { - ApplySerializedSystemTypeIdentity(rvtInfo.Elements, state); - ApplyValidatedOriginalFamilySymbols(rvtInfo.Elements, state); - ApplyOwnFamilyCutoutInputs(rvtInfo.Elements, state); + ApplySerializedSystemTypeIdentity(rvtInfo.Elements, state, elemByIdLookup); + ApplyValidatedOriginalFamilySymbols(rvtInfo.Elements, state, elemByIdLookup); + ApplyOwnFamilyCutoutInputs(rvtInfo.Elements, state, elemByIdLookup); ApplySolidTrimmedAxis(rvtInfo.Elements); - ApplyValidatedCeilingCanonicalTypes(rvtInfo.Elements, state); + ApplyValidatedCeilingCanonicalTypes(rvtInfo.Elements, state, elemByIdLookup); ApplySerializedStairData( rvtInfo.Elements, state.StairElementRootSource, state.StairTypeRootSource); - StairComponentSource.Apply(rvtInfo.Elements, state); + StairComponentSource.Apply(rvtInfo.Elements, state, elemByIdLookup); } if (state != null) { @@ -6474,8 +6667,8 @@ void ReportDistinctMissing(string label, Dictionary counts) } AddCategoryAndFamilyParams(rvtInfo); AddCurveLengths(rvtInfo); - ApplyMaterialAppearance(rvtInfo, state); - ApplyHvacSpaceTypeParams(rvtInfo, state); + ApplyMaterialAppearance(rvtInfo, state, elemByIdLookup); + ApplyHvacSpaceTypeParams(state, elemByIdLookup); if (state != null) ApplySerializedRoomNames(rvtInfo.Elements, state.RoomNameSource); if (state != null) ApplySerializedSpatialPhases(rvtInfo, state); if (state != null) ApplySerializedRoomPlanAreas(rvtInfo, state); @@ -6483,8 +6676,8 @@ 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, elemByIdLookup); + ApplySheetParams(rvtInfo, state, elemByIdLookup); ApplyTextNotes(rvtInfo, state); ApplyViewports(rvtInfo, state); ApplyViewPlanes(rvtInfo, state); @@ -6492,52 +6685,16 @@ void ReportDistinctMissing(string label, Dictionary counts) ApplyViewportScales(rvtInfo, state); AddViewAndDatumDefaults(rvtInfo); AddCurtainQuantities(rvtInfo); - EnrichTypeLevelBips(rvtInfo, state); - PropagateChainPlaceholders(rvtInfo, state); - PropagateTypeElementIdParams(rvtInfo, state); - PropagateFamilySymbolBlockDoubles(rvtInfo, state); - PropagateFamilySymbolBlockStrings(rvtInfo, state); - PropagateFamilySymbolBlockInts(rvtInfo, state); - PropagateFamilyElementIdParams(rvtInfo, state); - CoerceParamStorageByForge(rvtInfo, state); - ApplyDerivedDesignOptionName(rvtInfo); - 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); - ApplyStoredPhases(rvtInfo, state?.ElemClassIdx, - state?.ProjectPhaseOrderSource is { BlockCount: 1, PhaseIds: { } phaseOrder } ? phaseOrder : null); - 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); - ApplyWorksets(rvtInfo, state); - TraceElement(rvtInfo, "before-fixphase"); - FixUnresolvedPhaseCreated(rvtInfo); - TraceElement(rvtInfo, "after-fixphase"); - FixWallStructuralUsage(rvtInfo); - FixWallBaseConstraint(rvtInfo); - FixNodeConnectionStatus(rvtInfo, state); - AddCategoryConstantParams(rvtInfo, state); - // Wall centrelines the pattern scan missed: synthesize from face geometry (needs the width - // param, which type propagation has filled by now). - if (state != null) - foreach (var e in rvtInfo.Elements) - if (e.CategoryId == -2000011 && e.Location == null) - BuildLocationFromTailLine(e, (uint)e.Id, state); - ComputeSketchQuantities(rvtInfo, state); - if (state != null) ApplyCoarseDoorWindowSurfaces(rvtInfo, state); + EnrichTypeLevelBips(rvtInfo, state, elemByIdLookup); + // Detached quantity geometry reads final categories and GRep, independently of parameter propagation. + var quantities = state != null && SymbolDiagPath == null && !GRepParserV2.IsDecodeTracingEnabled() + && Environment.GetEnvironmentVariable("RVTIO_MESH_LOG") != "1" + && Environment.GetEnvironmentVariable("RVTIO_TRACE_ID") == null + && !TfBlockDeserializer.CaptureAllFields + ? Task.Run(() => ApplyCoarseDoorWindowSurfaces(rvtInfo, state)) : null; + try { ApplyParameterAndSketchPasses(); } + finally { quantities?.GetAwaiter().GetResult(); } + if (quantities == null && state != null) ApplyCoarseDoorWindowSurfaces(rvtInfo, state); ApplyFramingCopingDistance(rvtInfo); ApplyColumnAttachments(rvtInfo); ApplyMovesWithGrids(rvtInfo); @@ -6552,7 +6709,7 @@ void ReportDistinctMissing(string label, Dictionary counts) ApplyValidatedCeilingTypeReferenceNames( rvtInfo.Elements, state.CeilingTypeNameSource, - state.NativeParams, state.ElemClassIdx); + state.NativeParams, state.ElemClassIdx, elemByIdLookup); ApplyValidatedWindowTypeReferenceNames( rvtInfo.Elements, elemByIdLookup, state.NativeParams, state.ElementNameTable); @@ -6564,7 +6721,7 @@ void ReportDistinctMissing(string label, Dictionary counts) ApplyValidatedRoofOrRailingTypeReferenceNames(rvtInfo.Elements, state); ApplyValidatedRailingLengths(rvtInfo.Elements, state); ApplyValidatedFamilyNamesFromCanonicalTypeId(rvtInfo.Elements, state); - ApplyValidatedDoorTypeNames(rvtInfo.Elements, state); + ApplyValidatedDoorTypeNames(rvtInfo.Elements, state, elemByIdLookup); ApplyValidatedIfcTypeObjectNames(rvtInfo.Elements, state); ApplyBasicWallTypeFunctions(rvtInfo.Elements, state.BasicWallTypeFunctions); ApplyStackedWallTypes(rvtInfo.Elements, state); @@ -6574,66 +6731,107 @@ void ReportDistinctMissing(string label, Dictionary counts) ApplyCurtainPanelOrders(rvtInfo.Elements, state); RepairBasicWallTypeFunctionBodyFallbacks(rvtInfo.Elements, state); } - foreach (var e in rvtInfo.Elements) - { - Parameter? lv = null; bool hasSched = false; - foreach (var p in e.Parameters) - { - if (p.Id == -1001952) lv = p; - else if (p.Id == -1002062) { hasSched = true; break; } - } - if (!hasSched && !e.ScheduleLevelFromStoredFields && lv?.Value is int lvv && lvv > 0) - e.Parameters.Add(BipHelpers.MakeBipParam(-1002062, "SCHEDULE_LEVEL_PARAM", StorageType.ElementId, lvv)); - } - // 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) + Parallel.For(0, rvtInfo.Elements.Count, index => { - Parameter? gen = null, pan = null; + var e = rvtInfo.Elements[index]; + Parameter? level = null, height = null, panelHeight = null, width = null, panelWidth = null; + bool hasScheduleLevel = false; foreach (var p in e.Parameters) { - if (p.Id == -1001300) gen = p; - else if (p.Id == -1010300) pan = p; + switch (p.Id) + { + case -1001952: level = p; break; + case -1002062: hasScheduleLevel = true; break; + case -1001300: height = p; break; + case -1010300: panelHeight = p; break; + case -1001301: width = p; break; + case -1010301: panelWidth = p; break; + } } - if (gen?.Value is double gv && pan == null) + if (!hasScheduleLevel && !e.ScheduleLevelFromStoredFields && level?.Value is int levelId && levelId > 0) + e.Parameters.Add(BipHelpers.MakeBipParam(-1002062, "SCHEDULE_LEVEL_PARAM", StorageType.ElementId, levelId)); + + // Each curtain panel dimension has two parameter IDs. Fill the missing one. + if (height?.Value is double gv && panelHeight == null) { e.Parameters.Add(BipHelpers.MakeBipParam(-1010300, "CURTAIN_WALL_PANELS_HEIGHT", StorageType.Double, gv)); if (e.BoundingBoxDimensionParamIds != null && e.BoundingBoxDimensionParamIds.Contains(-1001300)) e.BoundingBoxDimensionParamIds.Add(-1010300); } - else if (pan?.Value is double pv && gen == null) + else if (panelHeight?.Value is double pv && height == null) { e.Parameters.Add(BipHelpers.MakeBipParam(-1001300, "GENERIC_HEIGHT", StorageType.Double, pv)); if (e.BoundingBoxDimensionParamIds != null && e.BoundingBoxDimensionParamIds.Contains(-1010300)) e.BoundingBoxDimensionParamIds.Add(-1001300); } - // 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) - { - if (p.Id == -1001301) genWidth = p; - else if (p.Id == -1010301) panWidth = p; - } - if (panWidth?.Value is double pw && genWidth == null) + if (panelWidth?.Value is double pw && width == null) { e.Parameters.Add(BipHelpers.MakeBipParam(-1001301, "GENERIC_WIDTH", StorageType.Double, pw)); if (e.BoundingBoxDimensionParamIds != null && e.BoundingBoxDimensionParamIds.Contains(-1010301)) e.BoundingBoxDimensionParamIds.Add(-1001301); } - else if (genWidth?.Value is double gw && panWidth == null) + else if (width?.Value is double gw && panelWidth == null) { e.Parameters.Add(BipHelpers.MakeBipParam(-1010301, "CURTAIN_WALL_PANELS_WIDTH", StorageType.Double, gw)); if (e.BoundingBoxDimensionParamIds != null && e.BoundingBoxDimensionParamIds.Contains(-1001301)) e.BoundingBoxDimensionParamIds.Add(-1010301); } - } - CreateElemTablePlaceholders(rvtInfo, state); + }); + CreateElemTablePlaceholders(rvtInfo, state, elemByIdLookup); ApplyHeaderBoundingBoxes(rvtInfo, state); Parameter.ResolveZeroElementIds(rvtInfo, state); // NOTE: PropagateFamilyTypeValues remains disabled. The chain rule that works perfectly for // instance 0x0702 values (value of entry K belongs to chain[K] = next entry's binKey) does // NOT generalize to type-level 0x0725 values. + return elemByIdLookup; + + void ApplyParameterAndSketchPasses() + { + var familyDefinitions = new Dictionary(); + PropagateChainPlaceholders(rvtInfo, state, familyDefinitions); + PropagateTypeElementIdParams(rvtInfo, state, elemByIdLookup); + PropagateFamilySymbolBlockDoubles(rvtInfo, state, familyDefinitions); + PropagateFamilySymbolBlockStrings(rvtInfo, state); + PropagateFamilySymbolBlockInts(rvtInfo, state); + PropagateFamilyElementIdParams(rvtInfo, state); + CoerceParamStorageByForge(rvtInfo, state); + ApplyDerivedDesignOptionName(rvtInfo); + ApplyCurveDriverLevelParams(rvtInfo, elemByIdLookup); + ApplyHostIdParam(rvtInfo, state?.ElemClassIdx, elemByIdLookup); + ApplyInstanceOriginOffsets(rvtInfo); + ApplyInstanceElevationFromLevel(rvtInfo, elemByIdLookup); + ApplyStructuralColumnParams(rvtInfo, elemByIdLookup); + ApplyRoomLevelParams(rvtInfo, elemByIdLookup); + ApplyFramingSymbolLength(rvtInfo, elemByIdLookup); + if (state != null) ApplyMullionSymbolLength(rvtInfo.Elements, state.NativeParams); + ApplyRoomBuildingTypeLoads(rvtInfo); + ApplyHeadHeight(rvtInfo, elemByIdLookup); + ApplyStructuralConnectionParams(rvtInfo, elemByIdLookup); + ApplyCrossSectionRotation(rvtInfo, elemByIdLookup); + ApplyDetailCurveFlag(rvtInfo, state?.ElemClassIdx); + ApplyStoredPhases(rvtInfo, state?.ElemClassIdx, + state?.ProjectPhaseOrderSource is { BlockCount: 1, PhaseIds: { } phaseOrder } ? phaseOrder : null); + TraceElement(rvtInfo, "after-phases"); + BuildSketchTopology(rvtInfo, state, elemByIdLookup); + // 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); + ApplyWorksets(rvtInfo, state); + TraceElement(rvtInfo, "before-fixphase"); + FixUnresolvedPhaseCreated(rvtInfo); + TraceElement(rvtInfo, "after-fixphase"); + FixWallStructuralUsage(rvtInfo); + FixWallBaseConstraint(rvtInfo); + FixNodeConnectionStatus(rvtInfo, state); + AddCategoryConstantParams(rvtInfo, state); + // Wall centrelines the pattern scan missed need the width filled by type propagation. + if (state != null) + foreach (var e in rvtInfo.Elements) + if (e.CategoryId == -2000011 && e.Location == null) + BuildLocationFromTailLine(e, (uint)e.Id, state); + ComputeSketchQuantities(rvtInfo, state, elemByIdLookup); + } } /// The box the parser rules measure: the tight box of the decoded geometry, else the @@ -6659,75 +6857,23 @@ internal static void ApplyHeaderBoundingBoxes(RevitFileInfo rvtInfo, ParsingStat } } - /// 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. - private static void AppendGeometry(GeometryData target, GeometryData source, long? instanceOrder = null) + // The source is freshly placed geometry. Its faces already own their coordinates. + private static void AppendPlacedGeometry(GeometryData target, GeometryData source, long? instanceOrder = null) { int faceOffset = target.Faces.Count; - int edgeOffset = target.Edges?.Count ?? 0; target.UntriangulatedFaces += source.UntriangulatedFaces; // Geometry node ids are unique within one GeometryData: the appended nodes follow the // existing ones. (a negative id marks a node that Revit does not take, see // GRepParserV2). int nodeOffset = target.Faces.Count == 0 ? 0 : target.Faces.Max(face => Math.Abs(face.GeometryNode)); - if (source.Edges is { Count: > 0 }) - { - target.Edges ??= new List(); - foreach (var edge in source.Edges) - target.Edges.Add(new GeoEdge - { - Start = (double[])edge.Start.Clone(), - End = (double[])edge.End.Clone(), - }); - } - - if (source.Vertices is { Count: > 0 }) - { - target.Vertices ??= new List(); - foreach (var vertex in source.Vertices) - target.Vertices.Add((double[])vertex.Clone()); - } - foreach (var face in source.Faces) { - target.Faces.Add(new GeoFace - { - Origin = (double[])face.Origin.Clone(), - XVector = (double[])face.XVector.Clone(), - YVector = (double[])face.YVector.Clone(), - Normal = (double[])face.Normal.Clone(), - Envelope = face.Envelope is null ? null : (double[])face.Envelope.Clone(), - Area = face.Area, - InnerLoops = face.InnerLoops?.Select(loop => (double[])loop.Clone()).ToList(), - OuterVertices = face.OuterVertices?.Select(v => (double[])v.Clone()).ToList(), - InnerVertices = face.InnerVertices? - .Select(loop => loop.Select(v => (double[])v.Clone()).ToList()).ToList(), - AnalyticCylinderOrigin = face.AnalyticCylinderOrigin is null - ? null : (double[])face.AnalyticCylinderOrigin.Clone(), - AnalyticCylinderAxis = face.AnalyticCylinderAxis is null - ? null : (double[])face.AnalyticCylinderAxis.Clone(), - AnalyticCylinderReferenceDirection = - face.AnalyticCylinderReferenceDirection is null - ? null : (double[])face.AnalyticCylinderReferenceDirection.Clone(), - AnalyticCylinderRadius = face.AnalyticCylinderRadius, - MeshEdgeBounds = face.MeshEdgeBounds, - MeshPlaneEnvelopeCorners = face.MeshPlaneEnvelopeCorners, - MeshArcs = face.MeshArcs, - QuadratureArea = face.QuadratureArea, - CurvedSurface = face.CurvedSurface, - PlaneSurface = face.PlaneSurface, - PlaneXAxis = face.PlaneXAxis, - PlaneYAxis = face.PlaneYAxis, - SourceFace = face.SourceFace, - MeshMarker = face.MeshMarker, - NestedRenderStyleId = face.NestedRenderStyleId ?? face.RenderStyleId, - GeometryNode = face.GeometryNode == 0 ? 0 : face.GeometryNode + Math.Sign(face.GeometryNode) * nodeOffset, - NodeOrder = instanceOrder is { } and not 0 && face.NodeOrder != 0 - ? GRepParserV2.NestOrderKey(instanceOrder.Value, face.NodeOrder) : face.NodeOrder, - GeometryStyle = face.GeometryStyle, - EdgeIndices = face.EdgeIndices?.Select(index => index + edgeOffset).ToList(), - }); + face.GeometryNode += Math.Sign(face.GeometryNode) * nodeOffset; + if (instanceOrder is { } and not 0 && face.NodeOrder != 0) + face.NodeOrder = GRepParserV2.NestOrderKey(instanceOrder.Value, face.NodeOrder); } + target.Faces.AddRange(source.Faces); // the nodes with an id follow the appended faces (node 0, the faces without a node id, // would merge with the nodes of the target) @@ -6746,30 +6892,11 @@ face.AnalyticCylinderReferenceDirection is null if (source.BrepSolids is { Count: > 0 }) { target.BrepSolids ??= new List(); - foreach (var solid in source.BrepSolids) - target.BrepSolids.Add(new GeoBrepSolid - { - FaceIndices = solid.FaceIndices.Select(index => index + faceOffset).ToList(), - IsClosed = solid.IsClosed, - }); - } - - if (source.Solids is { Count: > 0 }) - { - target.Solids ??= new List(); - target.Solids.AddRange(source.Solids); - } - - if (source.Instances is { Count: > 0 }) - { - target.Instances ??= new List(); - foreach (var instance in source.Instances) - target.Instances.Add(new GeoInstance - { - SymbolId = instance.SymbolId, - Transform = (double[])instance.Transform.Clone(), - NodeOrder = instance.NodeOrder, - }); + if (faceOffset != 0) + foreach (var solid in source.BrepSolids) + for (int index = 0; index < solid.FaceIndices.Count; index++) + solid.FaceIndices[index] += faceOffset; + target.BrepSolids.AddRange(source.BrepSolids); } } @@ -6780,19 +6907,26 @@ face.AnalyticCylinderReferenceDirection is null /// private static void FixUnresolvedPhaseCreated(RevitFileInfo info) { - var phaseVotes = new Dictionary(); + int domPhase = DominantCreatedPhase(info.Elements); + if (domPhase <= 0) return; + object? phaseValue = Parameter.BoxParsedValue(domPhase); + foreach (var e in info.Elements) + foreach (var p in e.Parameters) + if (p.Id == -1012100 && p.Value is int pv && pv < 0) + { p.Value = phaseValue; p.StorageType = StorageType.ElementId; break; } + } + + private static int DominantCreatedPhase(List elements) + { + var phaseVotes = new Dictionary(); + foreach (var e in 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; } - if (domPhase <= 0) return; - - foreach (var e in info.Elements) - foreach (var p in e.Parameters) - if (p.Id == -1012100 && p.Value is int pv && pv < 0) - { p.Value = domPhase; p.StorageType = StorageType.ElementId; break; } + return domPhase; } /// @@ -6882,11 +7016,9 @@ private static void PropagateInstanceCategoryFromType(RevitFileInfo info) /// Analytic geometry engine for Revit-computed quantities on sketch-based hosts (floors /// -2000032 / ceilings -2000038 / roofs -2000035). /// - private static void ComputeSketchQuantities(RevitFileInfo info, ParsingState? state) + private static void ComputeSketchQuantities(RevitFileInfo info, ParsingState? state, + IReadOnlyDictionary byId) { - var byId = new Dictionary(info.Elements.Count); - foreach (var e in info.Elements) byId[e.Id] = e; - foreach (var e in info.Elements) { if (e.CategoryId is not (-2000032 or -2000038 or -2000035)) continue; @@ -7136,10 +7268,21 @@ private static void FixNodeConnectionStatus(RevitFileInfo info, ParsingState? st if (state == null || state.ElemClassIdx.Count == 0) return; var incoming = new Dictionary(); foreach (var e in info.Elements) + if (e.CategoryId == -2009645 && e.Id > 0 + && state.ElemClassIdx.GetValueOrDefault((uint)e.Id) == 0x0884 + && FindParameterById(e.Parameters, -1001597) == null) + incoming.TryAdd(e.Id, 0); + if (incoming.Count != 0) { - if (e.References == null) continue; - foreach (var r in e.References) - { incoming.TryGetValue(r, out int c); incoming[r] = c + 1; } + foreach (var e in info.Elements) + { + if (e.References == null) continue; + foreach (var r in e.References) + { + ref int count = ref System.Runtime.InteropServices.CollectionsMarshal.GetValueRefOrNullRef(incoming, r); + if (!System.Runtime.CompilerServices.Unsafe.IsNullRef(ref count)) count++; + } + } } foreach (var e in info.Elements) { @@ -7167,32 +7310,22 @@ private static void FixNodeConnectionStatus(RevitFileInfo info, ParsingState? st /// Emit placeholder Elements for ElemTable-known ids that have no decoded block, so they still /// exist in the output. /// - private static void CreateElemTablePlaceholders(RevitFileInfo info, ParsingState? state) + private static void CreateElemTablePlaceholders(RevitFileInfo info, ParsingState? state, + Dictionary elemById) { if (state == null) return; - var existing = new HashSet(info.Elements.Count); - 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; } - - var src = new HashSet(state.ElemTable.Keys); - foreach (var k in state.ElemWorksets.Keys) src.Add(k); - foreach (var eid in src) + int? domPhase = null; + foreach (var eid in state.ElemTable.Keys.Concat(state.ElemWorksets.Keys)) { - if (eid == 0 || eid >= 0x0F000000 || existing.Contains((int)eid)) continue; + if (eid == 0 || eid >= 0x0F000000 || elemById.ContainsKey((int)eid)) continue; + domPhase ??= DominantCreatedPhase(info.Elements); // Runs last, after all category/workset passes, so nothing else touches these. var el = new Element { Id = (int)eid, TypeId = 0 }; el.Parameters.Add(BipHelpers.MakeBipParam(-1013201, "DESIGN_OPTION_ID", StorageType.ElementId, -1, hasNoRevitValue: true)); 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)); + el.Parameters.Add(BipHelpers.MakeBipParam(-1012100, "PHASE_CREATED", StorageType.ElementId, domPhase.Value)); + elemById.Add(el.Id, el); info.Elements.Add(el); } } @@ -7224,7 +7357,8 @@ private static void FixWallBaseConstraint(RevitFileInfo info) internal static void BuildSketchTopologyForTests(RevitFileInfo info, ParsingState state) => BuildSketchTopology(info, state); - private static void BuildSketchTopology(RevitFileInfo info, ParsingState? state) + private static void BuildSketchTopology(RevitFileInfo info, ParsingState? state, + IReadOnlyDictionary? byId = null) { if (state == null || state.SketchCurves.Count == 0) return; @@ -7233,8 +7367,7 @@ private static void BuildSketchTopology(RevitFileInfo info, ParsingState? state) if (!state.DetailCurveStyles.ContainsKey(k)) // detail/model lines aren't sketch profiles sketchLineIds.Add((int)k); - var byId = new Dictionary(); - foreach (var e in info.Elements) byId[e.Id] = e; + byId ??= IndexElements(info.Elements, keepLast: true); // owner candidate -> the sketch lines it references (a sketch owner lists all its lines; // dimensions/constraints reference only the 1-2 lines they measure, so require >=3). @@ -7361,7 +7494,7 @@ internal static Dictionary SketchLoopKeys(IEnumerable lineIds, IR } /// Order a set of sketch-line curves into closed loops by walking shared endpoints. - private static List> BuildSketchLoops(List lineIds, Dictionary byId) + private static List> BuildSketchLoops(List lineIds, IReadOnlyDictionary byId) { static (long, long, long) Key(double[] p) => ((long)Math.Round(p[0] * 1000), (long)Math.Round(p[1] * 1000), (long)Math.Round(p[2] * 1000)); @@ -7451,31 +7584,17 @@ private static void PropagateFamilyElementIdParams(RevitFileInfo rvtInfo, Parsin } if (symToVals.Count == 0) return; + var candidates = new List(); + var seen = new HashSet(); foreach (var e in rvtInfo.Elements) { - uint typeCandidate = e.TypeId > 0 ? (uint)e.TypeId : 0u; - var candidates = new List(); - if (e.References != null) - { - var seen = new HashSet { typeCandidate }; - foreach (var rid in e.References) - { - if (rid <= 0 || rid == e.Id) continue; - uint urid = (uint)rid; - if (!seen.Add(urid)) continue; - if (symToVals.ContainsKey(urid)) candidates.Add(urid); - } - } - if (typeCandidate != 0 && symToVals.ContainsKey(typeCandidate)) - candidates.Add(typeCandidate); - if (candidates.Count == 0) continue; + CollectFamilySymbolCandidates(e, symToVals, candidates, seen, typeFirst: false); foreach (var symId in candidates) { - if (!symToVals.TryGetValue(symId, out var vals)) continue; - foreach (var (projKey, elemValue) in vals) + foreach (var (projKey, elemValue) in symToVals[symId]) { - var p = e.Parameters.FirstOrDefault(pp => pp.Id == projKey); + var p = FindParameterById(e.Parameters, projKey); if (p == null) continue; // only fill existing params bool isPlaceholder = p.Value == null || (p.Value is int iv && (iv == 0 || iv == -1)) @@ -7488,6 +7607,30 @@ private static void PropagateFamilyElementIdParams(RevitFileInfo rvtInfo, Parsin } } + private static uint CollectFamilySymbolCandidates(Element element, Dictionary valuesBySymbol, + List candidates, HashSet seen, bool typeFirst) + { + candidates.Clear(); + seen.Clear(); + uint type = element.TypeId > 0 ? (uint)element.TypeId : 0; + bool hasType = type != 0 && valuesBySymbol.ContainsKey(type); + if (typeFirst && hasType) candidates.Add(type); + if (element.References != null) + foreach (int id in element.References) + if (id > 0 && id != element.Id && (uint)id != type + && valuesBySymbol.ContainsKey((uint)id) && seen.Add((uint)id)) + candidates.Add((uint)id); + if (!typeFirst && hasType) candidates.Add(type); + return type; + } + + private static Parameter? FindParameterById(List parameters, int id) + { + foreach (var parameter in parameters) + if (parameter.Id == id) return parameter; + return null; + } + /// /// Final pass: coerce a parameter's StorageType/Value based on its ForgeId spec when the /// current storage type clearly disagrees. @@ -7502,7 +7645,7 @@ private static void CoerceParamStorageByForge(RevitFileInfo rvtInfo, ParsingStat && state.ForgeParamDefs.TryGetValue((uint)p.Id, out var def)) { p.ForgeId = def.ForgeId; - if (string.IsNullOrEmpty(p.Definition?.Name) && !string.IsNullOrEmpty(def.DisplayName)) + if (string.IsNullOrEmpty(p.DefinitionName) && !string.IsNullOrEmpty(def.DisplayName)) { p.Definition ??= new Definition { Id = p.Id }; p.Definition.Name = def.DisplayName; @@ -7548,63 +7691,53 @@ private static void CoerceParamStorageByForge(RevitFileInfo rvtInfo, ParsingStat } } - private static void PropagateFamilySymbolBlockDoubles(RevitFileInfo rvtInfo, ParsingState? state) + private readonly record struct FamilyParameterDefinition(Parameter.DefinitionData Data, string? ForgeId); + + private static FamilyParameterDefinition FamilyDefinition(uint id, ParsingState state, + Dictionary definitions) + { + if (definitions.TryGetValue(id, out var definition)) return definition; + var (forgeId, displayName) = state.ForgeParamDefs.GetValueOrDefault(id); + Guid? guid = state.ParamDefGuids.TryGetValue(id, out var stored) ? stored : BipHelpers.ParseGuidFromForgeId(forgeId); + definition = new(new Parameter.DefinitionData((int)id, displayName, guid: guid), forgeId); + definitions.Add(id, definition); + return definition; + } + + private static void PropagateFamilySymbolBlockDoubles(RevitFileInfo rvtInfo, ParsingState? state, + Dictionary definitions) { if (state == null || state.FamilySymbolBlockDoubles.Count == 0) return; + var candidates = new List(); + var seen = new HashSet(); + var valuesBySymbol = new Dictionary(); foreach (var e in rvtInfo.Elements) { - // 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) - { - var seen = new HashSet { typeCandidate }; - foreach (var rid in e.References) - { - if (rid <= 0 || rid == e.Id) continue; - uint urid = (uint)rid; - if (!seen.Add(urid)) continue; - if (state.FamilySymbolBlockDoubles.ContainsKey(urid)) - shadowCandidates.Add(urid); - } - } - // Apply in order: SHADOWS FIRST (instance-specific values win), THEN type defaults fill - // any remaining gaps. This way the shadow's full value (e.g. 0.984) wins over the - // type's half-default (0.4921) for the same projKey. - var allCandidates = new List(); - allCandidates.AddRange(shadowCandidates); - if (typeCandidate != 0 && state.FamilySymbolBlockDoubles.ContainsKey(typeCandidate)) - allCandidates.Add(typeCandidate); - if (allCandidates.Count == 0) continue; - - foreach (var symId in allCandidates) + // A shadow's instance value fills the slot before the type default. + CollectFamilySymbolCandidates(e, state.FamilySymbolBlockDoubles, candidates, seen, typeFirst: false); + foreach (var symId in candidates) { - if (!state.FamilySymbolBlockDoubles.TryGetValue(symId, out var typeDoubles)) continue; - foreach (var (projKey, value) in typeDoubles) + if (!valuesBySymbol.TryGetValue(symId, out var values)) { // Skip 0.0 entries - they carry no info and would crush genuine Integer/String // values from other extractors. - if (value == 0.0) continue; + values = state.FamilySymbolBlockDoubles[symId].Where(pair => pair.Value != 0.0) + .Select(pair => (pair.Key, (object)pair.Value)).ToArray(); + valuesBySymbol.Add(symId, values); + } + foreach (var (projKey, value) in values) + { int pid = (int)projKey; - var p = e.Parameters.FirstOrDefault(pp => pp.Id == pid); + var p = FindParameterById(e.Parameters, pid); if (p == null) { - string? forgeId = null, dn = null; - Guid? guid = null; - if (state.ForgeParamDefs.TryGetValue(projKey, out var def)) - { forgeId = def.ForgeId; dn = def.DisplayName; } - if (state.ParamDefGuids.TryGetValue(projKey, out var binGuid)) guid = binGuid; - else guid = BipHelpers.ParseGuidFromForgeId(forgeId); - e.Parameters.Add(new Parameter + var definition = FamilyDefinition(projKey, state, definitions); + e.Parameters.Add(new Parameter(definition.Data) { Id = pid, StorageType = StorageType.Double, Value = value, - IsReadOnly = false, - ForgeId = forgeId, - Guid = guid, - Definition = new Definition { Id = pid, Name = dn }, + ForgeId = definition.ForgeId, }); } else @@ -7633,34 +7766,18 @@ private static void PropagateFamilySymbolBlockDoubles(RevitFileInfo rvtInfo, Par private static void PropagateFamilySymbolBlockInts(RevitFileInfo rvtInfo, ParsingState? state) { if (state == null || state.FamilySymbolBlockInts.Count == 0) return; + var candidates = new List(); + var seen = new HashSet(); foreach (var e in rvtInfo.Elements) { - 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) - { - var seen = new HashSet { typeCandidate }; - foreach (var rid in e.References) - { - if (rid <= 0 || rid == e.Id) continue; - uint urid = (uint)rid; - if (!seen.Add(urid)) continue; - if (state.FamilySymbolBlockInts.ContainsKey(urid)) - candidates.Add(urid); - } - } - if (candidates.Count == 0) continue; - + uint typeCandidate = CollectFamilySymbolCandidates(e, state.FamilySymbolBlockInts, candidates, seen, typeFirst: true); foreach (var symId in candidates) { bool isInstanceSpecific = symId != typeCandidate; - if (!state.FamilySymbolBlockInts.TryGetValue(symId, out var typeInts)) continue; - foreach (var (projKey, value) in typeInts) + foreach (var (projKey, value) in state.FamilySymbolBlockInts[symId]) { if (value == 0 && !isInstanceSpecific) continue; // type defaults of 0 are noise - var p = e.Parameters.FirstOrDefault(pp => pp.Id == projKey); + var p = FindParameterById(e.Parameters, projKey); if (p == null) continue; // don't ADD new params here; only fill in existing if (p.StorageType != StorageType.Integer && p.StorageType != StorageType.None) continue; bool isPlaceholder = p.Value == null @@ -7680,31 +7797,13 @@ private static void PropagateFamilySymbolBlockInts(RevitFileInfo rvtInfo, Parsin private static void PropagateFamilySymbolBlockStrings(RevitFileInfo rvtInfo, ParsingState? state) { if (state == null || state.FamilySymbolBlockStrings.Count == 0) return; + var candidates = new List(); + var seen = new HashSet(); foreach (var e in rvtInfo.Elements) { - 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) - { - var seen = new HashSet { typeCandidate }; - foreach (var rid in e.References) - { - if (rid <= 0 || rid == e.Id) continue; - uint urid = (uint)rid; - if (!seen.Add(urid)) continue; - if (state.FamilySymbolBlockStrings.ContainsKey(urid)) - candidates.Add(urid); - } - } - if (candidates.Count == 0) continue; + uint typeCandidate = CollectFamilySymbolCandidates(e, state.FamilySymbolBlockStrings, candidates, seen, typeFirst: true); foreach (var symId in candidates) - { - bool isInstanceSpecific = symId != typeCandidate; - if (!state.FamilySymbolBlockStrings.TryGetValue(symId, out var typeStrings)) continue; - ApplyTypeStrings(e, typeStrings, state, isInstanceSpecific); - } + ApplyTypeStrings(e, state.FamilySymbolBlockStrings[symId], state, symId != typeCandidate); } } @@ -7713,7 +7812,7 @@ private static void ApplyTypeStrings(Element e, Dictionary typeStri { foreach (var (projKey, value) in typeStrings) { - var p = e.Parameters.FirstOrDefault(pp => pp.Id == projKey); + var p = FindParameterById(e.Parameters, projKey); if (p == null) { string? forgeId = null, dn = null; @@ -7761,99 +7860,92 @@ private static void ApplyTypeStrings(Element e, Dictionary typeStri /// to ANOTHER real project element (not a Tf-class index) are param defs where the parameter /// value IS that TypeId. /// - private static void PropagateTypeElementIdParams(RevitFileInfo rvtInfo, ParsingState? state) + internal static void PropagateTypeElementIdParams(RevitFileInfo rvtInfo, ParsingState? state, + Dictionary elemById) { if (state == null) return; - var elemById = rvtInfo.Elements.ToDictionary(e => e.Id); + var existing = new HashSet(); + var definitionsByType = new Dictionary?>(); + var definitionsById = new Dictionary(); foreach (var e in rvtInfo.Elements) { - 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 (e.TypeId <= 0 || !elemById.TryGetValue(e.TypeId, out var typeElem) + || typeElem.References is not { Count: > 0 } references) continue; + if (!definitionsByType.TryGetValue(e.TypeId, out var definitions)) { - if (defId <= 0 || existing.Contains(defId) || !state.IsParameterElement((uint)defId)) continue; - if (!elemById.TryGetValue(defId, out var defElem)) continue; - int dt = defElem.TypeId; - if (dt == defId) continue; // self-ref - - // Pattern 1: defElem.TypeId is another real project element -> that's the param - // value. (Used for enum-list family params.) - if (dt > 1000 && elemById.TryGetValue(dt, out _)) + foreach (int id in references) { - bool looksLikeParamDef = - defElem.Category == "OST_Entourage" - || defElem.Category == "OST_GenericAnnotation" - || (defElem.Category == null && !string.IsNullOrEmpty(defElem.Name)); - if (looksLikeParamDef) + if (id <= 0) continue; + if (!definitionsById.TryGetValue(id, out var definition)) { - e.Parameters.Add(new Parameter - { - Id = defId, - StorageType = StorageType.ElementId, - Value = dt, - IsReadOnly = false, - Definition = new Definition - { - Id = defId, - Name = !string.IsNullOrEmpty(defElem.Name) ? defElem.Name : null, - }, - }); - existing.Add(defId); - continue; + if (!state.IsParameterElement((uint)id) || !elemById.TryGetValue(id, out var definitionElement)) continue; + definition = Describe(definitionElement); + definitionsById.Add(id, definition); } + if (definition is { } inherited) (definitions ??= new()).Add(inherited); } + definitionsByType.Add(e.TypeId, definitions); + } + if (definitions == null) continue; - // Add as placeholder with type inferred from the param-def name. Prefer the - // authoritative DisplayName from ForgeParamDefs over defElem.Name (the latter often - // holds a value/garbage). - if (dt <= 0 && defElem.Category == null) + existing.Clear(); + foreach (var parameter in e.Parameters) + if (parameter.Id > 0) existing.Add(parameter.Id); + foreach (var definition in definitions) + { + if (!existing.Add(definition.Id)) continue; + e.Parameters.Add(new Parameter(definition.Data) { - string? forgeId = null, dn = null; - Guid? guid = null; - if (state.ForgeParamDefs.TryGetValue((uint)defId, out var def)) - { forgeId = def.ForgeId; dn = def.DisplayName; } - if (state.ParamDefGuids.TryGetValue((uint)defId, out var binGuid)) guid = binGuid; - else guid = BipHelpers.ParseGuidFromForgeId(forgeId); - - string? typeHintName = dn ?? defElem.Name; - if (string.IsNullOrEmpty(typeHintName) || !IsParamDefName(typeHintName)) continue; - - // Use ForgeId spec for typing when available; otherwise heuristic from name. - StorageType st; object val; - if (forgeId != null && state.ForgeParamSpecs.TryGetValue(forgeId, out var spec)) - { - if (spec.Contains("bool") || spec.Contains("int")) - { st = StorageType.Integer; val = 0; } - else if (spec.Contains("number") || spec.Contains("length") - || spec.Contains("area") || spec.Contains("volume") - || spec.Contains("currency") || spec.StartsWith("autodesk.spec.aec")) - { st = StorageType.Double; val = 0.0; } - else if (spec.Contains("material") || spec.Contains("reference")) - { st = StorageType.ElementId; val = -1; } - else { st = StorageType.String; val = ""; } - } - else - { - (st, val) = InferTypeFromName(typeHintName); - } - e.Parameters.Add(new Parameter - { - Id = defId, - StorageType = st, - Value = val, - HasNoRevitValue = true, - IsReadOnly = false, - ForgeId = forgeId, - Guid = guid, - Definition = new Definition { Id = defId, Name = dn ?? typeHintName }, - }); - existing.Add(defId); - } + Id = definition.Id, + StorageType = definition.Storage, + Value = definition.Value, + HasNoRevitValue = definition.Placeholder, + ForgeId = definition.ForgeId, + }); + } + } + + InheritedTypeParameter? Describe(Element definition) + { + int id = definition.Id, valueId = definition.TypeId; + if (valueId == id) return null; + if (valueId > 1000 && elemById.ContainsKey(valueId) + && (definition.Category is "OST_Entourage" or "OST_GenericAnnotation" + || (definition.Category == null && !string.IsNullOrEmpty(definition.Name)))) + return new(new Parameter.DefinitionData(id, string.IsNullOrEmpty(definition.Name) ? null : definition.Name), + StorageType.ElementId, valueId, false); + if (valueId > 0 || definition.Category != null) return null; + + // The record name can hold a value; prefer the parameter definition's display name. + var (forgeId, displayName) = state.ForgeParamDefs.GetValueOrDefault((uint)id); + string? name = displayName ?? definition.Name; + if (string.IsNullOrEmpty(name) || !IsParamDefName(name)) return null; + Guid? guid = state.ParamDefGuids.TryGetValue((uint)id, out var binaryGuid) + ? binaryGuid : BipHelpers.ParseGuidFromForgeId(forgeId); + StorageType storage; + object value; + if (forgeId != null && state.ForgeParamSpecs.TryGetValue(forgeId, out var spec)) + { + if (spec.Contains("bool") || spec.Contains("int")) + { storage = StorageType.Integer; value = 0; } + else if (spec.Contains("number") || spec.Contains("length") || spec.Contains("area") + || spec.Contains("volume") || spec.Contains("currency") || spec.StartsWith("autodesk.spec.aec")) + { storage = StorageType.Double; value = 0.0; } + else if (spec.Contains("material") || spec.Contains("reference")) + { storage = StorageType.ElementId; value = -1; } + else { storage = StorageType.String; value = ""; } } + else (storage, value) = InferTypeFromName(name); + return new(new Parameter.DefinitionData(id, name, guid: guid), storage, value, true, forgeId); } } + private readonly record struct InheritedTypeParameter( + Parameter.DefinitionData Data, StorageType Storage, object Value, bool Placeholder, string? ForgeId = null) + { + internal int Id => Data.Id; + } + /// /// Heuristic: does the string look like a Revit family parameter name? True if it doesn't look /// like a verbose description (no spaces > certain length, no period inside a sentence) - it's @@ -7977,29 +8069,79 @@ private static void PropagateFamilyTypeValues(RevitFileInfo rvtInfo, ParsingStat private struct RefScan { public int? MaterialId, CoverTypeId, FillPatternId, SecondLevelId; + public int? PhaseId, WallId; public int FirstLevelId; + + internal readonly bool Selected(int id) => id > 0 && (MaterialId == id || CoverTypeId == id + || FillPatternId == id || FirstLevelId == id || SecondLevelId == id); } - private static void EnrichTypeLevelBips(RevitFileInfo rvtInfo, ParsingState? state) + private readonly struct TypeLevelDefault(int id, string name, StorageType storage, object value) { - if (state == null) return; - var elemById = rvtInfo.Elements.ToDictionary(e => e.Id); + private readonly Parameter.DefinitionData _definition = new(id, name, name); + private readonly bool _readOnly = BipHelpers.IsBipReadOnly(name); - // Per-instance: scan refs + type's refs together to find type-level params. - IEnumerable CollectRefs(Element e) + public int Id => _definition.Id; + + public Parameter Create() => new(_definition) { - 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; - } - var typePhases = new Dictionary(); - var typeRefSets = new Dictionary>(); + Id = Id, IsReadOnly = _readOnly, StorageType = storage, + Value = value, HasNoRevitValue = true, + }; + } + + private static readonly TypeLevelDefault[] CommonTypeLevelDefaults = + [ + new(-1010103, "ALL_MODEL_DESCRIPTION", StorageType.String, ""), + new(-1010104, "ALL_MODEL_URL", StorageType.String, ""), + new(-1010105, "ALL_MODEL_TYPE_COMMENTS", StorageType.String, ""), + new(-1010106, "ALL_MODEL_INSTANCE_COMMENTS", StorageType.String, ""), + new(-1010108, "ALL_MODEL_MANUFACTURER", StorageType.String, ""), + new(-1010109, "ALL_MODEL_MODEL", StorageType.String, ""), + new(-1001203, "ALL_MODEL_MARK", StorageType.String, ""), + new(-1140422, "KEYNOTE_PARAM", StorageType.String, ""), + new(-1002500, "UNIFORMAT_CODE", StorageType.String, ""), + new(-1002501, "UNIFORMAT_DESCRIPTION", StorageType.String, ""), + new(-1002502, "OMNICLASS_CODE", StorageType.String, ""), + new(-1002503, "OMNICLASS_DESCRIPTION", StorageType.String, ""), + new(-1152384, "ALL_MODEL_TYPE_IMAGE", StorageType.ElementId, -1), + new(-1002002, "ALL_MODEL_FAMILY_NAME", StorageType.String, ""), + new(-1002001, "SYMBOL_NAME_PARAM", StorageType.String, ""), + new(-1001405, "WINDOW_TYPE_ID", StorageType.String, ""), + new(-1001206, "FIRE_RATING", StorageType.String, ""), + new(-1005556, "STRUCTURAL_FAMILY_CODE_NAME", StorageType.String, ""), + new(-1001205, "ALL_MODEL_COST", StorageType.Double, 0.0), + ]; + + internal static void EnrichTypeLevelBips(RevitFileInfo rvtInfo, ParsingState? state, + Dictionary elemById) + { + if (state == null || rvtInfo.Elements.Count == 0) return; + + // Other elements only read a level's existing elevation during this pass. + var levelElevations = new Dictionary(); + foreach (var (id, element) in elemById) + if (element.CategoryId == -2000240 + && element.Parameters.FirstOrDefault(p => p.Id == -1007102)?.Value is double elevation) + levelElevations.Add(id, elevation); + Parallel.ForEach(System.Collections.Concurrent.Partitioner.Create(0, rvtInfo.Elements.Count), + range => EnrichTypeLevelBipRange(rvtInfo.Elements, range.Item1, range.Item2, state, elemById, levelElevations)); + } + + private static void EnrichTypeLevelBipRange(IReadOnlyList elements, int start, int end, + ParsingState state, Dictionary elemById, Dictionary levelElevations) + { + var typeScans = new Dictionary<(int TypeId, bool IsWall), RefScan>(); void Accumulate(ref RefScan scan, int rid, int ownerId, bool isWall) { - if (rid == ownerId || rid <= 0) return; if (!elemById.TryGetValue(rid, out var refElem)) return; - switch (refElem.CategoryId) + int? category = refElem.CategoryId; + // The phase and host rules also consider zero ids and self references. + if (category == -2000112) scan.PhaseId ??= rid; + if (category == -2000011) scan.WallId ??= rid; + if (rid == ownerId || rid <= 0) return; + switch (category) { case -2000700: scan.MaterialId ??= rid; break; // OST_Materials case -2009014: scan.CoverTypeId ??= rid; break; // OST_CoverType @@ -8018,138 +8160,134 @@ void Accumulate(ref RefScan scan, int rid, int ownerId, bool isWall) && !string.IsNullOrEmpty(refElem.Name) && isWall) scan.FillPatternId = rid; } - RefScan ScanRefs(Element e, bool isWall) + RefScan ScanRefs(Element e, List? typeRefs, bool isWall) { var scan = new RefScan { FirstLevelId = -1 }; - if (e.TypeId > 0 && elemById.TryGetValue(e.TypeId, out var t) && t.References != null) + if (typeRefs is { Count: > 0 }) { 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 typeRefs) Accumulate(ref typeScan, r, int.MinValue, isWall); 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); - scan = typeScan; + // A skipped self reference only changes the result if it supplied a selected value. + if (typeScan.Selected(e.Id)) + foreach (var r in typeRefs) Accumulate(ref scan, r, e.Id, isWall); + else scan = typeScan; } if (e.References != null) foreach (var r in e.References) Accumulate(ref scan, r, e.Id, isWall); return scan; } - RefScan RescanSkipping(IEnumerable refs, int skipId, bool isWall) + + var parametersById = new Dictionary(); + var pendingParameters = new List(); + void AddParameter(Parameter parameter) { - var scan = new RefScan { FirstLevelId = -1 }; - foreach (var r in refs) Accumulate(ref scan, r, skipId, isWall); - return scan; + parametersById.Add(parameter.Id, parameter); + pendingParameters.Add(parameter); } - void EnsureBip(Element e, int id, string name, StorageType st, object value, bool isApproximate = false, bool hasNoRevitValue = false) + void EnsureBip(int id, string name, StorageType st, T value, bool isApproximate = false, bool hasNoRevitValue = false) { - if (e.Parameters.Any(p => p.Id == id)) return; + if (parametersById.ContainsKey(id)) return; var parameter = BipHelpers.MakeBipParam(id, name, st, value, hasNoRevitValue: hasNoRevitValue); parameter.IsApproximate = isApproximate; - e.Parameters.Add(parameter); + AddParameter(parameter); } // Like EnsureBip but ALSO overrides existing sentinel (-) OR existing-wrong-id values. // expectedCategoryId optionally filters: existing value must be of that category, else // override. - void EnsureBipOrFixNull(Element e, int id, string name, StorageType st, int value, + void EnsureBipOrFixNull(int id, string name, StorageType st, int value, int? expectedCategoryId = null) { - var existing = e.Parameters.FirstOrDefault(p => p.Id == id); - if (existing == null) + if (!parametersById.TryGetValue(id, out var existing)) { - e.Parameters.Add(BipHelpers.MakeBipParam(id, name, st, value)); + AddParameter(BipHelpers.MakeBipParam(id, name, st, value)); return; } if (existing.Value is not int iv) { existing.Value = value; return; } bool isSentinel = iv == -1 || iv == 0; - bool wrongCategory = expectedCategoryId.HasValue - && elemById.TryGetValue(iv, out var ivElem) - && ivElem.CategoryId != expectedCategoryId.Value; - bool unknownElement = !elemById.ContainsKey(iv); + bool unknownElement = !elemById.TryGetValue(iv, out var ivElem); + bool wrongCategory = !unknownElement && expectedCategoryId.HasValue + && ivElem!.CategoryId != expectedCategoryId.Value; if ((isSentinel || wrongCategory || unknownElement) && value > 0) existing.Value = value; } - foreach (var e in rvtInfo.Elements) + for (int index = start; index < end; index++) { + var e = elements[index]; if (e.CategoryId == null) continue; int cat = e.CategoryId.Value; bool isWall = cat == -2000011; + parametersById.Clear(); + pendingParameters.Clear(); + foreach (var parameter in e.Parameters) + parametersById.TryAdd(parameter.Id, parameter); // Fix type-related BIPs to use the resolved TypeId (set during PostProcess). // AddComputedElementParams runs before TypeId resolution and stores the Tf-class index, // so we need to overwrite here once the real TypeId is known. - if (e.TypeId > 0 && elemById.ContainsKey(e.TypeId)) + Element? type = e.TypeId > 0 ? elemById.GetValueOrDefault(e.TypeId) : null; + if (type != null) { - foreach (int pid in new[] { -1002050, -1002000, -1002052, -1002051 }) + ReadOnlySpan typeBips = [-1002050, -1002000, -1002052, -1002051]; + foreach (int pid in typeBips) { - var p = e.Parameters.FirstOrDefault(pp => pp.Id == pid); - if (p == null) continue; - if (p.Value is int iv && iv > 0 && elemById.ContainsKey(iv) && iv != e.TypeId) - { - // Override only when the current value references a WRONG-category element - // AND e.TypeId references a genuine SAME-category type (a real - // improvement). - if (elemById[iv].CategoryId != e.CategoryId - && elemById.TryGetValue(e.TypeId, out var etElem) - && etElem.CategoryId == e.CategoryId) p.Value = e.TypeId; - } - else if (p.Value is int iv2 && (iv2 <= 0 || !elemById.ContainsKey(iv2))) - { + if (!parametersById.TryGetValue(pid, out var p) || p.Value is not int iv || iv == e.TypeId) continue; + // Preserve an existing real reference unless the resolved type improves its category. + if (iv <= 0 || !elemById.TryGetValue(iv, out var currentType) + || (currentType.CategoryId != e.CategoryId && type.CategoryId == e.CategoryId)) p.Value = e.TypeId; - } } } - var refScan = ScanRefs(e, isWall); + var refScan = ScanRefs(e, type?.References, isWall); int? materialId = refScan.MaterialId, coverTypeId = refScan.CoverTypeId, fillPatternId = refScan.FillPatternId, secondLevelId = refScan.SecondLevelId; int firstLevelId = refScan.FirstLevelId; if (materialId.HasValue) - EnsureBipOrFixNull(e, -1005500, "STRUCTURAL_MATERIAL_PARAM", StorageType.ElementId, materialId.Value, -2000700); + EnsureBipOrFixNull(-1005500, "STRUCTURAL_MATERIAL_PARAM", StorageType.ElementId, materialId.Value, -2000700); if (coverTypeId.HasValue) { - EnsureBipOrFixNull(e, -1013437, "CLEAR_COVER_OTHER", StorageType.ElementId, coverTypeId.Value, -2009014); - EnsureBipOrFixNull(e, -1013435, "CLEAR_COVER_EXTERIOR", StorageType.ElementId, coverTypeId.Value, -2009014); - EnsureBipOrFixNull(e, -1013436, "CLEAR_COVER_INTERIOR", StorageType.ElementId, coverTypeId.Value, -2009014); + EnsureBipOrFixNull(-1013437, "CLEAR_COVER_OTHER", StorageType.ElementId, coverTypeId.Value, -2009014); + EnsureBipOrFixNull(-1013435, "CLEAR_COVER_EXTERIOR", StorageType.ElementId, coverTypeId.Value, -2009014); + EnsureBipOrFixNull(-1013436, "CLEAR_COVER_INTERIOR", StorageType.ElementId, coverTypeId.Value, -2009014); } if (fillPatternId.HasValue) - EnsureBipOrFixNull(e, -1002106, "COARSE_SCALE_FILL_PATTERN_ID_PARAM", StorageType.ElementId, fillPatternId.Value); + EnsureBipOrFixNull(-1002106, "COARSE_SCALE_FILL_PATTERN_ID_PARAM", StorageType.ElementId, fillPatternId.Value); if (isWall) { // WALL_HEIGHT_TYPE: top constraint level if (secondLevelId.HasValue) - EnsureBipOrFixNull(e, -1001103, "WALL_HEIGHT_TYPE", StorageType.ElementId, secondLevelId.Value, -2000240); + EnsureBipOrFixNull(-1001103, "WALL_HEIGHT_TYPE", StorageType.ElementId, secondLevelId.Value, -2000240); // FUNCTION_PARAM from extracted compound structure data on the type if (e.TypeId > 0 && state.WallTypeFunctions.TryGetValue((uint)e.TypeId, out int fn)) - EnsureBip(e, -1001006, "FUNCTION_PARAM", StorageType.Integer, fn); + EnsureBip(-1001006, "FUNCTION_PARAM", StorageType.Integer, fn); // Wall default-ish int/string BIPs - EnsureBip(e, -1002111, "WRAPPING_AT_ENDS_PARAM", StorageType.Integer, 0, hasNoRevitValue: true); - EnsureBip(e, -1002112, "WRAPPING_AT_INSERTS_PARAM", StorageType.Integer, 0, hasNoRevitValue: true); - EnsureBip(e, -1002110, "COARSE_SCALE_FILL_PATTERN_COLOR", StorageType.Integer, 0, hasNoRevitValue: true); - EnsureBip(e, -1002103, "WALL_STRUCTURE_ID_PARAM", StorageType.None, -1, hasNoRevitValue: true); + EnsureBip(-1002111, "WRAPPING_AT_ENDS_PARAM", StorageType.Integer, 0, hasNoRevitValue: true); + EnsureBip(-1002112, "WRAPPING_AT_INSERTS_PARAM", StorageType.Integer, 0, hasNoRevitValue: true); + EnsureBip(-1002110, "COARSE_SCALE_FILL_PATTERN_COLOR", StorageType.Integer, 0, hasNoRevitValue: true); + EnsureBip(-1002103, "WALL_STRUCTURE_ID_PARAM", StorageType.None, -1, hasNoRevitValue: true); // WALL_ATTR_ROOM_BOUNDING (-1001007): physical walls default to "room bounding" = 1 - var rbParam = e.Parameters.FirstOrDefault(p => p.Id == -1001007); + var rbParam = parametersById.GetValueOrDefault(-1001007); if (rbParam == null) - EnsureBip(e, -1001007, "WALL_ATTR_ROOM_BOUNDING", StorageType.Integer, 1); + EnsureBip(-1001007, "WALL_ATTR_ROOM_BOUNDING", StorageType.Integer, 1); else if (rbParam.Value is int iv && iv == 0) rbParam.Value = 1; // override extracted 0 // STRUCTURAL_ANALYTICAL_MODEL (-1001552): walls default to 1 when structural // significant - var samParam = e.Parameters.FirstOrDefault(p => p.Id == -1001552); + var samParam = parametersById.GetValueOrDefault(-1001552); bool isStructural = e.Parameters.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); + EnsureBip(-1001552, "STRUCTURAL_ANALYTICAL_MODEL", StorageType.Integer, isStructural ? 1 : 0); else if (samParam.Value is int iv && iv == 0 && isStructural) samParam.Value = 1; } @@ -8157,73 +8295,54 @@ void EnsureBipOrFixNull(Element e, int id, string name, StorageType st, int valu // FamilyInstances). if (firstLevelId > 0) { - var flp = e.Parameters.FirstOrDefault(p => p.Id == -1001352); + var flp = parametersById.GetValueOrDefault(-1001352); if (flp == null) - e.Parameters.Add(BipHelpers.MakeBipParam(-1001352, "FAMILY_LEVEL_PARAM", StorageType.ElementId, firstLevelId)); + AddParameter(BipHelpers.MakeBipParam(-1001352, "FAMILY_LEVEL_PARAM", StorageType.ElementId, firstLevelId)); else if (flp.Value is int iv && (iv <= 0 || !elemById.ContainsKey(iv) || (elemById.TryGetValue(iv, out var lvlElem) && lvlElem.CategoryId != -2000240))) flp.Value = firstLevelId; // SCHEDULE_LEVEL_PARAM mirrors FAMILY_LEVEL_PARAM for FamilyInstances if (!e.ScheduleLevelFromStoredFields) - EnsureBipOrFixNull(e, -1002062, "SCHEDULE_LEVEL_PARAM", StorageType.ElementId, firstLevelId, -2000240); + EnsureBipOrFixNull(-1002062, "SCHEDULE_LEVEL_PARAM", StorageType.ElementId, firstLevelId, -2000240); } else { // No level - emit sentinel so the param exists - EnsureBip(e, -1001352, "FAMILY_LEVEL_PARAM", StorageType.ElementId, -1, hasNoRevitValue: true); + EnsureBip(-1001352, "FAMILY_LEVEL_PARAM", StorageType.ElementId, -1, hasNoRevitValue: true); } // 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 (!typePhases.TryGetValue(e.TypeId, out var typePhase)) - { - typePhase = null; - foreach (var rid in phaseType.References) - 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 (elemById.TryGetValue(rid, out var refElem) && refElem.CategoryId == -2000112) { phaseCreatedId = rid; break; } + int? phaseCreatedId = refScan.PhaseId; if (phaseCreatedId.HasValue) - EnsureBipOrFixNull(e, -1012100, "PHASE_CREATED", StorageType.ElementId, phaseCreatedId.Value, -2000112); + EnsureBipOrFixNull(-1012100, "PHASE_CREATED", StorageType.ElementId, phaseCreatedId.Value, -2000112); else - EnsureBip(e, -1012100, "PHASE_CREATED", StorageType.ElementId, -1, hasNoRevitValue: true); + EnsureBip(-1012100, "PHASE_CREATED", StorageType.ElementId, -1, hasNoRevitValue: true); // HOST_ID_PARAM: id of the host element. For FamilyInstances we use HostId if resolved, // else -1 (Revit returns -1 for free-standing instances). int hostId = e.HostId ?? -1; - if (e.CategoryId is -2000171 or -2000170) - { - foreach (var rid in CollectRefs(e)) - if (elemById.TryGetValue(rid, out var hw) && hw.CategoryId == -2000011) { hostId = rid; break; } - } - EnsureBip(e, -1002108, "HOST_ID_PARAM", StorageType.ElementId, hostId, hasNoRevitValue: hostId <= 0); + if (e.CategoryId is -2000171 or -2000170 && refScan.WallId is int wallId) hostId = wallId; + EnsureBip(-1002108, "HOST_ID_PARAM", StorageType.ElementId, hostId, hasNoRevitValue: hostId <= 0); // INSTANCE_FREE_HOST_PARAM: human-readable host label "Level: " (localized). Applies // to free-standing family instances where host is the level. if (firstLevelId > 0 && elemById.TryGetValue(firstLevelId, out var lvlE) && !string.IsNullOrEmpty(lvlE.Name)) - EnsureBip(e, -1001363, "INSTANCE_FREE_HOST_PARAM", StorageType.String, $"Уровень : {lvlE.Name}"); + EnsureBip(-1001363, "INSTANCE_FREE_HOST_PARAM", StorageType.String, $"Уровень : {lvlE.Name}"); // 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 } box && firstLevelId > 0 + && levelElevations.TryGetValue(firstLevelId, out double lvlElev)) { // Only when the level's elevation actually resolved - assuming 0 for an unresolved // level produced garbage elevations (= raw bbox z). - double minZ = GeometryBox(e)![2]; + double minZ = box[2]; double elev = Math.Round(minZ - lvlElev, 12); - var iepExisting = e.Parameters.FirstOrDefault(p => p.Id == -1001360); + var iepExisting = parametersById.GetValueOrDefault(-1001360); if (iepExisting == null) - e.Parameters.Add(BipHelpers.MakeBipParam(-1001360, "INSTANCE_ELEVATION_PARAM", StorageType.Double, elev)); + AddParameter(BipHelpers.MakeBipParam(-1001360, "INSTANCE_ELEVATION_PARAM", StorageType.Double, elev)); else { // Override -1 sentinel; preserve explicitly stored values that aren't sentinels @@ -8234,30 +8353,26 @@ void EnsureBipOrFixNull(Element e, int id, string name, StorageType st, int valu } // INSTANCE_OFFSET_POS_PARAM: face-flip flag, defaults to 0 - EnsureBip(e, -1001370, "INSTANCE_OFFSET_POS_PARAM", StorageType.Integer, 0, hasNoRevitValue: true); + EnsureBip(-1001370, "INSTANCE_OFFSET_POS_PARAM", StorageType.Integer, 0, hasNoRevitValue: true); // INSTANCE_FREE_HOST_OFFSET_PARAM = INSTANCE_ELEVATION_PARAM for free-host instances - var iep = e.Parameters.FirstOrDefault(p => p.Id == -1001360); + var iep = parametersById.GetValueOrDefault(-1001360); if (iep?.Value is double iepVal) - EnsureBip(e, -1001364, "INSTANCE_FREE_HOST_OFFSET_PARAM", StorageType.Double, iepVal); + EnsureBip(-1001364, "INSTANCE_FREE_HOST_OFFSET_PARAM", StorageType.Double, iepVal); // FAMILY_FREEINST_DEFAULT_ELEVATION: type-level default elevation, usually 0 - EnsureBip(e, -1154647, "FAMILY_FREEINST_DEFAULT_ELEVATION", StorageType.Double, 0.0, hasNoRevitValue: true); + EnsureBip(-1154647, "FAMILY_FREEINST_DEFAULT_ELEVATION", StorageType.Double, 0.0, hasNoRevitValue: true); // INSTANCE_SILL_HEIGHT_PARAM: for wall-hosted inserts the stored 0x08BE value // (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; - } + if (firstLevelId > 0) levelElevations.TryGetValue(firstLevelId, out lvlElev2); double computedSill = Math.Round(org[2] - lvlElev2, 12); - var sillExisting = e.Parameters.FirstOrDefault(p => p.Id == -1001361); + var sillExisting = parametersById.GetValueOrDefault(-1001361); if (sillExisting == null) - e.Parameters.Add(BipHelpers.MakeBipParam(-1001361, "INSTANCE_SILL_HEIGHT_PARAM", StorageType.Double, computedSill)); + AddParameter(BipHelpers.MakeBipParam(-1001361, "INSTANCE_SILL_HEIGHT_PARAM", StorageType.Double, computedSill)); else if (e.HostId is null or <= 0) sillExisting.Value = computedSill; // free instance: stored value is a 0 placeholder } @@ -8265,57 +8380,25 @@ void EnsureBipOrFixNull(Element e, int id, string name, StorageType st, int valu // 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)) + if (isWall && materialId.HasValue && elemById.ContainsKey(materialId.Value)) { - // 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(-1005430, "ANALYTICAL_HEAT_TRANSFER_COEFFICIENT", StorageType.Double, 3.4866666666666668, isApproximate: true); + EnsureBip(-1005436, "ANALYTICAL_ROUGHNESS", StorageType.Integer, 3, isApproximate: true); + EnsureBip(-1005435, "ANALYTICAL_ABSORPTANCE", StorageType.Double, 0.7, isApproximate: true); + EnsureBip(-1005434, "ANALYTICAL_THERMAL_MASS", StorageType.Double, 453330.0, isApproximate: true); + if (parametersById.GetValueOrDefault(-1001000)?.Value is double width) + EnsureBip(-1005431, "ANALYTICAL_THERMAL_RESISTANCE", StorageType.Double, + width / 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) + foreach (var parameter in CommonTypeLevelDefaults) + if (!parametersById.ContainsKey(parameter.Id)) + pendingParameters.Add(parameter.Create()); + e.Parameters.AddRange(pendingParameters); } } @@ -8324,82 +8407,38 @@ void EnsureBipOrFixNull(Element e, int id, string name, StorageType st, int valu /// instance. If the entry's projKey isn't in the instance's parameters, add it as an empty /// placeholder. /// - private static void PropagateChainPlaceholders(RevitFileInfo rvtInfo, ParsingState? state) + private static void PropagateChainPlaceholders(RevitFileInfo rvtInfo, ParsingState? state, + Dictionary definitions) { if (state == null || state.FamilyParamMaps.Count == 0) return; - var elemById = rvtInfo.Elements.ToDictionary(e => e.Id); + var byType = new Dictionary(); + var byId = new Dictionary(); foreach (var e in rvtInfo.Elements) { if (e.TypeId <= 0 || !state.FamilyParamMaps.TryGetValue((uint)e.TypeId, out var map)) continue; // Each chain entry produces a (binKey, projKey) mapping; the projKey is the actual // project param def ID. Ensure it exists on the instance with the right type. - foreach (var projKey in map.Values.Distinct()) + uint type = (uint)e.TypeId; + if (!byType.TryGetValue(type, out var placeholders)) { - int pid = (int)projKey; - var existingParam = e.Parameters.FirstOrDefault(p => p.Id == pid); - - string? forgeId = null, displayName = null; - Guid? guid = null; - if (state.ForgeParamDefs.TryGetValue(projKey, out var def)) - { forgeId = def.ForgeId; displayName = def.DisplayName; } - if (state.ParamDefGuids.TryGetValue(projKey, out var binGuid)) guid = binGuid; - else guid = BipHelpers.ParseGuidFromForgeId(forgeId); - - StorageType st = StorageType.String; - object value = ""; - string? spec = null; - if (forgeId != null) state.ForgeParamSpecs.TryGetValue(forgeId, out spec); - if (spec != null) - { - if (spec.Contains("bool") || spec.Contains("int")) - { st = StorageType.Integer; value = 0; } - else if (spec.StartsWith("autodesk.spec.aec:") - || spec.StartsWith("autodesk.spec.aec.") - || spec.Contains("number") || spec.Contains("length") - || spec.Contains("area") || spec.Contains("volume") - || spec.Contains("currency")) - { st = StorageType.Double; value = 0.0; } - else if (spec.Contains("material") || spec.Contains("reference") - || spec.Contains("category")) - { st = StorageType.ElementId; value = -1; } - else { st = StorageType.String; value = ""; } - } - else if (displayName != null) - { - // Heuristic by display name (Russian Revit family params) - string nl = displayName.ToLowerInvariant(); - if (nl.Contains("удален") || nl.Contains("ниша") || nl.Contains("вкл") - || nl.Contains("устаревш") || nl.Contains("согласован") - || nl.Contains("исключить") || nl.Contains("ручн") - || nl.Contains("круглое") || nl.Contains("ось") || nl.Contains("кругл") - || nl.Contains("автоглубин") || nl.Contains("элементы_управ") - || nl.Contains("в перекрыти") || nl.Contains("в стене") - || nl.StartsWith("обозначение_") && nl.EndsWith("_тип")) - { st = StorageType.Integer; value = 0; } - else if (nl.Contains("глубин") || nl.Contains("толщин") || nl.Contains("длин") - || nl.Contains("ширин") || nl.Contains("высот") || nl.Contains("диаметр") - || nl.Contains("площад") || nl.Contains("объем") - || nl.Contains("отметка") || nl.Contains("корректировка") - || nl.Contains("крутвопрос") || nl.Contains("количество") - || nl.Contains("расч_")) - { st = StorageType.Double; value = 0.0; } - else if (nl.Contains("материал") || nl.StartsWith("тип") || nl.StartsWith("обозначение ")) - { st = StorageType.ElementId; value = -1; } - } - + placeholders = map.Values.Distinct().Select(Describe).ToArray(); + byType.Add(type, placeholders); + } + foreach (var placeholder in placeholders) + { + var existingParam = FindParameterById(e.Parameters, placeholder.Id); + StorageType st = placeholder.Storage; + object value = placeholder.Value; if (existingParam == null) { - e.Parameters.Add(new Parameter + e.Parameters.Add(new Parameter(placeholder.Data) { - Id = pid, + Id = placeholder.Id, StorageType = st, Value = value, HasNoRevitValue = true, - IsReadOnly = false, - ForgeId = forgeId, - Guid = guid, - Definition = new Definition { Id = pid, Name = displayName }, + ForgeId = placeholder.ForgeId, }); } else @@ -8418,13 +8457,60 @@ private static void PropagateChainPlaceholders(RevitFileInfo rvtInfo, ParsingSta if (wasNoRevitValue) existingParam.HasNoRevitValue = true; } // Also fill in missing metadata - if (existingParam.ForgeId == null) existingParam.ForgeId = forgeId; - if (existingParam.Guid == null) existingParam.Guid = guid; - if (existingParam.Definition == null || string.IsNullOrEmpty(existingParam.Definition.Name)) - existingParam.Definition = new Definition { Id = pid, Name = displayName }; + existingParam.ForgeId ??= placeholder.ForgeId; + existingParam.UseGuidIfMissing(placeholder.Data); + if (string.IsNullOrEmpty(existingParam.DefinitionName)) + existingParam.SetDefinitionData(placeholder.Data); } } } + + InheritedTypeParameter Describe(uint id) + { + if (byId.TryGetValue(id, out var placeholder)) return placeholder; + var definition = FamilyDefinition(id, state, definitions); + StorageType storage = StorageType.String; + object value = ""; + string? spec = definition.ForgeId is { } forgeId ? state.ForgeParamSpecs.GetValueOrDefault(forgeId) : null; + if (spec != null) + { + if (spec.Contains("bool") || spec.Contains("int")) + { storage = StorageType.Integer; value = 0; } + else if (spec.StartsWith("autodesk.spec.aec:") + || spec.StartsWith("autodesk.spec.aec.") + || spec.Contains("number") || spec.Contains("length") + || spec.Contains("area") || spec.Contains("volume") + || spec.Contains("currency")) + { storage = StorageType.Double; value = 0.0; } + else if (spec.Contains("material") || spec.Contains("reference") || spec.Contains("category")) + { storage = StorageType.ElementId; value = -1; } + } + else if (definition.Data.Name is { } displayName) + { + // Heuristic by display name (Russian Revit family params) + string name = displayName.ToLowerInvariant(); + if (name.Contains("удален") || name.Contains("ниша") || name.Contains("вкл") + || name.Contains("устаревш") || name.Contains("согласован") + || name.Contains("исключить") || name.Contains("ручн") + || name.Contains("круглое") || name.Contains("ось") || name.Contains("кругл") + || name.Contains("автоглубин") || name.Contains("элементы_управ") + || name.Contains("в перекрыти") || name.Contains("в стене") + || name.StartsWith("обозначение_") && name.EndsWith("_тип")) + { storage = StorageType.Integer; value = 0; } + else if (name.Contains("глубин") || name.Contains("толщин") || name.Contains("длин") + || name.Contains("ширин") || name.Contains("высот") || name.Contains("диаметр") + || name.Contains("площад") || name.Contains("объем") + || name.Contains("отметка") || name.Contains("корректировка") + || name.Contains("крутвопрос") || name.Contains("количество") + || name.Contains("расч_")) + { storage = StorageType.Double; value = 0.0; } + else if (name.Contains("материал") || name.StartsWith("тип") || name.StartsWith("обозначение ")) + { storage = StorageType.ElementId; value = -1; } + } + placeholder = new(definition.Data, storage, value, true, definition.ForgeId); + byId.Add(id, placeholder); + return placeholder; + } } /// @@ -8451,7 +8537,7 @@ private static void ComputeWallSolids(List elements) foreach (var p in elem.Parameters) { - 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) @@ -8712,23 +8798,17 @@ private static void ComputeWallSolids(List elements) } - private static void AddBodyBipParams(Element elem, ElementRecord rec, uint elemId, ParsingState state) + private static void AddBodyBipParams(Element elem, ElementRecord rec, uint elemId, ParsingState state, HashSet seenIds) { if (rec.BipParams.Count == 0) return; - var seenIds = new HashSet(); 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, null, 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) @@ -8780,7 +8860,7 @@ private static void AddBodyBipParams(Element elem, ElementRecord rec, uint elemI } } if (param.Value == null) - param.Value = b.Value.HasValue ? (object)b.Value.Value : null; + param.Value = b.Value is int value ? Parameter.BoxParsedValue(value) : null; } if (!resolvedStored && (param.Value == null @@ -8800,8 +8880,9 @@ private static void AddBodyBipParams(Element elem, ElementRecord rec, uint elemI paramGuid = BipHelpers.ParseGuidFromForgeId(forgeId); param.ForgeId = forgeId; param.Guid = paramGuid; - param.Definition = new Definition { Id = b.BipId, Name = displayName }; - param.IsReadOnly = !rec.WritableParamIds.Contains(b.BipId); + param.Definition.Id = b.BipId; + param.Definition.Name = displayName; + param.IsReadOnly = rec.WritableParamIds?.Contains(b.BipId) != true; if (state.ElemBipDoubles.TryGetValue(elemId, out var userDblVals) && userDblVals.TryGetValue(b.BipId, out double userDbl)) { param.StorageType = StorageType.Double; param.Value = userDbl; } @@ -8811,7 +8892,7 @@ private static void AddBodyBipParams(Element elem, ElementRecord rec, uint elemI else { param.StorageType = b.Value.HasValue ? StorageType.Integer : StorageType.None; - param.Value = b.Value.HasValue ? (object)b.Value.Value : null; + param.Value = b.Value is int value ? Parameter.BoxParsedValue(value) : null; if (!b.Value.HasValue || b.Value.Value == -1) param.HasNoRevitValue = true; } } @@ -8819,13 +8900,12 @@ private static void AddBodyBipParams(Element elem, ElementRecord rec, uint elemI } } - private static void AddUserParams(Element elem, ElementRecord rec, uint elemId, ParsingState state) + private static void AddUserParams(Element elem, ElementRecord rec, uint elemId, ParsingState state, HashSet existingIds) { if (!state.ElemParamStrings.TryGetValue(elemId, out var paramStrMap)) return; - var existingIds = new HashSet(elem.Parameters.Select(p => p.Id)); foreach (var (paramDefId, strVal) in paramStrMap) { - if (existingIds.Contains((int)paramDefId)) continue; + if (!existingIds.Add((int)paramDefId)) continue; string? forgeId = null, displayName = null; Guid? paramGuid = null; if (state.ForgeParamDefs.TryGetValue(paramDefId, out var def)) @@ -8839,7 +8919,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.WritableParamIds?.Contains((int)paramDefId) != true, ForgeId = forgeId, Guid = paramGuid, Definition = new Definition { Id = (int)paramDefId, Name = displayName }, @@ -8847,22 +8927,16 @@ private static void AddUserParams(Element elem, ElementRecord rec, uint elemId, } } - private static void AddBipDoubles(Element elem, uint elemId, ParsingState state) + private static void AddBipDoubles(Element elem, uint elemId, ParsingState state, HashSet existing) { if (!state.ElemBipDoubles.TryGetValue(elemId, out var bipDblMap)) return; - var existing = new HashSet(elem.Parameters.Select(p => p.Id)); foreach (var (bipKey, bipVal) in bipDblMap) { - if (existing.Contains(bipKey)) continue; + if (!existing.Add(bipKey)) continue; 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 { @@ -8884,22 +8958,16 @@ private static void AddBipDoubles(Element elem, uint elemId, ParsingState state) } } - private static void AddBipInts(Element elem, uint elemId, ParsingState state) + private static void AddBipInts(Element elem, uint elemId, ParsingState state, HashSet existing) { if (!state.ElemBipInts.TryGetValue(elemId, out var bipIntMap)) return; - var existing = new HashSet(elem.Parameters.Select(p => p.Id)); foreach (var (bipKey, bipVal) in bipIntMap) { - if (existing.Contains(bipKey)) continue; + if (!existing.Add(bipKey)) continue; 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, null, bipVal)); } else { @@ -8922,27 +8990,20 @@ private static void AddBipInts(Element elem, uint elemId, ParsingState state) } } - private static void AddPropagatedBipDoubles(Element elem, uint elemId, ParsingState state) + private static void AddPropagatedBipDoubles(Element elem, uint elemId, ParsingState state, HashSet existing) { if (!state.Records.TryGetValue(elemId, out var rec) || rec.References.Count == 0) return; - var existing = new HashSet(elem.Parameters.Select(p => p.Id)); foreach (var refId in rec.References) { if (refId == elemId) continue; if (!state.ElemBipDoubles.TryGetValue(refId, out var refBipDbls)) continue; foreach (var (bipKey, bipVal) in refBipDbls) { - if (existing.Contains(bipKey)) continue; - existing.Add(bipKey); if (bipKey < 0) { + if (!existing.Add(bipKey)) continue; 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 { @@ -8954,19 +9015,18 @@ private static void AddPropagatedBipDoubles(Element elem, uint elemId, ParsingSt } } - private static void AddBaseFields(Element elem, uint elemId, ParsingState state) + private static void AddBaseFields(Element elem, uint elemId, ParsingState state, HashSet existing) { if (!state.ElemBaseFields.TryGetValue(elemId, out var bf)) return; - var existing = new HashSet(elem.Parameters.Select(p => p.Id)); - if (bf.AssocLevelId != -1 && !existing.Contains(-1001952)) + if (bf.AssocLevelId != -1 && existing.Add(-1001952)) elem.Parameters.Add(BipHelpers.MakeBipParam(-1001952, "LEVEL_PARAM", StorageType.ElementId, bf.AssocLevelId)); - if (!existing.Contains(-1002051)) + if (existing.Add(-1002051)) elem.Parameters.Add(BipHelpers.MakeBipParam(-1002051, "ELEM_FAMILY_PARAM", StorageType.ElementId, bf.FamId)); - if (bf.CreatedPhaseId > 0 && !existing.Contains(-1012100)) + if (bf.CreatedPhaseId > 0 && existing.Add(-1012100)) elem.Parameters.Add(BipHelpers.MakeBipParam(-1012100, "PHASE_CREATED", StorageType.ElementId, bf.CreatedPhaseId)); - if (bf.DemolishedPhaseId > 0 && !existing.Contains(-1012101)) + if (bf.DemolishedPhaseId > 0 && existing.Add(-1012101)) elem.Parameters.Add(BipHelpers.MakeBipParam(-1012101, "PHASE_DEMOLISHED", StorageType.ElementId, bf.DemolishedPhaseId)); - if (!existing.Contains(-1013201)) + if (existing.Add(-1013201)) elem.Parameters.Add(BipHelpers.MakeBipParam(-1013201, "DESIGN_OPTION_ID", StorageType.ElementId, bf.BaseDesignOptionId)); } @@ -8975,10 +9035,8 @@ private static void AddBaseFields(Element elem, uint elemId, ParsingState state) /// SYMBOL_ID_PARAM, etc. These parameters exist in Revit but are computed at runtime from /// element properties. /// - private static void AddComputedElementParams(Element elem, uint elemId, uint typeId, ParsingState state) + private static void AddComputedElementParams(Element elem, HashSet existing) { - var existing = new HashSet(elem.Parameters.Select(p => p.Id)); - // ElemTable contains no type link. ELEM_TYPE_PARAM / ELEM_FAMILY_AND_TYPE_PARAM / // SYMBOL_ID_PARAM / ELEM_FAMILY_PARAM must reference real type/family elements (id > // 100000). diff --git a/src/RvtIO/Parsing/GRepParserV2.EdgeBounds.cs b/src/RvtIO/Parsing/GRepParserV2.EdgeBounds.cs index 4c2ee3b2..8f4d5db7 100644 --- a/src/RvtIO/Parsing/GRepParserV2.EdgeBounds.cs +++ b/src/RvtIO/Parsing/GRepParserV2.EdgeBounds.cs @@ -68,11 +68,11 @@ internal static partial class GRepParserV2 // The bounding box of a geometry is computed per face: only authored Edge samples, // evaluated on the Edge's first active Face; neither a surface envelope nor analytic extrema. - private static Dictionary ReadFaceEdgeBounds(Cur c) + private static Dictionary ReadFaceEdgeBounds(Cur c, Dictionary> loops, + Dictionary edges) { var result = new Dictionary(); - var edges = EdgesByHandle(c); - foreach (var (face, indices) in CompleteFaceLoops(c)) + foreach (var (face, indices) in loops) { var faceEdges = TryGetFaceLoopEdges(c, face, indices, edges); if (faceEdges == null) continue; diff --git a/src/RvtIO/Parsing/GRepParserV2.FaceAreas.cs b/src/RvtIO/Parsing/GRepParserV2.FaceAreas.cs index 44fb5c75..b147c75d 100644 --- a/src/RvtIO/Parsing/GRepParserV2.FaceAreas.cs +++ b/src/RvtIO/Parsing/GRepParserV2.FaceAreas.cs @@ -29,10 +29,18 @@ private static Dictionary ComputeFaceAreas(Cur c, Dictionary> loopsByFace, Dictionary edges) { var result = new Dictionary(); + var facesWithCurvedEdges = new HashSet(); + foreach (var edge in c.Edges) + if (edge.HasAuthoredInterior) + { + facesWithCurvedEdges.Add(edge.FaceA); + facesWithCurvedEdges.Add(edge.FaceB); + } foreach (uint face in faces) { if (!surfaces.TryGetValue(face, out var surface) || surface.Kind is not (SurfKind.Plane or SurfKind.Cylinder) || surface.Kind == SurfKind.Cylinder && !c.IncludeNonVisible + || surface.Kind == SurfKind.Plane && !facesWithCurvedEdges.Contains(face) || !loopsByFace.TryGetValue(face, out var indices) || indices.Count == 0) continue; var coedges = SurfaceCoedges(c, face, indices, edges); diff --git a/src/RvtIO/Parsing/GRepParserV2.MeshNodes.cs b/src/RvtIO/Parsing/GRepParserV2.MeshNodes.cs index 40377575..a5c56efd 100644 --- a/src/RvtIO/Parsing/GRepParserV2.MeshNodes.cs +++ b/src/RvtIO/Parsing/GRepParserV2.MeshNodes.cs @@ -25,17 +25,17 @@ internal static partial class GRepParserV2 private static readonly bool MeshDisplayNodes = Environment.GetEnvironmentVariable("RVTIO_X_DISPLAYNODE") != "0"; private static List? BuildNodes(Cur c, Dictionary surfaces, HashSet bodyFaces, - IEnumerable inactiveBodyFaces, Dictionary> loopsByFace, + IEnumerable inactiveBodyFaces, Dictionary> loopsByFace, Dictionary edges, Dictionary nodeByFace, Dictionary nodeOrders, List<(int Node, int Style, int RenderStyleId)>? displayOnlyNodes = null, List? nodeMeasures = null, bool measureSourceNodes = false) { - var edges = EdgesByHandle(c); MeshMarkFreeformEdges(edges, surfaces); var inactiveByNode = inactiveBodyFaces.Where(nodeByFace.ContainsKey).GroupBy(h => nodeByFace[h].Node) .ToDictionary(g => g.Key, g => g.ToList()); var result = new List(); - var vertexTable = MeshVertexModel ? MeshVertexTable.Build(c, edges, surfaces, bodyFaces, loopsByFace) : null; + MeshVertexTable? vertexTable = null; + bool meshCurvedPlanarEdges = Environment.GetEnvironmentVariable("RVTIO_X_CURVEDEDGE") == "1"; // a geometry that carries no node ids at all (the own GRep of a railing or a wall) is the // one node 0 bool withoutNodes = !bodyFaces.Any(nodeByFace.ContainsKey); @@ -58,6 +58,13 @@ internal static partial class GRepParserV2 if (MeshNodeLog) DiagnosticSink.WriteLine($"[meshnode] eid={c.ElementId} node={group.Key} active {string.Join(",", group.GroupBy(h => surfaces.TryGetValue(h, out var sx) ? sx.Kind.ToString() : "none").Select(g => $"{g.Key}:{g.Count()}"))}" + $" inactive {(inactiveByNode.TryGetValue(group.Key, out var inx) ? string.Join(",", inx.GroupBy(h => c.DirectSurfaceByFace.TryGetValue(h, out var sy) ? sy.Kind.ToString() : "none").Select(g => $"{g.Key}:{g.Count()}")) : "-")}"); + // Planar nodes still contribute the analytic measures above, but emit no mesh. + if (!MeshNodeLog && !meshCurvedPlanarEdges + && group.All(h => surfaces.TryGetValue(h, out var surface) && surface.Kind == SurfKind.Plane) + && (!inactiveByNode.TryGetValue(group.Key, out var inactivePlanar) + || inactivePlanar.All(h => c.DirectSurfaceByFace.TryGetValue(h, out var surface) && surface.Kind == SurfKind.Plane))) + continue; + if (MeshVertexModel) vertexTable ??= MeshVertexTable.Build(c, edges, surfaces, bodyFaces, loopsByFace); var faces = new List(); foreach (uint handle in group) { @@ -73,7 +80,7 @@ internal static partial class GRepParserV2 curved |= surface.Kind != SurfKind.Plane; faces.Add(face); } - if (usable && !curved && Environment.GetEnvironmentVariable("RVTIO_X_CURVEDEDGE") == "1" + if (usable && !curved && meshCurvedPlanarEdges && faces.Any(f => f.Loops.Any(l => l.Coedges.Any(ce => ce.Curve is { Kind: not CurveKind.Line })))) curved = true; // Revit's isPlanar looks at every face of the node, the inactive ones included: diff --git a/src/RvtIO/Parsing/GRepParserV2.SourcePlanarLoops.cs b/src/RvtIO/Parsing/GRepParserV2.SourcePlanarLoops.cs index 7a3302b9..cc504a7b 100644 --- a/src/RvtIO/Parsing/GRepParserV2.SourcePlanarLoops.cs +++ b/src/RvtIO/Parsing/GRepParserV2.SourcePlanarLoops.cs @@ -10,10 +10,18 @@ internal static partial class GRepParserV2 { var topology = TfBlockDeserializer.SelectOwnGElementLoopTopology(graph, out failure); if (topology == null) return null; - var winding = TfBlockDeserializer.SelectOwnGElementEpsIndependentSamples(graph, out failure); - if (winding == null) return null; + // A face's sole closed loop takes the single-loop-outer branch before either EPS test. + bool onlySingleLoops = topology.Faces.All(face => face.Loops.Count == 0 + || face.Loops.Count == 1 && face.Loops[0].FaceQueueIndex == face.FaceQueueIndex + && face.Loops[0].GetOuterLoopsCandidate); + Dictionary<(int Face, int Loop), TfBlockDeserializer.GElementEpsIndependentLoop>? decisions = null; + if (!onlySingleLoops) + { + var winding = TfBlockDeserializer.SelectOwnGElementEpsIndependentSamples(graph, out failure); + if (winding == null) return null; + decisions = winding.Loops.ToDictionary(l => (l.FaceQueueIndex, l.LoopQueueIndex)); + } var nodes = graph.Nodes.ToDictionary(n => n.QueueIndex); - var decisions = winding.Loops.ToDictionary(l => (l.FaceQueueIndex, l.LoopQueueIndex)); var result = new Dictionary>(); foreach (var face in topology.Faces) { @@ -27,10 +35,15 @@ internal static partial class GRepParserV2 foreach (var loop in face.Loops) { failure = $"source-planar-loop:{face.FaceQueueIndex}:{loop.QueueIndex}"; + bool outer = true; if (loop.FaceQueueIndex != face.FaceQueueIndex - || loop.ClassId is not (1254 or 1257) || !loop.GetOuterLoopsCandidate - || !decisions.TryGetValue((face.FaceQueueIndex, loop.QueueIndex), out var decision) - || decision.IndependentShouldBeCcw is not bool outer) return null; + || loop.ClassId is not (1254 or 1257) || !loop.GetOuterLoopsCandidate) return null; + if (decisions != null) + { + if (!decisions.TryGetValue((face.FaceQueueIndex, loop.QueueIndex), out var decision) + || decision.IndependentShouldBeCcw is not bool isOuter) return null; + outer = isOuter; + } var vertices = TfBlockDeserializer.SelectSourceTwoPointPolygonVertices(loop, out string? why); if (vertices == null) { failure += ":" + why; return null; } var ring = new List(); @@ -49,6 +62,7 @@ internal static partial class GRepParserV2 var regions = ClassifyCoplanarRings(rings, exactPredicates: true); if (regions.Count + regions.Sum(r => r.Holes.Count) != rings.Count || regions.Any(r => !outerByRing[r.Outer] || r.Holes.Any(h => outerByRing[h]))) return null; + if (!TfBlockDeserializer.TryReadSourcePlaneBasis(plane, out var basis)) return null; var faces = new List(); var sourceLoops = rings.Select(WorldRing).ToList(); if (sourceLoops.Any(loop => loop == null)) return null; @@ -67,13 +81,11 @@ internal static partial class GRepParserV2 List? WorldRing(List ring) { - var world = new List(); + var world = new List(ring.Count); foreach (var uv in ring) { - var bits = TfBlockDeserializer.EvaluateSourceOwnPlanePoint(plane, - [BitConverter.DoubleToInt64Bits(uv[0]), BitConverter.DoubleToInt64Bits(uv[1])], out _); - if (bits == null) return null; - world.Add(bits.Select(BitConverter.Int64BitsToDouble).ToArray()); + if (!basis.TryEvaluate(uv[0], uv[1], out var point)) return null; + world.Add(point.ToArray()); } return world; } diff --git a/src/RvtIO/Parsing/GRepParserV2.cs b/src/RvtIO/Parsing/GRepParserV2.cs index a580d5df..4b660ab6 100644 --- a/src/RvtIO/Parsing/GRepParserV2.cs +++ b/src/RvtIO/Parsing/GRepParserV2.cs @@ -1,4 +1,5 @@ using RvtIO.Internal; +using Pt3 = RvtIO.Geometry.Meshing.Pt3; namespace RvtIO.Parsing; @@ -30,7 +31,7 @@ private sealed class DecodeStop : Exception { } /// /// Serialized class ids of the Face and Edge objects whose per-block counts feed . + /// cref="GRepData.QueueSummary"/>. /// internal const ushort GFaceClass = 1589; internal const ushort EdgeClass = 1243; @@ -50,6 +51,8 @@ private sealed class Cur public bool NativeWallBody; public bool IncludeNonVisible; public bool SawDetailCondition; // a node was judged below a detail-level condition + public Dictionary? ModelFilters; + public bool? HasRootMappedSource; public int BlockStart, BlockEnd; // this block's payload bounds (plane scan) public int LastEdgeEnd; // pos after the last decoded Edge public List<(ushort Cls, int V)> Queue = new(); @@ -101,6 +104,7 @@ private sealed class Cur public Dictionary ClassWalked = new(); public Dictionary TagBase = new(); public List DebugItemStarts = new(); + public ResyncUndo? ProbeUndo; // Grammar-first tail harvest: face-handle -> surface pairs recovered from unwalked regions // (post-gap objects belong to queue entries that never got enqueued). @@ -337,6 +341,9 @@ internal sealed class EdgeRec /// free form faces (see ). /// public bool FreeformShared; + public bool HasAuthoredInterior => (MeshRawEdgePoints && RawInterior != null && !FreeformShared + ? RawInterior : FreeformInterior).Count > 0; + private List FreeformInterior => MeshStoredEdgePoints ? AuthoredInterior ?? Interior : Interior; /// /// The points of the edge for the Revit decoder in order: start, interior points, end. /// @@ -358,7 +365,7 @@ public List AuthoredPoints() public List FreeformPoints() { var points = new List(Interior.Count + 2) { MeshStoredEdgePoints ? AuthoredStart ?? Start : Start }; - points.AddRange(MeshStoredEdgePoints ? AuthoredInterior ?? Interior : Interior); + points.AddRange(FreeformInterior); points.Add(MeshStoredEdgePoints ? AuthoredEndP ?? EndP : EndP); return points; } @@ -463,10 +470,16 @@ public List FreeformPoints() // (a cache of planes only is the planar reader's) if (curved && !faces.Any(entry => c.DirectSurfaceByFace[(uint)entry.item.V].Kind == SurfKind.Cylinder)) return null; - if (c.Edges.Any(edge => !edge.HasEndpoints || edge.FaceA == edge.FaceB + var edgeCounts = new Dictionary(faceHandles.Count); + foreach (var edge in c.Edges) + { + if (!edge.HasEndpoints || edge.FaceA == edge.FaceB || !faceHandles.Contains(edge.FaceA) || !faceHandles.Contains(edge.FaceB)) - || faceHandles.Any(handle => c.Edges.Count(edge => - edge.FaceA == handle || edge.FaceB == handle) < 3)) + return null; + edgeCounts[edge.FaceA] = edgeCounts.GetValueOrDefault(edge.FaceA) + 1; + edgeCounts[edge.FaceB] = edgeCounts.GetValueOrDefault(edge.FaceB) + 1; + } + if (edgeCounts.Count != faceHandles.Count || edgeCounts.Values.Any(count => count < 3)) return null; if (literal) return BuildLiteralSpaceBoundary(c); if (weldFeet > 0) RegisterSpaceWeldPoints(c); @@ -795,6 +808,8 @@ internal enum BodyMeasure { None, VisibleVolume, RawBodies, DirectionalRawSurfac public static GRepData? Parse(byte[] d, int blockStart, uint dataSize, bool nativeWallBody = false, bool requireCompleteWalk = false, bool measureSourceNodes = false, bool measureLighting = false, bool measureFills = false, BodyMeasure bodyMeasure = BodyMeasure.None) { + if (!requireCompleteWalk && !measureSourceNodes && !measureLighting && !measureFills && bodyMeasure == BodyMeasure.None) + return ParseCore(d, blockStart, dataSize, nativeWallBody, includeDetailLevels: true); var fine = ParseCore(d, blockStart, dataSize, nativeWallBody, requireCompleteWalk: requireCompleteWalk, measureSourceNodes: measureSourceNodes, measureLighting: measureLighting, measureFills: measureFills, bodyMeasure: bodyMeasure); if (fine is not { HasDetailLevelAlternatives: true }) return fine; @@ -842,9 +857,12 @@ internal static bool IsSameDetailLevelGeometry(GRepData fine, GRepData coarse) = && fine.Instances.Zip(coarse.Instances).All(pair => pair.First.SymbolElemId == pair.Second.SymbolElemId && pair.First.Transform.SequenceEqual(pair.Second.Transform)); + internal static GRepData? ParseNativeWallBodyCandidate(byte[] data, int start, uint size) + => ParseCore(data, start, size, nativeWallBody: true, includeDetailLevels: true, requireCylinderEdgeBounds: true); + private static GRepData? ParseCore(byte[] d, int blockStart, uint dataSize, bool nativeWallBody, bool includeNonVisible = false, bool requireCompleteWalk = false, bool measureSourceNodes = false, bool measureLighting = false, bool measureFills = false, - BodyMeasure bodyMeasure = BodyMeasure.None) + BodyMeasure bodyMeasure = BodyMeasure.None, bool includeDetailLevels = false, bool requireCylinderEdgeBounds = false) { int payloadStart = blockStart + 14; int payloadEnd = (int)Math.Min((long)blockStart + 16 + dataSize, d.Length); @@ -1020,15 +1038,12 @@ string Number(double value) => value.ToString("G17", } } } - var built = BuildGeometry(c, requireCompleteWalk, measureSourceNodes, measureLighting, measureFills, bodyMeasure); - if (built != null) - { - built.QueueClassCounts = c.Queue.GroupBy(item => item.Cls).ToDictionary(group => group.Key, group => group.Count()); - if (measureLighting && !built.QueueClassCounts.ContainsKey(GFaceClass)) built.LightingBodyMeasures = (0, 0, 0); - if (bodyMeasure != BodyMeasure.None && !built.QueueClassCounts.ContainsKey(GFaceClass)) built.SourceBodyMeasures = (0, 0, 0); - built.HasDetailLevelAlternatives = c.SawDetailCondition; - built.RootBoundingBox = ValidBox(c.RootBoundingBox) ? c.RootBoundingBox : null; - } + // BuildGeometry computes MeshEdgeBounds only when a directly decoded cylinder is present. + // The wall candidate must have these bounds on every face. + if (requireCylinderEdgeBounds && !c.DirectSurfaceByFace.Values.Any(surface => surface.Kind == SurfKind.Cylinder) + && !IsDecodeTracingEnabled()) + return null; + var built = BuildRepresentation(c, requireCompleteWalk, measureSourceNodes, measureLighting, measureFills, bodyMeasure); if (built != null && !includeNonVisible && t_detailLevel == 0 && c.Queue.Any(node => (node.Cls == SolidClass || ShouldAttachSymbolGeometry(node.Cls)) && c.ObjectGInfo.TryGetValue(node.V, out var info) && IsHiddenInstanceVariant(info.Flags))) @@ -1047,11 +1062,90 @@ string Number(double value) => value.ToString("G17", }); } if (MeshDiagPath != null) WriteMeshDiag(c, built, payloadEnd - blockStart); + if (includeDetailLevels && built is { HasDetailLevelAlternatives: true }) + { + // Detail conditions filter the decoded graph during geometry building. + // Full diagnostics also report the field walk for each representation. + bool replayDiagnostics = c.Debug || MeshDiagPath != null + || Environment.GetEnvironmentVariable("RVTIO_TOPO") is { Length: > 0 }; + try + { + var coarse = BuildAtLevel(CoarseDetailLevel); + if (!ReferenceEquals(built, coarse) && !IsSameDetailLevelGeometry(built, coarse)) built.Coarse = coarse; + var medium = BuildAtLevel(2); + if (!ReferenceEquals(built, medium) && !IsSameDetailLevelGeometry(built, medium)) built.Medium = medium; + } + finally { t_detailLevel = 0; } + + GRepData BuildAtLevel(int level) + { + // A walk can first diverge only at a filter it already reached at Fine. + if (!replayDiagnostics && c.ModelFilters != null + && c.ModelFilters.Values.All(filter => filter.Allows(FineDetailLevel) == filter.Allows(level))) + return built!; + t_detailLevel = level; + c.SawDetailCondition = false; + if (!replayDiagnostics) + foreach (var edge in c.Edges) + if (edge.RawInterior is { } raw) + { + // Tessellation rewrites the working points and their cached samples. + edge.Start = edge.RawStart; + edge.EndP = edge.RawEndP; + edge.Interior = raw; + edge.AuthoredStart = edge.AuthoredEndP = null; + edge.AuthoredInterior = null; + edge.SharedBoundaryPoints = null; + edge.FreeformShared = false; + } + return (replayDiagnostics ? ParseCore(d, blockStart, dataSize, nativeWallBody) : BuildRepresentation(c)) + ?? new GRepData(); + } + } + return built; + } + + private static GRepData? BuildRepresentation(Cur c, bool requireCompleteWalk = false, + bool measureSourceNodes = false, bool measureLighting = false, bool measureFills = false, + BodyMeasure bodyMeasure = BodyMeasure.None) + { + var built = BuildGeometry(c, requireCompleteWalk, measureSourceNodes, measureLighting, measureFills, bodyMeasure); + if (built == null) return null; + int faces = 0, edges = 0, solids = 0; + var counts = KeepStoredClassCounts ? new Dictionary() : null; + foreach (var (cls, _) in c.Queue) + { + switch (cls) + { + case GFaceClass: faces++; break; + case EdgeClass: edges++; break; + case SolidClass: solids++; break; + } + if (counts != null) counts[cls] = counts.GetValueOrDefault(cls) + 1; + } + built.QueueSummary = (faces, edges, solids); + built.QueueClassCounts = counts; + if (faces == 0) + { + if (measureLighting) built.LightingBodyMeasures = (0, 0, 0); + if (bodyMeasure != BodyMeasure.None) built.SourceBodyMeasures = (0, 0, 0); + } + built.HasDetailLevelAlternatives = c.SawDetailCondition; + built.RootBoundingBox = ValidBox(c.RootBoundingBox) ? c.RootBoundingBox : null; return built; } + /// Keep per-class object counts for the IFC type key diagnostics. + private static readonly bool KeepStoredClassCounts = Environment.GetEnvironmentVariable("RVTIO_TYPEKEY_DIAG") is { Length: > 0 }; + private static readonly string? MeshDiagPath = Environment.GetEnvironmentVariable("RVTIO_MESH_DIAG") is { Length: > 0 } meshDiag ? meshDiag : null; + + internal static bool IsDecodeTracingEnabled() => MeshDiagPath != null + || Environment.GetEnvironmentVariable("RVTIO_GREPV2_DBG") == "1" + || Environment.GetEnvironmentVariable("RVTIO_GREPV2_DBG_ID") is { Length: > 0 } + || Environment.GetEnvironmentVariable("RVTIO_TOPO") is { Length: > 0 } + || Environment.GetEnvironmentVariable("RVTIO_GREP_SLOW") is { Length: > 0 }; private static readonly object MeshDiagLock = new(); private static readonly HashSet MeshDiagSeen = new(); private static readonly HashSet FacetedTopologyClasses = MeshDiagPath == null ? [] @@ -1270,14 +1364,17 @@ private static void WalkQueueItem(Cur c, int qi) c.CurrentObjectClass = cls; var qf = TfBlockDeserializer.SerializationFields(cls); if (qf == null) throw Stop; - // Blob-headed items: refresh the class's tag base (tag = base + ordinal). - if (qf.Count > 0 && qf[0].Name == "m_GInfo" && c.CanRead(16)) + if (c.ProbeUndo is null or { TrackTagBase: true }) { - int tag0 = BitConverter.ToInt32(c.D, c.Pos); - if (tag0 >= 0 && tag0 < 0x100000) - c.TagBase[cls] = tag0 - c.ClassWalked.GetValueOrDefault(cls); + // Blob-headed items: refresh the class's tag base (tag = base + ordinal). + if (qf.Count > 0 && qf[0].Name == "m_GInfo" && c.CanRead(16)) + { + int tag0 = BitConverter.ToInt32(c.D, c.Pos); + if (tag0 >= 0 && tag0 < 0x100000) + c.TagBase[cls] = tag0 - c.ClassWalked.GetValueOrDefault(cls); + } + SetProbeValue(c.ClassWalked, cls, c.ClassWalked.GetValueOrDefault(cls) + 1, c.ProbeUndo?.ClassWalked); } - c.ClassWalked[cls] = c.ClassWalked.GetValueOrDefault(cls) + 1; if (MeshDiagPath != null && FacetedTopologyClasses.Contains(cls)) c.FtWalked[cls] = c.FtWalked.GetValueOrDefault(cls) + 1; if (cls == 1589) // Face -> walk schema, record handle + surface class @@ -1299,8 +1396,8 @@ private static void WalkQueueItem(Cur c, int qi) if (c.Queue[k].Cls is 522 or 983 or 763 or 3489 or 3881 or 2158 or 3576 or 2602 or 3954) { surf = c.Queue[k].Cls; - c.SurfaceOwnerByQueueIndex[k] = (uint)v; - c.SurfaceOwnerByHandle[(uint)c.Queue[k].V] = (uint)v; + SetProbeValue(c.SurfaceOwnerByQueueIndex, k, (uint)v, c.ProbeUndo?.SurfaceOwnerByQueueIndex); + SetProbeValue(c.SurfaceOwnerByHandle, (uint)c.Queue[k].V, (uint)v, c.ProbeUndo?.SurfaceOwnerByHandle); break; } c.SurfClasses.Add(surf); @@ -1863,7 +1960,53 @@ private static void CaptureSurface(Cur c, int queueIndex, uint surfaceHandle, Su if (surface.Kind == SurfKind.Unknown) return; if (c.SurfaceOwnerByQueueIndex.TryGetValue(queueIndex, out uint faceHandle) || c.SurfaceOwnerByHandle.TryGetValue(surfaceHandle, out faceHandle)) - c.DirectSurfaceByFace[faceHandle] = surface; + SetProbeValue(c.DirectSurfaceByFace, faceHandle, surface, c.ProbeUndo?.DirectSurfaceByFace); + } + + private sealed class ResyncUndo + { + public bool TrackTagBase; + public readonly List<(ushort Key, int Previous, bool Existed)> ClassWalked = []; + public readonly List<(uint Key, uint Previous, bool Existed)> SurfaceOwnerByHandle = []; + public readonly List<(int Key, uint Previous, bool Existed)> SurfaceOwnerByQueueIndex = []; + public readonly List<(uint Key, SurfaceRec Previous, bool Existed)> DirectSurfaceByFace = []; + public readonly List<(uint Key, bool Previous, bool Existed)> FaceHasFirstLoop = []; + public readonly List LastLoops = []; + + public void Restore(Cur c) + { + RestoreProbeValues(c.ClassWalked, ClassWalked); + RestoreProbeValues(c.SurfaceOwnerByHandle, SurfaceOwnerByHandle); + RestoreProbeValues(c.SurfaceOwnerByQueueIndex, SurfaceOwnerByQueueIndex); + RestoreProbeValues(c.DirectSurfaceByFace, DirectSurfaceByFace); + RestoreProbeValues(c.FaceHasFirstLoop, FaceHasFirstLoop); + for (int i = LastLoops.Count - 1; i >= 0; i--) + c.LastLoops.Remove(LastLoops[i]); + LastLoops.Clear(); + } + } + + private static void SetProbeValue(Dictionary map, TKey key, TValue value, + List<(TKey Key, TValue Previous, bool Existed)>? writes) where TKey : notnull + { + if (writes != null) + { + bool existed = map.TryGetValue(key, out var previous); + writes.Add((key, previous!, existed)); + } + map[key] = value; + } + + private static void RestoreProbeValues(Dictionary map, + List<(TKey Key, TValue Previous, bool Existed)> writes) where TKey : notnull + { + for (int i = writes.Count - 1; i >= 0; i--) + { + var (key, previous, existed) = writes[i]; + if (existed) map[key] = previous; + else map.Remove(key); + } + writes.Clear(); } /// @@ -1879,48 +2022,48 @@ private static bool TryResync(Cur c, ref int qi) if (!byClass.TryGetValue(c.Queue[i].Cls, out var l)) byClass[c.Queue[i].Cls] = l = new(); l.Add(i); } + ResyncUndo? undo = null; - bool DryRun(int off, int qj) + bool DryRun(int off, int qj, bool preserveTagJumpMap = false) { var snap = (Pos: c.Pos, Q: c.Queue.Count, FO: c.FaceOrder.Count, SC: c.SurfClasses.Count, E: c.Edges.Count, PM: c.PolyMeshes.Count, WS: c.WalkedSurfaces.Count, FC: c.FaceCount, - Sym: c.SymbolId, Trf: c.InstTrf, LE: c.LastEdgeEnd, - Ins: new List(c.Instances), - CW: new Dictionary(c.ClassWalked), TB: new Dictionary(c.TagBase), - SO: new Dictionary(c.SurfaceOwnerByHandle), - SQ: new Dictionary(c.SurfaceOwnerByQueueIndex), - DS: new Dictionary(c.DirectSurfaceByFace), - FL: new Dictionary(c.FaceHasFirstLoop), LL: new HashSet(c.LastLoops)); + Sym: c.SymbolId, Trf: c.InstTrf, LE: c.LastEdgeEnd, Ins: c.Instances.Count); + // Preserve the active tag-jump enumerator. The remaining probes only validate the payload. + var savedTagBase = preserveTagJumpMap ? new Dictionary(c.TagBase) : null; + c.ProbeUndo = undo ??= new ResyncUndo(); + undo.TrackTagBase = preserveTagJumpMap; 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); } catch (DecodeStop) { ok = false; } + finally { c.ProbeUndo = null; } // Roll the dry run back - the caller's loop re-walks for real. c.Pos = snap.Pos; + // Only existing queue entries were visited. Their new children are the appended suffix. + for (int i = c.QueueLinks.Count - 1; i >= snap.Q; i--) + { + var (parent, field) = c.QueueLinks[i]; + if (parent >= 0 && (c.Debug || field == "m_oConditions")) + { + var children = c.QueueChildren[parent]; + children.RemoveAt(children.Count - 1); + } + } c.Queue.RemoveRange(snap.Q, c.Queue.Count - snap.Q); if (c.QueueLinks.Count > snap.Q) c.QueueLinks.RemoveRange(snap.Q, c.QueueLinks.Count - snap.Q); - foreach (int key in c.QueueChildren.Keys.Where(key => key >= snap.Q).ToArray()) - c.QueueChildren.Remove(key); - foreach (var children in c.QueueChildren.Values) - children.RemoveAll(child => child >= snap.Q); - foreach (int key in c.QueueInts.Keys.Where(key => key >= snap.Q).ToArray()) c.QueueInts.Remove(key); - foreach (int key in c.QueueDoubles.Keys.Where(key => key >= snap.Q).ToArray()) c.QueueDoubles.Remove(key); - foreach (int key in c.QueueBytes.Keys.Where(key => key >= snap.Q).ToArray()) c.QueueBytes.Remove(key); c.FaceOrder.RemoveRange(snap.FO, c.FaceOrder.Count - snap.FO); c.SurfClasses.RemoveRange(snap.SC, c.SurfClasses.Count - snap.SC); c.Edges.RemoveRange(snap.E, c.Edges.Count - snap.E); c.PolyMeshes.RemoveRange(snap.PM, c.PolyMeshes.Count - snap.PM); c.WalkedSurfaces.RemoveRange(snap.WS, c.WalkedSurfaces.Count - snap.WS); c.FaceCount = snap.FC; c.SymbolId = snap.Sym; c.InstTrf = snap.Trf; - c.Instances = snap.Ins; + c.Instances.RemoveRange(snap.Ins, c.Instances.Count - snap.Ins); c.LastEdgeEnd = snap.LE; c.CapEdge = null; - c.ClassWalked = snap.CW; c.TagBase = snap.TB; - c.SurfaceOwnerByHandle = snap.SO; c.DirectSurfaceByFace = snap.DS; - c.SurfaceOwnerByQueueIndex = snap.SQ; - c.FaceHasFirstLoop = snap.FL; c.LastLoops = snap.LL; - foreach (int key in c.SpaceEdgeLoops.Keys.Where(key => key >= snap.Q).ToArray()) c.SpaceEdgeLoops.Remove(key); + if (savedTagBase != null) c.TagBase = savedTagBase; + undo.Restore(c); return ok && want >= 6; } @@ -1928,6 +2071,13 @@ bool DryRun(int off, int qj) int anchorCap = Math.Max(160, (c.BlockEnd - c.BlockStart) / 1024); for (int off = c.Pos + 1; off + 16 <= c.BlockEnd && anchorsTried < anchorCap; off++) { + // Every accepted anchor flag ends in 04, at the first flag byte on disk. + if (BitConverter.IsLittleEndian) + { + int skip = c.D.AsSpan(off + 12, c.BlockEnd - off - 15).IndexOf((byte)0x04); + if (skip < 0) break; + off += skip; + } // GInfoBlob anchor: [tag][ctrl=0][gstyle][known flags]. if (BitConverter.ToInt32(c.D, off + 4) != 0) continue; uint fl = BitConverter.ToUInt32(c.D, off + 12); @@ -1940,7 +2090,9 @@ bool DryRun(int off, int qj) // Tag-jump first: the anchor's tag maps to a queue ordinal per class. if (tag >= 0) - foreach (var (cls, baseT) in c.TagBase) + { + var tagJumpMap = c.TagBase; + foreach (var (cls, baseT) in tagJumpMap) { if (!byClass.TryGetValue(cls, out var lst)) continue; int ord = tag - baseT; @@ -1949,10 +2101,12 @@ bool DryRun(int off, int qj) if (ord >= 0 && ord < lst.Count) { int qj = lst[ord]; - if (qj > qi && qj < c.Queue.Count && DryRun(off, qj)) + if (qj > qi && qj < c.Queue.Count + && DryRun(off, qj, ReferenceEquals(tagJumpMap, c.TagBase))) { c.Pos = off; qi = qj - 1; return true; } } } + } // Fallback: window scan over the next pending items - near anchors only (distant // windows produced wrong relocks; distant recovery is tag-jump's job). @@ -2308,9 +2462,12 @@ private static void ReadPtr(Cur c, string? field = null) { int v = c.U32(); if (field == "m_pFirstLoop" && c.CurrentObjectClass == 1589) - c.FaceHasFirstLoop[(uint)c.CurrentObjectHandle] = v != 0; + SetProbeValue(c.FaceHasFirstLoop, (uint)c.CurrentObjectHandle, v != 0, c.ProbeUndo?.FaceHasFirstLoop); else if (field == "m_nextLoop" && v == 0 && c.CurrentObjectClass is 1254 or 1257 && c.CurrentQueueIndex >= 0) - c.LastLoops.Add(c.CurrentQueueIndex); + { + if (c.LastLoops.Add(c.CurrentQueueIndex)) + c.ProbeUndo?.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; @@ -2465,18 +2622,20 @@ private static bool ValidBox(double[]? box) => box is { Length: 6 } } } - foreach (var rawEdge in c.Edges) { rawEdge.RawStart = rawEdge.Start; rawEdge.RawEndP = rawEdge.EndP; rawEdge.RawInterior = rawEdge.Interior.ToList(); } + foreach (var rawEdge in c.Edges) { rawEdge.RawStart = rawEdge.Start; rawEdge.RawEndP = rawEdge.EndP; rawEdge.RawInterior = rawEdge.Interior; } // Per face handle: collect its edge UV segments (in that face's own surface frame). var byFace = new Dictionary>(); var cylinderLoopEdges = new Dictionary>(); var sourceEdgesByHandle = EdgesByHandle(c); - foreach (var (face, indices) in CompleteFaceLoops(c)) - if (c.NativeWallBody && c.DirectSurfaceByFace.TryGetValue(face, out var sourceSurface) && sourceSurface.Kind == SurfKind.Cylinder - && TryGetFaceLoopEdges(c, face, indices, sourceEdgesByHandle) is { } sourceLoopEdges) - cylinderLoopEdges[face] = sourceLoopEdges.Select(edge => edge.Handle).ToHashSet(); + var completeLoops = CompleteFaceLoops(c); + if (c.NativeWallBody) + foreach (var (face, indices) in completeLoops) + if (c.DirectSurfaceByFace.TryGetValue(face, out var sourceSurface) && sourceSurface.Kind == SurfKind.Cylinder + && TryGetFaceLoopEdges(c, face, indices, sourceEdgesByHandle) is { } sourceLoopEdges) + cylinderLoopEdges[face] = sourceLoopEdges.Select(edge => edge.Handle).ToHashSet(); var sharedCylinderEdges = cylinderLoopEdges.Values.SelectMany(handles => handles).ToHashSet(); var meshEdgeBounds = c.DirectSurfaceByFace.Values.Any(surface => surface.Kind == SurfKind.Cylinder) - ? ReadFaceEdgeBounds(c) : new Dictionary(); + ? ReadFaceEdgeBounds(c, completeLoops, sourceEdgesByHandle) : new Dictionary(); var meshArcsByFace = new Dictionary>(); var arcEdges = new HashSet(); void SampleCircularEdge(EdgeRec edge, SurfaceRec firstSurface, SurfaceRec secondSurface, bool resample) @@ -2523,23 +2682,22 @@ void CollectFaceSegments(bool captureWorld = false) { foreach (var e in c.Edges) { - var points = new List(e.Interior.Count + 2) { e.Start }; - points.AddRange(e.Interior); - points.Add(e.EndP); - for (int i = 0; i + 1 < points.Count; i++) + bool firstFace = !cylinderLoopEdges.TryGetValue(e.FaceA, out var firstLoopEdges) || firstLoopEdges.Contains(e.Handle); + bool secondFace = !cylinderLoopEdges.TryGetValue(e.FaceB, out var secondLoopEdges) || secondLoopEdges.Contains(e.Handle); + var a = e.Start; + for (int i = 0; i <= e.Interior.Count; i++) { - var a = points[i]; - var b = points[i + 1]; - if (!cylinderLoopEdges.TryGetValue(e.FaceA, out var firstLoopEdges) || firstLoopEdges.Contains(e.Handle)) + var b = i < e.Interior.Count ? e.Interior[i] : e.EndP; + if (firstFace) Add(e.FaceA, a.UA, a.VA, b.UA, b.VA, e, i, captureWorld); - if (!cylinderLoopEdges.TryGetValue(e.FaceB, out var secondLoopEdges) || secondLoopEdges.Contains(e.Handle)) + if (secondFace) Add(e.FaceB, a.UB, a.VB, b.UB, b.VB, e, i, captureWorld); + a = b; } } } CollectFaceSegments(captureWorld: true); - var authoredSamplingEdges = byFace.ToDictionary(pair => pair.Key, - pair => pair.Value.ToList()); + var authoredSamplingEdges = byFace; // Analytic face tessellation uses the U/V coordinates of every serialized trim vertex as // its interior grid. A grid line can intersect another topological edge between two @@ -2600,15 +2758,22 @@ void CollectFaceSegments(bool captureWorld = false) true); } + List? splitFractions = null; foreach (var edge in c.Edges) { - var points = new List(edge.Interior.Count + 2) { edge.Start }; - points.AddRange(edge.Interior); - points.Add(edge.EndP); bool periodicA = handleToSurf.TryGetValue(edge.FaceA, out var surfaceA) && surfaceA.Kind is SurfKind.Cylinder or SurfKind.Cone or SurfKind.Rev; bool periodicB = handleToSurf.TryGetValue(edge.FaceB, out var surfaceB) && surfaceB.Kind is SurfKind.Cylinder or SurfKind.Cone or SurfKind.Rev; + bool splitA = trimGrids.TryGetValue(edge.FaceA, out var gridA); + bool splitB = trimGrids.TryGetValue(edge.FaceB, out var gridB); + if (!periodicA && !periodicB && !splitA && !splitB + && (edge.SharedBoundaryPoints == null || edge.SharedBoundaryPoints.Count == edge.Interior.Count + 2)) + continue; + + var points = new List(edge.Interior.Count + 2) { edge.Start }; + points.AddRange(edge.Interior); + points.Add(edge.EndP); if (periodicA || periodicB) { for (int index = 1; index < points.Count; index++) @@ -2628,11 +2793,12 @@ void CollectFaceSegments(bool captureWorld = false) var refined = new List { points[0] }; var sharedRefined = edge.SharedBoundaryPoints is { } sourceShared && sourceShared.Count == points.Count ? new List { sourceShared[0] } : null; + var fractions = splitFractions ??= new(); for (int index = 0; index + 1 < points.Count; index++) { var first = points[index]; var second = points[index + 1]; - var fractions = new SortedSet(); + fractions.Clear(); void AddFractions(double start, double end, IReadOnlyList samples, bool periodic) { @@ -2653,20 +2819,24 @@ void AddFractions(double start, double end, } } } - if (trimGrids.TryGetValue(edge.FaceA, out var gridA)) + if (splitA) { AddFractions(first.UA, second.UA, gridA.U, gridA.PeriodicU); if (gridA.SplitV) AddFractions(first.VA, second.VA, gridA.V, periodic: false); } - if (trimGrids.TryGetValue(edge.FaceB, out var gridB)) + if (splitB) { AddFractions(first.UB, second.UB, gridB.U, gridB.PeriodicU); if (gridB.SplitV) AddFractions(first.VB, second.VB, gridB.V, periodic: false); } + fractions.Sort(); + double previousFraction = 0; foreach (double fraction in fractions) { + if (fraction == previousFraction) continue; + previousFraction = fraction; refined.Add(new EdgeUV { UA = first.UA + (second.UA - first.UA) * fraction, @@ -2687,12 +2857,15 @@ void AddFractions(double start, double end, } edge.Start = refined[0]; edge.EndP = refined[^1]; - edge.Interior = refined.Skip(1).SkipLast(1).ToList(); + edge.Interior = refined.GetRange(1, refined.Count - 2); edge.SharedBoundaryPoints = sharedRefined; } - byFace.Clear(); - CollectFaceSegments(); + if (splitFractions != null) + { + byFace = new(); + CollectFaceSegments(); + } var gd = new GRepData { @@ -2757,7 +2930,7 @@ void AddFractions(double start, double end, var inactiveBodyFaceHandles = bodyFaceHandles.Where(deadFaces.Contains).ToArray(); bodyFaceHandles.ExceptWith(deadFaces); displayFaceHandles.ExceptWith(deadFaces); - var loopsByFace = c.ExactPlanarSpaceBoundary && !c.CurvedSpaceBoundary ? new Dictionary>() : CompleteFaceLoops(c); + var loopsByFace = c.ExactPlanarSpaceBoundary && !c.CurvedSpaceBoundary ? new Dictionary>() : completeLoops; if (bodyMeasure != BodyMeasure.None) { var selected = lightingFaceHandles ?? bodyFaceHandles; @@ -2777,12 +2950,11 @@ void AddFractions(double start, double end, // The rings of an exact space boundary come from its segment graph; its serialized loops // only name the bounds of the IfcFace Revit writes for each Face (one bound per // loop, however many disjoint regions the Face owns). - var spaceLoopsByFace = c.ExactPlanarSpaceBoundary && !c.CurvedSpaceBoundary ? CompleteFaceLoops(c) : null; + var spaceLoopsByFace = c.ExactPlanarSpaceBoundary && !c.CurvedSpaceBoundary ? completeLoops : null; if (Environment.GetEnvironmentVariable("RVTIO_TOPO") is { Length: > 0 } topologyPath && (Environment.GetEnvironmentVariable("RVTIO_TOPO_EID") is not { Length: > 0 } topologyEids || topologyEids.Split(',').Contains(c.ElementId.ToString()))) DumpTopology(c, handleToSurf, bodyFaceHandles, spaceLoopsByFace ?? loopsByFace, topologyPath); - Dictionary? edgeByHandle = null; var chainFaces = new HashSet(); var chainEdges = new HashSet(); if (c.Debug) @@ -2837,8 +3009,8 @@ void AddFractions(double start, double end, : displayFaceHandles.Where(handle => geometryNodeByFace.TryGetValue(handle, out var owner) && displayNodeSet.Contains(owner.Node)).ToHashSet(); var nodeMeasures = new List(); gd.MeshNodes = BuildNodes(c, handleToSurf, displayFaces.Count > 0 ? bodyFaceHandles.Concat(displayFaces).ToHashSet() : bodyFaceHandles, - inactiveBodyFaceHandles, loopsByFace, geometryNodeByFace, nodeOrders, displayFaces.Count > 0 ? displayOnlyNodes : null, nodeMeasures, - measureSourceNodes: measureSourceNodes); + inactiveBodyFaceHandles, loopsByFace, sourceEdgesByHandle, geometryNodeByFace, nodeOrders, + displayFaces.Count > 0 ? displayOnlyNodes : null, nodeMeasures, measureSourceNodes); if (nodeMeasures.Count > 0) gd.NodeMeasures = nodeMeasures; } if (displayOnlyNodes.Count > 0) gd.DisplayOnlyNodes = displayOnlyNodes; @@ -3047,8 +3219,7 @@ void Bump(double[] p) List>? loopRings = null; if (loopsByFace.TryGetValue(kv.Key, out var faceLoops)) { - edgeByHandle ??= EdgesByHandle(c); - loopRings = TryOrderLoopRings(c, kv.Key, faceLoops, edgeByHandle, ToPlane(surf), segs, chainEdges); + loopRings = TryOrderLoopRings(c, kv.Key, faceLoops, sourceEdgesByHandle, ToPlane(surf), segs, chainEdges); if (loopRings == null) segs.Clear(); else chainFaces.Add(kv.Key); } if (loopRings == null) @@ -3079,8 +3250,7 @@ void Bump(double[] p) List>? spaceSourceLoops = null; if (spaceLoopsByFace != null && spaceLoopsByFace.TryGetValue(kv.Key, out var spaceFaceLoops)) { - edgeByHandle ??= EdgesByHandle(c); - spaceSourceLoops = TryOrderLoopRings(c, kv.Key, spaceFaceLoops, edgeByHandle, ToPlane(surf), [], []); + spaceSourceLoops = TryOrderLoopRings(c, kv.Key, spaceFaceLoops, sourceEdgesByHandle, ToPlane(surf), [], []); } // One serialized Face handle can own several disconnected coplanar regions. Only a @@ -3389,15 +3559,21 @@ internal static List BuildTopologicalSolids( if (faces.Count != faceHandles.Count) throw new ArgumentException("Every emitted face must have a serialized Face handle."); - var edges = serializedEdges.ToList(); var indicesByHandle = Enumerable.Range(0, faceHandles.Count) .GroupBy(index => faceHandles[index]) .ToDictionary(group => group.Key, group => group.ToList()); var parent = Enumerable.Range(0, faces.Count).ToArray(); int Find(int index) { - if (parent[index] != index) parent[index] = Find(parent[index]); - return parent[index]; + int root = index; + while (parent[root] != root) root = parent[root]; + while (index != root) + { + int next = parent[index]; + parent[index] = root; + index = next; + } + return root; } void Union(int first, int second) { @@ -3410,13 +3586,23 @@ void Union(int first, int second) Union(indices[0], index); static bool ValidHandle(uint handle) => handle != 0 && handle != 0xFFFFFFFF; - foreach (var edge in edges) + var connected = new HashSet(); + var dangling = new HashSet(); + foreach (var edge in serializedEdges) { - if (!ValidHandle(edge.FaceA) || !ValidHandle(edge.FaceB) - || !indicesByHandle.TryGetValue(edge.FaceA, out var first) - || !indicesByHandle.TryGetValue(edge.FaceB, out var second)) - continue; - Union(first[0], second[0]); + indicesByHandle.TryGetValue(edge.FaceA, out var first); + indicesByHandle.TryGetValue(edge.FaceB, out var second); + if (first != null && second != null && ValidHandle(edge.FaceA) && ValidHandle(edge.FaceB)) + { + Union(first[0], second[0]); + connected.Add(edge.FaceA); + connected.Add(edge.FaceB); + } + else + { + if (first != null) dangling.Add(edge.FaceA); + if (second != null) dangling.Add(edge.FaceB); + } } var solids = new List(); @@ -3425,13 +3611,9 @@ void Union(int first, int second) var faceIndices = component.OrderBy(index => index).ToList(); if (faceIndices.Count < 4) continue; - var handles = faceIndices.Select(index => faceHandles[index]).ToHashSet(); - bool hasTopology = handles.All(handle => edges.Any(edge => - edge.FaceA == handle || edge.FaceB == handle)); - bool topologicallyClosed = hasTopology && edges - .Where(edge => handles.Contains(edge.FaceA) || handles.Contains(edge.FaceB)) - .All(edge => ValidHandle(edge.FaceA) && ValidHandle(edge.FaceB) - && handles.Contains(edge.FaceA) && handles.Contains(edge.FaceB)); + // Every valid edge between emitted faces joined their components above. + bool topologicallyClosed = faceIndices.All(index => + connected.Contains(faceHandles[index]) && !dangling.Contains(faceHandles[index])); bool closed = topologicallyClosed || IsExactClosedShell(faces, faceIndices); solids.Add(new GRepSolid { FaceIndices = faceIndices, IsClosed = closed }); } @@ -3578,6 +3760,49 @@ internal static bool IsPhysicalBodySurface(uint flags) internal static uint NodeSurfaceFlags(int nodeClass, bool exactPlanarSpaceBoundary, uint flags) => exactPlanarSpaceBoundary && nodeClass == 1589 || nodeClass == 2038 ? flags & ~0x40000000u : flags; + private readonly record struct ModelFilter(int DetailLevels, bool HasDetail, bool HasDirection, bool AllEvaluated) + { + public bool Allows(int detail) => (DetailLevels & (1 << detail)) != 0; + } + + private static ModelFilter ReadModelFilter(Cur c, int parent) + { + int allowed = (1 << CoarseDetailLevel) | (1 << 2) | (1 << FineDetailLevel); + bool hasDetail = false, hasDirection = false, allEvaluated = true; + if (c.QueueChildren.TryGetValue(parent, out var children)) + foreach (int child in children) + { + if (child < 0 || child >= c.Queue.Count || child >= c.QueueLinks.Count + || c.QueueLinks[child].Field != "m_oConditions") continue; + bool? negated = c.QueueBytes.TryGetValue(child, out var values) + && values.TryGetValue("m_negateDirCondition", out var bytes) + && bytes.Count > 0 ? bytes[0] != 0 : null; + c.QueueInts.TryGetValue(child, out var intValues); + int? IntField(string name) => intValues != null && intValues.TryGetValue(name, out int value) ? value : null; + var condition = new SerializedModelCondition(c.Queue[child].Cls, negated, + IntField("m_comp"), IntField("m_param"), IntField("m_value")); + hasDetail |= IsDetailCondition(condition); + hasDirection |= condition.Class == 1996; + allEvaluated &= IsEvaluatedModelCondition(condition); + for (int detail = CoarseDetailLevel; detail <= FineDetailLevel; detail++) + if (!AllowsUncutModelCondition(condition, detail)) allowed &= ~(1 << detail); + } + return new ModelFilter(allowed, hasDetail, hasDirection, allEvaluated); + } + + private static bool HasRootMappedSource(Cur c) + { + foreach (var instance in c.Instances) + { + int owner = instance.OwnerQueueIndex; + if (owner >= 0 && owner < c.QueueLinks.Count && owner < c.Queue.Count + && c.QueueLinks[owner].ParentQueueIndex < 0 + && (!c.ObjectGInfo.TryGetValue(c.Queue[owner].V, out var info) || IsPhysicalBodySurface(info.Flags))) + return true; + } + return false; + } + /// Evaluate the serialized ownership path of a drawable GNode. private static bool IsPhysicalModelBranch(Cur c, int nodeQueueIndex, bool allowDisplaySurface = false, bool forLightingQuantity = false) { @@ -3613,38 +3838,14 @@ private static bool IsPhysicalModelBranch(Cur c, int nodeQueueIndex, bool allowD } if (ancestorItem.Cls != 2015) continue; - var conditions = (c.QueueChildren.GetValueOrDefault(ancestor) ?? []) - .Where(child => child >= 0 && child < c.Queue.Count - && child < c.QueueLinks.Count - && c.QueueLinks[child].Field == "m_oConditions") - .Select(child => - { - bool? negated = c.QueueBytes.TryGetValue(child, out var values) - && values.TryGetValue("m_negateDirCondition", out var bytes) - && bytes.Count > 0 ? bytes[0] != 0 : null; - int? IntField(string name) => - c.QueueInts.TryGetValue(child, out var intValues) - && intValues.TryGetValue(name, out int value) - ? value : null; - return new SerializedModelCondition( - c.Queue[child].Cls, negated, - IntField("m_comp"), IntField("m_param"), - IntField("m_value")); - }).ToList(); - if (conditions.Any(condition => condition.Class is 1999 or 2002 && condition.Parameter == 3)) - c.SawDetailCondition = true; - bool hasRootMappedSource = c.Instances.Any(instance => - instance.OwnerQueueIndex >= 0 - && instance.OwnerQueueIndex < c.QueueLinks.Count - && instance.OwnerQueueIndex < c.Queue.Count - && c.QueueLinks[instance.OwnerQueueIndex].ParentQueueIndex < 0 - && (!c.ObjectGInfo.TryGetValue( - c.Queue[instance.OwnerQueueIndex].V, out var instanceInfo) - || IsPhysicalBodySurface(instanceInfo.Flags))); - // Lighting quantities include solids from every direction at the selected detail level. - body = (forLightingQuantity || IsPhysicalBodyGeometryState(graphicalGeometryState, hasRootMappedSource, conditions)) - && AllowsFineUncutModelBranch(conditions) - && (!allowDisplaySurface || conditions.All(IsEvaluatedModelCondition)); + var filters = c.ModelFilters ??= new(); + if (!filters.TryGetValue(ancestor, out var filter)) + filters.Add(ancestor, filter = ReadModelFilter(c, ancestor)); + c.SawDetailCondition |= filter.HasDetail; + bool hasRootMappedSource = c.HasRootMappedSource ??= HasRootMappedSource(c); + body = (forLightingQuantity || IsPhysicalBodyGeometryState(graphicalGeometryState, hasRootMappedSource, filter.HasDirection, filter.HasDetail)) + && filter.Allows(t_detailLevel == 0 ? FineDetailLevel : t_detailLevel) + && (!allowDisplaySurface || filter.AllEvaluated); } return body; } @@ -3673,30 +3874,39 @@ internal static bool IsEvaluatedModelCondition(SerializedModelCondition conditio internal static bool IsPhysicalBodyGeometryState( bool graphicalState, bool hasRootMappedSource, IReadOnlyCollection conditions) - => !(conditions.Any(condition => condition.Class == 1996) - && (graphicalState || hasRootMappedSource)) - && (!graphicalState || !conditions.Any(condition => - (condition.Class is 1999 or 2002) && condition.Parameter == 3)); + => IsPhysicalBodyGeometryState(graphicalState, hasRootMappedSource, + conditions.Any(condition => condition.Class == 1996), conditions.Any(IsDetailCondition)); + + private static bool IsPhysicalBodyGeometryState(bool graphicalState, bool hasRootMappedSource, + bool hasDirectionCondition, bool hasDetailCondition) + => !(hasDirectionCondition && (graphicalState || hasRootMappedSource)) + && !(hasDetailCondition && graphicalState); /// A condition of a serialized model: class, negation, comparison, parameter and value. internal readonly record struct SerializedModelCondition( ushort Class, bool? Negated, int? Comparison, int? Parameter, int? Value); + private static bool IsDetailCondition(SerializedModelCondition condition) + => condition.Class is 1999 or 2002 && condition.Parameter == 3; + /// /// IFC is exported as an uncut three-dimensional model at Revit's Fine detail level. Revit /// serializes cut and detail alternatives as sibling GFilter branches. /// internal static bool AllowsFineUncutModelBranch( IEnumerable conditions) - => conditions.All(condition => condition.Class switch + => conditions.All(condition => AllowsUncutModelCondition(condition, FineDetailLevel)); + + private static bool AllowsUncutModelCondition(SerializedModelCondition condition, int detail) + => condition.Class switch { 1995 => condition.Negated == true, 1999 or 2002 when condition.Parameter == 3 && condition.Comparison is int comparison && condition.Value is int value - => CompareSerializedInteger(t_detailLevel == 0 ? FineDetailLevel : t_detailLevel, comparison, value), + => CompareSerializedInteger(detail, comparison, value), _ => true, - }); + }; /// /// The detail-level values a GConditionInt on parameter 3 compares against: Coarse 1, Medium 2, @@ -3987,50 +4197,46 @@ private static List ScanSurfacesGuided(byte[] d, int start, int end, { var res = new List(); int lim = Math.Min(end, d.Length); - static double[] V(byte[] b, int p) => new[] { BitConverter.ToDouble(b, p), BitConverter.ToDouble(b, p + 8), BitConverter.ToDouble(b, p + 16) }; - static double Len(double[] v) => Math.Sqrt(v[0] * v[0] + v[1] * v[1] + v[2] * v[2]); - static double Dot(double[] a, double[] b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; - static bool Unit(double[] v) => Math.Abs(Len(v) - 1) < 1e-9; - static bool Fin3(double[] v) => IsFinite(v[0]) && IsFinite(v[1]) && IsFinite(v[2]); + static Pt3 V(byte[] b, int p) => new(BitConverter.ToDouble(b, p), BitConverter.ToDouble(b, p + 8), BitConverter.ToDouble(b, p + 16)); + static bool Unit(Pt3 v) => Math.Abs(v.Norm - 1) < 1e-9; + static bool Fin3(Pt3 v) => IsFinite(v.X) && IsFinite(v.Y) && IsFinite(v.Z); // Surface payload = base Surface(523) fields FIRST: [m_Envelope: 4xf64 uv bounds] // [m_orientFlag: u8 in {0,1}], then the surface's own frame. - bool HasSurfPrefix(int p, out double[] env) + bool HasSurfPrefix(int p) { - env = new double[4]; if (p < 33) return false; - for (int k = 0; k < 4; k++) - { - env[k] = BitConverter.ToDouble(d, p - 33 + 8 * k); - if (!IsFinite(env[k])) return false; - } - byte orient = d[p - 1]; - return orient <= 1 && env[0] < env[2] && env[1] < env[3]; + double uMin = BitConverter.ToDouble(d, p - 33), vMin = BitConverter.ToDouble(d, p - 25); + double uMax = BitConverter.ToDouble(d, p - 17), vMax = BitConverter.ToDouble(d, p - 9); + return IsFinite(uMin) && IsFinite(vMin) && IsFinite(uMax) && IsFinite(vMax) + && d[p - 1] <= 1 && uMin < uMax && vMin < vMax; } + double[] ReadEnvelope(int p) => [BitConverter.ToDouble(d, p - 33), BitConverter.ToDouble(d, p - 25), + BitConverter.ToDouble(d, p - 17), BitConverter.ToDouble(d, p - 9)]; + bool TryPlane(int p, out SurfaceRec sr) { sr = default; - if (p + 72 > lim || !HasSurfPrefix(p, out var env)) return false; + if (p + 72 > lim || !HasSurfPrefix(p)) return false; var o = V(d, p); var x = V(d, p + 24); var y = V(d, p + 48); - if (!(Fin3(o) && Fin3(x) && Fin3(y) && Unit(x) && Unit(y) && Math.Abs(Dot(x, y)) < 1e-9)) return false; - sr = new SurfaceRec { Kind = SurfKind.Plane, O = o, X = x, Y = y, Env = env, Orient = d[p - 1] }; + if (!(Fin3(o) && Fin3(x) && Fin3(y) && Unit(x) && Unit(y) && Math.Abs(x.Dot(y)) < 1e-9)) return false; + sr = new SurfaceRec { Kind = SurfKind.Plane, O = o.ToArray(), X = x.ToArray(), Y = y.ToArray(), Env = ReadEnvelope(p), Orient = d[p - 1] }; return true; } bool TryFrame(int p, SurfKind kind, out SurfaceRec sr) { sr = default; - if (p + 104 > lim || !HasSurfPrefix(p, out var env)) return false; + if (p + 104 > lim || !HasSurfPrefix(p)) return false; var o = V(d, p); var x = V(d, p + 24); var y = V(d, p + 48); var z = V(d, p + 72); double r = BitConverter.ToDouble(d, p + 96); if (!(Fin3(o) && Fin3(x) && Fin3(y) && Fin3(z) && IsFinite(r))) return false; if (!(Unit(x) && Unit(y) && Unit(z))) return false; - if (Math.Abs(Dot(x, y)) > 1e-9 || Math.Abs(Dot(x, z)) > 1e-9 || Math.Abs(Dot(y, z)) > 1e-9) return false; - var cross = new[] { x[1] * y[2] - x[2] * y[1], x[2] * y[0] - x[0] * y[2], x[0] * y[1] - x[1] * y[0] }; - if (Math.Abs(Math.Abs(Dot(z, cross)) - 1) > 1e-6) return false; + if (Math.Abs(x.Dot(y)) > 1e-9 || Math.Abs(x.Dot(z)) > 1e-9 || Math.Abs(y.Dot(z)) > 1e-9) return false; + if (Math.Abs(Math.Abs(z.Dot(Pt3.Cross(x, y))) - 1) > 1e-6) return false; if (kind == SurfKind.Cylinder && !(Math.Abs(r) > 1e-4 && Math.Abs(r) < 1e5)) return false; if (kind == SurfKind.Cone && !(Math.Abs(r) > 1e-4 && Math.Abs(r) < 1.56)) return false; - sr = new SurfaceRec { Kind = kind, O = o, X = x, Y = y, Z = z, R = r, Env = env, Orient = d[p - 1] }; + sr = new SurfaceRec { Kind = kind, O = o.ToArray(), X = x.ToArray(), Y = y.ToArray(), Z = z.ToArray(), R = r, Env = ReadEnvelope(p), Orient = d[p - 1] }; return true; } @@ -4040,33 +4246,32 @@ bool TryFrame(int p, SurfKind kind, out SurfaceRec sr) bool TryRev(int p, out SurfaceRec sr) { sr = default; - if (p + 102 > lim || !HasSurfPrefix(p, out var env)) return false; + if (p + 102 > lim || !HasSurfPrefix(p)) return false; var o = V(d, p); var x = V(d, p + 24); var y = V(d, p + 48); var z = V(d, p + 72); if (!(Fin3(o) && Fin3(x) && Fin3(y) && Fin3(z))) return false; if (!(Unit(x) && Unit(y) && Unit(z))) return false; - if (Math.Abs(Dot(x, y)) > 1e-9 || Math.Abs(Dot(x, z)) > 1e-9 || Math.Abs(Dot(y, z)) > 1e-9) return false; + if (Math.Abs(x.Dot(y)) > 1e-9 || Math.Abs(x.Dot(z)) > 1e-9 || Math.Abs(y.Dot(z)) > 1e-9) return false; uint pv = BitConverter.ToUInt32(d, p + 96); ushort pcls = BitConverter.ToUInt16(d, p + 100); if (pcls != 1974 && pcls != 1736) return false; - sr = new SurfaceRec { Kind = SurfKind.Rev, O = o, X = x, Y = y, Z = z, Env = env, ProfileHandle = pv, Orient = d[p - 1] }; + sr = new SurfaceRec { Kind = SurfKind.Rev, O = o.ToArray(), X = x.ToArray(), Y = y.ToArray(), Z = z.ToArray(), Env = ReadEnvelope(p), ProfileHandle = pv, Orient = d[p - 1] }; return true; } bool FindArcAfter(int p, SurfaceRec rev, out ArcRec arc) { arc = default; + var axis = Pt3.From(rev.Z); int stop = Math.Min(lim - 112, p + 8192); for (int q = p; q < stop; q++) { var x = V(d, q); var y = V(d, q + 24); - if (!(Fin3(x) && Fin3(y) && Unit(x) && Unit(y) && Math.Abs(Dot(x, y)) < 1e-9)) continue; + if (!(Fin3(x) && Fin3(y) && Unit(x) && Unit(y) && Math.Abs(x.Dot(y)) < 1e-9)) continue; double r = BitConverter.ToDouble(d, q + 48); var cc = V(d, q + 56); if (!(IsFinite(r) && Math.Abs(r) > 1e-6 && Math.Abs(r) < 1e4 && Fin3(cc))) continue; // Meridian plane: the arc plane's normal must be perpendicular the revolution axis. - var n = new[] { x[1] * y[2] - x[2] * y[1], x[2] * y[0] - x[0] * y[2], x[0] * y[1] - x[1] * y[0] }; - if (Math.Abs(Dot(n, rev.Z)) > 0.05) continue; - arc = new ArcRec { R = r }; - Array.Copy(x, arc.X, 3); Array.Copy(y, arc.Y, 3); Array.Copy(cc, arc.C, 3); + if (Math.Abs(Pt3.Cross(x, y).Dot(axis)) > 0.05) continue; + arc = new ArcRec { R = r, X = x.ToArray(), Y = y.ToArray(), C = cc.ToArray() }; arc.T0 = BitConverter.ToDouble(d, q - 16); arc.T1 = BitConverter.ToDouble(d, q - 8); return true; } @@ -4112,9 +4317,9 @@ bool FindArcAfter(int p, SurfaceRec rev, out ArcRec arc) for (int p = Math.Max(0, start); p + 72 <= lim && res.Count < expected.Count;) { var o = V(d, p); var x = V(d, p + 24); var y = V(d, p + 48); - if (Fin3(o) && Fin3(x) && Fin3(y) && Unit(x) && Unit(y) && Math.Abs(Dot(x, y)) < 1e-9) + if (Fin3(o) && Fin3(x) && Fin3(y) && Unit(x) && Unit(y) && Math.Abs(x.Dot(y)) < 1e-9) { - res.Add(new SurfaceRec { Kind = SurfKind.Plane, O = o, X = x, Y = y }); + res.Add(new SurfaceRec { Kind = SurfKind.Plane, O = o.ToArray(), X = x.ToArray(), Y = y.ToArray() }); p += 72; continue; } @@ -4167,8 +4372,9 @@ static void SortUnique(List values) int MaxHermiteGridLines = t_coarseTessellation ? 24 : 200; uSamples = ThinSamples(uSamples, uKnots, MaxHermiteGridLines); vSamples = ThinSamples(vSamples, vKnots, MaxHermiteGridLines); + if (uSamples.Count < 2 || vSamples.Count < 2) yield break; - static double[] Hermite(double[] p0, double[] p1, double[] d0, double[] d1, + static Pt3 Hermite(Pt3 p0, Pt3 p1, Pt3 d0, Pt3 d1, double t, double parameterSpan) { double t2 = t * t, t3 = t2 * t; @@ -4176,14 +4382,12 @@ static double[] Hermite(double[] p0, double[] p1, double[] d0, double[] d1, double h10 = t3 - 2 * t2 + t; double h01 = -2 * t3 + 3 * t2; double h11 = t3 - t2; - return new[] - { - h00 * p0[0] + h10 * parameterSpan * d0[0] + h01 * p1[0] + h11 * parameterSpan * d1[0], - h00 * p0[1] + h10 * parameterSpan * d0[1] + h01 * p1[1] + h11 * parameterSpan * d1[1], - h00 * p0[2] + h10 * parameterSpan * d0[2] + h01 * p1[2] + h11 * parameterSpan * d1[2], - }; + return new Pt3( + h00 * p0.X + h10 * parameterSpan * d0.X + h01 * p1.X + h11 * parameterSpan * d1.X, + h00 * p0.Y + h10 * parameterSpan * d0.Y + h01 * p1.Y + h11 * parameterSpan * d1.Y, + h00 * p0.Z + h10 * parameterSpan * d0.Z + h01 * p1.Z + h11 * parameterSpan * d1.Z); } - double[] Eval(double u, double v) + Pt3 Eval(double u, double v) { int ui = Array.BinarySearch(uKnots, u); if (ui < 0) ui = ~ui - 1; @@ -4199,23 +4403,33 @@ double[] Eval(double u, double v) var n10 = nodes[vi * uKnots.Length + ui + 1]; var n01 = nodes[(vi + 1) * uKnots.Length + ui]; var n11 = nodes[(vi + 1) * uKnots.Length + ui + 1]; - var p0 = Hermite(n00.Point, n10.Point, n00.Du, n10.Du, tu, du); - var p1 = Hermite(n01.Point, n11.Point, n01.Du, n11.Du, tu, du); - var dv0 = Hermite(n00.Dv, n10.Dv, n00.Duv, n10.Duv, tu, du); - var dv1 = Hermite(n01.Dv, n11.Dv, n01.Duv, n11.Duv, tu, du); + var p0 = Hermite(Pt3.From(n00.Point), Pt3.From(n10.Point), Pt3.From(n00.Du), Pt3.From(n10.Du), tu, du); + var p1 = Hermite(Pt3.From(n01.Point), Pt3.From(n11.Point), Pt3.From(n01.Du), Pt3.From(n11.Du), tu, du); + var dv0 = Hermite(Pt3.From(n00.Dv), Pt3.From(n10.Dv), Pt3.From(n00.Duv), Pt3.From(n10.Duv), tu, du); + var dv1 = Hermite(Pt3.From(n01.Dv), Pt3.From(n11.Dv), Pt3.From(n01.Duv), Pt3.From(n11.Duv), tu, du); return Hermite(p0, p1, dv0, dv1, tv, dv); } + static bool ValidPoint(Pt3 point) => IsFinite(point.X) && IsFinite(point.Y) && IsFinite(point.Z); + + // Reuse sampled coordinates across neighboring cells. Each face still owns its vertices. + var currentRow = new Pt3[vSamples.Count]; + var nextRow = new Pt3[vSamples.Count]; + for (int j = 0; j < vSamples.Count; j++) currentRow[j] = Eval(uSamples[0], vSamples[j]); for (int i = 0; i + 1 < uSamples.Count; i++) + { + for (int j = 0; j < vSamples.Count; j++) nextRow[j] = Eval(uSamples[i + 1], vSamples[j]); for (int j = 0; j + 1 < vSamples.Count; j++) { - var quad = new List - { - Eval(uSamples[i], vSamples[j]), Eval(uSamples[i + 1], vSamples[j]), - Eval(uSamples[i + 1], vSamples[j + 1]), Eval(uSamples[i], vSamples[j + 1]), - }; - if (quad.All(p => p.All(IsFinite))) yield return quad; + var a = currentRow[j]; + var b = nextRow[j]; + var c = nextRow[j + 1]; + var d = currentRow[j + 1]; + if (ValidPoint(a) && ValidPoint(b) && ValidPoint(c) && ValidPoint(d)) + yield return [a.ToArray(), b.ToArray(), c.ToArray(), d.ToArray()]; } + (currentRow, nextRow) = (nextRow, currentRow); + } } /// diff --git a/src/RvtIO/Parsing/NameTableScanner.cs b/src/RvtIO/Parsing/NameTableScanner.cs index 5b5aaa93..e6486c92 100644 --- a/src/RvtIO/Parsing/NameTableScanner.cs +++ b/src/RvtIO/Parsing/NameTableScanner.cs @@ -23,8 +23,14 @@ public static void Scan(byte[] d, ParsingState state) int n = d.Length; // Anchor on the SECOND marker: [marker][targetId:4][nameLen:4][UTF-16 name][catId:4][trailing:4] // then validate backwards: a mostly-FF run of 28+ bytes preceded by [marker][holderEid]. - for (int p = 40; p + 16 <= n; p++) + const int maxNameLength = 500; + int last = n - 16; + Span chars = stackalloc char[maxNameLength]; + for (int p = 40; p <= last; p++) { + int next = d.AsSpan(p, last - p + 1).IndexOfAny((byte)1, (byte)4); + if (next < 0) break; + p += next; if (!IsMarker(d, p)) continue; uint targetId = BitConverter.ToUInt32(d, p + 4); @@ -38,7 +44,7 @@ public static void Scan(byte[] d, ParsingState state) nameLen = d[p + 8]; else continue; - if (nameLen < 1 || nameLen > 500 || p + 12 + nameLen * 2 + 8 > n) continue; + if (nameLen < 1 || nameLen > maxNameLength || p + 12 + nameLen * 2 + 8 > n) continue; // backward validation: an FF run of >=28 bytes (after skipping up to 8 zero // bytes; the FF-masked variant has a slightly longer run with isolated @@ -62,7 +68,6 @@ public static void Scan(byte[] d, ParsingState state) if (holderPos - 4 >= 0 && !IsMarker(d, holderPos - 4)) continue; // decode name; FF-masked variant corrupts high bytes of BMP-Latin chars - var chars = new char[nameLen]; bool ok = true; for (int k = 0; k < nameLen; k++) { @@ -79,11 +84,10 @@ public static void Scan(byte[] d, ParsingState state) if (catId < -2_200_000 || catId > -2_000_000) continue; uint trailing = BitConverter.ToUInt32(d, end + 4); - string name = new string(chars); // first entry wins (duplicates across incremental-save regions are identical) if (!state.ElementNameTable.ContainsKey(targetId)) { - state.ElementNameTable[targetId] = name; + state.ElementNameTable[targetId] = new string(chars[..nameLen]); state.NameEntryCategory[targetId] = catId; if (trailing > 0 && trailing < 50_000_000) state.NameEntryParentHolder[targetId] = trailing; diff --git a/src/RvtIO/Parsing/NativeFieldParameters.cs b/src/RvtIO/Parsing/NativeFieldParameters.cs index 05962e36..84469a3a 100644 --- a/src/RvtIO/Parsing/NativeFieldParameters.cs +++ b/src/RvtIO/Parsing/NativeFieldParameters.cs @@ -10,7 +10,11 @@ internal static class NativeFieldParameters { /// UnsetDomains: the same for a field that is "not set" (ElementId -1, double >= 1e29), which creates the parameter /// with that sentinel value only where the API shows it; null (rows accepted earlier): wherever the field exists. - internal readonly record struct Entry(int ParamId, StorageType Storage, string Key, string[] Domains, string[]? UnsetDomains); + internal readonly record struct Entry(int ParamId, StorageType Storage, string Key, string[] Domains, string[]? UnsetDomains) + { + internal bool RequiresIncompleteStores => + Key == "2960:m_grade" && ParamId is -1140422 or -1010108 or -1010104; + } internal static readonly Entry[] All = [ @@ -500,10 +504,40 @@ internal static class NativeFieldParameters new(-1001007, StorageType.Integer, "363:m_roomBounding", ["1604", "1913/-2000032", "3054", "3451", "3524/-2000011", "565", "642"], null), // Room Bounding new(-1001006, StorageType.Integer, "513:m_function", ["2559", "512"], null), ]; - internal static readonly HashSet<(int ParamId, string Key)> NotWithCompleteStores = [(-1140422, "2960:m_grade"), (-1010108, "2960:m_grade"), (-1010104, "2960:m_grade")]; - internal static readonly HashSet Keys = All.Select(entry => entry.Key).ToHashSet(StringComparer.Ordinal); + private static readonly Dictionary IntegerRows = IndexRows(StorageType.Integer); + private static readonly Dictionary DoubleRows = IndexRows(StorageType.Double); + private static readonly Dictionary StringRows = IndexRows(StorageType.String); + + private static Dictionary IndexRows(StorageType storage) => + Enumerable.Range(0, All.Length).Where(index => All[index].Storage == storage + || storage == StorageType.Integer && All[index].Storage == StorageType.ElementId) + .GroupBy(index => All[index].Key, StringComparer.Ordinal) + .ToDictionary(group => group.Key, group => group.ToArray(), StringComparer.Ordinal); + + internal static void CollectPresentRows(TfBlockDeserializer.NativeParams native, List rows, object?[] valuesByRow) + { + rows.Clear(); + Collect(native.Fields, IntegerRows, rows, valuesByRow); + Collect(native.DoubleFields, DoubleRows, rows, valuesByRow); + Collect(native.StringFields, StringRows, rows, valuesByRow); + // Several rows can set the same parameter, so replay the table's original order. + rows.Sort(); + + static void Collect(Dictionary fields, Dictionary index, + List rows, object?[] valuesByRow) + { + foreach (var field in fields) + { + if (!index.TryGetValue(field.Key, out var matches)) continue; + var value = Parameter.BoxParsedValue(field.Value); + rows.AddRange(matches); + foreach (int row in matches) valuesByRow[row] = value; + } + } + } + internal static readonly HashSet DeclaringClasses = All.Select(entry => int.Parse(entry.Key[..entry.Key.IndexOfAny(['#', ':'])], System.Globalization.CultureInfo.InvariantCulture)).ToHashSet(); } diff --git a/src/RvtIO/Parsing/OwnPartitionParts.cs b/src/RvtIO/Parsing/OwnPartitionParts.cs index c92cc254..5a043f4e 100644 --- a/src/RvtIO/Parsing/OwnPartitionParts.cs +++ b/src/RvtIO/Parsing/OwnPartitionParts.cs @@ -32,40 +32,44 @@ internal sealed record Classes(PartitionFraming.Tags Tags, int[] NodeKinds, int internal static Dictionary? Read(byte[] raw, Classes classes, int idWidth, out string? failure) { - var nodes = new Dictionary(); - var geometry = new Dictionary(); - var ambiguous = new HashSet(); - try + var collector = new Collector(classes, idWidth); + bool walked = PartitionFraming.Walk(raw, classes.Tags, idWidth, collector.Observe, out failure, out _); + failure = collector.Failure ?? failure; + return walked ? collector.Finish() : null; + } + + internal sealed class Collector(Classes classes, int idWidth) + { + private readonly Dictionary nodes = new(); + private readonly Dictionary geometry = new(); + private readonly HashSet ambiguous = new(); + private readonly ulong terminator = idWidth == 8 ? ulong.MaxValue : uint.MaxValue; + + internal string? Failure { get; private set; } + + internal void Observe(PartitionFraming.Record record) { - bool walked = PartitionFraming.Walk(raw, classes.Tags, idWidth, record => + if (Failure != null || record.Owner == terminator) return; + if (record.Owner > uint.MaxValue) { Failure = "record-owner"; return; } + uint owner = (uint)record.Owner; + var body = record.Body.Span; + if (body.Length < 2) { Failure = "record-class"; return; } + if (record.Block != 0) { - ulong terminator = idWidth == 8 ? ulong.MaxValue : uint.MaxValue; - if (record.Owner == terminator) return; - if (record.Owner > uint.MaxValue) throw new InvalidDataException("record-owner"); - uint owner = (uint)record.Owner; - var body = record.Body.Span; - if (body.Length < 2) throw new InvalidDataException("record-class"); - if (record.Block != 0) - { - if (nodes.ContainsKey(owner)) ambiguous.Add(owner); - return; - } - ushort kind = BinaryPrimitives.ReadUInt16LittleEndian(body); - var selected = record.Channel == 102 ? nodes : record.Channel == 103 ? geometry : null; - if (selected == null) return; - bool wanted = record.Channel == 102 ? classes.NodeKinds.Contains(kind) : kind == classes.GeometryKind; - // 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 _); - if (!walked) return null; - } - catch (InvalidDataException exception) - { - failure = exception.Message; - return null; + if (nodes.ContainsKey(owner)) ambiguous.Add(owner); + return; + } + ushort kind = BinaryPrimitives.ReadUInt16LittleEndian(body); + var selected = record.Channel == 102 ? nodes : record.Channel == 103 ? geometry : null; + if (selected == null) return; + bool wanted = record.Channel == 102 ? classes.NodeKinds.Contains(kind) : kind == classes.GeometryKind; + // 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); } - return nodes.Where(pair => !ambiguous.Contains(pair.Key) && geometry.ContainsKey(pair.Key)) + + internal Dictionary? Finish() => Failure != null ? null + : nodes.Where(pair => !ambiguous.Contains(pair.Key) && geometry.ContainsKey(pair.Key)) .ToDictionary(pair => pair.Key, pair => new WallParts(pair.Value, geometry[pair.Key])); } } diff --git a/src/RvtIO/Parsing/PartitionFraming.cs b/src/RvtIO/Parsing/PartitionFraming.cs index b49784f2..39016170 100644 --- a/src/RvtIO/Parsing/PartitionFraming.cs +++ b/src/RvtIO/Parsing/PartitionFraming.cs @@ -25,6 +25,8 @@ namespace RvtIO.Parsing; /// internal static class PartitionFraming { + private static ReadOnlySpan GzipHeader => [0x1f, 0x8b, 8, 0, 0, 0, 0, 0, 0, 0x0b]; + internal readonly record struct Tags(ushort ContentMarker, ushort ContentKey, ushort SegmentMarker, ushort SegmentCheckback, ushort SignatureMarker); /// One record of channel 101..103. is the index of the content block, 0 = the null-key map. @@ -94,6 +96,8 @@ internal static bool Walk(byte[] raw, Tags tags, int idWidth, Action onR var input = new Cursor(raw, paged: true); Require(input.U32() == 9 && input.U32() == 0, "format"); var keys = new HashSet(); + var scratch = new InflateScratch(); + using var prefetch = segmentBytes == null || OperatingSystem.IsBrowser() ? null : new SegmentPrefetch(tags); long inflated = 0; // output of all finished chains while (true) { @@ -116,6 +120,7 @@ internal static bool Walk(byte[] raw, Tags tags, int idWidth, Action onR long countSum = 0, sizeSum = 0; while (true) { + bool prefetched = prefetch?.Prepare(input) == true; Require(input.U16() == tags.SegmentMarker, "segment-marker"); uint flags = input.U32(), count = input.U32(), size = input.U32(), unc = input.U32(); if (size == 0) @@ -127,21 +132,37 @@ internal static bool Walk(byte[] raw, Tags tags, int idWidth, Action onR uint index = input.U32(); input.U32(); // the opaque value of the deposit is neither an owner nor a length Require(index is >= 101 and <= 103, "segment-index"); - var payload = input.Take((int)size - 8); + int payloadLength = (int)size - 8; + ReadOnlyMemory payload = default; + if (prefetched) input.SkipPayload(payloadLength); + else payload = input.Take(payloadLength); Require(input.U16() == tags.SegmentCheckback && input.U32() == size, "segment-checkback"); uint mode = flags & 3; if (mode is 0 or 2) Require(chainIndex == null, "chain-start"); else Require(chainIndex == index, "chain-continuation"); chainIndex = index; - 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()); + byte[]? decoded = prefetched ? prefetch!.Take() : null; + if (decoded == null) + { + int before = (int)chain.Length; + Inflate(payload, chain, scratch); + int length = (int)chain.Length - before; + segmentLengths?.Add(length); + segmentBytes?.Add(chain.GetBuffer().AsSpan(before, length).ToArray()); + } + else + { + Require(chain.Length + decoded.Length <= int.MaxValue, "gzip-length"); + segmentLengths?.Add(decoded.Length); + segmentBytes!.Add(decoded); + if (mode != 0) chain.Write(decoded); + } countSum += count; sizeSum += unc; if (mode is not (0 or 1)) continue; - var memory = chain.GetBuffer().AsMemory(0, checked((int)chain.Length)); + var memory = decoded != null && mode == 0 + ? decoded.AsMemory() : chain.GetBuffer().AsMemory(0, checked((int)chain.Length)); var records = new Cursor(memory); long actualCount = 0, actualSize = 0; while (records.Remaining > 0) @@ -162,7 +183,7 @@ internal static bool Walk(byte[] raw, Tags tags, int idWidth, Action onR onRecord(new Record(blocks, key, (int)index, owner, extra, memory.Slice(bodyAt, (int)bodySize), memory.Slice(begin, records.Position - begin), inflated + begin)); } Require(actualCount == countSum && actualSize == sizeSum, "chain-counts"); - inflated += chain.Length; + inflated += memory.Length; chain.SetLength(0); chain.Position = 0; chainIndex = null; @@ -194,21 +215,108 @@ internal static bool Walk(byte[] raw, Tags tags, int idWidth, Action onR return PagedGzipStream.RemoveSegments(raw); } - private static void Inflate(ReadOnlyMemory member, MemoryStream chain) + // A verified member is independent of its neighbours. Look ahead only for work + // scheduling, then let the main cursor commit records and report failures in order. + private sealed class SegmentPrefetch(Tags tags) : IDisposable + { + private const int BatchSize = 128; + private const int BatchBytes = 32 * 1024 * 1024; + private readonly List<(int Start, ReadOnlyMemory Payload)> _batch = new(BatchSize); + private readonly byte[]?[] _decoded = new byte[BatchSize][]; + private readonly string?[] _errors = new string?[BatchSize]; + private readonly ThreadLocal _scratch = new(() => new InflateScratch()); + private int _next; + + internal bool Prepare(Cursor input) + { + if (_next < _batch.Count && _batch[_next].Start == input.Position) return true; + Fill(input.Fork()); + return _batch.Count != 0; + } + + internal byte[] Take() + { + int index = _next++; + if (_errors[index] is { } error) throw new InvalidDataException(error); + var output = _decoded[index]!; + _decoded[index] = null; + return output; + } + + private void Fill(Cursor cursor) + { + _batch.Clear(); + _next = 0; + long expectedBytes = 0; + while (_batch.Count < BatchSize && cursor.Remaining >= 18) + { + int position = cursor.Position; + if (cursor.U16() != tags.SegmentMarker) break; + cursor.Skip(8); // The main walk validates flags and counts. + uint size = cursor.U32(); + cursor.Skip(4); + if (size < 26 || size > int.MaxValue || cursor.Remaining < size + 6L) break; + if (cursor.U32() is not (101 or 102 or 103)) break; + cursor.Skip(4); + var member = cursor.Take((int)size - 8); + if (cursor.U16() != tags.SegmentCheckback || cursor.U32() != size + || !member.Span[..10].SequenceEqual(GzipHeader)) break; + expectedBytes += BinaryPrimitives.ReadUInt32LittleEndian(member.Span[^4..]); + if (expectedBytes > BatchBytes) break; + _batch.Add((position, member)); + } + if (_batch.Count <= 1) + { + _batch.Clear(); + return; + } + + Parallel.For(0, _batch.Count, index => + { + var scratch = _scratch.Value!; + scratch.Output.SetLength(0); + _errors[index] = null; + try + { + Inflate(_batch[index].Payload, scratch.Output, scratch); + _decoded[index] = scratch.Output.ToArray(); + } + catch (Exception exception) when (exception is InvalidDataException or SharpZipBaseException or OverflowException) + { + _decoded[index] = null; + _errors[index] = exception.Message; + } + }); + } + + public void Dispose() => _scratch.Dispose(); + } + + private sealed class InflateScratch + { + internal readonly Inflater Inflater = new(noHeader: true); + internal readonly Crc32 Crc = new(); + internal readonly byte[] Buffer = new byte[32768]; + internal readonly MemoryStream Output = new(); + } + + private static void Inflate(ReadOnlyMemory member, MemoryStream chain, InflateScratch scratch) { var payload = member.Span; - Require(payload.Length >= 18 && payload[..10].SequenceEqual(new byte[] { 0x1f, 0x8b, 8, 0, 0, 0, 0, 0, 0, 0x0b }), "gzip-header"); + Require(payload.Length >= 18 && payload[..10].SequenceEqual(GzipHeader), "gzip-header"); uint expectedCrc = BinaryPrimitives.ReadUInt32LittleEndian(payload[^8..]); uint expectedLength = BinaryPrimitives.ReadUInt32LittleEndian(payload[^4..]); // shortcut: independently compressed members only; dictionary-dependent members reject // admission until their shared-window contract is implemented and tested. - var inflater = new Inflater(noHeader: true); + var inflater = scratch.Inflater; + inflater.Reset(); // The deflate data is read where it lies; the inflater stays inside the range it is given. var deflate = member[10..^8]; if (MemoryMarshal.TryGetArray(deflate, out var data)) inflater.SetInput(data.Array!, data.Offset, data.Count); else inflater.SetInput(deflate.ToArray()); - var crc = new Crc32(); - byte[] buffer = new byte[32768]; + var crc = scratch.Crc; + crc.Reset(); + byte[] buffer = scratch.Buffer; long length = 0; while (!inflater.IsFinished) { @@ -237,13 +345,19 @@ private sealed class Cursor(ReadOnlyMemory bytes, bool paged = false) internal int Position { get; private set; } internal int Remaining => length - Position; internal ReadOnlySpan Bytes(int count) => Take(count).Span; + internal Cursor Fork() => (Cursor)MemberwiseClone(); + + internal void SkipPayload(int count) + { + Require(count >= 0 && count <= Remaining, "bounds"); + Position += count; + } /// 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; - Position += count; + SkipPayload(count); if (count == 0) return default; if (!paged) return bytes.Slice(start, count); diff --git a/src/RvtIO/Parsing/RecordParser.cs b/src/RvtIO/Parsing/RecordParser.cs index 900a203f..62a3bbbb 100644 --- a/src/RvtIO/Parsing/RecordParser.cs +++ b/src/RvtIO/Parsing/RecordParser.cs @@ -8,8 +8,12 @@ internal static class RecordParser { internal static bool ContainsAnchoredR22Record(byte[] chunk, IReadOnlySet knownIds) { - for (int position = 0; position + 12 <= chunk.Length; position++) + int limit = chunk.Length - 11; + for (int position = 0; position < limit; position++) { + int nextMagic = chunk.AsSpan(position + 8, limit - position).IndexOfAny((byte)0x3C, (byte)0xF8); + if (nextMagic < 0) break; + position += nextMagic; if (!TryReadR22Header(chunk, position, out uint elementId, out int recordSize)) continue; int next = position + recordSize; @@ -26,6 +30,10 @@ internal static bool ContainsAnchoredR25Record(byte[] chunk, IReadOnlySet { for (int position = 0; position + 20 <= chunk.Length; position++) { + // The padding and the high bytes of the 19-bit body size precede the footer check. + if (BitConverter.ToUInt32(chunk, position + 4) != 0 + || chunk[position + 15] != 0 || chunk[position + 14] > 7) + continue; if (!TryReadR25Header(chunk, position, out uint elementId, out int recordSize)) continue; int next = position + recordSize; @@ -62,16 +70,15 @@ public static void ParseChunk(byte[] chunk, ParsingState state) if (!state.Records.ContainsKey(elemId)) { ushort subclass = BitConverter.ToUInt16(chunk, pos + 10); - var body = new byte[bodySize]; - Array.Copy(chunk, pos + 12, body, 0, (int)bodySize); + int bodyStart = pos + 12; + var body = chunk.AsMemory(bodyStart, (int)bodySize); var rec = new ElementRecord { ElemId = elemId, Body = body, Subclass = subclass }; ExtractReferences(rec); ExtractBodyParams(rec); - BlockParser.ExtractBlockStrings(body, 0, body.Length, elemId, state.ElemStrings); - BlockParser.ExtractBlockDoubles(body, 0, body.Length, elemId, state.ElemDoubles); + BlockParser.ExtractBlockStrings(chunk, bodyStart, next, elemId, state.ElemStrings); state.Records[elemId] = rec; // Extract after storing record (needs references for SymbolId validation) - BlockParser.ExtractFamilyInstanceTransform(body, 0, body.Length, elemId, state.FamilyInstanceTransforms, state.Records); + BlockParser.ExtractFamilyInstanceTransform(chunk, bodyStart, next, elemId, state.FamilyInstanceTransforms, state.Records); } pos = next; aligned = true; @@ -102,13 +109,13 @@ public static void ParseChunkR25(byte[] chunk, ParsingState state) uint bodySize = BitConverter.ToUInt32(chunk, pos + 12); if (!state.Records.ContainsKey(elemId)) { - var body = new byte[bodySize]; - Array.Copy(chunk, pos + 16, body, 0, (int)bodySize); + int bodyStart = pos + 16; + int bodyEnd = next - sizeof(uint); + var body = chunk.AsMemory(bodyStart, (int)bodySize); var rec = new ElementRecord { ElemId = elemId, Body = body, Subclass = 0 }; ExtractR25Body(rec); - BlockParser.ExtractBlockStrings(body, 0, body.Length, elemId, state.ElemStrings); - BlockParser.ExtractBlockDoubles(body, 0, body.Length, elemId, state.ElemDoubles); + BlockParser.ExtractBlockStrings(chunk, bodyStart, bodyEnd, elemId, state.ElemStrings); state.Records[elemId] = rec; } pos = next; @@ -176,10 +183,10 @@ private static bool TryReadR25Header(byte[] chunk, int position, /// then [assocLevelId:4][0:4][famId:4][0:4] etc. (8-byte element refs) private static void ExtractR25Body(ElementRecord rec) { - var body = rec.Body; + var body = rec.Body.Span; if (body.Length < 4) return; - ushort topClassId = BitConverter.ToUInt16(body, 0); + ushort topClassId = BitConverter.ToUInt16(body.Slice(0)); rec.Subclass = topClassId; // Store top-level Tf classId as subclass for classification if (R25ClassIdToCategory.TryGetValue(topClassId, out int catFromClass)) @@ -189,12 +196,12 @@ private static void ExtractR25Body(ElementRecord rec) int elemBasePos = -1; for (int i = 0; i + 10 <= body.Length; i += 2) { - if (BitConverter.ToUInt16(body, i) == 0x02EF) + if (BitConverter.ToUInt16(body.Slice(i)) == 0x02EF) { - uint ver = BitConverter.ToUInt32(body, i + 2); + uint ver = BitConverter.ToUInt32(body.Slice(i + 2)); if (ver == 1) { - uint selfId = BitConverter.ToUInt32(body, i + 6); + uint selfId = BitConverter.ToUInt32(body.Slice(i + 6)); if (selfId == rec.ElemId || ElementIdEncoding.IsSupported(selfId)) { elemBasePos = i; break; } } @@ -216,8 +223,8 @@ private static void ExtractR25Body(ElementRecord rec) // [assocLevelId:4][0:4] [famId:4][0:4] ... for (int r = 0; r < 8 && off + 8 <= body.Length; r++) { - uint refId = BitConverter.ToUInt32(body, off); - uint pad = BitConverter.ToUInt32(body, off + 4); + uint refId = BitConverter.ToUInt32(body.Slice(off)); + uint pad = BitConverter.ToUInt32(body.Slice(off + 4)); if (ElementIdEncoding.IsSupported(refId) && refId != 0xFFFFFFFF && pad == 0 && refId != rec.ElemId) { if (!rec.References.Contains(refId)) @@ -231,8 +238,8 @@ private static void ExtractR25Body(ElementRecord rec) // R25 uses [elemId:u32][zero:u32], with FFFFFFFF FFFFFFFF for null for (int i = 0; i + 8 <= body.Length; i += 2) { - uint refId = BitConverter.ToUInt32(body, i); - uint pad = BitConverter.ToUInt32(body, i + 4); + uint refId = BitConverter.ToUInt32(body.Slice(i)); + uint pad = BitConverter.ToUInt32(body.Slice(i + 4)); if (ElementIdEncoding.IsSupported(refId) && pad == 0 && refId != rec.ElemId && refId != 0xFFFFFFFF) { if (!rec.References.Contains(refId)) @@ -242,7 +249,7 @@ private static void ExtractR25Body(ElementRecord rec) if (topClassId == 0 && body.Length >= 6) { - int catId = BitConverter.ToInt32(body, 2); + int catId = BitConverter.ToInt32(body.Slice(2)); if (catId < -1 && catId > -3_000_000) rec.CategoryId = catId; } @@ -254,7 +261,7 @@ private static void ExtractR25Body(ElementRecord rec) int searchEnd = Math.Min(body.Length - 4, searchStart + 200); for (int i = searchStart; i <= searchEnd; i += 2) { - int val = BitConverter.ToInt32(body, i); + int val = BitConverter.ToInt32(body.Slice(i)); if (val < -1 && val > -3_000_000) { if (val <= -2000000 && val >= -2010000) @@ -273,11 +280,11 @@ private static void ExtractR25Body(ElementRecord rec) public static void ExtractReferences(ElementRecord rec) { - var body = rec.Body; + var body = rec.Body.Span; int markerPos = -1; for (int i = 0; i < body.Length - 2; i++) { - if (BitConverter.ToUInt16(body, i) == 0x0548) + if (BitConverter.ToUInt16(body.Slice(i)) == 0x0548) { markerPos = i; break; } } @@ -294,29 +301,29 @@ public static void ExtractReferences(ElementRecord rec) } if (refStart + 4 > body.Length) return; - int count = BitConverter.ToInt32(body, refStart); + int count = BitConverter.ToInt32(body.Slice(refStart)); if (count < 0 || count > 10000 || refStart + 4 + count * 4 > body.Length) { refStart += 48; // skip geometry doubles if (refStart + 4 > body.Length) return; - count = BitConverter.ToInt32(body, refStart); + count = BitConverter.ToInt32(body.Slice(refStart)); if (count < 0 || count > 10000 || refStart + 4 + count * 4 > body.Length) return; } while (refStart + 4 <= body.Length) { - count = BitConverter.ToInt32(body, refStart); + count = BitConverter.ToInt32(body.Slice(refStart)); if (count < 0 || count > 10000 || refStart + 4 + count * 4 > body.Length) break; refStart += 4; for (int i = 0; i < count; i++) { - uint refId = BitConverter.ToUInt32(body, refStart + i * 4); + uint refId = BitConverter.ToUInt32(body.Slice(refStart + i * 4)); if (refId > 0 && refId < 0xFFFFFF00) rec.References.Add(refId); } refStart += count * 4; if (refStart + 4 > body.Length) break; - int nextCount = BitConverter.ToInt32(body, refStart); + int nextCount = BitConverter.ToInt32(body.Slice(refStart)); if (nextCount < 0 || nextCount > 10000) break; } } @@ -326,16 +333,16 @@ public static void ExtractReferences(ElementRecord rec) /// by scanning past 14-byte entries until sentinel, then looking for valid doubles. /// Returns the offset of the first valid double, or -1. /// - private static int FindPostEntryGeomOffset(byte[] body) + private static int FindPostEntryGeomOffset(ReadOnlySpan body) { for (int pos = 2; pos + 14 <= body.Length; pos += 14) { - int classId = BitConverter.ToUInt16(body, pos + 10); + int classId = BitConverter.ToUInt16(body.Slice(pos + 10)); if (classId == 0 || classId == 0xFFFF) { for (int skip = pos + 14; skip + 48 <= body.Length; skip += 2) { - double d0 = BitConverter.ToDouble(body, skip); + double d0 = BitConverter.ToDouble(body.Slice(skip)); if (!double.IsNaN(d0) && !double.IsInfinity(d0) && Math.Abs(d0) > 1e-6 && Math.Abs(d0) < 1e6) return skip; } @@ -347,22 +354,22 @@ private static int FindPostEntryGeomOffset(byte[] body) public static void ExtractBodyParams(ElementRecord rec) { - var body = rec.Body; + var body = rec.Body.Span; if (body.Length < 4) return; int markerPos = -1; for (int i = 0; i < body.Length - 1; i++) - if (BitConverter.ToUInt16(body, i) == 0x0548) { markerPos = i; break; } + if (BitConverter.ToUInt16(body.Slice(i)) == 0x0548) { markerPos = i; break; } int entryLimit = markerPos >= 2 ? markerPos : body.Length; // Entry layout: [value:4][paramKey:4][fieldType:2][classId:2][flags:2] for (int pos = 2; pos + 14 <= entryLimit; pos += 14) { - int rawValue = BitConverter.ToInt32(body, pos); - int paramKey = BitConverter.ToInt32(body, pos + 4); - int fieldType = BitConverter.ToUInt16(body, pos + 8); - int classId = BitConverter.ToUInt16(body, pos + 10); + int rawValue = BitConverter.ToInt32(body.Slice(pos)); + int paramKey = BitConverter.ToInt32(body.Slice(pos + 4)); + int fieldType = BitConverter.ToUInt16(body.Slice(pos + 8)); + int classId = BitConverter.ToUInt16(body.Slice(pos + 10)); if (classId == 0 || classId == 0xFFFF) { // CategoryId is stored as int32 right after the last valid 14-byte entry @@ -372,8 +379,6 @@ public static void ExtractBodyParams(ElementRecord rec) break; } - rec.EntryValues.Add(rawValue); - if (paramKey == -1) { if (rawValue != -1 && (fieldType == 3 || fieldType == 4)) @@ -395,7 +400,7 @@ 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.WritableParamIds ??= new()).Add(paramKey); rec.BipParams.Add(new BipEntry(paramKey, bipName, fieldType, intVal)); } diff --git a/src/RvtIO/Parsing/StringScanner.cs b/src/RvtIO/Parsing/StringScanner.cs index bd45ca84..e2e78a6a 100644 --- a/src/RvtIO/Parsing/StringScanner.cs +++ b/src/RvtIO/Parsing/StringScanner.cs @@ -43,17 +43,24 @@ private static bool IsValidElementName( return true; } - public static bool IsValidParamName(string s) + public static bool IsValidParamName(string s) => IsValidParamName(s.AsSpan()); + + private static bool IsValidParamName(ReadOnlySpan s) { if (s.Length < 3 || s.Length > 100) return false; - if (s.StartsWith("autodesk.")) return false; - if (s.Contains('\\') || s.Contains('/')) return false; - if (s.StartsWith('(') && s.Contains(',')) return false; - if (s.All(char.IsDigit)) return false; + if (s.IndexOfAny('\\', '/') >= 0) return false; + if (s[0] == '(' && s.Contains(',')) return false; if (s.Length >= 10 && char.IsDigit(s[0]) && char.IsDigit(s[1]) && s[2] == '.') return false; - if (s.Length >= 36 && s.Count(c => c == '-') >= 4 && s.All(c => Uri.IsHexDigit(c) || c == '-')) return false; - if (s.Length >= 10 && s.All(c => Uri.IsHexDigit(c) || c == '-')) return false; - return s.Any(char.IsLetter); + bool hasLetter = false; + bool couldBeHexId = s.Length >= 10; + foreach (char c in s) + { + hasLetter |= char.IsLetter(c); + if (couldBeHexId) couldBeHexId = Uri.IsHexDigit(c) || c == '-'; + if (hasLetter && !couldBeHexId) + return !s.StartsWith("autodesk.", StringComparison.CurrentCulture); + } + return false; } /// Scan a chunk for element name strings near element IDs. @@ -63,6 +70,9 @@ public static void ScanChunk(byte[] d, HashSet elemSet, Dictionary>(); + var nearbyIds = new Queue<(int Offset, uint Id)>(); + int lastIdOffset = -1; + Span text = stackalloc char[200]; for (int j = 0; j + 6 <= d.Length; j++) { uint sLen = BitConverter.ToUInt32(d, j); @@ -82,23 +92,30 @@ public static void ScanChunk(byte[] d, HashSet elemSet, Dictionary(); if (!seenPerEid.TryGetValue(eid, out var seen)) diff --git a/src/RvtIO/Parsing/TfBlockDeserializer.CurtainPanelOrder.cs b/src/RvtIO/Parsing/TfBlockDeserializer.CurtainPanelOrder.cs index b7403052..44266030 100644 --- a/src/RvtIO/Parsing/TfBlockDeserializer.CurtainPanelOrder.cs +++ b/src/RvtIO/Parsing/TfBlockDeserializer.CurtainPanelOrder.cs @@ -6,11 +6,14 @@ internal static partial class TfBlockDeserializer /// the wall's CGDrivers one after the other, each grid's CurtainGrid.m_panelIds as written (the IFC exporter /// appends the panel ids of each driver's grid in this order). Null when the wall does not decode completely, has no curtain /// grid, or a panel list is not exactly a count followed by that many ids. Zero ids (empty cells) are kept. - internal static int[]? ExtractCurtainGridPanelIds(byte[] data, int start, uint size, ushort classId) + internal static int[]? ExtractCurtainGridPanelIds(byte[] data, int start, uint size, ushort classId, + WallCompleteInputRead? complete = null) { - if (!IsSubclassOf(classId, 362) - || ExtractOwnWallCompleteInputs(data, start, size, classId, out _) is not { } input) - return null; + if (!IsSubclassOf(classId, 362)) return null; + var input = complete == null + ? ExtractOwnWallCompleteInputs(data, start, size, classId, out _) + : complete.Read(out _); + if (input == null) return null; List? ids = null; foreach (var grid in input.LaterObjects) { diff --git a/src/RvtIO/Parsing/TfBlockDeserializer.GElementArchiveReferences.cs b/src/RvtIO/Parsing/TfBlockDeserializer.GElementArchiveReferences.cs index e38300e7..976ac3de 100644 --- a/src/RvtIO/Parsing/TfBlockDeserializer.GElementArchiveReferences.cs +++ b/src/RvtIO/Parsing/TfBlockDeserializer.GElementArchiveReferences.cs @@ -16,6 +16,14 @@ internal sealed record OwnGElementFreshArchiveReferences(int OwnerId, uint Exter /// missing-key outcome is preserved; an incomplete resolution is not a null or absent geometry. internal static OwnGElementFreshArchiveReferences? SelectOwnGElementFreshArchiveReferences( OwnGElementGeometryGraph graph, out string? failure) + { + var analysis = AnalyzeGElement(graph).Archive.Value; + failure = analysis.Failure; + return analysis.Value; + } + + private static OwnGElementFreshArchiveReferences? ReadOwnGElementFreshArchiveReferences( + OwnGElementGeometryGraph graph, out string? failure) { failure = "archive-reference-graph"; if (graph.OwnerId <= 0 || !HasGElementGraphSchemas()) return null; @@ -35,24 +43,29 @@ internal sealed record OwnGElementFreshArchiveReferences(int OwnerId, uint Exter registrations.Add(registration); } var links = new List(); - string context = "archive-reference-field"; + int contextSource = 0; + GElementGraphField? contextField = null; try { foreach (var node in graph.Nodes) Walk(node.QueueIndex, node.Fields); failure = null; return new(graph.OwnerId, 1, 2, registrations, links, links.All(l => l.Outcome != "missing-key")); } - catch (DecodeFail) { failure = context; return null; } + catch (DecodeFail) + { + failure = contextField == null ? "archive-reference-field" + : $"archive-reference-field:{contextSource}:{contextField.Declaring}:{contextField.Name}"; + return null; + } void Walk(int source, IReadOnlyList fields) { foreach (var field in fields) { - context = $"archive-reference-field:{source}:{field.Declaring}:{field.Name}"; - if (!GElementGraphSchemas.TryGetValue((ushort)field.Declaring, out var schema)) throw Fail; - var descriptors = schema.Fields.Where(f => f.Name == field.Name).ToArray(); - if (descriptors.Length != 1) throw Fail; - var descriptor = descriptors[0]; + contextSource = source; + contextField = field; + if (!GElementGraphFieldDescriptors.TryGetValue(((ushort)field.Declaring, field.Name), out var descriptor)) + throw Fail; for (int i = 0; i < field.Items.Count; i++) { var item = field.Items[i]; diff --git a/src/RvtIO/Parsing/TfBlockDeserializer.GElementGeometryGraph.cs b/src/RvtIO/Parsing/TfBlockDeserializer.GElementGeometryGraph.cs index 58ca7548..a02a1543 100644 --- a/src/RvtIO/Parsing/TfBlockDeserializer.GElementGeometryGraph.cs +++ b/src/RvtIO/Parsing/TfBlockDeserializer.GElementGeometryGraph.cs @@ -1,3 +1,5 @@ +using System.Runtime.CompilerServices; + namespace RvtIO.Parsing; internal static partial class TfBlockDeserializer @@ -14,6 +16,42 @@ internal sealed record GElementFaceSurfaceLink(int FaceQueueIndex, int SurfaceQu internal sealed record OwnGElementGeometryGraph(int OwnerId, uint OpaqueHeader, IReadOnlyList Nodes, IReadOnlyList FaceSurfaces, int End); + private static GElementGraphField RequireUniqueGraphField(GElementGraphNode node, int declaring, string name, + int? itemCount = null) + { + GElementGraphField? found = null; + for (int i = 0; i < node.Fields.Count; i++) + { + var field = node.Fields[i]; + if (field.Declaring != declaring || field.Name != name) continue; + if (found != null || itemCount is int count && field.Items.Count != count) throw Fail; + found = field; + } + return found ?? throw Fail; + } + + // Winding and nesting revisit these immutable inputs several times for the same graph. + // The cache follows the graph instance, including for failures and copies made with "with". + private static readonly ConditionalWeakTable GElementAnalyses = new(); + + private sealed class GElementGraphAnalysis(OwnGElementGeometryGraph graph) + { + internal Lazy<(OwnGElementFreshArchiveReferences? Value, string? Failure)> Archive { get; } = new(() => + (ReadOwnGElementFreshArchiveReferences(graph, out var failure), failure)); + + internal Lazy<(OwnGElementFreshLoopTopology? Value, string? Failure)> Topology { get; } = new(() => + (ReadOwnGElementLoopTopology(graph, out var failure), failure)); + + internal Lazy<(OwnGElementFreshLoopNestingInputs? Value, string? Failure)> LegacyNesting { get; } = new(() => + (ReadOwnGElementLoopNestingInputs(graph, 0, out var failure), failure)); + + internal Lazy<(OwnGElementFreshLoopNestingInputs? Value, string? Failure)> PositiveNesting { get; } = new(() => + (ReadOwnGElementLoopNestingInputs(graph, 1, out var failure), failure)); + } + + private static GElementGraphAnalysis AnalyzeGElement(OwnGElementGeometryGraph graph) => + GElementAnalyses.GetValue(graph, static key => new(key)); + /// Complete, footer-exact FIFO for the physical node kinds of the r22 layout. Owned Face -> Surface links /// use queue indices, never handles, order or shape matching. Non-owning references and flags remain raw: this does /// not reconstruct runtime pointers, document lookup, active faces or extrusion validity. @@ -35,13 +73,18 @@ internal sealed record OwnGElementGeometryGraph(int OwnerId, uint OpaqueHeader, var queue = new List<(ushort ClassId, uint Handle)>(); var nodes = new List(); string context = "root"; + int contextIndex = 0, contextOffset = 0; + ushort contextClass = 0; + TfField? contextField = null; try { nodes.Add(Node(-1, 2007, (uint)owner)); for (int index = 0; index < queue.Count; index++) { var entry = queue[index]; - context = $"fifo:{index}:{entry.ClassId}"; + context = "fifo"; + contextIndex = index; + contextClass = entry.ClassId; if (entry.ClassId is not (2007 or 2015 or 2009 or 2092 or 1996 or 1589 or 1243 or 1254 or 2014 or 522 or 1850 or 1848 or 1736 or 1999 or 1257 or 1974 or 983 or 1991 or 2238)) throw Fail; @@ -57,14 +100,26 @@ internal sealed record OwnGElementGeometryGraph(int OwnerId, uint OpaqueHeader, var pointer = node.Fields.Single(f => f.Declaring == 1589 && f.Name == "m_pSurf") .Items.Single().Pointer!; if (pointer.QueueIndex is not int surface) continue; - context = $"face-surface:{node.QueueIndex}:{surface}"; + context = "face-surface"; + contextIndex = node.QueueIndex; + contextOffset = surface; if (nodes[surface + 1].ClassId is not (522 or 983)) throw Fail; surfaces.Add(new(node.QueueIndex, surface)); } failure = null; return new(owner, BitConverter.ToUInt32(data, start + 4), nodes, surfaces, position - start); } - catch (DecodeFail) { failure = context; return null; } + catch (DecodeFail) + { + failure = context switch + { + "fifo" => $"fifo:{contextIndex}:{contextClass}", + "field" => $"field:{contextField!.Declaring}:{contextField.Name}:{contextOffset}", + "face-surface" => $"face-surface:{contextIndex}:{contextOffset}", + _ => context, + }; + return null; + } GElementGraphNode Node(int index, ushort cls, uint handle) { @@ -75,24 +130,33 @@ GElementGraphNode Node(int index, ushort cls, uint handle) IReadOnlyList ReadFields(ushort cls, int depth) { - if (depth >= 32 || !GElementGraphSchemas.ContainsKey(cls)) throw Fail; - var result = new List(); - foreach (var field in GElementGraphFields(cls)) result.Add(Field(field, depth)); + if (depth >= 32 || !GElementGraphFieldChains.TryGetValue(cls, out var fields)) throw Fail; + var result = new GElementGraphField[fields.Length]; + for (int i = 0; i < fields.Length; i++) result[i] = Field(fields[i], depth); return result; } GElementGraphField Field(TfField field, int depth) { - context = $"field:{field.Declaring}:{field.Name}:{position - start}"; int first = position - start; + context = "field"; + contextField = field; + contextOffset = first; int high = field.Mods >> 4; uint? count = high == 5 ? (uint)Raw(4, false) : high == 1 ? (uint)field.Cnt!.Value : null; uint length = count ?? 1; - var items = new List(); + IReadOnlyList items = []; if (length != uint.MaxValue) { if (length > 100_000 || length > (uint)((end - position) / Minimum(field))) throw Fail; - for (uint i = 0; i < length; i++) items.Add(Item(field, depth)); + if (length == 1) + items = new[] { Item(field, depth) }; + else if (length > 1) + { + var repeatedItems = new List(); + for (uint i = 0; i < length; i++) repeatedItems.Add(Item(field, depth)); + items = repeatedItems; + } } return new(field.Declaring, field.Name, count, first, position - start, items); } @@ -101,13 +165,13 @@ GElementGraphItem Item(TfField field, int depth) { if (++itemCount > 1_000_000) throw Fail; int first = position - start; - var values = new List(); + long[] values = []; GElementGraphPointer? pointer = null; IReadOnlyList children = []; - if (field.Type is 1 or 2) values.Add(Raw(1, false)); - else if (field.Type == 4) values.Add(Raw(4, true)); - else if (field.Type == 5) values.Add(Raw(4, false)); - else if (field.Type == 7) values.Add(Raw(8, true)); + if (field.Type is 1 or 2) values = [Raw(1, false)]; + else if (field.Type == 4) values = [Raw(4, true)]; + else if (field.Type == 5) values = [Raw(4, false)]; + else if (field.Type == 7) values = [Raw(8, true)]; else if (field.Type == 13) { int dimensions = (field.Declaring, field.Name) switch @@ -116,17 +180,17 @@ GElementGraphItem Item(TfField field, int depth) (2008, "m_bBox") or (2008, "m_tightbBox") or (78, "m_3x3") => 3, _ => throw Fail }; - for (int i = 0; i < dimensions; i++) values.Add(Raw(8, true)); + values = new long[dimensions]; + for (int i = 0; i < dimensions; i++) values[i] = Raw(8, true); } else if (field.Type == 14) { int low = field.Mods & 15; if (field.Declaring == 1246 && field.Name == "m_GInfo") { - for (int i = 0; i < 3; i++) values.Add(Raw(4, true)); - values.Add(Raw(4, false)); + values = [Raw(4, true), Raw(4, true), Raw(4, true), Raw(4, false)]; } - else if (low == 3) values.Add(Raw(4, false)); + else if (low == 3) values = [Raw(4, false)]; else if (low is 1 or 2) pointer = Pointer(); else { @@ -137,7 +201,7 @@ GElementGraphItem Item(TfField field, int depth) (523, "m_Envelope") => 524, _ => (ushort)(field.Ref ?? throw Fail) }; - if (cls == 0) values.Add(Raw(4, true)); // ElementId's own scalar, not a polymorphic pointer + if (cls == 0) values = [Raw(4, true)]; // ElementId's own scalar, not a polymorphic pointer else children = ReadFields(cls, depth + 1); } } @@ -173,15 +237,16 @@ GElementGraphPointer Pointer() ushort? cls = handle == 0 ? null : (ushort)Raw(2, false); int? index = null; ushort? token = null; - var bits = new List(); + long[] bits = []; if (cls == 4) { token = (ushort)Raw(2, false); if ((token & 255) != 8 || token >> 8 is not (0 or 1)) throw Fail; if (token >> 8 == 1) { - for (int i = 0; i < 6; i++) bits.Add(Raw(8, true)); - for (int i = 0; i < 2; i++) bits.Add(Raw(4, false)); + bits = new long[8]; + for (int i = 0; i < 6; i++) bits[i] = Raw(8, true); + for (int i = 6; i < bits.Length; i++) bits[i] = Raw(4, false); } } else if (cls is > 0) diff --git a/src/RvtIO/Parsing/TfBlockDeserializer.GElementGraphSchemas.cs b/src/RvtIO/Parsing/TfBlockDeserializer.GElementGraphSchemas.cs index e7bf4af0..30b6fd46 100644 --- a/src/RvtIO/Parsing/TfBlockDeserializer.GElementGraphSchemas.cs +++ b/src/RvtIO/Parsing/TfBlockDeserializer.GElementGraphSchemas.cs @@ -97,11 +97,18 @@ private static bool HasGElementGraphSchemas() => GElementGraphSchemas.All(pair = Schemas.TryGetValue(pair.Key, out var actual) && actual.Name == pair.Value.Name && actual.Base == pair.Value.Base && actual.Fields.SequenceEqual(pair.Value.Fields)); - private static IEnumerable GElementGraphFields(ushort classId) + private static readonly Dictionary GElementGraphFieldChains = + GElementGraphSchemas.Keys.ToDictionary(classId => classId, classId => EnumerateGElementGraphFields(classId).ToArray()); + + private static readonly Dictionary<(ushort Class, string Name), TfField> GElementGraphFieldDescriptors = + GElementGraphSchemas.SelectMany(schema => schema.Value.Fields.Select(field => (schema.Key, Field: field))) + .ToDictionary(entry => (entry.Key, entry.Field.Name), entry => entry.Field); + + private static IEnumerable EnumerateGElementGraphFields(ushort classId) { var schema = GElementGraphSchemas[classId]; if (schema.Base is int parent) - foreach (var field in GElementGraphFields((ushort)parent)) yield return field; + foreach (var field in EnumerateGElementGraphFields((ushort)parent)) yield return field; foreach (var field in schema.Fields) yield return field with { Declaring = classId }; } } diff --git a/src/RvtIO/Parsing/TfBlockDeserializer.GElementLoopNestingInputs.cs b/src/RvtIO/Parsing/TfBlockDeserializer.GElementLoopNestingInputs.cs index c6bf95d2..51696da4 100644 --- a/src/RvtIO/Parsing/TfBlockDeserializer.GElementLoopNestingInputs.cs +++ b/src/RvtIO/Parsing/TfBlockDeserializer.GElementLoopNestingInputs.cs @@ -87,6 +87,17 @@ GElementGraphField Field(string name, int count) /// version; not a full pntWithin or a complete cut/extrusion/IFC result. internal static OwnGElementFreshLoopNestingInputs? SelectOwnGElementLoopNestingInputs( OwnGElementGeometryGraph graph, int currentTessEpsVersion, out string? failure) + { + if (currentTessEpsVersion is not (0 or 1)) + return ReadOwnGElementLoopNestingInputs(graph, currentTessEpsVersion, out failure); + var analysis = AnalyzeGElement(graph); + var result = currentTessEpsVersion == 0 ? analysis.LegacyNesting.Value : analysis.PositiveNesting.Value; + failure = result.Failure; + return result.Value; + } + + private static OwnGElementFreshLoopNestingInputs? ReadOwnGElementLoopNestingInputs( + OwnGElementGeometryGraph graph, int currentTessEpsVersion, out string? failure) { var epsilon = SelectSourceTessEpsControl(0, currentTessEpsVersion, null, out failure); if (epsilon == null) return null; diff --git a/src/RvtIO/Parsing/TfBlockDeserializer.GElementLoopTopology.cs b/src/RvtIO/Parsing/TfBlockDeserializer.GElementLoopTopology.cs index fc74b9d3..8436780c 100644 --- a/src/RvtIO/Parsing/TfBlockDeserializer.GElementLoopTopology.cs +++ b/src/RvtIO/Parsing/TfBlockDeserializer.GElementLoopTopology.cs @@ -14,6 +14,8 @@ internal sealed record GElementLoopTopology(int QueueIndex, ushort ClassId, int? internal sealed record GElementFaceLoopTopology(int FaceQueueIndex, int? FirstLoopQueueIndex, IReadOnlyList Loops); internal sealed record OwnGElementFreshLoopTopology(int OwnerId, IReadOnlyList Faces); + private readonly record struct LoopEdgeData(int? Side0, int? Side1, byte Flags, + IReadOnlyList Endpoints, IReadOnlyList Interior); /// Face first/next loop order and a fresh ConstGEdgeIter(loop) forward traversal. Uses same-archive key /// bindings, the concrete virtual isLoop dispatch, the first matching face side and the flag-based point count. @@ -21,6 +23,14 @@ internal sealed record OwnGElementFreshLoopTopology(int OwnerId, IReadOnlyList internal static OwnGElementFreshLoopTopology? SelectOwnGElementLoopTopology( OwnGElementGeometryGraph graph, out string? failure) + { + var analysis = AnalyzeGElement(graph).Topology.Value; + failure = analysis.Failure; + return analysis.Value; + } + + private static OwnGElementFreshLoopTopology? ReadOwnGElementLoopTopology( + OwnGElementGeometryGraph graph, out string? failure) { var references = SelectOwnGElementFreshArchiveReferences(graph, out failure); if (references == null) return null; @@ -28,7 +38,9 @@ internal sealed record OwnGElementFreshLoopTopology(int OwnerId, IReadOnlyList n.QueueIndex); var links = new Dictionary<(int, int, string, int, int), GElementArchiveReference>(); - string context = "loop-topology"; + var edgeData = new Dictionary(); + string? stage = null; + int contextOwner = 0, contextTarget = 0; try { foreach (var link in references.References) @@ -41,7 +53,9 @@ internal sealed record OwnGElementFreshLoopTopology(int OwnerId, IReadOnlyList(); var constructorSeen = new HashSet(); + List? skipped = null; + HashSet? constructorSeen = null; int? initial = firstEdge; var cursor = loop; while (initial == cursor.QueueIndex) { - context = $"loop-topology-constructor:{index}:{cursor.QueueIndex}"; - if (!constructorSeen.Add(cursor.QueueIndex)) throw Fail; - skipped.Add(cursor.QueueIndex); + stage = "constructor"; + contextOwner = index; + contextTarget = cursor.QueueIndex; + if (!(constructorSeen ??= new()).Add(cursor.QueueIndex)) throw Fail; + (skipped ??= new()).Add(cursor.QueueIndex); int? following = Owned(cursor, 1255, "m_nextLoop", true); if (following == null) { initial = null; break; } cursor = Loop(following.Value); @@ -69,14 +86,20 @@ internal sealed record OwnGElementFreshLoopTopology(int OwnerId, IReadOnlyList?)skipped ?? Array.Empty(), initial, visits, end)); q = next; } faces.Add(new(face.QueueIndex, first, loops)); } failure = null; return new(graph.OwnerId, faces); } - catch (DecodeFail) { failure = context; return null; } + catch (DecodeFail) + { + failure = stage == null ? "loop-topology" : $"loop-topology-{stage}:{contextOwner}:{contextTarget}"; + return null; + } static bool LoopKind(ushort cls) => cls is 1254 or 1257; GElementGraphNode Loop(int q) @@ -106,15 +133,9 @@ GElementGraphNode Loop(int q) if (!nodes.TryGetValue(q, out var node) || !LoopKind(node.ClassId)) throw Fail; return node; } - GElementGraphField Field(GElementGraphNode node, int declaring, string name, int? count) - { - var fields = node.Fields.Where(f => f.Declaring == declaring && f.Name == name).ToArray(); - if (fields.Length != 1 || count is int length && fields[0].Items.Count != length) throw Fail; - return fields[0]; - } int? Owned(GElementGraphNode node, int declaring, string name, bool loopTarget) { - var item = Field(node, declaring, name, 1).Items[0]; var p = item.Pointer; + var item = RequireUniqueGraphField(node, declaring, name, 1).Items[0]; var p = item.Pointer; if (p == null || item.Values.Count != 0 || item.Fields.Count != 0) throw Fail; if (p.Handle == 0) { @@ -126,10 +147,11 @@ GElementGraphField Field(GElementGraphNode node, int declaring, string name, int || loopTarget && !LoopKind(n.ClassId)) throw Fail; return target; } - int? Weak(GElementGraphNode node, int declaring, string name, int item, int count, bool faceTarget) + int? Weak(GElementGraphNode node, int declaring, string name, int item, int count, bool faceTarget) => + WeakField(node, RequireUniqueGraphField(node, declaring, name, count), item, faceTarget); + int? WeakField(GElementGraphNode node, GElementGraphField field, int item, bool faceTarget) { - var field = Field(node, declaring, name, count); - if (!links.TryGetValue((node.QueueIndex, declaring, name, item, field.Items[item].Start), out var link)) throw Fail; + if (!links.TryGetValue((node.QueueIndex, field.Declaring, field.Name, item, field.Items[item].Start), out var link)) throw Fail; if (link.Outcome == "null") return null; if (link.Outcome != "own-node" || link.TargetQueueIndex is not int target || !nodes.TryGetValue(target, out var n) || n.ClassId != link.TargetClassId @@ -138,24 +160,26 @@ GElementGraphField Field(GElementGraphNode node, int declaring, string name, int } byte Byte(GElementGraphNode node, int declaring, string name) { - var item = Field(node, declaring, name, 1).Items[0]; + var item = RequireUniqueGraphField(node, declaring, name, 1).Items[0]; if (item.Values.Count != 1 || item.Values[0] is < 0 or > 255 || item.End - item.Start != 1 || item.Pointer != null || item.Fields.Count != 0) throw Fail; return (byte)item.Values[0]; } IReadOnlyList Points(GElementGraphNode node, string name, bool endpoints) { - var field = Field(node, 1244, name, endpoints ? 2 : null); + var field = RequireUniqueGraphField(node, 1244, name, endpoints ? 2 : null); if (field.Count == null || (field.Count == uint.MaxValue ? field.Items.Count != 0 : field.Count != field.Items.Count)) throw Fail; - var points = new List(); - foreach (var item in field.Items) + if (field.Items.Count == 0) return []; + var points = new GElementEdgeUvPoint[field.Items.Count]; + for (int i = 0; i < points.Length; i++) { + var item = field.Items[i]; if (item.Pointer != null || item.Values.Count != 0 || item.Fields.Count != 1 || item.End - item.Start != 32) throw Fail; var uv = item.Fields[0]; if (uv.Declaring != 1248 || uv.Name != "uv" || uv.Count != 2 || uv.Items.Count != 2) throw Fail; foreach (var side in uv.Items) if (side.Values.Count != 2 || side.Pointer != null || side.Fields.Count != 0 || side.End - side.Start != 16) throw Fail; - points.Add(new(item.Start, item.End, uv.Items[0].Values, uv.Items[1].Values)); + points[i] = new(item.Start, item.End, uv.Items[0].Values, uv.Items[1].Values); } return points; } diff --git a/src/RvtIO/Parsing/TfBlockDeserializer.GElementTwoPointProjection.cs b/src/RvtIO/Parsing/TfBlockDeserializer.GElementTwoPointProjection.cs index 1a98ea6e..86872e2e 100644 --- a/src/RvtIO/Parsing/TfBlockDeserializer.GElementTwoPointProjection.cs +++ b/src/RvtIO/Parsing/TfBlockDeserializer.GElementTwoPointProjection.cs @@ -1,3 +1,5 @@ +using RvtIO.Geometry.Meshing; + namespace RvtIO.Parsing; internal static partial class TfBlockDeserializer @@ -15,35 +17,53 @@ internal sealed record GElementFaceTwoPointProjections(int FaceQueueIndex, IRead internal sealed record OwnGElementFreshTwoPointProjections(int OwnerId, int CurrentTessEpsVersion, IReadOnlyList Faces, bool Complete); - /// Plane virtual 8 position output: (u*x + v*y) + origin, with no unit basis, normal, - /// first/second derivative outputs or orientation flip. - internal static IReadOnlyList? EvaluateSourceOwnPlanePoint(GElementGraphNode plane, - IReadOnlyList uvBits, out string? failure) + internal readonly record struct SourcePlaneBasis(Pt3 Origin, Pt3 X, Pt3 Y) { - failure = "plane-point"; - if (plane.ClassId != 522 || uvBits.Count != 2) return null; + internal bool TryEvaluate(double u, double v, out Pt3 point) + { + point = (u * X + v * Y) + Origin; + return double.IsFinite(u) && double.IsFinite(v) && point.IsFinite; + } + } + + internal static bool TryReadSourcePlaneBasis(GElementGraphNode plane, out SourcePlaneBasis basis) + { + basis = default; + if (plane.ClassId != 522) return false; try { - double[] origin = Vector("m_origin"), x = Vector("m_xVec"), y = Vector("m_yVec"); - double u = BitConverter.Int64BitsToDouble(uvBits[0]), v = BitConverter.Int64BitsToDouble(uvBits[1]); - if (!double.IsFinite(u) || !double.IsFinite(v)) throw Fail; - double[] point = [(u * x[0] + v * y[0]) + origin[0], (u * x[1] + v * y[1]) + origin[1], (u * x[2] + v * y[2]) + origin[2]]; - if (point.Any(a => !double.IsFinite(a))) throw Fail; - failure = null; return point.Select(BitConverter.DoubleToInt64Bits).ToArray(); + basis = new(Vector("m_origin"), Vector("m_xVec"), Vector("m_yVec")); + return true; } - catch (DecodeFail) { return null; } + catch (DecodeFail) { return false; } - double[] Vector(string name) + Pt3 Vector(string name) { - var fs = plane.Fields.Where(f => f.Declaring == 522 && f.Name == name).ToArray(); - if (fs.Length != 1 || fs[0].Count != 3 || fs[0].Items.Count != 3) throw Fail; - foreach (var item in fs[0].Items) + var field = RequireUniqueGraphField(plane, 522, name, 3); + if (field.Count != 3) throw Fail; + foreach (var item in field.Items) if (item.Values.Count != 1 || item.End - item.Start != 8 || item.Pointer != null || item.Fields.Count != 0) throw Fail; - var values = fs[0].Items.Select(i => BitConverter.Int64BitsToDouble(i.Values[0])).ToArray(); - if (values.Any(a => !double.IsFinite(a))) throw Fail; return values; + var vector = new Pt3(BitConverter.Int64BitsToDouble(field.Items[0].Values[0]), + BitConverter.Int64BitsToDouble(field.Items[1].Values[0]), + BitConverter.Int64BitsToDouble(field.Items[2].Values[0])); + return vector.IsFinite ? vector : throw Fail; } } + /// Plane virtual 8 position output: (u*x + v*y) + origin, with no unit basis, normal, + /// first/second derivative outputs or orientation flip. + internal static IReadOnlyList? EvaluateSourceOwnPlanePoint(GElementGraphNode plane, + IReadOnlyList uvBits, out string? failure) + { + failure = "plane-point"; + if (uvBits.Count != 2 || !TryReadSourcePlaneBasis(plane, out var basis) + || !basis.TryEvaluate(BitConverter.Int64BitsToDouble(uvBits[0]), + BitConverter.Int64BitsToDouble(uvBits[1]), out var point)) return null; + failure = null; + return new[] { BitConverter.DoubleToInt64Bits(point.X), BitConverter.DoubleToInt64Bits(point.Y), + BitConverter.DoubleToInt64Bits(point.Z) }; + } + /// Two-endpoint branch with a null EdgePnt output. Uses the denominator max(1e-18, d.d), the Y+X+Z dot /// order, the 1e-9 endpoint parameter snap, residual1*delta + (-t)*direction, then the unscaled XYZ length. /// Non-finite arithmetic and the warning policy are explicitly unsupported. diff --git a/src/RvtIO/Parsing/TfBlockDeserializer.WallCompleteInputs.cs b/src/RvtIO/Parsing/TfBlockDeserializer.WallCompleteInputs.cs index 459f228a..f915e42d 100644 --- a/src/RvtIO/Parsing/TfBlockDeserializer.WallCompleteInputs.cs +++ b/src/RvtIO/Parsing/TfBlockDeserializer.WallCompleteInputs.cs @@ -9,11 +9,34 @@ internal sealed record WallCompleteInputObject(int QueueIndex, ushort ClassId, u internal sealed record OwnWallCompleteInputs(OwnWallSixPhaseGeometryHistories Histories, IReadOnlyList LaterObjects, byte[] FrameBytes, int End); + /// Shares one validated FIFO walk and retains the late fields used by the model reader. + internal sealed class WallCompleteInputRead(byte[] data, int start, uint size, ushort classId) + { + private bool _read; + private OwnWallCompleteInputs? _input; + private string? _failure; + + internal OwnWallCompleteInputs? Read(out string? failure) + { + if (!_read) + { + _input = ExtractOwnWallCompleteInputs(data, start, size, classId, out _failure, retainAll: false); + _read = true; + } + failure = _failure; + return _input; + } + } + /// Own six-phase inputs and the full remaining unfiltered owned FIFO. Every later field has an exact retained /// byte span; the frame bytes also retain the root and prior payloads. Complete requires the exact footer boundary. /// This is serialized input, not a reconstructed table or active geometry. internal static OwnWallCompleteInputs? ExtractOwnWallCompleteInputs( byte[] data, int start, uint size, ushort classId, out string? failure) + => ExtractOwnWallCompleteInputs(data, start, size, classId, out failure, retainAll: true); + + private static OwnWallCompleteInputs? ExtractOwnWallCompleteInputs( + byte[] data, int start, uint size, ushort classId, out string? failure, bool retainAll) { var histories = ExtractOwnWallGeometryHistoriesCore(data, start, size, classId, true, out failure, out var tweaks, out var grids, out var cutouts, out var cursor, out var queue); @@ -23,35 +46,48 @@ internal sealed record OwnWallCompleteInputs(OwnWallSixPhaseGeometryHistories Hi var c = cursor!; c.ExactWallCompleteInputs = true; var objects = new List(); + int failedIndex = 0, failedPosition = 0; + ushort failedClass = 0; + TfField? failedField = null; try { for (int index = histories.TargetQueueIndex + 1; index < queue!.Count; index++) { var (cls, handle) = queue[index]; - failure = $"late:{index}:{cls}:schema"; - if (!IsCompleteWallInputClass(cls)) return null; - var fields = SerializationFields(cls) ?? throw Fail; + if (!IsCompleteWallInputClass(cls) || SerializationFields(cls) is not { } fields) + { failure = $"late:{index}:{cls}:schema"; return null; } + failedIndex = index; + failedClass = cls; int first = c.Pos - start; - var retained = new List(); + // The reader consumes the grid panel ids, location curve, and the helper's loop links. + List? retained = retainAll || cls is 901 or 938 or 1736 or 4041 ? [] : null; foreach (var field in fields) { - failure = $"late:{index}:{cls}:{field.Declaring}.{field.Name}:{c.Pos - start}"; int fieldStart = c.Pos, queueStart = queue.Count; + failedField = field; + failedPosition = fieldStart - start; ReadField(c, field, queue, 1, null); if (queue.Count > 100_000) throw Fail; - retained.Add(new(field.Declaring, field.Name, fieldStart - start, c.Pos - start, - data.AsSpan(fieldStart, c.Pos - fieldStart).ToArray(), - Enumerable.Range(queueStart, queue.Count - queueStart).ToArray())); + if (retained != null) + retained.Add(new(field.Declaring, field.Name, fieldStart - start, c.Pos - start, + data.AsSpan(fieldStart, c.Pos - fieldStart).ToArray(), + Enumerable.Range(queueStart, queue.Count - queueStart).ToArray())); } - objects.Add(new(index, cls, handle, first, c.Pos - start, retained)); + if (retained != null) objects.Add(new(index, cls, handle, first, c.Pos - start, retained)); } failure = "late-footer"; if (c.Pos != c.End) return null; failure = null; return new(new(histories, tweaks, grids, cutouts), objects, - data.AsSpan(start, checked((int)size + 16)).ToArray(), c.Pos - start); + retainAll ? data.AsSpan(start, checked((int)size + 16)).ToArray() : [], c.Pos - start); + } + catch (DecodeFail) + { + failure = failedField is { } field + ? $"late:{failedIndex}:{failedClass}:{field.Declaring}.{field.Name}:{failedPosition}" + : $"late:{failedIndex}:{failedClass}:schema"; + return null; } - catch (DecodeFail) { return null; } } private static bool IsCompleteWallInputClass(ushort cls) => cls is diff --git a/src/RvtIO/Parsing/TfBlockDeserializer.WallExtrusionHelper.cs b/src/RvtIO/Parsing/TfBlockDeserializer.WallExtrusionHelper.cs index 444e59db..bb015221 100644 --- a/src/RvtIO/Parsing/TfBlockDeserializer.WallExtrusionHelper.cs +++ b/src/RvtIO/Parsing/TfBlockDeserializer.WallExtrusionHelper.cs @@ -9,9 +9,13 @@ internal sealed record OwnWallHelperInput(ushort RootClassId, bool Present, bool /// Reads the profile helper from the complete owned FIFO of an own wall root (class 3524/361). /// Null when the frame is not completely readable or the helper is ambiguous (several cells, unknown loop class). - internal static OwnWallHelperInput? ExtractOwnWallHelperInput(byte[] data, int start, uint size, ushort classId) + internal static OwnWallHelperInput? ExtractOwnWallHelperInput(byte[] data, int start, uint size, ushort classId, + WallCompleteInputRead? shared = null) { - if (ExtractOwnWallCompleteInputs(data, start, size, classId, out _) is not { } input) return null; + var input = shared == null + ? ExtractOwnWallCompleteInputs(data, start, size, classId, out _) + : shared.Read(out _); + if (input == null) return null; var helpers = input.LaterObjects.Where(o => o.ClassId == 4041).ToArray(); if (helpers.Length == 0) return new(classId, false, false, []); if (helpers.Length != 1) return null; diff --git a/src/RvtIO/Parsing/TfBlockDeserializer.WallLocationLine.cs b/src/RvtIO/Parsing/TfBlockDeserializer.WallLocationLine.cs index aaaf1b15..e973e67a 100644 --- a/src/RvtIO/Parsing/TfBlockDeserializer.WallLocationLine.cs +++ b/src/RvtIO/Parsing/TfBlockDeserializer.WallLocationLine.cs @@ -6,7 +6,8 @@ internal static partial class TfBlockDeserializer { // Serialized driver input only: this does not confirm the geometry state. internal static CurveDriverData? ExtractOwnWallLocationLine( - byte[] data, int start, uint size, ushort classId, out string? failure) + byte[] data, int start, uint size, ushort classId, out string? failure, + WallCompleteInputRead? complete = null) { var references = ExtractOwnWallReferenceGeometryInputs(data, start, size, classId, out failure); if (references == null) return null; @@ -15,7 +16,9 @@ internal static partial class TfBlockDeserializer var drivers = references.CurveDrivers.Where(d => d.QueueIndex == driverIndex).ToArray(); if (drivers.Length != 1 || drivers[0].ControlData.Handle != 0 || drivers[0].Curve is not { ClassId: 1736, QueueIndex: int curveIndex }) return null; - var input = ExtractOwnWallCompleteInputs(data, start, size, classId, out failure); + var input = complete == null + ? ExtractOwnWallCompleteInputs(data, start, size, classId, out failure) + : complete.Read(out failure); if (input == null) return null; failure = "location-curve"; var history = input.Histories.Histories; diff --git a/src/RvtIO/Parsing/TfBlockDeserializer.cs b/src/RvtIO/Parsing/TfBlockDeserializer.cs index e88343d6..b1cffe68 100644 --- a/src/RvtIO/Parsing/TfBlockDeserializer.cs +++ b/src/RvtIO/Parsing/TfBlockDeserializer.cs @@ -27,24 +27,83 @@ namespace RvtIO.Parsing; /// internal static partial class TfBlockDeserializer { - internal sealed record TfField(string Name, byte Type, byte Mods, int? Ref, int? Cnt, int Declaring = 0); + internal sealed record TfField(string Name, byte Type, byte Mods, int? Ref, int? Cnt, int Declaring = 0) + { + private readonly string _name = Name; + private readonly int _declaring = Declaring; + private CaptureKeys? _captureKeys; + + public string Name + { + get => _name; + init { _name = value; _captureKeys = null; } + } + + public int Declaring + { + get => _declaring; + init { _declaring = value; _captureKeys = null; } + } + + internal string QualifiedKey => Keys.Qualified; + internal string? ProductionCaptureKey => Keys.Production; + + private CaptureKeys Keys => Volatile.Read(ref _captureKeys) ?? BuildCaptureKeys(); + + private CaptureKeys BuildCaptureKeys() + { + string key = Declaring.ToString(System.Globalization.CultureInfo.InvariantCulture) + ":" + Name; + var keys = new CaptureKeys(key, IsCapturedInProduction(key) ? key : null); + return Interlocked.CompareExchange(ref _captureKeys, keys, null) ?? keys; + } + + private sealed record CaptureKeys(string Qualified, string? Production); + + // Copying a field can change its declaring class or name. Capture keys are derived, not field identity. + public bool Equals(TfField? other) => other != null && Name == other.Name && Type == other.Type + && Mods == other.Mods && Ref == other.Ref && Cnt == other.Cnt && Declaring == other.Declaring; + public override int GetHashCode() => HashCode.Combine(Name, Type, Mods, Ref, Cnt, Declaring); + } internal sealed record TfClass(string Name, int? Base, List Fields); + // A root often has no rows in several of its parameter stores. + internal struct NativeRows : IReadOnlyList + { + private static readonly List Empty = []; + private List? _items; + + public readonly int Count => _items?.Count ?? 0; + public readonly T this[int index] => (_items ?? Empty)[index]; + public void Add(T item) => (_items ??= new()).Add(item); + public void EnsureAdditionalCapacity(int count) + { + if (count > 0) (_items ??= new(count)).EnsureCapacity(Count + count); + } + public void AddRange(NativeRows rows) + { + if (rows.Count > 0) (_items ??= new(rows.Count)).AddRange(rows._items!); + } + + public readonly List.Enumerator GetEnumerator() => (_items ?? Empty).GetEnumerator(); + readonly IEnumerator IEnumerable.GetEnumerator() => ((IEnumerable)(_items ?? Empty)).GetEnumerator(); + readonly System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() => GetEnumerator(); + } + internal sealed class NativeParams { /// All root-queued native parameter stores were decoded before the /// non-parameter deferred tail. False also covers a partially decoded store. public bool RootParameterStoresComplete { get; set; } /// Class tags of the cells of the element's CellList, when the deferred walk reached that object. - public List? CellClasses { get; set; } + public int[]? CellClasses { get; set; } public HashSet? RoofExtrusionFaceTags { get; set; } /// The deferred walk consumed every queued object of the record (so the NamedParams and cells are complete). public bool TailWalkComplete { get; set; } public IReadOnlyList? ExtensibleStorage { get; set; } - public List<(int ParamId, double Value)> Doubles { get; } = new(); - public List<(int ParamId, int Value)> Ints { get; } = new(); - public List<(int ParamId, string Value)> Strings { get; } = new(); - public List<(int ParamId, int Value)> ElementIds { get; } = new(); + public NativeRows<(int ParamId, double Value)> Doubles; + public NativeRows<(int ParamId, int Value)> Ints; + public NativeRows<(int ParamId, string Value)> Strings; + public NativeRows<(int ParamId, int Value)> ElementIds; /// Named schema fields captured during the walk (interesting ElementId /// refs like m_masterSymbolId / m_scheduleOnlyLevelId and small enums). @@ -53,7 +112,7 @@ internal sealed class NativeParams public Dictionary StringFields { get; } = new(); /// FamilyParams.m_params items in stored order (family parameters of the element). - public List NamedParams { get; } = new(); + public NativeRows NamedParams; public int Count => Doubles.Count + Ints.Count + Strings.Count + ElementIds.Count + Fields.Count + DoubleFields.Count + StringFields.Count; } @@ -306,12 +365,10 @@ private static void DiagNoteQueued(List<(ushort, uint)> queue) private static readonly HashSet DerivedInputDeclaringClasses = DerivedInputFieldKeys .Select(key => int.Parse(key[..key.IndexOf(':')], System.Globalization.CultureInfo.InvariantCulture)).ToHashSet(); - private static bool WantField(TfField f) => - (capturingNamedParam && f.Declaring == 715) - || CaptureAllFields - || (DerivedInputDeclaringClasses.Contains(f.Declaring) && DerivedInputFieldKeys.Contains(FieldKey(f))) - || (NativeFieldParameters.DeclaringClasses.Contains(f.Declaring) - && NativeFieldParameters.Keys.Contains(FieldKey(f))); + private static string? CaptureFieldKey(TfField f) => + CaptureAllFields || (capturingNamedParam && f.Declaring == 715) + ? FieldKey(f) + : f.ProductionCaptureKey; /// Every "Declaring:Name" key a production parse keeps, and the bare field names kept from the root. internal static IEnumerable CapturedKeys => DerivedInputFieldKeys.Concat(NativeFieldParameters.Keys); @@ -321,7 +378,7 @@ private static bool WantField(TfField f) => internal static bool IsCapturedInProduction(string key) => NativeFieldParameters.Keys.Contains(key) || DerivedInputFieldKeys.Contains(key); - private static string FieldKey(TfField f) => f.Declaring.ToString(System.Globalization.CultureInfo.InvariantCulture) + ":" + f.Name; + private static string FieldKey(TfField f) => f.QualifiedKey; /// Keyed (Declaring:Name) entries of a scratch capture are the only ones merged into the real result. private static void MergeKeyed(NativeParams from, NativeParams into) @@ -388,6 +445,7 @@ private static void MergeKeyed(NativeParams from, NativeParams into) private static readonly Lazy> _schemas = new(LoadSchemas); private static readonly System.Collections.Concurrent.ConcurrentDictionary> _chainCache = new(); + private static readonly Lazy _ancestors = new(BuildAncestors); public static Dictionary Schemas => _schemas.Value; @@ -409,37 +467,46 @@ private static Dictionary LoadSchemas() if (_chainCache.TryGetValue(classId, out var cached)) return cached; var schemas = Schemas; if (!schemas.ContainsKey(classId)) return null; - var chain = new List(); + Span chain = stackalloc int[32]; int? cur = classId; - int guard = 0; - while (cur.HasValue && schemas.TryGetValue(cur.Value, out var c) && guard++ < 32) + int count = 0, fieldCount = 0; + while (cur is int id && count < chain.Length && schemas.TryGetValue(id, out var c)) { - chain.Add(c); + chain[count++] = id; + fieldCount += c.Fields.Count; cur = c.Base; } - chain.Reverse(); - var fields = new List(); - var idByClass = new Dictionary(); - foreach (var kv in schemas) idByClass[kv.Value] = kv.Key; - foreach (var c in chain) + var fields = new List(fieldCount); + for (int index = count - 1; index >= 0; index--) { - int decl = idByClass.TryGetValue(c, out int d0) ? d0 : 0; - foreach (var fl in c.Fields) fields.Add(fl with { Declaring = decl }); + int declaring = chain[index]; + foreach (var field in schemas[declaring].Fields) fields.Add(field with { Declaring = declaring }); } return _chainCache.GetOrAdd(classId, fields); } public static bool IsSubclassOf(int classId, int baseClassId) { - int guard = 0; - int? current = classId; - while (current.HasValue && guard++ < 32) + if (classId == baseClassId) return true; + var ancestors = _ancestors.Value; + return (uint)classId < (uint)ancestors.Length + && ancestors[classId].AsSpan().Contains(baseClassId); + } + + private static int[]?[] BuildAncestors() + { + var schemas = Schemas; + var result = new int[]?[schemas.Keys.DefaultIfEmpty(-1).Max() + 1]; + Span chain = stackalloc int[31]; + foreach (var (classId, schema) in schemas) { - if (current.Value == baseClassId) return true; - current = Schemas.TryGetValue(current.Value, out var schema) - ? schema.Base : null; + int count = 0; + for (int? parent = schema.Base; parent is int id && count < chain.Length; + parent = schemas.GetValueOrDefault(id)?.Base) + chain[count++] = id; + if (count > 0) result[classId] = chain[..count].ToArray(); } - return false; + return result; } private sealed class Cursor @@ -547,7 +614,8 @@ private sealed class Cursor } private sealed class DecodeFail : Exception { } - private static readonly DecodeFail Fail = new(); + [ThreadStatic] private static DecodeFail? _fail; + private static DecodeFail Fail => _fail ??= new(); // Param-store deferred tags -> record class ids (record schemas drive field order). private static readonly Dictionary ParamSetTags = new() @@ -562,6 +630,9 @@ private sealed class DecodeFail : Exception { } /// reaching the deferred region or the class has no schema. /// public static NativeParams? ExtractParams(byte[] d, int blockStart, uint dataSize, ushort classId) + => ExtractParams(d, blockStart, dataSize, classId, rootOnly: false); + + private static NativeParams? ExtractParams(byte[] d, int blockStart, uint dataSize, ushort classId, bool rootOnly) { var fields = SerializationFields(classId); if (fields == null) return null; @@ -600,6 +671,7 @@ private sealed class DecodeFail : Exception { } DiagnosticSink.WriteLine($"rootfail eid={BitConverter.ToUInt32(d, blockStart)} cls={classId} at {lastReadField} trail={string.Join(">", readTrail ?? new())}"); return null; } + if (rootOnly) return res; try { @@ -618,34 +690,41 @@ private sealed class DecodeFail : Exception { } if (!ParamSetTags.TryGetValue(cls, out var tag)) break; // geometry tail begins uint n = ReadU32(cur); if (n > 100_000) return res; - var recFields = SerializationFields(tag.RecordClass); - if (recFields == null) return res; - for (uint i = 0; i < n; i++) + int possibleRows = Math.Min((int)n, (cur.End - cur.Pos) / (tag.Kind == 'D' ? 12 : 8)); + // These four layouts are fixed in the shipped 2022 schema. Double stores + // put the value before the ID, while the other stores put the ID first. + switch (tag.Kind) { - int paramId = 0; double dv = 0; int iv = 0; string sv = ""; - foreach (var rf in recFields) - { - switch (rf.Name) + case 'D': + res.Doubles.EnsureAdditionalCapacity(possibleRows); + for (int i = 0; i < n; i++) { - case "m_paramId": paramId = ReadI32(cur); break; - case "m_value" when tag.Kind == 'D': dv = ReadF64(cur); break; - case "m_value" when tag.Kind == 'A': sv = ReadString(cur); break; - case "m_value": iv = ReadI32(cur); break; - default: ReadField(cur, rf, new List<(ushort, uint)>(), 0, null); break; + double value = ReadF64(cur); + res.Doubles.Add((ReadI32(cur), value)); } - } - switch (tag.Kind) - { - case 'D': res.Doubles.Add((paramId, dv)); break; - case 'I': res.Ints.Add((paramId, iv)); break; - case 'A': res.Strings.Add((paramId, sv)); break; - case 'E': res.ElementIds.Add((paramId, iv)); break; - } + break; + case 'I': + res.Ints.EnsureAdditionalCapacity(possibleRows); + for (int i = 0; i < n; i++) res.Ints.Add((ReadI32(cur), ReadI32(cur))); + break; + case 'A': + res.Strings.EnsureAdditionalCapacity(possibleRows); + for (int i = 0; i < n; i++) res.Strings.Add((ReadI32(cur), ReadString(cur))); + break; + case 'E': + res.ElementIds.EnsureAdditionalCapacity(possibleRows); + for (int i = 0; i < n; i++) res.ElementIds.Add((ReadI32(cur), ReadI32(cur))); + break; } } - res.RootParameterStoresComplete = !queue.Skip(qi) - .Any(entry => ParamSetTags.ContainsKey(entry.Cls)); + res.RootParameterStoresComplete = true; + for (int index = qi; index < queue.Count; index++) + if (ParamSetTags.ContainsKey(queue[index].Cls)) + { + res.RootParameterStoresComplete = false; + break; + } // Walk the remaining deferred objects in queue order for NativeFieldParameters keys // (everything with RVTIO_ALL_FIELDS=2). Name-based captures are kept out via a scratch result. @@ -654,7 +733,8 @@ private sealed class DecodeFail : Exception { } var tail = new NativeParams(); var walked = CaptureAllFields ? new System.Text.StringBuilder() : null; string lastField = ""; - var refOccurrences = new Dictionary(); + Dictionary? refOccurrences = null; + NativeParams? namedScratch = null; bool tailDone = false; try { @@ -667,11 +747,12 @@ private sealed class DecodeFail : Exception { } if (qf == null) break; if (queue[qi].Cls == 715) { - var item = new NativeParams(); + var item = namedScratch ??= new NativeParams(); capturingNamedParam = true; try { foreach (var sf in qf) ReadField(cur, sf, queue, 1, item); } finally { capturingNamedParam = false; } tail.NamedParams.Add(NamedParamOf(item)); + ClearNamedParamFields(item); continue; } cur.TailClassId = queue[qi].Cls; @@ -697,9 +778,13 @@ private sealed class DecodeFail : Exception { } bool driveSpline = qi == cur.CurveDriverCurveQueueIndex && queue[qi].Cls == 2020; if (driveSpline) cur.HermiteNodes = new List(); int cellsBefore = queue[qi].Cls == 653 ? queue.Count : -1; - foreach (var sf in qf) { lastField = FieldKey(sf) + "/" + sf.Type + "/" + sf.Mods + "/" + sf.Ref; ReadField(cur, sf, queue, 1, tail); } + foreach (var sf in qf) + { + if (walked != null) lastField = FieldKey(sf) + "/" + sf.Type + "/" + sf.Mods + "/" + sf.Ref; + ReadField(cur, sf, queue, 1, tail); + } if (cellsBefore >= 0 && ReferenceEquals(queue, cur.RootQueue)) - tail.CellClasses = queue.Skip(cellsBefore).Select(entry => (int)entry.Item1).ToList(); + tail.CellClasses = ReadQueuedClasses(queue, cellsBefore); KeepAnyAttachTop(tail, queue[qi].Cls, attachedTopBefore); if (driveSpline) { @@ -716,7 +801,7 @@ private sealed class DecodeFail : Exception { } .Append(",f=").Append(tail.Fields.GetValueOrDefault("96:m_flags")).Append("},"); // Repeated reference objects in stored order: FamilyInstance.m_refs FamilyLevelRef (column // base, then top) and FamilySymbol.m_refs StructSetbackSymFamRef (framing start, then end). - if (ReferenceEquals(queue, cur.RootQueue)) CopyOccurrence(tail, qf, queue[qi].Cls, refOccurrences); + if (ReferenceEquals(queue, cur.RootQueue)) CopyOccurrence(tail, qf, queue[qi].Cls, ref refOccurrences); if (driveLine) { string curveKey = mullionLine ? "2520:m_pCurve" : "87:m_pCrv"; @@ -744,7 +829,8 @@ private sealed class DecodeFail : Exception { } if (walked != null) tail.StringFields["walk:"] = walked.ToString() + " queue=" + queue.Count + " rest=" + (cur.End - cur.Pos); res.TailWalkComplete = tailDone; MergeKeyed(tail, res); - res.NamedParams.AddRange(tail.NamedParams); + if (res.NamedParams.Count == 0) res.NamedParams = tail.NamedParams; + else res.NamedParams.AddRange(tail.NamedParams); if (tail.CellClasses != null) res.CellClasses = tail.CellClasses; } @@ -756,7 +842,7 @@ private sealed class DecodeFail : Exception { } if (classId == 3524) { bool sawDriver = false, gotLine = false; - var wallOccurrences = new Dictionary(); + Dictionary? wallOccurrences = null; var walkedWall = CaptureAllFields ? new System.Text.StringBuilder() : null; // The wall's own fields were read from its root; the deferred objects below carry fields of the same // names (GeomGenerator.m_id of every step, ...) that must not replace them. @@ -798,9 +884,9 @@ private sealed class DecodeFail : Exception { } int wallCellsBefore = cls == 653 ? queue.Count : -1; foreach (var sf in qf) ReadField(cur, sf, queue, 1, res); if (wallCellsBefore >= 0 && ReferenceEquals(queue, cur.RootQueue)) - res.CellClasses = queue.Skip(wallCellsBefore).Select(entry => (int)entry.Item1).ToList(); + res.CellClasses = ReadQueuedClasses(queue, wallCellsBefore); KeepAnyAttachTop(res, cls, attachedTopBefore); - CopyOccurrence(res, qf, cls, wallOccurrences); + CopyOccurrence(res, qf, cls, ref wallOccurrences); if (captureLine) { if (cur.WallLineCapture!.Count >= 8) @@ -852,9 +938,10 @@ internal static void KeepAnyAttachTop(NativeParams target, ushort cls, int befor /// FamilyLevelRef (column base, then top), FamilySymbol.m_refs StructSetbackSymFamRef (framing start, then end) /// and the curtain wall SpacingRuleInst pair (horizontal, then vertical grid). The connector calculations (2380, /// 2381, 2382, 3556) are also numbered across the classes, as "calc#n:class" and "calc#n:occurrence". - private static void CopyOccurrence(NativeParams target, List fields, ushort cls, Dictionary occurrences) + private static void CopyOccurrence(NativeParams target, List fields, ushort cls, ref Dictionary? occurrences) { if (cls is not (1801 or 3795 or 369 or 3556 or 3558 or 3950 or 2381 or 2382 or 2380 or 771)) return; + occurrences ??= new(); int occurrence = occurrences.TryGetValue(cls, out int seen) ? seen : 0; occurrences[cls] = occurrence + 1; if (cls is 2380 or 2381 or 2382 or 3556) @@ -885,6 +972,14 @@ private static void CopyOccurrence(NativeParams target, List fields, us } } + private static int[] ReadQueuedClasses(List<(ushort Cls, uint Id)> queue, int start) + { + var classes = new int[queue.Count - start]; + for (int i = 0; i < classes.Length; i++) + classes[i] = queue[start + i].Cls; + return classes; + } + /// Reads ROOM_NAME only from an owned RoomElem root and its complete four /// parameter stores. Geometry after the stores is outside this scope. The dedicated /// cursor keeps the RoomBoundingItem correction out of the legacy partial decoder. @@ -1138,6 +1233,13 @@ internal static bool TryExtractExactStairsTypeRoot( return true; } + private static readonly Lazy?> OwnElementFields = new(() => + { + var fields = SerializationFields(37); + return fields != null && HasExactSchemaField(fields, 37, "m_id", 14, 0, 20) + && HasExactSchemaField(fields, 37, "m_docAccess", 14, 0, null) ? fields : null; + }); + /// Own semantic Element class/identity prefix only, not a complete subtype or /// geometry graph. Header, size/footer, project document handle and named Element.m_id /// must agree. GElement frames cannot supply an Element's semantic class. @@ -1153,14 +1255,12 @@ internal static bool TryExtractOwnElementClass( || BitConverter.ToUInt32(data, (int)end - 4) != size) return false; uint headerOwner = BitConverter.ToUInt32(data, start); - var fields = SerializationFields(37); - if (headerOwner == 0 && classId != 3065 || headerOwner > int.MaxValue || fields == null - || !HasExactSchemaField(fields, 37, "m_id", 14, 0, 20) - || !HasExactSchemaField(fields, 37, "m_docAccess", 14, 0, null)) + var fields = OwnElementFields.Value; + if (headerOwner == 0 && classId != 3065 || headerOwner > int.MaxValue || fields == null) return false; var cursor = new Cursor { D = data, Pos = start + 14, End = (int)end - 4, RootClassId = classId }; var queue = new List<(ushort, uint)>(); - var root = new NativeParams(); + int namedOwner = -1; try { foreach (var field in fields) @@ -1170,10 +1270,11 @@ internal static bool TryExtractOwnElementClass( // Only the explicit project document handle, not an anonymous or foreign document. if (ReadU32(cursor) != 1) return false; } - else ReadField(cursor, field, queue, 0, root); + else if (field.Name == "m_id") namedOwner = ReadI32(cursor); + else ReadField(cursor, field, queue, 0, null); if (queue.Count > 100_000) return false; } - if (!root.Fields.TryGetValue("m_id", out int namedOwner) || namedOwner != headerOwner) + if (namedOwner != headerOwner) return false; ownerId = namedOwner; return true; @@ -1812,6 +1913,11 @@ private static void ReadDeferredObject( { uint count = ReadU32(cur); if (count > 100_000) throw Fail; + if (!CaptureAllFields) + { + SkipParameterStoreRows(cur, parameterStore.Kind, count); + return; + } var recordFields = SerializationFields(parameterStore.RecordClass) ?? throw Fail; for (uint index = 0; index < count; index++) @@ -1825,6 +1931,25 @@ private static void ReadDeferredObject( ReadField(cur, field, queue, 1, null); } + // Same four layouts as ExtractParams. These callers only need the deferred queue position. + private static void SkipParameterStoreRows(Cursor c, char kind, uint count) + { + if (kind == 'A') + { + for (uint index = 0; index < count; index++) + { + ReadI32(c); + uint length = ReadU32(c); + if (length > 10_000 || length * 2 > c.End - c.Pos) throw Fail; + c.Pos += (int)length * 2; + } + return; + } + int bytes = (int)count * (kind == 'D' ? 12 : 8); + if (bytes > c.End - c.Pos) throw Fail; + c.Pos += bytes; + } + /// Diagnostic-only: full deferred-queue trace of an owner block. /// Walks the owner's root schema fields (queuing every owned/polymorphic /// pointer), then resumes the FIFO, generically decoding every queued item via @@ -2118,15 +2243,20 @@ public static bool TryExtractNewCurtainWallTypeFunction( } private static bool HasExactOwnElementRoot(byte[] data, int start, uint size, ushort classId) + => ReadExactOwnElementRoot(data, start, size, classId) != null; + + private static NativeParams? ReadExactOwnElementRoot( + byte[] data, int start, uint size, ushort classId, bool includeDeferredFields = false) { if (start < 0 || start > data.Length - 16 || size > int.MaxValue || (long)start + 16 + size > data.Length || BitConverter.ToUInt32(data, start + 8) != size || BitConverter.ToUInt16(data, start + 12) != classId) - return false; - var root = ExtractParams(data, start, size, classId); + return null; + // Deferred merges keep the bare named fields of the root. + var root = ExtractParams(data, start, size, classId, rootOnly: !includeDeferredFields && !CaptureAllFields); return root != null && root.Fields.TryGetValue("m_id", out int owner) - && owner > 0 && (uint)owner == BitConverter.ToUInt32(data, start); + && owner > 0 && (uint)owner == BitConverter.ToUInt32(data, start) ? root : null; } /// The field that names the type of a system occurrence (declaring class and field name), null for another class. @@ -2148,22 +2278,22 @@ _ when IsSubclassOf(classId, 602) => (602, "m_idType"), internal static int? ExtractSystemOccurrenceTypeId(byte[] data, int start, uint size, ushort classId) { var field = SystemOccurrenceTypeField(classId); - if (field is not var (declaring, name) || !HasExactOwnElementRoot(data, start, size, classId)) return null; + if (field is not var (declaring, name)) return null; var fields = SerializationFields(classId); if (fields == null || !HasExactSchemaField(fields, declaring, name, 14, 0, 20)) return null; - var root = ExtractParams(data, start, size, classId)!; // RbsCurve.m_idType is captured under its declaring-class key, as a name shared with other classes would be ambiguous. - return root.Fields.TryGetValue(declaring == 602 ? "602:m_idType" : name, out int typeId) + var root = ReadExactOwnElementRoot(data, start, size, classId, includeDeferredFields: declaring == 602); + return root != null && root.Fields.TryGetValue(declaring == 602 ? "602:m_idType" : name, out int typeId) && typeId > 0 && typeId != BitConverter.ToInt32(data, start) ? typeId : null; } internal static int? ExtractFamilyInstanceSymbolId(byte[] data, int start, uint size, ushort classId) { - if (classId != 1794 || !HasExactOwnElementRoot(data, start, size, classId)) return null; + if (classId != 1794) return null; var fields = SerializationFields(classId); if (fields == null || !HasExactSchemaField(fields, 1794, "m_masterSymbolId", 14, 0, 20)) return null; - var root = ExtractParams(data, start, size, classId)!; - return root.Fields.TryGetValue("m_masterSymbolId", out int symbolId) + var root = ReadExactOwnElementRoot(data, start, size, classId); + return root != null && root.Fields.TryGetValue("m_masterSymbolId", out int symbolId) && symbolId > 0 && symbolId != BitConverter.ToInt32(data, start) ? symbolId : null; } @@ -2389,13 +2519,13 @@ private static bool TryReadOwnRootDiscriminator(byte[] data, int start, uint siz internal static int? ExtractRoofOrRailingTypeId(byte[] data, int start, uint size, ushort classId) { - if (classId is not (3451 or 3054 or 485) || !HasExactOwnElementRoot(data, start, size, classId)) return null; + if (classId is not (3451 or 3054 or 485)) return null; int declaring = classId == 485 ? 485 : 1605; string name = classId == 485 ? "m_stairsRailingAttrId" : "m_roofAttributesId"; var fields = SerializationFields(classId); if (fields == null || !HasExactSchemaField(fields, declaring, name, 14, 0, 20)) return null; - var root = ExtractParams(data, start, size, classId)!; - return root.Fields.TryGetValue(name, out int typeId) + var root = ReadExactOwnElementRoot(data, start, size, classId); + return root != null && root.Fields.TryGetValue(name, out int typeId) && typeId > 0 && typeId != BitConverter.ToInt32(data, start) ? typeId : null; } @@ -3090,6 +3220,11 @@ private sealed class StepLayoutSearch failure = "parameters"; uint count = ReadU32(cur); if (count > 100_000) return null; + if (!CaptureAllFields) + { + SkipParameterStoreRows(cur, parameterStore.Kind, count); + continue; + } var recordFields = SerializationFields(parameterStore.RecordClass); if (recordFields == null) return null; for (uint index = 0; index < count; index++) @@ -3226,6 +3361,11 @@ private sealed class StepLayoutSearch failure = "parameters"; uint count = ReadU32(cur); if (count > 100_000) return null; + if (!CaptureAllFields) + { + SkipParameterStoreRows(cur, parameterStore.Kind, count); + continue; + } var recordFields = SerializationFields(parameterStore.RecordClass); if (recordFields == null) return null; for (uint index = 0; index < count; index++) @@ -4495,7 +4635,7 @@ private static void ReadField(Cursor c, TfField f, List<(ushort, uint)> queue, i { string sv = ReadString(c); if (capture != null && CapturedStringFields.Contains(f.Name)) capture.StringFields[f.Name] = sv; - if (capture != null && WantField(f)) capture.StringFields[FieldKey(f)] = sv; + if (capture != null && CaptureFieldKey(f) is { } stringKey) capture.StringFields[stringKey] = sv; return; } if (hi == 1) @@ -4647,13 +4787,13 @@ private static void ReadScalar(Cursor c, TfField f, List<(ushort, uint)> queue, c.CutTopologyTrace?.Add($"q{c.CurrentDeferredQueueIndex}:" + $"{c.CurrentDeferredClassId}:{f.Name}={bv}"); if (capture != null && CapturedFields.Contains(f.Name)) capture.Fields[f.Name] = bv; - if (capture != null && WantField(f)) capture.Fields[FieldKey(f)] = bv; + if (capture != null && CaptureFieldKey(f) is { } flagKey) capture.Fields[flagKey] = bv; if (capture != null && f.Declaring == 699 && f.Name == "m_dormant" && c.AttachBaseOrTop is 0 or 1) capture.Fields[$"699:dormant@{c.AttachBaseOrTop}"] = bv; return; } case 0x02: case 0x03: - if (capture != null && c.Pos < c.End && WantField(f)) capture.Fields[FieldKey(f)] = c.D[c.Pos]; + if (capture != null && c.Pos < c.End && CaptureFieldKey(f) is { } byteKey) capture.Fields[byteKey] = c.D[c.Pos]; if (!c.Take(1)) throw Fail; return; case 0x04: @@ -4694,14 +4834,14 @@ private static void ReadScalar(Cursor c, TfField f, List<(ushort, uint)> queue, // Wall-join type: one per joined end, keyed by the pair's end index. if (capture != null && f.Name == "m_wallJoinType" && c.JoinEnd >= 0 && c.JoinEnd < 64) capture.Fields[$"wallJoinType@{c.JoinEnd}"] = v; - if (capture != null && WantField(f)) capture.Fields[FieldKey(f)] = v; + if (capture != null && CaptureFieldKey(f) is { } intKey) capture.Fields[intKey] = v; return; } case 0x05: case 0x06: - if (capture != null && c.Pos + 4 <= c.End && WantField(f)) + if (capture != null && c.Pos + 4 <= c.End && CaptureFieldKey(f) is { } scalarKey) { - if (f.Type == 0x05) capture.Fields[FieldKey(f)] = BitConverter.ToInt32(c.D, c.Pos); - else capture.DoubleFields[FieldKey(f)] = BitConverter.ToSingle(c.D, c.Pos); + if (f.Type == 0x05) capture.Fields[scalarKey] = BitConverter.ToInt32(c.D, c.Pos); + else capture.DoubleFields[scalarKey] = BitConverter.ToSingle(c.D, c.Pos); } if (!c.Take(4)) throw Fail; return; @@ -4716,7 +4856,7 @@ private static void ReadScalar(Cursor c, TfField f, List<(ushort, uint)> queue, && (CapturedDoubleFields.Contains(f.Name) || captureStairLength)) capture.DoubleFields[f.Name] = dv; - if (capture != null && WantField(f)) capture.DoubleFields[FieldKey(f)] = dv; + if (capture != null && CaptureFieldKey(f) is { } doubleKey) capture.DoubleFields[doubleKey] = dv; return; } case 0x0A: @@ -4761,7 +4901,7 @@ private static void ReadScalar(Cursor c, TfField f, List<(ushort, uint)> queue, { ReadPtr(c, queue); // Keyed capture of an owned pointer: 0 null, -1 external/untagged, otherwise the class tag. - if (capture != null && WantField(f)) capture.Fields[FieldKey(f)] = lastPolyClass; + if (capture != null && CaptureFieldKey(f) is { } ownedKey) capture.Fields[ownedKey] = lastPolyClass; return; } if (f.Ref == 20) // bare ElementId @@ -4787,7 +4927,7 @@ private static void ReadScalar(Cursor c, TfField f, List<(ushort, uint)> queue, && (CapturedFields.Contains(f.Name) || captureStairTypeId)) capture.Fields[f.Name] = v; - if (capture != null && WantField(f)) capture.Fields[FieldKey(f)] = v; + if (capture != null && CaptureFieldKey(f) is { } idKey) capture.Fields[idKey] = v; return; } if (f.Ref.HasValue) // inline struct @@ -4805,7 +4945,7 @@ private static void ReadScalar(Cursor c, TfField f, List<(ushort, uint)> queue, if (capture != null && CapturedFields.Contains(f.Name)) capture.Fields[f.Name] = unchecked((int)handle); // Keyed capture of a pointer field: 0 null, -1 plain handle, otherwise the class tag of the owned object. - if (capture != null && WantField(f)) capture.Fields[FieldKey(f)] = lastPolyClass; + if (capture != null && CaptureFieldKey(f) is { } pointerKey) capture.Fields[pointerKey] = lastPolyClass; return; } default: throw Fail; @@ -4905,7 +5045,7 @@ private static bool TryFieldOverride(Cursor c, TfField f, List<(ushort, uint)> q { if (SerializationFields(45) is not [{ Name: "m_typeId", Type: 8, Mods: 96 }]) throw Fail; string forgeId = ReadString(c); - if (WantField(f)) capture.StringFields[FieldKey(f)] = forgeId; + if (CaptureFieldKey(f) is { } forgeKey) capture.StringFields[forgeKey] = forgeId; return true; } // SpatialElementCalculationPointRegenData.m_position is an XYZ struct (three doubles); read here so that they are @@ -5937,6 +6077,13 @@ private static bool IsTrackedStepTail(Cursor c, int tailStart) item.Fields.GetValueOrDefault("715:m_instance") != 0, item.Fields.GetValueOrDefault("715:m_reporting") != 0); + private static void ClearNamedParamFields(NativeParams item) + { + item.Fields.Clear(); + item.DoubleFields.Clear(); + item.StringFields.Clear(); + } + private static void ReadInlineContainer(Cursor c, int cls, List<(ushort, uint)> queue, int depth, NativeParams? capture = null) { @@ -5944,13 +6091,15 @@ private static void ReadInlineContainer(Cursor c, int cls, List<(ushort, uint)> if (n > 100_000) throw Fail; if (cls == 715 && capture != null) { + NativeParams? scratch = null; for (uint i = 0; i < n; i++) { - var item = new NativeParams(); + var item = scratch ??= new NativeParams(); capturingNamedParam = true; try { ReadInlineStruct(c, cls, queue, depth, item); } finally { capturingNamedParam = false; } capture.NamedParams.Add(NamedParamOf(item)); + ClearNamedParamFields(item); } return; } diff --git a/src/RvtIO/Parsing/TfStreamWalker.BlockSlices.cs b/src/RvtIO/Parsing/TfStreamWalker.BlockSlices.cs new file mode 100644 index 00000000..94e0d1bf --- /dev/null +++ b/src/RvtIO/Parsing/TfStreamWalker.BlockSlices.cs @@ -0,0 +1,122 @@ +namespace RvtIO.Parsing; + +internal static partial class TfStreamWalker +{ + private readonly record struct BlockSlice(long Start, int Chunk, uint Size, ushort Class, uint Owner); + + // The logical segment and class order match ScanBlocks. Only a selected block spanning + // physical chunks is copied. The visitor receives the offset in its actual backing array. + internal static void ScanBlockSlices(IReadOnlyList chunks, HashSet targetIds, BlockVisitor visit, + int segmentTarget = SegmentTarget) + { + if (targetIds.Count == 0 || chunks.Count == 0) return; + var offsets = new long[chunks.Count + 1]; + for (int i = 0; i < chunks.Count; i++) offsets[i + 1] = offsets[i] + chunks[i].Length; + + var currentGeometry = new List(); + var earlierGeometry = new List(); + var curves = new List(); + int next = 0; + long carry = 0; + while (next < chunks.Count) + { + long segmentStart = offsets[next] - carry; + int first = next; + while (next < chunks.Count && offsets[next + 1] - segmentStart <= segmentTarget) next++; + if (next == first) next++; + long segmentEnd = offsets[next]; + bool last = next == chunks.Count; + long scanEnd = last ? segmentEnd : Math.Max(segmentStart, segmentEnd - MaxTargetBlock); + long markerStart = segmentStart + 12; + long markerEnd = Math.Min(scanEnd + 12, segmentEnd - 1); + + int chunkIndex = markerStart < markerEnd ? ChunkAt(markerStart) : next; + Action recordMarker = RecordMarker; + for (; chunkIndex < next && offsets[chunkIndex] < markerEnd; chunkIndex++) + { + byte[] data = chunks[chunkIndex]; + if (data.Length == 0) continue; + int localStart = (int)Math.Max(0, markerStart - offsets[chunkIndex]); + int localEnd = (int)Math.Min(data.Length, markerEnd - offsets[chunkIndex]); + ScanMarkers(data, localStart, Math.Min(localEnd, data.Length - 1), recordMarker); + if (localEnd == data.Length && IsBlockMarker(data[^1], chunks[ChunkAt(offsets[chunkIndex + 1])][0])) + RecordMarker(data.Length - 1); + } + + Emit(currentGeometry); + Emit(earlierGeometry); + Emit(curves); + carry = Math.Min(MaxTargetBlock, segmentEnd - segmentStart); + + void RecordMarker(int marker) + { + long blockStart = offsets[chunkIndex] + marker - 12; + int source = marker >= 12 ? chunkIndex : ChunkAt(blockStart); + scoped ReadOnlySpan header; + Span crossChunkHeader = stackalloc byte[14]; + if (marker >= 12 && marker + 1 < chunks[chunkIndex].Length) + header = chunks[chunkIndex].AsSpan(marker - 12, 14); + else + { + CopyBlock(source, blockStart, crossChunkHeader); + header = crossChunkHeader; + } + + uint size = BitConverter.ToUInt32(header[8..]); + if (size < 20 || size >= MaxTargetBlock || blockStart + 16 + size > segmentEnd) return; + uint owner = BitConverter.ToUInt32(header); + if (!targetIds.Contains(owner)) return; + var matches = header[12] switch + { + 0xD7 => currentGeometry, + 0xD6 => earlierGeometry, + _ => curves, + }; + matches.Add(new(blockStart, source, size, BitConverter.ToUInt16(header[12..]), owner)); + } + } + + int ChunkAt(long position) + { + int low = 0, high = chunks.Count; + while (low < high) + { + int middle = low + (high - low) / 2; + if (offsets[middle + 1] <= position) low = middle + 1; + else high = middle; + } + return low; + } + + void CopyBlock(int chunk, long start, Span destination) + { + int offset = (int)(start - offsets[chunk]); + while (!destination.IsEmpty) + { + var source = chunks[chunk++].AsSpan(offset); + int length = Math.Min(destination.Length, source.Length); + source[..length].CopyTo(destination); + destination = destination[length..]; + offset = 0; + } + } + + void Emit(List matches) + { + foreach (var match in matches) + { + byte[] data = chunks[match.Chunk]; + int start = (int)(match.Start - offsets[match.Chunk]); + int length = (int)match.Size + 16; + if (length > data.Length - start) + { + data = GC.AllocateUninitializedArray(length); + CopyBlock(match.Chunk, match.Start, data); + start = 0; + } + visit(data, start, match.Size, match.Class, match.Owner); + } + matches.Clear(); + } + } +} diff --git a/src/RvtIO/Parsing/TfStreamWalker.cs b/src/RvtIO/Parsing/TfStreamWalker.cs index 0e52d322..e59d8978 100644 --- a/src/RvtIO/Parsing/TfStreamWalker.cs +++ b/src/RvtIO/Parsing/TfStreamWalker.cs @@ -1,3 +1,7 @@ +using System.Numerics; +using System.Runtime.InteropServices; +using System.Runtime.Intrinsics; + namespace RvtIO.Parsing; /// @@ -15,20 +19,62 @@ internal static partial class TfStreamWalker 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 int SegmentTarget = 1_400_000_000; + // Freeform family symbols can exceed the anchored walk's MaxBlock. + private const int MaxTargetBlock = 8_000_000; + + internal sealed class SegmentSources + { + private readonly List<(int Start, int End, byte[] Chunk)> _ranges = []; - /// 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. + internal void SetSegment(IReadOnlyList chunks, int start, int end, int carryLength) + { + _ranges.Clear(); + int position = carryLength; + for (int index = start; index < end; index++) + { + byte[] chunk = chunks[index]; + if (chunk.Length == 0) continue; + _ranges.Add((position, position + chunk.Length, chunk)); + position += chunk.Length; + } + } + + // Deferred consumers only need the block. Holding the walk's contiguous buffer + // would retain up to 1.4 GB for a single candidate. + internal (byte[] Data, int Start) Retain(byte[] segment, int start, int length) + { + int low = 0, high = _ranges.Count; + while (low < high) + { + int middle = (low + high) / 2; + if (_ranges[middle].End <= start) low = middle + 1; + else high = middle; + } + if (low < _ranges.Count) + { + var range = _ranges[low]; + if (start >= range.Start && length <= range.End - start) + return (range.Chunk, start - range.Start); + } + return (segment.AsSpan(start, length).ToArray(), 0); + } + } + + /// Walks the concatenated chunks, reporting positions on the caller thread. 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 = SegmentTarget, + SegmentSources? sources = null) { - // As in WalkStreaming: the carried overlap and two maximum-sized items must fit in a segment. if (segTarget <= 3 * MaxBlock) throw new ArgumentOutOfRangeException(nameof(segTarget)); long total = 0; - foreach (var c in chunks) total += c.Length; - progress?.Invoke(0, total); + if (progress != null) + { + foreach (var chunk in chunks) total += chunk.Length; + progress(0, total); + } long segmentOffset = 0; Action? reportPosition = progress is null ? null : pos => progress(segmentOffset + pos, total); - int i = 0; var carry = Array.Empty(); // overlap tail from the previous segment while (i < chunks.Count) @@ -41,7 +87,7 @@ public static void Walk(IReadOnlyList chunks, HashSet knownIds, Bl i++; } if (start == i && i < chunks.Count) { size += chunks[i].Length; i++; } // oversized single chunk - var seg = new byte[size]; + var seg = GC.AllocateUninitializedArray(checked((int)size)); int off = carry.Length; Buffer.BlockCopy(carry, 0, seg, 0, carry.Length); for (int k = start; k < i; k++) @@ -53,6 +99,7 @@ public static void Walk(IReadOnlyList chunks, HashSet knownIds, Bl // Blocks starting in the final MaxBlock bytes may be cut: the next segment // re-walks them via the carried overlap (skip them here unless last segment). int visitLimit = last ? seg.Length : Math.Max(0, seg.Length - MaxBlock); + sources?.SetSegment(chunks, start, i, carry.Length); WalkSegment(seg, knownIds, visit, visitLimit, visitRecord, reportPosition); segmentOffset += visitLimit; if (!last) @@ -89,7 +136,7 @@ private static void WalkSegment(byte[] buf, HashSet knownIds, BlockVisitor if (!it.HasValue) { aligned = false; - pos++; + pos = reportPosition == null ? NextPossibleItem(buf, pos + 1) : pos + 1; continue; } var (isBlock, size, eid, cls, dataSize) = it.Value; @@ -102,64 +149,132 @@ private static void WalkSegment(byte[] buf, HashSet knownIds, BlockVisitor } } + // Skip only positions where the serialized size and both record markers rule out a header. + // The anchor and size-echo checks still run on every candidate, including unaligned ones. + private static int NextPossibleItem(byte[] data, int position) + { + if (position <= data.Length - 16 && BitConverter.ToUInt64(data, position) == 0 + && BitConverter.ToUInt64(data, position + 8) == 0) + { + // No all-zero header can anchor. Keep starts whose header reaches the first nonzero byte. + int nonzero = data.AsSpan(position + 16).IndexOfAnyExcept((byte)0); + if (nonzero < 0) return data.Length; + position += nonzero + 1; + } + if (!BitConverter.IsLittleEndian || !Vector256.IsHardwareAccelerated) return position; + int width = Vector256.Count; + ref byte first = ref MemoryMarshal.GetArrayDataReference(data); + for (; position <= data.Length - 11 - width; position += width) + { + var low = Vector256.LoadUnsafe(ref first, (nuint)(position + 8)); + var high = Vector256.LoadUnsafe(ref first, (nuint)(position + 9)); + var middleSize = Vector256.LoadUnsafe(ref first, (nuint)(position + 10)); + var highSize = Vector256.LoadUnsafe(ref first, (nuint)(position + 11)); + var block = Vector256.LessThan(middleSize, Vector256.Create((byte)16)) & Vector256.Equals(highSize, Vector256.Zero); + var r22 = Vector256.Equals(low, Vector256.Create((byte)0x3C)) & Vector256.Equals(high, Vector256.Create((byte)0x05)); + var r20 = Vector256.Equals(low, Vector256.Create((byte)0xF8)) & Vector256.Equals(high, Vector256.Create((byte)0x04)); + uint candidates = (block | r22 | r20).ExtractMostSignificantBits(); + if (candidates != 0) return position + BitOperations.TrailingZeroCount(candidates); + } + return position; + } + /// Targeted scan for GRep blocks (classIdx 0x07D7/0x07D6) of SPECIFIC element /// ids the anchored walk missed: family-SYMBOL regions can be unreachable when their /// 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, + SegmentSources? sources = null, int segmentTarget = SegmentTarget) { 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; int i = 0; var carry = Array.Empty(); + var currentGeometry = new List(); + var earlierGeometry = new List(); + var curves = new List(); 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 <= segmentTarget) { size += chunks[i].Length; i++; } if (start == i && i < chunks.Count) { size += chunks[i].Length; i++; } - var seg = new byte[size]; + var seg = GC.AllocateUninitializedArray(checked((int)size)); int off = carry.Length; Buffer.BlockCopy(carry, 0, seg, 0, carry.Length); for (int k = start; k < i; k++) { Buffer.BlockCopy(chunks[k], 0, seg, off, chunks[k].Length); off += chunks[k].Length; } bool last = i >= chunks.Count; - int scanLimit = last ? seg.Length : Math.Max(0, seg.Length - maxTargetBlock); + int scanLimit = last ? seg.Length : Math.Max(0, seg.Length - MaxTargetBlock); + sources?.SetSegment(chunks, start, i, carry.Length); + ScanMarkers(seg, 12, Math.Min(scanLimit + 12, seg.Length - 1), Record); + + // Keep class priority and stream order within each class. + Emit(currentGeometry); + Emit(earlierGeometry); + Emit(curves); + if (!last) + { + int tail = Math.Min(MaxTargetBlock, seg.Length); + carry = new byte[tail]; + Buffer.BlockCopy(seg, seg.Length - tail, carry, 0, tail); + } + + void Record(int marker) + { + int blockStart = marker - 12; + uint dataSize = BitConverter.ToUInt32(seg, blockStart + 8); + if (dataSize < 20 || dataSize >= MaxTargetBlock || blockStart + 16L + dataSize > seg.Length) return; + var matches = seg[marker] switch + { + 0xD7 => currentGeometry, + 0xD6 => earlierGeometry, + _ => curves, + }; + matches.Add(blockStart); + } - foreach (byte marker in (ReadOnlySpan)[0xD7, 0xD6, 0x46]) + void Emit(List matches) { - 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) + foreach (int blockStart in matches) { - 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++; + uint eid = BitConverter.ToUInt32(seg, blockStart); + if (targetIds.Contains(eid)) + visit(seg, blockStart, BitConverter.ToUInt32(seg, blockStart + 8), + BitConverter.ToUInt16(seg, blockStart + 12), eid); } + matches.Clear(); } - if (!last) + } + } + + private static bool IsBlockMarker(byte low, byte high) => + high == 0x07 && low is 0xD7 or 0xD6 || high == 0x03 && low == 0x46; + + private static void ScanMarkers(byte[] data, int start, int end, Action record) + { + int position = start; + if (BitConverter.IsLittleEndian && Vector256.IsHardwareAccelerated) + { + int width = Vector256.Count; + ref byte first = ref MemoryMarshal.GetArrayDataReference(data); + for (; position <= end - width; position += width) { - int tail = Math.Min(maxTargetBlock, seg.Length); - carry = new byte[tail]; - Buffer.BlockCopy(seg, seg.Length - tail, carry, 0, tail); + var low = Vector256.LoadUnsafe(ref first, (nuint)position); + var high = Vector256.LoadUnsafe(ref first, (nuint)(position + 1)); + var geometry = Vector256.Equals(low & Vector256.Create((byte)0xFE), Vector256.Create((byte)0xD6)) + & Vector256.Equals(high, Vector256.Create((byte)0x07)); + var curve = Vector256.Equals(low, Vector256.Create((byte)0x46)) + & Vector256.Equals(high, Vector256.Create((byte)0x03)); + uint candidates = (geometry | curve).ExtractMostSignificantBits(); + while (candidates != 0) + { + record(position + BitOperations.TrailingZeroCount(candidates)); + candidates &= candidates - 1; + } } } + for (; position < end; position++) + if (IsBlockMarker(data[position], data[position + 1])) record(position); } private static (bool IsBlock, int Size, uint Eid, ushort Cls, uint DataSize)? ParseItem( @@ -168,30 +283,22 @@ private static (bool IsBlock, int Size, uint Eid, ushort Cls, uint DataSize)? Pa if (pos + 12 > n) return null; uint eid = BitConverter.ToUInt32(buf, pos); if (!ElementIdEncoding.IsSupported(eid) && eid != 0) return null; - // Ids outside the known set (family-SYMBOL elements live in the family doc's own - // numbering and are absent from ElemTable) or above the plain-id ceiling may still - // anchor, but only on a BLOCK whose 4-byte footer echoes dataSize (strong - // signature; well-formed blocks always carry it). Without this, whole family- - // symbol regions (door leafs, fixture bodies) were skipped byte-by-byte. - bool needFooter = eid == 0 || !knownIds.Contains(eid); - if (!needFooter) + ushort magic = BitConverter.ToUInt16(buf, pos + 8); + if (magic is 0x053C or 0x04F8) { - ushort magic = BitConverter.ToUInt16(buf, pos + 8); uint bodySize = BitConverter.ToUInt32(buf, pos + 4); - if ((magic == 0x053C || magic == 0x04F8) && bodySize < 500_000 && pos + 12 + bodySize <= n) + if (bodySize < 500_000 && pos + 12 + bodySize <= n && eid != 0 && knownIds.Contains(eid)) return (false, 12 + (int)bodySize, eid, 0, 0); } if (pos + 16 > n) return null; uint ds = BitConverter.ToUInt32(buf, pos + 8); + // Every block needs a size echo. An owner outside ElemTable (including loaded + // family symbols) can anchor with that echo and a payload of at least eight bytes. + if (ds >= 1_000_000 || pos + 16 + ds > n + || BitConverter.ToUInt32(buf, pos + 12 + (int)ds) != ds + || (ds < 8 && (eid == 0 || !knownIds.Contains(eid)))) + return null; ushort ci = BitConverter.ToUInt16(buf, pos + 12); - if (ds < 1_000_000 && pos + 16 + ds <= n && TfBlockDeserializer.Schemas.ContainsKey(ci)) - { - // The footer echo is required for every block: an id of the known set alone let item-shaped bytes - // inside another block pass as a block and hide the items behind them. - if (BitConverter.ToUInt32(buf, pos + 12 + (int)ds) != ds || (needFooter && ds < 8)) - return null; - return (true, 16 + (int)ds, eid, ci, ds); - } - return null; + return TfBlockDeserializer.Schemas.ContainsKey(ci) ? (true, 16 + (int)ds, eid, ci, ds) : null; } } diff --git a/src/RvtIO/Parsing/WallWidthExtractor.cs b/src/RvtIO/Parsing/WallWidthExtractor.cs index be08705b..2824f735 100644 --- a/src/RvtIO/Parsing/WallWidthExtractor.cs +++ b/src/RvtIO/Parsing/WallWidthExtractor.cs @@ -4,16 +4,27 @@ namespace RvtIO.Parsing; internal static class WallWidthExtractor { + public static void Extract(ParsingState state) + { + var wallIds = new HashSet(); + foreach (var (id, record) in state.Records) + if (record.CategoryId == -2000011) wallIds.Add(id); + + var wallBlocks = ExtractFromBlocks(state, wallIds); + ExtractFromGrid(state); + ExtractFromBlockGrid(state, wallIds, wallBlocks); + } + /// Extract wall widths from 0xFFFF block Tf data (half-width anchor pattern). - public static void ExtractFromBlocks(ParsingState state) + private static List<(byte[] Chunk, uint Id, int Start, int End)> ExtractFromBlocks(ParsingState state, HashSet wallIds) { var nonRecordChunks = state.NonRecordChunks; var recordChunks = state.RecordChunks; - var records = state.Records; var wallTypeWidths = state.WallTypeWidths; var elemBipDoubles = state.ElemBipDoubles; var wallInstWidths = new Dictionary(); // instanceId to (width, typeId) + var wallBlocks = new List<(byte[] Chunk, uint Id, int Start, int End)>(); foreach (var chunk in nonRecordChunks.Concat(recordChunks)) { int pos = 0; @@ -33,35 +44,33 @@ public static void ExtractFromBlocks(ParsingState state) if (eid == 0) { pos += 4; continue; } if (dsz == 0) { pos++; continue; } if (pos + 16 + (int)dsz > chunk.Length) break; - uint ci = BitConverter.ToUInt32(chunk, pos + 12); - if ((ci >> 16) == 0xFFFF && records.TryGetValue(eid, out var rec) && rec.CategoryId == -2000011) + int dataStart = pos + 16; + pos = dataStart + (int)dsz; + if (!wallIds.Contains(eid)) continue; + if (dsz >= 48) wallBlocks.Add((chunk, eid, dataStart, pos)); + if ((BitConverter.ToUInt32(chunk, dataStart - 4) >> 16) != 0xFFFF || wallInstWidths.ContainsKey(eid)) continue; + for (int i = dataStart; i + 24 <= pos; i += 2) { - int dataStart = pos + 16; - int dataEnd = dataStart + (int)dsz; - for (int i = dataStart; i + 24 <= dataEnd; i += 2) + int wai = BitConverter.ToInt32(chunk, i); + int uli = BitConverter.ToInt32(chunk, i + 4); + int as2 = BitConverter.ToInt32(chunk, i + 8); + int at2 = BitConverter.ToInt32(chunk, i + 12); + int ab2 = BitConverter.ToInt32(chunk, i + 16); + int cf2 = BitConverter.ToInt32(chunk, i + 20); + if (wai <= 0) continue; + if (uli == 0) continue; + bool ap1 = as2 == -9 && at2 >= -100 && at2 <= 0 && ab2 >= -100 && ab2 <= 0; + bool ap2 = as2 == -1 && at2 == -1 && ab2 == -1; + if (!ap1 && !ap2) continue; + if (cf2 != -1) continue; + if (i - 16 >= dataStart) { - int wai = BitConverter.ToInt32(chunk, i); - int uli = BitConverter.ToInt32(chunk, i + 4); - int as2 = BitConverter.ToInt32(chunk, i + 8); - int at2 = BitConverter.ToInt32(chunk, i + 12); - int ab2 = BitConverter.ToInt32(chunk, i + 16); - int cf2 = BitConverter.ToInt32(chunk, i + 20); - if (wai <= 0) continue; - if (uli == 0) continue; - bool ap1 = as2 == -9 && at2 >= -100 && at2 <= 0 && ab2 >= -100 && ab2 <= 0; - bool ap2 = as2 == -1 && at2 == -1 && ab2 == -1; - if (!ap1 && !ap2) continue; - if (cf2 != -1) continue; - if (!wallInstWidths.ContainsKey(eid) && i - 16 >= dataStart) - { - double hw = BitConverter.ToDouble(chunk, i - 16); - if (hw > 0.001 && hw < 50 && !double.IsNaN(hw) && !double.IsInfinity(hw)) - wallInstWidths[eid] = (hw * 2, (uint)wai); - } - break; + double hw = BitConverter.ToDouble(chunk, i - 16); + if (hw > 0.001 && hw < 50 && !double.IsNaN(hw) && !double.IsInfinity(hw)) + wallInstWidths[eid] = (hw * 2, (uint)wai); } + break; } - pos += 16 + (int)dsz; } } foreach (var (eid, (w, tid)) in wallInstWidths) @@ -78,10 +87,11 @@ public static void ExtractFromBlocks(ParsingState state) bd.TryAdd(-1001000, w); } DiagnosticSink.WriteLine($"Wall widths extracted: {wallInstWidths.Count} instances, {wallTypeWidths.Count} types"); + return wallBlocks; } /// Extract wall widths from CompoundStructure Grid patterns near PreviewElemId. - public static void ExtractFromGrid(ParsingState state) + private static void ExtractFromGrid(ParsingState state) { var elemTable = state.ElemTable; var records = state.Records; @@ -102,7 +112,14 @@ public static void ExtractFromGrid(ParsingState state) { previewToWallType[refId] = eid; wallTypeDefIds.Add(eid); break; } } DiagnosticSink.WriteLine($"Wall type defs: {wallTypeDefIds.Count}, PreviewElemId mappings: {previewToWallType.Count}"); + if (previewToWallType.Count == 0) + { + DiagnosticSink.WriteLine($"Grid widths: 0 types added (total wallTypeWidths: {wallTypeWidths.Count})"); + DiagnosticSink.WriteLine($"Unmatched wall type defs: {-wallTypeWidths.Count}"); + return; + } + uint firstPreview = previewToWallType.Keys.Min(), lastPreview = previewToWallType.Keys.Max(); var previewPositions = new Dictionary>(); for (int ci = 0; ci < chunks.Count; ci++) { @@ -110,7 +127,7 @@ public static void ExtractFromGrid(ParsingState state) for (int pOff = 0; pOff + 4 <= chunk.Length; pOff++) { uint pv = BitConverter.ToUInt32(chunk, pOff); - if (!previewToWallType.TryGetValue(pv, out var wtId)) continue; + if (pv < firstPreview || pv > lastPreview || !previewToWallType.TryGetValue(pv, out var wtId)) continue; if (!previewPositions.TryGetValue(ci, out var list)) previewPositions[ci] = list = new List<(int, uint)>(); list.Add((pOff, wtId)); @@ -199,80 +216,45 @@ public static void ExtractFromGrid(ParsingState state) /// we scan each block's data for CompoundStructure Grid patterns and use the block's /// own elemId for association. Works for both ElemTable types and discovered types. /// - public static void ExtractFromBlockGrid(ParsingState state) + private static void ExtractFromBlockGrid(ParsingState state, HashSet wallIds, + List<(byte[] Chunk, uint Id, int Start, int End)> wallBlocks) { var records = state.Records; - var elemTable = state.ElemTable; var wallTypeWidths = state.WallTypeWidths; var elemBipDoubles = state.ElemBipDoubles; // Wall type element IDs: CategoryId=OST_Walls AND no instance-level params // (wall types do not have WALL_USER_HEIGHT_PARAM in their BIP doubles) var wallTypeIds = new HashSet(); - foreach (var (eid, rec) in records) + foreach (uint eid in wallIds) { - if (rec.CategoryId != -2000011) continue; // OST_Walls only if (wallTypeWidths.ContainsKey(eid)) continue; // already have width if (state.ElemBipDoubles.TryGetValue(eid, out var bd) && bd.ContainsKey(-1001105)) continue; // WALL_USER_HEIGHT_PARAM means instance wallTypeIds.Add(eid); } - foreach (var (eid, _) in elemTable) - { - if (wallTypeWidths.ContainsKey(eid)) continue; - if (!records.TryGetValue(eid, out var rec)) continue; - if (rec.CategoryId != -2000011) continue; - if (state.ElemBipDoubles.TryGetValue(eid, out var bd2) && bd2.ContainsKey(-1001105)) continue; - wallTypeIds.Add(eid); - } - if (wallTypeIds.Count == 0) return; var blockGridWidths = new Dictionary(); - foreach (var chunk in state.NonRecordChunks.Concat(state.RecordChunks)) + foreach (var (chunk, eid, start, end) in wallBlocks) { - int pos = 0; - while (pos + 16 <= chunk.Length) + if (!wallTypeIds.Contains(eid)) continue; + for (int g = start; g + 48 <= end; g++) { - uint eid = BitConverter.ToUInt32(chunk, pos); - if (pos + 12 <= chunk.Length) - { - uint rbs = BitConverter.ToUInt32(chunk, pos + 4); - ushort rm = BitConverter.ToUInt16(chunk, pos + 8); - if (rm == 0x053C && ElementIdEncoding.IsSupported(eid) - && rbs > 0 && rbs < 500_000 && pos + 12 + (int)rbs <= chunk.Length) - { pos += 12 + (int)rbs; continue; } - } - uint dsz = BitConverter.ToUInt32(chunk, pos + 8); - if (dsz > 1_000_000) { pos++; continue; } - if (eid == 0) { pos += 4; continue; } - if (dsz == 0) { pos++; continue; } - if (pos + 16 + (int)dsz > chunk.Length) break; - - if (wallTypeIds.Contains(eid) && dsz >= 48) + var (tw, nc) = DetectGrid(chunk, g); + if (nc >= 2) { - int dataStart = pos + 16; - int dataEnd = dataStart + (int)dsz; - for (int g = dataStart; g + 48 <= dataEnd; g++) - { - var (tw, nc) = DetectGrid(chunk, g); - if (nc >= 2) - { - if (!blockGridWidths.TryGetValue(eid, out var existing) || nc > existing.nCoords) - blockGridWidths[eid] = (tw, nc); - g += nc * 24 - 1; // skip past - } - } + if (!blockGridWidths.TryGetValue(eid, out var existing) || nc > existing.nCoords) + blockGridWidths[eid] = (tw, nc); + g += nc * 24 - 1; // skip past } - pos += 16 + (int)dsz; } } // CompoundStructure may also be in a record body, after the refs - foreach (var (eid, rec) in records) + foreach (uint eid in wallTypeIds) { - if (!wallTypeIds.Contains(eid)) continue; if (blockGridWidths.ContainsKey(eid)) continue; // already found in block - var body = rec.Body; + var body = records[eid].Body.Span; if (body.Length < 48) continue; for (int g = 0; g + 48 <= body.Length; g++) { @@ -300,24 +282,25 @@ public static void ExtractFromBlockGrid(ParsingState state) DiagnosticSink.WriteLine($"Block-grid widths: {added} types added (total wallTypeWidths: {wallTypeWidths.Count})"); } - private static (double totalW, int nCoords) DetectGrid(byte[] chunk, int off) + private static (double totalW, int nCoords) DetectGrid(ReadOnlySpan chunk, int off) { if (off + 48 > chunk.Length) return (0, 0); - if (BitConverter.ToInt64(chunk, off) != 0) return (0, 0); // Coord[0]=0.0 - if (BitConverter.ToUInt32(chunk, off + 8) != 0) return (0, 0); // Id[0]=0 - if (BitConverter.ToUInt32(chunk, off + 12) != 0) return (0, 0); // Orient[0]=0 - double v1 = BitConverter.ToDouble(chunk, off + 24); + if (BitConverter.ToInt64(chunk.Slice(off)) != 0) return (0, 0); // Coord[0]=0.0 + if (BitConverter.ToUInt32(chunk.Slice(off + 8)) != 0) return (0, 0); // Id[0]=0 + if (BitConverter.ToUInt32(chunk.Slice(off + 12)) != 0) return (0, 0); // Orient[0]=0 + double v1 = BitConverter.ToDouble(chunk.Slice(off + 24)); if (v1 <= 0.003 || v1 >= 5.0 || double.IsNaN(v1) || double.IsInfinity(v1)) return (0, 0); - var coords = new List { 0.0, v1 }; + double last = v1; + int count = 2; int nOff = off + 48; - while (nOff + 8 <= chunk.Length && coords.Count < 30) + while (nOff + 8 <= chunk.Length && count < 30) { - double vn = BitConverter.ToDouble(chunk, nOff); - if (vn <= coords[^1] + 0.0005 || vn >= 10.0 || double.IsNaN(vn) || double.IsInfinity(vn)) break; - coords.Add(vn); + double vn = BitConverter.ToDouble(chunk.Slice(nOff)); + if (vn <= last + 0.0005 || vn >= 10.0 || double.IsNaN(vn) || double.IsInfinity(vn)) break; + last = vn; + count++; nOff += 24; } - if (coords.Count < 2 || coords[^1] < 0.01 || coords[^1] > 10) return (0, 0); - return (coords[^1], coords.Count); + return last < 0.01 ? (0, 0) : (last, count); } } diff --git a/src/RvtIO/Parsing/WideNativeParams.cs b/src/RvtIO/Parsing/WideNativeParams.cs index 40db7c70..a8c21d9e 100644 --- a/src/RvtIO/Parsing/WideNativeParams.cs +++ b/src/RvtIO/Parsing/WideNativeParams.cs @@ -345,7 +345,7 @@ internal WideNativeParams(SchemaDocument schema, ElementIdMap? ids = null) { if (_walker.Class(walk.Queue[qi])?.Name != "CellList") continue; np.CellClasses = Enumerable.Range(walk.QueueCountAtStart[qi], walk.QueueEnd[qi] - walk.QueueCountAtStart[qi]) - .Select(i => R22Id(walk.Queue[i])).ToList(); + .Select(i => R22Id(walk.Queue[i])).ToArray(); break; } np.TailWalkComplete = walk.Exact; diff --git a/src/RvtIO/RvtDocument.cs b/src/RvtIO/RvtDocument.cs index 7ba80e60..0b225c9e 100644 --- a/src/RvtIO/RvtDocument.cs +++ b/src/RvtIO/RvtDocument.cs @@ -61,7 +61,7 @@ private ProjectInfo FillProjectInformation(ProjectInfo info) int id = (int)parameter; foreach (var p in element.Parameters) { - int parameterId = p.Definition?.Id is int definitionId && definitionId != 0 ? definitionId : p.Id; + int parameterId = p.DefinitionId is int definitionId && definitionId != 0 ? definitionId : p.Id; if (parameterId != id) continue; if (p.Value is string text && text.Length > 0) return text; } @@ -99,7 +99,7 @@ private RvtDocument(RevitFileInfo info, string? sourcePath = null) { foreach (var p in e.Parameters) { - if (p.Definition?.Name is "ELEM_TYPE_PARAM" or "ELEM_FAMILY_AND_TYPE_PARAM" + if (p.DefinitionName is "ELEM_TYPE_PARAM" or "ELEM_FAMILY_AND_TYPE_PARAM" && p.Value is int typeId && typeId > 0) { _typeElementIds.Add(typeId); diff --git a/src/RvtIO/RvtFileReader.OwnFamilyCutout.cs b/src/RvtIO/RvtFileReader.OwnFamilyCutout.cs index 088c3ab4..e25c0a48 100644 --- a/src/RvtIO/RvtFileReader.OwnFamilyCutout.cs +++ b/src/RvtIO/RvtFileReader.OwnFamilyCutout.cs @@ -6,7 +6,7 @@ namespace RvtIO; public partial class RvtFileReader { internal static void RecordOwnFamilyCutoutInputs(ParsingState state, byte[] data, - int start, uint size, ushort classId, uint owner) + int start, uint size, ushort classId, uint owner, TfBlockDeserializer.WallCompleteInputRead? complete = null) { bool own = start >= 0 && start <= data.Length - 4 && BitConverter.ToUInt32(data, start) == owner; if (classId == 1772) @@ -35,14 +35,15 @@ internal static void RecordOwnFamilyCutoutInputs(ParsingState state, byte[] data } if (classId is 3524 or 361) { + if (own) complete ??= new(data, start, size, classId); state.OwnWallCutoutSteps[owner] = state.OwnWallCutoutSteps.TryGetValue(owner, out var old) ? (old.BlockCount + 1, null, null, null) : (1, own ? TfBlockDeserializer.ExtractOwnWallCutoutSteps(data, start, size, classId, out _) : null, - own ? TfBlockDeserializer.ExtractOwnWallLocationLine(data, start, size, classId, out _) : null, + own ? TfBlockDeserializer.ExtractOwnWallLocationLine(data, start, size, classId, out _, complete) : null, own ? TfBlockDeserializer.ExtractOwnWallCrossSection(data, start, size, classId) : null); state.OwnWallHelpers[owner] = state.OwnWallHelpers.TryGetValue(owner, out var oldHelper) ? (oldHelper.BlockCount + 1, null) - : (1, own ? TfBlockDeserializer.ExtractOwnWallHelperInput(data, start, size, classId) : null); + : (1, own ? TfBlockDeserializer.ExtractOwnWallHelperInput(data, start, size, classId, complete) : null); state.OwnWallSide0Ids.Remove(owner); state.OwnWallBaseFaces.Remove(owner); state.OwnCurrentWallRoots.Remove(owner); @@ -51,7 +52,7 @@ internal static void RecordOwnFamilyCutoutInputs(ParsingState state, byte[] data && OwnPartitionParts.MatchesFrame(data, start, size, current.NodeSha256); if (currentRoot) state.OwnCurrentWallRoots.Add(owner); bool single = own && state.OwnWallCutoutSteps[owner].BlockCount == 1; - if ((currentRoot || single) && TfBlockDeserializer.ExtractOwnWallCompleteInputs(data, start, size, classId, out _) is { } input) + if ((currentRoot || single) && complete?.Read(out _) is { } input) { if (currentRoot && state.OwnWallCutoutSteps[owner].Steps is { Count: > 0 } && TfBlockDeserializer.SelectOwnWallSide0Id(input) is int sideId) diff --git a/src/RvtIO/RvtFileReader.OwnWallPlanarBodies.cs b/src/RvtIO/RvtFileReader.OwnWallPlanarBodies.cs index 87507d97..20a98e67 100644 --- a/src/RvtIO/RvtFileReader.OwnWallPlanarBodies.cs +++ b/src/RvtIO/RvtFileReader.OwnWallPlanarBodies.cs @@ -6,7 +6,8 @@ namespace RvtIO; public partial class RvtFileReader { - private static void ReadOwnWallPlanarBodies(ParsingState state) + private static void ReadOwnWallPlanarBodies(ParsingState state, + List<(byte[] Data, int Start, uint Size, ushort Cls, uint Owner)> candidates) { var owners = state.OwnedElementClassRoots.Where(entry => entry.Value.BlockCount == 1 && entry.Value.ClassId is 3524 or 361).Select(entry => entry.Key).ToHashSet(); @@ -15,14 +16,8 @@ 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)); - }); + // Class roots are complete now, including nodes stored after their geometry. + var jobs = candidates.Where(job => owners.Contains(job.Owner)).ToList(); var decoded = new (GRepData? Body, string? Failure)[jobs.Count]; var grepCounts = jobs.GroupBy(job => job.Owner).ToDictionary(group => group.Key, group => group.Count()); var nativeBodies = new GRepData?[jobs.Count]; @@ -32,8 +27,10 @@ private static void ReadOwnWallPlanarBodies(ParsingState state) Parallel.For(0, jobs.Count, index => { var (data, start, size, cls, owner) = jobs[index]; + // The merge records the count and rejects the body for every repeated owner. + if (grepCounts[owner] != 1) return; decoded[index] = DecodeOwnWallPlanarBody(data, start, size, cls, owner, out var graph); - if (graph != null && grepCounts[owner] == 1 && decoded[index].Body != null + if (graph != null && decoded[index].Body != null && state.OwnCurrentWallRoots.Contains(owner) && state.OwnPartitionWallParts?.TryGetValue(owner, out var current) == true && OwnPartitionParts.MatchesFrame(data, start, size, current.GeometrySha256)) @@ -43,13 +40,13 @@ private static void ReadOwnWallPlanarBodies(ParsingState state) groups[index] = TfBlockDeserializer.SelectOwnPostCutFaceGroups(graph, decoded[index].Body!.Faces.Select(face => face.SourceFace).ToArray()); } - if (graph != null && grepCounts[owner] == 1 && decoded[index].Body is { } trimmedBody + if (graph != null && decoded[index].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) - nativeBodies[index] = DecodeOwnNativeWallBody(state, data, start, size, cls, owner, grepCounts[owner]); + nativeBodies[index] = DecodeOwnNativeWallBody(state, data, start, size, cls, owner, grepCount: 1); }); for (int index = 0; index < jobs.Count; index++) { @@ -69,7 +66,7 @@ private static void ReadOwnWallPlanarBodies(ParsingState state) || BitConverter.ToUInt16(data, start + 12) != cls || !state.OwnedElementClassRoots.TryGetValue(owner, out var root) || root.BlockCount != 1 || root.ClassId is not (3524 or 361)) return null; - var body = GRepParserV2.Parse(data, start, size, nativeWallBody: true); + var body = GRepParserV2.ParseNativeWallBodyCandidate(data, start, size); if (!(body is { Faces.Count: > 0, Instances.Count: 0 } && body.Faces.All(face => face.MeshEdgeBounds is { Length: 6 }) && body.Faces.Any(face => face.AnalyticCylinderRadius > 0))) return null; diff --git a/src/RvtIO/RvtFileReader.TfNativeBlocks.cs b/src/RvtIO/RvtFileReader.TfNativeBlocks.cs new file mode 100644 index 00000000..c8aa6a9b --- /dev/null +++ b/src/RvtIO/RvtFileReader.TfNativeBlocks.cs @@ -0,0 +1,118 @@ +using RvtIO.Internal; +using RvtIO.Parsing; + +namespace RvtIO; + +public partial class RvtFileReader +{ + /// Native parameter decoding is independent across owners; replay results in stream order. + private sealed class TfNativeBlocks(ParsingState state, TfStreamWalker.SegmentSources sources) + { + private const int Capacity = 32_768; + private readonly List _blocks = []; + private readonly Dictionary _first = new(); + private int[]? _next; + private Update[]? _updates; + + private readonly record struct Block(byte[] Data, int Start, uint Size, ushort Class, uint Owner, bool Root); + private readonly record struct Update(TfBlockDeserializer.NativeParams? Values, GridDatumData? Grid, + bool Root, bool MergeDrive = false, Model.GridPlaneData? Level = null); + + internal void Add(byte[] data, int start, uint size, ushort cls, uint owner, bool root) + { + if (cls is not (2299 or 0x083C) && state.NativeParams.ContainsKey(owner) + && (!root || (state.NativeParamsFromRootClass.Contains(owner) + && !(state.R22View && TfBlockDeserializer.IsSubclassOf(cls, 1794))))) + return; + + var block = new Block(data, start, size, cls, owner, root); + if (TfBlockDeserializer.CaptureAllFields || OperatingSystem.IsBrowser()) + { + bool hasNative = state.NativeParams.ContainsKey(owner); + bool hasRoot = state.NativeParamsFromRootClass.Contains(owner); + Apply(owner, Decode(block, ref hasNative, ref hasRoot)); + return; + } + + // Queued blocks outlive the walk's segment buffer, which can reach 1.4 GB; keep only the block. + var (kept, keptStart) = sources.Retain(data, start, (int)size + 16); + _blocks.Add(block with { Data = kept, Start = keptStart }); + if (_blocks.Count == Capacity) Flush(); + } + + internal void Flush() + { + if (_blocks.Count == 0) return; + if (_next == null || _next.Length < _blocks.Count) + { + _next = new int[_blocks.Count]; + _updates = new Update[_blocks.Count]; + } + var next = _next; + var updates = _updates!; + for (int i = _blocks.Count - 1; i >= 0; i--) + { + uint owner = _blocks[i].Owner; + next[i] = _first.GetValueOrDefault(owner, -1); + _first[owner] = i; + } + Parallel.ForEach(_first, group => + { + bool hasNative = state.NativeParams.ContainsKey(group.Key); + bool hasRoot = state.NativeParamsFromRootClass.Contains(group.Key); + for (int i = group.Value; i >= 0; i = next[i]) + updates[i] = Decode(_blocks[i], ref hasNative, ref hasRoot); + }); + for (int i = 0; i < _blocks.Count; i++) + Apply(_blocks[i].Owner, updates[i]); + Array.Clear(updates, 0, _blocks.Count); + _blocks.Clear(); + _first.Clear(); + } + + private Update Decode(Block block, ref bool hasNative, ref bool hasRoot) + { + var (data, start, size, cls, _, root) = block; + // Datum subclasses provide their exact names and geometry even when an earlier block supplied parameters. + if (!hasNative || cls is 2299 or 0x083C || (root && !hasRoot)) + { + var values = TfBlockDeserializer.ExtractParams(data, start, size, cls); + bool decodedRoot = root && values is { Count: > 0 }; + hasRoot |= decodedRoot; + Model.GridPlaneData? level = null; + if (cls == 2299) + { + values ??= new TfBlockDeserializer.NativeParams(); + values.Fields["__isLevel"] = 1; + var name = TfBlockDeserializer.ExtractLevelName(data, start, size, cls); + if (!string.IsNullOrWhiteSpace(name)) values.StringFields["m_text"] = name; + level = TfBlockDeserializer.ExtractLevelPlane(data, start, size, cls); + if (level is { } plane && double.IsFinite(plane.Origin[2])) + values.DoubleFields["__levelElevation"] = plane.Origin[2]; + } + GridDatumData? grid = null; + if (cls == 0x083C && TfBlockDeserializer.ExtractGridDatum(data, start, size, cls) is { } datum) + grid = new GridDatumData(datum.Name, datum.StartPoint, datum.EndPoint, datum.CutVector, datum.LevelInterval, + datum.XVector, datum.Envelope, datum.Origin, datum.YVector); + if (values is not { Count: > 0 }) values = null; + hasNative |= values != null; + return new Update(values, grid, decodedRoot, Level: level); + } + + if (state.R22View && root && TfBlockDeserializer.IsSubclassOf(cls, 1794)) + return new Update(TfBlockDeserializer.ExtractParams(data, start, size, cls), null, false, MergeDrive: true); + return default; + } + + private void Apply(uint owner, Update update) + { + if (update.Root) state.NativeParamsFromRootClass.Add(owner); + if (update.MergeDrive) + AddDriveCurveFromRewrittenBlock(state.NativeParams[owner], update.Values); + else if (update.Values != null) + state.NativeParams[owner] = update.Values; + if (update.Grid is { } grid) state.GridDatums[owner] = grid; + if (update.Level is { } level) state.LevelPlanes[owner] = level; + } + } +} diff --git a/src/RvtIO/RvtFileReader.cs b/src/RvtIO/RvtFileReader.cs index 2a2282a6..4d788a54 100644 --- a/src/RvtIO/RvtFileReader.cs +++ b/src/RvtIO/RvtFileReader.cs @@ -188,6 +188,7 @@ private RevitFileInfo ReadCore(RootStorage root) var state = new ParsingState { SeparateFacesWithDistinctOpenings = _options.SeparateFacesWithDistinctOpenings, + CollectBlockClassInventory = false, ElemTable = elemTable, ElementIds = ids, ElemWorksets = elemWorksets, @@ -214,13 +215,20 @@ private RevitFileInfo ReadCore(RootStorage root) ClassifyAndParseRecords(chunks, state, diag); LogPhase("Records parsed"); - ParseBlocks(state, diag, progress); - LogPhase("Blocks parsed"); - - // Continuous-stream anchored walk: blocks cross chunk boundaries, so this sees many more blocks than the - // per-chunk walk. Extracts native parameter stores and re-runs the key block-driven signals at full coverage. - progress?.Report(new("parameter-stream")); - RunTfStreamWalk(state, progress); + var unreadableGReps = GRepParserV2.IsDecodeTracingEnabled() ? null : new HashSet(); + var blockGeometry = ParseBlocks(state, diag, progress, unreadableGReps, + overlapGeometry: progress == null && unreadableGReps != null + && !OperatingSystem.IsBrowser() && (state.WideSchema == null || state.R22View)); + // The anchored walk reaches blocks spanning chunks and decodes the native parameter stores. + try + { + LogPhase("Blocks parsed"); + progress?.Report(new("parameter-stream")); + RunTfStreamWalk(state, progress, unreadableGReps, blockGeometry); + } + finally { blockGeometry?.GetAwaiter().GetResult(); } + unreadableGReps = null; + blockGeometry = null; if (state.WideSchema == null) ReadOwnDocumentUnits(root, state, diag); if (wideSchema == null && state.ElemClassIdx.Values.Any(id => id is 2108 or 2111)) ReadNarrowGridAxes(root, state, diag); @@ -228,22 +236,30 @@ 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); + // The catalog reads finalized native captures. The string scan writes only its name candidates. + UserParameterCatalog? userParameters = null; + if (OperatingSystem.IsBrowser() || progress != null) + { + ScanElementStrings(); + userParameters = UserParameterCatalog.Build(state); + } + else Parallel.Invoke(ScanElementStrings, () => userParameters = UserParameterCatalog.Build(state)); + + void ScanElementStrings() + { + 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); + } LogPhase("Strings scanned"); diag?.WriteLine($"Elements with BIP doubles: {state.ElemBipDoubles.Count}"); - WallWidthExtractor.ExtractFromBlocks(state); - WallWidthExtractor.ExtractFromGrid(state); - WallWidthExtractor.ExtractFromBlockGrid(state); + WallWidthExtractor.Extract(state); // Optional text dump of the model if (_options.ExternalDumpPath != null) @@ -264,16 +280,15 @@ private RevitFileInfo ReadCore(RootStorage root) byte[] forgeMarker = System.Text.Encoding.Unicode.GetBytes("autodesk.parameter.aec.revit."); var forgeIdHits = new List<(int chunkIdx, int offset, string forgeId, uint parsedElemId)>(); - for (int ci = 0; ci < state.Chunks.Count; ci++) + var forgeHitsByChunk = new List<(int chunkIdx, int offset, string forgeId, uint parsedElemId)>?[state.Chunks.Count]; + Parallel.For(0, state.Chunks.Count, ci => { var chunk = state.Chunks[ci]; for (int j = 5; j + forgeMarker.Length <= chunk.Length; j++) { - if (chunk[j] != 0x61 || chunk[j + 1] != 0x00) continue; // 'a' - bool m2 = true; - for (int x = 0; x < forgeMarker.Length && m2; x++) - if (chunk[j + x] != forgeMarker[x]) m2 = false; - if (!m2) continue; + int next = chunk.AsSpan(j).IndexOf(forgeMarker); + if (next < 0) break; + j += next; var sb = new System.Text.StringBuilder(); for (int k = 0; j + k * 2 + 1 < chunk.Length; k++) @@ -302,10 +317,12 @@ private RevitFileInfo ReadCore(RootStorage root) var part = fid.Split("family:").LastOrDefault()?.Split('-').FirstOrDefault(); if (part != null) uint.TryParse(part, out parsedId); } - forgeIdHits.Add((ci, sLenOff, fid, parsedId)); + (forgeHitsByChunk[ci] ??= new()).Add((ci, sLenOff, fid, parsedId)); j += fid.Length * 2; } - } + }); + foreach (var hits in forgeHitsByChunk) + if (hits != null) forgeIdHits.AddRange(hits); int familyHits = forgeIdHits.Count(h => h.forgeId.Contains("family:")); int externalHits = forgeIdHits.Count(h => h.forgeId.Contains("external.")); diag?.WriteLine($" ForgeId scan: {forgeIdHits.Count} ({familyHits} family, {externalHits} external)"); @@ -440,18 +457,18 @@ private RevitFileInfo ReadCore(RootStorage root) if (!state.IsParameterElement(eid)) continue; if (state.ForgeParamDefs.TryGetValue(eid, out var existing) && existing.DisplayName != null) continue; if (!state.Records.TryGetValue(eid, out var rec)) continue; - var body = rec.Body; + var body = rec.Body.Span; int famId = -1; for (int p = 2; p + 2 <= body.Length - 10; p += 14) { - ushort classId = BitConverter.ToUInt16(body, p + 10); + ushort classId = BitConverter.ToUInt16(body[(p + 10)..]); if (classId == 0xFFFF || classId == 0) { // Tf base fields start here: [assocLevelId:4][famId:4] int tfStart = p + 14; // after sentinel entry if (tfStart + 8 <= body.Length) { - famId = BitConverter.ToInt32(body, tfStart + 4); + famId = BitConverter.ToInt32(body[(tfStart + 4)..]); } break; } @@ -547,7 +564,7 @@ private RevitFileInfo ReadCore(RootStorage root) if (!state.IsParameterElement(eid)) continue; if (state.ForgeParamDefs.TryGetValue(eid, out var ex4) && ex4.DisplayName != null) continue; if (!state.Records.TryGetValue(eid, out var rec)) continue; - var body = rec.Body; + var body = rec.Body.Span; if (body.Length <= 87) continue; // minimal body has no strings for (int j = 10; j + 40 <= body.Length; j++) @@ -569,7 +586,7 @@ private RevitFileInfo ReadCore(RootStorage root) for (int back = forgeOff - 2; back >= Math.Max(0, forgeOff - 500); back--) { if (back + 4 > body.Length) continue; - uint capLen = BitConverter.ToUInt32(body, back); + uint capLen = BitConverter.ToUInt32(body[back..]); if (capLen < 1 || capLen > 200) continue; int capEnd = back + 4 + (int)capLen * 2; int gap = forgeOff - capEnd; @@ -579,7 +596,7 @@ private RevitFileInfo ReadCore(RootStorage root) { int tryBack = back + lenTry; if (tryBack < 0 || tryBack + 4 > body.Length) continue; - uint tryLen = BitConverter.ToUInt32(body, tryBack); + uint tryLen = BitConverter.ToUInt32(body[tryBack..]); if (tryLen < 1 || tryLen > 200) continue; int tryEnd = tryBack + 4 + (int)tryLen * 2; int tryGap = forgeOff - tryEnd; @@ -758,12 +775,13 @@ private RevitFileInfo ReadCore(RootStorage root) .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); + state.SymbolPlacementGeometry = new(ReferenceEqualityComparer.Instance); + BuildOrderedElements(state.ElemTable.OrderBy(x => x.Key).ToArray(), rvtInfo.Elements, + (entry, parameterIds) => ElementBuilder.CreateElemTableElement(entry.Key, entry.Value, state, parameterIds)); LogPhase("Elements built"); - foreach (var eid in extraRecordIds) - ElementBuilder.BuildDiscoveredElement(eid, state, rvtInfo); + BuildOrderedElements(extraRecordIds, rvtInfo.Elements, + (id, parameterIds) => ElementBuilder.CreateDiscoveredElement(id, state, parameterIds)); LogPhase("Discovered elements built"); // GRep blocks discovered by the stream walk / targeted scan that no index knows: @@ -793,8 +811,9 @@ private RevitFileInfo ReadCore(RootStorage root) && !state.Records.ContainsKey(familySymbolId)) state.BlockOnlyIds.Add(familySymbolId); + var parameterIds = new HashSet(); foreach (var bid in state.BlockOnlyIds) - ElementBuilder.BuildBlockOnlyElement(bid, state, rvtInfo); + ElementBuilder.BuildBlockOnlyElement(bid, state, rvtInfo, parameterIds); // Wall function extraction: scan all chunks for classIdx=0x00012100 blocks ExtractWallFunctions(state); @@ -808,7 +827,8 @@ private RevitFileInfo ReadCore(RootStorage root) "Local" or "Central" => true, _ => null, }; - ElementBuilder.PostProcess(rvtInfo, state, diag); + var elementsById = ElementBuilder.PostProcess(rvtInfo, state, diag); + state.SymbolPlacementGeometry = null; if (state.GridAxes is { } axes) { rvtInfo.CurvedGridAxes = axes.Paths; @@ -816,11 +836,11 @@ private RevitFileInfo ReadCore(RootStorage root) } progress?.Report(new("finalize-model")); LogPhase("Post-processed"); - ElementBuilder.ApplyValidatedStairComponentTypeNames(rvtInfo.Elements, state); - ElementBuilder.ApplyValidatedCorniceTypeNames(rvtInfo.Elements, state); - ElementBuilder.ApplyValidatedDuctTypeNames(rvtInfo.Elements, state); - ElementBuilder.ApplyValidatedMepTypeNames(rvtInfo.Elements, state); - ElementBuilder.ApplyMepCurveTypeLinks(rvtInfo.Elements, state); + ElementBuilder.ApplyValidatedStairComponentTypeNames(rvtInfo.Elements, state, elementsById); + ElementBuilder.ApplyValidatedCorniceTypeNames(rvtInfo.Elements, state, elementsById); + ElementBuilder.ApplyValidatedDuctTypeNames(rvtInfo.Elements, state, elementsById); + ElementBuilder.ApplyValidatedMepTypeNames(rvtInfo.Elements, state, elementsById); + ElementBuilder.ApplyMepCurveTypeLinks(rvtInfo.Elements, state, elementsById); diag?.WriteLine($"MEP curve types: occurrences with an exact type link={rvtInfo.Elements.Count(e => e.SerializedMepCurveTypeId != null)}, " + $"link differs from the general type={rvtInfo.Elements.Count(e => e.SerializedMepCurveTypeId != null && e.SerializedMepCurveTypeId != e.FamilyTypeId)}, " + $"types with an own name={rvtInfo.Elements.Count(e => e.ValidatedMepTypeName != null)}"); @@ -835,7 +855,7 @@ 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.ApplyHostLabels(rvtInfo, systemFamilyNames, state.ElemClassIdx, elementsById); ElementBuilder.ApplyWorkPlaneLabels(rvtInfo, systemFamilyNames); ElementBuilder.ApplyColumnLocationMarks(rvtInfo, state.OwnDocumentUnitOptions?.Value, state.ElemClassIdx); ElementBuilder.ApplyMepSystemParams(rvtInfo, state, systemFamilyNames); @@ -891,8 +911,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"); - ResolveParameterUnits(rvtInfo, state); - Parameter.ResolveZeroElementIds(rvtInfo, state); + FinalizeParameterValues(rvtInfo, state); // Shared-coordinates / true-north placement: the project may be modelled // axis-aligned but exported (by Revit) rotated+offset into shared coords. The exact @@ -921,10 +940,24 @@ private RevitFileInfo ReadCore(RootStorage root) diag?.WriteLine($"Sketch topology: {sketchOwners} owners, " + $"{rvtInfo.Elements.Where(e => e.SketchLoops != null).Sum(e => e.SketchLoops!.Count)} loops"); - rvtInfo.UserParameters = UserParameterCatalog.Build(state); + rvtInfo.UserParameters = userParameters; return (rvtInfo, state); } + private static void BuildOrderedElements(IReadOnlyList input, List output, + Func, Element> build) + { + if (input.Count == 0) return; + var elements = new Element[input.Count]; + Parallel.ForEach(System.Collections.Concurrent.Partitioner.Create(0, input.Count), range => + { + var parameterIds = new HashSet(); + for (int index = range.Item1; index < range.Item2; index++) + elements[index] = build(input[index], parameterIds); + }); + output.AddRange(elements); + } + internal static void MergeElemScanStringsInChunkOrder( IReadOnlyList>?> partialResults, Dictionary> elemScanStrings) @@ -1013,8 +1046,9 @@ internal static void MergeElemScanStringsInChunkOrder( ReadWideElementIndex(root, state, partitionStreams, framedStreams, wideSchema, diag); ReadRebarBars(root, state, partitionStreams, framedStreams, wideSchema); ClassifyAndParseRecords(chunks, state, diag); - ParseBlocks(state, diag); - RunTfStreamWalk(state); + var unreadableGReps = GRepParserV2.IsDecodeTracingEnabled() ? null : new HashSet(); + ParseBlocks(state, diag, unreadable: unreadableGReps); + RunTfStreamWalk(state, unreadable: unreadableGReps); if (state.WideSchema == null) ReadOwnDocumentUnits(root, state, diag); diag?.WriteLine($"Grid datums: {state.GridDatums.Count}"); @@ -1383,19 +1417,29 @@ private List DecompressPartitions(RootStorage root, TextWriter? diag, var raw = new byte[partStream.Length]; partStream.ReadExactly(raw); - // shortcut: saved format9 with one partition stream; multi-stream scope needs its own load validation. - if (partEntries.Count == 1 && partEntry.Name == "0") - { - var framingSchema = FormatsSchema.TryRead(root); - 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) - : Fail("the schema lacks the framing or wall classes", out failure); - diag?.WriteLine($" Own partition wall parts: {ownPartitionWallParts?.Count.ToString() ?? "unavailable"} ({failure ?? "exact"})"); + // Saved format 9 with a single partition. Reuse the walk when both readers use the same framing. + bool readWallParts = partEntries.Count == 1 && partEntry.Name == "0"; + string? wallFailure = null; + OwnPartitionParts.Collector? wallCollector = null; + if (readWallParts) + { + var wallClasses = formats == null ? null : OwnPartitionParts.ClassesOf(formats); + if (wallClasses == null || ElemTableLayout.IdWidth(formats!) is not int framingWidth) + wallFailure = "the schema lacks the framing or wall classes"; + else if (framing == (wallClasses.Tags, framingWidth)) + wallCollector = new OwnPartitionParts.Collector(wallClasses, framingWidth); + else + ownPartitionWallParts = OwnPartitionParts.Read(raw, wallClasses, framingWidth, out wallFailure); } - var chunks = CutPartition(raw, framing, decompressor, out var stats, out string? framingFailure, out var framed, entityCellTag); + var chunks = CutPartition(raw, framing, decompressor, out var stats, out string? framingFailure, out var framed, entityCellTag, wallCollector); + if (wallCollector != null) + { + wallFailure = wallCollector.Failure ?? framingFailure; + if (framed != null) ownPartitionWallParts = wallCollector.Finish(); + } + if (readWallParts) + diag?.WriteLine($" Own partition wall parts: {ownPartitionWallParts?.Count.ToString() ?? "unavailable"} ({wallFailure ?? "exact"})"); int? partitionNumber = int.TryParse(partEntry.Name, out int parsedPartition) ? parsedPartition : null; if (framed != null && partitionNumber is int partNum) framed = framed with { Partition = partNum }; @@ -1426,14 +1470,12 @@ private List DecompressPartitions(RootStorage root, TextWriter? diag, return allChunks; } - private static Dictionary? Fail(string reason, out string? failure) { failure = reason; return null; } - /// 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, out (int Members, int Decoded, int Failed, int Recovered, int Unverified) stats, out string? framingFailure, out PartitionFraming.Framed? framed, - ushort? familyEntityCellTag = null) + ushort? familyEntityCellTag = null, OwnPartitionParts.Collector? wallCollector = null) { var segments = new List(); var items = new List(); @@ -1444,6 +1486,7 @@ internal static List CutPartition(byte[] raw, (PartitionFraming.Tags Tag 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 => { + wallCollector?.Observe(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)); else if (familyKeys != null && r.Key.Length != 0 && r.Channel == 102) @@ -1768,17 +1811,20 @@ internal static EpisodeTableParseResult ParseEpisodeGuids(IReadOnlyList private static void ClassifyAndParseRecords(List chunks, ParsingState state, TextWriter? diag) { - foreach (var chunk in chunks) + var formats = new byte[chunks.Count]; + Parallel.For(0, chunks.Count, index => + { + var chunk = chunks[index]; + if (RecordParser.ContainsAnchoredR22Record(chunk, state.AllKnownIds)) formats[index] = 22; + else if (RecordParser.ContainsAnchoredR25Record(chunk, state.AllKnownIds)) formats[index] = 25; + }); + for (int index = 0; index < chunks.Count; index++) { - bool hasRecords = RecordParser.ContainsAnchoredR22Record( - chunk, state.AllKnownIds); - bool isR25 = !hasRecords && RecordParser.ContainsAnchoredR25Record( - chunk, state.AllKnownIds); - hasRecords |= isR25; - if (hasRecords) + var chunk = chunks[index]; + if (formats[index] != 0) { state.RecordChunks.Add(chunk); - if (isR25) + if (formats[index] == 25) RecordParser.ParseChunkR25(chunk, state); else RecordParser.ParseChunk(chunk, state); @@ -1914,9 +1960,10 @@ internal static void RecordWallSweepReferenceSource( } internal static void RecordFamilySymbolReferenceSource( - ParsingState state, byte[] data, int start, uint size, ushort classId, uint owner) + ParsingState state, byte[] data, int start, uint size, ushort classId, uint owner, + TfBlockDeserializer.WallCompleteInputRead? complete = null) { - RecordOwnFamilyCutoutInputs(state, data, start, size, classId, owner); + RecordOwnFamilyCutoutInputs(state, data, start, size, classId, owner, complete); bool ownerMatches = start >= 0 && start <= data.Length - 4 && BitConverter.ToUInt32(data, start) == owner; if (TfBlockDeserializer.IsSubclassOf(classId, 1794)) { @@ -2364,7 +2411,8 @@ internal static void RecordSpaceBoundarySource( } internal static void RecordWallLocationLine( - ParsingState state, byte[] segment, int start, uint size, ushort classId, uint owner) + ParsingState state, byte[] segment, int start, uint size, ushort classId, uint owner, + TfBlockDeserializer.WallCompleteInputRead? complete = null) { if (!TfBlockDeserializer.IsSubclassOf(classId, 37)) return; if (!state.OwnedElementClassRoots.TryGetValue(owner, out var root) @@ -2373,20 +2421,22 @@ internal static void RecordWallLocationLine( if (classId is not (3524 or 361)) return; var line = (!state.CurveDriverCandidates.TryGetValue(owner, out var candidates) || candidates.Count == 0) && start >= 0 && start <= segment.Length - 4 && BitConverter.ToUInt32(segment, start) == owner - ? TfBlockDeserializer.ExtractOwnWallLocationLine(segment, start, size, classId, out _) : null; + ? TfBlockDeserializer.ExtractOwnWallLocationLine(segment, start, size, classId, out _, + complete ?? new(segment, start, size, classId)) : null; if (line != null) state.OwnWallLocationLines[owner] = line; } /// Records the panel order of a wall's curtain grid (). /// Every wall root counts: a second root of the same id makes the order ambiguous. internal static void RecordCurtainPanelOrder( - ParsingState state, byte[] segment, int start, uint size, ushort classId, uint owner) + ParsingState state, byte[] segment, int start, uint size, ushort classId, uint owner, + TfBlockDeserializer.WallCompleteInputRead? complete = null) { if (!TfBlockDeserializer.IsSubclassOf(classId, 362)) return; - var ids = start >= 0 && start <= segment.Length - 4 && BitConverter.ToUInt32(segment, start) == owner - ? TfBlockDeserializer.ExtractCurtainGridPanelIds(segment, start, size, classId) : null; state.CurtainPanelOrders[owner] = state.CurtainPanelOrders.TryGetValue(owner, out var old) - ? (old.BlockCount + 1, null) : (1, ids); + ? (old.BlockCount + 1, null) + : (1, start >= 0 && start <= segment.Length - 4 && BitConverter.ToUInt32(segment, start) == owner + ? TfBlockDeserializer.ExtractCurtainGridPanelIds(segment, start, size, classId, complete) : null); } /// The drive curve of a family instance in a file with its own schema: the field walk of the root block names no pointer @@ -2545,7 +2595,8 @@ private static void RecoverFramedScheduleTypes(ParsingState state, /// Continuous-stream anchored block walk (see TfStreamWalker): native param /// stores + full-coverage re-run of block-driven signals (curve owners, node owners, /// registry categories, sketch/detail curves). - internal static void RunTfStreamWalk(ParsingState state, IProgress? progress = null) + internal static void RunTfStreamWalk(ParsingState state, IProgress? progress = null, + HashSet? unreadable = null, Task? blockGeometry = null) { // The walk reads 4-byte ids and Revit 2022 class numbers; a 64-bit-id file is decoded by WideElementRecords. if (state.WideSchema != null && !state.R22View) return; @@ -2555,7 +2606,9 @@ internal static void RunTfStreamWalk(ParsingState state, IProgress(); + var wallGeometryCandidates = new List<(byte[] Data, int Start, uint Size, ushort Cls, uint Owner)>(); + var segmentSources = new TfStreamWalker.SegmentSources(); + var nativeBlocks = new TfNativeBlocks(state, segmentSources); // 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 = @@ -2595,8 +2648,10 @@ internal static void RunTfStreamWalk(ParsingState state, IProgress 0 }) state.NativeParamsFromRootClass.Add(eid); - if (cls == 2299) - { - np ??= new TfBlockDeserializer.NativeParams(); - np.Fields["__isLevel"] = 1; - var levelName = TfBlockDeserializer.ExtractLevelName( - seg, bs, (uint)ds, cls); - if (!string.IsNullOrWhiteSpace(levelName)) - np.StringFields["m_text"] = levelName; - if (TfBlockDeserializer.ExtractLevelPlane(seg, bs, (uint)ds, cls) is { } plane) - { - state.LevelPlanes[eid] = plane; - if (double.IsFinite(plane.Origin[2])) np.DoubleFields["__levelElevation"] = plane.Origin[2]; - } - } - if (np is { Count: > 0 }) state.NativeParams[eid] = np; - if (cls == 0x083C - && TfBlockDeserializer.ExtractGridDatum(seg, bs, (uint)ds, cls) - is { } gridDatum) - { - state.GridDatums[eid] = new GridDatumData( - gridDatum.Name, gridDatum.StartPoint, - gridDatum.EndPoint, gridDatum.CutVector, gridDatum.LevelInterval, gridDatum.XVector, gridDatum.Envelope, - gridDatum.Origin, gridDatum.YVector); - } - } - else if (state.R22View && rootClassBlock && TfBlockDeserializer.IsSubclassOf(cls, 1794) && state.NativeParams.TryGetValue(eid, out var fieldNp)) - AddDriveCurveFromRewrittenBlock(fieldNp, TfBlockDeserializer.ExtractParams(seg, bs, (uint)ds, cls)); + nativeBlocks.Add(seg, bs, ds, cls, eid, rootClassBlock); if (cls == 480) // BasePoint: internal + shared positions { var coordinates = TfBlockDeserializer.ExtractBasePointCoordinates( @@ -2705,9 +2729,8 @@ 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 is null ? null : (completed, total) => progress.Report(new("parameter-stream", completed, total)), + sources: segmentSources); + nativeBlocks.Flush(); progress?.Report(new("recover-geometry")); if (unanchoredTypeRoots != null) @@ -2757,7 +2782,18 @@ internal static void RunTfStreamWalk(ParsingState state, IProgress(); + foreach (var candidate in wallGeometryCandidates) + if (!state.GrepBlocks.ContainsKey(candidate.Owner)) + walkGReps.Add((candidate.Data, candidate.Start, candidate.Size, candidate.Owner)); + ApplyFirstDecodableGReps(state, walkGReps, unreadable); // Second pass: geometry blocks the anchored walk missed. Family symbols live in // the family doc's own id space (absent from ElemTable), so whole symbol regions @@ -2787,7 +2823,13 @@ internal static void RunTfStreamWalk(ParsingState state, IProgress(); - TfStreamWalker.ScanBlocks(state.Chunks, missingIds, (seg, bs, ds, cls, eid) => + bool scanSlices = dumpGrepEids.Count == 0 && !GRepParserV2.IsDecodeTracingEnabled(); + if (scanSlices) TfStreamWalker.ScanBlockSlices(state.Chunks, missingIds, VisitTarget); + else TfStreamWalker.ScanBlocks(state.Chunks, missingIds, VisitTarget, segmentSources); + int found = ApplyFirstDecodableGReps(state, scanGReps, unreadable); + DiagnosticSink.WriteLine($" [gscan] targeted scan recovered {found} G-blocks + {foundSketch} sketch curves for {missingIds.Count} candidate ids"); + + void VisitTarget(byte[] seg, int bs, uint ds, ushort cls, uint eid) { if (dumpGrepEids.Count > 0 && dumpGrepEids.Contains(eid)) { @@ -2824,44 +2866,84 @@ internal static void RunTfStreamWalk(ParsingState state, IProgressDecodes 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<(byte[] Segment, int Start, uint Size, uint Eid)> jobs, + HashSet? unreadable) { + // Previous passes already rejected these exact byte ranges. Group only candidates that can be tried. + if (unreadable is { Count: > 0 }) + jobs.RemoveAll(job => unreadable.Contains(new(job.Segment, job.Start, job.Size))); if (jobs.Count == 0) return 0; bool slowDiag = Environment.GetEnvironmentVariable("RVTIO_GREP_SLOW") is { Length: > 0 }; - int stored = 0; - BlockParser.DecodeGRepBlocksInOrder(jobs.Count, - index => + if (OperatingSystem.IsBrowser() || unreadable == null || slowDiag) + { + int count = 0; + BlockParser.DecodeGRepBlocksInOrder(jobs.Count, index => Decode(jobs[index]), + (index, geometry) => + { + var job = jobs[index]; + if (geometry == null) unreadable?.Add(new(job.Segment, job.Start, job.Size)); + if (StoreFirstDecodableGRep(state, job.Eid, geometry)) count++; + }); + return count; + } + + var decoded = new GRepData?[jobs.Count]; + var failed = new bool[jobs.Count]; + var candidates = Enumerable.Range(0, jobs.Count).ToLookup(index => jobs[index].Eid); + Parallel.ForEach(candidates, elementJobs => + { + foreach (int index in elementJobs) { var job = jobs[index]; - var clock = slowDiag ? System.Diagnostics.Stopwatch.StartNew() : null; var geometry = GRepParserV2.Parse(job.Segment, job.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 (geometry == null) + { + failed[index] = true; + continue; + } + decoded[index] = geometry; + break; + } + }); + int stored = 0; + for (int index = 0; index < jobs.Count; index++) + { + if (failed[index]) { - if (StoreFirstDecodableGRep(state, jobs[index].Eid, geometry)) stored++; - }); + var job = jobs[index]; + unreadable.Add(new(job.Segment, job.Start, job.Size)); + } + if (StoreFirstDecodableGRep(state, jobs[index].Eid, decoded[index])) stored++; + decoded[index] = null; + } return stored; + + GRepData? Decode((byte[] Segment, int Start, uint Size, uint Eid) job) + { + var clock = slowDiag ? System.Diagnostics.Stopwatch.StartNew() : null; + var geometry = GRepParserV2.Parse(job.Segment, job.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; + } } - /// Stores a decoded block for an element that has none yet; the first decodable block of an element wins. + /// Stores the first geometry the reader can decode for this element. internal static bool StoreFirstDecodableGRep(ParsingState state, uint eid, GRepData? geometry) => geometry != null && state.GrepBlocks.TryAdd(eid, geometry); - internal static void ParseBlocks(ParsingState state, TextWriter? diag, IProgress? progress = null) + internal static Task? ParseBlocks(ParsingState state, TextWriter? diag, IProgress? progress = null, + HashSet? unreadable = null, bool overlapGeometry = false) { const int passCount = 8; int completedPasses = 0; @@ -2877,69 +2959,51 @@ void Lap(string name) foreach (var eid in state.Records.Keys) state.AllKnownIds.Add(eid); - // Name-table scan: authoritative element names + symbol-to-family chain - foreach (var chunk in state.NonRecordChunks) - NameTableScanner.Scan(chunk, state); - foreach (var chunk in state.RecordChunks) - NameTableScanner.Scan(chunk, state); + // Each scan owns its result maps and keeps the original order of its input chunks. + var scans = new (string Name, Action Scan)[] + { + ("name table", () => ScanChunks(chunk => NameTableScanner.Scan(chunk, state))), + ("shading entries", () => ScanChunks(chunk => BlockParser.CollectShadingEntries(chunk, state.ShadingEntries))), + ("hvac tables", () => ScanChunks(chunk => BlockParser.CollectHvacTables( + chunk, state.AllKnownIds, state.HvacSpaceTypeParams, state.HvacScheduleRefs))), + ("level elevations", () => ScanChunks(chunk => BlockParser.CollectLevelElevations(chunk, state))), + ("bip strings", () => ScanChunks(chunk => BlockParser.CollectBipStrings(chunk, state))), + ("view planes", ScanTextNotesAndPlanes), + }; + var scanTimes = new TimeSpan[scans.Length]; + Parallel.For(0, scans.Length, index => + { + long started = System.Diagnostics.Stopwatch.GetTimestamp(); + scans[index].Scan(); + scanTimes[index] = System.Diagnostics.Stopwatch.GetElapsedTime(started); + }); diag?.WriteLine($"Name table: {state.ElementNameTable.Count} entries, {state.NameHolderTarget.Count} holders"); + for (int index = 0; index < scans.Length; index++) + { + diag?.WriteLine($"Timing: {scans[index].Name} {scanTimes[index].TotalSeconds:F1}s"); + progress?.Report(new("element-blocks", ++completedPasses, passCount)); + } + lap.Restart(); - Lap("name table"); - // Global shading-entry scan (holder id to color/shininess votes): fallback source for - // material colors when the material's own 0x09B6 block is not decodable. - foreach (var chunk in state.NonRecordChunks) - BlockParser.CollectShadingEntries(chunk, state.ShadingEntries); - foreach (var chunk in state.RecordChunks) - BlockParser.CollectShadingEntries(chunk, state.ShadingEntries); - - Lap("shading entries"); - // Chunk-level HVAC load-type scan (classIdx- and block-walk-independent). - foreach (var chunk in state.NonRecordChunks) - BlockParser.CollectHvacTables(chunk, state.AllKnownIds, state.HvacSpaceTypeParams, state.HvacScheduleRefs); - foreach (var chunk in state.RecordChunks) - BlockParser.CollectHvacTables(chunk, state.AllKnownIds, state.HvacSpaceTypeParams, state.HvacScheduleRefs); - - Lap("hvac tables"); - // Level-elevation candidates (gated to OST_Levels at application time). - foreach (var chunk in state.NonRecordChunks) - BlockParser.CollectLevelElevations(chunk, state); - foreach (var chunk in state.RecordChunks) - BlockParser.CollectLevelElevations(chunk, state); - - Lap("level elevations"); - // BIP-keyed strings (per-element marks/descriptions/comments/keynotes). - foreach (var chunk in state.NonRecordChunks) - BlockParser.CollectBipStrings(chunk, state); - foreach (var chunk in state.RecordChunks) - BlockParser.CollectBipStrings(chunk, state); - - Lap("bip strings"); - // Text notes: their own block holds the text and its position; the block walk of the project's own block does - // not reach every note, so every chunk is scanned for the class bytes. - foreach (var chunk in state.NonRecordChunks) - BlockParser.CollectTextNotes(chunk, state); - foreach (var chunk in state.RecordChunks) - BlockParser.CollectTextNotes(chunk, state); - - foreach (var chunk in state.NonRecordChunks) - BlockParser.CollectImageSizes(chunk, state); - foreach (var chunk in state.RecordChunks) - BlockParser.CollectImageSizes(chunk, state); + void ScanChunks(Action scan) + { + foreach (var chunk in state.NonRecordChunks) scan(chunk); + foreach (var chunk in state.RecordChunks) scan(chunk); + } - foreach (var chunk in state.NonRecordChunks) - BlockParser.CollectViewPlanes(chunk, state); - foreach (var chunk in state.RecordChunks) - 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); - - Lap("view planes"); + void ScanTextNotesAndPlanes() + { + ScanChunks(chunk => BlockParser.CollectTextNotes(chunk, state)); + var planeChunks = new HashSet(ReferenceEqualityComparer.Instance); + ScanChunks(chunk => + { + BlockParser.CollectViewPlanes(chunk, state, includeImages: true); + planeChunks.Add(chunk); + }); + // Some view blocks only appear in the unclassified chunks. + foreach (var chunk in state.Chunks) + if (planeChunks.Add(chunk)) BlockParser.CollectViewPlanes(chunk, state); + } // 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 @@ -2954,25 +3018,27 @@ void Lap(string name) 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); + if (!overlapGeometry) BlockParser.ApplyPendingGReps(state, firstPassGReps, unreadable); diag?.WriteLine($"Block-only elements: {state.BlockOnlyIds.Count}"); Lap("first parse pass"); // Second pass: re-parse for block-only elements + var secondPassGReps = new List(); if (state.BlockOnlyIds.Count > 0) { 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); + BlockParser.SkipRepeatedFirstGReps(firstPassGReps, secondPassGReps); + if (!overlapGeometry) BlockParser.ApplyPendingGReps(state, secondPassGReps, unreadable); } Lap("second parse pass"); - diag?.WriteLine($"GRep blocks: {state.GrepBlocks.Count} elements"); + bool deferGeometry = overlapGeometry && (firstPassGReps.Count > 0 || secondPassGReps.Count > 0); + if (!deferGeometry) diag?.WriteLine($"GRep blocks: {state.GrepBlocks.Count} elements"); diag?.WriteLine($"FamilyInstance transforms: {state.FamilyInstanceTransforms.Count} elements"); diag?.WriteLine($"Dimensions/constraints (0x091F+0x009D): {state.Dimensions.Count} elements"); diag?.WriteLine($"Sketch-line curves (0x0346): {state.SketchCurves.Count} elements"); @@ -2982,7 +3048,13 @@ void Lap(string name) diag?.WriteLine($"ForgeTypeId spec registry: {state.ForgeSpecRegistry.Count} entries"); if (state.ForgeParamSpecs.Count > 0) diag?.WriteLine($"ForgeId to spec mappings: {state.ForgeParamSpecs.Count} params"); - + return deferGeometry + ? Task.Run(() => + { + BlockParser.ApplyPendingGReps(state, firstPassGReps, unreadable); + BlockParser.ApplyPendingGReps(state, secondPassGReps, unreadable); + }) + : null; } /// @@ -2992,16 +3064,17 @@ void Lap(string name) private static void ExtractWallFunctions(ParsingState state) { // classIdx bytes: 00 21 01 00 (little-endian 0x00012100) - byte[] classIdxPattern = [0x00, 0x21, 0x01, 0x00]; + ReadOnlySpan classIdxPattern = [0x00, 0x21, 0x01, 0x00]; foreach (var chunk in state.NonRecordChunks.Concat(state.RecordChunks)) { // Scan for the classIdx pattern at offset +12 from a potential block header - for (int i = 0; i + 16 + 0x1C <= chunk.Length; i++) + int lastStart = chunk.Length - 16 - 0x1C; + for (int i = 0; i <= lastStart; i++) { - if (chunk[i + 12] != classIdxPattern[0] || chunk[i + 13] != classIdxPattern[1] - || chunk[i + 14] != classIdxPattern[2] || chunk[i + 15] != classIdxPattern[3]) - continue; + int next = chunk.AsSpan(i + 12, lastStart - i + classIdxPattern.Length).IndexOf(classIdxPattern); + if (next < 0) break; + i += next; uint eid = BitConverter.ToUInt32(chunk, i); if (eid == 0 || !state.AllKnownIds.Contains(eid)) continue; @@ -3011,11 +3084,9 @@ private static void ExtractWallFunctions(ParsingState state) // Read function enum at data offset 0x18 (block header is 16 bytes) int dataStart = i + 16; - if (dataStart + 0x1C > chunk.Length) continue; - int funcVal = BitConverter.ToInt32(chunk, dataStart + 0x18); - if (funcVal >= 0 && funcVal <= 5 && !state.WallTypeFunctions.ContainsKey(eid)) - state.WallTypeFunctions[eid] = funcVal; + if (funcVal >= 0 && funcVal <= 5) + state.WallTypeFunctions.TryAdd(eid, funcVal); } } } @@ -3070,11 +3141,21 @@ private static void ExtractExternalParamCaptionsFromRaw(ParsingState state, ref { // Scan all chunks for [FFFFFFFF][header][GUID:16][00 00][nameLen:4][caption] var guidToCaption = new Dictionary(); - foreach (var chunk in state.Chunks) + var byChunk = new Dictionary?[state.Chunks.Count]; + Parallel.For(0, byChunk.Length, index => byChunk[index] = ScanCaptionChunk(state.Chunks[index])); + foreach (var captions in byChunk) + if (captions != null) + foreach (var (guid, caption) in captions) guidToCaption.TryAdd(guid, caption); + + static Dictionary? ScanCaptionChunk(byte[] chunk) { + ReadOnlySpan sentinel = [0xFF, 0xFF, 0xFF, 0xFF]; + Dictionary? captions = null; for (int s = 0; s + 40 <= chunk.Length; s++) { - if (BitConverter.ToUInt32(chunk, s) != 0xFFFFFFFF) continue; + int next = chunk.AsSpan(s, chunk.Length - s - 36).IndexOf(sentinel); + if (next < 0) break; + s += next; for (int hdrOff = 4; hdrOff <= 14; hdrOff += 2) { int guidOff = s + hdrOff; @@ -3090,8 +3171,7 @@ private static void ExtractExternalParamCaptionsFromRaw(ParsingState state, ref bool isCyrillic = nhi == 0x04; bool isAsciiLetter = nhi == 0x00 && ((nlo2 >= 'A' && nlo2 <= 'Z') || (nlo2 >= 'a' && nlo2 <= 'z')); if (!isPrefix && !isCyrillic && !isAsciiLetter) continue; - var guidBytes = new byte[16]; - Array.Copy(chunk, guidOff, guidBytes, 0, 16); + var guidBytes = chunk.AsSpan(guidOff, 16); var guid = new Guid(guidBytes); if (guid == Guid.Empty) continue; int ff = 0, zz = 0; @@ -3105,11 +3185,11 @@ private static void ExtractExternalParamCaptionsFromRaw(ParsingState state, ref } string rawName = sb.ToString().Trim(); if (rawName.Length > 0 && (rawName[0] == '\u2026' || rawName[0] == '&')) rawName = rawName[1..]; - if (!string.IsNullOrEmpty(rawName) && !guidToCaption.ContainsKey(guid)) - guidToCaption[guid] = rawName; + if (!string.IsNullOrEmpty(rawName)) (captions ??= new()).TryAdd(guid, rawName); break; } } + return captions; } // Resolve GUID to elemId via record chunk table [GUID:16][elemId:4] var guidToElemId = new Dictionary(); @@ -3121,8 +3201,16 @@ private static void ExtractExternalParamCaptionsFromRaw(ParsingState state, ref if (g.HasValue) guidToElemId.TryAdd(g.Value, eid); } var captionPrefixes = BuildGuidPrefixSet(guidToCaption.Keys); - foreach (var chunk in state.RecordChunks) - MapRecordChunkGuids(chunk, guidToCaption, captionPrefixes, state.AllKnownIds, guidToElemId); + var idsByChunk = new Dictionary?[state.RecordChunks.Count]; + Parallel.For(0, idsByChunk.Length, index => + { + var ids = new Dictionary(); + MapRecordChunkGuids(state.RecordChunks[index], guidToCaption, captionPrefixes, state.AllKnownIds, ids); + if (ids.Count > 0) idsByChunk[index] = ids; + }); + foreach (var ids in idsByChunk) + if (ids != null) + foreach (var (guid, eid) in ids) guidToElemId[guid] = eid; int guidApplied = 0; foreach (var (guid, caption) in guidToCaption) { @@ -3335,7 +3423,7 @@ private static void ExtractBinaryParamGuids(ParsingState state, TextWriter? diag /// Recover the active project-location transform. The dominant repeated /// Z-rotation is true north; the survey BasePoint stores matching internal and shared /// positions, from which the translation follows exactly. - private static double[]? FindSharedTransform( + internal static double[]? FindSharedTransform( IReadOnlyList chunks, IReadOnlyDictionary basePoints, IReadOnlyDictionary records, @@ -3349,15 +3437,17 @@ private static void ExtractBinaryParamGuids(ParsingState state, TextWriter? diag static bool Unit(double v) => !double.IsNaN(v) && Math.Abs(v) <= 1.0000001; static bool AxisAligned(double s) => Math.Abs(s) < 1e-4 || Math.Abs(Math.Abs(s) - 1) < 1e-4; - var votes = new Dictionary(); // angle (micro-radians) -> occurrences - var representatives = new Dictionary(); - foreach (var chunk in chunks) + var votes = new Dictionary(); + for (int chunkIndex = 0; chunkIndex < chunks.Count; chunkIndex++) { - // Block payloads are not guaranteed to be 8-byte aligned. Walk all eight - // alignments so transforms shifted by strings or pointers are still found. - for (int alignment = 0; alignment < 8; alignment++) - for (int off = alignment; off + 72 <= chunk.Length; off += 8) + var chunk = chunks[chunkIndex]; + // For 1e-4 <= |c01| <= 1.0000001, its high byte is 0x3F or 0xBF. + int limit = chunk.Length - 71; + for (int off = 0; off < limit; off++) { + int next = chunk.AsSpan(off + 15, limit - off).IndexOfAny((byte)0x3F, (byte)0xBF); + if (next < 0) break; + off += next; double c00 = BitConverter.ToDouble(chunk, off); double c01 = BitConverter.ToDouble(chunk, off + 8); if (!Unit(c00) || !Unit(c01) || AxisAligned(c01)) continue; @@ -3373,38 +3463,43 @@ static bool AxisAligned(double s) => if (Math.Abs(c00 * c00 + c01 * c01 - 1) > 1e-9) continue; if (Math.Abs(c10 + c01) > 1e-9 || Math.Abs(c11 - c00) > 1e-9) continue; long key = (long)Math.Round(Math.Atan2(c01, c00) * 1e6); - votes.TryGetValue(key, out int count); - votes[key] = count + 1; - representatives.TryAdd(key, (c00, c01)); + if (!votes.TryGetValue(key, out var vote)) + votes[key] = (1, chunkIndex, off, c00, c01); + // Keep the first matrix in the original alignment-first order. + else if (vote.Chunk == chunkIndex && (off & 7) < (vote.Offset & 7)) + votes[key] = (vote.Count + 1, chunkIndex, off, c00, c01); + else + votes[key] = (vote.Count + 1, vote.Chunk, vote.Offset, vote.C, vote.S); } } double cc = 1, ss = 0; bool foundRotation = false; - var ranked = votes.OrderByDescending(v => v.Value).ToList(); - int top = ranked.Count > 0 ? ranked[0].Value : 0; - int runner = ranked.Count > 1 ? ranked[1].Value : 0; + var ranked = votes.Values.OrderByDescending(v => v.Count) + .ThenBy(v => v.Chunk).ThenBy(v => v.Offset & 7).ThenBy(v => v.Offset).Take(2).ToList(); + int top = ranked.Count > 0 ? ranked[0].Count : 0; + int runner = ranked.Count > 1 ? ranked[1].Count : 0; diag?.WriteLine($"Shared transform signals: basePoints={basePoints.Count}, rotations={votes.Count}, top={top}, runner={runner}"); // Require a clear, well-supported winner: the shared north is carried by many // records; a stray furniture angle is not (and does not clear a 2.5x runner-up). if (top >= 8 && top * 2 >= runner * 5) { - (cc, ss) = representatives[ranked[0].Key]; + (cc, ss) = (ranked[0].C, ranked[0].S); foundRotation = true; } diag?.WriteLine($"SharedTransform diag: foundRotation={foundRotation} cc={cc:R} ss={ss:R} " + $"angleRad={Math.Atan2(ss, cc):R} votes={votes.Count} top={top} runner={runner}"); if (diag != null && ranked.Count > 0) { - var (topC, topS) = representatives[ranked[0].Key]; + var (_, _, _, topC, topS) = ranked[0]; diag.WriteLine($"SharedTransform diag: topWinner(rawVote) angleRad={Math.Atan2(topS, topC):R} " - + $"c={topC:R} s={topS:R} count={ranked[0].Value}"); + + $"c={topC:R} s={topS:R} count={top}"); } if (diag != null && ranked.Count > 1) { - var (runnerC, runnerS) = representatives[ranked[1].Key]; + var (_, _, _, runnerC, runnerS) = ranked[1]; diag.WriteLine($"SharedTransform diag: runnerUp angleRad={Math.Atan2(runnerS, runnerC):R} " - + $"c={runnerC:R} s={runnerS:R} count={ranked[1].Value}"); + + $"c={runnerC:R} s={runnerS:R} count={runner}"); } if (diag != null) @@ -3509,35 +3604,32 @@ internal sealed record ActiveProjectLocation( return new ActiveProjectLocation([c, s, 0, -s, c, 0, 0, 0, 1.0, tx, ty, tz], latitude, longitude, elevation, placeName); } - private static void ResolveParameterUnits(RevitFileInfo rvtInfo, ParsingState state) + private static void FinalizeParameterValues(RevitFileInfo rvtInfo, ParsingState state) { - int resolved = 0; - foreach (var elem in rvtInfo.Elements) + var bySource = new System.Collections.Concurrent.ConcurrentDictionary< + (string? ForgeId, string? Name), Parameter.DisplayUnits?>(); + var (hasZeroPhase, hasZeroDimStyle) = Parameter.ResolveZeroElementIdDomains(rvtInfo, state); + Parallel.For(0, rvtInfo.Elements.Count, index => { + var elem = rvtInfo.Elements[index]; foreach (var param in elem.Parameters) { + param.ResolveZeroElementId(elem, hasZeroPhase, hasZeroDimStyle); if (param.StorageType != StorageType.Double) continue; - - string? specType = null; - - // Try the ForgeId spec mapping (from 0x0B3A blocks) - if (param.ForgeId != null && state.ForgeParamSpecs.TryGetValue(param.ForgeId, out var spec)) - specType = spec; - - // 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) continue; - - param.SpecType = specType; - var (symbol, factor) = GetUnitDisplay(unitCat); - param.UnitSymbol = symbol; - param.ConversionFactor = factor; - resolved++; + var key = (param.ForgeId, Name: param.DefinitionName); + var units = bySource.GetOrAdd(key, static (source, parsingState) => + { + string? specType = source.ForgeId == null ? null : parsingState.ForgeParamSpecs.GetValueOrDefault(source.ForgeId); + string? unitCat = specType != null ? GetUnitCategory(specType) : null; + if (unitCat == null && source.Name is { } bipName) + unitCat = GetUnitCategoryFromBipName(bipName); + if (unitCat == null) return null; + var (symbol, factor) = GetUnitDisplay(unitCat); + return new Parameter.DisplayUnits(specType, symbol, factor); + }, state); + if (units != null) param.SetDisplayUnits(units); } - } + }); } /// Extract unit category from spec type URN. @@ -3659,8 +3751,9 @@ private static void RemapInstanceParamKeys(ParsingState state, TextWriter? diag) diag?.WriteLine($"Family param maps: {state.FamilyParamMaps.Count} symbols; remapped {remappedStrings} strings, {remappedDoubles} doubles ({droppedNoMap} unmapped)"); } - private static void PrePropagateBipDoubles(ParsingState state, TextWriter? diag) + internal static void PrePropagateBipDoubles(ParsingState state, TextWriter? diag) { + var filtered = new Dictionary, Dictionary>(ReferenceEqualityComparer.Instance); int propagated = 0; for (int pass = 0; pass < 3; pass++) { @@ -3670,16 +3763,29 @@ private static void PrePropagateBipDoubles(ParsingState state, TextWriter? diag) if (state.ElemBipDoubles.ContainsKey(eid)) continue; if (rec.References.Count == 0) continue; Dictionary? inherited = null; + bool ownsMap = false; foreach (var refId in rec.References) { if (refId == eid) continue; if (!state.ElemBipDoubles.TryGetValue(refId, out var refDbls)) continue; - inherited ??= new Dictionary(); + if (inherited == null) + { + var builtIns = BuiltInsOf(refDbls); + if (builtIns.Count > 0) inherited = builtIns; + continue; + } + if (ReferenceEquals(inherited, refDbls)) continue; foreach (var (k, v) in refDbls) { // Only propagate BuiltInParameter keys (negative), not user params (positive IDs) - if (k < 0) - inherited.TryAdd(k, v); + if (k >= 0) continue; + if (!ownsMap) + { + if (inherited.ContainsKey(k)) continue; + inherited = new Dictionary(inherited); + ownsMap = true; + } + inherited.TryAdd(k, v); } } if (inherited != null && inherited.Count > 0) @@ -3704,8 +3810,10 @@ private static void PrePropagateBipDoubles(ParsingState state, TextWriter? diag) if (refId == eid) continue; if (state.WallTypeWidths.TryGetValue(refId, out var tw)) { - if (bd == null) state.ElemBipDoubles[eid] = bd = new Dictionary(); + // The old map can also be the inherited snapshot of another record. + bd = bd == null ? new Dictionary() : new Dictionary(bd); bd[-1001000] = tw; + state.ElemBipDoubles[eid] = bd; wallWidthPropagated++; break; } @@ -3713,6 +3821,21 @@ private static void PrePropagateBipDoubles(ParsingState state, TextWriter? diag) } if (wallWidthPropagated > 0) diag?.WriteLine($"Wall width propagated to {wallWidthPropagated} additional instances"); + + Dictionary BuiltInsOf(Dictionary source) + { + if (filtered.TryGetValue(source, out var builtIns)) return builtIns; + foreach (int key in source.Keys) + { + if (key < 0) continue; + builtIns = new Dictionary(); + foreach (var (id, value) in source) + if (id < 0) builtIns.Add(id, value); + filtered.Add(source, builtIns); + return builtIns; + } + return source; + } } /// diff --git a/tests/RvtIO.Tests/CompactJsonExporterTests.cs b/tests/RvtIO.Tests/CompactJsonExporterTests.cs index 8e80f662..e7ceb6fe 100644 --- a/tests/RvtIO.Tests/CompactJsonExporterTests.cs +++ b/tests/RvtIO.Tests/CompactJsonExporterTests.cs @@ -75,6 +75,37 @@ public void Nodes_CarryIdentityFields() Assert.All(elements, item => Assert.Equal(0, item.GetProperty("properties").GetArrayLength())); } + [Fact] + public void LargeExport_PreservesSerialBytesAndReport() + { + var info = Info(); + for (int id = 2200; id >= 100; id--) + info.Elements.Add(id % 2 == 0 ? Row(id, 3524, -2000011, typeId: 10) : Row(id, null, null)); + + var identity = new CompactIdentity(CompactUniverse.Select(info)); + var serial = CompactPropertySources.Create(info, null, true, CompactHeaderCategory.Of, identity: identity); + var parallel = CompactPropertySources.Create(info, null, true, identity: identity); + Assert.False(serial.CanFork); + Assert.True(parallel.CanFork); + + static (byte[] Bytes, CompactExportStats Stats, string Report) Export( + RevitFileInfo info, CompactIdentity identity, CompactPropertySources source) + { + using var output = new MemoryStream(); + using var report = new StringWriter(); + var stats = CompactJsonExporter.Export(info, output, source, report, identity); + source.Builtin.WriteReport(report); + return (output.ToArray(), stats, report.ToString()); + } + + var expected = Export(info, identity, serial); + var actual = Export(info, identity, parallel); + Assert.Equal(expected.Bytes, actual.Bytes); + Assert.Equal(expected.Stats, actual.Stats); + Assert.Equal(expected.Report, actual.Report); + Assert.Equal(serial.Builtin.LastIds, parallel.Builtin.LastIds); + } + private static string[] ElementNames(byte[] json) { using var doc = JsonDocument.Parse(json); diff --git a/tests/RvtIO.Tests/CompactSolidQuantitiesTests.cs b/tests/RvtIO.Tests/CompactSolidQuantitiesTests.cs index 1c44de3e..baecf22c 100644 --- a/tests/RvtIO.Tests/CompactSolidQuantitiesTests.cs +++ b/tests/RvtIO.Tests/CompactSolidQuantitiesTests.cs @@ -1,4 +1,5 @@ using RvtIO.Compact; +using RvtIO.Internal; using RvtIO.Model; using Xunit; @@ -75,6 +76,31 @@ public void NoSolid_IsShapeNone() Assert.Throws(() => CompactSolidQuantities.Value(CompactSolidQuantities.Measure(new GeometryData(), 2), "perimeter")); } + [Theory] + [InlineData(true, true, 0, 1)] + [InlineData(false, true, 1, 8)] + [InlineData(false, false, 2, 27)] + public void ElementMeasurementChoosesTheFirstDetailLevelWithSolids(bool coarse, bool medium, int level, double volume) + { + static GRepData Block(List box) => new() + { + Faces = box.Select(face => new GRepFace { Vertices = face.OuterVertices, PlaneSurface = true }).ToList(), + Solids = [new GRepSolid { FaceIndices = [0, 1, 2, 3, 4, 5], IsClosed = true }], + }; + var state = new ParsingState(); + state.GrepBlocks[10] = new GRepData + { + Coarse = coarse ? Block(Box(0, 0, 0, 1, 1, 1)) : new GRepData(), + Medium = medium ? Block(Box(0, 0, 0, 2, 2, 2)) : new GRepData(), + }; + var element = new Element { Id = 10, Geometry = Solids(true, Box(0, 0, 0, 3, 3, 3)) }; + + var result = CompactSolidQuantities.Measure(element, state); + + Assert.Equal(level, result.Level); + Assert.Equal(volume, result.Volume, 9); + } + private const string Lines = "V\tFamilyInstance\t-1012806\t-2001330\tsolid\tvolume\t120\n" + "V\tFamilyInstance\t-1012806\t-2001330\tnone\tempty\t9\n" + "V\tFamilyInstance\t-1012805\t-2000170\tone\tmaxface\t40\n" diff --git a/tests/RvtIO.Tests/DerivedInstanceParamsTests.cs b/tests/RvtIO.Tests/DerivedInstanceParamsTests.cs index 705a052d..10bc3691 100644 --- a/tests/RvtIO.Tests/DerivedInstanceParamsTests.cs +++ b/tests/RvtIO.Tests/DerivedInstanceParamsTests.cs @@ -21,6 +21,47 @@ public void RoomSeparationLineDoesNotUseItsNeighborAsAType() private static Parameter P(int id, StorageType storage, object value) => BipHelpers.MakeBipParam(id, id.ToString(), storage, value); private static object? Value(Element e, int id) => e.Parameters.FirstOrDefault(p => p.Id == id)?.Value; + [Fact] + public void TypeVotesCountEachOwnerOnceAndKeepTheFirstReferenceOnATie() + { + var first = new Element { Id = 1, CategoryId = -2000011, References = [1002, 1002, 1001] }; + var tie = new Element { Id = 2, CategoryId = -2000011, References = [1003, 1001] }; + var wall = new Element { Id = 3, CategoryId = -2000011, References = [1003] }; + var other = new Element { Id = 4, CategoryId = -2000023, References = [1002, 1001] }; + var info = new RevitFileInfo { Elements = [other, first, tie, wall] }; + + ElementBuilder.ResolveTypeParams(info, info.Elements.ToDictionary(element => element.Id)); + + Assert.Equal(1001, Value(first, -1002050)); + Assert.Equal(1003, Value(tie, -1002050)); + Assert.Null(Value(other, -1002050)); + } + + [Fact] + public void TypeElementIdParametersKeepReferenceOrderAndEachInstancesStoredValues() + { + var stored = new Element { Id = 10, TypeId = 20, Parameters = [P(501, StorageType.ElementId, 3000)] }; + var empty = new Element { Id = 11, TypeId = 20 }; + var type = new Element { Id = 20, References = [502, 501, 502, 503] }; + var first = new Element { Id = 501, TypeId = 2000, Name = "First" }; + var second = new Element { Id = 502, TypeId = 2000, Name = "Second" }; + var foreign = new Element { Id = 503, TypeId = 2000, Name = "Unverified definition" }; + var info = new RevitFileInfo { Elements = [stored, empty, type, first, second, foreign, new Element { Id = 2000 }] }; + var state = new ParsingState(); + state.OwnedElementClassRoots[501] = new(1, 2870); + state.OwnedElementClassRoots[502] = new(1, 2870); + state.OwnedElementClassRoots[503] = new(2, 2870); + + ElementBuilder.PropagateTypeElementIdParams(info, state, info.Elements.ToDictionary(element => element.Id)); + + Assert.Equal([501, 502], stored.Parameters.Select(parameter => parameter.Id)); + Assert.Equal([502, 501], empty.Parameters.Select(parameter => parameter.Id)); + Assert.Equal(3000, Value(stored, 501)); + Assert.Equal(2000, Value(empty, 501)); + Assert.NotSame(stored.Parameters[1], empty.Parameters[0]); + Assert.NotSame(stored.Parameters[1].Definition, empty.Parameters[0].Definition); + } + private static Element Level(int id, double elevation, string name = "L", double computationHeight = 0) { var level = new Element { Id = id, IsNativeLevel = true }; diff --git a/tests/RvtIO.Tests/ElemTableAuthorityTests.cs b/tests/RvtIO.Tests/ElemTableAuthorityTests.cs index a6616d7d..c61fdb7e 100644 --- a/tests/RvtIO.Tests/ElemTableAuthorityTests.cs +++ b/tests/RvtIO.Tests/ElemTableAuthorityTests.cs @@ -64,6 +64,28 @@ public void NonrepresentableIdsAndNegativePartitionSentinelsDoNotBecomePublicEle Assert.Empty(ElemTableReader.LastWorksets); } + [Fact] + public void PostProcessAddsEachMissingElementOnceInTableThenWorksetOrder() + { + var existing = new Element + { + Id = 10, + Parameters = [BipHelpers.MakeBipParam(-1012100, "PHASE_CREATED", StorageType.ElementId, 75)], + }; + var info = new RevitFileInfo { Elements = [existing] }; + var state = new ParsingState + { + ElemTable = new() { [10] = 0, [30] = 0, [20] = 0, [0] = 0 }, + ElemWorksets = new() { [20] = 1, [40] = 1, [30] = 1, [0x0F000000] = 1 }, + }; + + ElementBuilder.PostProcess(info, state); + + Assert.Equal([10, 30, 20, 40], info.Elements.Select(element => element.Id)); + Assert.All(info.Elements.Skip(1), element => + Assert.Equal(75, Assert.Single(element.Parameters, parameter => parameter.Id == -1012100).Value)); + } + [SkippableFact] public void ProductionReadUsesTheExactR22CensusAndNotHistoryAsType() { @@ -98,6 +120,36 @@ public void BuilderNeverPublishesTheLegacyHistoryValueAsAType(uint history) Assert.Equal(-1, Assert.Single(info.Elements).TypeId); } + [Fact] + public void BuilderKeepsParameterPrecedenceWhenReusingTheIdSet() + { + var state = new ParsingState(); + state.Records[100] = new ElementRecord + { + ElemId = 100, + References = [200], + BipParams = [new(501, null, 4, 10), new(501, null, 4, 20)], + }; + state.ElemParamStrings[100] = new() { [501] = "stored", [502] = "first" }; + state.ElemBipDoubles[100] = new() { [502] = 7, [-1001000] = 1 }; + state.ElemBipDoubles[200] = new() { [502] = 8, [-1001000] = 2, [-1004005] = 3 }; + state.ElemBaseFields[100] = new() { AssocLevelId = 40 }; + state.ElemBipInts[101] = new() { [502] = 9 }; + var info = new RevitFileInfo(); + var scratch = new HashSet(); + + ElementBuilder.BuildElemTableElement(100, 0, state, info, scratch); + ElementBuilder.BuildElemTableElement(101, 0, state, info, scratch); + + var first = info.Elements[0].Parameters; + Assert.Equal([501, 502, -1001000, -1004005, -1001952], first.Take(5).Select(p => p.Id)); + Assert.Equal("stored", Assert.Single(first, p => p.Id == 501).Value); + Assert.Equal("first", Assert.Single(first, p => p.Id == 502).Value); + Assert.Equal(1.0, Assert.Single(first, p => p.Id == -1001000).Value); + Assert.Equal(3.0, Assert.Single(first, p => p.Id == -1004005).Value); + Assert.Equal(9, Assert.Single(info.Elements[1].Parameters, p => p.Id == 502).Value); + } + [Theory] [InlineData((ushort)2870, 1, true)] [InlineData((ushort)2873, 1, true)] [InlineData((ushort)2876, 1, true)] [InlineData((ushort)512, 1, false)] diff --git a/tests/RvtIO.Tests/ElementBuilderGeometryTests.cs b/tests/RvtIO.Tests/ElementBuilderGeometryTests.cs index 1e772eec..7446ad7d 100644 --- a/tests/RvtIO.Tests/ElementBuilderGeometryTests.cs +++ b/tests/RvtIO.Tests/ElementBuilderGeometryTests.cs @@ -67,6 +67,22 @@ public void DeduplicateExactFaces_PreservesOneBitCoordinateDifference() Assert.Equal(2, geometry.Faces.Count); } + [Fact] + public void DeduplicateExactFaces_MatchesReorderedHolesAndKeepsTheirMultiplicity() + { + List outline = [[0, 0, 0], [4, 0, 0], [4, 4, 0], [0, 4, 0]]; + List first = [[1, 1, 0], [2, 1, 0], [1, 2, 0]]; + List second = [[2, 2, 0], [3, 2, 0], [2, 3, 0]]; + var a = new GeoFace { OuterVertices = outline, InnerVertices = [first, second] }; + var b = new GeoFace { OuterVertices = outline, InnerVertices = [second, [first[2], first[0], first[1]]] }; + var c = new GeoFace { OuterVertices = outline, InnerVertices = [first, first] }; + var geometry = new GeometryData { Faces = [a, b, c] }; + + ElementBuilder.DeduplicateExactFaces(geometry); + + Assert.Equal([a, c], geometry.Faces); + } + [Fact] public void AddCurveLengths_LocationCurvePath_IsNotApproximate() { @@ -142,4 +158,112 @@ public void ClipGeometryToBounds_UsesExactSerializedPlane() Assert.Contains(clipped.Faces.SelectMany(face => face.OuterVertices!), point => BitConverter.DoubleToInt64Bits(point[2]) == BitConverter.DoubleToInt64Bits(1.25)); } + + [Fact] + public void ClipGeometryToBounds_CopiesAndDeduplicatesAnUncutFace() + { + double[] a = [0, 0, 0], b = [1, 0, 0], c = [1, 1, 1]; + var source = new GeometryData { Faces = [new GeoFace { OuterVertices = [a, a, b, c, a] }] }; + + var clipped = ElementBuilder.ClipGeometryToBounds(source, [0, 0, 0, 1, 1, 1], out bool changed); + + Assert.False(changed); + Assert.NotNull(clipped); + var polygon = Assert.Single(clipped.Faces).OuterVertices!; + Assert.Equal([a, b, c], polygon); + Assert.NotSame(a, polygon[0]); + Assert.Equal(5, source.Faces[0].OuterVertices!.Count); + } + + [Fact] + public void ExactFaceDeduplicationKeepsBitwiseDistinctCornersAndTheFirstEquivalentFace() + { + double[] a = [0, 0, 0], b = [1, 0, 0], c = [0, 1, 0]; + var first = new GeoFace { OuterVertices = [a, b, c], InnerVertices = [[a], [b, c]] }; + var equivalent = new GeoFace { OuterVertices = [b, a, c], InnerVertices = [[c, b], [a]] }; + var distinct = new GeoFace { OuterVertices = [[-0.0, 0, 0], b, c], InnerVertices = [[a], [b, c]] }; + var noHoles = new GeoFace { OuterVertices = [a, b, c] }; + var emptyHole = new GeoFace { OuterVertices = [c, a, b], InnerVertices = [[]] }; + var data = new GeometryData { Faces = [first, equivalent, distinct, noHoles, emptyHole] }; + + ElementBuilder.DeduplicateExactFaces(data); + + Assert.Collection(data.Faces, face => Assert.Same(first, face), + face => Assert.Same(distinct, face), face => Assert.Same(noHoles, face)); + } + + [Fact] + public void PlacedSymbol_ReusesLocalFacesAcrossClippedAndUnclippedInstances() + { + double[] identity = [1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0]; + var symbol = TriangleAt(0); + var cache = new Dictionary(ReferenceEqualityComparer.Instance); + var state = new ParsingState { SymbolPlacementGeometry = cache }; + state.GrepBlocks[1] = symbol; + state.GrepBlocks[2] = new GRepData + { + BoundingBox = [0.5, 0, 0, 1, 1, 1], + Instances = [new GRepInstance { SymbolElemId = 1, Transform = identity }], + }; + + var info = new RevitFileInfo(); + ElementBuilder.BuildBlockOnlyElement(2, state, info); + var clipped = Assert.IsType(Assert.Single(info.Elements).Geometry); + var clippedFace = Assert.Single(clipped.Faces); + Assert.True(clipped.PlacedSymbolClipped); + Assert.All(clippedFace.OuterVertices!, point => Assert.InRange(point[0], 0.5, 1)); + Assert.Equal(clippedFace.OuterVertices![0], clippedFace.Origin); + Assert.NotSame(clippedFace.OuterVertices[0], clippedFace.Origin); + Assert.Null(clippedFace.QuadratureArea); + + var localGeometry = Assert.IsType(cache[symbol]); + clippedFace.OuterVertices[0][0] = 100; + var translated = (double[])identity.Clone(); + translated[9] = 10; + var placed = Assert.IsType(ElementBuilder.BuildPlacedSymbolGeometry(1, translated, state, [])); + var placedFace = Assert.Single(placed.Faces); + + Assert.Same(localGeometry, Assert.Single(cache).Value); + Assert.Equal(0, Assert.Single(localGeometry.Faces).OuterVertices![0][0]); + Assert.Equal([10, 0, 0, 11, 1, 0], placed.BoundingBox!); + Assert.Equal(7.0, placedFace.QuadratureArea); + Assert.Equal(42, placedFace.NestedRenderStyleId); + Assert.NotSame(placedFace.OuterVertices![0], placedFace.Origin); + } + + [Fact] + public void PlacedSymbol_CachesEachSelectedDetailRepresentation() + { + double[] identity = [1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0]; + var fine = TriangleAt(0); + fine.Coarse = TriangleAt(10); + fine.Medium = TriangleAt(20); + fine.CoarseQuantities = TriangleAt(30); + var cache = new Dictionary(ReferenceEqualityComparer.Instance); + var state = new ParsingState { SymbolPlacementGeometry = cache }; + state.GrepBlocks[1] = fine; + + double Place(ElementBuilder.GeometryDetail detail = ElementBuilder.GeometryDetail.Fine) => + ElementBuilder.BuildPlacedSymbolGeometry(1, identity, state, [], detail: detail)!.Faces[0].OuterVertices![0][0]; + + Parallel.Invoke( + () => Assert.Equal(0, Place()), + () => Assert.Equal(20, Place(ElementBuilder.GeometryDetail.Medium)), + () => Assert.Equal(10, Place(ElementBuilder.GeometryDetail.Coarse)), + () => Assert.Equal(30, Place(ElementBuilder.GeometryDetail.CoarseQuantities))); + Assert.Equal(0, Place()); + Assert.Equal(4, cache.Count); + } + + private static GRepData TriangleAt(double x) => new() + { + Faces = [new GRepFace + { + Vertices = [[x, 0, 0], [x + 1, 0, 0], [x, 1, 0]], + Origin = [x, 0, 0], + XVector = [0, 0, 1], + QuadratureArea = 7, + RenderStyleId = 42, + }], + }; } diff --git a/tests/RvtIO.Tests/GElementGeometryGraphTests.cs b/tests/RvtIO.Tests/GElementGeometryGraphTests.cs index 89a1b343..99af39d0 100644 --- a/tests/RvtIO.Tests/GElementGeometryGraphTests.cs +++ b/tests/RvtIO.Tests/GElementGeometryGraphTests.cs @@ -144,6 +144,8 @@ public void InvalidFrameAndLaterKindAreNotSkipped(string mutation) case "surface-kind": BitConverter.GetBytes((ushort)1736).CopyTo(bytes,offsets["surface-pointer"]+4); break; } Assert.Null(Read(bytes,out var failure)); Assert.NotNull(failure); + if (mutation == "unknown-kind") Assert.Equal($"field:1589:m_pSurf:{offsets["surface-pointer"]}", failure); + if (mutation == "unsupported-kind") Assert.Equal("fifo:5:523", failure); } [Theory] diff --git a/tests/RvtIO.Tests/GElementLoopTopologyTests.cs b/tests/RvtIO.Tests/GElementLoopTopologyTests.cs index ac22bc55..34c1b28b 100644 --- a/tests/RvtIO.Tests/GElementLoopTopologyTests.cs +++ b/tests/RvtIO.Tests/GElementLoopTopologyTests.cs @@ -114,6 +114,8 @@ public void RepeatedEdgesReachNativeIncrementLimitWithoutDeduplication() var loop = Read(Replace(Graph(), 2, Weak(1244, "m_next", 5, 0))).Faces[0].Loops[0]; Assert.Equal(100001, loop.Edges.Count); Assert.All(loop.Edges, e => Assert.Equal(2, e.EdgeQueueIndex)); Assert.Equal("increment-limit", loop.EndOutcome); Assert.Equal("advanced", loop.Edges[99999].Outcome); + Assert.Same(loop.Edges[0].FirstAndLastPoints, loop.Edges[^1].FirstAndLastPoints); + Assert.Same(loop.Edges[0].InteriorPoints, loop.Edges[^1].InteriorPoints); } [Fact] @@ -171,6 +173,20 @@ private static OwnGElementFreshLoopTopology Read(OwnGElementGeometryGraph graph) var value = SelectOwnGElementLoopTopology(graph, out var failure); Assert.Null(failure); return Assert.IsType(value); } + + [Fact] + public void ReusesReadOnlyTopologyForEachGraphInstance() + { + var graph = Graph(); + var topology = Read(graph); + Assert.Same(topology, Read(graph)); + var invalid = graph with { OwnerId = 0 }; + Assert.Null(SelectOwnGElementLoopTopology(invalid, out var firstFailure)); + Assert.Equal("archive-reference-graph", firstFailure); + Assert.Null(SelectOwnGElementLoopTopology(invalid, out var repeatedFailure)); + Assert.Equal(firstFailure, repeatedFailure); + Assert.Same(topology, Read(graph)); + } private static OwnGElementGeometryGraph Graph() => new(1000, 0, [Node(-1, 2007, 1000), Node(0, 1589, 3, Owned(1590, "m_pFirstLoop", (1, (ushort)1254, 4u))), Node(1, 1254, 4, Owned(1255, "m_nextLoop", (4, (ushort)1257, 7u)), Weak(1255, "m_pFace", 3), diff --git a/tests/RvtIO.Tests/GRepParserV2Tests.cs b/tests/RvtIO.Tests/GRepParserV2Tests.cs index f6675564..c567d125 100644 --- a/tests/RvtIO.Tests/GRepParserV2Tests.cs +++ b/tests/RvtIO.Tests/GRepParserV2Tests.cs @@ -1,3 +1,4 @@ +using System.Reflection; using RvtIO.Parsing; using RvtIO.Internal; using Xunit; @@ -6,6 +7,59 @@ namespace RvtIO.Tests; public class GRepParserV2Tests { + [Theory] + [InlineData(true)] + [InlineData(false)] + public void ResyncRestoresTrialStateBeforeReturningAnAnchor(bool completeTrial) + { + // One Face with a surface pointer, followed by five GNodes with only GInfo. + const int anchor = 1; + byte[] data = new byte[anchor + 50 + 5 * 16 - (completeTrial ? 0 : 8)]; + BitConverter.GetBytes(5).CopyTo(data, anchor); + BitConverter.GetBytes(-1).CopyTo(data, anchor + 8); + BitConverter.GetBytes(0x80004).CopyTo(data, anchor + 12); + BitConverter.GetBytes(17).CopyTo(data, anchor + 44); + BitConverter.GetBytes((ushort)522).CopyTo(data, anchor + 48); + + var parser = typeof(GRepParserV2); + var cursorType = parser.GetNestedType("Cur", BindingFlags.NonPublic)!; + var cursor = Activator.CreateInstance(cursorType, nonPublic: true)!; + void Set(string name, object value) => cursorType.GetField(name)!.SetValue(cursor, value); + T Get(string name) => (T)cursorType.GetField(name)!.GetValue(cursor)!; + + Set("D", data); + Set("End", data.Length); + Set("BlockEnd", data.Length); + Set("Debug", true); + List<(ushort Cls, int V)> queue = [(1589, 41), (1246, 42), (1246, 43), (1246, 44), (1246, 45), (1246, 46)]; + List<(int ParentQueueIndex, string Field)> links = + [(-1, "root"), (0, "existing"), (-1, "root"), (-1, "root"), (-1, "root"), (-1, "root")]; + Set("Queue", queue); + Set("QueueLinks", links); + Get>>("QueueChildren").Add(0, [1]); + Get>("ClassWalked").Add(1589, 3); + Get>("TagBase").Add(1589, 99); + Get>("SurfaceOwnerByHandle").Add(17, 99); + Get>("FaceHasFirstLoop").Add(41, true); + + object?[] arguments = [cursor, 0]; + var resync = parser.GetMethod("TryResync", BindingFlags.Static | BindingFlags.NonPublic)!; + Assert.Equal(completeTrial, (bool)resync.Invoke(null, arguments)!); + + Assert.Equal(completeTrial ? anchor : 0, Get("Pos")); + Assert.Equal(completeTrial ? -1 : 0, (int)arguments[1]!); + Assert.Equal(6, queue.Count); + Assert.Equal(6, links.Count); + Assert.Equal([1], Get>>("QueueChildren")[0]); + Assert.Equal(new KeyValuePair(1589, 3), Assert.Single(Get>("ClassWalked"))); + Assert.Equal(new KeyValuePair(1589, 99), Assert.Single(Get>("TagBase"))); + Assert.Equal(new KeyValuePair(17, 99), Assert.Single(Get>("SurfaceOwnerByHandle"))); + Assert.Empty(Get>("SurfaceOwnerByQueueIndex")); + Assert.True(Get>("FaceHasFirstLoop")[41]); + Assert.Empty(Get>("FaceOrder")); + Assert.Equal(5, Get>("ObjectGInfo")[41].Tag); + } + [Fact] public void ThinSamples_KeepsShortListsAndThinsLongOnesKeepingTheEndsAndKnots() { @@ -704,6 +758,37 @@ public void SerializedFaceTopology_PreservesIndependentSolids() Assert.All(solids, solid => Assert.True(solid.IsClosed)); } + [Theory] + [InlineData(0u)] + [InlineData(99u)] + [InlineData(uint.MaxValue)] + public void SerializedFaceTopology_AnEdgeToAMissingOrInvalidFaceOpensOnlyItsOwnSolid(uint missing) + { + var faces = Enumerable.Range(0, 8).Select(_ => new GRepFace()).ToList(); + var solids = GRepParserV2.BuildTopologicalSolids(faces, + [1, 2, 3, 4, 11, 12, 13, 14], + [(1u, 2u), (2u, 3u), (3u, 4u), (4u, 1u), (missing, 4u), + (11u, 12u), (12u, 13u), (13u, 14u), (14u, 11u)]); + + Assert.Collection(solids, + open => { Assert.Equal([0, 1, 2, 3], open.FaceIndices); Assert.False(open.IsClosed); }, + closed => { Assert.Equal([4, 5, 6, 7], closed.FaceIndices); Assert.True(closed.IsClosed); }); + } + + [Fact] + public void SerializedFaceTopology_HandlesALongChainOfFaceUnions() + { + const int count = 8192; + uint[] handles = Enumerable.Range(1, count).Select(i => (uint)i).ToArray(); + GRepFace[] faces = Enumerable.Range(0, count).Select(_ => new GRepFace()).ToArray(); + var edges = handles.Zip(handles.Skip(1), (first, second) => (second, first)); + + var solid = Assert.Single(GRepParserV2.BuildTopologicalSolids(faces, handles, edges)); + + Assert.True(solid.IsClosed); + Assert.Equal(Enumerable.Range(0, count), solid.FaceIndices); + } + [Theory] [InlineData(0x00088204u, true)] [InlineData(0x00288204u, false)] diff --git a/tests/RvtIO.Tests/IfcExporterBaseQuantitiesCurrentTailTests.cs b/tests/RvtIO.Tests/IfcExporterBaseQuantitiesCurrentTailTests.cs index afa6eeb9..b0cd82ba 100644 --- a/tests/RvtIO.Tests/IfcExporterBaseQuantitiesCurrentTailTests.cs +++ b/tests/RvtIO.Tests/IfcExporterBaseQuantitiesCurrentTailTests.cs @@ -292,7 +292,6 @@ public void CoarseSurface_DoorWhoseBlockHasACoarseLevel_IsMeasuredOnThatLevel() ElementBuilder.ApplyCoarseDoorWindowSurfaces(info, state); Assert.Equal(2.0, door.CoarseSurfaceArea!.Value, 9); - Assert.False(state.CoarseView); } [Fact] diff --git a/tests/RvtIO.Tests/NativeFieldDomainTests.cs b/tests/RvtIO.Tests/NativeFieldDomainTests.cs index 1373a63a..24395592 100644 --- a/tests/RvtIO.Tests/NativeFieldDomainTests.cs +++ b/tests/RvtIO.Tests/NativeFieldDomainTests.cs @@ -13,6 +13,31 @@ public class NativeFieldDomainTests private static Dictionary Classes(params (uint Id, ushort Class)[] items) => items.ToDictionary(i => i.Id, i => i.Class); + [Fact] + public void NativeParameterIndexKeepsFirstMatchAndEachElementsStoreIds() + { + const int height = -1001300, namedOnly = -1001206; + var first = new Parameter { Id = height }; + var duplicate = P(height, StorageType.Double, 9.0); + var one = new Element { Id = 10, Parameters = [first, duplicate] }; + var two = new Element { Id = 11 }; + var state = new ParsingState(); + var nativeOne = state.NativeParams[10] = new TfBlockDeserializer.NativeParams(); + nativeOne.Doubles.Add((height, 4.5)); + nativeOne.NamedParams.Add(new(namedOnly, "2 h", 0, 0, 0, false, false)); + var nativeTwo = state.NativeParams[11] = new TfBlockDeserializer.NativeParams(); + nativeTwo.Doubles.Add((height, 8.0)); + + ElementBuilder.ApplyNativeParams(new RevitFileInfo { Elements = [one, two] }, state); + + Assert.Equal(4.5, first.Value); + Assert.Equal(9.0, duplicate.Value); + Assert.Equal(8.0, Value(two, height)); + Assert.Equal([height], one.NativeParameterStoreIds); + Assert.Equal([height, namedOnly], one.NativeStoredParameterIds); + Assert.Equal([height], two.NativeStoredParameterIds); + } + [Fact] public void ParameterCreatedByTheTable_IsRemovedOutsideItsDomains_AndKeptInsideThem() { diff --git a/tests/RvtIO.Tests/NativeFieldParametersTests.cs b/tests/RvtIO.Tests/NativeFieldParametersTests.cs index c5b6ad4c..2c8363de 100644 --- a/tests/RvtIO.Tests/NativeFieldParametersTests.cs +++ b/tests/RvtIO.Tests/NativeFieldParametersTests.cs @@ -22,6 +22,29 @@ public void Table_IsBuiltInOnlyKeyedByDeclaringClassAndUniquePerParameterAndFiel Assert.NotEmpty(NativeFieldParameters.All); } + [Fact] + public void PresentRowsUseCapturedStorageAndKeepTableOrder() + { + var native = new TfBlockDeserializer.NativeParams(); + native.Fields["2628:m_categoryId"] = 21; + native.Fields["1064:m_categoryId"] = 42; + native.DoubleFields["1064:m_categoryId"] = 0.5; + native.Fields["1492:m_unknown"] = 9; + var rows = new List(); + var values = new object?[NativeFieldParameters.All.Length]; + + NativeFieldParameters.CollectPresentRows(native, rows, values); + + Assert.Equal( + [(-1140363, "1064:m_categoryId"), (-1140363, "2628:m_categoryId"), + (-1140362, "1064:m_categoryId"), (-1140362, "2628:m_categoryId")], + rows.Select(index => (NativeFieldParameters.All[index].ParamId, NativeFieldParameters.All[index].Key))); + Assert.Equal([42, 21, 42, 21], rows.Select(row => Assert.IsType(values[row]))); + Assert.Same(values[rows[0]], values[rows[2]]); + NativeFieldParameters.CollectPresentRows(new(), rows, values); + Assert.Empty(rows); + } + [Theory] [InlineData(-1001381, "1794:m_structUsage")] // Structural Usage [InlineData(-1001552, "308:m_enableAnalyticalModel")] // Enable Analytical Model diff --git a/tests/RvtIO.Tests/NonVisibleQuantityGeometryTests.cs b/tests/RvtIO.Tests/NonVisibleQuantityGeometryTests.cs index 69a4874c..582388bd 100644 --- a/tests/RvtIO.Tests/NonVisibleQuantityGeometryTests.cs +++ b/tests/RvtIO.Tests/NonVisibleQuantityGeometryTests.cs @@ -77,8 +77,6 @@ public void DoorArea_UsesQuantityViewForOwnOrNestedBodiesAndKeepsVisibleGeometry Assert.Equal(3, door.CoarseSurfaceArea!.Value, 12); Assert.Same(body, door.Geometry); Assert.Single(door.Geometry!.Faces); - Assert.False(state.CoarseView); - Assert.False(state.IncludeNonVisibleQuantities); } [Fact] diff --git a/tests/RvtIO.Tests/ParameterValueFormattingTests.cs b/tests/RvtIO.Tests/ParameterValueFormattingTests.cs index 970c138d..ea331983 100644 --- a/tests/RvtIO.Tests/ParameterValueFormattingTests.cs +++ b/tests/RvtIO.Tests/ParameterValueFormattingTests.cs @@ -1,10 +1,107 @@ using RvtIO.Model; +using RvtIO.Parsing; using Xunit; namespace RvtIO.Tests; public class ParameterValueFormattingTests { + [Fact] + public void ParsedNumericValuesShareExactBoxesAndPreserveTheirTypes() + { + var first = BipHelpers.MakeBipParam(-1002108, "HOST_ID_PARAM", StorageType.ElementId, -1, hasNoRevitValue: true); + var second = BipHelpers.MakeBipParam(-1002108, "HOST_ID_PARAM", StorageType.ElementId, -1, hasNoRevitValue: true); + Assert.Same(first.Value, second.Value); + Assert.IsType(first.Value); + Assert.True(first.HasNoRevitValue); + Assert.Same(Parameter.BoxParsedValue(0.0), Parameter.BoxParsedValue(0.0)); + Assert.IsType(Parameter.BoxParsedValue((short)1)); + Assert.Equal(long.MinValue, BitConverter.DoubleToInt64Bits( + Assert.IsType(Parameter.BoxParsedValue(BitConverter.Int64BitsToDouble(long.MinValue))))); + + object callerValue = -1; + first.Value = callerValue; + Assert.Same(callerValue, first.Value); + Assert.False(first.HasNoRevitValue); + Assert.True(second.HasNoRevitValue); + Assert.Equal(-1, Assert.IsType(second.Value)); + } + + [Fact] + public void OptionalGuidCanBeUpdatedOrClearedIndependentlyOnAShallowCopy() + { + var first = new Parameter(); + Assert.Null(first.Guid); + first.Guid = Guid.Parse("01234567-89ab-cdef-0123-456789abcdef"); + var copy = first.ShallowCopy(7.0); + Assert.Equal(first.Guid, copy.Guid); + + copy.Guid = Guid.Empty; + Assert.Equal(Guid.Empty, copy.Guid); + Assert.NotEqual(first.Guid, copy.Guid); + copy.Guid = null; + Assert.Null(copy.Guid); + Assert.NotNull(first.Guid); + } + + [Fact] + public void SharedDisplayUnitsCanBeEditedOnEachParameterIndependently() + { + var units = new Parameter.DisplayUnits("length", "mm", 304.8); + var original = new Parameter(); + original.SetDisplayUnits(units); + var clone = original.ShallowCopy(7.0); + + clone.UnitSymbol = "cm"; + clone.ConversionFactor = 30.48; + original.SpecType = null; + + Assert.Equal("length", clone.SpecType); + Assert.Equal("cm", clone.UnitSymbol); + Assert.Equal(30.48, clone.ConversionFactor); + Assert.Null(original.SpecType); + Assert.Equal("mm", original.UnitSymbol); + Assert.Equal(304.8, original.ConversionFactor); + } + + [Fact] + public void BuiltInDefinitionsStayIndependentAndShallowCopiesShareTheDefinition() + { + const int id = -1004005; + const string name = "CURVE_ELEM_LENGTH"; + var first = BipHelpers.MakeBipParam(id, name, StorageType.Double, 3.0); + var second = BipHelpers.MakeBipParam(id, name, StorageType.Double, 5.0); + first.Id = -1; + Assert.Equal(id, first.DefinitionId); + var clone = first.ShallowCopy(7.0); + Assert.Same(first.Definition, clone.Definition); + Assert.NotSame(first.Definition, second.Definition); + first.Definition.Name = "Edited"; + Assert.Equal("Edited", clone.DefinitionName); + Assert.Equal(name, second.DefinitionName); + Assert.Equal(name, first.DefinitionBuiltIn); + } + + [Fact] + public void UserDefinitionDataPreservesIndependentParameterEdits() + { + var guid = Guid.Parse("01234567-89ab-cdef-0123-456789abcdef"); + var definition = new Parameter.DefinitionData(123, "Width", guid: guid); + object value = 3.0; + var first = new Parameter(definition) { Value = value }; + var second = new Parameter(definition) { Value = value }; + + first.Definition.Name = "Edited"; + first.Guid = null; + first.Value = 5.0; + + Assert.Equal("Width", second.Definition.Name); + Assert.Equal(123, second.Definition.Id); + Assert.Null(second.Definition.BuiltInParameter); + Assert.Equal(guid, second.Guid); + Assert.Equal(3.0, second.AsDouble()); + } + [Fact] public void Parameter_AsValueString_CaseInsensitiveAndBipFallback() { diff --git a/tests/RvtIO.Tests/PartitionCutTests.cs b/tests/RvtIO.Tests/PartitionCutTests.cs index 6154e47a..75b546d0 100644 --- a/tests/RvtIO.Tests/PartitionCutTests.cs +++ b/tests/RvtIO.Tests/PartitionCutTests.cs @@ -132,4 +132,38 @@ private static void Segment(BinaryWriter w, uint channel, uint flags, byte[] rec w.Write(Id("SegmentCheckback")); w.Write(size); } + + [Theory] + [InlineData(0, "gzip-crc-length-or-extent")] + [InlineData(-1, "gzip-length")] + [InlineData(1, "gzip-crc-length-or-extent")] + public void PrefetchReportsCorruptMembersAtTheSamePointAsTheSerialWalk(int sizeDelta, string expectedFailure) + { + byte[] raw = TwoBlocks(); + ReadOnlySpan marker = [0x1f, 0x8b, 8, 0, 0, 0, 0, 0, 0, 0x0b]; + int first = raw.AsSpan().IndexOf(marker); + int second = first + marker.Length + raw.AsSpan(first + marker.Length).IndexOf(marker); + int payloadBytes = (int)BitConverter.ToUInt32(raw, second - 16) - 8; + int trailer = second + payloadBytes - 8; + if (sizeDelta == 0) raw[trailer] ^= 1; + else + { + var size = raw.AsSpan(trailer + 4, 4); + uint length = System.Buffers.Binary.BinaryPrimitives.ReadUInt32LittleEndian(size); + System.Buffers.Binary.BinaryPrimitives.WriteUInt32LittleEndian(size, (uint)(length + sizeDelta)); + } + var (tags, idWidth) = Framing; + var serial = new List<(int Channel, ulong Owner, long Offset)>(); + var parallel = new List<(int Channel, ulong Owner, long Offset)>(); + + Assert.False(PartitionFraming.Walk(raw, tags, idWidth, + record => serial.Add((record.Channel, record.Owner, record.Offset)), out var serialFailure, out _)); + Assert.False(PartitionFraming.Walk(raw, tags, idWidth, + record => parallel.Add((record.Channel, record.Owner, record.Offset)), out var parallelFailure, out _, segmentBytes: [])); + + Assert.Equal(expectedFailure, serialFailure); + Assert.Equal(serialFailure, parallelFailure); + Assert.NotEmpty(serial); + Assert.Equal(serial, parallel); + } } diff --git a/tests/RvtIO.Tests/ReaderScanTests.cs b/tests/RvtIO.Tests/ReaderScanTests.cs new file mode 100644 index 00000000..ae6d4025 --- /dev/null +++ b/tests/RvtIO.Tests/ReaderScanTests.cs @@ -0,0 +1,283 @@ +using System.Buffers.Binary; +using System.Runtime.InteropServices; +using RvtIO.Internal; +using RvtIO.Parsing; +using Xunit; + +namespace RvtIO.Tests; + +public class ReaderScanTests +{ + [Fact] + public void NameTableKeepsBothMarkersAndTheFirstNameForEachElement() + { + byte[] chunk = new byte[388]; + WriteEntry(12, 301, 201, "Longer name", masked: false); + WriteEntry(123, 302, 202, "Short", masked: true); + WriteEntry(239, 303, 201, "Later name", masked: true); + var state = new ParsingState(); + + NameTableScanner.Scan(chunk, state); + + Assert.Equal(2, state.ElementNameTable.Count); + Assert.Equal("Longer name", state.ElementNameTable[201]); + Assert.Equal("Short", state.ElementNameTable[202]); + Assert.Equal(201u, state.NameHolderTarget[303]); + + void WriteEntry(int start, uint holder, uint element, string name, bool masked) + { + chunk[start] = 1; + BinaryPrimitives.WriteUInt32LittleEndian(chunk.AsSpan(start + 4), holder); + chunk.AsSpan(start + 8, 28).Fill(0xFF); + int marker = start + 38; + BinaryPrimitives.WriteUInt32LittleEndian(chunk.AsSpan(marker), masked ? 0xFFFFFF04u : 1u); + BinaryPrimitives.WriteUInt32LittleEndian(chunk.AsSpan(marker + 4), element); + uint length = (uint)name.Length; + BinaryPrimitives.WriteUInt32LittleEndian(chunk.AsSpan(marker + 8), masked ? 0xFFFFFF00u | length : length); + for (int index = 0; index < name.Length; index++) + { + chunk[marker + 12 + 2 * index] = (byte)name[index]; + chunk[marker + 13 + 2 * index] = masked ? (byte)0xFF : (byte)0; + } + BinaryPrimitives.WriteInt32LittleEndian(chunk.AsSpan(marker + 12 + 2 * name.Length), -2000011); + } + } + + [Fact] + public void KeyedStringsKeepUnalignedBoundaryIdsAndTheLastPossibleEntry() + { + byte[] chunk = new byte[16 + 31]; + BinaryPrimitives.WriteUInt32LittleEndian(chunk, 42); + BinaryPrimitives.WriteUInt32LittleEndian(chunk.AsSpan(8), 31); + WriteString(17, -1_200_000, 'A'); + WriteString(27, -1_200_001, 'B'); + WriteString(37, -1_000_000, 'C'); + var state = new ParsingState(); + + BlockParser.CollectBipStrings(chunk, state); + + Assert.Equal(new[] { (-1_200_000, "A"), (-1_000_000, "C") }, + state.BipKeyedStrings[42].Select(pair => (pair.Key, pair.Value))); + + void WriteString(int offset, int id, char value) + { + BinaryPrimitives.WriteInt32LittleEndian(chunk.AsSpan(offset), id); + BinaryPrimitives.WriteUInt32LittleEndian(chunk.AsSpan(offset + 4), 1); + BinaryPrimitives.WriteUInt16LittleEndian(chunk.AsSpan(offset + 8), value); + } + } + + [Fact] + public void BlockStringsKeepTheFirstTwentyDistinctTrimmedValues() + { + byte[] chunk = new byte[28 * 12]; + for (int index = 0; index < 28; index++) + { + int offset = index * 12; + string value = $" {Math.Max(0, index - 1):D3}"; + BinaryPrimitives.WriteUInt32LittleEndian(chunk.AsSpan(offset), (uint)value.Length); + System.Text.Encoding.Unicode.GetBytes(value, chunk.AsSpan(offset + 4, 8)); + } + var strings = new Dictionary>(); + BlockParser.ExtractBlockStrings(chunk, 0, chunk.Length, 42, strings); + BlockParser.ExtractBlockStrings(chunk, 26 * 12, chunk.Length, 42, strings); + + Assert.Equal(Enumerable.Range(0, 20).Select(value => value.ToString("D3")), strings[42]); + } + + [Theory] + [InlineData(31, 2, 0)] + [InlineData(7, 500, 40)] + public void BlockStringsReadUnalignedLengthsAtBothEndsOfTheScan(int offset, int length, int trailingBytes) + { + byte[] data = new byte[offset + 4 + 2 * length + trailingBytes]; + Array.Fill(data, byte.MaxValue); + BinaryPrimitives.WriteUInt32LittleEndian(data.AsSpan(offset), (uint)length); + string value = new('Д', length); + System.Text.Encoding.Unicode.GetBytes(value, data.AsSpan(offset + 4)); + var strings = new Dictionary>(); + + BlockParser.ExtractBlockStrings(data, 0, data.Length, 42, strings); + + Assert.Equal(value, Assert.Single(strings[42])); + } + + [Fact] + public void NearbyNameWindowsKeepExactBoundariesAndStringOrder() + { + byte[] chunk = new byte[2_400]; + WriteName(650, "First name"); + WriteName(690, "Second name"); + WriteName(2_000, "Distant name"); + WriteId(50, 70_000); // outside the first window + WriteId(55, 70_001); + WriteId(745, 70_002); + WriteId(751, 70_003); + WriteId(1_403, 70_002); // the same owner is encountered again in a disjoint window + var strings = new Dictionary>(); + + StringScanner.ScanChunk(chunk, [70_000, 70_001, 70_002, 70_003], strings); + + Assert.False(strings.ContainsKey(70_000)); + Assert.Equal(["First name"], strings[70_001]); + Assert.Equal(["First name", "Second name", "Distant name"], strings[70_002]); + Assert.Equal(["Second name"], strings[70_003]); + + void WriteId(int offset, uint id) => BinaryPrimitives.WriteUInt32LittleEndian(chunk.AsSpan(offset), id); + + void WriteName(int offset, string value) + { + WriteId(offset, (uint)value.Length); + System.Text.Encoding.Unicode.GetBytes(value, chunk.AsSpan(offset + 4)); + } + } + + [Theory] + [InlineData("Ширина", true)] + [InlineData("abc123def", true)] + [InlineData("abcd123def", false)] + [InlineData("12. Дверь 1", false)] + [InlineData("folder\\name", false)] + [InlineData("(X,Y)", false)] + public void ParameterNamesKeepTheOriginalFilters(string name, bool expected) + => Assert.Equal(expected, StringScanner.IsValidParamName(name)); + + [Fact] + public void ParameterNamesUseTheCurrentCultureForTheMetadataPrefix() + { + const string name = "\u00adautodesk.spec"; + Assert.Equal(!name.StartsWith("autodesk.", StringComparison.CurrentCulture), StringScanner.IsValidParamName(name)); + } + + [Theory] + [InlineData(0x053C)] + [InlineData(0x04F8)] + public void R22ScanFindsTheLastPossibleUnalignedRecord(ushort marker) + { + byte[] chunk = new byte[19]; + BinaryPrimitives.WriteUInt32LittleEndian(chunk.AsSpan(6), 42); + BinaryPrimitives.WriteUInt32LittleEndian(chunk.AsSpan(10), 1); + BinaryPrimitives.WriteUInt16LittleEndian(chunk.AsSpan(14), marker); + + Assert.True(RecordParser.ContainsAnchoredR22Record(chunk, new HashSet { 42 })); + Assert.False(RecordParser.ContainsAnchoredR22Record(chunk, new HashSet())); + Assert.False(RecordParser.ContainsAnchoredR22Record(chunk[..^1], new HashSet { 42 })); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void RecordBodiesShareTheChunkAndExcludeHeadersAndFooters(bool r25) + { + const int start = 1; + int headerSize = r25 ? 16 : 12; + int footerSize = r25 ? 4 : 0; + // "AB" fits inside the first body. "CD" would require bytes past its end. + byte[] first = new byte['D']; + byte[] prefix = [0xEF, 0x01, 2, 0, 0, 0, (byte)'A', 0, (byte)'B', 0]; + prefix.CopyTo(first, 0); + first[^6] = 2; + first[^2] = (byte)'C'; + byte[] second = [0xEF, 0x01, 0, 0]; + int secondStart = start + headerSize + first.Length + footerSize; + var chunk = new byte[secondStart + headerSize + second.Length + footerSize]; + WriteRecord(start, 42, first); + WriteRecord(secondStart, 'D', second); + var state = new ParsingState(); + state.AllKnownIds.Add(42); + + if (r25) + RecordParser.ParseChunkR25(chunk, state); + else + RecordParser.ParseChunk(chunk, state); + + AssertBody(42, start + headerSize, first); + AssertBody('D', secondStart + headerSize, second); + // "D" starts the next header in R22 and the footer's size field in R25. + Assert.Equal(["AB"], state.ElemStrings[42]); + + void WriteRecord(int offset, uint id, byte[] body) + { + BinaryPrimitives.WriteUInt32LittleEndian(chunk.AsSpan(offset), id); + BinaryPrimitives.WriteInt32LittleEndian(chunk.AsSpan(offset + (r25 ? 12 : 4)), body.Length); + if (r25) + BinaryPrimitives.WriteInt32LittleEndian(chunk.AsSpan(offset + headerSize + body.Length), body.Length); + else + BinaryPrimitives.WriteUInt16LittleEndian(chunk.AsSpan(offset + 8), 0x053C); + body.CopyTo(chunk, offset + headerSize); + } + + void AssertBody(uint id, int offset, byte[] expected) + { + var body = state.Records[id].Body; + Assert.True(MemoryMarshal.TryGetArray(body, out var slice)); + Assert.Same(chunk, slice.Array); + Assert.Equal(offset, slice.Offset); + Assert.Equal(expected, body.ToArray()); + } + } + + [Fact] + public void HvacScanFindsAnUnalignedTableAtTheEndOfTheChunk() + { + const int start = 5; + var state = new ParsingState(); + var chunk = new byte[start + 0xCF]; + BinaryPrimitives.WriteUInt32LittleEndian(chunk.AsSpan(start + 0x24), 42); + BinaryPrimitives.WriteDoubleLittleEndian(chunk.AsSpan(start + 0x57), 251); + BinaryPrimitives.WriteDoubleLittleEndian(chunk.AsSpan(start + 0xAF), 329); + BinaryPrimitives.WriteUInt32LittleEndian(chunk.AsSpan(start + 0xC3), 1); + BinaryPrimitives.WriteUInt32LittleEndian(chunk.AsSpan(start + 0xC7), 2); + BinaryPrimitives.WriteUInt32LittleEndian(chunk.AsSpan(start + 0xCB), 3); + var ids = new HashSet { 42 }; + + BlockParser.CollectHvacTables(chunk[..^1], ids, state.HvacSpaceTypeParams, state.HvacScheduleRefs); + Assert.Empty(state.HvacSpaceTypeParams); + BlockParser.CollectHvacTables(chunk, ids, state.HvacSpaceTypeParams, state.HvacScheduleRefs); + + var parameters = Assert.Contains(42u, state.HvacSpaceTypeParams); + Assert.Equal(251, parameters[-1114709]); + Assert.Equal(329, parameters[-1114708]); + Assert.Equal((1, 2, 3), state.HvacScheduleRefs[42]); + } + + [Fact] + public void SharedTransformKeepsTheWinningAnglesFirstMatrixByAlignment() + { + const double angle = -0.5, laterAlignmentAngle = -0.5000001; + var chunk = new byte[9 * 80]; + for (int index = 0; index < 8; index++) + { + int start = index * 80 + (index == 0 ? 1 : 0); + var (s, c) = Math.SinCos(index == 0 ? laterAlignmentAngle : angle); + double[] matrix = [c, s, 0, -s, c, 0, 0, 0, 1]; + for (int entry = 0; entry < matrix.Length; entry++) + BinaryPrimitives.WriteDoubleLittleEndian(chunk.AsSpan(start + entry * sizeof(double)), matrix[entry]); + } + + var transform = RvtFileReader.FindSharedTransform([chunk], + new Dictionary(), new Dictionary(), null); + + Assert.NotNull(transform); + var (sin, cos) = Math.SinCos(angle); + Assert.Equal(cos, transform[0]); + Assert.Equal(sin, transform[1]); + } + + [Fact] + public void SecondBlockPassSkipsOnlyASoleIdenticalFirstGeometryCandidate() + { + byte[] chunk = new byte[80]; + var same = new BlockParser.PendingGRep(chunk, 1, 0, 16, false); + var later = same with { Start = 16 }; + var different = same with { Eid = 2 }; + var competing = same with { Eid = 3 }; + var another = competing with { Start = 32 }; + var familyCut = same with { Eid = 4, IsFamilyCut = true }; + List second = [same, later, different with { Start = 32 }, different, competing, familyCut]; + + BlockParser.SkipRepeatedFirstGReps([same, different, competing, another, familyCut], second); + + Assert.Equal([later, different with { Start = 32 }, different, competing, familyCut], second); + } +} diff --git a/tests/RvtIO.Tests/ScaledInstanceComponentTests.cs b/tests/RvtIO.Tests/ScaledInstanceComponentTests.cs index a5d1307a..46105866 100644 --- a/tests/RvtIO.Tests/ScaledInstanceComponentTests.cs +++ b/tests/RvtIO.Tests/ScaledInstanceComponentTests.cs @@ -236,4 +236,23 @@ public void OversizeComponentAtUnitScale_IsStillExpandedFace_ByFace() Assert.NotNull(placed); Assert.Equal(30, placed.Faces.Count); } + + [Fact] + public void PendingGeometryPreservesCollectionOrderAcrossBatches() + { + var block = SymbolBlock(); + uint size = BitConverter.ToUInt32(block, 8); + var rejected = new BlockParser.PendingGRep(new byte[16], 30, 0, 0, false); + var jobs = new List { new(block, 20, 0, size, false) }; + while (jobs.Count <= BlockParser.PendingGRepBatchSize) jobs.Add(rejected); + jobs.Add(new(block, 10, 0, size, false)); + var state = new ParsingState(); + var unreadable = new HashSet(); + + BlockParser.ApplyPendingGReps(state, jobs, unreadable); + + Assert.Equal(new uint[] { 20, 10 }, state.GrepBlocks.Keys.ToArray()); + Assert.All(state.GrepBlocks.Values, geometry => Assert.Single(geometry.Instances)); + Assert.Equal(new BlockParser.GRepRange(rejected.Chunk, 0, 0), Assert.Single(unreadable)); + } } diff --git a/tests/RvtIO.Tests/SourcePlanarFaceRegionTests.cs b/tests/RvtIO.Tests/SourcePlanarFaceRegionTests.cs index 356f8230..6fe54a67 100644 --- a/tests/RvtIO.Tests/SourcePlanarFaceRegionTests.cs +++ b/tests/RvtIO.Tests/SourcePlanarFaceRegionTests.cs @@ -42,6 +42,24 @@ public void OwnSentinelPartitionPreservesAnOuterAndItsHole() Assert.Equal(new double[] { 0, 0, 0 }, face.Vertices[0]); } + [Fact] + public void SingleOwnLoopAgreesWithBothEpsBranches() + { + var graph = F.Replace(Graph(), 1, F.Owned(1255, "m_nextLoop", null)); + var winding = SelectOwnGElementEpsIndependentSamples(graph, out var windingFailure); + Assert.Null(windingFailure); + Assert.True(Assert.Single(winding!.Loops).IndependentShouldBeCcw); + + var regions = GRepParserV2.SelectOwnPlanarFaceRegions(graph, out var failure); + + Assert.Null(failure); + var face = Assert.Single(regions![0]); + Assert.Null(face.InnerVertices); + Assert.Equal(4, face.Vertices!.Count); + Assert.Equal(face.Vertices, Assert.Single(face.SourceLoops!)); + Assert.NotSame(face.Vertices[0], face.SourceLoops![0][0]); + } + [Theory] [InlineData("missing-surface")] [InlineData("curved-surface")] [InlineData("open")] [InlineData("wrong-sentinel")] [InlineData("zero-world-area")] diff --git a/tests/RvtIO.Tests/SystemTypeIdentityTests.cs b/tests/RvtIO.Tests/SystemTypeIdentityTests.cs index b0b68839..3913bce5 100644 --- a/tests/RvtIO.Tests/SystemTypeIdentityTests.cs +++ b/tests/RvtIO.Tests/SystemTypeIdentityTests.cs @@ -18,6 +18,19 @@ public void CompleteOwnOccurrenceRoot_ProvidesItsTypeLink(int classId) Assert.Equal(500, TfBlockDeserializer.ExtractSystemOccurrenceTypeId(block, 0, Size(block), (ushort)classId)); } + [Fact] + public void CompleteOwnRootKeepsTypeLinkWhenDeferredParameterStoreIsTruncated() + { + const ushort classId = 3524; + byte[] block = Block(classId, "truncated_store"); + var parameters = TfBlockDeserializer.ExtractParams(block, 0, Size(block), classId); + + Assert.NotNull(parameters); + Assert.False(parameters.RootParameterStoresComplete); + Assert.Equal(parameters.Fields["m_WallAttributesId"], + TfBlockDeserializer.ExtractSystemOccurrenceTypeId(block, 0, Size(block), classId)); + } + [Theory] [InlineData("footer")] [InlineData("size")] [InlineData("class")] [InlineData("owner")] [InlineData("zero_owner")] [InlineData("zero_type")] @@ -275,6 +288,12 @@ private static byte[] Block(ushort cls, string? mutation = null) { if (field.Declaring == 37 && field.Name == "m_docAccess") { writer.Write(1u); continue; } if (field.Declaring == 37 && field.Name == "m_id") { writer.Write(100); continue; } + if (mutation == "truncated_store" && field is { Declaring: 37, Name: "m_pParamValueSetDouble" }) + { + writer.Write(uint.MaxValue); + writer.Write((ushort)0xB47); + continue; + } if (field.Name is "m_WallAttributesId" or "m_floorAttributesId" or "m_ceilingAttributesId") { if (mutation == "truncated") break; @@ -283,6 +302,7 @@ private static byte[] Block(ushort cls, string? mutation = null) } WriteDefault(field); } + if (mutation == "truncated_store") writer.Write(1u); writer.Write(0u); byte[] block = stream.ToArray(); uint size = (uint)block.Length - 16; BitConverter.GetBytes(size).CopyTo(block, 8); BitConverter.GetBytes(size).CopyTo(block, block.Length - 4); diff --git a/tests/RvtIO.Tests/TfBlockDeserializerGridTests.cs b/tests/RvtIO.Tests/TfBlockDeserializerGridTests.cs index 054fb7a3..4fc7874a 100644 --- a/tests/RvtIO.Tests/TfBlockDeserializerGridTests.cs +++ b/tests/RvtIO.Tests/TfBlockDeserializerGridTests.cs @@ -207,6 +207,22 @@ public void LevelElevation_IsDecodedFromTheAuthoredPlaneOrigin() Assert.Equal(47.25, elevation); } + [Fact] + public void TfWalkKeepsNativeParameterUpdatesInStreamOrder() + { + var (first, _) = CreateLevelBlock(10); + var (another, _) = CreateLevelBlock(20); + var (replacement, _) = CreateLevelBlock(30); + BitConverter.GetBytes(78u).CopyTo(another, 0); + var state = new ParsingState { Chunks = [[.. first, .. another, .. replacement]], AllKnownIds = [77, 78] }; + + RvtFileReader.RunTfStreamWalk(state); + + Assert.Equal([77u, 78u], state.NativeParams.Keys.ToArray()); + Assert.Equal(30.0, state.NativeParams[77].DoubleFields["__levelElevation"]); + Assert.Equal(20.0, state.NativeParams[78].DoubleFields["__levelElevation"]); + } + [Fact] public void SchemaDecodedGridDatum_IsAttachedAsTheAuthoritativeElementCurve() { diff --git a/tests/RvtIO.Tests/TfSchemaConcurrencyTests.cs b/tests/RvtIO.Tests/TfSchemaConcurrencyTests.cs index 5015d480..b73674c8 100644 --- a/tests/RvtIO.Tests/TfSchemaConcurrencyTests.cs +++ b/tests/RvtIO.Tests/TfSchemaConcurrencyTests.cs @@ -47,6 +47,57 @@ public async Task ConcurrentColdSerializationChains_KeepEveryDeclaringClass() finally { context.Unload(); } } + [Fact] + public void SerializationChainsMatchAllShippedClassBasesAndFields() + { + var schemas = TfBlockDeserializer.Schemas; + foreach (int classId in schemas.Keys) + { + var ancestors = new Stack(); + for (int? current = classId; current is int id && schemas.TryGetValue(id, out var schema); + current = schema.Base) + { + Assert.DoesNotContain(id, ancestors); + ancestors.Push(id); + } + + var expected = ancestors.SelectMany(id => schemas[id].Fields.Select(field => field with { Declaring = id })); + Assert.Equal(expected, TfBlockDeserializer.SerializationFields(classId)); + Assert.All(ancestors, baseId => Assert.True(TfBlockDeserializer.IsSubclassOf(classId, baseId))); + Assert.False(TfBlockDeserializer.IsSubclassOf(classId, int.MaxValue)); + } + Assert.Null(TfBlockDeserializer.SerializationFields(int.MaxValue)); + } + + [Fact] + public void NativeStoreRowsMatchTheShippedLayouts() + { + (string Name, byte Type, byte Mods, int? Ref) id = ("m_paramId", 14, 0, 20); + Assert.Equal([id, ("m_value", (byte)8, (byte)96, null)], Layout(2882)); + Assert.Equal([("m_value", (byte)7, (byte)0, null), id], Layout(2883)); + Assert.Equal([id, ("m_value", (byte)14, (byte)0, 20)], Layout(2884)); + Assert.Equal([id, ("m_value", (byte)4, (byte)0, null)], Layout(2885)); + + static IEnumerable<(string, byte, byte, int?)> Layout(int classId) => + TfBlockDeserializer.SerializationFields(classId)!.Select(field => + (field.Name, field.Type, field.Mods, field.Ref)); + } + + [Fact] + public void FieldCopiesRecomputeCaptureKeysWhenIdentityChanges() + { + var field = new TfBlockDeserializer.TfField("m_hostId", 14, 0, 20, null, 1795); + var equalBeforeCapture = field with { }; + + Assert.Equal("1795:m_hostId", field.ProductionCaptureKey); + Assert.Equal(equalBeforeCapture, field); + Assert.Equal(equalBeforeCapture.GetHashCode(), field.GetHashCode()); + Assert.Null((field with { Name = "m_uncaptured" }).ProductionCaptureKey); + var moved = field with { Declaring = 0 }; + Assert.Equal("0:m_hostId", moved.QualifiedKey); + Assert.Null(moved.ProductionCaptureKey); + } + private static Type Parser(AssemblyLoadContext context) => context .LoadFromAssemblyPath(typeof(TfBlockDeserializer).Assembly.Location) .GetType("RvtIO.Parsing.TfBlockDeserializer", throwOnError: true)!; diff --git a/tests/RvtIO.Tests/TfStreamWalkerStreamingTests.cs b/tests/RvtIO.Tests/TfStreamWalkerStreamingTests.cs index bed7264e..da5ba4ca 100644 --- a/tests/RvtIO.Tests/TfStreamWalkerStreamingTests.cs +++ b/tests/RvtIO.Tests/TfStreamWalkerStreamingTests.cs @@ -5,6 +5,99 @@ namespace RvtIO.Tests; public class TfStreamWalkerStreamingTests { + [Fact] + public void TargetedScanKeepsClassPriorityAndStreamOrderAcrossChunks() + { + byte[] Chunk(params (uint Id, ushort Class, uint Size)[] specs) + { + var bytes = new byte[48 * specs.Length]; + for (int index = 0; index < specs.Length; index++) + { + var (id, cls, size) = specs[index]; + int start = index * 48; + BitConverter.GetBytes(id).CopyTo(bytes, start); + BitConverter.GetBytes(size).CopyTo(bytes, start + 8); + BitConverter.GetBytes(cls).CopyTo(bytes, start + 12); + } + return bytes; + } + byte[] bytes = Chunk((10, 0x0346, 20), (11, 0x07D6, 20), (12, 0x07D7, 20), + (13, 0x07D7, 20), (14, 0x07D7, 20), (15, 0x07D7, 19), (16, 0x0346, 100)); + var visited = new List<(uint, ushort)>(); + + TfStreamWalker.ScanBlocks([bytes[..108], [], bytes[108..]], [10, 11, 12, 13, 15, 16], + (_, _, _, cls, id) => visited.Add((id, cls))); + + Assert.Equal([(12u, (ushort)0x07D7), (13u, (ushort)0x07D7), + (11u, (ushort)0x07D6), (10u, (ushort)0x0346)], visited); + } + + [Fact] + public void DeferredBlocksReuseContainingChunksAndCopyOnlyBytesAcrossBoundaries() + { + byte[] bytes = Blocks([101, 102]); + int boundary = 1_000_000; + byte[] first = bytes[..boundary], second = bytes[boundary..]; + var sources = new TfStreamWalker.SegmentSources(); + var retained = new List<(byte[] Data, int Start)>(); + + TfStreamWalker.Walk([first, [], second], [], (segment, start, size, _, _) => + retained.Add(sources.Retain(segment, start, (int)size + 16)), sources: sources); + + Assert.Equal(2, retained.Count); + Assert.Same(first, retained[0].Data); + Assert.Equal(0, retained[0].Start); + Assert.NotSame(first, retained[1].Data); + Assert.NotSame(second, retained[1].Data); + Assert.Equal(0, retained[1].Start); + Assert.Equal(bytes[800_016..], retained[1].Data); + + sources.SetSegment([second], 0, 1, boundary); + var carried = sources.Retain(bytes, boundary - 3, 6); + Assert.Equal(bytes[(boundary - 3)..(boundary + 3)], carried.Data); + } + + [Theory] + [InlineData(12_000_000)] + [InlineData(9_500_000)] + public void TargetedSlicesMatchStitchedScanAcrossPhysicalAndLogicalBoundaries(int segmentTarget) + { + const int chunkSize = 4_000_000, size = 32; + byte[] bytes = new byte[chunkSize * 4]; + Write(28, 101, 0x0346); + Write(chunkSize - 13, 102, 0x07D7); // the two marker bytes straddle a chunk + Write(chunkSize + 45, 103, 0x07D6); + Write(2 * chunkSize - 22, 104, 0x0346); // the header fits and the payload straddles + Write(2 * chunkSize + 54, 102, 0x07D7); + Write(3 * chunkSize - 7, 105, 0x07D7); // the size field straddles a chunk + Write(3 * chunkSize + 57, 106, 0x0346); + Write(bytes.Length - 17, 107, 0x07D7); // truncated at the end + byte[][] chunks = [[], bytes[..chunkSize], [], bytes[chunkSize..(2 * chunkSize)], + bytes[(2 * chunkSize)..(3 * chunkSize)], [], bytes[(3 * chunkSize)..], []]; + HashSet ids = [101, 102, 103, 104, 105, 106, 107]; + var expected = new List<(uint, ushort, string)>(); + var actual = new List<(uint, ushort, string)>(); + + TfStreamWalker.ScanBlocks(chunks, ids, (data, start, count, cls, id) => + expected.Add((id, cls, Convert.ToHexString(data.AsSpan(start, (int)count + 16)))), segmentTarget: segmentTarget); + TfStreamWalker.ScanBlockSlices(chunks, ids, (data, start, count, cls, id) => + { + if (id == 101) Assert.Same(chunks[1], data); + if (id is 104 or 105) Assert.Equal(size + 16, data.Length); + actual.Add((id, cls, Convert.ToHexString(data.AsSpan(start, (int)count + 16)))); + }, segmentTarget); + + Assert.Equal(7, expected.Count); + Assert.Equal(expected, actual); + + void Write(int offset, uint id, ushort cls) + { + BitConverter.GetBytes(id).CopyTo(bytes, offset); + BitConverter.GetBytes((uint)size).CopyTo(bytes, offset + 8); + BitConverter.GetBytes(cls).CopyTo(bytes, offset + 12); + } + } + [Theory] [InlineData(97_003, 3_400_000)] [InlineData(300_011, 3_700_000)] [InlineData(4_000_000, 3_400_000)] [InlineData(400_001, 1_400_000_000)] @@ -79,6 +172,20 @@ public void BlockShapedBytesOfAKnownIdWithoutTheFooterEchoAreNotABlock() Assert.Equal([102u, 103u], visits); } + [Fact] + public void ZeroPaddingStillFindsAnAnchorWhoseOwnerIsZero() + { + const int padding = 100_003; + byte[] blocks = Blocks([0, 102]); + byte[] stream = new byte[padding + blocks.Length]; + blocks.CopyTo(stream, padding); + var visits = new List<(int Offset, uint Owner)>(); + + TfStreamWalker.Walk([stream], [], (_, offset, _, _, owner) => visits.Add((offset, owner))); + + Assert.Equal([(padding, 0u), (padding + 800_016, 102u)], visits); + } + private static byte[] Blocks(uint[] ids) { const int size = 800_000, length = size + 16; diff --git a/tests/RvtIO.Tests/ViewPlaneTests.cs b/tests/RvtIO.Tests/ViewPlaneTests.cs index f66aecd0..aa13ff0a 100644 --- a/tests/RvtIO.Tests/ViewPlaneTests.cs +++ b/tests/RvtIO.Tests/ViewPlaneTests.cs @@ -49,6 +49,26 @@ public void CollectViewPlanes_ReadsThePlaneOfTheViewBlock() Assert.Equal([0, -1, 0], plane.Horiz); } + [Theory] + [InlineData(-0.999, 0)] + [InlineData(1.001, 1)] + public void CollectViewPlanes_FindsTheFallbackAtTheLastPayloadOffset(double verticalZ, int prefix) + { + var state = new ParsingState(); + double[] values = [0, 1, 0, 10, -2, 6, 100, 0, 0, verticalZ, 1, 0, 0]; + byte[] chunk = new byte[16 + prefix + values.Length * sizeof(double)]; + BinaryPrimitives.WriteUInt32LittleEndian(chunk, 500); + BinaryPrimitives.WriteInt32LittleEndian(chunk.AsSpan(8), chunk.Length - 16); + for (int index = 0; index < values.Length; index++) + BinaryPrimitives.WriteDoubleLittleEndian(chunk.AsSpan(16 + prefix + index * sizeof(double)), values[index]); + + BlockParser.CollectViewPlanes(chunk, state); + + var plane = Assert.Contains(500u, state.ViewPlanes); + Assert.Equal([10, -2, 6], plane.Origin); + Assert.Equal([0, 0, verticalZ], plane.Vert); + } + private static Element SectionView(int id, double[] origin) { return new Element diff --git a/tests/RvtIO.Tests/WallCompleteInputTests.cs b/tests/RvtIO.Tests/WallCompleteInputTests.cs index 930cd7eb..b84ce97c 100644 --- a/tests/RvtIO.Tests/WallCompleteInputTests.cs +++ b/tests/RvtIO.Tests/WallCompleteInputTests.cs @@ -122,6 +122,36 @@ public void EveryLatePayloadTruncationFailsWithAValidReframedFooter(int cls, int Assert.NotNull(Read(Block((ushort)cls, payload), out _)); } + [Theory] + [InlineData(2075, 8, false)] + [InlineData(1736, 80, true)] + public void ReaderInputIsReusedAndOnlyRetainsConsumedLateObjects(int cls, int width, bool retained) + { + byte[] block = Block((ushort)cls, new byte[width]); + var full = Read(block, out _)!; + var reader = new TfBlockDeserializer.WallCompleteInputRead(block, 0, BitConverter.ToUInt32(block, 8), 3524); + var selected = reader.Read(out var failure)!; + + Assert.Null(failure); + Assert.Same(selected, reader.Read(out _)); + Assert.Equal(full.End, selected.End); + Assert.Empty(selected.FrameBytes); + if (retained) + Assert.Equal(Assert.Single(full.LaterObjects).Fields.SelectMany(f => f.Bytes), + Assert.Single(selected.LaterObjects).Fields.SelectMany(f => f.Bytes)); + else + Assert.Empty(selected.LaterObjects); + + byte[] truncated = Block((ushort)cls, new byte[width - 1]); + var invalid = new TfBlockDeserializer.WallCompleteInputRead( + truncated, 0, BitConverter.ToUInt32(truncated, 8), 3524); + Assert.Null(Read(truncated, out var expectedFailure)); + Assert.Null(invalid.Read(out failure)); + Assert.Equal(expectedFailure, failure); + Assert.Null(invalid.Read(out failure)); + Assert.Equal(expectedFailure, failure); + } + [Theory] [InlineData(90)] [InlineData(901)] [InlineData(3634)] public void ExcessiveCountsFailRatherThanSkippingOrSeekingTheFooter(int cls) diff --git a/tests/RvtIO.Tests/WallThermalFallbackProvenanceTests.cs b/tests/RvtIO.Tests/WallThermalFallbackProvenanceTests.cs index 444fa934..729a5d52 100644 --- a/tests/RvtIO.Tests/WallThermalFallbackProvenanceTests.cs +++ b/tests/RvtIO.Tests/WallThermalFallbackProvenanceTests.cs @@ -1,4 +1,3 @@ -using System.Reflection; using System.Text.Json; using RvtIO.Internal; using RvtIO.Model; @@ -12,8 +11,7 @@ public class WallThermalFallbackProvenanceTests private static readonly int[] ThermalIds = [-1005430, -1005436, -1005435, -1005434, -1005431]; private static void Enrich(RevitFileInfo info, ParsingState? state) => - typeof(ElementBuilder).GetMethod("EnrichTypeLevelBips", BindingFlags.Static | BindingFlags.NonPublic)! - .Invoke(null, [info, state]); + ElementBuilder.EnrichTypeLevelBips(info, state, info.Elements.ToDictionary(element => element.Id)); private static (RevitFileInfo Info, Element Wall) Model() { @@ -23,6 +21,100 @@ private static (RevitFileInfo Info, Element Wall) Model() return (new RevitFileInfo { Elements = [wall, material] }, wall); } + [Fact] + public void EnrichUsesTheFirstParameterWhenTheSameIdOccursTwice() + { + var (info, wall) = Model(); + var first = BipHelpers.MakeBipParam(-1005500, "STRUCTURAL_MATERIAL_PARAM", StorageType.ElementId, -1); + var second = BipHelpers.MakeBipParam(-1005500, "STRUCTURAL_MATERIAL_PARAM", StorageType.ElementId, -2); + wall.Parameters.AddRange([first, second]); + + Enrich(info, new ParsingState()); + + Assert.Equal(20, first.Value); + Assert.Equal(-2, second.Value); + Assert.Equal([first, second], wall.Parameters.Where(parameter => parameter.Id == -1005500)); + } + + [Fact] + public void CommonDefaultsRetainStoredValuesAndAppendInRuleOrder() + { + var (info, wall) = Model(); + var stored = BipHelpers.MakeBipParam(-1010104, "ALL_MODEL_URL", StorageType.String, "stored"); + wall.Parameters.Add(stored); + + Enrich(info, new ParsingState()); + + Assert.Same(stored, Assert.Single(wall.Parameters, parameter => parameter.Id == -1010104)); + Assert.Equal("stored", stored.Value); + int first = wall.Parameters.FindIndex(parameter => parameter.Id == -1010103); + Assert.True(first >= 0); + Assert.Equal(-1010105, wall.Parameters[first + 1].Id); + Assert.Equal(-1001205, wall.Parameters[^1].Id); + Assert.All(wall.Parameters.Skip(first), parameter => Assert.True(parameter.HasNoRevitValue)); + } + + [Fact] + public void CommonDefaultDefinitionsCanBeEditedIndependently() + { + var (info, wall) = Model(); + Enrich(info, new ParsingState()); + + const int descriptionId = -1010103; + var wallDescription = Assert.Single(wall.Parameters, parameter => parameter.Id == descriptionId); + var materialDescription = Assert.Single(info.Elements[1].Parameters, parameter => parameter.Id == descriptionId); + wallDescription.Definition.Name = "Edited wall description"; + + Assert.Equal("ALL_MODEL_DESCRIPTION", materialDescription.Definition.Name); + Assert.Equal("", materialDescription.Value); + } + + [Fact] + public void DerivedOffsetCanReadAnElevationQueuedInTheSameBatch() + { + var level = new Element + { + Id = 1, + CategoryId = -2000240, + Parameters = [BipHelpers.MakeBipParam(-1007102, "LEVEL_ELEV", StorageType.Double, 1.25)], + }; + var instance = new Element { Id = 2, CategoryId = -2000151, References = [1], BoundingBox = [0, 0, 3, 5, 2, 5] }; + + Enrich(new RevitFileInfo { Elements = [level, instance] }, new ParsingState()); + + var elevation = Assert.Single(instance.Parameters, parameter => parameter.Id == -1001360); + var offset = Assert.Single(instance.Parameters, parameter => parameter.Id == -1001364); + Assert.Equal(1.75, elevation.Value); + Assert.Equal(elevation.Value, offset.Value); + Assert.True(instance.Parameters.IndexOf(elevation) < instance.Parameters.IndexOf(offset)); + } + + [Fact] + public void TypeReferencesKeepPriorityAndOnlyLevelSelectionExcludesSelf() + { + var phaseZero = new Element { Id = 0, CategoryId = -2000112, TypeId = 10 }; + var otherPhase = new Element { Id = 11, CategoryId = -2000112 }; + var level = new Element { Id = 1, CategoryId = -2000240, TypeId = 10 }; + var otherLevel = new Element { Id = 2, CategoryId = -2000240 }; + var host = new Element { Id = 3, CategoryId = -2000011 }; + var otherHost = new Element { Id = 4, CategoryId = -2000011 }; + var type = new Element { Id = 10, References = [1, 2, 0, 3] }; + var instance = new Element { Id = 20, CategoryId = -2000170, TypeId = 10, References = [11, 4] }; + + Enrich(new RevitFileInfo + { + Elements = [phaseZero, otherPhase, level, otherLevel, host, otherHost, type, instance], + }, new ParsingState()); + + Assert.Equal(2, Value(level, -1001352)); + Assert.Equal(1, Value(instance, -1001352)); + Assert.Equal(0, Value(phaseZero, -1012100)); + Assert.Equal(0, Value(instance, -1012100)); + Assert.Equal(3, Value(instance, -1002108)); + + static object? Value(Element element, int id) => Assert.Single(element.Parameters, p => p.Id == id).Value; + } + [Theory] [InlineData(-1005430, 3.4866666666666668, StorageType.Double)] [InlineData(-1005436, 3, StorageType.Integer)] diff --git a/tests/RvtIO.Tests/WallWidthExtractorTests.cs b/tests/RvtIO.Tests/WallWidthExtractorTests.cs new file mode 100644 index 00000000..f60d7d77 --- /dev/null +++ b/tests/RvtIO.Tests/WallWidthExtractorTests.cs @@ -0,0 +1,66 @@ +using RvtIO.Internal; +using RvtIO.Parsing; +using Xunit; + +namespace RvtIO.Tests; + +public class WallWidthExtractorTests +{ + [Fact] + public void InheritedDoublesShareTheFilteredSnapshotAndKeepWallWidthsLocal() + { + var state = new ParsingState(); + state.ElemBipDoubles[10] = new() { [20] = 42, [-1001105] = 8 }; + state.ElemBipDoubles[11] = new() { [-1001105] = 9, [-1001001] = 6 }; + state.WallTypeWidths[12] = 0.75; + state.Records[20] = new ElementRecord { References = [10, 12], CategoryId = -2000011 }; + state.Records[21] = new ElementRecord { References = [20] }; + state.Records[22] = new ElementRecord { References = [10] }; + state.Records[23] = new ElementRecord { References = [10, 11] }; + + RvtFileReader.PrePropagateBipDoubles(state, null); + + var inherited = state.ElemBipDoubles[21]; + Assert.Single(inherited); + Assert.Equal(8.0, inherited[-1001105]); + Assert.Same(inherited, state.ElemBipDoubles[22]); + Assert.Equal(0.75, state.ElemBipDoubles[20][-1001000]); + Assert.Equal(8.0, state.ElemBipDoubles[23][-1001105]); + Assert.Equal(6.0, state.ElemBipDoubles[23][-1001001]); + } + + [Fact] + public void Extract_KeepsFirstOrderedBlockGridBeforeRecordFallback() + { + var state = new ParsingState(); + state.Records[420] = new ElementRecord { CategoryId = -2000011, Body = Grid(1.5) }; + state.Records[421] = new ElementRecord { CategoryId = -2000011, Body = Grid(2) }; + state.Records[422] = new ElementRecord { CategoryId = -2000011, Body = Grid(3) }; + state.ElemBipDoubles[422] = new() { [-1001105] = 9 }; + state.NonRecordChunks.Add(Block(420, 0.5)); + state.RecordChunks.Add(Block(420, 1)); + + WallWidthExtractor.Extract(state); + + Assert.Equal(0.5, state.WallTypeWidths[420]); + Assert.Equal(0.5, state.ElemBipDoubles[420][-1001000]); + Assert.Equal(2.0, state.WallTypeWidths[421]); + Assert.False(state.WallTypeWidths.ContainsKey(422)); + } + + private static byte[] Grid(double width) + { + var grid = new byte[48]; + BitConverter.GetBytes(width).CopyTo(grid, 24); + return grid; + } + + private static byte[] Block(uint id, double width) + { + var block = new byte[64]; + BitConverter.GetBytes(id).CopyTo(block, 0); + BitConverter.GetBytes(48u).CopyTo(block, 8); + Grid(width).CopyTo(block, 16); + return block; + } +}