diff --git a/apps/editor/components/build-tab.tsx b/apps/editor/components/build-tab.tsx index efd3092f49..f0c9864d42 100644 --- a/apps/editor/components/build-tab.tsx +++ b/apps/editor/components/build-tab.tsx @@ -23,7 +23,7 @@ import { useTerraceDraft, useWallDrawVariant, } from '@pascal-app/editor' -import { useLiquidLineToolOptions } from '@pascal-app/nodes' +import { 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' @@ -268,14 +268,14 @@ export function BuildTab() {
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 812a60b5ec..7373ed99ec 100644 --- a/apps/editor/lib/build-tab-state.ts +++ b/apps/editor/lib/build-tab-state.ts @@ -39,6 +39,7 @@ export const ROOF_TYPE_OPTIONS: ReadonlyArray<{ label: string; value: RoofType } { label: 'Dutch', value: 'dutch' }, { label: 'Mansard', value: 'mansard' }, { label: 'Conical', value: 'conical' }, + { label: '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/editor/public/icons/roof-types/barrel.webp b/apps/editor/public/icons/roof-types/barrel.webp new file mode 100644 index 0000000000..cc95656e68 Binary files /dev/null and b/apps/editor/public/icons/roof-types/barrel.webp differ diff --git a/apps/editor/public/icons/roof-types/conical.webp b/apps/editor/public/icons/roof-types/conical.webp new file mode 100644 index 0000000000..db326712f4 Binary files /dev/null and b/apps/editor/public/icons/roof-types/conical.webp differ diff --git a/apps/editor/public/icons/roof-types/dutch.webp b/apps/editor/public/icons/roof-types/dutch.webp new file mode 100644 index 0000000000..d74cbbaab6 Binary files /dev/null and b/apps/editor/public/icons/roof-types/dutch.webp differ diff --git a/apps/editor/public/icons/roof-types/flat.webp b/apps/editor/public/icons/roof-types/flat.webp new file mode 100644 index 0000000000..f3736a0341 Binary files /dev/null and b/apps/editor/public/icons/roof-types/flat.webp differ diff --git a/apps/editor/public/icons/roof-types/gable.webp b/apps/editor/public/icons/roof-types/gable.webp new file mode 100644 index 0000000000..5ee9359c7e Binary files /dev/null and b/apps/editor/public/icons/roof-types/gable.webp differ diff --git a/apps/editor/public/icons/roof-types/gambrel.webp b/apps/editor/public/icons/roof-types/gambrel.webp new file mode 100644 index 0000000000..87b492ada3 Binary files /dev/null and b/apps/editor/public/icons/roof-types/gambrel.webp differ diff --git a/apps/editor/public/icons/roof-types/hip.webp b/apps/editor/public/icons/roof-types/hip.webp new file mode 100644 index 0000000000..15782fc5aa Binary files /dev/null and b/apps/editor/public/icons/roof-types/hip.webp differ diff --git a/apps/editor/public/icons/roof-types/mansard.webp b/apps/editor/public/icons/roof-types/mansard.webp new file mode 100644 index 0000000000..08ff238eef Binary files /dev/null and b/apps/editor/public/icons/roof-types/mansard.webp differ diff --git a/apps/editor/public/icons/roof-types/shed.webp b/apps/editor/public/icons/roof-types/shed.webp new file mode 100644 index 0000000000..f181d02803 Binary files /dev/null and b/apps/editor/public/icons/roof-types/shed.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/packages/core/src/contracts/reference-inventory.ts b/packages/core/src/contracts/reference-inventory.ts index 60f8c18879..7456336328 100644 --- a/packages/core/src/contracts/reference-inventory.ts +++ b/packages/core/src/contracts/reference-inventory.ts @@ -958,7 +958,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 c7fc1391e9..0dab1ea6a6 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -688,6 +688,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, @@ -701,6 +704,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..f7267e131f 100644 --- a/packages/core/src/node-slots/column.ts +++ b/packages/core/src/node-slots/column.ts @@ -3,10 +3,10 @@ import type { ColumnNode } from '../schema/nodes/column' export type ColumnSlotId = 'shaft' | 'base' | 'capital' | 'frame' -export const COLUMN_SHAFT_DEFAULT = 'library:concrete-plaster' -export const COLUMN_BASE_DEFAULT = 'library:concrete-plaster' -export const COLUMN_CAPITAL_DEFAULT = 'library:concrete-plaster' -export const COLUMN_FRAME_DEFAULT = 'library:metal-steel' +export const COLUMN_SHAFT_DEFAULT = 'library:preset-white' +export const COLUMN_BASE_DEFAULT = 'library:preset-white' +export const COLUMN_CAPITAL_DEFAULT = 'library:preset-white' +export const COLUMN_FRAME_DEFAULT = 'library:preset-white' export function columnSlots(node: ColumnNode): SlotDeclaration[] { if (node.source) diff --git a/packages/core/src/registry/types.ts b/packages/core/src/registry/types.ts index d57c7750da..aacece83ae 100644 --- a/packages/core/src/registry/types.ts +++ b/packages/core/src/registry/types.ts @@ -2232,6 +2232,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 509c379b71..e5a0eb281e 100644 --- a/packages/core/src/schema/index.ts +++ b/packages/core/src/schema/index.ts @@ -319,6 +319,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 5c0408521e..bc732c0608 100644 --- a/packages/core/src/schema/nodes/roof-segment.ts +++ b/packages/core/src/schema/nodes/roof-segment.ts @@ -5,10 +5,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 { RoofType } from './roof-types' export { 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 @@ -133,7 +136,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), @@ -767,7 +770,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/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..f304e06ae7 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,89 @@ 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 }) + } +}) diff --git a/packages/core/src/systems/elevator/elevator-runtime.ts b/packages/core/src/systems/elevator/elevator-runtime.ts index 7278dea0df..1665cffec2 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,20 +138,71 @@ 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 + ) + return state + const available = entries.filter((entry) => !elevator.disabledLevelIds.includes(entry.id)) + 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' + ? available.reduce( + (nearest, entry) => + !nearest || Math.abs(entry.baseY - state.carY) < Math.abs(nearest.baseY - state.carY) + ? entry + : nearest, + null, + ) + : 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 } + } const targetEntry = state.targetLevelId ? entries.find((entry) => entry.id === state.targetLevelId) @@ -234,6 +305,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 +332,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-move-overlay.tsx b/packages/editor/src/components/editor-2d/floorplan-registry-move-overlay.tsx index ef1de406d7..106bb49a8a 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 @@ -844,14 +844,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) ?? @@ -879,6 +890,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 && @@ -931,7 +947,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, @@ -947,7 +963,7 @@ export function FloorplanRegistryMoveOverlay() { useScene.getState().updateNode( movingNode.id as AnyNodeId, { - position: [sx, oldY, sz], + position, ...rotationPatch, } as Partial, ) @@ -999,6 +1015,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/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 e6fd5c8460..f0b193b8aa 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) @@ -1026,7 +1038,7 @@ export function MoveRegistryNodeTool({ node: source }: { node: AnyNode }) { }, ).position } - position = keepStartingElevation(position, rotationRef.current) + position = resolvePosition(keepStartingElevation(position, rotationRef.current)) const visualPosition = getVisualPosition(position) hasMovedRef.current = true setCursorPosition(visualPosition) @@ -1116,7 +1128,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 e7128bc87f..2c7afbe321 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 3bf74c6b75..1e8c586748 100644 --- a/packages/editor/src/components/ui/controls/slider-control.tsx +++ b/packages/editor/src/components/ui/controls/slider-control.tsx @@ -246,6 +246,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) => { @@ -376,6 +382,7 @@ export function SliderControl({ )} ) : mixed && !isDragging ? ( -
Mixed -
+ ) : ( -
@@ -417,7 +428,7 @@ export function SliderControl({ {Number(displayValue.toFixed(precision)).toFixed(precision)} {displayUnit && {displayUnit}} -
+ )}
diff --git a/packages/editor/src/components/ui/panels/panel-wrapper.tsx b/packages/editor/src/components/ui/panels/panel-wrapper.tsx index 316ebb2c91..3c0f6362a9 100644 --- a/packages/editor/src/components/ui/panels/panel-wrapper.tsx +++ b/packages/editor/src/components/ui/panels/panel-wrapper.tsx @@ -55,7 +55,7 @@ function clamp(value: number, min: number, max: number): number { * `data-viewer-bounds`) so it can't slide under the sidebar or top bar. * Falls back to the viewport when the marker isn't found. */ -function getDragBounds(el: HTMLElement | null): { +function getDragBounds(el: HTMLElement | null, inStack = false): { left: number top: number right: number @@ -66,7 +66,15 @@ function getDragBounds(el: HTMLElement | null): { if (!rect) { return { left: 0, top: 0, right: window.innerWidth, bottom: window.innerHeight } } - return { left: rect.left, top: rect.top, right: rect.right, bottom: rect.bottom } + const stack = inStack ? el?.closest('[data-right-stack]') : null + const stackRect = stack?.getBoundingClientRect() + const cardRect = stack?.querySelector('[data-right-stack-card]')?.getBoundingClientRect() + return { + left: rect.left, + top: stackRect ? stackRect.top - DRAG_MARGIN : rect.top, + right: rect.right, + bottom: cardRect && cardRect.height > 0 ? cardRect.top : rect.bottom, + } } /** @@ -225,7 +233,7 @@ export function PanelWrapper({ if ((e.target as HTMLElement).closest('button, input, label')) return const rect = panelRef.current?.getBoundingClientRect() if (!rect) return - const bounds = getDragBounds(panelRef.current) + const bounds = getDragBounds(panelRef.current, inStack) const base = offset ?? { x: 0, y: 0 } dragRef.current = { startX: e.clientX, @@ -245,7 +253,7 @@ export function PanelWrapper({ setIsDragging(true) e.currentTarget.setPointerCapture(e.pointerId) }, - [offset], + [offset, inStack], ) const handleHeaderPointerMove = useCallback((e: React.PointerEvent) => { @@ -276,22 +284,37 @@ export function PanelWrapper({ [handleCardToggle], ) - // Expanding can grow the panel past an edge if it was dragged there while - // collapsed — nudge it back inside the viewer bounds. + // Keep repositioned panels inside the available space as the card or viewer resizes. useLayoutEffect(() => { - if (isMobile || collapsed) return + if (isMobile) return const el = panelRef.current if (!el) return - const rect = el.getBoundingClientRect() - const bounds = getDragBounds(el) - const left = clamp(rect.left, bounds.left + DRAG_MARGIN, bounds.right - rect.width - DRAG_MARGIN) - const top = clamp(rect.top, bounds.top + DRAG_MARGIN, bounds.bottom - rect.height - DRAG_MARGIN) - const dx = left - rect.left - const dy = top - rect.top - if (Math.abs(dx) > 0.5 || Math.abs(dy) > 0.5) { - setOffset((prev) => ({ x: (prev?.x ?? 0) + dx, y: (prev?.y ?? 0) + dy })) + const fit = () => { + const rect = el.getBoundingClientRect() + const bounds = getDragBounds(el, inStack) + const left = clamp(rect.left, bounds.left + DRAG_MARGIN, bounds.right - rect.width - DRAG_MARGIN) + const top = clamp(rect.top, bounds.top + DRAG_MARGIN, bounds.bottom - rect.height - DRAG_MARGIN) + const dx = left - rect.left + const dy = top - rect.top + if (Math.abs(dx) > 0.5 || Math.abs(dy) > 0.5) { + setOffset((prev) => ({ x: (prev?.x ?? 0) + dx, y: (prev?.y ?? 0) + dy })) + } + } + fit() + const resize = new ResizeObserver(fit) + resize.observe(el) + const stack = el.closest('[data-right-stack]') + if (stack) { + resize.observe(stack) + const card = stack.querySelector('[data-right-stack-card]') + if (card) resize.observe(card) + } + window.addEventListener('resize', fit) + return () => { + resize.disconnect() + window.removeEventListener('resize', fit) } - }, [collapsed, isMobile]) + }, [collapsed, isMobile, inStack]) return (
{ +test('on a short window the help card scrolls to preserve editing space', () => { expect(rightStackFloors({ ...tall, naturalHeight: 500, stackHeight: 400 })).toEqual({ - inspector: 152, - card: 240, + inspector: 180, + card: 212, }) }) -test('on a very short window the inspector keeps its header and the card scrolls', () => { +test('expanded hints cannot squeeze the inspector down to just its header', () => { expect(rightStackFloors({ ...tall, naturalHeight: 500, stackHeight: 258 })).toEqual({ - inspector: 52, - card: 198, + inspector: 180, + card: 70, + }) +}) + +test('a column shorter than the inspector minimum still bounds both cards', () => { + expect(rightStackFloors({ ...tall, naturalHeight: 500, stackHeight: 100 })).toEqual({ + inspector: 92, + card: 0, }) }) diff --git a/packages/editor/src/components/ui/right-stack.tsx b/packages/editor/src/components/ui/right-stack.tsx index ad359d30aa..b39df781ae 100644 --- a/packages/editor/src/components/ui/right-stack.tsx +++ b/packages/editor/src/components/ui/right-stack.tsx @@ -1,6 +1,6 @@ 'use client' -import { createContext, type ReactNode, useContext, useEffect, useRef } from 'react' +import { createContext, type ReactNode, useContext, useLayoutEffect, useRef } from 'react' import { useIsMobile } from '../../hooks/use-mobile' import { cn } from '../../lib/utils' import { TOP_MENU_CLEARANCE } from './action-menu/placement' @@ -20,9 +20,8 @@ const GAP = 8 /** * The heights neither panel shrinks below. The inspector keeps 180 px (or its - * own height, if shorter) while the full card fits under it, and never less - * than its header row. The card shows in full whenever the column allows; on a - * very short window it gives way and scrolls on itself — both stay usable. + * own height, if shorter) and never less than its header row when the column allows. + * The card uses the remaining room and scrolls on itself on a short window — both stay usable. */ export function rightStackFloors(args: { naturalHeight: number @@ -33,9 +32,10 @@ export function rightStackFloors(args: { const { naturalHeight, headerHeight, cardHeight, stackHeight } = args const gap = naturalHeight > 0 && cardHeight > 0 ? GAP : 0 const header = Math.min(headerHeight, naturalHeight) - const inspector = Math.max( - header, - Math.min(INSPECTOR_MIN_HEIGHT, naturalHeight, stackHeight - cardHeight - gap), + const inspector = Math.min( + naturalHeight, + stackHeight, + Math.max(header, Math.min(INSPECTOR_MIN_HEIGHT, stackHeight - gap)), ) const card = Math.max(0, Math.min(cardHeight, stackHeight - gap - inspector)) return { inspector, card } @@ -78,7 +78,7 @@ export function RightStack({ // `min(180px, its own height)` has no CSS form for a flex item that scrolls, // so both floors are measured (`rightStackFloors`). - useEffect(() => { + useLayoutEffect(() => { if (isMobile) return const stack = stackRef.current const slot = inspectorRef.current @@ -88,18 +88,29 @@ export function RightStack({ const fit = () => { frame = 0 const { natural, header } = inspectorHeights(slot) + const cardHeight = Array.from(card.children).reduce( + (height, child) => height + child.scrollHeight + (child instanceof HTMLElement ? child.offsetHeight - child.clientHeight : 0), + 0, + ) const floors = rightStackFloors({ naturalHeight: natural, headerHeight: header, - cardHeight: card.scrollHeight, + cardHeight, stackHeight: stack.clientHeight, }) const inspectorMin = `${floors.inspector}px` const cardMin = `${floors.card}px` + // Custom panels may wrap PanelWrapper in a non-flex element. Give the + // card an explicit inherited limit so those wrappers cannot bypass it. + const available = Math.max(0, stack.clientHeight - floors.card - (natural > 0 && floors.card > 0 ? GAP : 0)) + const limit = `${available}px` + if (slot.style.getPropertyValue('--inspector-available-height') !== limit) { + slot.style.setProperty('--inspector-available-height', limit) + } if (slot.style.minHeight !== inspectorMin) slot.style.minHeight = inspectorMin if (card.style.minHeight !== cardMin) card.style.minHeight = cardMin // The card is click-through; it takes the pointer only when it has to scroll. - const pointer = floors.card < card.scrollHeight ? 'auto' : '' + const pointer = floors.card < cardHeight ? 'auto' : '' if (card.style.pointerEvents !== pointer) card.style.pointerEvents = pointer } const schedule = () => { diff --git a/packages/editor/src/index.tsx b/packages/editor/src/index.tsx index 1a456f90ff..a9ef645ba7 100644 --- a/packages/editor/src/index.tsx +++ b/packages/editor/src/index.tsx @@ -154,7 +154,11 @@ export { usePlacementCoordinator, } from './components/tools/item/use-placement-coordinator' export { MoveRegistryNodeTool } from './components/tools/registry/move-registry-node-tool' -export { useRegistryToolContext } from './components/tools/registry-tool-context' +export { + type RegistryToolContextValue, + RegistryToolProvider, + useRegistryToolContext, +} from './components/tools/registry-tool-context' export { CursorSphere } from './components/tools/shared/cursor-sphere' export { DRAFT_LABEL_Y_OFFSET, diff --git a/packages/editor/src/lib/floor-foundation-support.test.ts b/packages/editor/src/lib/floor-foundation-support.test.ts index 3ffb00ddbf..30c78b37bf 100644 --- a/packages/editor/src/lib/floor-foundation-support.test.ts +++ b/packages/editor/src/lib/floor-foundation-support.test.ts @@ -163,7 +163,6 @@ describe('Upper-floor height drag release (round-final item 6)', () => { test(`a drag of ${delta} m lands on release`, () => { const bedroom = plateOf(UPPER, 'Bedroom') const start = footprintHeightValue(nodes(), bedroom) - const past = useScene.temporal.getState().pastStates.length const preview = beginFootprintHeightPreview(bedroom.id) expect(preview.preview(start + delta / 2)).toBeNull() expect(preview.preview(start + delta)).toBeNull() @@ -171,7 +170,13 @@ describe('Upper-floor height drag release (round-final item 6)', () => { const after = nodes()[bedroom.id] as SlabNode expect(after.thickness).toBeCloseTo(bedroom.thickness + delta, 6) expect(footprintHeightValue(nodes(), after)).toBeCloseTo(start + delta, 6) - expect(useScene.temporal.getState().pastStates.length).toBe(past + 1) + useScene.temporal.getState().undo() + expect(footprintHeightValue(nodes(), nodes()[bedroom.id] as SlabNode)).toBeCloseTo(start, 6) + useScene.temporal.getState().redo() + expect(footprintHeightValue(nodes(), nodes()[bedroom.id] as SlabNode)).toBeCloseTo( + start + delta, + 6, + ) }) } }) diff --git a/packages/editor/src/lib/interaction/scope.ts b/packages/editor/src/lib/interaction/scope.ts index f1dccf4ad7..90fda42001 100644 --- a/packages/editor/src/lib/interaction/scope.ts +++ b/packages/editor/src/lib/interaction/scope.ts @@ -28,6 +28,7 @@ export type ReshapeKind = | 'tangent' // A kind's own reshape (wall 'split'): mounted from `def.affordanceTools[reshape]`. | 'split' + | 'trim' export type InteractionScope = | { kind: 'idle' } diff --git a/packages/editor/src/lib/placement-metadata.ts b/packages/editor/src/lib/placement-metadata.ts index 2d15e6344e..03daed47b4 100644 --- a/packages/editor/src/lib/placement-metadata.ts +++ b/packages/editor/src/lib/placement-metadata.ts @@ -17,6 +17,10 @@ export function isFreshPlacementMetadata(metadata: unknown): boolean { return getPlacementMetadataRecord(metadata).isNew === true } +export function stripPlacementMetadataFlags( + metadata: Record, +): Record +export function stripPlacementMetadataFlags(metadata: unknown): unknown export function stripPlacementMetadataFlags(metadata: unknown): unknown { if (typeof metadata !== 'object' || metadata === null || Array.isArray(metadata)) { return metadata diff --git a/packages/nodes/package.json b/packages/nodes/package.json index f5730b0b5f..7e60871fa9 100644 --- a/packages/nodes/package.json +++ b/packages/nodes/package.json @@ -1,7 +1,7 @@ { "name": "@pascal-app/nodes", "version": "1.0.4", - "description": "Built-in node bundles for the Pascal 3D editor — one folder per kind, exported as `builtinPlugin`", + "description": "Built-in node bundles for the Pascal 3D editor \u2014 one folder per kind, exported as `builtinPlugin`", "type": "module", "main": "./dist/index.js", "types": "./dist/index.d.ts", @@ -35,7 +35,8 @@ "build": "NODE_OPTIONS=--max-old-space-size=6144 tsc --build && bun ../../scripts/fix-node-esm-imports.ts dist", "dev": "tsgo --build --watch", "test": "bun test", - "prepublishOnly": "bun run build && bun test" + "prepublishOnly": "bun run build && bun test", + "bench:elevator": "bun test ./src/elevator/__bench__/rendering.bench.tsx && bun ./src/elevator/__bench__/runtime.ts" }, "peerDependencies": { "@pascal-app/core": "^1.0.4", diff --git a/packages/nodes/src/__tests__/column-tops.test.tsx b/packages/nodes/src/__tests__/column-tops.test.tsx index dc1ae960a6..0b03c1a4ca 100644 --- a/packages/nodes/src/__tests__/column-tops.test.tsx +++ b/packages/nodes/src/__tests__/column-tops.test.tsx @@ -397,7 +397,7 @@ for (const mover of ['catalog', 'registry'] as const) const narrow = width.apply(scene.get(host.id)!, 0.1, scene, { altKey: false }) expect(narrow.width).toBe(host.width) expect(planColumnEdit(host.id, { capitalStyle: 'none' } as never)).toBeNull() - const cap = planColumnEdit(host.id, { capitalStyle: 'stepped' } as never)! + const cap = planColumnEdit(host.id, { capitalStyle: 'stepped', height: 3.2 } as never)! expect(cap.some(([id]) => id === child.id)).toBe(true) await act(async () => useScene.getState().updateNodes(cap.map(([id, data]) => ({ id, data }))), @@ -405,6 +405,7 @@ for (const mover of ['catalog', 'registry'] as const) await settle(renderer) const resized = scene.get(host.id)! const top = getSurfaceProvider(resized).surfaces!(resized, { scene })[0]! + expect(top.position[1]).toBeCloseTo(3.2, 6) expect((scene.get(child.id) as ItemNode).position[1]).toBeCloseTo(top.position[1], 6) expect(sceneRegistry.nodes.get(child.id)!.getWorldPosition(new Vector3()).y).toBeCloseTo( top.position[1] + 0.4, diff --git a/packages/nodes/src/box-vent/definition.ts b/packages/nodes/src/box-vent/definition.ts index 53fd52d3e4..565abecbb0 100644 --- a/packages/nodes/src/box-vent/definition.ts +++ b/packages/nodes/src/box-vent/definition.ts @@ -176,6 +176,7 @@ const boxVentHandles: HandleDescriptor[] = [ */ export const boxVentDefinition: NodeDefinition = { kind: 'box-vent', + snapProfile: 'item', schemaVersion: 3, schema: BoxVentNode, category: 'structure', diff --git a/packages/nodes/src/box-vent/move-tool.tsx b/packages/nodes/src/box-vent/move-tool.tsx index 1c9ec30208..f3b40a8790 100644 --- a/packages/nodes/src/box-vent/move-tool.tsx +++ b/packages/nodes/src/box-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' @@ -86,9 +89,9 @@ export default function MoveBoxVentTool({ node }: { node: BoxVentNode }) { 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, }) } @@ -103,7 +106,8 @@ export default function MoveBoxVentTool({ node }: { node: BoxVentNode }) { 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') @@ -165,7 +169,7 @@ export default function MoveBoxVentTool({ node }: { node: BoxVentNode }) { 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/chimney/definition.ts b/packages/nodes/src/chimney/definition.ts index ea1d9a0135..308591d6b0 100644 --- a/packages/nodes/src/chimney/definition.ts +++ b/packages/nodes/src/chimney/definition.ts @@ -352,6 +352,7 @@ const WHITE_MATERIAL = { */ export const chimneyDefinition: NodeDefinition = { kind: 'chimney', + snapProfile: 'item', schemaVersion: 1, schema: ChimneyNode, category: 'structure', diff --git a/packages/nodes/src/chimney/move-tool.tsx b/packages/nodes/src/chimney/move-tool.tsx index b8e891c6ce..7ecaca64ff 100644 --- a/packages/nodes/src/chimney/move-tool.tsx +++ b/packages/nodes/src/chimney/move-tool.tsx @@ -13,6 +13,8 @@ import { import { consumePlacementDragRelease, copyCollectionIds, + isGridSnapActive, + isMagneticSnapActive, markToolCancelConsumed, triggerSFX, useEditor, @@ -128,9 +130,9 @@ const MoveChimneyTool = ({ node }: { node: ChimneyNode }) => { 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, }) } @@ -149,7 +151,11 @@ const MoveChimneyTool = ({ node }: { node: ChimneyNode }) => { const sx = Math.round(target.localX * 20) / 20 const sz = Math.round(target.localZ * 20) / 20 const prev = lastSnapRef.current - if (event.nativeEvent?.shiftKey !== true && (!prev || prev[0] !== sx || prev[1] !== sz)) { + if ( + isGridSnapActive() && + event.nativeEvent?.altKey !== true && + (!prev || prev[0] !== sx || prev[1] !== sz) + ) { triggerSFX('sfx:grid-snap') lastSnapRef.current = [sx, sz] } diff --git a/packages/nodes/src/column/__bench__/geometry.ts b/packages/nodes/src/column/__bench__/geometry.ts new file mode 100644 index 0000000000..bea7eb3adf --- /dev/null +++ b/packages/nodes/src/column/__bench__/geometry.ts @@ -0,0 +1,40 @@ +import { ColumnNode } from '@pascal-app/core' +import { createColumnShaftGeometry, createColumnSpiralGeometry } from '../geometry' +import { columnShaftLayout } from '../shape' + +// Run with bun packages/nodes/src/column/__bench__/geometry.ts. CPU construction only; not viewer FPS. +for (const scenario of ['round spiral', 'rectangular spiral', 'bulged fluted'] as const) { + const crossSection = scenario === 'rectangular spiral' ? 'rectangular' : 'round' + const node = ColumnNode.parse({ + crossSection, + shaftProfile: scenario === 'bulged fluted' ? 'bulged' : 'tapered', + shaftBulge: 0.12, + shaftSegmentCount: 32, + shaftDetail: scenario === 'bulged fluted' ? 'fluted' : 'spiral', + fluteCount: scenario === 'bulged fluted' ? 16 : 0, + spiralRibCount: scenario === 'bulged fluted' ? 0 : 24, + spiralTwist: 1, + }) + const { shaftHeight } = columnShaftLayout(node) + const start = performance.now() + let triangles = 0 + for (let i = 0; i < 30; i++) { + const geometries = [ + createColumnShaftGeometry(node, shaftHeight), + createColumnSpiralGeometry(node, shaftHeight), + ] + triangles = geometries.reduce( + (sum, geometry) => + sum + + (geometry ? (geometry.index?.count ?? geometry.getAttribute('position').count) / 3 : 0), + 0, + ) + for (const geometry of geometries) geometry?.dispose() + } + console.log({ + scenario, + meshes: scenario === 'bulged fluted' ? 1 : 2, + triangles, + millisecondsPerBuild: (performance.now() - start) / 30, + }) +} diff --git a/packages/nodes/src/column/bounds.ts b/packages/nodes/src/column/bounds.ts new file mode 100644 index 0000000000..fe8107edc2 --- /dev/null +++ b/packages/nodes/src/column/bounds.ts @@ -0,0 +1,157 @@ +import type { ColumnNode } from '@pascal-app/core' +import { + columnCapitalBlocks, + columnShaftLayout, + getShaftScaleAt, + getShaftSegmentCount, + getShaftTwistRadians, +} from './shape' + +/** Conservative, origin-centred XZ envelope shared by plan, collision and handles. */ +export function columnFootprintHalf(n: ColumnNode): { halfX: number; halfZ: number } { + if (n.source) { + const { min, max } = n.source.manifest.bounds + return { + halfX: Math.max(Math.abs(min[0]), Math.abs(max[0])), + halfZ: Math.max(Math.abs(min[2]), Math.abs(max[2])), + } + } + let halfX = 0, + halfZ = 0 + const include = (x: number, z = x) => { + halfX = Math.max(halfX, x) + halfZ = Math.max(halfZ, z) + } + const rectangular = n.crossSection === 'square' || n.crossSection === 'rectangular' + const block = (scale: number) => + include( + rectangular ? (n.width * scale) / 2 : n.radius * scale, + rectangular ? (n.depth * scale) / 2 : n.radius * scale, + ) + if (n.supportStyle !== 'vertical') { + const w = Math.max(0.04, n.braceWidth), + d = Math.max(0.04, n.braceDepth) + const bottom = Math.max(0.2, n.braceBottomSpread), + top = Math.max(0.2, n.braceTopSpread) + const plateX = n.bracePlateEnabled ? w * 0.95 : w / 2 + const plateZ = n.bracePlateEnabled ? d * 0.875 : d / 2 + const fork = n.supportStyle === 'y-frame' || n.supportStyle === 'v-frame' + const spatial = ['tripod', 'trestle', 'box-frame'].includes(n.supportStyle) + const span = fork + ? top + : n.supportStyle === 'a-frame' || n.supportStyle === 'portal-frame' || spatial + ? bottom + : Math.max(bottom, top) + include(span / 2 + plateX, (spatial ? top / 2 : 0) + plateZ) + if (n.supportStyle === 'a-frame' && n.bracePlateEnabled) include(w * 1.1, plateZ) + return { halfX, halfZ } + } + const layout = columnShaftLayout(n) + if (n.style === 'cluster') { + include(Math.max(n.radius * 0.78, n.width * 0.22) + Math.max(0.04, n.radius * 0.36)) + } else { + const count = getShaftSegmentCount(n) + for (let i = 0; i <= count; i++) { + const scale = getShaftScaleAt(n, i / count) + const yaw = getShaftTwistRadians(n, (i / count) * Math.max(0, count - 1)) + const c = Math.abs(Math.cos(yaw)), + s = Math.abs(Math.sin(yaw)) + if (rectangular) + include( + ((n.width * c + n.depth * s) * scale) / 2, + ((n.width * s + n.depth * c) * scale) / 2, + ) + else include(n.radius * scale) + } + } + if (n.style !== 'cluster' && n.edgeSoftness > 0) { + // Bevel rings also sample between the main profile sections. + const scale = Math.max(n.shaftStartScale, n.shaftEndScale) + Math.abs(n.shaftBulge) + if (rectangular && Math.abs(n.shaftTwistStep) > 0.001) + include((Math.hypot(n.width, n.depth) * scale) / 2) + else block(scale) + } + if (layout.baseHeight > 0) { + const w = (n.width * n.baseWidthScale) / 2, + d = (n.depth * n.baseDepthScale) / 2 + if (n.baseStyle === 'lotus' || n.baseStyle === 'ribbed-lotus') { + include(n.width * 0.64, n.depth * 0.64) + include( + Math.max(n.radius * n.baseWidthScale, w) * 0.86 + + (n.baseRibCount > 0 ? Math.max(0.01, n.width * 0.025) : 0), + ) + } else if (n.baseStyle === 'panelled-pedestal') { + const x = n.width * n.baseWidthScale, + z = n.depth * n.baseWidthScale + include(x * 0.51 + n.basePanelInset / 2, z * 0.51 + n.basePanelInset / 2) + include(n.width * 0.18) + } else if (n.baseStyle === 'square-plinth') + include(Math.max(w, n.width * 0.45), Math.max(d, n.depth * 0.45)) + else if (n.baseStyle === 'stepped-square') + include(Math.max(w, n.width * 0.25), Math.max(d, n.depth * 0.25)) + else if (n.baseStyle === 'round-rings') + include( + w * Math.max(1, n.baseRoundBandScale, n.baseNeckScale), + d * Math.max(1, n.baseRoundBandScale, n.baseNeckScale), + ) + else include(w, d) + if (n.baseCarvingLevel > 0 && ['base', 'all'].includes(n.carvingPlacement)) + include( + Math.max(n.radius * 1.04, Math.max(n.width, n.depth) / 2) + + layout.baseHeight * 0.14 + + 0.014, + ) + } + for (const cap of columnCapitalBlocks( + n, + layout.baseHeight + layout.shaftHeight, + layout.capitalHeight, + )) { + if (cap.kind === 'round') include(cap.radius!) + else if (cap.kind === 'column') block(cap.scale!) + else include(cap.width! / 2, cap.depth! / 2) + } + if (layout.capitalHeight > 0) { + if (['volute', 'ionic-volute'].includes(n.capitalStyle) && n.voluteCount > 0) + include(Math.max(n.width * 0.46, n.depth * 0.7) + n.voluteSize * 1.18) + if ( + ['leaf-carved', 'corinthian-leaf'].includes(n.capitalStyle) && + n.leafCount > 0 && + n.leafRows > 0 + ) + include( + Math.max(n.radius * 1.05, Math.max(n.width, n.depth) * 0.48) + + layout.capitalHeight * 0.14 + + 0.018, + ) + if (['south-indian-bracket', 'wood-bracket'].includes(n.capitalStyle) && n.pendantCount > 0) + include(Math.max(n.width, n.depth) * 0.56 + 0.035) + if ( + ['capital', 'all'].includes(n.carvingPlacement) && + (n.capitalBandCount > 0 || n.carvingLevel > 0 || n.capitalCarvingLevel > 0) + ) { + block(rectangular ? 1.28 : 1.24) + if (rectangular) + include( + n.width * 0.56 + Math.max(0.025, n.width / 7) / 2, + n.depth * 0.56 + Math.max(0.025, n.depth / 7) / 2, + ) + else include(n.radius * 1.24 + Math.max(0.012, Math.min(0.03, n.radius * 0.12))) + } + } + const shaftRadius = rectangular ? Math.hypot(n.width, n.depth) / 2 : n.radius + const maxScale = + Math.max(n.shaftStartScale, n.shaftEndScale) + + Math.max(0, n.shaftBulge) + + Math.max(0, -n.shaftBulge) + if (n.ringCount > 0) include(shaftRadius * (maxScale + 0.12)) + if (n.latheRingCount > 0 || n.shaftDetail === 'lathe-turned') + include(shaftRadius * (maxScale + 0.18)) + if (n.panelCount > 0 || n.style === 'dravidian-carved' || n.shaftDetail === 'panelled') + include(shaftRadius * maxScale + n.panelInsetDepth / 2 + Math.max(0.006, n.width * 0.014)) + if ((n.spiralRibCount > 0 || n.shaftDetail === 'spiral') && n.spiralTwist !== 0) + include(shaftRadius * maxScale + Math.max(0.012, n.radius * 0.06)) + if (n.lowerBandEnabled && ['shaft', 'all'].includes(n.carvingPlacement)) + include(shaftRadius * (maxScale + 0.12) + 0.012) + return { halfX, halfZ } +} diff --git a/packages/nodes/src/column/definition.test.ts b/packages/nodes/src/column/definition.test.ts index b47e2bf886..1dae8199f7 100644 --- a/packages/nodes/src/column/definition.test.ts +++ b/packages/nodes/src/column/definition.test.ts @@ -1,6 +1,10 @@ -import { describe, expect, test } from 'bun:test' -import { ColumnNode } from '@pascal-app/core' +import { afterEach, describe, expect, test } from 'bun:test' +import { ColumnNode, createSceneApi, useScene } from '@pascal-app/core' import { columnDefinition } from './definition' +import { columnEditPatch } from './edit-policy' + +const originalScene = useScene.getState() +afterEach(() => useScene.setState(originalScene, true)) describe('column definition', () => { test('keeps only user-owned handles for lean-to managed columns', () => { @@ -38,3 +42,26 @@ describe('column definition', () => { ]) }) }) + +test('round handle edits keep inspector dimensions in sync without rewriting the loaded node', () => { + const column = ColumnNode.parse({ radius: 0.3, width: 0.44, depth: 0.44 }) + const handles = + typeof columnDefinition.handles === 'function' + ? columnDefinition.handles(column) + : columnDefinition.handles! + const radius = handles.find((h) => h.kind === 'radial-resize')! + const scene = createSceneApi(useScene) + useScene.setState({ nodes: { [column.id]: column } }) + expect(radius.apply(column, 0.5, scene)).toMatchObject({ radius: 0.5, width: 1, depth: 1 }) + expect(column.width).toBe(0.44) +}) + +test('switching to square normalizes both axes, and managed posts reject layout edits', () => { + const column = ColumnNode.parse({ crossSection: 'rectangular', width: 1, depth: 2 }) + expect(columnEditPatch(column, { crossSection: 'square' })).toMatchObject({ width: 1, depth: 1 }) + const managed = { ...column, metadata: { managedByLeanTo: 'canopy', leanToRole: 'post' } } + expect( + columnEditPatch(managed, { width: 2, radius: 1, position: [1, 0, 0], rotation: 1 }), + ).toEqual({ rotation: 1 }) + expect(columnDefinition.capabilities.movable?.override?.({ node: managed })).toBeNull() +}) diff --git a/packages/nodes/src/column/definition.ts b/packages/nodes/src/column/definition.ts index a24e8d0148..ef13ea7810 100644 --- a/packages/nodes/src/column/definition.ts +++ b/packages/nodes/src/column/definition.ts @@ -14,6 +14,8 @@ import { collectStructuralGridAxes, resolveStructuralGridSnap, } from '../structural-grid/coordination' +import { columnFootprintHalf } from './bounds' +import { columnEditPatch, isManagedColumn } from './edit-policy' import { buildColumnFloorplan, computeColumnFloorplanLevelData } from './floorplan' import { columnResizeAffordance, columnRotateAffordance } from './floorplan-affordances' import { columnFloorplanMoveTarget } from './floorplan-move' @@ -67,7 +69,7 @@ function columnRadiusHandle(): HandleDescriptor { axis: 'x', min: MIN_COLUMN_RADIUS, currentValue: (n) => n.radius, - apply: (_n, newValue) => ({ radius: newValue }), + apply: (n, newValue) => columnEditPatch(n, { radius: newValue }), placement: { position: (n) => [n.radius + SIDE_HANDLE_OFFSET, n.height / 2, 0], }, @@ -89,7 +91,8 @@ function columnAxisHandle(axis: 'x' | 'z'): HandleDescriptor { anchor: 'center', min: axis === 'x' ? MIN_COLUMN_WIDTH : MIN_COLUMN_DEPTH, currentValue: (n) => (axis === 'x' ? n.width : n.depth), - apply: (_n, newValue) => (axis === 'x' ? { width: newValue } : { depth: newValue }), + apply: (n, newValue) => + columnEditPatch(n, axis === 'x' ? { width: newValue } : { depth: newValue }), placement: { position: (n) => { const half = axis === 'x' ? n.width / 2 : n.depth / 2 @@ -110,7 +113,7 @@ function columnUniformHandle(): HandleDescriptor { anchor: 'center', min: MIN_COLUMN_WIDTH, currentValue: (n) => n.width, - apply: (_n, newValue) => ({ width: newValue, depth: newValue }), + apply: (n, newValue) => columnEditPatch(n, { width: newValue, depth: newValue }), placement: { position: (n) => [n.width / 2 + SIDE_HANDLE_OFFSET, n.height / 2, 0], }, @@ -197,40 +200,6 @@ const STYLES_WITH_TOP_SPREAD = new Set([ 'v-frame', ]) -function isLeanToManagedColumn(node: ColumnNodeType): boolean { - const metadata = node.metadata - return ( - metadata !== null && - typeof metadata === 'object' && - !Array.isArray(metadata) && - metadata.managedByLeanTo !== undefined && - metadata.leanToRole === 'post' - ) -} - -// Resolve the column's visible XZ footprint half-extents per supportStyle -// + crossSection. Vertical supports use the shaft geometry (radius for -// round / octagonal / sixteen-sided, width/depth for square / rectangular); -// non-vertical supports fall back to the widest sensible brace bound so -// the rotation handle clears the splay. -function columnFootprintHalf(n: ColumnNodeType): { halfX: number; halfZ: number } { - if (n.source) return { halfX: n.width / 2, halfZ: n.depth / 2 } - if (n.supportStyle === 'vertical') { - if (ROUND_CROSS_SECTIONS.has(n.crossSection)) { - return { halfX: n.radius, halfZ: n.radius } - } - if (n.crossSection === 'square') { - return { halfX: n.width / 2, halfZ: n.width / 2 } - } - return { halfX: n.width / 2, halfZ: n.depth / 2 } - } - return { - halfX: - Math.max(n.width, n.braceWidth ?? 0, n.braceBottomSpread ?? 0, n.braceTopSpread ?? 0) / 2, - halfZ: Math.max(n.depth, n.braceDepth ?? 0) / 2, - } -} - // Whole-column rotation gizmo — same pattern as the elevator. Curved // two-headed arrow at the +X / +Z corner of the footprint, a guide ring // at the corner-diagonal radius on hover/drag. `apply` negates the @@ -315,7 +284,7 @@ function columnHandles(node: ColumnNodeType): HandleDescriptor[] // - square → uniform width+depth // - rectangular → width + depth (independent) const handles: HandleDescriptor[] = [] - const managedByLeanTo = isLeanToManagedColumn(node) + const managedByLeanTo = isManagedColumn(node) if (!managedByLeanTo) handles.push(columnHeightHandle()) if (node.supportStyle !== 'vertical') { handles.push(columnBraceHandle('x'), columnBraceHandle('z')) @@ -400,6 +369,14 @@ export const columnDefinition: NodeDefinition = { // mode-driven snapping the overhaul standardised). 2D move keeps using // `floorplanMoveTarget`, which wins the 2D move dispatch. movable: { + override: ({ node }) => + isManagedColumn(node as ColumnNodeType) + ? null + : { + axes: ['x', 'z'], + gridSnap: true, + groupMoveSnapPose: resolveColumnStructuralGridMoveSnap, + }, axes: ['x', 'z'], gridSnap: true, groupMoveSnapPose: resolveColumnStructuralGridMoveSnap, diff --git a/packages/nodes/src/column/edit-policy.ts b/packages/nodes/src/column/edit-policy.ts new file mode 100644 index 0000000000..3befe241c3 --- /dev/null +++ b/packages/nodes/src/column/edit-policy.ts @@ -0,0 +1,48 @@ +import type { ColumnNode } from '@pascal-app/core' + +export function isManagedColumn(node: ColumnNode): boolean { + return node.metadata?.managedByLeanTo !== undefined && node.metadata?.leanToRole === 'post' +} + +const managedFields = new Set([ + 'position', + 'height', + 'width', + 'depth', + 'radius', + 'crossSection', + 'baseStyle', + 'baseHeight', + 'baseWidthScale', + 'baseDepthScale', + 'slots', +]) + +/** Normalize edits, not loaded scenes: legacy independent dimensions remain readable. */ +export function columnEditPatch( + node: ColumnNode, + updates: Partial, +): Partial { + const patch = { ...updates } + if (!node.source && (patch.supportStyle ?? node.supportStyle) === 'vertical') { + const section = patch.crossSection ?? node.crossSection + if (['round', 'octagonal', 'sixteen-sided'].includes(section)) { + if (patch.radius !== undefined && patch.width === undefined) { + patch.width = patch.radius * 2 + patch.depth = patch.radius * 2 + } else if (patch.width !== undefined || patch.crossSection !== undefined) { + patch.radius = (patch.width ?? node.width) / 2 + patch.depth = patch.width ?? node.width + } + } else if ( + section === 'square' && + (patch.width !== undefined || patch.depth !== undefined || patch.crossSection !== undefined) + ) { + patch.width = patch.width ?? patch.depth ?? node.width + patch.depth = patch.width + patch.radius = patch.width / 2 + } + } + if (isManagedColumn(node)) for (const key of managedFields) delete patch[key] + return patch +} diff --git a/packages/nodes/src/column/floorplan-affordances.ts b/packages/nodes/src/column/floorplan-affordances.ts index 30c1f746df..aff418b905 100644 --- a/packages/nodes/src/column/floorplan-affordances.ts +++ b/packages/nodes/src/column/floorplan-affordances.ts @@ -8,6 +8,7 @@ import { import { isAngleSnapActive } from '@pascal-app/editor' import { rotateAffordanceDelta } from '../shared/rotate-affordance' import { rebuildScriptedSize } from '../shared/scripted-opening-handles' +import { columnEditPatch } from './edit-policy' import { planColumnEdit } from './hosted-resize' // Floor minimums — mirror the 3D handles in `column/definition.ts` so a @@ -64,6 +65,7 @@ export const columnResizeAffordance: FloorplanAffordance = { let lastPatch: Partial = {} const previewPatch = (patch: Partial) => { + patch = columnEditPatch(node, patch) if (!planColumnEdit(columnId, patch)) return lastPatch = patch useLiveNodeOverrides.getState().set(columnId, patch) diff --git a/packages/nodes/src/column/floorplan-move.ts b/packages/nodes/src/column/floorplan-move.ts index 92eb441c90..e35c93a50f 100644 --- a/packages/nodes/src/column/floorplan-move.ts +++ b/packages/nodes/src/column/floorplan-move.ts @@ -24,6 +24,7 @@ import { collectStructuralGridAxes, resolveStructuralGridSnap, } from '../structural-grid/coordination' +import { isManagedColumn } from './edit-policy' /** * 2D floor-plan move handler for column. Columns need the same footprint-edge @@ -35,6 +36,8 @@ import { */ export const columnFloorplanMoveTarget: FloorplanMoveTarget = ({ node, nodes }) => { + if (isManagedColumn(node)) + return { affectedIds: [], apply() {}, canCommit: () => false, commit() {} } const columnId = node.id as AnyNodeId const originalPosition: [number, number, number] = [...node.position] as [number, number, number] const rotationY = node.rotation ?? 0 @@ -47,6 +50,7 @@ export const columnFloorplanMoveTarget: FloorplanMoveTarget = ({ nod // Alignment candidates gathered once — scene is stable during the drag. const candidates = collectAlignmentAnchors(nodes, columnId) + const structuralGrids = collectStructuralGridAxes(nodes, node.parentId) const session: FloorplanMoveTargetSession = { affectedIds: [columnId], @@ -71,7 +75,7 @@ export const columnFloorplanMoveTarget: FloorplanMoveTarget = ({ nod ) const structuralSnap = isGridSnapActive() || isMagneticSnapActive() - ? resolveStructuralGridSnap(snapped, collectStructuralGridAxes(nodes, node.parentId)) + ? resolveStructuralGridSnap(snapped, structuralGrids) : null const coordinated = structuralSnap?.point ?? snapped const next: [number, number, number] = [coordinated[0], originalPosition[1], coordinated[1]] diff --git a/packages/nodes/src/column/floorplan.test.ts b/packages/nodes/src/column/floorplan.test.ts index dfca40a155..08cd876a70 100644 --- a/packages/nodes/src/column/floorplan.test.ts +++ b/packages/nodes/src/column/floorplan.test.ts @@ -1,7 +1,14 @@ import { describe, expect, test } from 'bun:test' import { ColumnNode, type GeometryContext, StructuralGridNode } from '@pascal-app/core' import { readFloorplanGeometryMetadata } from '@pascal-app/editor' -import { buildColumnFloorplan, computeColumnFloorplanLevelData } from './floorplan' +import { columnFootprintHalf } from './bounds' +import { columnDefinition } from './definition' +import { + buildColumnFloorplan, + computeColumnFloorplanLevelData, + getColumnFloorplanFootprint, +} from './floorplan' +import { columnFloorplanMoveTarget } from './floorplan-move' const context = { resolve: () => undefined, @@ -94,3 +101,31 @@ describe('buildColumnFloorplan', () => { expect(label && readFloorplanGeometryMetadata(label).annotationRole).toBe('column-center') }) }) + +test('managed posts expose rotation but no structural resize or move controls in plan', () => { + const column = ColumnNode.parse({ metadata: { managedByLeanTo: 'canopy', leanToRole: 'post' } }) + const geometry = buildColumnFloorplan(column, { ...context, viewState: { selected: true } }) + if (geometry?.kind !== 'group') throw new Error('Expected column plan') + expect(geometry.children.some((child) => child.kind === 'move-handle')).toBe(false) + expect(geometry.children.some((child) => child.kind === 'move-arrow')).toBe(false) + expect(geometry.children.some((child) => child.kind === 'rotate-arrow')).toBe(true) + const session = columnFloorplanMoveTarget({ node: column, nodes: { [column.id]: column } }) + expect(session.canCommit?.()).toBe(false) +}) + +test('disabled base and capital do not enlarge the plan or collision footprint', () => { + const column = ColumnNode.parse({ + radius: 0.2, + shaftStartScale: 1, + shaftEndScale: 1, + baseStyle: 'none', + capitalStyle: 'none', + baseWidthScale: 3, + capitalWidthScale: 3, + }) + expect(columnFootprintHalf(column)).toEqual({ halfX: 0.2, halfZ: 0.2 }) + const footprint = getColumnFloorplanFootprint(column) + expect(Math.max(...footprint.map(([x]) => x))).toBeCloseTo(0.2) + const floorPlaced = columnDefinition.capabilities.floorPlaced! + expect(floorPlaced.footprint!(column).dimensions).toEqual([0.4, column.height, 0.4]) +}) diff --git a/packages/nodes/src/column/floorplan.ts b/packages/nodes/src/column/floorplan.ts index 548ebc97b2..b72b94ed3a 100644 --- a/packages/nodes/src/column/floorplan.ts +++ b/packages/nodes/src/column/floorplan.ts @@ -12,6 +12,8 @@ import { collectStructuralGridAxes, resolveStructuralGridReference, } from '../structural-grid/coordination' +import { columnFootprintHalf } from './bounds' +import { isManagedColumn } from './edit-policy' import type { ColumnResizePayload } from './floorplan-affordances' // Offsets for the floor-plan selection arrows. Resize chevrons hug the @@ -69,7 +71,12 @@ export function buildColumnFloorplan( const isHighlighted = view?.highlighted ?? false const showSelectedChrome = isSelected || isHighlighted - const stroke = showSelectedChrome && palette ? palette.selectedStroke : '#374151' + const hovered = view?.hovered ?? false + const stroke = hovered + ? (palette?.wallHoverStroke ?? '#38bdf8') + : showSelectedChrome && palette + ? palette.selectedStroke + : '#374151' const fill = showSelectedChrome ? '#fed7aa' : '#9ca3af' // A scripted column draws its floor-plan image the way a catalog item does. const floorPlanUrl = scriptImages(node)?.floorPlan @@ -80,7 +87,7 @@ export function buildColumnFloorplan( // Transparent, not none: the body stays the hit target under the image. fill: floorPlanUrl ? 'transparent' : fill, stroke, - strokeWidth: showSelectedChrome ? 0.03 : 0.02, + strokeWidth: hovered ? 0.045 : showSelectedChrome ? 0.03 : 0.02, opacity: 0.92, metadata: floorplanGeometryMetadata({ annotationObstacle: 'bounds' }), } @@ -116,7 +123,7 @@ export function buildColumnFloorplan( if (showSelectedChrome) children.push({ ...body, fill: 'none', pointerEvents: 'none', metadata: undefined }) } - const { halfX, halfZ } = columnPlanHalfExtents(node) + const { halfX, halfZ } = columnFootprintHalf(node) const centerMarkHalf = Math.min(0.09, Math.max(0.035, Math.min(halfX, halfZ) * 0.45)) const centerX = node.position[0] const centerZ = node.position[2] @@ -185,10 +192,11 @@ export function buildColumnFloorplan( // `column/definition.ts`'s handle selection so what users can // manipulate in 3D top-view is the same in the floor plan. if (isSelected) { - children.push({ - kind: 'move-handle', - point: [node.position[0], node.position[2]], - }) + if (!isManagedColumn(node)) + children.push({ + kind: 'move-handle', + point: [node.position[0], node.position[2]], + }) const cx = node.position[0] const cz = node.position[2] @@ -241,6 +249,8 @@ export function buildColumnFloorplan( const halfBraceZ = Math.max(node.depth, node.braceDepth ?? 0) / 2 emitArrowAlong('brace-width', 'x', halfBraceX + RESIZE_ARROW_OFFSET) emitArrowAlong('brace-depth', 'z', halfBraceZ + RESIZE_ARROW_OFFSET) + } else if (isManagedColumn(node)) { + // The parent assembly owns this post's footprint. } else if (ROUND_CROSS_SECTIONS.has(node.crossSection)) { // Round shafts — single radius arrow. `radial-resize` factor 1 // (cursor delta = radius delta), so dragging the chevron @@ -298,40 +308,6 @@ export function getColumnFloorplanFootprint(node: ColumnNode): FloorplanPoint[] type PlanPoint = { x: number; y: number } -/** - * XZ half-extents for the column's plan footprint. Mirrors the 3D - * `columnFootprintHalf` so side-arrows + rotate-arrow ring the same - * bounding box the in-world handles use. Vertical supports read the - * shaft geometry; non-vertical supports use the widest brace bound so - * arrows clear the splay. - */ -function columnPlanHalfExtents(column: ColumnNode): { halfX: number; halfZ: number } { - if (column.source) return { halfX: column.width / 2, halfZ: column.depth / 2 } - if (column.supportStyle !== 'vertical') { - return { - halfX: - Math.max( - column.width, - column.braceWidth ?? 0, - column.braceBottomSpread ?? 0, - column.braceTopSpread ?? 0, - ) / 2, - halfZ: Math.max(column.depth, column.braceDepth ?? 0) / 2, - } - } - if ( - column.crossSection === 'round' || - column.crossSection === 'octagonal' || - column.crossSection === 'sixteen-sided' - ) { - return { halfX: column.radius, halfZ: column.radius } - } - if (column.crossSection === 'square') { - return { halfX: column.width / 2, halfZ: column.width / 2 } - } - return { halfX: column.width / 2, halfZ: column.depth / 2 } -} - function rotatePlanVector(x: number, y: number, rotation: number): [number, number] { const c = Math.cos(rotation) const s = Math.sin(rotation) @@ -359,88 +335,32 @@ function getRotatedRectanglePolygon( } function getColumnPlanFootprint(column: ColumnNode): PlanPoint[] { - const center: PlanPoint = { x: column.position[0], y: column.position[2] } - - // Brace-support columns: rotated rectangle spanning the base spread. + const { halfX, halfZ } = columnFootprintHalf(column) if ( - column.supportStyle === 'a-frame' || - column.supportStyle === 'y-frame' || - column.supportStyle === 'v-frame' || - column.supportStyle === 'x-brace' || - column.supportStyle === 'k-brace' || - column.supportStyle === 'single-strut' || - column.supportStyle === 'tripod' || - column.supportStyle === 'trestle' || - column.supportStyle === 'portal-frame' || - column.supportStyle === 'box-frame' + column.supportStyle === 'vertical' && + column.style !== 'cluster' && + ROUND_CROSS_SECTIONS.has(column.crossSection) && + column.baseStyle === 'none' && + ['none', 'simple', 'simple-slab'].includes(column.capitalStyle) && + column.panelCount === 0 && + column.shaftDetail !== 'panelled' ) { - const width = Math.max( - column.supportStyle === 'a-frame' || - column.supportStyle === 'x-brace' || - column.supportStyle === 'k-brace' || - column.supportStyle === 'single-strut' || - column.supportStyle === 'tripod' || - column.supportStyle === 'trestle' || - column.supportStyle === 'portal-frame' || - column.supportStyle === 'box-frame' - ? (column.braceBottomSpread ?? 1.2) - : 0, - column.braceTopSpread ?? - (column.supportStyle === 'y-frame' || - column.supportStyle === 'v-frame' || - column.supportStyle === 'x-brace' || - column.supportStyle === 'k-brace' || - column.supportStyle === 'single-strut' || - column.supportStyle === 'tripod' || - column.supportStyle === 'trestle' || - column.supportStyle === 'portal-frame' || - column.supportStyle === 'box-frame' - ? 1 - : 0), - (column.braceWidth ?? column.width) * 2, - ) - const depth = Math.max( - column.supportStyle === 'tripod' || - column.supportStyle === 'trestle' || - column.supportStyle === 'box-frame' - ? (column.braceTopSpread ?? 1) - : 0, - column.braceDepth ?? column.depth, - 0.08, - ) - return getRotatedRectanglePolygon(center, width, depth, -column.rotation) + const segments = + column.crossSection === 'octagonal' ? 8 : column.crossSection === 'sixteen-sided' ? 16 : 32 + return Array.from({ length: segments }, (_, i) => { + const angle = (i * Math.PI * 2) / segments + const [x, z] = rotatePlanVector( + Math.sin(angle) * halfX, + Math.cos(angle) * halfZ, + -column.rotation, + ) + return { x: column.position[0] + x, y: column.position[2] + z } + }) } - - // Standalone column: shaft profile expanded for base + capital. - const isRound = - column.crossSection === 'round' || - column.crossSection === 'octagonal' || - column.crossSection === 'sixteen-sided' - const shaftWidth = isRound ? column.radius * 2 : column.width - const shaftDepth = isRound ? column.radius * 2 : column.depth - const width = Math.max( - shaftWidth, - column.width * column.baseWidthScale, - column.width * column.capitalWidthScale, + return getRotatedRectanglePolygon( + { x: column.position[0], y: column.position[2] }, + halfX * 2, + halfZ * 2, + -column.rotation, ) - const depth = Math.max( - shaftDepth, - column.depth * column.baseDepthScale, - column.depth * column.capitalDepthScale, - ) - - if (column.crossSection === 'square' || column.crossSection === 'rectangular') { - return getRotatedRectanglePolygon(center, width, depth, -column.rotation) - } - - const segmentCount = - column.crossSection === 'octagonal' ? 8 : column.crossSection === 'sixteen-sided' ? 16 : 32 - - return Array.from({ length: segmentCount }, (_, index) => { - const angle = (index / segmentCount) * Math.PI * 2 - const localX = Math.cos(angle) * (width / 2) - const localY = Math.sin(angle) * (depth / 2) - const [offsetX, offsetY] = rotatePlanVector(localX, localY, -column.rotation) - return { x: center.x + offsetX, y: center.y + offsetY } - }) } diff --git a/packages/nodes/src/column/geometry-budget.test.ts b/packages/nodes/src/column/geometry-budget.test.ts new file mode 100644 index 0000000000..dedcd3e729 --- /dev/null +++ b/packages/nodes/src/column/geometry-budget.test.ts @@ -0,0 +1,22 @@ +import { expect, test } from 'bun:test' +import { ColumnNode } from '@pascal-app/core' +import { createColumnShaftGeometry, createColumnSpiralGeometry } from './geometry' + +test('curved fluted shafts and dense spiral decorations stay within triangle budgets', () => { + const node = ColumnNode.parse({ + shaftProfile: 'bulged', + shaftBulge: 0.12, + shaftSegmentCount: 32, + shaftDetail: 'fluted', + fluteCount: 16, + }) + const shaft = createColumnShaftGeometry(node, 2) + expect(shaft.index!.count / 3).toBeLessThan(10000) + const spiral = createColumnSpiralGeometry( + { ...node, shaftDetail: 'spiral', fluteCount: 0, spiralRibCount: 24, spiralTwist: 1 }, + 2, + )! + expect((spiral.index?.count ?? spiral.getAttribute('position').count) / 3).toBeLessThan(19000) + shaft.dispose() + spiral.dispose() +}) diff --git a/packages/nodes/src/column/geometry.ts b/packages/nodes/src/column/geometry.ts new file mode 100644 index 0000000000..cbfa216b20 --- /dev/null +++ b/packages/nodes/src/column/geometry.ts @@ -0,0 +1,422 @@ +import type { ColumnNode } from '@pascal-app/core' +import { BufferGeometry, Curve, Float32BufferAttribute, Shape, TubeGeometry, Vector3 } from 'three' +import { mergeGeometries, toCreasedNormals } from 'three/examples/jsm/utils/BufferGeometryUtils.js' +import { getSegments, getShaftScaleAt, getShaftSegmentCount, getShaftTwistRadians } from './shape' + +function mergeOwned(parts: BufferGeometry[]) { + if (!parts.length) return null + const mixed = parts.some((part) => part.index) && parts.some((part) => !part.index) + const compatible = mixed ? parts.map((part) => (part.index ? part.toNonIndexed() : part)) : parts + try { + return mergeGeometries(compatible) + } finally { + for (const part of new Set([...parts, ...compatible])) part.dispose() + } +} + +export function createColumnShaftGeometry( + node: Pick< + ColumnNode, + | 'crossSection' + | 'radius' + | 'width' + | 'depth' + | 'shaftProfile' + | 'shaftTaper' + | 'shaftBulge' + | 'shaftStartScale' + | 'shaftEndScale' + | 'shaftSegmentCount' + | 'shaftTwistStep' + | 'shaftCornerRadius' + | 'edgeSoftness' + | 'fluteCount' + | 'fluteWidth' + | 'fluteDepth' + | 'shaftDetail' + >, + height: number, + range = { start: 0, end: 1, outset: 0 }, +) { + const count = getShaftSegmentCount(node) + const rectangular = node.crossSection === 'square' || node.crossSection === 'rectangular' + const fluteCount = + node.crossSection === 'round' + ? Math.max(node.fluteCount, node.shaftDetail === 'fluted' ? 16 : 0) + : 0 + const radialSegments = fluteCount ? Math.max(32, fluteCount * 6) : getSegments(node) + const shape = new Shape() + if (rectangular) { + const x = node.width / 2, + z = node.depth / 2 + const r = Math.min(Math.max(0, node.shaftCornerRadius), Math.min(node.width, node.depth) * 0.45) + shape.moveTo(-x + r, -z) + shape.lineTo(x - r, -z) + if (r > 0) shape.absarc(x - r, -z + r, r, -Math.PI / 2, 0, false) + shape.lineTo(x, z - r) + if (r > 0) shape.absarc(x - r, z - r, r, 0, Math.PI / 2, false) + shape.lineTo(-x + r, z) + if (r > 0) shape.absarc(-x + r, z - r, r, Math.PI / 2, Math.PI, false) + shape.lineTo(-x, -z + r) + if (r > 0) shape.absarc(-x + r, -z + r, r, Math.PI, Math.PI * 1.5, false) + shape.closePath() + } + const contour = rectangular + ? shape + .getPoints(5) + .filter((point, i, points) => i === 0 || point.distanceTo(points[i - 1]!) > 1e-8) + : Array.from({ length: radialSegments }, (_, i) => { + const angle = (i * Math.PI * 2) / radialSegments + return { x: Math.sin(angle) * node.radius, y: Math.cos(angle) * node.radius } + }).reverse() + const first = contour[0]!, + last = contour.at(-1)! + if (Math.hypot(first.x - last.x, first.y - last.y) < 1e-8) contour.pop() + const positions: number[] = [], + uvs: number[] = [], + indices: number[] = [] + const perimeter = [0] + for (let j = 0; j < contour.length; j++) { + const a = contour[j]!, + b = contour[(j + 1) % contour.length]! + perimeter.push(perimeter[j]! + Math.hypot(b.x - a.x, b.y - a.y)) + } + const ringSize = contour.length + 1 + const endScale = + Math.min(getShaftScaleAt(node, range.start), getShaftScaleAt(node, range.end)) + range.outset + const bevel = Math.min( + Math.max(0, node.edgeSoftness), + height * 0.35, + (rectangular ? Math.min(node.width, node.depth) / 2 : node.radius) * endScale * 0.35, + ) + const levels = Array.from({ length: count + 1 }, (_, i) => (height * i) / count) + if (bevel > 0) { + for (let step = 1; step <= 4; step++) levels.push(bevel * (1 - Math.cos((step * Math.PI) / 8))) + // Keep top-edge ray hits stable for objects placed on the pillar. + for (let step = 1; step <= 12; step++) + levels.push(height - bevel * (1 - Math.cos((step * Math.PI) / 24))) + } + const rows = [...new Set(levels)].sort((a, b) => a - b) + const lastRow = rows.length - 1 + for (let i = 0; i <= lastRow; i++) { + const t = range.start + ((range.end - range.start) * rows[i]!) / height, + scale = getShaftScaleAt(node, t) + range.outset + const yaw = getShaftTwistRadians(node, t * Math.max(0, count - 1)) + for (let j = 0; j <= contour.length; j++) { + const p = contour[j % contour.length]! + const groove = fluteCount ? fluteInset(node, Math.atan2(p.y, p.x), scale) : 0 + const radialScale = scale - groove / node.radius + const distanceToEnd = Math.min(rows[i]!, height - rows[i]!) + const inset = + distanceToEnd < bevel + ? bevel - Math.sqrt(Math.max(0, bevel ** 2 - (bevel - distanceToEnd) ** 2)) + : 0 + const length = Math.hypot(p.x, p.y) + const softenedScale = Math.max(0.001, radialScale - inset / length) + positions.push( + softenedScale * (p.x * Math.cos(yaw) + p.y * Math.sin(yaw)), + rows[i]!, + softenedScale * (-p.x * Math.sin(yaw) + p.y * Math.cos(yaw)), + ) + uvs.push(perimeter[j]! * scale, rows[i]!) + if (i < lastRow && j < contour.length) { + const a = i * ringSize + j, + b = a + ringSize + indices.push(a, b, a + 1, a + 1, b, b + 1) + } + } + } + // Separate cap vertices keep the rim sharp and planar UVs in metres. + for (const row of [0, lastRow]) { + const start = positions.length / 3 + positions.push(0, row === 0 ? 0 : height, 0) + uvs.push(0, 0) + for (let j = 0; j < contour.length; j++) { + const offset = (row * ringSize + j) * 3 + positions.push(positions[offset]!, positions[offset + 1]!, positions[offset + 2]!) + uvs.push(positions[offset]!, positions[offset + 2]!) + const a = start + 1 + j, + b = start + 1 + ((j + 1) % contour.length) + indices.push(...(row === 0 ? [start, a, b] : [start, b, a])) + } + } + const geometry = new BufferGeometry() + geometry.setAttribute('position', new Float32BufferAttribute(positions, 3)) + geometry.setAttribute('uv', new Float32BufferAttribute(uvs, 2)) + geometry.setAttribute('uv2', geometry.getAttribute('uv').clone()) + geometry.setIndex(indices) + geometry.computeVertexNormals() + const normals = geometry.getAttribute('normal') + for (let i = 0; i <= lastRow; i++) { + const a = i * ringSize, + b = a + contour.length + const normal = new Vector3() + .fromBufferAttribute(normals, a) + .add(new Vector3().fromBufferAttribute(normals, b)) + .normalize() + normals.setXYZ(a, normal.x, normal.y, normal.z) + normals.setXYZ(b, normal.x, normal.y, normal.z) + } + if (node.crossSection !== 'round') { + const creased = toCreasedNormals(geometry, 0.2) + geometry.dispose() + return creased + } + return geometry +} + +type ShaftSurfaceNode = Pick< + ColumnNode, + | 'radius' + | 'width' + | 'depth' + | 'crossSection' + | 'shaftProfile' + | 'shaftTaper' + | 'shaftBulge' + | 'shaftStartScale' + | 'shaftEndScale' + | 'shaftSegmentCount' + | 'shaftTwistStep' + | 'shaftCornerRadius' + | 'fluteCount' + | 'fluteWidth' + | 'fluteDepth' + | 'shaftDetail' +> + +function fluteInset( + node: Pick, + angle: number, + scale: number, +) { + const count = Math.max(node.fluteCount, node.shaftDetail === 'fluted' ? 16 : 0) + if (!count) return 0 + const phase = Math.atan2(Math.sin(angle * count), Math.cos(angle * count)) / count + const halfWidth = Math.min(node.fluteWidth / 2, ((node.radius * scale * Math.PI) / count) * 0.8) + const distance = Math.abs(phase) * node.radius * scale + if (distance >= halfWidth) return 0 + return ( + (Math.min(node.fluteDepth, node.radius * scale * 0.35) * + (1 + Math.cos((Math.PI * distance) / halfWidth))) / + 2 + ) +} + +/** Interpolate the same sections as the shaft so details stay attached between rings. */ +function shaftPoint(node: ShaftSurfaceNode, height: number, angle: number, t: number) { + const count = getShaftSegmentCount(node), + row = Math.min(count - 1, Math.floor(t * count)) + const pointAt = (i: number) => { + const scale = getShaftScaleAt(node, i / count) + const c = Math.cos(angle), + s = Math.sin(angle) + let radius = node.radius + if (node.crossSection === 'square' || node.crossSection === 'rectangular') { + const x = node.width / 2, + z = node.depth / 2 + radius = Math.min(x / Math.max(1e-9, Math.abs(c)), z / Math.max(1e-9, Math.abs(s))) + const corner = Math.min(node.shaftCornerRadius, Math.min(node.width, node.depth) * 0.45) + if (Math.abs(radius * c) > x - corner && Math.abs(radius * s) > z - corner) { + const dot = Math.abs(c) * (x - corner) + Math.abs(s) * (z - corner) + radius = + dot + + Math.sqrt(Math.max(0, dot * dot - (x - corner) ** 2 - (z - corner) ** 2 + corner ** 2)) + } + } else { + const segments = getSegments(node) + const phase = + (((angle - Math.PI / 2) % ((2 * Math.PI) / segments)) + (2 * Math.PI) / segments) % + ((2 * Math.PI) / segments) + if (node.crossSection !== 'round') + radius *= Math.cos(Math.PI / segments) / Math.cos(phase - Math.PI / segments) + } + const distance = + radius * scale - (node.crossSection === 'round' ? fluteInset(node, angle, scale) : 0) + const yaw = getShaftTwistRadians(node, (i / count) * Math.max(0, count - 1)) + return new Vector3( + Math.cos(angle - yaw) * distance, + (height * i) / count, + Math.sin(angle - yaw) * distance, + ) + } + return pointAt(row).lerp(pointAt(row + 1), t * count - row) +} + +class SurfaceCurve extends Curve { + constructor(private readonly sample: (t: number) => Vector3) { + super() + } + getPoint(t: number, target = new Vector3()) { + return target.copy(this.sample(t)) + } +} + +function surfaceTube(sample: (t: number) => Vector3, steps: number, radius: number) { + const curve = new SurfaceCurve(sample) + const geometry = new TubeGeometry(curve, steps, radius, 6, false) + const uv = geometry.getAttribute('uv'), + length = curve.getLength() + for (let i = 0; i < uv.count; i++) + uv.setXY(i, uv.getX(i) * length, uv.getY(i) * Math.PI * 2 * radius) + geometry.setAttribute('uv2', uv.clone()) + return geometry +} + +export function createColumnSpiralGeometry( + node: ShaftSurfaceNode & Pick, + height: number, +) { + const count = Math.min(Math.max(node.spiralRibCount, node.shaftDetail === 'spiral' ? 12 : 0), 32) + if (!count || !node.spiralTwist || height <= 0) return null + const parts: BufferGeometry[] = [] + for (let i = 0; i < count; i++) { + parts.push( + surfaceTube( + (t) => + shaftPoint( + node, + height, + (i / count) * Math.PI * 2 + t * node.spiralTwist * Math.PI * 2, + 0.02 + t * 0.96, + ), + Math.max(32, Math.ceil(Math.abs(node.spiralTwist) * 32), getShaftSegmentCount(node) * 2), + Math.max(0.012, node.radius * 0.06), + ), + ) + } + return mergeOwned(parts) +} + +export function createColumnPanelGeometry(node: ColumnNode, height: number) { + const count = Math.max( + node.panelCount, + node.style === 'dravidian-carved' || node.shaftDetail === 'panelled' ? 3 : 0, + ) + if (!count || height <= 0) return null + const parts: BufferGeometry[] = [] + const halfHeight = Math.min(0.42, height / Math.max(4, count + 2)) / height / 2 + const rail = Math.max(0.006, node.width * 0.014) + const halfAngle = 0.33 + for (let row = 0; row < count; row++) { + const center = (row + 1) / (count + 1) + for (let face = 0; face < 4; face++) { + const angle = (face * Math.PI) / 2 + const line = (a: number, b: number, c: number, d: number) => { + parts.push( + surfaceTube( + (t) => { + const point = shaftPoint(node, height, angle + a + (c - a) * t, b + (d - b) * t) + const radial = new Vector3(point.x, 0, point.z).normalize() + return point.addScaledVector(radial, Math.max(0, node.panelInsetDepth) / 2) + }, + Math.max(16, getShaftSegmentCount(node) * 2), + rail, + ), + ) + } + line(-halfAngle, center - halfHeight, halfAngle, center - halfHeight) + line(-halfAngle, center + halfHeight, halfAngle, center + halfHeight) + line(-halfAngle, center - halfHeight, -halfAngle, center + halfHeight) + line(halfAngle, center - halfHeight, halfAngle, center + halfHeight) + if (node.panelShape === 'diamond') { + line(0, center + halfHeight * 0.8, halfAngle * 0.8, center) + line(halfAngle * 0.8, center, 0, center - halfHeight * 0.8) + line(0, center - halfHeight * 0.8, -halfAngle * 0.8, center) + line(-halfAngle * 0.8, center, 0, center + halfHeight * 0.8) + } else if (node.panelShape === 'arched') { + parts.push( + surfaceTube( + (t) => + shaftPoint( + node, + height, + angle + Math.cos(t * Math.PI) * halfAngle * 0.8, + center + Math.sin(t * Math.PI) * halfHeight * 0.8, + ), + 32, + rail, + ), + ) + } + } + } + return mergeOwned(parts) +} + +export function createColumnBandGeometry(node: ColumnNode, height: number) { + const parts: BufferGeometry[] = [] + const band = (t: number, thickness: number, outset: number) => { + const start = Math.max(0, t - thickness / height / 2) + const end = Math.min(1, t + thickness / height / 2) + const geometry = createColumnShaftGeometry( + { ...node, fluteCount: 0, shaftDetail: 'none' }, + (end - start) * height, + { start, end, outset }, + ) + geometry.translate(0, start * height, 0) + parts.push(geometry) + } + const ringSpread = Math.min(0.45, Math.max(0.04, node.ringSpread)) + for (let i = 0; i < node.ringCount; i++) { + const pairCount = Math.ceil(node.ringCount / 2) + const pairT = pairCount <= 1 ? 0 : Math.floor(i / 2) / (pairCount - 1) + const offset = Math.min(0.48, 0.06 + pairT * Math.max(0, ringSpread - 0.06)) + const oneSide = Math.min( + 0.48, + 0.06 + (i / Math.max(1, node.ringCount - 1)) * Math.max(0, ringSpread - 0.06), + ) + const t = + node.ringPlacement === 'even' + ? (i + 1) / (node.ringCount + 1) + : node.ringPlacement === 'top' + ? 1 - oneSide + : node.ringPlacement === 'bottom' + ? oneSide + : i % 2 + ? 1 - offset + : offset + band(t, Math.min(node.ringThickness, height / Math.max(8, node.ringCount * 3)), 0.12) + } + const count = Math.max(node.latheRingCount, node.shaftDetail === 'lathe-turned' ? 8 : 0) + for (let i = 0; i < count; i++) { + const offset = Math.min(0.48, 0.1 + Math.floor(i / 2) * 0.04) + const oneSide = Math.min(0.48, 0.08 + i * 0.04) + const t = + node.latheRingSpacing === 'even' + ? (i + 1) / (count + 1) + : node.latheRingSpacing === 'top' + ? 1 - oneSide + : node.latheRingSpacing === 'bottom' + ? oneSide + : i % 2 + ? 1 - offset + : offset + band(t, Math.min(0.04, height / Math.max(12, count * 3)), 0.1 + (i % 2) * 0.08) + } + if (node.lowerBandEnabled && ['shaft', 'all'].includes(node.carvingPlacement)) { + const size = Math.min(node.lowerBandHeight, height * 0.35) + band(0.12 + size / height / 2, size, 0.12) + const ribs = Math.max(6, node.lowerBandCarvingLevel * 6) + for (let i = 0; i < ribs; i++) { + parts.push( + surfaceTube( + (t) => { + const point = shaftPoint( + node, + height, + (i / ribs) * Math.PI * 2, + 0.12 + (size / height) * (0.19 + t * 0.62), + ) + point.x *= 1 + 0.12 / getShaftScaleAt(node, point.y / height) + point.z *= 1 + 0.12 / getShaftScaleAt(node, point.y / height) + return point + }, + 24, + 0.012, + ), + ) + } + } + return mergeOwned(parts) +} diff --git a/packages/nodes/src/column/hosted-resize.ts b/packages/nodes/src/column/hosted-resize.ts index ecefc05c4c..3c9914d162 100644 --- a/packages/nodes/src/column/hosted-resize.ts +++ b/packages/nodes/src/column/hosted-resize.ts @@ -1,12 +1,23 @@ -import { type AnyNode, type AnyNodeId, createSceneApi, useScene } from '@pascal-app/core' +import { + type AnyNode, + type AnyNodeId, + type ColumnNode, + createSceneApi, + useScene, +} from '@pascal-app/core' import { planHostedEdit } from '../shared/hosted-resize' +import { columnEditPatch } from './edit-policy' export const columnHostedPolicy = { + localSurfaces: true, host: (node: AnyNode) => node.type === 'column', child: (_node: AnyNode) => true, } -export function planColumnEdit(id: AnyNodeId, patch: Partial) { +export function planColumnEdit(id: AnyNodeId, patch: Partial) { + const node = useScene.getState().nodes[id] + if (node?.type !== 'column') return null + patch = columnEditPatch(node, patch) return planHostedEdit( createSceneApi(useScene), (scene) => scene.update(id, patch), diff --git a/packages/nodes/src/column/inspector-highlight.tsx b/packages/nodes/src/column/inspector-highlight.tsx new file mode 100644 index 0000000000..44e1b8c775 --- /dev/null +++ b/packages/nodes/src/column/inspector-highlight.tsx @@ -0,0 +1,213 @@ +'use client' + +import type { AnyNodeId, ColumnNode, ColumnSlotId } from '@pascal-app/core' +import { OVERLAY_LAYER, useViewer } from '@pascal-app/viewer' +import { type ReactNode, type RefObject, useEffect, useMemo, useRef } from 'react' +import { Box3, BufferGeometry, type Group, LineSegments, Matrix4, Mesh, Vector3 } from 'three' +import { LineBasicNodeMaterial, MeshBasicNodeMaterial } from 'three/webgpu' +import { create } from 'zustand' + +type Target = { part: ColumnSlotId | 'all'; axis?: 'x' | 'y' | 'z' } +type Highlight = Target & { owner: symbol; nodeId: AnyNodeId } +export const useColumnInspectorHighlight = create<{ active: Highlight | null }>(() => ({ + active: null, +})) + +export function clearColumnInspectorHighlight(owner: symbol) { + const active = useColumnInspectorHighlight.getState().active + if (active?.owner !== owner) return + useColumnInspectorHighlight.setState({ active: null }) + if (useViewer.getState().hoveredId === active.nodeId) useViewer.getState().setHoveredId(null) +} + +export function setColumnInspectorHighlight(owner: symbol, nodeId: AnyNodeId, target: Target) { + const previous = useColumnInspectorHighlight.getState().active + if ( + previous?.owner === owner && + previous.nodeId === nodeId && + previous.part === target.part && + previous.axis === target.axis + ) + return + useColumnInspectorHighlight.setState({ active: { owner, nodeId, ...target } }) + useViewer.getState().setHoveredId(nodeId) +} + +function targetFor(element: EventTarget | null): Target | null { + if (!(element instanceof Element)) return null + const region = element.closest('[data-column-part]') + if (!region) return null + const part = region.dataset.columnPart + if ( + part !== 'all' && + part !== 'base' && + part !== 'capital' && + part !== 'shaft' && + part !== 'frame' + ) + return null + const axis = element.closest('[data-column-axis]')?.dataset.columnAxis + return { part, axis: axis === 'x' || axis === 'y' || axis === 'z' ? axis : undefined } +} + +export function ColumnInspectorHover({ + nodeId, + children, +}: { + nodeId: AnyNodeId + children: ReactNode +}) { + const owner = useMemo(() => Symbol(`column-inspector:${nodeId}`), [nodeId]) + const pointer = useRef(null), + focus = useRef(null) + const update = () => { + const target = pointer.current ?? focus.current + if (target) setColumnInspectorHighlight(owner, nodeId, target) + else clearColumnInspectorHighlight(owner) + } + useEffect(() => { + pointer.current = null + focus.current = null + const clear = () => { + pointer.current = null + focus.current = null + clearColumnInspectorHighlight(owner) + } + const onKeyDown = (event: KeyboardEvent) => { + if (event.key === 'Escape') clear() + } + window.addEventListener('blur', clear) + window.addEventListener('keydown', onKeyDown) + return () => { + window.removeEventListener('blur', clear) + window.removeEventListener('keydown', onKeyDown) + clear() + } + }, [owner]) + return ( +
{ + pointer.current = targetFor(event.target) + update() + }} + onPointerCancel={() => { + pointer.current = null + focus.current = null + clearColumnInspectorHighlight(owner) + }} + onPointerLeave={() => { + pointer.current = null + update() + }} + onFocusCapture={(event) => { + focus.current = targetFor(event.target) + update() + }} + onBlurCapture={(event) => { + focus.current = event.currentTarget.contains(event.relatedTarget) + ? targetFor(event.relatedTarget) + : null + update() + }} + > + {children} +
+ ) +} + +export function ColumnInspectorOverlay({ + nodeId, + body, + node, + position, + rotation, +}: { + nodeId: AnyNodeId + body: RefObject + node: ColumnNode + position: [number, number, number] + rotation: number +}) { + const overlay = useRef(null) + const active = useColumnInspectorHighlight((state) => + state.active?.nodeId === nodeId ? state.active : null, + ) + useEffect(() => { + const source = body.current, + target = overlay.current + if (!active || !source || !target || node.id !== active.nodeId) return + const fill = new MeshBasicNodeMaterial({ + color: '#38bdf8', + transparent: true, + opacity: 0.28, + depthTest: false, + depthWrite: false, + }) + const lineMaterial = new LineBasicNodeMaterial({ + color: '#0284c7', + depthTest: false, + depthWrite: false, + }) + source.updateWorldMatrix(true, true) + const inverse = new Matrix4().copy(source.matrixWorld).invert() + const bounds = new Box3() + source.traverse((object) => { + if (!(object instanceof Mesh) || !object.visible) return + if (active.part !== 'all' && object.userData.slotId !== active.part) return + const matrix = new Matrix4().multiplyMatrices(inverse, object.matrixWorld) + const mesh = new Mesh(object.geometry, fill) + mesh.matrixAutoUpdate = false + mesh.matrix.copy(matrix) + mesh.layers.set(OVERLAY_LAYER) + mesh.raycast = () => {} + mesh.userData.pascalExport = 'strip' + target.add(mesh) + object.geometry.computeBoundingBox() + if (object.geometry.boundingBox) + bounds.union(object.geometry.boundingBox.clone().applyMatrix4(matrix)) + }) + let dimension: BufferGeometry | undefined + if (active.axis && !bounds.isEmpty()) { + const axis = active.axis, + a = bounds.min.clone(), + b = bounds.min.clone() + b[axis] = bounds.max[axis] + const offset = Math.max(0.06, bounds.getSize(new Vector3()).length() * 0.04) + const side = axis === 'x' ? 'z' : 'x' + a[side] -= offset + b[side] -= offset + const tick = new Vector3() + tick[side] = offset * 0.3 + dimension = new BufferGeometry().setFromPoints([ + a, + b, + a.clone().sub(tick), + a.clone().add(tick), + b.clone().sub(tick), + b.clone().add(tick), + ]) + const line = new LineSegments(dimension, lineMaterial) + line.layers.set(OVERLAY_LAYER) + line.raycast = () => {} + line.userData.pascalExport = 'strip' + target.add(line) + } + return () => { + target.clear() + dimension?.dispose() + fill.dispose() + lineMaterial.dispose() + } + }, [active, body, node]) + return ( + + ) +} diff --git a/packages/nodes/src/column/paint.test.tsx b/packages/nodes/src/column/paint.test.tsx new file mode 100644 index 0000000000..205e6be0bc --- /dev/null +++ b/packages/nodes/src/column/paint.test.tsx @@ -0,0 +1,156 @@ +import { expect, test } from 'bun:test' +import { + COLUMN_PRESETS, + ColumnNode, + clearSceneHistory, + columnSlots, + sceneRegistry, + useScene, +} from '@pascal-app/core' +import { useViewer } from '@pascal-app/viewer' +import { Mesh, MeshBasicMaterial, type MeshStandardMaterial } from 'three' +import { installMountedScene, mount } from '../__tests__/harness' +import { columnPaint } from './paint' +import { columnPresetUpdates } from './presets' +import { ColumnRenderer } from './renderer' + +installMountedScene() +const paint = { + preset: 'custom' as const, + properties: { + color: '#da3210', + roughness: 0.5, + metalness: 0, + opacity: 1, + transparent: false, + side: 'front' as const, + }, +} +const cases = [ + ...Object.entries(COLUMN_PRESETS).map(([name, preset]) => ({ + name, + node: ColumnNode.parse(preset), + })), + ...['fluted', 'spiral', 'panelled', 'lathe-turned'].map((shaftDetail) => ({ + name: shaftDetail, + node: ColumnNode.parse({ + shaftDetail, + shaftProfile: 'bulged', + fluteCount: shaftDetail === 'fluted' ? 16 : 0, + spiralTwist: 1, + ringCount: 4, + lowerBandEnabled: true, + baseStyle: 'ribbed-lotus', + capitalStyle: 'corinthian-leaf', + }), + })), +] +for (const { name, node } of cases) { + test(`${name}: every rendered surface has UVs and an isolated, reversible paint slot`, async () => { + useViewer.setState({ textures: true }) + useScene.setState({ nodes: { [node.id]: node }, materials: {} }) + await mount() + const root = sceneRegistry.nodes.get(node.id)! + const meshes: Mesh[] = [] + root.traverse((object) => { + if (object instanceof Mesh) meshes.push(object) + }) + expect(meshes.length).toBeGreaterThan(0) + const slots = columnSlots(node).map((slot) => slot.slotId) + for (const mesh of meshes) { + expect(slots).toContain(mesh.userData.slotId) + const material = mesh.material as MeshStandardMaterial + expect(material.color.getHexString()).toBe('e9e9e9') + expect(material.metalness).toBe(0) + expect(material.map).toBeNull() + expect(mesh.geometry.getAttribute('uv').count).toBe( + mesh.geometry.getAttribute('position').count, + ) + } + const baseline = meshes.map((mesh) => mesh.material) + const child = new Mesh(undefined, new MeshBasicMaterial()) + child.userData.slotId = meshes[0]!.userData.slotId + root.add(child) + const childMaterial = child.material + for (const role of new Set(meshes.map((mesh) => mesh.userData.slotId))) { + const restore = columnPaint.applyPreview({ + node, + role, + root, + material: paint, + materialPreset: undefined, + }) + expect(restore).not.toBeNull() + meshes.forEach((mesh, i) => { + if (mesh.userData.slotId === role) expect(mesh.material).not.toBe(baseline[i]) + else expect(mesh.material).toBe(baseline[i]) + }) + expect(child.material).toBe(childMaterial) + restore?.() + meshes.forEach((mesh, i) => { + expect(mesh.material).toBe(baseline[i]) + }) + } + root.remove(child) + child.geometry.dispose() + childMaterial.dispose() + }) +} + +test('eraser preview restores a legacy whole-pillar finish and can be cancelled', async () => { + const node = ColumnNode.parse({ material: paint, slots: { shaft: 'library:metal-steel' } }) + useViewer.setState({ textures: true }) + useScene.setState({ nodes: { [node.id]: node }, materials: {} }) + await mount() + const root = sceneRegistry.nodes.get(node.id)! + let shaft: Mesh | undefined + root.traverse((object) => { + if (object instanceof Mesh && object.userData.slotId === 'shaft') shaft = object + }) + const original = shaft!.material + const restore = columnPaint.applyPreview({ + node, + role: 'shaft', + root, + material: undefined, + materialPreset: undefined, + }) + expect((shaft!.material as MeshBasicMaterial).color.getHexString()).toBe('da3210') + restore?.() + expect(shaft!.material).toBe(original) +}) + +test('committed paint survives preset changes and scene serialization, with one-step undo', async () => { + const node = ColumnNode.parse({}) + useViewer.setState({ textures: true }) + useScene.setState({ nodes: { [node.id]: node }, materials: {}, readOnly: false }) + clearSceneHistory() + columnPaint.commit?.({ node, role: 'shaft', material: paint, materialPreset: undefined }) + const painted = useScene.getState().nodes[node.id] as ColumnNode + expect(painted.slots?.shaft).toStartWith('scene:') + expect(useScene.temporal.getState().pastStates).toHaveLength(1) + const restored = ColumnNode.parse( + JSON.parse( + JSON.stringify({ + ...painted, + ...columnPresetUpdates('basicPillar'), + shaftDetail: 'fluted', + fluteCount: 16, + }), + ), + ) + useScene.setState({ nodes: { [node.id]: restored } }) + await mount() + const root = sceneRegistry.nodes.get(node.id)! + let count = 0 + root.traverse((object) => { + if (object instanceof Mesh && object.userData.slotId === 'shaft') { + expect((object.material as MeshBasicMaterial).color.getHexString()).toBe('da3210') + count++ + } + }) + expect(count).toBeGreaterThan(0) + useScene.temporal.getState().undo() + useScene.temporal.getState().undo() + expect((useScene.getState().nodes[node.id] as ColumnNode).slots).toBeUndefined() +}) diff --git a/packages/nodes/src/column/paint.ts b/packages/nodes/src/column/paint.ts index 212d9f9fe0..9bc82b2ddf 100644 --- a/packages/nodes/src/column/paint.ts +++ b/packages/nodes/src/column/paint.ts @@ -1,5 +1,10 @@ import type { AnyNode } from '@pascal-app/core' -import { createSlotPaintCapability, previewSlotByUserData } from '../shared/slot-paint' +import type { Object3D } from 'three' +import { + createSlotPaintCapability, + declaredSlotLook, + previewSlotByUserData, +} from '../shared/slot-paint' import type { ColumnNode } from './schema' export const columnPaint = createSlotPaintCapability({ @@ -7,7 +12,17 @@ export const columnPaint = createSlotPaintCapability({ const slotId = args.hitObject?.userData?.slotId return typeof slotId === 'string' ? slotId : null }, - applyPreview: previewSlotByUserData, + applyPreview: (args) => { + // Hosted children can have identical slot names; preview only our own body. + const body = (args.root as Object3D).children.find((child) => child.name === 'column-body') + return body ? previewSlotByUserData({ ...args, root: body }) : null + }, + erasedLook: ({ node, role }) => { + const column = node as ColumnNode + return column.materialPreset || column.material + ? { material: column.material, materialPreset: column.materialPreset } + : declaredSlotLook(node, role) + }, legacyEffective: (node: AnyNode) => { const column = node as ColumnNode if (column.materialPreset || column.material) { diff --git a/packages/nodes/src/column/panel.tsx b/packages/nodes/src/column/panel.tsx index e2d15756ab..0b7f9e8774 100644 --- a/packages/nodes/src/column/panel.tsx +++ b/packages/nodes/src/column/panel.tsx @@ -2,50 +2,92 @@ import { type AnyNode, - COLUMN_PRESETS, + type AnyNodeId, + ColumnBaseStyle, + ColumnCapitalStyle, + ColumnCarvingPlacement, + ColumnCrossSection, type ColumnNode, - type ColumnPresetId, + ColumnPanelShape, + ColumnShaftDetail, + ColumnShaftProfile, + ColumnStyle, scriptImages, + useLiveNodeOverrides, useScene, } from '@pascal-app/core' import { ActionButton, ActionGroup, - cn, - PanelSection, + armMaterialPaint, + PanelSection as BasePanelSection, + SliderControl as BaseSliderControl, PanelWrapper, - SliderControl, ToggleControl, triggerSFX, useEditor, } from '@pascal-app/editor' import { useViewer } from '@pascal-app/viewer' -import { Move, Trash2 } from 'lucide-react' -import { useCallback } from 'react' +import { Move, PaintBucket, Trash2 } from 'lucide-react' +import { type ComponentProps, useCallback, useEffect, useMemo, useState } from 'react' import { AuthoredParams } from '../item/authored-params' +import { isManagedColumn } from './edit-policy' import { planColumnEdit } from './hosted-resize' +import { ColumnInspectorHover } from './inspector-highlight' +import { ColumnPresetGallery } from './preset-gallery' +import { columnSectionReset } from './presets' +import { createColumnPropertyPreview } from './property-preview' -const SELECT_CLASS = - 'h-10 w-full rounded-lg border border-border/50 bg-black/4 dark:bg-[#2C2C2E] px-3 text-sm text-foreground outline-none transition-colors hover:bg-black/8 dark:hover:bg-[#3e3e3e] focus:ring-1 focus:ring-border' +function PanelSection({ + part, + ...props +}: ComponentProps & { + part?: 'all' | 'shaft' | 'base' | 'capital' | 'frame' +}) { + return ( +
+ +
+ ) +} -const MANAGED_LEAN_TO_LAYOUT_FIELDS = new Set([ - 'position', - 'height', - 'width', - 'depth', - 'crossSection', - 'baseStyle', - 'baseHeight', - 'baseWidthScale', - 'baseDepthScale', - 'slots', -]) +function SliderControl({ + axis, + ...props +}: ComponentProps & { axis?: 'x' | 'y' | 'z' }) { + return ( +
+ +
+ ) +} -const COLUMN_PRESET_OPTIONS = Object.entries(COLUMN_PRESETS).map(([value, preset]) => ({ - value: value as ColumnPresetId, - label: preset.label, -})) +const shapeLabel = (value: string) => + value.replaceAll('-', ' ').replace(/\b\w/g, (letter) => letter.toUpperCase()) +const detailFields = [ + ['fluteCount', 'Flute Count', 0, 32, 1], + ['fluteDepth', 'Flute Depth', 0.005, 0.08, 0.005], + ['fluteWidth', 'Flute Width', 0.005, 0.1, 0.005], + ['spiralRibCount', 'Spiral Ribs', 0, 32, 1], + ['spiralTwist', 'Spiral Turns', -3, 3, 0.1], + ['panelCount', 'Carved Panels', 0, 24, 1], + ['panelInsetDepth', 'Panel Relief', 0, 0.1, 0.005], + ['latheRingCount', 'Lathe Rings', 0, 32, 1], + ['voluteCount', 'Volutes', 0, 8, 1], + ['voluteSize', 'Volute Size', 0.02, 0.3, 0.01], + ['leafCount', 'Leaves', 0, 48, 1], + ['leafRows', 'Leaf Rows', 0, 4, 1], + ['bracketDepth', 'Bracket Depth', 0, 1.5, 0.01], + ['bracketTierCount', 'Bracket Tiers', 0, 8, 1], + ['pendantCount', 'Pendants', 0, 16, 1], + ['baseRibCount', 'Base Ribs', 0, 48, 1], + ['baseCarvingLevel', 'Base Carving', 0, 4, 1], + ['capitalCarvingLevel', 'Capital Carving', 0, 4, 1], +] as const + +const SELECT_CLASS = + 'h-10 w-full rounded-lg border border-border/50 bg-black/4 dark:bg-[#2C2C2E] px-3 text-sm text-foreground outline-none transition-colors hover:bg-black/8 dark:hover:bg-[#3e3e3e] focus:ring-1 focus:ring-border' const COLUMN_PROPORTION_PRESETS = { slender: { @@ -99,125 +141,10 @@ const COLUMN_PROPORTION_OPTIONS = Object.entries(COLUMN_PROPORTION_PRESETS).map( }), ) -const SUPPORT_STYLE_OPTIONS: Array<{ label: string; value: ColumnNode['supportStyle'] }> = [ - { label: 'Vertical', value: 'vertical' }, - { label: 'A-Frame', value: 'a-frame' }, - { label: 'Y Support', value: 'y-frame' }, - { label: 'V Support', value: 'v-frame' }, - { label: 'X Brace', value: 'x-brace' }, - { label: 'K Brace', value: 'k-brace' }, - { label: 'Single Strut', value: 'single-strut' }, - { label: 'Tripod', value: 'tripod' }, - { label: 'Trestle', value: 'trestle' }, - { label: 'Portal Frame', value: 'portal-frame' }, - { label: 'Box Frame', value: 'box-frame' }, -] - -type NonVerticalSupportStyle = Exclude - -// Per-style brace defaults. Values mirror each support's renderer -// fall-through expressions so switching styles snaps the column to the -// shape that style was designed around — e.g. an A-frame opens wide at -// the foot and pinches at the top, an X-brace runs parallel legs, a -// tripod's "bottomSpread" / "topSpread" double as its X-span / Z-span. -// Without these, a user who customised one style (say A-frame bottom = -// 2.0) then switched to Y-frame would carry that 2.0 around in state -// even though Y-frame doesn't use it — and switching back to X-brace -// would inherit the leftover 0.12 top from A-frame, making the X look -// pinched. -const SUPPORT_STYLE_DEFAULTS: Record> = { - 'a-frame': { - braceBottomSpread: 1.4, - braceTopSpread: 0.12, - braceWidth: 0.16, - braceDepth: 0.16, - }, - 'y-frame': { - braceBottomSpread: 0.2, - braceTopSpread: 0.9, - braceWidth: 0.16, - braceDepth: 0.16, - }, - 'v-frame': { - braceBottomSpread: 0.2, - braceTopSpread: 1.0, - braceWidth: 0.16, - braceDepth: 0.16, - }, - 'x-brace': { - braceBottomSpread: 1.0, - braceTopSpread: 1.0, - braceWidth: 0.14, - braceDepth: 0.14, - }, - 'k-brace': { - braceBottomSpread: 1.0, - braceTopSpread: 1.0, - braceWidth: 0.14, - braceDepth: 0.14, - }, - 'single-strut': { - braceBottomSpread: 0.6, - braceTopSpread: 0.6, - braceWidth: 0.12, - braceDepth: 0.12, - }, - tripod: { - // bottomSpread = X span, topSpread = Z span (tripod's three legs). - braceBottomSpread: 1.1, - braceTopSpread: 1.1, - braceWidth: 0.12, - braceDepth: 0.12, - }, - trestle: { - braceBottomSpread: 1.2, - braceTopSpread: 1.0, - braceWidth: 0.16, - braceDepth: 0.16, - }, - 'portal-frame': { - braceBottomSpread: 1.4, - braceTopSpread: 1.0, - braceWidth: 0.16, - braceDepth: 0.16, - }, - 'box-frame': { - // bottomSpread = X span, topSpread = Z span (rectangular footprint). - braceBottomSpread: 1.4, - braceTopSpread: 1.0, - braceWidth: 0.16, - braceDepth: 0.16, - }, -} - function clamp(value: number, min: number, max: number) { return Math.min(max, Math.max(min, value)) } -function isManagedLeanToPost(node: ColumnNode): boolean { - const metadata = node.metadata - if (!metadata || typeof metadata !== 'object' || Array.isArray(metadata)) return false - const record = metadata as Record - return record.managedByLeanTo !== undefined && record.leanToRole === 'post' -} - -function filterManagedLeanToLayoutUpdates(updates: Partial): Partial { - const filtered = { ...updates } - for (const key of MANAGED_LEAN_TO_LAYOUT_FIELDS) { - delete filtered[key] - } - return filtered -} - -function presetUpdates(presetId: ColumnPresetId): Partial { - const { label, ...preset } = COLUMN_PRESETS[presetId] - return { - name: label, - supportStyle: 'supportStyle' in preset ? preset.supportStyle : 'vertical', - ...preset, - } -} - function proportionUpdates( node: ColumnNode, presetId: ColumnProportionPresetId, @@ -257,7 +184,7 @@ function shaftProfileUpdates(shaftProfile: ColumnNode['shaftProfile']): Partial< } } - if (shaftProfile === 'bulged') { + if (shaftProfile === 'bulged' || shaftProfile === 'baluster') { return { shaftProfile, shaftTaper: 0, @@ -298,20 +225,49 @@ export default function ColumnPanel() { const deleteNode = useScene((s) => s.deleteNode) const setMovingNode = useEditor((s) => s.setMovingNode) - const node = useScene((s) => + const storedNode = useScene((s) => selectedId ? (s.nodes[selectedId as AnyNode['id']] as ColumnNode | undefined) : undefined, ) + const overrides = useLiveNodeOverrides((s) => + selectedId ? s.overrides.get(selectedId as AnyNode['id']) : undefined, + ) + const [previewingPreset, setPreviewingPreset] = useState(false) + const node = + storedNode && overrides && !previewingPreset + ? ({ ...storedNode, ...overrides } as ColumnNode) + : storedNode + const preview = useMemo( + () => (selectedId ? createColumnPropertyPreview(selectedId as AnyNode['id']) : null), + [selectedId], + ) + useEffect(() => () => preview?.cancel(), [preview]) + const previewProp = useCallback( + (updates: Partial) => preview?.preview(updates), + [preview], + ) + const commitPreview = useCallback(() => preview?.commit(), [preview]) + const cancelPreview = useCallback(() => preview?.cancel(), [preview]) + const previewPreset = useCallback( + (updates: Partial) => { + // Presets preview the scene, while controls keep the committed shape's layout. + setPreviewingPreset(true) + preview?.preview(updates) + }, + [preview], + ) + const cancelPresetPreview = useCallback(() => { + preview?.cancel() + setPreviewingPreset(false) + }, [preview]) const handleUpdate = useCallback( (updates: Partial) => { if (!selectedId) return - const nextUpdates = - node && isManagedLeanToPost(node) ? filterManagedLeanToLayoutUpdates(updates) : updates - if (Object.keys(nextUpdates).length === 0) return - const updatesToApply = planColumnEdit(selectedId as AnyNode['id'], nextUpdates) + preview?.cancel() + const updatesToApply = planColumnEdit(selectedId as AnyNode['id'], updates) if (updatesToApply) updateNodes(updatesToApply.map(([id, data]) => ({ id, data }))) }, - [node, selectedId, updateNodes], + [selectedId, updateNodes, preview], ) const handleClose = useCallback(() => { @@ -326,7 +282,7 @@ export default function ColumnPanel() { }, [deleteNode, selectedId, setSelection]) const handleMove = useCallback(() => { - if (!node) return + if (!node || isManagedColumn(node)) return triggerSFX('sfx:item-pick') setMovingNode(node) setSelection({ selectedIds: [] }) @@ -334,8 +290,10 @@ export default function ColumnPanel() { if (!(node && node.type === 'column' && selectedId && selectedCount === 1)) return null const shaftProfile = node.shaftProfile ?? 'straight' + const radialSection = ['round', 'octagonal', 'sixteen-sided'].includes(node.crossSection) + const spatialFrame = ['tripod', 'trestle', 'box-frame'].includes(node.supportStyle) const supportStyle = node.supportStyle ?? 'vertical' - const managedByLeanTo = isManagedLeanToPost(node) + const managedByLeanTo = isManagedColumn(node) const isBraceSupport = supportStyle === 'a-frame' || supportStyle === 'y-frame' || @@ -348,6 +306,51 @@ export default function ColumnPanel() { supportStyle === 'portal-frame' || supportStyle === 'box-frame' + const renderDetails = (fields: readonly (typeof detailFields)[number][]) => + fields.map(([field, label, min, max, step]) => ( + previewProp({ [field]: value })} + onCommit={commitPreview} + onCancel={cancelPreview} + restoreOnCommit={false} + /> + )) + + const hasPanels = + node.panelCount > 0 || node.style === 'dravidian-carved' || node.shaftDetail === 'panelled' + const shaftFields = detailFields.filter(([field]) => { + if (field.startsWith('flute')) + return node.crossSection === 'round' && (node.fluteCount > 0 || node.shaftDetail === 'fluted') + if (field.startsWith('spiral')) return node.spiralRibCount > 0 || node.shaftDetail === 'spiral' + if (field.startsWith('panel')) return hasPanels + if (field === 'latheRingCount') + return node.latheRingCount > 0 || node.shaftDetail === 'lathe-turned' + return false + }) + const capitalFields = detailFields.filter(([field]) => { + if (node.capitalStyle === 'none') return false + if (field.startsWith('volute')) return ['volute', 'ionic-volute'].includes(node.capitalStyle) + if (field.startsWith('leaf')) + return ['leaf-carved', 'corinthian-leaf'].includes(node.capitalStyle) + if (field.startsWith('bracket') || field === 'pendantCount') + return ['south-indian-bracket', 'wood-bracket'].includes(node.capitalStyle) + return field === 'capitalCarvingLevel' && ['capital', 'all'].includes(node.carvingPlacement) + }) + const baseFields = detailFields.filter( + ([field]) => + node.baseStyle !== 'none' && + ((field === 'baseRibCount' && ['lotus', 'ribbed-lotus'].includes(node.baseStyle)) || + (field === 'baseCarvingLevel' && ['base', 'all'].includes(node.carvingPlacement))), + ) + return ( - {node.source ? ( - - ) : ( - <> - - - - - -
- {SUPPORT_STYLE_OPTIONS.map((option) => { - const isSelected = supportStyle === option.value - return ( - + + {!isBraceSupport && ( + <> +

Style

+ +

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 && ( -

- 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') && ( + 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 && ( +

+ 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="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' && ( + + +

+ 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} + value={node.shaftStartScale ?? 0.72} /> - handleUpdate({ shaftBulge: value })} - precision={2} - step={0.01} - value={node.shaftBulge ?? 0.12} - /> - - )} - - 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 && ( - 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' && ( + )} + {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({ - 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} - /> - )} - {node.capitalStyle === 'stepped' && ( - handleUpdate({ capitalStepSpread: value })} - precision={2} - step={0.01} - value={node.capitalStepSpread ?? 0.34} + step={5} + unit="°" + value={node.shaftTwistStep ?? 0} /> - )} - - {node.baseStyle !== 'none' && ( - handleUpdate({ baseHeight: value })} - precision={2} - step={0.02} - unit="m" - value={node.baseHeight} - /> - )} - {node.baseStyle !== 'none' && ( + {Math.abs(node.shaftTwistStep ?? 0) > 0.001 && ( + previewProp({ shaftSegmentCount: Math.round(value) })} + precision={0} + step={1} + value={node.shaftSegmentCount ?? 12} + /> + )} + + )} + + {!isBraceSupport && ( + <> + + +

+ Width and depth scales use Size. Band and neck scales use the base footprint. +

+ + {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)} +
+ + +

+ 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 && ( + + +

Shaft detail

+ + {hasPanels && ( + <> +

Panel shape

+ + + )} + {renderDetails(shaftFields)} - handleUpdate({ - baseWidthScale: value, - ...(node.crossSection === 'rectangular' ? {} : { baseDepthScale: value }), + previewProp({ + ringCount: Math.round(value) * 2, + ringPlacement: 'ends', + ringSpread: node.ringSpread ?? 0.16, + ringThickness: node.ringThickness ?? 0.055, }) } - precision={2} - step={0.02} - value={node.baseWidthScale ?? 1.24} - /> - )} - {node.baseStyle !== 'none' && node.crossSection === 'rectangular' && ( - handleUpdate({ baseDepthScale: value })} - precision={2} - step={0.02} - value={node.baseDepthScale ?? node.baseWidthScale ?? 1.24} - /> - )} - {node.baseStyle === 'round-rings' && ( - handleUpdate({ basePlinthHeightRatio: value })} - precision={2} - step={0.01} - value={node.basePlinthHeightRatio ?? 0.44} - /> - )} - {node.baseStyle === 'round-rings' && ( - handleUpdate({ baseRoundBandScale: value })} - precision={2} - step={0.01} - value={node.baseRoundBandScale ?? 0.92} - /> - )} - {node.baseStyle === 'round-rings' && ( - handleUpdate({ baseNeckScale: value })} - precision={2} - step={0.01} - value={node.baseNeckScale ?? 0.72} - /> - )} - {node.baseStyle === 'stepped-square' && ( - handleUpdate({ baseTierCount: Math.round(value) })} precision={0} step={1} - value={node.baseTierCount ?? 3} - /> - )} - {node.baseStyle === 'stepped-square' && ( - handleUpdate({ baseStepSpread: value })} - precision={2} - step={0.01} - value={node.baseStepSpread ?? 0.34} + value={Math.ceil((node.ringCount ?? 0) / 2)} /> - )} -
- )} - - )} - - handleUpdate({ rotation: (value * Math.PI) / 180 })} - precision={0} - step={1} - unit="°" - value={Math.round((node.rotation * 180) / Math.PI)} - /> - - - - - } label="Move" onClick={handleMove} /> + {(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') && ( + <> +

Carving placement

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

+ 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="Delete" - onClick={handleDelete} + icon={} + label="Paint Materials" + onClick={() => { + cancelPreview() + armMaterialPaint(undefined, 'surface') + }} /> - -
+ + + + previewProp({ rotation: (value * Math.PI) / 180 })} + precision={0} + step={1} + unit="°" + value={Math.round((node.rotation * 180) / Math.PI)} + /> + + + + + {!managedByLeanTo && ( + } label="Move" onClick={handleMove} /> + )} + } + label="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..fb79accbcb --- /dev/null +++ b/packages/nodes/src/column/preset-gallery.tsx @@ -0,0 +1,132 @@ +import { COLUMN_PRESETS, type ColumnNode, type ColumnPresetId } from '@pascal-app/core' +import { ChevronDown } from 'lucide-react' +import { useEffect, useRef } from 'react' +import { columnPresetUpdates } from './presets' + +const entries = Object.entries(COLUMN_PRESETS).map(([id, preset]) => ({ + id: id as ColumnPresetId, + label: preset.label, +})) + +export function ColumnPresetGallery({ + node, + onPreview, + onCancel, + onApply, +}: { + node: ColumnNode + onPreview: (patch: Partial) => void + onCancel: () => void + onApply: (patch: Partial) => void +}) { + 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() + }} + > + + + + Shape presets + {selected?.label ?? 'Choose a shape'} + + + +

+ 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..dc0c50aaee --- /dev/null +++ b/packages/nodes/src/column/presets.test.ts @@ -0,0 +1,95 @@ +import { expect, test } from 'bun:test' +import { + COLUMN_PRESETS, + ColumnNode, + type ColumnPresetId, + clearSceneHistory, + 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 clears all finish overrides', () => { + 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).toBeUndefined() + 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).toBeUndefined() + 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..33edd6ee11 --- /dev/null +++ b/packages/nodes/src/column/presets.ts @@ -0,0 +1,100 @@ +import { COLUMN_PRESETS, ColumnNode, type ColumnPresetId } 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({}) + 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..63fe09bf26 --- /dev/null +++ b/packages/nodes/src/column/renderer.test.tsx @@ -0,0 +1,313 @@ +import { expect, test } from 'bun:test' +import { COLUMN_PRESETS, ColumnNode, sceneRegistry, useScene } from '@pascal-app/core' +import { 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 { createColumnSpiralGeometry } from './geometry' +import { clearColumnInspectorHighlight, setColumnInspectorHighlight } from './inspector-highlight' +import { ColumnRenderer } 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() + } +}) diff --git a/packages/nodes/src/column/renderer.tsx b/packages/nodes/src/column/renderer.tsx index 1cb719a0cf..bba6ca9dac 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'] @@ -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 c77cbd2fd9..3bdd6df0e8 100644 --- a/packages/nodes/src/column/tool.tsx +++ b/packages/nodes/src/column/tool.tsx @@ -91,7 +91,16 @@ const ColumnTool = () => { // 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' && @@ -105,11 +114,8 @@ const ColumnTool = () => { 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, @@ -127,6 +133,7 @@ const ColumnTool = () => { } const onGridMove = (event: GridEvent) => { + refreshCandidates() if (!cursorVisibleRef.current) { cursorVisibleRef.current = true setCursorVisible(true) @@ -146,10 +153,7 @@ const ColumnTool = () => { }) 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]] @@ -195,6 +199,7 @@ const ColumnTool = () => { } const commitAtCursor = (event: FloorPlacementClickTriggerEvent) => { + refreshCandidates() const pointed = pointedSurfaceFor(event) ?? supportSurfaceRef.current supportSurfaceRef.current = pointed const fallbackPosition = @@ -207,10 +212,7 @@ const ColumnTool = () => { ) 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]] @@ -219,6 +221,7 @@ const ColumnTool = () => { const committedColumn = ColumnNode.parse({ ...column, ...patch, + id: undefined, }) useScene.getState().createNode(committedColumn, activeLevelId) useViewer.getState().setSelection({ selectedIds: [committedColumn.id] }) @@ -227,7 +230,7 @@ const ColumnTool = () => { 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 f921bef7f5..3b5c499814 100644 --- a/packages/nodes/src/door/move-tool.tsx +++ b/packages/nodes/src/door/move-tool.tsx @@ -13,6 +13,7 @@ import { runSceneHistoryDraftWrite, sceneRegistry, spatialGridManager, + useLiveNodeOverrides, useLiveTransforms, useScene, type WallEvent, @@ -381,6 +382,7 @@ const MoveDoorTool: React.FC<{ node: DoorNode }> = ({ node: movingDoorNode }) => } const applyPreview = (target: NonNullable) => { + useLiveNodeOverrides.getState().clear(movingDoorNode.id) // One grid-snap tick per real position step, keyed on the SNAPPED // along-wall position so it ticks only when the door actually moves to a // new cell (not on every micro mouse-move). Per-frame guard collapses any @@ -682,6 +684,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 @@ -699,14 +702,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], @@ -790,13 +786,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], @@ -810,6 +801,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() } @@ -886,6 +884,7 @@ const MoveDoorTool: React.FC<{ node: DoorNode }> = ({ node: movingDoorNode }) => placedId = movingDoorNode.id } + useLiveNodeOverrides.getState().clear(movingDoorNode.id) markHostDirty(segmentId) useLiveTransforms.getState().clear(movingDoorNode.id) @@ -898,6 +897,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() @@ -908,6 +908,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) @@ -1063,6 +1064,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.tsx b/packages/nodes/src/duct-fitting/selection.tsx index dfd54dd551..a7d9d2e0d3 100644 --- a/packages/nodes/src/duct-fitting/selection.tsx +++ b/packages/nodes/src/duct-fitting/selection.tsx @@ -7,15 +7,16 @@ import { type Cursor, type DuctFittingNode, type PortConnectivity, - pauseSceneHistory, resolveConnectivityUpdates, - resumeSceneHistory, sceneRegistry, + useLiveNodeOverrides, useScene, } from '@pascal-app/core' import { ARROW_COLOR, EDITOR_LAYER, + isAngleSnapActive, + isGridSnapActive, isTypingTarget, swallowNextClick, triggerSFX, @@ -49,6 +50,7 @@ import { type RotationAxis, } from '../shared/fitting-rotation' import { HandleCube, MoveChevron, RotateArc } from '../shared/selection-handles' +import { useNodeHandleDrag } from '../shared/use-node-handle-drag' import { fittingLegLength } from './ports' type Point = [number, number, number] @@ -331,7 +333,16 @@ 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 startDrag = useNodeHandleDrag(fitting.id) const { camera, gl } = useThree() const [frame, setFrame] = useState(null) // True while the cluster is latched open. Click the center cube to toggle. @@ -439,100 +450,38 @@ const FittingHandles = ({ fitting, target }: { fitting: DuctFittingNode; target: const beginDrag = ( cursor: Cursor, + handle: string, makeCompute: ( e: ThreeEvent, ) => (event: PointerEvent) => FittingTransform | null, ) => (e: ThreeEvent) => { e.stopPropagation() - const initialPosition = [...fitting.position] as Point - const initialRotation = [...fitting.rotation] as Point const connectivity = analyzePortConnectivity(fitting as AnyNode, useScene.getState().nodes) const compute = makeCompute(e) - pauseSceneHistory(useScene) - useViewer.getState().setInputDragging(true) setDragging(true) - document.body.style.cursor = cursor - let current: FittingTransform | null = null - - const buildBatch = (t: FittingTransform): { id: AnyNodeId; data: Partial }[] => [ - { - id: fitting.id as AnyNodeId, - data: preserveFittingParameters(fitting, t as Partial), - }, - ...connectivityUpdates(connectivity, t), - ] - - const onMove = (event: PointerEvent) => { - const next = compute(event) - if (!next) return - current = next - useScene.getState().updateNodes(buildBatch(next)) - } - - const cleanup = () => { - window.removeEventListener('pointermove', onMove) - window.removeEventListener('pointerup', onUp) - window.removeEventListener('pointercancel', onUp) - useViewer.getState().setInputDragging(false) - setDragging(false) - if (document.body.style.cursor === cursor) document.body.style.cursor = '' - } - - const onUp = () => { - // Swallow the trailing synthetic click so it doesn't reach the - // background-click deselect handler (cleanup drops `inputDragging` - // synchronously here). - swallowNextClick() - 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]), - ]) - resumeSceneHistory(useScene) - if (current) { - const scene = useScene.getState() - scene.updateNodes([ - ...buildBatch(current), - ...autoOffsetInvalidationUpdates(scene.nodes, fitting.id as AnyNodeId), + startDrag({ + nodeId: fitting.id, + handle, + cursor, + onEnd: () => setDragging(false), + onMove: (event, preview) => { + const next = compute(event) + if (!next) return + preview([ + { id: fitting.id, data: preserveFittingParameters(fitting, next) }, + ...connectivityUpdates(connectivity, next), ]) - } - } - - window.addEventListener('pointermove', onMove) - window.addEventListener('pointerup', onUp) - window.addEventListener('pointercancel', onUp) + }, + commitUpdates: (updates) => [ + ...updates, + ...autoOffsetInvalidationUpdates(useScene.getState().nodes, fitting.id), + ], + }) } // Move: translate the fitting along one world axis, anchored to the cursor's - // start coord so it doesn't jump on grab. Y is clamped at the floor; Shift - // bypasses grid snapping. + // start coord so it doesn't jump on grab. Y is clamped at the floor. const moveCompute = (axis: RotationAxis) => (e: ThreeEvent): ((event: PointerEvent) => FittingTransform | null) => { @@ -545,7 +494,7 @@ const FittingHandles = ({ fitting, target }: { fitting: DuctFittingNode; target: if (start === null) return null const s = sampleAxis(axis, event.clientX, event.clientY, anchorWorld) if (s === null) return null - const step = event.shiftKey ? 0 : useEditor.getState().gridSnapStep + const step = isGridSnapActive() ? useEditor.getState().gridSnapStep : 0 const delta = snap(s - start, step) if (delta === lastDelta) return null lastDelta = delta @@ -589,12 +538,14 @@ const FittingHandles = ({ fitting, target }: { fitting: DuctFittingNode; target: if (startBearing === null) return null const b = bearing(event.clientX, event.clientY) if (b === null) return null - // Snap the turn to 45° steps; Shift = smooth (no snap). + // The rotation context selects stepped or smooth turns. const raw = b - startBearing - const delta = event.shiftKey ? raw : Math.round(raw / ROTATE_STEP_RAD) * ROTATE_STEP_RAD + const delta = isAngleSnapActive() + ? Math.round(raw / ROTATE_STEP_RAD) * ROTATE_STEP_RAD + : raw // Tick the rotate SFX each time a fresh snap step is crossed (snapped - // turns only — a smooth Shift-drag has no discrete steps to mark). - if (!event.shiftKey) { + // turns only — a smooth drag has no discrete steps to mark). + if (isAngleSnapActive()) { const step = Math.round(raw / ROTATE_STEP_RAD) if (step !== lastStep) { lastStep = step @@ -612,7 +563,6 @@ const FittingHandles = ({ fitting, target }: { fitting: DuctFittingNode; target: (e: ThreeEvent) => { e.stopPropagation() const baseValue = fitting[dimension] - const initialPatch = { [dimension]: baseValue } as Partial const centerWorld = toWorld(fitting.position as Point) const axisWorld = axisToWorld(fitting.position as Point, axisLocal) const start = sampleAxisParameter( @@ -622,55 +572,33 @@ const FittingHandles = ({ fitting, target }: { fitting: DuctFittingNode; target: axisWorld, ) const { min, max } = dimensionBounds(dimension) - pauseSceneHistory(useScene) - useViewer.getState().setInputDragging(true) setDragging(true) - document.body.style.cursor = cursor - 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 onMove = (event: PointerEvent) => { - const rawDeltaM = - sampleAxisParameter(event.clientX, event.clientY, centerWorld, axisWorld) - start - const deltaIn = (rawDeltaM / INCHES_TO_METERS) * 2 - const nextRaw = baseValue + deltaIn - const nextValue = clamp(event.shiftKey ? nextRaw : snap(nextRaw, RESIZE_STEP_IN), min, max) - if (nextValue === lastValue) return - lastValue = nextValue - current = { [dimension]: nextValue } as Partial - if (!event.shiftKey) triggerSFX('sfx:grid-snap') - apply(current) - } - - const cleanup = () => { - window.removeEventListener('pointermove', onMove) - window.removeEventListener('pointerup', onUp) - window.removeEventListener('pointercancel', onUp) - useViewer.getState().setInputDragging(false) - setDragging(false) - if (document.body.style.cursor === cursor) document.body.style.cursor = '' - } - - const onUp = () => { - swallowNextClick() - cleanup() - apply(initialPatch) - resumeSceneHistory(useScene) - if (current) apply(current) - } - - window.addEventListener('pointermove', onMove) - window.addEventListener('pointerup', onUp) - window.addEventListener('pointercancel', onUp) + let lastValue = baseValue + startDrag({ + nodeId: fitting.id, + handle: dimension, + cursor, + onEnd: () => setDragging(false), + onMove: (event, preview) => { + const rawDeltaM = + sampleAxisParameter(event.clientX, event.clientY, centerWorld, axisWorld) - start + const nextRaw = baseValue + (rawDeltaM / INCHES_TO_METERS) * 2 + const nextValue = clamp( + isGridSnapActive() ? snap(nextRaw, RESIZE_STEP_IN) : nextRaw, + min, + max, + ) + if (nextValue === lastValue) return + lastValue = nextValue + if (isGridSnapActive()) triggerSFX('sfx:grid-snap') + preview([ + { + id: fitting.id, + data: preserveFittingParameters(fitting, { [dimension]: nextValue }), + }, + ]) + }, + }) } const extent = useMemo(() => fittingExtentM(fitting), [fitting]) @@ -864,6 +792,7 @@ const FittingHandles = ({ fitting, target }: { fitting: DuctFittingNode; target: key={a.key} onPointerDown={beginDrag( a.axis === 'y' ? 'ns-resize' : 'grabbing', + 'move', moveCompute(a.axis), )} position={a.position} @@ -874,7 +803,7 @@ const FittingHandles = ({ fitting, target }: { fitting: DuctFittingNode; target: {rotateArcs.map((arc) => ( diff --git a/packages/nodes/src/duct-segment/selection.tsx b/packages/nodes/src/duct-segment/selection.tsx index c1a302d1e1..4e6f40a8cd 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, @@ -601,6 +602,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..6b77cda090 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,132 @@ 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, + }) + try { + useScene.setState({ + nodes: { + [building.id]: building, + [level.id]: level, + [elevator.id]: elevator, + [slab.id]: slab, + }, + }) + 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: useScene.getState().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..6c52891d54 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 }) => [ + position[0], + resolveElevatorNodeSupportY(node as ElevatorNodeType, position), + 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 44235be543..09068870e3 100644 --- a/packages/nodes/src/elevator/panel.tsx +++ b/packages/nodes/src/elevator/panel.tsx @@ -6,7 +6,9 @@ import { type ElevatorNode, getLevelDisplayName, type LevelNode, + normalizeElevatorDimensions, requestElevatorLevel, + resolveElevatorDimensions, useInteractive, useLiveNodeOverrides, useLiveTransforms, @@ -15,11 +17,9 @@ import { import { ActionButton, ActionGroup, + PanelSection as BasePanelSection, duplicateNodeAndPickUp, - MetricControl, - PanelSection, PanelWrapper, - resolveElevatorNodeSupportY, resolveElevatorSupportY, SliderControl, triggerSFX, @@ -27,8 +27,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 @@ -94,6 +101,9 @@ type ElevatorMetricKey = | 'cabHeight' | 'doorWidth' | 'doorHeight' + | 'speed' + | 'doorDurationMs' + | 'dwellMs' type ElevatorAccessField = 'disabledLevelIds' | 'serviceOnlyLevelIds' @@ -127,18 +137,6 @@ 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) } @@ -147,6 +145,46 @@ function degreesToRadians(degrees: number) { return (degrees * Math.PI) / 180 } +function PanelSection({ + title, + children, + onReset, +}: { + title: string + children: ReactNode + onReset: (title: string) => void +}) { + return ( +
+ + {ELEVATOR_SECTION_FIELDS[title] && ( + + )} + {children} + +
+ ) +} + export default function ElevatorPanel() { const selectedId = useViewer((s) => s.selection.selectedIds[0]) const selectedCount = useViewer((s) => s.selection.selectedIds.length) @@ -166,6 +204,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, ) @@ -210,43 +249,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) }, @@ -402,15 +425,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) @@ -444,461 +478,542 @@ export default function ElevatorPanel() { destinationOrderByLevelId.set(levelId, index + 1) } + const resetSection = (title: string) => { + clearLivePreview() + handleUpdate(elevatorSectionReset(node, title)) + } + return ( - - - - } label="Move" onClick={handleMove} /> - } - label="Duplicate" - onClick={handleDuplicate} - /> - } - label="Delete" - onClick={handleDelete} + + + +
+ {Object.entries(ELEVATOR_PRESETS).map(([id, preset]) => ( + + ))} +
+ +

+ Hover or focus a section to highlight its parts. Cutaway affects this inspection only. +

+

+ Clear cab interior: {(dimensions.width - 0.16).toFixed(2)} ×{' '} + {(dimensions.depth - 0.08).toFixed(2)} × {(dimensions.cabHeight - 0.16).toFixed(2)} m. + Door opening: {dimensions.doorWidth.toFixed(2)} × {dimensions.doorHeight.toFixed(2)} m. +

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

+ 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} /> -
-
- - - { - 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) - }} + previewMetric('depth', value)} + onCommit={(value) => commitMetric('depth', value)} + precision={2} + restoreOnCommit={false} + onCancel={clearLivePreview} + step={0.05} + unit="m" + value={dimensions.depth} /> - { - triggerSFX('sfx:item-rotate') - commitTransform(displayPosition, displayRotation + Math.PI / 4) - }} + previewMetric('cabHeight', value)} + onCommit={(value) => commitMetric('cabHeight', value)} + precision={2} + restoreOnCommit={false} + onCancel={clearLivePreview} + step={0.05} + unit="m" + value={dimensions.cabHeight} /> -
-
+ - -
+
- From + 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} + /> + 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} + /> +
+
- To + Opening Style
-
- -
-
- 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} - /> - - - -
-
- 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} - /> -
- - -
-
- Opening Style -
- -
-
-
- Door Type +
+
+ 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 ( -
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} + /> + + + +
+
+
+ From +
+ +
+ +
+
+ To
- ) - })} -
- - - -
- {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 ( -
+
+ +
+
+ Default Floor +
+ +
+
+ + +
+ {servedLevels.map((level) => { + const isDisabled = disabledLevelIds.has(level.id) + const isServiceOnly = serviceOnlyLevelIds.has(level.id) + + return ( +
+ {getLevelDisplayName(level)} +
+ +
+
+ ) + })} +
+
+ + +
+ {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 ? ( + + Disabled + + ) : isServiceOnly ? ( + + Service + + ) : ( + stopOrder && ( + + Stop {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="Move" + onClick={handleMove} + /> + } + label="Duplicate" + onClick={handleDuplicate} + /> + } + label="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..fff7eeb36b --- /dev/null +++ b/packages/nodes/src/elevator/presets.ts @@ -0,0 +1,61 @@ +import { ElevatorNode, normalizeElevatorDimensions } from '@pascal-app/core' + +export const ELEVATOR_PRESETS = { + passenger: { + label: '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: '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: 'Glass', + width: 1.84, + depth: 1.84, + cabHeight: 2.35, + doorWidth: 0.95, + doorHeight: 2.1, + shaftStyle: 'glass', + doorStyle: 'center-opening', + doorPanelStyle: 'glass-frame', + }, +} as const + +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 b7e6974551..f8ed90c10d 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 85bbe690a8..9a75a20ba5 100644 --- a/packages/nodes/src/index.ts +++ b/packages/nodes/src/index.ts @@ -184,6 +184,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' @@ -210,6 +211,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/pipe-segment/selection.tsx b/packages/nodes/src/pipe-segment/selection.tsx index abb7646e59..8efe2b828c 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 PipeFittingNode, PipeSegmentNode, type PortConnectivity, @@ -456,6 +457,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 17024a27eb..e55e3dc070 100644 --- a/packages/nodes/src/roof-segment/definition.ts +++ b/packages/nodes/src/roof-segment/definition.ts @@ -3,6 +3,8 @@ import { getPitchFromActiveRoofHeight, getRoofSegmentResizePatch, type HandleDescriptor, + MAX_ROOF_PITCH, + MIN_ROOF_SEGMENT_DIMENSION, type NodeDefinition, RoofSegmentNode as RoofSegmentNodeSchema, type RoofSegmentNode as RoofSegmentNodeType, @@ -23,14 +25,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 9f9ae25e69..bbc5817ed8 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, @@ -14,7 +15,7 @@ import { commitSeatedRoofEdit } from '../roof/roof-level-target' 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 6f48478532..d32dfd82ee 100644 --- a/packages/nodes/src/roof-segment/panel.tsx +++ b/packages/nodes/src/roof-segment/panel.tsx @@ -11,6 +11,8 @@ import { isAutoRidgeVentEnabled, isDefaultRidgeVentNode, isGlazedRoofSegment, + MAX_ROOF_PITCH, + MIN_ROOF_SEGMENT_DIMENSION, normalizeRoofSegmentTrim, ROOF_SHAPE_DEFAULTS, type RoofSegmentNode, @@ -30,13 +32,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' const ROOF_TYPE_OPTIONS: { label: string; value: RoofType }[] = [ { label: 'Hip', value: 'hip' }, @@ -88,10 +93,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' @@ -107,7 +108,10 @@ function metadataRecord(metadata: unknown): Record { export default function RoofSegmentPanel() { 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) @@ -166,7 +170,6 @@ export default function RoofSegmentPanel() { ...metadataRecord(node?.metadata), autoGutter: false, autoRidgeVent: false, - showTrimPlanes: false, }, } : roofType === 'dutch' @@ -185,25 +188,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) @@ -289,11 +294,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(() => { @@ -304,7 +314,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 @@ -320,23 +329,48 @@ export default function RoofSegmentPanel() { title={node.name || 'Roof Segment'} width={300} > + handleRoofTypeChange(v)} - options={ROOF_TYPE_OPTIONS} + options={ROOF_TYPE_OPTIONS.map((option) => ({ + ...option, + label: ( + + + {option.label} + + ), + }))} value={node.roofType} disabled={managedLeanToRoofSegment} /> handleRoofTypeChange(v)} - options={ROOF_TYPE_OPTIONS_2} + options={ROOF_TYPE_OPTIONS_2.map((option) => ({ + ...option, + label: ( + + + {option.label} + + ), + }))} value={node.roofType} disabled={managedLeanToRoofSegment} /> handleRoofTypeChange(v)} - options={ROOF_TYPE_OPTIONS_3} + options={ROOF_TYPE_OPTIONS_3.map((option) => ({ + ...option, + label: ( + + + {option.label} + + ), + }))} value={node.roofType} disabled={managedLeanToRoofSegment} /> @@ -388,8 +422,7 @@ export default function RoofSegmentPanel() { {node.roofType === 'conical' ? ( handleUpdate({ width: v, depth: v })} precision={2} step={0.5} @@ -400,8 +433,7 @@ export default function RoofSegmentPanel() { <> handleUpdate({ width: v })} precision={2} step={0.5} @@ -410,8 +442,7 @@ export default function RoofSegmentPanel() { /> handleUpdate({ depth: v })} precision={2} step={0.5} @@ -466,7 +497,6 @@ export default function RoofSegmentPanel() { handleUpdate({ wallHeight: v })} precision={2} @@ -482,7 +512,7 @@ export default function RoofSegmentPanel() { handleUpdate({ pitch: v })} precision={0} @@ -614,7 +644,6 @@ export default function RoofSegmentPanel() { handleUpdate({ wallThickness: v })} precision={2} @@ -625,7 +654,6 @@ export default function RoofSegmentPanel() { {!isGlazedRoofSegment(node) && ( handleUpdate({ deckThickness: v })} precision={2} @@ -637,7 +665,6 @@ export default function RoofSegmentPanel() { {node.roofType === 'barrel' ? ( handleUpdate({ overhang: v })} precision={2} @@ -648,7 +675,6 @@ export default function RoofSegmentPanel() { ) : ( handleUpdate({ overhang: v / cosTheta })} precision={2} @@ -660,7 +686,6 @@ export default function RoofSegmentPanel() { {roofTypeHasRakes(node.roofType) && ( handleUpdate({ gableOverhang: v })} precision={2} @@ -672,7 +697,6 @@ export default function RoofSegmentPanel() { {!isGlazedRoofSegment(node) && ( handleUpdate({ shingleThickness: v })} precision={2} @@ -689,7 +713,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 3e94daa8f9..2e205e64b9 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,17 +150,15 @@ export const roofSegmentParametrics: ParametricDescriptor = { label: 'Deck thickness', unit: 'm', min: 0.04, - max: 0.3, step: 0.01, }, - { 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), }, @@ -159,7 +168,6 @@ export const roofSegmentParametrics: ParametricDescriptor = { label: 'Shingle thickness', unit: 'm', min: 0.02, - max: 0.3, step: 0.01, }, { 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..a7563380cb --- /dev/null +++ b/packages/nodes/src/roof/geometry-notice.tsx @@ -0,0 +1,24 @@ +import { type AnyNodeId, 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 failures = useGeometryStatus((state) => state.failures) + const failedId = ids.find((id) => failures.has(id)) + if (!failedId) return null + return ( +
+

+ {failures.get(failedId) === 'invalid-geometry' + ? 'Roof geometry is invalid. The previous shape is still shown. Adjust the dimensions or intersections and retry.' + : '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 21ad65018b..42ce9abc3a 100644 --- a/packages/nodes/src/roof/panel.tsx +++ b/packages/nodes/src/roof/panel.tsx @@ -37,6 +37,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' @@ -288,6 +289,7 @@ export default function RoofPanel() { title={node.name || '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 bc921f3d64..be237a3609 100644 --- a/packages/nodes/src/roof/tool.test.ts +++ b/packages/nodes/src/roof/tool.test.ts @@ -121,3 +121,105 @@ test('a porch drawn against the house over posts stays on its storey', () => { expect(roof.node).toMatchObject({ support: { kind: 'level' } }) 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') + } +}) diff --git a/packages/nodes/src/roof/tool.tsx b/packages/nodes/src/roof/tool.tsx index 8c8a047c08..f6fac9ea2f 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, @@ -441,182 +444,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 } @@ -675,10 +566,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), []) - const corner1Ref = useRef<[number, number, number] | null>(null) const previousGridPosRef = useRef<[number, number] | null>(null) const quarterTurnRef = useRef(false) @@ -1183,6 +1070,7 @@ export const RoofTool: React.FC = () => { ghostWallHeight, previewPitch, roofType, + roofDefaults, ) }, [ footprintSource, @@ -1192,38 +1080,13 @@ export const RoofTool: React.FC = () => { quarterTurn, resolvedPreviewDimensions, roofType, + roofDefaults, ]) - const roofGhostEdges = useMemo(() => { - if ( - invalidStandardWallHover || - !resolvedPreviewDimensions || - (roofType === 'conical' && footprintSource !== 'draw') - ) - return null - const placement = resolveRoofDraftPlacement( - resolvedPreviewDimensions.length, - resolvedPreviewDimensions.width, - quarterTurn, - 0, - roofType, - ) - return buildRoofGhostEdges( - placement.width, - placement.depth, - ghostWallHeight, - previewPitch, - roofType, - ) - }, [ - footprintSource, - ghostWallHeight, - invalidStandardWallHover, - previewPitch, - quarterTurn, - 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+covzg0i8WbM50IPrC3lvcEQPT4lhV82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DFGOaawCkmjgntXwixhsj8cotfd5zFIxLiJxyqIp5GZA/qbdDz/3bGYUGrRxidoglSLr+02a/EZezXR3YorSppgOyCnT6y7jQcGLy01GUskciicwaTkdzdbRezQly7rZ9DTfNl6Q0Ncpx5q9a4zhxkW2OfTDdo1HxIgcl2W5AOJjUh3jxTX5zKG7Sc/jCZN4S93hDDoFyq0ZU/JeHakydbLOUq2zmDw9f9AJQSjfOq2n/sXq2EuiK0Jk/EAYjya4blEMphhCaGOAA9ncN5nW8XxaY77AcnHZ4ut9y3i+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/opening-plane-offset-move.test.tsx b/packages/nodes/src/shared/opening-plane-offset-move.test.tsx index a4ac464b28..92d1566e1a 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, @@ -236,3 +241,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 d3153db432..aad4ef6e0b 100644 --- a/packages/nodes/src/shared/refrigerant-line-selection.tsx +++ b/packages/nodes/src/shared/refrigerant-line-selection.tsx @@ -5,16 +5,16 @@ import { type AnyNodeId, analyzePortConnectivity, type Cursor, + findLevelAncestorId, type LinesetNode, type LiquidLineNode, type PortConnectivity, - pauseSceneHistory, resolveConnectivityUpdates, - resumeSceneHistory, sceneRegistry, + useLiveNodeOverrides, useScene, } from '@pascal-app/core' -import { DimensionPill, swallowNextClick, triggerSFX, useEditor } from '@pascal-app/editor' +import { DimensionPill, isGridSnapActive, triggerSFX, useEditor } from '@pascal-app/editor' import { collectScenePorts, findNearestPortXZ } from '@pascal-app/editor/distribution' import { useViewer } from '@pascal-app/viewer' import { Html } from '@react-three/drei' @@ -23,6 +23,7 @@ import { useEffect, useMemo, useRef, useState } from 'react' import { type Group, type Object3D, Plane, Raycaster, Vector2, Vector3 } from 'three' import { REFRIGERANT_PORT_SYSTEMS } from './port-systems' import { HandleCube, MoveChevron } from './selection-handles' +import { useNodeHandleDrag } from './use-node-handle-drag' type RefrigerantLineKind = 'lineset' | 'liquid-line' type RefrigerantLineNode = LinesetNode | LiquidLineNode @@ -112,6 +113,9 @@ function RefrigerantLineEndpointHandles({ target: Object3D }) { const { camera, gl } = useThree() + const beginDrag = useNodeHandleDrag(line.id) + 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 @@ -129,7 +133,6 @@ function RefrigerantLineEndpointHandles({ index: number initialPath: Point[] current: Point - cleanup: () => void connectivity: PortConnectivity | null detached: boolean } | null>(null) @@ -235,9 +238,6 @@ function RefrigerantLineEndpointHandles({ const initialPath = line.path.map((p) => [...p] as Point) const startPoint = initialPath[index]! const connectivity = analyzePortConnectivity(line as AnyNode, useScene.getState().nodes) - pauseSceneHistory(useScene) - useViewer.getState().setInputDragging(true) - document.body.style.cursor = kind.axis === 'y' ? 'ns-resize' : 'grabbing' setDraggingIndex(index) const isEndpoint = index === 0 || index === initialPath.length - 1 @@ -249,117 +249,78 @@ function RefrigerantLineEndpointHandles({ : 0 const canSwing = swings && isEndpoint && pivot !== null && radius > 1e-6 - const onMove = (event: PointerEvent) => { - const drag = dragRef.current - if (!drag) return - const step = event.shiftKey ? 0 : useEditor.getState().gridSnapStep - const detached = event.altKey - let next: Point | null = null - if (canSwing && pivot) { - const aim = - kind.axis === 'y' - ? swingVertical(event, pivot, startPoint) - : swingHorizontal(event, pivot, startPoint) - if (aim) { - next = [ - snap(pivot[0] + aim[0] * radius, step), - Math.max(0, snap(pivot[1] + aim[1] * radius, step)), - snap(pivot[2] + aim[2] * radius, step), - ] + dragRef.current = { index, initialPath, current: startPoint, connectivity, detached: false } + beginDrag({ + nodeId: line.id, + handle: 'endpoint', + cursor: kind.axis === 'y' ? 'ns-resize' : 'grabbing', + onEnd: () => { + dragRef.current = null + setDraggingIndex(null) + }, + onMove: (event, preview) => { + const drag = dragRef.current + if (!drag) return + const step = isGridSnapActive() ? useEditor.getState().gridSnapStep : 0 + const detached = event.altKey + let next: Point | null = null + if (canSwing && pivot) { + const aim = + kind.axis === 'y' + ? swingVertical(event, pivot, startPoint) + : swingHorizontal(event, pivot, startPoint) + if (aim) { + next = [ + snap(pivot[0] + aim[0] * radius, step), + Math.max(0, snap(pivot[1] + aim[1] * radius, step)), + snap(pivot[2] + aim[2] * radius, step), + ] + } + } else if (kind.axis === 'y') { + const y = intersectVerticalY(event.clientX, event.clientY, toWorld(startPoint)) + if (y !== null) next = [startPoint[0], Math.max(0, snap(y, step)), startPoint[2]] + } else { + const plane = new Plane().setFromNormalAndCoplanarPoint(UP, toWorld(startPoint)) + const hit = intersect(event.clientX, event.clientY, plane) + if (hit) { + const local = toLocal(hit) + const [dx, dz] = kind.dir + const t = snap((local[0] - startPoint[0]) * dx + (local[2] - startPoint[2]) * dz, step) + next = [startPoint[0] + t * dx, startPoint[1], startPoint[2] + t * dz] + } } - } else if (kind.axis === 'y') { - const y = intersectVerticalY(event.clientX, event.clientY, toWorld(startPoint)) - if (y !== null) next = [startPoint[0], Math.max(0, snap(y, step)), startPoint[2]] - } else { - const plane = new Plane().setFromNormalAndCoplanarPoint(UP, toWorld(startPoint)) - const hit = intersect(event.clientX, event.clientY, plane) - if (hit) { - const local = toLocal(hit) - const [dx, dz] = kind.dir - const t = snap((local[0] - startPoint[0]) * dx + (local[2] - startPoint[2]) * dz, step) - next = [startPoint[0] + t * dx, startPoint[1], startPoint[2] + t * dz] + if (!next) return + if (isEndpoint) { + const port = findNearestPortXZ( + [next[0], next[1], next[2]], + collectScenePorts({ + excludeNodeId: line.id, + systems: REFRIGERANT_PORT_SYSTEMS, + levelId: (findLevelAncestorId(line.id, useScene.getState().nodes) ?? undefined) as + | AnyNodeId + | undefined, + }), + PORT_SNAP_RADIUS_M, + ) + if (port) next = [port.position[0], port.position[1], port.position[2]] } - } - if (!next) return - if (isEndpoint) { - const port = findNearestPortXZ( - [next[0], next[1], next[2]], - collectScenePorts({ excludeNodeId: line.id, systems: REFRIGERANT_PORT_SYSTEMS }), - PORT_SNAP_RADIUS_M, + if ( + next[0] === drag.current[0] && + next[1] === drag.current[1] && + next[2] === drag.current[2] && + detached === drag.detached ) - if (port) next = [port.position[0], port.position[1], port.position[2]] - } - if (next[0] === drag.current[0] && next[1] === drag.current[1] && next[2] === drag.current[2]) - return - drag.current = next - drag.detached = detached - if (step > 0) triggerSFX('sfx:grid-snap') - const path = line.path.map((p, i) => (i === drag.index ? next! : p)) as Point[] - useScene - .getState() - .updateNodes([ + return + drag.current = next + drag.detached = detached + if (step > 0) triggerSFX('sfx:grid-snap') + const path = line.path.map((p, i) => (i === drag.index ? next! : p)) as Point[] + preview([ { id: line.id as AnyNodeId, data: { path } as Partial }, ...(detached ? [] : followUpdates(drag.connectivity, path)), ]) - } - - const onUp = () => { - const drag = dragRef.current - if (!drag) return - swallowNextClick() - drag.cleanup() - dragRef.current = null - setDraggingIndex(null) - const detached = drag.detached - const finalPath = drag.initialPath.map((p, i) => - i === drag.index ? drag.current : p, - ) as Point[] - const revert = detached - ? [] - : (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]), - ]) - resumeSceneHistory(useScene) - const moved = finalPath[drag.index]!.some( - (v, axis) => v !== drag.initialPath[drag.index]![axis], - ) - if (moved) { - useScene - .getState() - .updateNodes([ - { id: line.id as AnyNodeId, data: { path: finalPath } as Partial }, - ...(detached ? [] : followUpdates(drag.connectivity, finalPath)), - ]) - } - } - - const cleanup = () => { - window.removeEventListener('pointermove', onMove) - window.removeEventListener('pointerup', onUp) - window.removeEventListener('pointercancel', onUp) - useViewer.getState().setInputDragging(false) - document.body.style.cursor = '' - } - - dragRef.current = { - index, - initialPath, - current: startPoint, - cleanup, - connectivity, - detached: false, - } - window.addEventListener('pointermove', onMove) - window.addEventListener('pointerup', onUp) - window.addEventListener('pointercancel', onUp) + }, + }) } const endpointArrows = useMemo(() => getEndpointArrows(line), [line]) @@ -399,9 +360,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..c439ab6dec --- /dev/null +++ b/packages/nodes/src/shared/selection-handles.test.tsx @@ -0,0 +1,221 @@ +import { beforeEach, expect, test } from 'bun:test' +import { + type AnyNode, + clearSceneHistory, + DuctFittingNode, + DuctSegmentNode, + getSceneHistoryPauseDepth, + LevelNode, + LinesetNode, + PipeSegmentNode, + useLiveNodeOverrides, + useScene, +} from '@pascal-app/core' +import { 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 pointer('keydown', undefined, { key: 'Escape' }) + 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/shared/use-node-handle-drag.ts b/packages/nodes/src/shared/use-node-handle-drag.ts new file mode 100644 index 0000000000..1c3afffd06 --- /dev/null +++ b/packages/nodes/src/shared/use-node-handle-drag.ts @@ -0,0 +1,116 @@ +import { + type AnyNode, + type AnyNodeId, + beginSceneHistoryPauseSession, + emitter, + useLiveNodeOverrides, + useScene, +} from '@pascal-app/core' +import { swallowNextClick, useInteractionScope } from '@pascal-app/editor' +import { useViewer } from '@pascal-app/viewer' +import { useCallback, useEffect, useRef } from 'react' + +type NodeUpdate = { id: AnyNodeId; data: Partial } +type HandleDragOptions = { + nodeId: AnyNodeId + handle: string + cursor: string + onMove: (event: PointerEvent, preview: (updates: NodeUpdate[]) => void) => void + commitUpdates?: (updates: NodeUpdate[]) => NodeUpdate[] + onEnd: () => void +} + +/** One pointer gesture owns its overrides, listeners, scope and history lease. */ +export function useNodeHandleDrag(nodeId: AnyNodeId) { + const cancelRef = useRef<(() => void) | null>(null) + // biome-ignore lint/correctness/useExhaustiveDependencies: changing the selected node must cancel the previous node's gesture. + useEffect(() => () => cancelRef.current?.(), [nodeId]) + + return useCallback((options: HandleDragOptions) => { + cancelRef.current?.() + const scope = { kind: 'handle-drag' as const, nodeId: options.nodeId, handle: options.handle } + useInteractionScope.getState().begin(scope) + const gesture = useInteractionScope.getState().gesture + const history = beginSceneHistoryPauseSession(useScene) + const previousCursor = document.body.style.cursor + document.body.style.cursor = options.cursor + useViewer.getState().setInputDragging(true) + let finished = false + let latest: NodeUpdate[] = [] + const fields = new Map() + + const clear = (id: AnyNodeId, keys: string[]) => { + useLiveNodeOverrides.getState().clearFields(id, keys) + if (useScene.getState().nodes[id]) useScene.getState().markDirty(id) + } + const preview = (updates: NodeUpdate[]) => { + if (finished) return + latest = updates.filter(({ id }) => !!useScene.getState().nodes[id]) + const next = new Map(latest.map(({ id, data }) => [id, Object.keys(data)])) + for (const [id, keys] of fields) { + const removed = keys.filter((key) => !next.get(id)?.includes(key)) + if (removed.length) clear(id, removed) + } + fields.clear() + for (const [id, keys] of next) fields.set(id, keys) + useLiveNodeOverrides.getState().setMany(latest.map(({ id, data }) => [id, data])) + for (const { id } of latest) useScene.getState().markDirty(id) + } + const finish = (commit: boolean) => { + if (finished) return + finished = true + window.removeEventListener('pointermove', onMove) + window.removeEventListener('pointerup', onUp) + window.removeEventListener('pointercancel', onCancel) + window.removeEventListener('blur', onCancel) + window.removeEventListener('keydown', onKeyDown) + emitter.off('tool:cancel', onCancel) + unsubscribeScope() + cancelRef.current = null + swallowNextClick() + try { + const nodes = useScene.getState().nodes + const changed = latest.filter(({ id, data }) => { + const node = nodes[id] + return ( + node && + Object.entries(data).some( + ([key, value]) => + JSON.stringify((node as Record)[key]) !== JSON.stringify(value), + ) + ) + }) + if (commit && changed.length) { + const updates = options.commitUpdates?.(changed) ?? changed + history.commitStep(() => useScene.getState().updateNodes(updates)) + } + } finally { + for (const [id, keys] of fields) clear(id, keys) + history.end() + useViewer.getState().setInputDragging(false) + if (document.body.style.cursor === options.cursor) + document.body.style.cursor = previousCursor + if (useInteractionScope.getState().gesture === gesture) useInteractionScope.getState().end() + options.onEnd() + } + } + const onMove = (event: PointerEvent) => options.onMove(event, preview) + const onUp = () => finish(true) + const onCancel = () => finish(false) + const onKeyDown = (event: KeyboardEvent) => { + if (event.key !== 'Escape') return + event.preventDefault() + onCancel() + } + const unsubscribeScope = useInteractionScope.subscribe((state) => { + if (state.gesture !== gesture) onCancel() + }) + cancelRef.current = onCancel + window.addEventListener('pointermove', onMove) + window.addEventListener('pointerup', onUp) + window.addEventListener('pointercancel', onCancel) + window.addEventListener('blur', onCancel) + window.addEventListener('keydown', onKeyDown) + emitter.on('tool:cancel', onCancel) + }, []) +} 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 bd525c089c..f67d3dfb87 100644 --- a/packages/nodes/src/window/move-tool.tsx +++ b/packages/nodes/src/window/move-tool.tsx @@ -844,14 +844,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 0229e1d432..87c98e1a01 100644 --- a/packages/viewer/src/index.ts +++ b/packages/viewer/src/index.ts @@ -315,6 +315,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 { 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 5c87fc47a1..557f616ff4 100644 --- a/packages/viewer/src/systems/elevator/elevator-interaction-system.test.ts +++ b/packages/viewer/src/systems/elevator/elevator-interaction-system.test.ts @@ -1,6 +1,6 @@ import { describe, expect, test } from 'bun:test' import { BoxGeometry, Group, Mesh, MeshBasicMaterial, Raycaster, Scene, Vector3 } from 'three' -import { collectElevatorButtons } from './elevator-interaction-system' +import { collectElevatorButtons, pickElevatorButton } from './elevator-interaction-system' describe('elevator buttons', () => { test('a click raycasts only the buttons, past a mesh whose groups have no material', () => { @@ -24,3 +24,32 @@ describe('elevator buttons', () => { expect(raycaster.intersectObjects(buttons, true).map((hit) => hit.object)).toContain(button) }) }) + +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 d5e3a64f37..fe833e4a69 100644 --- a/packages/viewer/src/systems/roof/roof-system.tsx +++ b/packages/viewer/src/systems/roof/roof-system.tsx @@ -45,6 +45,7 @@ import { computeBoundsTree } from 'three-mesh-bvh' import { applyWorldScaleBoxUVs } from '../../lib/box-uv' import { ensureRenderableGeometryAttributes, subtractCsgBrush } from '../../lib/csg-utils' import { isRevealAssembling } from '../construction-reveal/construction-reveal' +import { setGeometryFailure, useGeometryStatus } from '../geometry/geometry-status' function csgGeometry(brush: Brush): THREE.BufferGeometry { return brush.geometry as unknown as THREE.BufferGeometry @@ -447,7 +448,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) + try { + updateMergedRoofGeometry(node as RoofNode, group, nodes) + } catch (error) { + setGeometryFailure(node.id, 'build-failed') + console.error('Roof rebuild failed:', error) + } roofsProcessed++ pendingRoofUpdates.delete(id) @@ -467,7 +473,18 @@ function updateRoofSegmentGeometry( nodes?: Record, adapter?: RoofGeometryAdapter, ) { - const newGeo = generateRoofSegmentGeometry(node, nodes) + let newGeo: THREE.BufferGeometry + try { + newGeo = generateRoofSegmentGeometry(node, nodes) + } 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 @@ -496,70 +513,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( @@ -589,7 +607,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]), @@ -668,6 +691,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 } @@ -789,6 +813,7 @@ function updateMergedRoofGeometry( ) warnedMergedRoofNaNIds.add(roofNode.id) } + setGeometryFailure(roofNode.id, 'invalid-geometry') resultGeo.dispose() if (combined !== shinDeck) shinDeck.geometry.dispose() totalShinSlab.geometry.dispose() @@ -829,9 +854,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) } @@ -851,6 +878,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() @@ -2047,18 +2075,24 @@ export function generateRoofSegmentGeometry( } result.computeVertexNormals() ensureRenderableGeometryAttributes(result) + setGeometryFailure(node.id, null) return result } const brushes = withSegmentUvMatrix(segmentWorldMatrix, () => getRoofSegmentBrushes(node, { fascia: wearsFascia(node, parentRoof) }), ) 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 @@ -2087,8 +2121,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) @@ -2113,6 +2148,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/scripts/column-thumbnail-prompts.json b/scripts/column-thumbnail-prompts.json new file mode 100644 index 0000000000..a6947a5181 --- /dev/null +++ b/scripts/column-thumbnail-prompts.json @@ -0,0 +1,88 @@ +{ + "generator": "image_gen", + "workflow": "Each preset was placed alone using the actual editor column renderer, cropped to the item canvas, passed as the image reference, generated and installed before clearing the scene and placing the next preset.", + "format": { + "type": "webp", + "width": 256, + "height": 256, + "quality": 82, + "alphaQuality": 90 + }, + "images": [ + { + "id": "basicPillar", + "path": "apps/editor/public/icons/column-presets/basicPillar.webp", + "prompt": "Generate a polished gallery thumbnail from the supplied actual-editor screenshot. Treat the screenshot as authoritative: preserve precisely the object's geometry, proportions, all parts, silhouette and camera angle. Change only material and lighting to soft matte lavender/periwinkle clay, subtle ambient occlusion, soft studio highlights. No added ornaments, no extra parts, no text. Single object centered, entirely visible, transparent background, square composition with generous even padding. This is Straight Round pillar. Preserve its slim cylindrical shaft, circular thick top cap and two stepped square base slabs." + }, + { + "id": "squarePillar", + "path": "apps/editor/public/icons/column-presets/squarePillar.webp", + "prompt": "Generate a polished gallery thumbnail from the supplied actual-editor screenshot. Screenshot is authoritative: preserve exactly geometry, proportions, silhouette, parts and camera angle. Only change material/lighting to soft matte lavender/periwinkle clay, ambient occlusion and soft studio highlights. Square Block pillar: rectangular straight shaft, one thick square top slab and one thick square bottom slab as pictured. No additional steps or ornaments. Single centered fully visible object, transparent background, square composition, generous padding. No text." + }, + { + "id": "taperedPillar", + "path": "apps/editor/public/icons/column-presets/taperedPillar.webp", + "prompt": "Create polished gallery thumbnail using supplied screenshot as authoritative geometry reference. Preserve exact silhouette, proportions, camera and every part: slightly tapered round shaft wider at bottom, narrower at top, thick circular cap, two stepped square base slabs. Only restyle material to soft matte lavender/periwinkle clay with soft studio lighting and ambient occlusion. No extra details or ornaments. Isolated single centered fully visible object, square composition with padding, transparent background, no text." + }, + { + "id": "bulgedPillar", + "path": "apps/editor/public/icons/column-presets/bulgedPillar.webp", + "prompt": "Create polished gallery thumbnail from actual-editor screenshot, preserving exact geometry, silhouette, proportions and camera angle. Soft Bulged pillar has a slim round shaft subtly wider in the middle, tapering smoothly toward both ends, thick circular cap, two stepped square base slabs. Do not exaggerate bulge. Only change to soft matte lavender/periwinkle clay material with soft studio highlights and ambient occlusion. Transparent background, one centered fully visible object, square composition padded evenly, no text, no extra parts or ornaments." + }, + { + "id": "hourglassPillar", + "path": "apps/editor/public/icons/column-presets/hourglassPillar.webp", + "prompt": "Make polished gallery thumbnail from actual-editor screenshot. Geometry reference is authoritative: preserve exact silhouette, proportions, all parts and camera. Slim round Hourglass pillar shaft with subtle inward waist, slightly wider at both ends, thick circular cap and two stepped square base slabs. Do not exaggerate waist. Change only material and lighting to soft matte lavender/periwinkle clay, soft studio highlights, subtle ambient occlusion. Single centered entirely visible object on transparent background, square padded composition. No text or added ornaments." + }, + { + "id": "aFrameSupport", + "path": "apps/editor/public/icons/column-presets/aFrameSupport.webp", + "prompt": "Restyle actual-editor screenshot into polished lavender gallery icon. Preserve precisely the pictured geometry, all proportions and camera angle: just TWO straight rectangular beams leaning together at top, open inverted-V A-frame, NO horizontal crossbar, NO base plates, NO top plate. Keep beam lengths, thickness and spacing exact. Soft matte lavender/periwinkle clay, soft studio light, subtle ambient occlusion. One centered fully visible object, transparent background, square padded composition, no text or extra geometry." + }, + { + "id": "yFrameSupport", + "path": "apps/editor/public/icons/column-presets/yFrameSupport.webp", + "prompt": "Create polished gallery thumbnail from screenshot of actual Y Support. Preserve exact geometry, camera, proportions, angles and silhouette: one vertical rectangular stem splitting into two straight rectangular upper arms. No caps, bases, plates or additional beams. Only change surface to matte lavender/periwinkle clay, soft studio lighting and subtle ambient occlusion. Keep screenshot orientation and relative lengths. One centered fully visible object, transparent background, square padded composition, no text." + }, + { + "id": "vFrameSupport", + "path": "apps/editor/public/icons/column-presets/vFrameSupport.webp", + "prompt": "Restyle this actual-editor screenshot into a polished gallery thumbnail. Preserve exact geometry and view: two long narrow rectangular beams make a tall narrow V meeting at bottom, no vertical stem, no plates, no crossbars. Keep exact beam thickness, angles and proportions from screenshot. Soft matte lavender/periwinkle clay with soft studio highlights and subtle ambient occlusion. Transparent background, one fully visible centered object, square composition and generous even padding. No text, no invented parts." + }, + { + "id": "xBraceSupport", + "path": "apps/editor/public/icons/column-presets/xBraceSupport.webp", + "prompt": "Create polished gallery thumbnail from supplied actual-editor screenshot. Preserve exact geometry, camera, silhouette and proportions: two long straight rectangular beams cross at center into a tall narrow X. No other beams, plates, bolts or ornaments. Keep screenshot angles and thickness. Restyle only material/lighting to soft matte lavender/periwinkle clay, soft studio highlights, ambient occlusion. Single centered entirely visible object, transparent background, padded square composition, no text." + }, + { + "id": "kBraceSupport", + "path": "apps/editor/public/icons/column-presets/kBraceSupport.webp", + "prompt": "Restyle screenshot into polished gallery thumbnail, preserving EXACT pictured geometry, orientation and camera. This K brace has a full-height vertical rectangular beam on the RIGHT, and two diagonal rectangular beams branching from its midpoint toward UPPER LEFT and LOWER LEFT. Preserve lengths, angles, thickness, depth and silhouette from screenshot. Do not mirror or rotate. No additional parts. Soft matte lavender/periwinkle clay, soft studio lighting, subtle ambient occlusion. Single centered entirely visible object on transparent background, square padded composition, no text." + }, + { + "id": "singleStrutSupport", + "path": "apps/editor/public/icons/column-presets/singleStrutSupport.webp", + "prompt": "Make a polished gallery thumbnail using actual-editor screenshot as exact geometry reference. One single long thin rectangular straight beam leaning diagonally from lower left to upper right. Preserve exact length-to-thickness proportions, angle, camera and flat ends. No plates or extra objects. Change only to soft matte lavender/periwinkle clay material, soft studio highlights, subtle ambient occlusion. Fully visible centered single object, transparent background, padded square composition. No text." + }, + { + "id": "tripodSupport", + "path": "apps/editor/public/icons/column-presets/tripodSupport.webp", + "prompt": "Restyle actual-editor screenshot into polished gallery thumbnail, preserving EXACT geometry, camera, silhouette and proportions. Three straight slim rectangular legs meet at a single high apex and spread to three distinct feet: left slanting leg, near-central front leg, right rear leg, exactly as shown. Keep all three visible, no extra beams or connectors, no platform, no plates. Soft matte lavender/periwinkle clay, soft studio highlights, subtle ambient occlusion. Centered entirely visible isolated object, transparent background, square padded composition, no text." + }, + { + "id": "trestleSupport", + "path": "apps/editor/public/icons/column-presets/trestleSupport.webp", + "prompt": "Restyle actual-editor screenshot into polished gallery thumbnail. Screenshot is authoritative for exact geometry and camera: tall trestle composed of FOUR long splayed rectangular legs in two inverted-V pairs connected by ONE narrow top ridge beam. Preserve the pictured overlapping legs, proportions and orientation precisely. No horizontal lower crossbars, no platforms, no plates. Soft matte lavender/periwinkle clay, soft studio highlights, subtle ambient occlusion. Single centered fully visible object, transparent background, square padded composition, no text." + }, + { + "id": "portalFrameSupport", + "path": "apps/editor/public/icons/column-presets/portalFrameSupport.webp", + "prompt": "Make polished gallery thumbnail using supplied actual-editor screenshot as authoritative geometry. Preserve exactly the tall portal frame: TWO vertical slim rectangular posts connected by ONE top rectangular beam, open at bottom. Keep exact proportions, thickness, orientation, camera perspective and silhouette. No bottom beam, no plates or extra parts. Only restyle surface to soft matte lavender/periwinkle clay with soft studio highlights and ambient occlusion. Single centered fully visible object, transparent background, padded square composition, no text." + }, + { + "id": "boxFrameSupport", + "path": "apps/editor/public/icons/column-presets/boxFrameSupport.webp", + "prompt": "Restyle this actual-editor screenshot into a polished gallery thumbnail. Preserve exactly its geometry, proportions, silhouette and camera: tall open rectangular cuboid frame, FOUR vertical rectangular corner posts connected by four top perimeter beams and four bottom perimeter beams. All sides hollow, no filled surfaces, no diagonal bracing. Keep precise relative heights, widths and slim beam thickness from screenshot. Soft matte lavender/periwinkle clay material, soft studio highlights, subtle ambient occlusion. One centered entirely visible object, transparent background, padded square composition. No text or added parts." + } + ] +} diff --git a/scripts/elevator-thumbnail-prompts.json b/scripts/elevator-thumbnail-prompts.json new file mode 100644 index 0000000000..91f209d8fb --- /dev/null +++ b/scripts/elevator-thumbnail-prompts.json @@ -0,0 +1,20 @@ +{ + "workflow": "Place each actual preset alone, crop the object screenshot, generate and install the WebP, then clear and repeat.", + "images": [ + { + "id": "passenger", + "path": "apps/editor/public/icons/elevator-presets/passenger.webp", + "prompt": "Create a polished gallery thumbnail based on this actual editor screenshot. Preserve the exact geometry, silhouette, camera angle and proportions: tall rectangular solid elevator shaft with two stacked center-opening doors, floor indicator above each door and a small call panel beside each. Keep all details in their actual positions. Apply soft matte lavender/periwinkle clay material to the shaft, slightly darker lavender metal doors, retain small dark control screens. Soft studio lighting, subtle ambient occlusion. One centered fully visible object with even padding, square transparent background. No added objects, labels, people, extra floors or invented features." + }, + { + "id": "service", + "path": "apps/editor/public/icons/elevator-presets/service.webp", + "prompt": "Create a polished gallery thumbnail using this actual editor screenshot as the authoritative geometry reference. Preserve exact proportions, silhouette and camera: tall wide/deep solid rectangular service elevator shaft, two stacked broad single sliding door panels with horizontal segmentation, one indicator above and call panel beside each. Keep all parts exactly positioned. Soft matte lavender/periwinkle clay shaft, slightly darker lavender metal doors, dark controls. Soft studio lighting and ambient occlusion. Fully visible centered single object, padded square composition, transparent background. No added details, text, people or extra floors." + }, + { + "id": "glass", + "path": "apps/editor/public/icons/elevator-presets/glass.webp", + "prompt": "Generate a polished gallery thumbnail from this actual editor screenshot, preserving its exact geometry, camera, proportions and part positions. Tall rectangular two-level elevator: translucent pale blue glass side shaft panel, solid front facade with two stacked glass-frame center-opening doors, cap on top, visible lower cab through side glass, small dark call panels and floor indicators. Restyle the solid frame and cab to soft matte lavender/periwinkle clay; glass stays lightly translucent with cool lavender-blue tint. Do not add or remove any structures. Single entirely visible centered object, square padded composition, transparent background, soft studio lighting, no text or people." + } + ] +} diff --git a/scripts/roof-thumbnail-prompts.json b/scripts/roof-thumbnail-prompts.json new file mode 100644 index 0000000000..c8e9f37017 --- /dev/null +++ b/scripts/roof-thumbnail-prompts.json @@ -0,0 +1,58 @@ +{ + "generator": "image_gen", + "workflow": "For each roof, place the actual roof alone, crop its screenshot, generate from that reference, install the WebP, clear the scene, then place the next roof.", + "format": { + "type": "webp", + "width": 256, + "height": 256, + "quality": 82, + "alphaQuality": 90 + }, + "images": [ + { + "id": "gable", + "path": "apps/editor/public/icons/roof-types/gable.webp", + "prompt": "Create a polished architectural editor gallery thumbnail. Reference image 1 is the authoritative actual GABLE roof geometry: preserve its exact silhouette, proportions, roof slope, two sloped planes, ridge, eave overhangs and triangular end wall, and the same three-quarter camera view. Reference image 2 is STYLE ONLY: match its soft matte lavender/periwinkle clay shading, subtle ambient occlusion, clean edges, and transparent background. Restyle the roof and end wall in harmonious lavender tones. Remove the screenshot background, ground, textures, grid and UI. One fully visible centered roof object with even padding in a square transparent image. No house beneath it, extra features, gutters, text, labels, people, logos or invented geometry." + }, + { + "id": "hip", + "path": "apps/editor/public/icons/roof-types/hip.webp", + "prompt": "Create a polished HIP roof thumbnail from reference image 1, the actual editor roof. Preserve exact geometry and the same elevated three-quarter camera: rectangular footprint, four sloping roof faces meeting at a short central ridge, continuous eave overhang and low wall base. This is a hip roof, with no triangular vertical gable ends. Reference image 2 is style only: match the matte lavender/periwinkle clay material, soft studio lighting, subtle ambient occlusion and clean edges of the existing gable thumbnail. Remove ground, screenshot background and shingle texture. Single complete centered object with even padding, square composition, transparent background. No house, added objects, text or invented structures." + }, + { + "id": "shed", + "path": "apps/editor/public/icons/roof-types/shed.webp", + "prompt": "Generate a polished SHED roof gallery thumbnail. Image 1 is the authoritative geometry: preserve the single rectangular sloping roof plane, high rear edge, low front eave, triangular side infill wall, proportions, overhangs and elevated three-quarter view. Image 2 is style reference only: matte lavender/periwinkle clay, soft studio lighting, subtle ambient occlusion and clean edges. Match that thumbnail family. Remove ground, background, texture, and every UI fragment. Show one complete centered roof with even square padding on a transparent background. Do not add a second slope, house, people, text, gutters or new features." + }, + { + "id": "flat", + "path": "apps/editor/public/icons/roof-types/flat.webp", + "prompt": "Make a polished FLAT roof thumbnail using image 1 as exact geometry reference: a thin flat rectangular roof plate with shallow wall base and slight perimeter overhang, viewed from the same elevated three-quarter angle. Preserve the completely level unbroken top and its proportions. Image 2 is STYLE ONLY: match matte lavender/periwinkle clay, soft lighting and ambient occlusion. Remove screenshot ground, texture and background. One fully visible centered object, padded square transparent background. No pitch, ridge, parapet, extra walls, house, labels or added objects." + }, + { + "id": "gambrel", + "path": "apps/editor/public/icons/roof-types/gambrel.webp", + "prompt": "Create a polished architectural GAMBREL roof thumbnail from screenshot reference 1. Preserve the actual pictured geometry exactly: long central ridge, two slope sections on each side with the longitudinal kink/break, barn-shaped end-wall outline, overhangs, proportions and camera angle. Do not replace the observed shape with a different generic barn roof. Reference 2 is STYLE ONLY, matte lavender/periwinkle clay, soft studio lighting and subtle ambient occlusion. Remove shingle texture and background. One complete centered isolated roof, even padding, square transparent background. No added house, dormers, gutters, text or objects." + }, + { + "id": "dutch", + "path": "apps/editor/public/icons/roof-types/dutch.webp", + "prompt": "Create a polished DUTCH roof gallery thumbnail based strictly on screenshot 1: preserve the broad lower hipped skirt, raised upper gable roof, small triangular white gablet end with its projecting rake board, the slope transition, all proportions, silhouette and same camera. Image 2 is only the desired matte lavender/periwinkle clay style with soft studio light and ambient occlusion. Remove screenshot ground, background and shingle texture. One complete roof, centered with even padding in a square transparent image. Do not simplify into a standard gable or hip, do not add a house, dormers, text or extra objects." + }, + { + "id": "mansard", + "path": "apps/editor/public/icons/roof-types/mansard.webp", + "prompt": "Generate a polished MANSARD roof thumbnail from actual editor screenshot 1. Preserve the exact roof silhouette, rectangular footprint, lower four-sided skirt and distinct inset upper roof with its short ridge, all slope breaks and proportions, at the same elevated three-quarter camera. Follow the screenshot instead of a generic mansard house. Image 2 is STYLE ONLY: matte lavender/periwinkle clay, soft studio lighting, clean shading and ambient occlusion. Remove all ground, background and shingle textures. One complete centered roof, square padded transparent background, no house, windows, extra objects, labels or text." + }, + { + "id": "conical", + "path": "apps/editor/public/icons/roof-types/conical.webp", + "prompt": "Create a polished CONICAL roof thumbnail from actual editor screenshot 1. Preserve exact circular eave, centered pointed apex, straight conical slope, shallow circular wall base, proportions and elevated camera angle. Reference 2 is STYLE ONLY: soft matte lavender/periwinkle clay with clean studio lighting and subtle ambient occlusion. Remove shingle lines, screenshot background and ground. Single fully visible centered cone roof with even square padding, transparent background. No tower, house, added rings, text, labels or objects." + }, + { + "id": "barrel", + "path": "apps/editor/public/icons/roof-types/barrel.webp", + "prompt": "Generate a polished BARREL roof thumbnail from actual editor screenshot 1. Preserve its exact elongated arched roof geometry, circular cross-section, gently faceted curved covering, arched end infill, thin overhang edges, proportions and the same elevated three-quarter camera angle. Image 2 supplies STYLE ONLY: soft matte lavender/periwinkle clay, studio lighting and subtle ambient occlusion. Remove background, ground and shingle texture. One complete centered roof with even padding in a square transparent image. No gable ridge, house, glazing grid, extra features, text or other objects." + } + ] +} diff --git a/wiki/architecture/node-definitions.md b/wiki/architecture/node-definitions.md index 77c0917633..ebc9c91cc1 100644 --- a/wiki/architecture/node-definitions.md +++ b/wiki/architecture/node-definitions.md @@ -645,3 +645,13 @@ What stands in a `room` (walls along it, furniture in it) is revealed together a - [systems.md](systems.md) — per-kind systems, frame-priority ordering, and core/viewer split. - [scene-registry.md](scene-registry.md) — how `sceneRegistry` indexes nodes by ID and type. - [Registry type definitions](../../packages/core/src/registry/types.ts) — schemas, capabilities, parametrics and MCP contracts for node kinds. + + +### Resolving a moved pose + +`capabilities.movable.resolvePosition({ node, position, nodes })` returns the +stored position after snapping. Both the generic 3D mover and 2D plan mover call +it for live preview and again at commit, so a changed support is re-elected at +release. Use it for kind-owned placement rules such as a building-parented +elevator's landing height. It must not write scene state; the framework owns +live previews and the single commit. Omission preserves the proposed position. 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