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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ API between minor releases.
- Import BCF 2.1 topics and open their cameras, clipping and matched components in the offline viewer.
- Preview distance measurement points and snap to visible vertices, edge midpoints and edges near the pointer.
- Use each instance's projected size for orbit detail when the measured frame budget has room.
- Fill cut faces of closed meshes on demand and rotate the section box around Z with a ring or slider.

### Fixed

Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ Built clean-room under the [IOExtend](https://github.com/IOExtend) organization.
- toolbar with labelled groups: navigation, sections, measure, display and view;
- context menu: properties, hide, isolate, show all, zoom to object, section box around the object, copy Id;
- view cube that follows the camera exactly, with face clicks, 90° arrows and a home button;
- section planes (up to six, moved and rotated with an in-scene gizmo) or a section box (keep inside or cut inside, face handles, move by the centre, box around the selection);
- section planes (up to six) or a section box with face handles, a centre handle and rotation around Z, with optional fill on cut faces of closed meshes;
- point-to-point distance measurement previews the point under the cursor and snaps to visible vertices, edge midpoints and edges within eight screen pixels;
- display modes (materials, textures, white, wireframe), viewport background color, grid lines and a global opacity slider;
- saved viewpoints with a viewpoint tour, clash results, a 4D schedule player and linked-file visibility, each shown only when the document has that data.
Expand Down
7 changes: 7 additions & 0 deletions docs/getting-started.md
Original file line number Diff line number Diff line change
Expand Up @@ -130,3 +130,10 @@ The model's up axis is +Z. The interface is in Russian when the browser language
- H hides the selection, I isolates it, Shift+H shows everything, F zooms to the selection (or fits the model), Esc
stops the viewpoint tour, closes the open menu or popup, clears the measurement, or clears the selection. Each
Esc press handles one action.

In the **Sections** panel, enable **Fill cut faces** to fill the cross-sections of consistently wound, closed meshes.
The fill is visual. Picking and measurement continue to use model triangles. Large models take extra work while
fill is enabled.

Turn a section box around Z with the blue ring or the **Rotation around Z** slider. Face handles resize along the
box's rotated axes. Fitting a new box or restoring a saved section starts from its axis-aligned bounds.
2 changes: 1 addition & 1 deletion docs/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ The generated HTML is a single file with no external dependencies that works off
- **Large models**: geometry merged into spatial chunks per material with few draw calls; hiding, selection and colouring are per-object data, not geometry rebuilds.
- **Navigation**: orbit around the point under the cursor, pan with the middle or right button, zoom to the cursor, perspective or orthographic camera, and a view cube that follows the camera.
- **Selection**: click, Ctrl+click, window and crossing box selection, context menu, hotkeys (H, I, Shift+H, F, Esc), model tree by category with search and a properties panel.
- **Sections**: up to six section planes moved and rotated with an in-scene gizmo, or a section box that keeps or cuts its inside, with face handles and a box around the selection.
- **Sections**: up to six section planes or a section box that rotates around Z and keeps or cuts its inside. Fill cut faces of closed meshes on demand.
- **Tools**: point-to-point distance, display modes (materials, textures, white, wireframe), grid lines and global opacity.
- **Coordination data**: saved viewpoints and a viewpoint tour, clash results, a 4D schedule player and linked-file visibility.
- **Russian and English interface**, chosen from the browser language.
Expand Down
393 changes: 205 additions & 188 deletions src/IOViewer/Viewer/dist/viewer.js

Large diffs are not rendered by default.

23 changes: 17 additions & 6 deletions src/IOViewer/Viewer/src/engine/modelScene.js
Original file line number Diff line number Diff line change
Expand Up @@ -287,6 +287,10 @@ export class ModelScene {
return this._slotOf.length;
}

get slotCount() {
return this._slotInstance.length;
}

// Where instance i is drawn (its chunk mesh and slot; null and -1 without vertices) and its element (-1 = none).
instance(i) {
const slot = this._slotOf[i];
Expand All @@ -310,19 +314,22 @@ export class ModelScene {
return this._slotInstance[slot];
}

// Runs fn with `material` on every chunk's triangles (and triangles shown in wireframe mode), e.g. for picking.
withMaterial(material, fn, pickCamera = null) {
this._picking = true;
// Picking uses every shown triangle. Section stencils use the same ranges as the visible frame.
withMaterial(material, fn, { pickCamera = null, section = false } = {}) {
this._picking = !section;
if (pickCamera && this._pickBounds && this._units.length > this._chunkCount) {
this._pickFrustum = frustumPlanes(pickCamera, this._planes);
const { x, y, z } = pickCamera.position;
this._pickViewPadding = PICK_ROUNDING * (Math.abs(x) + Math.abs(y) + Math.abs(z));
}
for (const unit of this._units) {
unit.mesh.material = material;
this._showUnit(unit);
if (section) {
unit.mesh.visible = (unit.mesh.visible || !!unit.lines?.visible) && unit.bucket.material.opacity > 0;
if (unit.lines) unit.lines.visible = false;
} else this._showUnit(unit);
}
for (const unit of this._compactCells) this._cellAttributes(unit, false);
if (!section) for (const unit of this._compactCells) this._cellAttributes(unit, false);
try {
return fn();
} finally {
Expand All @@ -336,7 +343,7 @@ export class ModelScene {
unit.mesh.visible = false;
if (unit.lines) unit.lines.visible = false;
}
for (const unit of this._compactCells) this._cellAttributes(unit, true);
if (!section) for (const unit of this._compactCells) this._cellAttributes(unit, true);
}
}

Expand Down Expand Up @@ -381,6 +388,10 @@ export class ModelScene {
this._changed('appearance');
}

get opacity() {
return this._opacity;
}

// Cut below minPixels using the measured instance bounds for cells and the size-ordered span for merged chunks.
// A wholly cut unit is hidden before Three submits it. Reset to 0 to restore every shown instance.
setDetail(minPixels, viewHeight = 1) {
Expand Down
2 changes: 1 addition & 1 deletion src/IOViewer/Viewer/src/engine/picking.js
Original file line number Diff line number Diff line change
Expand Up @@ -245,7 +245,7 @@ export class Picker {
try {
renderer.setRenderTarget(target);
renderer.setClearColor(0x000000, 0);
this.scene.withMaterial(material, () => renderer.render(this.scene.root, camera), camera);
this.scene.withMaterial(material, () => renderer.render(this.scene.root, camera), { pickCamera: camera });
renderer.readRenderTargetPixels(target, 0, 0, target.width, target.height, pixels);
} finally {
renderer.setRenderTarget(previous.target);
Expand Down
6 changes: 6 additions & 0 deletions src/IOViewer/Viewer/src/i18n.js
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,9 @@ const dictionaries = {
'sections.cutInside': 'Вырезать внутри',
'sections.fitSelection': 'По выделенному',
'sections.showGizmo': 'Показывать манипулятор',
'sections.boxYaw': 'Поворот вокруг Z',
'sections.fill': 'Заливка срезов',
'sections.fillUnavailable': 'Заливка недоступна без буфера трафарета WebGL',
'sections.maxPlanes': 'Не больше 6 плоскостей',
'unit.m': 'м',
'display.materials': 'Материалы',
Expand Down Expand Up @@ -218,6 +221,9 @@ const dictionaries = {
'sections.cutInside': 'Cut inside',
'sections.fitSelection': 'Fit to selection',
'sections.showGizmo': 'Show gizmo',
'sections.boxYaw': 'Rotation around Z',
'sections.fill': 'Fill cut faces',
'sections.fillUnavailable': 'Section fill requires a WebGL stencil buffer',
'sections.maxPlanes': 'At most 6 planes',
'unit.m': 'm',
'display.materials': 'Materials',
Expand Down
26 changes: 17 additions & 9 deletions src/IOViewer/Viewer/src/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import { selectInRect, screenBoxes } from './select/boxSelect.js';
import { mountUI } from './ui/app.js';
import { Sections } from './tools/sections.js';
import { SectionGizmo } from './tools/sectionGizmo.js';
import { boxFullyClipped } from './tools/sectionMath.js';
import { SectionCaps } from './tools/sectionCaps.js';
import { mountSections } from './ui/sectionsPanel.js';
import { Measure } from './tools/measure.js';
import { MeasureSnap } from './tools/measureSnap.js';
Expand All @@ -38,7 +38,7 @@ function showMessage(text) {
try {
const meta = readModelMeta(document, startup);
if (meta.title) document.title = meta.title;
const context = canvas.getContext('webgl2', { antialias: true });
const context = canvas.getContext('webgl2', { antialias: true, stencil: true });
if (context) start(loadModelData(document, startup, meta), context);
else showMessage(t('noWebGL'));
} catch (error) {
Expand All @@ -48,14 +48,16 @@ try {

function start(data, context) {
const renderer = new THREE.WebGLRenderer({
canvas, context, antialias: true, logarithmicDepthBuffer: needsLogarithmicDepth(data.meta),
canvas, context, antialias: true, stencil: true, logarithmicDepthBuffer: needsLogarithmicDepth(data.meta),
});
renderer.setPixelRatio(window.devicePixelRatio);
renderer.autoClearStencil = false; // the cap pass clears its stencil per face
renderer.localClippingEnabled = true;

const world = new THREE.Scene();
const initialBackground = '#1f2228';
world.background = new THREE.Color(initialBackground);
const background = new THREE.Color(initialBackground);
renderer.setClearColor(background, 1);
const sky = new THREE.HemisphereLight('#ffffff', '#8a8f99', 1.6);
sky.position.set(0, 0, 1);
world.add(sky);
Expand All @@ -82,6 +84,8 @@ function start(data, context) {
world.add(scene.root);
// Sections never change which elements are shown, so they leave the bounds (orbit pivot, near/far) as they are.
const sections = new Sections(scene, scene.visibleBox(), data.meta.sections);
const canFillSections = context.getContextAttributes()?.stencil === true;
let sectionCaps;
const sectionGizmo = new SectionGizmo(sections, canvas);
world.add(sectionGizmo.group); // outside scene.root: the picking id pass renders only the model
const uiRoot = document.getElementById('ioviewer-ui');
Expand Down Expand Up @@ -129,7 +133,10 @@ function start(data, context) {
grids.update(controls.camera, rect);
motionDetail.begin(controls.camera, rect.height, performance.now());
firstRender?.('renderStart');
renderer.render(world, controls.camera);
if (sections.fill && canFillSections) {
sectionCaps ??= new SectionCaps(scene, sections, data);
sectionCaps.render(renderer, world, controls.camera);
} else renderer.render(world, controls.camera);
if (firstRender) {
firstRender('renderEnd');
firstRender = undefined;
Expand Down Expand Up @@ -196,7 +203,7 @@ function start(data, context) {
const selection = new Selection();
selection.addEventListener('change', () => scene.setHighlighted([...selection.values()]));
const ui = mountUI({ root: uiRoot, data, scene, controls, picker, selection, measure });
mountSections({ root: uiRoot, ...ui, sections, selection });
mountSections({ root: uiRoot, ...ui, sections, selection, canFill: canFillSections });
const { meta } = data;
const restoreLinkedModels = mountLinks({ ...ui, files: meta.linkedFiles ?? [], elements: meta.elements, scene });
mountViews({ ...ui, controls, scene, sections, selection, restoreLinkedModels,
Expand All @@ -205,7 +212,8 @@ function start(data, context) {
world.add(clashes.group); // overlay, like the measure
const timeliner = mountTimeliner({ root: uiRoot, ...ui, timeliner: meta.timeliner, elements: meta.elements, scene });
const setBackground = (color) => {
const { r, g, b } = world.background.set(color);
renderer.setClearColor(background.set(color), 1);
const { r, g, b } = background;
// The equality point of the white and black contrast ratios against a linear sRGB background.
const luminance = 0.2126 * r + 0.7152 * g + 0.0722 * b;
const text = luminance > Math.sqrt(0.0525) - 0.05 ? '#000' : '#fff';
Expand Down Expand Up @@ -260,8 +268,8 @@ function start(data, context) {
}
const box = new THREE.Box3();
const found = selectInRect(rect, mode, screenBoxes(scene, controls.camera, canvas.getBoundingClientRect()));
const { planes, intersection } = sections.clipping(); // once, not per element
const shown = found.filter((i) => !boxFullyClipped(scene.elementBox(i, box), planes, intersection));
const clip = sections.clipping(); // once, not per element
const shown = found.filter((i) => !sections.isCut(scene.elementBox(i, box), clip));
selection.set(ctrl ? [...selection.values(), ...shown] : shown);
});

Expand Down
156 changes: 156 additions & 0 deletions src/IOViewer/Viewer/src/tools/sectionCaps.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,156 @@
import * as THREE from 'three';
import { positionsView } from '../engine/quantize.js';
import { HIDE_BRANCH, SLOT_DECODE, SLOT_PARS } from '../engine/slotShader.js';
import { extentAlong, planeRect } from './sectionMath.js';

const Z = new THREE.Vector3(0, 0, 1);
const CAP_COLOR = '#e9ad68';

// Tessellation duplicates vertices at normal or UV seams. Weld exact exported positions and require every
// undirected edge to have one triangle in each direction. Open sheets cannot leave stray stencil counts.
export function isClosedGeometry(positions, indices) {
const vertex = new Uint32Array(positions.length / 3);
const points = new Map();
for (let i = 0; i < vertex.length; i++) {
const x = positions[i * 3], y = positions[i * 3 + 1], z = positions[i * 3 + 2];
if (!Number.isFinite(x) || !Number.isFinite(y) || !Number.isFinite(z)) return false;
const key = `${x},${y},${z}`;
if (!points.has(key)) points.set(key, points.size);
vertex[i] = points.get(key);
}
if (points.size < 4 || indices.length % 3) return false;
const edges = new Map();
let open = 0;
for (let i = 0; i < indices.length; i += 3) {
const corners = [vertex[indices[i]], vertex[indices[i + 1]], vertex[indices[i + 2]]];
const [a, b, c] = corners;
if (a === undefined || b === undefined || c === undefined) return false;
if (a === b || b === c || c === a) continue;
for (let j = 0; j < 3; j++) {
const a = corners[j], b = corners[(j + 1) % 3];
const direction = a < b ? 1 : -1;
const key = a < b ? `${a},${b}` : `${b},${a}`;
const seen = edges.get(key);
if (seen !== undefined && seen !== -direction) return false;
edges.set(key, seen === undefined ? direction : 0);
open += seen === undefined ? 1 : -1;
}
}
return edges.size > 0 && open === 0;
}

// The standalone page keeps the binary available for sparse reads after upload. Classification and GPU storage
// are deferred to the first filled section, once per shared shape and one byte per slot.
function closedSlots(model, data) {
const { instances, geometries } = data.meta;
const geometryOf = data.readView(instances.geometry);
const { width, height } = model.slotUniforms.slotState.value.image;
const mask = new Uint8Array(width * height);
const classified = new Map();
for (let slot = 0; slot < model.slotCount; slot++) {
const g = geometryOf[model.slotInstance(slot)];
if (!classified.has(g)) {
const geometry = geometries[g];
const closed = isClosedGeometry(positionsView({ view: data.readView }, geometry), data.readView(geometry.indices));
classified.set(g, closed ? 255 : 0);
}
mask[slot] = classified.get(g);
}
const texture = new THREE.DataTexture(mask, width, height, THREE.RedFormat);
texture.needsUpdate = true;
return texture;
}

function stencilMaterial(uniforms, plane, side, stencilZPass) {
const material = new THREE.ShaderMaterial({
uniforms,
vertexShader: /* glsl */ `
#include <common>
${SLOT_PARS}
#include <clipping_planes_pars_vertex>
uniform highp sampler2D closedSlots;
void main() {
${SLOT_DECODE}
vec3 transformed = slotPosition;
#include <project_vertex>
#include <clipping_planes_vertex>
${HIDE_BRANCH}
if ( texelFetch( closedSlots, st, 0 ).r < 0.5 ) gl_Position = vec4( 0.0, 0.0, 2.0, 1.0 );
}`,
fragmentShader: /* glsl */ `
#include <clipping_planes_pars_fragment>
void main() {
#include <clipping_planes_fragment>
gl_FragColor = vec4( 0.0 );
}`,
side, stencilZPass, stencilWrite: true, clipping: true, clippingPlanes: [plane],
colorWrite: false, depthTest: false, depthWrite: false,
});
material.index0AttributeName = 'q';
return material;
}

export class SectionCaps {
constructor(model, sections, data) {
this.model = model;
this.sections = sections;
this.data = data;
this._farSide = new THREE.Plane();
this._surface = new THREE.Mesh(new THREE.PlaneGeometry(1, 1), new THREE.MeshBasicMaterial({
color: CAP_COLOR, side: THREE.DoubleSide, forceSinglePass: true,
stencilWrite: true, stencilFunc: THREE.NotEqualStencilFunc, stencilWriteMask: 0,
}));
}

render(renderer, world, camera) {
const { sections, model } = this;
const { planes, intersection } = sections.clipping();
const faces = intersection ? planes.map((plane) => plane.clone().negate()) : planes;
const crosses = (plane) => Math.abs(plane.distanceToPoint(sections.center)) < extentAlong(sections.modelBox, plane.normal);
if (model.opacity === 0 || !faces.some(crosses)) return renderer.render(world, camera);

if (!this._stencils) {
const uniforms = { ...model.slotUniforms, closedSlots: { value: closedSlots(model, this.data) } };
this._stencils = [
stencilMaterial(uniforms, this._farSide, THREE.BackSide, THREE.IncrementWrapStencilOp),
stencilMaterial(uniforms, this._farSide, THREE.FrontSide, THREE.DecrementWrapStencilOp),
];
}
const material = this._surface.material;
material.opacity = model.opacity;
if (material.transparent !== (model.opacity < 1)) {
material.transparent = model.opacity < 1;
material.depthWrite = !material.transparent;
material.needsUpdate = true;
}

const autoClear = renderer.autoClear;
renderer.autoClear = false;
try {
renderer.clear();
const viewDirection = camera.isOrthographicCamera ? camera.getWorldDirection(new THREE.Vector3()) : null;
faces.forEach((plane, index) => {
if (!crosses(plane)) return;
const facing = viewDirection ? -plane.normal.dot(viewDirection) : plane.distanceToPoint(camera.position);
if (facing === 0) return;
this._farSide.copy(plane);
if (facing > 0) this._farSide.negate();
renderer.clearStencil();
// Count signed crossings behind the cap. Outside the solid, front and back cancel.
for (const stencil of this._stencils)
model.withMaterial(stencil, () => renderer.render(model.root, camera), { section: true });

this._surface.quaternion.setFromUnitVectors(Z, plane.normal);
const rect = planeRect(sections.modelBox, this._surface.quaternion, plane.coplanarPoint(new THREE.Vector3()));
this._surface.position.copy(rect.center);
this._surface.scale.set(rect.width, rect.height, 1);
// Both box modes close the same six face rectangles; the other five inward planes bound each face.
material.clippingPlanes = faces.filter((_, i) => i !== index);
renderer.render(this._surface, camera);
});
renderer.render(world, camera);
} finally {
renderer.autoClear = autoClear;
}
}
}
Loading
Loading