Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions docs/public-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,9 @@ and visibility.
Embedded element IDs and their clash and schedule references use decimal strings outside JavaScript's safe integer range.
- `HtmlViewerOptions`: Title, which data to include (properties, viewpoints, grids, 4D schedule, clashes), the initial display mode (`InitialWireframe`, `InitialWhiteMode`), and `MaxMeshVertices`, which is unlimited by default; when a lower limit leaves meshes out, the viewer shows how many were written.
- `JsonViewerExporter`: Writes a `ViewerDocument` as viewer JSON (`"Kind": "ioviewer"`, `"Format": 2`). A scene alone is written with IOScene's `SceneJson`.
- `ClusterSourceWriter.Export(document, stream, options)`: Writes the triangle records and review metadata for the
clustered viewer into an empty, writable, seekable stream and returns the number of triangles written. The caller
retains ownership of the stream.

### Compute and export clash results

Expand Down
20 changes: 16 additions & 4 deletions src/IOViewer/Exporters/ClusterSourceWriter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@

namespace IOViewer.Exporters;

// Disk-backed handoff to the offline LOD builder. A record is at most 8,192 triangles.
internal static class ClusterSourceWriter
/// <summary>Writes a seekable mesh source for the clustered viewer's page builder.</summary>
public static class ClusterSourceWriter
{
private const int RecordIndices = 8192 * 3;
private const uint Signature = 0x33534d49; // IMS3
Expand All @@ -25,8 +25,7 @@ internal static long Save(ViewerDocument doc, string target, HtmlViewerOptions o
{
long triangles;
using (var stream = new FileStream(temporary, FileMode.CreateNew, FileAccess.Write, FileShare.None, 65536))
using (var writer = new BinaryWriter(stream))
triangles = Write(doc, writer, options);
triangles = Export(doc, stream, options);
File.Move(temporary, path);
return triangles;
}
Expand All @@ -36,6 +35,19 @@ internal static long Save(ViewerDocument doc, string target, HtmlViewerOptions o
}
}

/// <summary>Writes an IMS mesh source and returns the number of triangles. The fresh destination must be
/// writable and seekable. The caller retains ownership of the stream.</summary>
public static long Export(ViewerDocument document, Stream destination, HtmlViewerOptions? options = null)
{
ArgumentNullException.ThrowIfNull(document);
ArgumentNullException.ThrowIfNull(destination);
if (!destination.CanWrite || !destination.CanSeek || destination.Length != 0 || destination.Position != 0)
throw new ArgumentException("Use an empty, writable, seekable stream.", nameof(destination));

using var writer = new BinaryWriter(destination, System.Text.Encoding.UTF8, leaveOpen: true);
return Write(document, writer, options ?? new HtmlViewerOptions());
}

private static long Write(ViewerDocument doc, BinaryWriter writer, HtmlViewerOptions options)
{
var scene = doc.Scene;
Expand Down
401 changes: 17 additions & 384 deletions src/IOViewer/Viewer/build-mesh-pages.js

Large diffs are not rendered by default.

412 changes: 412 additions & 0 deletions src/IOViewer/Viewer/src/stream/meshBuilder.js

Large diffs are not rendered by default.

7 changes: 4 additions & 3 deletions src/IOViewer/Viewer/src/stream/meshLod.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { MESH_BUDGET, MIB } from './manifest.js';
import { readPlacements, residentBytes, sizeOfPage, validateMeshPages, viewsOfPage } from './meshPages.js';
import { mountMeshTools } from './meshTools.js';
import { meshScene } from './meshScene.js';
import { fetchMeshResource } from './meshSource.js';
import { SectionCaps } from '../tools/sectionCaps.js';

const canvas = document.querySelector('canvas');
Expand All @@ -27,7 +28,7 @@ function show(text) {

async function fetchRange(path, bytes, signal) {
const start = profile && performance.now();
const response = await fetch(path, { cache: 'no-store', signal });
const response = await fetchMeshResource(path, { cache: 'no-store', signal });
if (!response.ok || Number(response.headers.get('content-length')) !== bytes) throw new Error(`${path} failed (${response.status}).`);
const data = await response.arrayBuffer();
if (profile) profile.fetch(performance.now() - start, data.byteLength);
Expand All @@ -45,7 +46,7 @@ const box = ({ min, max }) => new THREE.Box3(new THREE.Vector3(...min), new THRE
const BASE_ERROR = 1.5, MERGE_ERROR = 1, MOVE_SETTLE = 180;

try {
const response = await fetch('/manifest.json');
const response = await fetchMeshResource('/manifest.json');
if (!response.ok) throw new Error(`Manifest: HTTP ${response.status}.`);
const manifest = validateMeshPages(await response.json());
if (manifest.review?.title) document.title = manifest.review.title;
Expand Down Expand Up @@ -85,7 +86,7 @@ async function start(manifest, context) {
let rasterScale = 1, lastScaleChange = -Infinity;
let drawn = new Set();
if (manifest.overview) {
const response = await fetch('/overview.bin', { cache: 'no-store' });
const response = await fetchMeshResource('/overview.bin', { cache: 'no-store' });
if (!response.ok || Number(response.headers.get('content-length')) !== manifest.overview) throw new Error('Invalid overview size.');
const overview = await response.arrayBuffer();
if (overview.byteLength !== manifest.overview) throw new Error('Truncated overview.');
Expand Down
51 changes: 51 additions & 0 deletions src/IOViewer/Viewer/src/stream/meshSource.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import { MESH_MANIFEST_BYTES, sizeOfPage, validateMeshPages } from './meshPages.js';

export function fetchMeshResource(path, options) {
const local = globalThis.IOVIEWER_MESH_SOURCE;
return local ? local.fetch(path, options) : fetch(path, options);
}

// openFile returns a File or Blob from private storage. Page payloads stay in storage until requested.
export async function openMeshPackage(openFile) {
const manifestFile = await openFile('manifest.json');
if (manifestFile.size > MESH_MANIFEST_BYTES) throw new Error('Manifest exceeds its size limit.');
const manifest = validateMeshPages(JSON.parse(await manifestFile.text()));
const files = new Map();

async function slice(name, length, offset, size, signal) {
if (!files.has(name)) files.set(name, Promise.resolve().then(() => openFile(name)).catch((error) => {
files.delete(name);
throw error;
}));
const file = await files.get(name);
signal?.throwIfAborted();
if (file.size !== length || offset + size > file.size) throw new Error('Invalid mesh data file size.');
return new Response(file.slice(offset, offset + size), { headers: { 'Content-Length': String(size) } });
}

return {
async fetch(path, { signal } = {}) {
signal?.throwIfAborted();
if (path === '/manifest.json') return new Response(manifestFile);
if (path === '/overview.bin' && manifest.overview)
return slice('overview.bin', manifest.overview, 0, manifest.overview, signal);
const match = /^\/(pages|shapes|elements)\/(0|[1-9]\d*)$/.exec(path);
if (match) {
const id = Number(match[2]);
if (match[1] === 'pages' && manifest.pages[id]) {
const page = manifest.pages[id];
return slice('meshes.bin', manifest.bytes, page.offset, sizeOfPage(page), signal);
}
if (match[1] === 'shapes' && manifest.shapes?.[id]) {
const shape = manifest.shapes[id];
return slice('shapes.bin', manifest.shapeBytes, shape.offset, sizeOfPage(shape), signal);
}
if (match[1] === 'elements' && manifest.elements?.[id]?.size) {
const element = manifest.elements[id];
return slice('elements.bin', manifest.propertyBytes, element.offset, element.size, signal);
}
}
return new Response(null, { status: 404 });
},
};
}
57 changes: 57 additions & 0 deletions src/IOViewer/Viewer/src/stream/meshStorage.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import { buildMeshPagesFromSource } from './meshBuilder.js';

const WINDOW_BYTES = 64 * 1024;

// Called in a dedicated worker. The caller owns the empty temporary output directory.
export async function buildLocalMeshPackage(file, directory, includeBim = true, onProgress) {
const reader = new FileReaderSync();
let windowStart = -1, bytes;
const source = {
length: file.size,
read(target, offset) {
if (offset >= file.size || target.length === 0) return 0;
const start = Math.floor(offset / WINDOW_BYTES) * WINDOW_BYTES;
if (start !== windowStart) {
bytes = new Uint8Array(reader.readAsArrayBuffer(file.slice(start, start + WINDOW_BYTES)));
windowStart = start;
}
const inside = offset - start;
const part = bytes.subarray(inside, inside + target.length);
target.set(part);
return part.length;
},
};

// OPFS acquisition is asynchronous. The mesh builder only uses synchronous reads and writes.
const handles = new Map();
try {
for (const name of ['meshes.bin', 'shapes.bin', 'elements.bin', 'manifest.json']) {
const file = await directory.getFileHandle(name, { create: true });
const handle = await file.createSyncAccessHandle();
handles.set(name, handle);
if (handle.getSize() !== 0) throw new Error('Mesh output must be empty.');
}
return await buildMeshPagesFromSource(source, (name) => {
const handle = handles.get(name);
let end = 0;
return {
read: (target, offset) => handle.read(target, { at: offset }),
write(data) {
let written = 0;
while (written < data.length) {
const count = handle.write(data.subarray(written), { at: end + written });
if (count <= 0) throw new Error('Could not write the local mesh package.');
written += count;
}
end += written;
},
close() {
handle.close();
handles.delete(name);
},
};
}, includeBim, onProgress);
} finally {
for (const handle of handles.values()) handle.close();
}
}
3 changes: 2 additions & 1 deletion src/IOViewer/Viewer/src/stream/meshTools.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import { mountViews } from '../ui/viewsPanel.js';
import { mountClashes } from '../ui/clashesPanel.js';
import { mountLinks } from '../ui/linksPanel.js';
import { mountTimeliner } from '../ui/timeliner.js';
import { fetchMeshResource } from './meshSource.js';
import { meshSnapCandidates } from './meshSnap.js';

// Trace the original leaves independently of the cut on screen. The nearest hit gives the same element at every LOD.
Expand Down Expand Up @@ -101,7 +102,7 @@ export function mountMeshTools({ manifest, roots, nodes, bounds, world, controls
const data = { meta, async loadProperties(index, signal) {
const entry = elements[index];
if (!entry.size) return null;
const response = await fetch(`/elements/${index}`, { signal });
const response = await fetchMeshResource(`/elements/${index}`, { signal });
if (!response.ok || Number(response.headers.get('content-length')) !== entry.size) throw new Error('Invalid element response.');
const loaded = await response.json();
if (loaded?.id !== entry.id || !loaded.properties || typeof loaded.properties !== 'object' || Array.isArray(loaded.properties)
Expand Down
62 changes: 50 additions & 12 deletions src/IOViewer/Viewer/test/unit/meshPages.test.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,21 @@
import assert from 'node:assert/strict';
import { mkdtemp, readFile, rm, rmdir, writeFile } from 'node:fs/promises';
import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { basename, dirname, join, resolve } from 'node:path';
import test from 'node:test';
import { buildMeshPages, focusBounds } from '../../build-mesh-pages.js';
import { buildMeshPagesFromSource } from '../../src/stream/meshBuilder.js';
import { INSTANCE_BYTES, MESH_FORMAT, pageBytes, readPlacements, validateMeshPages, viewsOfPage } from '../../src/stream/meshPages.js';
import { openMeshPackage } from '../../src/stream/meshSource.js';

const bounds = { min: [0, 0, 0], max: [1, 1, 0] };
const fixtureRoot = resolve(tmpdir());

async function removeFixture(folder) {
assert.equal(dirname(resolve(folder)), fixtureRoot);
assert.match(basename(folder), /^ioviewer-(mesh|bim)-pages-/);
await rm(folder, { recursive: true, force: true, maxRetries: 3 });
}

test('a shared shape has one byte range and instance batches validate their own placement data', () => {
const shape = { vertices: 3, indices: 3, offset: 0 };
Expand Down Expand Up @@ -49,7 +58,7 @@ test('the initial focus ignores a remote record with less than one percent of th
});

test('a native geometry record produces the same indexed triangle and preserves alpha', async () => {
const folder = await mkdtemp(join(tmpdir(), 'ioviewer-mesh-pages-'));
const folder = await mkdtemp(join(fixtureRoot, 'ioviewer-mesh-pages-'));
const output = join(folder, 'output'), source = join(folder, 'one.ivmesh');
try {
const bytes = Buffer.alloc(116);
Expand All @@ -73,14 +82,12 @@ test('a native geometry record produces the same indexed triangle and preserves
assert.deepEqual([...mesh.normal], [0, 0, 32767, 0, 0, 32767, 0, 0, 32767]);
assert.deepEqual([...mesh.color], [255, 0, 0, 128, 255, 0, 0, 128, 255, 0, 0, 128]);
} finally {
await Promise.all([source, join(output, 'manifest.json'), join(output, 'meshes.bin')].map((file) => rm(file, { force: true })));
await rmdir(output).catch((error) => { if (error.code !== 'ENOENT') throw error; });
await rmdir(folder);
await removeFixture(folder);
}
});

test('IMS2 preserves exact IDs and property ranges and also packs geometry alone', async () => {
const folder = await mkdtemp(join(tmpdir(), 'ioviewer-bim-pages-'));
const folder = await mkdtemp(join(fixtureRoot, 'ioviewer-bim-pages-'));
const source = join(folder, 'one.ivmesh'), review = join(folder, 'review'), geometry = join(folder, 'geometry');
const property = Buffer.from('{"id":"9007199254740993","name":"Slab","category":"Floors","properties":{"Identity":{"Type":"Slab"}}}');
try {
Expand All @@ -103,6 +110,41 @@ test('IMS2 preserves exact IDs and property ranges and also packs geometry alone
const annotated = await buildMeshPages(source, review);
assert.deepEqual(annotated.elements, [{ ...bounds, id: '9007199254740993', name: 'Slab', category: 'Floors', offset: 0, size: property.length }]);
assert.deepEqual(await readFile(join(review, 'elements.bin')), property);
const browserFiles = new Map(), progress = [];
function copy(bytes, target, offset, size = target.length) {
const part = bytes.subarray(offset, offset + Math.min(size, target.length));
target.set(part);
return part.length;
}
const fromRanges = await buildMeshPagesFromSource({
length: input.length,
read: (target, offset) => copy(input, target, offset, 7),
}, (name) => {
let bytes = Buffer.alloc(0);
return {
read: (target, offset) => copy(bytes, target, offset),
write: (part) => { bytes = Buffer.concat([bytes, part]); },
close: () => { browserFiles.set(name, bytes); },
};
}, true, update => progress.push(update));
assert.deepEqual(fromRanges, annotated);
assert.deepEqual(progress, [
{ phase: 'triangles', completed: 0, total: 1 },
{ phase: 'triangles', completed: 1, total: 1 },
{ phase: 'properties', completed: 0, total: 1 },
{ phase: 'properties', completed: 1, total: 1 },
]);
for (const [name, data] of browserFiles) assert.deepEqual(data, await readFile(join(review, name)));

const local = await openMeshPackage(async (name) => new Blob([browserFiles.get(name)]));
const response = await local.fetch('/pages/0');
assert.equal(Number(response.headers.get('Content-Length')), browserFiles.get('meshes.bin').length);
assert.deepEqual(Buffer.from(await response.arrayBuffer()), browserFiles.get('meshes.bin'));
assert.deepEqual(await (await local.fetch('/elements/0')).json(), JSON.parse(property));
assert.equal((await local.fetch('/pages/01')).status, 404);
const abort = new AbortController();
abort.abort();
await assert.rejects(local.fetch('/pages/0', { signal: abort.signal }), { name: 'AbortError' });
const shape = await buildMeshPages(source, geometry, false);
assert.equal(shape.elements, undefined);
const detailed = viewsOfPage(Uint8Array.from(await readFile(join(review, 'meshes.bin'))).buffer, annotated.pages[0]);
Expand All @@ -111,10 +153,6 @@ test('IMS2 preserves exact IDs and property ranges and also packs geometry alone
assert.deepEqual(detailed.position, bare.position);
assert.deepEqual(detailed.index, bare.index);
} finally {
await Promise.all([source, join(review, 'elements.bin'), ...[review, geometry].flatMap((dir) => [
join(dir, 'manifest.json'), join(dir, 'meshes.bin'),
])].map((file) => rm(file, { force: true })));
for (const dir of [review, geometry]) await rmdir(dir).catch((error) => { if (error.code !== 'ENOENT') throw error; });
await rmdir(folder);
await removeFixture(folder);
}
});
5 changes: 5 additions & 0 deletions tests/IOViewer.Tests/ClusterSourceTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,11 @@ public void KeepsWorldCoordinatesWhenAReusableTemplateWouldLoseDetail()
try
{
Assert.Equal(3, ClusterSourceWriter.Save(new ViewerDocument(scene), path, new HtmlViewerOptions()));
using var stream = new MemoryStream();
Assert.Equal(3, ClusterSourceWriter.Export(new ViewerDocument(scene), stream));
Assert.True(stream.CanWrite);
Assert.Equal(File.ReadAllBytes(path), stream.ToArray());
Assert.Throws<ArgumentException>(() => ClusterSourceWriter.Export(new ViewerDocument(scene), stream));
using var reader = new BinaryReader(File.OpenRead(path));
Assert.Equal("IMS4"u8.ToArray(), reader.ReadBytes(4));
Assert.Equal(0, reader.ReadDouble());
Expand Down