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
3 changes: 3 additions & 0 deletions src/RvtIO.Scene/RvtSceneOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,7 @@ public sealed class RvtSceneOptions

/// <summary>Includes straight model lines and reinforcement described by its centre lines.</summary>
public bool IncludeModelLinesAndReinforcement { get; set; }

/// <summary>Includes reference geometry for project grids and levels.</summary>
public bool IncludeDatumGeometry { get; set; }
}
9 changes: 7 additions & 2 deletions src/RvtIO.Scene/RvtSceneReader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,11 @@ public static RvtSceneResult Read(RvtDocument document, MeshSet meshes, RvtScene
}

private static ElementMeshOptions? MeshOptions(RvtSceneOptions? options) =>
options?.IncludeModelLinesAndReinforcement == true ? new() { IncludeModelLinesAndReinforcement = true } : null;
options is null ? null : new()
{
IncludeModelLinesAndReinforcement = options.IncludeModelLinesAndReinforcement,
IncludeDatumGeometry = options.IncludeDatumGeometry,
};

private static string RequiredKey(RvtSceneOptions? options) => options?.ModelKey is { Length: > 0 } key ? key
: throw new ArgumentException("A document has no file name: give the model key in RvtSceneOptions.ModelKey.", nameof(options));
Expand Down Expand Up @@ -168,7 +172,7 @@ private static RvtSceneResult Map(RvtDocument document, MeshSet meshes, string m
{
Id = mesh.ElementId,
ModelId = ModelId,
LevelId = storeys.GetStoreyId(mesh.ElementId),
LevelId = mesh.IsDatum ? null : storeys.GetStoreyId(mesh.ElementId),
SourceId = element?.UniqueId,
IfcGuid = element != null ? IfcGuidOf(element) : null,
Kind = SceneNodeKind.Element,
Expand Down Expand Up @@ -273,6 +277,7 @@ private static RvtSceneResult Map(RvtDocument document, MeshSet meshes, string m
Diagnostics = report,
ElementCount = scene.Elements.Count,
ElementsWithGeometry = withGeometry,
HiddenDatumIds = meshes.Elements.Where(mesh => mesh.IsDatum).Select(mesh => (long)mesh.ElementId).ToArray(),
Coverage = coverage,
GeometryCount = scene.Geometries.Count,
InstanceCount = scene.Instances.Count,
Expand Down
3 changes: 3 additions & 0 deletions src/RvtIO.Scene/RvtSceneResult.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,9 @@ public sealed class RvtSceneResult
/// <summary>The number of elements that have at least one instance.</summary>
public int ElementsWithGeometry { get; init; }

/// <summary>Revit datum IDs whose reference geometry is hidden by default in native export.</summary>
public IReadOnlyList<long> HiddenDatumIds { get; init; } = [];

/// <summary>The number of elements by the coverage of their meshes; a coverage that no element has is not listed.</summary>
public IReadOnlyDictionary<MeshCoverage, int> Coverage { get; init; } = new Dictionary<MeshCoverage, int>();

Expand Down
1 change: 1 addition & 0 deletions src/RvtIO/Internal/ParsingState.cs
Original file line number Diff line number Diff line change
Expand Up @@ -390,6 +390,7 @@ public TfBlockDeserializer.UnitsElemOptions? OwnDocumentUnitOptions
/// the serialized datum text, free end, bubble end and cut vector. The element-level
/// name remains authoritative for the grid mark because datum text may name its head type.</summary>
public Dictionary<uint, GridDatumData> GridDatums { get; } = new();
public Dictionary<uint, Model.GridPlaneData> LevelPlanes { get; } = new();
public Dictionary<uint, AreaSketchPlane> AreaReinforcementPlanes { get; } = new();
public (List<Model.GridAxis> Paths, HashSet<int> Members)? GridAxes { get; set; }

Expand Down
3 changes: 3 additions & 0 deletions src/RvtIO/Meshes/ElementMeshOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,7 @@ public sealed class ElementMeshOptions

/// <summary>Includes decoded straight model lines and meshes of reinforcement described by its centre lines.</summary>
public bool IncludeModelLinesAndReinforcement { get; set; }

/// <summary>Includes the finite reference lines of grids and levels for native cache export.</summary>
public bool IncludeDatumGeometry { get; set; }
}
49 changes: 49 additions & 0 deletions src/RvtIO/Meshes/ElementMeshes.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using RvtIO.BuiltIns;
using RvtIO.Geometry.Meshing;
using RvtIO.Internal;
using RvtIO.Model;
using RvtIO.Parsing;

Expand Down Expand Up @@ -167,9 +168,57 @@ int MaterialOf(GeoFace face)
UntriangulatedFaces = failed,
});
}
if (options.IncludeDatumGeometry)
{
var existing = elements.Select(element => element.ElementId).ToHashSet();
double lowestLevel = info.Elements.Where(element => BuildingStoreyResolver.IsProjectLevel(element) && element.LevelPlane != null)
.Select(element => element.LevelPlane!.Origin[2]).Where(double.IsFinite).DefaultIfEmpty(double.NaN).Min();
foreach (var element in info.Elements)
if (!existing.Contains(element.Id) && DatumLinePairs(element, lowestLevel) is { } linePairs)
{
elements.Add(new ElementMesh
{
ElementId = element.Id, LinePairs = linePairs, IsDatum = true, Coverage = MeshCoverage.Complete,
});
}
}
return new MeshSet { Elements = elements, Symbols = placedSymbols, GeometryUndecoded = info.WideLayoutNotRewritten };
}

private static MeshVector[]? DatumLinePairs(Element element, double lowestLevel)
{
var plane = element.CategoryId switch
{
(int)BuiltInCategory.OST_Levels when BuildingStoreyResolver.IsProjectLevel(element) => element.LevelPlane,
(int)BuiltInCategory.OST_Grids => element.GridPlane,
_ => null,
};
if (plane?.Envelope is not [var u0, var v0, var u1, var v1]
|| plane.Origin.Length != 3 || plane.XVector.Length != 3 || plane.YVector.Length != 3
|| !plane.Envelope.Concat(plane.Origin).Concat(plane.XVector).Concat(plane.YVector).All(double.IsFinite)
|| !(u1 > u0 && v1 > v0)) return null;

MeshVector Point(double u, double v) => new(
plane.Origin[0] + u * plane.XVector[0] + v * plane.YVector[0],
plane.Origin[1] + u * plane.XVector[1] + v * plane.YVector[1],
plane.Origin[2] + u * plane.XVector[2] + v * plane.YVector[2]);

if (element.CategoryId == (int)BuiltInCategory.OST_Grids)
{
double bottom = plane.YVector[2] >= 0 ? v0 : v1;
if (double.IsFinite(lowestLevel) && plane.YVector[2] != 0)
bottom = Math.Clamp((lowestLevel - plane.Origin[2]) / plane.YVector[2], v0, v1);
return [Point(u0, bottom), Point(u1, bottom)];
}
// Level outlines follow the west and north bounds in project coordinates.
MeshVector[] corners = [Point(u0, v0), Point(u0, v1), Point(u1, v0), Point(u1, v1)];
double west = corners.Min(point => point.X);
double north = corners.Max(point => point.Y);
double z = plane.Origin[2];
MeshVector corner = new(west, north, z);
return [new(west, corners.Min(point => point.Y), z), corner, corner, new(corners.Max(point => point.X), north, z)];
}

// A ghost node is a Geometry node Revit exports that has no polygon here (display surfaces, or a duplicate of another node).
private static MeshCoverage CoverageOf(bool drawn, GeometryData geometry, int failed, bool symbolGhosts) =>
!drawn ? MeshCoverage.NoGeometry
Expand Down
3 changes: 3 additions & 0 deletions src/RvtIO/Meshes/MeshSet.cs
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,9 @@ public sealed class ElementMesh
/// <summary>Independent line segments listed as consecutive endpoint pairs, in document feet.</summary>
public IReadOnlyList<MeshVector>? LinePairs { get; init; }

/// <summary>Whether the line pairs are datum references that are hidden by default.</summary>
public bool IsDatum { get; init; }

/// <summary>How completely <see cref="Meshes"/> and <see cref="Placements"/> represent the element.</summary>
public MeshCoverage Coverage { get; init; }

Expand Down
3 changes: 3 additions & 0 deletions src/RvtIO/Model/Element.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1058,6 +1058,9 @@ internal bool RootClassIs(string className) => NativeRootClassName != null
[JsonIgnore]
internal GridPlaneData? GridPlane { get; set; }

[JsonIgnore]
internal GridPlaneData? LevelPlane { get; set; }

/// <summary>CompoundStructure layers (wall/floor/ceiling types). Each layer has thickness, function, material.</summary>
public List<MaterialLayer>? Layers { get; set; }

Expand Down
1 change: 1 addition & 0 deletions src/RvtIO/Parsing/ElementBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3601,6 +3601,7 @@ void ApplyType(int typeId)
if (np.Fields.ContainsKey("__isLevel"))
{
e.IsNativeLevel = true;
e.LevelPlane = state.LevelPlanes.GetValueOrDefault((uint)e.Id);
if (np.DoubleFields.TryGetValue("__levelElevation", out double levelElevation)
&& double.IsFinite(levelElevation))
Apply(-1007102, StorageType.Double, levelElevation, force: true);
Expand Down
12 changes: 7 additions & 5 deletions src/RvtIO/Parsing/TfBlockDeserializer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4146,17 +4146,19 @@ double[] PointAt(double parameter) =>
origin.ToArray(), yVector.ToArray());
}

/// <summary>Decode the exact Level elevation from its authored datum Plane origin.</summary>
public static double? ExtractLevelElevation(byte[] d, int blockStart, uint dataSize,
/// <summary>Decode a Level's authored finite datum plane.</summary>
public static Model.GridPlaneData? ExtractLevelPlane(byte[] d, int blockStart, uint dataSize,
ushort classId)
{
if (classId != 2299) return null;
var surface = ExtractDatumPlaneSurface(d, blockStart, dataSize, classId);
if (surface == null) return null;
double elevation = surface.Value.Origin[2];
return double.IsFinite(elevation) ? elevation : null;
return surface is { } plane ? new(plane.Envelope, plane.Origin, plane.XVector, plane.YVector) : null;
}

public static double? ExtractLevelElevation(byte[] d, int blockStart, uint dataSize, ushort classId) =>
ExtractLevelPlane(d, blockStart, dataSize, classId) is { } plane && double.IsFinite(plane.Origin[2])
? plane.Origin[2] : null;

private static (double[] Envelope, double[] Origin, double[] XVector, double[] YVector)?
ExtractDatumPlaneSurface(byte[] d, int blockStart, uint dataSize, ushort classId)
{
Expand Down
8 changes: 5 additions & 3 deletions src/RvtIO/RvtFileReader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2524,9 +2524,11 @@ internal static void RunTfStreamWalk(ParsingState state)
seg, bs, (uint)ds, cls);
if (!string.IsNullOrWhiteSpace(levelName))
np.StringFields["m_text"] = levelName;
if (TfBlockDeserializer.ExtractLevelElevation(
seg, bs, (uint)ds, cls) is double levelElevation)
np.DoubleFields["__levelElevation"] = levelElevation;
if (TfBlockDeserializer.ExtractLevelPlane(seg, bs, (uint)ds, cls) is { } plane)
{
state.LevelPlanes[eid] = plane;
if (double.IsFinite(plane.Origin[2])) np.DoubleFields["__levelElevation"] = plane.Origin[2];
}
}
if (np is { Count: > 0 }) state.NativeParams[eid] = np;
if (cls == 0x083C
Expand Down
31 changes: 31 additions & 0 deletions tests/RvtIO.Tests/NwcSupplementalGeometryTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,37 @@ public void NativeAreaReinforcementKeepsBothCopiesOfTheHostOutline()
Assert.Equal(2, points.Chunk(2).Count(pair => pair[0].X != pair[1].X && pair[0].Y != pair[1].Y));
}

[Fact]
public void NativeDatumsKeepTheirIdsAndHiddenReferenceGeometry()
{
var level = new Element
{
Id = 1, Name = "Level", CategoryId = (int)BuiltInCategory.OST_Levels,
IsNativeLevel = true, SerializedFamilyId = -1, SerializedUnplacedOwnerId = -1, SerializedOwnerDbViewId = -1,
LevelPlane = new([1, -4, 5, 0], [0, 0, 2], [0, 1, 0], [-1, 0, 0]),
};
var grid = new Element
{
Id = 2, Name = "Grid", CategoryId = (int)BuiltInCategory.OST_Grids,
GridPlane = new([1, 0, 6, 10], [0, 0, 0], [1, 0, 0], [0, 0, 1]),
};
var document = RvtDocument.FromInfo(new RevitFileInfo { Elements = [level, grid] });
Assert.Empty(RvtSceneReader.Read(document, new() { ModelKey = "model" }).Document.Elements);
var scene = RvtSceneReader.Read(document, new() { ModelKey = "model", IncludeDatumGeometry = true });
Assert.Equal([1L, 2L], scene.HiddenDatumIds);
var native = Nwc.NwcExport.Build(scene.Document, "model.rvt", 0, DateTime.UnixEpoch, native: true, scene.HiddenDatumIds.ToHashSet());
Assert.All(native.Meshes, mesh => Assert.True(mesh.Node!.IsHidden));
var levelMesh = native.Meshes.Single(mesh => mesh.Node!.Name == "Level");
var levelPoints = levelMesh.GetWorldVertices().ToArray();
Assert.Equal(new NwcIO.Model.Vector3d(0, 0.3048, 2 * 0.3048), levelPoints[levelMesh.LineIndices[0]]);
Assert.Equal(new NwcIO.Model.Vector3d(0, 5 * 0.3048, 2 * 0.3048), levelPoints[levelMesh.LineIndices[1]]);
Assert.Equal(levelPoints[levelMesh.LineIndices[1]], levelPoints[levelMesh.LineIndices[2]]);
Assert.Equal(new NwcIO.Model.Vector3d(4 * 0.3048, 5 * 0.3048, 2 * 0.3048), levelPoints[levelMesh.LineIndices[3]]);
var gridMesh = native.Meshes.Single(mesh => mesh.Node!.Name == "Grid");
Assert.Equal(2, gridMesh.LineIndices.Count);
Assert.All(gridMesh.GetWorldVertices(), point => Assert.Equal(2 * 0.3048, point.Z, 12));
}

[Fact]
public void SweepKeepsTheStoredRadiusAndExtentsOfAStraightBar()
{
Expand Down
4 changes: 3 additions & 1 deletion tools/RvtIO.Nwc/NwcExport.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@ internal static class NwcExport
// The optional metadata is written by NwcIO 0.14 and interpreted by the linked-cache reader.
private const string MetreCacheOption = "IOExtend.NwcWriter.Scene/1";
private const string LinkClass = "IOExtend.NwcWriter.Link";
internal static NwcDocument Build(SceneDocument scene, string sourceName, long sourceLength, DateTime timestamp, bool native = false)
internal static NwcDocument Build(SceneDocument scene, string sourceName, long sourceLength, DateTime timestamp,
bool native = false, IReadOnlySet<long>? hiddenDatumIds = null)
{
if (scene.Validate().FirstOrDefault(d => d.Severity == SceneSeverity.Error) is { } error)
throw new InvalidDataException(error.Message);
Expand Down Expand Up @@ -44,6 +45,7 @@ internal static NwcDocument Build(SceneDocument scene, string sourceName, long s
{
node.Class = "LcRevitElement";
node.IfcGlobalId = element.IfcGuid;
node.IsHidden = hiddenDatumIds?.Contains(element.Id) == true;
}
AddText(node, "Revit", "Element ID", id);
AddText(node, "Revit", "UniqueId", element.SourceId);
Expand Down
8 changes: 6 additions & 2 deletions tools/RvtIO.Nwc/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -47,13 +47,17 @@ public static int Main(string[] args)

var source = new FileInfo(input);
long length = source.Length;
var scene = RvtSceneReader.Read(input, native ? new RvtSceneOptions { IncludeModelLinesAndReinforcement = true } : null);
var scene = RvtSceneReader.Read(input, native ? new RvtSceneOptions
{
IncludeModelLinesAndReinforcement = true,
IncludeDatumGeometry = true,
} : null);
foreach (var diagnostic in scene.Diagnostics.Where(d => d.Severity != SceneSeverity.Info))
Console.Error.WriteLine($"RVT {diagnostic.Severity} [{diagnostic.Code}]: {diagnostic.Message}");
if (scene.Diagnostics.Any(d => d.Severity == SceneSeverity.Error))
return 2;

var cache = NwcExport.Build(scene.Document, source.Name, length, source.LastWriteTimeUtc, native);
var cache = NwcExport.Build(scene.Document, source.Name, length, source.LastWriteTimeUtc, native, scene.HiddenDatumIds.ToHashSet());
NwcExport.Save(cache, output, native);
int lines = cache.Meshes.Count(mesh => mesh.LineIndices.Count != 0);
string lineCount = lines > 0 ? $" and {lines} line meshes" : "";
Expand Down
Loading