diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 145ac2b0..2b2ea0e4 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -92,6 +92,19 @@ files again after the change, using the same options. Compare the before and after IFC and JSON outputs, investigate differences, and explain intentional changes in the pull request. +For a timed large-model comparison, build both Release CLIs for the same framework in +separate directories. Run them sequentially on the same machine, with enough temporary +disk space for one complete export (full JSON can be much larger than the input): + +```sh +python tools/benchmark-export.py model.rvt before/RvtIO.Cli.dll after/RvtIO.Cli.dll --runs 3 --min-speedup 2 +``` + +The script alternates build order, fixes the IFC timestamp and checks SHA-256 of IFC, +both JSON formats, Scene and the report after each run. It prints wall time, peak +working set on Windows and median batch speedup. `--compare-separate` also times four +independent candidate exports; their speedup from batching is reported separately. + ## Pull requests Include: diff --git a/src/RvtIO.Cli/ExportCommand.cs b/src/RvtIO.Cli/ExportCommand.cs index 4c3f2413..e582ee0b 100644 --- a/src/RvtIO.Cli/ExportCommand.cs +++ b/src/RvtIO.Cli/ExportCommand.cs @@ -15,6 +15,22 @@ private sealed record ExportArguments(string[] Args, string RvtPath, string? Ifc IfcProfile Profile, string? ExportPhaseOption, string? RoomPhaseOption, bool IncludeIfcRevitParameters, bool RevitParameterGroups, bool BaseQuantities, string JsonClassPrefix, bool OpeningLegacyAxes, DateTimeOffset? IfcTimestamp, IfcUnitFamily? IfcLengthUnit); + private sealed record ExportInput(RevitFileInfo Geometry, RevitFileInfo Json, JsonReadFacts GeometryNames, + JsonReadFacts JsonFacts, ParsingState? QuantityState, IReadOnlyCollection TableRows); + + private static ExportInput ReadExportInput(string path, RvtReaderOptions options, bool compact, bool dumpSolids, bool debugNative) + { + var reader = new RvtFileReader(options); + var model = reader.Read(path); + var state = reader.LastParsingState ?? throw new InvalidOperationException("The reader kept no parsing state."); + var json = reader.WideModel ?? model; + var names = new JsonReadFacts(state, compact && reader.WideState == null, debugNative && reader.WideState == null); + // The quantity pass may still need raw geometry. All other consumers read the model and named maps only. + var quantities = compact && (json.GeometryUndecoded || dumpSolids) && (state.R22View || !model.GeometryUndecoded) + ? state : null; + return new(model, json, names, reader.WideState is { } wide ? new JsonReadFacts(wide, compact, debugNative) : names, quantities, state.ElemTable.Keys); + } + // The export: reads the file and writes the IFC, the compact JSON or the full JSON dump. private static int Export(ExportArguments arguments) { @@ -103,10 +119,9 @@ private static int Export(ExportArguments arguments) string inputName = Path.GetFileName(rvtPath); long inputBytes = File.Exists(rvtPath) ? new FileInfo(rvtPath).Length : 0; - var reader = new RvtFileReader(options); var swRead = System.Diagnostics.Stopwatch.StartNew(); - RevitFileInfo rvtInfo; - try { rvtInfo = reader.Read(rvtPath); } + ExportInput input; + try { input = ReadExportInput(rvtPath, options, compactJsonPath != null, args.SkipLast(1).Contains("--dev-solids"), args.Contains("--dev-native")); } catch (RvtInputException ex) { return EndRun(reportPath, ExportReport.Failed(inputName, inputBytes, ex.Kind, ex.Message, RvtExitCodes.InputError, readDiagnostics, raiseLimits, allowPartial, null, strict), @@ -127,7 +142,7 @@ private static int Export(ExportArguments arguments) } Console.Error.WriteLine($"Timing: read {swRead.Elapsed.TotalSeconds:F1}s"); var report = ExportReport.ForRead(inputName, inputBytes, readDiagnostics, raiseLimits, allowPartial, - reader.LastParsingState?.ElemTable.Keys.ToList() ?? [], rvtInfo, strict); + input.TableRows, input.Geometry, strict); foreach (var hit in readDiagnostics.LimitHits) Console.Error.WriteLine($"warning: stream {hit.Stream} was cut by the reader limit {hit.Limit} ({hit.Value.ToString("N0", System.Globalization.CultureInfo.InvariantCulture)}): {hit.Detail}"); if (report.ExitCode == RvtExitCodes.LimitExceeded) @@ -144,15 +159,14 @@ private static int Export(ExportArguments arguments) $"error: the read of '{inputName}' was partial ({reasons}). Nothing was exported (exit code {report.ExitCode}). Omit --strict to export what was read."); } - var jsonModel = reader.WideModel ?? rvtInfo; - var jsonState = reader.WideState ?? reader.LastParsingState ?? throw new InvalidOperationException("The reader kept no parsing state."); - var ifcModel = rvtInfo; - var ifcState = reader.LastParsingState ?? throw new InvalidOperationException("The reader kept no parsing state."); + var jsonModel = input.Json; + var jsonState = input.JsonFacts; + var ifcModel = input.Geometry; if (scenePath != null) { var swScene = System.Diagnostics.Stopwatch.StartNew(); - var doc = RvtDocument.FromInfo(ifcModel); + var doc = RvtDocument.ForSceneExport(ifcModel); var sceneResult = RvtIO.Scene.RvtSceneReader.Read(doc, new RvtIO.Scene.RvtSceneOptions { ModelKey = Path.GetFileName(rvtPath) @@ -191,7 +205,7 @@ private static int Export(ExportArguments arguments) if (roomPhase != null) Console.Error.WriteLine($"IFC room export phase: {roomPhase}"); // A 64-bit-id file has no scanned fallback names: the exporter reads the validated ones, as the JSON dump does. if (ifcModel.GeometryUndecoded) - RvtIO.Export.ValidatedElementNames.Apply(ifcModel, ifcState); + RvtIO.Export.ValidatedElementNames.Apply(ifcModel, input.GeometryNames); var skipLog = new SkipLog(); var exporter = new IfcExporter(Console.Error, includeIfcRevitParameters) { SkipLog = skipLog, ExportPhaseId = exportPhase, ExportAllPhases = exportPhaseOption == "all", RoomExportPhaseId = roomPhase, ExportRoomsOfAllPhases = roomPhaseOption == "all", RevitParameterGroups = revitParameterGroups, Profile = profile, BaseQuantities = baseQuantities, OpeningQuantitiesSwapped = openingLegacyAxes, Timestamp = ifcTimestamp, LengthUnit = ifcLengthUnit }; var swExport = System.Diagnostics.Stopwatch.StartNew(); @@ -228,9 +242,9 @@ private static int Export(ExportArguments arguments) var compactGate = RvtIO.Compact.CompactValueGate.ForLayout(jsonModel.GeometryUndecoded); CompactSolidQuantities? compactQuantities = null; // Only wide-layout property rules and the explicit solids dump consume this index. - if ((jsonModel.GeometryUndecoded || solidsPath != null) && (ifcState.R22View || !ifcModel.GeometryUndecoded)) + if ((jsonModel.GeometryUndecoded || solidsPath != null) && input.QuantityState is { } quantityState) { - compactQuantities = CompactSolidQuantities.From(ifcModel, ifcState, compactGate.HasSolidRules); + compactQuantities = CompactSolidQuantities.From(ifcModel, quantityState, compactGate.HasSolidRules); } else if (jsonModel.GeometryUndecoded) { @@ -240,9 +254,7 @@ private static int Export(ExportArguments arguments) // --dev-solids-only stops after it if (solidsPath != null) { - var measured = compactQuantities ?? ((ifcState.R22View || !ifcModel.GeometryUndecoded) - ? CompactSolidQuantities.From(ifcModel, ifcState, null) - : CompactSolidQuantities.Read(rvtPath, options, null)); + var measured = compactQuantities ?? CompactSolidQuantities.Read(rvtPath, options, null); using var solidsWriter = new StreamWriter(solidsPath, false, new System.Text.UTF8Encoding(false)); RvtIO.Compact.CompactSolidFacts.Dump(measured, jsonModel.SerializedFormatSettings, solidsWriter); if (args.Contains("--dev-solids-only")) return 0; @@ -301,7 +313,7 @@ static string TsvText(string? text) => text == null ? "\\N" CompactJsonExporter.Export(jsonModel, compactJsonPath, compactSource, Console.Error, compactIdentity, new CompactJsonExportOptions { JsonClassNamePrefix = jsonClassPrefix }); compactSource.Builtin.WriteReport(Console.Error); - if (ifcPath == null) + if (reportPath != null && ifcPath == null) report.SetJsonExport(jsonModel, full: false); } @@ -313,7 +325,7 @@ static string TsvText(string? text) => text == null ? "\\N" DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull, NumberHandling = JsonNumberHandling.AllowNamedFloatingPointLiterals, Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping, - Converters = { new JsonStringEnumConverter(), new RvtIO.Model.ParameterListConverter() }, + Converters = { new JsonStringEnumConverter() }, }; #if !NET9_0_OR_GREATER jsonOpts.Converters.Add(new RvtIO.Cli.ShortestDoubleConverter()); @@ -327,13 +339,14 @@ static string TsvText(string? text) => text == null ? "\\N" // De-duplicate parameter definitions into a shared table so each element parameter only stores its value (keyed by id). jsonModel.BuildParameterDefinitionTable(); + jsonOpts.Converters.Add(new ParameterListConverter(jsonModel.ParameterDefinitions!.Keys, jsonOpts.Encoder)); // Stream directly to the file (avoids building one ~GB string in memory, which runs out of memory on large files). using (var fs = File.Create(fullJsonPath)) - JsonSerializer.Serialize(fs, jsonModel, jsonOpts); + FullJsonOutput.Write(fs, jsonModel, jsonOpts); Console.Error.WriteLine($"JSON written to {fullJsonPath} ({jsonModel.Elements.Count} elements, " + $"{jsonModel.ParameterDefinitions?.Count ?? 0} param defs)"); - if (ifcPath == null && compactJsonPath == null) + if (reportPath != null && ifcPath == null && compactJsonPath == null) report.SetJsonExport(jsonModel, full: true); } return EndRun(reportPath, report, null); diff --git a/src/RvtIO.Cli/FullJsonOutput.cs b/src/RvtIO.Cli/FullJsonOutput.cs new file mode 100644 index 00000000..5a661e09 --- /dev/null +++ b/src/RvtIO.Cli/FullJsonOutput.cs @@ -0,0 +1,142 @@ +using System.Text.Json; +using System.Text.Json.Serialization; +using RvtIO.Model; + +internal static class FullJsonOutput +{ + private const int Batch = 64; + private const int BufferLimit = 2 << 20; + + // workerCount lets tests exercise the parallel path on a single-CPU machine. + internal static void Write(FileStream output, RevitFileInfo model, JsonSerializerOptions options, int? workerCount = null) + { + int workers = workerCount ?? Math.Min(8, Environment.ProcessorCount); + if (model.Elements.Count < 4096 || workers < 2) + { + JsonSerializer.Serialize(output, model, options); + return; + } + + var rootOptions = new JsonSerializerOptions(options); + rootOptions.Converters.Insert(0, new Elements(output, options, workers)); + using var writer = new Utf8JsonWriter(new FileBuffer(output), new JsonWriterOptions { Indented = options.WriteIndented, Encoder = options.Encoder }); + JsonSerializer.Serialize(writer, model, rootOptions); + writer.Flush(); + output.SetLength(output.Position); + } + + // Metadata and embedded family storage outside Elements must stream as well. An externally + // supplied Utf8JsonWriter over a Stream would retain the bytes between explicit flushes. + private sealed class FileBuffer(FileStream output) : System.Buffers.IBufferWriter + { + private byte[] _buffer = new byte[64 << 10]; + public void Advance(int count) => output.Write(_buffer, 0, count); + public Memory GetMemory(int sizeHint = 0) + { + if (sizeHint > _buffer.Length) _buffer = new byte[sizeHint]; + return _buffer; + } + public Span GetSpan(int sizeHint = 0) => GetMemory(sizeHint).Span; + } + + // Each batch is serialized at depth two, just like the Elements property of the model. + // The serializer supplies the envelope, including the runtime's exact indentation and newline. + private sealed class Elements(FileStream output, JsonSerializerOptions options, int workers) : JsonConverter> + { + public override List Read(ref Utf8JsonReader reader, Type type, JsonSerializerOptions opts) => throw new NotSupportedException(); + + public override void Write(Utf8JsonWriter writer, List elements, JsonSerializerOptions opts) + { + byte[] sample = JsonSerializer.SerializeToUtf8Bytes(new[] { new[] { 0 } }, options); + int prefix = Array.LastIndexOf(sample, (byte)'[') + 1; + int afterValue = Array.IndexOf(sample, (byte)'0') + 1; + int suffix = sample.Length - afterValue; + int indent = Array.IndexOf(sample, (byte)']') - afterValue; + writer.WriteStartArray(); + writer.Flush(); + var buffers = new BatchBuffer[workers]; + var pending = new Task[workers]; + for (int i = 0; i < workers; i++) + { + buffers[i] = new(); + pending[i] = Start(i, i * Batch); + } + try + { + for (int offset = 0, slot = 0; offset < elements.Count; slot = (slot + 1) % workers) + { + pending[slot].GetAwaiter().GetResult(); + if (offset != 0) output.WriteByte((byte)','); + var buffer = buffers[slot]; + if (buffer.Length != 0) + output.Write(buffer.GetBuffer(), prefix, (int)buffer.Length - prefix - suffix); + else + { + // A single element can be larger than the entire worker budget. Use the + // serializer's normal streaming path and overwrite the trailing array delimiters. + SerializeBatch(new SkipPrefix(output, prefix), offset); + output.Position -= suffix; + } + if (elements.Count - offset > workers * Batch) + pending[slot] = Start(slot, offset + workers * Batch); + offset += Math.Min(Batch, elements.Count - offset); + } + } + finally + { + // Workers never write to the file. Join them on an I/O or serialization + // failure without replacing the first exception in output order. + Task.WhenAll(pending).ConfigureAwait(ConfigureAwaitOptions.SuppressThrowing).GetAwaiter().GetResult(); + } + if (elements.Count > 0) output.Write(sample, afterValue, indent); + writer.WriteEndArray(); + + Task Start(int slot, int start) => start >= elements.Count ? Task.CompletedTask : Task.Run(() => + { + var buffer = buffers[slot]; + buffer.SetLength(0); + try { SerializeBatch(buffer, start); } + catch (BatchTooLarge) { buffer.SetLength(0); } + }); + + void SerializeBatch(Stream stream, int start) => + JsonSerializer.Serialize(stream, new[] { elements.GetRange(start, Math.Min(Batch, elements.Count - start)) }, options); + } + } + + private sealed class BatchTooLarge : Exception; + + private sealed class BatchBuffer() : MemoryStream(new byte[BufferLimit], 0, BufferLimit, writable: true, publiclyVisible: true) + { + public override void Write(byte[] buffer, int offset, int count) + { + if (Position + count > BufferLimit) throw new BatchTooLarge(); + base.Write(buffer, offset, count); + } + public override void Write(ReadOnlySpan buffer) + { + if (Position + buffer.Length > BufferLimit) throw new BatchTooLarge(); + base.Write(buffer); + } + } + + private sealed class SkipPrefix(Stream target, int skip) : Stream + { + public override void Write(byte[] buffer, int offset, int count) => Write(buffer.AsSpan(offset, count)); + public override void Write(ReadOnlySpan buffer) + { + int ignored = Math.Min(skip, buffer.Length); + skip -= ignored; + target.Write(buffer[ignored..]); + } + public override bool CanRead => false; + public override bool CanSeek => false; + public override bool CanWrite => true; + public override long Length => throw new NotSupportedException(); + public override long Position { get => throw new NotSupportedException(); set => throw new NotSupportedException(); } + public override int Read(byte[] buffer, int offset, int count) => throw new NotSupportedException(); + public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); + public override void SetLength(long value) => throw new NotSupportedException(); + public override void Flush() => target.Flush(); + } +} diff --git a/src/RvtIO/Compact/CompactBuiltinParameters.cs b/src/RvtIO/Compact/CompactBuiltinParameters.cs index a37f0642..50e8fc9d 100644 --- a/src/RvtIO/Compact/CompactBuiltinParameters.cs +++ b/src/RvtIO/Compact/CompactBuiltinParameters.cs @@ -43,7 +43,7 @@ internal readonly record struct CompactBuiltinResult( private readonly Func _headerCategory; private readonly bool _usesDefaultHeaderCategory; private readonly CompactValueGate? _gate; - private readonly ParsingState? _state; + private readonly JsonReadFacts? _state; private readonly CompactSolidQuantities? _quantities; private readonly double? _surveyOffsetFeet; private readonly string? _lookupNoneText; @@ -59,7 +59,7 @@ internal readonly record struct CompactBuiltinResult( /// Shared (survey) elevation minus internal elevation of the active project location, null when the /// location is not resolved exactly. public CompactBuiltinParameters(CompactElementNames names, CompactFormatSettings? format, CompactListFileFacts file, - Func? headerCategory = null, CompactValueGate? gate = null, ParsingState? state = null, double? surveyOffsetFeet = null, + Func? headerCategory = null, CompactValueGate? gate = null, JsonReadFacts? state = null, double? surveyOffsetFeet = null, string? lookupNoneText = null, CompactSolidQuantities? quantities = null) { _quantities = quantities; @@ -376,7 +376,8 @@ private bool IsLoadableFamilyInstance(Element element) => /// The first FamilyParams record of the element for the id (the reader keeps the first of a repeated id). private TfBlockDeserializer.NamedParamRecord? OwnRecord(Element element, int id) { - if (_state == null || !_state.NativeParams.TryGetValue((uint)element.Id, out var native)) return null; + if (_state == null) return null; + var native = _state.StoresOf((uint)element.Id); foreach (var record in native.NamedParams) if (record.ParamId == id) return record; return null; @@ -420,13 +421,16 @@ record != null ? record.Str : element.Parameters.FirstOrDefault(p => p.Id == Ana } // a number is printed from the value of the store itself: the reader's parameter of the same id can have been replaced by a // derived value (wall openings: Base Offset stored as 109,01, 0 in the reader's parameter) - if (storage == StorageType.Double && _state != null && _state.NativeParams.TryGetValue((uint)element.Id, out var native) - && native.Doubles.Any(item => item.ParamId == id)) + if (storage == StorageType.Double && _state != null) { - if (spec.Length == 0 || _format == null) { reason = "double without a spec or format settings"; return null; } - string? formatted = CompactValueFormatter.Format(native.Doubles.First(item => item.ParamId == id).Value, spec, _format); - if (formatted == null) reason = "stored double not formatted (unit or spec unknown)"; - return formatted; + foreach (var row in _state.StoresOf((uint)element.Id).Doubles) + { + if (row.ParamId != id) continue; + if (spec.Length == 0 || _format == null) { reason = "double without a spec or format settings"; return null; } + string? formatted = CompactValueFormatter.Format(row.Value, spec, _format); + if (formatted == null) reason = "stored double not formatted (unit or spec unknown)"; + return formatted; + } } if (held == null) reason = "stored value not available as text"; return held; diff --git a/src/RvtIO/Compact/CompactElementNames.cs b/src/RvtIO/Compact/CompactElementNames.cs index 70463d57..b6b579e5 100644 --- a/src/RvtIO/Compact/CompactElementNames.cs +++ b/src/RvtIO/Compact/CompactElementNames.cs @@ -17,10 +17,10 @@ internal sealed class CompactElementNames { private readonly Dictionary _byId; private readonly Dictionary _counts; - private readonly ParsingState? _state; + private readonly JsonReadFacts? _state; private readonly ConcurrentDictionary _cache = new(); - public CompactElementNames(RevitFileInfo info, ParsingState? state) + public CompactElementNames(RevitFileInfo info, JsonReadFacts? state) { ArgumentNullException.ThrowIfNull(info); _state = state; @@ -33,7 +33,7 @@ public CompactElementNames(RevitFileInfo info, ParsingState? state) } } - internal void ApplyValidatedNames(RevitFileInfo info, ParsingState state) => + internal void ApplyValidatedNames(RevitFileInfo info, JsonReadFacts state) => ValidatedElementNames.Apply(info, state, _byId, _counts); /// The element with the id, null when the file has none. diff --git a/src/RvtIO/Compact/CompactPropertySources.cs b/src/RvtIO/Compact/CompactPropertySources.cs index f5796fb5..78cf7834 100644 --- a/src/RvtIO/Compact/CompactPropertySources.cs +++ b/src/RvtIO/Compact/CompactPropertySources.cs @@ -39,7 +39,7 @@ internal CompactPropertySources(CompactBuiltinParameters builtin, CompactIfcPara internal CompactPropertySources Fork() => new(_builtin.Fork(), _ifc, _user, _identityRules); /// The composite of a file. - internal static CompactPropertySources Create(RevitFileInfo info, ParsingState? state, bool? isProjectDocument, + internal static CompactPropertySources Create(RevitFileInfo info, JsonReadFacts? state, bool? isProjectDocument, Func? headerCategory = null, bool gated = true, CompactIdentity? identity = null, CompactSolidQuantities? quantities = null, CompactElementNames? names = null) { diff --git a/src/RvtIO/Export/ValidatedElementNames.cs b/src/RvtIO/Export/ValidatedElementNames.cs index bdef3ee4..e5f5aad8 100644 --- a/src/RvtIO/Export/ValidatedElementNames.cs +++ b/src/RvtIO/Export/ValidatedElementNames.cs @@ -37,7 +37,7 @@ internal static class ValidatedElementNames /// number of elements that keep a name. Destructive: call it only on the way to the JSON dump, never before the IFC /// export or the API, which read as a fallback. /// - internal static int Apply(RevitFileInfo info, ParsingState state) + internal static int Apply(RevitFileInfo info, JsonReadFacts state) { var byId = new Dictionary(info.Elements.Count); var counts = new Dictionary(info.Elements.Count); @@ -49,7 +49,7 @@ internal static int Apply(RevitFileInfo info, ParsingState state) return Apply(info, state, byId, counts); } - internal static int Apply(RevitFileInfo info, ParsingState state, + internal static int Apply(RevitFileInfo info, JsonReadFacts state, IReadOnlyDictionary byId, IReadOnlyDictionary counts) { // Resolve everything before assigning: no resolution may read another element's replaced Name. @@ -67,7 +67,7 @@ internal static int Apply(RevitFileInfo info, ParsingState state, /// The first validated name of the element, in the order of ; null when unvalidated. internal static Validation? Resolve( - Element element, IReadOnlyDictionary byId, IReadOnlyDictionary counts, ParsingState state) + Element element, IReadOnlyDictionary byId, IReadOnlyDictionary counts, JsonReadFacts state) { foreach (Validation validation in Candidates(element, byId, counts, state)) return validation; @@ -76,11 +76,11 @@ internal static int Apply(RevitFileInfo info, ParsingState state, /// The validated names of the element in priority order. A named element (a type, level or material) reports /// its own name and nothing else; only an occurrence with no name of its own reports the name of its type, as the - /// Revit API does. A type element (it owns a Symbol-subclass root, ) has no + /// Revit API does. A type element (it owns a Symbol-subclass root, ) has no /// type: the link it carries points at another symbol, so without a validated name of its own it has none. /// Two different names in the result would contradict each other. internal static IEnumerable Candidates( - Element element, IReadOnlyDictionary byId, IReadOnlyDictionary counts, ParsingState state) + Element element, IReadOnlyDictionary byId, IReadOnlyDictionary counts, JsonReadFacts state) { if (element.Id < 0 || element.Id == 0 && state.WideSchema == null && !state.ElemClassIdx.ContainsKey(0)) yield break; bool named = false; @@ -96,7 +96,7 @@ internal static IEnumerable Candidates( /// The element is itself the named one. The own SymbolInfo name of a unique type root comes before the name /// table: the table holds another string for the pipe, flex pipe and insulation types. - private static IEnumerable OwnNames(Element element, ParsingState state) + private static IEnumerable OwnNames(Element element, JsonReadFacts state) { uint id = (uint)element.Id; if (state.WideNames.TryGetValue(id, out string? wideName) && Named(wideName)) yield return new(wideName, "wide-own-name"); @@ -114,15 +114,14 @@ private static IEnumerable OwnNames(Element element, ParsingState st yield return new(symbol.Name!, "family-symbol"); if (state.ElementNameTable.TryGetValue(id, out string? tableName) && Named(tableName)) yield return new(tableName, "name-table"); - if (state.NativeParams.TryGetValue(id, out var native) && native.Fields.ContainsKey("__isLevel") - && native.StringFields.TryGetValue("m_text", out string? levelName) && Named(levelName)) + if (state.StoresOf(id).LevelName is { } levelName && Named(levelName)) yield return new(levelName, "level"); if (Named(element.SerializedMaterialName)) yield return new(element.SerializedMaterialName!, "material"); } /// An occurrence: the name of its type, through the links the IFC exporter confirms. private static IEnumerable TypeNames( - Element element, IReadOnlyDictionary byId, IReadOnlyDictionary counts, ParsingState state) + Element element, IReadOnlyDictionary byId, IReadOnlyDictionary counts, JsonReadFacts state) { if (IfcExporter.ResolveMepCurveTypeName(element, byId) is { } mepName && Named(mepName)) yield return new(mepName, "mep-curve-type"); @@ -151,7 +150,7 @@ private static IEnumerable TypeNames( /// The SymbolInfo name of the host object type's own unique root, when its class and category agree with the /// occurrences ( sets /// only then). - private static string? HostTypeName(Element type, ParsingState state) => + private static string? HostTypeName(Element type, JsonReadFacts state) => type.SerializedHostTypeLayers != null && state.HostTypeCompoundStructures.TryGetValue((uint)type.Id, out var validation) && Named(validation.TypeName) ? validation.TypeName : null; diff --git a/src/RvtIO/Ifc/IfcExporter.Dialect.cs b/src/RvtIO/Ifc/IfcExporter.Dialect.cs index a8488996..40868d10 100644 --- a/src/RvtIO/Ifc/IfcExporter.Dialect.cs +++ b/src/RvtIO/Ifc/IfcExporter.Dialect.cs @@ -307,7 +307,8 @@ internal static string CurrentSlabPredefinedType(Element occurrence, Element? ty /// The trailing attributes of an IfcStairFlight in the current profile: NumberOfRiser, RiserHeight and NumberOfTreads of the run /// (its own riser count and per-run riser height), TreadLength of its stairs. An attribute whose source is not decoded stays unset. /// - internal static string StairFlightAttributes(Element run, IReadOnlyDictionary elementsById) + internal static string StairFlightAttributes(Element run, IReadOnlyDictionary elementsById, + Dictionary>? stairRuns = null) { string risers = "$", treads = "$", riserHeight = "$", treadLength = "$"; if (run.SerializedStairRunInput is { Numbers: { } numbers } input && input.OwnerId == run.Id) @@ -317,7 +318,7 @@ internal static string StairFlightAttributes(Element run, IReadOnlyDictionary 0 && indexSpan > 0) { risers = runRisers.ToString(CultureInfo.InvariantCulture); - if (StairRunCountsAgree(run, elementsById, numbers, current: true) && StairRunTreads(run, numbers, current: true) is int count && count > 0) + if (StairRunCountsAgree(run, elementsById, numbers, current: true, stairRuns) && StairRunTreads(run, numbers, current: true) is int count && count > 0) treads = count.ToString(CultureInfo.InvariantCulture); double runRiserMillimetres = (numbers.TopElevation - numbers.BottomElevation) / indexSpan * 304.8; if (double.IsFinite(runRiserMillimetres) && runRiserMillimetres > 0) diff --git a/src/RvtIO/Ifc/IfcExporter.QuantitiesCurrent.cs b/src/RvtIO/Ifc/IfcExporter.QuantitiesCurrent.cs index e00200d1..4a2b72b7 100644 --- a/src/RvtIO/Ifc/IfcExporter.QuantitiesCurrent.cs +++ b/src/RvtIO/Ifc/IfcExporter.QuantitiesCurrent.cs @@ -1632,11 +1632,15 @@ private static double PieceArea( private List ColumnQuantitiesCurrent(Element element, ProfileExtrusion? body) { var result = new List(); - var shells = ShellsOfCurrent(element.Geometry); - var totals = SolidTotalsCurrent(shells); + // Most written extrusions already carry their section and have a stored volume. + // Orienting and measuring the whole shell is only needed by the fallback. + List? shells = null; + List Shells() => shells ??= ShellsOfCurrent(element.Geometry); + (double Volume, double Area)? totals = null; + (double Volume, double Area)? Totals() => totals ??= SolidTotalsCurrent(Shells()); // The measures of the node with the end faces stand for the solid of a round column (a vertical cylinder) only. - var capTotals = RoundCylinderCurrent(element.Geometry) != null ? CapNodeTotalsCurrent(element.Geometry) : null; - if ((ExtrusionDataCurrent(body, shells) ?? RoundExtrusionDataCurrent(element.Geometry)) is { } extrusion) + (double Volume, double Area)? CapTotals() => RoundCylinderCurrent(element.Geometry) != null ? CapNodeTotalsCurrent(element.Geometry) : null; + if ((ExtrusionDataCurrent(body, body == null ? Shells() : []) ?? RoundExtrusionDataCurrent(element.Geometry)) is { } extrusion) { double length = extrusion.Depth, area = extrusion.Area; // The outer surface counts the loops of the holes as well (outer + inner perimeter). @@ -1653,14 +1657,15 @@ private List ColumnQuantitiesCurrent(Element element, ProfileExtr double? netVolume = element.MediumSolidTotals?.Volume ?? (extrusion.NominalArea is { } nomArea && (element.HasMediumAlternatives || NodeSolidTotalsCurrent(element.Geometry) == null) ? length * nomArea - : (ComputedHostVolumeCurrent(element) ?? NodeSolidTotalsCurrent(element.Geometry)?.Volume ?? capTotals?.Volume ?? totals?.Volume)); + : (ComputedHostVolumeCurrent(element) ?? NodeSolidTotalsCurrent(element.Geometry)?.Volume ?? CapTotals()?.Volume ?? Totals()?.Volume)); AddIfPositive(result, QuantityKind.Volume, "NetVolume", netVolume); } else { - AddIfPositive(result, QuantityKind.Area, "CrossSectionArea", ComputedHostAreaCurrent(element) ?? (capTotals?.Area ?? totals?.Area) / 2); + var capTotals = CapTotals(); + AddIfPositive(result, QuantityKind.Area, "CrossSectionArea", ComputedHostAreaCurrent(element) ?? (capTotals?.Area ?? Totals()?.Area) / 2); AddIfPositive(result, QuantityKind.Volume, "NetVolume", - ComputedHostVolumeCurrent(element) ?? NodeSolidTotalsCurrent(element.Geometry)?.Volume ?? capTotals?.Volume ?? totals?.Volume); + ComputedHostVolumeCurrent(element) ?? NodeSolidTotalsCurrent(element.Geometry)?.Volume ?? capTotals?.Volume ?? Totals()?.Volume); } return result; } @@ -1704,9 +1709,10 @@ private List BeamQuantitiesCurrent(Element element, ProfileExtrus /// the riser indices of the run (a sketched run without an end riser keeps all of it), and only where the risers agree with those stored /// for its stair. It is not the NumberOfTreads attribute of the flight, which counts the risers of such a run one less, as the file does: /// an assembled run whose attribute is set still takes no Length. Null without a run input or when the counts do not agree. - internal static int? RunLengthTreadsCurrent(Element run, IReadOnlyDictionary elementsById) => + internal static int? RunLengthTreadsCurrent(Element run, IReadOnlyDictionary elementsById, + Dictionary>? stairRuns = null) => run.SerializedStairRunInput is { Numbers: { } numbers } input && input.OwnerId == run.Id - && StairRunRisers(run, numbers) > 0 && StairRunCountsAgree(run, elementsById, numbers) + && StairRunRisers(run, numbers) > 0 && StairRunCountsAgree(run, elementsById, numbers, current: false, stairRuns) && StairRunTreads(run, numbers) is int treads && treads > 0 ? treads : null; /// The inputs of the Length surrogate of a run are the ones it was calibrated on: the family of the run before its type was diff --git a/src/RvtIO/Ifc/IfcExporter.cs b/src/RvtIO/Ifc/IfcExporter.cs index a711e6d5..82985001 100644 --- a/src/RvtIO/Ifc/IfcExporter.cs +++ b/src/RvtIO/Ifc/IfcExporter.cs @@ -736,12 +736,17 @@ string SiteCoordinate(double feet) => var elemById = new Dictionary(); + var stairRuns = new Dictionary>(); var elementIdOccurrenceCounts = new Dictionary(); var elementOrderById = new Dictionary(); for (int elementIndex = 0; elementIndex < info.Elements.Count; elementIndex++) { var e = info.Elements[elementIndex]; - elemById.TryAdd(e.Id, e); + if (elemById.TryAdd(e.Id, e) && e.SerializedStairRunInput is { } run) + { + if (!stairRuns.TryGetValue(run.StairsId, out var group)) stairRuns.Add(run.StairsId, group = []); + group.Add(e); + } elementIdOccurrenceCounts.TryGetValue(e.Id, out int occurrenceCount); elementIdOccurrenceCounts[e.Id] = occurrenceCount + 1; elementOrderById.TryAdd(e.Id, elementIndex); @@ -4636,7 +4641,7 @@ fallbackSourceOwnerTagId is null elem, ifcType, elemById, elementIdOccurrenceCounts, CurrentProfile); string elemName = elemTypeName.Length == 0 ? elem.Id.ToString() : $"{elemTypeName}:{elem.Id}"; if (CurrentProfile && IsRunLengthRuleCurrent(elem, ifcType, elemById, elementIdOccurrenceCounts) - && RunLengthTreadsCurrent(elem, elemById) is int lengthTreads) + && RunLengthTreadsCurrent(elem, elemById, stairRuns) is int lengthTreads) LengthRuleRunsCurrent[elem.Id] = lengthTreads; if (ifcType == "IFCSTAIR") elemName = ResolveNativeStairName(elem, elemById, elementIdOccurrenceCounts, CurrentProfile) ?? elemName; @@ -4696,7 +4701,7 @@ fallbackSourceOwnerTagId is null "IFCRAMP" => $"{S(productGlobalId)},{R(ownerHistId)},{S(elemName)},$,{S(elemTypeName)},{R(elemPlacementId)},{shapeArg},{S(elem.Id.ToString())},.NOTDEFINED.", "IFCSTAIRFLIGHT" => - $"{S(productGlobalId)},{R(ownerHistId)},{S(elemName)},$,{S(elemTypeName)},{R(elemPlacementId)},{shapeArg},{S(elem.Id.ToString())},{(CurrentProfile ? StairFlightAttributes(elem, elemById) : "$,$,$,$")}", + $"{S(productGlobalId)},{R(ownerHistId)},{S(elemName)},$,{S(elemTypeName)},{R(elemPlacementId)},{shapeArg},{S(elem.Id.ToString())},{(CurrentProfile ? StairFlightAttributes(elem, elemById, stairRuns) : "$,$,$,$")}", "IFCCOLUMN" or "IFCBEAM" or "IFCMEMBER" or "IFCPLATE" or "IFCRAMPFLIGHT" or "IFCCURTAINWALL" or "IFCFURNISHINGELEMENT" or "IFCFLOWSEGMENT" @@ -4908,7 +4913,7 @@ fallbackSourceOwnerTagId is null w, elem, elemEntityId, ownerHistId, ifcType, quantityTakeOffReferenceValueId.Value, elemById, elementIdOccurrenceCounts, - propertySingleValueIds, CurrentProfile); + propertySingleValueIds, stairRuns, CurrentProfile); } if (quantityTakeOffReferenceValueId.HasValue && CurrentProfile && ifcType == "IFCRAMP") { @@ -8763,8 +8768,10 @@ internal static List ComputeClosedComponents(GeometryDat continue; } - if (!TryOrientExactFacetedShell(geo.Faces, facetedIndices, - out var orientedFaces, + List orientedFaces; + if (exactShells is [var complete] && complete.Indices.Count == facetedIndices.Count) + orientedFaces = complete.Faces; + else if (!TryOrientExactFacetedShell(geo.Faces, facetedIndices, out orientedFaces, triangulateNonPlanarFaces: !preserveValidatedPlanarFaces)) orientedFaces = facetedIndices.Select(index => geo.Faces[index]).ToList(); // Two independently authored BReps may share source faces. @@ -9416,6 +9423,7 @@ internal static bool TryOrientPrecisionContractedFacetedShell( var parent = new Dictionary<(long X, long Y, long Z), (long X, long Y, long Z)>(); + static bool Finite(double[] p) => p.Length >= 3 && double.IsFinite(p[0]) && double.IsFinite(p[1]) && double.IsFinite(p[2]); IEnumerable> Rings(GeoFace face) { if (face.OuterVertices is { Count: > 0 } outer) yield return outer; @@ -9424,7 +9432,7 @@ IEnumerable> Rings(GeoFace face) foreach (int faceIndex in indices) foreach (var ring in Rings(faces[faceIndex])) foreach (var point in ring) - if (point.Length >= 3 && point.Take(3).All(double.IsFinite)) + if (Finite(point)) { var key = IfcPrecisionKeyFeet(point); parent.TryAdd(key, key); @@ -9473,7 +9481,7 @@ GeoFace Materialize(GeoFace source) { double[] Point(double[] point) { - if (point.Length < 3 || !point.Take(3).All(double.IsFinite)) + if (!Finite(point)) return (double[])point.Clone(); var key = IfcPrecisionKeyFeet(point); // Alternative display rings are copied for metadata fidelity but do not participate @@ -9497,16 +9505,14 @@ double[] Point(double[] point) changed = false; foreach (int faceIndex in indices) { - if (!FaceCollapsesAtIfcPrecision(Materialize(faces[faceIndex]))) continue; + bool? collapsed = null; foreach (var ring in Rings(faces[faceIndex])) { for (int edgeIndex = 0; edgeIndex < ring.Count; edgeIndex++) { var first = ring[edgeIndex]; var second = ring[(edgeIndex + 1) % ring.Count]; - if (first.Length < 3 || second.Length < 3 - || !first.Take(3).All(double.IsFinite) - || !second.Take(3).All(double.IsFinite)) + if (!Finite(first) || !Finite(second)) continue; double dx = second[0] - first[0]; double dy = second[1] - first[1]; @@ -9517,7 +9523,11 @@ double[] Point(double[] point) continue; var firstKey = IfcPrecisionKeyFeet(first); var secondKey = IfcPrecisionKeyFeet(second); - if (firstKey != secondKey && Union(firstKey, secondKey)) + // Only a short edge between distinct bins can change this face's unions. + // Test collapse once, before the first such union changes the current mapping. + if (firstKey != secondKey + && (collapsed ??= FaceCollapsesAtIfcPrecision(Materialize(faces[faceIndex]))) + && Union(firstKey, secondKey)) { contracted = true; changed = true; @@ -9566,6 +9576,7 @@ bool HasSubPrecisionEdge(GeoFace face) if (dxFeet * dxFeet + dyFeet * dyFeet + dzFeet * dzFeet <= precisionSquared) return true; + if (boundaryRoots.Count == 0) continue; var first = IfcPrecisionKeyFeet(firstPoint); var second = IfcPrecisionKeyFeet(secondPoint); var dx = (System.Numerics.BigInteger)second.X - first.X; @@ -9602,9 +9613,10 @@ bool HasSubPrecisionEdge(GeoFace face) // A collapsed strip can leave a sub-precision boundary cycle even when none of its // surviving facets is itself degenerate. + (List Sources, List Faces) prepared; while (true) { - var prepared = PrepareFaces(); + prepared = PrepareFaces(); var faceMap = Enumerable.Range(0, prepared.Faces.Count) .ToDictionary(index => index, index => prepared.Faces[index]); var preparedIndices = Enumerable.Range(0, prepared.Faces.Count).ToList(); @@ -9703,9 +9715,8 @@ void AddIncident((long X, long Y, long Z) vertex, } if (!contracted) return false; - var finalFaces = PrepareFaces(); - retainedSourceIndices.AddRange(finalFaces.Sources); - var contractedFaces = finalFaces.Faces; + retainedSourceIndices.AddRange(prepared.Sources); + var contractedFaces = prepared.Faces; bool oriented = contractedFaces.Count >= 4 && TryOrientExactFacetedShell(contractedFaces, Enumerable.Range(0, contractedFaces.Count).ToList(), out orientedFaces); @@ -63625,7 +63636,7 @@ private static void ExportStairOccurrenceCommonPropertySet( string ifcType, int referenceValueId, IReadOnlyDictionary elementsById, IReadOnlyDictionary elementIdOccurrenceCounts, - Dictionary<(string PropertyName, string ValueExpr), int> valuePool, bool currentProfile = false) + Dictionary<(string PropertyName, string ValueExpr), int> valuePool, Dictionary> stairRuns, bool currentProfile) { (string psetName, string seedPrefix) = ifcType switch { @@ -63694,9 +63705,9 @@ private static void ExportStairOccurrenceCommonPropertySet( } } if (ifcType == "IFCSTAIRFLIGHT") - AddStairFlightProperties(w, elem, elementsById, valueIds, currentProfile); + AddStairFlightProperties(w, elem, elementsById, valueIds, currentProfile, stairRuns); else if (ifcType == "IFCSTAIR" && stairType != null) - AddStairTreadCount(w, elem, elementsById, stairType, valueIds, currentProfile); + AddStairTreadCount(w, elem, elementsById, stairType, valueIds, stairRuns, currentProfile); int psetId = w.Add("IFCPROPERTYSET", $"{S(IfcGuid.FromName($"{seedPrefix}-pset:{elem.Id}"))},{R(ownerHistId)},{S(psetName)},$,{StepWriter.List(valueIds.Select(R))}"); w.Add("IFCRELDEFINESBYPROPERTIES", @@ -63712,12 +63723,13 @@ private static int StairRunRisers(Element run, TfBlockDeserializer.StairRunNumbe StairRunIndexSpan(numbers) - (current && run.SerializedStairRunInput?.Style == TfBlockDeserializer.StairRunStyle.Sketched && numbers.EndWithRiser == 0 ? 1 : 0); private static bool StairRunCountsAgree(Element run, IReadOnlyDictionary elementsById, - TfBlockDeserializer.StairRunNumbers numbers, bool current = false) + TfBlockDeserializer.StairRunNumbers numbers, bool current, Dictionary>? stairRuns) { int stairsId = run.SerializedStairRunInput!.StairsId; if (!elementsById.TryGetValue(stairsId, out var stairs) || stairs.SerializedActualNumberOfRisers is not int stored) return true; - int runsOfStairs = elementsById.Values.Count(other => other.SerializedStairRunInput?.StairsId == stairsId); + int runsOfStairs = stairRuns == null ? elementsById.Values.Count(other => other.SerializedStairRunInput?.StairsId == stairsId) + : stairRuns.GetValueOrDefault(stairsId)?.Count ?? 0; return runsOfStairs != 1 || stored == StairRunRisers(run, numbers, current); } @@ -63730,14 +63742,15 @@ numbers.BeginWithRiser is 0 or 1 && numbers.EndWithRiser is 0 or 1 /// Pset_StairCommon.NumberOfTreads of a stair: the sum of the tread counts of its runs. /// private static void AddStairTreadCount(StepWriter w, Element stair, - IReadOnlyDictionary elementsById, Element stairType, List valueIds, bool current = false) + IReadOnlyDictionary elementsById, Element stairType, List valueIds, Dictionary> stairRuns, bool current) { if (HasStairCommonOverrideCandidate(stair, stairType, "NumberOfTreads", "Pset_StairCommon")) return; int treads = 0, runs = 0; - foreach (var run in elementsById.Values) + if (!stairRuns.TryGetValue(stair.Id, out var owned)) return; + foreach (var run in owned) { if (run.SerializedStairRunInput is not { Numbers: { } numbers } input || input.StairsId != stair.Id) continue; - if (!StairRunCountsAgree(run, elementsById, numbers, current) || StairRunTreads(run, numbers, current) is not int runTreads) return; + if (!StairRunCountsAgree(run, elementsById, numbers, current, stairRuns) || StairRunTreads(run, numbers, current) is not int runTreads) return; treads += runTreads; runs++; } if (runs == 0 || treads <= 0) return; @@ -63767,7 +63780,7 @@ private static void AddStairTreadCount(StepWriter w, Element stair, /// run type, the walking line offset (half the run width. /// private static void AddStairFlightProperties(StepWriter w, Element run, - IReadOnlyDictionary elementsById, List valueIds, bool currentProfile = false) + IReadOnlyDictionary elementsById, List valueIds, bool currentProfile, Dictionary> stairRuns) { if (run.SerializedStairRunInput is not { Numbers: { } numbers } input || input.OwnerId != run.Id || !elementsById.TryGetValue(run.FamilyTypeId > 0 ? run.FamilyTypeId : run.TypeId, out var runType) @@ -63781,7 +63794,7 @@ private static void AddStairFlightProperties(StepWriter w, Element run, string Length(string measure, double millimetres) => $"{measure}({D17(millimetres)})"; int risers = StairRunIndexSpan(numbers), countedRisers = StairRunRisers(run, numbers, currentProfile); - bool countsAgree = StairRunCountsAgree(run, elementsById, numbers, currentProfile); + bool countsAgree = StairRunCountsAgree(run, elementsById, numbers, currentProfile, stairRuns); if (countsAgree && countedRisers > 0 && Free("NumberOfRiser")) Add("NumberOfRiser", $"IFCCOUNTMEASURE({D17(countedRisers)})"); if (countsAgree && Free("NumberOfTreads") && StairRunTreads(run, numbers, currentProfile) is int treads && treads > 0) Add("NumberOfTreads", $"IFCCOUNTMEASURE({D17(treads)})"); diff --git a/src/RvtIO/Internal/JsonReadFacts.cs b/src/RvtIO/Internal/JsonReadFacts.cs new file mode 100644 index 00000000..7ff1d38e --- /dev/null +++ b/src/RvtIO/Internal/JsonReadFacts.cs @@ -0,0 +1,66 @@ +using RvtIO.Parsing; + +namespace RvtIO.Internal; + +/// Decoded sources of validated element names and stored JSON parameter values. +internal class JsonReadFacts +{ + /// First block class ID (low 16 bits) seen per element in the continuous walk. + public Dictionary ElemClassIdx { get; } = new(); + /// The file's own schema, or null for the shipped 2022 layout. + public FileSchema? WideSchema { get; set; } + /// The element's own name from its root in the file's schema. + public Dictionary WideNames { get; } = new(); + /// Authoritative name-table entries, indexed by named element (not holder). + public Dictionary ElementNameTable { get; set; } = new(); + /// Own FamilySymbol SymbolInfo name; every Symbol subclass root counts. + public Dictionary FamilySymbolNames { get; } = new(); + /// Own RoofAttributes/StairsRailingAttr names; all Symbol roots count. + public Dictionary RoofOrRailingTypeNames { get; } = new(); + /// Every Symbol root counts; duplicates invalidate the class and discriminator. + public Dictionary SystemTypeRoots { get; } = new(); + /// Own CompoundStructure fields and SymbolInfo name; all HostObjAttr roots count. + public Dictionary + HostTypeCompoundStructures { get; } = new(); + /// Native m_pParamValueSet stores and captured fields by element. + public Dictionary NativeParams { get; set; } = new(); + + internal readonly record struct JsonStores( + TfBlockDeserializer.NativeRows<(int ParamId, double Value)> Doubles, + TfBlockDeserializer.NativeRows NamedParams, string? LevelName); + private readonly Dictionary? _stores; + + internal JsonStores StoresOf(uint id) => _stores != null ? _stores.GetValueOrDefault(id) + : NativeParams.TryGetValue(id, out var native) ? Stores(native, true) : default; + + private static JsonStores Stores(TfBlockDeserializer.NativeParams native, bool withValues) => + new(withValues ? native.Doubles : default, withValues ? native.NamedParams : default, + native.Fields.ContainsKey("__isLevel") ? native.StringFields.GetValueOrDefault("m_text") : null); + + protected JsonReadFacts() { } + + // Keep these maps, but not the partition buffers, the record index or the geometry decoder. + internal JsonReadFacts(JsonReadFacts facts, bool withValues, bool debugNative = false) + { + ElemClassIdx = facts.ElemClassIdx; + WideSchema = facts.WideSchema; + WideNames = facts.WideNames; + ElementNameTable = facts.ElementNameTable; + FamilySymbolNames = facts.FamilySymbolNames; + RoofOrRailingTypeNames = facts.RoofOrRailingTypeNames; + SystemTypeRoots = facts.SystemTypeRoots; + HostTypeCompoundStructures = facts.HostTypeCompoundStructures; + if (debugNative) + NativeParams = facts.NativeParams; + else + { + _stores = new(); + foreach (var (id, native) in facts.NativeParams) + { + var held = Stores(native, withValues); + if (held.Doubles.Count != 0 || held.NamedParams.Count != 0 || held.LevelName != null) + _stores.Add(id, held); + } + } + } +} diff --git a/src/RvtIO/Internal/ParsingState.cs b/src/RvtIO/Internal/ParsingState.cs index 68cb265d..055bc12f 100644 --- a/src/RvtIO/Internal/ParsingState.cs +++ b/src/RvtIO/Internal/ParsingState.cs @@ -2,7 +2,7 @@ namespace RvtIO.Internal; -internal class ParsingState +internal class ParsingState : JsonReadFacts { public Dictionary? OwnPartitionWallParts { get; set; } public Dictionary OwnWallSide0Ids { get; } = new(); @@ -83,10 +83,6 @@ public TfBlockDeserializer.UnitsElemOptions? OwnDocumentUnitOptions return null; } - /// First block classId (low16) seen per element in the continuous walk. Used to - /// assign category from the empirical high-purity classIdx->category table, applied late. - public Dictionary ElemClassIdx { get; } = new(); - /// ElementHeader.m_categroryId of the element records the continuous walk accepted (see ); /// a null value marks an id whose records disagree or whose header could not be read. public Dictionary HeaderCategories { get; } = new(); @@ -101,11 +97,7 @@ public TfBlockDeserializer.UnitsElemOptions? OwnDocumentUnitOptions /// a verdict when the records agree it is there or agree there is none, null when they disagree or no record was read. public Dictionary HeaderBoundingBoxes { get; } = new(); - /// The file's own class schema when its element ids are 64-bit (Revit 2025 layout, see ); - /// null for the 32-bit layouts, which keep the shipped Revit 2022 tables. - public Parsing.FileSchema? WideSchema { get; set; } - - /// The partition chunks of this file were rewritten into the Revit 2022 layout (), + /// The partition chunks of this file were rewritten into the Revit 2022 layout (), /// so the 2022 record, block and geometry readers apply to them. public bool R22View { get; set; } @@ -132,16 +124,13 @@ public TfBlockDeserializer.UnitsElemOptions? OwnDocumentUnitOptions /// instead of scanning the partition chunks. internal bool ReadsFramedRecords => (WideSchema == null || R22View) && FramedPartitions is { Count: > 0 } framed && framed.All(f => f is { IdWidth: 4 }); - /// The own name of an element of a file, read from its root block by the schema-driven walk. - public Dictionary WideNames { get; } = new(); - /// The bars of the reinforcement elements (Rebar, RebarInSystem) by element id, read by . public Dictionary RebarBars { get; } = new(); /// The beam systems (JoistSystem) by element id, read by . public Dictionary JoistSystems { get; } = new(); - /// Schema name of the Element-derived root class per element id, filled only for files. + /// Schema name of the Element-derived root class per element id, filled only for files. public Dictionary NativeRootClassNames { get; } = new(); /// Local worksharing username from BasicFileInfo ("Username: ..."); null when not @@ -157,7 +146,8 @@ public TfBlockDeserializer.UnitsElemOptions? OwnDocumentUnitOptions 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 System.Collections.Concurrent.ConcurrentDictionary>? SymbolPlacementGeometry { get; set; } + internal Dictionary? ReaderParameterDefinitions { get; set; } internal Dictionary RailingQuantityInputs { get; } = new(); public Dictionary OwnWallPlanarBodies { get; } = new(); @@ -239,17 +229,9 @@ public TfBlockDeserializer.UnitsElemOptions? OwnDocumentUnitOptions /// Semantic Element kind/owner prefix, independent of display names /// and later subtype fields. Every Element root counts against target uniqueness. public Dictionary ComputedSymbolTargetClasses { get; } = new(); - /// Own FamilySymbol SymbolInfo name; every Symbol subclass root counts. - public Dictionary FamilySymbolNames { get; } = new(); /// Own roof/railing attribute links; all HostObject/BaseRailing roots count. public Dictionary RoofOrRailingTypeIds { get; } = new(); - /// Own RoofAttributes/StairsRailingAttr names; all Symbol roots count. - public Dictionary RoofOrRailingTypeNames { get; } = new(); - - /// Own Symbol-subclass roots: every root counts; only a well-formed own root - /// records its class and family discriminator. Duplicates clear both. - public Dictionary SystemTypeRoots { get; } = new(); /// Own StairsRunType/StairsLandingType/StairsSupportType SymbolInfo names. SystemTypeRoots /// separately counts every Symbol root, including unsupported/conflicting classes. @@ -332,12 +314,6 @@ public TfBlockDeserializer.UnitsElemOptions? OwnDocumentUnitOptions public Dictionary CeilingCompoundStructureLayerSource { get; set; } = new(); - /// Own HostObjAttr CompoundStructure fields and own SymbolInfo name. - /// Deferred objects after these records are not part of this metadata validation. - /// Every HostObjAttr root counts, including unsupported/malformed/duplicate roots. - public Dictionary - HostTypeCompoundStructures { get; } = new(); - /// Own bounded class-646 CEILING_THICKNESS getter result in internal feet. /// HostTypeCompoundStructures and SystemTypeRoots retain all ambiguity counts. public Dictionary CompoundCeilingTypeThicknessFeet { get; } = new(); @@ -408,9 +384,6 @@ public TfBlockDeserializer.UnitsElemOptions? OwnDocumentUnitOptions /// detail arcs the GInfoBlob pattern scan can't reach). public Dictionary CurveGeometry { get; set; } = new(); - /// Native parameter stores per element, deserialized from the Element base - /// class m_pParamValueSet* containers (schema-driven). - public Dictionary NativeParams { get; set; } = new(); /// Elements whose NativeParams came from a block of their own ElemTable class (the element root). public HashSet NativeParamsFromRootClass { get; } = new(); @@ -530,11 +503,6 @@ internal bool IsParameterElement(uint id) => OwnedElementClassRoots.TryGetValue( /// Element names extracted natively from 0xFFFF blocks (SymbolInfo.Name equivalent). public Dictionary NativeElementNames { get; set; } = new(); - /// Authoritative element names from name-table entries. - /// Pattern: [01][holderEid][FF x28][01][targetId][len][UTF-16 name][catId][parentHolderId|GUID]. - /// Maps NAMED element id (targetId) -> name. - public Dictionary ElementNameTable { get; set; } = new(); - /// Name-holder element -> named element. The holder is the small companion /// element that owns the name-table block (often targetId+1). public Dictionary NameHolderTarget { get; set; } = new(); diff --git a/src/RvtIO/Model/Geometry.cs b/src/RvtIO/Model/Geometry.cs index 1652a0f2..1f262c5d 100644 --- a/src/RvtIO/Model/Geometry.cs +++ b/src/RvtIO/Model/Geometry.cs @@ -230,11 +230,16 @@ internal GeoFace(double[] origin, double[] normal, bool includePlaneAxes = true) /// An edge connecting two 3D points. public class GeoEdge { + /// Creates an edge with two independent zero-valued points. + public GeoEdge() : this(new double[3], new double[3]) { } + + internal GeoEdge(double[] start, double[] end) => (Start, End) = (start, end); + /// Start point [x, y, z] in feet. - public double[] Start { get; set; } = new double[3]; + public double[] Start { get; set; } /// End point [x, y, z] in feet. - public double[] End { get; set; } = new double[3]; + public double[] End { get; set; } } /// diff --git a/src/RvtIO/Model/Parameter.cs b/src/RvtIO/Model/Parameter.cs index b4d22333..a0abd679 100644 --- a/src/RvtIO/Model/Parameter.cs +++ b/src/RvtIO/Model/Parameter.cs @@ -23,11 +23,12 @@ internal sealed class DefinitionData(int id, string? name, string? builtInParame internal sealed record DisplayUnits(string? SpecType, string? Symbol, double? Factor); private static readonly DisplayUnits NoDisplayUnits = new(null, null, null); + private static readonly DefinitionData EmptyDefinition = new(0, null); private object? _definition; private DisplayUnits? _displayUnits; /// Creates a parameter with its own empty definition. - public Parameter() => _definition = new Definition(); + public Parameter() => _definition = EmptyDefinition; internal Parameter(Definition definition) => _definition = definition; internal Parameter(DefinitionData definition) @@ -418,7 +419,19 @@ public long AsElementId64() => [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public string? SourceElementId => NativeElementId?.ToString(CultureInfo.InvariantCulture); - internal long? NativeElementId { get; set; } + // Keep the presence flag alongside the other flags, rather than a padded + // Nullable on every parameter. Zero and long.MinValue are both representable. + private bool _hasNativeElementId; + private long _nativeElementId; + internal long? NativeElementId + { + get => _hasNativeElementId ? _nativeElementId : null; + set + { + _nativeElementId = value.GetValueOrDefault(); + _hasNativeElementId = value.HasValue; + } + } /// /// Get a formatted display string for the value. diff --git a/src/RvtIO/Model/ParameterListConverter.cs b/src/RvtIO/Model/ParameterListConverter.cs index 4ba42d84..e216b620 100644 --- a/src/RvtIO/Model/ParameterListConverter.cs +++ b/src/RvtIO/Model/ParameterListConverter.cs @@ -13,6 +13,18 @@ namespace RvtIO.Model /// public class ParameterListConverter : JsonConverter> { + private readonly Dictionary? _keys; + + /// Writes values using the caller's serializer options and converters. + public ParameterListConverter() { } + + // The CLI's full dump uses fixed JSON options and knows every parameter key before writing. + internal ParameterListConverter(IEnumerable definitionIds, System.Text.Encodings.Web.JavaScriptEncoder encoder) + { + _keys = definitionIds.ToDictionary(id => id, id => JsonEncodedText.Encode( + id.ToString(System.Globalization.CultureInfo.InvariantCulture), encoder)); + } + /// public override List Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) => throw new NotSupportedException("ParameterListConverter is write-only."); @@ -27,11 +39,14 @@ public override void Write(Utf8JsonWriter writer, List value, JsonSer // First occurrence wins (matches Element.LookupParameter semantics) so a // rare duplicate id does not produce an invalid repeated JSON property. if (!seen.Add(p.Id)) continue; - writer.WritePropertyName(p.Id.ToString(System.Globalization.CultureInfo.InvariantCulture)); + if (_keys != null && _keys.TryGetValue(p.Id, out var key)) + writer.WritePropertyName(key); + else writer.WritePropertyName(p.Id.ToString(System.Globalization.CultureInfo.InvariantCulture)); if (p.SourceElementId is string sourceId) writer.WriteStringValue(sourceId); - else - JsonSerializer.Serialize(writer, p.Value, options); + else if (_keys != null && p.Value is int integer) writer.WriteNumberValue(integer); + else if (_keys != null && p.Value is string text) writer.WriteStringValue(text); + else JsonSerializer.Serialize(writer, p.Value, options); } writer.WriteEndObject(); } diff --git a/src/RvtIO/Parsing/ElementBuilder.cs b/src/RvtIO/Parsing/ElementBuilder.cs index 491ac648..d14aa112 100644 --- a/src/RvtIO/Parsing/ElementBuilder.cs +++ b/src/RvtIO/Parsing/ElementBuilder.cs @@ -254,16 +254,14 @@ static int MostFrequent(IEnumerable values) => values.GroupBy(value => valu var cache = state.SymbolPlacementGeometry; GeometryData? own; - if (cache == null) own = BuildLocalFaces(); + if (symbol.Faces.Count == 0) own = null; + else if (cache == null) own = BuildGeometryData(symbol, state.SeparateFacesWithDistinctOpenings, includeEdgesAndInstances: false); 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); - } + // Only placements of the same representation wait for its local faces. + own = cache.GetOrAdd(symbol, static (block, separate) => new Lazy( + () => BuildGeometryData(block, separate, includeEdgesAndInstances: false)), + state.SeparateFacesWithDistinctOpenings).Value; } if (own?.Faces is { Count: > 0 }) { @@ -284,9 +282,6 @@ static int MostFrequent(IEnumerable values) => values.GroupBy(value => valu if (detail != GeometryDetail.CoarseQuantities) SetGeometryBoundsFromFaces(result); return result; - GeometryData? BuildLocalFaces() => symbol.Faces.Count > 0 - ? BuildGeometryData(symbol, state.SeparateFacesWithDistinctOpenings, includeEdgesAndInstances: false) - : null; } finally { @@ -864,11 +859,7 @@ int GetOrAddVertex(double x, double y, double z) int AddEdge(int v0, int v1) { int idx = geo.Edges!.Count; - geo.Edges.Add(new GeoEdge - { - Start = geo.Vertices![v0], - End = geo.Vertices[v1], - }); + geo.Edges.Add(new GeoEdge(geo.Vertices![v0], geo.Vertices[v1])); return idx; } @@ -923,10 +914,8 @@ List EnvelopeToCorners(double[] env, double[] origin, double[] xv, dou } seenFaces[key] = geo.Faces.Count; } - var gf = new GeoFace + var gf = new GeoFace(fp.Origin, fp.XVector) // V2 stores the polygon normal in XVector. { - Origin = fp.Origin, - Normal = fp.XVector, // V2 stashes the polygon normal here OuterVertices = poly, InnerVertices = fp.InnerVertices, AlternativeOuterVertices = fp.AlternativeOuterVertices, @@ -977,12 +966,10 @@ List EnvelopeToCorners(double[] env, double[] origin, double[] xv, dou fp.XVector[2] * fp.YVector[0] - fp.XVector[0] * fp.YVector[2], fp.XVector[0] * fp.YVector[1] - fp.XVector[1] * fp.YVector[0], }; - var geoFace = new GeoFace + var geoFace = new GeoFace(fp.Origin, normal, includePlaneAxes: false) { - Origin = fp.Origin, XVector = fp.XVector, YVector = fp.YVector, - Normal = normal, Envelope = fp.Envelope, RenderStyleId = fp.RenderStyleId, GeometryNode = fp.GeometryNode, @@ -3645,22 +3632,12 @@ void ApplyType(int typeId) existing.HasNoRevitValue = namedUnset; continue; } - string? namedForge = null, namedName = null; - if (state.ForgeParamDefs.TryGetValue((uint)named.ParamId, out var namedDef)) - (namedForge, namedName) = namedDef; - e.Parameters.Add(new Parameter - { - Id = named.ParamId, - StorageType = namedStorage, - Value = namedValue, - HasNoRevitValue = namedUnset, - IsReadOnly = false, - ForgeId = namedForge, - Guid = state.ParamDefGuids.TryGetValue((uint)named.ParamId, out var namedGuid) - ? namedGuid : BipHelpers.ParseGuidFromForgeId(namedForge), - Definition = new Definition { Id = named.ParamId, Name = namedName }, - }); - byId[named.ParamId] = e.Parameters[^1]; + var parameter = CreateUserParameter((uint)named.ParamId, state); + parameter.StorageType = namedStorage; + parameter.Value = namedValue; + parameter.HasNoRevitValue = namedUnset; + e.Parameters.Add(parameter); + byId[named.ParamId] = parameter; } // Parameters stored verbatim in a schema field. NativeFieldParameters.CollectPresentRows(np, nativeFieldRows, nativeFieldValues); @@ -5143,18 +5120,17 @@ internal static void ApplyValidatedDistributionTypeReferenceNames(IReadOnlyList< /// Attaches the own-root top-attachment flag to each uniquely materialized wall whose single /// SWall/ArcWall root was read exactly. Returns how many walls received a value. /// - internal static int ApplyWallJoinedToTop(IReadOnlyList elements, ParsingState state) + internal static int ApplyWallJoinedToTop(IReadOnlyList elements, ParsingState state, + IReadOnlyDictionary? unique = null) { - var counts = new Dictionary(); - foreach (Element element in elements) - counts[element.Id] = counts.GetValueOrDefault(element.Id) + 1; + unique ??= BuildUniqueElementIndex(elements); int applied = 0; foreach (Element element in elements) { element.SerializedWallJoinedToTop = null; if (element.Id <= 0 || element.CategoryId != -2000011 - || counts[element.Id] != 1 + || !unique.ContainsKey(element.Id) || !state.WallJoinedToTop.TryGetValue((uint)element.Id, out var source) || source.BlockCount != 1 || source.JoinedToTop is not bool joinedToTop) @@ -5204,18 +5180,17 @@ internal static (int Elements, int ReplacedUniqueIds) ApplyExportIds( /// Attaches the exact control joins of each uniquely materialized wall's own driver (). /// - internal static int ApplyWallEndJoins(IReadOnlyList elements, ParsingState state) + internal static int ApplyWallEndJoins(IReadOnlyList elements, ParsingState state, + IReadOnlyDictionary? unique = null) { - var counts = new Dictionary(); - foreach (Element element in elements) - counts[element.Id] = counts.GetValueOrDefault(element.Id) + 1; + unique ??= BuildUniqueElementIndex(elements); int applied = 0; foreach (Element element in elements) { element.SerializedWallEndJoins = null; if (element.Id <= 0 || element.CategoryId != -2000011 - || counts[element.Id] != 1 + || !unique.ContainsKey(element.Id) || !state.WallEndJoins.TryGetValue((uint)element.Id, out var source) || source.BlockCount != 1 || source.Joins is not { } joins) @@ -5231,17 +5206,15 @@ internal static int ApplyWallEndJoins(IReadOnlyList elements, ParsingSt /// CompoundStructure layers to uniquely materialized OST_Ceilings types. /// internal static (int Materials, int CeilingTypes) ApplyCeilingFinishSource( - IReadOnlyList elements, ParsingState state) + IReadOnlyList elements, ParsingState state, IReadOnlyDictionary? unique = null) { - var counts = new Dictionary(); - foreach (Element element in elements) - counts[element.Id] = counts.GetValueOrDefault(element.Id) + 1; + unique ??= BuildUniqueElementIndex(elements); int materials = 0, ceilingTypes = 0; foreach (Element element in elements) { element.SerializedMaterialName = null; element.SerializedCeilingTypeLayers = null; - if (element.Id <= 0 || counts[element.Id] != 1) continue; + if (element.Id <= 0 || !unique.ContainsKey(element.Id)) continue; if (state.MaterialNames.TryGetValue((uint)element.Id, out var material) && material.BlockCount == 1 && material.Name != null) { @@ -5281,19 +5254,16 @@ private static bool TryGetAgreedHostType(Element element, int occurrences, Parsi }; } - internal static int ApplyHostTypeCompoundStructures(IReadOnlyList elements, ParsingState state) + internal static int ApplyHostTypeCompoundStructures(IReadOnlyList elements, ParsingState state, + IReadOnlyDictionary? unique = null) { - var counts = new Dictionary(); + unique ??= BuildUniqueElementIndex(elements); + int applied = 0; foreach (var element in elements) { element.SerializedHostTypeLayers = null; element.ValidatedHostTypeLayerSetName = null; - counts[element.Id] = counts.GetValueOrDefault(element.Id) + 1; - } - int applied = 0; - foreach (var element in elements) - { - if (!TryGetAgreedHostType(element, counts[element.Id], state, out var validation)) continue; + if (!unique.ContainsKey(element.Id) || !TryGetAgreedHostType(element, 1, state, out var validation)) continue; element.SerializedHostTypeLayers = validation.Layers; if (!string.IsNullOrWhiteSpace(validation.TypeName) && !string.IsNullOrEmpty(element.ValidatedSystemFamilyName)) element.ValidatedHostTypeLayerSetName = $"{element.ValidatedSystemFamilyName}:{validation.TypeName}"; @@ -7637,6 +7607,7 @@ private static uint CollectFamilySymbolCandidates(Element element, Dictionary /// private static void CoerceParamStorageByForge(RevitFileInfo rvtInfo, ParsingState? state) { + var byForgeId = new Dictionary(StringComparer.Ordinal); foreach (var e in rvtInfo.Elements) { foreach (var p in e.Parameters) @@ -7653,38 +7624,37 @@ private static void CoerceParamStorageByForge(RevitFileInfo rvtInfo, ParsingStat } var fid = p.ForgeId; if (string.IsNullOrEmpty(fid)) continue; - bool isStringSpec = fid.Contains("spec.string") || fid.Contains("string:url"); - bool isBoolSpec = fid.Contains("spec.bool") || fid.Contains("spec:bool"); - bool isNumericSpec = fid.Contains("spec.aec:") || fid.Contains("spec.number") - || fid.Contains("spec:length") || fid.Contains("spec:area") - || fid.Contains("spec:volume") || fid.Contains("spec.int"); - bool isEmptyPlaceholder = p.Value == null || (p.Value is string s && (string.IsNullOrEmpty(s) || s == "-1")) || (p.Value is int iv && (iv == 0 || iv == -1)) || (p.Value is double dv && dv == 0.0); if (!isEmptyPlaceholder) continue; + if (!byForgeId.TryGetValue(fid, out var spec)) + byForgeId[fid] = spec = (fid.Contains("spec.string") || fid.Contains("string:url"), + fid.Contains("spec.bool") || fid.Contains("spec:bool"), + fid.Contains("spec.aec:") || fid.Contains("spec.number") || fid.Contains("spec:length") + || fid.Contains("spec:area") || fid.Contains("spec:volume") || fid.Contains("spec.int")); bool wasNoRevitValue = p.HasNoRevitValue || p.Value == null || (p.Value is string ps && ps == "-1") || (p.Value is int piv && piv == -1); - if (isStringSpec && p.StorageType != StorageType.String) + if (spec.Text && p.StorageType != StorageType.String) { p.StorageType = StorageType.String; p.Value = ""; if (wasNoRevitValue) p.HasNoRevitValue = true; } - else if (isBoolSpec && p.StorageType != StorageType.Integer) + else if (spec.Boolean && p.StorageType != StorageType.Integer) { p.StorageType = StorageType.Integer; - p.Value = 0; + p.Value = Parameter.BoxParsedValue(0); if (wasNoRevitValue) p.HasNoRevitValue = true; } - else if (isNumericSpec && p.StorageType == StorageType.String) + else if (spec.Numeric && p.StorageType == StorageType.String) { p.StorageType = StorageType.Double; - p.Value = 0.0; + p.Value = Parameter.BoxParsedValue(0.0); if (wasNoRevitValue) p.HasNoRevitValue = true; } } @@ -7697,9 +7667,8 @@ private static FamilyParameterDefinition FamilyDefinition(uint id, ParsingState 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); + var (data, forgeId) = DefinitionOf(id, state); + definition = new(data, forgeId); definitions.Add(id, definition); return definition; } @@ -7815,29 +7784,20 @@ private static void ApplyTypeStrings(Element e, Dictionary typeStri var p = FindParameterById(e.Parameters, projKey); if (p == null) { - string? forgeId = null, dn = null; - Guid? guid = null; - if (projKey > 0 && state.ForgeParamDefs.TryGetValue((uint)projKey, out var def)) - { forgeId = def.ForgeId; dn = def.DisplayName; } - if (projKey > 0 && state.ParamDefGuids.TryGetValue((uint)projKey, out var binGuid)) guid = binGuid; - else guid = BipHelpers.ParseGuidFromForgeId(forgeId); - if (dn == null && projKey < 0 && Lookup.BipNames.Lookup.TryGetValue(projKey, out var bipName)) - dn = bipName; - e.Parameters.Add(new Parameter + if (projKey > 0) { - Id = projKey, - StorageType = StorageType.String, - Value = value, - IsReadOnly = projKey < 0 && BipHelpers.IsBipReadOnly(dn), - ForgeId = forgeId, - Guid = guid, - Definition = new Definition - { - Id = projKey, - Name = dn, - BuiltInParameter = projKey < 0 ? dn : null, - }, - }); + var parameter = CreateUserParameter((uint)projKey, state); + parameter.StorageType = StorageType.String; + parameter.Value = value; + e.Parameters.Add(parameter); + } + else + { + string? name = projKey < 0 ? Lookup.BipNames.Lookup.GetValueOrDefault(projKey) : null; + var parameter = BipHelpers.MakeBipParam(projKey, name, StorageType.String, value); + parameter.IsReadOnly = projKey < 0 && BipHelpers.IsBipReadOnly(name); + e.Parameters.Add(parameter); + } } else { @@ -8798,6 +8758,34 @@ private static void ComputeWallSolids(List elements) } + // The field and GUID maps are complete before building elements in parallel. Share the + // immutable metadata, not the Parameter or its publicly editable Definition. + internal static Dictionary ReaderParameterDefinitions(ParsingState state) + { + var definitions = new Dictionary(state.ForgeParamDefs.Count); + foreach (uint id in state.ForgeParamDefs.Keys) definitions.Add(id, ReadDefinition(id, state)); + foreach (var (id, guid) in state.ParamDefGuids) + if (!definitions.ContainsKey(id)) definitions.Add(id, (new((int)id, null, guid: guid), null)); + return definitions; + } + + private static (Parameter.DefinitionData, string?) ReadDefinition(uint id, ParsingState state) + { + var (forgeId, name) = state.ForgeParamDefs.GetValueOrDefault(id); + Guid? guid = state.ParamDefGuids.TryGetValue(id, out var stored) ? stored : BipHelpers.ParseGuidFromForgeId(forgeId); + return (new((int)id, name, guid: guid), forgeId); + } + + private static (Parameter.DefinitionData, string?) DefinitionOf(uint id, ParsingState state) => + state.ReaderParameterDefinitions?.TryGetValue(id, out var definition) == true + ? definition : ReadDefinition(id, state); + + private static Parameter CreateUserParameter(uint id, ParsingState state) + { + var (data, forgeId) = DefinitionOf(id, state); + return new Parameter(data) { Id = (int)id, ForgeId = forgeId }; + } + private static void AddBodyBipParams(Element elem, ElementRecord rec, uint elemId, ParsingState state, HashSet seenIds) { if (rec.BipParams.Count == 0) return; @@ -8805,7 +8793,7 @@ private static void AddBodyBipParams(Element elem, ElementRecord rec, uint elemI { if (b.BipId == 0 || !seenIds.Add(b.BipId)) continue; var param = b.BipId < 0 ? BipHelpers.MakeBipParam(b.BipId, b.BipName, null, null) - : new Parameter { Id = b.BipId, StorageType = StorageType.None }; + : CreateUserParameter((uint)b.BipId, state); if (b.BipId < 0) { @@ -8870,18 +8858,6 @@ private static void AddBodyBipParams(Element elem, ElementRecord rec, uint elemI } else { - string? forgeId = null, displayName = null; - Guid? paramGuid = null; - if (state.ForgeParamDefs.TryGetValue((uint)b.BipId, out var def)) - { forgeId = def.ForgeId; displayName = def.DisplayName; } - if (state.ParamDefGuids.TryGetValue((uint)b.BipId, out var binGuid)) - paramGuid = binGuid; - else - paramGuid = BipHelpers.ParseGuidFromForgeId(forgeId); - param.ForgeId = forgeId; - param.Guid = paramGuid; - 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)) @@ -8906,24 +8882,11 @@ private static void AddUserParams(Element elem, ElementRecord rec, uint elemId, foreach (var (paramDefId, strVal) in paramStrMap) { if (!existingIds.Add((int)paramDefId)) continue; - string? forgeId = null, displayName = null; - Guid? paramGuid = null; - if (state.ForgeParamDefs.TryGetValue(paramDefId, out var def)) - { forgeId = def.ForgeId; displayName = def.DisplayName; } - if (state.ParamDefGuids.TryGetValue(paramDefId, out var binGuid)) - paramGuid = binGuid; - else - paramGuid = BipHelpers.ParseGuidFromForgeId(forgeId); - elem.Parameters.Add(new Parameter - { - Id = (int)paramDefId, - StorageType = StorageType.String, - Value = strVal, - IsReadOnly = rec.WritableParamIds?.Contains((int)paramDefId) != true, - ForgeId = forgeId, - Guid = paramGuid, - Definition = new Definition { Id = (int)paramDefId, Name = displayName }, - }); + var parameter = CreateUserParameter(paramDefId, state); + parameter.StorageType = StorageType.String; + parameter.Value = strVal; + parameter.IsReadOnly = rec.WritableParamIds?.Contains((int)paramDefId) != true; + elem.Parameters.Add(parameter); } } @@ -8940,20 +8903,10 @@ private static void AddBipDoubles(Element elem, uint elemId, ParsingState state, } else { - string? forgeId = null, displayName = null; - Guid? paramGuid = null; - if (state.ForgeParamDefs.TryGetValue((uint)bipKey, out var def)) - { forgeId = def.ForgeId; displayName = def.DisplayName; } - if (state.ParamDefGuids.TryGetValue((uint)bipKey, out var binGuid)) - paramGuid = binGuid; - else - paramGuid = BipHelpers.ParseGuidFromForgeId(forgeId); - elem.Parameters.Add(new Parameter - { - Id = bipKey, StorageType = StorageType.Double, Value = bipVal, - ForgeId = forgeId, Guid = paramGuid, - Definition = new Definition { Id = bipKey, Name = displayName }, - }); + var parameter = CreateUserParameter((uint)bipKey, state); + parameter.StorageType = StorageType.Double; + parameter.Value = Parameter.BoxParsedValue(bipVal); + elem.Parameters.Add(parameter); } } } @@ -8971,21 +8924,10 @@ private static void AddBipInts(Element elem, uint elemId, ParsingState state, Ha } else { - // User integer parameter (positive key = param definition element ID) - string? forgeId = null, displayName = null; - Guid? paramGuid = null; - if (state.ForgeParamDefs.TryGetValue((uint)bipKey, out var def)) - { forgeId = def.ForgeId; displayName = def.DisplayName; } - if (state.ParamDefGuids.TryGetValue((uint)bipKey, out var binGuid)) - paramGuid = binGuid; - else - paramGuid = BipHelpers.ParseGuidFromForgeId(forgeId); - elem.Parameters.Add(new Parameter - { - Id = bipKey, StorageType = StorageType.Integer, Value = bipVal, - ForgeId = forgeId, Guid = paramGuid, - Definition = new Definition { Id = bipKey, Name = displayName }, - }); + var parameter = CreateUserParameter((uint)bipKey, state); + parameter.StorageType = StorageType.Integer; + parameter.Value = Parameter.BoxParsedValue(bipVal); + elem.Parameters.Add(parameter); } } } diff --git a/src/RvtIO/Parsing/GRepParserV2.cs b/src/RvtIO/Parsing/GRepParserV2.cs index 4b660ab6..529877d9 100644 --- a/src/RvtIO/Parsing/GRepParserV2.cs +++ b/src/RvtIO/Parsing/GRepParserV2.cs @@ -27,7 +27,8 @@ internal static partial class GRepParserV2 private static double ChordTolerance => TessellationChordToleranceFeet * (t_coarseTessellation ? 16 : 1); private sealed class DecodeStop : Exception { } - private static readonly DecodeStop Stop = new(); + [ThreadStatic] private static DecodeStop? t_stop; + private static DecodeStop Stop => t_stop ??= new(); /// /// Serialized class ids of the Face and Edge objects whose per-block counts feed capture endpoints via schema walk { + if (EdgeHasFixedLayout.Value && TryReadCompleteEdge(c, (uint)v, qi)) return; c.CapEdge = new EdgeRec { Handle = (uint)v, QueueIndex = qi }; foreach (var sf in qf) ReadField(c, sf, 1); if (c.CapEdge.HasEndpoints) c.Edges.Add(c.CapEdge); @@ -1759,6 +1761,59 @@ double[] ReadParameters() } } + private static readonly Lazy EdgeHasFixedLayout = new(() => TfBlockDeserializer.SerializationFields(EdgeClass) is + [{ Declaring: 1246, Name: "m_GInfo", Type: 14, Mods: 0 }, + { Declaring: 1244, Name: "m_pFace", Type: 14, Mods: 19, Cnt: 2 }, + { Declaring: 1244, Name: "m_next", Type: 14, Mods: 19, Cnt: 2 }, + { Declaring: 1244, Name: "m_prev", Type: 14, Mods: 19, Cnt: 2 }, + { Declaring: 1244, Name: "m_interiorEdgePnts", Type: 14, Mods: 80 }, + { Declaring: 1244, Name: "m_firstAndLastEdgePnts", Type: 14, Mods: 16, Cnt: 2, Ref: 1248 }, + { Declaring: 1244, Name: "m_flags", Type: 2, Mods: 0 }]); + + // GNode.m_GInfo, the three handle pairs, the counted UV samples, two endpoints and flags. + // Fall back before consuming anything on a short or invalid item: the recovery walk + // uses the exact position and partial state at which the field reader stops. + private static bool TryReadCompleteEdge(Cur c, uint handle, int queueIndex) + { + const int prefix = 44, sampleSize = 32, tail = 2 * sampleSize + 1; + int start = c.Pos; + if (c.End - start < prefix + tail) return false; + var bytes = c.D.AsSpan(start, c.End - start); + int category = BitConverter.ToInt32(bytes[8..]); + if (category < -3_000_000) return false; + uint count = BitConverter.ToUInt32(bytes[40..]); + if (count == uint.MaxValue) count = 0; + if (count > 100_000 || count > (bytes.Length - prefix - tail) / sampleSize) return false; + int endPoints = prefix + (int)count * sampleSize; + if (handle != 0) + c.ObjectGInfo[(int)handle] = (BitConverter.ToInt32(bytes), BitConverter.ToInt32(bytes[4..]), + category, BitConverter.ToUInt32(bytes[12..])); + // Dry runs discard the entire edge; its fields do not enqueue any children. + if (c.ProbeUndo == null) + { + var edge = new EdgeRec + { + Handle = handle, QueueIndex = queueIndex, HasEndpoints = true, + FaceA = BitConverter.ToUInt32(bytes[16..]), FaceB = BitConverter.ToUInt32(bytes[20..]), + NextA = BitConverter.ToUInt32(bytes[24..]), NextB = BitConverter.ToUInt32(bytes[28..]), + PrevA = BitConverter.ToUInt32(bytes[32..]), PrevB = BitConverter.ToUInt32(bytes[36..]), + Start = System.Runtime.InteropServices.MemoryMarshal.Read(bytes[endPoints..]), + EndP = System.Runtime.InteropServices.MemoryMarshal.Read(bytes[(endPoints + sampleSize)..]), + Flags = bytes[endPoints + 2 * sampleSize], + }; + if (count > 0) + { + System.Runtime.InteropServices.CollectionsMarshal.SetCount(edge.Interior, (int)count); + System.Runtime.InteropServices.MemoryMarshal.Cast(bytes[prefix..endPoints]) + .CopyTo(System.Runtime.InteropServices.CollectionsMarshal.AsSpan(edge.Interior)); + } + c.Edges.Add(edge); + } + c.LastEdgeEnd = c.Pos = start + endPoints + tail; + c.CapEdge = null; + return true; + } + /// /// The serialized control points are homogeneous XYZW records and the full knot vector follows /// them inline. @@ -2306,6 +2361,13 @@ private static void ReadField(Cur c, TfBlockDeserializer.TfField f, int depth) uint n = (uint)c.U32(); if (n == 0xFFFFFFFF) return; if (n > 100000) throw Stop; + // A probe rolls its edge back. UV samples have fixed width and no value-dependent validation. + if (c.ProbeUndo != null) + { + if (32L * n > c.End - c.Pos) throw Stop; + c.Pos += (int)n * 32; + return; + } // Each EdgePnt contains the UV coordinates in both adjacent faces. Every sample is part // of the serialized trim polyline; dropping them collapses a closed circular edge to a // zero-length chord. diff --git a/src/RvtIO/Parsing/TfBlockDeserializer.cs b/src/RvtIO/Parsing/TfBlockDeserializer.cs index b1cffe68..834835db 100644 --- a/src/RvtIO/Parsing/TfBlockDeserializer.cs +++ b/src/RvtIO/Parsing/TfBlockDeserializer.cs @@ -4415,6 +4415,13 @@ private static string ReadString(Cursor c) private static void ReadField(Cursor c, TfField f, List<(ushort, uint)> queue, int depth, NativeParams? capture) { + // Every Element-derived record starts with these same fields. They use the + // ordinary field grammar: no release-specific override is declared on Element. + if (f.Declaring == 37 && depth == 0 && !CaptureAllFields) + { + ReadDeclaredField(c, f, queue, depth, capture); + return; + } if (CaptureAllFields) { diagCurrentField = FieldKey(f); @@ -4630,6 +4637,11 @@ private static void ReadField(Cursor c, TfField f, List<(ushort, uint)> queue, i } if (depth > 40) throw Fail; if (!c.ExactWallCompleteInputs && TryFieldOverride(c, f, queue, depth, capture)) return; + ReadDeclaredField(c, f, queue, depth, capture); + } + + private static void ReadDeclaredField(Cursor c, TfField f, List<(ushort, uint)> queue, int depth, NativeParams? capture) + { int hi = f.Mods >> 4; if (hi == 6) { diff --git a/src/RvtIO/Parsing/WideBlockWalker.cs b/src/RvtIO/Parsing/WideBlockWalker.cs index d574728a..5cebec88 100644 --- a/src/RvtIO/Parsing/WideBlockWalker.cs +++ b/src/RvtIO/Parsing/WideBlockWalker.cs @@ -85,7 +85,7 @@ private sealed class Fail(string message) : Exception(message); internal const string AllItemsKeyPrefix = "all:"; private readonly Dictionary _classes; - private readonly ConcurrentDictionary _chains = new(); + private readonly ConcurrentDictionary _chains = new(); private readonly Func _keyOf; private readonly HashSet _recordClasses; private readonly ConcurrentDictionary<(int, string), string?> _keys = new(); @@ -140,18 +140,38 @@ internal void UseEntitySchemas(IReadOnlyDictionary schemas private readonly ElementIdMap? _ids; - private (SchemaClass Declaring, SchemaField Field)[] Chain(int classId) => _chains.GetOrAdd(classId, id => + private sealed class StoredField(SchemaClass declaring, SchemaField field) + { + internal readonly SchemaClass Declaring = declaring; + internal readonly SchemaField Field = field; + internal readonly string QualifiedName = declaring.Name + "." + field.Name; + private string? _key; + private volatile bool _resolved; + + // Resolve only fields the walk reaches. Different chains can inherit the same field. + internal string? Key(WideBlockWalker walker) + { + if (!_resolved) + { + _key = walker.KeyOf(Declaring, Field); + _resolved = true; + } + return _key; + } + } + + private StoredField[] Chain(int classId) => _chains.GetOrAdd(classId, static (id, classes) => { var order = new List(); for (int guard = 0; id != 0 && guard < 64; guard++) { - if (!_classes.TryGetValue(id, out var c)) throw new Fail("class " + id + " has no schema"); + if (!classes.TryGetValue(id, out var c)) throw new Fail("class " + id + " has no schema"); order.Add(c); id = c.Base; } order.Reverse(); - return order.SelectMany(c => c.Fields.Where(f => f.Stored).Select(f => (c, f))).ToArray(); - }); + return order.SelectMany(c => c.Fields.Where(f => f.Stored).Select(f => new StoredField(c, f))).ToArray(); + }, _classes); /// True when the class derives from (or is) the named class. internal bool IsA(int classId, string baseName) @@ -177,7 +197,11 @@ internal Walk Run(byte[] data, int offset, int size, int classId, Func? record = entityCell ? new EntityFields() : entityFields; if (record == null && _recordClasses.Contains(classId)) record = new(); if (record != null && c.AtRoot) record[RootFieldKey] = c.RootField; - foreach (var (declaring, field) in Chain(classId)) ReadField(c, declaring, field, depth, record); + foreach (var field in Chain(classId)) ReadField(c, field.Declaring, field.Field, field.Key(this), depth, record); if (entityCell) (c.Walk.EntityCells ??= [])[c.QueueIndex] = record!.GetValueOrDefault("m_entityMap"); else if (record != null && entityFields == null) @@ -321,7 +345,7 @@ private void ReadEntityPayload(Context c, int queued, int depth) EntityFields? values = c.Walk.EntityPayloads?.GetValueOrDefault(c.QueueIndex); foreach (var field in _entityLayouts[-1 - queued]!) { - ReadField(c, _entityBlob, field, depth, values); + ReadField(c, _entityBlob, field, KeyOf(_entityBlob, field), depth, values); values?.TryAdd(field.Name, UnavailableEntityValue); } } @@ -351,12 +375,11 @@ private bool QueueEntityPayload(Context c, uint handle, EntityFields? values) return true; } - private void ReadField(Context c, SchemaClass declaring, SchemaField f, int depth, Dictionary? record) + private void ReadField(Context c, SchemaClass declaring, SchemaField f, string? key, int depth, Dictionary? record) { int hi = f.Mods >> 4; c.Declaring = declaring; c.Field = f; - string? key = KeyOf(declaring, f); if (hi == 6) { Scalar(c, declaring, f, key, depth, record, null); @@ -397,8 +420,11 @@ private void ReadField(Context c, SchemaClass declaring, SchemaField f, int dept Scalar(c, declaring, f, key, depth, record, null); } - private string? KeyOf(SchemaClass declaring, SchemaField f) => - _keys.GetOrAdd((declaring.Id, f.Name), _ => _keyOf(declaring, f)); + private string? KeyOf(SchemaClass declaring, SchemaField f) + { + var key = (declaring.Id, f.Name); + return _keys.TryGetValue(key, out var value) ? value : _keys.GetOrAdd(key, _keyOf(declaring, f)); + } private void Scalar(Context c, SchemaClass declaring, SchemaField f, string? key, int depth, Dictionary? record, object? unused) { diff --git a/src/RvtIO/Parsing/WideElementRecords.cs b/src/RvtIO/Parsing/WideElementRecords.cs index 54ea0612..cf27b04d 100644 --- a/src/RvtIO/Parsing/WideElementRecords.cs +++ b/src/RvtIO/Parsing/WideElementRecords.cs @@ -115,7 +115,8 @@ internal sealed class Index : ids.TryGetKey(id, out int key) && wanted.Contains((uint)key), onRootBlock == null ? null : (id, buf, off, size, cls, _) => onRootBlock(ids == null ? (uint)id : (uint)ids.Key(id), buf, off, size, cls), framed); - /// Indexes serialized element IDs. The root callback also receives the framed partition number when available. + /// Indexes serialized element IDs. Each root callback receives a payload offset in its supplied buffer + /// and the framed partition number when available. internal static Index? BuildIndexWithPartitions( IReadOnlyList> streams, FileSchema schema, Func wanted, Action? onRootBlock, IReadOnlyList? framed = null) @@ -151,43 +152,54 @@ internal sealed class Index long total = 0; foreach (var c in chunks) total += c.Length; if (total > int.MaxValue - 64) return null; - var buf = new byte[total]; - int off = 0; - foreach (var c in chunks) { Buffer.BlockCopy(c, 0, buf, off, c.Length); off += c.Length; } var recordIds = new HashSet(); var blockClasses = new Dictionary(); // -1: the stream holds blocks of two classes for the id - var rootBlocks = onRootBlock == null ? null : new List<(long Id, int Offset, int Size, int Class)>(); - void Header(int p, int size, long id) + var rootBlocks = onRootBlock == null ? null : new List<(long Id, byte[] Data, int Offset, int Size, int Class)>(); + void Header(byte[] buf, int p, int size, long id) { index.Records++; if (!wanted(id)) return; recordIds.Add(id); RecordCategory(buf, p + width - 8, size, categoryWidth, entry, id, index, conflictCategory, conflictDesignOption, outlineTags); } - void Block(int p, int size, long id, int cls) + void Block(byte[] buf, int p, int size, long id, int cls) { index.Blocks++; if (!isElement[cls] || !wanted(id)) return; blockClasses[id] = blockClasses.TryGetValue(id, out int prior) && prior != cls ? -1 : cls; - rootBlocks?.Add((id, p + width + 8, size, cls)); + rootBlocks?.Add((id, buf, p + width + 8, size, cls)); + } + if (frame == null) + { + var buf = new byte[total]; + int off = 0; + foreach (var c in chunks) { Buffer.BlockCopy(c, 0, buf, off, c.Length); off += c.Length; } + Walk(buf, header.Id, width, known, wanted, Header, Block); } - if (frame == null) Walk(buf, header.Id, width, known, wanted, Header, Block); else foreach (var item in frame.Items) { if (item.Owner > long.MaxValue) continue; long owner = (long)item.Owner; if (owner > uint.MaxValue && !wanted(owner)) continue; - int p = (int)item.Offset; - if (item.Channel == 101 && item.Length >= width + 16 && BitConverter.ToUInt16(buf, p + width + 4) == header.Id) - Header(p, item.Length - width - 8, owner); - else if (item.Channel == 102 && item.Length >= width + 20 && BitConverter.ToUInt16(buf, p + width + 8) is var cls && cls < known.Length && known[cls]) - Block(p, item.Length - width - 12, owner, cls); + if (item.Channel == 101 && item.Length >= width + 16) + { + var (data, p, _) = frame.Bytes(item); + if (BitConverter.ToUInt16(data, p + width + 4) == header.Id) + Header(data, p, item.Length - width - 8, owner); + } + else if (item.Channel == 102 && item.Length >= width + 20) + { + var (data, p, _) = frame.Bytes(item); + int cls = BitConverter.ToUInt16(data, p + width + 8); + if (cls < known.Length && known[cls]) + Block(data, p, item.Length - width - 12, owner, cls); + } } // payload (class id first) of every Element-derived block whose stream holds the header record of its id if (rootBlocks != null) - foreach (var (blockId, offset, size, cls) in rootBlocks) - if (recordIds.Contains(blockId)) onRootBlock!(blockId, buf, offset, size, cls, frame?.Partition); + foreach (var (blockId, data, offset, size, cls) in rootBlocks) + if (recordIds.Contains(blockId)) onRootBlock!(blockId, data, offset, size, cls, frame?.Partition); foreach (var (id, cls) in blockClasses) { if (!recordIds.Contains(id)) continue; @@ -204,7 +216,7 @@ void Block(int p, int size, long id, int cls) /// The position-by-position scan: every candidate whose length echo holds is a header record or a block (item start, size, id). private static void Walk(byte[] b, int headerId, int w, bool[] known, Func wanted, - Action header, Action block) + Action header, Action block) { int n = b.Length; int p = 0; @@ -217,7 +229,7 @@ private static void Walk(byte[] b, int headerId, int w, bool[] known, Func= 8 && size < 4_000_000 && p + w + 8L + size <= n && BitConverter.ToUInt32(b, p + w + 4 + (int)size) == size) { - header(p, (int)size, id); + header(b, p, (int)size, id); p += w + 8 + (int)size; continue; } @@ -227,7 +239,7 @@ private static void Walk(byte[] b, int headerId, int w, bool[] known, Func= 8 && blockSize < 8_000_000 && cls < known.Length && known[cls] && p + w + 12L + blockSize <= n && BitConverter.ToUInt32(b, p + w + 8 + (int)blockSize) == blockSize) { - block(p, (int)blockSize, id, cls); + block(b, p, (int)blockSize, id, cls); p += w + 12 + (int)blockSize; continue; } diff --git a/src/RvtIO/Parsing/WideNativeParams.cs b/src/RvtIO/Parsing/WideNativeParams.cs index a8c21d9e..c458d1fe 100644 --- a/src/RvtIO/Parsing/WideNativeParams.cs +++ b/src/RvtIO/Parsing/WideNativeParams.cs @@ -35,6 +35,9 @@ internal sealed partial class WideNativeParams /// Revit's internal names ("SecretInternal..." styles) are not the names Revit prints. private const string InternalNamePrefix = "SecretInternal"; + private static readonly Dictionary NameFieldOrder = NameFields + .Select((name, index) => (name, index)).ToDictionary(field => field.name, field => field.index, StringComparer.Ordinal); + internal const string GroupTypeKey = "301:m_groupTypeId"; private const string ParamDefPointerKey = "2870:m_pParamDef.class"; @@ -66,7 +69,6 @@ internal sealed partial class WideNativeParams private const string DiscriminatorKey = "sys:discriminator"; private readonly WideBlockWalker _walker; - private readonly HashSet _nameFields = new(NameFields, StringComparer.Ordinal); private readonly SchemaDocument _schema; private readonly Dictionary _r22ByName; private readonly Dictionary _r22; @@ -129,7 +131,7 @@ internal WideNativeParams(SchemaDocument schema, ElementIdMap? ids = null) if (Revit2027ApiValues.RootFields.Contains(key)) return key; bool keyed = r22 != 0 && _r22[r22].Fields.Any(f => f.Name == field.Name) && _bases.Contains(key); bool rootName = TfBlockDeserializer.CapturedFieldNames.Contains(field.Name); - bool name = field.Type == 8 && _nameFields.Contains(declaring.Name + "." + field.Name); + bool name = field.Type == 8 && NameFieldOrder.ContainsKey(declaring.Name + "." + field.Name); if (keyed || rootName || name) return key; // the origin of the plane a datum plane (a Level) stands on, read by LevelElevation if (declaring.Name == "Plane" && field.Name == "m_origin") return PlaneOriginKey; @@ -178,17 +180,22 @@ internal WideNativeParams(SchemaDocument schema, ElementIdMap? ids = null) { // the SymbolInfo name of a leader or dimension style is not always the name Revit prints if (_walker.IsA(rootClassId, "LeaderStyle") || _walker.IsA(rootClassId, "DimensionStyle")) return null; - foreach (string field in NameFields) + Span seen = stackalloc bool[NameFields.Length]; + seen.Clear(); + int best = NameFields.Length; + string? name = null; + foreach (var c in walk.Captures) { - if (field == "ParamDef.m_caption" && !_walker.IsA(rootClassId, "ParamElem")) continue; - foreach (var c in walk.Captures) - { - if (c.Kind != WideBlockWalker.CaptureKind.Text || c.DeclaringClass + "." + c.Field != field) continue; - if (c.Text is { Length: > 0 } text && !text.StartsWith(InternalNamePrefix, StringComparison.Ordinal)) return text; - break; // the first object of that class decides - } + if (c.Kind != WideBlockWalker.CaptureKind.Text || !NameFieldOrder.TryGetValue(c.DeclaringClass + "." + c.Field, out int rank) + || rank >= best || seen[rank]) continue; + seen[rank] = true; // The first text for a given field decides, even when it cannot name the element. + if (c.Text is not { Length: > 0 } text || text.StartsWith(InternalNamePrefix, StringComparison.Ordinal) + || (NameFields[rank] == "ParamDef.m_caption" && !_walker.IsA(rootClassId, "ParamElem"))) continue; + if (rank == 0) return text; + best = rank; + name = text; } - return null; + return name; } /// The elevation (feet) of a Level: the Z of the origin of its datum plane, which the Revit 2022 reader takes from the diff --git a/src/RvtIO/RvtDocument.cs b/src/RvtIO/RvtDocument.cs index 0b225c9e..95b66193 100644 --- a/src/RvtIO/RvtDocument.cs +++ b/src/RvtIO/RvtDocument.cs @@ -356,10 +356,13 @@ public static RvtDocument OpenStream(Stream stream, RvtReaderOptions? options = public static RvtDocument FromInfo(RevitFileInfo info) { ArgumentNullException.ThrowIfNull(info); - return new RvtDocument(CloneForDocument(info)); + return new RvtDocument(CloneForDocument(info, sceneOnly: false)); } - private static RevitFileInfo CloneForDocument(RevitFileInfo info) + // Used only while mapping the CLI scene. The view is never handed to a caller that could edit a parameter. + internal static RvtDocument ForSceneExport(RevitFileInfo info) => new(CloneForDocument(info, sceneOnly: true)); + + private static RevitFileInfo CloneForDocument(RevitFileInfo info, bool sceneOnly) { var cloned = info.ShallowCopy(); cloned.Elements = new List(info.Elements.Count); @@ -369,7 +372,12 @@ private static RevitFileInfo CloneForDocument(RevitFileInfo info) copy.Parameters = new List(elem.Parameters.Count); foreach (var p in elem.Parameters) { - copy.Parameters.Add(p.ShallowCopy(p.Value)); + // Document construction can repair two empty references, remap an element ID or resolve a zero target. + // All other parameters are only read by the scene mapper. + bool needsCopy = !sceneOnly || p.HasResolvedZeroElementId + || (p.StorageType == StorageType.ElementId && p.Value is int id && (id == 0 || info.ElementIds != null)) + || (!p.HasValue && p.DefinitionName is "SYMBOL_ID_PARAM" or "ELEM_FAMILY_PARAM"); + copy.Parameters.Add(needsCopy ? p.ShallowCopy(p.Value) : p); } cloned.Elements.Add(copy); } diff --git a/src/RvtIO/RvtFileReader.cs b/src/RvtIO/RvtFileReader.cs index 4d788a54..cf2fcee9 100644 --- a/src/RvtIO/RvtFileReader.cs +++ b/src/RvtIO/RvtFileReader.cs @@ -219,6 +219,11 @@ private RevitFileInfo ReadCore(RootStorage root) var blockGeometry = ParseBlocks(state, diag, progress, unreadableGReps, overlapGeometry: progress == null && unreadableGReps != null && !OperatingSystem.IsBrowser() && (state.WideSchema == null || state.R22View)); + // ParseBlocks has finished adding record/block-only IDs. The scalar walk and + // geometry recovery only read that set; neither consumes the scanned strings. + // Snapshot the ID set: the background geometry decode still runs while the scan reads it. + var scanIds = new HashSet(state.AllKnownIds); + var stringScan = blockGeometry != null ? Task.Run(ScanElementStrings) : null; // The anchored walk reaches blocks spanning chunks and decodes the native parameter stores. try { @@ -226,7 +231,15 @@ private RevitFileInfo ReadCore(RootStorage root) progress?.Report(new("parameter-stream")); RunTfStreamWalk(state, progress, unreadableGReps, blockGeometry); } - finally { blockGeometry?.GetAwaiter().GetResult(); } + finally + { + // Join both background tasks. A single failure keeps its type; two surface together instead of one hiding the other. + try { Task.WaitAll(new Task?[] { blockGeometry, stringScan }.OfType().ToArray()); } + catch (AggregateException failure) when (failure.InnerExceptions.Count == 1) + { + System.Runtime.ExceptionServices.ExceptionDispatchInfo.Capture(failure.InnerExceptions[0]).Throw(); + } + } unreadableGReps = null; blockGeometry = null; if (state.WideSchema == null) ReadOwnDocumentUnits(root, state, diag); @@ -238,7 +251,9 @@ private RevitFileInfo ReadCore(RootStorage root) progress?.Report(new("element-properties")); // The catalog reads finalized native captures. The string scan writes only its name candidates. UserParameterCatalog? userParameters = null; - if (OperatingSystem.IsBrowser() || progress != null) + if (stringScan != null) + userParameters = UserParameterCatalog.Build(state); + else if (OperatingSystem.IsBrowser() || progress != null) { ScanElementStrings(); userParameters = UserParameterCatalog.Build(state); @@ -251,7 +266,7 @@ void ScanElementStrings() Parallel.For(0, chunks.Count, chunkIndex => { var localStrings = new Dictionary>(); - StringScanner.ScanChunk(chunks[chunkIndex], state.AllKnownIds, localStrings); + StringScanner.ScanChunk(chunks[chunkIndex], scanIds, localStrings); if (localStrings.Count > 0) partialResults[chunkIndex] = localStrings; }); MergeElemScanStringsInChunkOrder(partialResults, state.ElemScanStrings); @@ -776,6 +791,7 @@ void ScanElementStrings() .OrderBy(k => k).ToList(); state.SymbolPlacementGeometry = new(ReferenceEqualityComparer.Instance); + state.ReaderParameterDefinitions = ElementBuilder.ReaderParameterDefinitions(state); BuildOrderedElements(state.ElemTable.OrderBy(x => x.Key).ToArray(), rvtInfo.Elements, (entry, parameterIds) => ElementBuilder.CreateElemTableElement(entry.Key, entry.Value, state, parameterIds)); @@ -828,6 +844,7 @@ void ScanElementStrings() _ => null, }; var elementsById = ElementBuilder.PostProcess(rvtInfo, state, diag); + state.ReaderParameterDefinitions = null; state.SymbolPlacementGeometry = null; if (state.GridAxes is { } axes) { @@ -852,25 +869,25 @@ void ScanElementStrings() // reader without a requested locale (the legacy profile) is unchanged var familyNames = systemFamilyNames ?? Lookup.RevitSystemFamilyNames.LoadPreviousReleaseFamilies(rvtInfo.Metadata.RevitVersion, systemFamilyLocale, _options.SystemFamilyNameLocale); - int systemFamilyTypes = ElementBuilder.ApplyValidatedSystemFamilyNames(rvtInfo.Elements, state, familyNames); + int systemFamilyTypes = ElementBuilder.ApplyValidatedSystemFamilyNames(rvtInfo.Elements, state, familyNames, elementsById); ReadCompactLookupText(rvtInfo); - ElementBuilder.ApplyValidatedStairOccurrenceNames(rvtInfo.Elements, familyNames); + ElementBuilder.ApplyValidatedStairOccurrenceNames(rvtInfo.Elements, familyNames, elementsById); ElementBuilder.ApplyHostLabels(rvtInfo, systemFamilyNames, state.ElemClassIdx, elementsById); ElementBuilder.ApplyWorkPlaneLabels(rvtInfo, systemFamilyNames); ElementBuilder.ApplyColumnLocationMarks(rvtInfo, state.OwnDocumentUnitOptions?.Value, state.ElemClassIdx); ElementBuilder.ApplyMepSystemParams(rvtInfo, state, systemFamilyNames); ElementBuilder.ApplyConnectorGraph(rvtInfo, state); - ElementBuilder.ApplyStairNameParameterScopes(rvtInfo.Elements, state); + ElementBuilder.ApplyStairNameParameterScopes(rvtInfo.Elements, state, elementsById); diag?.WriteLine($"System family names: locale={rvtInfo.Metadata.SavedLocale ?? "?"}, " + $"resources={(systemFamilyNames != null ? "loaded" : "unavailable")}, types={systemFamilyTypes}"); LogPhase("Names and parameters applied"); - int wallTopAttachments = ElementBuilder.ApplyWallJoinedToTop(rvtInfo.Elements, state); + int wallTopAttachments = ElementBuilder.ApplyWallJoinedToTop(rvtInfo.Elements, state, elementsById); diag?.WriteLine($"Wall top attachment: roots={state.WallJoinedToTop.Count}, " + $"duplicate={state.WallJoinedToTop.Values.Count(v => v.BlockCount != 1)}, " + $"unread={state.WallJoinedToTop.Values.Count(v => v.BlockCount == 1 && v.JoinedToTop == null)}, " + $"top={state.WallJoinedToTop.Values.Count(v => v.BlockCount == 1 && v.JoinedToTop == true)}, " + $"walls={wallTopAttachments}"); - int wallEndJoins = ElementBuilder.ApplyWallEndJoins(rvtInfo.Elements, state); + int wallEndJoins = ElementBuilder.ApplyWallEndJoins(rvtInfo.Elements, state, elementsById); diag?.WriteLine($"Wall end joins: roots={state.WallEndJoins.Count}, " + $"duplicate={state.WallEndJoins.Values.Count(v => v.BlockCount != 1)}, " + $"unread={state.WallEndJoins.Values.Count(v => v.BlockCount == 1 && v.Joins == null)}, walls={wallEndJoins}" @@ -878,14 +895,14 @@ void ScanElementStrings() ? "; unread by reason: " + string.Join(", ", state.WallEndJoinFailures .OrderByDescending(entry => entry.Value).Take(8).Select(entry => $"{entry.Key}={entry.Value}")) : "")); - var (namedMaterials, ceilingTypes) = ElementBuilder.ApplyCeilingFinishSource(rvtInfo.Elements, state); + var (namedMaterials, ceilingTypes) = ElementBuilder.ApplyCeilingFinishSource(rvtInfo.Elements, state, elementsById); diag?.WriteLine($"Ceiling finish source: materials={namedMaterials}/{state.MaterialNames.Count}, " + $"ceiling types={ceilingTypes}/{state.CeilingCompoundStructureLayerSource.Count}"); - int hostLayerTypes = ElementBuilder.ApplyHostTypeCompoundStructures(rvtInfo.Elements, state); + int hostLayerTypes = ElementBuilder.ApplyHostTypeCompoundStructures(rvtInfo.Elements, state, elementsById); diag?.WriteLine($"Host type compound structures: types={hostLayerTypes}/{state.HostTypeCompoundStructures.Count}"); - int ceilingThicknessTypes = ElementBuilder.ApplyCompoundCeilingTypeThickness(rvtInfo.Elements, state); + int ceilingThicknessTypes = ElementBuilder.ApplyCompoundCeilingTypeThickness(rvtInfo.Elements, state, elementsById); diag?.WriteLine($"Own computed ceiling thickness: types={ceilingThicknessTypes}/{state.CompoundCeilingTypeThicknessFeet.Count}"); - int wallThicknessOccurrences = ElementBuilder.ApplyBasicWallTypeThickness(rvtInfo.Elements, state); + int wallThicknessOccurrences = ElementBuilder.ApplyBasicWallTypeThickness(rvtInfo.Elements, state, elementsById); diag?.WriteLine($"Own computed wall thickness: occurrences={wallThicknessOccurrences}/{state.BasicWallTypeThicknessFeet.Count}"); rvtInfo.SerializedDocumentGuid = state.DocumentDetachGuid; ReadCompactFormatSettings(rvtInfo, state); @@ -959,21 +976,24 @@ private static void BuildOrderedElements(IReadOnlyList input, List>?> partialResults, + Dictionary>?[] partialResults, Dictionary> elemScanStrings) { // HashSet-backed dedupe: rebar-heavy models attribute thousands of strings per // element, and List.Contains per insert made this merge quadratic. var mergeSeen = new Dictionary>(); - for (int chunkIndex = 0; chunkIndex < partialResults.Count; chunkIndex++) + for (int chunkIndex = 0; chunkIndex < partialResults.Length; chunkIndex++) { var partial = partialResults[chunkIndex]; + partialResults[chunkIndex] = null; if (partial == null) continue; foreach (var (eid, strings) in partial) { - if (!elemScanStrings.TryGetValue(eid, out var list)) - elemScanStrings[eid] = list = new List(); + // ScanChunk has already deduplicated each local list. Transfer the first + // one; only owners seen in another chunk need a cross-chunk membership set. + if (elemScanStrings.TryAdd(eid, strings)) continue; + var list = elemScanStrings[eid]; if (!mergeSeen.TryGetValue(eid, out var seen)) mergeSeen[eid] = seen = new HashSet(list); foreach (var s in strings) diff --git a/tests/RvtIO.Tests/CompactLegacyJsonIdentityTests.cs b/tests/RvtIO.Tests/CompactLegacyJsonIdentityTests.cs index d3354ba3..0a77e89e 100644 --- a/tests/RvtIO.Tests/CompactLegacyJsonIdentityTests.cs +++ b/tests/RvtIO.Tests/CompactLegacyJsonIdentityTests.cs @@ -36,7 +36,7 @@ private static RevitFileInfo Synthetic() return info; } - private static string Serialize(RevitFileInfo info) + private static string Serialize(RevitFileInfo info, bool cacheKeys) { var options = new JsonSerializerOptions { @@ -44,16 +44,19 @@ private static string Serialize(RevitFileInfo info) DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull, NumberHandling = JsonNumberHandling.AllowNamedFloatingPointLiterals, Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping, - Converters = { new JsonStringEnumConverter(), new ParameterListConverter() }, + Converters = { new JsonStringEnumConverter() }, }; info.BuildParameterDefinitionTable(); + options.Converters.Add(cacheKeys ? new ParameterListConverter(info.ParameterDefinitions!.Keys, options.Encoder) : new ParameterListConverter()); return JsonSerializer.Serialize(info, options).Replace("\r\n", "\n"); } - [Fact] - public void LegacyDumpOfASyntheticFile_IsUnchanged() + [Theory] + [InlineData(false)] + [InlineData(true)] + public void LegacyDumpOfASyntheticFile_IsUnchanged(bool cacheKeys) { - string json = Serialize(Synthetic()); + string json = Serialize(Synthetic(), cacheKeys); string hash = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(json))).ToLowerInvariant(); Assert.True(hash == ExpectedSha256, $"legacy JSON changed (SHA-256 {hash}):\n{json}"); } diff --git a/tests/RvtIO.Tests/ElementBuilderGeometryTests.cs b/tests/RvtIO.Tests/ElementBuilderGeometryTests.cs index 7446ad7d..60364904 100644 --- a/tests/RvtIO.Tests/ElementBuilderGeometryTests.cs +++ b/tests/RvtIO.Tests/ElementBuilderGeometryTests.cs @@ -197,7 +197,7 @@ 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 cache = new System.Collections.Concurrent.ConcurrentDictionary>(ReferenceEqualityComparer.Instance); var state = new ParsingState { SymbolPlacementGeometry = cache }; state.GrepBlocks[1] = symbol; state.GrepBlocks[2] = new GRepData @@ -216,14 +216,14 @@ public void PlacedSymbol_ReusesLocalFacesAcrossClippedAndUnclippedInstances() Assert.NotSame(clippedFace.OuterVertices[0], clippedFace.Origin); Assert.Null(clippedFace.QuadratureArea); - var localGeometry = Assert.IsType(cache[symbol]); + var localGeometry = Assert.IsType(cache[symbol].Value); 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.Same(localGeometry, Assert.Single(cache).Value.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); @@ -239,7 +239,7 @@ public void PlacedSymbol_CachesEachSelectedDetailRepresentation() fine.Coarse = TriangleAt(10); fine.Medium = TriangleAt(20); fine.CoarseQuantities = TriangleAt(30); - var cache = new Dictionary(ReferenceEqualityComparer.Instance); + var cache = new System.Collections.Concurrent.ConcurrentDictionary>(ReferenceEqualityComparer.Instance); var state = new ParsingState { SymbolPlacementGeometry = cache }; state.GrepBlocks[1] = fine; diff --git a/tests/RvtIO.Tests/FullJsonOutputTests.cs b/tests/RvtIO.Tests/FullJsonOutputTests.cs new file mode 100644 index 00000000..87a2d22f --- /dev/null +++ b/tests/RvtIO.Tests/FullJsonOutputTests.cs @@ -0,0 +1,72 @@ +using System.Text.Encodings.Web; +using System.Text.Json; +using System.Text.Json.Serialization; +using RvtIO.Model; +using Xunit; + +namespace RvtIO.Tests; + +public class FullJsonOutputTests +{ + private static JsonSerializerOptions Options(bool indented) => new() + { + WriteIndented = indented, + DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull, + Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping, + }; + + // The worker count is fixed so the parallel path runs even on a single-CPU machine. + private static void AssertMatchesTheStreamingSerializer(RevitFileInfo model, JsonSerializerOptions options) + { + using var expected = new MemoryStream(); + JsonSerializer.Serialize(expected, model, options); + string path = TestFiles.Scratch($"full-{Guid.NewGuid():N}.json"); + try + { + using (var output = File.Create(path)) FullJsonOutput.Write(output, model, options, workerCount: 4); + Assert.True(expected.ToArray().AsSpan().SequenceEqual(File.ReadAllBytes(path))); + } + finally { File.Delete(path); } + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void ParallelAndOversizedBatchesMatchTheStreamingSerializer(bool indented) + { + var model = new RevitFileInfo { SitePlaceName = "after the elements" }; + for (int i = 0; i < 4201; i++) + model.Elements.Add(new Element { Id = i, Name = "имя ]],\n\"" + i }); + // The first, an interior and the final batch must fall back to streaming. + model.Elements[0].Name = model.Elements[517].Name = model.Elements[^1].Name = new string('ё', 1_100_000); + var options = Options(indented); + options.Converters.Add(new ParameterListConverter()); + AssertMatchesTheStreamingSerializer(model, options); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void KeyedParameterValuesMatchTheStreamingSerializerInParallelBatches(bool indented) + { + var model = new RevitFileInfo(); + for (int i = 0; i < 4201; i++) + model.Elements.Add(new Element + { + Id = i, + Name = "e" + i, + Parameters = + [ + new Parameter { Id = -1001000, StorageType = StorageType.Integer, Value = i }, + new Parameter { Id = -1002000, StorageType = StorageType.String, Value = "текст \"" + i + "\"" }, + new Parameter { Id = 262801, StorageType = StorageType.Double, Value = i / 8.0 }, + // A repeated id keeps its first value. + new Parameter { Id = -1001000, StorageType = StorageType.Integer, Value = -i }, + ], + }); + var options = Options(indented); + model.BuildParameterDefinitionTable(); + options.Converters.Add(new ParameterListConverter(model.ParameterDefinitions!.Keys, options.Encoder)); + AssertMatchesTheStreamingSerializer(model, options); + } +} diff --git a/tests/RvtIO.Tests/IfcExporterTypeObjectsTests.cs b/tests/RvtIO.Tests/IfcExporterTypeObjectsTests.cs index d4c40110..453c330f 100644 --- a/tests/RvtIO.Tests/IfcExporterTypeObjectsTests.cs +++ b/tests/RvtIO.Tests/IfcExporterTypeObjectsTests.cs @@ -1227,7 +1227,7 @@ public void StairFlight_PropertiesComeFromTheRunNumbersAndItsStairs() var writer = new StepWriter(); var values = new List(); typeof(IfcExporter).GetMethod("AddStairFlightProperties", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static)! - .Invoke(null, [writer, run, elements, values, false]); + .Invoke(null, [writer, run, elements, values, false, new Dictionary> { [stairs.Id] = [run] }]); var written = values.Select(id => Enumerable.Range(0, writer.EntityCount).Select(writer.EntityAt).Single(e => e.Id == id).Args).ToList(); Assert.Equal( [ diff --git a/tests/RvtIO.Tests/MultiOutputExportTests.cs b/tests/RvtIO.Tests/MultiOutputExportTests.cs index 80f2498c..bb82e0a1 100644 --- a/tests/RvtIO.Tests/MultiOutputExportTests.cs +++ b/tests/RvtIO.Tests/MultiOutputExportTests.cs @@ -213,8 +213,10 @@ public void MultiOutput_MissingPathOption_ExitsWithCode1(string option) } } - [Fact] - public void MultiOutput_RvtDocumentFromInfo_DoesNotMutateSourceInfo() + [Theory] + [InlineData(false)] + [InlineData(true)] + public void MultiOutput_DocumentPreparationDoesNotMutateSourceInfo(bool sceneOnly) { var info = new RvtIO.Model.RevitFileInfo { @@ -254,7 +256,7 @@ public void MultiOutput_RvtDocumentFromInfo_DoesNotMutateSourceInfo() string originalName = info.Elements[0].Name; object? originalSymbolValue = info.Elements[0].Parameters[0].Value; - var doc = RvtDocument.FromInfo(info); + var doc = sceneOnly ? RvtDocument.ForSceneExport(info) : RvtDocument.FromInfo(info); Assert.NotNull(doc); // Document element has synthesized params and resolved names @@ -270,6 +272,25 @@ public void MultiOutput_RvtDocumentFromInfo_DoesNotMutateSourceInfo() Assert.Equal(originalSymbolValue, info.Elements[0].Parameters[0].Value); } + [Fact] + public void SceneExport_ResolvesZeroAndWideReferencesOnlyInTheSceneView() + { + const long wideId = (long)int.MaxValue + 1; + var ids = new RvtIO.Parsing.ElementIdMap([]); + var phase = new RvtIO.Model.Parameter { Id = -1012100, StorageType = RvtIO.Model.StorageType.ElementId, Value = 0 }; + var wide = new RvtIO.Model.Parameter { StorageType = RvtIO.Model.StorageType.ElementId, Value = ids.Key(wideId) }; + var info = new RvtIO.Model.RevitFileInfo + { + ElementIds = ids, + Elements = [new() { Id = 0, CategoryId = -2000112 }, new() { Id = 1, Parameters = [phase, wide] }], + }; + var parameters = RvtDocument.ForSceneExport(info).GetElement(1)!.Parameters; + Assert.True(parameters[0].HasResolvedZeroElementId); + Assert.Equal(wideId, parameters[1].AsElementId64()); + Assert.False(phase.HasResolvedZeroElementId); + Assert.Null(wide.SourceElementId); + } + [Fact] public async Task MultiOutput_IfcWithBareCompactJson_ExportsBothFiles() { diff --git a/tests/RvtIO.Tests/ParameterValueFormattingTests.cs b/tests/RvtIO.Tests/ParameterValueFormattingTests.cs index ea331983..402a141f 100644 --- a/tests/RvtIO.Tests/ParameterValueFormattingTests.cs +++ b/tests/RvtIO.Tests/ParameterValueFormattingTests.cs @@ -44,6 +44,21 @@ public void OptionalGuidCanBeUpdatedOrClearedIndependentlyOnAShallowCopy() Assert.NotNull(first.Guid); } + [Theory] + [InlineData(0L)] + [InlineData(long.MinValue)] + [InlineData(long.MaxValue)] + public void NativeReferenceCanBeClearedWithoutChangingTheCopy(long id) + { + var parameter = new Parameter { StorageType = StorageType.ElementId, Value = 7, NativeElementId = id }; + var copy = parameter.ShallowCopy(parameter.Value); + parameter.NativeElementId = null; + Assert.Equal(7L, parameter.AsElementId64()); + Assert.Null(parameter.SourceElementId); + Assert.Equal(id, copy.AsElementId64()); + Assert.Equal(id.ToString(System.Globalization.CultureInfo.InvariantCulture), copy.SourceElementId); + } + [Fact] public void SharedDisplayUnitsCanBeEditedOnEachParameterIndependently() { diff --git a/tests/RvtIO.Tests/WideElementRecordsTests.cs b/tests/RvtIO.Tests/WideElementRecordsTests.cs index de9ed7d2..2962106b 100644 --- a/tests/RvtIO.Tests/WideElementRecordsTests.cs +++ b/tests/RvtIO.Tests/WideElementRecordsTests.cs @@ -509,24 +509,32 @@ public void BuildIndex_IgnoresAnElementBlockInAStreamWithoutTheHeaderRecordOfThe Assert.Equal(ids.Wall, index.RootClasses[11]); } - [Fact] - public void BuildIndex_ReadsAFramedStreamByTheRecordsOfTheProjectBlockOnly() + [Theory] + [InlineData(false)] + [InlineData(true)] + public void BuildIndex_ReadsAFramedStreamByTheRecordsOfTheProjectBlockOnly(bool splitRoot) { var (stream, ids) = BuildSchema(); var schema = FileSchema.Parse(stream)!; byte[] header = Record(ids, 10, [], -2000011), root = Block(10, ids.Level); + root[^5] = 0xA7; // last byte of the root payload, before the size echo // the same id in the document of a loaded family, a keyed block the framing does not list var data = Join(header, root, Record(ids, 10, [], -5), Block(10, ids.Wall)); - var framed = new PartitionFraming.Framed([data[..20], data[20..]], + int split = header.Length + 17; // between the two bytes of the root class tag + byte[][] chunks = splitRoot ? [data[..20], data[20..split], [], data[split..]] : [data[..20], data[20..]]; + var framed = new PartitionFraming.Framed(chunks, [new(101, 10, 0, header.Length), new(102, 10, header.Length, root.Length)], 8); - var roots = new List<(uint Id, int Offset, int Size, int Class)>(); + var roots = new List<(uint Id, int Class, byte[] Payload)>(); - var index = WideElementRecords.BuildIndex([[data]], schema, new HashSet { 10 }, (id, _, offset, size, cls) => roots.Add((id, offset, size, cls)), [framed])!; + var index = WideElementRecords.BuildIndex([chunks], schema, new HashSet { 10 }, + (id, buffer, offset, size, cls) => roots.Add((id, cls, buffer.AsSpan(offset, size).ToArray())), [framed])!; Assert.Equal(-2000011, index.HeaderCategories[10]); Assert.Equal(ids.Level, index.RootClasses[10]); Assert.Equal((1, 1), (index.Records, index.Blocks)); - Assert.Equal([(10u, header.Length + 16, root.Length - 20, ids.Level)], roots); + var found = Assert.Single(roots); + Assert.Equal((10u, ids.Level), (found.Id, found.Class)); + Assert.Equal(root[16..^4], found.Payload); // the scan takes the family's records for a second copy of the element, and the copies disagree var scanned = WideElementRecords.BuildIndex([[data]], schema, new HashSet { 10 })!; Assert.Null(scanned.HeaderCategories[10]); @@ -536,6 +544,24 @@ public void BuildIndex_ReadsAFramedStreamByTheRecordsOfTheProjectBlockOnly() Assert.Null(otherWidth.HeaderCategories[10]); } + [Fact] + public void FramedIndex_AllocationDoesNotScaleWithUnindexedFamilyData() + { + var (stream, ids) = BuildSchema(); + var schema = FileSchema.Parse(stream)!; + byte[] header = Record(ids, 10, [], -2000011), root = Block(10, ids.Level); + byte[][] chunks = [header, root, new byte[4 << 20]]; + var frame = new PartitionFraming.Framed(chunks, + [new(101, 10, 0, header.Length), new(102, 10, header.Length, root.Length)], 8); + var wanted = new HashSet { 10 }; + long before = GC.GetAllocatedBytesForCurrentThread(); + var index = WideElementRecords.BuildIndex([chunks], schema, wanted, framed: [frame])!; + long allocated = GC.GetAllocatedBytesForCurrentThread() - before; + + Assert.Equal(ids.Level, index.RootClasses[10]); + Assert.True(allocated < chunks[2].Length, $"Indexing two project records allocated {allocated} bytes."); + } + private sealed record OutlineIds(int Header, int Outline, int Parents, int Level); /// A schema whose ElementHeader has the layout of the files: ids, m_viewRules, m_abFlags4Bytes, m_classDef and the pointers diff --git a/tests/RvtIO.Tests/WideNativeParamsTests.cs b/tests/RvtIO.Tests/WideNativeParamsTests.cs index e7af2694..7ead19f3 100644 --- a/tests/RvtIO.Tests/WideNativeParamsTests.cs +++ b/tests/RvtIO.Tests/WideNativeParamsTests.cs @@ -49,6 +49,34 @@ private static SchemaField Field(string name, byte type, byte mods = 0, int? ref private static readonly WideNativeParams Params = new(Schema()); + [Theory] + [InlineData("Symbol", "Symbol")] + [InlineData("", "Family")] + [InlineData("SecretInternalStyle", "Family")] + public void OwnName_PrefersTheHighestRankedFieldAndOnlyItsFirstText(string symbol, string expected) + { + var walk = new WideBlockWalker.Walk(); + void Name(string declaring, string text) => walk.Captures.Add(new("name", WideBlockWalker.CaptureKind.Text, + 0, 0, text, false, 0, declaring, "m_name")); + Name("Material", "Material"); + Name("SymbolInfo", symbol); + Name("SymbolInfo", "Second symbol"); + Name("FamilyBase", "Family"); + Assert.Equal(expected, Params.OwnName(walk, RootId)); + } + + [Fact] + public void OwnName_UsesAParameterCaptionOnlyForAParameterElement() + { + var schema = Schema(); + schema.Classes.Add(new(22, "ParamElem", 0, 1, [], [])); + var reader = new WideNativeParams(schema); + var walk = new WideBlockWalker.Walk(); + walk.Captures.Add(new("caption", WideBlockWalker.CaptureKind.Text, 0, 0, "Caption", false, 0, "ParamDef", "m_caption")); + Assert.Null(reader.OwnName(walk, RootId)); + Assert.Equal("Caption", reader.OwnName(walk, 22)); + } + private static byte[] Block(int classId, Action body) { var stream = new MemoryStream(); diff --git a/tools/benchmark-export.py b/tools/benchmark-export.py new file mode 100644 index 00000000..01fbdb04 --- /dev/null +++ b/tools/benchmark-export.py @@ -0,0 +1,119 @@ +"""Compare Release CLI builds on a local RVT. Requires Python 3.8+ and dotnet. + +Example: python tools/benchmark-export.py model.rvt before/RvtIO.Cli.dll after/RvtIO.Cli.dll --runs 3 +Each process exports IFC, compact JSON, full JSON and Scene together. The temporary +directory must have room for one set of outputs. Times exclude hashing and cleanup. +Add --compare-separate to time four independent processes of the candidate build too. +""" +import argparse +import ctypes +import hashlib +import json +import math +import os +from pathlib import Path +import statistics +import subprocess +import tempfile +import time + + +def sha256(path): + digest = hashlib.sha256() + with path.open("rb") as stream: + for chunk in iter(lambda: stream.read(1024 * 1024), b""): + digest.update(chunk) + return digest.hexdigest() + + +FILES = {"ifc": "model.ifc", "compact-json": "compact.json", "full-json": "full.json", "scene": "scene.json"} + + +def run(cli, model, directory, formats): + outputs = {flag: FILES[flag] for flag in formats} + outputs["report"] = "report.json" + command = ["dotnet", str(cli), str(model)] + if "ifc" in formats: + command.extend(["--ifc-timestamp", "2000-01-01T00:00:00Z"]) + for flag, name in outputs.items(): + command.extend(["--" + flag, str(directory / name)]) + log = directory / "stderr.log" + with log.open("wb") as stderr: + start = time.perf_counter() + with subprocess.Popen(command, stdout=subprocess.DEVNULL, stderr=stderr) as process: + code = process.wait() + elapsed = time.perf_counter() - start + peak = None + if os.name == "nt": + class MemoryCounters(ctypes.Structure): + _fields_ = [("size", ctypes.c_uint32), ("faults", ctypes.c_uint32), + ("peak", ctypes.c_size_t), ("rest", ctypes.c_size_t * 7)] + + memory = MemoryCounters() + memory.size = ctypes.sizeof(memory) + if not ctypes.windll.psapi.GetProcessMemoryInfo( + ctypes.c_void_p(int(process._handle)), ctypes.byref(memory), memory.size): + raise ctypes.WinError() + peak = memory.peak + if code: + with log.open("rb") as stderr: + stderr.seek(max(0, log.stat().st_size - 2000)) + raise RuntimeError(f"{cli} exited with {code}: {stderr.read().decode(errors='replace')}") + return {"seconds": round(elapsed, 3), "peakWorkingSetBytes": peak, + "outputs": {k: sha256(directory / name) for k, name in outputs.items()}} + + +def main(): + ap = argparse.ArgumentParser(description=__doc__) + for name in ("model", "baseline", "candidate"): + ap.add_argument(name, type=Path) + ap.add_argument("--runs", type=int, default=3, help="runs per build (default: 3)") + ap.add_argument("--min-speedup", type=float, help="require this median improvement over the baseline batch") + ap.add_argument("--temp-dir", type=Path, help="parent directory for temporary exports") + ap.add_argument("--compare-separate", action="store_true", help="also compare the four separate candidate exports with its batch") + args = ap.parse_args() + if args.runs < 1: + ap.error("--runs must be positive") + if args.min_speedup is not None and not (math.isfinite(args.min_speedup) and args.min_speedup > 0): + ap.error("--min-speedup must be finite and positive") + for path in (args.model, args.baseline, args.candidate): + if not path.is_file(): + ap.error(f"file not found: {path}") + builds = {"baseline": args.baseline.resolve(), "candidate": args.candidate.resolve()} + times = {key: [] for key in builds} + separate = [] + expected = None + for i in range(args.runs): + for name in (list(builds) if i % 2 == 0 else list(reversed(builds))): + with tempfile.TemporaryDirectory(dir=args.temp_dir) as tmp: + result = run(builds[name], args.model.resolve(), Path(tmp).resolve(), FILES) + print(json.dumps({"build": name, "run": i + 1, **result}), flush=True) + if expected is None: + expected = result["outputs"] + for output, digest in result["outputs"].items(): + if expected[output] != digest: + raise SystemExit(f"Byte mismatch: {name}, run {i + 1}, {output}") + times[name].append(result["seconds"]) + if args.compare_separate: + seconds = 0 + for fmt in FILES: + with tempfile.TemporaryDirectory(dir=args.temp_dir) as tmp: + result = run(builds["candidate"], args.model.resolve(), Path(tmp).resolve(), [fmt]) + print(json.dumps({"build": "candidate", "run": i + 1, "format": fmt, **result}), flush=True) + if result["outputs"][fmt] != expected[fmt]: + raise SystemExit(f"Single export differs from batch: run {i + 1}, {fmt}") + seconds += result["seconds"] + separate.append(seconds) + medians = {name: statistics.median(values) for name, values in times.items()} + summary = {"inputBytes": args.model.stat().st_size, "medianSeconds": medians, + "speedup": medians["baseline"] / medians["candidate"]} + if separate: + summary.update(separateSeconds=statistics.median(separate), + batchVsSeparate=statistics.median(separate) / medians["candidate"]) + print(json.dumps(summary)) + if args.min_speedup is not None and summary["speedup"] < args.min_speedup: + raise SystemExit(f"Batch speedup {summary['speedup']:.3f}x is below the target {args.min_speedup:g}x") + + +if __name__ == "__main__": + main()