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
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ API between minor releases.
- `ioviewer` reads Navisworks `.nwc` caches through `NwcIO.Scene` 0.13.0.
- Standalone HTML opens with the section box or cutting planes saved in `ViewerDocument`.
- Change or reset the viewport background color from the display menu.
- Saved viewpoints can restore clipping, hidden elements and linked-file checkboxes. The viewpoint list and the
tour both use the saved state.

### Fixed

Expand Down
30 changes: 29 additions & 1 deletion docs/public-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,14 +27,42 @@ The model data is the IOScene scene model, referenced by the `IOViewer` package.
### Viewer document (`IOViewer.Model`)

- `ViewerDocument`: a `Scene` plus what only the viewer uses: `SectionPlanes`, `SectionBox` and `HiddenModelKeys`, the
keys of the linked models hidden at start. `Title` reads and writes `Scene.Title`.
keys of the linked models hidden at start. `ViewpointStates` adds optional state to saved cameras. `Title` reads and
writes `Scene.Title`.
- `ViewerSectionPlane`: Cutting plane defined by axis or custom normal. `Offset` is the signed distance in metres
from the scene origin along its unit normal. By default the plane cuts the side the normal points to. `Inverted`
cuts the opposite side.
- `ViewerSectionBox`: 6-sided clipping volume in scene coordinates. `Inverted` cuts inside the box.
Exported HTML opens in box mode when the box is enabled, or in planes mode with the first six enabled planes.
Both are available if the document supplies both. Editing handles start hidden.

#### Saved viewpoint state

Use a unique `SceneViewpoint.Id` and the same key in `ViewerDocument.ViewpointStates`. A `ViewerViewpointState` can
restore clipping, element visibility and linked-file checkboxes. The view list and the tour apply the same state.

```csharp
doc.Scene.Viewpoints.Add(new SceneViewpoint
{
Id = "mep-review",
Name = "MEP review",
Camera = new SceneCamera { Position = new(8, -12, 6), Target = new(0, 0, 2) },
});
doc.ViewpointStates["mep-review"] = new ViewerViewpointState
{
SectionPlanes = [new ViewerSectionPlane(ViewerSectionAxis.Z, 4)],
HiddenElementIds = [42],
HiddenModelKeys = ["structure.rvt"],
};
```

IDs refer to `SceneElement.Id`, and linked models use `SceneModel.Key`. The example assumes element `42` and linked
model `structure.rvt` already exist in the scene. Each supplied list replaces its layer. Use an empty list to clear
its hides, or `null` to preserve the current layer. Use `SectionPlanes = []` with no box to clear clipping, or leave
both clipping properties null to keep it. An enabled section box takes priority over the planes. The 4D schedule
continues to control its own layer. Viewer JSON keeps the state, and old camera-only views preserve current clipping
and visibility.

### Exporters (`IOViewer.Exporters`)

- `HtmlViewerExporter`: Generates self-contained, offline-ready 3D HTML viewers using packed Base64 binary buffers. Takes a `ViewerDocument` or a `SceneDocument`. The page is written to the output stream as it is produced.
Expand Down
5 changes: 4 additions & 1 deletion src/IOViewer/Exporters/JsonViewerExporter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ namespace IOViewer.Exporters;

/// <summary>
/// Writes a <see cref="ViewerDocument"/> as viewer JSON: <c>{ "Kind": "ioviewer", "Format": 2, "Scene": {...},
/// "SectionPlanes", "SectionBox", "HiddenModelKeys" }</c>, with the scene in the encoding of scene JSON.
/// "SectionPlanes", "SectionBox", "HiddenModelKeys", "ViewpointStates" }</c>, with the scene in the encoding of scene JSON.
/// </summary>
/// <remarks>A scene alone is written as a scene file with <see cref="SceneJson"/>.</remarks>
public static class JsonViewerExporter
Expand Down Expand Up @@ -67,19 +67,22 @@ internal sealed class ViewerJsonFile
public List<ViewerSectionPlane> SectionPlanes { get; set; } = [];
public ViewerSectionBox? SectionBox { get; set; }
public List<string> HiddenModelKeys { get; set; } = [];
public Dictionary<string, ViewerViewpointState>? ViewpointStates { get; set; }

public static ViewerJsonFile From(ViewerDocument doc) => new()
{
Scene = doc.Scene,
SectionPlanes = doc.SectionPlanes,
SectionBox = doc.SectionBox,
HiddenModelKeys = doc.HiddenModelKeys,
ViewpointStates = doc.ViewpointStates is { Count: > 0 } ? doc.ViewpointStates : null,
};

public ViewerDocument ToDocument() => new(Scene)
{
SectionPlanes = SectionPlanes,
SectionBox = SectionBox,
HiddenModelKeys = HiddenModelKeys,
ViewpointStates = ViewpointStates ?? [],
};
}
104 changes: 88 additions & 16 deletions src/IOViewer/Exporters/ViewerPayloadWriter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -43,8 +43,8 @@ internal sealed class ViewerPayloadWriter
private readonly List<uint> _instanceMaterial = [];
private readonly List<int> _instanceElement = [];
private readonly List<float> _instanceMatrix = [];
private readonly List<(string Axis, Vector3d Normal, double Offset, bool Flipped)> _sectionPlanes = [];
private (BoundingBox3d Bounds, bool Inverted)? _sectionBox;
private readonly Dictionary<string, PreparedViewpoint> _viewpointStates = new(StringComparer.Ordinal);
private SectionState _sections;
private BoundingBox3d _bounds;
private Vector3d _rtcOffset;
private int _drawable;
Expand All @@ -64,15 +64,17 @@ private ViewerPayloadWriter(ViewerDocument doc, HtmlViewerOptions options)
public static ViewerPayloadWriter Create(ViewerDocument doc, HtmlViewerOptions options)
{
var writer = new ViewerPayloadWriter(doc, options);
writer.Build();
writer.BuildSections(doc);
var elementIndex = writer.Build();
writer._sections = writer.BuildSections(doc.SectionPlanes, doc.SectionBox);
writer.BuildViewpointStates(doc.ViewpointStates, elementIndex);
writer.ValidateMetadata();
return writer;
}

private void BuildSections(ViewerDocument doc)
private SectionState BuildSections(List<ViewerSectionPlane>? planes, ViewerSectionBox? sectionBox)
{
foreach (var plane in doc.SectionPlanes ?? [])
var output = new List<(string Axis, Vector3d Normal, double Offset, bool Flipped)>();
foreach (var plane in planes ?? [])
{
if (plane is not { Enabled: true }) continue;
var (axis, normal) = plane.Axis switch
Expand All @@ -91,15 +93,47 @@ private void BuildSections(ViewerDocument doc)
// n·p = offset in scene coordinates, and p = rtcPoint + rtcOffset.
double offset = plane.Offset - Vector3d.Dot(normal, _rtcOffset);
if (!double.IsFinite(offset)) throw new InvalidDataException("The section plane offset must be finite in viewer coordinates.");
_sectionPlanes.Add((axis, normal, offset, plane.Inverted));
if (_sectionPlanes.Count == MaxSectionPlanes) break;
output.Add((axis, normal, offset, plane.Inverted));
if (output.Count == MaxSectionPlanes) break;
}

if (doc.SectionBox is not { Enabled: true } box) return;
if (sectionBox is not { Enabled: true } box) return new(output, null);
var bounds = new BoundingBox3d(box.Min - _rtcOffset, box.Max - _rtcOffset);
if (bounds.IsEmpty || !IsFinite(bounds.Min) || !IsFinite(bounds.Max))
throw new InvalidDataException("The section box must have finite bounds with Min at or below Max on each axis.");
_sectionBox = (bounds, box.Inverted);
return new(output, (bounds, box.Inverted));
}

private void BuildViewpointStates(Dictionary<string, ViewerViewpointState>? states, Dictionary<long, int> elementIndex)
{
if (!_options.IncludeViewpoints || states is not { Count: > 0 }) return;

var linkedKeys = _scene.Models.Skip(1).Select(model => model.Key).ToHashSet(StringComparer.Ordinal);
foreach (var view in _scene.Viewpoints)
{
if (view.Id is not { } id || !states.TryGetValue(id, out var state)) continue;
if (state is null) throw new InvalidDataException($"Viewpoint '{id}' has a null state.");
if (_viewpointStates.ContainsKey(id))
throw new InvalidDataException($"Viewpoint state '{id}' matches more than one saved camera.");

SectionState? sections = state.SectionPlanes is not null || state.SectionBox is not null
? BuildSections(state.SectionPlanes, state.SectionBox)
: null;
int[]? hiddenElements = state.HiddenElementIds?.Select(elementId =>
elementIndex.TryGetValue(elementId, out int index)
? index
: throw new InvalidDataException($"Viewpoint '{id}' references unknown element {elementId}.")).ToArray();
string[]? hiddenModels = state.HiddenModelKeys?.ToArray();
if (hiddenModels?.Any(key => !linkedKeys.Contains(key)) == true)
throw new InvalidDataException($"Viewpoint '{id}' references an unknown linked model or the host.");
_viewpointStates.Add(id, new(sections, hiddenElements, hiddenModels));
}

foreach (string id in states.Keys)
{
if (!_viewpointStates.ContainsKey(id))
throw new InvalidDataException($"Viewpoint state '{id}' has no saved camera.");
}
}

private static bool IsFinite(Vector3d v) => double.IsFinite(v.X) && double.IsFinite(v.Y) && double.IsFinite(v.Z);
Expand Down Expand Up @@ -154,7 +188,7 @@ public static int UndrawnInstances(SceneDocument scene)
return scene.Instances.Count(i => topology.TryGetValue(i.GeometryId, out var t) && t != SceneTopology.Triangles);
}

private void Build()
private Dictionary<long, int> Build()
{
var geometries = new Dictionary<int, SceneGeometry>();
foreach (var geometry in _scene.Geometries)
Expand Down Expand Up @@ -263,6 +297,7 @@ private void Build()
_blob.Add(CollectionsMarshal.AsSpan(_instanceMaterial)),
_blob.Add(CollectionsMarshal.AsSpan(_instanceElement)),
_blob.Add(CollectionsMarshal.AsSpan(_instanceMatrix)));
return elementIndex;
}

private static void CheckIndices(IReadOnlyList<int> indices, int vertexCount, string owner)
Expand Down Expand Up @@ -699,7 +734,7 @@ public void WriteMeta(Stream output)
}
w.WriteEndArray();

WriteSections(w);
if (_sections.Planes.Count > 0 || _sections.Box is not null) WriteSections(w, _sections);
WriteViewpoints(w);
WriteGrids(w);
WriteTimeLiner(w);
Expand All @@ -709,12 +744,11 @@ public void WriteMeta(Stream output)
w.WriteEndObject();
}

private void WriteSections(Utf8JsonWriter w)
private static void WriteSections(Utf8JsonWriter w, SectionState sections)
{
if (_sectionPlanes.Count == 0 && _sectionBox is null) return;
w.WriteStartObject("sections");
w.WriteStartArray("planes");
foreach (var plane in _sectionPlanes)
foreach (var plane in sections.Planes)
{
w.WriteStartObject();
w.WriteString("axis", plane.Axis);
Expand All @@ -724,7 +758,7 @@ private void WriteSections(Utf8JsonWriter w)
w.WriteEndObject();
}
w.WriteEndArray();
if (_sectionBox is { } box)
if (sections.Box is { } box)
{
WriteBox(w, "box", box.Bounds, Vector3d.Zero);
w.WriteBoolean("cutInside", box.Inverted);
Expand All @@ -747,6 +781,17 @@ private void WriteViewpoints(Utf8JsonWriter w)
// A projection this version does not know is perspective (the enum is open).
w.WriteString("projection", vp.Camera.Projection == SceneProjection.Orthographic ? "orthographic" : "perspective");
w.WriteEndObject();
if (vp.Id is { } id && _viewpointStates.TryGetValue(id, out var state))
{
if (state.Sections is { } sections) WriteSections(w, sections);
if (state.HiddenElements is { } elements) WriteIndices(w, "hiddenElements", elements);
if (state.HiddenModels is { } models)
{
w.WriteStartArray("hiddenModelKeys");
foreach (string key in models) w.WriteStringValue(key);
w.WriteEndArray();
}
}
w.WriteEndObject();
}
}
Expand Down Expand Up @@ -827,12 +872,23 @@ void WriteTask(SceneTask t)
private void WriteLinkedFiles(Utf8JsonWriter w)
{
w.WriteStartArray("linkedFiles");
if (_scene.Models.Count < 2)
{
w.WriteEndArray();
return;
}
int host = _scene.Models[0].Id;
var members = _scene.Elements.Select((element, index) => (element.ModelId, index))
.Where(member => member.ModelId != host)
.ToLookup(member => member.ModelId, member => member.index);
foreach (var model in _scene.Models.Skip(1))
{
w.WriteStartObject();
w.WriteString("key", model.Key);
w.WriteString("name", model.Name);
w.WriteString("path", model.Path ?? string.Empty);
w.WriteBoolean("visible", !_hiddenModels.Contains(model.Key));
WriteIndices(w, "members", members[model.Id]);
w.WriteEndObject();
}
w.WriteEndArray();
Expand Down Expand Up @@ -889,6 +945,17 @@ private static void WriteView(Utf8JsonWriter w, string name, BlobView? view)
else w.WriteNullValue();
}

private static void WriteIndices(Utf8JsonWriter w, string name, IEnumerable<int> values)
{
w.WriteStartArray(name);
foreach (int index in values)
{
w.WriteNumberValue(index);
FlushIfLarge(w);
}
w.WriteEndArray();
}

private static void WriteVector(Utf8JsonWriter w, string name, Vector3d v)
{
if (!IsFinite(v)) throw new InvalidDataException($"The '{name}' vector is not finite in viewer coordinates.");
Expand All @@ -913,6 +980,11 @@ private static void FlushIfLarge(Utf8JsonWriter w)
if (w.BytesPending > FlushThreshold) w.Flush();
}

private readonly record struct SectionState(
List<(string Axis, Vector3d Normal, double Offset, bool Flipped)> Planes, (BoundingBox3d Bounds, bool Inverted)? Box);

private sealed record PreparedViewpoint(SectionState? Sections, int[]? HiddenElements, string[]? HiddenModels);

private readonly record struct MaterialKey(byte R, byte G, byte B, double Opacity, int? Texture);

// Origin is META q.o: set for u16 grid-step positions, null for f32.
Expand Down
3 changes: 3 additions & 0 deletions src/IOViewer/Model/ViewerDocument.cs
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,9 @@ public ViewerDocument(SceneDocument scene)
/// </summary>
public List<string> HiddenModelKeys { get; set; } = [];

/// <summary>Optional viewer state keyed by a unique, non-null <see cref="SceneViewpoint.Id"/> in this scene.</summary>
public Dictionary<string, ViewerViewpointState> ViewpointStates { get; set; } = [];

/// <summary>Title of the scene: reads and writes <see cref="SceneDocument.Title"/>.</summary>
[JsonIgnore]
public string Title
Expand Down
28 changes: 28 additions & 0 deletions src/IOViewer/Model/ViewerViewpointState.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
using IOScene;

namespace IOViewer.Model;

/// <summary>Optional clipping and visibility to restore along with a saved camera.</summary>
public sealed class ViewerViewpointState
{
/// <summary>
/// Cutting planes in scene coordinates. Null preserves clipping unless a section box is supplied.
/// An empty list clears clipping when there is no enabled box.
/// </summary>
public List<ViewerSectionPlane>? SectionPlanes { get; set; }

/// <summary>Section box in scene coordinates. An enabled box takes precedence over the planes.</summary>
public ViewerSectionBox? SectionBox { get; set; }

/// <summary>
/// Scene element IDs to hide in the user's visibility layer. Null preserves that layer and an empty list shows
/// all elements in it. Linked files and schedules still apply their own visibility.
/// </summary>
public List<long>? HiddenElementIds { get; set; }

/// <summary>
/// <see cref="SceneModel.Key"/> values of hidden linked models. Null preserves the linked-file checkboxes and an
/// empty list checks all linked files with elements. The host is controlled through <see cref="HiddenElementIds"/>.
/// </summary>
public List<string>? HiddenModelKeys { get; set; }
}
346 changes: 173 additions & 173 deletions src/IOViewer/Viewer/dist/viewer.js

Large diffs are not rendered by default.

21 changes: 14 additions & 7 deletions src/IOViewer/Viewer/src/data.js
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,12 @@ const records = (value) => Array.isArray(value) && value.every(object);
const vector = (value) => Array.isArray(value) && value.length === 3 && value.every((n) => typeof n === 'number');
const box = (value) => object(value) && vector(value.min) && vector(value.max);

const sectionState = (state) => state == null || (object(state) && records(state.planes)
&& state.planes.every((plane) => vector(plane.normal) && plane.normal.every(Number.isFinite)
&& plane.normal.some((value) => value !== 0) && Number.isFinite(plane.offset))
&& (state.box == null || (box(state.box) && state.box.max.every(Number.isFinite)
&& state.box.min.every((value, i) => Number.isFinite(value) && value <= state.box.max[i]))));

function validateMeta(meta) {
if (!object(meta) || !records(meta.elements) || !records(meta.geometries) || !records(meta.materials) || !object(meta.instances)) {
throw new ModelDataError('META must describe elements, geometries, materials and instances.');
Expand Down Expand Up @@ -80,17 +86,18 @@ function validateMeta(meta) {
throw new ModelDataError('Invalid META material.');
}
}
const elementIndices = (values) => values == null || (Array.isArray(values) &&
values.every((i) => Number.isInteger(i) && i >= 0 && i < meta.elements.length));
if (meta.grids?.some((grid) => !vector(grid.start) || !vector(grid.end))
|| meta.viewpoints?.some((view) => !vector(view.camera?.position) || !vector(view.camera?.target))
|| meta.viewpoints?.some((view) => !vector(view.camera?.position) || !vector(view.camera?.target)
|| !sectionState(view.sections) || !elementIndices(view.hiddenElements)
|| (view.hiddenModelKeys != null && (!Array.isArray(view.hiddenModelKeys) ||
!view.hiddenModelKeys.every((key) => typeof key === 'string'))))
|| meta.clashTests?.some((test) => !records(test.clashes) || test.clashes.some((clash) => !vector(clash.point)))) {
throw new ModelDataError('Invalid META grids, viewpoints or clashes.');
}
const { sections } = meta;
if (sections != null && (!object(sections) || !records(sections.planes)
|| sections.planes.some((plane) => !vector(plane.normal) || typeof plane.offset !== 'number')
|| (sections.box != null && !box(sections.box)))) {
throw new ModelDataError('Invalid META sections.');
}
if (meta.linkedFiles?.some((file) => !elementIndices(file.members))) throw new ModelDataError('Invalid META linked file members.');
if (!sectionState(meta.sections)) throw new ModelDataError('Invalid META sections.');
}

export function readModelMeta(doc = document, startup) {
Expand Down
Loading
Loading