Skip to content
Open
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
13 changes: 13 additions & 0 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
51 changes: 32 additions & 19 deletions src/RvtIO.Cli/ExportCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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<uint> 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)
{
Expand Down Expand Up @@ -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),
Expand All @@ -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)
Expand All @@ -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)
Expand Down Expand Up @@ -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();
Expand Down Expand Up @@ -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)
{
Expand All @@ -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;
Expand Down Expand Up @@ -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);
}

Expand All @@ -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());
Expand All @@ -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);
Expand Down
142 changes: 142 additions & 0 deletions src/RvtIO.Cli/FullJsonOutput.cs
Original file line number Diff line number Diff line change
@@ -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<byte>
{
private byte[] _buffer = new byte[64 << 10];
public void Advance(int count) => output.Write(_buffer, 0, count);
public Memory<byte> GetMemory(int sizeHint = 0)
{
if (sizeHint > _buffer.Length) _buffer = new byte[sizeHint];
return _buffer;
}
public Span<byte> 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<List<Element>>
{
public override List<Element> Read(ref Utf8JsonReader reader, Type type, JsonSerializerOptions opts) => throw new NotSupportedException();

public override void Write(Utf8JsonWriter writer, List<Element> 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<byte> 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<byte> 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();
}
}
Loading
Loading