From df98f46503cd4e0def0f229b88c83e4104f27a28 Mon Sep 17 00:00:00 2001 From: mahach666 <79989386+mahach666@users.noreply.github.com> Date: Wed, 18 Nov 2026 18:44:51 +0300 Subject: [PATCH] Export placed source models into one standalone viewer --- CHANGELOG.md | 1 + README.md | 13 + docs/public-api.md | 6 +- src/IOViewer.Cli/Program.cs | 65 +++- src/IOViewer.Cli/SceneFederation.cs | 282 ++++++++++++++++++ src/IOViewer/Exporters/JsonViewerExporter.cs | 7 +- src/IOViewer/Exporters/ViewerPayloadWriter.cs | 24 +- src/IOViewer/Model/ViewerDocument.cs | 6 +- src/IOViewer/Model/ViewerViewpointState.cs | 3 +- src/IOViewer/Viewer/playwright.config.js | 2 +- .../Viewer/test/e2e/federation.spec.js | 59 ++++ src/IOViewer/Viewer/test/e2e/global-setup.js | 12 + tests/IOViewer.Tests/FederatedCliTests.cs | 182 +++++++++++ 13 files changed, 633 insertions(+), 29 deletions(-) create mode 100644 src/IOViewer.Cli/SceneFederation.cs create mode 100644 src/IOViewer/Viewer/test/e2e/federation.spec.js create mode 100644 tests/IOViewer.Tests/FederatedCliTests.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index aeaf492..800fad9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,6 +16,7 @@ API between minor releases. - Keyboard navigation and visible focus in the model tree and context menu. - Select multiple elements in the model tree and open the viewer context menu from its rows. - Filter the model tree by source model, level and category, and optionally isolate the matches in 3D. +- Export explicitly placed source models together in one standalone HTML viewer with independent visibility. ### Fixed diff --git a/README.md b/README.md index 959e5ea..2229bd5 100644 --- a/README.md +++ b/README.md @@ -100,6 +100,19 @@ ioviewer model.nwc -o viewer.html ioviewer model.glb --serve ``` +Pass `--add` and `--placement` to combine several source models into one offline HTML viewer. + +```sh +ioviewer architecture.ifc --add services.rvt --placement 10,20,3,90 -o coordination.html +``` + +The first input defines the coordinate space. Each `--add` takes a file followed by +`--placement x,y,z,yaw`. Rotate counterclockwise about +Z by `yaw` degrees, then translate by +`x,y,z` metres. Use `0,0,0,0` for a source already in the first model's coordinates. Repeat the +pair to add more inputs. The viewer lists all models in the Linked files panel with individual +visibility controls. The first input supplies any startup clipping. Saved views from added sources +are placed with their models. A saved section box requires a yaw that is a multiple of 90 degrees. + Export structured JSON snapshots: ```sh diff --git a/docs/public-api.md b/docs/public-api.md index fdbc307..bc9fce4 100644 --- a/docs/public-api.md +++ b/docs/public-api.md @@ -26,9 +26,9 @@ 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. `ViewpointStates` adds optional state to saved cameras. `Title` reads and - writes `Scene.Title`. +- `ViewerDocument` holds the scene, startup clipping, and the model keys hidden at start in `HiddenModelKeys`. + `ShowHostInModelList` adds the first model to the Linked files controls so it can be hidden independently. + `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. diff --git a/src/IOViewer.Cli/Program.cs b/src/IOViewer.Cli/Program.cs index ce6cae4..f5dc1a0 100644 --- a/src/IOViewer.Cli/Program.cs +++ b/src/IOViewer.Cli/Program.cs @@ -33,6 +33,9 @@ with NwcIO. Conversion diagnostics are reported as warnings or errors. Options: -o, --output Destination path for exported HTML or JSON file. + --add --placement + Add another model. Translation is in metres and yaw in degrees about +Z. + Repeat the pair for each model. Use 0,0,0,0 for an already aligned source. --title Page title shown in the browser tab. --wireframe Enable wireframe display mode by default. --white-mode Enable white/clay architectural rendering mode by default. @@ -76,6 +79,7 @@ public static int Main(string[] args) string? outputPath = null; string? customTitle = null; string? explicitJsonPath = null; + var additional = new List<(string Path, Transform3d Placement)>(); bool wireframe = false; bool whiteMode = false; bool includeProps = true; @@ -106,6 +110,16 @@ public static int Main(string[] args) } customTitle = args[++i]; break; + case "--add": + if (i + 3 >= args.Length || args[i + 1].StartsWith('-') || args[i + 2] != "--placement" + || !SceneFederation.TryParsePlacement(args[i + 3], out var placement)) + { + Console.Error.WriteLine("Error: Each --add <file> requires --placement <x,y,z,yaw> with four finite numbers."); + return 1; + } + additional.Add((args[i + 1], placement)); + i += 3; + break; case "--wireframe": wireframe = true; break; @@ -165,29 +179,38 @@ public static int Main(string[] args) Console.Error.WriteLine($"Error: File not found: '{inputPath}'."); return 2; } + foreach (var source in additional) + { + if (File.Exists(source.Path)) continue; + Console.Error.WriteLine($"Error: File not found: '{Printable(source.Path)}'."); + return 2; + } outputPath ??= Path.ChangeExtension(inputPath, ".html"); var sw = Stopwatch.StartNew(); ViewerDocument doc; - IReadOnlyList<SceneDiagnostic> diagnostics = []; + int adapterCode; + string sourcePath = inputPath; try { - string ext = Path.GetExtension(inputPath).ToLowerInvariant(); - doc = ext switch + doc = Load(inputPath, out var diagnostics); + adapterCode = ExitCode(diagnostics); + if (additional.Count > 0) { - ".glb" => GlbViewerImporter.Load(inputPath), - ".obj" => ObjViewerImporter.Load(inputPath), - ".json" => JsonViewerImporter.Load(inputPath), - ".ifc" or ".ifczip" => FromIfc(inputPath, out diagnostics), - ".rvt" => FromRvt(inputPath, out diagnostics), - ".nwc" => FromNwc(inputPath, out diagnostics), - _ => throw new NotSupportedException($"Unsupported input file extension: '{ext}'. Supported: .glb, .obj, .json, .ifc, .ifczip, .rvt, .nwc.") - }; + SceneFederation.SetInputPath(doc.Scene, inputPath); + foreach (var source in additional) + { + sourcePath = source.Path; + var input = Load(sourcePath, out diagnostics); + SceneFederation.Append(doc, input, sourcePath, source.Placement); + adapterCode = Math.Max(adapterCode, ExitCode(diagnostics)); + } + } } catch (Exception ex) { - Console.Error.WriteLine($"Error: Failed to load '{inputPath}': {Printable(ex.Message)}"); + Console.Error.WriteLine($"Error: Failed to load '{Printable(sourcePath)}': {Printable(ex.Message)}"); return 3; } @@ -248,7 +271,23 @@ public static int Main(string[] args) return 5; } - return ExitCode(diagnostics); + return adapterCode; + } + + private static ViewerDocument Load(string path, out IReadOnlyList<SceneDiagnostic> diagnostics) + { + diagnostics = []; + string ext = Path.GetExtension(path).ToLowerInvariant(); + return ext switch + { + ".glb" => GlbViewerImporter.Load(path), + ".obj" => ObjViewerImporter.Load(path), + ".json" => JsonViewerImporter.Load(path), + ".ifc" or ".ifczip" => FromIfc(path, out diagnostics), + ".rvt" => FromRvt(path, out diagnostics), + ".nwc" => FromNwc(path, out diagnostics), + _ => throw new NotSupportedException($"Unsupported input file extension: '{ext}'. Supported: .glb, .obj, .json, .ifc, .ifczip, .rvt, .nwc.") + }; } private static ViewerDocument FromIfc(string path, out IReadOnlyList<SceneDiagnostic> diagnostics) diff --git a/src/IOViewer.Cli/SceneFederation.cs b/src/IOViewer.Cli/SceneFederation.cs new file mode 100644 index 0000000..efb0762 --- /dev/null +++ b/src/IOViewer.Cli/SceneFederation.cs @@ -0,0 +1,282 @@ +using System.Globalization; +using System.Numerics; +using IOScene; +using IOViewer.Model; + +namespace IOViewer.Cli; + +internal static class SceneFederation +{ + internal static bool TryParsePlacement(string value, out Transform3d placement) + { + placement = default; + string[] tokens = value.Split(','); + if (tokens.Length != 4) return false; + Span<double> coordinates = stackalloc double[4]; + for (int i = 0; i < tokens.Length; i++) + { + if (!double.TryParse(tokens[i], NumberStyles.Float, CultureInfo.InvariantCulture, out coordinates[i]) + || !double.IsFinite(coordinates[i])) return false; + } + + double angle = Math.IEEERemainder(coordinates[3], 360); + var (sin, cos) = angle switch + { + 0 => (0d, 1d), + 90 => (1d, 0d), + -90 => (-1d, 0d), + 180 or -180 => (0d, -1d), + _ => Math.SinCos(angle * Math.PI / 180), + }; + placement = new(new(cos, sin, 0), new(-sin, cos, 0), Vector3d.UnitZ, + new(coordinates[0], coordinates[1], coordinates[2])); + return true; + } + + internal static void SetInputPath(SceneDocument scene, string path) + { + if (scene.Models.Count == 0) throw new InvalidDataException("A federated source must contain a model."); + if (string.IsNullOrEmpty(scene.Models[0].Path)) scene.Models[0].Path = path; + } + + // The CLI owns both documents. Move the imported records and keep geometry buffers shared. + internal static void Append(ViewerDocument target, ViewerDocument source, string path, Transform3d placement) + { + var to = target.Scene; + var from = source.Scene; + SetInputPath(from, path); + string sourceHost = from.Models[0].Key; + ResolveClashNames(to); + ResolveClashNames(from); + // Reserve references as well as definitions so an orphan never attaches to a different source. + var modelIds = RemapIds(to.Models.Select(m => m.Id).Concat(to.Elements.Select(e => e.ModelId)) + .Concat(to.Levels.Select(l => l.ModelId)).Concat(to.Grids.Select(g => g.ModelId)) + .Concat(to.Schedules.Select(s => s.ModelId).OfType<int>()), from.Models.Select(m => m.Id)); + var levelIds = RemapIds(to.Levels.Select(l => l.Id).Concat(to.Elements.Select(e => e.LevelId).OfType<int>()), + from.Levels.Select(l => l.Id)); + var geometryIds = RemapIds(to.Geometries.Select(g => g.Id).Concat(to.Instances.Select(i => i.GeometryId)), + from.Geometries.Select(g => g.Id)); + var materialIds = RemapIds(to.Materials.Select(m => m.Id).Concat(to.Instances.Select(i => i.MaterialId).OfType<int>()), + from.Materials.Select(m => m.Id)); + var textureIds = RemapIds(to.Textures.Select(t => t.Id).Concat(to.Materials.Select(m => m.TextureId).OfType<int>()), + from.Textures.Select(t => t.Id)); + var propertyIds = RemapIds(to.PropertySets.Select(p => p.Id).Concat(to.Elements.SelectMany(e => e.PropertySetIds)), + from.PropertySets.Select(p => p.Id)); + var sourceElements = from.Elements.ToDictionary(e => e.Id); + var elementIds = RemapIds(ElementReferences(to).Concat(target.ViewpointStates.Values.SelectMany(s => s?.HiddenElementIds ?? [])), + ElementReferences(from).Distinct()); + var rotation = placement with { Translation = Vector3d.Zero }; + + var keys = to.Models.Select(m => m.Key).ToHashSet(StringComparer.Ordinal); + target.HiddenModelKeys.RemoveAll(key => !keys.Contains(key) || (!target.ShowHostInModelList && key == to.Models[0].Key)); + keys.UnionWith(target.ViewpointStates.Values.SelectMany(s => s?.HiddenModelKeys ?? [])); + var reservedKeys = from.Models.Select(m => m.Key).ToHashSet(StringComparer.Ordinal); + var modelKeys = new Dictionary<string, string>(StringComparer.Ordinal); + foreach (var model in from.Models) + { + model.Id = modelIds[model.Id]; + string original = model.Key; + model.Key = Unique(original, keys, reservedKeys); + modelKeys.Add(original, model.Key); + } + foreach (var level in from.Levels) + { + level.Id = levelIds[level.Id]; + level.ModelId = modelIds[level.ModelId]; + level.Elevation += placement.Translation.Z; + } + foreach (var geometry in from.Geometries) geometry.Id = geometryIds[geometry.Id]; + foreach (var texture in from.Textures) texture.Id = textureIds[texture.Id]; + foreach (var material in from.Materials) + { + material.Id = materialIds[material.Id]; + if (material.TextureId is int texture) material.TextureId = textureIds[texture]; + } + foreach (var propertySet in from.PropertySets) propertySet.Id = propertyIds[propertySet.Id]; + foreach (var element in from.Elements) + { + element.Id = elementIds[element.Id]; + element.ModelId = modelIds[element.ModelId]; + if (element.LevelId is int level) element.LevelId = levelIds[level]; + if (element.ParentId is long parent) element.ParentId = elementIds[parent]; + element.PropertySetIds = element.PropertySetIds.Select(id => propertyIds[id]).ToList(); + } + foreach (var instance in from.Instances) + { + instance.ElementId = elementIds[instance.ElementId]; + instance.GeometryId = geometryIds[instance.GeometryId]; + if (instance.MaterialId is int material) instance.MaterialId = materialIds[material]; + var oriented = (instance.Transform ?? Transform3d.Identity).Then(rotation); + instance.Transform = oriented with { Translation = oriented.Translation + placement.Translation }; + } + foreach (var grid in from.Grids) + { + grid.ModelId = modelIds[grid.ModelId]; + foreach (var line in grid.Lines) + { + line.Start = placement.Apply(line.Start); + line.End = placement.Apply(line.End); + line.Elevation += placement.Translation.Z; + } + } + foreach (var schedule in from.Schedules) + { + if (schedule.ModelId is int model) schedule.ModelId = modelIds[model]; + foreach (var task in AllTasks(schedule.Tasks)) + task.ElementIds = task.ElementIds.Select(id => elementIds[id]).ToList(); + } + foreach (var clash in from.ClashTests.SelectMany(test => test.Clashes)) + { + if (clash.Element1Id is long first) clash.Element1Id = elementIds[first]; + if (clash.Element2Id is long second) clash.Element2Id = elementIds[second]; + clash.Point = placement.Apply(clash.Point); + } + + var viewIds = to.Viewpoints.Select(v => v.Id).OfType<string>().ToHashSet(StringComparer.Ordinal); + viewIds.UnionWith(target.ViewpointStates.Keys); + var reservedViews = from.Viewpoints.Select(v => v.Id).OfType<string>().ToHashSet(StringComparer.Ordinal); + var states = new Dictionary<string, ViewerViewpointState>(source.ViewpointStates, StringComparer.Ordinal); + if (from.Viewpoints.GroupBy(view => view.Id).Any(group => + group.Key is { } id && states.ContainsKey(id) && group.Skip(1).Any())) + throw new InvalidDataException("A saved viewpoint state matches more than one camera."); + foreach (var view in from.Viewpoints) + { + view.Camera.Position = placement.Apply(view.Camera.Position); + view.Camera.Target = placement.Apply(view.Camera.Target); + view.Camera.Up = rotation.Apply(view.Camera.Up); + if (view.Id is not { } oldId) continue; + view.Id = Unique(oldId, viewIds, reservedViews); + if (!states.Remove(oldId, out var state)) continue; + if (state is null) throw new InvalidDataException($"Viewpoint '{oldId}' has a null state."); + if (state.HiddenElementIds?.Any(id => !sourceElements.ContainsKey(id)) == true) + throw new InvalidDataException($"Viewpoint '{oldId}' references an unknown element."); + state.HiddenElementIds = state.HiddenElementIds?.Select(id => elementIds[id]).ToList(); + state.HiddenModelKeys = state.HiddenModelKeys?.Select(key => modelKeys[key]).ToList(); + TransformSections(state, placement, rotation); + target.ViewpointStates.Add(view.Id, state); + } + if (states.Count != 0) throw new InvalidDataException("A saved viewpoint state has no matching camera."); + + target.HiddenModelKeys.AddRange(source.HiddenModelKeys + .Where(key => (source.ShowHostInModelList || key != sourceHost) && modelKeys.ContainsKey(key)) + .Select(key => modelKeys[key])); + target.ShowHostInModelList = true; + to.Models.AddRange(from.Models); + to.Levels.AddRange(from.Levels); + to.Geometries.AddRange(from.Geometries); + to.Materials.AddRange(from.Materials); + to.Textures.AddRange(from.Textures); + to.PropertySets.AddRange(from.PropertySets); + to.Elements.AddRange(from.Elements); + to.Instances.AddRange(from.Instances); + to.Grids.AddRange(from.Grids); + to.Schedules.AddRange(from.Schedules); + to.Viewpoints.AddRange(from.Viewpoints); + to.ClashTests.AddRange(from.ClashTests); + } + + private static void TransformSections(ViewerViewpointState state, Transform3d placement, Transform3d rotation) + { + foreach (var plane in state.SectionPlanes ?? []) + { + var normal = plane.Axis switch + { + ViewerSectionAxis.X => Vector3d.UnitX, + ViewerSectionAxis.Y => Vector3d.UnitY, + ViewerSectionAxis.Z => Vector3d.UnitZ, + ViewerSectionAxis.Custom => plane.Normal, + _ => throw new InvalidDataException($"Unknown section plane axis: {plane.Axis}."), + }; + double scale = Math.Max(Math.Abs(normal.X), Math.Max(Math.Abs(normal.Y), Math.Abs(normal.Z))); + if (!double.IsFinite(scale) || scale == 0) + throw new InvalidDataException("The section plane normal must be finite and nonzero."); + plane.Normal = rotation.Apply(new Vector3d(normal.X / scale, normal.Y / scale, normal.Z / scale).Normalized()); + plane.Offset += Vector3d.Dot(plane.Normal, placement.Translation); + plane.Axis = ViewerSectionAxis.Custom; + } + if (state.SectionBox is not { } box) return; + if (rotation.XAxis.X != 0 && rotation.XAxis.Y != 0) + throw new InvalidDataException("A saved section box needs a placement yaw that is a multiple of 90 degrees."); + var bounds = new BoundingBox3d(box.Min, box.Max); + if (bounds.IsEmpty) throw new InvalidDataException("A saved section box has invalid bounds."); + var moved = BoundingBox3d.Empty.Encapsulate(placement.Apply(box.Min)).Encapsulate(placement.Apply(box.Max)); + box.Min = moved.Min; + box.Max = moved.Max; + } + + private static void ResolveClashNames(SceneDocument scene) + { + // The viewer resolves names only when unique. Apply that rule within each source before other names are added. + var unresolved = scene.ClashTests.SelectMany(test => test.Clashes) + .Where(clash => clash.Element1Id is null || clash.Element2Id is null).ToArray(); + if (unresolved.Length == 0) return; + var requested = new HashSet<string>(StringComparer.Ordinal); + foreach (var clash in unresolved) + { + if (clash.Element1Id is null) requested.Add(clash.Element1Name); + if (clash.Element2Id is null) requested.Add(clash.Element2Name); + } + var names = new Dictionary<string, long?>(StringComparer.Ordinal); + var ids = scene.Elements.Select(element => element.Id).ToHashSet(); + long missing = -1; + while (ids.Contains(missing)) missing--; + foreach (var element in scene.Elements) + if (element.Name is { } name && requested.Contains(name) && !names.TryAdd(name, element.Id)) + names[name] = null; + foreach (var clash in unresolved) + { + clash.Element1Id ??= Find(clash.Element1Name); + clash.Element2Id ??= Find(clash.Element2Name); + } + long Find(string? name) => name is not null ? names.GetValueOrDefault(name) ?? missing : missing; + } + + private static IEnumerable<SceneTask> AllTasks(IEnumerable<SceneTask> tasks) + { + foreach (var task in tasks) + { + yield return task; + foreach (var child in AllTasks(task.Children)) yield return child; + } + } + + private static IEnumerable<long> ElementReferences(SceneDocument scene) + { + foreach (var element in scene.Elements) + { + yield return element.Id; + if (element.ParentId is long parent) yield return parent; + } + foreach (var instance in scene.Instances) yield return instance.ElementId; + foreach (var task in scene.Schedules.SelectMany(s => AllTasks(s.Tasks))) + foreach (var id in task.ElementIds) yield return id; + foreach (var clash in scene.ClashTests.SelectMany(test => test.Clashes)) + { + if (clash.Element1Id is long first) yield return first; + if (clash.Element2Id is long second) yield return second; + } + } + + private static Dictionary<T, T> RemapIds<T>(IEnumerable<T> used, IEnumerable<T> incoming) where T : IBinaryInteger<T> + { + var taken = used.ToHashSet(); + var map = new Dictionary<T, T>(); + T next = T.One; + foreach (T id in incoming) + { + while (!taken.Add(next)) next = checked(next + T.One); + map.Add(id, next); + } + return map; + } + + private static string Unique(string key, HashSet<string> used, HashSet<string> reserved) + { + if (used.Add(key)) return key; + for (int i = 2; ; i++) + { + string candidate = FormattableString.Invariant($"{key}#{i}"); + if (!reserved.Contains(candidate) && used.Add(candidate)) return candidate; + } + } +} diff --git a/src/IOViewer/Exporters/JsonViewerExporter.cs b/src/IOViewer/Exporters/JsonViewerExporter.cs index 8b54d9c..7fcce60 100644 --- a/src/IOViewer/Exporters/JsonViewerExporter.cs +++ b/src/IOViewer/Exporters/JsonViewerExporter.cs @@ -1,4 +1,5 @@ using System.Text.Json; +using System.Text.Json.Serialization; using IOScene; using IOViewer.Model; @@ -6,7 +7,7 @@ namespace IOViewer.Exporters; /// <summary> /// Writes a <see cref="ViewerDocument"/> as viewer JSON: <c>{ "Kind": "ioviewer", "Format": 2, "Scene": {...}, -/// "SectionPlanes", "SectionBox", "HiddenModelKeys", "ViewpointStates" }</c>, with the scene in the encoding of scene JSON. +/// "SectionPlanes", "SectionBox", "HiddenModelKeys", "ShowHostInModelList", "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 @@ -67,6 +68,8 @@ internal sealed class ViewerJsonFile public List<ViewerSectionPlane> SectionPlanes { get; set; } = []; public ViewerSectionBox? SectionBox { get; set; } public List<string> HiddenModelKeys { get; set; } = []; + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)] + public bool ShowHostInModelList { get; set; } public Dictionary<string, ViewerViewpointState>? ViewpointStates { get; set; } public static ViewerJsonFile From(ViewerDocument doc) => new() @@ -75,6 +78,7 @@ internal sealed class ViewerJsonFile SectionPlanes = doc.SectionPlanes, SectionBox = doc.SectionBox, HiddenModelKeys = doc.HiddenModelKeys, + ShowHostInModelList = doc.ShowHostInModelList, ViewpointStates = doc.ViewpointStates is { Count: > 0 } ? doc.ViewpointStates : null, }; @@ -83,6 +87,7 @@ internal sealed class ViewerJsonFile SectionPlanes = SectionPlanes, SectionBox = SectionBox, HiddenModelKeys = HiddenModelKeys, + ShowHostInModelList = ShowHostInModelList, ViewpointStates = ViewpointStates ?? [], }; } diff --git a/src/IOViewer/Exporters/ViewerPayloadWriter.cs b/src/IOViewer/Exporters/ViewerPayloadWriter.cs index cbf9d89..898451f 100644 --- a/src/IOViewer/Exporters/ViewerPayloadWriter.cs +++ b/src/IOViewer/Exporters/ViewerPayloadWriter.cs @@ -19,7 +19,7 @@ namespace IOViewer.Exporters; /// such geometries share one written geometry; a geometry that several instances place is written once in local /// coordinates and placed by each instance's matrix. Only triangle geometries are drawn: instances of lines, points /// or a topology this version does not know are skipped and counted in META <c>skipped</c>. The first model of the -/// scene is the host; the elements of the other models carry a link, and those models are listed as linked files. +/// scene is the host; listed models carry a link on their elements and can be hidden independently. /// </remarks> internal sealed class ViewerPayloadWriter { @@ -30,6 +30,7 @@ internal sealed class ViewerPayloadWriter private readonly SceneDocument _scene; private readonly HashSet<string> _hiddenModels; + private readonly int _firstListedModel; private readonly HtmlViewerOptions _options; private readonly BinaryBlobBuilder _blob = new(); private readonly List<GeometryEntry> _geometries = []; @@ -56,6 +57,7 @@ private ViewerPayloadWriter(ViewerDocument doc, HtmlViewerOptions options) { _scene = doc.Scene; _hiddenModels = [.. doc.HiddenModelKeys]; + _firstListedModel = doc.ShowHostInModelList ? 0 : 1; _options = options; } @@ -108,7 +110,7 @@ private void BuildViewpointStates(Dictionary<string, ViewerViewpointState>? stat { if (!_options.IncludeViewpoints || states is not { Count: > 0 }) return; - var linkedKeys = _scene.Models.Skip(1).Select(model => model.Key).ToHashSet(StringComparer.Ordinal); + var linkedKeys = _scene.Models.Skip(_firstListedModel).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; @@ -708,7 +710,7 @@ public void WriteMeta(Stream output) // An element of a linked model carries the model's path, else its name, as the linked file list shows it. var links = new Dictionary<int, string?>(); - for (int i = 1; i < _scene.Models.Count; i++) + for (int i = _firstListedModel; i < _scene.Models.Count; i++) { var model = _scene.Models[i]; links.TryAdd(model.Id, string.IsNullOrEmpty(model.Path) ? model.Name : model.Path); @@ -739,7 +741,8 @@ public void WriteMeta(Stream output) if (el.LevelId is int levelId) w.WriteNumber("levelId", levelId); // The first model is the default so single-source files do not repeat its ID on every element. if (el.ModelId != host?.Id) w.WriteNumber("modelId", el.ModelId); - if (host is null || el.ModelId == host.Id || links.GetValueOrDefault(el.ModelId) is not { Length: > 0 } link) w.WriteNull("link"); + if ((_firstListedModel != 0 && el.ModelId == host?.Id) + || links.GetValueOrDefault(el.ModelId) is not { Length: > 0 } link) w.WriteNull("link"); else w.WriteString("link", link); if (!string.IsNullOrEmpty(el.SourceId)) w.WriteString("sourceId", el.SourceId); w.WriteEndObject(); @@ -885,20 +888,25 @@ void WriteTask(SceneTask t) private void WriteLinkedFiles(Utf8JsonWriter w) { w.WriteStartArray("linkedFiles"); - if (_scene.Models.Count < 2) + if (_scene.Models.Count <= _firstListedModel) { w.WriteEndArray(); return; } int host = _scene.Models[0].Id; var members = _scene.Elements.Select((element, index) => (element.ModelId, index)) - .Where(member => member.ModelId != host) + .Where(member => _firstListedModel == 0 || member.ModelId != host) .ToLookup(member => member.ModelId, member => member.index); - foreach (var model in _scene.Models.Skip(1)) + var listed = _scene.Models.Skip(_firstListedModel); + var repeatedNames = _firstListedModel == 0 + ? listed.GroupBy(model => model.Name).Where(group => group.Skip(1).Any()).Select(group => group.Key).ToHashSet() + : []; + foreach (var model in listed) { w.WriteStartObject(); w.WriteString("key", model.Key); - w.WriteString("name", model.Name); + string name = repeatedNames.Contains(model.Name) ? FormattableString.Invariant($"{model.Name} (#{model.Id})") : model.Name; + w.WriteString("name", name); w.WriteString("path", model.Path ?? string.Empty); w.WriteBoolean("visible", !_hiddenModels.Contains(model.Key)); WriteIndices(w, "members", members[model.Id]); diff --git a/src/IOViewer/Model/ViewerDocument.cs b/src/IOViewer/Model/ViewerDocument.cs index 621db2d..40affd8 100644 --- a/src/IOViewer/Model/ViewerDocument.cs +++ b/src/IOViewer/Model/ViewerDocument.cs @@ -36,11 +36,13 @@ public ViewerDocument(SceneDocument scene) public ViewerSectionBox? SectionBox { get; set; } /// <summary> - /// Keys (<see cref="SceneModel.Key"/>) of the models hidden at start. The first model of the scene is the host - /// and is always shown; the others are listed as linked files. + /// Keys (<see cref="SceneModel.Key"/>) of the models hidden at start. This applies to models listed in the viewer. /// </summary> public List<string> HiddenModelKeys { get; set; } = []; + /// <summary>Include the first model in the viewer's model visibility list, as in a federated export.</summary> + public bool ShowHostInModelList { 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; } = []; diff --git a/src/IOViewer/Model/ViewerViewpointState.cs b/src/IOViewer/Model/ViewerViewpointState.cs index 43af60c..5664392 100644 --- a/src/IOViewer/Model/ViewerViewpointState.cs +++ b/src/IOViewer/Model/ViewerViewpointState.cs @@ -22,7 +22,8 @@ public sealed class ViewerViewpointState /// <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"/>. + /// empty list checks all listed models with elements. The host is listed when the document enables + /// <see cref="ViewerDocument.ShowHostInModelList"/>. /// </summary> public List<string>? HiddenModelKeys { get; set; } } diff --git a/src/IOViewer/Viewer/playwright.config.js b/src/IOViewer/Viewer/playwright.config.js index 37b6ab0..7731050 100644 --- a/src/IOViewer/Viewer/playwright.config.js +++ b/src/IOViewer/Viewer/playwright.config.js @@ -16,7 +16,7 @@ export default defineConfig({ { name: 'firefox', testMatch: ['**/smoke.spec.js', '**/selection.spec.js', '**/sections.spec.js', '**/accessibility.spec.js', - '**/tree-selection.spec.js', '**/tree-filters.spec.js'], + '**/tree-selection.spec.js', '**/tree-filters.spec.js', '**/federation.spec.js'], use: { browserName: 'firefox', // Under Linux, Xvfb supplies the display Firefox uses to create a WebGL context in CI. diff --git a/src/IOViewer/Viewer/test/e2e/federation.spec.js b/src/IOViewer/Viewer/test/e2e/federation.spec.js new file mode 100644 index 0000000..63b3221 --- /dev/null +++ b/src/IOViewer/Viewer/test/e2e/federation.spec.js @@ -0,0 +1,59 @@ +import { test, expect } from '@playwright/test'; +import path from 'node:path'; +import { pathToFileURL } from 'node:url'; +import { viewerDir } from './global-setup.js'; + +test.use({ locale: 'en-US', offline: true }); + +test('placed sources keep independent visibility, properties and geometry in one offline page', async ({ page }) => { + const errors = []; + const network = []; + page.on('pageerror', (error) => errors.push(error.message)); + page.on('request', (request) => { if (/^https?:/.test(request.url())) network.push(request.url()); }); + await page.goto(pathToFileURL(path.join(viewerDir, 'test-results', 'federated.html')).href); + await page.evaluate(() => window.__ioviewer.ready); + + const model = await page.evaluate(() => { + const { scene } = window.__ioviewer; + const meta = JSON.parse(document.getElementById('ioviewer-meta').textContent); + const { rtcOffset } = meta; + return { + ids: meta.elements.map((element) => element.id), + boxes: [0, 2, 3].map((index) => { + const box = scene.elementBox(index); + return [box.min, box.max].map((v) => v.toArray().map((value, i) => value + rtcOffset[i])); + }), + }; + }); + expect(new Set(model.ids).size).toBe(4); + const expected = [ + [[0, 0, 0], [0.3, 0.3, 0.3]], + [[9.7, 20, 3], [10, 20.3, 3.3]], + [[9.7, 20.5, 3], [10, 20.8, 3.3]], + ]; + model.boxes.flat(2).forEach((value, i) => expect(value).toBeCloseTo(expected.flat(2)[i], 2)); + + const visible = () => page.evaluate(() => Array.from({ length: 4 }, (_, i) => window.__ioviewer.scene.isVisible(i))); + await page.locator('.ioviewer-rail-button[data-panel="links"]').click(); + const links = page.locator('.ioviewer-side-panel[data-panel="links"]'); + const architecture = links.getByRole('checkbox', { name: /^Architecture/ }); + const services = links.getByRole('checkbox', { name: /^Services/ }); + await expect(architecture).toBeChecked(); + await expect(services).toBeChecked(); + await architecture.uncheck(); + expect(await visible()).toEqual([false, false, true, true]); + await services.uncheck(); + expect(await visible()).toEqual([false, false, false, false]); + await architecture.check(); + expect(await visible()).toEqual([true, true, false, false]); + await services.check(); + + await page.locator('.ioviewer-rail-button[data-panel="model"]').click(); + await page.getByRole('searchbox').fill('Services part 1'); + await page.getByRole('treeitem', { name: /^Services part 1/ }).click(); + const properties = page.locator('#ioviewer-properties'); + await expect(properties).toContainText('Discipline'); + await expect(properties.getByText('Services', { exact: true })).toBeVisible(); + expect(errors).toEqual([]); + expect(network).toEqual([]); +}); diff --git a/src/IOViewer/Viewer/test/e2e/global-setup.js b/src/IOViewer/Viewer/test/e2e/global-setup.js index 1f9f848..c4aaff1 100644 --- a/src/IOViewer/Viewer/test/e2e/global-setup.js +++ b/src/IOViewer/Viewer/test/e2e/global-setup.js @@ -73,6 +73,18 @@ export default function globalSetup() { exportHtml(shear, 'shear'); const results = path.join(viewerDir, 'test-results'); + const sources = ['Architecture', 'Services'].map((name) => { + const doc = largeModel(2); + doc.Title = name; + doc.Elements.forEach((element, i) => { + element.Name = `${name} part ${i + 1}`; + element.Properties = { Source: { Discipline: name } }; + }); + const file = path.join(results, `${name}.json`); + writeFileSync(file, JSON.stringify(doc)); + return file; + }); + exportHtml(sources[0], 'federated', ['--add', sources[1], '--placement', '10,20,3,90']); const wide = largeModel(2); for (const [i, id] of ['9007199254740992', '9007199254740993'].entries()) { wide.Elements[i].Id = wide.Meshes[i].ElementId = JSON.rawJSON(id); diff --git a/tests/IOViewer.Tests/FederatedCliTests.cs b/tests/IOViewer.Tests/FederatedCliTests.cs new file mode 100644 index 0000000..95cf44f --- /dev/null +++ b/tests/IOViewer.Tests/FederatedCliTests.cs @@ -0,0 +1,182 @@ +using IOScene; +using IOViewer.Cli; +using IOViewer.Exporters; +using IOViewer.Importers; +using IOViewer.Model; +using Xunit; + +namespace IOViewer.Tests; + +[Collection("Console")] +public sealed class FederatedCliTests : IDisposable +{ + private readonly DirectoryInfo _scratch = Directory.CreateTempSubdirectory("ioviewer-federation-"); + + private string Save(string name, ViewerDocument doc) + { + string path = Path.Combine(_scratch.FullName, name + ".json"); + JsonViewerExporter.Save(doc, path); + return path; + } + + private static ViewerDocument Model(string name) + { + var scene = TestScenes.Empty(name); + scene.Levels.Add(new() { Id = 1, ModelId = 1, Name = "Level 1", Elevation = 1 }); + scene.Textures.Add(new() { Id = 1, MimeType = "image/png", Data = [1, 2, 3] }); + scene.Materials.Add(new() { Id = 1, Name = name, TextureId = 1 }); + scene.PropertySets.Add(new() + { + Id = 1, Name = "Source", + Properties = [new() { Name = "Discipline", Value = SceneValue.FromText(name) }], + }); + var shape = scene.Geometry([Vector3d.Zero, new(2, 0, 0), Vector3d.UnitY], [0, 1, 2]); + scene.Place(shape, Transform3d.Translate(new(2, 0, 1))); + scene.Place(shape, Transform3d.Translate(new(4, 0, 2))); + foreach (var instance in scene.Instances) instance.MaterialId = 1; + scene.Elements[0].Name = name; + scene.Elements[0].SourceId = "source-1"; + scene.Elements[0].LevelId = 1; + scene.Elements[0].PropertySetIds = [1]; + scene.Elements[1].ParentId = 1; + scene.Viewpoints.Add(new() { Id = "front", Camera = new() { Position = new(2, 0, 1), Target = Vector3d.UnitX } }); + return new(scene); + } + + [Fact] + public void Export_MapsSourceIdentityAndReferencesAndPlacesTheAdditionalModel() + { + string host = Save("architecture", Model("Architecture")); + var services = Model("Services"); + services.Scene.Grids.Add(new() + { + ModelId = 1, + Lines = [new() { Start = Vector3d.Zero, End = Vector3d.UnitX, Elevation = 1 }], + }); + services.Scene.Schedules.Add(new() + { + ModelId = 1, + Tasks = [new() { Id = "parent", Children = [new() { Id = "child", ElementIds = [1, 2] }] }], + }); + services.Scene.ClashTests.Add(new() + { + Clashes = + [ + new() { Id = "test", Element1Id = 1, Element2Id = 2, Point = Vector3d.UnitX }, + new() { Id = "by-name", Element1Name = "Services", Element2Name = "Architecture" }, + ], + }); + services.ViewpointStates.Add("front", new() + { + HiddenElementIds = [1], + SectionPlanes = [new(ViewerSectionAxis.X, 2)], + SectionBox = new(new(0, 0, 0), new(2, 1, 1)), + }); + string addition = Save("services", services); + string output = Path.Combine(_scratch.FullName, "combined.html"); + string snapshot = Path.Combine(_scratch.FullName, "combined.json"); + Assert.Equal(0, Program.Main([host, "--add", addition, "--placement", "10,20,3,90", "-o", output, "--json", snapshot])); + + var combined = JsonViewerImporter.Load(snapshot); + Assert.True(combined.ShowHostInModelList); + var scene = combined.Scene; + Assert.Equal(["model", "model#2"], scene.Models.Select(model => model.Key)); + Assert.Equal([host, addition], scene.Models.Select(model => model.Path)); + Assert.Equal([1L, 2L, 3L, 4L], scene.Elements.Select(element => element.Id)); + Assert.Equal(["source-1", "source-1"], scene.Elements.Select(element => element.SourceId).OfType<string>()); + var added = scene.Elements[2]; + Assert.Equal(scene.Models[1].Id, added.ModelId); + Assert.Equal(3, scene.Elements[3].ParentId); + Assert.Equal(scene.Levels[1].Id, added.LevelId); + Assert.Equal(4, scene.Levels[1].Elevation); + Assert.Equal(scene.PropertySets[1].Id, Assert.Single(added.PropertySetIds)); + Assert.Equal(scene.Materials[1].Id, scene.Instances[2].MaterialId); + Assert.Equal(scene.Textures[1].Id, scene.Materials[1].TextureId); + Assert.Equal(scene.Instances[2].GeometryId, scene.Instances[3].GeometryId); + Assert.NotEqual(scene.Instances[0].GeometryId, scene.Instances[2].GeometryId); + Assert.Equal(new Vector3d(10, 22, 4), scene.Instances[2].Transform!.Value.Translation); + Assert.Equal(new Vector3d(10, 24, 4), scene.Instances[2].Transform!.Value.Apply(new(2, 0, 0))); + Assert.Equal(new Vector3d(10, 21, 3), Assert.Single(Assert.Single(scene.Grids).Lines).End); + Assert.Equal([3L, 4L], scene.Schedules[0].Tasks[0].Children[0].ElementIds); + var clash = scene.ClashTests[0].Clashes[0]; + Assert.Equal((3L, 4L), (clash.Element1Id, clash.Element2Id)); + Assert.Equal(new Vector3d(10, 21, 3), clash.Point); + var byName = scene.ClashTests[0].Clashes[1]; + Assert.Equal(3, byName.Element1Id); + Assert.DoesNotContain(scene.Elements, element => element.Id == byName.Element2Id); + Assert.Equal("front#2", scene.Viewpoints[1].Id); + Assert.Equal(new Vector3d(10, 22, 4), scene.Viewpoints[1].Camera.Position); + var state = combined.ViewpointStates["front#2"]; + Assert.Equal([3L], state.HiddenElementIds); + Assert.Equal(Vector3d.UnitY, state.SectionPlanes![0].Normal); + Assert.Equal(22, state.SectionPlanes[0].Offset); + Assert.Equal(new Vector3d(9, 20, 3), state.SectionBox!.Min); + Assert.Equal(new Vector3d(10, 22, 4), state.SectionBox.Max); + + var view = ViewerHtml.Parse(File.ReadAllText(output)); + Assert.Equal(4, view.InstanceCount); + var files = view.Meta.GetProperty("linkedFiles"); + Assert.Equal([0, 1], files[0].GetProperty("members").EnumerateArray().Select(member => member.GetInt32())); + Assert.Equal([2, 3], files[1].GetProperty("members").EnumerateArray().Select(member => member.GetInt32())); + Assert.Equal("Architecture", view.Props.GetProperty("1").GetProperty("Source").GetProperty("Discipline").GetString()); + Assert.Equal("Services", view.Props.GetProperty("3").GetProperty("Source").GetProperty("Discipline").GetString()); + + // A combined snapshot can be exported again with the same independent host visibility. + Assert.Equal(2, ViewerHtml.Export(combined).Meta.GetProperty("linkedFiles").GetArrayLength()); + } + + [Theory] + [InlineData("0,0,0")] + [InlineData("NaN,0,0,0")] + [InlineData("0,0,0,Infinity")] + public void Export_MissingOrInvalidPlacementIsAUsageError(string placement) + { + Assert.Equal(1, Program.Main(["base.obj", "--add", "other.obj"])); + Assert.Equal(1, Program.Main(["base.obj", "--add", "other.obj", "--placement", placement])); + } + + [Fact] + public void Export_ARejectablePlacementLeavesAnExistingOutputUntouched() + { + string host = Save("host", Model("Host")); + var services = Model("Services"); + services.ViewpointStates.Add("front", new() { SectionBox = new() }); + string addition = Save("services", services); + string output = Path.Combine(_scratch.FullName, "existing.html"); + File.WriteAllText(output, "existing output"); + + Assert.Equal(2, Program.Main([host, "--add", Path.Combine(_scratch.FullName, "missing.json"), + "--placement", "0,0,0,0", "-o", output])); + Assert.Equal(3, Program.Main([host, "--add", addition, "--placement", "0,0,0,45", "-o", output])); + Assert.Equal("existing output", File.ReadAllText(output)); + } + + [Fact] + public void Export_RepeatedInputKeepsEachPlacementIndependentlyIdentifiable() + { + string source = Save("source", Model("Structure")); + string output = Path.Combine(_scratch.FullName, "repeated.html"); + Assert.Equal(0, Program.Main([source, "--add", source, "--placement", "10,0,0,0", + "--add", source, "--placement", "-10,0,0,-90", "-o", output])); + var view = ViewerHtml.Parse(File.ReadAllText(output)); + var sources = view.Meta.GetProperty("linkedFiles").EnumerateArray().ToArray(); + Assert.Equal(["model", "model#2", "model#3"], sources.Select(file => file.GetProperty("key").GetString())); + Assert.Equal(["Structure (#1)", "Structure (#2)", "Structure (#3)"], + sources.Select(file => file.GetProperty("name").GetString())); + } + + [Fact] + public void Export_AHostWithMissingGeometryCannotBorrowTheOtherSourcesGeometryId() + { + var broken = Model("Host"); + broken.Scene.Instances[0].GeometryId = 2; + string host = Save("host", broken); + string addition = Save("addition", Model("Services")); + string output = Path.Combine(_scratch.FullName, "combined.html"); + + Assert.Equal(3, Program.Main([host, "--add", addition, "--placement", "0,0,0,0", "-o", output])); + Assert.False(File.Exists(output)); + } + + public void Dispose() => _scratch.Delete(recursive: true); +}