Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,12 @@ API between minor releases.

### Changed

- Reading reuses local family symbol geometry, builds independent elements in parallel, and reduces parameter and geometry
allocations during decoding and post-processing. Compact JSON prepares properties in bounded batches and writes them
in element ID order.
- The reader inflates validated partition members in parallel, reuses a single partition walk for wall records, and skips
repeated geometry work during block recovery. Native parameter decoding keeps the original order of records for each owner.

- `SaveAs` and `Rewrite` to another directory also check the saved paths of the linked images of a project, as they already did for linked models and point clouds. They refuse with `relative-reference-relocation` when a relative image path would resolve to a different file or the layout of a link cannot be verified. See the [writing guide](docs/writing.md).

### Fixed
Expand Down
7 changes: 6 additions & 1 deletion docs/public-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,12 @@ A zero total means the reader has no work count for that update. Counts describe

`CompactJsonExporter.Export` passes `Progress` to its first read only. A file of a wide layout is then read a second time
for solid quantities; that read reports the single update `quantities` after the first read's `complete`, and the JSON
writing that follows reports nothing.
writing that follows reports nothing. Large Compact JSON exports can prepare row properties in bounded parallel batches.
Rows are written in element ID order.

The reader reuses a family's local symbol geometry across its placements. Each placement retains its own transformed
coordinates. Parameters can share immutable definition metadata internally and materialize their own mutable
`Definition` on access.

## Model

Expand Down
11 changes: 7 additions & 4 deletions src/RvtIO.Cli/ExportCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -204,8 +204,9 @@ private static int Export(ExportArguments arguments)
if (compactJsonPath != null)
{
// The compact export reads Element.Name only where it is validated (the IFC branch above keeps the fallback names).
RvtIO.Export.ValidatedElementNames.Apply(jsonModel, jsonState);
var compactIdentity = new CompactIdentity(CompactUniverse.Select(jsonModel));
var names = new CompactElementNames(jsonModel, jsonState);
names.ApplyValidatedNames(jsonModel, jsonState);
var compactIdentity = new CompactIdentity(CompactUniverse.Enumerate(jsonModel));
// --dev-candidates <tsv>: measurement run without the value gate; writes (id, parameter, stored text, derived text, class) of every
// listed parameter for the value gate. --dev-trace <tsv>: writes (id, class, parameter, reason) of every listed parameter
// (reason empty: written) and of every element whose list is unknown (parameter 0). --dev-facts <tsv>: writes the facts that decide
Expand All @@ -226,7 +227,8 @@ private static int Export(ExportArguments arguments)
// or from the in-memory R22 model when available.
var compactGate = RvtIO.Compact.CompactValueGate.ForLayout(jsonModel.GeometryUndecoded);
CompactSolidQuantities? compactQuantities = null;
if (ifcState.R22View || !ifcModel.GeometryUndecoded)
// Only wide-layout property rules and the explicit solids dump consume this index.
if ((jsonModel.GeometryUndecoded || solidsPath != null) && (ifcState.R22View || !ifcModel.GeometryUndecoded))
{
compactQuantities = CompactSolidQuantities.From(ifcModel, ifcState, compactGate.HasSolidRules);
}
Expand All @@ -247,7 +249,8 @@ private static int Export(ExportArguments arguments)
}
// A project (.rvt) is a document without an owner family; an .rfa is not decided.
var compactSource = CompactPropertySources.Create(jsonModel, jsonState,
rvtPath.EndsWith(".rvt", StringComparison.OrdinalIgnoreCase) ? true : null, gated: candidatesPath == null, identity: compactIdentity, quantities: compactQuantities);
rvtPath.EndsWith(".rvt", StringComparison.OrdinalIgnoreCase) ? true : null,
gated: candidatesPath == null, identity: compactIdentity, quantities: compactQuantities, names: names);
using var candidatesWriter = candidatesPath == null ? null : new StreamWriter(candidatesPath, false, new System.Text.UTF8Encoding(false));
using var traceWriter = tracePath == null ? null : new StreamWriter(tracePath, false, new System.Text.UTF8Encoding(false));
using var factsWriter = factsPath == null ? null : new StreamWriter(factsPath, false, new System.Text.UTF8Encoding(false));
Expand Down
2 changes: 1 addition & 1 deletion src/RvtIO.Cli/InspectBatchDump.cs
Original file line number Diff line number Diff line change
Expand Up @@ -316,7 +316,7 @@ public static void Run(RevitFileInfo info, string idsPath, string outPath, Parsi
/// IfcExporter's private ParameterNameEquals convention - duplicated here deliberately so
/// this diagnostic-only tool has no dependency on IfcExporter internals.</summary>
private static bool NameMatches(RvtIO.Model.Parameter parameter, string name) =>
parameter.Definition?.Name is string parameterName
parameter.DefinitionName is string parameterName
&& string.Equals(
parameterName.Replace(" ", null), name.Replace(" ", null),
StringComparison.InvariantCultureIgnoreCase);
Expand Down
2 changes: 1 addition & 1 deletion src/RvtIO.Cli/ListCategoryDump.cs
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ public static void Run(RevitFileInfo info, int categoryId, string outPath)
private static string? NamedStringParam(Element e, string name)
{
foreach (var p in e.Parameters)
if (p.Definition?.Name is string n
if (p.DefinitionName is string n
&& string.Equals(n.Replace(" ", null), name.Replace(" ", null),
StringComparison.InvariantCultureIgnoreCase)
&& p.Value is string v)
Expand Down
10 changes: 5 additions & 5 deletions src/RvtIO.Cli/ReadCommands.cs
Original file line number Diff line number Diff line change
Expand Up @@ -113,14 +113,14 @@ private static int Inspect(string rvtPath, string? externalDumpPath, string? ext
// RVTIO_INSPECT_ALL=1 lists every parameter, not the first twenty.
int listedParameters = Environment.GetEnvironmentVariable("RVTIO_INSPECT_ALL") == "1" ? int.MaxValue : 20;
foreach (var p in elem.Parameters.Take(listedParameters))
Console.WriteLine($" [{p.Id}] {p.Definition?.Name ?? "?"} = {p.Value} ({p.StorageType})");
Console.WriteLine($" [{p.Id}] {p.DefinitionName ?? "?"} = {p.Value} ({p.StorageType})");
if (elem.Parameters.Count > listedParameters)
Console.WriteLine($" ... +{elem.Parameters.Count - listedParameters} more");
foreach (var p in elem.Parameters.Skip(listedParameters).Where(parameter =>
parameter.Definition?.Name?.Contains("WIDTH", StringComparison.OrdinalIgnoreCase) == true
|| parameter.Definition?.Name?.Contains("HEIGHT", StringComparison.OrdinalIgnoreCase) == true
|| parameter.Definition?.Name?.Contains("ROUGH", StringComparison.OrdinalIgnoreCase) == true))
Console.WriteLine($" size [{p.Id}] {p.Definition?.Name ?? "?"} = {p.Value} ({p.StorageType})");
parameter.DefinitionName?.Contains("WIDTH", StringComparison.OrdinalIgnoreCase) == true
|| parameter.DefinitionName?.Contains("HEIGHT", StringComparison.OrdinalIgnoreCase) == true
|| parameter.DefinitionName?.Contains("ROUGH", StringComparison.OrdinalIgnoreCase) == true))
Console.WriteLine($" size [{p.Id}] {p.DefinitionName ?? "?"} = {p.Value} ({p.StorageType})");
if (elem.References != null)
Console.WriteLine($" References ({elem.References.Count}): {string.Join(", ", elem.References)}");
if (elem.Dimension != null)
Expand Down
2 changes: 1 addition & 1 deletion src/RvtIO.Cli/RvtIO.Cli.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
<TargetFrameworks>net8.0;net10.0</TargetFrameworks>
<!-- The read and export are allocation-heavy: server GC with a large gen0 budget cut a full run by ~20%. -->
<ServerGarbageCollection>true</ServerGarbageCollection>
<ConcurrentGarbageCollection>false</ConcurrentGarbageCollection>
<ConcurrentGarbageCollection>true</ConcurrentGarbageCollection>
</PropertyGroup>

<ItemGroup>
Expand Down
49 changes: 39 additions & 10 deletions src/RvtIO/Compact/CompactBuiltinParameters.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using System.Collections.Frozen;
using RvtIO.Internal;
using RvtIO.Model;
using RvtIO.Parsing;
Expand All @@ -20,6 +21,8 @@ internal sealed class CompactBuiltinParameters
/// <summary>The built-in entries of an element (ascending id) and the (group, label) pairs left without a validated value.</summary>
internal readonly record struct CompactBuiltinResult(
IReadOnlyList<(int Id, CompactProperty Property)> Entries, IReadOnlySet<(string Group, string Label)> Unvalidated);
private static readonly IReadOnlySet<(string Group, string Label)> EmptyUnvalidated =
FrozenSet<(string Group, string Label)>.Empty;

/// <summary>ELEM_DESIGN_OPTION_ID ("Design Option"). Without design option sets no element is in an option, so the
/// parameter is the null id and prints "None".</summary>
Expand All @@ -34,16 +37,19 @@ internal readonly record struct CompactBuiltinResult(
}

private readonly CompactElementNames _names;
private readonly Func<int, Element?> _findElement;
private readonly CompactFormatSettings? _format;
private readonly CompactListFileFacts _file;
private readonly Func<Element, int?> _headerCategory;
private readonly bool _usesDefaultHeaderCategory;
private readonly CompactValueGate? _gate;
private readonly ParsingState? _state;
private readonly CompactSolidQuantities? _quantities;
private readonly double? _surveyOffsetFeet;
private readonly string? _lookupNoneText;
private readonly Dictionary<int, Parameter> _held = [];
private readonly HashSet<int> _conflicting = [];
private readonly HashSet<(string Group, string Label)> _seen = [];
private readonly Dictionary<string, int> _skipped = new(StringComparer.Ordinal);

/// <param name="gate">Which value sources are trusted per parameter; null writes the derived value for every parameter and
Expand All @@ -61,8 +67,10 @@ public CompactBuiltinParameters(CompactElementNames names, CompactFormatSettings
_state = state;
_surveyOffsetFeet = surveyOffsetFeet;
_names = names;
_findElement = names.Find;
_format = format;
_file = file;
_usesDefaultHeaderCategory = headerCategory == null;
_headerCategory = headerCategory ?? CompactHeaderCategory.Of;
_gate = gate;
}
Expand Down Expand Up @@ -93,6 +101,26 @@ public CompactBuiltinParameters(CompactElementNames names, CompactFormatSettings

public int Elements { get; private set; }

internal bool CanFork => _usesDefaultHeaderCategory
&& Trace == null && FactsTrace == null && Candidates == null && IdListOverride == null;

internal CompactBuiltinParameters Fork() =>
new(_names, _format, _file, gate: _gate, state: _state, surveyOffsetFeet: _surveyOffsetFeet,
lookupNoneText: _lookupNoneText, quantities: _quantities);

internal void CollectReport(CompactBuiltinParameters worker)
{
if (worker.Elements == 0) return;
Elements += worker.Elements;
Written += worker.Written;
ElementsWithList += worker.ElementsWithList;
LastIds = worker.LastIds;
foreach (var (reason, count) in worker._skipped)
_skipped[reason] = _skipped.GetValueOrDefault(reason) + count;
worker.Elements = worker.Written = worker.ElementsWithList = 0;
worker._skipped.Clear();
}

/// <summary>The entries in ascending id order, and the (group, label) pairs that are listed but whose value is not written: a later
/// parameter with the same pair must not be written either, because the writer keeps the first value of a repeated pair.
/// Ids owned by another source (<paramref name="isOwned"/>) are not looked at.</summary>
Expand All @@ -101,23 +129,24 @@ public CompactBuiltinResult GetEntries(Element element, Func<int, bool>? isOwned
Elements++;
int? header = _headerCategory(element);
string recordClass = ElementListFacts.RecordClassName(element) ?? "";
var facts = new ElementListFacts(element, header, _file, id => _names.Find(id));
var facts = new ElementListFacts(element, header, _file, _findElement);
FactsTrace?.Invoke(element, facts);
var list = IdListOverride?.Invoke(element) is { } forced
? new CompactListResult(forced, null)
: CompactParameterLists.GetBuiltinIds(recordClass, facts);
LastIds = list.Ids;
if (list.Ids is not { } ids)
{
Skip("list: " + list.Unknown);
Trace?.Invoke(element, 0, "list: " + list.Unknown);
return new([], new HashSet<(string, string)>());
string reason = "list: " + list.Unknown;
Skip(reason);
Trace?.Invoke(element, 0, reason);
return new([], EmptyUnvalidated);
}
ElementsWithList++;
Prepare(element);
var result = new List<(int, CompactProperty)>(ids.Length);
var unvalidated = new HashSet<(string, string)>();
var seen = new HashSet<(string, string)>();
HashSet<(string Group, string Label)>? unvalidated = null;
_seen.Clear();
foreach (int id in ids)
{
if (isOwned?.Invoke(id) == true) continue;
Expand All @@ -135,8 +164,8 @@ public CompactBuiltinResult GetEntries(Element element, Func<int, bool>? isOwned
}
string? text = ValueText(element, id, header, out string? reason);
// a repeated (group, label): the first id is the one kept, whatever the writer is given later
bool first = seen.Add((group, label));
if (!first && text != null && unvalidated.Contains((group, label)))
bool first = _seen.Add((group, label));
if (!first && text != null && unvalidated?.Contains((group, label)) == true)
{
text = null;
reason = "label shared with an earlier parameter whose value is not written";
Expand All @@ -145,14 +174,14 @@ public CompactBuiltinResult GetEntries(Element element, Func<int, bool>? isOwned
{
Skip(reason!);
Trace?.Invoke(element, id, reason);
if (first) unvalidated.Add((group, label));
if (first) (unvalidated ??= new()).Add((group, label));
continue;
}
Trace?.Invoke(element, id, null);
result.Add((id, new CompactProperty(group, label, text)));
Written++;
}
return new(result, unvalidated);
return new(result, unvalidated ?? EmptyUnvalidated);
}

private void Prepare(Element element)
Expand Down
21 changes: 13 additions & 8 deletions src/RvtIO/Compact/CompactElementNames.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using System.Collections.Concurrent;
using RvtIO.Export;
using RvtIO.Internal;
using RvtIO.Model;
Expand All @@ -14,36 +15,40 @@ namespace RvtIO.Compact;
/// </summary>
internal sealed class CompactElementNames
{
private readonly Dictionary<int, Element> _byId = [];
private readonly Dictionary<int, int> _counts = [];
private readonly Dictionary<int, Element> _byId;
private readonly Dictionary<int, int> _counts;
private readonly ParsingState? _state;
private readonly Dictionary<int, string?> _cache = [];
private readonly ConcurrentDictionary<int, string?> _cache = new();

public CompactElementNames(RevitFileInfo info, ParsingState? state)
{
ArgumentNullException.ThrowIfNull(info);
_state = state;
_byId = new(info.Elements.Count);
_counts = new(info.Elements.Count);
foreach (Element element in info.Elements)
{
_byId.TryAdd(element.Id, element);
_counts[element.Id] = _counts.GetValueOrDefault(element.Id) + 1;
}
}

internal void ApplyValidatedNames(RevitFileInfo info, ParsingState state) =>
ValidatedElementNames.Apply(info, state, _byId, _counts);

/// <summary>The element with the id, null when the file has none.</summary>
public Element? Find(int id) => _byId.GetValueOrDefault(id);

/// <summary>The validated name of the element with the id; null when there is none.</summary>
public string? NameOf(int id)
public string? NameOf(int id) => _cache.GetOrAdd(id, static (key, names) => names.ResolveName(key), this);

private string? ResolveName(int id)
{
if (_cache.TryGetValue(id, out string? known)) return known;
string? name = null;
if (_byId.TryGetValue(id, out Element? element))
name = _state != null
? ValidatedElementNames.Resolve(element, _byId, _counts, _state)?.Name
: element.RuleClassName == "MaterialElem" ? element.SerializedMaterialName : null;
if (string.IsNullOrWhiteSpace(name)) name = null;
_cache[id] = name;
return name;
return string.IsNullOrWhiteSpace(name) ? null : name;
}
}
2 changes: 2 additions & 0 deletions src/RvtIO/Compact/CompactIdentity.cs
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ private readonly record struct ClassRule(
private readonly Dictionary<int, Element> _rows = [];
private readonly Func<Element, int?> _headerCategory;
private readonly Func<Element, string?> _elementName;
internal bool UsesDefaultResolvers { get; }

/// <param name="rows">The elements of the element table (<see cref="CompactUniverse"/>); a type is looked up among them.</param>
/// <param name="headerCategory">The header category of an element, null when unknown (default <see cref="CompactHeaderCategory.Of"/>).</param>
Expand All @@ -70,6 +71,7 @@ public CompactIdentity(IEnumerable<Element> rows, Func<Element, int?>? headerCat
{
ArgumentNullException.ThrowIfNull(rows);
foreach (var element in rows) _rows.TryAdd(element.Id, element);
UsesDefaultResolvers = headerCategory == null && elementName == null;
_headerCategory = headerCategory ?? CompactHeaderCategory.Of;
_elementName = elementName ?? (element => element.Name);
}
Expand Down
Loading
Loading