diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md index 2ea413f..4196ff2 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.md +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -6,7 +6,7 @@ labels: bug **IOViewer version** (`ioviewer --version` or the package version): -**Input format** (`.glb`, `.obj`, `.json` or a `ViewerDocument` built in code): +**Input format** (`.glb`, `.obj`, `.json`, `.ifc`, `.ifczip`, `.rvt`, or a `SceneDocument` or `ViewerDocument` built in code): **Browser and operating system** (for problems in the generated viewer): diff --git a/CHANGELOG.md b/CHANGELOG.md index e2df442..7ec408d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,8 +6,10 @@ API between minor releases. ## [Unreleased] +## [0.3.0] - 2026-11-13 + Version 0.3.0 builds the viewer on the scene model of the [IOScene](https://github.com/IOExtend/IOScene) package -(`IOScene` `[0.1.0-preview.2, 0.2.0-0)`, a new dependency of the `IOViewer` package). This is a breaking change of the +(`IOScene` `[0.1.0, 0.2.0-0.0)`, a new dependency of the `IOViewer` package). This is a breaking change of the library API. What breaks for existing users: 1. The model types move to namespace `IOScene` with `Scene*` names, `ViewerClash*` included; `doc.Elements` becomes @@ -71,6 +73,12 @@ the `IOViewer` package). The `IOViewer.Cli` tool only gains inputs. - The HTML viewer shows `SceneElement.SourceId`, the element's id in its source format (such as a Revit UniqueId or an IFC GlobalId), as its own row in the properties panel ("Source ID" / "ID источника"), and the model tree search finds it. It is written to the page's element list only when set. +- The `ioviewer` tool reads IFC (`.ifc`, `.ifczip`) through `IfcIO.Scene` 0.11.1 and Revit (`.rvt`) through + `RvtIO.Scene` 0.4.0. The model key is the file name; the title is the IFC project name, or the Revit file name. What + the engine could not convert (such as an element without geometry) is printed to standard error as one warning or + error per kind with its count. When the engine reported an error (elements may be missing), the requested output + (the page, the JSON or both) is still written and the tool exits with code 4. The `IOViewer` library still references no engine; only the `IOViewer.Cli` tool + package ships IfcIO, RvtIO and their dependencies (see `THIRD-PARTY-NOTICES.md`). ### Changed - `JsonViewerExporter` writes viewer JSON format 2: `{ "Kind": "ioviewer", "Format": 2, "Scene", "SectionPlanes", diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index f7582c7..b28f981 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -40,21 +40,24 @@ The repository ships no customer models. ### Local feed for unpublished packages The model data comes from the `IOScene` package. `Directory.Packages.props` -references it with a range such as `[0.1.0-preview.1, 0.2.0-0)`: a patch of -IOScene is additive and a minor is breaking. NuGet restores the lowest version -in the range that it finds. - -To build against an IOScene version that is not on nuget.org yet (an IOScene -preview, or the lower bound itself before it is published), pack IOScene into -a local folder and pass that folder: +references it with a range such as `[0.1.0, 0.2.0-0.0)`: a patch of IOScene +adds or fixes and a minor is breaking, and the `-0.0` keeps out the previews of +the next minor (nuget.org refuses the shorter bound `-0` in a dependency). NuGet +restores the lowest version in the range that it finds. + +To build against an IOScene version that is not on nuget.org yet, start the +range at that version (for a new minor, move the upper bound too, for example +`[0.2.0-preview.1, 0.3.0-0.0)`, and raise `IfcIO.Scene` and `RvtIO.Scene` to +versions built on that minor: IfcIO.Scene 0.11.1 and RvtIO.Scene 0.4.0 accept +only IOScene `[0.1.0, 0.2.0-0.0)`), pack IOScene into a local folder and pass +that folder: ```sh dotnet build IOViewer.slnx -c Release -p:RestoreAdditionalProjectSources= dotnet test IOViewer.slnx -c Release --no-build ``` -For a newer preview, also raise the lower bound of the range to it. Once a -restore has put the package in the NuGet global packages folder, later +Once a restore has put the package in the NuGet global packages folder, later restores, `dotnet run` of the tools and `npm run e2e` find it there. Do not commit a `nuget.config` that points to a local feed, and commit a lower bound only when that version is on nuget.org: until then, restoring the solution @@ -131,7 +134,10 @@ Push a tag matching the package version, such as `v0.2.0`, to run `release.yml`. The workflow builds and tests the solution, publishes the NuGet packages through Trusted Publishing, and then attaches packages, symbols, source and checksums to a GitHub release, marked as a prerelease when the version has a hyphen (`v0.3.0-preview.1`). The release notes are the section of `CHANGELOG.md` for the version, so add that section before -the tag; the workflow stops before publishing when it is missing. +the tag; the workflow stops before publishing when it is missing. `tools/pack-release.ps1` also stops it when the +`IOViewer` package would depend on a missing or preview IOScene lower bound, or on a dependency bound that nuget.org +refuses (a bound with metadata, or a prerelease label of one part that does not start with a letter). +Before the tag, run the Revit test with a real Revit 2022 file, which CI does not have: set `IOVIEWER_RVT_FILE` to its path and run `dotnet test IOViewer.slnx -c Release --filter Cli_ConvertRvtToHtml`. The NuGet policy must name this repository, `release.yml`, the configured NuGet profile and the `IOViewer*` package pattern. ## Licensing contributions diff --git a/Directory.Build.props b/Directory.Build.props index cec0e6d..7c6cd9f 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -14,7 +14,7 @@ - 0.3.0-preview.1 + 0.3.0 mahach666 Copyright (c) 2026 mahach666 IOViewer diff --git a/Directory.Packages.props b/Directory.Packages.props index 7ef9376..1ad170d 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -3,8 +3,11 @@ true - - + + + + diff --git a/README.md b/README.md index bc7883d..9fdcb68 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg?style=flat-square)](https://opensource.org/licenses/MIT) [![Platform](https://img.shields.io/badge/.NET-8.0%20%7C%2010.0-512BD4?style=flat-square&logo=dotnet)](https://dotnet.microsoft.com/) -IOViewer is a fast, 100% managed .NET library and command line tool that generates standalone interactive 3D WebGL / HTML BIM & CAD model viewers from code, glTF/GLB, Wavefront OBJ, or JSON. Geometry read by sibling libraries ([RvtIO](https://github.com/IOExtend/RvtIO), [IfcIO](https://github.com/IOExtend/IfcIO), and [NwcIO](https://github.com/IOExtend/NwcIO)) can be passed in by building a `SceneDocument` in code. The scene model comes from the [IOScene](https://github.com/IOExtend/IOScene) package; IOViewer has no direct dependency on the format libraries. +IOViewer is a fast, 100% managed .NET library and command line tool that generates standalone interactive 3D WebGL / HTML BIM & CAD model viewers from code, glTF/GLB, Wavefront OBJ, or JSON. Geometry read by sibling libraries ([RvtIO](https://github.com/IOExtend/RvtIO), [IfcIO](https://github.com/IOExtend/IfcIO), and [NwcIO](https://github.com/IOExtend/NwcIO)) can be passed in by building a `SceneDocument` in code, and the `ioviewer` command line tool reads IFC and Revit files directly through IfcIO and RvtIO. The scene model comes from the [IOScene](https://github.com/IOExtend/IOScene) package; the IOViewer library has no dependency on the format libraries. The generated HTML is a single file with no external dependencies that works offline: it opens from disk (`file://`) in a current browser with WebGL 2 and makes no network requests. The viewer is built on [three.js](https://threejs.org/), which is embedded in the file (see [THIRD-PARTY-NOTICES.md](THIRD-PARTY-NOTICES.md)). @@ -64,7 +64,7 @@ Add the library to a .NET project: dotnet add package IOViewer ``` -The library examples below are for 0.3.0, which builds on the IOScene scene model and is in preview; 0.2.0 has the +The library examples below are for 0.3.0, which builds on the IOScene scene model; 0.2.0 has the earlier model, and [CHANGELOG.md](CHANGELOG.md) lists how its types map to the new ones. The library targets .NET 8 and .NET 10. It uses managed code without native dependencies or Windows-only APIs and supports Windows, Linux, and macOS. @@ -80,6 +80,10 @@ ioviewer model.glb -o viewer.html # Convert Wavefront OBJ model to interactive HTML viewer ioviewer model.obj -o viewer.html +# Convert an IFC model (.ifc or .ifczip, read with IfcIO) or a Revit model (.rvt, read with RvtIO) +ioviewer model.ifc +ioviewer model.rvt -o viewer.html + # Convert and immediately preview in default web browser via built-in HTTP server ioviewer model.glb --serve ``` @@ -91,7 +95,9 @@ Export structured JSON snapshots: ioviewer model.glb -o model.json ``` -Diagnostics and progress go to standard error. Run `ioviewer --help` for the full list of options. +Diagnostics and progress go to standard error, including what IfcIO or RvtIO could not convert (one warning or error +per kind, with its count). When the engine reported an error, elements may be missing: the output is still written and +the exit code is 4. Run `ioviewer --help` for the full list of options and exit codes. ## Library diff --git a/SECURITY.md b/SECURITY.md index 4fa544f..f1fa429 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -19,7 +19,8 @@ is credited unless you prefer otherwise. IOViewer reads files that can come from untrusted sources and writes HTML that is opened in a browser. Problems that matter most: -- crashes, hangs or unbounded memory use caused by a crafted `.glb`, `.obj` or `.json` file; +- crashes, hangs or unbounded memory use caused by a crafted `.glb`, `.obj`, `.json`, `.ifc`, `.ifczip` or `.rvt` file + (the CLI reads IFC and Revit files through IfcIO and RvtIO); - script injection into the generated HTML through model names, properties or other text taken from the input; - writing files outside the path a command was given; - the `--serve` preview server exposing files other than the generated viewer, or listening beyond the local machine; diff --git a/THIRD-PARTY-NOTICES.md b/THIRD-PARTY-NOTICES.md index 8106a2c..2aa6ccc 100644 --- a/THIRD-PARTY-NOTICES.md +++ b/THIRD-PARTY-NOTICES.md @@ -35,3 +35,47 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ``` + +## IOViewer.Cli tool package + +The `IOViewer.Cli` tool package reads IFC and Revit files through the engine adapters, so besides `IOViewer` and +`IOScene` (MIT, copyright (c) 2026 mahach666) it ships the assemblies listed below. The `IOViewer` library package +references none of them. + +| Component | Use | License | +|---|---|---| +| [IfcIO](https://github.com/IOExtend/IfcIO) 0.11.1 and IfcIO.Scene 0.11.1 | read IFC files into a scene | MIT, copyright (c) 2026 IfcIO contributors | +| [RvtIO](https://github.com/IOExtend/RvtIO) 0.4.0 and RvtIO.Scene 0.4.0 | read Revit files into a scene | MIT, copyright (c) 2026 mahach666 | +| .NET runtime libraries (DeflateManaged sources, compiled into RvtIO) | managed inflate implementation adapted for tolerant decoding | MIT, copyright (c) .NET Foundation and Contributors | +| [OpenMcdf](https://github.com/openmcdf/openmcdf) 3.4.0, used by RvtIO | reads the compound file container of Revit files | MPL-2.0, copyright (c) 2010-2026 Federico Blaseotto, Jeremy Powell | +| [SharpZipLib](https://github.com/icsharpcode/SharpZipLib) 1.4.2, used by RvtIO | stream decompression | MIT, copyright (c) 2000-2022 SharpZipLib Contributors | + +OpenMcdf is distributed unmodified under the Mozilla Public License 2.0 (); its source +code is available at . + +The MIT-licensed components above are distributed under the following terms, each with the copyright line given in the +table: + +```text +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +``` + +buildingSMART and IFC are registered trademarks or standards of buildingSMART International Ltd.; IfcIO is an +independent implementation of the IFC schemas. Autodesk and Revit are trademarks of Autodesk, Inc.; RvtIO is not +affiliated with, endorsed by or sponsored by Autodesk. diff --git a/docs/getting-started.md b/docs/getting-started.md index 4ab6ba5..9b1cd77 100644 --- a/docs/getting-started.md +++ b/docs/getting-started.md @@ -16,12 +16,18 @@ dotnet add package IOViewer ## Command line usage -Convert any glTF 2.0 Binary (`.glb`) or Wavefront OBJ (`.obj`) into a self-contained 3D HTML viewer: +Convert any glTF 2.0 Binary (`.glb`), Wavefront OBJ (`.obj`), IFC (`.ifc`, `.ifczip`, read with IfcIO) or Revit +(`.rvt`, read with RvtIO) model into a self-contained 3D HTML viewer: ```sh # Convert 3D model into an interactive standalone HTML viewer ioviewer model.glb -o viewer.html +# IFC and Revit models; what the engine could not convert is printed as warnings or errors on standard error, +# and an error (elements may be missing) gives exit code 4 after the output is written +ioviewer model.ifc +ioviewer model.rvt + # Launch local preview server and open in default browser ioviewer model.glb --serve ``` diff --git a/docs/index.md b/docs/index.md index 2a616b0..e763835 100644 --- a/docs/index.md +++ b/docs/index.md @@ -4,7 +4,7 @@ title: IOViewer # IOViewer -**IOViewer** is a fast, 100% managed .NET library and CLI tool for generating standalone interactive 3D WebGL / HTML BIM & CAD model viewers directly from code or file formats (glTF/GLB, Wavefront OBJ, and JSON). +**IOViewer** is a fast, 100% managed .NET library and CLI tool for generating standalone interactive 3D WebGL / HTML BIM & CAD model viewers directly from code or file formats (glTF/GLB, Wavefront OBJ and JSON; the CLI tool also reads IFC and Revit files through IfcIO and RvtIO). The generated HTML is a single file with no external dependencies that works offline: it opens from disk in a current browser with WebGL 2, without servers, plug-ins or network requests. The viewer is built on three.js, embedded in the file. @@ -24,7 +24,7 @@ The generated HTML is a single file with no external dependencies that works off - [Getting started](getting-started.md): install the package or CLI tool and generate your first 3D viewer. - [Public API](public-api.md): supported surface and key entry points of the library. -- [Third-party notices](https://github.com/IOExtend/IOViewer/blob/main/THIRD-PARTY-NOTICES.md): the three.js license. +- [Third-party notices](https://github.com/IOExtend/IOViewer/blob/main/THIRD-PARTY-NOTICES.md): the three.js license and the components the command line tool ships. - [Source on GitHub](https://github.com/IOExtend/IOViewer) and [DeepWiki](https://deepwiki.com/IOExtend/IOViewer) for an automatically generated overview of the repository. IOViewer is not affiliated with, endorsed by or sponsored by Autodesk. Autodesk, Revit, Navisworks, ViewCube and TimeLiner are trademarks of Autodesk, Inc. diff --git a/src/IOViewer.Cli/IOViewer.Cli.csproj b/src/IOViewer.Cli/IOViewer.Cli.csproj index c13d185..682f220 100644 --- a/src/IOViewer.Cli/IOViewer.Cli.csproj +++ b/src/IOViewer.Cli/IOViewer.Cli.csproj @@ -9,10 +9,15 @@ net8.0;net10.0 true false + + NU1901;NU1902;NU1903 + + diff --git a/src/IOViewer.Cli/Program.cs b/src/IOViewer.Cli/Program.cs index 29d9984..1d3466d 100644 --- a/src/IOViewer.Cli/Program.cs +++ b/src/IOViewer.Cli/Program.cs @@ -1,25 +1,32 @@ using System.Diagnostics; +using System.Globalization; using System.Net; using System.Reflection; +using System.Text; +using IfcIO.Scene; +using IOScene; using IOViewer.Exporters; using IOViewer.Importers; using IOViewer.Model; +using RvtIO.Scene; namespace IOViewer.Cli; internal static class Program { private const string UsageText = """ - Usage: ioviewer [output.html] [options] + Usage: ioviewer [output.html] [options] ioviewer --help | --version Generates standalone interactive 3D WebGL / HTML BIM & CAD model viewers - from 3D models (glTF/GLB, Wavefront OBJ, JSON). The HTML file has no - external dependencies and works offline. JSON input is viewer JSON, an - IOScene scene file or an IOViewer 0.1/0.2 snapshot. + from 3D models (glTF/GLB, Wavefront OBJ, JSON, IFC, Revit). The HTML file + has no external dependencies and works offline. JSON input is viewer JSON, + an IOScene scene file or an IOViewer 0.1/0.2 snapshot. IFC (.ifc, .ifczip) + is read with IfcIO and Revit (.rvt) with RvtIO; what they could not convert + is reported as warnings or errors. Arguments: - Path to input 3D model (.glb, .obj, or .json). + Path to input 3D model (.glb, .obj, .json, .ifc, .ifczip or .rvt). [output] Destination path for exported file (.html or .json). Default: .html. @@ -41,6 +48,7 @@ 0 Success 1 Usage error (missing or invalid arguments) 2 File not found 3 Data format error or parsing failure + 4 Output written, but IfcIO or RvtIO reported an error: elements may be missing """; public static int Main(string[] args) @@ -159,6 +167,7 @@ public static int Main(string[] args) var sw = Stopwatch.StartNew(); ViewerDocument doc; + IReadOnlyList diagnostics = []; try { string ext = Path.GetExtension(inputPath).ToLowerInvariant(); @@ -167,12 +176,14 @@ public static int Main(string[] args) ".glb" => GlbViewerImporter.Load(inputPath), ".obj" => ObjViewerImporter.Load(inputPath), ".json" => JsonViewerImporter.Load(inputPath), - _ => throw new NotSupportedException($"Unsupported input file extension: '{ext}'. Supported: .glb, .obj, .json.") + ".ifc" or ".ifczip" => FromIfc(inputPath, out diagnostics), + ".rvt" => FromRvt(inputPath, out diagnostics), + _ => throw new NotSupportedException($"Unsupported input file extension: '{ext}'. Supported: .glb, .obj, .json, .ifc, .ifczip, .rvt.") }; } catch (Exception ex) { - Console.Error.WriteLine($"Error: Failed to load '{inputPath}': {ex.Message}"); + Console.Error.WriteLine($"Error: Failed to load '{inputPath}': {Printable(ex.Message)}"); return 3; } @@ -205,7 +216,7 @@ public static int Main(string[] args) } catch (Exception ex) when (ex is InvalidDataException or ArgumentException) { - Console.Error.WriteLine($"Error: Failed to export '{inputPath}': {ex.Message}"); + Console.Error.WriteLine($"Error: Failed to export '{inputPath}': {Printable(ex.Message)}"); return 3; } var fi = new FileInfo(outputPath); @@ -229,9 +240,47 @@ public static int Main(string[] args) StartServe(outputPath, servePort); } - return 0; + return ExitCode(diagnostics); } + private static ViewerDocument FromIfc(string path, out IReadOnlyList diagnostics) + { + var result = IfcSceneReader.Read(path); + diagnostics = result.Diagnostics; + return FromScene(path, result.Document, diagnostics); + } + + private static ViewerDocument FromRvt(string path, out IReadOnlyList diagnostics) + { + var result = RvtSceneReader.Read(path); + diagnostics = result.Diagnostics; + return FromScene(path, result.Document, diagnostics); + } + + // An error of the engine adapter means elements may be missing: the output is still written, and the exit code says so. + internal static int ExitCode(IReadOnlyList diagnostics) => + diagnostics.Any(d => d.Severity == SceneSeverity.Error) ? 4 : 0; + + // The engine adapters key the model by its file name, as the other importers do; the title falls back to it too. + internal static ViewerDocument FromScene(string path, SceneDocument scene, IReadOnlyList diagnostics) + { + if (string.IsNullOrEmpty(scene.Title)) scene.Title = Path.GetFileNameWithoutExtension(path); + // Information entries (such as an element that has no geometry by design) are not reported; one line per kind. + foreach (var kind in diagnostics.Where(d => d.Severity != SceneSeverity.Info).GroupBy(d => (d.Severity, d.Code))) + { + int more = kind.Count() - 1; + string label = kind.Key.Severity == SceneSeverity.Error ? "Error" : "Warning"; + Console.Error.WriteLine($"{label}: {kind.Key.Code}: {Printable(kind.First().Message)}{(more > 0 ? $" ({more} more)" : "")}"); + } + return new ViewerDocument(scene); + } + + // Messages can quote names from the model file: control characters (escape sequences, line breaks) and format + // characters (bidirectional overrides, invisible tag characters) become '?'. Runes, so characters above U+FFFF count too. + internal static string Printable(string text) => + string.Concat(text.EnumerateRunes().Select(r => + Rune.IsControl(r) || Rune.GetUnicodeCategory(r) == UnicodeCategory.Format ? "?" : r.ToString())); + private static void StartServe(string htmlPath, int port) { string url = $"http://localhost:{port}/"; diff --git a/src/IOViewer/IOViewer.csproj b/src/IOViewer/IOViewer.csproj index e301b35..4809433 100644 --- a/src/IOViewer/IOViewer.csproj +++ b/src/IOViewer/IOViewer.csproj @@ -5,7 +5,7 @@ IOViewer true $(DefaultItemExcludes);Viewer/node_modules/** - + $(NoWarn);NU5104 diff --git a/tests/IOViewer.Tests/CliTests.cs b/tests/IOViewer.Tests/CliTests.cs index f4fdc30..198b680 100644 --- a/tests/IOViewer.Tests/CliTests.cs +++ b/tests/IOViewer.Tests/CliTests.cs @@ -3,6 +3,8 @@ namespace IOViewer.Tests; +// Redirects Console.Out and Console.Error; see ModelAndCliIntegrationTests. +[Collection("Console")] public class CliTests { private static readonly string[] HelpArgs = ["--help"]; @@ -19,7 +21,7 @@ public void Cli_Help_ReturnsSuccessAndShowsUsage() int code = Program.Main(HelpArgs); Assert.Equal(0, code); string output = sw.ToString(); - Assert.Contains("ioviewer ", output); + Assert.Contains("ioviewer ", output); Assert.Contains("--wireframe", output); Assert.Contains("--white-mode", output); Assert.Contains("--serve", output); diff --git a/tests/IOViewer.Tests/ModelAndCliIntegrationTests.cs b/tests/IOViewer.Tests/ModelAndCliIntegrationTests.cs index d9dc573..ee95a96 100644 --- a/tests/IOViewer.Tests/ModelAndCliIntegrationTests.cs +++ b/tests/IOViewer.Tests/ModelAndCliIntegrationTests.cs @@ -1,11 +1,15 @@ using IOScene; using IOViewer.Cli; using IOViewer.Exporters; +using IOViewer.Importers; using IOViewer.Model; +using RvtIO.Scene; using Xunit; namespace IOViewer.Tests; +// Console.Error and Console.Out are process-wide: tests that redirect them share one collection, so they never run in parallel. +[Collection("Console")] public class ModelAndCliIntegrationTests { [Fact] @@ -189,4 +193,237 @@ public void Cli_ConvertsEveryJsonKindToHtml(string kind) if (File.Exists(tempHtml)) File.Delete(tempHtml); } } + + private const string Hostile = "\">"; + + // Project, site, building and storey; a wall box with Pset_WallCommon, a window without a style (drawn + // translucent by its IFC class) and a proxy whose name and property set are hostile strings. Lengths in mm. + private const string SmokeIfc = $""" + ISO-10303-21; + HEADER; + FILE_DESCRIPTION((''),'2;1'); + FILE_NAME('smoke.ifc','2026-01-01T00:00:00',(''),(''),'','',''); + FILE_SCHEMA(('IFC2X3')); + ENDSEC; + DATA; + #1=IFCPROJECT('0SmokeProject000000001',$,'Smoke',$,$,$,$,(#20),#10); + #10=IFCUNITASSIGNMENT((#11)); + #11=IFCSIUNIT(*,.LENGTHUNIT.,.MILLI.,.METRE.); + #20=IFCGEOMETRICREPRESENTATIONCONTEXT($,'Model',3,1.E-05,#21,$); + #21=IFCAXIS2PLACEMENT3D(#22,$,$); + #22=IFCCARTESIANPOINT((0.,0.,0.)); + #30=IFCSITE('0SmokeSite000000000001',$,'Site',$,$,#31,$,$,.ELEMENT.,$,$,$,$,$); + #31=IFCLOCALPLACEMENT($,#21); + #32=IFCBUILDING('0SmokeBuilding00000001',$,'Building',$,$,#33,$,$,.ELEMENT.,$,$,$); + #33=IFCLOCALPLACEMENT(#31,#21); + #40=IFCBUILDINGSTOREY('0SmokeStorey0000000001',$,'Level 1',$,$,#41,$,$,.ELEMENT.,0.); + #41=IFCLOCALPLACEMENT(#33,#21); + #50=IFCRELAGGREGATES('0SmokeAggregates000001',$,$,$,#1,(#30)); + #51=IFCRELAGGREGATES('0SmokeAggregates000002',$,$,$,#30,(#32)); + #52=IFCRELAGGREGATES('0SmokeAggregates000003',$,$,$,#32,(#40)); + #100=IFCWALL('1SmokeWall000000000001',$,'Wall',$,$,#101,#102,$); + #101=IFCLOCALPLACEMENT(#41,#21); + #102=IFCPRODUCTDEFINITIONSHAPE($,$,(#103)); + #103=IFCSHAPEREPRESENTATION(#20,'Body','Brep',(#104)); + #104=IFCFACETEDBREP(#105); + #105=IFCCLOSEDSHELL((#110,#111,#112,#113,#114,#115)); + #110=IFCFACE((#120)); + #111=IFCFACE((#121)); + #112=IFCFACE((#122)); + #113=IFCFACE((#123)); + #114=IFCFACE((#124)); + #115=IFCFACE((#125)); + #120=IFCFACEOUTERBOUND(#130,.T.); + #121=IFCFACEOUTERBOUND(#131,.T.); + #122=IFCFACEOUTERBOUND(#132,.T.); + #123=IFCFACEOUTERBOUND(#133,.T.); + #124=IFCFACEOUTERBOUND(#134,.T.); + #125=IFCFACEOUTERBOUND(#135,.T.); + #130=IFCPOLYLOOP((#200,#203,#202,#201)); + #131=IFCPOLYLOOP((#204,#205,#206,#207)); + #132=IFCPOLYLOOP((#200,#201,#205,#204)); + #133=IFCPOLYLOOP((#201,#202,#206,#205)); + #134=IFCPOLYLOOP((#202,#203,#207,#206)); + #135=IFCPOLYLOOP((#203,#200,#204,#207)); + #200=IFCCARTESIANPOINT((0.,0.,0.)); + #201=IFCCARTESIANPOINT((4000.,0.,0.)); + #202=IFCCARTESIANPOINT((4000.,200.,0.)); + #203=IFCCARTESIANPOINT((0.,200.,0.)); + #204=IFCCARTESIANPOINT((0.,0.,3000.)); + #205=IFCCARTESIANPOINT((4000.,0.,3000.)); + #206=IFCCARTESIANPOINT((4000.,200.,3000.)); + #207=IFCCARTESIANPOINT((0.,200.,3000.)); + #300=IFCPROPERTYSINGLEVALUE('FireRating',$,IFCLABEL('EI 60'),$); + #301=IFCPROPERTYSET('2SmokePsetWall00000001',$,'Pset_WallCommon',$,(#300)); + #302=IFCRELDEFINESBYPROPERTIES('2SmokeDefinesWall00001',$,$,$,(#100),#301); + #400=IFCWINDOW('1SmokeWindow0000000001',$,'Window',$,$,#401,#402,$,1000.,1000.); + #401=IFCLOCALPLACEMENT(#41,#403); + #403=IFCAXIS2PLACEMENT3D(#404,$,$); + #404=IFCCARTESIANPOINT((0.,-1000.,0.)); + #402=IFCPRODUCTDEFINITIONSHAPE($,$,(#405)); + #405=IFCSHAPEREPRESENTATION(#20,'Body','Brep',(#406)); + #406=IFCFACETEDBREP(#105); + #500=IFCBUILDINGELEMENTPROXY('1SmokeHostile000000001',$,'{Hostile}',$,$,#501,#502,$,$); + #501=IFCLOCALPLACEMENT(#41,#503); + #503=IFCAXIS2PLACEMENT3D(#504,$,$); + #504=IFCCARTESIANPOINT((0.,1000.,0.)); + #502=IFCPRODUCTDEFINITIONSHAPE($,$,(#505)); + #505=IFCSHAPEREPRESENTATION(#20,'Body','Brep',(#506)); + #506=IFCFACETEDBREP(#105); + #510=IFCPROPERTYSINGLEVALUE('{Hostile}',$,IFCLABEL('{Hostile}'),$); + #511=IFCPROPERTYSET('2SmokePsetHostile00001',$,'{Hostile}',$,(#510)); + #512=IFCRELDEFINESBYPROPERTIES('2SmokeDefinesHostile01',$,$,$,(#500),#511); + #600=IFCRELCONTAINEDINSPATIALSTRUCTURE('2SmokeContainment00001',$,$,$,(#100,#400,#500),#40); + ENDSEC; + END-ISO-10303-21; + """; + + [Fact] + public void Cli_ConvertIfcToHtml_ReadsTheModelThroughIfcIO() + { + var tempIfc = Path.Combine(Path.GetTempPath(), $"test_model_{Guid.NewGuid():N}.ifc"); + var tempHtml = Path.ChangeExtension(tempIfc, ".html"); + var tempJson = Path.ChangeExtension(tempIfc, ".json"); + using var errors = new StringWriter(); + var origErr = Console.Error; + try + { + File.WriteAllText(tempIfc, SmokeIfc); + Console.SetError(errors); + + int code = Program.Main([tempIfc, "--json", tempJson]); + + Assert.Equal(0, code); + Assert.Equal("", errors.ToString()); + var scene = JsonViewerImporter.Load(tempJson).Scene; + Assert.Empty(scene.Validate()); + Assert.Equal(Path.GetFileName(tempIfc), Assert.Single(scene.Models).Key); + + var view = ViewerHtml.Parse(File.ReadAllText(tempHtml)); + Assert.Equal("Smoke", view.Meta.GetProperty("title").GetString()); + Assert.Equal(3, view.InstanceCount); + var elements = view.Meta.GetProperty("elements").EnumerateArray().ToList(); + + // The wall's property set and GlobalId reach the page. + Assert.Equal("EI 60", view.Props.GetProperty("100").GetProperty("Pset_WallCommon").GetProperty("FireRating").GetString()); + var wall = Assert.Single(elements, e => e.GetProperty("id").GetInt64() == 100); + Assert.Equal("1SmokeWall000000000001", wall.GetProperty("sourceId").GetString()); + + // Hostile names and values are kept as data and escaped in the page. + Assert.Equal(Hostile, view.Props.GetProperty("500").GetProperty(Hostile).GetProperty(Hostile).GetString()); + Assert.Equal(Hostile, Assert.Single(elements, e => e.GetProperty("id").GetInt64() == 500).GetProperty("name").GetString()); + Assert.DoesNotContain(Hostile, view.Html, StringComparison.Ordinal); + + // The window has no style, so it is drawn in its class colour at half opacity (alpha 128 of 255). + Assert.Contains( + view.Meta.GetProperty("materials").EnumerateArray(), + m => Math.Abs(m.GetProperty("opacity").GetDouble() - 128 / 255.0) < 1e-6); + } + finally + { + Console.SetError(origErr); + foreach (var file in new[] { tempIfc, tempHtml, tempJson }) + { + if (File.Exists(file)) File.Delete(file); + } + } + } + + [Fact] + public void Cli_AdapterDiagnostics_AreReportedOncePerSeverityAndKind() + { + using var errors = new StringWriter(); + var origErr = Console.Error; + try + { + Console.SetError(errors); + + Program.FromScene("model.rvt", new SceneDocument(), + [ + new(SceneSeverity.Error, "read-cut", "Cut one."), + new(SceneSeverity.Error, "read-cut", "Cut two."), + new(SceneSeverity.Warning, "read-cut", "Cut warning."), + new(SceneSeverity.Warning, "no-geometry", "No geometry."), + new(SceneSeverity.Info, "skipped", "Skipped."), + new(SceneSeverity.Warning, "empty-mesh", "Element 'x\u001b]0;t\u0007\r\nError: forged‮gpj.exe' has no mesh."), + ]); + + Assert.Equal( + string.Join(Environment.NewLine, + "Error: read-cut: Cut one. (1 more)", + "Warning: read-cut: Cut warning.", + "Warning: no-geometry: No geometry.", + "Warning: empty-mesh: Element 'x?]0;t???Error: forged?gpj.exe' has no mesh.", + ""), + errors.ToString()); + } + finally + { + Console.SetError(origErr); + } + } + + [Fact] + public void Cli_Printable_ReplacesControlAndFormatCharactersOnly() + { + Assert.Equal("Стена 1 «A» ?? ? ? ? ?? 😀", Program.Printable("Стена 1 «A» \t\n \u0085 ⁦ ​ \U000E0041\U000E007F 😀")); + } + + [Fact] + public void Cli_ExitCode_IsFourOnlyWhenTheAdapterReportedAnError() + { + Assert.Equal(0, Program.ExitCode([])); + Assert.Equal(0, Program.ExitCode( + [ + new(SceneSeverity.Warning, "no-geometry", "No geometry."), + new(SceneSeverity.Info, "skipped", "Skipped."), + ])); + Assert.Equal(4, Program.ExitCode( + [ + new(SceneSeverity.Warning, "no-geometry", "No geometry."), + new(SceneSeverity.Error, "read-cut", "Cut."), + ])); + } + + // A real Revit file cannot be committed; run with IOVIEWER_RVT_FILE set to one before a release. + [RvtFileFact] + public void Cli_ConvertRvtToHtml_ReadsTheModelThroughRvtIO() + { + var rvt = Environment.GetEnvironmentVariable(RvtFileFactAttribute.Variable)!; + var tempHtml = Path.Combine(Path.GetTempPath(), $"test_viewer_{Guid.NewGuid():N}.html"); + var tempJson = Path.ChangeExtension(tempHtml, ".json"); + using var errors = new StringWriter(); + var origErr = Console.Error; + try + { + Console.SetError(errors); + int code = Program.Main([rvt, "-o", tempHtml, "--json", tempJson]); + Console.SetError(origErr); + + // An engine error still writes both outputs and gives exit code 4; anything else must be a clean 0. + bool engineError = RvtSceneReader.Read(rvt).Diagnostics.Any(d => d.Severity == SceneSeverity.Error); + Assert.True(code == (engineError ? 4 : 0), $"exit code {code}: {errors}"); + Assert.Empty(JsonViewerImporter.Load(tempJson).Scene.Validate()); + Assert.True(ViewerHtml.Parse(File.ReadAllText(tempHtml)).InstanceCount > 0); + } + finally + { + Console.SetError(origErr); + if (File.Exists(tempHtml)) File.Delete(tempHtml); + if (File.Exists(tempJson)) File.Delete(tempJson); + } + } + + private sealed class RvtFileFactAttribute : FactAttribute + { + public const string Variable = "IOVIEWER_RVT_FILE"; + + public RvtFileFactAttribute() + { + if (string.IsNullOrEmpty(Environment.GetEnvironmentVariable(Variable))) + { + Skip = $"Set {Variable} to the path of a Revit 2022 file to run this test."; + } + } + } } diff --git a/tools/pack-release.ps1 b/tools/pack-release.ps1 index 465fed8..96cc3d2 100644 --- a/tools/pack-release.ps1 +++ b/tools/pack-release.ps1 @@ -73,8 +73,51 @@ if ($LASTEXITCODE -ne 0) { throw "git archive failed with exit code $LASTEXITCOD # 5. Pack NuGet Packages Write-Host "Packing NuGet packages..." +# Packages left from an earlier run would be checked and published together with this version. +Get-ChildItem -LiteralPath $Output -File | Where-Object { $_.Extension -in '.nupkg', '.snupkg' } | Remove-Item Invoke-DotNet pack (Join-Path $root 'IOViewer.slnx') -c Release --no-build -o $Output +Write-Host "Checking package dependencies..." +Add-Type -AssemblyName System.IO.Compression.FileSystem +$checkedViewer = $false +foreach ($package in Get-ChildItem -LiteralPath $Output -Filter '*.nupkg') { + $zip = [System.IO.Compression.ZipFile]::OpenRead($package.FullName) + try { + $entry = @($zip.Entries | Where-Object { $_.FullName -notlike '*/*' -and $_.Name -like '*.nuspec' })[0] + $reader = New-Object System.IO.StreamReader($entry.Open()) + try { $nuspec = [xml]$reader.ReadToEnd() } finally { $reader.Dispose() } + } + finally { $zip.Dispose() } + $dependencies = @($nuspec.SelectNodes("//*[local-name()='dependency']")) + # IOScene lower bound: replaces the NU5104 check that the IOScene range switches off: no package built on a preview contract reaches nuget.org. + if ($package.Name -eq "IOViewer.$version.nupkg") { + $checkedViewer = $true + $scene = @($dependencies | Where-Object { $_.GetAttribute('id') -eq 'IOScene' }) + if ($scene.Count -eq 0) { throw "$($package.Name) has no dependency on IOScene" } + foreach ($dependency in $scene) { + $range = $dependency.GetAttribute('version') + $lower = $range.TrimStart('[', '(').Split(',')[0].Trim() + if ($lower -eq '' -or $lower.Contains('-')) { + throw "$($package.Name) depends on IOScene '$range', whose lower bound is missing or a preview; release on a published IOScene" + } + } + } + # Bounds nuget.org accepts: nuget.org refuses a dependency bound with metadata, or one whose prerelease label has one part and does not start + # with a letter (NuGetGallery ManifestValidator.ValidateDependencyVersion); dotnet pack accepts both, so only the push would fail. + foreach ($dependency in $dependencies) { + $range = $dependency.GetAttribute('version') + foreach ($bound in $range.Trim('[', ']', '(', ')').Split(',')) { + $bound = $bound.Trim() + $label = if ($bound.Contains('-')) { $bound.Substring($bound.IndexOf('-') + 1) } else { '' } + if ($bound.Contains('+') -or ($label -ne '' -and -not $label.Contains('.') -and $label -notmatch '^[a-z][0-9a-z-]*$')) { + throw "$($package.Name) depends on $($dependency.GetAttribute('id')) '$range', whose bound '$bound' nuget.org refuses" + } + } + } +} +# NuGet names the package by the normalized version; a Version written otherwise would skip the IOScene lower-bound check without this. +if (-not $checkedViewer) { throw "IOViewer.$version.nupkg was not found in '$Output'; its IOScene dependency was not checked" } + # 6. Checksums Write-Host "Calculating SHA-256 sums..." $sumsFile = Join-Path $Output 'SHA256SUMS.txt'