diff --git a/apps/editor/components/build-tab.tsx b/apps/editor/components/build-tab.tsx index e65e9c569a..244d72b32b 100644 --- a/apps/editor/components/build-tab.tsx +++ b/apps/editor/components/build-tab.tsx @@ -25,7 +25,11 @@ import { useWallDrawVariant, withToolShortcut, } from '@pascal-app/editor' -import { framingPostToolChoices, useLiquidLineToolOptions } from '@pascal-app/nodes' +import { + framingPostToolChoices, + RoofTypeThumbnail, + useLiquidLineToolOptions, +} from '@pascal-app/nodes' import { useViewer } from '@pascal-app/viewer' import Image from 'next/image' import { useCallback, useEffect, useRef, useState, useSyncExternalStore } from 'react' @@ -307,14 +311,14 @@ export function BuildTab() {
{i18n._({ id: 'app.buildTab.roofType', message: 'Roof type' })}
-
+
{ROOF_TYPE_OPTIONS.map((roofType) => { const active = activeTool === 'roof' && activeRoofType === roofType.value return ( ) diff --git a/apps/editor/lib/build-tab-state.test.ts b/apps/editor/lib/build-tab-state.test.ts index 6e40d899b4..4718da8b25 100644 --- a/apps/editor/lib/build-tab-state.test.ts +++ b/apps/editor/lib/build-tab-state.test.ts @@ -36,5 +36,6 @@ test('roof creation exposes every supported roof type', () => { 'dutch', 'mansard', 'conical', + 'barrel', ]) }) diff --git a/apps/editor/lib/build-tab-state.ts b/apps/editor/lib/build-tab-state.ts index 3f89267ae6..fb7d920756 100644 --- a/apps/editor/lib/build-tab-state.ts +++ b/apps/editor/lib/build-tab-state.ts @@ -48,6 +48,10 @@ export const ROOF_TYPE_OPTIONS: ReadonlyArray<{ label: MessageDescriptor; value: label: /* i18n */ { id: 'app.lib.buildTabState.conical', message: 'Conical' }, value: 'conical', }, + { + label: /* i18n */ { id: 'app.lib.buildTabState.barrel', message: 'Barrel' }, + value: 'barrel', + }, ] export function getActiveRoofFeatureId( diff --git a/apps/editor/public/icons/column-presets/aFrameSupport.webp b/apps/editor/public/icons/column-presets/aFrameSupport.webp new file mode 100644 index 0000000000..5edd17ed9f Binary files /dev/null and b/apps/editor/public/icons/column-presets/aFrameSupport.webp differ diff --git a/apps/editor/public/icons/column-presets/basicPillar.webp b/apps/editor/public/icons/column-presets/basicPillar.webp new file mode 100644 index 0000000000..c118cc96f9 Binary files /dev/null and b/apps/editor/public/icons/column-presets/basicPillar.webp differ diff --git a/apps/editor/public/icons/column-presets/boxFrameSupport.webp b/apps/editor/public/icons/column-presets/boxFrameSupport.webp new file mode 100644 index 0000000000..4a72e5fd37 Binary files /dev/null and b/apps/editor/public/icons/column-presets/boxFrameSupport.webp differ diff --git a/apps/editor/public/icons/column-presets/bulgedPillar.webp b/apps/editor/public/icons/column-presets/bulgedPillar.webp new file mode 100644 index 0000000000..2852bf991e Binary files /dev/null and b/apps/editor/public/icons/column-presets/bulgedPillar.webp differ diff --git a/apps/editor/public/icons/column-presets/hourglassPillar.webp b/apps/editor/public/icons/column-presets/hourglassPillar.webp new file mode 100644 index 0000000000..0967a2ef59 Binary files /dev/null and b/apps/editor/public/icons/column-presets/hourglassPillar.webp differ diff --git a/apps/editor/public/icons/column-presets/kBraceSupport.webp b/apps/editor/public/icons/column-presets/kBraceSupport.webp new file mode 100644 index 0000000000..498867da51 Binary files /dev/null and b/apps/editor/public/icons/column-presets/kBraceSupport.webp differ diff --git a/apps/editor/public/icons/column-presets/portalFrameSupport.webp b/apps/editor/public/icons/column-presets/portalFrameSupport.webp new file mode 100644 index 0000000000..23fb8d5151 Binary files /dev/null and b/apps/editor/public/icons/column-presets/portalFrameSupport.webp differ diff --git a/apps/editor/public/icons/column-presets/singleStrutSupport.webp b/apps/editor/public/icons/column-presets/singleStrutSupport.webp new file mode 100644 index 0000000000..ccba835623 Binary files /dev/null and b/apps/editor/public/icons/column-presets/singleStrutSupport.webp differ diff --git a/apps/editor/public/icons/column-presets/squarePillar.webp b/apps/editor/public/icons/column-presets/squarePillar.webp new file mode 100644 index 0000000000..1bd217dbfa Binary files /dev/null and b/apps/editor/public/icons/column-presets/squarePillar.webp differ diff --git a/apps/editor/public/icons/column-presets/taperedPillar.webp b/apps/editor/public/icons/column-presets/taperedPillar.webp new file mode 100644 index 0000000000..f146ba11a1 Binary files /dev/null and b/apps/editor/public/icons/column-presets/taperedPillar.webp differ diff --git a/apps/editor/public/icons/column-presets/trestleSupport.webp b/apps/editor/public/icons/column-presets/trestleSupport.webp new file mode 100644 index 0000000000..4456d18738 Binary files /dev/null and b/apps/editor/public/icons/column-presets/trestleSupport.webp differ diff --git a/apps/editor/public/icons/column-presets/tripodSupport.webp b/apps/editor/public/icons/column-presets/tripodSupport.webp new file mode 100644 index 0000000000..0ec9c92fbd Binary files /dev/null and b/apps/editor/public/icons/column-presets/tripodSupport.webp differ diff --git a/apps/editor/public/icons/column-presets/vFrameSupport.webp b/apps/editor/public/icons/column-presets/vFrameSupport.webp new file mode 100644 index 0000000000..f42fe89a4d Binary files /dev/null and b/apps/editor/public/icons/column-presets/vFrameSupport.webp differ diff --git a/apps/editor/public/icons/column-presets/xBraceSupport.webp b/apps/editor/public/icons/column-presets/xBraceSupport.webp new file mode 100644 index 0000000000..5190386c68 Binary files /dev/null and b/apps/editor/public/icons/column-presets/xBraceSupport.webp differ diff --git a/apps/editor/public/icons/column-presets/yFrameSupport.webp b/apps/editor/public/icons/column-presets/yFrameSupport.webp new file mode 100644 index 0000000000..866ddd005e Binary files /dev/null and b/apps/editor/public/icons/column-presets/yFrameSupport.webp differ diff --git a/apps/editor/public/icons/elevator-presets/glass.webp b/apps/editor/public/icons/elevator-presets/glass.webp new file mode 100644 index 0000000000..a9ff2b40a8 Binary files /dev/null and b/apps/editor/public/icons/elevator-presets/glass.webp differ diff --git a/apps/editor/public/icons/elevator-presets/passenger.webp b/apps/editor/public/icons/elevator-presets/passenger.webp new file mode 100644 index 0000000000..1210322222 Binary files /dev/null and b/apps/editor/public/icons/elevator-presets/passenger.webp differ diff --git a/apps/editor/public/icons/elevator-presets/service.webp b/apps/editor/public/icons/elevator-presets/service.webp new file mode 100644 index 0000000000..edf46e2809 Binary files /dev/null and b/apps/editor/public/icons/elevator-presets/service.webp differ diff --git a/apps/ifc-converter/AGENTS.md b/apps/ifc-converter/AGENTS.md index 643577dfae..af3b7c8411 100644 --- a/apps/ifc-converter/AGENTS.md +++ b/apps/ifc-converter/AGENTS.md @@ -1,6 +1,6 @@ -# This is NOT the Next.js you know +## This is NOT the Next.js you know This version has breaking changes — APIs, conventions, and file structure may all differ from your training data. Read the relevant guide in `node_modules/next/dist/docs/` (resolved from this file's directory; in monorepos the `next` package may not be visible from the repo root) before writing any code. Heed deprecation notices. diff --git a/i18n/literal-baseline.json b/i18n/literal-baseline.json index 415522eff5..c04b90fbcb 100644 --- a/i18n/literal-baseline.json +++ b/i18n/literal-baseline.json @@ -416,9 +416,6 @@ "part", "parts" ], - "packages/editor/src/components/ui/controls/slider-control.tsx": [ - "Mixed" - ], "packages/editor/src/components/ui/controls/terrain-sculpt-panel.tsx": [ "Clear terrain", "Click the ground to pick its height as the target.", diff --git a/packages/core/src/contracts/reference-inventory.ts b/packages/core/src/contracts/reference-inventory.ts index 8fec01c12e..9bbccb342f 100644 --- a/packages/core/src/contracts/reference-inventory.ts +++ b/packages/core/src/contracts/reference-inventory.ts @@ -1074,7 +1074,6 @@ export const METADATA_NON_REFERENCES: readonly { path: string; reason: string }[ 'porch', 'renderPass', 'role', - 'showTrimPlanes', 'storyShell', 'suppressedDimensionSegmentIndexes', ]), diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index fd3ccc72ef..5dd1ca71b7 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -834,7 +834,13 @@ export { useRegistryVersion } from './registry/use-registry-version' export * from './schema' export * from './schema/nodes/stair-defaults' export * from './services' -export { isMovable, movePlanToward, moveToward, resolveMovable } from './services/movement' +export { + isMovable, + isMoveLocked, + movePlanToward, + moveToward, + resolveMovable, +} from './services/movement' export * from './services/project-file-sink' export { collectionIdsOf, @@ -948,6 +954,9 @@ export { } from './store/use-scene' export { resolveElevatorDispatchTarget } from './systems/elevator/elevator-dispatch' export { + ELEVATOR_MIN_CAB_DIMENSION, + ELEVATOR_MIN_CAB_HEIGHT, + ELEVATOR_MIN_WALL_THICKNESS, type ElevatorDoorSide, getElevatorCabCenterZ, getElevatorCabDepth, @@ -961,6 +970,8 @@ export { getResolvedElevatorDoorPanelStyle, getResolvedElevatorDoorStyle, getResolvedElevatorShaftStyle, + normalizeElevatorDimensions, + resolveElevatorDimensions, } from './systems/elevator/elevator-geometry' export { syncAutoElevatorOpenings } from './systems/elevator/elevator-opening-sync' export { ElevatorOpeningSystem } from './systems/elevator/elevator-opening-system' diff --git a/packages/core/src/node-slots/column.ts b/packages/core/src/node-slots/column.ts index a70cb1623e..dc35748ab8 100644 --- a/packages/core/src/node-slots/column.ts +++ b/packages/core/src/node-slots/column.ts @@ -8,6 +8,17 @@ export const COLUMN_BASE_DEFAULT = 'library:concrete-plaster' export const COLUMN_CAPITAL_DEFAULT = 'library:concrete-plaster' export const COLUMN_FRAME_DEFAULT = 'library:metal-steel' +/** + * Written onto newly created columns. The slot defaults above stay the render + * fallback, so saved columns that never had `slots` keep their look (E-003). + */ +export const NEW_COLUMN_SLOTS: Readonly> = { + shaft: 'library:preset-white', + base: 'library:preset-white', + capital: 'library:preset-white', + frame: 'library:preset-white', +} + export function columnSlots(node: ColumnNode): SlotDeclaration[] { if (node.source) return node.source.manifest.slots.map((slot) => ({ diff --git a/packages/core/src/registry/index.ts b/packages/core/src/registry/index.ts index 30f42f591d..dfba788bb7 100644 --- a/packages/core/src/registry/index.ts +++ b/packages/core/src/registry/index.ts @@ -38,6 +38,7 @@ export { hasRegistry3DMoveTool, isDrawnViaTool, isDrawnViaToolKind, + isNodeDuplicable, isNodeKindEnabled, isPresettable, isPresettableKind, diff --git a/packages/core/src/registry/registry.ts b/packages/core/src/registry/registry.ts index 93eb525481..42a82448b3 100644 --- a/packages/core/src/registry/registry.ts +++ b/packages/core/src/registry/registry.ts @@ -318,6 +318,16 @@ export function isRegistryMovable(kind: string): boolean { return false } +/** + * Whether Duplicate, copy and paste may clone this node: its kind is not + * `duplicable: false` and its `duplicable.allow` (if any) accepts it. + */ +export function isNodeDuplicable(node: AnyNode): boolean { + const duplicable = nodeRegistry.get(node.type)?.capabilities.duplicable + if (duplicable === false) return false + return typeof duplicable === 'object' && duplicable.allow ? duplicable.allow({ node }) : true +} + /** * Whether the kind has a move tool that MOUNTS in the 3D viewport — the * generic `capabilities.movable` mover or a bespoke `affordanceTools.move`. diff --git a/packages/core/src/registry/types.ts b/packages/core/src/registry/types.ts index 9aa916e011..fdafa42949 100644 --- a/packages/core/src/registry/types.ts +++ b/packages/core/src/registry/types.ts @@ -1700,6 +1700,8 @@ export type DuplicableConfig = { /** 'with-children' preserves the root-only draft lifecycle for childless nodes. */ subtree?: boolean | 'with-children' prepareSubtreeClone?: (args: DuplicateSubtreeCloneArgs) => DuplicateSubtreeCloneResult + /** Per-node opt-out, e.g. a post its lean-to generates and counts itself. */ + allow?: (args: { node: AnyNode }) => boolean } // ─── Capabilities ──────────────────────────────────────────────────── @@ -2277,6 +2279,12 @@ export type CapabilityCtx = { node: AnyNode } export type CutsContext = { nodes: Readonly> } export type MovableConfig = { + /** Resolve the stored pose after snapping, during preview and again on commit. */ + resolvePosition?: (args: { + node: AnyNode + position: [number, number, number] + nodes: Readonly> + }) => [number, number, number] axes: ReadonlyArray<'x' | 'y' | 'z'> gridSnap?: boolean /** Keep an existing floor-placed node on its current level and visual elevation while dragging. */ diff --git a/packages/core/src/schema/index.ts b/packages/core/src/schema/index.ts index c9dffa9c5b..675ff11c45 100644 --- a/packages/core/src/schema/index.ts +++ b/packages/core/src/schema/index.ts @@ -380,6 +380,8 @@ export { getSegmentSlopeFrame, hasSegmentMaterialOverride, isBandedShedSegment, + MAX_ROOF_PITCH, + MIN_ROOF_SEGMENT_DIMENSION, MIN_ROOF_SEGMENT_TRIM_SPAN, normalizeRoofSegmentTrim, ROOF_SHAPE_DEFAULTS, diff --git a/packages/core/src/schema/nodes/roof-segment-resize.ts b/packages/core/src/schema/nodes/roof-segment-resize.ts index 69d3e1bc53..2160bb650a 100644 --- a/packages/core/src/schema/nodes/roof-segment-resize.ts +++ b/packages/core/src/schema/nodes/roof-segment-resize.ts @@ -1,6 +1,7 @@ import { getActiveRoofHeight, getPitchFromActiveRoofHeight, + MAX_ROOF_PITCH, type RoofSegmentNode, } from './roof-segment' @@ -25,5 +26,5 @@ export function getRoofSegmentResizePatch( if (node.roofType === 'barrel') return { depth: dimension, barrelRise: Math.min(dimension / 2, rise), position } const pitch = getPitchFromActiveRoofHeight({ ...node, depth: dimension, roofHeight: rise }) - return { depth: dimension, pitch: Math.max(0, Math.min(85, pitch)), position } + return { depth: dimension, pitch: Math.max(0, Math.min(MAX_ROOF_PITCH, pitch)), position } } diff --git a/packages/core/src/schema/nodes/roof-segment-surface.test.ts b/packages/core/src/schema/nodes/roof-segment-surface.test.ts index 57bec7db01..71228e7841 100644 --- a/packages/core/src/schema/nodes/roof-segment-surface.test.ts +++ b/packages/core/src/schema/nodes/roof-segment-surface.test.ts @@ -1,5 +1,10 @@ import { describe, expect, test } from 'bun:test' -import { getRoofSegmentSurfaceY, ROOF_SHAPE_DEFAULTS, RoofSegmentNode } from './roof-segment' +import { + getActiveRoofHeight, + getRoofSegmentSurfaceY, + ROOF_SHAPE_DEFAULTS, + RoofSegmentNode, +} from '@pascal-app/core' describe('getRoofSegmentSurfaceY', () => { test('falls linearly from a conical apex in every radial direction', () => { @@ -79,3 +84,42 @@ describe('getRoofSegmentSurfaceY', () => { expect(getRoofSegmentSurfaceY(segment, localX, localZ)).toBeCloseTo(expected, 6) }) }) + +test('gambrel surface follows its lower and upper slopes across the kink', () => { + const node = RoofSegmentNode.parse({ + roofType: 'gambrel', + width: 10, + depth: 8, + wallHeight: 0, + pitch: 45, + }) + const peak = getActiveRoofHeight(node) + expect(getRoofSegmentSurfaceY(node, 0, 3)).toBeCloseTo(1, 6) + expect(getRoofSegmentSurfaceY(node, 0, 2)).toBeCloseTo(2, 6) + expect(getRoofSegmentSurfaceY(node, 0, 1)).toBeCloseTo((peak + 2) / 2, 6) +}) + +test('mansard surface includes the shoulder and a ridge on rectangular footprints', () => { + const node = RoofSegmentNode.parse({ + roofType: 'mansard', + width: 12, + depth: 8, + wallHeight: 0, + pitch: 45, + }) + const peak = getActiveRoofHeight(node) + expect(getRoofSegmentSurfaceY(node, 0, 3.4)).toBeCloseTo(0.6, 6) + expect(getRoofSegmentSurfaceY(node, 0, 2.8)).toBeCloseTo(1.2, 6) + expect(getRoofSegmentSurfaceY(node, 1, 0)).toBeCloseTo(peak, 6) + expect(getRoofSegmentSurfaceY(node, 5.4, 0)).toBeCloseTo(0.6, 6) +}) + +test('rectangular hip surface stays at crown height along the ridge in either orientation', () => { + for (const [width, depth, x, z] of [ + [10, 6, 1, 0], + [6, 10, 0, 1], + ]) { + const node = RoofSegmentNode.parse({ roofType: 'hip', width, depth, wallHeight: 0, pitch: 45 }) + expect(getRoofSegmentSurfaceY(node, x!, z!)).toBeCloseTo(3, 6) + } +}) diff --git a/packages/core/src/schema/nodes/roof-segment.ts b/packages/core/src/schema/nodes/roof-segment.ts index b64eea2d2d..9af6df02d6 100644 --- a/packages/core/src/schema/nodes/roof-segment.ts +++ b/packages/core/src/schema/nodes/roof-segment.ts @@ -6,10 +6,13 @@ import type { MaterialSchema as MaterialSchemaType } from '../material' import { MaterialSchema } from '../material' import { getBarrelRoofProfile } from './barrel-roof' import { RoofGlazing, RoofSystemType } from './roof-glazing' +import { getRoofModuleFaces, getRoofShapeRatios } from './roof-segment-shape' import { RoofEaveCut, RoofType } from './roof-types' export { RoofEaveCut, RoofType } from './roof-types' export const MIN_ROOF_SEGMENT_TRIM_SPAN = 0.1 +export const MIN_ROOF_SEGMENT_DIMENSION = 0.5 +export const MAX_ROOF_PITCH = 85 const DEFAULT_ROOF_SEGMENT_WIDTH = 8 const DEFAULT_ROOF_SEGMENT_DEPTH = 6 @@ -134,7 +137,7 @@ export const RoofSegmentNode = BaseNode.extend({ // For gable/hip/shed this is the only slope; for gambrel/mansard/dutch // it is the steep (lower) slope. The overall peak height is derived // from pitch + footprint + roofType via getActiveRoofHeight(). - pitch: z.number().min(0).max(85).default(40), + pitch: z.number().min(0).max(MAX_ROOF_PITCH).default(40), // Structure thicknesses wallThickness: z.number().default(0.1), deckThickness: z.number().default(0.1), @@ -787,7 +790,40 @@ export function getRoofSegmentSurfaceY( const peakY = node.wallHeight + activeRh if (activeRh === 0) return node.wallHeight - if (node.roofType === 'gable' || node.roofType === 'gambrel' || node.roofType === 'mansard') { + if (node.roofType === 'gambrel' || node.roofType === 'mansard' || node.roofType === 'hip') { + const faces = getRoofModuleFaces({ + type: node.roofType, + w: node.width, + d: node.depth, + wh: node.wallHeight, + rh: activeRh, + baseY: node.wallHeight - 1, + baseW: node.width, + baseD: node.depth, + tanTheta: slopeFrame.tanTheta, + insets: {}, + shapeRatios: getRoofShapeRatios(node), + }) + let top: number | undefined + for (const face of faces) { + const a = face[0] + if (!a) continue + for (let i = 1; i + 1 < face.length; i++) { + const b = face[i]!, + c = face[i + 1]! + const determinant = (b.z - c.z) * (a.x - c.x) + (c.x - b.x) * (a.z - c.z) + if (Math.abs(determinant) < 1e-10) continue + const u = ((b.z - c.z) * (localX - c.x) + (c.x - b.x) * (localZ - c.z)) / determinant + const v = ((c.z - a.z) * (localX - c.x) + (a.x - c.x) * (localZ - c.z)) / determinant + if (u < -1e-8 || v < -1e-8 || u + v > 1 + 1e-8) continue + const y = u * a.y + v * b.y + (1 - u - v) * c.y + top = top === undefined ? y : Math.max(top, y) + } + } + if (top !== undefined) return top + } + + if (node.roofType === 'gable') { const t = node.depth > 0 ? Math.abs(localZ) / (node.depth / 2) : 0 return peakY - t * activeRh } diff --git a/packages/core/src/services/drag-session.test.ts b/packages/core/src/services/drag-session.test.ts index 5852dc7734..23ce48c04e 100644 --- a/packages/core/src/services/drag-session.test.ts +++ b/packages/core/src/services/drag-session.test.ts @@ -1,4 +1,4 @@ -import { beforeEach, describe, expect, mock, test } from 'bun:test' +import { afterEach, beforeEach, describe, expect, mock, test } from 'bun:test' import { z } from 'zod' import { nodeRegistry, registerNode } from '../registry/registry' import type { AnyNodeDefinition, DragAction, Relations, SceneApi } from '../registry/types' @@ -81,9 +81,12 @@ function makeAction(): DragAction<{ id: AnyNodeId }, { x: number }> { } describe('createDragSession', () => { + let restoreRegistry = () => {} beforeEach(() => { + restoreRegistry = nodeRegistry._snapshot() nodeRegistry._reset() }) + afterEach(() => restoreRegistry()) test('start pauses history; commit resumes', () => { const scene = makeSpyScene() diff --git a/packages/core/src/services/movement.ts b/packages/core/src/services/movement.ts index 3e8e38a26f..4616268b6d 100644 --- a/packages/core/src/services/movement.ts +++ b/packages/core/src/services/movement.ts @@ -97,3 +97,16 @@ export function isMovable(node: AnyNode): boolean { const config = resolveMovable(node) return config != null && config.axes.length > 0 } + +/** + * True when the node's `movable.override` locks this particular node (a lean-to + * post, a cabinet run behind its selection proxy). The lock outranks the kind's + * other movers — `floorplanMoveTarget`, `affordanceTools.move`, group pick-up — + * which only know the kind, not the node. + */ +export function isMoveLocked(node: AnyNode): boolean { + const base = nodeRegistry.get(node.type)?.capabilities.movable + if (!base?.override) return false + const config = resolveMovable(node) + return config !== base && config !== null && config.axes.length === 0 +} diff --git a/packages/core/src/systems/elevator/elevator-geometry.ts b/packages/core/src/systems/elevator/elevator-geometry.ts index ad7fe62cd7..ff2d86afcb 100644 --- a/packages/core/src/systems/elevator/elevator-geometry.ts +++ b/packages/core/src/systems/elevator/elevator-geometry.ts @@ -8,6 +8,9 @@ import type { export type ElevatorDoorSide = 'left' | 'right' const DEFAULT_ELEVATOR_SHAFT_WALL_THICKNESS = 0.09 +export const ELEVATOR_MIN_CAB_DIMENSION = 0.8 +export const ELEVATOR_MIN_CAB_HEIGHT = 1.8 +export const ELEVATOR_MIN_WALL_THICKNESS = 0.04 export function getResolvedElevatorDoorStyle( doorStyle: ElevatorNode['doorStyle'] | undefined, @@ -43,13 +46,14 @@ export function getElevatorDoorLeafX( doorStyle: ElevatorNode['doorStyle'] | undefined, ) { const resolvedDoorStyle = getResolvedElevatorDoorStyle(doorStyle) + const amount = Math.min(1, Math.max(0, doorOpen)) + const leafWidth = getElevatorDoorLeafWidth(openingWidth, doorStyle) + const openCenter = (openingWidth + leafWidth) / 2 if (resolvedDoorStyle === 'center-opening') { const direction = side === 'left' ? -1 : 1 - return direction * (openingWidth / 4 + doorOpen * openingWidth * 0.34) + return direction * (openingWidth / 4 + amount * (openCenter - openingWidth / 4)) } - - const direction = resolvedDoorStyle === 'single-left' ? -1 : 1 - return direction * doorOpen * openingWidth * 0.68 + return (resolvedDoorStyle === 'single-left' ? -1 : 1) * amount * openCenter } export function getElevatorDoorLeafWidth( @@ -62,25 +66,57 @@ export function getElevatorDoorLeafWidth( } export function getElevatorCabWidth(node: ElevatorNode) { - return Math.max(node.width, 0.8) + return Math.max(node.width, ELEVATOR_MIN_CAB_DIMENSION) } export function getElevatorCabDepth(node: ElevatorNode) { - return Math.max(node.depth, 0.8) + return Math.max(node.depth, ELEVATOR_MIN_CAB_DIMENSION) } export function getElevatorShaftWallThickness(node: ElevatorNode) { - return Math.max(node.shaftWallThickness ?? DEFAULT_ELEVATOR_SHAFT_WALL_THICKNESS, 0.04) + return Math.max( + node.shaftWallThickness ?? DEFAULT_ELEVATOR_SHAFT_WALL_THICKNESS, + ELEVATOR_MIN_WALL_THICKNESS, + ) } export function getElevatorShaftWidth(node: ElevatorNode, cabWidth = getElevatorCabWidth(node)) { - return Math.max(node.shaftWidth ?? cabWidth, cabWidth, 0.8) + return Math.max(node.shaftWidth ?? cabWidth, cabWidth, ELEVATOR_MIN_CAB_DIMENSION) } export function getElevatorShaftDepth(node: ElevatorNode, cabDepth = getElevatorCabDepth(node)) { - return Math.max(node.shaftDepth ?? cabDepth, cabDepth, 0.8) + return Math.max(node.shaftDepth ?? cabDepth, cabDepth, ELEVATOR_MIN_CAB_DIMENSION) } export function getElevatorCabCenterZ(node: ElevatorNode) { return -getElevatorShaftDepth(node) / 2 + getElevatorCabDepth(node) / 2 } + +/** Shared effective dimensions keep legacy scenes readable without rewriting stored data. */ +export function resolveElevatorDimensions(node: ElevatorNode) { + const width = getElevatorCabWidth(node) + const depth = getElevatorCabDepth(node) + const cabHeight = Math.max(node.cabHeight, ELEVATOR_MIN_CAB_HEIGHT) + const shaftWidth = getElevatorShaftWidth(node, width) + const shaftDepth = getElevatorShaftDepth(node, depth) + return { + width, + depth, + cabHeight, + shaftWidth, + shaftDepth, + shaftWallThickness: getElevatorShaftWallThickness(node), + doorWidth: Math.min(Math.max(node.doorWidth, 0.45), width - 0.18, shaftWidth - 0.18), + doorHeight: Math.min(Math.max(node.doorHeight, 1.2), cabHeight - 0.1), + } +} + +/** Apply on dimension edits only; absent shaft dimensions retain automatic cab sizing. */ +export function normalizeElevatorDimensions(node: ElevatorNode) { + const dimensions = resolveElevatorDimensions(node) + return { + ...dimensions, + shaftWidth: node.shaftWidth === undefined ? undefined : dimensions.shaftWidth, + shaftDepth: node.shaftDepth === undefined ? undefined : dimensions.shaftDepth, + } +} diff --git a/packages/core/src/systems/elevator/elevator-opening-sync.test.ts b/packages/core/src/systems/elevator/elevator-opening-sync.test.ts index ca476072f2..d1b992c2c1 100644 --- a/packages/core/src/systems/elevator/elevator-opening-sync.test.ts +++ b/packages/core/src/systems/elevator/elevator-opening-sync.test.ts @@ -160,3 +160,52 @@ describe('syncAutoElevatorOpenings', () => { expect(slabUpdate?.data.holeMetadata).toEqual([{ source: 'manual' }]) }) }) + +for (const legacyParent of [false, true]) { + test(`elevator openings stay inside the owning building with legacy parenting ${legacyParent}`, () => { + const a = BuildingNode.parse({}) + const b = BuildingNode.parse({}) + const groundA = LevelNode.parse({ parentId: a.id, level: 0 }) + const upperA = LevelNode.parse({ parentId: a.id, level: 1 }) + const groundB = LevelNode.parse({ parentId: b.id, level: 0 }) + const upperB = LevelNode.parse({ parentId: b.id, level: 1 }) + const elevator = ElevatorNode.parse({ + parentId: legacyParent ? groundA.id : a.id, + fromLevelId: groundA.id, + toLevelId: upperA.id, + }) + a.children = [groundA.id, upperA.id, ...(legacyParent ? [] : [elevator.id])] + b.children = [groundB.id, upperB.id] + if (legacyParent) groundA.children = [elevator.id] + const polygon: [number, number][] = [ + [-5, -5], + [5, -5], + [5, 5], + [-5, 5], + ] + const ownSlab = SlabNode.parse({ parentId: upperA.id, polygon }) + const ownCeiling = CeilingNode.parse({ parentId: groundA.id, polygon }) + const otherSlab = SlabNode.parse({ parentId: upperB.id, polygon }) + const otherCeiling = CeilingNode.parse({ parentId: groundB.id, polygon }) + const nodes = Object.fromEntries( + [ + a, + b, + groundA, + upperA, + groundB, + upperB, + elevator, + ownSlab, + ownCeiling, + otherSlab, + otherCeiling, + ].map((n) => [n.id, n]), + ) + const ids = syncAutoElevatorOpenings(nodes).map((update) => update.id) + expect(ids).toContain(ownSlab.id) + expect(ids).toContain(ownCeiling.id) + expect(ids).not.toContain(otherSlab.id) + expect(ids).not.toContain(otherCeiling.id) + }) +} diff --git a/packages/core/src/systems/elevator/elevator-opening-sync.ts b/packages/core/src/systems/elevator/elevator-opening-sync.ts index 1c42e873ae..aa7e1e8160 100644 --- a/packages/core/src/systems/elevator/elevator-opening-sync.ts +++ b/packages/core/src/systems/elevator/elevator-opening-sync.ts @@ -90,39 +90,14 @@ function isCoveredByExistingHole(existingHoles: Point2D[][], autoHole: Point2D[] return existingHoles.some((existingHole) => polygonContainsPolygon(existingHole, autoHole)) } -function getServedLevelRange(elevator: ElevatorNode, nodes: Record) { - const servedLevels = resolveElevatorServiceLevels(elevator, nodes) - if (servedLevels.length < 2) return null - - const levelNumbers = servedLevels.map((level) => level.level) - return { - max: Math.max(...levelNumbers), - min: Math.min(...levelNumbers), - sortedServedLevels: servedLevels, - } -} - -function getLevelNumber(levelId: string | null, nodes: Record) { - if (!levelId) return - const node = nodes[levelId as AnyNodeId] - return node?.type === 'level' ? node.level : undefined -} - function shouldApplyElevatorToSlab( elevator: ElevatorNode, slabLevelId: string, nodes: Record, ) { - const range = getServedLevelRange(elevator, nodes) - if (!range) return false - - const slabLevel = getLevelNumber(slabLevelId, nodes) - if (slabLevel !== undefined) { - return slabLevel > range.min && slabLevel <= range.max - } - - const servedIndex = range.sortedServedLevels.findIndex((level) => level.id === slabLevelId) - return servedIndex > 0 + return ( + resolveElevatorServiceLevels(elevator, nodes).findIndex((level) => level.id === slabLevelId) > 0 + ) } function shouldApplyElevatorToCeiling( @@ -130,16 +105,9 @@ function shouldApplyElevatorToCeiling( ceilingLevelId: string, nodes: Record, ) { - const range = getServedLevelRange(elevator, nodes) - if (!range) return false - - const ceilingLevel = getLevelNumber(ceilingLevelId, nodes) - if (ceilingLevel !== undefined) { - return ceilingLevel >= range.min && ceilingLevel < range.max - } - - const servedIndex = range.sortedServedLevels.findIndex((level) => level.id === ceilingLevelId) - return servedIndex >= 0 && servedIndex < range.sortedServedLevels.length - 1 + const levels = resolveElevatorServiceLevels(elevator, nodes) + const index = levels.findIndex((level) => level.id === ceilingLevelId) + return index >= 0 && index < levels.length - 1 } function getElevatorOpeningPolygon(elevator: ElevatorNode): Point2D[] { diff --git a/packages/core/src/systems/elevator/elevator-runtime.test.ts b/packages/core/src/systems/elevator/elevator-runtime.test.ts index 43e714df4d..72c5ec5cda 100644 --- a/packages/core/src/systems/elevator/elevator-runtime.test.ts +++ b/packages/core/src/systems/elevator/elevator-runtime.test.ts @@ -1,10 +1,13 @@ import { describe, expect, test } from 'bun:test' import type { AnyNodeId } from '../../schema' -import { ElevatorNode } from '../../schema' +import { BuildingNode, ElevatorNode, LevelNode } from '../../schema' +import { useInteractive } from '../../store/use-interactive' +import useScene from '../../store/use-scene' import { createElevatorInteractiveState, openElevatorDoorState, queueElevatorRequest, + requestElevatorLevel, stepElevatorRuntimeState, } from './elevator-runtime' import type { ElevatorLevelEntry } from './elevator-service' @@ -83,3 +86,106 @@ describe('elevator runtime helpers', () => { expect(open.requestedStops).toEqual([upperLevelId]) }) }) + +test('stationary cab follows edits to its level elevation', () => { + const state = createElevatorInteractiveState(groundLevelId, 0) + const changedEntries = entries.map((entry) => ({ ...entry, baseY: entry.baseY + 1 })) + const next = stepElevatorRuntimeState({ + defaultEntry: changedEntries[0]!, + entries: changedEntries, + elevator, + now: 1, + delta: 0.016, + state, + }) + expect(next.carY).toBe(1) + expect(next.phase).toBe('idle') +}) + +test('a disabled destination is removed and a moving cab returns to an available landing', () => { + const state = { + ...createElevatorInteractiveState(groundLevelId, 0), + carY: 1, + phase: 'moving' as const, + targetLevelId: upperLevelId, + queue: [upperLevelId], + requestedStops: [upperLevelId], + } + const next = stepElevatorRuntimeState({ + defaultEntry: entries[0]!, + entries, + elevator: { ...elevator, disabledLevelIds: [upperLevelId] }, + now: 1, + delta: 0.01, + state, + }) + expect(next.targetLevelId).toBe(groundLevelId) + expect(next.carY).toBeLessThan(1) + expect(next.queue).not.toContain(upperLevelId) + expect(next.requestedStops).not.toContain(upperLevelId) +}) + +test('removing the current landing reconciles the cab to a served landing', () => { + const next = stepElevatorRuntimeState({ + defaultEntry: entries[1]!, + entries: [entries[1]!], + elevator, + now: 1, + delta: 0.016, + state: createElevatorInteractiveState(groundLevelId, 0), + }) + expect(next.currentLevelId).toBe(upperLevelId) + expect(next.carY).toBe(entries[1]!.baseY) + expect(next.queue).toEqual([]) + expect(next.doorOpen).toBe(0) +}) + +test('requests reject disabled and unserved stops but permit service-only cab stops', () => { + const before = useScene.getState().nodes + const interactiveBefore = useInteractive.getState().elevators + try { + const building = BuildingNode.parse({}) + const levels = [0, 1, 2].map((level) => LevelNode.parse({ parentId: building.id, level })) + const node = ElevatorNode.parse({ + parentId: building.id, + fromLevelId: levels[0]!.id, + toLevelId: levels[1]!.id, + disabledLevelIds: [levels[1]!.id], + }) + building.children = [...levels.map((level) => level.id), node.id] + useScene.setState({ + nodes: Object.fromEntries([building, ...levels, node].map((n) => [n.id, n])), + }) + requestElevatorLevel(node.id, levels[1]!.id) + requestElevatorLevel(node.id, levels[2]!.id) + expect(useInteractive.getState().elevators[node.id]?.queue ?? []).toEqual([]) + useScene.setState({ + nodes: { + ...useScene.getState().nodes, + [node.id]: { ...node, disabledLevelIds: [], serviceOnlyLevelIds: [levels[1]!.id] }, + }, + }) + requestElevatorLevel(node.id, levels[1]!.id) + expect(useInteractive.getState().elevators[node.id]?.queue).toEqual([levels[1]!.id]) + } finally { + useScene.setState({ nodes: before }) + useInteractive.setState({ elevators: interactiveBefore }) + } +}) + +test('an idle cab on a landing that becomes disabled leaves for the nearest available landing', () => { + const disabledUpper = { ...elevator, disabledLevelIds: [upperLevelId] } + let state = createElevatorInteractiveState(upperLevelId, 2.5) + for (let tick = 0; tick < 10 && state.currentLevelId !== groundLevelId; tick++) { + state = stepElevatorRuntimeState({ + defaultEntry: entries[0]!, + entries, + elevator: disabledUpper, + now: tick, + delta: 0.1, + state, + }) + } + expect(state.currentLevelId).toBe(groundLevelId) + expect(state.carY).toBe(0) +}) diff --git a/packages/core/src/systems/elevator/elevator-runtime.ts b/packages/core/src/systems/elevator/elevator-runtime.ts index 7278dea0df..d3b4ba35ed 100644 --- a/packages/core/src/systems/elevator/elevator-runtime.ts +++ b/packages/core/src/systems/elevator/elevator-runtime.ts @@ -34,7 +34,13 @@ function getInitialElevatorState( const node = nodes[elevatorId] if (node?.type !== 'elevator') return null - const { defaultEntry } = resolveElevatorLevels(node, nodes) + const { entries, defaultEntry: configuredDefault } = resolveElevatorLevels(node, nodes) + const defaultEntry = + entries.find( + (entry) => entry.id === configuredDefault?.id && !node.disabledLevelIds.includes(entry.id), + ) ?? + entries.find((entry) => !node.disabledLevelIds.includes(entry.id)) ?? + configuredDefault if (!defaultEntry) return null return createElevatorInteractiveState(defaultEntry.id as AnyNodeId, defaultEntry.baseY) @@ -83,6 +89,9 @@ export function openElevatorDoorState(state: ElevatorInteractiveState): Elevator export function requestElevatorLevel(elevatorId: AnyNodeId, levelId: AnyNodeId) { const nodes = useScene.getState().nodes + const node = nodes[elevatorId] + if (node?.type !== 'elevator' || node.disabledLevelIds.includes(levelId)) return + if (!resolveElevatorLevels(node, nodes).entries.some((entry) => entry.id === levelId)) return const current = ensureElevatorState(elevatorId, nodes) if (!current) return @@ -97,6 +106,17 @@ export function openElevatorDoor(elevatorId: AnyNodeId) { const current = ensureElevatorState(elevatorId, nodes) if (!current) return + const node = nodes[elevatorId] + if ( + node?.type !== 'elevator' || + !current.currentLevelId || + node.disabledLevelIds.includes(current.currentLevelId) + ) + return + if ( + !resolveElevatorLevels(node, nodes).entries.some((entry) => entry.id === current.currentLevelId) + ) + return const next = openElevatorDoorState(current) if (next === current) return @@ -118,19 +138,79 @@ export function stepElevatorRuntimeState({ now: number state: ElevatorInteractiveState }): ElevatorInteractiveState { - const currentEntry = entries.find((entry) => entry.id === state.currentLevelId) ?? defaultEntry - if (currentEntry.id !== state.currentLevelId) { - return { + const stationaryEntry = entries.find((entry) => entry.id === state.currentLevelId) + if ( + state.phase === 'idle' && + !state.queue.length && + !state.requestedStops.length && + !state.targetLevelId && + state.doorOpen === 0 && + stationaryEntry?.baseY === state.carY && + !elevator.disabledLevelIds.includes(stationaryEntry.id) + ) + return state + const available = entries.filter((entry) => !elevator.disabledLevelIds.includes(entry.id)) + const nearestAvailable = () => + available.reduce( + (nearest, entry) => + !nearest || Math.abs(entry.baseY - state.carY) < Math.abs(nearest.baseY - state.carY) + ? entry + : nearest, + null, + ) + const fallback = + available.find((entry) => entry.id === defaultEntry.id) ?? available[0] ?? defaultEntry + const currentEntry = entries.find((entry) => entry.id === state.currentLevelId) + if (!currentEntry) { + return createElevatorInteractiveState(fallback.id as AnyNodeId, fallback.baseY) + } + const canServe = (id: AnyNodeId) => available.some((entry) => entry.id === id) + const queue = state.queue.filter(canServe) + const requestedStops = state.requestedStops.filter(canServe) + if ( + queue.length !== state.queue.length || + requestedStops.length !== state.requestedStops.length + ) { + state = { ...state, queue, requestedStops } + } + if (state.targetLevelId && !canServe(state.targetLevelId)) { + const destination = state.phase === 'moving' ? nearestAvailable() : null + state = { ...state, - currentLevelId: currentEntry.id as AnyNodeId, - carY: currentEntry.baseY, - targetLevelId: null, - phase: 'idle', - phaseStartedAt: null, - queue: [], - requestedStops: [], - doorOpen: 0, + targetLevelId: (destination?.id as AnyNodeId) ?? null, + ...(destination + ? { + queue: [ + destination.id as AnyNodeId, + ...state.queue.filter((id) => id !== destination.id), + ], + } + : {}), } + if (state.phase === 'moving' && !destination) { + return { + ...createElevatorInteractiveState(currentEntry.id as AnyNodeId, currentEntry.baseY), + doorOpen: 0, + } + } + } + if (state.phase !== 'moving' && Math.abs(state.carY - currentEntry.baseY) > EPSILON) { + state = { ...state, carY: currentEntry.baseY } + } + if ( + elevator.disabledLevelIds.includes(currentEntry.id) && + (state.phase === 'open' || state.phase === 'opening') + ) { + state = { ...state, phase: 'closing', phaseStartedAt: now } + } + if ( + elevator.disabledLevelIds.includes(currentEntry.id) && + state.phase !== 'moving' && + !state.targetLevelId && + !state.queue.length + ) { + const destination = nearestAvailable() + if (destination) state = { ...state, queue: [destination.id as AnyNodeId] } } const targetEntry = state.targetLevelId @@ -234,6 +314,22 @@ export function stepElevatorRuntimeState({ } } +const runtimeConfigurations = new WeakMap< + Record, + Array<{ node: ElevatorNode; levels: ReturnType }> +>() + +function elevatorConfigurations(nodes: Record) { + let configurations = runtimeConfigurations.get(nodes) + if (!configurations) { + configurations = Object.values(nodes) + .filter((node): node is ElevatorNode => node.type === 'elevator') + .map((node) => ({ node, levels: resolveElevatorLevels(node, nodes) })) + runtimeConfigurations.set(nodes, configurations) + } + return configurations +} + export function stepElevatorRuntimes(now: number, delta: number) { const nodes = useScene.getState().nodes const interactive = useInteractive.getState() @@ -245,18 +341,25 @@ export function stepElevatorRuntimes(now: number, delta: number) { } } - for (const node of Object.values(nodes)) { - if (node.type !== 'elevator') continue - + for (const { node, levels } of elevatorConfigurations(nodes)) { const elevatorId = node.id as AnyNodeId - const { entries, defaultEntry } = resolveElevatorLevels(node, nodes) - if (!defaultEntry) continue + const { entries, defaultEntry } = levels + if (!defaultEntry) { + if (useInteractive.getState().elevators[elevatorId]) interactive.removeElevator(elevatorId) + continue + } const state = useInteractive.getState().elevators[elevatorId] if (!state) { + const initialEntry = + entries.find( + (entry) => entry.id === defaultEntry.id && !node.disabledLevelIds.includes(entry.id), + ) ?? + entries.find((entry) => !node.disabledLevelIds.includes(entry.id)) ?? + defaultEntry useInteractive .getState() - .initElevator(elevatorId, defaultEntry.id as AnyNodeId, defaultEntry.baseY) + .initElevator(elevatorId, initialEntry.id as AnyNodeId, initialEntry.baseY) continue } diff --git a/packages/core/src/systems/elevator/elevator-service.test.ts b/packages/core/src/systems/elevator/elevator-service.test.ts index baf250c93f..1fbb472308 100644 --- a/packages/core/src/systems/elevator/elevator-service.test.ts +++ b/packages/core/src/systems/elevator/elevator-service.test.ts @@ -43,7 +43,7 @@ describe('resolveElevatorLevels', () => { levels.map((level) => stacked.get(level.id)?.baseY), ) expect(resolved.shaftBaseY).toBe(stacked.get('level_0')?.baseY) - expect(resolved.shaftTopY).toBeCloseTo(8.2) + expect(resolved.shaftTopY).toBeCloseTo(8.35) }) // A negative offset large enough to sink the top level's ceiling below the @@ -74,7 +74,29 @@ describe('resolveElevatorLevels', () => { [building, ...levels, elevator].map((node) => [node.id, node]), ) as Record - // level_0 ceiling is 3; level_1 sits at 3 - 2.5 = 0.5 and tops out at 2.5. - expect(resolveElevatorLevels(elevator, nodes).shaftTopY).toBeCloseTo(3) + // The upper landing is at 0.5; its 2.35 m cab needs a further 0.3 m of headroom. + expect(resolveElevatorLevels(elevator, nodes).shaftTopY).toBeCloseTo(3.15) }) }) + +test('the shaft cap clears a tall cab at every landing, including a thick shaft shell', () => { + const building = BuildingNode.parse({}) + const levels = [0, 1].map((level) => + LevelNode.parse({ parentId: building.id, level, height: 2.5 }), + ) + const elevator = ElevatorNode.parse({ + parentId: building.id, + fromLevelId: levels[0]!.id, + toLevelId: levels[1]!.id, + cabHeight: 4, + shaftWallThickness: 0.8, + }) + building.children = [...levels.map((level) => level.id), elevator.id] + const nodes = Object.fromEntries([building, ...levels, elevator].map((node) => [node.id, node])) + const resolved = resolveElevatorLevels(elevator, nodes) + for (const entry of resolved.entries) { + expect(resolved.shaftTopY - elevator.shaftWallThickness).toBeGreaterThan( + entry.baseY + elevator.cabHeight, + ) + } +}) diff --git a/packages/core/src/systems/elevator/elevator-service.ts b/packages/core/src/systems/elevator/elevator-service.ts index 6dd227d9b8..bd51df89a8 100644 --- a/packages/core/src/systems/elevator/elevator-service.ts +++ b/packages/core/src/systems/elevator/elevator-service.ts @@ -1,5 +1,6 @@ import type { AnyNode, AnyNodeId, ElevatorNode, LevelNode } from '../../schema' import { getLevelElevations } from '../../services/storey' +import { resolveElevatorDimensions } from './elevator-geometry' export type ElevatorLevelEntry = { id: LevelNode['id'] @@ -80,7 +81,7 @@ export function resolveElevatorServiceLevels( return levels.slice(minIndex, maxIndex + 1) } -export function resolveElevatorLevels( +function computeElevatorLevels( elevator: ElevatorNode, nodes: Record, ): { @@ -90,6 +91,10 @@ export function resolveElevatorLevels( shaftTopY: number totalHeight: number } { + const dimensions = resolveElevatorDimensions(elevator) + const cabHeight = dimensions.cabHeight + // Keep the cab below the cap even when a thick shaft wall also makes a thick cap. + const topClearance = Math.max(0.3, dimensions.shaftWallThickness + 0.01) const allLevels = resolveElevatorBuildingLevels(elevator, nodes) const levelElevations = getLevelElevations(nodes as Record) @@ -121,17 +126,42 @@ export function resolveElevatorLevels( if (!elevation) continue stackTopY = Math.max(stackTopY, elevation.baseY + elevation.height) } - const shaftTopY = nextLevel + const configuredTopY = nextLevel ? (levelElevations.get(nextLevel.id)?.baseY ?? stackTopY) : lastServedLevel ? stackTopY - : elevator.cabHeight + 0.3 + : cabHeight + topClearance + + const shaftTopY = Math.max( + configuredTopY, + shaftBaseY + cabHeight + topClearance, + ...entries.map((entry) => entry.baseY + cabHeight + topClearance), + ) return { entries, defaultEntry, shaftBaseY, shaftTopY, - totalHeight: Math.max(shaftTopY - shaftBaseY, elevator.cabHeight + 0.3), + totalHeight: Math.max(shaftTopY - shaftBaseY, cabHeight + topClearance), + } +} + +const levelCache = new WeakMap< + Record, + WeakMap> +>() + +export function resolveElevatorLevels(elevator: ElevatorNode, nodes: Record) { + let cache = levelCache.get(nodes) + if (!cache) { + cache = new WeakMap() + levelCache.set(nodes, cache) + } + let resolved = cache.get(elevator) + if (!resolved) { + resolved = computeElevatorLevels(elevator, nodes) + cache.set(elevator, resolved) } + return resolved } diff --git a/packages/editor/src/components/editor-2d/floorplan-registry-action-menu.tsx b/packages/editor/src/components/editor-2d/floorplan-registry-action-menu.tsx index 534cf11775..9ad4a9a63f 100644 --- a/packages/editor/src/components/editor-2d/floorplan-registry-action-menu.tsx +++ b/packages/editor/src/components/editor-2d/floorplan-registry-action-menu.tsx @@ -7,6 +7,7 @@ import { collectionIdsOf, createSceneApi, getWallMidpointHandlePoint, + isNodeDuplicable, type NodeQuickAction, nodeRegistry, runAsSingleSceneHistoryStep, @@ -255,7 +256,7 @@ export function FloorplanRegistryActionMenu() { const canMove = !registryMoveDisabled(node) && (!!def.capabilities.movable || !!def.floorplanMoveTarget || !!def.affordanceTools?.move) - const canDuplicate = def.capabilities.duplicable !== false + const canDuplicate = isNodeDuplicable(node) const canDelete = def.capabilities.deletable !== false const canAddHole = node.type === 'slab' || node.type === 'ceiling' diff --git a/packages/editor/src/components/editor-2d/floorplan-registry-move-overlay.tsx b/packages/editor/src/components/editor-2d/floorplan-registry-move-overlay.tsx index 123c3e18c6..30cde81b5b 100644 --- a/packages/editor/src/components/editor-2d/floorplan-registry-move-overlay.tsx +++ b/packages/editor/src/components/editor-2d/floorplan-registry-move-overlay.tsx @@ -850,14 +850,25 @@ export function FloorplanRegistryMoveOverlay() { } boxEl.setAttribute('transform', transform) const oldY = originalPosition[1] + const position = nodeRegistry.get(movingNode.type)?.capabilities?.movable?.resolvePosition?.({ + node: useScene.getState().nodes[movingNode.id] ?? movingNode, + position: [finalX, oldY, finalZ], + nodes: useScene.getState().nodes, + }) ?? [finalX, oldY, finalZ] + if (def?.capabilities?.movable?.resolvePosition) { + useLiveTransforms.getState().set(movingNode.id, { + position: position as [number, number, number], + rotation: currentRotation, + }) + } lastPositionValid = movableValidityConfig?.isValidPosition ? movableValidityConfig.isValidPosition({ node: { ...movingNode, - position: [finalX, oldY, finalZ], + position, rotation: currentRotation, } as AnyNode, - position: [finalX, oldY, finalZ], + position: position as [number, number, number], rotation: currentRotation, levelId: (useViewer.getState().selection.levelId as AnyNodeId | null) ?? @@ -885,6 +896,11 @@ export function FloorplanRegistryMoveOverlay() { (storedRotation as [number?, number?, number?])[2] ?? 0, ] : snapped.rotation + const position = nodeRegistry.get(movingNode.type)?.capabilities?.movable?.resolvePosition?.({ + node: useScene.getState().nodes[movingNode.id] ?? movingNode, + position: [sx, oldY, sz], + nodes: useScene.getState().nodes, + }) ?? [sx, oldY, sz] const rotationPatch = 'rotation' in movingNode ? { rotation } : {} const atomicPreview = isFreshPlacement && @@ -937,7 +953,7 @@ export function FloorplanRegistryMoveOverlay() { const committedId = commitFreshPlacementSubtree( movingNode.id as AnyNodeId, { - position: [sx, oldY, sz], + position, ...rotationPatch, metadata: stripPlacementMetadataFlags((movingNode as { metadata?: unknown }).metadata), visible: true, @@ -953,7 +969,7 @@ export function FloorplanRegistryMoveOverlay() { useScene.getState().updateNode( movingNode.id as AnyNodeId, { - position: [sx, oldY, sz], + position, ...rotationPatch, } as Partial, ) @@ -1005,6 +1021,8 @@ export function FloorplanRegistryMoveOverlay() { for (const relatedEntry of relatedEntries) { relatedEntry.style.visibility = '' } + if (def?.capabilities?.movable?.resolvePosition) + useLiveTransforms.getState().clear(movingNode.id) boxEl.remove() useAlignmentGuides.getState().clear() } diff --git a/packages/editor/src/components/editor/duplicate-node.ts b/packages/editor/src/components/editor/duplicate-node.ts index 5a16cfc857..450a4428dd 100644 --- a/packages/editor/src/components/editor/duplicate-node.ts +++ b/packages/editor/src/components/editor/duplicate-node.ts @@ -9,6 +9,7 @@ import { FenceNode, generateId, ItemNode, + isNodeDuplicable, nodeRegistry, RoofSegmentNode, runSceneHistoryDraftWrite, @@ -48,7 +49,7 @@ export function copyCollectionIds(copy: AnyNode): CollectionId[] { * every inspector's Duplicate. The copy is in the collections its source is in. */ export function duplicateNodeAndPickUp(node: AnyNode) { - if (!node.parentId) return + if (!(node.parentId && isNodeDuplicable(node))) return if (startZoneRoomTransform(node, 'duplicate')) return sfxEmitter.emit('sfx:item-pick') const { setMovingNode } = useEditor.getState() diff --git a/packages/editor/src/components/editor/floating-action-menu.tsx b/packages/editor/src/components/editor/floating-action-menu.tsx index 00772cfaab..ddb4ed8b53 100644 --- a/packages/editor/src/components/editor/floating-action-menu.tsx +++ b/packages/editor/src/components/editor/floating-action-menu.tsx @@ -14,6 +14,7 @@ import { getWallThickness, isCurvedWall, isDerivedNode, + isNodeDuplicable, isRegistryMovable, isRegistrySelectable, isSplineFence, @@ -681,6 +682,7 @@ export function FloatingActionMenu() { onDelete={handleDelete} onDuplicate={ node && + isNodeDuplicable(node as AnyNode) && node.type !== 'spawn' && !DELETE_ONLY_TYPES.includes(node.type) && !HOLE_TYPES.includes(node.type) diff --git a/packages/editor/src/components/editor/group-transform-shared.ts b/packages/editor/src/components/editor/group-transform-shared.ts index 68ab00bf00..9adbca5489 100644 --- a/packages/editor/src/components/editor/group-transform-shared.ts +++ b/packages/editor/src/components/editor/group-transform-shared.ts @@ -3,6 +3,7 @@ import { type AnyNodeId, calculateLevelMiters, getWallPlanFootprint, + isMoveLocked, nodeRegistry, resolveBuildingForLevel, sceneRegistry, @@ -99,7 +100,8 @@ export function classifyParticipant( levelId: string | null, sceneNodes: Record, ): ParticipantKind | null { - if (!node || !isInGroupTransformScope(node, levelId, sceneNodes)) return null + if (!node || !isInGroupTransformScope(node, levelId, sceneNodes) || isMoveLocked(node)) + return null const shape = classifyPlacementShape(node) if (shape) return shape const start = (node as { start?: unknown }).start diff --git a/packages/editor/src/components/systems/roof/roof-edit-system.test.tsx b/packages/editor/src/components/systems/roof/roof-edit-system.test.tsx index 2b65b52f66..c9b47f059d 100644 --- a/packages/editor/src/components/systems/roof/roof-edit-system.test.tsx +++ b/packages/editor/src/components/systems/roof/roof-edit-system.test.tsx @@ -38,7 +38,6 @@ test('roof trim drag keeps its plane hit over a surface joining and leaving a ba id: 'rseg_batch_drag', width: 10, depth: 10, - metadata: { showTrimPlanes: true }, }) const source = new THREE.Group() const surface = new THREE.Mesh(new THREE.BoxGeometry(30, 0.25, 30), new THREE.MeshBasicMaterial()) @@ -52,6 +51,9 @@ test('roof trim drag keeps its plane hit over a surface joining and leaving a ba hoveredId: null, selection: { buildingId: null, levelId: null, zoneId: null, selectedIds: [segment.id] }, }) + useInteractionScope + .getState() + .begin({ kind: 'reshaping', reshape: 'trim', nodeId: segment.id, driver: 'tool' }) await root.configure({ gl: { domElement: canvas, @@ -99,6 +101,18 @@ test('roof trim drag keeps its plane hit over a surface joining and leaving a ba events.dispatchEvent(new Event('pointercancel')) }) expect(useLiveNodeOverrides.getState().overrides.has(segment.id)).toBe(false) + const fieldEscape = Object.assign(new Event('keydown'), { key: 'Escape' }) + Object.defineProperty(fieldEscape, 'target', { + value: { closest: () => ({ tagName: 'INPUT' }) }, + }) + await act(async () => { + events.dispatchEvent(fieldEscape) + }) + expect(useInteractionScope.getState().scope.kind).toBe('reshaping') + await act(async () => { + events.dispatchEvent(Object.assign(new Event('keydown'), { key: 'Escape' })) + }) + expect(useInteractionScope.getState().scope.kind).toBe('idle') } finally { await act(async () => { root.render(null) diff --git a/packages/editor/src/components/systems/roof/roof-edit-system.tsx b/packages/editor/src/components/systems/roof/roof-edit-system.tsx index ea90db78e5..194989b7a8 100644 --- a/packages/editor/src/components/systems/roof/roof-edit-system.tsx +++ b/packages/editor/src/components/systems/roof/roof-edit-system.tsx @@ -34,6 +34,7 @@ import { LineBasicNodeMaterial, MeshBasicNodeMaterial } from 'three/webgpu' import { EDITOR_LAYER } from '../../../lib/constants' import { isHistoryShortcut } from '../../../lib/history' import { getHoveredRoofSegmentOutlineProxyName } from '../../../lib/roof-hover-outline-proxy' +import { isTypingTarget } from '../../../lib/typing-target' import useInteractionScope, { useMovingNode } from '../../../store/use-interaction-scope' import { swallowNextClick } from '../../editor/handles/use-handle-drag' @@ -1006,15 +1007,6 @@ function getTrimCursor(side: RoofTrimSide): string { } } -function shouldShowTrimPlanes(metadata: unknown): boolean { - return ( - typeof metadata === 'object' && - metadata !== null && - !Array.isArray(metadata) && - (metadata as Record).showTrimPlanes === true - ) -} - function commitSegmentTrim(segment: RoofSegmentNode, trim: RoofSegmentTrim) { const scene = useScene.getState() scene.applyNodeChanges({ @@ -1031,6 +1023,28 @@ function RoofTrimHandles() { return node?.type === 'roof-segment' ? (node as RoofSegmentNode) : null }) const readOnly = useScene((s) => s.readOnly) + const showTrimPlanes = useInteractionScope( + (s) => + s.scope.kind === 'reshaping' && s.scope.reshape === 'trim' && s.scope.nodeId === selectedId, + ) + useEffect(() => { + const end = () => + useInteractionScope + .getState() + .endIf( + (scope) => + scope.kind === 'reshaping' && scope.reshape === 'trim' && scope.nodeId === selectedId, + ) + const onKey = (event: KeyboardEvent) => { + if (isTypingTarget(event.target)) return + if (event.key === 'Escape') end() + } + window.addEventListener('keydown', onKey) + return () => { + window.removeEventListener('keydown', onKey) + end() + } + }, [selectedId]) const liveOverrideKey = useLiveNodeOverrides((s) => segment ? JSON.stringify(s.overrides.get(segment.id) ?? null) : null, ) @@ -1042,7 +1056,10 @@ function RoofTrimHandles() { const zoom = camera instanceof THREE.OrthographicCamera ? 1 / camera.zoom : 1 const handleBaseScale = zoom * TRIM_HANDLE_BASE_SCALE - useEffect(() => () => dragCleanupRef.current?.(), []) + useEffect(() => { + if (!selectedId || !showTrimPlanes || readOnly) dragCleanupRef.current?.() + return () => dragCleanupRef.current?.() + }, [selectedId, showTrimPlanes, readOnly]) const liveSegment = useMemo(() => { if (!segment) return null @@ -1059,8 +1076,6 @@ function RoofTrimHandles() { groupRef.current.matrixAutoUpdate = false }) - const showTrimPlanes = shouldShowTrimPlanes(liveSegment?.metadata) - if (readOnly || !segment || !liveSegment || !showTrimPlanes) return null const trim = normalizeRoofSegmentTrim(liveSegment) @@ -1314,9 +1329,7 @@ function RoofTrimHandles() { document.body.style.cursor = getTrimCursor(side) setDraggingSide(side) - useInteractionScope - .getState() - .begin({ kind: 'handle-drag', nodeId: segmentId, handle: getTrimLabel(side) }) + useViewer.getState().setInputDragging(true) useScene.temporal.getState().pause() @@ -1355,9 +1368,7 @@ function RoofTrimHandles() { document.body.style.cursor = '' } useScene.temporal.getState().resume() - useInteractionScope - .getState() - .endIf((scope) => scope.kind === 'handle-drag' && scope.nodeId === segmentId) + useViewer.getState().setInputDragging(false) setDraggingSide(null) dragCleanupRef.current = null @@ -1393,7 +1404,7 @@ function RoofTrimHandles() { onCancel() } - dragCleanupRef.current = cleanup + dragCleanupRef.current = onCancel window.addEventListener('pointermove', onMove) window.addEventListener('pointerup', onUp) window.addEventListener('pointercancel', onCancel) diff --git a/packages/editor/src/components/tools/elevator/elevator-defaults.ts b/packages/editor/src/components/tools/elevator/elevator-defaults.ts deleted file mode 100644 index 8d85864bfd..0000000000 --- a/packages/editor/src/components/tools/elevator/elevator-defaults.ts +++ /dev/null @@ -1,8 +0,0 @@ -export const DEFAULT_ELEVATOR_WIDTH = 1.84 -export const DEFAULT_ELEVATOR_DEPTH = 1.84 -export const DEFAULT_ELEVATOR_CAB_HEIGHT = 2.35 -export const DEFAULT_ELEVATOR_DOOR_WIDTH = 0.95 -export const DEFAULT_ELEVATOR_DOOR_HEIGHT = 2.1 -export const DEFAULT_ELEVATOR_SPEED = 2.2 -export const DEFAULT_ELEVATOR_DOOR_DURATION_MS = 900 -export const DEFAULT_ELEVATOR_DWELL_MS = 1400 diff --git a/packages/editor/src/components/tools/elevator/move-elevator-tool.tsx b/packages/editor/src/components/tools/elevator/move-elevator-tool.tsx deleted file mode 100644 index 185587ab17..0000000000 --- a/packages/editor/src/components/tools/elevator/move-elevator-tool.tsx +++ /dev/null @@ -1,262 +0,0 @@ -import { - type AnyNodeId, - type BuildingNode, - type ElevatorNode, - ElevatorNode as ElevatorNodeSchema, - emitter, - type GridEvent, - type LevelNode, - pauseSceneHistory, - resumeSceneHistory, - sceneRegistry, - useLiveTransforms, - useScene, -} from '@pascal-app/core' -import { useCallback, useEffect, useRef, useState } from 'react' -import { markToolCancelConsumed } from '../../../hooks/use-keyboard' -import { resolveElevatorSupportY } from '../../../lib/elevator-support' -import { consumePlacementDragRelease } from '../../../lib/placement-drag-release' -import { sfxEmitter } from '../../../lib/sfx-bus' -import { isTypingTarget } from '../../../lib/typing-target' -import useEditor from '../../../store/use-editor' -import { CursorSphere } from '../shared/cursor-sphere' - -function stripMoveMetadata(metadata: ElevatorNode['metadata']) { - if (typeof metadata !== 'object' || metadata === null || Array.isArray(metadata)) { - return metadata - } - - const nextMeta = { ...(metadata as Record) } - delete nextMeta.isNew - delete nextMeta.isTransient - return nextMeta as ElevatorNode['metadata'] -} - -export function MoveElevatorTool({ - node: movingNode, - onCommitted, -}: { - node: ElevatorNode - onCommitted?: (nodeId: AnyNodeId) => void -}) { - const onCommittedRef = useRef(onCommitted) - const historyPausedRef = useRef(false) - const previousGridPosRef = useRef<[number, number] | null>(null) - const dragAnchorRef = useRef<[number, number] | null>(null) - const previewPositionRef = useRef([ - movingNode.position[0], - movingNode.position[1], - movingNode.position[2], - ]) - const [cursorPosition, setCursorPosition] = useState<[number, number, number]>(() => [ - movingNode.position[0], - movingNode.position[1], - movingNode.position[2], - ]) - - const exitMoveMode = useCallback(() => { - useEditor.getState().setMovingNode(null) - }, []) - - useEffect(() => { - onCommittedRef.current = onCommitted - }, [onCommitted]) - - useEffect(() => { - const pauseHistory = () => { - const temporal = useScene.temporal.getState() - if (historyPausedRef.current || !temporal.isTracking) return - pauseSceneHistory(useScene) - historyPausedRef.current = true - } - const resumeHistory = () => { - if (!historyPausedRef.current) return - resumeSceneHistory(useScene) - historyPausedRef.current = false - } - - pauseHistory() - dragAnchorRef.current = null - previousGridPosRef.current = null - const movingNodeId = (movingNode as { id?: ElevatorNode['id'] }).id - - const meta = - typeof movingNode.metadata === 'object' && movingNode.metadata !== null - ? (movingNode.metadata as Record) - : {} - const isNew = !!meta.isNew - const committedMeta = stripMoveMetadata(movingNode.metadata) - const original = { - position: [...movingNode.position] as ElevatorNode['position'], - rotation: movingNode.rotation, - metadata: movingNode.metadata, - } - - let wasCommitted = false - let wasCancelled = false - let pendingRotation = movingNode.rotation - const supportBuildingId = movingNode.parentId as BuildingNode['id'] | null | undefined - const supportLevelId = (movingNode.fromLevelId ?? movingNode.defaultLevelId) as - | LevelNode['id'] - | null - - const applyPreview = ( - position: ElevatorNode['position'], - rotation: ElevatorNode['rotation'], - ) => { - if (movingNodeId) { - useLiveTransforms.getState().set(movingNodeId, { position, rotation }) - } - - const object = movingNodeId ? sceneRegistry.nodes.get(movingNodeId) : null - if (object) { - object.position.set(position[0], position[1], position[2]) - object.rotation.y = rotation - } - } - - const resetObject = ( - position: ElevatorNode['position'], - rotation: ElevatorNode['rotation'], - ) => { - const object = movingNodeId ? sceneRegistry.nodes.get(movingNodeId) : null - if (object) { - object.position.set(position[0], position[1], position[2]) - object.rotation.y = rotation - } - } - - const clearPreview = () => { - if (movingNodeId) { - useLiveTransforms.getState().clear(movingNodeId) - } - } - - const onGridMove = (event: GridEvent) => { - const bypassSnap = event.nativeEvent?.shiftKey === true - const rawX = bypassSnap ? event.localPosition[0] : Math.round(event.localPosition[0] * 2) / 2 - const rawZ = bypassSnap ? event.localPosition[2] : Math.round(event.localPosition[2] * 2) / 2 - const anchor = dragAnchorRef.current ?? [rawX, rawZ] - dragAnchorRef.current = anchor - const gridX = movingNode.position[0] + (rawX - anchor[0]) - const gridZ = movingNode.position[2] + (rawZ - anchor[1]) - const supportY = resolveElevatorSupportY({ - buildingId: supportBuildingId, - preferredLevelId: supportLevelId, - x: gridX, - z: gridZ, - }) - - if ( - !bypassSnap && - previousGridPosRef.current && - (gridX !== previousGridPosRef.current[0] || gridZ !== previousGridPosRef.current[1]) - ) { - sfxEmitter.emit('sfx:grid-snap') - } - - previousGridPosRef.current = [gridX, gridZ] - setCursorPosition([gridX, supportY, gridZ]) - previewPositionRef.current = [gridX, supportY, gridZ] - applyPreview(previewPositionRef.current, pendingRotation) - } - - const onGridClick = (event: GridEvent) => { - if (wasCommitted) return - const nextPosition: ElevatorNode['position'] = [...previewPositionRef.current] - - wasCommitted = true - clearPreview() - resumeHistory() - if (movingNodeId && useScene.getState().nodes[movingNodeId as AnyNodeId]) { - useScene.getState().updateNode(movingNodeId as AnyNodeId, { - position: nextPosition, - rotation: pendingRotation, - metadata: committedMeta, - }) - onCommittedRef.current?.(movingNodeId as AnyNodeId) - } else if (movingNode.parentId) { - const elevator = ElevatorNodeSchema.parse({ - ...movingNode, - id: undefined, - position: nextPosition, - rotation: pendingRotation, - metadata: committedMeta, - }) - useScene.getState().createNode(elevator, movingNode.parentId as AnyNodeId) - onCommittedRef.current?.(elevator.id as AnyNodeId) - } - - sfxEmitter.emit('sfx:item-place') - exitMoveMode() - event.nativeEvent?.stopPropagation?.() - } - - const onPlacementDragPointerUp = (event: PointerEvent) => { - if (!consumePlacementDragRelease(event)) return - onGridClick({ nativeEvent: event } as unknown as GridEvent) - } - - const onCancel = () => { - wasCancelled = true - clearPreview() - if (isNew && movingNodeId) { - useScene.getState().deleteNode(movingNodeId as AnyNodeId) - } else { - if (movingNodeId) { - useScene.getState().updateNode(movingNodeId as AnyNodeId, { - position: original.position, - rotation: original.rotation, - metadata: original.metadata, - }) - } - } - resetObject(original.position, original.rotation) - resumeHistory() - markToolCancelConsumed() - exitMoveMode() - } - - const onKeyDown = (event: KeyboardEvent) => { - if (isTypingTarget(event.target)) return - - const ROTATION_STEP = Math.PI / 4 - let rotationDelta = 0 - if (event.key === 'r' || event.key === 'R') rotationDelta = ROTATION_STEP - else if (event.key === 't' || event.key === 'T') rotationDelta = -ROTATION_STEP - - if (rotationDelta !== 0) { - event.preventDefault() - sfxEmitter.emit('sfx:item-rotate') - pendingRotation += rotationDelta - applyPreview(previewPositionRef.current, pendingRotation) - } - } - - emitter.on('grid:move', onGridMove) - emitter.on('grid:click', onGridClick) - emitter.on('tool:cancel', onCancel) - window.addEventListener('keydown', onKeyDown) - window.addEventListener('pointerup', onPlacementDragPointerUp) - - return () => { - clearPreview() - if (!(wasCommitted || wasCancelled || isNew) && movingNodeId) { - useScene.getState().updateNode(movingNodeId as AnyNodeId, { - position: original.position, - rotation: original.rotation, - metadata: original.metadata, - }) - resetObject(original.position, original.rotation) - } - resumeHistory() - emitter.off('grid:move', onGridMove) - emitter.off('grid:click', onGridClick) - emitter.off('tool:cancel', onCancel) - window.removeEventListener('keydown', onKeyDown) - window.removeEventListener('pointerup', onPlacementDragPointerUp) - } - }, [movingNode, exitMoveMode]) - - return -} diff --git a/packages/editor/src/components/tools/item/move-tool.tsx b/packages/editor/src/components/tools/item/move-tool.tsx index c47a6a61e5..2f3f0c4016 100644 --- a/packages/editor/src/components/tools/item/move-tool.tsx +++ b/packages/editor/src/components/tools/item/move-tool.tsx @@ -1,8 +1,7 @@ -import type { AnyNodeId, ElevatorNode, SpawnNode } from '@pascal-app/core' +import type { AnyNodeId, SpawnNode } from '@pascal-app/core' import { createSceneApi, nodeRegistry, useScene } from '@pascal-app/core' import { Suspense, useMemo } from 'react' import { useMovingNode } from '../../../store/use-interaction-scope' -import { MoveElevatorTool } from '../elevator/move-elevator-tool' import { MoveRegistryNodeTool } from '../registry/move-registry-node-tool' import { getRegistryAffordanceTool } from '../shared/affordance-dispatch' @@ -20,8 +19,6 @@ import { getRegistryAffordanceTool } from '../shared/affordance-dispatch' * 2. `MoveRegistryNodeTool` — generic translate-on-XZ for kinds that only * declare `capabilities.movable` (shelf, spawn, duct-terminal, * hvac-equipment, …). - * 3. `elevator` is the lone remaining legacy arm — its bespoke cab/shaft - * mover hasn't been ported to a kind-owned affordance yet. */ export const MoveTool: React.FC<{ onNodeMoved?: (nodeId: AnyNodeId) => void @@ -47,7 +44,5 @@ export const MoveTool: React.FC<{ return } - if (movingNode.type === 'elevator') - return return null } diff --git a/packages/editor/src/components/tools/registry/move-registry-node-tool.test.ts b/packages/editor/src/components/tools/registry/move-registry-node-tool.test.ts index 09a409c28a..fa5436bd2c 100644 --- a/packages/editor/src/components/tools/registry/move-registry-node-tool.test.ts +++ b/packages/editor/src/components/tools/registry/move-registry-node-tool.test.ts @@ -107,6 +107,7 @@ test('focus completion: mounted registry mover owns only outside R T and Alt', a cancelAnimationFrame: { configurable: true, value: (key: number) => frames.delete(key) }, IS_REACT_ACT_ENVIRONMENT: { configurable: true, value: true }, }) + let supportY = 0 core.registerNode({ kind: node.type, schemaVersion: 1, @@ -114,7 +115,14 @@ test('focus completion: mounted registry mover owns only outside R T and Alt', a schema: z.object({ type: z.literal(node.type) }).passthrough(), defaults: () => ({}), capabilities: { - movable: { isValidPosition: () => false }, + movable: { + isValidPosition: () => false, + resolvePosition: ({ position }: { position: [number, number, number] }) => [ + position[0], + supportY, + position[2], + ], + }, floorPlaced: { collides: true, footprint: (candidate: AnyNode) => ({ @@ -251,6 +259,39 @@ test('focus completion: mounted registry mover owns only outside R T and Alt', a expect((await key('t', false)).defaultPrevented).toBe(true) expect(mesh.rotation.y).toBeCloseTo(0.25) expect(core.useLiveTransforms.getState().transforms.get(id)?.rotation).toBeCloseTo(0.25) + supportY = 0.75 + await act(async () => { + core.emitter.emit('grid:move', { + nativeEvent: { + target: { closest: () => null }, + } as unknown as import('@pascal-app/core').GridEvent['nativeEvent'], + position: [7, 0, 3], + localPosition: [7, 0, 3], + stopPropagation() {}, + } as import('@pascal-app/core').GridEvent) + flushFrames() + }) + expect(mesh.position.y).toBeCloseTo(0.75) + expect(core.useLiveTransforms.getState().transforms.get(id)?.position?.[1]).toBeCloseTo(0.75) + expect( + (core.useScene.getState().nodes[id] as unknown as { position: number[] }).position[1], + ).toBe(0) + supportY = 1.25 + await key('Alt', false) + await act(async () => { + core.emitter.emit('grid:click', { + nativeEvent: { + target: { closest: () => null }, + } as unknown as import('@pascal-app/core').GridEvent['nativeEvent'], + position: [7, 0, 3], + localPosition: [7, 0, 3], + stopPropagation() {}, + } as import('@pascal-app/core').GridEvent) + flushFrames() + }) + expect( + (core.useScene.getState().nodes[id] as unknown as { position: number[] }).position[1], + ).toBeCloseTo(1.25) } finally { if (root) await act(async () => { diff --git a/packages/editor/src/components/tools/registry/move-registry-node-tool.tsx b/packages/editor/src/components/tools/registry/move-registry-node-tool.tsx index d7dccdbc4a..fa8c28555f 100644 --- a/packages/editor/src/components/tools/registry/move-registry-node-tool.tsx +++ b/packages/editor/src/components/tools/registry/move-registry-node-tool.tsx @@ -484,6 +484,18 @@ export function MoveRegistryNodeTool({ node: source }: { node: AnyNode }) { return Array.isArray(rotation) ? [rotation[0] ?? 0, y, rotation[2] ?? 0] : y } + const resolvePosition = (position: [number, number, number]) => { + const nodes = useScene.getState().nodes + const current = nodes[node.id] ?? node + return ( + nodeRegistry.get(current.type)?.capabilities?.movable?.resolvePosition?.({ + node: current, + position, + nodes, + }) ?? position + ) + } + const keepStartingElevation = (position: [number, number, number], yaw: number) => { if (!preserveLevelAndElevation) return position const rotation = toCommitRotation(yaw) @@ -1032,7 +1044,7 @@ export function MoveRegistryNodeTool({ node: source }: { node: AnyNode }) { }, ).position } - position = keepStartingElevation(position, rotationRef.current) + position = resolvePosition(keepStartingElevation(position, rotationRef.current)) // Carry connected ductwork along (preview only — committed on drop). A // position the connected joints cannot follow holds the last frame, // which is what the drop commits. @@ -1124,7 +1136,7 @@ export function MoveRegistryNodeTool({ node: source }: { node: AnyNode }) { // tool — unless Alt (free place) is held to force placement. Other kinds // carry no validity box (`validRef` stays true), so they're never blocked. if (!validRef.current && !altRef.current) return - const position: [number, number, number] = [...lastCursorRef.current] + const position = resolvePosition([...lastCursorRef.current]) const rotation = toCommitRotation(rotationRef.current) let committedId = node.id as AnyNodeId diff --git a/packages/editor/src/components/tools/tool-manager.tsx b/packages/editor/src/components/tools/tool-manager.tsx index 5a21f1c966..16c4a9c7af 100644 --- a/packages/editor/src/components/tools/tool-manager.tsx +++ b/packages/editor/src/components/tools/tool-manager.tsx @@ -41,7 +41,6 @@ import { FloorRegionControls3D } from '../editor/floor-region-controls' import { OpenWallEnds3DLayer } from '../editor/open-wall-ends-3d-layer' import { OpeningGuides3DLayer } from '../editor/opening-guides-3d-layer' import { WallSnapBeaconLayer } from '../editor/wall-snap-beacon-layer' -import { ElevatorTool } from './elevator/elevator-tool' import { MoveTool } from './item/move-tool' import { WallPaintRegionTool } from './paint-region/wall-paint-region-tool' import { RegistryToolProvider } from './registry-tool-context' @@ -305,21 +304,6 @@ export const ToolManager: React.FC = () => { const handlePlacedNodeSelected = (nodeId: AnyNodeId) => { setSelection({ selectedIds: [nodeId] }) } - const handlePlacedElevatorSelected = ( - nodeId: AnyNodeId, - elevatorBuildingId: BuildingNode['id'], - ) => { - // Preserve the active level. `setSelection`'s hierarchy guard nulls - // `levelId` whenever `buildingId` is passed without an explicit - // `levelId` — which deselected the current floor plan the moment an - // elevator was placed. Pass the current level through so the floor - // plan stays selected. - setSelection({ - buildingId: elevatorBuildingId, - levelId: activeLevelId ?? null, - selectedIds: [nodeId], - }) - } return ( @@ -463,14 +447,7 @@ export const ToolManager: React.FC = () => { )} - {!movingNode && !useRegistryTool && showBuildTool && tool === 'elevator' && ( - - )} - {!movingNode && BuildToolComponent && tool !== 'elevator' ? : null} + {!movingNode && BuildToolComponent ? : null} {/* Figma-style alignment guides published by the move / placement tools above. Lives inside the building-local group so the building-local guide coords render at the right world position. */} diff --git a/packages/editor/src/components/ui/controls/slider-control.tsx b/packages/editor/src/components/ui/controls/slider-control.tsx index 995c02a494..a668019066 100644 --- a/packages/editor/src/components/ui/controls/slider-control.tsx +++ b/packages/editor/src/components/ui/controls/slider-control.tsx @@ -1,6 +1,6 @@ 'use client' -import { formatNumber, parseLocalizedNumber, useLocale, useScene } from '@pascal-app/core' +import { formatNumber, parseLocalizedNumber, useLocale, useScene, usePascalI18n } from '@pascal-app/core' import { useCallback, useEffect, useRef, useState } from 'react' import { lingoUnitSpec, measurementHint, parseMeasurement } from '../../../lib/measurement-parser' import { useLinearDisplay } from '../../../lib/use-linear-display' @@ -71,6 +71,7 @@ export function SliderControl({ restoreOnCommit = true, mixed = false, }: SliderControlProps) { + const i18n = usePascalI18n() const locale = useLocale() // Values and bounds stay in meters; gestures and input use the displayed unit. const { isImperial, displayUnit, parseUnit, precision, step, toDisplay, toStored } = @@ -260,6 +261,12 @@ export function SliderControl({ [], ) + useEffect(() => { + const cancelOnBlur = () => { if (dragRef.current || editingRef.current) cancelEdit() } + window.addEventListener('blur', cancelOnBlur) + return () => window.removeEventListener('blur', cancelOnBlur) + }, [cancelEdit]) + useEffect(() => { if (!isDragging) return const escape = (event: KeyboardEvent) => { @@ -392,6 +399,7 @@ export function SliderControl({ )} ) : mixed && !isDragging ? ( -
- Mixed -
+ {i18n._({ id: 'editor.controls.sliderControl.mixed', message: 'Mixed' })} + ) : ( -
@@ -433,7 +445,7 @@ export function SliderControl({ {formatDisplay(displayValue)} {displayUnit && {displayUnit}} -
+ )}
diff --git a/packages/editor/src/components/ui/panels/mobile-selection-bar.tsx b/packages/editor/src/components/ui/panels/mobile-selection-bar.tsx index f3878e10ed..5d3d0f6b7e 100644 --- a/packages/editor/src/components/ui/panels/mobile-selection-bar.tsx +++ b/packages/editor/src/components/ui/panels/mobile-selection-bar.tsx @@ -12,8 +12,8 @@ interface MobileSelectionBarProps { node: AnyNode | null label?: string icon?: string - onMove: () => void - onDuplicate: () => void + onMove?: () => void + onDuplicate?: () => void onDelete: () => void onEdit: () => void } @@ -58,28 +58,32 @@ export function MobileSelectionBar({
- - + {onMove && ( + + )} + {onDuplicate && ( + + )} + + {!isBraceSupport && ( + <> +

+ {i18n._({ id: 'node.column.panel.style', message: 'Style' })} +

+ +

+ {i18n._({ id: 'node.column.panel.crossSection', message: 'Cross section' })} +

+ handleUpdate({ shaftCornerRadius: value })} + onChange={(value) => previewProp({ edgeSoftness: value })} precision={3} step={0.005} unit="m" - value={node.shaftCornerRadius ?? 0.035} + value={node.edgeSoftness ?? 0.025} /> - )} - - )} - + {(node.crossSection === 'square' || node.crossSection === 'rectangular') && ( + previewProp({ shaftCornerRadius: value })} + precision={3} + step={0.005} + unit="m" + value={node.shaftCornerRadius ?? 0.035} + /> + )} + + )} + - - {managedByLeanTo && ( -

- {i18n._({ - id: 'node.column.panel.heightAndFootprintAreControlledBy', - message: - 'Height and footprint are controlled by the lean-to extension. Rotate or change the support style here; resize from the parent lean-to.', - })} -

- )} - {!isBraceSupport && !managedByLeanTo && ( - - )} - {!managedByLeanTo && ( - handleUpdate({ height: value })} - precision={2} - step={0.05} - unit="m" - value={node.height} - /> - )} - {isBraceSupport ? ( - <> - {(supportStyle === 'a-frame' || - supportStyle === 'x-brace' || - supportStyle === 'k-brace' || - supportStyle === 'single-strut' || - supportStyle === 'tripod' || - supportStyle === 'trestle' || - supportStyle === 'portal-frame' || - supportStyle === 'box-frame') && ( + {i18n._({ id: 'node.column.panel.resetSize', message: 'Reset size' })} + + {isBraceSupport && ( + <> - handleUpdate({ - braceBottomSpread: value, - braceTopSpread: - supportStyle === 'a-frame' - ? Math.min(node.braceTopSpread ?? 0.12, value) - : (node.braceTopSpread ?? 1), - }) - } + min={0.04} + onChange={(value) => previewProp({ braceWidth: value, width: value })} precision={2} - step={0.05} + step={0.01} unit="m" - value={node.braceBottomSpread ?? 1.2} + value={node.braceWidth ?? node.width} /> - )} - handleUpdate({ braceTopSpread: value })} - precision={2} - step={0.02} - unit="m" - value={ - node.braceTopSpread ?? - (supportStyle === 'y-frame' || - supportStyle === 'v-frame' || - supportStyle === 'x-brace' || - supportStyle === 'k-brace' || - supportStyle === 'single-strut' || - supportStyle === 'tripod' || - supportStyle === 'trestle' || - supportStyle === 'portal-frame' || - supportStyle === 'box-frame' - ? 1 - : 0.12) - } - /> - handleUpdate({ bracePlateEnabled: checked })} - /> - - ) : !managedByLeanTo ? ( - <> - - handleUpdate({ - width: value, - radius: value / 2, - ...(node.crossSection === 'rectangular' ? {} : { depth: value }), - }) - } - precision={2} - step={0.02} - unit="m" - value={node.width} - /> - {node.crossSection === 'rectangular' && ( handleUpdate({ depth: value })} + min={0.04} + onChange={(value) => previewProp({ braceDepth: value, depth: value })} precision={2} - step={0.02} + step={0.01} unit="m" - value={node.depth} + value={node.braceDepth ?? node.depth} /> - )} - - ) : null} -
- - {!isBraceSupport && ( - - - {shaftProfile === 'straight' && ( + + )} + {managedByLeanTo && ( +

+ {i18n._({ + id: 'node.column.panel.heightAndFootprintAreControlledBy', + message: + 'Height and footprint are controlled by the lean-to extension. Rotate or change the support style here; resize from the parent lean-to.', + })} +

+ )} + {!isBraceSupport && !managedByLeanTo && ( + + )} + {!managedByLeanTo && ( - handleUpdate({ shaftStartScale: value, shaftEndScale: value }) - } + onCommit={commitPreview} + onCancel={cancelPreview} + restoreOnCommit={false} + label={i18n._({ id: 'node.column.panel.height', message: 'Height' })} + axis="y" + max={1000} + min={0.2} + onChange={(value) => previewProp({ height: value })} precision={2} - step={0.02} - value={node.shaftStartScale ?? 0.72} + step={0.05} + unit="m" + value={node.height} /> )} - {shaftProfile === 'tapered' && ( + {isBraceSupport ? ( <> - handleUpdate({ shaftStartScale: value })} - precision={2} - step={0.02} - value={node.shaftStartScale ?? 0.82} - /> - handleUpdate({ shaftEndScale: value })} - precision={2} - step={0.02} - value={node.shaftEndScale ?? 0.72} - /> - handleUpdate({ shaftTaper: value })} - precision={2} - step={0.01} - value={node.shaftTaper ?? 0.14} + {(supportStyle === 'a-frame' || + supportStyle === 'x-brace' || + supportStyle === 'k-brace' || + supportStyle === 'single-strut' || + supportStyle === 'tripod' || + supportStyle === 'trestle' || + supportStyle === 'portal-frame' || + supportStyle === 'box-frame') && ( + + previewProp({ + braceBottomSpread: value, + braceTopSpread: + supportStyle === 'a-frame' + ? Math.min(node.braceTopSpread ?? 0.12, value) + : (node.braceTopSpread ?? 1), + }) + } + precision={2} + step={0.05} + unit="m" + value={node.braceBottomSpread ?? 1.2} + /> + )} + {supportStyle !== 'portal-frame' && ( + previewProp({ braceTopSpread: value })} + precision={2} + step={0.02} + unit="m" + value={ + node.braceTopSpread ?? + (supportStyle === 'y-frame' || + supportStyle === 'v-frame' || + supportStyle === 'x-brace' || + supportStyle === 'k-brace' || + supportStyle === 'single-strut' || + supportStyle === 'tripod' || + supportStyle === 'trestle' || + supportStyle === 'box-frame' + ? 1 + : 0.12) + } + /> + )} + handleUpdate({ bracePlateEnabled: checked })} /> - )} - {shaftProfile === 'bulged' && ( + ) : !managedByLeanTo ? ( <> - handleUpdate({ shaftStartScale: value, shaftEndScale: value }) + previewProp({ + width: value, + radius: value / 2, + ...(node.crossSection === 'rectangular' ? {} : { depth: value }), + }) } precision={2} step={0.02} - value={node.shaftStartScale ?? 0.68} - /> - handleUpdate({ shaftBulge: value })} - precision={2} - step={0.01} - value={node.shaftBulge ?? 0.12} + unit="m" + value={radialSection ? node.radius * 2 : node.width} /> + {node.crossSection === 'rectangular' && ( + previewProp({ depth: value })} + precision={2} + step={0.02} + unit="m" + value={node.depth} + /> + )} - )} - {shaftProfile === 'hourglass' && ( - <> + ) : null} +
+ + {!isBraceSupport && node.style !== 'cluster' && ( + + +

+ {i18n._({ + id: 'node.column.panel.scalesMultiplyTheDimensionsInSize', + message: 'Scales multiply the dimensions in Size. A ratio of 0.2 means 20%.', + })} +

+ + {shaftProfile === 'straight' && ( - handleUpdate({ shaftStartScale: value, shaftEndScale: value }) + previewProp({ shaftStartScale: value, shaftEndScale: value }) } precision={2} step={0.02} - value={node.shaftStartScale ?? 0.84} - /> - handleUpdate({ shaftBulge: value })} - precision={2} - step={0.01} - value={node.shaftBulge ?? 0.12} + value={node.shaftStartScale ?? 0.72} /> - - )} - - handleUpdate({ - shaftTwistStep: value, - ...(Math.abs(value) > 0.001 && (node.shaftSegmentCount ?? 1) < 8 - ? { shaftSegmentCount: 12 } - : {}), - }) - } - precision={0} - step={5} - unit="°" - value={node.shaftTwistStep ?? 0} - /> - {Math.abs(node.shaftTwistStep ?? 0) > 0.001 && ( - handleUpdate({ shaftSegmentCount: Math.round(value) })} - precision={0} - step={1} - value={node.shaftSegmentCount ?? 12} - /> - )} - - handleUpdate({ - ringCount: Math.round(value) * 2, - ringPlacement: 'ends', - ringSpread: node.ringSpread ?? 0.16, - ringThickness: node.ringThickness ?? 0.055, - }) - } - precision={0} - step={1} - value={Math.ceil((node.ringCount ?? 0) / 2)} - /> - {(node.ringCount ?? 0) > 0 && ( + )} + {shaftProfile === 'tapered' && ( + <> + previewProp({ shaftStartScale: value })} + precision={2} + step={0.02} + value={node.shaftStartScale ?? 0.82} + /> + previewProp({ shaftEndScale: value })} + precision={2} + step={0.02} + value={node.shaftEndScale ?? 0.72} + /> + previewProp({ shaftTaper: value })} + precision={2} + step={0.01} + value={node.shaftTaper ?? 0.14} + /> + + )} + {(shaftProfile === 'bulged' || shaftProfile === 'baluster') && ( + <> + + previewProp({ shaftStartScale: value, shaftEndScale: value }) + } + precision={2} + step={0.02} + value={node.shaftStartScale ?? 0.68} + /> + previewProp({ shaftBulge: value })} + precision={2} + step={0.01} + value={node.shaftBulge ?? 0.12} + /> + + )} + {shaftProfile === 'hourglass' && ( + <> + + previewProp({ shaftStartScale: value, shaftEndScale: value }) + } + precision={2} + step={0.02} + value={node.shaftStartScale ?? 0.84} + /> + previewProp({ shaftBulge: value })} + precision={2} + step={0.01} + value={node.shaftBulge ?? 0.12} + /> + + )} handleUpdate({ ringThickness: value })} - precision={3} - step={0.005} - unit="m" - value={node.ringThickness ?? 0.055} - /> - )} - {(node.ringCount ?? 0) > 0 && ( - handleUpdate({ ringSpread: value, ringPlacement: 'ends' })} - precision={2} - step={0.01} - value={node.ringSpread ?? 0.16} - /> - )} -
- )} - - {!isBraceSupport && ( - - - {node.capitalStyle !== 'none' && ( - handleUpdate({ capitalHeight: value })} - precision={2} - step={0.02} - unit="m" - value={node.capitalHeight} - /> - )} - {node.capitalStyle !== 'none' && ( - - handleUpdate({ - capitalWidthScale: value, - ...(node.crossSection === 'rectangular' ? {} : { capitalDepthScale: value }), + previewProp({ + shaftTwistStep: value, + ...(Math.abs(value) > 0.001 && (node.shaftSegmentCount ?? 1) < 8 + ? { shaftSegmentCount: 12 } + : {}), }) } - precision={2} - step={0.02} - value={node.capitalWidthScale ?? 1.28} - /> - )} - {node.capitalStyle !== 'none' && node.crossSection === 'rectangular' && ( - handleUpdate({ capitalDepthScale: value })} - precision={2} - step={0.02} - value={node.capitalDepthScale ?? node.capitalWidthScale ?? 1.28} - /> - )} - {node.capitalStyle === 'stepped' && ( - handleUpdate({ capitalTierCount: Math.round(value) })} precision={0} - step={1} - value={node.capitalTierCount ?? 3} + step={5} + unit="°" + value={node.shaftTwistStep ?? 0} /> - )} - {node.capitalStyle === 'stepped' && ( - handleUpdate({ capitalStepSpread: value })} - precision={2} - step={0.01} - value={node.capitalStepSpread ?? 0.34} - /> - )} - { + const baseStyle = event.target.value as ColumnNode['baseStyle'] + handleUpdate({ + baseStyle, + ...(baseStyle === 'none' + ? {} + : { + baseHeight: Math.max(node.baseHeight, 0.12), + baseTierCount: + baseStyle === 'stepped-square' + ? Math.max(node.baseTierCount ?? 3, 3) + : node.baseTierCount, + baseWidthScale: Math.max( + node.baseWidthScale ?? 1.24, + baseStyle === 'stepped-square' ? 1.42 : 1.24, + ), + baseDepthScale: Math.max( + node.baseDepthScale ?? 1.24, + baseStyle === 'stepped-square' ? 1.42 : 1.24, + ), + baseStepSpread: + baseStyle === 'stepped-square' + ? Math.max(node.baseStepSpread ?? 0.34, 0.34) + : node.baseStepSpread, + basePlinthHeightRatio: + baseStyle === 'round-rings' + ? (node.basePlinthHeightRatio ?? 0.44) + : node.basePlinthHeightRatio, + baseRoundBandScale: + baseStyle === 'round-rings' + ? (node.baseRoundBandScale ?? 0.92) + : node.baseRoundBandScale, + baseNeckScale: + baseStyle === 'round-rings' + ? (node.baseNeckScale ?? 0.72) + : node.baseNeckScale, + }), + }) + }} + value={node.baseStyle ?? 'square-plinth'} + > + {ColumnBaseStyle.options.map((value) => ( + + ))} + + {node.baseStyle !== 'none' && ( + previewProp({ baseHeight: value })} + precision={2} + step={0.02} + unit="m" + value={node.baseHeight} + /> + )} + {node.baseStyle !== 'none' && ( + + previewProp({ + baseWidthScale: value, + ...(node.crossSection === 'rectangular' ? {} : { baseDepthScale: value }), + }) + } + precision={2} + step={0.02} + value={node.baseWidthScale ?? 1.24} + /> + )} + {node.baseStyle !== 'none' && node.crossSection === 'rectangular' && ( + previewProp({ baseDepthScale: value })} + precision={2} + step={0.02} + value={node.baseDepthScale ?? node.baseWidthScale ?? 1.24} + /> + )} + {node.baseStyle === 'round-rings' && ( + previewProp({ basePlinthHeightRatio: value })} + precision={2} + step={0.01} + value={node.basePlinthHeightRatio ?? 0.44} + /> + )} + {node.baseStyle === 'round-rings' && ( + previewProp({ baseRoundBandScale: value })} + precision={2} + step={0.01} + value={node.baseRoundBandScale ?? 0.92} + /> + )} + {node.baseStyle === 'round-rings' && ( + previewProp({ baseNeckScale: value })} + precision={2} + step={0.01} + value={node.baseNeckScale ?? 0.72} + /> + )} + {node.baseStyle === 'stepped-square' && ( + previewProp({ baseTierCount: Math.round(value) })} + precision={0} + step={1} + value={node.baseTierCount ?? 3} + /> + )} + {node.baseStyle === 'stepped-square' && ( + previewProp({ baseStepSpread: value })} + precision={2} + step={0.01} + value={node.baseStepSpread ?? 0.34} + /> + )} + {renderDetails(baseFields)} + + + +

+ {i18n._({ + id: 'node.column.panel.widthAndDepthScalesMultiplyThe', + message: 'Width and depth scales multiply the dimensions in Size.', + })} +

+ + {node.capitalStyle !== 'none' && ( + previewProp({ capitalHeight: value })} + precision={2} + step={0.02} + unit="m" + value={node.capitalHeight} + /> + )} + {node.capitalStyle !== 'none' && ( + + previewProp({ + capitalWidthScale: value, + ...(node.crossSection === 'rectangular' + ? {} + : { capitalDepthScale: value }), + }) + } + precision={2} + step={0.02} + value={node.capitalWidthScale ?? 1.28} + /> + )} + {node.capitalStyle !== 'none' && node.crossSection === 'rectangular' && ( + previewProp({ capitalDepthScale: value })} + precision={2} + step={0.02} + value={node.capitalDepthScale ?? node.capitalWidthScale ?? 1.28} + /> + )} + {node.capitalStyle === 'stepped' && ( + previewProp({ capitalTierCount: Math.round(value) })} + precision={0} + step={1} + value={node.capitalTierCount ?? 3} + /> + )} + {node.capitalStyle === 'stepped' && ( + previewProp({ capitalStepSpread: value })} + precision={2} + step={0.01} + value={node.capitalStepSpread ?? 0.34} + /> + )} + {renderDetails(capitalFields)} +
+ + )} + {!isBraceSupport && ( + - - - )} - - )} - - handleUpdate({ rotation: (value * Math.PI) / 180 })} - precision={0} - step={1} - unit="°" - value={Math.round((node.rotation * 180) / Math.PI)} - /> - - - - + {(node.ringCount ?? 0) > 0 && ( + previewProp({ ringThickness: value })} + precision={3} + step={0.005} + unit="m" + value={node.ringThickness ?? 0.055} + /> + )} + {(node.ringCount ?? 0) > 0 && ( + previewProp({ ringSpread: value, ringPlacement: 'ends' })} + precision={2} + step={0.01} + value={node.ringSpread ?? 0.16} + /> + )} + {(node.baseStyle !== 'none' || node.capitalStyle !== 'none') && ( + <> +

+ {i18n._({ + id: 'node.column.panel.carvingPlacement', + message: 'Carving placement', + })} +

+ + + )} +
+ )} + + )} + + +

+ {i18n._({ + id: 'node.column.panel.chooseAMaterialThenClickThe', + message: 'Choose a material, then click the surface to paint.', + })} +

+
+ {(node.source + ? ['all'] + : isBraceSupport + ? ['frame'] + : [ + 'shaft', + ...(node.baseStyle !== 'none' ? ['base'] : []), + ...(node.capitalStyle !== 'none' ? ['capital'] : []), + ] + ).map((part) => ( + + ))} +
} - label={i18n._({ id: 'node.column.panel.move', message: 'Move' })} - onClick={handleMove} + icon={} + label={i18n._({ id: 'node.column.panel.paintMaterials', message: 'Paint Materials' })} + onClick={() => { + cancelPreview() + armMaterialPaint(undefined, 'surface') + }} /> - } - label={i18n._({ id: 'node.column.panel.delete', message: 'Delete' })} - onClick={handleDelete} +
+ + + previewProp({ rotation: (value * Math.PI) / 180 })} + precision={0} + step={1} + unit="°" + value={Math.round((node.rotation * 180) / Math.PI)} /> - - + + + + + {!managedByLeanTo && ( + } + label={i18n._({ id: 'node.column.panel.move', message: 'Move' })} + onClick={handleMove} + /> + )} + } + label={i18n._({ id: 'node.column.panel.delete', message: 'Delete' })} + onClick={handleDelete} + /> + + + ) } diff --git a/packages/nodes/src/column/parametrics.ts b/packages/nodes/src/column/parametrics.ts index 0c3ace670b..7c2acce1ff 100644 --- a/packages/nodes/src/column/parametrics.ts +++ b/packages/nodes/src/column/parametrics.ts @@ -16,7 +16,7 @@ export const columnParametrics: ParametricDescriptor = { { label: 'Dimensions', fields: [ - { key: 'height', kind: 'number', unit: 'm', min: 0.5, max: 1000, step: 0.05 }, + { key: 'height', kind: 'number', unit: 'm', min: 0.2, max: 1000, step: 0.05 }, { key: 'width', kind: 'number', unit: 'm', min: 0.1, max: 1000, step: 0.01 }, { key: 'depth', kind: 'number', unit: 'm', min: 0.1, max: 1000, step: 0.01 }, ], diff --git a/packages/nodes/src/column/preset-gallery.tsx b/packages/nodes/src/column/preset-gallery.tsx new file mode 100644 index 0000000000..6499541202 --- /dev/null +++ b/packages/nodes/src/column/preset-gallery.tsx @@ -0,0 +1,177 @@ +import { + COLUMN_PRESETS, + type ColumnNode, + type ColumnPresetId, + type MessageDescriptor, + usePascalI18n, +} from '@pascal-app/core' +import { ChevronDown } from 'lucide-react' +import { useEffect, useRef } from 'react' +import { columnPresetUpdates } from './presets' + +/** Preset names in the UI language; core's `COLUMN_PRESETS` labels stay English. */ +const COLUMN_PRESET_LABELS: Record = { + basicPillar: /* i18n */ { id: 'node.column.preset.basicPillar', message: 'Straight Round' }, + squarePillar: /* i18n */ { id: 'node.column.preset.squarePillar', message: 'Square Block' }, + taperedPillar: /* i18n */ { id: 'node.column.preset.taperedPillar', message: 'Tapered Round' }, + bulgedPillar: /* i18n */ { id: 'node.column.preset.bulgedPillar', message: 'Soft Bulged' }, + hourglassPillar: /* i18n */ { id: 'node.column.preset.hourglassPillar', message: 'Hourglass' }, + aFrameSupport: /* i18n */ { id: 'node.column.preset.aFrameSupport', message: 'A-Frame Support' }, + yFrameSupport: /* i18n */ { id: 'node.column.preset.yFrameSupport', message: 'Y Support' }, + vFrameSupport: /* i18n */ { id: 'node.column.preset.vFrameSupport', message: 'V Support' }, + xBraceSupport: /* i18n */ { id: 'node.column.preset.xBraceSupport', message: 'X Brace' }, + kBraceSupport: /* i18n */ { id: 'node.column.preset.kBraceSupport', message: 'K Brace' }, + singleStrutSupport: /* i18n */ { + id: 'node.column.preset.singleStrutSupport', + message: 'Single Strut', + }, + tripodSupport: /* i18n */ { id: 'node.column.preset.tripodSupport', message: 'Tripod Support' }, + trestleSupport: /* i18n */ { id: 'node.column.preset.trestleSupport', message: 'Trestle Frame' }, + portalFrameSupport: /* i18n */ { + id: 'node.column.preset.portalFrameSupport', + message: 'Portal Frame', + }, + boxFrameSupport: /* i18n */ { id: 'node.column.preset.boxFrameSupport', message: 'Box Frame' }, +} + +const entries = Object.keys(COLUMN_PRESETS).map((id) => ({ + id: id as ColumnPresetId, + label: COLUMN_PRESET_LABELS[id as ColumnPresetId], +})) + +export function ColumnPresetGallery({ + node, + onPreview, + onCancel, + onApply, +}: { + node: ColumnNode + onPreview: (patch: Partial) => void + onCancel: () => void + onApply: (patch: Partial) => void +}) { + const i18n = usePascalI18n() + const detailsRef = useRef(null) + const scrolling = useRef(false) + const cancelPointerPreview = () => { + if (!detailsRef.current?.querySelector('button:focus-visible')) onCancel() + } + const selected = entries.find(({ id }) => + Object.entries(columnPresetUpdates(id)).every( + ([key, value]) => node[key as keyof ColumnNode] === value, + ), + ) + useEffect(() => { + const handleEscape = (event: KeyboardEvent) => { + if (event.key === 'Escape') onCancel() + } + window.addEventListener('keydown', handleEscape) + window.addEventListener('blur', onCancel) + return () => { + window.removeEventListener('keydown', handleEscape) + window.removeEventListener('blur', onCancel) + onCancel() + } + }, [onCancel]) + return ( +
{ + scrolling.current = false + cancelPointerPreview() + }} + onWheel={() => { + scrolling.current = true + onCancel() + }} + onToggle={(event) => { + if (!event.currentTarget.open) onCancel() + }} + > + + + + + {i18n._({ id: 'node.column.presetGallery.shapePresets', message: 'Shape presets' })} + + + {(selected && i18n._(selected.label)) ?? + i18n._({ id: 'node.column.presetGallery.chooseAShape', message: 'Choose a shape' })} + + + + +

+ {i18n._({ + id: 'node.column.presetGallery.hoverOrFocusToPreviewClick', + message: + 'Hover or focus to preview; click to apply. Materials are kept. Escape cancels the preview.', + })} +

+
+ {entries.map(({ id, label }) => ( + + ))} +
+
+ ) +} diff --git a/packages/nodes/src/column/presets.test.ts b/packages/nodes/src/column/presets.test.ts new file mode 100644 index 0000000000..1d3305a057 --- /dev/null +++ b/packages/nodes/src/column/presets.test.ts @@ -0,0 +1,96 @@ +import { expect, test } from 'bun:test' +import { + COLUMN_PRESETS, + ColumnNode, + type ColumnPresetId, + clearSceneHistory, + NEW_COLUMN_SLOTS, + useLiveNodeOverrides, + useScene, +} from '@pascal-app/core' +import { installMountedScene } from '../__tests__/harness' +import { columnPresetUpdates, columnSectionReset } from './presets' +import { createColumnPropertyPreview } from './property-preview' + +installMountedScene() + +test('all shape presets preserve identity, placement and finishes', () => { + const original = ColumnNode.parse({ + name: 'Entrance pillar', + position: [2, 0, 4], + materialPreset: 'concrete', + slots: { shaft: 'library:stone' }, + }) + for (const id of Object.keys(COLUMN_PRESETS) as ColumnPresetId[]) { + const result = ColumnNode.parse({ ...original, ...columnPresetUpdates(id) }) + expect(result).toMatchObject({ + id: original.id, + name: original.name, + position: original.position, + materialPreset: original.materialPreset, + slots: original.slots, + }) + } +}) + +test('section resets are isolated and material reset restores the new-column finish', () => { + const original = ColumnNode.parse({ + height: 4, + baseHeight: 0.4, + capitalHeight: 0.5, + materialPreset: 'concrete', + slots: { shaft: 'library:stone' }, + }) + const base = ColumnNode.parse({ ...original, ...columnSectionReset('Base') }) + expect(base.baseHeight).toBe(ColumnNode.parse({}).baseHeight) + expect(base.height).toBe(4) + expect(base.capitalHeight).toBe(0.5) + expect(base.slots).toEqual(original.slots) + const finish = ColumnNode.parse({ ...original, ...columnSectionReset('Materials') }) + expect(finish.material).toBeUndefined() + expect(finish.materialPreset).toBeUndefined() + expect(finish.slots).toEqual(NEW_COLUMN_SLOTS) + expect(finish.height).toBe(4) +}) + +test('switching preset previews cancels cleanly and applying is one undoable edit', () => { + const original = ColumnNode.parse({ name: 'Keep name', materialPreset: 'concrete' }) + useScene.setState({ nodes: { [original.id]: original }, dirtyNodes: new Set(), readOnly: false }) + clearSceneHistory() + const preview = createColumnPropertyPreview(original.id) + const ids = Object.keys(COLUMN_PRESETS) as ColumnPresetId[] + preview.preview(columnPresetUpdates(ids[1]!)) + expect(useScene.getState().nodes[original.id]).toBe(original) + preview.cancel() + expect(useLiveNodeOverrides.getState().get(original.id)).toBeUndefined() + expect(useScene.temporal.getState().pastStates).toHaveLength(0) + preview.preview(columnPresetUpdates(ids[2]!)) + preview.commit() + expect(useScene.getState().nodes[original.id]).toMatchObject({ + name: 'Keep name', + materialPreset: 'concrete', + ...columnPresetUpdates(ids[2]!), + }) + expect(useScene.temporal.getState().pastStates).toHaveLength(1) + useScene.temporal.getState().undo() + expect(useScene.getState().nodes[original.id]).toEqual(original) +}) + +test('material reset clears persisted finishes and undo restores them', () => { + const original = ColumnNode.parse({ + materialPreset: 'concrete', + slots: { shaft: 'library:stone' }, + }) + useScene.setState({ nodes: { [original.id]: original }, dirtyNodes: new Set(), readOnly: false }) + clearSceneHistory() + const preview = createColumnPropertyPreview(original.id) + preview.preview(columnSectionReset('Materials')) + preview.commit() + const changed = useScene.getState().nodes[original.id] as ColumnNode + expect(changed.materialPreset).toBeUndefined() + expect(changed.slots).toEqual(NEW_COLUMN_SLOTS) + expect(changed.height).toBe(original.height) + expect(useScene.temporal.getState().pastStates).toHaveLength(1) + useScene.temporal.getState().undo() + expect(useScene.getState().nodes[original.id]).toEqual(original) +}) diff --git a/packages/nodes/src/column/presets.ts b/packages/nodes/src/column/presets.ts new file mode 100644 index 0000000000..dfe64c6109 --- /dev/null +++ b/packages/nodes/src/column/presets.ts @@ -0,0 +1,100 @@ +import { COLUMN_PRESETS, ColumnNode, type ColumnPresetId, NEW_COLUMN_SLOTS } from '@pascal-app/core' + +export function columnPresetUpdates(id: ColumnPresetId): Partial { + const { label: _label, ...preset } = COLUMN_PRESETS[id] + return { supportStyle: 'vertical', ...preset } +} + +const resetFields = { + Shape: [ + 'style', + 'crossSection', + 'edgeSoftness', + 'shaftCornerRadius', + 'supportStyle', + 'bracePlateEnabled', + ], + Size: [ + 'height', + 'width', + 'depth', + 'radius', + 'braceWidth', + 'braceDepth', + 'braceBottomSpread', + 'braceTopSpread', + ], + Profile: [ + 'shaftProfile', + 'shaftTaper', + 'shaftBulge', + 'shaftStartScale', + 'shaftEndScale', + 'shaftSegmentCount', + 'shaftTwistStep', + ], + Base: [ + 'baseStyle', + 'baseHeight', + 'baseWidthScale', + 'baseDepthScale', + 'baseTierCount', + 'baseStepSpread', + 'basePlinthHeightRatio', + 'baseRoundBandScale', + 'baseNeckScale', + 'baseRoundBandCount', + 'baseRibCount', + 'baseCarvingLevel', + 'basePanelInset', + ], + Capital: [ + 'capitalStyle', + 'capitalHeight', + 'capitalWidthScale', + 'capitalDepthScale', + 'capitalTierCount', + 'capitalStepSpread', + 'capitalBandCount', + 'voluteSize', + 'voluteCount', + 'leafCount', + 'leafRows', + 'bracketDepth', + 'bracketTierCount', + 'pendantCount', + 'capitalCarvingLevel', + ], + 'Surface Details': [ + 'shaftDetail', + 'fluteCount', + 'fluteDepth', + 'fluteWidth', + 'spiralTwist', + 'spiralRibCount', + 'panelCount', + 'panelInsetDepth', + 'panelShape', + 'latheRingCount', + 'latheRingSpacing', + 'ringCount', + 'ringPlacement', + 'ringThickness', + 'ringSpread', + 'carvingLevel', + 'carvingPlacement', + 'lowerBandEnabled', + 'lowerBandHeight', + 'lowerBandCarvingLevel', + 'dentilCount', + 'beadCount', + ], + Materials: ['material', 'materialPreset', 'slots'], + Transform: ['rotation'], +} as const satisfies Record + +export type ColumnResetSection = keyof typeof resetFields +export function columnSectionReset(section: ColumnResetSection): Partial { + const defaults = ColumnNode.parse({ slots: { ...NEW_COLUMN_SLOTS } }) + return Object.fromEntries(resetFields[section].map((key) => [key, defaults[key]])) +} diff --git a/packages/nodes/src/column/property-preview.test.ts b/packages/nodes/src/column/property-preview.test.ts new file mode 100644 index 0000000000..907bb35933 --- /dev/null +++ b/packages/nodes/src/column/property-preview.test.ts @@ -0,0 +1,74 @@ +import { expect, test } from 'bun:test' +import { + ColumnNode, + clearSceneHistory, + ItemNode, + useLiveNodeOverrides, + useScene, +} from '@pascal-app/core' +import { boxAsset, installMountedScene } from '../__tests__/harness' +import { createColumnPropertyPreview } from './property-preview' +import { columnTopSurfaces } from './surface' + +installMountedScene() +function seed() { + const host = ColumnNode.parse({ + crossSection: 'rectangular', + width: 1, + depth: 1, + capitalStyle: 'simple', + height: 2, + }) + const child = ItemNode.parse({ + parentId: host.id, + asset: boxAsset, + position: [0.2, columnTopSurfaces(host)[0]!.position[1], 0], + }) + host.children = [child.id] + useScene.setState({ + nodes: { [host.id]: host, [child.id]: child }, + dirtyNodes: new Set(), + readOnly: false, + }) + clearSceneHistory() + return { host, child, preview: createColumnPropertyPreview(host.id) } +} +test('inspector height previews carry hosted children without scene writes and commit one undo step', () => { + const { host, child, preview } = seed() + const baseline = useScene.getState().nodes + preview.preview({ height: 3 }) + preview.preview({ height: 4 }) + expect(useScene.getState().nodes).toBe(baseline) + expect(useLiveNodeOverrides.getState().get(host.id)?.height).toBe(4) + expect(useLiveNodeOverrides.getState().get(child.id)?.position).toEqual([0.2, 4, 0]) + expect(useScene.temporal.getState().pastStates).toHaveLength(0) + preview.commit() + expect(useLiveNodeOverrides.getState().overrides.size).toBe(0) + expect(useScene.getState().nodes[host.id]).toMatchObject({ height: 4 }) + expect(useScene.temporal.getState().pastStates).toHaveLength(1) + useScene.temporal.getState().undo() + expect(useScene.getState().nodes[host.id]).toEqual(host) + expect(useScene.getState().nodes[child.id]).toEqual(child) +}) +test('cancelling a property preview restores both nodes and preserves unrelated override fields', () => { + const { host, child, preview } = seed() + const baseline = useScene.getState().nodes + useLiveNodeOverrides.getState().set(host.id, { visible: false }) + preview.preview({ height: 3 }) + preview.cancel() + expect(useScene.getState().nodes).toBe(baseline) + expect(useLiveNodeOverrides.getState().get(host.id)).toEqual({ visible: false }) + expect(useLiveNodeOverrides.getState().get(child.id)).toBeUndefined() + expect(useScene.temporal.getState().pastStates).toHaveLength(0) +}) +test('a rejected resize retains the last valid preview and a no-op produces no undo', () => { + const { host, preview } = seed() + preview.preview({ height: host.height }) + preview.commit() + expect(useScene.temporal.getState().pastStates).toHaveLength(0) + preview.preview({ width: 0.8 }) + preview.preview({ width: 0.01 }) + expect(useLiveNodeOverrides.getState().get(host.id)?.width).toBe(0.8) + preview.commit() + expect(useScene.getState().nodes[host.id]).toMatchObject({ width: 0.8 }) +}) diff --git a/packages/nodes/src/column/property-preview.ts b/packages/nodes/src/column/property-preview.ts new file mode 100644 index 0000000000..1bd291ee9b --- /dev/null +++ b/packages/nodes/src/column/property-preview.ts @@ -0,0 +1,50 @@ +import { type AnyNodeId, type ColumnNode, useLiveNodeOverrides, useScene } from '@pascal-app/core' +import { planColumnEdit } from './hosted-resize' + +/** A property gesture owns only the fields it previews, including hosted-child positions. */ +export function createColumnPropertyPreview(id: AnyNodeId) { + let pending: Partial = {} + const fields = new Map() + const clear = () => { + for (const [nodeId, keys] of fields) { + useLiveNodeOverrides.getState().clearFields(nodeId, keys) + if (useScene.getState().nodes[nodeId]) useScene.getState().markDirty(nodeId) + } + fields.clear() + } + return { + preview(patch: Partial) { + const next = { ...pending, ...patch } + const updates = planColumnEdit(id, next) + if (!updates || useScene.getState().readOnly) return + pending = next + clear() + for (const [nodeId, data] of updates) fields.set(nodeId, Object.keys(data)) + useLiveNodeOverrides.getState().setMany(updates) + for (const [nodeId] of updates) useScene.getState().markDirty(nodeId) + }, + commit() { + const updates = planColumnEdit(id, pending) + try { + if (!updates) return + const nodes = useScene.getState().nodes + const changed = updates.filter(([nodeId, data]) => + Object.entries(data).some( + ([key, value]) => + JSON.stringify((nodes[nodeId] as Record | undefined)?.[key]) !== + JSON.stringify(value), + ), + ) + if (changed.length) + useScene.getState().updateNodes(changed.map(([id, data]) => ({ id, data }))) + } finally { + clear() + pending = {} + } + }, + cancel() { + clear() + pending = {} + }, + } +} diff --git a/packages/nodes/src/column/renderer.test.tsx b/packages/nodes/src/column/renderer.test.tsx new file mode 100644 index 0000000000..084eaa6761 --- /dev/null +++ b/packages/nodes/src/column/renderer.test.tsx @@ -0,0 +1,349 @@ +import { expect, test } from 'bun:test' +import { + COLUMN_PRESETS, + ColumnNode, + type ColumnNode as ColumnNodeType, + type ColumnSlotId, + sceneRegistry, + useScene, +} from '@pascal-app/core' +import { createMaterialFromPresetRef, OVERLAY_LAYER, useViewer } from '@pascal-app/viewer' +import { act } from '@react-three/test-renderer' +import { Box3, type Mesh, Raycaster, Vector3 } from 'three' +import { installMountedScene, mount } from '../__tests__/harness' +import { columnFootprintHalf } from './bounds' +import { columnDefinition } from './definition' +import { createColumnSpiralGeometry } from './geometry' +import { clearColumnInspectorHighlight, setColumnInspectorHighlight } from './inspector-highlight' +import { ColumnRenderer, resolveColumnSlotMaterial } from './renderer' + +installMountedScene() +const frames = [ + 'a-frame', + 'y-frame', + 'v-frame', + 'x-brace', + 'k-brace', + 'single-strut', + 'tripod', + 'trestle', + 'portal-frame', + 'box-frame', +] as const +const examples = [ + ...Object.entries(COLUMN_PRESETS).map(([name, preset]) => ({ + name, + node: ColumnNode.parse(preset), + })), + { + name: 'twisted decorated rectangular', + node: ColumnNode.parse({ + crossSection: 'rectangular', + shaftProfile: 'bulged', + shaftBulge: 0.4, + shaftTwistStep: 12, + shaftStartScale: 1.6, + shaftEndScale: 1.2, + ringCount: 6, + latheRingCount: 8, + lowerBandEnabled: true, + carvingPlacement: 'all', + panelCount: 4, + spiralRibCount: 2, + spiralTwist: 1, + }), + }, + ...frames.map((supportStyle) => ({ + name: supportStyle, + node: ColumnNode.parse({ + supportStyle, + braceBottomSpread: 4, + braceTopSpread: 3, + braceWidth: 0.7, + braceDepth: 0.6, + }), + })), +] +for (const { name, node } of examples) { + test(`${name} collision envelope contains its rendered geometry`, async () => { + useScene.setState({ nodes: { [node.id]: node } }) + await mount() + const root = sceneRegistry.nodes.get(node.id)! + root.updateMatrixWorld(true) + const actual = new Box3().setFromObject(root, true) + const bounds = columnFootprintHalf(node) + expect(actual.min.x).toBeGreaterThanOrEqual(-bounds.halfX - 1e-6) + expect(actual.max.x).toBeLessThanOrEqual(bounds.halfX + 1e-6) + expect(actual.min.z).toBeGreaterThanOrEqual(-bounds.halfZ - 1e-6) + expect(actual.max.z).toBeLessThanOrEqual(bounds.halfZ + 1e-6) + }) +} +test('resizing and unmounting releases owned geometry without disposing shared materials', async () => { + const node = ColumnNode.parse({ crossSection: 'rectangular', shaftProfile: 'tapered' }) + useScene.setState({ nodes: { [node.id]: node } }) + const renderer = await mount() + const geometries = new Set() + const materials = new Set() + sceneRegistry.nodes.get(node.id)!.traverse((object) => { + const mesh = object as Mesh + if (mesh.isMesh) { + geometries.add(mesh.geometry) + materials.add(mesh.material) + } + }) + const disposed = new Set() + let disposedMaterials = 0 + for (const geometry of geometries) + geometry.addEventListener('dispose', () => disposed.add(geometry)) + for (const material of materials) + for (const entry of Array.isArray(material) ? material : [material]) + entry.addEventListener('dispose', () => disposedMaterials++) + await renderer.update() + expect(disposed.size).toBeGreaterThan(0) + await renderer.unmount() + expect(disposed.size).toBe(geometries.size) + expect(disposedMaterials).toBe(0) +}) + +for (const crossSection of ['round', 'rectangular', 'octagonal'] as const) { + test(`${crossSection} tapered shaft is continuous and ends at the declared top`, async () => { + const node = ColumnNode.parse({ + crossSection, + baseStyle: 'none', + capitalStyle: 'none', + shaftProfile: 'tapered', + shaftStartScale: 1, + shaftEndScale: 0.5, + shaftTaper: 0, + shaftSegmentCount: 8, + shaftCornerRadius: 0, + shaftDetail: 'none', + ringCount: 0, + height: 4, + radius: 0.5, + width: 1, + depth: 1, + }) + useScene.setState({ nodes: { [node.id]: node } }) + await mount() + const root = sceneRegistry.nodes.get(node.id)! + root.updateMatrixWorld(true) + const bounds = new Box3().setFromObject(root, true) + expect(bounds.max.y).toBeCloseTo(4, 6) + const top = new Raycaster(new Vector3(0.1, 5, 0), new Vector3(0, -1, 0)).intersectObject( + root, + true, + ) + expect(top[0]!.point.y).toBeCloseTo(4, 6) + // Adjacent samples must follow the same slope through a former section boundary. + const hits = [1.999, 2, 2.001].map( + (y) => + new Raycaster(new Vector3(2, y, 0), new Vector3(-1, 0, 0)).intersectObject(root, true)[0]! + .point.x, + ) + expect(hits[0]! - hits[2]!).toBeCloseTo(0.000125, 5) + expect(hits[1]).toBeCloseTo(0.375, 5) + }) +} + +test('flutes recess into a tapered shaft rather than adding rods', async () => { + const node = ColumnNode.parse({ + baseStyle: 'none', + capitalStyle: 'none', + radius: 0.5, + shaftProfile: 'tapered', + shaftStartScale: 1, + shaftEndScale: 0.5, + shaftTaper: 0, + shaftDetail: 'fluted', + fluteCount: 16, + fluteDepth: 0.04, + fluteWidth: 0.08, + ringCount: 0, + height: 4, + }) + useScene.setState({ nodes: { [node.id]: node } }) + await mount() + const root = sceneRegistry.nodes.get(node.id)! + root.updateMatrixWorld(true) + const groove = new Raycaster(new Vector3(2, 2, 0), new Vector3(-1, 0, 0)).intersectObject( + root, + true, + )[0]! + expect(groove.point.x).toBeCloseTo(0.375 - 0.04, 5) + const angle = Math.PI / 16 + const direction = new Vector3(Math.cos(angle), 0, Math.sin(angle)) + const crest = new Raycaster( + direction.clone().multiplyScalar(2).setY(2), + direction.clone().negate(), + ).intersectObject(root, true)[0]! + expect(Math.hypot(crest.point.x, crest.point.z)).toBeCloseTo(0.375, 5) +}) + +test('spiral rib centers follow the bulged and twisted shaft surface', () => { + const node = ColumnNode.parse({ + radius: 0.5, + shaftProfile: 'bulged', + shaftBulge: 0.2, + shaftStartScale: 0.8, + shaftEndScale: 0.4, + shaftTaper: 0, + shaftTwistStep: 10, + shaftSegmentCount: 24, + spiralRibCount: 1, + spiralTwist: 1, + shaftDetail: 'none', + fluteCount: 0, + }) + const geometry = createColumnSpiralGeometry(node, 4)! + const positions = geometry.getAttribute('position') + // Six tube vertices surround each center; the seventh duplicates its UV seam. + const row = 24, + center = new Vector3() + for (let j = 0; j < 6; j++) center.add(new Vector3().fromBufferAttribute(positions, row * 7 + j)) + center.multiplyScalar(1 / 6) + const t = center.y / 4 + expect(t).toBeGreaterThan(0.45) + expect(t).toBeLessThan(0.55) + expect(Math.hypot(center.x, center.z)).toBeCloseTo( + 0.5 * (0.8 - 0.4 * t + 0.2 * Math.sin(Math.PI * t)), + 3, + ) + expect(Math.atan2(center.z, center.x)).toBeCloseTo( + ((t - 0.02) / 0.96) * Math.PI * 2 - (t * 230 * Math.PI) / 180, + 3, + ) + geometry.dispose() +}) + +for (const edgeSoftness of [0, 0.04]) { + test(`shaft end softness ${edgeSoftness} preserves its envelope and planar top`, async () => { + const node = ColumnNode.parse({ + baseStyle: 'none', + capitalStyle: 'none', + radius: 0.5, + shaftProfile: 'straight', + shaftStartScale: 1, + shaftEndScale: 1, + shaftTaper: 0, + fluteCount: 0, + ringCount: 0, + edgeSoftness, + height: 3, + }) + useScene.setState({ nodes: { [node.id]: node } }) + await mount() + const root = sceneRegistry.nodes.get(node.id)! + root.updateMatrixWorld(true) + const box = new Box3().setFromObject(root, true) + expect(box.min.y).toBeCloseTo(0, 6) + expect(box.max.y).toBeCloseTo(3, 6) + expect(box.max.x).toBeCloseTo(0.5, 6) + const ray = (x: number) => + new Raycaster(new Vector3(x, 4, 0), new Vector3(0, -1, 0)).intersectObject(root, true)[0]! + expect(ray(0.1).point.y).toBeCloseTo(3, 6) + if (edgeSoftness) expect(ray(0.49).point.y).toBeLessThan(2.999) + else expect(ray(0.49).point.y).toBeCloseTo(3, 6) + }) +} + +test('lotus neck reaches the shaft without an air gap', async () => { + const node = ColumnNode.parse({ + baseStyle: 'lotus', + baseHeight: 0.5, + baseRibCount: 0, + capitalStyle: 'none', + edgeSoftness: 0, + ringCount: 0, + }) + useScene.setState({ nodes: { [node.id]: node } }) + await mount() + const root = sceneRegistry.nodes.get(node.id)! + root.updateMatrixWorld(true) + for (const y of [0.495, 0.505]) { + expect( + new Raycaster(new Vector3(2, y, 0), new Vector3(-1, 0, 0)).intersectObject(root, true).length, + ).toBeGreaterThan(0) + } +}) + +test('inspector hover isolates the named part without changing materials, picking, or scene data', async () => { + const node = ColumnNode.parse({ baseStyle: 'simple-square', capitalStyle: 'simple' }) + useScene.setState({ nodes: { [node.id]: node } }) + const renderer = await mount() + const root = sceneRegistry.nodes.get(node.id)! + const originals: Mesh[] = [] + root.traverse((object) => { + const mesh = object as Mesh + if (mesh.isMesh) originals.push(mesh) + }) + const materials = originals.map((mesh) => mesh.material) + const nodes = useScene.getState().nodes + const boundsBefore = new Box3().setFromObject(root, true) + const owner = Symbol('inspector test') + try { + await act(async () => setColumnInspectorHighlight(owner, node.id, { part: 'base', axis: 'y' })) + const highlights: Mesh[] = [] + root.parent!.getObjectByName('column-inspector-highlight')!.traverse((object) => { + const mesh = object as Mesh + if (mesh.isMesh && mesh.layers.isEnabled(OVERLAY_LAYER)) highlights.push(mesh) + }) + expect(highlights.length).toBeGreaterThan(0) + for (const mesh of highlights) { + expect( + originals.some( + (original) => original.userData.slotId === 'base' && original.geometry === mesh.geometry, + ), + ).toBe(true) + expect(mesh.userData.pascalExport).toBe('strip') + const hits: ReturnType = [] + mesh.raycast(new Raycaster(), hits) + expect(hits).toHaveLength(0) + } + expect(originals.map((mesh) => mesh.material)).toEqual(materials) + expect(useScene.getState().nodes).toBe(nodes) + expect(new Box3().setFromObject(root, true)).toEqual(boundsBefore) + expect(useViewer.getState().hoveredId).toBe(node.id) + await act(async () => clearColumnInspectorHighlight(Symbol('another inspector'))) + expect( + root.parent!.getObjectByName('column-inspector-highlight')!.children.length, + ).toBeGreaterThan(0) + let disposed = 0 + for (const mesh of originals) mesh.geometry.addEventListener('dispose', () => disposed++) + await act(async () => clearColumnInspectorHighlight(owner)) + expect(root.parent!.getObjectByName('column-inspector-highlight')!.children).toHaveLength(0) + expect(useViewer.getState().hoveredId).toBeNull() + expect(disposed).toBe(0) + } finally { + clearColumnInspectorHighlight(owner) + await renderer.unmount() + } +}) + +test('saved columns without slots keep the legacy finish; new columns are white', () => { + const resolve = (node: ColumnNodeType, slotId: ColumnSlotId) => + resolveColumnSlotMaterial({ + colorPreset: 'white', + legacyMaterial: null, + node, + sceneMaterials: {}, + shading: 'rendered', + slotId, + textures: true, + }) + const color = (ref: string) => + ( + createMaterialFromPresetRef(ref, 'rendered') as unknown as { color: { getHex(): number } } + ).color.getHex() + const finish = (material: unknown) => (material as { color: { getHex(): number } }).color.getHex() + expect(color('library:concrete-plaster')).not.toBe(color('library:preset-white')) + + const saved = ColumnNode.parse({ supportStyle: 'k-brace' }) + expect(saved.slots).toBeUndefined() + expect(finish(resolve(saved, 'shaft'))).toBe(color('library:concrete-plaster')) + expect(finish(resolve(saved, 'frame'))).toBe(color('library:metal-steel')) + + const placed = ColumnNode.parse({ ...columnDefinition.defaults(), supportStyle: 'k-brace' }) + expect(finish(resolve(placed, 'shaft'))).toBe(color('library:preset-white')) + expect(finish(resolve(placed, 'frame'))).toBe(color('library:preset-white')) +}) diff --git a/packages/nodes/src/column/renderer.tsx b/packages/nodes/src/column/renderer.tsx index 1cb719a0cf..9142baf7da 100644 --- a/packages/nodes/src/column/renderer.tsx +++ b/packages/nodes/src/column/renderer.tsx @@ -32,17 +32,17 @@ import { useNodeEvents, useViewer, } from '@pascal-app/viewer' -import { createContext, type ReactNode, useContext, useEffect, useMemo, useRef } from 'react' +import { createContext, memo, type ReactNode, useContext, useEffect, useMemo, useRef } from 'react' import { BufferGeometry, Float32BufferAttribute, type Group, type Material } from 'three' import { ScriptedOpeningModel } from '../shared/scripted-opening' import { - columnCapitalBlocks, - columnShaftLayout, - getSegments, - getShaftScaleAt, - getShaftSegmentCount, - getShaftTwistRadians, -} from './shape' + createColumnBandGeometry, + createColumnPanelGeometry, + createColumnShaftGeometry, + createColumnSpiralGeometry, +} from './geometry' +import { ColumnInspectorOverlay } from './inspector-highlight' +import { columnCapitalBlocks, columnShaftLayout, getSegments } from './shape' type ColumnSlotMaterials = Record type SceneMaterials = ReturnType['materials'] @@ -93,7 +93,7 @@ function createLegacyColumnMaterial({ return baseMaterial(shading) } -function resolveColumnSlotMaterial({ +export function resolveColumnSlotMaterial({ colorPreset, legacyMaterial, node, @@ -216,6 +216,8 @@ function MappedBox({ return createColumnBoxGeometry(width, height, depth, bevelRadius) }, [bevelRadius, depth, height, width]) + useEffect(() => () => geometry?.dispose(), [geometry]) + if (!geometry) return null return ( @@ -332,6 +334,8 @@ function FlatEndedBeam({ return geometry }, [depth, length, start, end, width]) + useEffect(() => () => geometry?.dispose(), [geometry]) + if (!geometry) return null return ( @@ -344,8 +348,8 @@ function FlatEndedBeam({ function AFrameSupport({ node }: { node: ColumnNode }) { const height = Math.max(0.2, node.height) - const braceWidth = clamp(node.braceWidth ?? node.width, 0.04, 1.6) - const braceDepth = clamp(node.braceDepth ?? node.depth, 0.04, 1.6) + const braceWidth = Math.max(0.04, node.braceWidth ?? node.width) + const braceDepth = Math.max(0.04, node.braceDepth ?? node.depth) const bottomSpread = Math.max(0.2, node.braceBottomSpread ?? Math.max(node.width * 3, 1.2)) const topSpread = clamp(node.braceTopSpread ?? 0.12, 0, bottomSpread) const bottomY = 0 @@ -392,8 +396,8 @@ function AFrameSupport({ node }: { node: ColumnNode }) { function YFrameSupport({ node }: { node: ColumnNode }) { const height = Math.max(0.2, node.height) - const braceWidth = clamp(node.braceWidth ?? node.width, 0.04, 1.6) - const braceDepth = clamp(node.braceDepth ?? node.depth, 0.04, 1.6) + const braceWidth = Math.max(0.04, node.braceWidth ?? node.width) + const braceDepth = Math.max(0.04, node.braceDepth ?? node.depth) const topSpread = Math.max(0.2, node.braceTopSpread ?? 0.9) const splitY = height * 0.56 const foot: VectorTuple = [0, 0, 0] @@ -433,8 +437,8 @@ function YFrameSupport({ node }: { node: ColumnNode }) { function VFrameSupport({ node }: { node: ColumnNode }) { const height = Math.max(0.2, node.height) - const braceWidth = clamp(node.braceWidth ?? node.width, 0.04, 1.6) - const braceDepth = clamp(node.braceDepth ?? node.depth, 0.04, 1.6) + const braceWidth = Math.max(0.04, node.braceWidth ?? node.width) + const braceDepth = Math.max(0.04, node.braceDepth ?? node.depth) const topSpread = Math.max(0.2, node.braceTopSpread ?? 1) const foot: VectorTuple = [0, 0, 0] const leftTop: VectorTuple = [-topSpread / 2, height, 0] @@ -471,8 +475,8 @@ function VFrameSupport({ node }: { node: ColumnNode }) { function XBraceSupport({ node }: { node: ColumnNode }) { const height = Math.max(0.2, node.height) - const braceWidth = clamp(node.braceWidth ?? node.width, 0.04, 1.6) - const braceDepth = clamp(node.braceDepth ?? node.depth, 0.04, 1.6) + const braceWidth = Math.max(0.04, node.braceWidth ?? node.width) + const braceDepth = Math.max(0.04, node.braceDepth ?? node.depth) const bottomSpread = Math.max(0.2, node.braceBottomSpread ?? 1) const topSpread = Math.max(0.2, node.braceTopSpread ?? 1) const leftBottom: VectorTuple = [-bottomSpread / 2, 0, 0] @@ -523,8 +527,8 @@ function XBraceSupport({ node }: { node: ColumnNode }) { function KBraceSupport({ node }: { node: ColumnNode }) { const height = Math.max(0.2, node.height) - const braceWidth = clamp(node.braceWidth ?? node.width, 0.04, 1.6) - const braceDepth = clamp(node.braceDepth ?? node.depth, 0.04, 1.6) + const braceWidth = Math.max(0.04, node.braceWidth ?? node.width) + const braceDepth = Math.max(0.04, node.braceDepth ?? node.depth) const spread = Math.max(0.2, Math.max(node.braceBottomSpread ?? 1, node.braceTopSpread ?? 1)) const leftBottom: VectorTuple = [-spread / 2, 0, 0] const leftTop: VectorTuple = [-spread / 2, height, 0] @@ -574,8 +578,8 @@ function KBraceSupport({ node }: { node: ColumnNode }) { function SingleStrutSupport({ node }: { node: ColumnNode }) { const height = Math.max(0.2, node.height) - const braceWidth = clamp(node.braceWidth ?? node.width, 0.04, 1.6) - const braceDepth = clamp(node.braceDepth ?? node.depth, 0.04, 1.6) + const braceWidth = Math.max(0.04, node.braceWidth ?? node.width) + const braceDepth = Math.max(0.04, node.braceDepth ?? node.depth) const spread = Math.max(0.2, Math.max(node.braceBottomSpread ?? 1, node.braceTopSpread ?? 1)) const bottom: VectorTuple = [-spread / 2, 0, 0] const top: VectorTuple = [spread / 2, height, 0] @@ -608,8 +612,8 @@ function SingleStrutSupport({ node }: { node: ColumnNode }) { function TripodSupport({ node }: { node: ColumnNode }) { const height = Math.max(0.2, node.height) - const braceWidth = clamp(node.braceWidth ?? node.width, 0.04, 1.6) - const braceDepth = clamp(node.braceDepth ?? node.depth, 0.04, 1.6) + const braceWidth = Math.max(0.04, node.braceWidth ?? node.width) + const braceDepth = Math.max(0.04, node.braceDepth ?? node.depth) const width = Math.max(0.2, node.braceBottomSpread ?? 1.1) const depth = Math.max(0.2, node.braceTopSpread ?? 1.1) const top: VectorTuple = [0, height, 0] @@ -658,8 +662,8 @@ function TripodSupport({ node }: { node: ColumnNode }) { function TrestleSupport({ node }: { node: ColumnNode }) { const height = Math.max(0.2, node.height) - const braceWidth = clamp(node.braceWidth ?? node.width, 0.04, 1.6) - const braceDepth = clamp(node.braceDepth ?? node.depth, 0.04, 1.6) + const braceWidth = Math.max(0.04, node.braceWidth ?? node.width) + const braceDepth = Math.max(0.04, node.braceDepth ?? node.depth) const width = Math.max(0.2, node.braceBottomSpread ?? 1.2) const depth = Math.max(0.2, node.braceTopSpread ?? 1) const zPositions = [-depth / 2, depth / 2] @@ -719,8 +723,8 @@ function TrestleSupport({ node }: { node: ColumnNode }) { function PortalFrameSupport({ node }: { node: ColumnNode }) { const height = Math.max(0.2, node.height) - const braceWidth = clamp(node.braceWidth ?? node.width, 0.04, 1.6) - const braceDepth = clamp(node.braceDepth ?? node.depth, 0.04, 1.6) + const braceWidth = Math.max(0.04, node.braceWidth ?? node.width) + const braceDepth = Math.max(0.04, node.braceDepth ?? node.depth) const width = Math.max(0.2, node.braceBottomSpread ?? 1.4) const leftBottom: VectorTuple = [-width / 2, 0, 0] const rightBottom: VectorTuple = [width / 2, 0, 0] @@ -763,8 +767,8 @@ function PortalFrameSupport({ node }: { node: ColumnNode }) { function BoxFrameSupport({ node }: { node: ColumnNode }) { const height = Math.max(0.2, node.height) - const braceWidth = clamp(node.braceWidth ?? node.width, 0.04, 1.6) - const braceDepth = clamp(node.braceDepth ?? node.depth, 0.04, 1.6) + const braceWidth = Math.max(0.04, node.braceWidth ?? node.width) + const braceDepth = Math.max(0.04, node.braceDepth ?? node.depth) const width = Math.max(0.2, node.braceBottomSpread ?? 1.4) const depth = Math.max(0.2, node.braceTopSpread ?? 1) const corners: VectorTuple[] = [ @@ -867,6 +871,8 @@ function MappedCylinder({ }) }, [height, radius, radiusBottom, radiusTop, radiusX, radiusZ, segments]) + useEffect(() => () => geometry?.dispose(), [geometry]) + if (!geometry) return null return ( @@ -912,6 +918,8 @@ function MappedCone({ }) }, [height, radiusX, radiusZ, segments]) + useEffect(() => () => geometry?.dispose(), [geometry]) + if (!geometry) return null return ( @@ -946,6 +954,8 @@ function MappedSphere({ return createColumnSphereGeometry(radius, segments, verticalSegments) }, [radius, segments, verticalSegments]) + useEffect(() => () => geometry?.dispose(), [geometry]) + if (!geometry) return null return ( @@ -988,6 +998,8 @@ function MappedTorus({ }) }, [arc, ringRadius, scaleX, scaleY, scaleZ, tubeRadius]) + useEffect(() => () => geometry?.dispose(), [geometry]) + if (!geometry) return null return ( @@ -1030,74 +1042,67 @@ function SquareBlock({ } function RoundBlock({ - x = 0, y, - z = 0, height, radius, + radiusX = 1, + radiusZ = 1, segments = 32, + x = 0, + z = 0, }: { - x?: number y: number - z?: number height: number radius: number + radiusX?: number + radiusZ?: number segments?: number + x?: number + z?: number }) { + const edgeSoftness = useContext(ColumnEdgeSoftnessContext) + const slotId = useContext(ColumnSlotContext) + const geometry = useMemo(() => { + const geometry = createColumnShaftGeometry( + { + crossSection: segments === 8 ? 'octagonal' : segments === 16 ? 'sixteen-sided' : 'round', + radius, + width: radius * 2, + depth: radius * 2, + shaftProfile: 'straight', + shaftTaper: 0, + shaftBulge: 0, + shaftStartScale: 1, + shaftEndScale: 1, + shaftSegmentCount: 1, + shaftTwistStep: 0, + shaftCornerRadius: 0, + edgeSoftness: edgeSoftness / Math.max(1, radiusX, radiusZ), + fluteCount: 0, + fluteWidth: 0.02, + fluteDepth: 0, + shaftDetail: 'none', + }, + height, + ) + geometry.scale(radiusX, 1, radiusZ) + const uv = geometry.getAttribute('uv') + const circumferenceRatio = Math.sqrt((radiusX ** 2 + radiusZ ** 2) / 2) + const positions = geometry.getAttribute('position'), + normals = geometry.getAttribute('normal') + for (let i = 0; i < uv.count; i++) { + if (Math.abs(normals.getY(i)) > 0.99) uv.setXY(i, positions.getX(i), positions.getZ(i)) + else uv.setX(i, uv.getX(i) * circumferenceRatio) + } + geometry.setAttribute('uv2', uv.clone()) + return geometry + }, [radius, radiusX, radiusZ, segments, height, edgeSoftness]) + useEffect(() => () => geometry.dispose(), [geometry]) return ( - - ) -} - -function RoundedRectangleShaftSegment({ - y, - height, - width, - depth, - cornerRadius, -}: { - y: number - height: number - width: number - depth: number - cornerRadius: number -}) { - if (height <= 0) return null - - const radius = Math.min(Math.max(0, cornerRadius), Math.min(width, depth) * 0.45) - if (radius <= 0.001) { - return - } - - const innerWidth = Math.max(0, width - radius * 2) - const innerDepth = Math.max(0, depth - radius * 2) - const cornerX = width / 2 - radius - const cornerZ = depth / 2 - radius - - return ( - - {innerWidth > 0 && ( - - )} - {innerDepth > 0 && ( - - )} - {( - [ - [cornerX, cornerZ], - [cornerX, -cornerZ], - [-cornerX, cornerZ], - [-cornerX, -cornerZ], - ] satisfies [number, number][] - ).map(([x, z], index) => ( - - ))} - + + + + ) } @@ -1114,13 +1119,14 @@ function OvalBlock({ depth: number segments?: number }) { + const radius = Math.min(width, depth) / 2 return ( - ) @@ -1150,52 +1156,84 @@ function ColumnBlock({ return } -function TaperedRoundShaft({ node, y, height }: { node: ColumnNode; y: number; height: number }) { - const segmentCount = getShaftSegmentCount(node) - const segmentHeight = height / segmentCount - - return ( - - {Array.from({ length: segmentCount }, (_, index) => { - const t = (index + 0.5) / segmentCount - const profileScale = getShaftScaleAt(node, t) - return ( - - - - ) - })} - +function MergedShaft({ node, y, height }: { node: ColumnNode; y: number; height: number }) { + const { + crossSection, + radius, + width, + depth, + shaftProfile, + shaftTaper, + shaftBulge, + shaftStartScale, + shaftEndScale, + shaftSegmentCount, + shaftTwistStep, + shaftCornerRadius, + edgeSoftness, + fluteCount, + fluteWidth, + fluteDepth, + shaftDetail, + } = node + const geometry = useMemo( + () => + createColumnShaftGeometry( + { + crossSection, + radius, + width, + depth, + shaftProfile, + shaftTaper, + shaftBulge, + shaftStartScale, + shaftEndScale, + shaftSegmentCount, + shaftTwistStep, + shaftCornerRadius, + edgeSoftness, + fluteCount, + fluteWidth, + fluteDepth, + shaftDetail, + }, + height, + ), + [ + height, + crossSection, + radius, + width, + depth, + shaftProfile, + shaftTaper, + shaftBulge, + shaftStartScale, + shaftEndScale, + shaftSegmentCount, + shaftTwistStep, + shaftCornerRadius, + edgeSoftness, + fluteCount, + fluteWidth, + fluteDepth, + shaftDetail, + ], ) -} - -function TaperedSquareShaft({ node, y, height }: { node: ColumnNode; y: number; height: number }) { - const segmentCount = getShaftSegmentCount(node) - const segmentHeight = height / segmentCount - + useEffect(() => () => geometry?.dispose(), [geometry]) + if (!geometry) return null return ( - - {Array.from({ length: segmentCount }, (_, index) => { - const t = (index + 0.5) / segmentCount - const profileScale = getShaftScaleAt(node, t) - return ( - - - - ) - })} - + + + + ) } @@ -1230,15 +1268,7 @@ function Shaft({ node, y, height }: { node: ColumnNode; y: number; height: numbe ) } - if ( - node.crossSection === 'round' || - node.crossSection === 'octagonal' || - node.crossSection === 'sixteen-sided' - ) { - return - } - - return + return } function Base({ node, height }: { node: ColumnNode; height: number }) { @@ -1293,7 +1323,7 @@ function Base({ node, height }: { node: ColumnNode; height: number }) { return ( { - const pairIndex = Math.floor(index / 2) - const nearTop = index % 2 === 1 - const pairCount = Math.ceil(node.ringCount / 2) - const pairT = pairCount <= 1 ? 0 : pairIndex / (pairCount - 1) - const offset = Math.min(0.48, 0.06 + pairT * Math.max(0, ringSpread - 0.06)) - const oneSideT = - 0.06 + (index / Math.max(1, node.ringCount - 1)) * Math.max(0, ringSpread - 0.06) - const t = - ringPlacement === 'even' - ? (index + 1) / (node.ringCount + 1) - : ringPlacement === 'top' - ? 1 - Math.min(0.48, oneSideT) - : ringPlacement === 'bottom' - ? Math.min(0.48, oneSideT) - : nearTop - ? 1 - offset - : offset - return { - scale: Math.min(1.4, getShaftScaleAt(node, t) + 0.12), - y: shaftY + shaftHeight * t - ringHeight / 2, - } - }).sort((a, b) => a.y - b.y) - - return ( - - {rings.map((ring, index) => ( - - ))} - - ) -} - -function LatheBands({ - node, - shaftY, - shaftHeight, -}: { - node: ColumnNode - shaftY: number - shaftHeight: number -}) { - const latheRingCount = Math.max( - node.latheRingCount ?? 0, - node.shaftDetail === 'lathe-turned' ? 8 : 0, - ) - if (latheRingCount <= 0 || shaftHeight <= 0) return null - - const placement = node.latheRingSpacing ?? 'ends' - const bandHeight = Math.min(0.04, shaftHeight / Math.max(12, latheRingCount * 3)) - const bands = Array.from({ length: latheRingCount }, (_, index) => { - const pairIndex = Math.floor(index / 2) - const nearTop = index % 2 === 1 - const offset = Math.min(0.48, 0.1 + pairIndex * 0.04) - const t = - placement === 'even' - ? (index + 1) / (latheRingCount + 1) - : placement === 'top' - ? 1 - Math.min(0.48, 0.08 + index * 0.04) - : placement === 'bottom' - ? Math.min(0.48, 0.08 + index * 0.04) - : nearTop - ? 1 - offset - : offset - return shaftY + shaftHeight * t - bandHeight / 2 - }).sort((a, b) => a - b) - - return ( - - {bands.map((y, index) => ( - - ))} - - ) -} - -function Flutes({ +const detailFields = [ + 'crossSection', + 'radius', + 'width', + 'depth', + 'shaftProfile', + 'shaftTaper', + 'shaftBulge', + 'shaftStartScale', + 'shaftEndScale', + 'shaftSegmentCount', + 'shaftTwistStep', + 'shaftCornerRadius', + 'edgeSoftness', + 'fluteCount', + 'fluteWidth', + 'fluteDepth', + 'shaftDetail', + 'spiralRibCount', + 'spiralTwist', + 'panelCount', + 'style', + 'panelShape', + 'panelInsetDepth', + 'ringCount', + 'ringSpread', + 'ringThickness', + 'ringPlacement', + 'latheRingCount', + 'latheRingSpacing', + 'lowerBandEnabled', + 'lowerBandHeight', + 'lowerBandCarvingLevel', + 'carvingPlacement', +] as const satisfies readonly (keyof ColumnNode)[] + +const ShaftDetails = memo( + function ShaftDetails(props: { node: ColumnNode; shaftHeight: number; shaftY: number }) { + return ( + <> + + + + + ) + }, + (a, b) => + a.shaftHeight === b.shaftHeight && + a.shaftY === b.shaftY && + detailFields.every((key) => a.node[key] === b.node[key]), +) + +function ShaftBands({ node, shaftY, shaftHeight, @@ -1554,103 +1537,20 @@ function Flutes({ shaftY: number shaftHeight: number }) { - const fluteCount = Math.max(node.fluteCount, node.shaftDetail === 'fluted' ? 16 : 0) - if (fluteCount <= 0 || shaftHeight <= 0 || node.crossSection !== 'round') return null - - const fluteDepth = node.fluteDepth ?? 0.02 - const fluteWidth = node.fluteWidth ?? fluteDepth - const fluteRadius = Math.max(0.006, fluteWidth * 0.42) - const shaftRadius = node.radius * 0.74 - - return ( - - {Array.from({ length: fluteCount }, (_, index) => { - const angle = (index / fluteCount) * Math.PI * 2 - const x = Math.cos(angle) * shaftRadius - const z = Math.sin(angle) * shaftRadius - return ( - - ) - })} - - ) -} - -function DravidianPanelFace({ - position, - rotation = 0, - panelHeight, - panelWidth, - rail, - reliefDepth, - panelShape, -}: { - position: [number, number, number] - rotation?: number - panelHeight: number - panelWidth: number - rail: number - reliefDepth: number - panelShape: NonNullable -}) { + const geometry = useMemo(() => createColumnBandGeometry(node, shaftHeight), [node, shaftHeight]) + useEffect(() => () => geometry?.dispose(), [geometry]) + if (!geometry) return null return ( - - - - - - {panelShape === 'diamond' && ( - - )} - {panelShape === 'arched' && ( - - )} - + + + + ) } @@ -1663,51 +1563,20 @@ function DravidianShaftPanels({ shaftY: number shaftHeight: number }) { - const panelCount = Math.max( - node.panelCount ?? 0, - node.style === 'dravidian-carved' || node.shaftDetail === 'panelled' ? 3 : 0, - ) - if (panelCount <= 0 || shaftHeight <= 0) return null - - const shaftWidth = node.width * 0.72 - const shaftDepth = node.depth * 0.72 - const panelHeight = Math.min(0.42, shaftHeight / Math.max(4, panelCount + 2)) - const panelWidth = node.width * 0.26 - const rail = Math.max(0.012, node.width * 0.028) - const reliefDepth = Math.max(0.012, node.panelInsetDepth ?? node.width * 0.025) - const rows = Array.from({ length: panelCount }, (_, index) => (index + 1) / (panelCount + 1)) - const panelShape = node.panelShape ?? 'rectangle' - - const faceProps = { panelHeight, panelWidth, rail, reliefDepth, panelShape } - + const geometry = useMemo(() => createColumnPanelGeometry(node, shaftHeight), [node, shaftHeight]) + useEffect(() => () => geometry?.dispose(), [geometry]) + if (!geometry) return null return ( - - {rows.map((t, rowIndex) => { - const y = shaftY + shaftHeight * t - return ( - - - - - - - ) - })} - + + + + ) } @@ -1720,91 +1589,20 @@ function SpiralRibs({ shaftY: number shaftHeight: number }) { - const spiralRibCount = node.spiralRibCount ?? 0 - const spiralTwist = node.spiralTwist ?? 0 - const shaftTaper = node.shaftTaper ?? 0 - const ribCountSetting = Math.max(spiralRibCount, node.shaftDetail === 'spiral' ? 12 : 0) - if (ribCountSetting <= 0 || spiralTwist === 0 || shaftHeight <= 0) return null - - const ribCount = Math.min(ribCountSetting, 24) - const stepCount = 28 - const ribDistance = node.radius * 0.78 - const ribWidth = Math.max(0.012, node.radius * 0.06) - const segmentHeight = (shaftHeight / stepCount) * 1.18 - const lean = spiralTwist > 0 ? -0.55 : 0.55 - - return ( - - {Array.from({ length: ribCount * stepCount }, (_, index) => { - const ribIndex = index % ribCount - const stepIndex = Math.floor(index / ribCount) - const t = (stepIndex + 0.5) / stepCount - const angle = (ribIndex / ribCount) * Math.PI * 2 + t * spiralTwist * Math.PI * 2 - const taperScale = 1 - Math.min(shaftTaper, 0.85) * t - return ( - - ) - })} - - ) -} - -function LowerCarvedBand({ - node, - shaftY, - shaftHeight, -}: { - node: ColumnNode - shaftY: number - shaftHeight: number -}) { - const placement = node.carvingPlacement ?? 'capital' - if ( - !node.lowerBandEnabled || - shaftHeight <= 0 || - (placement !== 'shaft' && placement !== 'all') - ) { - return null - } - - const bandHeight = Math.min(node.lowerBandHeight ?? 0.24, shaftHeight * 0.35) - const y = shaftY + shaftHeight * 0.12 - const level = Math.max(1, node.lowerBandCarvingLevel ?? 1) - const count = Math.max(6, level * 6) - const distance = Math.max(node.radius * 0.82, Math.max(node.width, node.depth) * 0.36) - + const geometry = useMemo(() => createColumnSpiralGeometry(node, shaftHeight), [node, shaftHeight]) + useEffect(() => () => geometry?.dispose(), [geometry]) + if (!geometry) return null return ( - - - {Array.from({ length: count }, (_, index) => { - const angle = (index / count) * Math.PI * 2 - return ( - - ) - })} - + + + + ) } @@ -2150,20 +1948,11 @@ function ColumnBody({ node }: { node: ColumnNode }) { - - - - - - { export const ColumnRenderer = ({ node: rawNode }: { node: ColumnNode }) => { const ref = useRef(null!) + const bodyRef = useRef(null) // Merge any live drag override so width / depth / radius / height // arrows update the mesh on every pointer move, with zustand only // hearing the commit on release. Subscribes narrowly to this node's @@ -2298,11 +2088,20 @@ export const ColumnRenderer = ({ node: rawNode }: { node: ColumnNode }) => { userData={modelData} {...handlers} > - {node.source ? : } + + {node.source ? : } + {node.children.map((id) => ( ))} + ) diff --git a/packages/nodes/src/column/shape.ts b/packages/nodes/src/column/shape.ts index 7aa40a24c9..591f11cac4 100644 --- a/packages/nodes/src/column/shape.ts +++ b/packages/nodes/src/column/shape.ts @@ -1,15 +1,17 @@ import type { ColumnNode } from '@pascal-app/core' -export function getSegments(node: ColumnNode) { +export function getSegments(node: Pick) { if (node.crossSection === 'octagonal') return 8 if (node.crossSection === 'sixteen-sided') return 16 return 32 } -function getShaftProfile(node: ColumnNode) { +function getShaftProfile(node: Pick) { return node.shaftProfile ?? (node.shaftTaper > 0 ? 'tapered' : 'straight') } -export function getShaftSegmentCount(node: ColumnNode) { +export function getShaftSegmentCount( + node: Pick, +) { const shaftProfile = getShaftProfile(node) const shaftTaper = node.shaftTaper ?? 0 const hasTwist = Math.abs(node.shaftTwistStep ?? 0) > 0.001 @@ -21,11 +23,17 @@ export function getShaftSegmentCount(node: ColumnNode) { ) } -export function getShaftTwistRadians(node: ColumnNode, index: number) { +export function getShaftTwistRadians(node: Pick, index: number) { return ((node.shaftTwistStep ?? 0) * Math.PI * index) / 180 } -export function getShaftScaleAt(node: ColumnNode, t: number) { +export function getShaftScaleAt( + node: Pick< + ColumnNode, + 'shaftProfile' | 'shaftTaper' | 'shaftStartScale' | 'shaftEndScale' | 'shaftBulge' + >, + t: number, +) { const shaftProfile = getShaftProfile(node) const shaftTaper = Math.min(node.shaftTaper ?? 0, 0.85) const startScale = node.shaftStartScale ?? 0.72 @@ -111,7 +119,7 @@ export function columnCapitalBlocks(node: ColumnNode, y: number, height: number) return { kind: 'box', y: y + (index * height) / count, - height: (height / count) * 1.01, + height: height / count, width: node.width * Math.max(0.5, widthScale - spread), depth: node.depth * Math.max(0.5, depthScale - spread), } diff --git a/packages/nodes/src/column/surface.ts b/packages/nodes/src/column/surface.ts index 2f7d174873..68430f9fa5 100644 --- a/packages/nodes/src/column/surface.ts +++ b/packages/nodes/src/column/surface.ts @@ -43,8 +43,10 @@ export function columnTopSurfaces(node: ColumnNode): DeclaredHostSurface[] { let region: SurfaceRegion if (cap) { y = cap.y + cap.height - if (cap.kind === 'round') region = roundRegion(cap.radius!, getSegments(node)) - else { + if (cap.kind === 'round') { + const bevel = Math.min(node.edgeSoftness, cap.height * 0.35, cap.radius! * 0.35) + region = roundRegion(cap.radius! - bevel, getSegments(node)) + } else { const bevel = Math.min( Math.max(0, node.edgeSoftness ?? 0.025), Math.min(cap.width!, cap.depth!, cap.height) * 0.35, @@ -53,17 +55,22 @@ export function columnTopSurfaces(node: ColumnNode): DeclaredHostSurface[] { } } else { const segments = getShaftSegmentCount(node) - const scale = getShaftScaleAt(node, (segments - 0.5) / segments) + const scale = getShaftScaleAt(node, 1) const yaw = getShaftTwistRadians(node, segments - 1) - y = layout.shaftY + layout.shaftHeight + (layout.shaftHeight / segments) * 0.015 + y = layout.shaftY + layout.shaftHeight if (node.crossSection === 'square' || node.crossSection === 'rectangular') { const corner = Math.min( Math.max(0, node.shaftCornerRadius ?? 0.035), Math.min(node.width, node.depth) * 0.45, ) * scale - const x = (node.width * scale) / 2 - corner - const z = (node.depth * scale) / 2 - corner + const bevel = Math.min( + node.edgeSoftness, + layout.shaftHeight * 0.35, + (Math.min(node.width, node.depth) / 2) * Math.min(getShaftScaleAt(node, 0), scale) * 0.35, + ) + const x = (node.width * scale) / 2 - corner - bevel + const z = (node.depth * scale) / 2 - corner - bevel region = { kind: 'polygon', points: [ @@ -76,7 +83,18 @@ export function columnTopSurfaces(node: ColumnNode): DeclaredHostSurface[] { -px! * Math.sin(yaw) + pz! * Math.cos(yaw), ]), } - } else region = roundRegion(node.radius * scale, getSegments(node), yaw) + } else { + const fluted = + node.crossSection === 'round' && (node.fluteCount > 0 || node.shaftDetail === 'fluted') + const inset = + (fluted ? Math.min(node.fluteDepth, node.radius * scale * 0.35) : 0) + + Math.min( + node.edgeSoftness, + layout.shaftHeight * 0.35, + node.radius * Math.min(getShaftScaleAt(node, 0), scale) * 0.35, + ) + region = roundRegion(node.radius * scale - inset, getSegments(node), yaw) + } } return [{ id: 'top', position: [0, y, 0], normal: [0, 1, 0], region }] } diff --git a/packages/nodes/src/column/tool.test.tsx b/packages/nodes/src/column/tool.test.tsx new file mode 100644 index 0000000000..80d777916a --- /dev/null +++ b/packages/nodes/src/column/tool.test.tsx @@ -0,0 +1,44 @@ +import { expect, test } from 'bun:test' +import { clearSceneHistory, emitter, type GridEvent, LevelNode, useScene } from '@pascal-app/core' +import { useEditor, usePlacementPreview } from '@pascal-app/editor' +import { useViewer } from '@pascal-app/viewer' +import { act } from '@react-three/test-renderer' +import { installMountedScene, mount } from '../__tests__/harness' +import ColumnTool from './tool' + +installMountedScene() +test('repeated placement reuses a transient ghost but persists distinct columns and undo steps', async () => { + const level = LevelNode.parse({}) + useScene.setState({ nodes: { [level.id]: level }, rootNodeIds: [level.id], readOnly: false }) + useViewer.getState().setSelection({ levelId: level.id }) + useEditor.getState().setSnappingMode('item', 'off') + useEditor.getState().setContinuation('point', 'repeat') + clearSceneHistory() + const renderer = await mount() + const send = async (type: 'grid:move' | 'grid:click', x: number) => { + await act(async () => + emitter.emit(type, { + position: [x, 0, 0], + localPosition: [x, 0, 0], + nativeEvent: {}, + stopPropagation() {}, + } as GridEvent), + ) + } + const initial = useScene.getState().nodes + await send('grid:move', 1) + const id = usePlacementPreview.getState().node!.id + await send('grid:move', 2) + expect(usePlacementPreview.getState().node!.id).toBe(id) + expect(useScene.getState().nodes).toBe(initial) + await send('grid:click', 2) + await send('grid:move', 4) + await send('grid:click', 4) + const columns = Object.values(useScene.getState().nodes).filter((node) => node.type === 'column') + expect(columns).toHaveLength(2) + expect(new Set(columns.map((node) => node.id)).size).toBe(2) + expect(columns.every((node) => node.id !== id)).toBe(true) + expect(useScene.temporal.getState().pastStates).toHaveLength(2) + await renderer.unmount() + expect(usePlacementPreview.getState().node).toBeNull() +}) diff --git a/packages/nodes/src/column/tool.tsx b/packages/nodes/src/column/tool.tsx index 29f7ffc70a..c4278b196b 100644 --- a/packages/nodes/src/column/tool.tsx +++ b/packages/nodes/src/column/tool.tsx @@ -7,6 +7,7 @@ import { collectAlignmentAnchors, emitter, type GridEvent, + NEW_COLUMN_SLOTS, resolveFrozenFloorPlacementPatch, resolveSupportSlabPatch, useScene, @@ -53,6 +54,7 @@ function createColumnFromPreset(presetId: ColumnPresetId, position: [number, num position, rotation: 0, ...preset, + slots: { ...NEW_COLUMN_SLOTS }, }) } @@ -93,7 +95,16 @@ const PillarTool = () => { // here and refreshed after each placement so a just-placed column becomes a // target for the next one. `previewNode.id` never collides with a scene // node, so nothing real is excluded. - let alignmentCandidates = collectAlignmentAnchors(useScene.getState().nodes, previewNode.id) + let candidateNodes = useScene.getState().nodes + let alignmentCandidates = collectAlignmentAnchors(candidateNodes, previewNode.id) + let structuralGrids = collectStructuralGridAxes(candidateNodes, activeLevelId) + const refreshCandidates = () => { + const nodes = useScene.getState().nodes + if (nodes === candidateNodes) return + candidateNodes = nodes + alignmentCandidates = collectAlignmentAnchors(nodes, previewNode.id) + structuralGrids = collectStructuralGridAxes(nodes, activeLevelId) + } const pointedSurfaceFor = (event: FloorPlacementClickTriggerEvent) => typeof HTMLCanvasElement !== 'undefined' && @@ -107,11 +118,8 @@ const PillarTool = () => { position: [number, number, number], surface: PointerSupportSurface | null, ) => { - const column = ColumnNode.parse({ - ...createColumnFromPreset(DEFAULT_COLUMN_PRESET_ID, position), - parentId: activeLevelId, - }) - const nodes = { ...useScene.getState().nodes, [column.id]: column } + const column = { ...previewNode, position, parentId: activeLevelId } + const nodes = useScene.getState().nodes const patch = surface?.sourceNodeId ? resolveFrozenFloorPlacementPatch(column, nodes, { position, @@ -129,6 +137,7 @@ const PillarTool = () => { } const onGridMove = (event: GridEvent) => { + refreshCandidates() if (!cursorVisibleRef.current) { cursorVisibleRef.current = true setCursorVisible(true) @@ -148,10 +157,7 @@ const PillarTool = () => { }) const structuralSnap = isGridSnapActive() || isMagneticSnapActive() - ? resolveStructuralGridSnap( - [alignedPosition[0], alignedPosition[2]], - collectStructuralGridAxes(useScene.getState().nodes, activeLevelId), - ) + ? resolveStructuralGridSnap([alignedPosition[0], alignedPosition[2]], structuralGrids) : null const planPosition: [number, number, number] = structuralSnap ? [structuralSnap.point[0], alignedPosition[1], structuralSnap.point[1]] @@ -197,6 +203,7 @@ const PillarTool = () => { } const commitAtCursor = (event: FloorPlacementClickTriggerEvent) => { + refreshCandidates() const pointed = pointedSurfaceFor(event) ?? supportSurfaceRef.current supportSurfaceRef.current = pointed const fallbackPosition = @@ -209,10 +216,7 @@ const PillarTool = () => { ) const structuralSnap = isGridSnapActive() || isMagneticSnapActive() - ? resolveStructuralGridSnap( - [fallbackPosition[0], fallbackPosition[2]], - collectStructuralGridAxes(useScene.getState().nodes, activeLevelId), - ) + ? resolveStructuralGridSnap([fallbackPosition[0], fallbackPosition[2]], structuralGrids) : null const planPosition: [number, number, number] = structuralSnap ? [structuralSnap.point[0], 0, structuralSnap.point[1]] @@ -221,6 +225,7 @@ const PillarTool = () => { const committedColumn = ColumnNode.parse({ ...column, ...patch, + id: undefined, }) useScene.getState().createNode(committedColumn, activeLevelId) useViewer.getState().setSelection({ selectedIds: [committedColumn.id] }) @@ -229,7 +234,7 @@ const PillarTool = () => { usePlacementPreview.getState().clear() if (useEditor.getState().getContinuation('point') === 'repeat') { // The placed column is now a valid alignment target for the next one. - alignmentCandidates = collectAlignmentAnchors(useScene.getState().nodes, previewNode.id) + refreshCandidates() } else { cursorVisibleRef.current = false setCursorVisible(false) diff --git a/packages/nodes/src/cupola/definition.ts b/packages/nodes/src/cupola/definition.ts index f49574a1a6..f2014719a3 100644 --- a/packages/nodes/src/cupola/definition.ts +++ b/packages/nodes/src/cupola/definition.ts @@ -110,6 +110,7 @@ const cupolaHandles: HandleDescriptor[] = [ */ export const cupolaDefinition: NodeDefinition = { kind: 'cupola', + snapProfile: 'item', schemaVersion: 4, schema: CupolaNode, category: 'structure', diff --git a/packages/nodes/src/cupola/move-tool.tsx b/packages/nodes/src/cupola/move-tool.tsx index 0e02936bbb..01cf5f78e6 100644 --- a/packages/nodes/src/cupola/move-tool.tsx +++ b/packages/nodes/src/cupola/move-tool.tsx @@ -12,7 +12,10 @@ import { } from '@pascal-app/core' import { consumePlacementDragRelease, + isGridSnapActive, + isMagneticSnapActive, markToolCancelConsumed, + stripPlacementMetadataFlags, triggerSFX, useEditor, } from '@pascal-app/editor' @@ -84,9 +87,9 @@ export default function MoveCupolaTool({ node }: { node: CupolaNode }) { const rawTarget = roofDrag.resolve(event) if (!rawTarget) return null return snapRoofSurfaceNodeTarget({ - target: snapRelativeRoofDragTarget(rawTarget, event.nativeEvent?.shiftKey === true), + target: snapRelativeRoofDragTarget(rawTarget, event.nativeEvent?.altKey === true), node, - bypass: event.nativeEvent?.shiftKey === true, + bypass: !isMagneticSnapActive() || event.nativeEvent?.altKey === true, }) } @@ -101,7 +104,8 @@ export default function MoveCupolaTool({ node }: { node: CupolaNode }) { const sx = Math.round(target.localX * 20) / 20 const sz = Math.round(target.localZ * 20) / 20 if ( - event.nativeEvent?.shiftKey !== true && + isGridSnapActive() && + event.nativeEvent?.altKey !== true && (!lastSnap || lastSnap[0] !== sx || lastSnap[1] !== sz) ) { triggerSFX('sfx:grid-snap') @@ -159,7 +163,7 @@ export default function MoveCupolaTool({ node }: { node: CupolaNode }) { position: [target.localX, target.localY, target.localZ], rotation: original.rotation, visible: true, - metadata: {}, + metadata: stripPlacementMetadataFlags(original.metadata), }) useScene.temporal.getState().pause() diff --git a/packages/nodes/src/door/move-tool.tsx b/packages/nodes/src/door/move-tool.tsx index 795673e3fe..4e177f536f 100644 --- a/packages/nodes/src/door/move-tool.tsx +++ b/packages/nodes/src/door/move-tool.tsx @@ -421,6 +421,9 @@ const MoveDoorTool: React.FC<{ node: DoorNode }> = ({ node: movingDoorNode }) => } const applyPreview = (target: NonNullable) => { + useLiveNodeOverrides + .getState() + .clearFields(movingDoorNode.id, ['position', 'rotation', 'roofFace']) if (target.transomHeight !== undefined) useLiveNodeOverrides .getState() @@ -738,6 +741,7 @@ const MoveDoorTool: React.FC<{ node: DoorNode }> = ({ node: movingDoorNode }) => // later wall-snap / commit has a clean base, but stays `visible:false` until // a wall is hovered. const freeFollowAt = (localX: number, localZ: number) => { + useLiveNodeOverrides.getState().clear(movingDoorNode.id) freeFollowing = true lastTarget = null lastRoofEvent = null @@ -755,14 +759,7 @@ const MoveDoorTool: React.FC<{ node: DoorNode }> = ({ node: movingDoorNode }) => // (back = rotated π) instead of forcing 0, so an R press isn't undone on // the next mousemove. const yaw = sideOverride === 'back' ? Math.PI : 0 - if (currentHostId === levelId) { - updateDraft({ - position: [localX, y, localZ], - rotation: [0, yaw, 0], - side: sideOverride, - visible: false, - }) - } else { + if (currentHostId !== levelId) { if (currentHostId && currentHostId !== levelId) markHostDirty(currentHostId) updateDraft({ position: [localX, y, localZ], @@ -847,13 +844,8 @@ const MoveDoorTool: React.FC<{ node: DoorNode }> = ({ node: movingDoorNode }) => // On a roof face the real mesh is the preview — drop the free-follow ghost // and reveal the node. revealRealNode() - if (currentHostId === target.segment.id) { - updateDraft({ - position: target.position, - rotation: [0, 0, 0], - roofFace: target.face.id, - }) - } else { + if (currentHostId !== target.segment.id) { + useLiveNodeOverrides.getState().clear(movingDoorNode.id) updateDraft({ position: target.position, rotation: [0, 0, 0], @@ -867,6 +859,13 @@ const MoveDoorTool: React.FC<{ node: DoorNode }> = ({ node: movingDoorNode }) => markHostDirty(currentHostId) currentHostId = target.segment.id } + useLiveNodeOverrides.getState().set(movingDoorNode.id, { + position: target.position, + rotation: [0, 0, 0], + roofFace: target.face.id, + }) + useScene.getState().markDirty(movingDoorNode.id) + markHostDirtyThrottled(target.segment.id) updateRoofCursor(target, event.node as RoofNode) event.stopPropagation() } @@ -945,6 +944,7 @@ const MoveDoorTool: React.FC<{ node: DoorNode }> = ({ node: movingDoorNode }) => placedId = movingDoorNode.id } + useLiveNodeOverrides.getState().clear(movingDoorNode.id) markHostDirty(segmentId) useLiveTransforms.getState().clear(movingDoorNode.id) @@ -957,6 +957,7 @@ const MoveDoorTool: React.FC<{ node: DoorNode }> = ({ node: movingDoorNode }) => } const onRoofLeave = () => { + useLiveNodeOverrides.getState().clear(movingDoorNode.id) // Mirror onWallLeave: don't revert to origin here — onGridMove takes // over on the same pointermove (snap to a nearby wall or free-follow). hideCursor() @@ -967,6 +968,7 @@ const MoveDoorTool: React.FC<{ node: DoorNode }> = ({ node: movingDoorNode }) => } const onCancel = () => { + useLiveNodeOverrides.getState().clear(movingDoorNode.id) useLiveTransforms.getState().clear(movingDoorNode.id) if (isNew) { useScene.getState().deleteNode(movingDoorNode.id) @@ -1124,6 +1126,7 @@ const MoveDoorTool: React.FC<{ node: DoorNode }> = ({ node: movingDoorNode }) => } return () => { + useLiveNodeOverrides.getState().clear(movingDoorNode.id) const current = useScene.getState().nodes[movingDoorNode.id as AnyNodeId] as | DoorNode | undefined diff --git a/packages/nodes/src/duct-fitting/selection.test.tsx b/packages/nodes/src/duct-fitting/selection.test.tsx index f002d1863b..c61f1fca06 100644 --- a/packages/nodes/src/duct-fitting/selection.test.tsx +++ b/packages/nodes/src/duct-fitting/selection.test.tsx @@ -4,6 +4,7 @@ import { BuildingNode, DuctFittingNode, DuctSegmentNode, + getEffectiveNode, LevelNode, SiteNode, useScene, @@ -97,7 +98,8 @@ function seed(item: SnappingMode = 'lines') { return fitting.id as AnyNodeId } -const fittingOf = (id: AnyNodeId) => useScene.getState().nodes[id] as DuctFittingNode +const fittingOf = (id: AnyNodeId) => + getEffectiveNode(useScene.getState().nodes[id] as DuctFittingNode) function client(point: Point) { const ndc = new Vector3(...point).project(camera) @@ -204,7 +206,8 @@ test('a joined duct goes back to its start when the fitting slide returns to the dirtyNodes: new Set([level.id, duct.id]), }) useScene.temporal.getState().clear() - const ductPath = () => (useScene.getState().nodes[duct.id] as DuctSegmentNode).path + const ductPath = () => + getEffectiveNode(useScene.getState().nodes[duct.id] as DuctSegmentNode).path const renderer = await mount() await openCluster(renderer) diff --git a/packages/nodes/src/duct-fitting/selection.tsx b/packages/nodes/src/duct-fitting/selection.tsx index 1f7e9b49f4..c5ed8146c4 100644 --- a/packages/nodes/src/duct-fitting/selection.tsx +++ b/packages/nodes/src/duct-fitting/selection.tsx @@ -11,6 +11,7 @@ import { resolveConnectivityUpdates, resumeSceneHistory, sceneRegistry, + useLiveNodeOverrides, useScene, } from '@pascal-app/core' import { @@ -53,8 +54,8 @@ import { ROTATE_STEP_RAD, type RotationAxis, } from '../shared/fitting-rotation' -import { createFollowerFrames } from '../shared/follower-frames' import { useHandleDragScope } from '../shared/handle-drag-scope' +import { createLivePreview } from '../shared/live-preview' import { HandleCube, MoveChevron, RotateArc } from '../shared/selection-handles' import { fittingLegLength } from './ports' @@ -340,7 +341,15 @@ const DuctFittingSelectionAffordance = () => { return createPortal(, mount, undefined) } -const FittingHandles = ({ fitting, target }: { fitting: DuctFittingNode; target: Object3D }) => { +const FittingHandles = ({ + fitting: storedFitting, + target, +}: { + fitting: DuctFittingNode + target: Object3D +}) => { + const override = useLiveNodeOverrides((state) => state.overrides.get(storedFitting.id)) + const fitting = override ? ({ ...storedFitting, ...override } as DuctFittingNode) : storedFitting const { camera, gl } = useThree() const [frame, setFrame] = useState(null) // True while the cluster is latched open. Click the center cube to toggle. @@ -459,11 +468,8 @@ const FittingHandles = ({ fitting, target }: { fitting: DuctFittingNode; target: ) => (e: ThreeEvent) => { e.stopPropagation() - const initialPosition = [...fitting.position] as Point - const initialRotation = [...fitting.rotation] as Point - const startNodes = useScene.getState().nodes - const connectivity = analyzePortConnectivity(fitting as AnyNode, startNodes) - const followerFrame = createFollowerFrames(startNodes, fitting.id as AnyNodeId) + const connectivity = analyzePortConnectivity(fitting as AnyNode, useScene.getState().nodes) + const livePreview = createLivePreview() const compute = makeCompute(e) pauseSceneHistory(useScene) useViewer.getState().setInputDragging(true) @@ -497,7 +503,7 @@ const FittingHandles = ({ fitting, target }: { fitting: DuctFittingNode; target: const batch = buildBatch(next) if (!batch) return current = next - useScene.getState().updateNodes(followerFrame(batch)) + livePreview.publish(batch) } const cleanup = () => { @@ -512,36 +518,7 @@ const FittingHandles = ({ fitting, target }: { fitting: DuctFittingNode; target: const finish = (commit: boolean) => { cleanup() - // Single-undo dance: revert the fitting AND its followers to the - // pre-drag state while history is still paused, resume, then re-apply - // the final transform as one tracked change. - const reverts: { id: AnyNodeId; data: Partial }[] = ( - connectivity?.connections ?? [] - ).map((conn) => { - if (conn.kind !== 'rigid-node') { - return { id: conn.nodeId, data: { path: conn.startPath } as Partial } - } - const node = useScene.getState().nodes[conn.nodeId] - return { - id: conn.nodeId, - data: - node?.type === 'duct-fitting' - ? preserveFittingParameters(node as DuctFittingNode, { - position: conn.startPosition as Point, - }) - : ({ position: conn.startPosition } as Partial), - } - }) - useScene.getState().updateNodes([ - { - id: fitting.id as AnyNodeId, - data: preserveFittingParameters(fitting, { - position: initialPosition, - rotation: initialRotation, - }), - }, - ...reverts.filter((u) => useScene.getState().nodes[u.id]), - ]) + livePreview.clear() resumeSceneHistory(useScene) if (!commit) return const batch = current && buildBatch(current) @@ -651,7 +628,7 @@ const FittingHandles = ({ fitting, target }: { fitting: DuctFittingNode; target: (e: ThreeEvent) => { e.stopPropagation() const baseValue = fitting[dimension] - const initialPatch = { [dimension]: baseValue } as Partial + const livePreview = createLivePreview() const centerWorld = toWorld(fitting.position as Point) const axisWorld = axisToWorld(fitting.position as Point, axisLocal) const start = sampleAxisParameter( @@ -672,14 +649,9 @@ const FittingHandles = ({ fitting, target }: { fitting: DuctFittingNode; target: let current: Partial | null = null let lastValue = Number.NaN - const apply = (patch: Partial) => { - useScene.getState().updateNodes([ - { - id: fitting.id as AnyNodeId, - data: preserveFittingParameters(fitting, patch), - }, - ]) - } + const update = (patch: Partial) => [ + { id: fitting.id as AnyNodeId, data: preserveFittingParameters(fitting, patch) }, + ] const onMove = (event: PointerEvent) => { const rawDeltaM = @@ -694,7 +666,7 @@ const FittingHandles = ({ fitting, target }: { fitting: DuctFittingNode; target: lastValue = nextValue current = { [dimension]: nextValue } as Partial if (snapped) triggerSFX('sfx:grid-snap') - apply(current) + livePreview.publish(update(current)) } const cleanup = () => { @@ -709,9 +681,9 @@ const FittingHandles = ({ fitting, target }: { fitting: DuctFittingNode; target: const finish = (commit: boolean) => { cleanup() - apply(initialPatch) + livePreview.clear() resumeSceneHistory(useScene) - if (commit && current) apply(current) + if (commit && current) useScene.getState().updateNodes(update(current)) } const onUp = () => { diff --git a/packages/nodes/src/duct-segment/selection.tsx b/packages/nodes/src/duct-segment/selection.tsx index 74cecde21e..3fc7655261 100644 --- a/packages/nodes/src/duct-segment/selection.tsx +++ b/packages/nodes/src/duct-segment/selection.tsx @@ -7,6 +7,7 @@ import { type Cursor, type DuctFittingNode, DuctSegmentNode, + findLevelAncestorId, nodeRegistry, type PortConnectivity, pauseSceneHistory, @@ -623,6 +624,9 @@ const DuctPointHandles = ({ duct, target }: { duct: DuctSegmentNode; target: Obj [next[0], next[1], next[2]], collectScenePorts({ excludeNodeId: duct.id, + levelId: (findLevelAncestorId(duct.id, useScene.getState().nodes) ?? undefined) as + | AnyNodeId + | undefined, systems: DUCT_PORT_SYSTEMS, }), PORT_SNAP_RADIUS_M, diff --git a/packages/nodes/src/elevator/__bench__/rendering.bench.tsx b/packages/nodes/src/elevator/__bench__/rendering.bench.tsx new file mode 100644 index 0000000000..c31aeba2ad --- /dev/null +++ b/packages/nodes/src/elevator/__bench__/rendering.bench.tsx @@ -0,0 +1,38 @@ +// Run: bun test ./packages/nodes/src/elevator/__bench__/rendering.bench.tsx +import { test } from 'bun:test' +import { BuildingNode, ElevatorNode, LevelNode, useScene } from '@pascal-app/core' +import { InstancedMesh, Mesh } from 'three' +import { installMountedScene, mount } from '../../__tests__/harness' +import { ElevatorRenderer } from '../renderer' + +installMountedScene() +test('reports elevator mesh and triangle counts for two and twenty floors', async () => { + for (const count of [2, 20]) { + const building = BuildingNode.parse({}) + const levels = Array.from({ length: count }, (_, level) => + LevelNode.parse({ parentId: building.id, level, height: 3 }), + ) + const node = ElevatorNode.parse({ + parentId: building.id, + fromLevelId: levels[0]!.id, + toLevelId: levels.at(-1)!.id, + }) + building.children = [...levels.map((level) => level.id), node.id] + useScene.setState({ + nodes: Object.fromEntries([building, ...levels, node].map((n) => [n.id, n])), + }) + const renderer = await mount() + let meshes = 0, + triangles = 0 + renderer.scene.instance.traverse((object) => { + if (object instanceof Mesh) { + meshes++ + triangles += + ((object.geometry.index?.count ?? object.geometry.getAttribute('position').count) / 3) * + (object instanceof InstancedMesh ? object.count : 1) + } + }) + console.log(JSON.stringify({ floors: count, meshes, triangles })) + await renderer.unmount() + } +}) diff --git a/packages/nodes/src/elevator/__bench__/runtime.ts b/packages/nodes/src/elevator/__bench__/runtime.ts new file mode 100644 index 0000000000..6203f6e21a --- /dev/null +++ b/packages/nodes/src/elevator/__bench__/runtime.ts @@ -0,0 +1,50 @@ +import { + BlockNode, + BuildingNode, + ElevatorNode, + LevelNode, + stepElevatorRuntimes, + useInteractive, + useScene, +} from '@pascal-app/core' + +const building = BuildingNode.parse({}) +const levels = [0, 1].map((level) => LevelNode.parse({ parentId: building.id, level, height: 3 })) +const elevators = Array.from({ length: 20 }, () => + ElevatorNode.parse({ + parentId: building.id, + fromLevelId: levels[0]!.id, + toLevelId: levels[1]!.id, + }), +) +building.children = [ + ...levels.map((level) => level.id), + ...elevators.map((elevator) => elevator.id), +] +const values = [ + building, + ...levels, + ...elevators, + ...Array.from({ length: 2000 }, () => BlockNode.parse({ parentId: levels[0]!.id })), +] +let scans = 0 +const nodes = new Proxy(Object.fromEntries(values.map((node) => [node.id, node])), { + ownKeys(target) { + scans++ + return Reflect.ownKeys(target) + }, +}) +useScene.setState({ nodes }) +useInteractive.setState({ elevators: {} }) +stepElevatorRuntimes(0, 1 / 60) +const warmupScans = scans +for (let frame = 1; frame <= 100; frame++) stepElevatorRuntimes((frame * 1000) / 60, 1 / 60) +console.log( + JSON.stringify({ + nodes: values.length, + elevators: elevators.length, + idleFrames: 100, + warmupSceneScans: warmupScans, + idleSceneScans: scans - warmupScans, + }), +) diff --git a/packages/nodes/src/elevator/definition.test.ts b/packages/nodes/src/elevator/definition.test.ts index ebf7c9c633..d41f71dfd4 100644 --- a/packages/nodes/src/elevator/definition.test.ts +++ b/packages/nodes/src/elevator/definition.test.ts @@ -2,12 +2,22 @@ import { afterEach, beforeEach, describe, expect, test } from 'bun:test' import { type AnyNodeDefinition, type AnyNodeId, + BuildingNode, ElevatorNode, + getElevatorDoorLeafWidth, + getElevatorDoorLeafX, + LevelNode, nodeRegistry, + normalizeElevatorDimensions, registerNode, + resolveElevatorDimensions, + SlabNode, + spatialGridManager, useScene, } from '@pascal-app/core' import { elevatorDefinition } from './definition' +import { buildElevatorFloorplan } from './floorplan' +import { ELEVATOR_PRESETS, elevatorPresetPatch, elevatorSectionReset } from './presets' describe('elevatorDefinition', () => { // The elevator has no dirty consumer: it ships no `def.geometry` (so @@ -52,3 +62,131 @@ describe('elevatorDefinition', () => { }) }) }) + +test('dimension edits keep stored sizes consistent and preserve automatic shaft sizing', () => { + const node = ElevatorNode.parse({ width: 1, depth: 1, cabHeight: 2, doorWidth: 3, doorHeight: 4 }) + const normalized = normalizeElevatorDimensions(node) + expect(normalized.doorWidth).toBeCloseTo(0.82) + expect(normalized.doorHeight).toBeCloseTo(1.9) + expect(normalized.shaftWidth).toBeUndefined() + const resized = normalizeElevatorDimensions({ ...node, width: 0.6, shaftWidth: 0.5 }) + expect(resized.width).toBe(0.8) + expect(resized.shaftWidth).toBe(0.8) + expect(resized.doorWidth).toBeCloseTo(0.62) + expect(resolveElevatorDimensions(ElevatorNode.parse({ ...node, ...resized })).width).toBe( + resized.width, + ) +}) + +for (const doorStyle of ['center-opening', 'single-left', 'single-right'] as const) { + test(`${doorStyle} doors clear the full opening at the end of travel`, () => { + for (const width of [0.45, 0.95, 2]) { + const leafWidth = getElevatorDoorLeafWidth(width, doorStyle) + const sides = + doorStyle === 'center-opening' + ? (['left', 'right'] as const) + : ([doorStyle === 'single-left' ? 'left' : 'right'] as const) + for (const side of sides) { + const center = getElevatorDoorLeafX(side, width, 1, doorStyle) + expect(Math.abs(center) - leafWidth / 2).toBeCloseTo(width / 2) + const closed = getElevatorDoorLeafX(side, width, 0, doorStyle) + expect(Math.abs(closed)).toBeCloseTo(doorStyle === 'center-opening' ? width / 4 : 0) + } + } + }) +} + +test('floor plans show the elevator only on served floors in its building', () => { + const building = BuildingNode.parse({}) + const levels = [0, 1, 2].map((level) => LevelNode.parse({ parentId: building.id, level })) + const node = ElevatorNode.parse({ + parentId: building.id, + fromLevelId: levels[0]!.id, + toLevelId: levels[1]!.id, + }) + building.children = [...levels.map((level) => level.id), node.id] + const nodes = Object.fromEntries([building, ...levels, node].map((n) => [n.id, n])) + for (const [index, parent] of levels.entries()) { + const geometry = buildElevatorFloorplan(node, { + parent, + children: [], + siblings: [], + resolve: (id) => nodes[id], + }) + if (index < 2) expect(geometry?.kind).toBe('group') + else expect(geometry).toBeNull() + } +}) + +test('preset and section edits preserve service configuration, transforms and paint', () => { + const node = ElevatorNode.parse({ + position: [2, 0.2, 3], + rotation: 1, + fromLevelId: 'level_a', + toLevelId: 'level_b', + slots: { cab: 'library:metal-steel' }, + }) + for (const id of Object.keys(ELEVATOR_PRESETS) as Array) { + const next = ElevatorNode.parse({ ...node, ...elevatorPresetPatch(node, id) }) + expect(next.slots).toEqual(node.slots) + expect(next.position).toEqual(node.position) + expect(next.rotation).toBe(node.rotation) + expect(next.fromLevelId).toBe(node.fromLevelId) + expect(next.toLevelId).toBe(node.toLevelId) + expect(ElevatorNode.parse(JSON.parse(JSON.stringify(next)))).toEqual(next) + const reset = { ...next, ...elevatorSectionReset(next, 'Cab') } + expect(reset.width).toBe(1.84) + expect(reset.slots).toEqual(node.slots) + } +}) + +test('moving an elevator resolves its landing across split-level slabs in both directions', () => { + const previous = useScene.getState() + const building = BuildingNode.parse({ + id: 'building_move_support', + children: ['level_move_support'], + }) + const level = LevelNode.parse({ id: 'level_move_support', parentId: building.id }) + const elevator = ElevatorNode.parse({ + parentId: building.id, + fromLevelId: level.id, + position: [0, 0, 0], + }) + const slab = SlabNode.parse({ + id: 'slab_move_support', + parentId: level.id, + polygon: [ + [4, -4], + [10, -4], + [10, 4], + [4, 4], + ], + elevation: 0.8, + }) + const nodes = { + [building.id]: building, + [level.id]: level, + [elevator.id]: elevator, + [slab.id]: slab, + } + try { + useScene.setState({ nodes: {} }) + spatialGridManager.handleNodeCreated(slab, level.id) + const resolve = elevatorDefinition.capabilities.movable!.resolvePosition! + for (const [x, expected] of [ + [6, 0.8], + [0, 0], + [6, 0.8], + ]) { + const position = resolve({ + node: elevator, + position: [x!, 0, 0], + nodes, + }) + expect(position).toEqual([x!, expected!, 0]) + } + } finally { + spatialGridManager.handleNodeDeleted(slab.id, level.id) + useScene.setState(previous) + } +}) diff --git a/packages/nodes/src/elevator/definition.ts b/packages/nodes/src/elevator/definition.ts index e1ba9f44c0..9c5b672b3f 100644 --- a/packages/nodes/src/elevator/definition.ts +++ b/packages/nodes/src/elevator/definition.ts @@ -1,4 +1,6 @@ import { + ELEVATOR_MIN_CAB_DIMENSION, + ELEVATOR_MIN_CAB_HEIGHT, ElevatorNode as ElevatorNodeSchema, type ElevatorNode as ElevatorNodeType, elevatorSlots, @@ -9,8 +11,11 @@ import { getElevatorShaftWidth, type HandleDescriptor, type NodeDefinition, + normalizeElevatorDimensions, + resolveElevatorDimensions, resolveElevatorLevels, } from '@pascal-app/core' +import { resolveElevatorNodeSupportY } from '@pascal-app/editor' import { buildElevatorFloorplan } from './floorplan' import { elevatorResizeAffordance, elevatorRotateAffordance } from './floorplan-affordances' import { elevatorPaint } from './paint' @@ -20,8 +25,8 @@ import { ElevatorNode } from './schema' const SIDE_HANDLE_OFFSET = 0.22 const HEIGHT_HANDLE_OFFSET = 0.3 const MOVE_FRONT_OFFSET = 0.35 -const MIN_ELEVATOR_DIM = 0.6 -const MIN_CAB_HEIGHT = 1.4 +const MIN_ELEVATOR_DIM = ELEVATOR_MIN_CAB_DIMENSION +const MIN_CAB_HEIGHT = ELEVATOR_MIN_CAB_HEIGHT const ROTATE_CORNER_OFFSET = 0.4 const ROTATE_RING_OFFSET = 0.08 @@ -38,8 +43,13 @@ function elevatorAxisHandle(axis: 'x' | 'z'): HandleDescriptor axis, anchor: 'center', min: MIN_ELEVATOR_DIM, - currentValue: (n) => (axis === 'x' ? n.width : n.depth), - apply: (_n, newValue) => (axis === 'x' ? { width: newValue } : { depth: newValue }), + currentValue: (n) => + axis === 'x' ? resolveElevatorDimensions(n).width : resolveElevatorDimensions(n).depth, + apply: (n, newValue) => + normalizeElevatorDimensions({ + ...n, + ...(axis === 'x' ? { width: newValue } : { depth: newValue }), + }), placement: { position: (n) => { const cabWidth = getElevatorCabWidth(n) @@ -72,7 +82,7 @@ function elevatorCabHeightHandle(): HandleDescriptor { anchor: 'min', min: MIN_CAB_HEIGHT, currentValue: (n) => Math.max(n.cabHeight, MIN_CAB_HEIGHT), - apply: (_n, newValue) => ({ cabHeight: newValue }), + apply: (n, newValue) => normalizeElevatorDimensions({ ...n, cabHeight: newValue }), placement: { position: (n, scene) => { const { shaftTopY } = resolveElevatorLevels(n, scene.nodes()) @@ -164,13 +174,6 @@ const elevatorHandles: HandleDescriptor[] = [ elevatorMoveHandle(), ] -/** - * Elevator — Stage A registration. Wrap-exports the legacy renderer + - * the three legacy systems (runtime / interaction / opening) bundled - * as one `def.system`. Move / inspector still go through legacy - * (`MoveElevatorTool`, ``) via panel-manager's - * hardcoded switch. - */ export const elevatorDefinition: NodeDefinition = { kind: 'elevator', schemaVersion: 1, @@ -201,7 +204,15 @@ export const elevatorDefinition: NodeDefinition = { // (and the side move-arrows emitted from `def.floorplan`) drive the // 2D body-move flow through `FloorplanRegistryMoveOverlay`'s // Path 2 — position[0] / position[2] update with a 0.5m grid snap. - movable: { axes: ['x', 'z'], gridSnap: true }, + movable: { + axes: ['x', 'z'], + gridSnap: true, + resolvePosition: ({ node, position, nodes }) => [ + position[0], + resolveElevatorNodeSupportY(node as ElevatorNodeType, position, nodes), + position[2], + ], + }, // Align by the OUTER SHAFT (shaft + wall — what's drawn in plan and 3D), // not the cab `width × depth`: the cab is inset by the shaft wall + // clearance, so cab corners sit ~9 cm inside the visible edge — past the @@ -227,7 +238,7 @@ export const elevatorDefinition: NodeDefinition = { const e = node as ElevatorNodeType const { halfX, halfZ } = elevatorOuterHalfExtents(e) const { shaftBaseY, totalHeight } = resolveElevatorLevels(e, nodes ?? {}) - const cabHeight = Math.max(e.cabHeight, 1.4) + const cabHeight = resolveElevatorDimensions(e).cabHeight const shaftHeight = Math.max(totalHeight, cabHeight + 0.3) return { size: [halfX * 2, shaftHeight, halfZ * 2], @@ -240,6 +251,7 @@ export const elevatorDefinition: NodeDefinition = { paint: elevatorPaint, }, + tool: () => import('./tool'), parametrics: elevatorParametrics, handles: elevatorHandles, @@ -275,7 +287,7 @@ export const elevatorDefinition: NodeDefinition = { presentation: { label: 'Elevator', description: 'A multi-level elevator shaft with configurable openings per level.', - icon: { kind: 'url', src: '/icons/wallcut.webp' }, + icon: { kind: 'url', src: '/icons/elevator.webp' }, paletteSection: 'structure', paletteOrder: 80, }, diff --git a/packages/nodes/src/elevator/floorplan-affordances.ts b/packages/nodes/src/elevator/floorplan-affordances.ts index cfa5073370..c8435ad83f 100644 --- a/packages/nodes/src/elevator/floorplan-affordances.ts +++ b/packages/nodes/src/elevator/floorplan-affordances.ts @@ -1,14 +1,17 @@ import { type AnyNodeId, + ELEVATOR_MIN_CAB_DIMENSION, type ElevatorNode, type FloorplanAffordance, + normalizeElevatorDimensions, + resolveElevatorDimensions, useLiveNodeOverrides, useScene, } from '@pascal-app/core' import { isAngleSnapActive } from '@pascal-app/editor' import { rotateAffordanceDelta } from '../shared/rotate-affordance' -const MIN_ELEVATOR_DIM = 0.6 +const MIN_ELEVATOR_DIM = ELEVATOR_MIN_CAB_DIMENSION type ElevatorResizePayload = { axis: 'x' | 'z'; side: 1 | -1 } @@ -23,7 +26,8 @@ export const elevatorResizeAffordance: FloorplanAffordance = { start({ node, payload, initialPlanPoint }) { const { axis, side } = payload as ElevatorResizePayload const elevatorId = node.id as AnyNodeId - const initialValue = axis === 'x' ? node.width : node.depth + const initialValue = + axis === 'x' ? resolveElevatorDimensions(node).width : resolveElevatorDimensions(node).depth const cx = node.position[0] const cz = node.position[2] const rotation = node.rotation ?? 0 @@ -49,9 +53,13 @@ export const elevatorResizeAffordance: FloorplanAffordance = { const delta = (currentLocal - initialLocal) * side const newValue = Math.max(MIN_ELEVATOR_DIM, initialValue + 2 * delta) lastValue = newValue - useLiveNodeOverrides - .getState() - .set(elevatorId, axis === 'x' ? { width: newValue } : { depth: newValue }) + useLiveNodeOverrides.getState().set( + elevatorId, + normalizeElevatorDimensions({ + ...node, + ...(axis === 'x' ? { width: newValue } : { depth: newValue }), + }), + ) useScene.getState().markDirty(elevatorId) }, canCommit() { @@ -59,9 +67,13 @@ export const elevatorResizeAffordance: FloorplanAffordance = { }, commit() { useLiveNodeOverrides.getState().clear(elevatorId) - useScene - .getState() - .updateNode(elevatorId, axis === 'x' ? { width: lastValue } : { depth: lastValue }) + useScene.getState().updateNode( + elevatorId, + normalizeElevatorDimensions({ + ...node, + ...(axis === 'x' ? { width: lastValue } : { depth: lastValue }), + }), + ) }, } }, diff --git a/packages/nodes/src/elevator/floorplan.ts b/packages/nodes/src/elevator/floorplan.ts index e6e3285628..f5f863709d 100644 --- a/packages/nodes/src/elevator/floorplan.ts +++ b/packages/nodes/src/elevator/floorplan.ts @@ -4,6 +4,7 @@ import { type FloorplanGeometry, type FloorplanPoint, type GeometryContext, + resolveElevatorDimensions, resolveElevatorServiceLevelIds, useInteractive, useLiveNodeOverrides, @@ -29,8 +30,6 @@ import { * subscribes to both stores so this builder re-runs on change. */ -const STAGE_LEVEL_FILTER_HIDE = false - export function buildElevatorFloorplan( node: ElevatorNode, ctx: GeometryContext, @@ -45,7 +44,7 @@ export function buildElevatorFloorplan( // hosted on, which is the active level when the registry layer walks // from `levelId`). const parentLevelId = ctx.parent?.id - if (STAGE_LEVEL_FILTER_HIDE && parentLevelId) { + if (parentLevelId) { const sceneNodes = collectAllNodes(ctx) const serviceLevelIds = resolveElevatorServiceLevelIds(display, sceneNodes) if (!serviceLevelIds.includes(parentLevelId as AnyNodeId)) { @@ -53,12 +52,12 @@ export function buildElevatorFloorplan( } } - const wallThickness = Math.max(display.shaftWallThickness ?? 0.09, 0.04) - const cabWidth = Math.max(display.width, 0.8) - const cabDepth = Math.max(display.depth, 0.8) - const shaftWidth = Math.max(display.shaftWidth ?? display.width, cabWidth, 0.8) - const shaftDepth = Math.max(display.shaftDepth ?? display.depth, cabDepth, 0.8) - const doorWidth = Math.min(Math.max(display.doorWidth, 0.45), shaftWidth - 0.24) + const { + shaftWallThickness: wallThickness, + shaftWidth, + shaftDepth, + doorWidth, + } = resolveElevatorDimensions(display) const outerHalfW = Math.max(0.1, shaftWidth / 2 + wallThickness) const outerHalfD = Math.max(0.1, shaftDepth / 2 + wallThickness) const innerHalfW = Math.max(0.05, shaftWidth / 2) diff --git a/packages/nodes/src/elevator/inspection.tsx b/packages/nodes/src/elevator/inspection.tsx new file mode 100644 index 0000000000..47105d12b2 --- /dev/null +++ b/packages/nodes/src/elevator/inspection.tsx @@ -0,0 +1,111 @@ +import type { AnyNodeId, ElevatorNode, ElevatorSlotId } from '@pascal-app/core' +import { OVERLAY_LAYER } from '@pascal-app/viewer' +import { useFrame } from '@react-three/fiber' +import { type ReactNode, type RefObject, useEffect, useRef } from 'react' +import { type Group, Matrix4, Mesh } from 'three' +import { MeshBasicNodeMaterial } from 'three/webgpu' +import { create } from 'zustand' + +export const useElevatorInspection = create<{ + nodeId: AnyNodeId | null + cutaway: boolean + part: ElevatorSlotId | null +}>(() => ({ nodeId: null, cutaway: false, part: null })) + +export function ElevatorInspectorHover({ + nodeId, + children, +}: { + nodeId: AnyNodeId + children: ReactNode +}) { + useEffect(() => { + useElevatorInspection.setState({ nodeId, part: null, cutaway: false }) + const clear = () => useElevatorInspection.setState({ part: null }) + const onEscape = (event: KeyboardEvent) => { + if (event.key === 'Escape') clear() + } + window.addEventListener('blur', clear) + window.addEventListener('keydown', onEscape) + return () => { + window.removeEventListener('blur', clear) + window.removeEventListener('keydown', onEscape) + useElevatorInspection.setState({ nodeId: null, part: null, cutaway: false }) + } + }, [nodeId]) + const highlight = (element: EventTarget | null) => { + const slot = + element instanceof Element + ? element.closest('[data-elevator-part]')?.dataset.elevatorPart + : undefined + useElevatorInspection.setState({ + part: + slot === 'cab' || slot === 'doors' || slot === 'shaft' || slot === 'glass' ? slot : null, + }) + } + return ( +
highlight(event.target)} + onPointerLeave={() => highlight(null)} + onFocusCapture={(event) => highlight(event.target)} + onBlurCapture={(event) => highlight(event.relatedTarget)} + > + {children} +
+ ) +} + +export function ElevatorInspectionOverlay({ + node, + source, +}: { + node: ElevatorNode + source: RefObject +}) { + const ref = useRef(null) + const part = useElevatorInspection((state) => (state.nodeId === node.id ? state.part : null)) + const copies = useRef>([]) + useEffect(() => { + if (!part || !ref.current || !source.current || !node.id) return + const target = ref.current + const fill = new MeshBasicNodeMaterial({ + color: '#38bdf8', + opacity: 0.3, + transparent: true, + depthWrite: false, + depthTest: false, + }) + source.current.traverse((object) => { + if (!(object instanceof Mesh) || object.userData.slotId !== part) return + const copy = new Mesh(object.geometry, fill) + copy.matrixAutoUpdate = false + copy.layers.set(OVERLAY_LAYER) + copy.raycast = () => {} + copy.userData.pascalExport = 'strip' + target.add(copy) + copies.current.push({ source: object, copy }) + }) + return () => { + target.clear() + copies.current = [] + fill.dispose() + } + }, [part, source, node]) + useFrame(() => { + if (!part || !ref.current) return + ref.current.updateWorldMatrix(true, false) + const inverse = new Matrix4().copy(ref.current.matrixWorld).invert() + for (const pair of copies.current) { + pair.source.updateWorldMatrix(true, false) + pair.copy.matrix.multiplyMatrices(inverse, pair.source.matrixWorld) + } + }) + return ( + + ) +} diff --git a/packages/nodes/src/elevator/panel.tsx b/packages/nodes/src/elevator/panel.tsx index 7186712776..0dfd66785b 100644 --- a/packages/nodes/src/elevator/panel.tsx +++ b/packages/nodes/src/elevator/panel.tsx @@ -7,7 +7,9 @@ import { getLevelDisplayName, type LevelNode, type MessageDescriptor, + normalizeElevatorDimensions, requestElevatorLevel, + resolveElevatorDimensions, useInteractive, useLiveNodeOverrides, useLiveTransforms, @@ -17,11 +19,9 @@ import { import { ActionButton, ActionGroup, + PanelSection as BasePanelSection, duplicateNodeAndPickUp, - MetricControl, - PanelSection, PanelWrapper, - resolveElevatorNodeSupportY, resolveElevatorSupportY, SliderControl, triggerSFX, @@ -29,8 +29,15 @@ import { } from '@pascal-app/editor' import { useViewer } from '@pascal-app/viewer' import { Copy, Move, Send, Trash2 } from 'lucide-react' -import { useCallback, useEffect } from 'react' +import { type ReactNode, useCallback, useEffect } from 'react' import { useShallow } from 'zustand/react/shallow' +import { ElevatorInspectorHover, useElevatorInspection } from './inspection' +import { + ELEVATOR_PRESETS, + ELEVATOR_SECTION_FIELDS, + elevatorPresetPatch, + elevatorSectionReset, +} from './presets' function findLevelId(levels: LevelNode[], levelId: string | null | undefined) { if (!levelId) return null @@ -96,6 +103,9 @@ type ElevatorMetricKey = | 'cabHeight' | 'doorWidth' | 'doorHeight' + | 'speed' + | 'doorDurationMs' + | 'dwellMs' type ElevatorAccessField = 'disabledLevelIds' | 'serviceOnlyLevelIds' @@ -139,26 +149,20 @@ const SHAFT_STYLE_OPTIONS: Array<{ label: MessageDescriptor value: ElevatorNode['shaftStyle'] }> = [ - { label: /* i18n */ { id: 'node.elevator.panel.solid', message: 'Solid' }, value: 'solid' }, - { label: /* i18n */ { id: 'node.elevator.panel.glass', message: 'Glass' }, value: 'glass' }, + { + label: /* i18n */ { id: 'node.elevator.panel.solid', message: 'Solid' }, + value: 'solid', + }, + { + label: /* i18n */ { id: 'node.elevator.panel.glass', message: 'Glass' }, + value: 'glass', + }, ] function roundMeters(value: number) { return Math.round(value * 100) / 100 } -function getResolvedShaftWidth(node: ElevatorNode) { - return Math.max(node.shaftWidth ?? node.width, node.width, 0.8) -} - -function getResolvedShaftDepth(node: ElevatorNode) { - return Math.max(node.shaftDepth ?? node.depth, node.depth, 0.8) -} - -function getResolvedShaftWallThickness(node: ElevatorNode) { - return Math.max(node.shaftWallThickness ?? 0.09, 0.04) -} - function radiansToDegrees(radians: number) { return Math.round((radians * 180) / Math.PI) } @@ -167,6 +171,65 @@ function degreesToRadians(degrees: number) { return (degrees * Math.PI) / 180 } +type ElevatorSection = + | 'Cab' + | 'Shaft' + | 'Doors' + | 'Service' + | 'Access' + | 'Destination' + | 'Motion' + | 'Actions' + | 'Position' + | 'Rotation' + +function PanelSection({ + section, + title, + children, + onReset, +}: { + section: ElevatorSection + title: string + children: ReactNode + onReset: (section: ElevatorSection) => void +}) { + const i18n = usePascalI18n() + return ( +
+ + {ELEVATOR_SECTION_FIELDS[section] && ( + + )} + {children} + +
+ ) +} + export default function ElevatorPanel() { const i18n = usePascalI18n() const selectedId = useViewer((s) => s.selection.selectedIds[0]) @@ -187,6 +250,7 @@ export default function ElevatorPanel() { }), ) + const cutaway = useElevatorInspection((state) => state.nodeId === selectedId && state.cutaway) const node = useScene((s) => selectedId ? (s.nodes[selectedId as AnyNode['id']] as ElevatorNode | undefined) : undefined, ) @@ -231,43 +295,27 @@ export default function ElevatorPanel() { useLiveTransforms.getState().clear(selectedId as AnyNodeId) }, [selectedId]) - useEffect(() => { - if (!(selectedId && node?.type === 'elevator')) return - const supportY = resolveElevatorNodeSupportY(node) - if (node.position[1] >= supportY - 1e-4) return - - updateNode(selectedId as AnyNode['id'], { - position: [node.position[0], supportY, node.position[2]], - }) - }, [ - node?.defaultLevelId, - node?.fromLevelId, - node?.id, - node?.parentId, - node?.position[0], - node?.position[1], - node?.position[2], - node?.type, - selectedId, - updateNode, - node, - ]) - const previewMetric = useCallback( (key: K, value: ElevatorNode[K]) => { - if (!selectedId) return - useLiveNodeOverrides.getState().set(selectedId as AnyNodeId, { [key]: value }) + if (!(selectedId && node)) return + useLiveNodeOverrides.getState().set(selectedId as AnyNodeId, { + [key]: value, + ...normalizeElevatorDimensions({ ...node, [key]: value }), + }) }, - [selectedId], + [selectedId, node], ) const commitMetric = useCallback( (key: K, value: ElevatorNode[K]) => { - if (!selectedId) return + if (!(selectedId && node)) return const hasChange = !(node && Math.abs(Number(node[key]) - Number(value)) <= 1e-6) if (hasChange) { - updateNode(selectedId as AnyNode['id'], { [key]: value } as Partial) + updateNode(selectedId as AnyNode['id'], { + [key]: value, + ...normalizeElevatorDimensions({ ...node, [key]: value }), + }) } useLiveNodeOverrides.getState().clear(selectedId as AnyNodeId) }, @@ -423,15 +471,26 @@ export default function ElevatorPanel() { [node, levels, handleUpdate], ) + useEffect(() => { + const cancel = () => clearLivePreview() + const key = (event: KeyboardEvent) => { + if (event.key === 'Escape') cancel() + } + window.addEventListener('blur', cancel) + window.addEventListener('keydown', key) + return () => { + window.removeEventListener('blur', cancel) + window.removeEventListener('keydown', key) + } + }, [clearLivePreview]) + if (!(node && node.type === 'elevator' && selectedId && selectedCount === 1)) return null const displayNode = liveOverrides ? ({ ...node, ...liveOverrides } as ElevatorNode) : node const displayPosition = liveTransform?.position ?? displayNode.position const displayRotation = liveTransform?.rotation ?? displayNode.rotation const displayRotationDegrees = radiansToDegrees(displayRotation) - const displayShaftWidth = getResolvedShaftWidth(displayNode) - const displayShaftDepth = getResolvedShaftDepth(displayNode) - const displayShaftWallThickness = getResolvedShaftWallThickness(displayNode) + const dimensions = resolveElevatorDimensions(displayNode) const fromLevelId = getResolvedFromLevelId(node, levels) const toLevelId = getResolvedToLevelId(node, levels, fromLevelId) const servedLevels = getServiceLevels(levels, fromLevelId, toLevelId) @@ -465,471 +524,624 @@ export default function ElevatorPanel() { destinationOrderByLevelId.set(levelId, index + 1) } + const resetSection = (section: ElevatorSection) => { + clearLivePreview() + handleUpdate(elevatorSectionReset(node, section)) + } + return ( - - - - } - label={i18n._({ id: 'node.elevator.panel.move', message: 'Move' })} - onClick={handleMove} + + + +
+ {Object.entries(ELEVATOR_PRESETS).map(([id, preset]) => ( + + ))} +
+ +

+ {i18n._({ + id: 'node.elevator.panel.hoverOrFocusASectionTo', + message: + 'Hover or focus a section to highlight its parts. Cutaway affects this inspection only.', + })} +

+

+ {i18n._({ + id: 'node.elevator.panel.cabInteriorAndDoorOpening', + message: + 'Clear cab interior: {width} × {depth} × {height} m. Door opening: {doorWidth} × {doorHeight} m.', + values: { + width: (dimensions.width - 0.16).toFixed(2), + depth: (dimensions.depth - 0.08).toFixed(2), + height: (dimensions.cabHeight - 0.16).toFixed(2), + doorWidth: dimensions.doorWidth.toFixed(2), + doorHeight: dimensions.doorHeight.toFixed(2), + }, + })} +

+ {servedLevels.some((level) => (level.height ?? 2.5) < dimensions.cabHeight + 0.3) && ( +

+ {i18n._({ + id: 'node.elevator.panel.theCabNeedsMoreHeadroomThan', + message: + 'The cab needs more headroom than one or more served floors provide. Check the floor heights.', + })} +

+ )} +
+ + previewMetric('width', value)} + onCommit={(value) => commitMetric('width', value)} + precision={2} + restoreOnCommit={false} + onCancel={clearLivePreview} + step={0.05} + unit="m" + value={dimensions.width} /> - } - label={i18n._({ id: 'node.elevator.panel.duplicate', message: 'Duplicate' })} - onClick={handleDuplicate} + previewMetric('depth', value)} + onCommit={(value) => commitMetric('depth', value)} + precision={2} + restoreOnCommit={false} + onCancel={clearLivePreview} + step={0.05} + unit="m" + value={dimensions.depth} /> - } - label={i18n._({ id: 'node.elevator.panel.delete', message: 'Delete' })} - onClick={handleDelete} + previewMetric('cabHeight', value)} + onCommit={(value) => commitMetric('cabHeight', value)} + precision={2} + restoreOnCommit={false} + onCancel={clearLivePreview} + step={0.05} + unit="m" + value={dimensions.cabHeight} /> -
-
- - - { - const position = getSupportedPosition(value, displayPosition[2]) - previewTransform(position, displayRotation) - }} - onCommit={(value) => { - const position = getSupportedPosition(value, displayPosition[2]) - commitTransform(position, displayRotation) - }} - precision={2} - restoreOnCommit={false} - step={0.05} - unit="m" - value={roundMeters(displayPosition[0])} - /> - { - const position: ElevatorNode['position'] = [ - displayPosition[0], - value, - displayPosition[2], - ] - previewTransform(position, displayRotation) - }} - onCommit={(value) => { - const position: ElevatorNode['position'] = [ - displayPosition[0], - value, - displayPosition[2], - ] - commitTransform(position, displayRotation) - }} - precision={2} - restoreOnCommit={false} - step={0.05} - unit="m" - value={roundMeters(displayPosition[1])} - /> - { - const position = getSupportedPosition(displayPosition[0], value) - previewTransform(position, displayRotation) - }} - onCommit={(value) => { - const position = getSupportedPosition(displayPosition[0], value) - commitTransform(position, displayRotation) - }} - precision={2} - restoreOnCommit={false} - step={0.05} - unit="m" - value={roundMeters(displayPosition[2])} - /> - - - - previewTransform(displayPosition, degreesToRadians(degrees))} - onCommit={(degrees) => commitTransform(displayPosition, degreesToRadians(degrees))} - precision={0} - restoreOnCommit={false} - step={1} - unit="°" - value={displayRotationDegrees} - /> -
- { - triggerSFX('sfx:item-rotate') - commitTransform(displayPosition, displayRotation - Math.PI / 4) - }} + + + +
+
+ {i18n._({ id: 'node.elevator.panel.shaftStyle', message: 'Shaft Style' })} +
+ +
+ previewMetric('shaftWidth', Math.max(value, dimensions.width))} + onCommit={(value) => commitMetric('shaftWidth', Math.max(value, dimensions.width))} + precision={2} + restoreOnCommit={false} + onCancel={clearLivePreview} + step={0.05} + unit="m" + value={dimensions.shaftWidth} /> - { - triggerSFX('sfx:item-rotate') - commitTransform(displayPosition, displayRotation + Math.PI / 4) - }} + previewMetric('shaftDepth', Math.max(value, dimensions.depth))} + onCommit={(value) => commitMetric('shaftDepth', Math.max(value, dimensions.depth))} + precision={2} + restoreOnCommit={false} + onCancel={clearLivePreview} + step={0.05} + unit="m" + value={dimensions.shaftDepth} /> -
-
+ previewMetric('shaftWallThickness', value)} + onCommit={(value) => commitMetric('shaftWallThickness', value)} + precision={2} + restoreOnCommit={false} + onCancel={clearLivePreview} + step={0.01} + unit="m" + value={dimensions.shaftWallThickness} + /> + - -
+
- {i18n._({ id: 'node.elevator.panel.from', message: 'From' })} + {i18n._({ id: 'node.elevator.panel.openingStyle', message: 'Opening Style' })}
+
+
+
+ {i18n._({ id: 'node.elevator.panel.doorType', message: 'Door Type' })} +
+
+ previewMetric('doorWidth', value)} + onCommit={(value) => commitMetric('doorWidth', value)} + precision={2} + restoreOnCommit={false} + onCancel={clearLivePreview} + step={0.05} + unit="m" + value={dimensions.doorWidth} + /> + previewMetric('doorHeight', value)} + onCommit={(value) => commitMetric('doorHeight', value)} + precision={2} + restoreOnCommit={false} + onCancel={clearLivePreview} + step={0.05} + unit="m" + value={dimensions.doorHeight} + /> +
+ + +
+
+
+ {i18n._({ id: 'node.elevator.panel.from', message: 'From' })} +
+ +
+ +
+
+ {i18n._({ id: 'node.elevator.panel.to', message: 'To' })} +
+ +
+
- {i18n._({ id: 'node.elevator.panel.to', message: 'To' })} + {i18n._({ id: 'node.elevator.panel.defaultFloor', message: 'Default Floor' })}
-
+
-
-
- {i18n._({ id: 'node.elevator.panel.defaultFloor', message: 'Default Floor' })} -
- -
- - - - previewMetric('width', value)} - onCommit={(value) => commitMetric('width', value)} - precision={2} - restoreOnCommit={false} - step={0.05} - unit="m" - value={displayNode.width} - /> - previewMetric('depth', value)} - onCommit={(value) => commitMetric('depth', value)} - precision={2} - restoreOnCommit={false} - step={0.05} - unit="m" - value={displayNode.depth} - /> - previewMetric('cabHeight', value)} - onCommit={(value) => commitMetric('cabHeight', value)} - precision={2} - restoreOnCommit={false} - step={0.05} - unit="m" - value={displayNode.cabHeight} - /> - - - -
-
- {i18n._({ id: 'node.elevator.panel.shaftStyle', message: 'Shaft Style' })} -
- -
- previewMetric('shaftWidth', Math.max(value, displayNode.width))} - onCommit={(value) => commitMetric('shaftWidth', Math.max(value, displayNode.width))} - precision={2} - restoreOnCommit={false} - step={0.05} - unit="m" - value={displayShaftWidth} - /> - previewMetric('shaftDepth', Math.max(value, displayNode.depth))} - onCommit={(value) => commitMetric('shaftDepth', Math.max(value, displayNode.depth))} - precision={2} - restoreOnCommit={false} - step={0.05} - unit="m" - value={displayShaftDepth} - /> - previewMetric('shaftWallThickness', value)} - onCommit={(value) => commitMetric('shaftWallThickness', value)} - precision={2} - restoreOnCommit={false} - step={0.01} - unit="m" - value={displayShaftWallThickness} - /> -
- - -
-
- {i18n._({ id: 'node.elevator.panel.openingStyle', message: 'Opening Style' })} -
- -
-
-
- {i18n._({ id: 'node.elevator.panel.doorType', message: 'Door Type' })} -
- -
- previewMetric('doorWidth', value)} - onCommit={(value) => commitMetric('doorWidth', value)} - precision={2} - restoreOnCommit={false} - step={0.05} - unit="m" - value={displayNode.doorWidth} - /> - previewMetric('doorHeight', value)} - onCommit={(value) => commitMetric('doorHeight', value)} - precision={2} - restoreOnCommit={false} - step={0.05} - unit="m" - value={displayNode.doorHeight} - /> -
- - -
- {servedLevels.map((level) => { - const isDisabled = disabledLevelIds.has(level.id) - const isServiceOnly = serviceOnlyLevelIds.has(level.id) - - return ( -
- {getLevelDisplayName(level)} -
- - -
-
- ) - })} -
-
+ +
+ {servedLevels.map((level) => { + const isDisabled = disabledLevelIds.has(level.id) + const isServiceOnly = serviceOnlyLevelIds.has(level.id) - -
- {servedLevels.map((level) => { - const isActive = activeLevelId === level.id - const stopOrder = destinationOrderByLevelId.get(level.id) - const isDisabled = disabledLevelIds.has(level.id) - const isServiceOnly = serviceOnlyLevelIds.has(level.id) - return ( - +
+
+ ) + })} +
+ + + +
+ {servedLevels.map((level) => { + const isActive = activeLevelId === level.id + const stopOrder = destinationOrderByLevelId.get(level.id) + const isDisabled = disabledLevelIds.has(level.id) + const isServiceOnly = serviceOnlyLevelIds.has(level.id) + return ( + - ) - })} -
-
- - - handleUpdate({ speed: value })} - precision={1} - step={0.1} - unit="m/s" - value={node.speed} - /> - handleUpdate({ doorDurationMs: value })} - step={50} - unit="ms" - value={node.doorDurationMs} - /> - handleUpdate({ dwellMs: value })} - step={100} - unit="ms" - value={node.dwellMs} - /> - - + + {getLevelDisplayName(level)} + {isDisabled ? ( + + {i18n._({ id: 'node.elevator.panel.disabled', message: 'Disabled' })} + + ) : isServiceOnly ? ( + + {i18n._({ id: 'node.elevator.panel.service', message: 'Service' })} + + ) : ( + stopOrder && ( + + {i18n._({ + id: 'node.elevator.panel.stopStoporder', + message: 'Stop {stopOrder}', + values: { stopOrder }, + })} + + ) + )} + + + {isDisabled ? '×' : (stopOrder ?? )} + + + ) + })} + + + + + previewMetric('speed', value)} + onCommit={(value) => commitMetric('speed', value)} + restoreOnCommit={false} + onCancel={clearLivePreview} + precision={1} + step={0.1} + unit="m/s" + value={node.speed} + /> + previewMetric('doorDurationMs', value)} + onCommit={(value) => commitMetric('doorDurationMs', value)} + restoreOnCommit={false} + onCancel={clearLivePreview} + step={50} + unit="ms" + value={node.doorDurationMs} + /> + previewMetric('dwellMs', value)} + onCommit={(value) => commitMetric('dwellMs', value)} + restoreOnCommit={false} + onCancel={clearLivePreview} + step={100} + unit="ms" + value={node.dwellMs} + /> + + + + } + label={i18n._({ id: 'node.elevator.panel.move', message: 'Move' })} + onClick={handleMove} + /> + } + label={i18n._({ id: 'node.elevator.panel.duplicate', message: 'Duplicate' })} + onClick={handleDuplicate} + /> + } + label={i18n._({ id: 'node.elevator.panel.delete', message: 'Delete' })} + onClick={handleDelete} + /> + + + + + { + const position = getSupportedPosition(value, displayPosition[2]) + previewTransform(position, displayRotation) + }} + onCommit={(value) => { + const position = getSupportedPosition(value, displayPosition[2]) + commitTransform(position, displayRotation) + }} + precision={2} + restoreOnCommit={false} + onCancel={clearLivePreview} + step={0.05} + unit="m" + value={roundMeters(displayPosition[0])} + /> + { + const position: ElevatorNode['position'] = [ + displayPosition[0], + value, + displayPosition[2], + ] + previewTransform(position, displayRotation) + }} + onCommit={(value) => { + const position: ElevatorNode['position'] = [ + displayPosition[0], + value, + displayPosition[2], + ] + commitTransform(position, displayRotation) + }} + precision={2} + restoreOnCommit={false} + onCancel={clearLivePreview} + step={0.05} + unit="m" + value={roundMeters(displayPosition[1])} + /> + { + const position = getSupportedPosition(displayPosition[0], value) + previewTransform(position, displayRotation) + }} + onCommit={(value) => { + const position = getSupportedPosition(displayPosition[0], value) + commitTransform(position, displayRotation) + }} + precision={2} + restoreOnCommit={false} + onCancel={clearLivePreview} + step={0.05} + unit="m" + value={roundMeters(displayPosition[2])} + /> + + + + previewTransform(displayPosition, degreesToRadians(degrees))} + onCommit={(degrees) => commitTransform(displayPosition, degreesToRadians(degrees))} + precision={0} + restoreOnCommit={false} + onCancel={clearLivePreview} + step={1} + unit="°" + value={displayRotationDegrees} + /> +
+ { + triggerSFX('sfx:item-rotate') + commitTransform(displayPosition, displayRotation - Math.PI / 4) + }} + /> + { + triggerSFX('sfx:item-rotate') + commitTransform(displayPosition, displayRotation + Math.PI / 4) + }} + /> +
+
+ + ) } diff --git a/packages/nodes/src/elevator/parametrics.ts b/packages/nodes/src/elevator/parametrics.ts index aae4d6bccf..1f8d69a074 100644 --- a/packages/nodes/src/elevator/parametrics.ts +++ b/packages/nodes/src/elevator/parametrics.ts @@ -1,4 +1,8 @@ -import type { ElevatorNode, ParametricDescriptor } from '@pascal-app/core' +import { + type ElevatorNode, + normalizeElevatorDimensions, + type ParametricDescriptor, +} from '@pascal-app/core' export const elevatorParametrics: ParametricDescriptor = { groups: [ @@ -19,9 +23,9 @@ export const elevatorParametrics: ParametricDescriptor = { { label: 'Cab', fields: [ - { key: 'width', kind: 'number', unit: 'm', min: 0.8, max: 1000, step: 0.05 }, - { key: 'depth', kind: 'number', unit: 'm', min: 0.8, max: 1000, step: 0.05 }, - { key: 'cabHeight', kind: 'number', unit: 'm', min: 1.8, max: 1000, step: 0.05 }, + { key: 'width', kind: 'number', unit: 'm', min: 0.8, step: 0.05 }, + { key: 'depth', kind: 'number', unit: 'm', min: 0.8, step: 0.05 }, + { key: 'cabHeight', kind: 'number', unit: 'm', min: 1.8, step: 0.05 }, ], }, { @@ -33,7 +37,6 @@ export const elevatorParametrics: ParametricDescriptor = { label: 'Wall thickness', unit: 'm', min: 0.04, - max: 1000, step: 0.01, }, { @@ -47,8 +50,8 @@ export const elevatorParametrics: ParametricDescriptor = { { label: 'Doors', fields: [ - { key: 'doorWidth', kind: 'number', unit: 'm', min: 0.45, max: 1000, step: 0.05 }, - { key: 'doorHeight', kind: 'number', unit: 'm', min: 1.2, max: 1000, step: 0.05 }, + { key: 'doorWidth', kind: 'number', unit: 'm', min: 0.45, step: 0.05 }, + { key: 'doorHeight', kind: 'number', unit: 'm', min: 1.2, step: 0.05 }, { key: 'doorStyle', kind: 'enum', @@ -95,9 +98,6 @@ export const elevatorParametrics: ParametricDescriptor = { ], }, ], - derive: (next) => ({ - doorHeight: Math.min(next.doorHeight, Math.max(1.2, next.cabHeight - 0.1)), - doorWidth: Math.min(next.doorWidth, Math.max(0.45, next.width - 0.1)), - }), + derive: (next) => normalizeElevatorDimensions(next), customPanel: () => import('./panel'), } diff --git a/packages/nodes/src/elevator/presets.ts b/packages/nodes/src/elevator/presets.ts new file mode 100644 index 0000000000..5953dc7585 --- /dev/null +++ b/packages/nodes/src/elevator/presets.ts @@ -0,0 +1,74 @@ +import { ElevatorNode, type MessageDescriptor, normalizeElevatorDimensions } from '@pascal-app/core' + +export const ELEVATOR_PRESETS: Record< + 'passenger' | 'service' | 'glass', + Pick< + ElevatorNode, + | 'width' + | 'depth' + | 'cabHeight' + | 'doorWidth' + | 'doorHeight' + | 'shaftStyle' + | 'doorStyle' + | 'doorPanelStyle' + > & { label: MessageDescriptor } +> = { + passenger: { + label: /* i18n */ { id: 'node.elevator.preset.passenger', message: 'Passenger' }, + width: 1.84, + depth: 1.84, + cabHeight: 2.35, + doorWidth: 0.95, + doorHeight: 2.1, + shaftStyle: 'solid', + doorStyle: 'center-opening', + doorPanelStyle: 'solid-panel', + }, + service: { + label: /* i18n */ { id: 'node.elevator.preset.service', message: 'Service' }, + width: 2.4, + depth: 3, + cabHeight: 2.7, + doorWidth: 1.4, + doorHeight: 2.4, + shaftStyle: 'solid', + doorStyle: 'single-left', + doorPanelStyle: 'segmented-panel', + }, + glass: { + label: /* i18n */ { id: 'node.elevator.preset.glass', message: 'Glass' }, + width: 1.84, + depth: 1.84, + cabHeight: 2.35, + doorWidth: 0.95, + doorHeight: 2.1, + shaftStyle: 'glass', + doorStyle: 'center-opening', + doorPanelStyle: 'glass-frame', + }, +} + +export function elevatorPresetPatch( + node: ElevatorNode, + id: keyof typeof ELEVATOR_PRESETS, +): Partial { + const { label: _label, ...preset } = ELEVATOR_PRESETS[id] + const next = { ...node, ...preset, shaftWidth: undefined, shaftDepth: undefined } + return { ...preset, ...normalizeElevatorDimensions(next) } +} + +export const ELEVATOR_SECTION_FIELDS: Record = { + Cab: ['width', 'depth', 'cabHeight'], + Shaft: ['shaftWidth', 'shaftDepth', 'shaftStyle', 'shaftWallThickness'], + Doors: ['doorWidth', 'doorHeight', 'doorStyle', 'doorPanelStyle'], + Motion: ['speed', 'doorDurationMs', 'dwellMs'], +} + +export function elevatorSectionReset(node: ElevatorNode, section: string) { + const defaults = ElevatorNode.parse({}) + const patch = Object.fromEntries( + (ELEVATOR_SECTION_FIELDS[section] ?? []).map((key) => [key, defaults[key]]), + ) + return { ...patch, ...normalizeElevatorDimensions({ ...node, ...patch }) } +} diff --git a/packages/nodes/src/elevator/renderer.test.tsx b/packages/nodes/src/elevator/renderer.test.tsx index 038a98c72a..a184d78de6 100644 --- a/packages/nodes/src/elevator/renderer.test.tsx +++ b/packages/nodes/src/elevator/renderer.test.tsx @@ -1,8 +1,17 @@ import { expect, test } from 'bun:test' -import { ElevatorNode } from '@pascal-app/core' +import { + BuildingNode, + ElevatorNode, + elevatorSlots, + LevelNode, + useInteractive, + useScene, +} from '@pascal-app/core' import { useViewer } from '@pascal-app/viewer' -import { Mesh } from 'three' +import { Box3, type Material, Mesh, Raycaster, Vector3 } from 'three' import { installMountedScene, mount } from '../__tests__/harness' +import { useElevatorInspection } from './inspection' +import { elevatorPaint } from './paint' import { ElevatorRenderer } from './renderer' installMountedScene() @@ -26,3 +35,175 @@ test('a glass elevator shaft receives shadows without casting them, like window expect(opaqueCasters.length).toBeGreaterThan(0) await renderer.unmount() }) + +for (const doorPanelStyle of ['glass-frame', 'solid-panel', 'segmented-panel'] as const) { + test(`${doorPanelStyle} paintable surfaces keep metre-scale UVs and reversible slot previews`, async () => { + const node = ElevatorNode.parse({ + shaftStyle: 'glass', + doorPanelStyle, + width: 2, + depth: 1.4, + cabHeight: 3, + shaftWallThickness: 0.2, + }) + useViewer.setState({ textures: true, shading: 'rendered' }) + const renderer = await mount() + const meshes: Mesh[] = [] + renderer.scene.instance.traverse((child) => { + if (child instanceof Mesh && child.userData.slotId) meshes.push(child) + }) + expect(meshes.length).toBeGreaterThan(0) + const slots = elevatorSlots(node).map((slot) => slot.slotId) + for (const mesh of meshes) { + expect(slots).toContain(mesh.userData.slotId) + const position = mesh.geometry.getAttribute('position') + const uv = mesh.geometry.getAttribute('uv') + expect(uv.count).toBe(position.count) + for (let face = 0; face < position.count; face += 4) { + const a = face, + b = face + 3 + const distance = Math.hypot( + (position.getX(a) - position.getX(b)) * mesh.scale.x, + (position.getY(a) - position.getY(b)) * mesh.scale.y, + (position.getZ(a) - position.getZ(b)) * mesh.scale.z, + ) + expect(Math.hypot(uv.getX(a) - uv.getX(b), uv.getY(a) - uv.getY(b))).toBeCloseTo( + distance, + 5, + ) + } + } + const original = meshes.map((mesh) => mesh.material) + for (const role of new Set(meshes.map((mesh) => mesh.userData.slotId))) { + const restore = elevatorPaint.applyPreview({ + node, + role, + root: renderer.scene.instance, + material: { + preset: 'custom', + properties: { + color: '#da3210', + roughness: 0.5, + metalness: 0, + opacity: 1, + transparent: false, + side: 'front', + }, + }, + materialPreset: undefined, + }) + expect(restore).not.toBeNull() + meshes.forEach((mesh, index) => { + if (mesh.userData.slotId === role) expect(mesh.material).not.toBe(original[index]) + else expect(mesh.material).toBe(original[index]) + }) + restore?.() + meshes.forEach((mesh, index) => { + expect(mesh.material).toBe(original[index]) + }) + } + await renderer.unmount() + }) +} + +test('resizing releases old surface geometry, reuses glass finishes, and disposes owned glass on unmount', async () => { + const node = ElevatorNode.parse({ shaftStyle: 'glass' }) + useViewer.setState({ textures: true, shading: 'rendered' }) + useScene.setState({ materials: {} }) + const renderer = await mount() + const findGlass = () => { + let found: Mesh | undefined + renderer.scene.instance.traverse((child) => { + if (!found && child instanceof Mesh && child.userData.slotId === 'glass') found = child + }) + return found! + } + const glass = findGlass() + let geometryDisposals = 0, + materialDisposals = 0 + glass.geometry.addEventListener('dispose', () => geometryDisposals++) + const material = glass.material as Material + material.addEventListener('dispose', () => materialDisposals++) + await renderer.update() + expect(geometryDisposals).toBe(1) + expect(findGlass().material).toBe(material) + expect(materialDisposals).toBe(0) + await renderer.unmount() + expect(materialDisposals).toBe(1) +}) + +test('shaft cutaway hides its shell while retaining the cab, door surfaces and stored geometry', async () => { + const node = ElevatorNode.parse({ shaftStyle: 'glass' }) + const renderer = await mount() + const meshes: Mesh[] = [] + renderer.scene.instance.traverse((child) => { + if (child instanceof Mesh && child.userData.slotId) meshes.push(child) + }) + const geometry = meshes.map((mesh) => mesh.geometry) + const { act } = await import('@react-three/test-renderer') + await act(async () => { + useElevatorInspection.setState({ nodeId: node.id, cutaway: true, part: null }) + }) + expect( + meshes.filter((mesh) => mesh.userData.slotId === 'shaft').every((mesh) => !mesh.visible), + ).toBe(true) + expect( + meshes.filter((mesh) => mesh.userData.slotId === 'cab').every((mesh) => mesh.visible), + ).toBe(true) + meshes.forEach((mesh, index) => { + expect(mesh.geometry).toBe(geometry[index]) + }) + await act(async () => { + useElevatorInspection.setState({ nodeId: null, cutaway: false, part: null }) + }) + expect(meshes.every((mesh) => mesh.visible)).toBe(true) + await renderer.unmount() +}) + +for (const doorStyle of ['center-opening', 'single-left', 'single-right'] as const) { + test(`${doorStyle}: doors travel in separate pockets behind the stationary call panel`, async () => { + const building = BuildingNode.parse({}) + const level = LevelNode.parse({ parentId: building.id, level: 0 }) + building.children = [level.id] + const node = ElevatorNode.parse({ parentId: building.id, doorStyle, shaftWallThickness: 0.04 }) + useScene.setState({ nodes: { [building.id]: building, [level.id]: level, [node.id]: node } }) + useViewer.setState({ textures: true, shading: 'rendered' }) + const renderer = await mount() + const root = renderer.scene.instance + const panel = root.getObjectByName('landing-call-panel')! + expect(panel).toBeDefined() + const walls: Mesh[] = [] + root.traverse((object) => { + if (object instanceof Mesh && object.userData.slotId === 'shaft') walls.push(object) + }) + for (const amount of [0, 0.5, 1]) { + useInteractive.getState().setElevatorState(node.id, { + currentLevelId: level.id, + doorOpen: amount, + carY: 0, + }) + await renderer.advanceFrames(1, 1 / 60) + root.updateMatrixWorld(true) + const panelBounds = new Box3().setFromObject(panel) + const landing = new Box3(), + cab = new Box3() + root.traverse((object) => { + if (object.name.startsWith('landing-door-')) landing.union(new Box3().setFromObject(object)) + if (object.name.startsWith('cab-door-') && object.name !== 'cab-door-surround') + cab.union(new Box3().setFromObject(object)) + }) + expect(landing.isEmpty()).toBe(false) + expect(cab.isEmpty()).toBe(false) + expect(landing.min.z).toBeGreaterThan(panelBounds.max.z) + expect(cab.min.z).toBeGreaterThan(landing.max.z + 0.01) + const ray = new Raycaster( + new Vector3(panel.position.x, 0.6, panelBounds.min.z - 1), + new Vector3(0, 0, 1), + ) + const hits = ray.intersectObjects(walls, false) + expect(hits.length).toBeGreaterThan(0) + expect(hits[0]!.point.z).toBeLessThan(landing.min.z) + } + await renderer.unmount() + }) +} diff --git a/packages/nodes/src/elevator/renderer.tsx b/packages/nodes/src/elevator/renderer.tsx index 5abb6be62c..82180b09d9 100644 --- a/packages/nodes/src/elevator/renderer.tsx +++ b/packages/nodes/src/elevator/renderer.tsx @@ -10,17 +10,13 @@ import { type ElevatorDoorSide, type ElevatorNode, type ElevatorSlotId, - getElevatorCabDepth, - getElevatorCabWidth, getElevatorDoorLeafSides, getElevatorDoorLeafWidth, getElevatorDoorLeafX, - getElevatorShaftDepth, - getElevatorShaftWallThickness, - getElevatorShaftWidth, getResolvedElevatorDoorPanelStyle as getResolvedDoorPanelStyle, getResolvedElevatorDoorStyle as getResolvedDoorStyle, getResolvedElevatorShaftStyle as getResolvedShaftStyle, + resolveElevatorDimensions, resolveElevatorLevels, useInteractive, useLiveNodeOverrides, @@ -40,17 +36,33 @@ import { useViewer, } from '@pascal-app/viewer' import { useFrame } from '@react-three/fiber' -import { createContext, useCallback, useContext, useLayoutEffect, useMemo, useRef } from 'react' +import { + Children, + createContext, + isValidElement, + type ReactNode, + useCallback, + useContext, + useEffect, + useLayoutEffect, + useMemo, + useRef, +} from 'react' import { BoxGeometry, + type BufferGeometry, CylinderGeometry, type Group, type InstancedMesh, type Material, + Matrix4, Object3D, TorusGeometry, + Vector3, } from 'three' +import { mergeGeometries } from 'three/examples/jsm/utils/BufferGeometryUtils.js' import { useShallow } from 'zustand/react/shallow' +import { ElevatorInspectionOverlay, useElevatorInspection } from './inspection' const DEFAULT_STRUCTURE_WHITE = '#f2f0ed' const SHAFT_WALL_COLOR = DEFAULT_STRUCTURE_WHITE @@ -64,9 +76,9 @@ const PANEL_COLOR = '#1f2937' type Vector3Tuple = [number, number, number] const UNIT_BOX_GEOMETRY = new BoxGeometry(1, 1, 1) -const BUTTON_FACE_GEOMETRY = new CylinderGeometry(1, 0.92, 1, 24) -const BUTTON_GLOW_GEOMETRY = new CylinderGeometry(1.42, 1.42, 1, 24) -const BUTTON_RING_GEOMETRY = new TorusGeometry(1.12, 0.12, 8, 24) +const BUTTON_FACE_GEOMETRY = new CylinderGeometry(1, 0.92, 1, 12) +const BUTTON_GLOW_GEOMETRY = new CylinderGeometry(1.42, 1.42, 1, 12) +const BUTTON_RING_GEOMETRY = new TorusGeometry(1.12, 0.12, 6, 12) const LABEL_MATRIX_DUMMY = new Object3D() const SHAFT_TOP_FRAME_CLEARANCE = 0.006 @@ -371,14 +383,14 @@ function getElevatorMaterials( type ElevatorSceneMaterials = ReturnType['materials'] function resolveElevatorFinishMaterial( - node: ElevatorNode, + slots: ElevatorNode['slots'], slotId: ElevatorSlotId, slotDefault: string, sceneMaterials: ElevatorSceneMaterials, shading: RenderShading, roughness: number, ): Material { - const ref = node.slots?.[slotId] + const ref = slots?.[slotId] if (ref) { const resolved = resolveMaterialRef(ref, sceneMaterials, shading) if (resolved) return resolved @@ -389,14 +401,14 @@ function resolveElevatorFinishMaterial( function withElevatorGlassTransparency(material: Material): Material { const glass = material.clone() glass.depthWrite = false - glass.opacity = 0.2 + glass.opacity = material.opacity < 1 ? material.opacity : 0.2 glass.transparent = true glass.needsUpdate = true return glass } function getResolvedElevatorMaterials( - node: ElevatorNode, + slots: ElevatorNode['slots'], shading: RenderShading, textures: boolean, colorPreset: ColorPreset, @@ -406,7 +418,7 @@ function getResolvedElevatorMaterials( if (!textures) return materials const cab = resolveElevatorFinishMaterial( - node, + slots, 'cab', ELEVATOR_CAB_SLOT_DEFAULT, sceneMaterials, @@ -414,7 +426,7 @@ function getResolvedElevatorMaterials( 0.48, ) const doors = resolveElevatorFinishMaterial( - node, + slots, 'doors', ELEVATOR_DOORS_SLOT_DEFAULT, sceneMaterials, @@ -422,7 +434,7 @@ function getResolvedElevatorMaterials( 0.34, ) const shaft = resolveElevatorFinishMaterial( - node, + slots, 'shaft', ELEVATOR_SHAFT_SLOT_DEFAULT, sceneMaterials, @@ -431,7 +443,7 @@ function getResolvedElevatorMaterials( ) const glass = withElevatorGlassTransparency( resolveElevatorFinishMaterial( - node, + slots, 'glass', ELEVATOR_GLASS_SLOT_DEFAULT, sceneMaterials, @@ -504,6 +516,106 @@ const SEGMENT_PROPS: Record< upperRight: { position: [0.32, 0.22, 0], size: [0.11, 0.42, 0.018] }, } +function createElevatorBox(width: number, height: number, depth: number) { + const box = new BoxGeometry(width, height, depth) + const uv = box.getAttribute('uv') + const faceSpans = [ + [depth, height], + [depth, height], + [width, depth], + [width, depth], + [width, height], + [width, height], + ] + for (let face = 0; face < 6; face++) { + const [u, v] = faceSpans[face]! + for (let vertex = face * 4; vertex < face * 4 + 4; vertex++) { + uv.setXY(vertex, uv.getX(vertex) * u!, uv.getY(vertex) * v!) + } + } + return box +} + +type BatchBox = { + material: Material + position?: Vector3Tuple + scale: Vector3Tuple + slotId: ElevatorSlotId + castShadow?: boolean + receiveShadow?: boolean +} + +const ElevatorCutawayContext = createContext(false) + +function StaticBoxes({ children }: { children: ReactNode }) { + const cutaway = useContext(ElevatorCutawayContext) + const boxes = Children.toArray(children) + .filter(isValidElement) + .map((child) => child.props as BatchBox) + const signature = JSON.stringify(boxes.map((box) => ({ ...box, material: box.material.uuid }))) + const batches = useMemo(() => { + const groups = new Map< + string, + { + parts: BufferGeometry[] + material: string + slotId: ElevatorSlotId + castShadow: boolean + receiveShadow: boolean + } + >() + for (const box of JSON.parse(signature) as Array< + Omit & { material: string } + >) { + const key = [box.material, box.slotId, box.castShadow, box.receiveShadow].join(':') + let group = groups.get(key) + if (!group) { + group = { + parts: [], + material: box.material, + slotId: box.slotId, + castShadow: !!box.castShadow, + receiveShadow: !!box.receiveShadow, + } + groups.set(key, group) + } + const geometry = createElevatorBox(...box.scale) + geometry.applyMatrix4(new Matrix4().makeTranslation(...(box.position ?? [0, 0, 0]))) + group.parts.push(geometry) + } + return [...groups.values()].map(({ parts, ...group }) => { + const geometry = mergeGeometries(parts)! + for (const part of parts) part.dispose() + return { ...group, geometry } + }) + }, [signature]) + useEffect( + () => () => { + for (const batch of batches) batch.geometry.dispose() + }, + [batches], + ) + return ( + + {batches.map((batch) => { + const material = boxes.find((box) => box.material.uuid === batch.material)!.material + return ( + + ) + })} + + ) +} + function BoxPrimitive({ castShadow = false, material, @@ -521,16 +633,27 @@ function BoxPrimitive({ scale: Vector3Tuple slotId?: ElevatorSlotId }) { + const [width, height, depth] = scale + const geometry = useMemo(() => { + if (!slotId) return UNIT_BOX_GEOMETRY + return createElevatorBox(width, height, depth) + }, [width, height, depth, slotId]) + useEffect( + () => () => { + if (geometry !== UNIT_BOX_GEOMETRY) geometry.dispose() + }, + [geometry], + ) return ( ) @@ -788,6 +911,19 @@ function ElevatorMeshButton({ queued: boolean radius?: number }) { + const detailRef = useRef(null) + const detailPosition = useMemo(() => new Vector3(), []) + const cameraPosition = useMemo(() => new Vector3(), []) + useFrame(({ camera }) => { + const detail = detailRef.current + if (!detail) return + detail.getWorldPosition(detailPosition) + camera.getWorldPosition(cameraPosition) + const orthographic = camera as typeof camera & { isOrthographicCamera?: boolean; zoom: number } + detail.visible = orthographic.isOrthographicCamera + ? orthographic.zoom * radius >= 0.5 + : cameraPosition.distanceToSquared(detailPosition) < 18 * 18 + }) const { BUTTON_FACE_MATERIALS, BUTTON_GLOW_MATERIALS, @@ -817,26 +953,6 @@ function ElevatorMeshButton({ return ( - {!disabled && (active || queued) && ( - - )} - - {label && ( - + {!disabled && (active || queued) && ( + + )} + - )} - {glyph === 'door-open' && ( - - )} + {label && ( + + )} + {glyph === 'door-open' && ( + + )} + ) } @@ -879,7 +1017,7 @@ function getElevatorLevelContextNodes( result[level.id] = level for (const levelChildId of level.children) { const child = nodes[levelChildId as AnyNodeId] - if (child?.type === 'ceiling' || child?.type === 'wall') { + if (child?.type === 'ceiling' || child?.type === 'wall' || child?.type === 'slab') { result[child.id] = child } } @@ -945,7 +1083,11 @@ function DoorLeaf({ }, 2.6) return ( - + {resolvedPanelStyle === 'glass-frame' ? ( <> - - + + {[-1, 1].flatMap((side) => + [-1, 1].map((face) => ( + + )), + )} {headerHeight > 0.01 && ( - + ) } @@ -1205,6 +1348,7 @@ function LandingDoor({ } export const ElevatorRenderer = ({ node }: { node: ElevatorNode }) => { + const cutaway = useElevatorInspection((state) => state.nodeId === node.id && state.cutaway) const ref = useRef(null!) const cabRef = useRef(null) const handlers = useNodeEvents(node, 'elevator') @@ -1222,8 +1366,21 @@ export const ElevatorRenderer = ({ node }: { node: ElevatorNode }) => { useShallow((state) => getElevatorLevelContextNodes(renderNode, state.nodes)), ) const materials = useMemo( - () => getResolvedElevatorMaterials(renderNode, shading, textures, colorPreset, sceneMaterials), - [colorPreset, renderNode, sceneMaterials, shading, textures], + () => + getResolvedElevatorMaterials( + renderNode.slots, + shading, + textures, + colorPreset, + sceneMaterials, + ), + [colorPreset, renderNode.slots, sceneMaterials, shading, textures], + ) + useEffect( + () => () => { + if (textures) materials.GLASS_MATERIAL.dispose() + }, + [materials, textures], ) const { CAB_MATERIAL, @@ -1262,18 +1419,16 @@ export const ElevatorRenderer = ({ node }: { node: ElevatorNode }) => { cabRef.current.position.y = runtime.carY }, 2.6) - const cabWidth = getElevatorCabWidth(renderNode) - const cabDepth = getElevatorCabDepth(renderNode) - const shaftWidth = getElevatorShaftWidth(renderNode, cabWidth) - const shaftDepth = getElevatorShaftDepth(renderNode, cabDepth) - const cabHeight = Math.max(renderNode.cabHeight, 1.4) - const shaftWallThickness = getElevatorShaftWallThickness(renderNode) - const doorWidth = Math.min( - Math.max(renderNode.doorWidth, 0.45), - cabWidth - 0.18, - shaftWidth - 0.18, - ) - const doorHeight = Math.min(Math.max(renderNode.doorHeight, 1.2), cabHeight - 0.1) + const { + width: cabWidth, + depth: cabDepth, + shaftWidth, + shaftDepth, + cabHeight, + shaftWallThickness, + doorWidth, + doorHeight, + } = resolveElevatorDimensions(renderNode) const doorPanelStyle = getResolvedDoorPanelStyle(renderNode.doorPanelStyle) const doorStyle = getResolvedDoorStyle(renderNode.doorStyle) const shaftStyle = getResolvedShaftStyle(renderNode.shaftStyle) @@ -1339,16 +1494,29 @@ export const ElevatorRenderer = ({ node }: { node: ElevatorNode }) => { runtimeSnapshot?.phase === 'opening' || runtimeStatus?.phase === 'open' || runtimeSnapshot?.phase === 'open' - const frontWallZ = -shaftDepth / 2 - shaftWallThickness / 2 - const frontZ = frontWallZ - shaftWallThickness / 2 - 0.018 - const landingPanelX = Math.min(shaftWidth / 2 - 0.16, doorWidth / 2 + 0.18) + const frontWallDepth = Math.max(shaftWallThickness, 0.13) + const frontWallZ = -shaftDepth / 2 - frontWallDepth / 2 + const landingDoorZ = frontWallZ + const cabDoorZ = -shaftDepth / 2 + 0.055 + const frontZ = -shaftDepth / 2 - frontWallDepth + const jambWidth = (shaftWidth - doorWidth) / 2 + const landingPanelWidth = Math.min(0.18, jambWidth - 0.02) + const landingPanelX = (shaftWidth + doorWidth) / 4 + const cabReturnWidth = (cabWidth - doorWidth) / 2 const cabCenterZ = -shaftDepth / 2 + cabDepth / 2 const cabPanelX = cabWidth / 2 - 0.075 const cabPanelZ = cabCenterZ - cabDepth / 2 + 0.36 - const cabButtonColumns = entries.length > 1 ? 2 : 1 + const maxButtonRows = Math.max(1, Math.floor((cabHeight - 0.65) / 0.15)) + const cabButtonColumns = Math.max( + entries.length > 1 ? 2 : 1, + Math.ceil(entries.length / maxButtonRows), + ) const cabButtonRows = Math.max(1, Math.ceil(entries.length / cabButtonColumns)) - const cabButtonSpacingX = 0.14 - const cabButtonSpacingY = 0.15 + const cabButtonSpacingX = Math.min( + 0.14, + Math.max(0.035, (cabDepth - 0.65) / (cabButtonColumns + 1)), + ) + const cabButtonSpacingY = Math.min(0.15, (cabHeight - 0.65) / (cabButtonRows + 1)) const cabDoorButtonOffsetX = 0.17 const cabFloorButtonOffsetX = entries.length > 0 ? -cabDoorButtonOffsetX / 2 : 0 const cabDoorButtonX = @@ -1375,230 +1543,267 @@ export const ElevatorRenderer = ({ node }: { node: ElevatorNode }) => { return ( - - - - - - - - - - - - - - - - - - - - - - + + + - - {entries.map((entry, index) => { - const column = index % cabButtonColumns - const row = Math.floor(index / cabButtonColumns) - const isDisabledLevel = disabledLevelIds.has(entry.id) - const x = - cabFloorButtonOffsetX + (column - (cabButtonColumns - 1) / 2) * cabButtonSpacingX - const y = (row - (cabButtonRows - 1) / 2) * cabButtonSpacingY - - return ( - - ) - })} - - - + + + + + + - {entrySpans.map(({ entry, levelTopY }) => { - const isCurrentLevel = activeLevelId === entry.id - const isDisabledLevel = disabledLevelIds.has(entry.id) - const isServiceOnlyLevel = serviceOnlyLevelIds.has(entry.id) - const isQueuedLevel = !isDisabledLevel && queuedLevelIds.has(entry.id) - const isPendingLevel = pendingLevelId === entry.id - const showLandingReadout = isCurrentLevel || isPendingLevel || isQueuedLevel - - return ( - - - - - + + + + + + {[-1, 1].map((side) => ( + + ))} + + + + + + + + + + {entries.map((entry, index) => { + const column = index % cabButtonColumns + const row = Math.floor(index / cabButtonColumns) + const isDisabledLevel = disabledLevelIds.has(entry.id) + const x = + cabFloorButtonOffsetX + (column - (cabButtonColumns - 1) / 2) * cabButtonSpacingX + const y = (row - (cabButtonRows - 1) / 2) * cabButtonSpacingY + + return ( + + ) + })} + + + + + {entrySpans.map(({ entry, levelTopY }) => { + const isCurrentLevel = activeLevelId === entry.id + const isDisabledLevel = disabledLevelIds.has(entry.id) + const isServiceOnlyLevel = serviceOnlyLevelIds.has(entry.id) + const isQueuedLevel = !isDisabledLevel && queuedLevelIds.has(entry.id) + const isPendingLevel = pendingLevelId === entry.id + const showLandingReadout = isCurrentLevel || isPendingLevel || isQueuedLevel + + return ( + + - 0.5 - } - buttonKind="landing" - disabled={isDisabledLevel || isServiceOnlyLevel} + - + + + 0.5 + } + buttonKind="landing" + disabled={isDisabledLevel || isServiceOnlyLevel} + elevatorId={elevatorId} + levelId={entry.id as AnyNodeId} + position={[0, 0.06, -0.045]} + queued={isQueuedLevel} + radius={Math.min(0.045, landingPanelWidth * 0.3)} + /> + + - - ) - })} - + ) + })} + + + ) } diff --git a/packages/nodes/src/elevator/system.tsx b/packages/nodes/src/elevator/system.tsx index e45853b982..5bf58fa735 100644 --- a/packages/nodes/src/elevator/system.tsx +++ b/packages/nodes/src/elevator/system.tsx @@ -1,6 +1,7 @@ 'use client' import { ElevatorOpeningSystem, stepElevatorRuntimes } from '@pascal-app/core' +import { useEditor } from '@pascal-app/editor' import { ElevatorInteractionSystem } from '@pascal-app/viewer' import { useFrame } from '@react-three/fiber' @@ -21,10 +22,11 @@ function ElevatorRuntimeSystem() { * `ElevatorOpeningSystem` (wall + slab cutout cascade). */ export default function ElevatorSystem() { + const enabled = useEditor((state) => state.mode === 'select' || state.isPreviewMode) return ( <> - + ) diff --git a/packages/editor/src/components/tools/elevator/elevator-tool.tsx b/packages/nodes/src/elevator/tool.tsx similarity index 90% rename from packages/editor/src/components/tools/elevator/elevator-tool.tsx rename to packages/nodes/src/elevator/tool.tsx index b374f30a5b..c6449b3a98 100644 --- a/packages/editor/src/components/tools/elevator/elevator-tool.tsx +++ b/packages/nodes/src/elevator/tool.tsx @@ -9,29 +9,35 @@ import { resolveAlignment, useScene, } from '@pascal-app/core' -import { useEffect, useMemo, useRef } from 'react' -import * as THREE from 'three' -import { resolveCurrentBuildingId, resolveElevatorSupportY } from '../../../lib/elevator-support' -import { sfxEmitter } from '../../../lib/sfx-bus' -import { isTypingTarget } from '../../../lib/typing-target' -import useAlignmentGuides from '../../../store/use-alignment-guides' -import useEditor, { +import { + CursorSphere, isAlignmentGuideActive, isGridSnapActive, isMagneticSnapActive, -} from '../../../store/use-editor' -import usePlacementPreview from '../../../store/use-placement-preview' -import { CursorSphere } from '../shared/cursor-sphere' -import { - DEFAULT_ELEVATOR_CAB_HEIGHT, - DEFAULT_ELEVATOR_DEPTH, - DEFAULT_ELEVATOR_DOOR_DURATION_MS, - DEFAULT_ELEVATOR_DOOR_HEIGHT, - DEFAULT_ELEVATOR_DOOR_WIDTH, - DEFAULT_ELEVATOR_DWELL_MS, - DEFAULT_ELEVATOR_SPEED, - DEFAULT_ELEVATOR_WIDTH, -} from './elevator-defaults' + resolveCurrentBuildingId, + resolveElevatorSupportY, + triggerSFX, + useAlignmentGuides, + useEditor, + usePlacementPreview, + useRegistryToolContext, +} from '@pascal-app/editor' +import { useViewer } from '@pascal-app/viewer' +import { useEffect, useMemo, useRef } from 'react' +import * as THREE from 'three' + +const defaults = ElevatorNode.parse({}) +const DEFAULT_ELEVATOR_WIDTH = defaults.width +const DEFAULT_ELEVATOR_DEPTH = defaults.depth +const DEFAULT_ELEVATOR_CAB_HEIGHT = defaults.cabHeight +const DEFAULT_ELEVATOR_DOOR_WIDTH = defaults.doorWidth +const DEFAULT_ELEVATOR_DOOR_HEIGHT = defaults.doorHeight +const DEFAULT_ELEVATOR_SPEED = defaults.speed +const DEFAULT_ELEVATOR_DOOR_DURATION_MS = defaults.doorDurationMs +const DEFAULT_ELEVATOR_DWELL_MS = defaults.dwellMs +const isTypingTarget = (target: EventTarget | null) => + target instanceof HTMLElement && + !!target.closest('input, textarea, select, [contenteditable="true"]') const GRID_OFFSET = 0.02 /** Figma-style alignment-snap threshold (meters), matching the move tools. */ @@ -82,7 +88,10 @@ function createElevatorPreviewGeometry(): THREE.BufferGeometry { } function createElevatorPreviewEdgeGeometry(): THREE.BufferGeometry { - return new THREE.EdgesGeometry(createElevatorPreviewGeometry()) + const box = createElevatorPreviewGeometry() + const edges = new THREE.EdgesGeometry(box) + box.dispose() + return edges } function commitElevatorPlacement( @@ -120,10 +129,13 @@ function commitElevatorPlacement( createNode(elevator, buildingId) onPlaced?.(elevator.id as AnyNodeId, buildingId) - sfxEmitter.emit('sfx:structure-build') + triggerSFX('sfx:structure-build') } -export const ElevatorTool: React.FC = ({ buildingId, levelId, onPlaced }) => { +export default function ElevatorTool() { + const { activeLevelId: levelId, selectNode } = useRegistryToolContext() + const buildingId = useViewer((state) => state.selection.buildingId) + const onPlaced = useMemo(() => (id: AnyNodeId) => selectNode(id), [selectNode]) const cursorRef = useRef(null) const previewRef = useRef(null) const rotationRef = useRef(0) @@ -242,7 +254,7 @@ export const ElevatorTool: React.FC = ({ buildingId, levelId, previousGridPosRef.current && (gridX !== previousGridPosRef.current[0] || gridZ !== previousGridPosRef.current[1]) ) { - sfxEmitter.emit('sfx:grid-snap') + triggerSFX('sfx:grid-snap') } previousGridPosRef.current = [gridX, gridZ] @@ -294,7 +306,7 @@ export const ElevatorTool: React.FC = ({ buildingId, levelId, if (rotationDelta !== 0) { event.preventDefault() - sfxEmitter.emit('sfx:item-rotate') + triggerSFX('sfx:item-rotate') rotationRef.current += rotationDelta if (previewRef.current) previewRef.current.rotation.y = rotationRef.current // Reflect the rotation in the 2D ghost immediately (no pointer move diff --git a/packages/nodes/src/eyebrow-vent/definition.ts b/packages/nodes/src/eyebrow-vent/definition.ts index 010df84785..bcc99f6364 100644 --- a/packages/nodes/src/eyebrow-vent/definition.ts +++ b/packages/nodes/src/eyebrow-vent/definition.ts @@ -113,6 +113,7 @@ const eyebrowVentHandles: HandleDescriptor[] = [ */ export const eyebrowVentDefinition: NodeDefinition = { kind: 'eyebrow-vent', + snapProfile: 'item', schemaVersion: 3, schema: EyebrowVentNode, category: 'structure', diff --git a/packages/nodes/src/eyebrow-vent/move-tool.tsx b/packages/nodes/src/eyebrow-vent/move-tool.tsx index 8798e441d3..71659e8ecb 100644 --- a/packages/nodes/src/eyebrow-vent/move-tool.tsx +++ b/packages/nodes/src/eyebrow-vent/move-tool.tsx @@ -12,7 +12,10 @@ import { } from '@pascal-app/core' import { consumePlacementDragRelease, + isGridSnapActive, + isMagneticSnapActive, markToolCancelConsumed, + stripPlacementMetadataFlags, triggerSFX, useEditor, } from '@pascal-app/editor' @@ -85,9 +88,9 @@ export default function MoveEyebrowVentTool({ node }: { node: EyebrowVentNode }) const rawTarget = roofDrag.resolve(event) if (!rawTarget) return null return snapRoofSurfaceNodeTarget({ - target: snapRelativeRoofDragTarget(rawTarget, event.nativeEvent?.shiftKey === true), + target: snapRelativeRoofDragTarget(rawTarget, event.nativeEvent?.altKey === true), node, - bypass: event.nativeEvent?.shiftKey === true, + bypass: !isMagneticSnapActive() || event.nativeEvent?.altKey === true, }) } @@ -102,7 +105,8 @@ export default function MoveEyebrowVentTool({ node }: { node: EyebrowVentNode }) const sx = Math.round(target.localX * 20) / 20 const sz = Math.round(target.localZ * 20) / 20 if ( - event.nativeEvent?.shiftKey !== true && + isGridSnapActive() && + event.nativeEvent?.altKey !== true && (!lastSnap || lastSnap[0] !== sx || lastSnap[1] !== sz) ) { triggerSFX('sfx:grid-snap') @@ -160,7 +164,7 @@ export default function MoveEyebrowVentTool({ node }: { node: EyebrowVentNode }) position: [target.localX, target.localY, target.localZ], rotation: original.rotation, visible: true, - metadata: {}, + metadata: stripPlacementMetadataFlags(original.metadata), }) useScene.temporal.getState().pause() diff --git a/packages/nodes/src/gutter/move-tool.tsx b/packages/nodes/src/gutter/move-tool.tsx index 78c104cc28..e9957fe609 100644 --- a/packages/nodes/src/gutter/move-tool.tsx +++ b/packages/nodes/src/gutter/move-tool.tsx @@ -12,7 +12,9 @@ import { } from '@pascal-app/core' import { consumePlacementDragRelease, + isGridSnapActive, markToolCancelConsumed, + stripPlacementMetadataFlags, triggerSFX, useEditor, } from '@pascal-app/editor' @@ -93,7 +95,7 @@ export default function MoveGutterTool({ node }: { node: GutterNode }) { const resolveTarget = (event: RoofEvent): GutterDragTarget | null => { const rawTarget = roofDrag.resolve(event) if (!rawTarget) return null - const target = snapRelativeRoofDragTarget(rawTarget, event.nativeEvent?.shiftKey === true) + const target = snapRelativeRoofDragTarget(rawTarget, event.nativeEvent?.altKey === true) return { segment: target.segment, snap: resolveEaveSnap(target.segment, target.localX, target.localZ), @@ -119,7 +121,8 @@ export default function MoveGutterTool({ node }: { node: GutterNode }) { const sx = Math.round(snap.eaveX * 20) / 20 const sz = Math.round(snap.eaveZ * 20) / 20 if ( - event.nativeEvent?.shiftKey !== true && + isGridSnapActive() && + event.nativeEvent?.altKey !== true && (!lastSnap || lastSnap[0] !== sx || lastSnap[1] !== sz) ) { triggerSFX('sfx:grid-snap') @@ -180,7 +183,7 @@ export default function MoveGutterTool({ node }: { node: GutterNode }) { position: [snap.eaveX, snap.eaveY, snap.eaveZ], rotation: snap.rotation, visible: true, - metadata: {}, + metadata: stripPlacementMetadataFlags(original.metadata), }) useScene.temporal.getState().pause() diff --git a/packages/nodes/src/index.ts b/packages/nodes/src/index.ts index 6d3496e33c..fa69368fb1 100644 --- a/packages/nodes/src/index.ts +++ b/packages/nodes/src/index.ts @@ -197,6 +197,7 @@ export { ductFittingDefinition } from './duct-fitting' export { ductSegmentDefinition } from './duct-segment' export { ductTerminalDefinition } from './duct-terminal' export { elevatorDefinition } from './elevator' +export { ELEVATOR_PRESETS, elevatorPresetPatch } from './elevator/presets' export { eyebrowVentDefinition } from './eyebrow-vent' export { beginFenceFeaturePlacement, fenceDefinition } from './fence' export { fenceGateDefinition, fenceOpeningDefinition } from './fence-feature/definition' @@ -223,6 +224,7 @@ export { type RoofFootprintSourceChoice, roofDefinition, useRoofFootprintSource export { glazedRoofGeometryAdapter } from './roof/glazed-geometry' export { createGlazedRoofMaterials } from './roof/glazed-materials' export { createRoofGlazingPreview } from './roof/glazing-preview' +export { RoofTypeThumbnail } from './roof/type-thumbnail' export { roofSegmentDefinition } from './roof-segment' export { scanDefinition } from './scan' export { separatorDefinition } from './separator/definition' diff --git a/packages/nodes/src/lineset/selection.test.tsx b/packages/nodes/src/lineset/selection.test.tsx index 3ddabc16c9..97e5e49663 100644 --- a/packages/nodes/src/lineset/selection.test.tsx +++ b/packages/nodes/src/lineset/selection.test.tsx @@ -2,6 +2,7 @@ import { beforeEach, expect, test } from 'bun:test' import { type AnyNodeId, BuildingNode, + getEffectiveNode, LevelNode, LinesetNode, SiteNode, @@ -100,7 +101,8 @@ function seed() { return { first: first.id as AnyNodeId, second: second.id as AnyNodeId } } -const pathOf = (id: AnyNodeId) => (useScene.getState().nodes[id] as LinesetNode).path +const pathOf = (id: AnyNodeId) => + getEffectiveNode(useScene.getState().nodes[id] as LinesetNode).path const history = () => useScene.temporal.getState() function client(point: Point) { diff --git a/packages/nodes/src/pipe-segment/selection.tsx b/packages/nodes/src/pipe-segment/selection.tsx index 431cb5c037..2e3756a747 100644 --- a/packages/nodes/src/pipe-segment/selection.tsx +++ b/packages/nodes/src/pipe-segment/selection.tsx @@ -5,6 +5,7 @@ import { type AnyNodeId, analyzePortConnectivity, type Cursor, + findLevelAncestorId, type PipeSegmentNode, type PortConnectivity, pauseSceneHistory, @@ -482,6 +483,9 @@ const PipePointHandles = ({ pipe, target }: { pipe: PipeSegmentNode; target: Obj [next[0], next[1], next[2]], collectScenePorts({ excludeNodeId: pipe.id, + levelId: (findLevelAncestorId(pipe.id, useScene.getState().nodes) ?? undefined) as + | AnyNodeId + | undefined, systems: DWV_PORT_SYSTEMS, }), PORT_SNAP_RADIUS_M, diff --git a/packages/nodes/src/ridge-vent/definition.ts b/packages/nodes/src/ridge-vent/definition.ts index 1be7ae925e..48fd5a4ae7 100644 --- a/packages/nodes/src/ridge-vent/definition.ts +++ b/packages/nodes/src/ridge-vent/definition.ts @@ -157,6 +157,7 @@ const ridgeVentHandles: HandleDescriptor[] = [ */ export const ridgeVentDefinition: NodeDefinition = { kind: 'ridge-vent', + snapProfile: 'item', schemaVersion: 1, schema: RidgeVentNode, category: 'structure', diff --git a/packages/nodes/src/ridge-vent/move-tool.tsx b/packages/nodes/src/ridge-vent/move-tool.tsx index 70508f5eb0..6490d9588f 100644 --- a/packages/nodes/src/ridge-vent/move-tool.tsx +++ b/packages/nodes/src/ridge-vent/move-tool.tsx @@ -12,7 +12,9 @@ import { } from '@pascal-app/core' import { consumePlacementDragRelease, + isGridSnapActive, markToolCancelConsumed, + stripPlacementMetadataFlags, triggerSFX, useEditor, } from '@pascal-app/editor' @@ -86,7 +88,7 @@ export default function MoveRidgeVentTool({ node }: { node: RidgeVentNode }) { const resolveTarget = (event: RoofEvent): RidgeVentDragTarget | null => { const rawTarget = roofDrag.resolve(event) if (!rawTarget) return null - const target = snapRelativeRoofDragTarget(rawTarget, event.nativeEvent?.shiftKey === true) + const target = snapRelativeRoofDragTarget(rawTarget, event.nativeEvent?.altKey === true) const snap = resolveRidgeSnap(target.segment, target.localX, target.localZ) if (!snap) return null const yOffset = original.position[1] ?? 0 @@ -110,7 +112,8 @@ export default function MoveRidgeVentTool({ node }: { node: RidgeVentNode }) { const sx = Math.round(target.localX * 20) / 20 const sz = Math.round(target.localZ * 20) / 20 if ( - event.nativeEvent?.shiftKey !== true && + isGridSnapActive() && + event.nativeEvent?.altKey !== true && (!lastSnap || lastSnap[0] !== sx || lastSnap[1] !== sz) ) { triggerSFX('sfx:grid-snap') @@ -167,7 +170,7 @@ export default function MoveRidgeVentTool({ node }: { node: RidgeVentNode }) { position: [target.localX, original.position[1] ?? 0, target.localZ], rotation: target.rotation, visible: true, - metadata: {}, + metadata: stripPlacementMetadataFlags(original.metadata), }) useScene.temporal.getState().pause() diff --git a/packages/nodes/src/roof-segment/definition.ts b/packages/nodes/src/roof-segment/definition.ts index b2abad9376..247d442e47 100644 --- a/packages/nodes/src/roof-segment/definition.ts +++ b/packages/nodes/src/roof-segment/definition.ts @@ -4,6 +4,8 @@ import { getPitchFromActiveRoofHeight, getRoofSegmentResizePatch, type HandleDescriptor, + MAX_ROOF_PITCH, + MIN_ROOF_SEGMENT_DIMENSION, type NodeDefinition, type RoofNode, RoofSegmentNode as RoofSegmentNodeSchema, @@ -41,14 +43,14 @@ const HEIGHT_HANDLE_OFFSET = 0.3 const ROOF_HANDLE_CLEARANCE = 0.15 const ROTATE_CORNER_OFFSET = 0.4 const ROTATE_RING_OFFSET = 0.08 -const MIN_ROOF_DIM = 1 +const MIN_ROOF_DIM = MIN_ROOF_SEGMENT_DIMENSION const MIN_WALL_HEIGHT = 0 // Clamp used for handle Y placement so arrows stay visible on flat / // wall-less segments where `wallHeight ≈ 0` would put them on the floor. const MIN_WALL_DISPLAY = 0.3 // Pitch is stored in degrees on the schema; same clamp the panel applies. const MIN_PITCH = 0 -const MAX_PITCH = 85 +const MAX_PITCH = MAX_ROOF_PITCH // Floor-to-peak height of the assembled segment. Pitch drag drives this // value directly and back-solves the pitch angle via the slope-frame diff --git a/packages/nodes/src/roof-segment/floorplan-affordances.ts b/packages/nodes/src/roof-segment/floorplan-affordances.ts index d407cd568a..3175b74a81 100644 --- a/packages/nodes/src/roof-segment/floorplan-affordances.ts +++ b/packages/nodes/src/roof-segment/floorplan-affordances.ts @@ -3,6 +3,7 @@ import { type FloorplanAffordance, type FloorplanMoveTarget, getRoofSegmentResizePatch, + MIN_ROOF_SEGMENT_DIMENSION, type RoofNode, type RoofSegmentNode, snapScalar, @@ -27,7 +28,7 @@ import { import { createFloorplanCursorResolver } from '../shared/floorplan-cursor' import { rotateAffordanceDelta } from '../shared/rotate-affordance' -const MIN_ROOF_DIM = 1 +const MIN_ROOF_DIM = MIN_ROOF_SEGMENT_DIMENSION type RoofSegmentResizePayload = { mode: 'radial' } | { axis: 'x' | 'z'; side: 1 | -1 } diff --git a/packages/nodes/src/roof-segment/panel.tsx b/packages/nodes/src/roof-segment/panel.tsx index 2332c4cc0f..f7979748ac 100644 --- a/packages/nodes/src/roof-segment/panel.tsx +++ b/packages/nodes/src/roof-segment/panel.tsx @@ -11,7 +11,9 @@ import { isAutoRidgeVentEnabled, isDefaultRidgeVentNode, isGlazedRoofSegment, + MAX_ROOF_PITCH, type MessageDescriptor, + MIN_ROOF_SEGMENT_DIMENSION, normalizeRoofSegmentTrim, ROOF_SHAPE_DEFAULTS, type RoofEaveCut, @@ -35,13 +37,16 @@ import { ToggleControl, triggerSFX, useEditor, + useInteractionScope, } from '@pascal-app/editor' import { useViewer } from '@pascal-app/viewer' import { Check, Copy, Move, Pencil, RotateCcw, Trash2 } from 'lucide-react' import { useCallback } from 'react' import { BarrelRoofPanel } from '../roof/barrel-panel' +import { RoofGeometryNotice } from '../roof/geometry-notice' import { RoofGlazingPanel } from '../roof/glazing-panel' import { commitSeatedRoofEdit } from '../roof/roof-level-target' +import { RoofTypeThumbnail } from '../roof/type-thumbnail' import { RoofBuildUpSection } from './build-up-section' const ROOF_TYPE_OPTIONS: { label: MessageDescriptor; value: RoofType }[] = [ @@ -127,10 +132,6 @@ function hasSegmentTrim(node: RoofSegmentNode): boolean { return Object.values(normalizeRoofSegmentTrim(node)).some((value) => value > 0) } -function shouldShowTrimPlanes(metadata: unknown): boolean { - return metadataRecord(metadata).showTrimPlanes === true -} - function isManagedLeanToRoofSegment(metadata: unknown): boolean { const record = metadataRecord(metadata) return record.managedByLeanTo !== undefined && record.leanToRole === 'roof-segment' @@ -147,7 +148,10 @@ export default function RoofSegmentPanel() { const i18n = usePascalI18n() const selectedId = useViewer((s) => s.selection.selectedIds[0]) const setSelection = useViewer((s) => s.setSelection) - const updateNode = useScene((s) => s.updateNode) + const showTrimPlanes = useInteractionScope( + (s) => + s.scope.kind === 'reshaping' && s.scope.reshape === 'trim' && s.scope.nodeId === selectedId, + ) const setMovingNode = useEditor((s) => s.setMovingNode) const setRoofHostDragArmedId = useEditor((s) => s.setRoofHostDragArmedId) const unit = useViewer((s) => s.unit) @@ -227,7 +231,6 @@ export default function RoofSegmentPanel() { ...metadataRecord(node?.metadata), autoGutter: false, autoRidgeVent: false, - showTrimPlanes: false, }, } : roofType === 'dutch' @@ -246,25 +249,27 @@ export default function RoofSegmentPanel() { ) const handleClose = useCallback(() => { - if (node && shouldShowTrimPlanes(node.metadata)) { - updateNode(node.id, { - metadata: { ...metadataRecord(node.metadata), showTrimPlanes: false }, - }) - } + useInteractionScope + .getState() + .endIf( + (scope) => + scope.kind === 'reshaping' && scope.reshape === 'trim' && scope.nodeId === node?.id, + ) setSelection({ selectedIds: [] }) - }, [node, setSelection, updateNode]) + }, [node, setSelection]) const handleBack = useCallback(() => { if (node?.parentId) { - if (shouldShowTrimPlanes(node.metadata)) { - updateNode(node.id, { - metadata: { ...metadataRecord(node.metadata), showTrimPlanes: false }, - }) - } + useInteractionScope + .getState() + .endIf( + (scope) => + scope.kind === 'reshaping' && scope.reshape === 'trim' && scope.nodeId === node?.id, + ) setRoofHostDragArmedId(node.parentId as AnyNodeId) setSelection({ selectedIds: [node.parentId] }) } - }, [node, setRoofHostDragArmedId, setSelection, updateNode]) + }, [node, setRoofHostDragArmedId, setSelection]) const handleDuplicate = useCallback(() => { if (node) duplicateNodeAndPickUp(node) @@ -350,11 +355,16 @@ export default function RoofSegmentPanel() { (editing: boolean) => { if (!node) return triggerSFX('sfx:item-pick') - handleUpdate({ - metadata: { ...metadataRecord(node.metadata), showTrimPlanes: editing }, - }) + const interaction = useInteractionScope.getState() + if (editing) + interaction.begin({ kind: 'reshaping', reshape: 'trim', nodeId: node.id, driver: 'tool' }) + else + interaction.endIf( + (scope) => + scope.kind === 'reshaping' && scope.reshape === 'trim' && scope.nodeId === node.id, + ) }, - [handleUpdate, node], + [node], ) const handleResetTrim = useCallback(() => { @@ -365,7 +375,6 @@ export default function RoofSegmentPanel() { if (!(node && node.type === 'roof-segment' && selectedId)) return null - const showTrimPlanes = shouldShowTrimPlanes(node.metadata) const managedLeanToRoofSegment = isManagedLeanToRoofSegment(node.metadata) const conicalCoverage = getConicalRoofCoverage(node) // both overhangs in plan, past the walls' outside faces; the node keeps the eaves' along the slope @@ -383,11 +392,20 @@ export default function RoofSegmentPanel() { } width={300} > + handleRoofTypeChange(v)} - options={ROOF_TYPE_OPTIONS.map((option) => ({ ...option, label: i18n._(option.label) }))} + options={ROOF_TYPE_OPTIONS.map((option) => ({ + ...option, + label: ( + + + {i18n._(option.label)} + + ), + }))} value={node.roofType} disabled={managedLeanToRoofSegment} /> @@ -395,7 +413,12 @@ export default function RoofSegmentPanel() { onChange={(v) => handleRoofTypeChange(v)} options={ROOF_TYPE_OPTIONS_2.map((option) => ({ ...option, - label: i18n._(option.label), + label: ( + + + {i18n._(option.label)} + + ), }))} value={node.roofType} disabled={managedLeanToRoofSegment} @@ -404,7 +427,12 @@ export default function RoofSegmentPanel() { onChange={(v) => handleRoofTypeChange(v)} options={ROOF_TYPE_OPTIONS_3.map((option) => ({ ...option, - label: i18n._(option.label), + label: ( + + + {i18n._(option.label)} + + ), }))} value={node.roofType} disabled={managedLeanToRoofSegment} @@ -471,8 +499,7 @@ export default function RoofSegmentPanel() { {node.roofType === 'conical' ? ( handleUpdate({ width: v, depth: v })} precision={2} step={0.5} @@ -487,8 +514,7 @@ export default function RoofSegmentPanel() { ? i18n._({ id: 'node.roofSegment.panel.length', message: 'Length' }) : i18n._({ id: 'node.roofSegment.panel.width', message: 'Width' }) } - max={1000} - min={0.5} + min={MIN_ROOF_SEGMENT_DIMENSION} onChange={(v) => handleUpdate({ width: v })} precision={2} step={0.5} @@ -501,8 +527,7 @@ export default function RoofSegmentPanel() { ? i18n._({ id: 'node.roofSegment.panel.span', message: 'Span' }) : i18n._({ id: 'node.roofSegment.panel.depth', message: 'Depth' }) } - max={1000} - min={0.5} + min={MIN_ROOF_SEGMENT_DIMENSION} onChange={(v) => handleUpdate({ depth: v })} precision={2} step={0.5} @@ -564,7 +589,6 @@ export default function RoofSegmentPanel() { > handleUpdate({ wallHeight: v })} precision={2} @@ -580,7 +604,7 @@ export default function RoofSegmentPanel() { handleUpdate({ pitch: v })} precision={0} @@ -720,7 +744,6 @@ export default function RoofSegmentPanel() { > handleUpdate({ wallThickness: v })} precision={2} @@ -732,7 +755,6 @@ export default function RoofSegmentPanel() { {!(isGlazedRoofSegment(node) || node.buildUp) && ( handleUpdate({ deckThickness: v })} precision={2} @@ -744,7 +766,6 @@ export default function RoofSegmentPanel() { {node.roofType === 'barrel' ? ( handleUpdate({ overhang: v })} precision={2} @@ -755,7 +776,6 @@ export default function RoofSegmentPanel() { ) : ( handleUpdate({ overhang: v / cosTheta })} precision={2} @@ -770,7 +790,6 @@ export default function RoofSegmentPanel() { id: 'node.roofSegment.panel.gableOverhang', message: 'Gable overhang', })} - max={3} min={0} onChange={(v) => handleUpdate({ gableOverhang: v })} precision={2} @@ -782,7 +801,6 @@ export default function RoofSegmentPanel() { {!(isGlazedRoofSegment(node) || node.buildUp) && ( handleUpdate({ shingleThickness: v })} precision={2} @@ -814,7 +832,6 @@ export default function RoofSegmentPanel() { {node.fascia && ( handleUpdate({ fasciaHeight: v })} precision={2} diff --git a/packages/nodes/src/roof-segment/parametrics.ts b/packages/nodes/src/roof-segment/parametrics.ts index 39df0fdc4a..e3b37ba3a6 100644 --- a/packages/nodes/src/roof-segment/parametrics.ts +++ b/packages/nodes/src/roof-segment/parametrics.ts @@ -1,17 +1,22 @@ -import { type ParametricDescriptor, type RoofSegmentNode, roofTypeHasRakes } from '@pascal-app/core' +import { + MAX_ROOF_PITCH, + MIN_ROOF_SEGMENT_DIMENSION, + type ParametricDescriptor, + type RoofSegmentNode, + roofTypeHasRakes, +} from '@pascal-app/core' export const roofSegmentParametrics: ParametricDescriptor = { groups: [ { label: 'Footprint', fields: [ - { key: 'width', kind: 'number', unit: 'm', min: 0.5, max: 1000, step: 0.5 }, + { key: 'width', kind: 'number', unit: 'm', min: MIN_ROOF_SEGMENT_DIMENSION, step: 0.5 }, { key: 'depth', kind: 'number', unit: 'm', - min: 0.5, - max: 1000, + min: MIN_ROOF_SEGMENT_DIMENSION, step: 0.5, visibleIf: (node) => node.roofType !== 'conical', }, @@ -26,10 +31,17 @@ export const roofSegmentParametrics: ParametricDescriptor = { label: 'Wall', unit: 'm', min: 0, - max: 1000, step: 0.1, }, - { key: 'pitch', kind: 'number', label: 'Pitch', unit: '°', min: 0, max: 85, step: 1 }, + { + key: 'pitch', + kind: 'number', + label: 'Pitch', + unit: '°', + min: 0, + max: MAX_ROOF_PITCH, + step: 1, + }, { key: 'conicalFullCircle', kind: 'boolean', @@ -130,7 +142,6 @@ export const roofSegmentParametrics: ParametricDescriptor = { label: 'Wall thickness', unit: 'm', min: 0.05, - max: 1, step: 0.05, }, { @@ -139,19 +150,17 @@ export const roofSegmentParametrics: ParametricDescriptor = { label: 'Deck thickness', unit: 'm', min: 0.04, - max: 0.3, step: 0.01, // Layers set it: edited here it would part from them. visibleIf: (node) => !node.buildUp, }, - { key: 'overhang', kind: 'number', unit: 'm', min: 0, max: 1, step: 0.05 }, + { key: 'overhang', kind: 'number', unit: 'm', min: 0, step: 0.05 }, { key: 'gableOverhang', kind: 'number', label: 'Gable overhang', unit: 'm', min: 0, - max: 3, step: 0.05, visibleIf: (node) => roofTypeHasRakes(node.roofType), }, @@ -161,7 +170,6 @@ export const roofSegmentParametrics: ParametricDescriptor = { label: 'Shingle thickness', unit: 'm', min: 0.02, - max: 0.3, step: 0.01, // Layers set it: edited here it would part from them. visibleIf: (node) => !node.buildUp, diff --git a/packages/nodes/src/roof-segment/renderer.test.tsx b/packages/nodes/src/roof-segment/renderer.test.tsx index 586aa6e0d1..a7830beb91 100644 --- a/packages/nodes/src/roof-segment/renderer.test.tsx +++ b/packages/nodes/src/roof-segment/renderer.test.tsx @@ -72,3 +72,68 @@ test('a painted segment whose renderer mounts after the scene-load pass still bu await renderer.unmount() } }) + +test('a failed roof rebuild keeps the last valid mesh and recovers after retry', async () => { + const { nodeRegistry, registerNode, SkylightNode } = await import('@pascal-app/core') + const { useGeometryStatus } = await import('@pascal-app/viewer') + const previous = useScene.getState() + const restoreRegistry = nodeRegistry._snapshot() + let fail = false + registerNode({ + kind: 'skylight', + schemaVersion: 1, + schema: SkylightNode, + capabilities: { + roofAccessory: { + buildCut: () => { + if (fail) throw new Error('Cut geometry unavailable') + return null + }, + }, + }, + }) + const roof = RoofNode.parse({ id: 'roof_recovery', children: ['rseg_recovery'] }) + const segment = RoofSegmentNode.parse({ + id: 'rseg_recovery', + parentId: roof.id, + children: ['skylight_recovery'], + }) + const skylight = SkylightNode.parse({ + id: 'skylight_recovery', + parentId: segment.id, + roofSegmentId: segment.id, + }) + useScene.setState({ + nodes: { [roof.id]: roof, [segment.id]: segment, [skylight.id]: skylight }, + rootNodeIds: [roof.id], + dirtyNodes: new Set([segment.id]), + }) + const renderer = await create( + <> + + + , + ) + try { + await renderer.advanceFrames(2, 1 / 60) + const mesh = sceneRegistry.nodes.get(segment.id) as Mesh + const validGeometry = mesh.geometry + expect(validGeometry.getAttribute('position').count).toBeGreaterThan(3) + const stored = useScene.getState().nodes[segment.id] + fail = true + useScene.getState().markDirty(segment.id) + await renderer.advanceFrames(1, 1 / 60) + expect(mesh.geometry).toBe(validGeometry) + expect(useGeometryStatus.getState().failures.has(segment.id)).toBe(true) + expect(useScene.getState().nodes[segment.id]).toBe(stored) + fail = false + useScene.getState().markDirty(segment.id) + await renderer.advanceFrames(1, 1 / 60) + expect(mesh.geometry).not.toBe(validGeometry) + expect(useGeometryStatus.getState().failures.has(segment.id)).toBe(false) + } finally { + await renderer.unmount() + restoreRegistry() + useScene.setState(previous) + } +}) diff --git a/packages/nodes/src/roof/geometry-notice.tsx b/packages/nodes/src/roof/geometry-notice.tsx new file mode 100644 index 0000000000..a5dd9e66fd --- /dev/null +++ b/packages/nodes/src/roof/geometry-notice.tsx @@ -0,0 +1,36 @@ +import { type AnyNodeId, usePascalI18n, useScene } from '@pascal-app/core' +import { ActionButton } from '@pascal-app/editor' +import { useGeometryStatus } from '@pascal-app/viewer' + +export function RoofGeometryNotice({ ids }: { ids: readonly AnyNodeId[] }) { + const i18n = usePascalI18n() + const failures = useGeometryStatus((state) => state.failures) + const failedId = ids.find((id) => failures.has(id)) + if (!failedId) return null + return ( +
+

+ {failures.get(failedId) === 'invalid-geometry' + ? i18n._({ + id: 'node.roof.geometryNotice.roofGeometryIsInvalidThePrevious', + message: + 'Roof geometry is invalid. The previous shape is still shown. Adjust the dimensions or intersections and retry.', + }) + : i18n._({ + id: 'node.roof.geometryNotice.roofGeometryCouldNotBeRebuilt', + message: + 'Roof geometry could not be rebuilt. The previous shape is still shown. Adjust the dimensions or intersections and retry.', + })} +

+ { + for (const id of ids) if (failures.has(id)) useScene.getState().markDirty(id) + }} + /> +
+ ) +} diff --git a/packages/nodes/src/roof/panel.tsx b/packages/nodes/src/roof/panel.tsx index c429035d6f..d4cbb4fe5e 100644 --- a/packages/nodes/src/roof/panel.tsx +++ b/packages/nodes/src/roof/panel.tsx @@ -44,6 +44,7 @@ import { useViewer } from '@pascal-app/viewer' import { Copy, Move, Plus, Trash2 } from 'lucide-react' import { useCallback, useState } from 'react' import { useShallow } from 'zustand/react/shallow' +import { RoofGeometryNotice } from '../roof/geometry-notice' import { RoofGlazingPanel } from '../roof/glazing-panel' import { commitSeatedRoofEdit } from './roof-level-target' @@ -323,6 +324,7 @@ export default function RoofPanel() { title={node.name || i18n._({ id: 'node.roof.panel.roof', message: 'Roof' })} width={300} > + segment.id)]} /> {levelMove && ( diff --git a/packages/nodes/src/roof/tool.test.ts b/packages/nodes/src/roof/tool.test.ts index 71a57af696..e105d4af9c 100644 --- a/packages/nodes/src/roof/tool.test.ts +++ b/packages/nodes/src/roof/tool.test.ts @@ -134,6 +134,108 @@ test('a porch drawn against the house over posts stays on its storey', () => { expect(updated).toEqual([]) }) +test('drawing ghosts follow every selected roof form instead of a gable fallback', async () => { + const { RoofSegmentNode, getActiveRoofHeight, RoofType } = await import('@pascal-app/core') + const { buildRoofGhostGeometry } = await import('./tool') + const { DoubleSide, Mesh, MeshBasicMaterial, Raycaster, Vector3 } = await import('three') + const material = new MeshBasicMaterial({ side: DoubleSide }) + try { + for (const type of RoofType.options) { + const node = RoofSegmentNode.parse({ + roofType: type, + width: 8, + depth: 6, + wallHeight: 0.5, + pitch: 40, + }) + const geometry = buildRoofGhostGeometry(8, 6, 0.5, 40, type) + try { + geometry.computeBoundingBox() + expect(geometry.boundingBox!.max.y).toBeCloseTo(0.5 + getActiveRoofHeight(node), 5) + const mesh = new Mesh(geometry, material) + mesh.updateMatrixWorld(true) + const heightAt = (x: number, z: number) => { + const ray = new Raycaster(new Vector3(x, 20, z), new Vector3(0, -1, 0)) + return ray.intersectObject(mesh)[0]?.point.y + } + const crown = heightAt(0, 0)! + expect(Number.isFinite(crown)).toBe(true) + if (type === 'flat') expect(heightAt(2, 1)).toBeCloseTo(0.5, 5) + if (type === 'hip') expect(heightAt(3.9, 0)!).toBeLessThan(crown / 2) + if (type === 'shed') expect(heightAt(0, -2.5)!).toBeGreaterThan(heightAt(0, 2.5)!) + if (type === 'barrel') expect(heightAt(0, 1.5)!).toBeGreaterThan(0.5) + if (type === 'conical') expect(heightAt(3.5, 0)!).toBeLessThan(crown / 2) + } finally { + geometry.dispose() + } + } + } finally { + material.dispose() + } +}) + +test('remounting the roof tool retains the menu-selected shape', async () => { + const { createElement, StrictMode } = await import('react') + const { create } = await import('@react-three/test-renderer') + const { RegistryToolProvider } = await import('@pascal-app/editor') + const { RoofTool } = await import('./tool') + const previousWindow = Object.getOwnPropertyDescriptor(globalThis, 'window') + const animationGlobals = [ + 'requestAnimationFrame', + 'cancelAnimationFrame', + 'IS_REACT_ACT_ENVIRONMENT', + ] as const + const previousGlobals = animationGlobals.map( + (key) => [key, Object.getOwnPropertyDescriptor(globalThis, key)] as const, + ) + Object.defineProperties(globalThis, { + requestAnimationFrame: { configurable: true, value: () => 0 }, + cancelAnimationFrame: { configurable: true, value: () => {} }, + IS_REACT_ACT_ENVIRONMENT: { configurable: true, value: true }, + }) + const previousScope = (await import('@pascal-app/editor')).useInteractionScope.getState().scope + Object.defineProperty(globalThis, 'window', { + configurable: true, + value: Object.assign(new EventTarget(), { + requestAnimationFrame: () => 0, + cancelAnimationFrame: () => {}, + }), + }) + const nodes = {} + let renderer: Awaited> | undefined + try { + useEditor.getState().setToolDefaults('roof', { roofType: 'hip' }) + renderer = await create( + createElement( + StrictMode, + {}, + createElement(RegistryToolProvider, { + value: { + activeLevelId: null, + sceneApi: { nodes: () => nodes } as SceneApi, + isCameraDragging: () => false, + selectNode: () => {}, + unit: 'metric', + }, + children: createElement(RoofTool), + }), + ), + ) + await renderer.unmount() + renderer = undefined + expect(useEditor.getState().toolDefaults.roof?.roofType).toBe('hip') + } finally { + await renderer?.unmount() + ;(await import('@pascal-app/editor')).useInteractionScope.setState({ scope: previousScope }) + for (const [key, descriptor] of previousGlobals) { + if (descriptor) Object.defineProperty(globalThis, key, descriptor) + else Reflect.deleteProperty(globalThis, key) + } + if (previousWindow) Object.defineProperty(globalThis, 'window', previousWindow) + else Reflect.deleteProperty(globalThis, 'window') + } +}) + // Standard trusses bear on the top plate: a raised heel is an explicit Wall Height, never a default. test('a drawn roof bears on the top plate, and a raised heel stays a setting', () => { const { level, created, sceneApi } = setup() diff --git a/packages/nodes/src/roof/tool.tsx b/packages/nodes/src/roof/tool.tsx index 723aa24618..1edf9f4cdf 100644 --- a/packages/nodes/src/roof/tool.tsx +++ b/packages/nodes/src/roof/tool.tsx @@ -6,6 +6,9 @@ import { emitter, type GridEvent, getActiveRoofHeight, + getRoofModuleFaces, + getRoofShapeRatios, + getSegmentSlopeFrame, getWallArcData, getWallBaseElevationForNodes, getWallEffectiveHeightForNodes, @@ -579,182 +582,70 @@ type PreviewState = { levelY: number } -function buildRoofGhostGeometry( +export function buildRoofGhostGeometry( width: number, depth: number, wallHeight: number, pitchDeg: number, roofType: RoofType, + defaults: Record = {}, ) { - const safeWidth = Math.max(width, 0.1) - const safeDepth = Math.max(depth, 0.1) - const halfWidth = safeWidth / 2 - const halfDepth = safeDepth / 2 - const ridgeHeight = wallHeight + Math.tan((pitchDeg * Math.PI) / 180) * halfDepth - - if (roofType === 'conical') { - const roofHeight = Math.max(0.001, Math.tan((pitchDeg * Math.PI) / 180) * halfWidth) - const geometry = new THREE.ConeGeometry(halfWidth, roofHeight, 48) - geometry.translate(0, wallHeight + roofHeight / 2, 0) - return geometry - } - - const vertices = [ - // Front slope - -halfWidth, - wallHeight, - -halfDepth, - halfWidth, - wallHeight, - -halfDepth, - halfWidth, - ridgeHeight, - 0, - - -halfWidth, - wallHeight, - -halfDepth, - halfWidth, - ridgeHeight, - 0, - -halfWidth, - ridgeHeight, - 0, - - // Back slope - -halfWidth, - ridgeHeight, - 0, - halfWidth, - ridgeHeight, - 0, - halfWidth, - wallHeight, - halfDepth, - - -halfWidth, - ridgeHeight, - 0, - halfWidth, - wallHeight, - halfDepth, - -halfWidth, - wallHeight, - halfDepth, - - // Left gable - -halfWidth, - wallHeight, - -halfDepth, - -halfWidth, - ridgeHeight, - 0, - -halfWidth, - wallHeight, - halfDepth, - - // Right gable - halfWidth, - wallHeight, - -halfDepth, - halfWidth, + const node = RoofSegmentNode.parse({ + ...defaults, + width: Math.max(width, 0.1), + depth: Math.max(depth, 0.1), wallHeight, - halfDepth, - halfWidth, - ridgeHeight, - 0, - ] - - const geometry = new BufferGeometry() - geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3)) - geometry.computeVertexNormals() - return geometry -} - -function buildRoofGhostEdges( - width: number, - depth: number, - wallHeight: number, - pitchDeg: number, - roofType: RoofType, -) { - const safeWidth = Math.max(width, 0.1) - const safeDepth = Math.max(depth, 0.1) - const halfWidth = safeWidth / 2 - const halfDepth = safeDepth / 2 - const ridgeHeight = wallHeight + Math.tan((pitchDeg * Math.PI) / 180) * halfDepth - - if (roofType === 'conical') { - const roofHeight = Math.max(0.001, Math.tan((pitchDeg * Math.PI) / 180) * halfWidth) - const cone = new THREE.ConeGeometry(halfWidth, roofHeight, 48) - cone.translate(0, wallHeight + roofHeight / 2, 0) - const edges = new THREE.EdgesGeometry(cone, 10) - cone.dispose() - return edges + pitch: pitchDeg, + roofType, + }) + const { activeRh, tanTheta } = getSegmentSlopeFrame(node) + const faces = getRoofModuleFaces({ + type: node.roofType, + w: node.width, + d: node.depth, + wh: node.wallHeight, + rh: activeRh, + baseY: 0, + baseW: node.width, + baseD: node.depth, + tanTheta, + insets: {}, + shapeRatios: getRoofShapeRatios(node), + dutchTopRakeThickness: node.dutchTopRakeThickness, + conicalStartAngle: node.conicalFullCircle ? 0 : node.conicalStartAngle, + conicalSweepAngle: node.conicalFullCircle ? Math.PI * 2 : node.conicalSweepAngle, + }) + const positions: number[] = [] + for (const face of faces) { + if (face.length < 3) continue + const origin = new THREE.Vector3(face[0]!.x, face[0]!.y, face[0]!.z) + const normal = new THREE.Vector3() + for (let i = 1; i + 1 < face.length && normal.lengthSq() < 1e-12; i++) { + normal.crossVectors( + new THREE.Vector3(face[i]!.x, face[i]!.y, face[i]!.z).sub(origin), + new THREE.Vector3(face[i + 1]!.x, face[i + 1]!.y, face[i + 1]!.z).sub(origin), + ) + } + if (normal.lengthSq() < 1e-12) continue + const axis = + Math.abs(normal.y) >= Math.max(Math.abs(normal.x), Math.abs(normal.z)) + ? 'y' + : Math.abs(normal.x) > Math.abs(normal.z) + ? 'x' + : 'z' + const contour = face.map( + (v) => new THREE.Vector2(axis === 'x' ? v.y : v.x, axis === 'z' ? v.y : v.z), + ) + for (const triangle of THREE.ShapeUtils.triangulateShape(contour, [])) { + for (const index of triangle) { + const vertex = face[index]! + positions.push(vertex.x, vertex.y, vertex.z) + } + } } - - const vertices = [ - // Base rectangle - -halfWidth, - wallHeight, - -halfDepth, - halfWidth, - wallHeight, - -halfDepth, - halfWidth, - wallHeight, - -halfDepth, - halfWidth, - wallHeight, - halfDepth, - halfWidth, - wallHeight, - halfDepth, - -halfWidth, - wallHeight, - halfDepth, - -halfWidth, - wallHeight, - halfDepth, - -halfWidth, - wallHeight, - -halfDepth, - - // Ridge + gable edges - -halfWidth, - ridgeHeight, - 0, - halfWidth, - ridgeHeight, - 0, - -halfWidth, - wallHeight, - -halfDepth, - -halfWidth, - ridgeHeight, - 0, - -halfWidth, - ridgeHeight, - 0, - -halfWidth, - wallHeight, - halfDepth, - halfWidth, - wallHeight, - -halfDepth, - halfWidth, - ridgeHeight, - 0, - halfWidth, - ridgeHeight, - 0, - halfWidth, - wallHeight, - halfDepth, - ] - const geometry = new BufferGeometry() - geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3)) + geometry.setAttribute('position', new Float32BufferAttribute(positions, 3)) + geometry.computeVertexNormals() return geometry } @@ -812,9 +703,6 @@ export const RoofTool: React.FC = () => { } }, [currentLevelId]) - // Clear preset-seeded defaults on deactivation so a later manual roof draw - // isn't built with a stale preset's parameters. Unmount-only. - useEffect(() => () => useEditor.getState().setToolDefaults('roof', null), []) // Each arming starts with the ridge along the long side. Unmount-only. useEffect(() => () => useRoofRidgeMode.getState().reset(), []) @@ -1331,6 +1219,7 @@ export const RoofTool: React.FC = () => { ghostWallHeight, previewPitch, roofType, + roofDefaults, ) }, [ footprintSource, @@ -1340,38 +1229,13 @@ export const RoofTool: React.FC = () => { ridgeMode, resolvedPreviewDimensions, roofType, + roofDefaults, ]) - const roofGhostEdges = useMemo(() => { - if ( - invalidStandardWallHover || - !resolvedPreviewDimensions || - (roofType === 'conical' && footprintSource !== 'draw') - ) - return null - const placement = resolveRoofDraftPlacement( - resolvedPreviewDimensions.length, - resolvedPreviewDimensions.width, - ridgeMode, - 0, - roofType, - ) - return buildRoofGhostEdges( - placement.width, - placement.depth, - ghostWallHeight, - previewPitch, - roofType, - ) - }, [ - footprintSource, - ghostWallHeight, - invalidStandardWallHover, - previewPitch, - ridgeMode, - resolvedPreviewDimensions, - roofType, - ]) + const roofGhostEdges = useMemo( + () => (roofGhostGeometry ? new THREE.EdgesGeometry(roofGhostGeometry, 10) : null), + [roofGhostGeometry], + ) useEffect(() => { if (invalidStandardWallHover) outlineRef.current.visible = false diff --git a/packages/nodes/src/roof/type-thumbnail-assets.ts b/packages/nodes/src/roof/type-thumbnail-assets.ts new file mode 100644 index 0000000000..b5ec0e4a2b --- /dev/null +++ b/packages/nodes/src/roof/type-thumbnail-assets.ts @@ -0,0 +1,20 @@ +import type { RoofType } from '@pascal-app/core' + +// WebP payloads are bundled so node inspectors work in every consuming host. +export const roofTypeThumbnails: Record = { + barrel: + 'data:image/webp;base64,UklGRlgWAABXRUJQVlA4WAoAAAAQAAAA/wAA/wAAQUxQSE8LAAARsMAAkCI3UrdmdA4eMzk5ZmZmZmZmZvL5npmZ/5iZmcmf538/+o/DOjmyN7BdqlZJO9A1XTWzz44IiJKshm2eUUMV8VAkRUKy8wOm619j/mPMf4z5j/8OgU1tB+lah/ff/dbfZgyPthaMzHn3V4996dg1ba5S3S4nscak65152+ACKlze55mo9Vb/JklWs25Xfs2+aW0iInAAgLkLwLk2eCIYOGdSF1Oy5hx/0IOj5H3O1pdeWS0QnPc0dN6EjtKdeIxZue8vnrwD9OwLATz9+cS0+yi579I635hLHhz6ilemTDvcGmu7jdVqP2qVlK+uED29Y/Y97SZW46+ZS9gGn12RFLhv/WwC7hq5B/2BfL58PAWp9YP1uoNiU7Pq3VU1RN4M7Kn1uWUypflzj5lOEIGHpyBNv3S8sbbhc1e6g3wkjVvgD0cmJkma3NseH0TMRWQuwi/vGn03Yo1tjGRtH3gXf7SFlyD/4CaRfdjm4DCT7wtwStEC0oJvrlhdaaLJKTVr/ZocSiRkLcJz+pY0NomcY+ufdpxBWTGhP4jhCfjd01JjbaO6PHCkk2SQN+covzg0i8WbM50IPrC3lvcEQPT4lhV82Pw83yDr7QUI0innLqy0fz6VqVhj8rCNoV9KneQVJI4y3L9UtUOJhpDUXJFP4nkscZ6mn5c2XSSamgvySVoqHcvs22wTcIctax3FFwD5RzZWsCG11qpN+7Z9lpQrC348pZJi6x1sbzXsC+9qymJFonOvnmxsIgirlt30vpcLttULgqehLBJtmgnYmkmvUxtRUUtXVaYdaJtmAk7MzYFgW78Pemw9wVuV1qpMV+hMiFWU1pezs8nm0PcBxCgRpRCY9XVI0y+bLGVkFRZab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A9ncN5nW8XxaY77AcnHZ4ut9y3i+IhMHVSlse0mRfsPnJO4pgr0NLXRHhhryUv4XNWXMvemH4rjbY4dLwBEyQJhd4vLisX8IX516b13Azj+XTqWx0ZE+mT1CZxDdBbcJc/6YsdHswfHLsbhysFCCn7lYgzL24/j0Izl+oKfb9Hft+nheaWlbJxZGQ5/W+mA/KasQbnsi6dZ4KnxO4TTRM9DC4H5Grt1dfy0862rEthQMYfNCadHGwWnawCQ5TueuL73pwfkHLmhtxGAIYwLOBbdTNXJzJ3Xcrv+tX7MZsZL8h/jcRV6SeVoEGkIculcuVjuPnRpogEkbXNmko+ZA0S6pWzqLeUByz9OPB3pwGgSoWrVhUNj94GjtndmOtCWIgpOwOmTMWXMY5rjHckxEQ3HTbO33049gSBdQd4hzsvMF4wQMLjBhwQw81JOuyzOoiWborglvaKnasFcd/XWp8gLFemxkUmAMJjzNu1/EmpzRCayJ4XMiv9V5KQAAWcZk+/6X4Eh/C7rNMKMnjyM26RclN2MKP2U+NmG5Vm6M8DPsL2tv8AWwYjzFJ0OW+W719bVx7N4sYsk21FdL5JWbm45pxYHm7ct4LUGC/4cRC4nfA5jW1ko9Sd9XyXhrUWKQ7miE5B4o/yAcL8p4bn4t/4TRkyNogAAAAAAAAA', +} diff --git a/packages/nodes/src/roof/type-thumbnail.test.tsx b/packages/nodes/src/roof/type-thumbnail.test.tsx new file mode 100644 index 0000000000..4c27f6b5cc --- /dev/null +++ b/packages/nodes/src/roof/type-thumbnail.test.tsx @@ -0,0 +1,27 @@ +import { expect, test } from 'bun:test' +import type { RoofType } from '@pascal-app/core' +import { RoofTypeThumbnail } from '@pascal-app/nodes' +import { createElement } from 'react' +import { renderToStaticMarkup } from 'react-dom/server' + +test('roof thumbnails render portable WebP images without host assets', () => { + const types: RoofType[] = [ + 'hip', + 'gable', + 'shed', + 'flat', + 'gambrel', + 'dutch', + 'mansard', + 'conical', + 'barrel', + ] + for (const type of types) { + const html = renderToStaticMarkup(createElement(RoofTypeThumbnail, { type })) + const payload = html.match(/src="data:image\/webp;base64,([^"]+)"/)?.[1] + expect(payload).toBeDefined() + const bytes = Buffer.from(payload!, 'base64') + expect(bytes.subarray(0, 4).toString()).toBe('RIFF') + expect(bytes.subarray(8, 12).toString()).toBe('WEBP') + } +}) diff --git a/packages/nodes/src/roof/type-thumbnail.tsx b/packages/nodes/src/roof/type-thumbnail.tsx new file mode 100644 index 0000000000..a7f91ac8c5 --- /dev/null +++ b/packages/nodes/src/roof/type-thumbnail.tsx @@ -0,0 +1,15 @@ +import type { RoofType } from '@pascal-app/core' +import { roofTypeThumbnails } from './type-thumbnail-assets' + +export function RoofTypeThumbnail({ type }: { type: RoofType }) { + return ( + + ) +} diff --git a/packages/nodes/src/shared/hosted-resize.ts b/packages/nodes/src/shared/hosted-resize.ts index 30bb5964ce..f37e430a37 100644 --- a/packages/nodes/src/shared/hosted-resize.ts +++ b/packages/nodes/src/shared/hosted-resize.ts @@ -23,6 +23,8 @@ export type HostedEditPolicy = { host: (node: AnyNode) => boolean child: (node: AnyNode) => boolean provider?: SurfaceProvider + /** Surfaces depend only on the edited host, not other scene nodes. */ + localSurfaces?: boolean } type Nodes = Record @@ -39,9 +41,10 @@ export function hostedChildUpdates( before: Nodes, after: Nodes, policy: HostedEditPolicy, + hostIds?: Iterable, ): HostedUpdate[] | null { const updates: HostedUpdate[] = [] - for (const host of Object.values(before)) { + for (const host of hostIds ? Array.from(hostIds, (id) => before[id]!) : Object.values(before)) { if (!policy.host(host)) continue const children = ((host as AnyNode & { children?: string[] }).children ?? []) .map((id) => before[id as AnyNodeId]) @@ -133,7 +136,7 @@ export function planHostedEdit( policy: HostedEditPolicy, ): HostedUpdate[] | null { const before = sceneApi.nodes() - const after = { ...before } + const after: Nodes = policy.localSurfaces ? Object.create(before) : { ...before } const updates = new Map>() let supported = true const staged: SceneApi = { @@ -157,7 +160,12 @@ export function planHostedEdit( } apply(staged) if (!supported) return null - const children = hostedChildUpdates(before, after, policy) + const children = hostedChildUpdates( + before, + after, + policy, + policy.localSurfaces ? updates.keys() : undefined, + ) if (!children) return null for (const [id, data] of children) updates.set(id, data) return [...updates] as HostedUpdate[] @@ -188,8 +196,11 @@ export function withHostedChildren( }, policy, ) - const hasHostedChildren = (scene: SceneApi) => - Object.values(scene?.nodes() ?? {}).some( + const hasHostedChildren = (scene: SceneApi, edited: N) => + (policy.localSurfaces + ? [scene.get(edited.id) ?? edited] + : Object.values(scene?.nodes() ?? {}) + ).some( (node) => policy.host(node) && ((node as AnyNode & { children?: string[] }).children ?? []).some((id) => { @@ -201,20 +212,20 @@ export function withHostedChildren( ...descriptor, apply(node: N, value: number, sceneApi: SceneApi, modifiers?: HandleDragModifiers) { const patch = descriptor.apply(node, value, sceneApi, modifiers) - if (!hasHostedChildren(sceneApi) || plan(node, patch, sceneApi, modifiers)) return patch + if (!hasHostedChildren(sceneApi, node) || plan(node, patch, sceneApi, modifiers)) return patch const target = sceneApi.get(descriptor.overrideTarget?.(node, sceneApi) ?? node.id) ?? node return Object.fromEntries( Object.keys(patch).map((key) => [key, (target as Record)[key]]), ) as Partial }, previewOverrides(node, value, sceneApi, modifiers) { - if (!hasHostedChildren(sceneApi)) + if (!hasHostedChildren(sceneApi, node)) return descriptor.previewOverrides?.(node, value, sceneApi, modifiers) ?? [] const patch = descriptor.apply(node, value, sceneApi, modifiers) return plan(node, patch, sceneApi, modifiers) ?? [] }, commit(node, patch, sceneApi, modifiers) { - if (!hasHostedChildren(sceneApi)) { + if (!hasHostedChildren(sceneApi, node)) { if (descriptor.commit) descriptor.commit(node, patch, sceneApi, modifiers) else sceneApi.update(descriptor.overrideTarget?.(node, sceneApi) ?? node.id, patch) return diff --git a/packages/nodes/src/shared/live-preview.ts b/packages/nodes/src/shared/live-preview.ts new file mode 100644 index 0000000000..fe0dc07cc1 --- /dev/null +++ b/packages/nodes/src/shared/live-preview.ts @@ -0,0 +1,35 @@ +import { type AnyNode, type AnyNodeId, useLiveNodeOverrides, useScene } from '@pascal-app/core' + +type NodeUpdate = { id: AnyNodeId; data: Partial } + +/** + * A handle drag's transient preview through `useLiveNodeOverrides`: each frame + * replaces the previous one, so a node the current frame no longer moves (a + * detached or zero-delta follower) shows its committed state again. + */ +export function createLivePreview() { + const previewed = new Set() + const drop = (id: AnyNodeId) => { + useLiveNodeOverrides.getState().clear(id) + if (useScene.getState().nodes[id]) useScene.getState().markDirty(id) + previewed.delete(id) + } + return { + publish(updates: NodeUpdate[]) { + const scene = useScene.getState() + const entries = updates + .filter((update) => scene.nodes[update.id]) + .map((update) => [update.id, update.data as Record] as const) + const next = new Set(entries.map(([id]) => id)) + for (const id of [...previewed]) if (!next.has(id)) drop(id) + useLiveNodeOverrides.getState().setMany(entries) + for (const [id] of entries) { + previewed.add(id) + scene.markDirty(id) + } + }, + clear() { + for (const id of [...previewed]) drop(id) + }, + } +} diff --git a/packages/nodes/src/shared/opening-plane-offset-move.test.tsx b/packages/nodes/src/shared/opening-plane-offset-move.test.tsx index b522ec2771..229cdef759 100644 --- a/packages/nodes/src/shared/opening-plane-offset-move.test.tsx +++ b/packages/nodes/src/shared/opening-plane-offset-move.test.tsx @@ -3,9 +3,14 @@ import { type AnyNode, type AnyNodeId, BuildingNode, + clearSceneHistory, DoorNode, emitter, + getRoofSegmentWallFaces, LevelNode, + RoofNode, + RoofSegmentNode, + roofFacePointToSegment, sceneRegistry, spatialGridManager, useLiveNodeOverrides, @@ -237,3 +242,65 @@ describe('opening move keeps the wall-local plane offset on its own wall', () => }) } }) + +for (const finish of ['commit', 'cancel'] as const) { + test(`door roof slide previews without scene writes and ${finish}s cleanly`, async () => { + const node = seedScene('door') as DoorNode + const roof = RoofNode.parse({ parentId: LEVEL_ID }) + const segment = RoofSegmentNode.parse({ + parentId: roof.id, + width: 12, + depth: 10, + wallHeight: 4, + }) + const face = getRoofSegmentWallFaces(segment)[0]! + const segmentObject = new Group() + sceneRegistry.nodes.set(segment.id, segmentObject) + useScene.setState(({ nodes }) => ({ + nodes: { + ...nodes, + [roof.id]: { ...roof, children: [segment.id] }, + [segment.id]: segment, + }, + })) + clearSceneHistory() + const renderer = await create() + const event = (u: number) => ({ + node: useScene.getState().nodes[roof.id], + position: roofFacePointToSegment(segment, face.id, [u, node.height / 2, 0]), + normal: face.normal, + object: segmentObject, + nativeEvent: { timeStamp: u }, + stopPropagation() {}, + }) + try { + await act(async () => emitter.emit('roof:enter', event(2) as never)) + expect(useScene.getState().nodes[node.id]?.parentId).toBe(segment.id) + const baseline = useScene.getState().nodes + await act(async () => { + emitter.emit('roof:move', event(3) as never) + emitter.emit('roof:move', event(4) as never) + }) + expect(useScene.getState().nodes).toBe(baseline) + expect(useLiveNodeOverrides.getState().get(node.id)?.position).toEqual([ + 4, + node.height / 2, + 0, + ]) + expect(useScene.temporal.getState().pastStates).toHaveLength(0) + await act(async () => { + if (finish === 'commit') emitter.emit('roof:click', event(4) as never) + else emitter.emit('tool:cancel') + }) + expect(useLiveNodeOverrides.getState().get(node.id)).toBeUndefined() + if (finish === 'commit') { + expect((current(node.id) as DoorNode).position).toEqual([4, node.height / 2, 0]) + expect(useScene.temporal.getState().pastStates).toHaveLength(1) + useScene.temporal.getState().undo() + } else expect(useScene.temporal.getState().pastStates).toHaveLength(0) + expect(current(node.id)).toEqual(node) + } finally { + await renderer.unmount() + } + }) +} diff --git a/packages/nodes/src/shared/refrigerant-line-selection.tsx b/packages/nodes/src/shared/refrigerant-line-selection.tsx index cf59c658c3..39f058710b 100644 --- a/packages/nodes/src/shared/refrigerant-line-selection.tsx +++ b/packages/nodes/src/shared/refrigerant-line-selection.tsx @@ -5,6 +5,7 @@ import { type AnyNodeId, analyzePortConnectivity, type Cursor, + findLevelAncestorId, type LinesetNode, type LiquidLineNode, type PortConnectivity, @@ -12,6 +13,7 @@ import { resolveConnectivityUpdates, resumeSceneHistory, sceneRegistry, + useLiveNodeOverrides, useScene, } from '@pascal-app/core' import { @@ -28,8 +30,8 @@ import { Html } from '@react-three/drei' import { createPortal, type ThreeEvent, useFrame, useThree } from '@react-three/fiber' import { useEffect, useMemo, useRef, useState } from 'react' import { type Group, type Object3D, Plane, Raycaster, Vector2, Vector3 } from 'three' -import { createFollowerFrames } from './follower-frames' import { useHandleDragScope } from './handle-drag-scope' +import { createLivePreview } from './live-preview' import { REFRIGERANT_PORT_SYSTEMS } from './port-systems' import { HandleCube, MoveChevron } from './selection-handles' @@ -121,6 +123,8 @@ function RefrigerantLineEndpointHandles({ target: Object3D }) { const { camera, gl } = useThree() + const override = useLiveNodeOverrides((state) => state.overrides.get(line.id)) + const displayLine = override ? ({ ...line, ...override } as RefrigerantLineNode) : line const outerRef = useRef(null) useFrame(() => { const outer = outerRef.current @@ -247,9 +251,8 @@ function RefrigerantLineEndpointHandles({ e.stopPropagation() const initialPath = line.path.map((p) => [...p] as Point) const startPoint = initialPath[index]! - const startNodes = useScene.getState().nodes - const connectivity = analyzePortConnectivity(line as AnyNode, startNodes) - const frame = createFollowerFrames(startNodes, line.id as AnyNodeId) + const connectivity = analyzePortConnectivity(line as AnyNode, useScene.getState().nodes) + const livePreview = createLivePreview() pauseSceneHistory(useScene) useViewer.getState().setInputDragging(true) document.body.style.cursor = kind.axis === 'y' ? 'ns-resize' : 'grabbing' @@ -303,7 +306,13 @@ function RefrigerantLineEndpointHandles({ if (isEndpoint) { const port = findNearestPortXZ( [next[0], next[1], next[2]], - collectScenePorts({ excludeNodeId: line.id, systems: REFRIGERANT_PORT_SYSTEMS }), + collectScenePorts({ + excludeNodeId: line.id, + levelId: (findLevelAncestorId(line.id, useScene.getState().nodes) ?? undefined) as + | AnyNodeId + | undefined, + systems: REFRIGERANT_PORT_SYSTEMS, + }), PORT_SNAP_RADIUS_M, ) if (port) next = [port.position[0], port.position[1], port.position[2]] @@ -317,11 +326,10 @@ function RefrigerantLineEndpointHandles({ drag.current = next drag.detached = detached if (step > 0) triggerSFX('sfx:grid-snap') - useScene - .getState() - .updateNodes( - frame([{ id: line.id as AnyNodeId, data: { path } as Partial }, ...follow]), - ) + livePreview.publish([ + { id: line.id as AnyNodeId, data: { path } as Partial }, + ...follow, + ]) } const finish = (commit: boolean) => { @@ -334,17 +342,7 @@ function RefrigerantLineEndpointHandles({ const finalPath = drag.initialPath.map((p, i) => i === drag.index ? drag.current : p, ) as Point[] - const revert = (drag.connectivity?.connections ?? []).map((conn) => - conn.kind === 'rigid-node' - ? { id: conn.nodeId, data: { position: conn.startPosition } as Partial } - : { id: conn.nodeId, data: { path: conn.startPath } as Partial }, - ) - useScene - .getState() - .updateNodes([ - { id: line.id as AnyNodeId, data: { path: drag.initialPath } as Partial }, - ...revert.filter((u) => useScene.getState().nodes[u.id]), - ]) + livePreview.clear() resumeSceneHistory(useScene) if (!commit) return const moved = finalPath[drag.index]!.some( @@ -427,9 +425,9 @@ function RefrigerantLineEndpointHandles({ ) })} {draggingIndex !== null && - line.path[draggingIndex] && + displayLine.path[draggingIndex] && (() => { - const point = line.path[draggingIndex]! + const point = displayLine.path[draggingIndex]! const origin = dragRef.current?.initialPath[draggingIndex] ?? point const deltas = [point[0] - origin[0], point[1] - origin[1], point[2] - origin[2]] const axes = ['x', 'y', 'z'] as const diff --git a/packages/nodes/src/shared/relative-roof-drag.ts b/packages/nodes/src/shared/relative-roof-drag.ts index 8dcb775be1..a9b0bc33bf 100644 --- a/packages/nodes/src/shared/relative-roof-drag.ts +++ b/packages/nodes/src/shared/relative-roof-drag.ts @@ -5,6 +5,7 @@ import { type RoofSegmentNode, sceneRegistry, } from '@pascal-app/core' +import { isGridSnapActive, useEditor } from '@pascal-app/editor' import { useViewer } from '@pascal-app/viewer' import * as THREE from 'three' import { type RoofSegmentHit, resolveRoofSegmentHit } from './roof-segment-hit' @@ -18,8 +19,6 @@ export type RelativeRoofDragTarget = { hit: RoofSegmentHit } -const ROOF_DRAG_SNAP_STEP_M = 0.05 - type RelativeRoofDragState = { segmentId: string anchor: [number, number] @@ -121,9 +120,10 @@ export function snapRelativeRoofDragTarget( target: RelativeRoofDragTarget, bypass = false, ): RelativeRoofDragTarget { - if (bypass) return target - const localX = Math.round(target.localX / ROOF_DRAG_SNAP_STEP_M) * ROOF_DRAG_SNAP_STEP_M - const localZ = Math.round(target.localZ / ROOF_DRAG_SNAP_STEP_M) * ROOF_DRAG_SNAP_STEP_M + const step = isGridSnapActive() ? useEditor.getState().gridSnapStep : 0 + if (bypass || step <= 0) return target + const localX = Math.round(target.localX / step) * step + const localZ = Math.round(target.localZ / step) * step const surfaceOffsetY = target.localY - getSurfaceY(target.localX, target.localZ, target.segment) const localY = getSurfaceY(localX, localZ, target.segment) + surfaceOffsetY return { diff --git a/packages/nodes/src/shared/roof-accessory-move.test.tsx b/packages/nodes/src/shared/roof-accessory-move.test.tsx new file mode 100644 index 0000000000..e5d29cdc01 --- /dev/null +++ b/packages/nodes/src/shared/roof-accessory-move.test.tsx @@ -0,0 +1,97 @@ +import { expect, test } from 'bun:test' +import { + type AnyNode, + clearSceneHistory, + emitter, + getRoofSegmentSurfaceY, + LevelNode, + RoofNode, + RoofSegmentNode, + sceneRegistry, + useScene, +} from '@pascal-app/core' +import { getActiveSnapContext, useEditor } from '@pascal-app/editor' +import { useViewer } from '@pascal-app/viewer' +import { act } from '@react-three/test-renderer' +import type { ComponentType } from 'react' +import { Group } from 'three' +import { installMountedScene, mount } from '../__tests__/harness' +import { builtinPlugin } from '../index' + +installMountedScene() +for (const kind of [ + 'box-vent', + 'cupola', + 'eyebrow-vent', + 'gutter', + 'ridge-vent', + 'skylight', + 'solar-panel', + 'turbine-vent', +]) { + for (const mode of ['off', 'grid', 'force'] as const) { + test(`${kind} ${mode} move preserves metadata and follows snapping mode`, async () => { + const level = LevelNode.parse({}) + const roof = RoofNode.parse({ parentId: level.id }) + const segment = RoofSegmentNode.parse({ + parentId: roof.id, + roofType: 'gable', + width: 12, + depth: 10, + }) + const def = builtinPlugin.nodes!.find((entry) => entry.kind === kind)! + const metadata = { assetId: 'asset-42', provenance: { source: 'survey' }, isTransient: true } + const node = def.schema.parse({ + ...def.defaults(), + parentId: segment.id, + roofSegmentId: segment.id, + position: [0, getRoofSegmentSurfaceY(segment, 0, 1), 1], + metadata, + }) as AnyNode + const entries: AnyNode[] = [ + { ...level, children: [roof.id] }, + { ...roof, children: [segment.id] }, + { ...segment, children: [node.id] }, + node, + ] + useScene.setState({ + nodes: Object.fromEntries(entries.map((entry) => [entry.id, entry])), + rootNodeIds: [level.id], + readOnly: false, + dirtyNodes: new Set(), + }) + for (const entry of entries) sceneRegistry.nodes.set(entry.id, new Group()) + useViewer.getState().setSelection({ levelId: level.id, selectedIds: [node.id] }) + useEditor.getState().setMovingNode(node) + useEditor.getState().setSnappingMode('item', mode === 'off' ? 'off' : 'grid') + useEditor.setState({ gridSnapStep: 0.5 }) + clearSceneHistory() + const { default: Component } = await def.affordanceTools!.move!() + const Tool = Component as ComponentType<{ node: AnyNode }> + const renderer = await mount() + expect(getActiveSnapContext()).toBe('item') + const roofEvent = (x: number) => ({ + node: useScene.getState().nodes[roof.id], + position: [x, getRoofSegmentSurfaceY(segment, x, 1), 1], + nativeEvent: { timeStamp: x, shiftKey: true, altKey: mode === 'force' }, + stopPropagation() {}, + }) + await act(async () => { + emitter.emit('roof:enter', roofEvent(0) as never) + emitter.emit('roof:move', roofEvent(0.73) as never) + emitter.emit('roof:click', roofEvent(0.73) as never) + }) + expect( + (useScene.getState().nodes[node.id] as { position: number[] }).position[0], + ).toBeCloseTo(mode === 'grid' ? 0.5 : 0.73) + expect(useScene.getState().nodes[node.id]?.metadata).toEqual({ + assetId: 'asset-42', + provenance: { source: 'survey' }, + }) + expect(useScene.temporal.getState().pastStates).toHaveLength(1) + await renderer.unmount() + await act(async () => useScene.temporal.getState().undo()) + expect(useScene.getState().nodes[node.id]?.metadata).toEqual(metadata) + }) + } +} diff --git a/packages/nodes/src/shared/roof-surface.test.ts b/packages/nodes/src/shared/roof-surface.test.ts index b0dd4bf045..4301019a33 100644 --- a/packages/nodes/src/shared/roof-surface.test.ts +++ b/packages/nodes/src/shared/roof-surface.test.ts @@ -101,3 +101,11 @@ describe('getRoofSurfaceFaceBoundsAt', () => { expect(center).toBeGreaterThan(waist) }) }) + +test('changing a Dutch rake updates the accessory face extent after a cached query', () => { + const node = fixtureSegment({ roofType: 'dutch', width: 12, depth: 8, dutchGabletRake: 0 }) + const before = getRoofSurfaceFaceBoundsAt(node, 0, 3) + const after = getRoofSurfaceFaceBoundsAt({ ...node, dutchGabletRake: 0.8 }, 0, 3) + expect(after.polygon).not.toEqual(before.polygon) + expect(getRoofSurfaceFaceBoundsAt(node, 0, 3).maxX).toBe(before.maxX) +}) diff --git a/packages/nodes/src/shared/roof-surface.ts b/packages/nodes/src/shared/roof-surface.ts index e55f300711..c56b7f6408 100644 --- a/packages/nodes/src/shared/roof-surface.ts +++ b/packages/nodes/src/shared/roof-surface.ts @@ -120,6 +120,8 @@ function roofSurfaceFaceCacheKey(segment: RoofSegmentNode): string { segment.dutchHipWidthRatio ?? ROOF_SHAPE_DEFAULTS.dutchHipWidthRatio, segment.dutchHipHeightRatio ?? ROOF_SHAPE_DEFAULTS.dutchHipHeightRatio, segment.dutchWaistLengthRatio ?? ROOF_SHAPE_DEFAULTS.dutchWaistLengthRatio, + segment.dutchGabletRake ?? ROOF_SHAPE_DEFAULTS.dutchGabletRake, + segment.dutchTopRakeThickness ?? ROOF_SHAPE_DEFAULTS.dutchTopRakeThickness, ].join('|') } diff --git a/packages/nodes/src/shared/selection-handles.test.tsx b/packages/nodes/src/shared/selection-handles.test.tsx new file mode 100644 index 0000000000..8409cb95c1 --- /dev/null +++ b/packages/nodes/src/shared/selection-handles.test.tsx @@ -0,0 +1,226 @@ +import { beforeEach, expect, test } from 'bun:test' +import { + type AnyNode, + clearSceneHistory, + DuctFittingNode, + DuctSegmentNode, + getSceneHistoryPauseDepth, + LevelNode, + LinesetNode, + PipeSegmentNode, + useLiveNodeOverrides, + useScene, +} from '@pascal-app/core' +import { + cancelActiveTool, + getActiveSnapContext, + useEditor, + useInteractionScope, +} from '@pascal-app/editor' +import { useViewer } from '@pascal-app/viewer' +import { useThree } from '@react-three/fiber' +import { act } from '@react-three/test-renderer' +import { type ComponentType, useMemo } from 'react' +import { type Camera, Vector3 } from 'three' +import { + GeometrySystem, + installMountedScene, + LevelScene, + mount, + settle, +} from '../__tests__/harness' +import { builtinPlugin } from '../index' + +installMountedScene() +beforeEach(() => { + window.requestAnimationFrame = globalThis.requestAnimationFrame + window.cancelAnimationFrame = globalThis.cancelAnimationFrame +}) +let camera: Camera +function Scene({ level, Selection }: { level: LevelNode; Selection: ComponentType }) { + const three = useThree() + camera = three.camera + useMemo(() => { + camera.position.set(4, 8, 6) + camera.lookAt(0, 1, 0) + camera.updateMatrixWorld() + three.gl.domElement.getBoundingClientRect = () => + ({ left: 0, top: 0, width: 1000, height: 1000 }) as DOMRect + }, [three]) + return ( + <> + + + + + ) +} +function client(point: number[]) { + const projected = new Vector3(...point).project(camera) + return { clientX: (projected.x + 1) * 500, clientY: (1 - projected.y) * 500 } +} +async function pointer(type: string, point?: number[], extra = {}) { + await act(async () => { + window.dispatchEvent( + Object.assign(new Event(type, { cancelable: true }), { + button: 0, + shiftKey: false, + altKey: false, + ...(point ? client(point) : {}), + ...extra, + }), + ) + }) +} +const hitAreas = (renderer: Awaited>) => + renderer.scene.findAll( + (entry) => typeof entry.props.onPointerDown === 'function' && entry.props.userData, + ) +async function press(renderer: Awaited>, index: number, point: number[]) { + const target = new Vector3(...point) + if (index > 0) target.x -= index === 2 ? 0.24 : 0.4 + const handle = hitAreas(renderer).sort( + (a, b) => + a.instance.getWorldPosition(new Vector3()).distanceToSquared(target) - + b.instance.getWorldPosition(new Vector3()).distanceToSquared(target), + )[0]! + expect(handle).toBeDefined() + await renderer.fireEvent(handle, 'pointerDown', { + object: handle.instance, + point: new Vector3(...point), + nativeEvent: { + ...client(point), + button: 0, + stopPropagation() {}, + stopImmediatePropagation() {}, + }, + stopPropagation() {}, + }) +} +async function seed( + kind: 'duct-fitting' | 'lineset' | 'duct-segment' | 'pipe-segment', + otherFloor = false, +) { + const level = LevelNode.parse({ level: 0 }) + const above = LevelNode.parse({ level: 1 }) + const schema = + kind === 'duct-fitting' + ? DuctFittingNode + : kind === 'lineset' + ? LinesetNode + : kind === 'duct-segment' + ? DuctSegmentNode + : PipeSegmentNode + const node = schema.parse({ + parentId: level.id, + position: [0, 1, 0], + path: [ + [0, 1, 0], + [2, 1, 0], + ], + }) + const foreign = schema.parse({ + parentId: above.id, + path: [ + [-1, 7, 0], + [-3, 7, 0], + ], + }) + const nodes: AnyNode[] = [ + { ...level, children: [node.id] }, + node, + ...(otherFloor ? [{ ...above, children: [foreign.id] }, foreign] : []), + ] + useScene.setState({ + nodes: Object.fromEntries(nodes.map((n) => [n.id, n])), + rootNodeIds: [level.id], + dirtyNodes: new Set(), + readOnly: false, + }) + useInteractionScope.getState().end() + useEditor.setState({ mode: 'select', tool: null, gridSnapStep: 0.5 }) + useEditor.getState().setSnappingMode('item', 'off') + useEditor.getState().setSnappingMode('polygon', 'off') + useViewer.getState().setSelection({ levelId: level.id, selectedIds: [node.id] }) + clearSceneHistory() + const def = builtinPlugin.nodes!.find((entry) => entry.kind === kind)! + const { default: Selection } = await def.affordanceTools!.selection!() + const renderer = await mount() + await settle(renderer) + return { renderer, node } +} +for (const kind of ['duct-fitting', 'lineset'] as const) { + for (const ending of [ + 'pointerup', + 'pointercancel', + 'escape', + 'unmount', + 'scope-change', + ] as const) { + test(`${kind} ${ending} keeps the preview transient and releases the gesture`, async () => { + const { renderer, node } = await seed(kind) + await press(renderer, 0, [0, 1, 0]) + await press(renderer, 1, [0, 1, 0]) + const baseline = useScene.getState().nodes + await pointer('pointermove', [-1, 1, 0]) + expect(useScene.getState().nodes).toBe(baseline) + expect(useLiveNodeOverrides.getState().get(node.id)).toBeDefined() + expect(useScene.temporal.getState().pastStates).toHaveLength(0) + expect(getSceneHistoryPauseDepth()).toBeGreaterThan(0) + if (ending === 'unmount') await renderer.unmount() + else if (ending === 'escape') await act(async () => void cancelActiveTool()) + else if (ending === 'scope-change') + await act(async () => + useInteractionScope + .getState() + .begin({ kind: 'handle-drag', nodeId: 'another-node', handle: 'move' }), + ) + else await pointer(ending) + expect(useLiveNodeOverrides.getState().overrides.size).toBe(0) + expect(getSceneHistoryPauseDepth()).toBe(0) + expect(useViewer.getState().inputDragging).toBe(false) + if (ending === 'pointerup') { + expect(useScene.temporal.getState().pastStates).toHaveLength(1) + await act(async () => useScene.temporal.getState().undo()) + expect(useScene.getState().nodes[node.id]).toEqual(node) + } else { + expect(useScene.getState().nodes).toBe(baseline) + expect(useScene.temporal.getState().pastStates).toHaveLength(0) + } + await pointer('pointermove', [-2, 1, 0]) + expect(useLiveNodeOverrides.getState().overrides.size).toBe(0) + }) + } +} +for (const kind of ['lineset', 'duct-segment', 'pipe-segment'] as const) { + test(`${kind} endpoint ignores ports from another level`, async () => { + const { renderer, node } = await seed(kind, true) + await press(renderer, 0, [0, 1, 0]) + await press(renderer, kind === 'duct-segment' ? 2 : 1, [0, 1, 0]) + await pointer('pointermove', [-1, 1, 0]) + const path = useLiveNodeOverrides.getState().get(node.id)?.path as number[][] + expect(path).toBeDefined() + expect(path[0]![1]).toBeCloseTo(1) + await pointer('pointercancel') + }) +} +for (const kind of ['duct-fitting', 'lineset'] as const) { + test(`${kind} honors Off/Grid modes without a held Shift bypass`, async () => { + const { renderer, node } = await seed(kind) + await press(renderer, 0, [0, 1, 0]) + await press(renderer, 1, [0, 1, 0]) + expect(getActiveSnapContext()).toBe(kind === 'duct-fitting' ? 'item' : 'polygon') + await pointer('pointermove', [-0.73, 1, 0]) + const coordinate = () => { + const draft = useLiveNodeOverrides.getState().get(node.id)! + return kind === 'duct-fitting' + ? (draft.position as number[])[0]! + : (draft.path as number[][])[0]![0]! + } + expect(coordinate()).toBeCloseTo(-0.73) + useEditor.getState().setSnappingMode(kind === 'duct-fitting' ? 'item' : 'polygon', 'grid') + await pointer('pointermove', [-0.73, 1, 0], { shiftKey: true }) + expect(coordinate()).toBeCloseTo(-0.5) + await pointer('pointercancel') + }) +} diff --git a/packages/nodes/src/shared/structural-parametrics.test.ts b/packages/nodes/src/shared/structural-parametrics.test.ts index b9d787cd49..2f610941e7 100644 --- a/packages/nodes/src/shared/structural-parametrics.test.ts +++ b/packages/nodes/src/shared/structural-parametrics.test.ts @@ -31,7 +31,7 @@ describe('structural spatial settings', () => { expect(visibleKeys(elevator, elevatorParametrics.groups)).toContain('doorStyle') const derived = elevatorParametrics.derive?.({ ...elevator, width: 0.8 }, { width: 0.8 }) - expect(derived?.doorWidth).toBeCloseTo(0.7) + expect(derived?.doorWidth).toBeCloseTo(0.62) }) test('exposes the settings appropriate to each stair shape', () => { diff --git a/packages/nodes/src/skylight/definition.ts b/packages/nodes/src/skylight/definition.ts index a7549d3e3b..5b05d96820 100644 --- a/packages/nodes/src/skylight/definition.ts +++ b/packages/nodes/src/skylight/definition.ts @@ -218,6 +218,7 @@ const skylightHandles: HandleDescriptor[] = [ */ export const skylightDefinition: NodeDefinition = { kind: 'skylight', + snapProfile: 'item', schemaVersion: 1, schema: SkylightNode, category: 'structure', diff --git a/packages/nodes/src/skylight/move-tool.tsx b/packages/nodes/src/skylight/move-tool.tsx index ddc88ff25d..f017ddb063 100644 --- a/packages/nodes/src/skylight/move-tool.tsx +++ b/packages/nodes/src/skylight/move-tool.tsx @@ -12,7 +12,10 @@ import { } from '@pascal-app/core' import { consumePlacementDragRelease, + isGridSnapActive, + isMagneticSnapActive, markToolCancelConsumed, + stripPlacementMetadataFlags, triggerSFX, useEditor, } from '@pascal-app/editor' @@ -89,9 +92,9 @@ export default function MoveSkylightTool({ node }: { node: SkylightNode }) { const rawTarget = roofDrag.resolve(event) if (!rawTarget) return null return snapRoofSurfaceNodeTarget({ - target: snapRelativeRoofDragTarget(rawTarget, event.nativeEvent?.shiftKey === true), + target: snapRelativeRoofDragTarget(rawTarget, event.nativeEvent?.altKey === true), node, - bypass: event.nativeEvent?.shiftKey === true, + bypass: !isMagneticSnapActive() || event.nativeEvent?.altKey === true, }) } @@ -132,7 +135,11 @@ export default function MoveSkylightTool({ node }: { node: SkylightNode }) { const onRoofMove = (event: RoofEvent) => { const sx = Math.round(event.position[0] * 20) / 20 const sz = Math.round(event.position[2] * 20) / 20 - if (event.nativeEvent?.shiftKey !== true && (sx !== lastSnapX || sz !== lastSnapZ)) { + if ( + isGridSnapActive() && + event.nativeEvent?.altKey !== true && + (sx !== lastSnapX || sz !== lastSnapZ) + ) { triggerSFX('sfx:grid-snap') lastSnapX = sx lastSnapZ = sz @@ -172,7 +179,7 @@ export default function MoveSkylightTool({ node }: { node: SkylightNode }) { position: [target.localX, target.localY, target.localZ], rotation: finalRotation, visible: true, - metadata: {}, + metadata: stripPlacementMetadataFlags(original.metadata), }) if (original.roofSegmentId && original.roofSegmentId !== (targetSegmentId as string)) { diff --git a/packages/nodes/src/solar-panel/definition.ts b/packages/nodes/src/solar-panel/definition.ts index 9f8ebcd116..5294b20491 100644 --- a/packages/nodes/src/solar-panel/definition.ts +++ b/packages/nodes/src/solar-panel/definition.ts @@ -227,6 +227,7 @@ const solarPanelHandles: HandleDescriptor[] = [ */ export const solarPanelDefinition: NodeDefinition = { kind: 'solar-panel', + snapProfile: 'item', schemaVersion: 1, schema: SolarPanelNode, category: 'structure', diff --git a/packages/nodes/src/solar-panel/move-tool.tsx b/packages/nodes/src/solar-panel/move-tool.tsx index c295dd6789..1b4612732a 100644 --- a/packages/nodes/src/solar-panel/move-tool.tsx +++ b/packages/nodes/src/solar-panel/move-tool.tsx @@ -13,7 +13,10 @@ import { import { consumePlacementDragRelease, EDITOR_LAYER, + isGridSnapActive, + isMagneticSnapActive, markToolCancelConsumed, + stripPlacementMetadataFlags, triggerSFX, useEditor, } from '@pascal-app/editor' @@ -117,9 +120,9 @@ export default function MoveSolarPanelTool({ node }: { node: SolarPanelNode }) { const rawTarget = roofDrag.resolve(event) if (!rawTarget) return null return snapRoofSurfaceNodeTarget({ - target: snapRelativeRoofDragTarget(rawTarget, event.nativeEvent?.shiftKey === true), + target: snapRelativeRoofDragTarget(rawTarget, event.nativeEvent?.altKey === true), node, - bypass: event.nativeEvent?.shiftKey === true, + bypass: !isMagneticSnapActive() || event.nativeEvent?.altKey === true, }) } @@ -133,7 +136,11 @@ export default function MoveSolarPanelTool({ node }: { node: SolarPanelNode }) { const sx = Math.round(target.localX * 20) / 20 const sz = Math.round(target.localZ * 20) / 20 - if (event.nativeEvent?.shiftKey !== true && (sx !== lastSnapX || sz !== lastSnapZ)) { + if ( + isGridSnapActive() && + event.nativeEvent?.altKey !== true && + (sx !== lastSnapX || sz !== lastSnapZ) + ) { triggerSFX('sfx:grid-snap') lastSnapX = sx lastSnapZ = sz @@ -198,7 +205,7 @@ export default function MoveSolarPanelTool({ node }: { node: SolarPanelNode }) { // semantics so the renderer's surfaceQuat is in the correct frame. surfaceNormal: [segLocalNormal.x, segLocalNormal.y, segLocalNormal.z], visible: true, - metadata: {}, + metadata: stripPlacementMetadataFlags(original.metadata), }) if (original.roofSegmentId && original.roofSegmentId !== (targetSegmentId as string)) { diff --git a/packages/nodes/src/turbine-vent/definition.ts b/packages/nodes/src/turbine-vent/definition.ts index 48e995a9b4..e170e52959 100644 --- a/packages/nodes/src/turbine-vent/definition.ts +++ b/packages/nodes/src/turbine-vent/definition.ts @@ -82,6 +82,7 @@ const turbineVentHandles: HandleDescriptor[] = [ */ export const turbineVentDefinition: NodeDefinition = { kind: 'turbine-vent', + snapProfile: 'item', schemaVersion: 3, schema: TurbineVentNode, category: 'structure', diff --git a/packages/nodes/src/turbine-vent/move-tool.tsx b/packages/nodes/src/turbine-vent/move-tool.tsx index 4ae4cf9556..3828244a30 100644 --- a/packages/nodes/src/turbine-vent/move-tool.tsx +++ b/packages/nodes/src/turbine-vent/move-tool.tsx @@ -12,7 +12,10 @@ import { } from '@pascal-app/core' import { consumePlacementDragRelease, + isGridSnapActive, + isMagneticSnapActive, markToolCancelConsumed, + stripPlacementMetadataFlags, triggerSFX, useEditor, } from '@pascal-app/editor' @@ -85,9 +88,9 @@ export default function MoveTurbineVentTool({ node }: { node: TurbineVentNode }) const rawTarget = roofDrag.resolve(event) if (!rawTarget) return null return snapRoofSurfaceNodeTarget({ - target: snapRelativeRoofDragTarget(rawTarget, event.nativeEvent?.shiftKey === true), + target: snapRelativeRoofDragTarget(rawTarget, event.nativeEvent?.altKey === true), node, - bypass: event.nativeEvent?.shiftKey === true, + bypass: !isMagneticSnapActive() || event.nativeEvent?.altKey === true, }) } @@ -102,7 +105,8 @@ export default function MoveTurbineVentTool({ node }: { node: TurbineVentNode }) const sx = Math.round(target.localX * 20) / 20 const sz = Math.round(target.localZ * 20) / 20 if ( - event.nativeEvent?.shiftKey !== true && + isGridSnapActive() && + event.nativeEvent?.altKey !== true && (!lastSnap || lastSnap[0] !== sx || lastSnap[1] !== sz) ) { triggerSFX('sfx:grid-snap') @@ -160,7 +164,7 @@ export default function MoveTurbineVentTool({ node }: { node: TurbineVentNode }) position: [target.localX, target.localY, target.localZ], rotation: original.rotation, visible: true, - metadata: {}, + metadata: stripPlacementMetadataFlags(original.metadata), }) useScene.temporal.getState().pause() diff --git a/packages/nodes/src/window/move-tool.tsx b/packages/nodes/src/window/move-tool.tsx index a69164d53f..2d05c29a4c 100644 --- a/packages/nodes/src/window/move-tool.tsx +++ b/packages/nodes/src/window/move-tool.tsx @@ -859,14 +859,7 @@ const MoveWindowTool: React.FC<{ node: WindowNode }> = ({ node: movingWindowNode // Scene writes, not overrides: leaving the wall must actually remove the // window from the wall's `children` or the CSG cut trails the ghost // around the old wall (see the wall-branch note in `applyPreview`). - if (currentHostId === levelId) { - updateDraft({ - position: [localX, sillCenterY, localZ], - rotation: [0, yaw, 0], - side: sideOverride, - visible: false, - }) - } else { + if (currentHostId !== levelId) { if (currentHostId && currentHostId !== levelId) markHostDirty(currentHostId) updateDraft({ position: [localX, sillCenterY, localZ], diff --git a/packages/nodes/tsconfig.json b/packages/nodes/tsconfig.json index f657cfb7db..e4cb5d043e 100644 --- a/packages/nodes/tsconfig.json +++ b/packages/nodes/tsconfig.json @@ -11,6 +11,20 @@ "types": ["node"] }, "include": ["src"], - "exclude": ["node_modules", "dist", "**/*.test.ts", "**/*.test.tsx", "**/__tests__/**"], - "references": [{ "path": "../core" }, { "path": "../viewer" }] + "exclude": [ + "node_modules", + "dist", + "**/*.test.ts", + "**/*.test.tsx", + "**/__tests__/**", + "**/*.bench.tsx" + ], + "references": [ + { + "path": "../core" + }, + { + "path": "../viewer" + } + ] } diff --git a/packages/viewer/src/index.ts b/packages/viewer/src/index.ts index c0a8a0696d..9f20f753f9 100644 --- a/packages/viewer/src/index.ts +++ b/packages/viewer/src/index.ts @@ -417,6 +417,11 @@ export { ElevatorInteractionSystem } from './systems/elevator/elevator-interacti // elevation under its footprint. Replaces the per-kind elevation block // that used to live inside `ItemSystem`. export { FloorElevationSystem } from './systems/floor-elevation/floor-elevation-system' +export { + type GeometryFailure, + setGeometryFailure, + useGeometryStatus, +} from './systems/geometry/geometry-status' export { GuideSystem } from './systems/guide/guide-system' export { InteractiveSystem } from './systems/interactive/interactive-system' export { openingSettled, proceduralSettled } from './systems/interactive/opening-settled' diff --git a/packages/viewer/src/systems/elevator/elevator-interaction-system.test.ts b/packages/viewer/src/systems/elevator/elevator-interaction-system.test.ts index 0d0b0a26b3..0a152ed557 100644 --- a/packages/viewer/src/systems/elevator/elevator-interaction-system.test.ts +++ b/packages/viewer/src/systems/elevator/elevator-interaction-system.test.ts @@ -13,7 +13,7 @@ import { Vector3, } from 'three' import { createPascalPointerEvents, type ViewerBreadcrumb } from '../../lib/pointer-events' -import { collectElevatorButtons } from './elevator-interaction-system' +import { collectElevatorButtons, pickElevatorButton } from './elevator-interaction-system' const cleanups: (() => void)[] = [] afterEach(() => { @@ -150,3 +150,32 @@ describe('elevator buttons', () => { ]) }) }) + +test('buttons behind opaque walls or hidden elevator groups cannot be clicked', () => { + const scene = new Scene() + const panel = new Group() + panel.userData.elevatorButton = { + action: 'open-door', + disabled: false, + elevatorId: 'e', + kind: 'cab', + } + panel.add(new Mesh(new BoxGeometry(1, 1, 0.1), new MeshBasicMaterial())) + const wall = new Mesh(new BoxGeometry(2, 2, 0.1), new MeshBasicMaterial()) + wall.position.z = 1 + scene.add(panel, wall) + scene.updateMatrixWorld(true) + const ray = new Raycaster(new Vector3(0, 0, 5), new Vector3(0, 0, -1)) + expect(pickElevatorButton(scene, ray)).toBeNull() + wall.visible = false + expect(pickElevatorButton(scene, ray)?.elevatorId).toBe('e') + panel.visible = false + expect(pickElevatorButton(scene, ray)).toBeNull() + panel.visible = true + wall.visible = true + wall.material = [new MeshBasicMaterial()] + wall.geometry.clearGroups() + wall.geometry.addGroup(0, Number.POSITIVE_INFINITY, 4) + expect(() => pickElevatorButton(scene, ray)).not.toThrow() + expect(pickElevatorButton(scene, ray)?.elevatorId).toBe('e') +}) diff --git a/packages/viewer/src/systems/elevator/elevator-interaction-system.tsx b/packages/viewer/src/systems/elevator/elevator-interaction-system.tsx index 539723ae5e..dbca24776e 100644 --- a/packages/viewer/src/systems/elevator/elevator-interaction-system.tsx +++ b/packages/viewer/src/systems/elevator/elevator-interaction-system.tsx @@ -8,7 +8,7 @@ import { } from '@pascal-app/core' import { useThree } from '@react-three/fiber' import { useEffect, useRef } from 'react' -import { type Object3D, Raycaster, Vector2 } from 'three' +import { Mesh, type Object3D, Raycaster, Vector2 } from 'three' type ElevatorButtonAction = 'open-door' | 'request-level' @@ -38,6 +38,7 @@ function getElevatorButtonData(object: Object3D): ElevatorButtonUserData | null * whose meshes this capture-phase listener must not trip over. */ export function collectElevatorButtons(object: Object3D, into: Object3D[] = []): Object3D[] { + if (!object.visible) return into if ((object.userData as { elevatorButton?: unknown }).elevatorButton) { into.push(object) return into @@ -46,7 +47,49 @@ export function collectElevatorButtons(object: Object3D, into: Object3D[] = []): return into } -export function ElevatorInteractionSystem() { +/** Ignore malformed material groups during transient paint updates, rather than raycasting invalid faces. */ +export function pickElevatorButton( + scene: Object3D, + raycaster: Raycaster, +): ElevatorButtonUserData | null { + const buttons = collectElevatorButtons(scene) + const faces: Object3D[] = [] + for (const button of buttons) + button.traverseVisible((object) => { + if (object instanceof Mesh) faces.push(object) + }) + const hit = raycaster.intersectObjects(faces, false)[0] + if (!hit) return null + const blockers: Mesh[] = [] + scene.traverseVisible((object) => { + if ( + !(object instanceof Mesh) || + getElevatorButtonData(object) || + object.userData.pascalExport === 'strip' + ) + return + if ( + Array.isArray(object.material) && + object.geometry.groups.some( + (group: { materialIndex?: number; count: number }) => + !object.material[group.materialIndex ?? 0] || !Number.isFinite(group.count), + ) + ) + return + blockers.push(object) + }) + const occluded = raycaster.intersectObjects(blockers, false).some((intersection) => { + if (intersection.distance >= hit.distance - 0.001) return false + const mesh = intersection.object as Mesh + const material = Array.isArray(mesh.material) + ? mesh.material[intersection.face?.materialIndex ?? 0] + : mesh.material + return material?.visible && (!material.transparent || material.opacity >= 0.95) + }) + return occluded ? null : getElevatorButtonData(hit.object) +} + +export function ElevatorInteractionSystem({ enabled = true }: { enabled?: boolean }) { const camera = useThree((state) => state.camera) const gl = useThree((state) => state.gl) const scene = useThree((state) => state.scene) @@ -57,7 +100,7 @@ export function ElevatorInteractionSystem() { const canvas = gl.domElement const handlePointerDown = (event: PointerEvent) => { - if (event.button !== 0) return + if (event.button !== 0 || !enabled) return const buttons = collectElevatorButtons(scene) if (buttons.length === 0) return @@ -70,10 +113,7 @@ export function ElevatorInteractionSystem() { const raycaster = raycasterRef.current raycaster.setFromCamera(pointer, camera) - const button = raycaster - .intersectObjects(buttons, true) - .map((intersection) => getElevatorButtonData(intersection.object)) - .find((data): data is ElevatorButtonUserData => data !== null) + const button = pickElevatorButton(scene, raycaster) if (!button || button.disabled) return @@ -104,7 +144,7 @@ export function ElevatorInteractionSystem() { return () => { canvas.removeEventListener('pointerdown', handlePointerDown, true) } - }, [camera, gl, scene]) + }, [camera, gl, scene, enabled]) return null } diff --git a/packages/viewer/src/systems/geometry/geometry-status.ts b/packages/viewer/src/systems/geometry/geometry-status.ts new file mode 100644 index 0000000000..487624b614 --- /dev/null +++ b/packages/viewer/src/systems/geometry/geometry-status.ts @@ -0,0 +1,27 @@ +import { type AnyNodeId, useScene } from '@pascal-app/core' +import { create } from 'zustand' + +export type GeometryFailure = 'build-failed' | 'invalid-geometry' + +/** Geometry failures describe the current rendering, never saved building data. */ +export const useGeometryStatus = create<{ failures: ReadonlyMap }>( + () => ({ + failures: new Map(), + }), +) + +export function setGeometryFailure(id: AnyNodeId, message: GeometryFailure | null) { + const current = useGeometryStatus.getState().failures + if ((current.get(id) ?? null) === message) return + const failures = new Map(current) + if (message) failures.set(id, message) + else failures.delete(id) + useGeometryStatus.setState({ failures }) +} + +useScene.subscribe((scene, previous) => { + const failures = useGeometryStatus.getState().failures + for (const id of failures.keys()) { + if (scene.hydrationId !== previous.hydrationId || !scene.nodes[id]) setGeometryFailure(id, null) + } +}) diff --git a/packages/viewer/src/systems/roof/roof-system.tsx b/packages/viewer/src/systems/roof/roof-system.tsx index 1bbb4d1cce..425c10e964 100644 --- a/packages/viewer/src/systems/roof/roof-system.tsx +++ b/packages/viewer/src/systems/roof/roof-system.tsx @@ -52,6 +52,7 @@ import { applyWorldScaleBoxUVs } from '../../lib/box-uv' import { ensureRenderableGeometryAttributes, subtractCsgBrush } from '../../lib/csg-utils' import useViewer from '../../store/use-viewer' import { isRevealAssembling } from '../construction-reveal/construction-reveal' +import { setGeometryFailure, useGeometryStatus } from '../geometry/geometry-status' import { ROOF_GABLE_LEFT_MATERIAL_INDEX, ROOF_GABLE_RIGHT_MATERIAL_INDEX, @@ -473,7 +474,12 @@ export const RoofSystem = ({ geometryAdapter }: { geometryAdapter?: RoofGeometry // Built even while hidden: a roof assembling from its segments (construction // reveal) hides its shell, and must show it whole the moment it is captured. rememberMergedInputs(node as RoofNode, nodes) - updateMergedRoofGeometry(node as RoofNode, group, nodes, framing) + try { + updateMergedRoofGeometry(node as RoofNode, group, nodes, framing) + } catch (error) { + setGeometryFailure(node.id, 'build-failed') + console.error('Roof rebuild failed:', error) + } roofsProcessed++ pendingRoofUpdates.delete(id) @@ -494,7 +500,18 @@ function updateRoofSegmentGeometry( adapter?: RoofGeometryAdapter, framing = false, ) { - const newGeo = generateRoofSegmentGeometry(node, nodes, { framing }) + let newGeo: THREE.BufferGeometry + try { + newGeo = generateRoofSegmentGeometry(node, nodes, { framing }) + } catch (error) { + setGeometryFailure(node.id, 'build-failed') + console.error('Roof segment rebuild failed:', error) + return + } + if (useGeometryStatus.getState().failures.has(node.id)) { + newGeo.dispose() + return + } mesh.geometry.dispose() mesh.geometry = newGeo @@ -523,70 +540,71 @@ function subtractAccessoryCuts( let workingShin = brushes.shinSlab let workingDeck = brushes.deckSlab let workingWall = brushes.wallBrush - for (const childElemId of segment.children ?? []) { - const storedChild = nodes[childElemId as AnyNodeId] - if (!storedChild) continue - const childElem = getEffectiveNode(storedChild) - const meta = - typeof childElem.metadata === 'object' && childElem.metadata !== null - ? (childElem.metadata as Record) - : undefined - if (meta?.isTransient) continue - - const childDef = nodeRegistry.get(childElem.type) - const buildCut = childDef?.capabilities?.roofAccessory?.buildCut - if (!buildCut) continue - - const cutGeo = buildCut(childElem, segment) - if (!cutGeo) continue - - // Wrap the kind-emitted geometry in a Brush. Kinds return raw - // shapes; the viewer welds (mandatory after rotations leave - // duplicated verts), attaches a single material group, and - // builds the bounds tree — keeping kind code free of - // three-bvh-csg / three-mesh-bvh imports. - const welded = mergeVertices(cutGeo, 1e-4) - cutGeo.dispose() - const idxCount = welded.getIndex()?.count ?? 0 - if (idxCount === 0) { - welded.dispose() - continue - } - welded.clearGroups() - welded.addGroup(0, idxCount, 0) - welded.computeVertexNormals() - ensureRenderableGeometryAttributes(welded) - computeGeometryBoundsTree(welded) - const cut = new Brush(welded, dummyMats[0]) - cut.updateMatrixWorld() - - const cutScope = childDef?.capabilities?.roofAccessory?.cutScope ?? 'all' - try { - if (cutScope !== 'wall') { - const nextShin = csgEvaluator.evaluate(workingShin, cut, SUBTRACTION) as Brush - workingShin.geometry.dispose() - prepareBrushForCSG(nextShin) - workingShin = nextShin - - const nextDeck = csgEvaluator.evaluate(workingDeck, cut, SUBTRACTION) as Brush - workingDeck.geometry.dispose() - prepareBrushForCSG(nextDeck) - workingDeck = nextDeck + try { + for (const childElemId of segment.children ?? []) { + const storedChild = nodes[childElemId as AnyNodeId] + if (!storedChild) continue + const childElem = getEffectiveNode(storedChild) + const meta = + typeof childElem.metadata === 'object' && childElem.metadata !== null + ? (childElem.metadata as Record) + : undefined + if (meta?.isTransient) continue + + const childDef = nodeRegistry.get(childElem.type) + const buildCut = childDef?.capabilities?.roofAccessory?.buildCut + if (!buildCut) continue + + const cutGeo = buildCut(childElem, segment) + if (!cutGeo) continue + + // Wrap the kind-emitted geometry in a Brush. Kinds return raw + // shapes; the viewer welds (mandatory after rotations leave + // duplicated verts), attaches a single material group, and + // builds the bounds tree — keeping kind code free of + // three-bvh-csg / three-mesh-bvh imports. + const welded = mergeVertices(cutGeo, 1e-4) + cutGeo.dispose() + const idxCount = welded.getIndex()?.count ?? 0 + if (idxCount === 0) { + welded.dispose() + continue } + welded.clearGroups() + welded.addGroup(0, idxCount, 0) + welded.computeVertexNormals() + ensureRenderableGeometryAttributes(welded) + computeGeometryBoundsTree(welded) + const cut = new Brush(welded, dummyMats[0]) + cut.updateMatrixWorld() + + const cutScope = childDef?.capabilities?.roofAccessory?.cutScope ?? 'all' + try { + if (cutScope !== 'wall') { + const nextShin = csgEvaluator.evaluate(workingShin, cut, SUBTRACTION) as Brush + workingShin.geometry.dispose() + prepareBrushForCSG(nextShin) + workingShin = nextShin + + const nextDeck = csgEvaluator.evaluate(workingDeck, cut, SUBTRACTION) as Brush + workingDeck.geometry.dispose() + prepareBrushForCSG(nextDeck) + workingDeck = nextDeck + } - const nextWall = csgEvaluator.evaluate(workingWall, cut, SUBTRACTION) as Brush - workingWall.geometry.dispose() - prepareBrushForCSG(nextWall) - workingWall = nextWall - } catch (e) { - console.error(`[${childElem.type}] cut CSG failed:`, e) - } finally { - cut.geometry.dispose() + const nextWall = csgEvaluator.evaluate(workingWall, cut, SUBTRACTION) as Brush + workingWall.geometry.dispose() + prepareBrushForCSG(nextWall) + workingWall = nextWall + } finally { + cut.geometry.dispose() + } } + } finally { + brushes.shinSlab = workingShin + brushes.deckSlab = workingDeck + brushes.wallBrush = workingWall } - brushes.shinSlab = workingShin - brushes.deckSlab = workingDeck - brushes.wallBrush = workingWall } function getMergedRoofSegmentBrushes( @@ -622,7 +640,12 @@ function getMergedRoofSegmentBrushes( return null } - subtractAccessoryCuts(brushes, segment, nodes) + try { + subtractAccessoryCuts(brushes, segment, nodes) + } catch (error) { + disposeRoofSegmentBrushSet(brushes) + throw error + } _matrix.compose( _position.set(segment.position[0], segment.position[1], segment.position[2]), @@ -702,6 +725,7 @@ function updateMergedRoofGeometry( // Not BoxGeometry: its 6 groups against the merged mesh's 4-material array // crash GLTFExporter (materials[4] → undefined) when the roof bakes. mergedMesh.geometry = createDegenerateRoofPlaceholder() + setGeometryFailure(roofNode.id, null) return } @@ -823,6 +847,7 @@ function updateMergedRoofGeometry( ) warnedMergedRoofNaNIds.add(roofNode.id) } + setGeometryFailure(roofNode.id, 'invalid-geometry') resultGeo.dispose() if (combined !== shinDeck) shinDeck.geometry.dispose() totalShinSlab.geometry.dispose() @@ -879,9 +904,11 @@ function updateMergedRoofGeometry( ensureRenderableGeometryAttributes(finalGeo) mergedMesh.geometry.dispose() mergedMesh.geometry = finalGeo + setGeometryFailure(roofNode.id, null) if (combined !== shinDeck) shinDeck.geometry.dispose() } catch (e) { + setGeometryFailure(roofNode.id, 'build-failed') console.error('Merged roof CSG failed:', e) } @@ -901,6 +928,7 @@ function updateMergedRoofGeometry( ensureRenderableGeometryAttributes(finalGeo) mergedMesh.geometry.dispose() mergedMesh.geometry = finalGeo + setGeometryFailure(roofNode.id, null) } for (const geometry of directSegmentGeometries) { if (geometry !== finalGeo) geometry.dispose() @@ -2426,6 +2454,7 @@ export function generateRoofSegmentGeometry( } result.computeVertexNormals() ensureRenderableGeometryAttributes(result) + setGeometryFailure(node.id, null) return result } const brushes = withSegmentUvMatrix(segmentWorldMatrix, () => @@ -2435,12 +2464,17 @@ export function generateRoofSegmentGeometry( }), ) if (!brushes) { - // Fallback: simple box + setGeometryFailure(node.id, 'build-failed') return new THREE.BoxGeometry(node.width, node.wallHeight, node.depth) } if (nodes) { - subtractAccessoryCuts(brushes, node, nodes) + try { + subtractAccessoryCuts(brushes, node, nodes) + } catch (error) { + disposeRoofSegmentBrushSet(brushes) + throw error + } } const { deckSlab, shinSlab, wallBrush, innerBrush, rakeBoards } = brushes @@ -2469,8 +2503,9 @@ export function generateRoofSegmentGeometry( resultGeo = csgGeometry(combined) if (geometryHasInvalidAttributes(resultGeo)) { resultGeo.dispose() + setGeometryFailure(node.id, 'invalid-geometry') resultGeo = csgGeometry(wallBrush).clone() - } + } else setGeometryFailure(node.id, null) const resultMaterials = csgMaterials(combined) @@ -2496,6 +2531,7 @@ export function generateRoofSegmentGeometry( hollowWall?.geometry.dispose() if (combined !== shinDeck) shinDeck.geometry.dispose() } catch (e) { + setGeometryFailure(node.id, 'build-failed') console.error('Roof CSG failed:', e) resultGeo = csgGeometry(wallBrush).clone() } diff --git a/wiki/architecture/plugin-authoring.md b/wiki/architecture/plugin-authoring.md index 531af7775a..9f9bd555c4 100644 --- a/wiki/architecture/plugin-authoring.md +++ b/wiki/architecture/plugin-authoring.md @@ -427,6 +427,11 @@ DECISIONS.md E-017. Framework packages never import a node pack to implement the object on its original level and visual elevation during a move. Fresh placement still follows the chosen support. Stored Y remains an offset from the support, not an absolute world height. +- `capabilities.movable.resolvePosition({ node, position, nodes })` returns the + stored position after snapping. The generic 3D mover and the 2D plan mover + call it for the live preview and again at commit, so a changed support is + re-elected at release (a building-parented elevator's landing height). It is + pure: it must not write scene state. Omitted, the proposed position is kept. - `capabilities.movable.parentFrame.independent` keeps selection/manipulation on the child instead of promoting its parent. The frame's conversion hooks still own cursor and rotation conversion in 2D and 3D. diff --git a/wiki/images/node-tool-review/barrel-roof.jpg b/wiki/images/node-tool-review/barrel-roof.jpg new file mode 100644 index 0000000000..dde57c85fd Binary files /dev/null and b/wiki/images/node-tool-review/barrel-roof.jpg differ diff --git a/wiki/images/node-tool-review/pillar-presets.jpg b/wiki/images/node-tool-review/pillar-presets.jpg new file mode 100644 index 0000000000..169008a550 Binary files /dev/null and b/wiki/images/node-tool-review/pillar-presets.jpg differ diff --git a/wiki/images/node-tool-review/roof-inspector-thumbnails.jpg b/wiki/images/node-tool-review/roof-inspector-thumbnails.jpg new file mode 100644 index 0000000000..41899c0502 Binary files /dev/null and b/wiki/images/node-tool-review/roof-inspector-thumbnails.jpg differ diff --git a/wiki/images/node-tool-review/roof-menu-and-thumbnails.jpg b/wiki/images/node-tool-review/roof-menu-and-thumbnails.jpg new file mode 100644 index 0000000000..d391326e78 Binary files /dev/null and b/wiki/images/node-tool-review/roof-menu-and-thumbnails.jpg differ