diff --git a/INTERFACE.md b/INTERFACE.md index 8b1c3ffa..9aea618a 100644 --- a/INTERFACE.md +++ b/INTERFACE.md @@ -1938,6 +1938,18 @@ the UI is a view `heph render` can reproduce; free orbit snapshots the nearest readout shows camera state and scale — a screen-space fact, never rendered through ``. +**Appearance cluster — operator chrome, bound to the pin.** A small control +strip on the viewport drives the display authorship §3.11 already specified: +wireframe, fit, ortho, grid, axis triad, material override. Defaults match the +authored picture (shaded, orthographic, grid and triad on, material at +`--viewport-part` with the ≥4.5:1 part-vs-ground floor). Fit re-applies +`cameras.py`'s framing for the current named view. Wireframe hides the fill and +keeps the silhouette. Ortho off is a perspective viewing aid; the named views +and `heph render` remain orthographic. The cluster is **not** workspace state: +§4.5 stays closed. It authors no material the engine did not already project. +G4.5's thresholds are unchanged — the strip is fixed-size chrome and does not +move on a visibility toggle. + During a rebuild the viewport keeps the **last completed** artifact and the header shows `stale` with the ref it is showing. `architecture.md` §3 already guarantees a long build never blocks inspection; the UI's job is to express diff --git a/web/e2e/README.md b/web/e2e/README.md index 25d1e706..1dfa3ca1 100644 --- a/web/e2e/README.md +++ b/web/e2e/README.md @@ -147,7 +147,8 @@ frames, so the two cameras agree by construction. `[data-field]`, `[data-check]`+`[data-badge]`, `[data-dfm-finding]`, `[data-dfm-descriptor]`, `[data-visibility-toggle]`, `[data-testid="viewport"]` with `data-glb-state` / `data-artifact-ref` / `data-section-state`, -`[data-viewport-canvas]`, `[data-explode-t]`, `[data-section-control]` with +`[data-viewport-canvas]`, `[data-appearance]` / `[data-appearance-control]`, +`[data-explode-t]`, `[data-section-control]` with `data-section-plane`, `[data-section-plate]`+`data-plate-ref`, `[data-testid="stream-panel"|"transcript"]`, `[data-history-state]`, `[data-history-pages]`, `[data-stream-state]`, `[data-session-tab]` with diff --git a/web/e2e/design-system.spec.ts b/web/e2e/design-system.spec.ts index 9391032f..196ea61a 100644 --- a/web/e2e/design-system.spec.ts +++ b/web/e2e/design-system.spec.ts @@ -266,6 +266,22 @@ test("the grid readout reports the grid that exists, and the triad names its axe // colour never replaces the letter, so all three axes are named in words a // screen reader and a monochrome print both keep. await expect(page.locator("[data-axis-triad]")).toBeVisible(); + // §5.5's operator cluster: present, defaults matching the authored picture. + // Existing selectors above are unchanged; this only adds the new strip. + await expect(page.locator("[data-appearance]")).toBeVisible(); + for (const [control, pressed] of [ + ["wireframe", "false"], + ["ortho", "true"], + ["grid", "true"], + ["triad", "true"], + ["materialOverride", "true"], + ] as const) { + await expect(page.locator(`[data-appearance-control="${control}"]`)).toHaveAttribute( + "aria-pressed", + pressed, + ); + } + await expect(page.locator('[data-appearance-control="fit"]')).toBeEnabled(); for (const axis of ["x", "y", "z"]) { await expect(page.locator(`[data-axis-label="${axis}"]`)).toHaveText(axis.toUpperCase()); await expect(page.locator(`[data-axis="${axis}"]`)).toHaveAttribute( diff --git a/web/src/components/stage/viewport/AppearanceControls.module.css b/web/src/components/stage/viewport/AppearanceControls.module.css new file mode 100644 index 00000000..289ea57d --- /dev/null +++ b/web/src/components/stage/viewport/AppearanceControls.module.css @@ -0,0 +1,27 @@ +/* + * Copyright 2026 The Hephaestus Authors + * SPDX-License-Identifier: Apache-2.0 + * + * Operator appearance cluster. Layout only — buttons are the system primitive. + * + * Top-left, opposite the view cube, so the two orientation surfaces do not + * share a corner. Fixed size: wrapping is allowed but the cluster does not + * grow when a solid is hidden, which is the G4.5 constraint GridReadout + * already documents. + */ + +.cluster { + position: absolute; + top: var(--space-3); + left: var(--space-3); + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 2px; /* one-off: a control cluster is tighter than --gap-stack */ + max-width: 22rem; + padding: var(--space-1); + border: 1px solid var(--border-strong); + border-radius: var(--radius-card); + background: var(--surface-overlay); + box-shadow: var(--elev-popover); +} diff --git a/web/src/components/stage/viewport/AppearanceControls.tsx b/web/src/components/stage/viewport/AppearanceControls.tsx new file mode 100644 index 00000000..dac80437 --- /dev/null +++ b/web/src/components/stage/viewport/AppearanceControls.tsx @@ -0,0 +1,102 @@ +// Copyright 2026 The Hephaestus Authors +// SPDX-License-Identifier: Apache-2.0 +// +// Operator appearance cluster (INTERFACE.md §3.11, §5.5). +// +// §3.11 already authors the picture. This strip is the operator chrome that +// drives it: wireframe, fit, ortho, grid, axis triad, material override. It is +// a small cluster on the viewport that loads the pinned GLB — not a second +// inspector, and not a second toolbar. +// +// THE STORE IS THE AUTHORITY, the same way ExplodeSlider writes `explode_t` +// and never touches the scene. `Viewport.tsx` has one effect per flag and +// pushes it into the engine, so the canvas and the buttons cannot disagree. +// Fit is the exception that proves the rule: it is an action, not a flag, and +// it calls the engine's existing `frame()` — `cameras.py`'s construction — +// rather than inventing a second camera. +// +// DEFAULTS ARE THE AUTHORED PICTURE. A strip that arrived pressed-off would +// move G4.5's control-region pixels and §3.11.2's contrast floor by existing. +// The cluster is fixed-size chrome and does not grow on a visibility toggle. +// +// No new icon id: §3.12 is closed at 18. The words live in `copy.ts`. + +import { useSyncExternalStore } from "react"; +import { copy } from "../../../copy"; +import { appearanceStore, type AppearanceToggle } from "../../../state/appearance"; +import { Button } from "../../../system"; +import styles from "./AppearanceControls.module.css"; + +export interface AppearanceControlsProps { + /** False when no pinned GLB is on the canvas — Fit has nothing to frame. */ + readonly canFit: boolean; + /** Re-apply the current named view's framing. */ + readonly onFit: () => void; +} + +const TOGGLE_COPY: Readonly> = { + wireframe: copy.viewport.appearance.wireframe, + ortho: copy.viewport.appearance.ortho, + grid: copy.viewport.appearance.grid, + triad: copy.viewport.appearance.triad, + materialOverride: copy.viewport.appearance.material, +}; + +/** Issue #10's listed order: wireframe / fit / ortho / grid / triad / material. */ +const CLUSTER_ORDER = ["wireframe", "fit", "ortho", "grid", "triad", "materialOverride"] as const; + +export function AppearanceControls({ canFit, onFit }: AppearanceControlsProps): React.JSX.Element { + const appearance = useSyncExternalStore( + appearanceStore.subscribe, + appearanceStore.getSnapshot, + appearanceStore.getSnapshot, + ); + + return ( +
+ {CLUSTER_ORDER.map((field) => + field === "fit" ? ( + canFit ? ( + + ) : ( + + ) + ) : ( + + ), + )} +
+ ); +} diff --git a/web/src/components/stage/viewport/AxisTriad.module.css b/web/src/components/stage/viewport/AxisTriad.module.css index b61c51c5..9b19bb6d 100644 --- a/web/src/components/stage/viewport/AxisTriad.module.css +++ b/web/src/components/stage/viewport/AxisTriad.module.css @@ -14,6 +14,10 @@ * permitted against. */ +.triad[data-axis-hidden] { + visibility: hidden; +} + .triad { position: absolute; /* One-off geometric offset: the readout is `--space-3` from the bottom and is diff --git a/web/src/components/stage/viewport/AxisTriad.tsx b/web/src/components/stage/viewport/AxisTriad.tsx index 55372cc4..915b2319 100644 --- a/web/src/components/stage/viewport/AxisTriad.tsx +++ b/web/src/components/stage/viewport/AxisTriad.tsx @@ -58,9 +58,11 @@ const LABEL_REACH = 1.42; export interface AxisTriadProps { /** The live engine, or `null` before it exists / after it is disposed. */ readonly engine: ViewportEngine | null; + /** §5.5's operator toggle. Default on — the authored picture. */ + readonly visible?: boolean; } -export function AxisTriad({ engine }: AxisTriadProps): React.JSX.Element { +export function AxisTriad({ engine, visible = true }: AxisTriadProps): React.JSX.Element { const lines = useRef>>({}); const labels = useRef>>({}); @@ -95,9 +97,11 @@ export function AxisTriad({ engine }: AxisTriadProps): React.JSX.Element { {AXES.map((axis) => (
{/* The bounds belong to the *loaded* GLB: while none is loaded the diff --git a/web/src/copy.ts b/web/src/copy.ts index 45bbfe21..e0d4d69b 100644 --- a/web/src/copy.ts +++ b/web/src/copy.ts @@ -186,7 +186,7 @@ export const copy = { reset: "Reset to default", }, - /** §5. The viewport, its two overlays, and every named absence it can reach. */ + /** §5. The viewport, its overlays, and every named absence it can reach. */ viewport: { label: "Geometry", /** @@ -252,6 +252,41 @@ export const copy = { label: "Axis orientation", axis: { x: "X", y: "Y", z: "Z" }, }, + /** + * Operator appearance cluster (§3.11, §5.5). Words, not icons: the sprite + * is closed at 18 ids and these controls are a scan, not a status. + */ + appearance: { + label: "Viewport appearance", + wireframe: { + label: "Wireframe", + explain: "Hide the fill and keep the silhouette. Hidden solids still disappear with their outline.", + }, + fit: { + label: "Fit", + explain: + "Frame the pinned artifact the way the renderer frames this named view. Orbit and zoom return to that framing.", + disabled: "No pinned artifact is on the canvas, so there is nothing to frame.", + }, + ortho: { + label: "Ortho", + explain: + "Orthographic projection, matching the named views the renderer can reproduce. Off is a perspective viewing aid; Fit and the view cube stay the same camera.", + }, + grid: { + label: "Grid", + explain: "Ground grid, spaced at the step the readout reports.", + }, + triad: { + label: "Axes", + explain: "Axis triad in the same Z-up frame as the camera.", + }, + material: { + label: "Material", + explain: + "Override every solid with the viewport part colour, at least 4.5:1 against the ground. Off restores the exporter's own material; it does not invent a new one.", + }, + }, viewCube: { label: "Standard views", namedLabel: "Named views", diff --git a/web/src/state/appearance.ts b/web/src/state/appearance.ts new file mode 100644 index 00000000..a87ed037 --- /dev/null +++ b/web/src/state/appearance.ts @@ -0,0 +1,112 @@ +// Copyright 2026 The Hephaestus Authors +// SPDX-License-Identifier: Apache-2.0 +// +// Viewport appearance (INTERFACE.md §3.11, §5.5) — operator chrome, not +// workspace state. +// +// §3.11 already authors the picture: a material at `--viewport-part` with a +// ≥4.5:1 part-vs-ground floor, a silhouette, a ground grid, an axis triad, and +// an orthographic camera framed like `cameras.py`. This store is the operator +// cluster that *drives* those decisions. It holds no geometry and no server +// value. Four consequences: +// +// * **It is not workspace state.** §4.5's record is closed and carries no +// appearance field. Putting wireframe or a hidden grid in the URL would widen +// a closed vocabulary, and a link that silently hid the floor would be a link +// that showed a different instrument than the one it names. Appearance is +// therefore session-local, like `state/visibility.ts`, and does not survive a +// reload. +// * **Defaults are the authored picture.** Wireframe off, ortho on, grid on, +// triad on, material override on. G4.5's control region and §3.11.2's contrast +// floor are measured against that picture; this store must not move those +// pixels by existing. +// * **The material is not invented here.** Override on means the one authored +// `MeshStandardMaterial` at `--viewport-part`. Override off restores the +// exporter's own material, which is a selection ID, not a colour the operator +// chose. There is no third material and no catalog. +// * **Bound to the pin, not to a second inspector.** The cluster lives on the +// viewport that loads `GET /artifacts/{ref}/gltf` for `artifact_ref`. Fit +// re-applies `cameras.py`'s framing for the current named view. Nothing here +// writes the pin. + +/** The five toggles the cluster exposes. Fit is an action, not a flag. */ +export const APPEARANCE_TOGGLES = [ + "wireframe", + "ortho", + "grid", + "triad", + "materialOverride", +] as const; +export type AppearanceToggle = (typeof APPEARANCE_TOGGLES)[number]; + +export interface AppearanceState { + readonly wireframe: boolean; + readonly ortho: boolean; + readonly grid: boolean; + readonly triad: boolean; + readonly materialOverride: boolean; +} + +/** §3.11's authored picture — the only defaults this store may have. */ +export const DEFAULT_APPEARANCE: AppearanceState = { + wireframe: false, + ortho: true, + grid: true, + triad: true, + materialOverride: true, +}; + +type Listener = () => void; + +function sameAppearance(a: AppearanceState, b: AppearanceState): boolean { + return ( + a.wireframe === b.wireframe && + a.ortho === b.ortho && + a.grid === b.grid && + a.triad === b.triad && + a.materialOverride === b.materialOverride + ); +} + +/** + * The appearance record, as an external store for `useSyncExternalStore`. + * + * The snapshot is the record itself and it is replaced (never mutated) on every + * write, so identity comparison is a correct change test. + */ +export class AppearanceStore { + #state: AppearanceState; + readonly #listeners = new Set(); + + constructor(initial: AppearanceState = DEFAULT_APPEARANCE) { + this.#state = initial; + } + + subscribe = (listener: Listener): (() => void) => { + this.#listeners.add(listener); + return () => { + this.#listeners.delete(listener); + }; + }; + + getSnapshot = (): AppearanceState => this.#state; + + /** Flip one flag. Returns nothing: the store is the authority, not the caller. */ + toggle(field: AppearanceToggle): void { + this.#commit({ ...this.#state, [field]: !this.#state[field] }); + } + + /** Test seam: put the store back to the authored picture. */ + reset(): void { + this.#commit(DEFAULT_APPEARANCE); + } + + #commit(next: AppearanceState): void { + if (sameAppearance(this.#state, next)) return; + this.#state = next; + for (const listener of this.#listeners) listener(); + } +} + +/** The process-wide store. One workspace, one viewport. */ +export const appearanceStore = new AppearanceStore(); diff --git a/web/src/viewport/display.ts b/web/src/viewport/display.ts index 63be9cc1..64cfe72f 100644 --- a/web/src/viewport/display.ts +++ b/web/src/viewport/display.ts @@ -449,3 +449,58 @@ export function buildGroundGrid(spec: GroundGridSpec, palette: ViewportPalette): }, }; } + +/** + * The two display flags that mutate the loaded meshes. Grid, triad and ortho + * live on the engine / the DOM — they are not a material decision. + * + * `materialOverride` on means every mesh wears the one authored material at + * `--viewport-part` (the ≥4.5:1 floor). Off restores the exporter's own + * material, which is a selection ID, not a colour. There is no third material. + * + * `wireframe` on hides the fill and keeps the silhouette. The edges are + * children of the mesh (§3.11.4), so hiding the *material* rather than the + * *node* is what leaves the outline standing. A hidden solid (§5.4) still + * hides both, because that is hierarchical visibility on the node. + */ +export interface DisplayAppearance { + readonly wireframe: boolean; + readonly materialOverride: boolean; +} + +/** Collect meshes first: `traverse` walks `children` live. */ +function meshesOf(root: Object3D): Mesh[] { + const meshes: Mesh[] = []; + root.traverse((object: Object3D) => { + const mesh = object as Mesh; + if (mesh.isMesh === true) meshes.push(mesh); + }); + return meshes; +} + +/** + * Apply the operator's material / wireframe flags to an already-authored tree. + * + * Idempotent and order-independent with `authorDisplay`: a mesh that was never + * authored has no `SOURCE_MATERIAL_KEY` and is left alone, so a call before + * load is a no-op rather than a guess. + */ +export function applyAppearance( + root: Object3D, + authored: MeshStandardMaterial, + appearance: DisplayAppearance, +): void { + const meshes = meshesOf(root); + for (const mesh of meshes) { + const source = mesh.userData[SOURCE_MATERIAL_KEY]; + if (source === undefined) continue; + mesh.material = appearance.materialOverride ? authored : source; + } + // The authored material is shared. One write covers every overridden mesh. + authored.visible = appearance.materialOverride && !appearance.wireframe; + for (const mesh of meshes) { + const source = mesh.userData[SOURCE_MATERIAL_KEY] as MeshStandardMaterial | undefined; + if (source === undefined || source === authored) continue; + source.visible = !appearance.materialOverride && !appearance.wireframe; + } +} diff --git a/web/src/viewport/engine.ts b/web/src/viewport/engine.ts index c9599d7e..a3103688 100644 --- a/web/src/viewport/engine.ts +++ b/web/src/viewport/engine.ts @@ -44,6 +44,7 @@ import { DirectionalLight, Group, OrthographicCamera, + PerspectiveCamera, Plane, SRGBColorSpace, Scene, @@ -56,12 +57,14 @@ import { GLTFLoader, type GLTF } from "three/addons/loaders/GLTFLoader.js"; import { OrbitControls } from "three/addons/controls/OrbitControls.js"; import { nameForDirection } from "./cameras"; import { + applyAppearance, authorDisplay, buildGroundGrid, gridStep, groundGridSpec, readViewportPalette, type AuthoredDisplay, + type DisplayAppearance, type GroundGrid, type ViewportPalette, } from "./display"; @@ -70,6 +73,7 @@ import { applyClipping, applyExplode, applyFraming, + applyPerspectiveFraming, applyVisibility, boundsAt, framingFor, @@ -96,7 +100,9 @@ export class ViewportEngine { readonly canvas: HTMLCanvasElement; private readonly renderer: WebGLRenderer; private readonly scene: Scene; - private readonly camera: OrthographicCamera; + private readonly orthoCamera: OrthographicCamera; + private readonly perspCamera: PerspectiveCamera; + private camera: OrthographicCamera | PerspectiveCamera; private readonly controls: OrbitControls; private readonly root = new Group(); /** @@ -113,6 +119,8 @@ export class ViewportEngine { private readonly frameListeners = new Set<() => void>(); private display: AuthoredDisplay | null = null; + private appearance: DisplayAppearance = { wireframe: false, materialOverride: true }; + private ortho = true; private grid: GroundGrid | null = null; private step = 0; private index: SolidIndex | null = null; @@ -161,10 +169,13 @@ export class ViewportEngine { this.scene.add(this.root); this.scene.add(this.gridRoot); - this.camera = new OrthographicCamera(-1, 1, 1, -1, 0.1, 1000); + this.orthoCamera = new OrthographicCamera(-1, 1, 1, -1, 0.1, 1000); + this.perspCamera = new PerspectiveCamera(35, 1, 0.1, 1000); + this.camera = this.orthoCamera; // Z-up, matching `cameras.py`'s frame. three.js defaults to Y-up, and a // viewport in the other convention would show every named view rotated. - this.camera.up.set(0, 0, 1); + this.orthoCamera.up.set(0, 0, 1); + this.perspCamera.up.set(0, 0, 1); // Lights ride with the camera so shading does not change meaning when the // view does: the picture is an instrument reading, not a beauty render. @@ -200,6 +211,7 @@ export class ViewportEngine { // loader's `associations` map, which only ever names nodes the loader made. // Authoring first proves the join is unaffected by what we add. this.display = authorDisplay(gltf.scene, this.palette); + applyAppearance(gltf.scene, this.display.material, this.appearance); this.root.add(gltf.scene); this.index = indexSolidNodes(gltf, geometry); this.bounds = boundsAt(this.index, 0); @@ -258,9 +270,7 @@ export class ViewportEngine { const framing = framingFor(bounds, view, this.aspect()); if (framing === null) return; this.framing = framing; - applyFraming(this.camera, framing); - this.camera.zoom = 1; - this.camera.updateProjectionMatrix(); + this.applyCurrentFraming(framing); this.controls.target.set(framing.target[0], framing.target[1], framing.target[2]); this.controls.update(); // §3.11.5's grid is stepped off the span this framing just fixed — the same @@ -294,6 +304,76 @@ export class ViewportEngine { this.render(); } + /** + * Operator appearance flags that mutate the loaded meshes (§3.11). + * + * Grid visibility and the camera projection are the other half and have + * their own setters — they are not a material decision. + */ + setAppearance(appearance: DisplayAppearance): void { + this.appearance = appearance; + const display = this.display; + if (display === null) return; + applyAppearance(this.root, display.material, appearance); + this.render(); + } + + /** + * Show or hide §3.11.5's ground grid. The step is unchanged: hiding the + * lines does not invent a different spacing, and the readout reports 0 when + * the caller has turned the grid off. + */ + setGridVisible(visible: boolean): void { + this.gridRoot.visible = visible; + this.render(); + } + + /** + * Orthographic (the `cameras.py` projection) or a perspective viewing aid + * that keeps the same eye, target and vertical extent. + * + * Default is ortho. Named views and `heph render` stay orthographic; this + * flag only changes how the working canvas projects them. + */ + setOrtho(ortho: boolean): void { + if (ortho === this.ortho) return; + this.ortho = ortho; + const previous = this.camera; + const next = ortho ? this.orthoCamera : this.perspCamera; + next.position.copy(previous.position); + next.up.copy(previous.up); + next.near = previous.near; + next.far = previous.far; + next.lookAt(this.controls.target); + for (const child of [...previous.children]) next.add(child); + this.scene.remove(previous); + this.scene.add(next); + this.camera = next; + this.controls.object = next; + // Keep the current pose. Fit is the action that snaps back to the named + // view; toggling the projection must not steal an orbit. + const distance = Math.max(next.position.distanceTo(this.controls.target), 1e-6); + const aspect = this.aspect(); + const halfHeight = + previous === this.orthoCamera + ? this.orthoCamera.top / this.orthoCamera.zoom + : Math.tan((this.perspCamera.fov * Math.PI) / 360) * distance; + if (ortho) { + this.orthoCamera.top = halfHeight; + this.orthoCamera.bottom = -halfHeight; + this.orthoCamera.left = -halfHeight * aspect; + this.orthoCamera.right = halfHeight * aspect; + this.orthoCamera.zoom = 1; + this.orthoCamera.updateProjectionMatrix(); + } else { + this.perspCamera.fov = (2 * Math.atan(halfHeight / distance) * 180) / Math.PI; + this.perspCamera.aspect = aspect; + this.perspCamera.updateProjectionMatrix(); + } + this.controls.update(); + this.render(); + } + /** §5.3's live preview: `null` clears every clipping plane. */ setSection(plane: SectionPlaneSpec | null): void { if (plane === null) { @@ -316,16 +396,26 @@ export class ViewportEngine { // Keep the vertical extent and re-fit the horizontal one, so a resize // changes how much is visible and never how large a millimetre is. const halfWidth = framing.halfHeight * this.aspect(); - this.camera.left = -halfWidth; - this.camera.right = halfWidth; - this.camera.updateProjectionMatrix(); + if (this.camera === this.orthoCamera) { + this.orthoCamera.left = -halfWidth; + this.orthoCamera.right = halfWidth; + this.orthoCamera.updateProjectionMatrix(); + } else { + this.perspCamera.aspect = this.aspect(); + this.perspCamera.updateProjectionMatrix(); + } } this.render(); } /** The camera's current half-height in model units — the grid readout's scale. */ scale(): number { - return this.camera.top / this.camera.zoom; + if (this.camera === this.orthoCamera) { + return this.orthoCamera.top / this.orthoCamera.zoom; + } + const distance = this.perspCamera.position.distanceTo(this.controls.target); + const halfAngle = (this.perspCamera.fov * Math.PI) / 360; + return Math.tan(halfAngle) * distance; } /** @@ -401,6 +491,17 @@ export class ViewportEngine { return size.y > 0 ? size.x / size.y : 1; } + /** Apply the last named-view framing to whichever camera is live. */ + private applyCurrentFraming(framing: Framing): void { + if (this.camera === this.orthoCamera) { + applyFraming(this.orthoCamera, framing); + this.orthoCamera.zoom = 1; + this.orthoCamera.updateProjectionMatrix(); + } else { + applyPerspectiveFraming(this.perspCamera, framing); + } + } + private clearRoot(): void { for (const child of [...this.root.children]) this.root.remove(child); // The authored material and the edge geometries are ours; the GLB's own diff --git a/web/src/viewport/scene.ts b/web/src/viewport/scene.ts index 9773b493..833bb95e 100644 --- a/web/src/viewport/scene.ts +++ b/web/src/viewport/scene.ts @@ -24,7 +24,14 @@ // carries `meshes` alone. Reading the association is the same fact from the // party that actually built the tree. -import { Box3, Vector3, type Object3D, type OrthographicCamera, type Plane } from "three"; +import { + Box3, + Vector3, + type Object3D, + type OrthographicCamera, + type PerspectiveCamera, + type Plane, +} from "three"; import type { GLTF } from "three/addons/loaders/GLTFLoader.js"; import { eyeDirection, upHint, viewAngles } from "./cameras"; import { explodeTranslation, type Displacement } from "./explode"; @@ -259,6 +266,39 @@ export function applyFraming(camera: OrthographicCamera, framing: Framing): void camera.updateMatrixWorld(true); } +/** + * Vertical FOV that matches an orthographic `halfHeight` at `distance`. + * + * The named views and `heph render` stay orthographic. Perspective is a + * viewing aid that keeps the same eye, target and vertical extent so Fit and + * the view cube still mean one camera. Returns 0 when the pair is not a + * positive finite framing — there is no sensible FOV for an unframed camera + * and none is invented. + */ +export function perspectiveFovDeg(halfHeight: number, distance: number): number { + if (!Number.isFinite(halfHeight) || !Number.isFinite(distance)) return 0; + if (halfHeight <= 0 || distance <= 0) return 0; + return (2 * Math.atan(halfHeight / distance) * 180) / Math.PI; +} + +/** Point a perspective camera at the same framing `applyFraming` uses. */ +export function applyPerspectiveFraming(camera: PerspectiveCamera, framing: Framing): void { + camera.position.set(framing.eye[0], framing.eye[1], framing.eye[2]); + camera.up.set(framing.up[0], framing.up[1], framing.up[2]); + camera.near = framing.near; + camera.far = framing.far; + const distance = Math.hypot( + framing.eye[0] - framing.target[0], + framing.eye[1] - framing.target[1], + framing.eye[2] - framing.target[2], + ); + camera.fov = perspectiveFovDeg(framing.halfHeight, distance); + camera.aspect = framing.halfHeight > 0 ? framing.halfWidth / framing.halfHeight : 1; + camera.lookAt(framing.target[0], framing.target[1], framing.target[2]); + camera.updateProjectionMatrix(); + camera.updateMatrixWorld(true); +} + /** * World-space bounding-box centres, keyed by `solid_index`. * diff --git a/web/test/appearance.test.ts b/web/test/appearance.test.ts new file mode 100644 index 00000000..cbb13776 --- /dev/null +++ b/web/test/appearance.test.ts @@ -0,0 +1,82 @@ +// Copyright 2026 The Hephaestus Authors +// SPDX-License-Identifier: Apache-2.0 +// +// The appearance store (INTERFACE.md §3.11, §5.5). +// +// Two properties: defaults are the authored picture, and the store is not +// workspace state. Assertions are on fields, never on wording. + +import { afterEach, describe, expect, it } from "vitest"; +import { + APPEARANCE_TOGGLES, + AppearanceStore, + DEFAULT_APPEARANCE, + appearanceStore, +} from "../src/state/appearance"; +import { DEFAULT_STATE, encodeWorkspaceUrl } from "../src/state/workspace"; + +afterEach(() => { + appearanceStore.reset(); +}); + +describe("appearance defaults are §3.11's authored picture", () => { + it("starts shaded, orthographic, grid and triad on, override on", () => { + expect(DEFAULT_APPEARANCE).toEqual({ + wireframe: false, + ortho: true, + grid: true, + triad: true, + materialOverride: true, + }); + expect(new AppearanceStore().getSnapshot()).toEqual(DEFAULT_APPEARANCE); + }); + + it("exposes exactly the five toggles — Fit is an action, not a flag", () => { + expect(APPEARANCE_TOGGLES).toEqual([ + "wireframe", + "ortho", + "grid", + "triad", + "materialOverride", + ]); + expect(APPEARANCE_TOGGLES).not.toContain("fit"); + }); +}); + +describe("the appearance store", () => { + it("toggles one field and leaves the others", () => { + const store = new AppearanceStore(); + store.toggle("wireframe"); + expect(store.getSnapshot().wireframe).toBe(true); + expect(store.getSnapshot().ortho).toBe(true); + store.toggle("grid"); + expect(store.getSnapshot().grid).toBe(false); + expect(store.getSnapshot().wireframe).toBe(true); + }); + + it("notifies once per real change and never on a no-op reset", () => { + const store = new AppearanceStore(); + let notifications = 0; + const stop = store.subscribe(() => { + notifications += 1; + }); + store.toggle("triad"); + store.toggle("triad"); + store.reset(); + expect(notifications).toBe(2); + store.reset(); + expect(notifications).toBe(2); + stop(); + store.toggle("ortho"); + expect(notifications).toBe(2); + }); + + it("is not written into the workspace URL — §4.5 stays closed", () => { + const url = encodeWorkspaceUrl(DEFAULT_STATE); + expect(url).not.toContain("wireframe"); + expect(url).not.toContain("ortho"); + expect(url).not.toContain("material"); + expect(url).not.toMatch(/[?&]grid=/); + expect(url).not.toContain("triad"); + }); +}); diff --git a/web/test/appearanceControls.test.tsx b/web/test/appearanceControls.test.tsx new file mode 100644 index 00000000..647ddff3 --- /dev/null +++ b/web/test/appearanceControls.test.tsx @@ -0,0 +1,72 @@ +// Copyright 2026 The Hephaestus Authors +// SPDX-License-Identifier: Apache-2.0 +// +// The appearance cluster's markup contract (INTERFACE.md §3.11, §5.5). +// +// Assertions are on `data-*` attributes and pressed/disabled state, never on +// wording (§3). The cluster must exist without inventing a new inspector +// panel or a new icon id. + +import { afterEach, describe, expect, it } from "vitest"; +import { renderToStaticMarkup } from "react-dom/server"; +import type { ReactElement } from "react"; + +import { AppearanceControls } from "../src/components/stage/viewport/AppearanceControls"; +import { APPEARANCE_TOGGLES, appearanceStore } from "../src/state/appearance"; + +function render(element: ReactElement): HTMLElement { + const host = document.createElement("div"); + host.innerHTML = renderToStaticMarkup(element); + return host; +} + +afterEach(() => { + appearanceStore.reset(); +}); + +describe("AppearanceControls — bound to the pin, not a second inspector", () => { + it("emits one toolbar with the five toggles and Fit", () => { + const host = render( undefined} />); + const cluster = host.querySelector("[data-appearance]"); + expect(cluster?.getAttribute("role")).toBe("toolbar"); + for (const field of APPEARANCE_TOGGLES) { + expect(host.querySelector(`[data-appearance-control="${field}"]`)).not.toBeNull(); + } + expect(host.querySelector('[data-appearance-control="fit"]')).not.toBeNull(); + const order = [...host.querySelectorAll("[data-appearance-control]")].map((node) => + node.getAttribute("data-appearance-control"), + ); + expect(order).toEqual(["wireframe", "fit", "ortho", "grid", "triad", "materialOverride"]); + }); + + it("defaults match the authored picture — G4.5/§3.11.2 must not move by existing", () => { + const host = render( undefined} />); + const pressed = (field: string): string | null => + host.querySelector(`[data-appearance-control="${field}"]`)?.getAttribute("aria-pressed") ?? + null; + expect(pressed("wireframe")).toBe("false"); + expect(pressed("ortho")).toBe("true"); + expect(pressed("grid")).toBe("true"); + expect(pressed("triad")).toBe("true"); + expect(pressed("materialOverride")).toBe("true"); + }); + + it("disables Fit when no pinned artifact is on the canvas, with a reason", () => { + const host = render( undefined} />); + const fit = host.querySelector('[data-appearance-control="fit"]'); + expect(fit?.hasAttribute("disabled")).toBe(true); + expect(fit?.getAttribute("title")).toBeTruthy(); + expect(fit?.getAttribute("aria-describedby")).toBeTruthy(); + }); + + it("keeps Fit enabled when the pin is on the canvas", () => { + const host = render( undefined} />); + const fit = host.querySelector('[data-appearance-control="fit"]'); + expect(fit?.hasAttribute("disabled")).toBe(false); + }); + + it("does not introduce an icon id — §3.12 stays closed", () => { + const host = render( undefined} />); + expect(host.querySelector("[data-icon]")).toBeNull(); + }); +}); diff --git a/web/test/display.test.ts b/web/test/display.test.ts index 9fd149e4..2ffe9a9f 100644 --- a/web/test/display.test.ts +++ b/web/test/display.test.ts @@ -38,6 +38,7 @@ import { GRID_TARGET_DIVISIONS, SOURCE_MATERIAL_KEY, authorDisplay, + applyAppearance, buildGroundGrid, gridStep, groundGridSpec, @@ -393,6 +394,63 @@ describe("buildGroundGrid (§3.11.5)", () => { // The palette read // --------------------------------------------------------------------------- +describe("applyAppearance — wireframe and override, no invented material", () => { + it("hides the fill and keeps the silhouette when wireframe is on", () => { + const { scene, meshes } = loadedScene(2); + const display = authorDisplay(scene, PALETTE); + applyAppearance(scene, display.material, { wireframe: true, materialOverride: true }); + + expect(display.material.visible).toBe(false); + for (const mesh of meshes) { + expect(mesh.material).toBe(display.material); + expect(childEdges(mesh)).toHaveLength(1); + expect(childEdges(mesh)[0]?.visible).toBe(true); + } + }); + + it("restores the exporter material when override is off, and invents none", () => { + const { scene, meshes } = loadedScene(2); + const display = authorDisplay(scene, PALETTE); + const preserved = meshes[0]?.userData[SOURCE_MATERIAL_KEY] as MeshStandardMaterial; + + applyAppearance(scene, display.material, { wireframe: false, materialOverride: false }); + + expect(meshes[0]?.material).toBe(preserved); + expect(meshes[1]?.material).toBe(meshes[1]?.userData[SOURCE_MATERIAL_KEY]); + expect(display.material.visible).toBe(false); + expect(preserved.visible).toBe(true); + // The restored colour is still the selection ID, not a new display colour. + const rgb = { r: 0, g: 0, b: 0 }; + preserved.color.getRGB(rgb, LinearSRGBColorSpace); + expect([ + Math.round(rgb.r * 255), + Math.round(rgb.g * 255), + Math.round(rgb.b * 255), + ]).toEqual(idToRgb(0)); + }); + + it("puts the authored material back when override returns, at the part token", () => { + const { scene, meshes } = loadedScene(1); + const display = authorDisplay(scene, PALETTE); + applyAppearance(scene, display.material, { wireframe: false, materialOverride: false }); + applyAppearance(scene, display.material, { wireframe: false, materialOverride: true }); + + expect(meshes[0]?.material).toBe(display.material); + expect(display.material.visible).toBe(true); + expect(display.material.color.getHex()).toBe(PALETTE.part.getHex()); + }); + + it("is a no-op on a tree that was never authored", () => { + const { scene, meshes } = loadedScene(1); + const display = authorDisplay(scene, PALETTE); + const stranger = new Group(); + stranger.add(exporterMesh(9)); + applyAppearance(stranger, display.material, { wireframe: true, materialOverride: true }); + expect((stranger.children[0] as Mesh).material).not.toBe(display.material); + expect(meshes[0]?.material).toBe(display.material); + }); +}); + describe("readViewportPalette (§3.6, §3.11)", () => { // The channel triples are written as decimals and composed here rather than // as `#rrggbb` literals: `no-palette-token` (§3.14) refuses a hex anywhere diff --git a/web/test/viewport.test.ts b/web/test/viewport.test.ts index 429ffe4d..53f6a9b5 100644 --- a/web/test/viewport.test.ts +++ b/web/test/viewport.test.ts @@ -11,7 +11,7 @@ // that does — holds no logic of its own. import { describe, expect, it } from "vitest"; -import { Box3, Group, Mesh, Vector3 } from "three"; +import { Box3, Group, Mesh, PerspectiveCamera, Vector3 } from "three"; import type { Object3D } from "three"; import type { GLTF } from "three/addons/loaders/GLTFLoader.js"; import { GlbFormatError, readGlbGeometry } from "../src/viewport/glb"; @@ -33,9 +33,11 @@ import { } from "../src/viewport/section"; import { applyExplode, + applyPerspectiveFraming, applyVisibility, boundsAt, framingFor, + perspectiveFovDeg, indexSolidNodes, solidCentroids, } from "../src/viewport/scene"; @@ -404,6 +406,31 @@ describe("scene (§5.2, §5.4)", () => { const bounds = new Box3(new Vector3(0, 0, 0), new Vector3(1, 1, 1)); expect(framingFor(bounds, "sideways", 1)).toBeNull(); }); + + it("derives a perspective FOV from the same half-height the ortho camera uses", () => { + // A 50-unit half-height at 100 units of distance is 2*atan(0.5) degrees. + expect(perspectiveFovDeg(50, 100)).toBeCloseTo((2 * Math.atan(0.5) * 180) / Math.PI, 10); + expect(perspectiveFovDeg(0, 100)).toBe(0); + expect(perspectiveFovDeg(10, 0)).toBe(0); + expect(perspectiveFovDeg(Number.NaN, 10)).toBe(0); + }); + + it("places a perspective camera on the same eye/target as the ortho framing", () => { + const bounds = new Box3(new Vector3(-5, -5, -5), new Vector3(5, 5, 5)); + const framing = framingFor(bounds, "iso", 1); + expect(framing).not.toBeNull(); + if (framing === null) return; + const camera = new PerspectiveCamera(); + applyPerspectiveFraming(camera, framing); + expect(camera.position.toArray()).toEqual([...framing.eye]); + const distance = Math.hypot( + framing.eye[0] - framing.target[0], + framing.eye[1] - framing.target[1], + framing.eye[2] - framing.target[2], + ); + expect(camera.fov).toBeCloseTo(perspectiveFovDeg(framing.halfHeight, distance), 10); + expect(camera.aspect).toBeCloseTo(framing.halfWidth / framing.halfHeight, 10); + }); }); // ---------------------------------------------------------------------------