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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ API between minor releases.
duplicate element IDs, missing textures and conflicting legacy mesh arrays before publishing the output.
- Virtualize long clash lists. Show the existing localized messages for malformed model metadata and scenes without
drawable geometry, and set the model title when WebGL 2 is unavailable.
- Keep close geometry visible and pickable in kilometre-scale models. Orthographic wheel zoom changes the
magnification around the cursor while keeping the camera at the same depth.

## [0.3.1] - 2026-11-13

Expand Down
358 changes: 186 additions & 172 deletions src/IOViewer/Viewer/dist/viewer.js

Large diffs are not rendered by default.

33 changes: 26 additions & 7 deletions src/IOViewer/Viewer/src/engine/picking.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,22 @@ import { SLOT_DECODE, SLOT_PARS } from './slotShader.js';
const VERTEX = /* glsl */ `
#include <common>
${SLOT_PARS}
#include <logdepthbuf_pars_vertex>
#include <clipping_planes_pars_vertex>
varying vec3 vPos;
varying vec2 vSlot;
#ifdef IO_PICK_DEPTH
varying float vViewDepth;
#endif
void main() {
${SLOT_DECODE}
vec3 transformed = slotPosition;
#include <project_vertex>
#include <logdepthbuf_vertex>
#include <clipping_planes_vertex>
#ifdef IO_PICK_DEPTH
vViewDepth = -mvPosition.z;
#endif
vec4 wp = vec4( transformed, 1.0 );
#ifdef USE_INSTANCING
wp = instanceMatrix * wp;
Expand All @@ -24,18 +32,24 @@ void main() {
if ( state.a < 0.5 ) gl_Position = vec4( 0.0, 0.0, 2.0, 1.0 );
}`;

// IO_PICK_RGBA8: slot + 1 as 4 bytes, little-endian; IO_PICK_DEPTH: the fragment depth packed into 4 bytes.
// IO_PICK_RGBA8: slot + 1 as 4 bytes; IO_PICK_DEPTH: the bits of the view-space depth, both little-endian.
const FRAGMENT = /* glsl */ `
#include <common>
#include <packing>
#include <logdepthbuf_pars_fragment>
#include <clipping_planes_pars_fragment>
varying vec3 vPos;
varying vec2 vSlot;
#ifdef IO_PICK_DEPTH
varying float vViewDepth;
#endif
void main() {
#include <clipping_planes_fragment>
#include <logdepthbuf_fragment>
float id = floor( vSlot.x + 0.5 ) * 4096.0 + floor( vSlot.y + 0.5 ) + 1.0;
#if defined( IO_PICK_DEPTH )
gl_FragColor = packDepthToRGBA( gl_FragCoord.z );
uint bits = floatBitsToUint( vViewDepth );
uvec4 bytes = ( uvec4( bits ) >> uvec4( 0u, 8u, 16u, 24u ) ) & 255u;
gl_FragColor = vec4( bytes ) / 255.0;
#elif defined( IO_PICK_RGBA8 )
gl_FragColor = vec4( mod( id, 256.0 ), mod( floor( id / 256.0 ), 256.0 ), mod( floor( id / 65536.0 ), 256.0 ), floor( id / 16777216.0 ) ) / 255.0;
#else
Expand Down Expand Up @@ -117,10 +131,15 @@ export class Picker {
if (slot < 0) return null;
const element = this.scene.slotElement(slot);
if (this._float) return { element, point: new THREE.Vector3(pixel[0], pixel[1], pixel[2]) };
const [r, g, b, a] = this._render(this._depthMaterial, x, y, rect);
const depth = r / 256 + g / 65536 + b / 16777216 + a / 255 / 16777216; // three's unpackRGBAToDepth on the bytes
const ndc = new THREE.Vector3(((x + 0.5) / rect.width) * 2 - 1, 1 - ((y + 0.5) / rect.height) * 2, depth * 2 - 1);
return { element, point: ndc.unproject(this.camera) };
const bytes = this._render(this._depthMaterial, x, y, rect);
const depth = new DataView(bytes.buffer).getFloat32(0, true);
// Recover the world point from view-space depth, independent of the depth buffer mapping.
const camera = this.camera;
const point = new THREE.Vector3(((x + 0.5) / rect.width) * 2 - 1, 1 - ((y + 0.5) / rect.height) * 2, -1)
.applyMatrix4(camera.projectionMatrixInverse);
if (camera.isPerspectiveCamera) point.multiplyScalar(-depth / point.z);
else point.z = -depth;
return { element, point: point.applyMatrix4(camera.matrixWorld) };
}

// Draws the model with `material` into the 1x1 target at pixel (x, y) and reads it back.
Expand Down
6 changes: 4 additions & 2 deletions src/IOViewer/Viewer/src/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import * as THREE from 'three';
import { loadModelData, ModelDataError, readModelMeta } from './data.js';
import { ModelScene, ModelTooLargeError } from './engine/modelScene.js';
import { lang, t } from './i18n.js';
import { NavigationControls } from './nav/controls.js';
import { NavigationControls, needsLogarithmicDepth } from './nav/controls.js';
import { ViewCube } from './nav/viewCube.js';
import { Picker } from './engine/picking.js';
import { MotionDetail } from './engine/motionDetail.js';
Expand Down Expand Up @@ -46,7 +46,9 @@ try {
}

function start(data, context) {
const renderer = new THREE.WebGLRenderer({ canvas, context, antialias: true });
const renderer = new THREE.WebGLRenderer({
canvas, context, antialias: true, logarithmicDepthBuffer: needsLogarithmicDepth(data.meta),
});
renderer.setPixelRatio(window.devicePixelRatio);
renderer.localClippingEnabled = true;

Expand Down
64 changes: 56 additions & 8 deletions src/IOViewer/Viewer/src/nav/controls.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,27 @@ import { isClick, orbit, zoomTowards, wheelZoomFactor, boxSelectMode, interpolat

const ORBIT_SPEED = 0.005; // radians per pixel
const DEFAULT_DIRECTION = new THREE.Vector3(1, -1, 0.8).normalize();
const NEAR_MIN = 0.01; // metres
const FAR_MARGIN = 1.05;
const LINEAR_DEPTH_RATIO = 5000;

const detail = (type, d) => new CustomEvent(type, { detail: d });

export function needsLogarithmicDepth({ bbox, grids }) {
const finitePoint = (p) => Array.isArray(p) && p.length === 3 && p.every(Number.isFinite);
if (!finitePoint(bbox?.min) || !finitePoint(bbox?.max)) return true;
const bounds = new THREE.Box3(new THREE.Vector3(...bbox.min), new THREE.Vector3(...bbox.max));
if (bounds.isEmpty()) return true;
const point = new THREE.Vector3();
for (const grid of grids ?? []) {
if (!finitePoint(grid.start) || !finitePoint(grid.end)) return true;
bounds.expandByPoint(point.fromArray(grid.start));
bounds.expandByPoint(point.fromArray(grid.end));
}
// Inside the bounding sphere, its diameter bounds far. Keep early depth testing when this fits the linear range.
return bounds.getSize(point).length() * FAR_MARGIN > NEAR_MIN * LINEAR_DEPTH_RATIO;
}

// Navisworks-style camera: left drag orbits (or pans), middle/right drag pans, wheel zooms to the cursor.
// Pointer coordinates in events and in `pick(x, y)` are client pixels; `pick` returns a Vector3 or null.
// `visibleBox()` gives the box of what is shown; it drives the orbit pivot fallback and near/far.
Expand Down Expand Up @@ -48,7 +66,13 @@ export class NavigationControls extends EventTarget {
const next = kind === 'perspective' ? this._perspective : this._orthographic;
const previous = this.camera;
if (next === previous) return;
this._stopAnimation();
next.position.copy(previous.position);
if (previous.isOrthographicCamera) {
// Match the apparent scale at the target when going back to a perspective camera.
next.position.sub(this.target).divideScalar(previous.zoom).add(this.target);
}
next.zoom = 1;
next.quaternion.copy(previous.quaternion);
next.up.copy(previous.up);
previous.parent?.add(next);
Expand All @@ -72,9 +96,11 @@ export class NavigationControls extends EventTarget {
}
const sphere = this._rangeSphere();
if (sphere) {
const toCentre = cam.position.distanceTo(sphere.center);
cam.far = (toCentre + sphere.radius) * 1.05;
cam.near = Math.max((toCentre - sphere.radius) * 0.95, cam.far / 5000);
const toCentre = sphere.center.clone().sub(cam.position);
const forward = new THREE.Vector3(0, 0, -1).applyQuaternion(cam.quaternion);
cam.far = Math.max(1e-6, (toCentre.length() + sphere.radius) * FAR_MARGIN);
const nearest = toCentre.dot(forward) - sphere.radius;
cam.near = Math.max(nearest * 0.95, Math.min(NEAR_MIN, cam.far / 2));
}
cam.updateProjectionMatrix();
this.dispatchEvent(new Event('change'));
Expand Down Expand Up @@ -120,22 +146,28 @@ export class NavigationControls extends EventTarget {
if (direction.lengthSq() < 1e-12) direction.copy(DEFAULT_DIRECTION);
const position = direction.normalize().multiplyScalar(distance).add(sphere.center);
if (animate) this.animateTo({ position, target: sphere.center });
else this._set(position, sphere.center);
else {
this.camera.zoom = 1;
this._set(position, sphere.center);
}
}

zoomToBox(box) {
this.fitBox(box, true);
}

// Swings the camera round the target (see interpolateView); `up` stays +Z, so it is accepted and ignored.
animateTo({ position, target }, ms = 400) {
animateTo({ position, target, zoom = 1 }, ms = 400) {
this._stopAnimation();
const from = { position: this.camera.position.clone(), target: this.target.clone() };
const to = { position: position ?? from.position, target: target ?? from.target };
const fromZoom = this.camera.zoom;
const start = performance.now();
const step = (now) => {
const k = Math.min((now - start) / ms, 1);
const r = interpolateView(from, to, k * k * (3 - 2 * k));
const eased = k * k * (3 - 2 * k);
const r = interpolateView(from, to, eased);
if (this.camera.isOrthographicCamera) this.camera.zoom = THREE.MathUtils.lerp(fromZoom, zoom, eased);
this._set(r.position, r.target);
this._animation = k < 1 ? requestAnimationFrame(step) : 0;
};
Expand Down Expand Up @@ -198,7 +230,7 @@ export class NavigationControls extends EventTarget {
const height = Math.max(this.dom.clientHeight, 1);
const worldPerPixel = cam.isPerspectiveCamera
? (2 * cam.position.distanceTo(this.target) * Math.tan(THREE.MathUtils.degToRad(cam.fov / 2))) / height
: (cam.top - cam.bottom) / height;
: (cam.top - cam.bottom) / cam.zoom / height;
const right = new THREE.Vector3(1, 0, 0).applyQuaternion(cam.quaternion);
const up = new THREE.Vector3(0, 1, 0).applyQuaternion(cam.quaternion);
// The model follows the hand, so the camera moves the other way.
Expand Down Expand Up @@ -257,13 +289,29 @@ export class NavigationControls extends EventTarget {
e.preventDefault();
if (e.deltaY === 0) return; // a horizontal swipe or Shift+wheel does not zoom
this._stopAnimation();
const factor = wheelZoomFactor(e.deltaY, e.deltaMode, this.dom.clientHeight);
const cam = this.camera;
if (cam.isOrthographicCamera) {
const { left, top, width, height } = this.dom.getBoundingClientRect();
if (!width || !height) return;
const zoom = THREE.MathUtils.clamp(cam.zoom / factor, 1e-6, 1e6);
// Translate in the view plane by the change in the cursor offset. Depth and the pivot distance stay fixed.
const shift = new THREE.Vector3(
(2 * (e.clientX - left) / width - 1) * cam.right,
(1 - 2 * (e.clientY - top) / height) * cam.top,
0,
).multiplyScalar(1 / cam.zoom - 1 / zoom).applyQuaternion(cam.quaternion);
cam.zoom = zoom;
this._set(cam.position.clone().add(shift), this.target.clone().add(shift));
return;
}
// One pick per animation frame: notches arriving within a frame zoom towards the same point.
if (!this._wheelPick) {
this._wheelPick = { point: this.pick(e.clientX, e.clientY) };
requestAnimationFrame(() => (this._wheelPick = null));
}
const point = this._wheelPick.point ?? this.target;
const r = zoomTowards(this.camera.position, this.target, point, wheelZoomFactor(e.deltaY, e.deltaMode, this.dom.clientHeight));
const r = zoomTowards(cam.position, this.target, point, factor);
this._set(r.position, r.target);
}
}
6 changes: 5 additions & 1 deletion src/IOViewer/Viewer/src/nav/viewCube.js
Original file line number Diff line number Diff line change
Expand Up @@ -259,6 +259,10 @@ export class ViewCube {
_look(direction) {
const { controls } = this;
const distance = controls.camera.position.distanceTo(controls.target);
controls.animateTo({ position: direction.clone().multiplyScalar(distance).add(controls.target), target: controls.target.clone() });
controls.animateTo({
position: direction.clone().multiplyScalar(distance).add(controls.target),
target: controls.target.clone(),
zoom: controls.camera.zoom,
});
}
}
9 changes: 9 additions & 0 deletions src/IOViewer/Viewer/test/e2e/global-setup.js
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,15 @@ export default function globalSetup() {
const large = path.join(viewerDir, 'test-results', 'large.json');
writeFileSync(large, JSON.stringify(largeModel(LARGE_ELEMENTS)));
exportHtml(large, 'large');
const depthRange = largeModel(3);
depthRange.Meshes[1].Transform.Translation.Y = -5000;
const distant = depthRange.Meshes[2].Transform;
distant.Translation = { X: 100, Y: 5000, Z: 0 };
distant.XAxis = { X: 100, Y: 0, Z: 0 };
distant.ZAxis = { X: 0, Y: 0, Z: 100 };
const depthRangePath = path.join(viewerDir, 'test-results', 'depth-range.json');
writeFileSync(depthRangePath, JSON.stringify(depthRange));
exportHtml(depthRangePath, 'depth-range');
const shear = path.join(viewerDir, 'test-results', 'shear.json');
writeFileSync(shear, JSON.stringify(shearModel()));
exportHtml(shear, 'shear');
Expand Down
33 changes: 33 additions & 0 deletions src/IOViewer/Viewer/test/e2e/navigation.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,39 @@ test('orthographic projection keeps the pose and the visible size at the target'
expect(errors).toEqual([]);
});

test('orthographic wheel zoom keeps the cursor point and the camera depth', async ({ page }) => {
await open(page);
const x = 730, y = 350;
await page.mouse.move(x, y);
const sample = () => page.evaluate(({ x, y }) => {
const { camera, controls } = window.__ioviewer;
camera.updateMatrixWorld();
const depth = controls.target.clone().project(camera).z;
const cursor = camera.position.clone().set(2 * x / innerWidth - 1, 1 - 2 * y / innerHeight, depth).unproject(camera);
return {
position: camera.position.toArray(),
forward: camera.getWorldDirection(camera.position.clone()).toArray(),
distance: camera.position.distanceTo(controls.target),
cursor: cursor.toArray(),
scale: camera.projectionMatrix.elements[5],
};
}, { x, y });

await page.evaluate(() => window.__ioviewer.controls.setProjection('orthographic'));
const before = await sample();
await page.mouse.wheel(0, -100);
await frame(page);
const after = await sample();
const depthShift = after.position.reduce((sum, v, i) => sum + (v - before.position[i]) * before.forward[i], 0);
expect(depthShift).toBeCloseTo(0, 8);
expect(after.distance).toBeCloseTo(before.distance, 8);
expect(after.scale / before.scale).toBeCloseTo(1 / 0.85, 8);
after.cursor.forEach((value, i) => expect(value).toBeCloseTo(before.cursor[i], 8));

await page.evaluate(() => window.__ioviewer.controls.setProjection('perspective'));
expect((await sample()).distance).toBeCloseTo(before.distance * 0.85, 8);
});

test('animateTo moves the camera to the requested pose', async ({ page }) => {
await open(page);
const final = await page.evaluate(async () => {
Expand Down
38 changes: 38 additions & 0 deletions src/IOViewer/Viewer/test/e2e/smoke.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,44 @@ test('building renders the model and counts elements', async ({ page }) => {
expect(requests).toEqual([]);
});

for (const pickFloat of [true, false]) {
test(`a fitting 25 cm away remains drawable and pickable in a 10 km model (pickFloat: ${pickFloat})`, async ({ page }) => {
await page.addInitScript((value) => { window.IOVIEWER_TEST = { pickFloat: value }; }, pickFloat);
const { errors } = await open(page, 'depth-range');
const expected = await page.evaluate(() => {
const { controls, scene } = window.__ioviewer;
const box = scene.elementBox(0);
const target = box.getCenter(box.min.clone());
controls._set(target.clone().setY(box.min.y - 0.25), target);
return box.min.y;
});
const hit = await page.evaluate(() => {
const { picker, camera } = window.__ioviewer;
const pick = picker.pick(innerWidth / 2, innerHeight / 2);
const logDepth = picker.renderer.capabilities.logarithmicDepthBuffer;
return { near: camera.near, far: camera.far, logDepth, element: pick?.element, y: pick?.point.y };
});
expect(hit.far).toBeGreaterThan(5000);
expect(hit.near).toBeLessThan(0.25);
expect(hit.logDepth).toBe(true);
expect(hit.element).toBe(0);
expect(hit.y).toBeCloseTo(expected, 3);
await renderedCenter(page);

const farHit = await page.evaluate(() => {
const { controls, picker, scene } = window.__ioviewer;
const box = scene.elementBox(2);
const target = box.getCenter(box.min.clone());
controls._set(target.clone().setY(box.min.y - 4876.33), target);
const pick = picker.pick(innerWidth / 2, innerHeight / 2);
return { element: pick?.element, surfaceError: pick ? pick.point.y - box.min.y : Infinity };
});
expect(farHit.element).toBe(2);
expect(farHit.surfaceError).toBeCloseTo(0, 2);
expect(errors).toEqual([]);
});
}

test('empty document shows "no geometry"', async ({ page }) => {
const { errors, requests } = await open(page, 'empty');

Expand Down
9 changes: 9 additions & 0 deletions src/IOViewer/Viewer/test/unit/nav.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,19 @@ import { test } from 'node:test';
import assert from 'node:assert/strict';
import * as THREE from 'three';
import { isClick, orbit, zoomTowards, boxSelectMode } from '../../src/nav/math.js';
import { needsLogarithmicDepth } from '../../src/nav/controls.js';

const v = (x, y, z) => new THREE.Vector3(x, y, z);
const near = (a, b, eps = 1e-9) => assert.ok(Math.abs(a - b) < eps, `${a} != ${b}`);

test('logarithmic depth covers a wide model or grids that extend beyond its bounds', () => {
const bbox = { min: [0, 0, 0], max: [47, 0, 0] };
assert.equal(needsLogarithmicDepth({ bbox, grids: null }), false);
assert.equal(needsLogarithmicDepth({ bbox: { ...bbox, max: [48, 0, 0] } }), true);
assert.equal(needsLogarithmicDepth({ bbox, grids: [{ start: [-2, 0, 0], end: [40, 0, 0] }] }), true);
assert.equal(needsLogarithmicDepth({}), true);
});

test('isClick uses a 4 px threshold', () => {
assert.equal(isClick({ x: 0, y: 0 }, { x: 3, y: 0 }), true);
assert.equal(isClick({ x: 0, y: 0 }, { x: 5, y: 0 }), false);
Expand Down
Loading