diff --git a/apps/editor/components/build-tab.tsx b/apps/editor/components/build-tab.tsx index efd3092f49..f669120ad4 100644 --- a/apps/editor/components/build-tab.tsx +++ b/apps/editor/components/build-tab.tsx @@ -539,6 +539,10 @@ export function BuildTab() { + {(activeTool === 'duct-segment' || activeTool === 'pipe-segment') && ( + + )} + {(['duct-fitting', 'pipe-fitting'] as const) .filter((kind) => (kind === 'duct-fitting' ? ductContext : pipeContext)) .map((kind) => ( diff --git a/apps/editor/lib/build-palette.ts b/apps/editor/lib/build-palette.ts index 5b8bd1f385..780e32e8a3 100644 --- a/apps/editor/lib/build-palette.ts +++ b/apps/editor/lib/build-palette.ts @@ -160,7 +160,7 @@ export function activateBuildTool(kind: string): void { useViewer.getState().setSelection({ selectedIds: [], zoneId: null }) editor.setPhase('building') editor.setCatalogCategory(null) - editor.setToolDefaults(kind, null) + if (!definition?.distributionRole) editor.setToolDefaults(kind, null) editor.setMode('build') editor.setTool(kind) } diff --git a/packages/core/src/registry/types.ts b/packages/core/src/registry/types.ts index f7f51ae749..ba678affa0 100644 --- a/packages/core/src/registry/types.ts +++ b/packages/core/src/registry/types.ts @@ -426,6 +426,8 @@ export type ToolOption = { /** Row label. Sentence case, e.g. 'Create from'. */ label: string choices: readonly ToolOptionChoice[] + /** Optional exact numeric entry instead of choice buttons. */ + input?: { min?: number; max?: number; step?: number; unit?: string } /** Subscribe to live value changes (Zustand-store-like); returns unsubscribe. */ subscribe: (onChange: () => void) => () => void /** Current value token. */ diff --git a/packages/editor/src/components/tools/distribution/distribution-run-tool.test.tsx b/packages/editor/src/components/tools/distribution/distribution-run-tool.test.tsx index e14c753226..e3096868c7 100644 --- a/packages/editor/src/components/tools/distribution/distribution-run-tool.test.tsx +++ b/packages/editor/src/components/tools/distribution/distribution-run-tool.test.tsx @@ -1,6 +1,6 @@ import { expect, test } from 'bun:test' import { emitter, type GridEvent, useScene, WallNode } from '@pascal-app/core' -import { useEditor, useInteractionScope } from '@pascal-app/editor' +import { type EditorGridEvent, useEditor, useInteractionScope } from '@pascal-app/editor' import { useThree } from '@react-three/fiber' import { act, create } from '@react-three/test-renderer' import { useDistributionRunTool } from './distribution-run-tool' @@ -123,3 +123,94 @@ test.each(['duct-segment', 'pipe-segment'] as const)( } }, ) + +test.each(['duct-segment', 'pipe-segment'] as const)( + '%s routes at an exact elevation and updates a vertical target without pointer movement', + async (toolName) => { + const previousEditor = useEditor.getState() + const previousScope = useInteractionScope.getState() + const previousWindow = Object.getOwnPropertyDescriptor(globalThis, 'window') + const previousAct = Object.getOwnPropertyDescriptor(globalThis, 'IS_REACT_ACT_ENVIRONMENT') + Object.defineProperty(globalThis, 'window', { + value: new EventTarget(), + configurable: true, + writable: true, + }) + Object.defineProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT', { + value: true, + configurable: true, + writable: true, + }) + let tool: ReturnType | undefined + const commits: Array<[number, number, number]> = [] + let routingMode: 'horizontal' | 'vertical' = 'horizontal' + let targetElevation = 4 + function Host() { + const { gl } = useThree() + gl.domElement.getBoundingClientRect = () => + ({ left: 0, top: 0, width: 100, height: 100 }) as DOMRect + tool = useDistributionRunTool({ + active: true, + levelId: 'level_test', + toolName, + routingMode, + elevation: 2, + targetElevation, + getPorts: () => [], + findBody: () => null, + commit: ({ end }) => { + commits.push(end) + return { nextStart: end, nextConnection: { port: null, body: null } } + }, + }) + return null + } + let renderer: Awaited> | undefined + const event = (x: number): GridEvent => ({ + position: [x, 0, 0], + localPosition: [x, 0, 0], + nativeEvent: {} as GridEvent['nativeEvent'], + }) + try { + useEditor.setState({ snappingModeByContext: { wall: 'off', polygon: 'off', item: 'off' } }) + useEditor.getState().showView('2d') + renderer = await create() + await act(async () => { + emitter.emit('grid:click', event(1)) + }) + expect(tool?.start).toEqual([1, 2, 0]) + await act(async () => { + emitter.emit('grid:click', event(3)) + }) + expect(commits).toEqual([[3, 2, 0]]) + await act(async () => { + const planEvent: EditorGridEvent = { + ...event(7), + screenProjection: { pointer: [120, 180], localToScreen: [1, 0, 0, 1, 0, 0] }, + } + emitter.emit('grid:move', planEvent) + }) + expect(tool?.cursorScreen).toEqual({ x: 120, y: 180, depth: 0 }) + await act(async () => useEditor.getState().showView('3d')) + expect(tool?.cursorScreen).toBeNull() + routingMode = 'vertical' + await renderer.update() + expect(tool?.cursor).toEqual([3, 4, 0]) + targetElevation = 5 + await renderer.update() + expect(tool?.cursor).toEqual([3, 5, 0]) + await act(async () => { + emitter.emit('grid:click', event(7)) + }) + expect(commits.at(-1)).toEqual([3, 5, 0]) + } finally { + await renderer?.unmount() + useEditor.setState(previousEditor) + useInteractionScope.setState(previousScope) + if (previousWindow) Object.defineProperty(globalThis, 'window', previousWindow) + else Reflect.deleteProperty(globalThis, 'window') + if (previousAct) Object.defineProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT', previousAct) + else Reflect.deleteProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT') + } + }, +) diff --git a/packages/editor/src/components/tools/distribution/distribution-run-tool.tsx b/packages/editor/src/components/tools/distribution/distribution-run-tool.tsx index 3a772abd50..b679d4d87b 100644 --- a/packages/editor/src/components/tools/distribution/distribution-run-tool.tsx +++ b/packages/editor/src/components/tools/distribution/distribution-run-tool.tsx @@ -11,6 +11,7 @@ import { isGridSnapActive, isMagneticSnapActive, isTypingTarget, + isViewVisible, markToolCancelConsumed, publishPlacementSurface, triggerSFX, @@ -218,6 +219,11 @@ export type DistributionRunToolConfig = { active: boolean levelId: AnyNodeId | null toolName: string + routingMode?: 'surface' | 'horizontal' | 'vertical' + /** Level-local centreline elevation, or the target height for a vertical leg. */ + elevation?: number + targetElevation?: number + connectCrossings?: boolean initialStart?: RunPoint | null initialConnection?: RunConnection | null getPorts: () => ScenePort[] @@ -516,6 +522,7 @@ function surfacePointFromEvent( export function useDistributionRunTool(config: DistributionRunToolConfig) { const { camera, gl } = useThree() + const planVisible = useEditor((state) => isViewVisible(state, '2d')) const initialStartRef = useRef( config.initialStart ? [...config.initialStart] : null, ) @@ -526,6 +533,7 @@ export function useDistributionRunTool(config: DistributionRunToolConfig) { const [cursor, setCursor] = useState(initialStartRef.current) const [snapTarget, setSnapTarget] = useState(null) const [snapScreen, setSnapScreen] = useState(null) + const [cursorScreen, setCursorScreen] = useState(null) const [endConnection, setEndConnection] = useState({ port: null, body: null, @@ -584,6 +592,7 @@ export function useDistributionRunTool(config: DistributionRunToolConfig) { const typed = Number.parseFloat(lengthInputRef.current) if ( !currentStart || + configRef.current.routingMode === 'vertical' || !Number.isFinite(typed) || typed <= 0 || resolved.port || @@ -614,23 +623,26 @@ export function useDistributionRunTool(config: DistributionRunToolConfig) { const hit = surfacePointFromEvent(event, adapter.levelId) const currentStart = startRef.current const previous = lastResolvedRef.current - const lockedWallTarget = currentStart ? lockedWallTargetRef.current : null + const explicitRoute = adapter.routingMode && adapter.routingMode !== 'surface' + const lockedWallTarget = currentStart && !explicitRoute ? lockedWallTargetRef.current : null const lockedWallHit = lockedWallTarget && isSameRunWallSurface(lockedWallTarget, event.surfaceHit) - const working = lockedWallTarget - ? { - ...lockedWallTarget.frame, - origin: lockedWallTarget.frame.origin.map( - (value, index) => - value + - lockedWallTarget.frame.normal[index]! * - (adapter.surfaceClearance?.(lockedWallTarget) ?? 0), - ) as RunPoint, - } - : !event.surfaceHit && previous?.surfaceTarget?.kind === 'wall' && currentStart - ? createRunSurfaceFrame(currentStart, UP) - : (previous?.frame ?? (currentStart ? createRunSurfaceFrame(currentStart) : null)) - const hasSurface = !!event.surfaceHit || !working || !event.localRay + const working = explicitRoute + ? createRunSurfaceFrame([0, currentStart?.[1] ?? adapter.elevation ?? 0, 0]) + : lockedWallTarget + ? { + ...lockedWallTarget.frame, + origin: lockedWallTarget.frame.origin.map( + (value, index) => + value + + lockedWallTarget.frame.normal[index]! * + (adapter.surfaceClearance?.(lockedWallTarget) ?? 0), + ) as RunPoint, + } + : !event.surfaceHit && previous?.surfaceTarget?.kind === 'wall' && currentStart + ? createRunSurfaceFrame(currentStart, UP) + : (previous?.frame ?? (currentStart ? createRunSurfaceFrame(currentStart) : null)) + const hasSurface = !explicitRoute && (!!event.surfaceHit || !working || !event.localRay) const target = lockedWallTarget ?? (hasSurface ? hit.target : null) const hitForCursor = lockedWallTarget ? lockedWallHit @@ -643,16 +655,35 @@ export function useDistributionRunTool(config: DistributionRunToolConfig) { hit: hitForCursor, working, ray: event.localRay, - fallback: previous?.point ?? currentStart ?? hit.point, + fallback: explicitRoute ? [...hit.point] : (previous?.point ?? currentStart ?? hit.point), clearance: adapter.surfaceClearance?.(target) ?? 0, }) + if (explicitRoute) { + const elevation = currentStart?.[1] ?? adapter.elevation ?? 0 + resolved.point[1] = elevation + if (currentStart && adapter.routingMode === 'vertical') { + return { + point: [currentStart[0], adapter.targetElevation ?? currentStart[1], currentStart[2]], + frame: createRunSurfaceFrame(currentStart), + surfaceTarget: null, + snapped: null, + directionMode: 'vertical', + port: null, + body: null, + } + } + } const bypass = event.nativeEvent?.altKey === true const gridStep = !bypass && isGridSnapActive() ? useEditor.getState().gridSnapStep : 0 const angleLocked = !bypass && (isAngleSnapActive() || isGridSnapActive()) let point = currentStart ? resolved.point : snapRunPointToSurface(resolved.point, resolved.frame, gridStep) - const forcedDirection = forcedDirectionRef.current + const selectedDirection = forcedDirectionRef.current + const forcedDirection = + explicitRoute && selectedDirection && Math.abs(selectedDirection[1]) > 1e-6 + ? null + : selectedDirection if (currentStart && forcedDirection) { point = projectRunToDirection(currentStart, point, forcedDirection) } @@ -665,7 +696,11 @@ export function useDistributionRunTool(config: DistributionRunToolConfig) { if (currentStart && gridStep > 0) { point = snapRunLength(currentStart, point, gridStep) } - const sample = { frame: resolved.frame, surfaceTarget: target } + const drawingTarget: RunSurfaceTarget | null = + explicitRoute && adapter.levelId + ? { kind: 'surface', levelId: adapter.levelId, frame: resolved.frame } + : target + const sample = { frame: resolved.frame, surfaceTarget: drawingTarget } const native = (event.nativeEvent ?? {}) as { clientX?: number clientY?: number @@ -709,7 +744,10 @@ export function useDistributionRunTool(config: DistributionRunToolConfig) { if (bypass || !(isGridSnapActive() || isMagneticSnapActive() || isAngleSnapActive())) return null const source = startConnectionRef.current.port - const hit = findScreenPort(adapter.getPorts(), pointer, projectConnection, source) + const ports = adapter + .getPorts() + .filter((port) => !explicitRoute || Math.abs(port.position[1] - point[1]) < 1e-4) + const hit = findScreenPort(ports, pointer, projectConnection, source) if (hit) { return { frame: createRunSurfaceFrame([...hit.port.position]), @@ -722,8 +760,14 @@ export function useDistributionRunTool(config: DistributionRunToolConfig) { body: null, } } - const body = adapter.findBody(candidate, target) - if (body && acceptsConnection(body.point) && body.nodeId !== source?.nodeId) { + const body = + adapter.connectCrossings === false ? null : adapter.findBody(candidate, drawingTarget) + if ( + body && + (!explicitRoute || Math.abs(body.point[1] - point[1]) < 1e-4) && + acceptsConnection(body.point) && + body.nodeId !== source?.nodeId + ) { return { ...sample, point: body.point, @@ -739,7 +783,7 @@ export function useDistributionRunTool(config: DistributionRunToolConfig) { if (connection) return connection // Rank displayed directions before a surface projection discards height. if (currentStart && event.localRay && !bypass && (forcedDirection || angleLocked)) { - const source = startConnectionRef.current.port?.direction ?? null + const source = explicitRoute ? null : (startConnectionRef.current.port?.direction ?? null) const candidates = forcedDirection ? [forcedDirection] : source @@ -795,7 +839,7 @@ export function useDistributionRunTool(config: DistributionRunToolConfig) { forcedDirection || (Math.abs(directionHit.direction[1]) > 1e-6 && target?.kind === 'floor') ? null - : target, + : drawingTarget, snapped: null, directionMode: 'angle', port: null, @@ -943,7 +987,12 @@ export function useDistributionRunTool(config: DistributionRunToolConfig) { setAltActive(false) } + const updateCursorScreen = (event: GridEvent) => { + const pointer = getGridEventScreenProjection(event)?.pointer + setCursorScreen(pointer ? { x: pointer[0], y: pointer[1], depth: 0 } : null) + } const onMove = (event: RunPointerEvent) => { + updateCursorScreen(event) lastPointerRef.current = event const clientY = (event.nativeEvent as { clientY?: number } | undefined)?.clientY if (typeof clientY === 'number') lastClientYRef.current = clientY @@ -965,6 +1014,7 @@ export function useDistributionRunTool(config: DistributionRunToolConfig) { } const onClick = (event: GridEvent) => { + updateCursorScreen(event) event.nativeEvent?.stopPropagation?.() const currentStart = startRef.current if (altAnchorRef.current && currentStart) { @@ -985,8 +1035,10 @@ export function useDistributionRunTool(config: DistributionRunToolConfig) { port: resolved.port, body: resolved.port ? null : resolved.body, } - if (shouldLockRunWallSurface(resolved.surfaceTarget, connection)) { - lockedWallTargetRef.current = resolved.surfaceTarget + if (!configRef.current.routingMode || configRef.current.routingMode === 'surface') { + if (shouldLockRunWallSurface(resolved.surfaceTarget, connection)) { + lockedWallTargetRef.current = resolved.surfaceTarget + } } triggerSFX('sfx:grid-snap') startConnectionRef.current = connection @@ -1028,6 +1080,11 @@ export function useDistributionRunTool(config: DistributionRunToolConfig) { setAltActive(true) return } + if ( + configRef.current.routingMode === 'vertical' && + (event.key === 'Tab' || /^[0-9.,]$/.test(event.key)) + ) + return if ( event.key === 'Tab' && startRef.current && @@ -1037,7 +1094,10 @@ export function useDistributionRunTool(config: DistributionRunToolConfig) { ) { event.preventDefault() event.stopImmediatePropagation() - const source = startConnectionRef.current.port?.direction + const source = + configRef.current.routingMode === 'horizontal' + ? null + : startConnectionRef.current.port?.direction const candidates = source ? run3DDirectionCandidates(source) : runHorizontalDirectionCandidates(null) @@ -1143,18 +1203,39 @@ export function useDistributionRunTool(config: DistributionRunToolConfig) { } }, [camera, gl, config.active, updateLengthInput]) + // The resolver reads config through a ref; changing these controls must refresh a stationary cursor. + // biome-ignore lint/correctness/useExhaustiveDependencies: configuration changes invalidate the cursor + useEffect(() => { + forcedDirectionRef.current = null + if (config.routingMode !== 'surface') lockedWallTargetRef.current = null + refreshCursor() + }, [ + config.routingMode, + config.elevation, + config.targetElevation, + config.connectCrossings, + refreshCursor, + ]) + return { refreshCursor, + routingMode: config.routingMode, start, cursor, snapTarget, snapScreen, + cursorScreen: planVisible ? cursorScreen : null, altActive, directionMode, lengthInput, validationMessage, onLengthInputChange: updateLengthInput, onDirectionSelect: (direction: RunPoint) => { + if ( + configRef.current.routingMode === 'vertical' || + (configRef.current.routingMode === 'horizontal' && Math.abs(direction[1]) > 1e-6) + ) + return forcedDirectionRef.current = direction setDirectionMode('angle') refreshCursorRef.current() @@ -1175,6 +1256,7 @@ export function DistributionRunCursor({ extraParts = [], cursorRef, directionMode, + routingMode, startDirection, lengthInput, validationMessage, @@ -1190,6 +1272,7 @@ export function DistributionRunCursor({ extraParts?: DimensionPillPart[] cursorRef?: RefObject directionMode: RunDirectionMode + routingMode?: 'surface' | 'horizontal' | 'vertical' startDirection?: readonly [number, number, number] | null lengthInput?: string validationMessage?: string | null @@ -1199,8 +1282,8 @@ export function DistributionRunCursor({ }) { const lengthFieldRef = useRef(null) useEffect(() => { - if (start) lengthFieldRef.current?.focus() - }, [start]) + if (start && routingMode !== 'vertical') lengthFieldRef.current?.focus() + }, [start, routingMode]) if (!cursor) return null const parts: DimensionPillPart[] = [ ...(start @@ -1261,9 +1344,9 @@ export function DistributionRunCursor({ cursor={cursor} mode={directionMode} snapped={!!snapTarget} - sourceDirection={startDirection ?? null} + sourceDirection={routingMode === 'horizontal' ? null : (startDirection ?? null)} start={start} - onDirectionSelect={onDirectionSelect} + onDirectionSelect={routingMode === 'vertical' ? undefined : onDirectionSelect} /> )} - {start ? ( + {start && routingMode === 'vertical' ? ( + + Target elevation: {cursor[1].toFixed(2)} m · click or Enter to place + + ) : start ? ( Length:{' '} {option.label} - - {option.choices.map((choice) => { - const selected = active && choice.value === value - const thumbnail = getChoiceThumbnail?.(option, choice.value) - return ( - { - triggerSFX('sfx:menu-click') - option.set(choice.value) - onSelect?.(option, choice.value) - }} - onMouseEnter={() => triggerSFX('sfx:menu-hover')} - type="button" - > - {thumbnail && ( - - )} - {choice.label} - - ) - })} - + {option.input ? ( + + { + const next = event.target.valueAsNumber + if ( + Number.isFinite(next) && + !event.target.validity.rangeUnderflow && + !event.target.validity.rangeOverflow + ) { + option.set(String(next)) + onSelect?.(option, String(next)) + } else event.target.value = value + }} + onKeyDown={(event) => { + if (event.key === 'Enter') event.currentTarget.blur() + }} + /> + {option.input.unit} + + ) : ( + + {option.choices.map((choice) => { + const selected = active && choice.value === value + const thumbnail = getChoiceThumbnail?.(option, choice.value) + return ( + { + triggerSFX('sfx:menu-click') + option.set(choice.value) + onSelect?.(option, choice.value) + }} + onMouseEnter={() => triggerSFX('sfx:menu-hover')} + type="button" + > + {thumbnail && ( + + )} + {choice.label} + + ) + })} + + )} {activeChoice && activeChoice.description ? ( {activeChoice.description} diff --git a/packages/nodes/src/agent-operations/duct-tools.test.ts b/packages/nodes/src/agent-operations/duct-tools.test.ts new file mode 100644 index 0000000000..4e35f57eda --- /dev/null +++ b/packages/nodes/src/agent-operations/duct-tools.test.ts @@ -0,0 +1,398 @@ +import { afterEach, beforeEach, expect, test } from 'bun:test' +import { fileURLToPath } from 'node:url' +import { Client } from '@modelcontextprotocol/sdk/client/index.js' +import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js' +import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js' +import { + type AnyNode, + DuctFittingNode, + DuctSegmentNode, + LevelNode, + nodeRegistry, + registerNode, +} from '@pascal-app/core' +import { SceneBridge } from '@pascal-app/mcp/bridge' +import { createSceneOperations } from '@pascal-app/mcp/operations' +import { registerOperationTool } from '@pascal-app/mcp/tools/shared-tools' +import { ductFittingDefinition, ductSegmentDefinition } from '@pascal-app/nodes' +import { builtinAgentOperations } from '@pascal-app/nodes/agent-operations' +import { builtinAgentTools } from '@pascal-app/nodes/agent-tools' + +let restore: ReturnType +beforeEach(() => { + restore = nodeRegistry._snapshot() + registerNode(ductSegmentDefinition) + registerNode(ductFittingDefinition) +}) +afterEach(() => restore()) +const level = LevelNode.parse({}) +const run = (extra = {}) => + DuctSegmentNode.parse({ + parentId: level.id, + shape: 'round', + diameter: 6, + path: [ + [0, 0, 0], + [6, 0, 0], + ], + ...extra, + }) +const scene = (...nodes: AnyNode[]) => + Object.fromEntries([level, ...nodes].map((node) => [node.id, node])) +const edit = builtinAgentOperations.duct_edit +const context = { activeLevelId: level.id } + +test('duct operation is offered with dimensions and edit scopes', () => { + const contract = builtinAgentTools.tools.find((tool) => tool.name === 'duct_edit')! + expect(contract.runsIn).toBe('operation') + expect(contract.input).toHaveProperty('alignment') +}) + +test('face resize preserves the top of an unconnected rectangular run', () => { + const duct = run({ shape: 'rect', width: 14, height: 8 }) + const result = edit( + scene(duct), + { nodeId: duct.id, action: 'resize', height: 12, alignment: 'top' }, + context, + ) + const resized = { ...duct, ...result.changes!.update![0]!.data } as typeof duct + expect(resized.path[0]![1] + (resized.height * 0.0254) / 2).toBeCloseTo( + (duct.height * 0.0254) / 2, + 8, + ) + expect(duct.path[0]![1]).toBe(0) +}) + +test('branch resize follows an elbow and keeps the two collars joined', () => { + const elbow = DuctFittingNode.parse({ + parentId: level.id, + fittingType: 'elbow', + shape: 'round', + diameter: 6, + position: [3, 0, 0], + rotation: [0, 0, 0], + }) + const a = run({ + path: [ + [0, 0, 0], + [2.8095, 0, 0], + ], + }) + const b = run({ + path: [ + [3, 0, 0.1905], + [3, 0, 4], + ], + }) + const result = edit( + scene(a, b, elbow), + { nodeId: a.id, action: 'resize', scope: 'branch', diameter: 10 }, + context, + ) + const after = scene(a, b, elbow) + for (const update of result.changes!.update!) + after[update.id] = { ...after[update.id], ...update.data } as AnyNode + expect(result.changes!.update).toHaveLength(3) + expect((after[b.id] as typeof b).diameter).toBe(10) + const ports = ductFittingDefinition.ports!(after[elbow.id] as typeof elbow) + expect((after[a.id] as typeof a).path[1]).toEqual([...ports[0]!.position]) + expect((after[b.id] as typeof b).path[0]).toEqual([...ports[1]!.position]) +}) + +test('segment resize inserts a transition while leaving its neighbour fixed', () => { + const a = run({ + path: [ + [0, 0, 0], + [3, 0, 0], + ], + }) + const b = run({ + path: [ + [3, 0, 0], + [6, 0, 0], + ], + }) + const result = edit(scene(a, b), { nodeId: b.id, action: 'resize', diameter: 10 }, context) + expect(result.changes!.update!.map((entry) => entry.id)).toEqual([b.id]) + const adapter = result.changes!.create![0]!.node as typeof DuctFittingNode._output + expect(adapter.fittingType).toBe('reducer') + const ports = ductFittingDefinition.ports!(adapter) + expect([...ports[0]!.position]).toEqual(a.path[1]!) + expect((result.changes!.update![0]!.data as typeof b).path[0]).toEqual([...ports[1]!.position]) +}) + +test('branch resize stops at a tee without resizing its other branches', () => { + const tee = DuctFittingNode.parse({ + parentId: level.id, + fittingType: 'tee', + shape: 'round', + diameter: 6, + position: [0, 0, 0], + }) + const duct = run({ + path: [ + [0.1905, 0, 0], + [6, 0, 0], + ], + }) + const result = edit( + scene(duct, tee), + { nodeId: duct.id, action: 'resize', scope: 'branch', diameter: 10 }, + context, + ) + expect(result.changes!.update!.map((entry) => entry.id)).toEqual([duct.id]) + expect(result.changes!.create).toHaveLength(1) +}) + +test('face alignment refuses connected runs rather than separating collars', () => { + const a = run({ + path: [ + [0, 0, 0], + [3, 0, 0], + ], + }) + const b = run({ + path: [ + [3, 0, 0], + [6, 0, 0], + ], + }) + expect(() => + edit(scene(a, b), { nodeId: b.id, action: 'resize', diameter: 10, alignment: 'top' }, context), + ).toThrow('Face alignment') +}) + +test('resize refuses a transition that consumes the remaining run', () => { + const a = run({ + path: [ + [0, 0, 0], + [3, 0, 0], + ], + }) + const b = run({ + path: [ + [3, 0, 0], + [3.2, 0, 0], + ], + }) + expect(() => + edit(scene(a, b), { nodeId: b.id, action: 'resize', diameter: 10 }, context), + ).toThrow('Not enough straight duct') +}) + +for (const offset of [1, -1]) + test(`obstacle offset ${offset} keeps original endpoints and joins every new collar`, () => { + const duct = run() + const result = edit( + scene(duct), + { nodeId: duct.id, action: 'offset', offset, from: 1, to: 4 }, + context, + ) + const first = { ...duct, ...result.changes!.update![0]!.data } as typeof duct + const created = result.changes!.create!.map((entry) => entry.node) + const ducts = [first, ...created.filter((node) => node.type === 'duct-segment')] + expect(created.filter((node) => node.type === 'duct-fitting')).toHaveLength(4) + expect(first.path[0]).toEqual(duct.path[0]!) + expect(ducts.at(-1)!.path[1]).toEqual(duct.path[1]!) + expect(ducts[2]!.path[0]![1]).toBe(offset) + const ports = [first, ...created].flatMap((node) => + nodeRegistry.get(node.type)!.ports!(node).map((port) => ({ ...port, nodeId: node.id })), + ) + const open = ports.filter( + (port) => + !ports.some( + (other) => + other.nodeId !== port.nodeId && + Math.hypot(...port.position.map((n, i) => n - other.position[i]!)) < 1e-6, + ), + ) + expect(open).toHaveLength(2) + }) + +test('offset refuses insufficient space without mutating the scene', () => { + const duct = run() + const nodes = scene(duct) + const before = JSON.stringify(nodes) + expect(() => + edit(nodes, { nodeId: duct.id, action: 'offset', offset: 0.1, from: 1, to: 4 }, context), + ).toThrow('Allow') + expect(JSON.stringify(nodes)).toBe(before) +}) + +test('nearby ducts on a different level are not resized', () => { + const duct = run() + const other = run({ + parentId: LevelNode.parse({}).id, + path: [ + [6, 0, 0], + [9, 0, 0], + ], + }) + const result = edit( + scene(duct, other), + { nodeId: duct.id, action: 'resize', scope: 'branch', diameter: 10 }, + context, + ) + expect(result.changes!.update!.map((entry) => entry.id)).toEqual([duct.id]) +}) + +test('duct offset works through MCP and undoes in one step', async () => { + const duct = run() + const root = { ...level, children: [duct.id] } + const bridge = new SceneBridge() + bridge.setScene(scene(root, duct), [level.id]) + bridge.clearHistory() + const server = new McpServer({ name: 'duct-test', version: '0.0.0' }) + const contract = builtinAgentTools.tools.find((tool) => tool.name === 'duct_edit')! + registerOperationTool(server, createSceneOperations({ bridge }), { + contract, + operation: edit, + annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: false }, + }) + const client = new Client({ name: 'duct-test', version: '0.0.0' }) + const [serverTransport, clientTransport] = InMemoryTransport.createLinkedPair() + await Promise.all([server.connect(serverTransport), client.connect(clientTransport)]) + try { + const result = await client.callTool({ + name: 'duct_edit', + arguments: { nodeId: duct.id, action: 'offset', from: 1, to: 4, offset: 1 }, + }) + expect(result.isError).not.toBe(true) + expect( + Object.values(bridge.getNodes()).filter((node) => node.type === 'duct-fitting'), + ).toHaveLength(4) + bridge.undo() + expect(bridge.getNodes()[duct.id]?.path).toEqual(duct.path) + expect( + Object.values(bridge.getNodes()).filter((node) => node.type === 'duct-fitting'), + ).toHaveLength(0) + } finally { + await client.close() + await server.close() + } +}) + +test('face alignment moves automatic caps with the resized run', () => { + const duct = run({ shape: 'rect', width: 14, height: 8 }) + const cap = DuctFittingNode.parse({ + parentId: level.id, + fittingType: 'end-cap', + shape: 'rect', + width: 14, + height: 8, + position: [6.025, 0, 0], + }) + const result = edit( + scene(duct, cap), + { nodeId: duct.id, action: 'resize', height: 12, alignment: 'top' }, + context, + ) + expect(result.changes!.create).toHaveLength(0) + const resized = result.changes!.update!.find((entry) => entry.id === duct.id)!.data as typeof duct + const resizedCap = result.changes!.update!.find((entry) => entry.id === cap.id)! + .data as typeof cap + expect(resizedCap.height).toBe(12) + expect(resized.path[1]![1]).toBeCloseTo(-0.0508, 6) + expect(resizedCap.position[1]).toBeCloseTo(-0.0508, 6) +}) + +test('an obstacle offset transfers the far automatic cap to the tail section', () => { + const duct = run() + const cap = DuctFittingNode.parse({ + parentId: level.id, + fittingType: 'end-cap', + position: [6.025, 0, 0], + shape: 'round', + diameter: 6, + metadata: { automaticRunEndCapOwnerId: duct.id, automaticRunEndCapEndpoint: 'end' }, + }) + const before = scene(duct, cap) + const outcome = edit( + before, + { nodeId: duct.id, action: 'offset', from: 1, to: 5, offset: 1 }, + context, + ) + const next = { ...before } + for (const entry of outcome.changes!.create!) next[entry.node.id] = entry.node + for (const entry of outcome.changes!.update!) + next[entry.id] = { ...next[entry.id], ...entry.data } as AnyNode + const updatedCap = next[cap.id] as DuctFittingNode + expect(updatedCap.position).toEqual(cap.position) + const tail = next[updatedCap.metadata.automaticRunEndCapOwnerId as string] as DuctSegmentNode + expect(tail.id).not.toBe(duct.id) + expect(tail.path.at(-1)).toEqual(duct.path.at(-1)) + expect( + ductSegmentDefinition.parametrics!.onDeleteCascade!(tail, next, new Set(), new Set([tail.id])), + ).toContain(cap.id) +}) + +test('agent operations bundle for a headless host without editor or viewer dependencies', async () => { + const result = await Bun.build({ + entrypoints: [fileURLToPath(import.meta.resolve('@pascal-app/nodes/agent-operations'))], + target: 'bun', + write: false, + external: ['@pascal-app/core', '@pascal-app/core/*', 'three', 'zod'], + plugins: [ + { + name: 'headless-operation-boundary', + setup(build) { + build.onResolve( + { filter: /^(@pascal-app\/(viewer|editor)(\/|$)|react(-dom)?($|\/)|@react-three\/)/ }, + (args) => { + throw new Error(`Headless operations cannot load ${args.path} from ${args.importer}`) + }, + ) + }, + }, + ], + }) + expect(result.success).toBe(true) +}) + +test('duct offsets detach every split section from the original wall', () => { + const duct = run({ + wallAttachment: { + wallId: 'wall_offset_host', + side: 'front', + startUV: [0, 0], + endUV: [6, 0], + offset: 0.1, + }, + }) + const nodes = scene(duct) + const before = JSON.stringify(nodes) + const outcome = edit( + nodes, + { nodeId: duct.id, action: 'offset', from: 1, to: 4, offset: 1 }, + context, + ) + const patch = outcome.changes!.update!.find((entry) => entry.id === duct.id)!.data + const sections = [ + { ...duct, ...patch }, + ...outcome + .changes!.create!.map((entry) => entry.node) + .filter((node) => node.type === 'duct-segment'), + ] + expect(sections).toHaveLength(5) + for (const section of sections) { + expect(section.wallAttachment).toBeUndefined() + expect(section.hangerOverrides).toBeUndefined() + } + expect(JSON.stringify(nodes)).toBe(before) +}) + +test('duct offsets refuse custom hangers and hosted children without partial edits', () => { + const custom = run({ hangerOverrides: { '0:0': { fraction: 0.5 } } }) + const hosted = run() + const child = DuctFittingNode.parse({ parentId: hosted.id }) + for (const [duct, nodes] of [ + [custom, scene(custom)], + [hosted, scene(hosted, child)], + ] as const) { + const before = JSON.stringify(nodes) + expect(() => + edit(nodes, { nodeId: duct.id, action: 'offset', from: 1, to: 4, offset: 1 }, context), + ).toThrow('Remove custom hanger adjustments or hosted children') + expect(JSON.stringify(nodes)).toBe(before) + } +}) diff --git a/packages/nodes/src/agent-operations/index.ts b/packages/nodes/src/agent-operations/index.ts index 2702c42586..49aa41fd89 100644 --- a/packages/nodes/src/agent-operations/index.ts +++ b/packages/nodes/src/agent-operations/index.ts @@ -1,8 +1,18 @@ import type { AgentOperations } from '@pascal-app/core/agent-operations' import { checkKitchenClearance, finishKitchenRun } from '../cabinet/finish-operation' +import { editDuct } from '../duct-segment/edit-operation' +import { connectPipe } from '../pipe-segment/connect-operation' +import { editPipeGrade } from '../pipe-segment/grade-operation' +import { offsetPipe } from '../pipe-segment/offset-operation' +import { resizePipe } from '../pipe-segment/resize-operation' export { checkKitchenClearance, finishKitchenRun } export const builtinAgentOperations = { + pipe_connect: connectPipe, + pipe_offset: offsetPipe, + pipe_resize: resizePipe, + pipe_grade: editPipeGrade, + duct_edit: editDuct, kitchen_finish_run: finishKitchenRun, kitchen_check_clearance: checkKitchenClearance, } satisfies AgentOperations diff --git a/packages/nodes/src/agent-operations/pipe-connect.test.ts b/packages/nodes/src/agent-operations/pipe-connect.test.ts new file mode 100644 index 0000000000..34b63afb16 --- /dev/null +++ b/packages/nodes/src/agent-operations/pipe-connect.test.ts @@ -0,0 +1,161 @@ +import { afterEach, beforeEach, expect, test } from 'bun:test' +import { + type AnyNode, + LevelNode, + nodeRegistry, + type PipeFittingNode, + type PipeSegmentNode, + PipeTrapNode, + registerNode, +} from '@pascal-app/core' +import { + PipeCollarInspector, + pipeFittingDefinition, + pipeSegmentDefinition, + pipeTrapDefinition, +} from '@pascal-app/nodes' +import { builtinAgentOperations } from '@pascal-app/nodes/agent-operations' +import { createElement } from 'react' +import { renderToStaticMarkup } from 'react-dom/server' + +let restore: ReturnType +beforeEach(() => { + restore = nodeRegistry._snapshot() + registerNode(pipeSegmentDefinition) + registerNode(pipeFittingDefinition) + registerNode(pipeTrapDefinition) +}) +afterEach(() => restore()) +const level = LevelNode.parse({}) +const trap = () => + PipeTrapNode.parse({ + parentId: level.id, + position: [1, 2, 3], + rotation: Math.PI / 4, + diameter: 1.5, + pipeMaterial: 'abs', + }) +const scene = (...nodes: AnyNode[]) => Object.fromEntries([level, ...nodes].map((n) => [n.id, n])) +const edit = builtinAgentOperations.pipe_connect +const context = { activeLevelId: level.id } +const endpoint = (node: PipeTrapNode, portId = 'outlet', length = 2) => { + const port = pipeTrapDefinition.ports!(node).find((p) => p.id === portId)! + return port.position.map((v, i) => v + length * port.direction[i]!) as [number, number, number] +} +test('connects a rotated trap outlet using its profile and leaves the trap unchanged', () => { + const node = trap(), + nodes = scene(node), + before = JSON.stringify(nodes) + const result = edit(nodes, { nodeId: node.id, portId: 'outlet', end: endpoint(node) }, context) + expect(JSON.stringify(nodes)).toBe(before) + expect(result.changes!.update).toBeUndefined() + const pipe = result + .changes!.create!.map((entry) => entry.node) + .find((n): n is PipeSegmentNode => n.type === 'pipe-segment')! + expect(pipe.path[0]).toEqual([...pipeTrapDefinition.ports!(node)[1]!.position]) + expect(pipe.diameter).toBe(1.5) + expect(pipe.pipeMaterial).toBe('abs') + expect(pipe.parentId).toBe(level.id) + expect(result.result.reducers).toBe(0) +}) +test('a larger branch inserts a reducer with coincident, opposing collars', () => { + const node = trap(), + result = edit( + scene(node), + { nodeId: node.id, portId: 'outlet', end: endpoint(node), diameter: 3 }, + context, + ) + const created = result.changes!.create!.map((entry) => entry.node) + const reducer = created.find( + (n): n is PipeFittingNode => n.type === 'pipe-fitting' && n.fittingType === 'reducer', + )! + const pipe = created.find((n): n is PipeSegmentNode => n.type === 'pipe-segment')! + const source = pipeTrapDefinition.ports!(node)[1]!, + ports = pipeFittingDefinition.ports!(reducer) + for (let i = 0; i < 3; i++) { + expect(ports[0]!.position[i]).toBeCloseTo(source.position[i]!, 10) + expect(ports[1]!.position[i]).toBeCloseTo(pipe.path[0]![i]!, 10) + } + expect(ports[0]!.direction.reduce((sum, v, i) => sum + v * source.direction[i]!, 0)).toBeCloseTo( + -1, + 10, + ) + expect(ports.map((p) => p.diameter)).toEqual([1.5, 3]) +}) +test('vertical fixture-side connections follow the inlet axis', () => { + const node = trap(), + result = edit( + scene(node), + { nodeId: node.id, portId: 'inlet', end: endpoint(node, 'inlet') }, + context, + ) + const pipe = result.changes!.create![0]!.node as PipeSegmentNode + expect(pipe.path[0]![0]).toBe(pipe.path[1]![0]) + expect(pipe.path[0]![2]).toBe(pipe.path[1]![2]) + expect(pipe.path[1]![1] - pipe.path[0]![1]).toBeCloseTo(2) +}) +test('occupied, wrong-direction, stale and cramped collars refuse atomically', () => { + const node = trap(), + nodes = scene(node) + const first = edit(nodes, { nodeId: node.id, portId: 'outlet', end: endpoint(node) }, context) + const connected = scene(node, ...first.changes!.create!.map((entry) => entry.node)) + expect(() => + edit(connected, { nodeId: node.id, portId: 'outlet', end: endpoint(node) }, context), + ).toThrow('already connected') + for (const input of [ + { nodeId: node.id, portId: 'missing', end: endpoint(node) }, + { nodeId: node.id, portId: 'outlet', end: endpoint(node, 'outlet', -2) }, + { nodeId: node.id, portId: 'outlet', end: endpoint(node, 'outlet', 0.1), diameter: 8 }, + { nodeId: node.id, portId: 'outlet', end: endpoint(node), diameter: 10 }, + ]) + expect(() => edit(nodes, input, context)).toThrow() +}) +test('the inspector exposes collar size and elevation', () => { + const node = trap() + const html = renderToStaticMarkup(createElement(PipeCollarInspector, { node })) + expect(html).toContain('Draw from collar') + expect(html).toContain('1.5 in') + expect(html).toContain('2.030 m') +}) + +test('collar connection works through MCP and undoes as one edit', async () => { + const { Client } = await import('@modelcontextprotocol/sdk/client/index.js') + const { InMemoryTransport } = await import('@modelcontextprotocol/sdk/inMemory.js') + const { McpServer } = await import('@modelcontextprotocol/sdk/server/mcp.js') + const { SceneBridge } = await import('@pascal-app/mcp/bridge') + const { createSceneOperations } = await import('@pascal-app/mcp/operations') + const { registerOperationTool } = await import('@pascal-app/mcp/tools/shared-tools') + const { builtinAgentTools } = await import('@pascal-app/nodes/agent-tools') + const run = trap() + const bridge = new SceneBridge() + bridge.setScene(scene({ ...level, children: [run.id] }, run), [level.id]) + bridge.clearHistory() + const server = new McpServer({ name: 'pipe-connect-test', version: '0.0.0' }) + registerOperationTool(server, createSceneOperations({ bridge }), { + contract: builtinAgentTools.tools.find((tool) => tool.name === 'pipe_connect')!, + operation: edit, + annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: false }, + }) + const client = new Client({ name: 'pipe-connect-test', version: '0.0.0' }) + const [serverTransport, clientTransport] = InMemoryTransport.createLinkedPair() + await Promise.all([server.connect(serverTransport), client.connect(clientTransport)]) + try { + const result = await client.callTool({ + name: 'pipe_connect', + arguments: { nodeId: run.id, portId: 'outlet', end: endpoint(run), diameter: 3 }, + }) + expect(result.isError).not.toBe(true) + expect(bridge.getNodes()[run.id]).toEqual(run) + expect( + Object.values(bridge.getNodes()).filter((node) => node.type === 'pipe-fitting'), + ).toHaveLength(2) + bridge.undo() + expect(bridge.getNodes()[run.id]).toEqual(run) + expect( + Object.values(bridge.getNodes()).filter((node) => node.type === 'pipe-fitting'), + ).toHaveLength(0) + } finally { + await client.close() + await server.close() + } +}) diff --git a/packages/nodes/src/agent-operations/pipe-grade.test.ts b/packages/nodes/src/agent-operations/pipe-grade.test.ts new file mode 100644 index 0000000000..19f4c2d31a --- /dev/null +++ b/packages/nodes/src/agent-operations/pipe-grade.test.ts @@ -0,0 +1,249 @@ +import { afterEach, beforeEach, expect, test } from 'bun:test' +import { + type AnyNode, + LevelNode, + nodeRegistry, + PipeFittingNode, + PipeSegmentNode, + registerNode, + useLiveNodeOverrides, + useScene, +} from '@pascal-app/core' +import { pipeFittingDefinition, pipeSegmentDefinition } from '@pascal-app/nodes' +import { builtinAgentOperations } from '@pascal-app/nodes/agent-operations' + +let restore: ReturnType +beforeEach(() => { + restore = nodeRegistry._snapshot() + registerNode(pipeSegmentDefinition) + registerNode(pipeFittingDefinition) +}) +const originalRaf = globalThis.requestAnimationFrame +const originalCancelRaf = globalThis.cancelAnimationFrame +beforeEach(() => { + globalThis.requestAnimationFrame = () => 0 + globalThis.cancelAnimationFrame = () => {} +}) +afterEach(() => { + restore() + globalThis.requestAnimationFrame = originalRaf + globalThis.cancelAnimationFrame = originalCancelRaf +}) +const level = LevelNode.parse({}) +const makePipe = ( + path: number[][] = [ + [0, 2, 0], + [4, 1.92, 0], + ], +) => PipeSegmentNode.parse({ parentId: level.id, path, diameter: 2, system: 'waste' }) +const scene = (...nodes: AnyNode[]) => + Object.fromEntries([level, ...nodes].map((node) => [node.id, node])) +const edit = builtinAgentOperations.pipe_grade +const context = { activeLevelId: level.id } +function editedPath(pipe: PipeSegmentNode, input: Parameters[1]) { + const result = edit(scene(pipe), input, context) + return (result.changes!.update!.find((entry) => entry.id === pipe.id)!.data as PipeSegmentNode) + .path +} + +test('changing grade can preserve either endpoint elevation', () => { + const pipe = makePipe() + const start = editedPath(pipe, { + nodeId: pipe.id, + action: 'grade', + gradePercent: 3, + anchor: 'start', + }) + expect(start[0]![1]).toBe(2) + expect(start[1]![1]).toBeCloseTo(1.88) + const end = editedPath(pipe, { nodeId: pipe.id, action: 'grade', gradePercent: 3, anchor: 'end' }) + expect(end[1]![1]).toBeCloseTo(1.92) + expect(end[0]![1]).toBeCloseTo(2.04) +}) +test('reversing downhill flow changes elevation rather than only a label', () => { + const pipe = makePipe() + expect( + editedPath(pipe, { nodeId: pipe.id, action: 'grade', gradePercent: 2, flow: 'reverse' })[1]![1], + ).toBeCloseTo(2.08) +}) +test('extending either endpoint preserves signed grade and the opposite elevation', () => { + const pipe = makePipe() + const end = editedPath(pipe, { + nodeId: pipe.id, + action: 'endpoint', + pointIndex: 1, + point: [8, 1.92, 0], + }) + expect(end[1]![1]).toBeCloseTo(1.84) + const start = editedPath(pipe, { + nodeId: pipe.id, + action: 'endpoint', + pointIndex: 0, + point: [-4, 2, 0], + }) + expect(start[0]![1]).toBeCloseTo(2.08) + expect(start[1]![1]).toBe(1.92) +}) +test('elevation edits translate every vertex without flattening mixed grades', () => { + const pipe = makePipe([ + [0, 2, 0], + [2, 1.96, 0], + [2, 1.96, 3], + ]) + const path = editedPath(pipe, { nodeId: pipe.id, action: 'elevation', elevation: 4 }) + expect(path).toEqual([ + [0, 4, 0], + [2, 3.96, 0], + [2, 3.96, 3], + ]) +}) +test('polyline edits preserve each leg grade, rather than averaging the whole run', () => { + const pipe = makePipe([ + [0, 2, 0], + [2, 1.96, 0], + [2, 1.87, 3], + ]) + const path = editedPath(pipe, { + nodeId: pipe.id, + action: 'endpoint', + pointIndex: 1, + point: [4, 1.96, 0], + }) + expect(path[1]![1]).toBeCloseTo(1.92) + expect((path[1]![1] - path[2]![1]) / Math.hypot(2, 3)).toBeCloseTo(0.03) +}) +test('vertical legs retain their height when grading a mixed route', () => { + const pipe = makePipe([ + [0, 2, 0], + [4, 2, 0], + [4, 0, 0], + ]) + const path = editedPath(pipe, { nodeId: pipe.id, action: 'grade', gradePercent: 2 }) + expect(path[1]![1]).toBeCloseTo(1.92) + expect(path[2]![1]).toBeCloseTo(-0.08) +}) +test('tilting a vertical stack is refused', () => { + const pipe = makePipe([ + [0, 2, 0], + [0, 0, 0], + ]) + expect(() => + editedPath(pipe, { nodeId: pipe.id, action: 'endpoint', pointIndex: 1, point: [1, 0, 0] }), + ).toThrow('vertical stack') +}) +test('collapsed horizontal leg and invalid grade are refused without scene mutation', () => { + const pipe = makePipe() + const nodes = scene(pipe) + const before = JSON.stringify(nodes) + expect(() => + edit(nodes, { nodeId: pipe.id, action: 'endpoint', pointIndex: 1, point: [0, 2, 0] }, context), + ).toThrow() + expect(() => + edit(nodes, { nodeId: pipe.id, action: 'grade', gradePercent: NaN }, context), + ).toThrow() + expect(JSON.stringify(nodes)).toBe(before) +}) +test('turning a connected collar is refused instead of silently breaking it', () => { + const pipe = makePipe() + const fitting = PipeFittingNode.parse({ + parentId: level.id, + fittingType: 'elbow', + position: [4.14, 1.92, 0], + diameter: 2, + }) + const ports = pipeFittingDefinition.ports!(fitting) + const inlet = ports[0]! + pipe.path[1] = [...inlet.position] + expect(() => + edit(scene(pipe, fitting), { nodeId: pipe.id, action: 'grade', gradePercent: 5 }, context), + ).toThrow('collar') +}) +test('plan-view editing previews grade without writing the scene until commit', () => { + const pipe = makePipe() + const previous = useScene.getState().nodes + useScene.setState({ nodes: scene(pipe) }) + try { + const affordance = pipeSegmentDefinition.floorplanAffordances!['move-path-point']! + const session = affordance.start({ + node: pipe, + nodes: scene(pipe), + payload: { pointIndex: 1 }, + initialPlanPoint: [4, 0], + }) + session.apply({ + planPoint: [8, 0], + modifiers: { altKey: false, ctrlKey: false, metaKey: false, shiftKey: false }, + }) + expect(useScene.getState().nodes[pipe.id]).toEqual(pipe) + expect(session.canCommit()).toBe(true) + session.commit!() + const result = useScene.getState().nodes[pipe.id] as PipeSegmentNode + expect(result.path[1]![1]).toBeCloseTo(1.84) + } finally { + useLiveNodeOverrides.getState().clear(pipe.id) + useScene.setState({ nodes: previous }) + } +}) + +test('grade edits carry end caps and keep both collars coincident', () => { + const pipe = makePipe([ + [0, 2, 0], + [4, 2, 0], + ]) + const cap = PipeFittingNode.parse({ + parentId: level.id, + fittingType: 'end-cap', + position: [4.025, 2, 0], + diameter: 2, + }) + cap.position[0] += 4 - pipeFittingDefinition.ports!(cap)[0]!.position[0] + const result = edit( + scene(pipe, cap), + { nodeId: pipe.id, action: 'grade', gradePercent: 2 }, + context, + ) + const path = ( + result.changes!.update!.find((entry) => entry.id === pipe.id)!.data as PipeSegmentNode + ).path + const capUpdate = result.changes!.update!.find((entry) => entry.id === cap.id)! + const nextCap = { ...cap, ...capUpdate.data } as typeof cap + const port = pipeFittingDefinition.ports!(nextCap)[0]! + expect(port.position[0]).toBeCloseTo(path[1]![0]) + expect(port.position[1]).toBeCloseTo(path[1]![1]) +}) + +test('grade tool works through MCP and undoes as one edit', async () => { + const { Client } = await import('@modelcontextprotocol/sdk/client/index.js') + const { InMemoryTransport } = await import('@modelcontextprotocol/sdk/inMemory.js') + const { McpServer } = await import('@modelcontextprotocol/sdk/server/mcp.js') + const { SceneBridge } = await import('@pascal-app/mcp/bridge') + const { createSceneOperations } = await import('@pascal-app/mcp/operations') + const { registerOperationTool } = await import('@pascal-app/mcp/tools/shared-tools') + const { builtinAgentTools } = await import('@pascal-app/nodes/agent-tools') + const pipe = makePipe() + const bridge = new SceneBridge() + bridge.setScene(scene({ ...level, children: [pipe.id] }, pipe), [level.id]) + bridge.clearHistory() + const server = new McpServer({ name: 'pipe-grade-test', version: '0.0.0' }) + registerOperationTool(server, createSceneOperations({ bridge }), { + contract: builtinAgentTools.tools.find((tool) => tool.name === 'pipe_grade')!, + operation: edit, + annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: false }, + }) + const client = new Client({ name: 'pipe-grade-test', version: '0.0.0' }) + const [serverTransport, clientTransport] = InMemoryTransport.createLinkedPair() + await Promise.all([server.connect(serverTransport), client.connect(clientTransport)]) + try { + const result = await client.callTool({ + name: 'pipe_grade', + arguments: { nodeId: pipe.id, action: 'grade', gradePercent: 3 }, + }) + expect(result.isError).not.toBe(true) + expect((bridge.getNodes()[pipe.id] as PipeSegmentNode).path[1]![1]).toBeCloseTo(1.88) + bridge.undo() + expect(bridge.getNodes()[pipe.id]?.path).toEqual(pipe.path) + } finally { + await client.close() + await server.close() + } +}) diff --git a/packages/nodes/src/agent-operations/pipe-offset.test.ts b/packages/nodes/src/agent-operations/pipe-offset.test.ts new file mode 100644 index 0000000000..3f9afa2549 --- /dev/null +++ b/packages/nodes/src/agent-operations/pipe-offset.test.ts @@ -0,0 +1,199 @@ +import { afterEach, beforeEach, expect, test } from 'bun:test' +import { + type AnyNode, + LevelNode, + nodeRegistry, + PipeFittingNode, + PipeSegmentNode, + registerNode, +} from '@pascal-app/core' +import { pipeFittingDefinition, pipeSegmentDefinition } from '@pascal-app/nodes' +import { builtinAgentOperations } from '@pascal-app/nodes/agent-operations' + +let restore: ReturnType +beforeEach(() => { + restore = nodeRegistry._snapshot() + registerNode(pipeSegmentDefinition) + registerNode(pipeFittingDefinition) +}) +afterEach(() => restore()) +const level = LevelNode.parse({}) +const makePipe = (grade = 0.02) => + PipeSegmentNode.parse({ + parentId: level.id, + path: [ + [0, 2, 0], + [6, 2 - 10 * grade, 8], + ], + diameter: 4, + pipeMaterial: 'cast-iron', + autoHangers: true, + }) +const scene = (...nodes: AnyNode[]) => + Object.fromEntries([level, ...nodes].map((node) => [node.id, node])) +const edit = builtinAgentOperations.pipe_offset +const context = { activeLevelId: level.id } +const request = (pipe: PipeSegmentNode, offset = 0.5) => ({ + nodeId: pipe.id, + from: 2, + to: 8, + offset, +}) +function nextScene(before: Record, outcome: ReturnType) { + const next = { ...before } + for (const entry of outcome.changes?.update ?? []) + next[entry.id] = { ...next[entry.id], ...entry.data } as AnyNode + for (const entry of outcome.changes?.create ?? []) next[entry.node.id] = entry.node + return next +} +const gradeOf = (run: PipeSegmentNode) => + (run.path[0]![1] - run.path[1]![1]) / + Math.hypot(run.path[1]![0] - run.path[0]![0], run.path[1]![2] - run.path[0]![2]) + +for (const grade of [0, 0.02, -0.02]) + for (const offset of [0.5, -0.5]) { + test(`offset ${offset} preserves grade ${grade} and joins every fitting collar`, () => { + const pipe = makePipe(grade), + before = scene(pipe), + snapshot = JSON.stringify(before) + const outcome = edit(before, request(pipe, offset), context) + expect(JSON.stringify(before)).toBe(snapshot) + const next = nextScene(before, outcome) + const runs = Object.values(next).filter( + (node): node is PipeSegmentNode => node.type === 'pipe-segment', + ) + const fittings = Object.values(next).filter( + (node): node is PipeFittingNode => node.type === 'pipe-fitting', + ) + expect(runs).toHaveLength(5) + expect(fittings).toHaveLength(4) + expect(runs[0]!.path[0]).toEqual(pipe.path[0]) + expect(runs.at(-1)!.path.at(-1)).toEqual(pipe.path[1]) + for (const index of [0, 2, 4]) expect(gradeOf(runs[index]!)).toBeCloseTo(grade, 10) + for (const run of runs) { + expect(run.diameter).toBe(4) + expect(run.pipeMaterial).toBe('cast-iron') + expect(run.autoHangers).toBe(true) + } + const runPorts = runs.flatMap((run) => pipeSegmentDefinition.ports!(run)) + for (const fitting of fittings) { + expect(fitting.parentId).toBe(level.id) + for (const port of pipeFittingDefinition.ports!(fitting)) { + const mates = runPorts.filter( + (other) => Math.hypot(...port.position.map((v, i) => v - other.position[i]!)) < 1e-8, + ) + expect(mates).toHaveLength(1) + expect( + port.direction.reduce((sum, v, i) => sum + v * mates[0]!.direction[i]!, 0), + ).toBeCloseTo(-1, 10) + } + } + const center = runs[2]!.path[0]! + const distance = Math.hypot(center[0], center[2]) + expect(center[1] - (2 - distance * grade)).toBeCloseTo(offset, 10) + expect(outcome.result.uphill).toBe(true) + }) + } +test('fixed caps keep their geometry and the far cap follows ownership to the new tail', () => { + const pipe = makePipe() + const cap = PipeFittingNode.parse({ + parentId: level.id, + fittingType: 'end-cap', + position: [6, 1.8, 8], + metadata: { automaticRunEndCapOwnerId: pipe.id, automaticRunEndCapEndpoint: 'end' }, + }) + const before = scene(pipe, cap), + outcome = edit(before, request(pipe), context), + next = nextScene(before, outcome) + const nextCap = next[cap.id] as PipeFittingNode + expect(nextCap.position).toEqual(cap.position) + expect(nextCap.rotation).toEqual(cap.rotation) + const tail = next[nextCap.metadata.automaticRunEndCapOwnerId as string] as PipeSegmentNode + expect(tail.id).not.toBe(pipe.id) + expect(tail.path.at(-1)).toEqual(pipe.path.at(-1)) + expect( + pipeSegmentDefinition.parametrics!.onDeleteCascade!(tail, next, new Set(), new Set([tail.id])), + ).toContain(cap.id) +}) +test('invalid, vertical, polyline and cramped offsets refuse without edits', () => { + const pipe = makePipe(), + before = scene(pipe), + snapshot = JSON.stringify(before) + for (const patch of [ + { offset: 0 }, + { offset: NaN }, + { from: -1 }, + { to: 11 }, + { from: 7 }, + { offset: 0.01 }, + { from: 0.01 }, + { from: 8, to: 2 }, + ]) { + expect(() => edit(before, { ...request(pipe), ...patch }, context)).toThrow() + expect(JSON.stringify(before)).toBe(snapshot) + } + for (const path of [ + [ + [0, 0, 0], + [0, 3, 0], + ], + [ + [0, 0, 0], + [2, 0, 0], + [4, 0, 0], + ], + ]) { + const other = PipeSegmentNode.parse({ path }) + expect(() => edit(scene(other), request(other), context)).toThrow() + } +}) +test('custom hanger positions are not silently discarded by a split', () => { + const pipe = { ...makePipe(), hangerOverrides: { '0': { fraction: 0.5 } } } + expect(() => edit(scene(pipe), request(pipe), context)).toThrow('hanger') +}) +test('vent offsets do not report a waste-flow warning', () => { + const pipe = { ...makePipe(), system: 'vent' as const } + expect(edit(scene(pipe), request(pipe), context).result.uphill).toBe(false) +}) + +test('offset tool works through MCP and undoes as one edit', async () => { + const { Client } = await import('@modelcontextprotocol/sdk/client/index.js') + const { InMemoryTransport } = await import('@modelcontextprotocol/sdk/inMemory.js') + const { McpServer } = await import('@modelcontextprotocol/sdk/server/mcp.js') + const { SceneBridge } = await import('@pascal-app/mcp/bridge') + const { createSceneOperations } = await import('@pascal-app/mcp/operations') + const { registerOperationTool } = await import('@pascal-app/mcp/tools/shared-tools') + const { builtinAgentTools } = await import('@pascal-app/nodes/agent-tools') + const run = makePipe() + const bridge = new SceneBridge() + bridge.setScene(scene({ ...level, children: [run.id] }, run), [level.id]) + bridge.clearHistory() + const server = new McpServer({ name: 'pipe-offset-test', version: '0.0.0' }) + registerOperationTool(server, createSceneOperations({ bridge }), { + contract: builtinAgentTools.tools.find((tool) => tool.name === 'pipe_offset')!, + operation: edit, + annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: false }, + }) + const client = new Client({ name: 'pipe-offset-test', version: '0.0.0' }) + const [serverTransport, clientTransport] = InMemoryTransport.createLinkedPair() + await Promise.all([server.connect(serverTransport), client.connect(clientTransport)]) + try { + const result = await client.callTool({ + name: 'pipe_offset', + arguments: request(run), + }) + expect(result.isError).not.toBe(true) + expect((bridge.getNodes()[run.id] as PipeSegmentNode).path[0]).toEqual(run.path[0]) + expect( + Object.values(bridge.getNodes()).filter((node) => node.type === 'pipe-fitting'), + ).toHaveLength(4) + bridge.undo() + expect(bridge.getNodes()[run.id]).toEqual(run) + expect( + Object.values(bridge.getNodes()).filter((node) => node.type === 'pipe-fitting'), + ).toHaveLength(0) + } finally { + await client.close() + await server.close() + } +}) diff --git a/packages/nodes/src/agent-operations/pipe-resize.test.ts b/packages/nodes/src/agent-operations/pipe-resize.test.ts new file mode 100644 index 0000000000..c86e0477aa --- /dev/null +++ b/packages/nodes/src/agent-operations/pipe-resize.test.ts @@ -0,0 +1,197 @@ +import { afterEach, beforeEach, expect, test } from 'bun:test' +import { + type AnyNode, + LevelNode, + nodeRegistry, + PipeFittingNode, + PipeSegmentNode, + PipeTrapNode, + registerNode, +} from '@pascal-app/core' +import { pipeFittingDefinition, pipeSegmentDefinition, pipeTrapDefinition } from '@pascal-app/nodes' +import { builtinAgentOperations } from '@pascal-app/nodes/agent-operations' + +let restore: ReturnType +beforeEach(() => { + restore = nodeRegistry._snapshot() + registerNode(pipeSegmentDefinition) + registerNode(pipeFittingDefinition) + registerNode(pipeTrapDefinition) +}) +afterEach(() => restore()) +const level = LevelNode.parse({}) +const pipe = (path: number[][], diameter = 2) => + PipeSegmentNode.parse({ parentId: level.id, path, diameter }) +const fitting = (fittingType: PipeFittingNode['fittingType'], rotation = [0, 0, 0]) => + PipeFittingNode.parse({ parentId: level.id, fittingType, rotation }) +const ports = (node: AnyNode) => nodeRegistry.get(node.type)!.ports!(node) +const scene = (...nodes: AnyNode[]) => Object.fromEntries([level, ...nodes].map((n) => [n.id, n])) +const edit = builtinAgentOperations.pipe_resize +const context = { activeLevelId: level.id } +const attached = (f: PipeFittingNode, portIndex: number, length = 3) => { + const p = ports(f)[portIndex]! + return pipe([[...p.position], p.position.map((v, i) => v + p.direction[i]! * length)]) +} +const nextNode = (node: AnyNode, result: ReturnType) => + ({ ...node, ...result.changes?.update?.find((entry) => entry.id === node.id)?.data }) as AnyNode + +test('branch resize carries a sloped coupling and both runs without changing grades', () => { + const joint = fitting('coupling', [0, 0, -Math.atan(0.02)]) + const a = attached(joint, 0), + b = attached(joint, 1) + const result = edit(scene(a, b, joint), { nodeId: a.id, diameter: 4, scope: 'branch' }, context) + expect(result.result.runs).toBe(2) + expect(result.changes!.create).toHaveLength(0) + const newJoint = nextNode(joint, result) + for (const [i, run] of [a, b].entries()) { + const next = nextNode(run, result) as PipeSegmentNode + expect(next.diameter).toBe(4) + expect(next.path[0]).toEqual([...ports(newJoint)[i]!.position]) + expect(next.path[1]).toEqual(run.path[1]) + const grade = (p: PipeSegmentNode) => + (p.path[0]![1] - p.path[1]![1]) / Math.abs(p.path[0]![0] - p.path[1]![0]) + expect(grade(next)).toBeCloseTo(grade(run), 10) + } +}) +test('segment scope inserts a reducer while leaving its connected fitting and neighbor fixed', () => { + const joint = fitting('coupling', [0, 0, -Math.atan(0.02)]) + const a = attached(joint, 0), + b = attached(joint, 1) + const result = edit(scene(a, b, joint), { nodeId: a.id, diameter: 4 }, context) + expect(result.result.runs).toBe(1) + expect(result.changes!.create).toHaveLength(1) + expect(nextNode(joint, result)).toEqual(joint) + expect(nextNode(b, result)).toEqual(b) + const reducer = result.changes!.create![0]!.node + const reducerPorts = ports(reducer) + for (let i = 0; i < 3; i++) + expect(reducerPorts[0]!.position[i]).toBeCloseTo(ports(joint)[0]!.position[i]!, 10) + expect(reducerPorts[1]!.position).toEqual((nextNode(a, result) as PipeSegmentNode).path[0]!) + expect(reducerPorts.map((p) => p.diameter)).toEqual([2, 4]) +}) +test('branch traversal stops at junctions and existing size changes', () => { + for (const kind of ['wye', 'sanitary-tee', 'cross', 'reducer'] as const) { + const joint = fitting(kind) + const a = attached(joint, 0), + b = attached(joint, 1) + const result = edit(scene(a, b, joint), { nodeId: a.id, diameter: 4, scope: 'branch' }, context) + expect(result.result.runs).toBe(1) + expect(nextNode(joint, result)).toEqual(joint) + expect(nextNode(b, result)).toEqual(b) + expect(result.changes!.create).toHaveLength(1) + } +}) +test('a fitting beside a different-size pipe stays fixed', () => { + const joint = fitting('coupling'), + a = attached(joint, 0), + b = { ...attached(joint, 1), diameter: 3 } + const result = edit(scene(a, b, joint), { nodeId: a.id, diameter: 4, scope: 'branch' }, context) + expect(nextNode(joint, result)).toEqual(joint) + expect(nextNode(b, result)).toEqual(b) + expect(result.changes!.create).toHaveLength(1) +}) +test('resizing caps keeps pipe endpoints fixed', () => { + const cap = fitting('end-cap', [0, 0, -Math.atan(0.02)]), + run = attached(cap, 0) + const result = edit(scene(run, cap), { nodeId: run.id, diameter: 8 }, context) + expect(result.changes!.create).toHaveLength(0) + expect((nextNode(run, result) as PipeSegmentNode).path).toEqual(run.path) + const nextCap = nextNode(cap, result) + expect((nextCap as PipeFittingNode).diameter).toBe(8) + ports(cap)[0]!.position.forEach((v, i) => { + expect(ports(nextCap)[0]!.position[i]).toBeCloseTo(v, 10) + }) +}) +test('short runs and ambiguous connections are refused without mutation', () => { + const joint = fitting('coupling'), + short = attached(joint, 0, 0.15) + const nodes = scene(joint, short), + before = JSON.stringify(nodes) + expect(() => edit(nodes, { nodeId: short.id, diameter: 8 }, context)).toThrow('straight pipe') + expect(JSON.stringify(nodes)).toBe(before) + const a = attached(joint, 0), + duplicate = attached(joint, 0) + expect(() => edit(scene(joint, a, duplicate), { nodeId: a.id, diameter: 4 }, context)).toThrow( + 'overlapping', + ) +}) +test('same size is a no-op and invalid diameters are refused', () => { + const run = pipe([ + [0, 2, 0], + [3, 1.94, 0], + ]) + expect(edit(scene(run), { nodeId: run.id, diameter: 2 }, context).changes).toBeUndefined() + for (const diameter of [NaN, Infinity, 0, 9]) + expect(() => edit(scene(run), { nodeId: run.id, diameter }, context)).toThrow() +}) + +test('trap collars stay fixed and receive a reducer', () => { + const trap = PipeTrapNode.parse({ parentId: level.id }) + const collar = ports(trap)[1]! + const run = pipe([ + [...collar.position], + collar.position.map((v, i) => v + collar.direction[i]! * 3), + ]) + const result = edit(scene(run, trap), { nodeId: run.id, diameter: 4, scope: 'branch' }, context) + expect(nextNode(trap, result)).toEqual(trap) + expect(result.changes!.create).toHaveLength(1) + ports(result.changes!.create![0]!.node)[0]!.position.forEach((v, i) => { + expect(v).toBeCloseTo(collar.position[i]!, 10) + }) +}) +test('vertical stacks resize without tilting and branch traversal includes elbows', () => { + for (const kind of ['coupling', 'elbow'] as const) { + const joint = fitting(kind, [0, 0, Math.PI / 2]) + const a = attached(joint, 0), + b = attached(joint, 1) + const result = edit(scene(a, b, joint), { nodeId: a.id, diameter: 4, scope: 'branch' }, context) + expect(result.result.runs).toBe(2) + const next = nextNode(a, result) as PipeSegmentNode + expect(next.path[0]![0]).toBeCloseTo(next.path[1]![0], 10) + expect(next.path[0]![2]).toBeCloseTo(next.path[1]![2], 10) + expect(result.changes!.create).toHaveLength(0) + } +}) + +test('resize tool works through MCP and undoes as one edit', async () => { + const { Client } = await import('@modelcontextprotocol/sdk/client/index.js') + const { InMemoryTransport } = await import('@modelcontextprotocol/sdk/inMemory.js') + const { McpServer } = await import('@modelcontextprotocol/sdk/server/mcp.js') + const { SceneBridge } = await import('@pascal-app/mcp/bridge') + const { createSceneOperations } = await import('@pascal-app/mcp/operations') + const { registerOperationTool } = await import('@pascal-app/mcp/tools/shared-tools') + const { builtinAgentTools } = await import('@pascal-app/nodes/agent-tools') + const joint = fitting('coupling') + const run = attached(joint, 0) + const bridge = new SceneBridge() + bridge.setScene(scene({ ...level, children: [run.id, joint.id] }, run, joint), [level.id]) + bridge.clearHistory() + const server = new McpServer({ name: 'pipe-resize-test', version: '0.0.0' }) + registerOperationTool(server, createSceneOperations({ bridge }), { + contract: builtinAgentTools.tools.find((tool) => tool.name === 'pipe_resize')!, + operation: edit, + annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: false }, + }) + const client = new Client({ name: 'pipe-resize-test', version: '0.0.0' }) + const [serverTransport, clientTransport] = InMemoryTransport.createLinkedPair() + await Promise.all([server.connect(serverTransport), client.connect(clientTransport)]) + try { + const result = await client.callTool({ + name: 'pipe_resize', + arguments: { nodeId: run.id, diameter: 4 }, + }) + expect(result.isError).not.toBe(true) + expect((bridge.getNodes()[run.id] as PipeSegmentNode).diameter).toBe(4) + expect( + Object.values(bridge.getNodes()).filter((node) => node.type === 'pipe-fitting'), + ).toHaveLength(2) + bridge.undo() + expect(bridge.getNodes()[run.id]).toEqual(run) + expect( + Object.values(bridge.getNodes()).filter((node) => node.type === 'pipe-fitting'), + ).toHaveLength(1) + } finally { + await client.close() + await server.close() + } +}) diff --git a/packages/nodes/src/agent-tools/contracts.test.ts b/packages/nodes/src/agent-tools/contracts.test.ts index 643c38ff9a..77a10edbcb 100644 --- a/packages/nodes/src/agent-tools/contracts.test.ts +++ b/packages/nodes/src/agent-tools/contracts.test.ts @@ -6,15 +6,24 @@ import { builtinAgentTools } from '@pascal-app/nodes/agent-tools' // The plugin's contracts are declared where core's are, including the hosted chat's sandbox, // which rejects packages that depend on Node modules: they import zod and core's types only. -test('the kitchen tool contracts reach only zod', () => { +test('the built-in tool contracts use sandbox-safe entry points', () => { const source = readFileSync(resolve(import.meta.dir, 'index.ts'), 'utf8') const runtime = [ ...source.matchAll(/^(?:import|export)\s+(?!type\s)[^'"]*?from\s+['"]([^'"]+)['"]/gm), ].map((match) => match[1]) - expect(runtime).toEqual(['zod']) + expect(runtime).toEqual(['@pascal-app/core/agent-tools', 'zod']) }) -test('the kitchen tools take no bare length and show every default', () => { - expect(bareNumberPaths(builtinAgentTools.tools)).toEqual([]) +test('the built-in tools accept unit notation for lengths and show every default', () => { + expect(bareNumberPaths(builtinAgentTools.tools)).toEqual(['pipe_grade.gradePercent']) expect(unshownDefaultPaths(builtinAgentTools.tools)).toEqual([]) }) + +test('MEP length inputs normalize unit-bearing text before operations run', () => { + const resize = builtinAgentTools.tools.find((tool) => tool.name === 'pipe_resize')! + expect(resize.input.diameter.parse('0.5 ft')).toBe(6) + const offset = builtinAgentTools.tools.find((tool) => tool.name === 'pipe_offset')! + expect(offset.input.offset.parse('50 cm')).toBe(0.5) + const duct = builtinAgentTools.tools.find((tool) => tool.name === 'duct_edit')! + expect(duct.input.width.parse('2 ft')).toBe(24) +}) diff --git a/packages/nodes/src/agent-tools/index.ts b/packages/nodes/src/agent-tools/index.ts index a9c78de942..297bbc0c3d 100644 --- a/packages/nodes/src/agent-tools/index.ts +++ b/packages/nodes/src/agent-tools/index.ts @@ -1,4 +1,4 @@ -import type { PluginAgentTools } from '@pascal-app/core/agent-tools' +import { measurement, type PluginAgentTools } from '@pascal-app/core/agent-tools' import { z } from 'zod' export const finishKitchenRunTool = { @@ -17,9 +17,93 @@ export const checkKitchenClearanceTool = { input: { nodeId: z.string() }, runsIn: 'operation' as const, } +export const editDuctTool = { + name: 'duct_edit' as const, + title: 'Resize or offset duct', + description: + 'Resize a duct segment or its same-profile branch through elbows, couplings, dampers and caps. Stops at junctions, profile changes and equipment; inserts transitions at fixed boundary collars. Center alignment supports connected runs; face alignment supports free straight runs. Offset adds four elbows to a straight horizontal run while preserving endpoints. from and to are bend positions measured in metres from the start; offset is signed vertical displacement in metres. Does not detect obstacles: check clearance. Refuses insufficient fitting space without partial edits. One undo step.', + input: { + nodeId: z.string(), + action: z.enum(['resize', 'offset']), + scope: z.enum(['segment', 'branch']).optional(), + alignment: z.enum(['center', 'top', 'bottom', 'left', 'right']).optional(), + shape: z.enum(['round', 'rect', 'oval']).optional(), + diameter: measurement('length', 'in').optional(), + width: measurement('length', 'in').optional(), + height: measurement('length', 'in').optional(), + offset: measurement('length', 'm').optional(), + from: measurement('length', 'm').optional(), + to: measurement('length', 'm').optional(), + }, + runsIn: 'operation' as const, +} +export const pipeGradeTool = { + name: 'pipe_grade' as const, + title: 'Edit pipe grade and elevation', + description: + 'Set grade (percent fall over horizontal travel), flow direction, or an anchored elevation above the level. point is a numeric [x, y, z] tuple in level-local metres, not a unit-bearing length string. Endpoint edits preserve each existing leg grade; vertical elevation edits translate the run. Vertical legs retain their rise. Refuses edits that would regrade connected pipes or move fixed equipment. One undo step.', + input: { + nodeId: z.string(), + action: z.enum(['grade', 'endpoint', 'elevation']), + detach: z.boolean().optional(), + gradePercent: z.number().finite().nonnegative().optional(), + flow: z.enum(['forward', 'reverse']).optional(), + anchor: z.enum(['start', 'end']).optional(), + pointIndex: z.number().int().nonnegative().optional(), + point: z.tuple([z.number().finite(), z.number().finite(), z.number().finite()]).optional(), + elevation: measurement('length', 'm').optional(), + }, + runsIn: 'operation' as const, +} +export const pipeResizeTool = { + name: 'pipe_resize' as const, + title: 'Resize connected pipe', + description: + 'Resize a segment or same-size, same-material branch through elbows, couplings and cleanouts. Stops at junctions, reducers and fixed fixture/equipment collars. Resizes caps and inserts reducers at size boundaries while preserving each leg grade. Refuses ambiguous collars or insufficient straight length without partial edits. One undo step.', + input: { + nodeId: z.string(), + diameter: measurement('length', 'in', { min: 1.25, max: 8 }), + scope: z.enum(['segment', 'branch']).optional(), + }, + runsIn: 'operation' as const, +} +export const pipeOffsetTool = { + name: 'pipe_offset' as const, + title: 'Offset pipe around obstacle', + description: + 'Add four bends to a straight non-vertical pipe, keeping both boundary collars fixed and preserving grade on the parallel sections. from and to are horizontal distances in metres from the start to the first and last bend; offset is signed vertical displacement in metres. Connectors each consume abs(offset) horizontal travel. Refuses insufficient fitting space without partial edits. Reports uphill waste connectors; this is geometric routing, not drainage or obstacle-clearance validation. One undo step.', + input: { + nodeId: z.string(), + from: measurement('length', 'm'), + to: measurement('length', 'm'), + offset: measurement('length', 'm'), + }, + runsIn: 'operation' as const, +} +export const pipeConnectTool = { + name: 'pipe_connect' as const, + title: 'Connect a pipe to a fixed collar', + description: + 'Draw from an open registered waste/vent fixture, trap or fitting collar to a free endpoint. end is a numeric [x, y, z] tuple in level-local metres, not a unit-bearing length string. Inherits diameter, material and system. The first section must follow the collar direction; add subsequent bends from the new pipe. A different diameter inserts a reducer without moving the source. Refuses occupied collars, incompatible directions and insufficient reducer space. One undo step. Ordinary catalog models without authored ports are unsupported.', + input: { + nodeId: z.string(), + portId: z.string(), + end: z.tuple([z.number().finite(), z.number().finite(), z.number().finite()]), + diameter: measurement('length', 'in', { min: 1.25, max: 8 }).optional(), + }, + runsIn: 'operation' as const, +} export const builtinAgentTools = { pluginId: 'pascal:core', apiVersion: 1, - version: '1.0.0', - tools: [finishKitchenRunTool, checkKitchenClearanceTool], + version: '1.1.1', + tools: [ + finishKitchenRunTool, + checkKitchenClearanceTool, + editDuctTool, + pipeGradeTool, + pipeResizeTool, + pipeOffsetTool, + pipeConnectTool, + ], } satisfies PluginAgentTools diff --git a/packages/nodes/src/duct-fitting/floorplan.ts b/packages/nodes/src/duct-fitting/floorplan.ts index 60f5aef436..7b5eeb21dd 100644 --- a/packages/nodes/src/duct-fitting/floorplan.ts +++ b/packages/nodes/src/duct-fitting/floorplan.ts @@ -1,6 +1,6 @@ import type { FloorplanGeometry, GeometryContext } from '@pascal-app/core' import { MeshStandardMaterial } from 'three' -import { INCHES_TO_METERS } from '../duct-segment/geometry' +import { INCHES_TO_METERS } from '../duct-segment/profile' import { accessoryFloorplan } from '../shared/accessory-floorplan' import { buildDuctAccessory } from './accessory-geometry' import { buildDuctFittingGeometry } from './geometry' diff --git a/packages/nodes/src/duct-fitting/geometry.ts b/packages/nodes/src/duct-fitting/geometry.ts index b2ef94de62..2e042b57f8 100644 --- a/packages/nodes/src/duct-fitting/geometry.ts +++ b/packages/nodes/src/duct-fitting/geometry.ts @@ -19,8 +19,8 @@ import { buildRectSection, buildSection, createDuctMaterial, - INCHES_TO_METERS, } from '../duct-segment/geometry' +import { INCHES_TO_METERS } from '../duct-segment/profile' import { buildDuctAccessory } from './accessory-geometry' import { adapterShape, localFittingPorts } from './ports' import type { DuctFittingNode } from './schema' diff --git a/packages/nodes/src/duct-fitting/selection.tsx b/packages/nodes/src/duct-fitting/selection.tsx index dfd54dd551..a81fdc4155 100644 --- a/packages/nodes/src/duct-fitting/selection.tsx +++ b/packages/nodes/src/duct-fitting/selection.tsx @@ -40,7 +40,7 @@ import { Vector3, } from 'three' import { LineBasicNodeMaterial, MeshBasicNodeMaterial } from 'three/webgpu' -import { INCHES_TO_METERS } from '../duct-segment/geometry' +import { INCHES_TO_METERS } from '../duct-segment/profile' import { autoOffsetInvalidationUpdates } from '../shared/auto-offset-tag' import { AXIS_VECTORS, diff --git a/packages/nodes/src/duct-segment/continuation.test.ts b/packages/nodes/src/duct-segment/continuation.test.ts index 0787cd3629..6d5a4371ca 100644 --- a/packages/nodes/src/duct-segment/continuation.test.ts +++ b/packages/nodes/src/duct-segment/continuation.test.ts @@ -228,3 +228,31 @@ describe('duct continuation', () => { expect(points[1]?.[1]).toBeCloseTo(2) }) }) + +test('drafting from an equipment collar inherits its section and system', async () => { + const { hvacEquipmentDefinition } = await import('@pascal-app/nodes') + const { HvacEquipmentNode } = await import('@pascal-app/core') + const restore = nodeRegistry._snapshot() + try { + registerNode(hvacEquipmentDefinition) + const equipment = HvacEquipmentNode.parse({ + equipmentType: 'air-handler', + returnShape: 'rect', + returnWidth: 20, + returnHeight: 10, + }) + const port = hvacEquipmentDefinition.ports!(equipment).find((port) => port.system === 'return')! + const seed = resolveDuctContinuationSeed( + { continuation: { nodeId: equipment.id, portId: port.id } }, + { [equipment.id]: equipment }, + ) + expect(seed?.port?.position).toEqual(port.position) + expect(seed?.port?.nodeId).toBe(equipment.id) + expect(seed?.duct.shape).toBe('rect') + expect(seed?.duct.width).toBe(20) + expect(seed?.duct.height).toBe(10) + expect(seed?.duct.system).toBe('return') + } finally { + restore() + } +}) diff --git a/packages/nodes/src/duct-segment/continuation.ts b/packages/nodes/src/duct-segment/continuation.ts index 8c79df38be..92a4c391d8 100644 --- a/packages/nodes/src/duct-segment/continuation.ts +++ b/packages/nodes/src/duct-segment/continuation.ts @@ -2,7 +2,9 @@ import { type AnyNode, type AnyNodeId, type DuctFittingNode, + DuctSegmentNode, type FloorplanAffordance, + nodeRegistry, useScene, } from '@pascal-app/core' import { useEditor } from '@pascal-app/editor' @@ -15,8 +17,7 @@ import { type RunContinuationHandlePlan, resolveDuctContinuationHandle, } from '../shared/elbow-branch-continuation' -import { ductPortDiameterIn } from './geometry' -import type { DuctSegmentNode } from './schema' +import { ductPortDiameterIn } from './profile' export type DuctEndpoint = 'start' | 'end' @@ -30,6 +31,7 @@ export type DuctContinuationSeed = { type DuctContinuationDefaults = { continuation?: { nodeId?: unknown + portId?: unknown endpoint?: unknown fittingId?: unknown segmentIndex?: unknown @@ -86,6 +88,32 @@ export function resolveDuctContinuationSeed( nodes: Record, ): DuctContinuationSeed | null { const continuation = (defaults as DuctContinuationDefaults | null)?.continuation + if (typeof continuation?.portId === 'string' && typeof continuation.nodeId === 'string') { + const source = nodes[continuation.nodeId] + const port = + source && + nodeRegistry + .get(source.type) + ?.ports?.(source) + .find((p) => p.id === continuation.portId) + if (!port || (port.system !== 'supply' && port.system !== 'return')) return null + return { + duct: DuctSegmentNode.parse({ + parentId: source.parentId, + path: [ + [...port.position], + port.position.map((value, index) => value + port.direction[index]!), + ], + shape: port.shape ?? 'round', + diameter: port.diameter, + width: port.width ?? 14, + height: port.height ?? 8, + system: port.system, + }), + port: { ...port, nodeId: source.id }, + body: null, + } + } const endpoint = continuation?.endpoint const nodeId = continuation?.nodeId if (endpoint === 'branch' && typeof nodeId === 'string') { @@ -145,6 +173,9 @@ export function activateDuctBranch( if (!segment || !next) return const editor = useEditor.getState() editor.setToolDefaults('duct-segment', { + ...editor.toolDefaults['duct-segment'], + routingMode: 'surface', + crossingMode: 'connect', continuation: { nodeId: duct.id, endpoint: 'branch', segmentIndex, point }, shape: duct.shape, diameter: duct.diameter, @@ -168,6 +199,9 @@ export function activateDuctContinuation( if (!ductEndpointPort(duct, endpoint)) return const editor = useEditor.getState() editor.setToolDefaults('duct-segment', { + ...editor.toolDefaults['duct-segment'], + routingMode: 'surface', + crossingMode: 'connect', continuation: { nodeId: duct.id, endpoint, ...(fittingId ? { fittingId } : {}) }, shape: duct.shape, diameter: duct.diameter, diff --git a/packages/nodes/src/duct-segment/definition.ts b/packages/nodes/src/duct-segment/definition.ts index e39730bf8e..b56c7794fd 100644 --- a/packages/nodes/src/duct-segment/definition.ts +++ b/packages/nodes/src/duct-segment/definition.ts @@ -3,10 +3,12 @@ import { ductBodyPaint } from '../shared/duct-body-paint' import { createPathPointMoveAffordance } from '../shared/path-point-affordance' import { createSegmentMoveAffordance } from '../shared/path-segment-affordance' import { createRunHangerToolHint } from '../shared/run-hanger-mode' +import { ductRunToolOptions } from '../shared/run-tool-options' import { ductBranchAffordance, ductContinuationAffordance } from './continuation' import { buildDuctSegmentFloorplan } from './floorplan' -import { buildDuctSegmentGeometry, ductPortDiameterIn } from './geometry' +import { buildDuctSegmentGeometry } from './geometry' import { ductSegmentParametrics } from './parametrics' +import { ductPortDiameterIn } from './profile' import { DuctSegmentNode } from './schema' /** @@ -174,6 +176,7 @@ export const ductSegmentDefinition: NodeDefinition = { }, tool: () => import('./tool'), + toolOptions: ductRunToolOptions, toolHints: [ { key: 'Click', label: 'Start segment' }, { key: 'Click again', label: 'Place and continue' }, diff --git a/packages/nodes/src/duct-segment/draw-plan.test.ts b/packages/nodes/src/duct-segment/draw-plan.test.ts index 3effbcc3df..a881ceb2b4 100644 --- a/packages/nodes/src/duct-segment/draw-plan.test.ts +++ b/packages/nodes/src/duct-segment/draw-plan.test.ts @@ -1,5 +1,6 @@ import { expect, test } from 'bun:test' -import { DuctSegmentNode, useScene } from '@pascal-app/core' +import { DuctSegmentNode, HvacEquipmentNode, useScene } from '@pascal-app/core' +import { getHvacEquipmentPorts } from '../hvac-equipment/ports' import { ductSurfaceClearanceM, planDuctDraw } from './tool' const profile = { shape: 'round' as const, diameter: 6, width: 12, height: 8 } @@ -90,3 +91,99 @@ test('a short branch reports failure instead of omitting its tee', () => { useScene.setState({ nodes: original }) } }) + +test('cross without joining leaves the trunk intact while connect inserts a cross', () => { + const trunk = DuctSegmentNode.parse({ + parentId: 'level_test', + shape: 'round', + path: [ + [0, 2, -3], + [0, 2, 3], + ], + }) + const previous = useScene.getState().nodes + const nodes = { [trunk.id]: trunk } + useScene.setState({ nodes }) + const surface = { + kind: 'surface' as const, + levelId: 'level_test' as const, + frame: { + origin: [0, 2, 0] as [number, number, number], + normal: [0, 1, 0] as [number, number, number], + tangent: [1, 0, 0] as [number, number, number], + bitangent: [0, 0, 1] as [number, number, number], + }, + } + try { + const connected = planDuctDraw( + [-3, 2, 0], + [3, 2, 0], + null, + null, + null, + null, + profile, + nodes, + surface, + ) + expect(connected?.validationMessage).toBeNull() + expect(connected?.fittings.some((fitting) => fitting.fittingType === 'cross')).toBe(true) + expect(connected?.updates.some((update) => update.id === trunk.id)).toBe(true) + const defaults = { crossingMode: 'cross', shape: 'round' as const } + const separate = planDuctDraw( + [-3, 2, 0], + [3, 2, 0], + null, + null, + null, + null, + profile, + nodes, + surface, + false, + defaults, + ) + expect(separate?.validationMessage).toBeNull() + expect(separate?.fittings.some((fitting) => fitting.fittingType === 'cross')).toBe(false) + expect(separate?.updates.some((update) => update.id === trunk.id)).toBe(false) + expect(separate?.ducts).toHaveLength(1) + expect(useScene.getState().nodes[trunk.id]).toEqual(trunk) + } finally { + useScene.setState({ nodes: previous }) + } +}) + +test('fixed equipment collars require a straight, matching-system connection', () => { + const equipment = HvacEquipmentNode.parse({ + parentId: 'level_test', + supplyShape: 'round', + supplyDiameter: 6, + returnShape: 'round', + returnDiameter: 6, + }) + const nodes = { [equipment.id]: equipment } + for (const port of getHvacEquipmentPorts(equipment).filter((p) => p.system !== 'refrigerant')) { + const source = { ...port, nodeId: equipment.id } + const start: [number, number, number] = [...port.position] + const end = start.map((value, index) => value + port.direction[index]! * 2) as [ + number, + number, + number, + ] + const plan = planDuctDraw(start, end, source, null, null, null, profile, nodes)! + expect(plan.validationMessage).toBeNull() + expect(plan.ducts[0]!.system).toBe(port.system) + expect(plan.ducts[0]!.path[0]).toEqual(start) + const wrongAxis: [number, number, number] = [start[0], start[1], start[2] + 2] + for (const invalid of [ + planDuctDraw(start, wrongAxis, source, null, null, null, profile, nodes), + planDuctDraw(start, end, source, null, null, null, profile, nodes, null, false, { + system: port.system === 'supply' ? 'return' : 'supply', + }), + ]) { + expect(invalid?.validationMessage).toBeTruthy() + expect(invalid?.ducts).toHaveLength(0) + expect(invalid?.updates).toHaveLength(0) + } + } +}) diff --git a/packages/nodes/src/duct-segment/edit-inspector.tsx b/packages/nodes/src/duct-segment/edit-inspector.tsx new file mode 100644 index 0000000000..094b868453 --- /dev/null +++ b/packages/nodes/src/duct-segment/edit-inspector.tsx @@ -0,0 +1,226 @@ +'use client' + +import { type AnyNodeId, type DuctSegmentNode, useScene } from '@pascal-app/core' +import { useMemo, useState } from 'react' +import RunHangerInspector from '../shared/run-hanger-inspector' +import { type DuctEditInput, editDuct } from './edit-operation' + +export default function DuctEditInspector({ node }: { node: DuctSegmentNode }) { + return ( + <> + + + > + ) +} + +function DuctEditForm({ node }: { node: DuctSegmentNode }) { + const nodes = useScene((state) => state.nodes) + const [input, setInput] = useState({ + nodeId: node.id, + action: 'resize', + scope: 'segment', + alignment: 'center', + shape: node.shape, + diameter: node.diameter, + width: node.width, + height: node.height, + from: 1, + to: 2, + offset: 1, + }) + const [notice, setNotice] = useState('') + const preview = useMemo(() => { + try { + return { outcome: editDuct(nodes, input, { activeLevelId: node.parentId }), error: '' } + } catch (error) { + return { + outcome: null, + error: error instanceof Error ? error.message : 'Unable to plan this edit.', + } + } + }, [nodes, input, node.parentId]) + const update = (patch: Partial) => { + setInput((previous) => ({ ...previous, ...patch })) + setNotice('') + } + const numberField = ( + key: 'diameter' | 'width' | 'height' | 'from' | 'to' | 'offset', + label: string, + ) => ( + + {label} + update({ [key]: event.target.valueAsNumber })} + /> + + ) + const changes = preview.outcome?.changes + const count = (changes?.update?.length ?? 0) + (changes?.create?.length ?? 0) + const paths = + input.action === 'offset' && changes + ? [ + ...changes + .update!.filter((entry) => entry.id === node.id) + .map((entry) => (entry.data as DuctSegmentNode).path), + ...changes.create!.flatMap((entry) => + entry.node.type === 'duct-segment' ? [entry.node.path] : [], + ), + ] + : [] + const length = Math.hypot(...node.path[1]!.map((v, i) => v - node.path[0]![i]!)) + const elevation = Math.max(Math.abs(input.offset ?? 1), 0.1) + const project = (point: number[]) => { + const along = + point.reduce( + (sum, value, i) => + sum + (value - node.path[0]![i]!) * (node.path[1]![i]! - node.path[0]![i]!), + 0, + ) / (length || 1) + const baseline = (input.offset ?? 0) > 0 ? 90 : 26 + return `${16 + (along / (length || 1)) * 228},${baseline - ((point[1]! - node.path[0]![1]) / elevation) * 64}` + } + return ( + + Edit duct route + update({ action: event.target.value as DuctEditInput['action'] })} + > + Resize with connections + Offset around obstacle + + {input.action === 'resize' ? ( + <> + update({ scope: event.target.value as DuctEditInput['scope'] })} + > + This segment + Connected same-size branch + + + Branch stops at junctions, size changes and equipment. Boundary collars stay fixed. + + update({ shape: event.target.value as DuctEditInput['shape'] })} + > + Round + Rectangular + Oval + + {input.shape === 'round' ? ( + numberField('diameter', 'Diameter (in)') + ) : ( + <> + {numberField('width', 'Width (in)')} + {numberField('height', 'Height (in)')} + > + )} + + update({ alignment: event.target.value as DuctEditInput['alignment'] }) + } + > + Keep centerline + Keep top face + Keep bottom face + Keep left face + Keep right face + + + Face alignment applies to free straight runs. Left and right follow the run’s section + axes. + + > + ) : ( + <> + {numberField('from', 'First bend from start (m)')} + {numberField('to', 'Last bend from start (m)')} + {numberField('offset', 'Vertical offset (m)')} + + Positive moves up; negative moves down. Four elbows preserve both endpoints. Check the + obstacle’s clearance; this does not detect collisions. + + > + )} + {paths.length > 0 && ( + + + Offset side elevation preview + + + + + Side elevation · dashed line is the original route + + + )} + + {preview.error || + `${changes?.update?.length ?? 0} existing parts affected · ${changes?.create?.length ?? 0} new parts`} + + { + try { + const outcome = editDuct(useScene.getState().nodes, input, { + activeLevelId: node.parentId, + }) + const plan = outcome.changes + if (plan) + useScene.getState().applyNodeChanges({ + create: plan.create?.map((entry) => ({ + ...entry, + parentId: entry.parentId as AnyNodeId | undefined, + })), + update: plan.update?.map((entry) => ({ ...entry, id: entry.id as AnyNodeId })), + }) + setNotice(String(outcome.result.message)) + } catch (error) { + setNotice(error instanceof Error ? error.message : 'Unable to apply edit.') + } + }} + > + Apply {input.action === 'resize' ? 'resize' : 'offset'} + + {notice && {notice}} + + ) +} diff --git a/packages/nodes/src/duct-segment/edit-operation.ts b/packages/nodes/src/duct-segment/edit-operation.ts new file mode 100644 index 0000000000..1811562d19 --- /dev/null +++ b/packages/nodes/src/duct-segment/edit-operation.ts @@ -0,0 +1,351 @@ +import { + type AnyNode, + type AnyNodeId, + DuctFittingNode, + DuctSegmentNode, + nodeRegistry, +} from '@pascal-app/core' +import type { AgentOperation, SceneChanges, SceneNodes } from '@pascal-app/core/agent-operations' +import { refuse } from '@pascal-app/core/agent-tools' +import type { ScenePort } from '@pascal-app/editor/distribution' +import { Vector3 } from 'three' +import { fittingLegLength, getDuctFittingPorts } from '../duct-fitting/ports' +import { type DuctProfile, planElbowAtPort, profileDiameterIn } from '../shared/auto-fitting' +import { autoOffsetInvalidationUpdates } from '../shared/auto-offset-tag' +import { transferRunEndCapOwnership } from '../shared/automatic-run-end-cap' +import { ductProfilesMatch, planDuctAdapter } from '../shared/duct-adapter' +import { rectSectionAxes, rollToContinueAcrossElbow } from './profile' + +type Point = [number, number, number] +export type DuctEditInput = { + nodeId: string + action: 'resize' | 'offset' + scope?: 'segment' | 'branch' + alignment?: 'center' | 'top' | 'bottom' | 'left' | 'right' + shape?: 'round' | 'rect' | 'oval' + diameter?: number + width?: number + height?: number + offset?: number + from?: number + to?: number +} + +function portsOf(node: AnyNode): ScenePort[] { + const definition = nodeRegistry.get(node.type) + if (!definition?.ports) return [] + return definition.ports(node).map((port) => ({ ...port, nodeId: node.id })) +} +const distance = (a: readonly number[], b: readonly number[]) => + Math.hypot(a[0]! - b[0]!, a[1]! - b[1]!, a[2]! - b[2]!) +function mates(port: ScenePort, ports: ScenePort[]): ScenePort[] { + return ports.filter( + (other) => + other.nodeId !== port.nodeId && + other.system === port.system && + distance(port.position, other.position) < 0.005 && + new Vector3(...port.direction).dot(new Vector3(...other.direction)) < -0.99, + ) +} +function profileOf(node: AnyNode, port: ScenePort): DuctProfile { + if (node.type === 'duct-segment') return node + return { + shape: port.shape ?? 'round', + diameter: port.diameter, + width: port.width ?? port.diameter, + height: port.height ?? port.diameter, + } +} +function validPaths(before: SceneNodes, changes: SceneChanges) { + for (const entry of changes.update ?? []) { + const old = before[entry.id] + if (old?.type !== 'duct-segment' || !('path' in entry.data) || !entry.data.path) continue + const path = entry.data.path as Point[] + for (let i = 1; i < path.length; i++) { + const original = new Vector3(...old.path[i]!).sub(new Vector3(...old.path[i - 1]!)) + const next = new Vector3(...path[i]!).sub(new Vector3(...path[i - 1]!)) + if (next.length() < 0.08 || next.dot(original) <= 0) + refuse( + 'duct_clearance', + 'Not enough straight duct for the fittings. Use a longer run or a smaller size change.', + ) + } + } +} + +/** One plan is used by the inspector and agent hosts; neither writes a partial network. */ +export const editDuct: AgentOperation = (before, input) => { + const duct = before[input.nodeId] + if (duct?.type !== 'duct-segment') return refuse('duct_not_found', 'Select a duct run.') + if (!nodeRegistry.get('duct-segment')?.ports) + return refuse('node_capability_unavailable', 'Register duct node definitions before editing.') + const changes: SceneChanges = { create: [], update: [] } + if (input.action === 'offset') { + if ( + Object.values(before).some((node) => node.parentId === duct.id) || + Object.keys(duct.hangerOverrides ?? {}).length + ) + return refuse( + 'duct_offset_attachments', + 'Remove custom hanger adjustments or hosted children before splitting this run.', + ) + const { offset = 0, from = 0, to = 0 } = input + if ( + ![offset, from, to].every(Number.isFinite) || + duct.path.length !== 2 || + Math.abs(duct.path[0]![1] - duct.path[1]![1]) > 0.001 + ) + return refuse('duct_offset_route', 'Choose a straight horizontal run for an obstacle offset.') + const start = new Vector3(...duct.path[0]!) + const end = new Vector3(...duct.path[1]!) + const axis = end.clone().sub(start).normalize() + const length = start.distanceTo(end) + const leg = fittingLegLength(profileDiameterIn(duct)) + if ( + from < leg + 0.08 || + to > length - leg - 0.08 || + to - from < 2 * leg + 0.08 || + Math.abs(offset) < 2 * leg + 0.08 + ) + return refuse( + 'duct_offset_clearance', + `Allow ${(2 * leg + 0.08).toFixed(2)} m for the rise and offset span, and ${(leg + 0.08).toFixed(2)} m at each end.`, + ) + const up = new Vector3(0, Math.sign(offset), 0) + const a = start.clone().addScaledVector(axis, from) + const b = a.clone().add(new Vector3(0, offset, 0)) + const d = start.clone().addScaledVector(axis, to) + const c = d.clone().add(new Vector3(0, offset, 0)) + const corners = [a, b, c, d] + const incoming = [axis, up, axis, up.clone().negate()] + const outgoing = [up, axis, up.clone().negate(), axis] + const elbows = corners.map( + (corner, i) => + planElbowAtPort( + { + id: 'end', + nodeId: duct.id, + position: corner.toArray(), + direction: incoming[i]!.toArray(), + diameter: profileDiameterIn(duct), + system: duct.system, + }, + outgoing[i]!.toArray(), + duct, + )!, + ) + const paths: Point[][] = [ + [start.toArray(), elbows[0]!.trimmedPortPoint], + [elbows[0]!.collarPoint, elbows[1]!.trimmedPortPoint], + [elbows[1]!.collarPoint, elbows[2]!.trimmedPortPoint], + [elbows[2]!.collarPoint, elbows[3]!.trimmedPortPoint], + [elbows[3]!.collarPoint, end.toArray()], + ] + // Rolled rectangular sections require a twist, which the elbow schema cannot express. + if (duct.shape !== 'round' && Math.abs(duct.roll) > 0.001) + return refuse('duct_offset_roll', 'Reset the section roll before adding an obstacle offset.') + changes.update!.push({ + id: duct.id, + data: { path: paths[0], wallAttachment: undefined, hangerOverrides: undefined }, + }) + const { id: _id, ...defaults } = duct + for (const path of paths.slice(1)) + changes.create!.push({ + node: DuctSegmentNode.parse({ + ...defaults, + metadata: {}, + wallAttachment: undefined, + hangerOverrides: undefined, + path, + roll: + duct.shape === 'round' + ? 0 + : rollToContinueAcrossElbow( + axis, + duct.roll, + axis, + new Vector3(...path[1]!).sub(new Vector3(...path[0]!)).normalize(), + ), + }), + parentId: duct.parentId ?? undefined, + }) + const tail = changes.create!.at(-1)!.node + changes.update!.push(...transferRunEndCapOwnership(before, duct.id, tail.id, 'end')) + for (const elbow of elbows) + changes.create!.push({ node: elbow.fitting, parentId: duct.parentId ?? undefined }) + } else { + const targetResult = DuctSegmentNode.safeParse({ + ...duct, + shape: input.shape ?? duct.shape, + diameter: input.diameter ?? duct.diameter, + width: input.width ?? duct.width, + height: input.height ?? duct.height, + }) + if (!targetResult.success) + return refuse( + 'duct_profile_invalid', + 'Enter duct dimensions within the supported profile range.', + ) + const target = targetResult.data + if (ductProfilesMatch(duct, target)) + return { result: { message: 'The duct already has this profile.', affected: [] }, changes } + const levelNodes = Object.values(before).filter((node) => node.parentId === duct.parentId) + const ports = levelNodes.flatMap(portsOf) + const selected = new Set([duct.id]) + for (const port of ports.filter((p) => p.nodeId === duct.id)) { + for (const mate of mates(port, ports)) { + const owner = before[mate.nodeId] + if (owner?.type === 'duct-fitting' && owner.fittingType === 'end-cap') + selected.add(owner.id) + } + } + const queue: AnyNode[] = [duct] + if (input.scope === 'branch') { + while (queue.length) { + const current = queue.shift()! + for (const port of ports.filter((p) => p.nodeId === current.id)) { + for (const mate of mates(port, ports)) { + const owner = before[mate.nodeId]! + const traversable = + owner.type === 'duct-segment' || + (owner.type === 'duct-fitting' && + ['elbow', 'coupling', 'damper', 'end-cap'].includes(owner.fittingType) && + ports + .filter((p) => p.nodeId === owner.id) + .every((p) => + mates(p, ports).every((m) => before[m.nodeId]?.type === 'duct-segment'), + )) + if ( + !selected.has(owner.id) && + traversable && + owner.system === duct.system && + ductProfilesMatch(profileOf(owner, mate), duct) + ) { + selected.add(owner.id) + queue.push(owner) + } + } + } + } + } + const alignment = input.alignment ?? 'center' + const connected = ports.some( + (port) => + port.nodeId === duct.id && + mates(port, ports).some( + (mate) => + !selected.has(mate.nodeId) || + before[mate.nodeId]?.type !== 'duct-fitting' || + (before[mate.nodeId] as DuctFittingNode).fittingType !== 'end-cap', + ), + ) + if (alignment !== 'center' && (connected || duct.path.length !== 2)) + return refuse( + 'duct_alignment_anchored', + 'Face alignment requires a free straight run. Use center alignment to keep connected collars fixed.', + ) + const updated = new Map() + for (const id of selected) { + const node = before[id]! + if (node.type === 'duct-segment') { + let path = node.path.map((p) => [...p] as Point) + if (alignment !== 'center') { + const axes = rectSectionAxes( + new Vector3(...path[1]!).sub(new Vector3(...path[0]!)).normalize(), + node.roll, + ) + if (axes.height.y < 0) axes.height.negate() + const side = alignment === 'left' || alignment === 'right' + const dimension = (p: DuctProfile) => + p.shape === 'round' ? p.diameter : side ? p.width : p.height + const sign = alignment === 'top' || alignment === 'right' ? 1 : -1 + const delta = (side ? axes.width : axes.height) + .clone() + .multiplyScalar((sign * (dimension(node) - dimension(target)) * 0.0254) / 2) + path = path.map((p) => new Vector3(...p).add(delta).toArray()) + } + updated.set(id, { + ...node, + shape: target.shape, + diameter: target.diameter, + width: target.width, + height: target.height, + path, + ductMaterial: + node.ductMaterial === 'spiral' && target.shape !== 'round' + ? 'sheet-metal' + : node.ductMaterial, + }) + } else if (node.type === 'duct-fitting') { + updated.set( + id, + DuctFittingNode.parse({ + ...node, + shape: target.shape, + diameter: profileDiameterIn(target), + diameter2: profileDiameterIn(target), + width: target.width, + height: target.height, + }), + ) + } + } + if (alignment !== 'center') { + const resized = updated.get(duct.id) as DuctSegmentNode + const delta = new Vector3(...resized.path[0]!).sub(new Vector3(...duct.path[0]!)) + for (const id of selected) { + const cap = updated.get(id) + if (cap?.type === 'duct-fitting' && cap.fittingType === 'end-cap') + cap.position = new Vector3(...cap.position).add(delta).toArray() + } + } + for (const id of selected) { + const node = updated.get(id)! + if (node.type !== 'duct-segment') continue + for (const port of ports.filter((p) => p.nodeId === id)) { + const matches = mates(port, ports) + if (matches.length > 1) + return refuse( + 'duct_connection_ambiguous', + 'More than one collar shares an endpoint. Resolve the connection before resizing.', + ) + const mate = matches[0] + if (!mate) continue + const owner = before[mate.nodeId]! + let point: Point = [...port.position] + if (selected.has(owner.id)) { + const changed = updated.get(owner.id)! + if (changed.type === 'duct-fitting') + point = [...getDuctFittingPorts(changed).find((p) => p.id === mate.id)!.position] + } else { + const adapter = planDuctAdapter(mate, profileOf(owner, mate), target) + if (adapter) { + changes.create!.push({ node: adapter.fitting, parentId: duct.parentId ?? undefined }) + point = adapter.collarPoint + } + } + node.path[port.id === 'start' ? 0 : node.path.length - 1] = point + } + } + for (const [id, node] of updated) changes.update!.push({ id, data: node }) + validPaths(before, changes) + } + const touched = changes.update!.map((entry) => entry.id as AnyNodeId) + const invalidations = touched.flatMap((id) => autoOffsetInvalidationUpdates({ ...before }, id)) + for (const entry of invalidations) { + const existing = changes.update!.find((update) => update.id === entry.id) + if (existing) existing.data = { ...existing.data, ...entry.data } as Partial + else changes.update!.push(entry) + } + return { + result: { + message: + input.action === 'offset' + ? 'Offset with four elbows; original end connections stay fixed. Check obstacle clearance before applying.' + : 'Ducts resized; boundary collars stay fixed with transitions where needed.', + affected: changes.update!.map((entry) => entry.id), + created: changes.create!.length, + }, + changes, + } +} diff --git a/packages/nodes/src/duct-segment/floorplan.ts b/packages/nodes/src/duct-segment/floorplan.ts index 66cee29600..e3e815f275 100644 --- a/packages/nodes/src/duct-segment/floorplan.ts +++ b/packages/nodes/src/duct-segment/floorplan.ts @@ -1,7 +1,7 @@ import type { FloorplanGeometry, FloorplanPoint, GeometryContext } from '@pascal-app/core' import { runHangerFloorplan } from '../shared/run-hangers' import { ductContinuationHandlePlan, ductEndpointPort } from './continuation' -import { INCHES_TO_METERS } from './geometry' +import { INCHES_TO_METERS } from './profile' import type { DuctSegmentNode } from './schema' const SUPPLY_CENTERLINE = '#d4825a' diff --git a/packages/nodes/src/duct-segment/geometry.ts b/packages/nodes/src/duct-segment/geometry.ts index 8eec23845b..3c92463304 100644 --- a/packages/nodes/src/duct-segment/geometry.ts +++ b/packages/nodes/src/duct-segment/geometry.ts @@ -24,9 +24,9 @@ import { Vector3, } from 'three' import { buildRunHangers } from '../shared/run-hangers' +import { INCHES_TO_METERS, rectSectionAxes } from './profile' import type { DuctSegmentNode } from './schema' -export const INCHES_TO_METERS = 0.0254 // Insulation wraps the duct in a roughly uniform shell. A strictly physical // mapping (fiberglass ≈ R-3.2 per inch) makes low R-values nearly invisible // at screen scale — R-1 would add only ~8 mm over a 15 cm duct. So the shell @@ -45,96 +45,8 @@ function pickInsulationThickness(r: number): number { const SUPPLY_COLOR = '#d4825a' const RETURN_COLOR = '#5a8ad4' -const RADIAL_SEGMENTS = 24 - const UP = new Vector3(0, 1, 0) - -/** - * Area-equivalent round diameter (inches) for a rect cross-section — - * what a rect trunk advertises on its ports so round fittings / branches - * mate at a sensible size. - */ -export function equivalentDiameterIn(widthIn: number, heightIn: number): number { - return 2 * Math.sqrt((widthIn * heightIn) / Math.PI) -} - -/** - * Area-equivalent round diameter (inches) for a flat-oval cross-section: - * a rectangle of (width − height) × height plus the two semicircular caps. - */ -export function ovalEquivalentDiameterIn(widthIn: number, heightIn: number): number { - const minor = Math.min(widthIn, heightIn) - const major = Math.max(widthIn, heightIn) - const area = (major - minor) * minor + Math.PI * (minor / 2) ** 2 - return 2 * Math.sqrt(area / Math.PI) -} - -/** The diameter (inches) a duct segment presents at its ports. */ -export function ductPortDiameterIn(node: { - shape?: 'round' | 'rect' | 'oval' - diameter: number - width?: number - height?: number -}): number { - if (node.shape === 'rect' && node.width && node.height) { - return equivalentDiameterIn(node.width, node.height) - } - if (node.shape === 'oval' && node.width && node.height) { - return ovalEquivalentDiameterIn(node.width, node.height) - } - return node.diameter -} - -/** - * Cross-section axes for a rect run along `dir`, rolled `roll` radians - * about the run direction. At roll 0: width is the horizontal axis - * (UP × dir) and height the vertical one — vertical runs, where that - * cross product degenerates, fall back to world X/Z. `roll` rotates the - * pair in the plane perpendicular to `dir`, letting a riser carry the - * orientation of the run it turned off instead of the bare fallback. - */ -export function rectSectionAxes(dir: Vector3, roll = 0): { width: Vector3; height: Vector3 } { - const d = dir.clone().normalize() - const xBase = new Vector3().crossVectors(UP, d) - if (xBase.lengthSq() < 1e-8) xBase.set(1, 0, 0) - xBase.normalize() - const zBase = new Vector3().crossVectors(xBase, d) - const c = Math.cos(roll) - const s = Math.sin(roll) - const width = xBase.clone().multiplyScalar(c).addScaledVector(zBase, s) - const height = xBase.clone().multiplyScalar(-s).addScaledVector(zBase, c) - return { width, height } -} - -/** - * Roll (radians) that keeps a rect cross-section continuous across an - * elbow: the dimension lying along the joint's hinge — the bend-plane - * normal `portDir × newDir`, perpendicular to both legs — must stay on - * the same physical face on the new run as on the source run. Returns 0 - * for an in-plane (degenerate-normal) joint, so horizontal turns keep - * the natural width-horizontal orientation. - */ -export function rollToContinueAcrossElbow( - sourceDir: Vector3, - sourceRoll: number, - portDir: Vector3, - newDir: Vector3, -): number { - const n = new Vector3().crossVectors(portDir, newDir) - if (n.lengthSq() < 1e-8) return 0 - n.normalize() - const src = rectSectionAxes(sourceDir, sourceRoll) - const carriesWidth = Math.abs(src.width.dot(n)) >= Math.abs(src.height.dot(n)) - const d = newDir.clone().normalize() - const xBase = new Vector3().crossVectors(UP, d) - if (xBase.lengthSq() < 1e-8) xBase.set(1, 0, 0) - xBase.normalize() - const zBase = new Vector3().crossVectors(xBase, d) - // Place the hinge-aligned face on the same axis the source carries it. - return carriesWidth - ? Math.atan2(n.dot(zBase), n.dot(xBase)) - : Math.atan2(-n.dot(xBase), n.dot(zBase)) -} +const RADIAL_SEGMENTS = 24 /** * Rect box spanning `start`→`end`. Orientation comes from `rectSectionAxes` diff --git a/packages/nodes/src/duct-segment/move-tool.tsx b/packages/nodes/src/duct-segment/move-tool.tsx index 256ad6b9b2..a5256943c2 100644 --- a/packages/nodes/src/duct-segment/move-tool.tsx +++ b/packages/nodes/src/duct-segment/move-tool.tsx @@ -42,7 +42,7 @@ import { type RunTranslationOffsetPlan, } from '../shared/run-translation-offset' import { translateWallRun } from '../shared/wall-run-move' -import { rectSectionAxes } from './geometry' +import { rectSectionAxes } from './profile' type Vec3 = [number, number, number] diff --git a/packages/nodes/src/duct-segment/parametrics.ts b/packages/nodes/src/duct-segment/parametrics.ts index 4a4fbfec5f..1afa80f6f7 100644 --- a/packages/nodes/src/duct-segment/parametrics.ts +++ b/packages/nodes/src/duct-segment/parametrics.ts @@ -3,7 +3,7 @@ import { Vector3 } from 'three' import { getDuctFittingPorts } from '../duct-fitting/ports' import { findAutomaticRunEndCapIds } from '../shared/automatic-run-end-cap' import { fittingDeletionPlansForRun } from '../shared/fitting-deletion-cleanup' -import { rollToContinueAcrossElbow } from './geometry' +import { rollToContinueAcrossElbow } from './profile' import type { DuctSegmentNode } from './schema' /** A run endpoint sitting this close to a collar counts as mated. */ @@ -112,7 +112,7 @@ export const ductSegmentParametrics: ParametricDescriptor = { plan.deleteFitting ? [plan.fittingId, ...plan.cascadeDeleteIds] : [], ), ], - trailingSection: () => import('../shared/run-hanger-inspector'), + trailingSection: () => import('./edit-inspector'), groups: [ { label: 'Hangers', @@ -157,39 +157,6 @@ export const ductSegmentParametrics: ParametricDescriptor = { options: ['supply', 'return'], display: 'segmented', }, - { - key: 'shape', - kind: 'enum', - options: ['round', 'rect', 'oval'], - display: 'segmented', - }, - { - key: 'diameter', - kind: 'number', - unit: 'in', - min: 4, - max: 24, - step: 1, - visibleIf: (n) => n.shape === 'round', - }, - { - key: 'width', - kind: 'number', - unit: 'in', - min: 4, - max: 60, - step: 1, - visibleIf: (n) => n.shape !== 'round', - }, - { - key: 'height', - kind: 'number', - unit: 'in', - min: 3, - max: 40, - step: 1, - visibleIf: (n) => n.shape !== 'round', - }, ], }, { diff --git a/packages/nodes/src/duct-segment/profile.ts b/packages/nodes/src/duct-segment/profile.ts new file mode 100644 index 0000000000..b6b5a80952 --- /dev/null +++ b/packages/nodes/src/duct-segment/profile.ts @@ -0,0 +1,91 @@ +import { Vector3 } from 'three' + +export const INCHES_TO_METERS = 0.0254 +const UP = new Vector3(0, 1, 0) + +/** + * Area-equivalent round diameter (inches) for a rect cross-section — + * what a rect trunk advertises on its ports so round fittings / branches + * mate at a sensible size. + */ +export function equivalentDiameterIn(widthIn: number, heightIn: number): number { + return 2 * Math.sqrt((widthIn * heightIn) / Math.PI) +} + +/** + * Area-equivalent round diameter (inches) for a flat-oval cross-section: + * a rectangle of (width − height) × height plus the two semicircular caps. + */ +export function ovalEquivalentDiameterIn(widthIn: number, heightIn: number): number { + const minor = Math.min(widthIn, heightIn) + const major = Math.max(widthIn, heightIn) + const area = (major - minor) * minor + Math.PI * (minor / 2) ** 2 + return 2 * Math.sqrt(area / Math.PI) +} + +/** The diameter (inches) a duct segment presents at its ports. */ +export function ductPortDiameterIn(node: { + shape?: 'round' | 'rect' | 'oval' + diameter: number + width?: number + height?: number +}): number { + if (node.shape === 'rect' && node.width && node.height) { + return equivalentDiameterIn(node.width, node.height) + } + if (node.shape === 'oval' && node.width && node.height) { + return ovalEquivalentDiameterIn(node.width, node.height) + } + return node.diameter +} + +/** + * Cross-section axes for a rect run along `dir`, rolled `roll` radians + * about the run direction. At roll 0: width is the horizontal axis + * (UP × dir) and height the vertical one — vertical runs, where that + * cross product degenerates, fall back to world X/Z. `roll` rotates the + * pair in the plane perpendicular to `dir`, letting a riser carry the + * orientation of the run it turned off instead of the bare fallback. + */ +export function rectSectionAxes(dir: Vector3, roll = 0): { width: Vector3; height: Vector3 } { + const d = dir.clone().normalize() + const xBase = new Vector3().crossVectors(UP, d) + if (xBase.lengthSq() < 1e-8) xBase.set(1, 0, 0) + xBase.normalize() + const zBase = new Vector3().crossVectors(xBase, d) + const c = Math.cos(roll) + const s = Math.sin(roll) + const width = xBase.clone().multiplyScalar(c).addScaledVector(zBase, s) + const height = xBase.clone().multiplyScalar(-s).addScaledVector(zBase, c) + return { width, height } +} + +/** + * Roll (radians) that keeps a rect cross-section continuous across an + * elbow: the dimension lying along the joint's hinge — the bend-plane + * normal `portDir × newDir`, perpendicular to both legs — must stay on + * the same physical face on the new run as on the source run. Returns 0 + * for an in-plane (degenerate-normal) joint, so horizontal turns keep + * the natural width-horizontal orientation. + */ +export function rollToContinueAcrossElbow( + sourceDir: Vector3, + sourceRoll: number, + portDir: Vector3, + newDir: Vector3, +): number { + const n = new Vector3().crossVectors(portDir, newDir) + if (n.lengthSq() < 1e-8) return 0 + n.normalize() + const src = rectSectionAxes(sourceDir, sourceRoll) + const carriesWidth = Math.abs(src.width.dot(n)) >= Math.abs(src.height.dot(n)) + const d = newDir.clone().normalize() + const xBase = new Vector3().crossVectors(UP, d) + if (xBase.lengthSq() < 1e-8) xBase.set(1, 0, 0) + xBase.normalize() + const zBase = new Vector3().crossVectors(xBase, d) + // Place the hinge-aligned face on the same axis the source carries it. + return carriesWidth + ? Math.atan2(n.dot(zBase), n.dot(xBase)) + : Math.atan2(-n.dot(xBase), n.dot(zBase)) +} diff --git a/packages/nodes/src/duct-segment/selection.tsx b/packages/nodes/src/duct-segment/selection.tsx index c1a302d1e1..23098bc6ef 100644 --- a/packages/nodes/src/duct-segment/selection.tsx +++ b/packages/nodes/src/duct-segment/selection.tsx @@ -66,7 +66,7 @@ import { type DuctEndpoint, ductContinuationHandlePlan, } from './continuation' -import { INCHES_TO_METERS } from './geometry' +import { INCHES_TO_METERS } from './profile' /** Port-snap radius for dragged run endpoints (meters, XZ). */ const PORT_SNAP_RADIUS_M = 0.4 diff --git a/packages/nodes/src/duct-segment/tool.tsx b/packages/nodes/src/duct-segment/tool.tsx index 16e6608aa7..8e5f5d9af2 100644 --- a/packages/nodes/src/duct-segment/tool.tsx +++ b/packages/nodes/src/duct-segment/tool.tsx @@ -1,6 +1,6 @@ 'use client' -import { type AnyNode, type DuctFittingNode, DuctSegmentNode } from '@pascal-app/core' +import { type AnyNode, type DuctFittingNode, DuctSegmentNode, nodeRegistry } from '@pascal-app/core' import { EDITOR_LAYER, triggerSFX, @@ -21,7 +21,7 @@ import { stepNominalRunSize, useDistributionRunTool, } from '@pascal-app/editor/distribution' -import { useEffect, useMemo, useRef, useState } from 'react' +import { useEffect, useMemo, useRef } from 'react' import { Euler, type Group, Vector3 } from 'three' import { getDuctFittingPorts } from '../duct-fitting/ports' import { @@ -43,9 +43,10 @@ import { DuctSegmentGhost, FittingGhost } from '../shared/mep-ghost' import { DUCT_PORT_SYSTEMS, runSectionHalfSizeM } from '../shared/port-systems' import { RunHangerPreview } from '../shared/run-hanger-controls' import { useRunHangerMode } from '../shared/run-hanger-mode' +import { clearRunContinuation, updateRunDefaults } from '../shared/run-tool-options' import { currentDuctContinuationSeed, ductEndpointPort } from './continuation' import { ductSegmentDefinition } from './definition' -import { rectSectionAxes, rollToContinueAcrossElbow } from './geometry' +import { rectSectionAxes, rollToContinueAcrossElbow } from './profile' /** * Continuous placement tool for duct segments. @@ -343,6 +344,34 @@ export function planDuctDraw( updates: [], delete: [], }) + const system = toolDefaults.system ?? startPort?.system ?? endPort?.system ?? 'supply' + for (const [port, away] of [ + [startPort, dir], + [endPort, [-dir[0], -dir[1], -dir[2]]], + ] as const) { + if (!port) continue + const owner = nodes[port.nodeId] + if (!owner || owner.type === 'duct-segment' || owner.type === 'duct-fitting') continue + const occupied = Object.values(nodes).some( + (node) => + node.id !== owner.id && + node.parentId === owner.parentId && + (nodeRegistry.get(node.type)?.ports?.(node) ?? []).some( + (other) => + other.system === port.system && + dist2([...other.position], [...port.position]) < 0.005 ** 2, + ), + ) + const message = + port.system !== system + ? 'Use the same supply or return system as the collar.' + : occupied + ? 'This collar is already connected.' + : new Vector3(...away).dot(new Vector3(...port.direction).normalize()) < 0.9999 + ? 'Draw the first section straight out of the collar, then add a bend from the new duct endpoint.' + : null + if (message) return { ...invalidPlan(), validationMessage: message } + } if (startPlan?.hasClearance === false || endPlan?.hasClearance === false) return invalidPlan() const startRealign = startPlan ? null : realignPlanFor(startPort, dir, nodes) const endRealign = endPlan ? null : realignPlanFor(endPort, [-dir[0], -dir[1], -dir[2]], nodes) @@ -413,11 +442,12 @@ export function planDuctDraw( if (!endTee && endTeePlan) ductEnd = endRealign?.collarPoint ?? end const realigns = [startRealign, endRealign].filter((p) => p !== null) - const crossHit = surface - ? findRunBodyCrossingSurface(start, end, BODY_SNAP_RADIUS_M, surface, { - kinds: ['duct-segment'], - }) - : null + const crossHit = + surface && (toolDefaults as Record).crossingMode !== 'cross' + ? findRunBodyCrossingSurface(start, end, BODY_SNAP_RADIUS_M, surface, { + kinds: ['duct-segment'], + }) + : null const crossOwner = crossHit ? nodes[crossHit.nodeId] : null const crossTappedElsewhere = crossHit?.nodeId === trunkBody?.nodeId || crossHit?.nodeId === endTrunkBody?.nodeId @@ -453,6 +483,7 @@ export function planDuctDraw( DuctSegmentNode.parse({ ...defaults, ...toolDefaults, + system, autoHangers, hangerStyle, name: profile.shape === 'rect' ? 'Trunk' : 'Duct run', @@ -532,29 +563,55 @@ const DuctSegmentTool = () => { const autoHangersRef = useRef(autoHangers) autoHangersRef.current = autoHangers const pendingPromotionRef = useRef(continuationSeed?.promotedFitting ?? null) - const [profile, setProfile] = useState(() => { - const defaults = ductSegmentDefinition.defaults() as DraftProfile - const seeded = useEditor.getState().toolDefaults['duct-segment'] as - | Partial - | undefined - return { - shape: continuationSeed?.duct.shape ?? seeded?.shape ?? defaults.shape, - diameter: continuationSeed?.duct.diameter ?? seeded?.diameter ?? defaults.diameter, - width: continuationSeed?.duct.width ?? seeded?.width ?? defaults.width, - height: continuationSeed?.duct.height ?? seeded?.height ?? defaults.height, - } - }) + const initialProfile = useRef(null) + if (!initialProfile.current) + initialProfile.current = (() => { + const defaults = ductSegmentDefinition.defaults() as DraftProfile + const seeded = useEditor.getState().toolDefaults['duct-segment'] as + | Partial + | undefined + return { + shape: continuationSeed?.duct.shape ?? seeded?.shape ?? defaults.shape, + diameter: continuationSeed?.duct.diameter ?? seeded?.diameter ?? defaults.diameter, + width: continuationSeed?.duct.width ?? seeded?.width ?? defaults.width, + height: continuationSeed?.duct.height ?? seeded?.height ?? defaults.height, + } + })() + const profile = useMemo( + () => ({ + shape: toolDefaults?.shape ?? initialProfile.current!.shape, + diameter: toolDefaults?.diameter ?? initialProfile.current!.diameter, + width: toolDefaults?.width ?? initialProfile.current!.width, + height: toolDefaults?.height ?? initialProfile.current!.height, + }), + [toolDefaults?.shape, toolDefaults?.diameter, toolDefaults?.width, toolDefaults?.height], + ) + const setProfile = (value: DraftProfile | ((current: DraftProfile) => DraftProfile)) => + updateRunDefaults('duct-segment', typeof value === 'function' ? value(profile) : value) const profileRef = useRef(profile) profileRef.current = profile useEffect(() => { const mode = useRunHangerMode.getState() mode.setEnabled('duct-segment', initialAutoHangersRef.current) - return () => mode.setEnabled('duct-segment', false) + return () => { + updateRunDefaults('duct-segment', { + autoHangers: useRunHangerMode.getState().enabled['duct-segment'], + }) + mode.setEnabled('duct-segment', false) + } }, []) const run = useDistributionRunTool({ active: !!activeLevelId, levelId: activeLevelId, toolName: 'duct-segment', + routingMode: + hangerDefaults?.routingMode === 'horizontal' || hangerDefaults?.routingMode === 'vertical' + ? hangerDefaults.routingMode + : 'surface', + elevation: typeof hangerDefaults?.elevation === 'number' ? hangerDefaults.elevation : 0, + targetElevation: + typeof hangerDefaults?.targetElevation === 'number' ? hangerDefaults.targetElevation : 3, + connectCrossings: hangerDefaults?.crossingMode !== 'cross', initialStart: continuationSeed ? ([...(continuationSeed.port?.position ?? continuationSeed.body?.point ?? [0, 0, 0])] as [ number, @@ -574,6 +631,15 @@ const DuctSegmentTool = () => { surfaceClearance: (surface) => surface ? ductSurfaceClearanceM(profileRef.current, surface.kind === 'wall') : 0, minimumSegmentLength: 0.08, + resolveFreeEnd: (start, end, connection) => { + const port = connection.port + const owner = port ? sceneApi.get(port.nodeId) : null + if (!port || !owner || owner.type === 'duct-segment' || owner.type === 'duct-fitting') + return end + const axis = new Vector3(...port.direction).normalize() + const distance = Math.max(0, new Vector3(...end).sub(new Vector3(...start)).dot(axis)) + return new Vector3(...start).addScaledVector(axis, distance).toArray() + }, inheritFromConnection: ({ port }) => { if (!port) return const inherited = inheritProfile(port, sceneApi.nodes()) @@ -682,14 +748,8 @@ const DuctSegmentTool = () => { }) useEffect(() => { - if (!toolDefaults) return - setProfile((current) => ({ - shape: toolDefaults.shape ?? current.shape, - diameter: toolDefaults.diameter ?? current.diameter, - width: toolDefaults.width ?? current.width, - height: toolDefaults.height ?? current.height, - })) - }, [toolDefaults]) + updateRunDefaults('duct-segment', initialProfile.current!) + }, []) const previewPlan = useMemo(() => { if (!(activeLevelId && run.start && run.cursor)) return null @@ -720,6 +780,11 @@ const DuctSegmentTool = () => { run.surfaceTarget, sceneApi, ]) + // Profile changes alter the centreline clearance even with a stationary pointer. + // biome-ignore lint/correctness/useExhaustiveDependencies: the resolver reads the profile through a ref + useEffect(() => { + run.refreshCursor() + }, [profile, run.refreshCursor]) const ghostFittings = useMemo(() => previewPlan?.fittings ?? [], [previewPlan]) useEffect(() => { @@ -734,7 +799,7 @@ const DuctSegmentTool = () => { ) }, [autoHangers, hangerStyle, ghostFittings, profile, run.cursor, run.start]) useEffect(() => () => usePathDraftPreview.getState().clear('duct-segment'), []) - useEffect(() => () => useEditor.getState().setToolDefaults('duct-segment', null), []) + useEffect(() => () => clearRunContinuation('duct-segment'), []) if (!activeLevelId) return null const extraParts = @@ -748,8 +813,32 @@ const DuctSegmentTool = () => { return ( ['reducer', 'transition'].includes(fitting.fittingType)) + .map((fitting) => { + const size = (outlet: boolean) => { + const shape = outlet + ? (fitting.outletShape ?? fitting.shape2) + : (fitting.inletShape ?? fitting.shape) + return shape === 'round' + ? `Ø${outlet ? fitting.diameter2 : fitting.diameter} in` + : `${outlet ? fitting.width2 : fitting.width} × ${outlet ? fitting.height2 : fitting.height} in ${shape}` + } + const ports = getDuctFittingPorts(fitting) + const length = new Vector3(...ports[0]!.position).distanceTo( + new Vector3(...ports[1]!.position), + ) + return `${size(false)} → ${size(true)} · ${length.toFixed(2)} m long` + }) + .join('; ') || undefined + } point={run.cursor} target={run.endConnection.port} + screen={run.snapScreen ?? run.cursorScreen} + error={ + run.cursorScreen ? (previewPlan?.validationMessage ?? run.validationMessage) : undefined + } levelId={activeLevelId} profile={{ ...profile, @@ -761,6 +850,7 @@ const DuctSegmentTool = () => { cursor={run.cursor} cursorRef={cursorRef} directionMode={run.directionMode} + routingMode={run.routingMode} extraParts={extraParts} lengthInput={run.lengthInput} onLengthInputChange={run.onLengthInputChange} diff --git a/packages/nodes/src/duct-terminal/geometry.ts b/packages/nodes/src/duct-terminal/geometry.ts index 28475dfab2..e3321e9d89 100644 --- a/packages/nodes/src/duct-terminal/geometry.ts +++ b/packages/nodes/src/duct-terminal/geometry.ts @@ -7,7 +7,8 @@ import { MeshStandardMaterial, Vector3, } from 'three' -import { createOvalSectionGeometry, INCHES_TO_METERS } from '../duct-segment/geometry' +import { createOvalSectionGeometry } from '../duct-segment/geometry' +import { INCHES_TO_METERS } from '../duct-segment/profile' import { COLLAR_LENGTH, mountQuaternion, terminalSystem } from './ports' import type { DuctTerminalNode } from './schema' diff --git a/packages/nodes/src/duct-terminal/parametrics.ts b/packages/nodes/src/duct-terminal/parametrics.ts index 4df7760ef7..d905fb9db9 100644 --- a/packages/nodes/src/duct-terminal/parametrics.ts +++ b/packages/nodes/src/duct-terminal/parametrics.ts @@ -2,6 +2,7 @@ import type { ParametricDescriptor } from '@pascal-app/core' import type { DuctTerminalNode } from './schema' export const ductTerminalParametrics: ParametricDescriptor = { + trailingSection: () => import('../shared/duct-collar-inspector'), groups: [ { label: 'Terminal', diff --git a/packages/nodes/src/duct-terminal/ports.ts b/packages/nodes/src/duct-terminal/ports.ts index c53b81f786..045dc0a068 100644 --- a/packages/nodes/src/duct-terminal/ports.ts +++ b/packages/nodes/src/duct-terminal/ports.ts @@ -1,6 +1,6 @@ import type { NodePort } from '@pascal-app/core' import { Euler, Quaternion, Vector3 } from 'three' -import { equivalentDiameterIn, ovalEquivalentDiameterIn } from '../duct-segment/geometry' +import { equivalentDiameterIn, ovalEquivalentDiameterIn } from '../duct-segment/profile' import type { DuctTerminalNode } from './schema' /** Collar stub length in meters behind the face. */ diff --git a/packages/nodes/src/hvac-equipment/floorplan.ts b/packages/nodes/src/hvac-equipment/floorplan.ts index e15b850455..4870fcd23f 100644 --- a/packages/nodes/src/hvac-equipment/floorplan.ts +++ b/packages/nodes/src/hvac-equipment/floorplan.ts @@ -1,5 +1,5 @@ import type { FloorplanGeometry, FloorplanPoint, GeometryContext } from '@pascal-app/core' -import { INCHES_TO_METERS } from '../duct-segment/geometry' +import { INCHES_TO_METERS } from '../duct-segment/profile' import { getHvacEquipmentPorts } from './ports' import type { HvacEquipmentNode } from './schema' diff --git a/packages/nodes/src/hvac-equipment/geometry.ts b/packages/nodes/src/hvac-equipment/geometry.ts index 72fb612256..bcc193e5b1 100644 --- a/packages/nodes/src/hvac-equipment/geometry.ts +++ b/packages/nodes/src/hvac-equipment/geometry.ts @@ -12,11 +12,8 @@ import { TorusGeometry, Vector3, } from 'three' -import { - createOvalSectionGeometry, - INCHES_TO_METERS, - rectSectionAxes, -} from '../duct-segment/geometry' +import { createOvalSectionGeometry } from '../duct-segment/geometry' +import { INCHES_TO_METERS, rectSectionAxes } from '../duct-segment/profile' import { localEquipmentPorts, localRefrigerantPorts } from './ports' import type { HvacEquipmentNode } from './schema' diff --git a/packages/nodes/src/hvac-equipment/parametrics.ts b/packages/nodes/src/hvac-equipment/parametrics.ts index 9130f9ed0a..db6d1557ae 100644 --- a/packages/nodes/src/hvac-equipment/parametrics.ts +++ b/packages/nodes/src/hvac-equipment/parametrics.ts @@ -2,6 +2,7 @@ import type { ParametricDescriptor } from '@pascal-app/core' import type { HvacEquipmentNode } from './schema' export const hvacEquipmentParametrics: ParametricDescriptor = { + trailingSection: () => import('../shared/duct-collar-inspector'), groups: [ { label: 'Equipment', diff --git a/packages/nodes/src/hvac-equipment/ports.ts b/packages/nodes/src/hvac-equipment/ports.ts index 9bcfb21c29..55e8262f95 100644 --- a/packages/nodes/src/hvac-equipment/ports.ts +++ b/packages/nodes/src/hvac-equipment/ports.ts @@ -1,6 +1,6 @@ import type { NodePort } from '@pascal-app/core' import { Vector3 } from 'three' -import { equivalentDiameterIn, ovalEquivalentDiameterIn } from '../duct-segment/geometry' +import { equivalentDiameterIn, ovalEquivalentDiameterIn } from '../duct-segment/profile' import type { HvacEquipmentNode } from './schema' type CollarShape = 'round' | 'rect' | 'oval' diff --git a/packages/nodes/src/index.ts b/packages/nodes/src/index.ts index 85bbe690a8..7e79d88560 100644 --- a/packages/nodes/src/index.ts +++ b/packages/nodes/src/index.ts @@ -213,6 +213,7 @@ export { createRoofGlazingPreview } from './roof/glazing-preview' export { roofSegmentDefinition } from './roof-segment' export { scanDefinition } from './scan' export { separatorDefinition } from './separator/definition' +export { default as PipeCollarInspector } from './shared/pipe-collar-inspector' export { shelfDefinition } from './shelf' export { siteDefinition } from './site' export { skylightDefinition } from './skylight' diff --git a/packages/nodes/src/lineset/floorplan.ts b/packages/nodes/src/lineset/floorplan.ts index 7de546cc1d..4d6b118bea 100644 --- a/packages/nodes/src/lineset/floorplan.ts +++ b/packages/nodes/src/lineset/floorplan.ts @@ -1,5 +1,5 @@ import type { FloorplanGeometry, FloorplanPoint, GeometryContext } from '@pascal-app/core' -import { INCHES_TO_METERS } from '../duct-segment/geometry' +import { INCHES_TO_METERS } from '../duct-segment/profile' import type { LinesetNode } from './schema' const COPPER_LINE = '#b06b3f' diff --git a/packages/nodes/src/lineset/geometry.ts b/packages/nodes/src/lineset/geometry.ts index 154a7c3e60..ab2ba5f151 100644 --- a/packages/nodes/src/lineset/geometry.ts +++ b/packages/nodes/src/lineset/geometry.ts @@ -1,5 +1,5 @@ import { CylinderGeometry, Group, Mesh, MeshStandardMaterial, SphereGeometry, Vector3 } from 'three' -import { INCHES_TO_METERS } from '../duct-segment/geometry' +import { INCHES_TO_METERS } from '../duct-segment/profile' import type { LinesetNode } from './schema' const RADIAL_SEGMENTS = 16 diff --git a/packages/nodes/src/liquid-line/floorplan.ts b/packages/nodes/src/liquid-line/floorplan.ts index 13b03943a3..f87a3e6dec 100644 --- a/packages/nodes/src/liquid-line/floorplan.ts +++ b/packages/nodes/src/liquid-line/floorplan.ts @@ -1,5 +1,5 @@ import type { FloorplanGeometry, FloorplanPoint, GeometryContext } from '@pascal-app/core' -import { INCHES_TO_METERS } from '../duct-segment/geometry' +import { INCHES_TO_METERS } from '../duct-segment/profile' import type { LiquidLineNode } from './schema' const COPPER_LINE = '#b06b3f' diff --git a/packages/nodes/src/liquid-line/geometry.ts b/packages/nodes/src/liquid-line/geometry.ts index 6b7cd42771..db7e112db8 100644 --- a/packages/nodes/src/liquid-line/geometry.ts +++ b/packages/nodes/src/liquid-line/geometry.ts @@ -1,5 +1,5 @@ import { CylinderGeometry, Group, Mesh, MeshStandardMaterial, SphereGeometry, Vector3 } from 'three' -import { INCHES_TO_METERS } from '../duct-segment/geometry' +import { INCHES_TO_METERS } from '../duct-segment/profile' import type { LiquidLineNode } from './schema' const RADIAL_SEGMENTS = 16 diff --git a/packages/nodes/src/pipe-fitting/floorplan.ts b/packages/nodes/src/pipe-fitting/floorplan.ts index 15200d0935..c5b2983840 100644 --- a/packages/nodes/src/pipe-fitting/floorplan.ts +++ b/packages/nodes/src/pipe-fitting/floorplan.ts @@ -1,5 +1,5 @@ import type { FloorplanGeometry, GeometryContext } from '@pascal-app/core' -import { INCHES_TO_METERS } from '../duct-segment/geometry' +import { INCHES_TO_METERS } from '../duct-segment/profile' import { accessoryFloorplan } from '../shared/accessory-floorplan' import { buildPipeFittingGeometry } from './geometry' import { getPipeFittingPorts } from './ports' diff --git a/packages/nodes/src/pipe-fitting/geometry.ts b/packages/nodes/src/pipe-fitting/geometry.ts index dc1f18d47e..a9720e8669 100644 --- a/packages/nodes/src/pipe-fitting/geometry.ts +++ b/packages/nodes/src/pipe-fitting/geometry.ts @@ -11,7 +11,7 @@ import { TubeGeometry, Vector3, } from 'three' -import { INCHES_TO_METERS } from '../duct-segment/geometry' +import { INCHES_TO_METERS } from '../duct-segment/profile' import { createPipeMaterial } from '../pipe-segment/geometry' import { addPlug, addProfile } from '../shared/accessory-geometry' import { localPipeFittingPorts } from './ports' diff --git a/packages/nodes/src/pipe-fitting/parametrics.ts b/packages/nodes/src/pipe-fitting/parametrics.ts index 0d2946cc01..fa52d2fd36 100644 --- a/packages/nodes/src/pipe-fitting/parametrics.ts +++ b/packages/nodes/src/pipe-fitting/parametrics.ts @@ -57,6 +57,7 @@ export const pipeFittingParametrics: ParametricDescriptor = { return updates }, + trailingSection: () => import('../shared/pipe-collar-inspector'), groups: [ { label: 'Fitting', diff --git a/packages/nodes/src/pipe-fitting/ports.ts b/packages/nodes/src/pipe-fitting/ports.ts index 336efc3682..db9db1f574 100644 --- a/packages/nodes/src/pipe-fitting/ports.ts +++ b/packages/nodes/src/pipe-fitting/ports.ts @@ -1,6 +1,6 @@ import type { NodePort } from '@pascal-app/core' import { Euler, Vector3 } from 'three' -import { INCHES_TO_METERS } from '../duct-segment/geometry' +import { INCHES_TO_METERS } from '../duct-segment/profile' import type { PipeFittingNode } from './schema' /** Hub stub length in meters — pipe fittings are stubbier than duct diff --git a/packages/nodes/src/pipe-segment/collar-connection.ts b/packages/nodes/src/pipe-segment/collar-connection.ts new file mode 100644 index 0000000000..8f7e78924f --- /dev/null +++ b/packages/nodes/src/pipe-segment/collar-connection.ts @@ -0,0 +1,89 @@ +import { type AnyNode, nodeRegistry, PipeFittingNode } from '@pascal-app/core' +import { refuse } from '@pascal-app/core/agent-tools' +import type { ScenePort } from '@pascal-app/editor/distribution' +import { Euler, Quaternion, Vector3 } from 'three' +import { pipeFittingLegLength } from '../pipe-fitting/ports' + +type Point = [number, number, number] +export function pipeCollar( + nodes: Readonly>, + nodeId: string, + portId: string, +): ScenePort | null { + const node = nodes[nodeId] + const port = + node && + nodeRegistry + .get(node.type) + ?.ports?.(node) + .find((port) => port.id === portId) + return port && (port.system === 'waste' || port.system === 'vent') + ? { ...port, nodeId: node.id } + : null +} +export function pipeCollarOccupied( + nodes: Readonly>, + port: ScenePort, +): boolean { + const owner = nodes[port.nodeId] + return Object.values(nodes).some( + (node) => + node.id !== port.nodeId && + node.parentId === owner?.parentId && + (nodeRegistry.get(node.type)?.ports?.(node) ?? []).some( + (other) => + other.system === port.system && + new Vector3(...other.position).distanceTo(new Vector3(...port.position)) < 0.005, + ), + ) +} + +/** Fixed collars cannot be trimmed like pipe endpoints; leave straight along their axis. */ +export function planPipeCollarConnection( + nodes: Readonly>, + source: ScenePort, + toward: Point, + diameter: number, + system: string, + material: PipeFittingNode['pipeMaterial'], +) { + const port = pipeCollar(nodes, source.nodeId, source.id) + if (!port || new Vector3(...port.position).distanceTo(new Vector3(...source.position)) > 1e-6) + return refuse( + 'pipe_collar_changed', + 'The connection moved or disappeared. Select the collar again.', + ) + if (port.system !== system) + return refuse('pipe_collar_system', 'Use the same waste or vent system as the collar.') + if (pipeCollarOccupied(nodes, port)) + return refuse('pipe_collar_occupied', 'This collar is already connected.') + const axis = new Vector3(...port.direction).normalize() + const travel = new Vector3(...toward).sub(new Vector3(...port.position)) + if (travel.length() < 0.05 || axis.dot(travel.clone().normalize()) < 0.999999) + return refuse( + 'pipe_collar_direction', + 'Draw the first section straight out of the collar, then add a bend from the new pipe endpoint.', + ) + if (diameter === port.diameter) + return { point: [...port.position] as Point, fittings: [] as PipeFittingNode[] } + const leg = pipeFittingLegLength(Math.max(diameter, port.diameter)) + if (travel.length() < 2 * leg + 0.05) + return refuse('pipe_collar_space', 'Lengthen the pipe to leave room for the reducer.') + const rotation = new Euler().setFromQuaternion( + new Quaternion().setFromUnitVectors(new Vector3(1, 0, 0), axis), + ) + const fitting = PipeFittingNode.parse({ + parentId: nodes[source.nodeId]!.parentId, + fittingType: 'reducer', + diameter: port.diameter, + diameter2: diameter, + system: port.system, + pipeMaterial: material, + position: new Vector3(...port.position).addScaledVector(axis, leg).toArray(), + rotation: [rotation.x, rotation.y, rotation.z], + }) + return { + point: new Vector3(...port.position).addScaledVector(axis, 2 * leg).toArray() as Point, + fittings: [fitting], + } +} diff --git a/packages/nodes/src/pipe-segment/connect-operation.ts b/packages/nodes/src/pipe-segment/connect-operation.ts new file mode 100644 index 0000000000..1dd79f9333 --- /dev/null +++ b/packages/nodes/src/pipe-segment/connect-operation.ts @@ -0,0 +1,70 @@ +import { nodeRegistry, PipeSegmentNode } from '@pascal-app/core' +import type { AgentOperation } from '@pascal-app/core/agent-operations' +import { refuse } from '@pascal-app/core/agent-tools' +import { createPipeRunEndCap } from '../shared/automatic-run-end-cap' +import { pipeCollar, planPipeCollarConnection } from './collar-connection' + +export type PipeConnectInput = { + nodeId: string + portId: string + end: [number, number, number] + diameter?: number +} +export const connectPipe: AgentOperation = (nodes, input) => { + const owner = nodes[input.nodeId] + const port = pipeCollar(nodes, input.nodeId, input.portId) + if (!owner || !port || owner.type === 'pipe-segment') + return refuse('pipe_collar_missing', 'Choose a fixture, trap or fitting waste/vent collar.') + if (!input.end.every(Number.isFinite)) + return refuse('pipe_endpoint_invalid', 'Enter a finite endpoint.') + const diameter = input.diameter ?? port.diameter + const parsed = PipeSegmentNode.safeParse({ + parentId: owner.parentId, + path: [[...port.position], input.end], + diameter, + system: port.system, + pipeMaterial: 'pipeMaterial' in owner ? owner.pipeMaterial : 'pvc', + }) + if (!parsed.success) + return refuse('pipe_size_invalid', 'Use a supported pipe diameter between 1.25 and 8 inches.') + const pipe = parsed.data + const plan = planPipeCollarConnection( + nodes, + port, + input.end, + diameter, + pipe.system, + pipe.pipeMaterial, + ) + // An endpoint at another collar must use the draw tool's two-ended connection planning. + if ( + Object.values(nodes).some( + (node) => + node.parentId === owner.parentId && + (nodeRegistry.get(node.type)?.ports?.(node) ?? []).some( + (other) => + other.system === port.system && + Math.hypot(...other.position.map((v, i) => v - input.end[i]!)) < 0.005, + ), + ) + ) + return refuse( + 'pipe_endpoint_occupied', + 'Choose a free endpoint; use pipe drawing to join an existing collar.', + ) + pipe.path = [plan.point, input.end] + const cap = createPipeRunEndCap(pipe)! + return { + result: { + message: 'Pipe connected; source collar remains fixed.', + pipeId: pipe.id, + reducers: plan.fittings.length, + }, + changes: { + create: [pipe, ...plan.fittings, cap].map((node) => ({ + node, + parentId: owner.parentId ?? undefined, + })), + }, + } +} diff --git a/packages/nodes/src/pipe-segment/continuation.test.ts b/packages/nodes/src/pipe-segment/continuation.test.ts index 806a864864..0741fb4a57 100644 --- a/packages/nodes/src/pipe-segment/continuation.test.ts +++ b/packages/nodes/src/pipe-segment/continuation.test.ts @@ -179,3 +179,59 @@ describe('pipe continuation', () => { } }) }) + +test('continuing from either endpoint inherits the signed grade', async () => { + const { useEditor } = await import('@pascal-app/editor') + const { activatePipeContinuation } = await import('./continuation') + const previous = useEditor.getState() + const pipe = PipeSegmentNode.parse({ + path: [ + [0, 2, 0], + [4, 1.92, 0], + ], + system: 'waste', + }) + try { + activatePipeContinuation(pipe, 'end') + expect(useEditor.getState().toolDefaults['pipe-segment']).toMatchObject({ + fall: 'sloped', + flowDirection: 'forward', + }) + expect(Number(useEditor.getState().toolDefaults['pipe-segment']?.gradePercent)).toBeCloseTo(2) + activatePipeContinuation(pipe, 'start') + expect(useEditor.getState().toolDefaults['pipe-segment']?.flowDirection).toBe('reverse') + } finally { + useEditor.setState(previous) + } +}) + +test('an open trap collar seeds the exact elevation, direction and material', async () => { + const { PipeTrapNode } = await import('@pascal-app/core') + const { pipeTrapDefinition } = await import('@pascal-app/nodes') + const restore = nodeRegistry._snapshot() + try { + registerNode(pipeTrapDefinition) + registerNode(pipeSegmentDefinition) + const trap = PipeTrapNode.parse({ + position: [1, 2, 3], + rotation: Math.PI / 4, + diameter: 1.5, + pipeMaterial: 'abs', + }) + const port = pipeTrapDefinition.ports!(trap)[1]! + const defaults = { continuation: { nodeId: trap.id, portId: port.id } } + const seed = resolvePipeContinuationSeed(defaults, { [trap.id]: trap }) + expect(seed?.port).toEqual({ ...port, nodeId: trap.id }) + expect(seed?.pipe.diameter).toBe(1.5) + expect(seed?.pipe.pipeMaterial).toBe('abs') + const occupied = PipeSegmentNode.parse({ + path: [[...port.position], port.position.map((v, i) => v + port.direction[i]!)], + }) + expect( + resolvePipeContinuationSeed(defaults, { [trap.id]: trap, [occupied.id]: occupied }), + ).toBeNull() + expect(resolvePipeContinuationSeed(defaults, {})).toBeNull() + } finally { + restore() + } +}) diff --git a/packages/nodes/src/pipe-segment/continuation.ts b/packages/nodes/src/pipe-segment/continuation.ts index f7590e203f..cdf445a02e 100644 --- a/packages/nodes/src/pipe-segment/continuation.ts +++ b/packages/nodes/src/pipe-segment/continuation.ts @@ -10,7 +10,9 @@ import { type RunContinuationHandlePlan, resolvePipeContinuationHandle, } from '../shared/elbow-branch-continuation' -import type { PipeSegmentNode } from './schema' +import { pipeCollar, pipeCollarOccupied } from './collar-connection' +import { PipeSegmentNode } from './schema' +import { pipeGrade } from './slope' export type PipeEndpoint = 'start' | 'end' @@ -24,6 +26,7 @@ export type PipeContinuationSeed = { type PipeContinuationDefaults = { continuation?: { nodeId?: unknown + portId?: unknown endpoint?: unknown fittingId?: unknown segmentIndex?: unknown @@ -80,6 +83,19 @@ export function resolvePipeContinuationSeed( nodes: Record, ): PipeContinuationSeed | null { const continuation = (defaults as PipeContinuationDefaults | null)?.continuation + if (typeof continuation?.nodeId === 'string' && typeof continuation.portId === 'string') { + const source = nodes[continuation.nodeId] + const port = pipeCollar(nodes, continuation.nodeId, continuation.portId) + if (!source || !port || pipeCollarOccupied(nodes, port)) return null + const profile = PipeSegmentNode.safeParse({ + parentId: source.parentId, + diameter: port.diameter, + system: port.system, + pipeMaterial: 'pipeMaterial' in source ? source.pipeMaterial : 'pvc', + path: [[...port.position], port.position.map((value, i) => value + port.direction[i]!)], + }) + return profile.success ? { pipe: profile.data, port, body: null } : null + } const endpoint = continuation?.endpoint const nodeId = continuation?.nodeId if (endpoint === 'branch' && typeof nodeId === 'string') { @@ -137,6 +153,9 @@ export function activatePipeBranch( if (!pipe.path[segmentIndex] || !pipe.path[segmentIndex + 1]) return const editor = useEditor.getState() editor.setToolDefaults('pipe-segment', { + ...editor.toolDefaults['pipe-segment'], + routingMode: 'surface', + crossingMode: 'connect', continuation: { nodeId: pipe.id, endpoint: 'branch', segmentIndex, point }, }) useViewer.getState().setSelection({ selectedIds: [] }) @@ -151,7 +170,22 @@ export function activatePipeContinuation( if (!pipeEndpointPort(pipe, endpoint)) return const editor = useEditor.getState() editor.setToolDefaults('pipe-segment', { + ...editor.toolDefaults['pipe-segment'], + routingMode: 'surface', + crossingMode: 'connect', continuation: { nodeId: pipe.id, endpoint, ...(fittingId ? { fittingId } : {}) }, + ...(() => { + const a = endpoint === 'end' ? pipe.path.at(-2)! : pipe.path[1]! + const b = endpoint === 'end' ? pipe.path.at(-1)! : pipe.path[0]! + const grade = pipeGrade(a, b) + return grade === null + ? { fall: 'level' } + : { + fall: Math.abs(grade) > 1e-6 ? 'sloped' : 'level', + gradePercent: Math.abs(grade) * 100, + flowDirection: grade < 0 ? 'reverse' : 'forward', + } + })(), }) useViewer.getState().setSelection({ selectedIds: [] }) editor.setTool('pipe-segment') diff --git a/packages/nodes/src/pipe-segment/definition.ts b/packages/nodes/src/pipe-segment/definition.ts index 6384aecd1b..aad356664e 100644 --- a/packages/nodes/src/pipe-segment/definition.ts +++ b/packages/nodes/src/pipe-segment/definition.ts @@ -1,9 +1,10 @@ import type { NodeDefinition } from '@pascal-app/core' -import { createPathPointMoveAffordance } from '../shared/path-point-affordance' import { createRunHangerToolHint } from '../shared/run-hanger-mode' +import { pipeRunToolOptions } from '../shared/run-tool-options' import { pipeBranchAffordance, pipeContinuationAffordance } from './continuation' import { buildPipeSegmentFloorplan } from './floorplan' import { buildPipeSegmentGeometry } from './geometry' +import { pipeGradePointAffordance } from './grade-affordance' import { pipeSegmentParametrics } from './parametrics' import { PipeSegmentNode } from './schema' @@ -103,7 +104,7 @@ export const pipeSegmentDefinition: NodeDefinition = { // `affordanceTools.selection` handles. The builder emits an // `endpoint-handle` per path vertex; this drags the matching point. floorplanAffordances: { - 'move-path-point': createPathPointMoveAffordance('pipe-segment'), + 'move-path-point': pipeGradePointAffordance, 'continue-run': pipeContinuationAffordance, 'branch-run': pipeBranchAffordance, }, @@ -122,6 +123,7 @@ export const pipeSegmentDefinition: NodeDefinition = { }, tool: () => import('./tool'), + toolOptions: pipeRunToolOptions, toolHints: [ { key: 'Click', label: 'Start run' }, { key: 'Click again', label: 'Place and continue' }, @@ -135,7 +137,8 @@ export const pipeSegmentDefinition: NodeDefinition = { presentation: { label: 'DWV Pipe', - description: 'Drain / waste / vent pipe run — draw level or toggle a ¼″ per foot fall with S.', + description: + 'Drain / waste / vent pipe run — draw level or choose grade and downhill direction.', icon: { kind: 'url', src: '/icons/dwv-pipes.webp' }, paletteSection: 'structure', paletteOrder: 95, diff --git a/packages/nodes/src/pipe-segment/floorplan.ts b/packages/nodes/src/pipe-segment/floorplan.ts index db30a2f0c0..ecd71f81ec 100644 --- a/packages/nodes/src/pipe-segment/floorplan.ts +++ b/packages/nodes/src/pipe-segment/floorplan.ts @@ -1,8 +1,9 @@ import type { FloorplanGeometry, FloorplanPoint, GeometryContext } from '@pascal-app/core' -import { INCHES_TO_METERS } from '../duct-segment/geometry' +import { INCHES_TO_METERS } from '../duct-segment/profile' import { runHangerFloorplan } from '../shared/run-hangers' import { pipeContinuationHandlePlan, pipeEndpointPort } from './continuation' import type { PipeSegmentNode } from './schema' +import { pipeGrade } from './slope' const WASTE_COLOR = '#57534e' const VENT_COLOR = '#78716c' @@ -87,6 +88,41 @@ export function buildPipeSegmentFloorplan( // Selection chrome: one draggable handle per path vertex (2D twin of the // 3D selection handles). Routes to the shared `move-path-point` affordance. if (view?.selected) { + for (let i = 1; i < node.path.length; i++) { + const a = node.path[i - 1]!, + b = node.path[i]! + const grade = pipeGrade(a, b) + if (grade === null || Math.abs(grade) < 1e-6) continue + const length = Math.hypot(b[0] - a[0], b[2] - a[2]) + const sign = Math.sign(grade), + dx = ((b[0] - a[0]) / length) * sign, + dz = ((b[2] - a[2]) / length) * sign + const x = (a[0] + b[0]) / 2, + z = (a[2] + b[2]) / 2, + size = Math.min(0.12, length / 5) + children.push({ + kind: 'polyline', + points: [ + [x - dx * size - (dz * size) / 2, z - dz * size + (dx * size) / 2], + [x, z], + [x - dx * size + (dz * size) / 2, z - dz * size - (dx * size) / 2], + ], + stroke, + strokeWidth: 2, + vectorEffect: 'non-scaling-stroke', + }) + children.push({ + kind: 'text', + x: x - dz * 0.18, + y: z + dx * 0.18, + text: `${(Math.abs(grade) * 100).toFixed(2)}%`, + fontSize: 0.12, + fill: stroke, + textAnchor: 'middle', + upright: true, + }) + } + for (let k = 0; k < points.length; k++) { children.push({ kind: 'endpoint-handle', diff --git a/packages/nodes/src/pipe-segment/geometry.ts b/packages/nodes/src/pipe-segment/geometry.ts index 3b2263fd69..ab4f346bde 100644 --- a/packages/nodes/src/pipe-segment/geometry.ts +++ b/packages/nodes/src/pipe-segment/geometry.ts @@ -1,6 +1,7 @@ import type { GeometryContext } from '@pascal-app/core' import { Group, Mesh, MeshStandardMaterial, SphereGeometry, Vector3 } from 'three' -import { buildSection, INCHES_TO_METERS } from '../duct-segment/geometry' +import { buildSection } from '../duct-segment/geometry' +import { INCHES_TO_METERS } from '../duct-segment/profile' import { buildRunHangers } from '../shared/run-hangers' import type { PipeSegmentNode } from './schema' diff --git a/packages/nodes/src/pipe-segment/grade-affordance.ts b/packages/nodes/src/pipe-segment/grade-affordance.ts new file mode 100644 index 0000000000..1bef847ba9 --- /dev/null +++ b/packages/nodes/src/pipe-segment/grade-affordance.ts @@ -0,0 +1,72 @@ +import { + type AnyNode, + type AnyNodeId, + analyzePortConnectivity, + type FloorplanAffordance, + type PipeSegmentNode, + useLiveNodeOverrides, + useScene, +} from '@pascal-app/core' +import { isGridSnapActive, snapPointToGrid } from '@pascal-app/editor' +import { editPipeGrade } from './grade-operation' + +export const pipeGradePointAffordance: FloorplanAffordance = { + start({ node, payload, nodes }) { + const index = (payload as { pointIndex: number }).pointIndex + const point = node.path[index] + let updates: { id: AnyNodeId; data: Partial }[] = [] + const previewIds = new Set() + const clear = () => { + for (const id of previewIds) { + useLiveNodeOverrides.getState().clear(id) + useScene.getState().markDirty(id) + } + previewIds.clear() + } + return { + affectedIds: [ + node.id, + ...analyzePortConnectivity(node, nodes).connections.map((connection) => connection.nodeId), + ], + apply({ planPoint, modifiers }) { + clear() + updates = [] + if (!point) return + const [x, z] = isGridSnapActive() + ? snapPointToGrid([planPoint[0], planPoint[1]]) + : planPoint + try { + const outcome = editPipeGrade( + nodes, + { + nodeId: node.id, + action: 'endpoint', + pointIndex: index, + point: [x, point[1], z], + detach: modifiers.altKey, + }, + { activeLevelId: node.parentId }, + ) + updates = (outcome.changes?.update ?? []).map((entry) => ({ + ...entry, + id: entry.id as AnyNodeId, + })) + useLiveNodeOverrides + .getState() + .setMany(updates.map((entry) => [entry.id, entry.data as Record])) + for (const entry of updates) { + previewIds.add(entry.id) + useScene.getState().markDirty(entry.id) + } + } catch { + /* Invalid frames leave the committed route in place. */ + } + }, + canCommit: () => updates.length > 0, + commit() { + clear() + useScene.getState().updateNodes(updates) + }, + } + }, +} diff --git a/packages/nodes/src/pipe-segment/grade-inspector.tsx b/packages/nodes/src/pipe-segment/grade-inspector.tsx new file mode 100644 index 0000000000..5815148a29 --- /dev/null +++ b/packages/nodes/src/pipe-segment/grade-inspector.tsx @@ -0,0 +1,123 @@ +'use client' +import { type AnyNodeId, type PipeSegmentNode, useScene } from '@pascal-app/core' +import { useState } from 'react' +import RunHangerInspector from '../shared/run-hanger-inspector' +import { editPipeGrade, type PipeGradeInput } from './grade-operation' +import PipeOffsetInspector from './offset-inspector' +import PipeResizeInspector from './resize-inspector' +import { pipeGrade, pipeGradeLabel } from './slope' + +export default function PipeGradeInspector({ node }: { node: PipeSegmentNode }) { + return ( + <> + + + + + > + ) +} +function GradeForm({ node }: { node: PipeSegmentNode }) { + const initial = pipeGrade(node.path[0]!, node.path[1]!) ?? 0 + const [grade, setGrade] = useState(Math.abs(initial) * 100) + const [flow, setFlow] = useState<'forward' | 'reverse'>(initial < 0 ? 'reverse' : 'forward') + const [anchor, setAnchor] = useState<'start' | 'end'>('start') + const [elevation, setElevation] = useState(node.path[0]![1]) + const [message, setMessage] = useState('') + const apply = (input: Partial) => { + try { + const outcome = editPipeGrade( + useScene.getState().nodes, + { nodeId: node.id, action: 'grade', anchor, ...input }, + { activeLevelId: node.parentId }, + ) + useScene.getState().applyNodeChanges({ + update: outcome.changes?.update?.map((entry) => ({ + ...entry, + id: entry.id as AnyNodeId, + })), + }) + setMessage('Applied in one undo step.') + } catch (error) { + setMessage(error instanceof Error ? error.message : 'Unable to edit pipe.') + } + } + return ( + + Grade and flow + + Centerline elevations above level: start {node.path[0]![1].toFixed(3)} m · end{' '} + {node.path.at(-1)![1].toFixed(3)} m + + {node.path.slice(1).map((point, index) => ( + + Leg {index + 1}: {pipeGradeLabel(node.path[index]!, point)} + + ))} + + Arrows show downhill direction. Level runs have no gravity fall. Editing a path point + preserves each leg’s grade. + + + Grade (%) + setGrade(event.target.valueAsNumber)} + className="w-24 border bg-background p-1" + /> + + setFlow(event.target.value as typeof flow)} + > + Start → end + End → start + + { + const next = event.target.value as typeof anchor + setAnchor(next) + setElevation(next === 'start' ? node.path[0]![1] : node.path.at(-1)![1]) + }} + > + Keep start elevation + Keep end elevation + + apply({ gradePercent: grade, flow })} + > + Apply grade to horizontal legs + + + {anchor === 'start' ? 'Start' : 'End'} elevation (m) + setElevation(event.target.valueAsNumber)} + className="w-24 border bg-background p-1" + /> + + apply({ action: 'elevation', elevation })} + > + Move elevation, keep grades + + {message && {message}} + + ) +} diff --git a/packages/nodes/src/pipe-segment/grade-operation.ts b/packages/nodes/src/pipe-segment/grade-operation.ts new file mode 100644 index 0000000000..8887ec5653 --- /dev/null +++ b/packages/nodes/src/pipe-segment/grade-operation.ts @@ -0,0 +1,161 @@ +import { + type AnyNode, + type AnyNodeId, + analyzePortConnectivity, + nodeRegistry, + type PipeSegmentNode, + resolveConnectivityUpdates, +} from '@pascal-app/core' +import type { AgentOperation } from '@pascal-app/core/agent-operations' +import { refuse } from '@pascal-app/core/agent-tools' +import { planRunEndCapFollowUpdates } from '../shared/automatic-run-end-cap' +import { applyPipeGrade, pipeGradesMatch, preservePipeGrades } from './slope' + +type Point = [number, number, number] +export type PipeGradeInput = { + nodeId: string + action: 'grade' | 'endpoint' | 'elevation' + gradePercent?: number + flow?: 'forward' | 'reverse' + anchor?: 'start' | 'end' + pointIndex?: number + point?: Point + elevation?: number + detach?: boolean +} + +/** Refuse a connected edit that would silently regrade another run. */ +export function pipeUpdatesPreserveGrades( + nodes: Readonly>, + updates: { id: string; data: Partial }[], + exceptId?: string, +): boolean { + return updates.every((update) => { + const node = nodes[update.id] + return ( + update.id === exceptId || + node?.type !== 'pipe-segment' || + !('path' in update.data) || + !update.data.path || + pipeGradesMatch(node.path, update.data.path as Point[]) + ) + }) +} + +export const editPipeGrade: AgentOperation = (nodes, input) => { + const pipe = nodes[input.nodeId] + if (pipe?.type !== 'pipe-segment') return refuse('pipe_not_found', 'Select a pipe run.') + if (!nodeRegistry.get('pipe-segment')?.ports) + return refuse('node_capability_unavailable', 'Register pipe node definitions before editing.') + let path: Point[] = pipe.path.map((p) => [...p]) + if (input.action === 'grade') { + const grade = input.gradePercent + if (grade === undefined || !Number.isFinite(grade) || grade < 0) + return refuse('pipe_grade_invalid', 'Enter a finite, non-negative grade percentage.') + const signed = (grade / 100) * (input.flow === 'reverse' ? -1 : 1) + for (let i = 1; i < path.length; i++) { + const previous = pipe.path[i - 1]! + const current = pipe.path[i]! + // Vertical legs keep their height; grades describe horizontal travel only. + path[i] = + Math.hypot(current[0] - previous[0], current[2] - previous[2]) < 1e-6 + ? [current[0], path[i - 1]![1] + current[1] - previous[1], current[2]] + : applyPipeGrade(path[i - 1]!, current, signed) + } + if (input.anchor === 'end') { + const dy = pipe.path.at(-1)![1] - path.at(-1)![1] + path = path.map((p) => [p[0], p[1] + dy, p[2]]) + } + } else if (input.action === 'elevation') { + if (input.elevation === undefined || !Number.isFinite(input.elevation)) + return refuse('pipe_elevation_invalid', 'Enter a finite elevation above the level.') + const index = input.anchor === 'end' ? path.length - 1 : 0 + const dy = input.elevation - path[index]![1] + path = path.map((p) => [p[0], p[1] + dy, p[2]]) + } else { + const index = input.pointIndex + if ( + index === undefined || + !Number.isInteger(index) || + !path[index] || + !input.point || + input.point.some((v) => !Number.isFinite(v)) + ) + return refuse('pipe_endpoint_invalid', 'Choose a valid path point and finite coordinates.') + path[index] = input.point + const constrained = preservePipeGrades(pipe.path, path, index) + if (!constrained) + return refuse( + 'pipe_grade_conflict', + 'This edit collapses a run or tilts a vertical stack. Move the whole stack instead.', + ) + path = constrained + } + const detached = input.action === 'endpoint' && input.detach === true + const next: PipeSegmentNode = { ...pipe, path, wallAttachment: undefined } + const connectivity = analyzePortConnectivity(pipe, { ...nodes }) + for (const endpoint of ['start', 'end'] as const) { + if (detached) continue + const mates = connectivity.adjacency[pipe.id]?.[endpoint] ?? [] + if ( + !mates.some((mate) => { + const owner = nodes[mate.nodeId] + return owner?.type !== 'pipe-fitting' || owner.fittingType !== 'end-cap' + }) + ) + continue + const index = endpoint === 'start' ? 0 : path.length - 1 + const neighbor = endpoint === 'start' ? 1 : path.length - 2 + const oldDirection = pipe.path[index]!.map((v, i) => v - pipe.path[neighbor]![i]!) + const newDirection = path[index]!.map((v, i) => v - path[neighbor]![i]!) + const oldLength = Math.hypot(...oldDirection), + newLength = Math.hypot(...newDirection) + const dot = + oldDirection.reduce((sum, v, i) => sum + v * newDirection[i]!, 0) / (oldLength * newLength) + if (!Number.isFinite(dot) || dot < 0.999999) + return refuse( + 'pipe_connection_angle', + 'This would turn a connected collar. Adjust the fitting or detach the run before changing its direction or grade.', + ) + } + const follow = !detached && connectivity ? resolveConnectivityUpdates(connectivity, next) : [] + const caps = detached + ? [] + : (['start', 'end'] as const).flatMap((end) => + planRunEndCapFollowUpdates(pipe, next, end, { ...nodes }), + ) + const capIds = new Set(caps.map((cap) => cap.id)) + const update = [ + { id: pipe.id as AnyNodeId, data: { path, wallAttachment: undefined } as Partial }, + ...follow.filter((entry) => !capIds.has(entry.id)), + ...caps, + ] + if (!pipeUpdatesPreserveGrades(nodes, update, pipe.id)) + return refuse( + 'pipe_connected_grade', + 'This would change a connected pipe’s grade. Adjust the connected route explicitly first.', + ) + if ( + update.some((entry) => { + const owner = nodes[entry.id] + return ( + owner && + owner.id !== pipe.id && + owner.type !== 'pipe-segment' && + owner.type !== 'pipe-fitting' + ) + }) + ) + return refuse( + 'pipe_fixed_connection', + 'This edit would move a fixture or equipment connection. Keep that endpoint fixed.', + ) + return { + result: { + message: 'Pipe elevations updated; grades preserved on connected runs.', + startElevation: path[0]![1], + endElevation: path.at(-1)![1], + }, + changes: { update }, + } +} diff --git a/packages/nodes/src/pipe-segment/move-tool.tsx b/packages/nodes/src/pipe-segment/move-tool.tsx index 2ede3a9dae..23fefcb59f 100644 --- a/packages/nodes/src/pipe-segment/move-tool.tsx +++ b/packages/nodes/src/pipe-segment/move-tool.tsx @@ -33,6 +33,7 @@ import { } from '../shared/ghost-alignment' import { type RunMoveConnectivity, startRunMoveConnectivity } from '../shared/run-move-connectivity' import { translateWallRun } from '../shared/wall-run-move' +import { pipeUpdatesPreserveGrades } from './grade-operation' type Vec3 = [number, number, number] @@ -217,8 +218,10 @@ export const MovePipeSegmentTool: React.FC<{ node: AnyNode }> = ({ node }) => { event.nativeEvent?.stopPropagation?.() return } - committed = true const finalPath = previewPathRef.current + const gradeUpdates = connectivity?.commitUpdates({ path: finalPath }) ?? [] + if (!pipeUpdatesPreserveGrades(useScene.getState().nodes, gradeUpdates)) return + committed = true useScene.temporal.getState().resume() let selectId = nodeId diff --git a/packages/nodes/src/pipe-segment/offset-inspector.tsx b/packages/nodes/src/pipe-segment/offset-inspector.tsx new file mode 100644 index 0000000000..e854d31b75 --- /dev/null +++ b/packages/nodes/src/pipe-segment/offset-inspector.tsx @@ -0,0 +1,149 @@ +'use client' +import { type AnyNodeId, type PipeSegmentNode, useScene } from '@pascal-app/core' +import { useMemo, useState } from 'react' +import { offsetPipe, type PipeOffsetInput } from './offset-operation' + +type Point = [number, number, number] +export default function PipeOffsetInspector({ node }: { node: PipeSegmentNode }) { + const [open, setOpen] = useState(false) + return ( + + setOpen(!open)} + > + Offset around obstacle + + {open && } + + ) +} +function OffsetForm({ node }: { node: PipeSegmentNode }) { + const nodes = useScene((state) => state.nodes) + const start = node.path[0]!, + end = node.path.at(-1)! + const length = Math.hypot(end[0] - start[0], end[2] - start[2]) + const [input, setInput] = useState({ + nodeId: node.id, + from: Number((length / 4).toFixed(3)), + to: Number(((length * 3) / 4).toFixed(3)), + offset: Number(Math.min(0.5, length / 8).toFixed(3)), + }) + const [notice, setNotice] = useState('') + const [appliedPath, setAppliedPath] = useState(null) + const preview = useMemo(() => { + try { + return { outcome: offsetPipe(nodes, input, { activeLevelId: node.parentId }), error: '' } + } catch (error) { + return { + outcome: null, + error: error instanceof Error ? error.message : 'Unable to plan offset.', + } + } + }, [nodes, input, node.parentId]) + const paths = (preview.outcome?.result.paths ?? []) as Point[][] + const all = [start, end, ...paths.flat()] + const minY = Math.min(...all.map((p) => p[1])), + maxY = Math.max(...all.map((p) => p[1])) + const project = (p: Point) => { + const distance = + ((p[0] - start[0]) * (end[0] - start[0]) + (p[2] - start[2]) * (end[2] - start[2])) / + (length || 1) + return `${16 + (228 * distance) / (length || 1)},${100 - (80 * (p[1] - minY)) / (maxY - minY || 1)}` + } + const apply = () => { + try { + const outcome = offsetPipe(useScene.getState().nodes, input, { activeLevelId: node.parentId }) + useScene.getState().applyNodeChanges({ + create: outcome.changes?.create?.map((entry) => ({ + ...entry, + parentId: entry.parentId as AnyNodeId, + })), + update: outcome.changes?.update?.map((entry) => ({ ...entry, id: entry.id as AnyNodeId })), + }) + setNotice('Offset applied in one undo step. End connections stayed fixed.') + const appliedNode = useScene.getState().nodes[node.id] + setAppliedPath(appliedNode?.type === 'pipe-segment' ? JSON.stringify(appliedNode.path) : null) + } catch (error) { + setNotice(error instanceof Error ? error.message : 'Unable to apply offset.') + } + } + if (appliedPath === JSON.stringify(node.path)) return {notice} + return ( + + + Choose the first and last bend by horizontal distance from the start. Positive offset goes + up; negative goes down. Each connector uses the offset height in horizontal travel. + + {(['from', 'to', 'offset'] as const).map((key) => ( + + {{ from: 'First bend (m)', to: 'Last bend (m)', offset: 'Vertical offset (m)' }[key]} + { + setInput({ ...input, [key]: event.target.valueAsNumber }) + setNotice('') + }} + /> + + ))} + {paths.length > 0 && ( + <> + + + + {[start, end].map((point, index) => { + const [cx, cy] = project(point).split(',') + return + })} + + + Side profile (schematic). Four bends · five pipe sections. Parallel sections keep the + original grade; both end connections stay fixed. + + {preview.outcome?.result.uphill === true && ( + + This offset includes an uphill waste section. It does not provide continuous downhill + drainage. + + )} + > + )} + + Check obstacle clearance. The preview does not detect collisions. + + {preview.error && {preview.error}} + + Apply pipe offset + + {notice && {notice}} + + ) +} diff --git a/packages/nodes/src/pipe-segment/offset-operation.ts b/packages/nodes/src/pipe-segment/offset-operation.ts new file mode 100644 index 0000000000..2366eca507 --- /dev/null +++ b/packages/nodes/src/pipe-segment/offset-operation.ts @@ -0,0 +1,132 @@ +import { type AnyNode, type AnyNodeId, nodeRegistry, PipeSegmentNode } from '@pascal-app/core' +import type { AgentOperation, SceneChanges } from '@pascal-app/core/agent-operations' +import { refuse } from '@pascal-app/core/agent-tools' +import { Vector3 } from 'three' +import { planPipeElbowAtPort } from '../shared/auto-fitting' +import { autoOffsetInvalidationUpdates } from '../shared/auto-offset-tag' +import { transferRunEndCapOwnership } from '../shared/automatic-run-end-cap' +import { pipeGrade, pipeGradesMatch } from './slope' + +export type PipeOffsetInput = { nodeId: string; from: number; to: number; offset: number } +type Point = [number, number, number] + +export const offsetPipe: AgentOperation = (nodes, input) => { + const pipe = nodes[input.nodeId] + if (pipe?.type !== 'pipe-segment') return refuse('pipe_not_found', 'Select a pipe run.') + if (!nodeRegistry.get('pipe-segment')?.ports || !nodeRegistry.get('pipe-fitting')?.ports) + return refuse( + 'node_capability_unavailable', + 'Register pipe and fitting definitions before editing.', + ) + if (pipe.path.length !== 2 || ![input.from, input.to, input.offset].every(Number.isFinite)) + return refuse('pipe_offset_route', 'Choose a straight run and enter finite offset dimensions.') + if ( + Object.values(nodes).some((node) => node.parentId === pipe.id) || + Object.keys(pipe.hangerOverrides ?? {}).length + ) + return refuse( + 'pipe_offset_attachments', + 'Remove custom hanger adjustments or hosted children before splitting this run.', + ) + const start = new Vector3(...pipe.path[0]!), + end = new Vector3(...pipe.path[1]!) + const delta = end.clone().sub(start) + const length = Math.hypot(delta.x, delta.z) + if (length < 0.001 || Math.abs(input.offset) < 0.001) + return refuse('pipe_offset_route', 'Choose a non-vertical run and a non-zero vertical offset.') + const axis = delta.clone().divideScalar(length) + const at = (distance: number) => start.clone().addScaledVector(axis, distance) + const travel = Math.abs(input.offset) + const a = at(input.from), + b = at(input.from + travel).add(new Vector3(0, input.offset, 0)) + const d = at(input.to), + c = at(input.to - travel).add(new Vector3(0, input.offset, 0)) + const corners = [start, a, b, c, d, end] + if (input.from <= 0 || input.to >= length || input.to - input.from <= 2 * travel) + return refuse( + 'pipe_offset_space', + 'Place the bends inside the run and allow more than twice the offset height between the first and last bend.', + ) + const directions = corners.slice(1).map((point, i) => point.clone().sub(corners[i]!).normalize()) + const elbows = [a, b, c, d].map((corner, i) => { + const plan = planPipeElbowAtPort( + { + id: 'end', + nodeId: pipe.id, + position: corner.toArray(), + direction: directions[i]!.toArray(), + diameter: pipe.diameter, + system: pipe.system, + }, + directions[i + 1]!.toArray(), + pipe.diameter, + pipe.pipeMaterial, + ) + if (!plan) + return refuse('pipe_offset_angle', 'The requested bends cannot be formed on this route.') + return plan + }) + const paths: Point[][] = [ + [start.toArray(), elbows[0]!.trimmedPortPoint], + [elbows[0]!.collarPoint, elbows[1]!.trimmedPortPoint], + [elbows[1]!.collarPoint, elbows[2]!.trimmedPortPoint], + [elbows[2]!.collarPoint, elbows[3]!.trimmedPortPoint], + [elbows[3]!.collarPoint, end.toArray()], + ] + for (const [i, path] of paths.entries()) { + const segment = new Vector3(...path[1]!).sub(new Vector3(...path[0]!)) + if ( + !segment.toArray().every(Number.isFinite) || + segment.length() < 0.001 || + segment.normalize().dot(directions[i]!) < 0.999999 + ) + return refuse( + 'pipe_offset_space', + 'Not enough straight pipe between the bends. Increase the offset height or spacing, or move the bends away from the endpoints.', + ) + } + if ([0, 2, 4].some((i) => !pipeGradesMatch(pipe.path, paths[i]!))) + return refuse('pipe_offset_grade', 'This offset cannot preserve the existing grade.') + const { id: _id, ...defaults } = pipe + const newRuns = paths.slice(1).map((path) => + PipeSegmentNode.parse({ + ...defaults, + metadata: {}, + path, + wallAttachment: undefined, + hangerOverrides: undefined, + }), + ) + const changes: SceneChanges = { + update: [ + { + id: pipe.id, + data: { path: paths[0], wallAttachment: undefined, hangerOverrides: undefined }, + }, + ], + create: [ + ...newRuns, + ...elbows.map((elbow) => ({ ...elbow.fitting, parentId: pipe.parentId })), + ].map((node) => ({ node, parentId: pipe.parentId ?? undefined })), + } + changes.update!.push(...transferRunEndCapOwnership(nodes, pipe.id, newRuns.at(-1)!.id, 'end')) + for (const entry of autoOffsetInvalidationUpdates({ ...nodes }, pipe.id as AnyNodeId)) { + const existing = changes.update!.find((update) => update.id === entry.id) + if (existing) existing.data = { ...existing.data, ...entry.data } as Partial + else changes.update!.push(entry) + } + const grade = pipeGrade(pipe.path[0]!, pipe.path[1]!)! + const uphill = + grade === 0 || paths.some((path) => (path[1]![1] - path[0]![1]) * Math.sign(grade) > 1e-6) + return { + changes, + result: { + message: 'Four-bend offset; boundary connections and parallel-run grades preserved.', + paths, + uphill: pipe.system === 'waste' && uphill, + offset: input.offset, + fittings: 4, + runs: 5, + }, + } +} diff --git a/packages/nodes/src/pipe-segment/parametrics.ts b/packages/nodes/src/pipe-segment/parametrics.ts index 33e165a830..f11d161239 100644 --- a/packages/nodes/src/pipe-segment/parametrics.ts +++ b/packages/nodes/src/pipe-segment/parametrics.ts @@ -22,7 +22,7 @@ export const pipeSegmentParametrics: ParametricDescriptor = { plan.deleteFitting ? [plan.fittingId, ...plan.cascadeDeleteIds] : [], ), ], - trailingSection: () => import('../shared/run-hanger-inspector'), + trailingSection: () => import('./grade-inspector'), groups: [ { label: 'Hangers', @@ -67,14 +67,6 @@ export const pipeSegmentParametrics: ParametricDescriptor = { options: ['waste', 'vent'], display: 'segmented', }, - { - key: 'diameter', - kind: 'number', - unit: 'in', - min: 1.25, - max: 6, - step: 0.25, - }, ], }, { diff --git a/packages/nodes/src/pipe-segment/resize-inspector.tsx b/packages/nodes/src/pipe-segment/resize-inspector.tsx new file mode 100644 index 0000000000..034eb55645 --- /dev/null +++ b/packages/nodes/src/pipe-segment/resize-inspector.tsx @@ -0,0 +1,84 @@ +'use client' +import { type AnyNodeId, type PipeSegmentNode, useScene } from '@pascal-app/core' +import { useState } from 'react' +import { resizePipe } from './resize-operation' + +export default function PipeResizeInspector({ node }: { node: PipeSegmentNode }) { + const [diameter, setDiameter] = useState(node.diameter) + const [scope, setScope] = useState<'segment' | 'branch'>('segment') + const [message, setMessage] = useState('') + const apply = (preview: boolean) => { + try { + const outcome = resizePipe( + useScene.getState().nodes, + { nodeId: node.id, diameter, scope }, + { activeLevelId: node.parentId }, + ) + if (preview || !outcome.changes) { + setMessage( + outcome.changes + ? `${outcome.result.runs} runs, ${outcome.result.fittings} fittings, ${outcome.result.reducers} new reducers. Grades stay unchanged.` + : String(outcome.result.message), + ) + return + } + useScene.getState().applyNodeChanges({ + create: outcome.changes.create?.map((entry) => ({ + ...entry, + parentId: entry.parentId as AnyNodeId, + })), + update: outcome.changes.update?.map((entry) => ({ ...entry, id: entry.id as AnyNodeId })), + }) + setMessage('Resized in one undo step. Grades and boundary connections preserved.') + } catch (error) { + setMessage(error instanceof Error ? error.message : 'Unable to resize pipe.') + } + } + return ( + + Pipe size + Current diameter: {node.diameter} in + + Diameter (in) + { + setDiameter(event.target.valueAsNumber) + setMessage('') + }} + className="w-24 border bg-background p-1" + /> + + { + setScope(event.target.value as typeof scope) + setMessage('') + }} + className="w-full border bg-background p-1" + > + This segment + Connected branch + + + Branches stop at junctions, size or material changes, and fixture connections. Reducers keep + boundary collars fixed. + + + apply(true)}> + Check resize + + apply(false)}> + Apply pipe size + + + {message && {message}} + + ) +} diff --git a/packages/nodes/src/pipe-segment/resize-operation.ts b/packages/nodes/src/pipe-segment/resize-operation.ts new file mode 100644 index 0000000000..aaea86f09a --- /dev/null +++ b/packages/nodes/src/pipe-segment/resize-operation.ts @@ -0,0 +1,170 @@ +import { type AnyNode, nodeRegistry, PipeFittingNode, PipeSegmentNode } from '@pascal-app/core' +import type { AgentOperation, SceneChanges } from '@pascal-app/core/agent-operations' +import { refuse } from '@pascal-app/core/agent-tools' +import type { ScenePort } from '@pascal-app/editor/distribution' +import { Euler, Quaternion, Vector3 } from 'three' +import { pipeFittingLegLength } from '../pipe-fitting/ports' +import { pipeGradesMatch } from './slope' + +type Point = [number, number, number] +export type PipeResizeInput = { nodeId: string; diameter: number; scope?: 'segment' | 'branch' } +const portsOf = (node: AnyNode): ScenePort[] => + nodeRegistry + .get(node.type) + ?.ports?.(node) + .map((port) => ({ ...port, nodeId: node.id })) ?? [] +const vector = (point: readonly [number, number, number]) => new Vector3(...point) + +export const resizePipe: AgentOperation = (nodes, input) => { + const root = nodes[input.nodeId] + if (root?.type !== 'pipe-segment') return refuse('pipe_not_found', 'Select a pipe run.') + if (!nodeRegistry.get('pipe-segment')?.ports || !nodeRegistry.get('pipe-fitting')?.ports) + return refuse( + 'node_capability_unavailable', + 'Register pipe and fitting definitions before resizing.', + ) + if (!PipeSegmentNode.safeParse({ ...root, diameter: input.diameter }).success) + return refuse('pipe_size_invalid', 'Enter a pipe diameter between 1.25 and 8 inches.') + const ports = Object.values(nodes) + .filter((node) => node.parentId === root.parentId) + .flatMap(portsOf) + const mates = (port: ScenePort) => + ports.filter( + (other) => + other.nodeId !== port.nodeId && + other.system === port.system && + vector(other.position).distanceTo(vector(port.position)) < 0.005, + ) + const mateOf = (port: ScenePort) => { + const found = mates(port) + if (found.length > 1) + return refuse('pipe_ambiguous_connection', 'Resolve overlapping connections before resizing.') + const mate = found[0] + if (mate && vector(mate.direction).dot(vector(port.direction)) > -0.999999) + return refuse('pipe_connection_angle', 'Align the connected collars before resizing.') + return mate + } + const selected = new Set([root.id]) + const queue: AnyNode[] = [root] + for (const node of queue) { + for (const port of portsOf(node)) { + const mate = mateOf(port) + if (!mate || selected.has(mate.nodeId)) continue + const owner = nodes[mate.nodeId]! + const cap = owner.type === 'pipe-fitting' && owner.fittingType === 'end-cap' + const sameSize = 'diameter' in owner && owner.diameter === root.diameter + const sameMaterial = 'pipeMaterial' in owner && owner.pipeMaterial === root.pipeMaterial + const throughFitting = + owner.type === 'pipe-fitting' && + ['elbow', 'coupling', 'cleanout'].includes(owner.fittingType) && + portsOf(owner).every((collar) => + mates(collar).every((neighbor) => { + const run = nodes[neighbor.nodeId] + return ( + run?.type === 'pipe-segment' && + run.diameter === root.diameter && + run.pipeMaterial === root.pipeMaterial + ) + }), + ) + if ( + sameSize && + (cap || + (input.scope === 'branch' && + sameMaterial && + (owner.type === 'pipe-segment' || throughFitting))) + ) { + selected.add(owner.id) + queue.push(owner) + } + } + } + if (input.diameter === root.diameter) + return { result: { message: 'The branch already has this diameter.' } } + const changed = new Map() + for (const node of queue) { + if (node.type === 'pipe-segment') + changed.set(node.id, { + ...node, + diameter: input.diameter, + path: node.path.map((p) => [...p]), + wallAttachment: undefined, + }) + else if (node.type === 'pipe-fitting') { + const next = PipeFittingNode.parse({ + ...node, + diameter: input.diameter, + diameter2: input.diameter, + }) + if (portsOf(node).length === 1) { + // Keep a cap's inlet fixed while its body grows away from the run. + const delta = vector(portsOf(node)[0]!.position).sub(vector(portsOf(next)[0]!.position)) + next.position = vector(next.position).add(delta).toArray() + } + changed.set(node.id, next) + } + } + const create: NonNullable = [] + for (const node of queue) { + if (node.type !== 'pipe-segment') continue + const next = changed.get(node.id) as PipeSegmentNode + for (const port of portsOf(node)) { + const mate = mateOf(port) + if (!mate) continue + const index = port.id === 'start' ? 0 : next.path.length - 1 + if (selected.has(mate.nodeId)) { + const updatedMate = portsOf(changed.get(mate.nodeId)!).find((p) => p.id === mate.id)! + // Adjacent runs keep their shared point; only fitting collars move. + if ( + nodes[mate.nodeId]?.type === 'pipe-fitting' && + portsOf(changed.get(mate.nodeId)!).length > 1 + ) + next.path[index] = [...updatedMate.position] + continue + } + if (mate.diameter === input.diameter) continue + const axis = vector(mate.direction).normalize() + const leg = pipeFittingLegLength(Math.max(mate.diameter, input.diameter)) + const rotation = new Euler().setFromQuaternion( + new Quaternion().setFromUnitVectors(new Vector3(1, 0, 0), axis), + ) + const fitting = PipeFittingNode.parse({ + parentId: root.parentId, + fittingType: 'reducer', + system: root.system, + pipeMaterial: root.pipeMaterial, + diameter: mate.diameter, + diameter2: input.diameter, + position: vector(mate.position).addScaledVector(axis, leg).toArray(), + rotation: [rotation.x, rotation.y, rotation.z], + }) + create.push({ node: fitting, parentId: root.parentId! }) + next.path[index] = [...portsOf(fitting).find((p) => p.id === 'outlet')!.position] + } + for (let i = 1; i < next.path.length; i++) { + const before = vector(node.path[i]!) + .sub(vector(node.path[i - 1]!)) + .normalize() + const after = vector(next.path[i]!).sub(vector(next.path[i - 1]!)) + if (after.length() < 0.001 || before.dot(after.clone().normalize()) < 0.999999) + return refuse( + 'pipe_resize_space', + 'Not enough straight pipe for the new fittings. Extend the route first.', + ) + } + if (!pipeGradesMatch(node.path, next.path as Point[])) + return refuse( + 'pipe_resize_grade', + 'This resize would change the pipe grade. Adjust the fitting layout first.', + ) + } + return { + result: { + message: 'Pipe sizes updated; grades and boundary connections preserved.', + runs: queue.filter((n) => n.type === 'pipe-segment').length, + fittings: queue.filter((n) => n.type === 'pipe-fitting').length, + reducers: create.length, + }, + changes: { create, update: [...changed].map(([id, node]) => ({ id, data: node })) }, + } +} diff --git a/packages/nodes/src/pipe-segment/selection.tsx b/packages/nodes/src/pipe-segment/selection.tsx index abb7646e59..9e8cd0f4bb 100644 --- a/packages/nodes/src/pipe-segment/selection.tsx +++ b/packages/nodes/src/pipe-segment/selection.tsx @@ -46,6 +46,8 @@ import { type PipeEndpoint, pipeContinuationHandlePlan, } from './continuation' +import { pipeUpdatesPreserveGrades } from './grade-operation' +import { pipeGradesMatch, preservePipeGrades } from './slope' /** Port-snap radius for dragged run endpoints (meters, XZ). */ const PORT_SNAP_RADIUS_M = 0.4 @@ -153,6 +155,7 @@ const PipePointHandles = ({ pipe, target }: { pipe: PipeSegmentNode; target: Obj }) const unit = useViewer((s) => s.unit) const [draggingIndex, setDraggingIndex] = useState(null) + const [gradeNotice, setGradeNotice] = useState('') const [runMoving, setRunMoving] = useState(false) const [verticalGhost, setVerticalGhost] = useState<{ tint: 'valid' | 'invalid' @@ -280,6 +283,15 @@ const PipePointHandles = ({ pipe, target }: { pipe: PipeSegmentNode; target: Obj next: Point, detached: boolean, ): { id: AnyNodeId; data: Partial }[] | null => { + const constrained = preservePipeGrades( + drag.initialPath, + drag.initialPath.map((point, index) => (index === drag.index ? next : point)), + drag.index, + ) + if (!constrained) return null + next = constrained[drag.index]! + const checked = (updates: { id: AnyNodeId; data: Partial }[]) => + pipeUpdatesPreserveGrades(useScene.getState().nodes, updates) ? updates : null const wall = pipe.wallAttachment ? useScene.getState().nodes[pipe.wallAttachment.wallId] : undefined @@ -291,14 +303,9 @@ const PipePointHandles = ({ pipe, target }: { pipe: PipeSegmentNode; target: Obj path: Point[], updates: { id: AnyNodeId; data: Partial }[], ) => { - if (drag.index !== 0 && drag.index !== drag.initialPath.length - 1) return updates - const endpoint = drag.index === 0 ? 'start' : 'end' const nextPipe = { ...pipe, path } as PipeSegmentNode - const capUpdates = planRunEndCapFollowUpdates( - pipe, - nextPipe, - endpoint, - useScene.getState().nodes, + const capUpdates = (['start', 'end'] as const).flatMap((endpoint) => + planRunEndCapFollowUpdates(pipe, nextPipe, endpoint, useScene.getState().nodes), ) const capIds = new Set(capUpdates.map((update) => update.id)) return [...updates.filter((update) => !capIds.has(update.id)), ...capUpdates] @@ -306,37 +313,39 @@ const PipePointHandles = ({ pipe, target }: { pipe: PipeSegmentNode; target: Obj if (!detached && drag.fittingEndpoint) { const plan = planFittingEndpointReaim(drag.fittingEndpoint, drag.index, next) // Out of the elbow's buildable turn range — hold this frame. - if (!plan) return null - return withEndCapFollow(plan.path, [ - { - id: pipe.id as AnyNodeId, - data: { path: plan.path, wallAttachment: attachmentFor(plan.path) }, - }, - { id: plan.fittingUpdate.id, data: plan.fittingUpdate.data }, - ...(drag.jointPartner - ? [ - { - id: drag.jointPartner!.id, - data: { - path: drag.jointPartner!.startPath.map((p, i) => - i === (drag.index === 0 ? drag.jointPartner!.startPath.length - 1 : 0) - ? drag.index === 0 - ? plan.path[plan.path.length - 1]! - : plan.path[0]! - : p, - ), - } as Partial, - }, - ] - : []), - ]) + if (!plan || !pipeGradesMatch(drag.initialPath, plan.path)) return null + return checked( + withEndCapFollow(plan.path, [ + { + id: pipe.id as AnyNodeId, + data: { path: plan.path, wallAttachment: attachmentFor(plan.path) }, + }, + { id: plan.fittingUpdate.id, data: plan.fittingUpdate.data }, + ...(drag.jointPartner + ? [ + { + id: drag.jointPartner!.id, + data: { + path: drag.jointPartner!.startPath.map((p, i) => + i === (drag.index === 0 ? drag.jointPartner!.startPath.length - 1 : 0) + ? drag.index === 0 + ? plan.path[plan.path.length - 1]! + : plan.path[0]! + : p, + ), + } as Partial, + }, + ] + : []), + ]), + ) } - const path = drag.initialPath.map((p, i) => (i === drag.index ? next : p)) as Point[] + const path = constrained const updates = [ { id: pipe.id as AnyNodeId, data: { path, wallAttachment: attachmentFor(path) } }, ...(detached ? [] : connectivityUpdatesForPath(drag.connectivity, path)), ] - return detached ? updates : withEndCapFollow(path, updates) + return checked(detached ? updates : withEndCapFollow(path, updates)) } /** World-space position of a local path point. */ @@ -465,7 +474,13 @@ const PipePointHandles = ({ pipe, target }: { pipe: PipeSegmentNode; target: Obj if (next[0] === drag.current[0] && next[1] === drag.current[1] && next[2] === drag.current[2]) return const batch = buildDragBatch(drag, next, detached) - if (!batch) return + if (!batch) { + setGradeNotice( + 'This edit cannot preserve the pipe grade and connected collars. Adjust the fitting or use Grade and flow.', + ) + return + } + setGradeNotice('') drag.current = next drag.detached = detached if (step > 0) triggerSFX('sfx:grid-snap') @@ -556,6 +571,7 @@ const PipePointHandles = ({ pipe, target }: { pipe: PipeSegmentNode; target: Obj } const livePreviewIds = new Set() const publishLivePreview = (updates: { id: AnyNodeId; data: Partial }[]) => { + if (!pipeUpdatesPreserveGrades(nodesById, updates)) return const scene = useScene.getState() const entries = updates .filter((update) => scene.nodes[update.id]) @@ -724,6 +740,7 @@ const PipePointHandles = ({ pipe, target }: { pipe: PipeSegmentNode; target: Obj ...plan.updates.filter((u) => scene.nodes[u.id]), ...followUpdates, ] + if (!pipeUpdatesPreserveGrades(nodesById, updates)) return scene.applyNodeChanges({ create: minted.map((node) => ({ node: node as AnyNode, parentId })), delete: (plan.delete ?? []).filter((id) => scene.nodes[id]), @@ -756,6 +773,7 @@ const PipePointHandles = ({ pipe, target }: { pipe: PipeSegmentNode; target: Obj }, ...translationPlan.updates, ] + if (!pipeUpdatesPreserveGrades(nodesById, updates)) return scene.applyNodeChanges({ create: created.map((node) => ({ node: node as AnyNode, @@ -770,6 +788,7 @@ const PipePointHandles = ({ pipe, target }: { pipe: PipeSegmentNode; target: Obj return } const updates = batchFor(finalPath) + if (!pipeUpdatesPreserveGrades(nodesById, updates)) return useScene.getState().updateNodes(updates) ensureSceneObjectsVisible(updates.map((update) => update.id)) } @@ -844,6 +863,16 @@ const PipePointHandles = ({ pipe, target }: { pipe: PipeSegmentNode; target: Obj return ( + {gradeNotice && runCenter && ( + + + {gradeNotice} + + + )} {verticalGhost?.fittings.map((f) => ( ))} diff --git a/packages/nodes/src/pipe-segment/slope.ts b/packages/nodes/src/pipe-segment/slope.ts index 7a97cfe058..1584d48b65 100644 --- a/packages/nodes/src/pipe-segment/slope.ts +++ b/packages/nodes/src/pipe-segment/slope.ts @@ -10,3 +10,60 @@ export function applyPipeGrade(start: Point, end: Point, grade: number): [number if (horizontal < 1e-6 || !Number.isFinite(grade)) return [...end] return [end[0], start[1] - horizontal * grade, end[2]] } + +/** Preserve each leg's grade, including vertical rises, while anchoring one endpoint. */ +export function preservePipeGrades( + initial: readonly Point[], + proposed: readonly Point[], + movedIndex: number, +): [number, number, number][] | null { + if (initial.length !== proposed.length || initial.length < 2) return null + const path = proposed.map((p) => [...p] as [number, number, number]) + const original = initial[movedIndex] + const moved = path[movedIndex] + if (!original || !moved || path.some((p) => p.some((v) => !Number.isFinite(v)))) return null + if (Math.hypot(moved[0] - original[0], moved[2] - original[2]) < 1e-8) { + const dy = moved[1] - original[1] + return initial.map((p) => [p[0], p[1] + dy, p[2]]) + } + const drops: number[] = [] + for (let i = 1; i < path.length; i++) { + const grade = pipeGrade(initial[i - 1]!, initial[i]!) + const length = Math.hypot(path[i]![0] - path[i - 1]![0], path[i]![2] - path[i - 1]![2]) + if (grade === null && length > 1e-6) return null + if (grade !== null && length < 0.001) return null + drops.push(grade === null ? initial[i - 1]![1] - initial[i]![1] : grade * length) + } + if (movedIndex === 0) { + path.at(-1)![1] = initial.at(-1)![1] + for (let i = path.length - 2; i >= 0; i--) path[i]![1] = path[i + 1]![1] + drops[i]! + } else { + path[0]![1] = initial[0]![1] + for (let i = 1; i < path.length; i++) path[i]![1] = path[i - 1]![1] - drops[i - 1]! + } + return path +} + +export function pipeGradesMatch(initial: readonly Point[], next: readonly Point[]): boolean { + if ( + initial.length !== next.length || + next.some((point) => point.some((value) => !Number.isFinite(value))) + ) + return false + for (let i = 1; i < initial.length; i++) { + const before = pipeGrade(initial[i - 1]!, initial[i]!) + const after = pipeGrade(next[i - 1]!, next[i]!) + if (before === null ? after !== null : after === null || Math.abs(before - after) > 1e-6) + return false + } + return true +} + +export function pipeGradeLabel(start: Point, end: Point): string { + if (Math.hypot(...start.map((v, i) => v - end[i]!)) < 1e-6) return 'Choose an endpoint' + const grade = pipeGrade(start, end) + if (grade === null) + return `Vertical · ${start[1] > end[1] ? 'start → end' : 'end → start'} (down)` + if (Math.abs(grade) < 1e-6) return 'Level · no gravity fall' + return `${(Math.abs(grade) * 100).toFixed(2)}% · 1:${(1 / Math.abs(grade)).toFixed(1)} · ${grade > 0 ? 'start → end' : 'end → start'} (down)` +} diff --git a/packages/nodes/src/pipe-segment/tool.tsx b/packages/nodes/src/pipe-segment/tool.tsx index 8063dd9f02..149a4b3454 100644 --- a/packages/nodes/src/pipe-segment/tool.tsx +++ b/packages/nodes/src/pipe-segment/tool.tsx @@ -23,7 +23,7 @@ import { stepNominalRunSize, useDistributionRunTool, } from '@pascal-app/editor/distribution' -import { useEffect, useRef, useState } from 'react' +import { useEffect, useRef } from 'react' import { Vector3 } from 'three' import { planPipeBranchTap, @@ -42,9 +42,11 @@ import { PipeFittingGhost } from '../shared/mep-ghost' import { DWV_PORT_SYSTEMS, runSectionHalfSizeM } from '../shared/port-systems' import { RunHangerPreview } from '../shared/run-hanger-controls' import { useRunHangerMode } from '../shared/run-hanger-mode' +import { clearRunContinuation, updateRunDefaults } from '../shared/run-tool-options' +import { planPipeCollarConnection } from './collar-connection' import { currentPipeContinuationSeed, pipeEndpointPort } from './continuation' import { pipeSegmentDefinition } from './definition' -import { applyPipeGrade } from './slope' +import { applyPipeGrade, pipeGrade, pipeGradeLabel } from './slope' const PIPE_DIAMETERS_IN = [1.25, 1.5, 2, 3, 4, 6] as const const BODY_SNAP_RADIUS_M = 0.3 @@ -87,20 +89,29 @@ const PipeSegmentTool = () => { pipeMaterial: PipeSegmentNode['pipeMaterial'] system: PipeSegmentNode['system'] } - const [system, setSystem] = useState<'waste' | 'vent'>( - continuationSeed?.pipe.system ?? toolDefaults?.system ?? defaults.system, - ) - const [sloped, setSloped] = useState(false) - const slopePercent = 100 / 48 - const slopeDirection = 1 + const system = toolDefaults?.system ?? continuationSeed?.pipe.system ?? defaults.system + const setSystem = ( + value: + | PipeSegmentNode['system'] + | ((current: PipeSegmentNode['system']) => PipeSegmentNode['system']), + ) => + updateRunDefaults('pipe-segment', { + system: typeof value === 'function' ? value(system) : value, + }) + const sloped = hangerDefaults?.fall === 'sloped' + const setSloped = (value: (current: boolean) => boolean) => + updateRunDefaults('pipe-segment', { fall: value(sloped) ? 'sloped' : 'level' }) + const slopePercent = + typeof hangerDefaults?.gradePercent === 'number' ? hangerDefaults.gradePercent : 100 / 48 + const slopeDirection = hangerDefaults?.flowDirection === 'reverse' ? -1 : 1 const gradeRef = useRef(slopePercent / 100) gradeRef.current = (slopeDirection * slopePercent) / 100 - const [diameter, setDiameter] = useState( - continuationSeed?.pipe.diameter ?? toolDefaults?.diameter ?? defaults.diameter, - ) - const [pipeMaterial, setPipeMaterial] = useState( - continuationSeed?.pipe.pipeMaterial ?? toolDefaults?.pipeMaterial ?? defaults.pipeMaterial, - ) + const diameter = toolDefaults?.diameter ?? continuationSeed?.pipe.diameter ?? defaults.diameter + const setDiameter = (diameter: number) => updateRunDefaults('pipe-segment', { diameter }) + const pipeMaterial = + toolDefaults?.pipeMaterial ?? continuationSeed?.pipe.pipeMaterial ?? defaults.pipeMaterial + const setPipeMaterial = (pipeMaterial: PipeSegmentNode['pipeMaterial']) => + updateRunDefaults('pipe-segment', { pipeMaterial }) const systemRef = useRef(system) systemRef.current = system const slopedRef = useRef(sloped) @@ -113,15 +124,22 @@ const PipeSegmentTool = () => { useEffect(() => { const mode = useRunHangerMode.getState() mode.setEnabled('pipe-segment', initialAutoHangersRef.current) - return () => mode.setEnabled('pipe-segment', false) + return () => { + updateRunDefaults('pipe-segment', { + autoHangers: useRunHangerMode.getState().enabled['pipe-segment'], + }) + mode.setEnabled('pipe-segment', false) + } }, []) useEffect(() => { - if (!toolDefaults) return - if (toolDefaults.system) setSystem(toolDefaults.system) - if (typeof toolDefaults.diameter === 'number') setDiameter(toolDefaults.diameter) - if (toolDefaults.pipeMaterial) setPipeMaterial(toolDefaults.pipeMaterial) - }, [toolDefaults]) + if (continuationSeed) + updateRunDefaults('pipe-segment', { + system: continuationSeed.pipe.system, + diameter: continuationSeed.pipe.diameter, + pipeMaterial: continuationSeed.pipe.pipeMaterial, + }) + }, [continuationSeed]) const commitSegment = ({ start: rawStart, @@ -180,16 +198,47 @@ const PipeSegmentTool = () => { const startBend = bendPlanFor(promotedFitting ? null : startConnection.port, direction) const endBend = bendPlanFor(endConnection.port, [-direction[0], -direction[1], -direction[2]]) - const invalidPlan = () => + const invalidPlan = (message = FITTING_CLEARANCE_MESSAGE) => previewOnly ? { - validationMessage: FITTING_CLEARANCE_MESSAGE, + validationMessage: message, nextStart: rawStart, nextConnection: startConnection, previewPipes: [] as PipeSegmentNode[], previewFittings: [] as PipeFittingNode[], } : null + const fixedConnection = (port: ScenePort | null, toward: RunPoint) => { + const owner = port && sceneApi.get(port.nodeId) + return port && owner && owner.type !== 'pipe-segment' + ? planPipeCollarConnection( + sceneApi.nodes(), + port, + toward, + diameterRef.current, + systemRef.current, + pipeMaterialRef.current, + ) + : null + } + let startCollar: ReturnType, + endCollar: ReturnType + try { + startCollar = fixedConnection(promotedFitting ? null : startConnection.port, end) + endCollar = fixedConnection(endConnection.port, start) + } catch (error) { + return invalidPlan(error instanceof Error ? error.message : 'Unable to connect collar.') + } + const actualGrade = pipeGrade(start, end) + if ( + slopedRef.current && + systemRef.current === 'waste' && + actualGrade !== null && + Math.abs(actualGrade - gradeRef.current) > 1e-5 + ) + return invalidPlan( + 'The connection elevation conflicts with the chosen grade. Adjust the grade or target elevation.', + ) if (startBend?.hasClearance === false || endBend?.hasClearance === false) return invalidPlan() const startBody = startBend ? null : startConnection.body const startOwner = startBody ? sceneApi.get(startBody.nodeId) : null @@ -210,14 +259,16 @@ const PipeSegmentTool = () => { : null if (endBody?.nodeId === startBody?.nodeId) endTap = null - const pipeStart = startBend?.collarPoint ?? startTap?.branchCollar ?? start - const pipeEnd = endBend?.collarPoint ?? endTap?.branchCollar ?? end + const pipeStart = + startBend?.collarPoint ?? startTap?.branchCollar ?? startCollar?.point ?? start + const pipeEnd = endBend?.collarPoint ?? endTap?.branchCollar ?? endCollar?.point ?? end const bends = [startBend, endBend].filter((plan) => plan !== null) - const crossHit = surfaceTarget - ? findRunBodyCrossingSurface(start, end, BODY_SNAP_RADIUS_M, surfaceTarget, { - kinds: ['pipe-segment'], - }) - : null + const crossHit = + surfaceTarget && hangerDefaults?.crossingMode !== 'cross' + ? findRunBodyCrossingSurface(start, end, BODY_SNAP_RADIUS_M, surfaceTarget, { + kinds: ['pipe-segment'], + }) + : null const crossOwner = crossHit ? sceneApi.get(crossHit.nodeId) : null const cross = crossHit && @@ -282,6 +333,17 @@ const PipeSegmentTool = () => { return { ...pipe, wallAttachment } } const attachedPipes = pipes.map(attachPipe) + if ( + slopedRef.current && + systemRef.current === 'waste' && + attachedPipes.some((pipe) => { + const grade = pipeGrade(pipe.path[0]!, pipe.path.at(-1)!) + return grade !== null && Math.abs(grade - gradeRef.current) > 1e-5 + }) + ) + return invalidPlan( + 'The fitting collars cannot maintain the chosen grade. Adjust the connection or grade.', + ) const sceneNodes = sceneApi.nodes() const consumedEndCapIds = Array.from( new Set([ @@ -300,6 +362,10 @@ const PipeSegmentTool = () => { const changes = { create: [ + ...[...(startCollar?.fittings ?? []), ...(endCollar?.fittings ?? [])].map((node) => ({ + node, + parentId: activeLevelId, + })), ...bends.map((plan) => ({ node: plan.fitting, parentId: activeLevelId, @@ -379,6 +445,14 @@ const PipeSegmentTool = () => { active: !!activeLevelId, levelId: activeLevelId, toolName: 'pipe-segment', + routingMode: + hangerDefaults?.routingMode === 'horizontal' || hangerDefaults?.routingMode === 'vertical' + ? hangerDefaults.routingMode + : 'surface', + elevation: typeof hangerDefaults?.elevation === 'number' ? hangerDefaults.elevation : 0, + targetElevation: + typeof hangerDefaults?.targetElevation === 'number' ? hangerDefaults.targetElevation : 3, + connectCrossings: hangerDefaults?.crossingMode !== 'cross', initialStart: continuationSeed ? ([ ...(continuationSeed.port?.position ?? continuationSeed.body?.point ?? [0, 0, 0]), @@ -396,16 +470,49 @@ const PipeSegmentTool = () => { surfaceClearance: (surface) => (surface ? runSectionHalfSizeM(diameterRef.current) : 0), minimumSegmentLength: 0.05, resolveFreeEnd: (start, end, startConnection) => { + const port = startConnection.port + if ( + port && + sceneApi.get(port.nodeId)?.type !== 'pipe-segment' && + !pendingPromotionRef.current + ) { + const axis = new Vector3(...port.direction).normalize() + const distance = Math.max(0, new Vector3(...end).sub(new Vector3(...start)).dot(axis)) + return new Vector3(...start).addScaledVector(axis, distance).toArray() as RunPoint + } if (!slopedRef.current || systemRef.current !== 'waste') return end return applyPipeGrade(start, end, gradeRef.current) }, inheritFromConnection: ({ port, body }) => { const ownerId = port?.nodeId ?? body?.nodeId const owner = ownerId ? sceneApi.get(ownerId) : null - if (owner?.type !== 'pipe-segment') return + if (owner?.type !== 'pipe-segment') { + if (port && (port.system === 'waste' || port.system === 'vent')) { + setDiameter(port.diameter) + setSystem(port.system) + if (owner && 'pipeMaterial' in owner) setPipeMaterial(owner.pipeMaterial) + const grade = pipeGrade([0, 0, 0], [...port.direction]) ?? 0 + updateRunDefaults('pipe-segment', { + fall: Math.abs(grade) > 1e-6 ? 'sloped' : 'level', + gradePercent: Math.abs(grade) * 100, + flowDirection: grade < 0 ? 'reverse' : 'forward', + }) + } + return + } setDiameter(owner.diameter) setPipeMaterial(owner.pipeMaterial) setSystem(owner.system) + const index = body?.segmentIndex ?? (port?.id === 'start' ? 0 : owner.path.length - 2) + const grade = pipeGrade(owner.path[index]!, owner.path[index + 1]!) + if (grade !== null) { + const inherited = port?.id === 'start' ? -grade : grade + updateRunDefaults('pipe-segment', { + fall: Math.abs(grade) > 1e-6 ? 'sloped' : 'level', + gradePercent: Math.abs(grade) * 100, + flowDirection: inherited < 0 ? 'reverse' : 'forward', + }) + } }, commit: commitSegment, onShortcut: (event) => { @@ -439,7 +546,7 @@ const PipeSegmentTool = () => { // biome-ignore lint/correctness/useExhaustiveDependencies: settings must refresh a stationary cursor useEffect(() => { if (!run.altActive) refreshCursor() - }, [sloped, system, run.altActive, refreshCursor]) + }, [sloped, slopePercent, slopeDirection, system, diameter, run.altActive, refreshCursor]) const displayStart = run.start const previewPlan = @@ -465,14 +572,23 @@ const PipeSegmentTool = () => { }) }, [autoHangers, hangerStyle, diameter, displayStart, run.cursor, system]) useEffect(() => () => usePathDraftPreview.getState().clear('pipe-segment'), []) - useEffect(() => () => useEditor.getState().setToolDefaults('pipe-segment', null), []) + useEffect(() => () => clearRunContinuation('pipe-segment'), []) if (!activeLevelId) return null return ( @@ -480,6 +596,7 @@ const PipeSegmentTool = () => { altActive={run.altActive} cursor={run.cursor} directionMode={run.directionMode} + routingMode={run.routingMode} extraParts={[{ key: 'diameter', prefix: 'Ø', value: diameter * 0.0254 }]} lengthInput={run.lengthInput} onLengthInputChange={run.onLengthInputChange} diff --git a/packages/nodes/src/pipe-trap/geometry.ts b/packages/nodes/src/pipe-trap/geometry.ts index d0f85a8ae4..dcea7e2cd3 100644 --- a/packages/nodes/src/pipe-trap/geometry.ts +++ b/packages/nodes/src/pipe-trap/geometry.ts @@ -1,5 +1,6 @@ import { DoubleSide, Group, Mesh, SphereGeometry, TorusGeometry, Vector3 } from 'three' -import { buildSection, INCHES_TO_METERS } from '../duct-segment/geometry' +import { buildSection } from '../duct-segment/geometry' +import { INCHES_TO_METERS } from '../duct-segment/profile' import { createPipeMaterial } from '../pipe-segment/geometry' import type { PipeTrapNode } from './schema' diff --git a/packages/nodes/src/pipe-trap/parametrics.ts b/packages/nodes/src/pipe-trap/parametrics.ts index 502377cb6c..f060c95fdd 100644 --- a/packages/nodes/src/pipe-trap/parametrics.ts +++ b/packages/nodes/src/pipe-trap/parametrics.ts @@ -2,6 +2,7 @@ import type { ParametricDescriptor } from '@pascal-app/core' import type { PipeTrapNode } from './schema' export const pipeTrapParametrics: ParametricDescriptor = { + trailingSection: () => import('../shared/pipe-collar-inspector'), groups: [ { label: 'Trap', diff --git a/packages/nodes/src/shared/accessory-placement.ts b/packages/nodes/src/shared/accessory-placement.ts index 464f7da39f..6f6021ab4c 100644 --- a/packages/nodes/src/shared/accessory-placement.ts +++ b/packages/nodes/src/shared/accessory-placement.ts @@ -2,7 +2,7 @@ import type { AnyNode, AnyNodeId, DuctFittingNode, PipeFittingNode } from '@pasc import type { ScenePort } from '@pascal-app/editor/distribution' import { Euler, Matrix4, Quaternion, Vector3 } from 'three' import { adapterShape } from '../duct-fitting/ports' -import { rectSectionAxes } from '../duct-segment/geometry' +import { rectSectionAxes } from '../duct-segment/profile' import { reducerOutletDiameter } from './reducer-size' export function inheritFittingProfile( diff --git a/packages/nodes/src/shared/auto-fitting.ts b/packages/nodes/src/shared/auto-fitting.ts index 4952968a5f..a5b7a89efc 100644 --- a/packages/nodes/src/shared/auto-fitting.ts +++ b/packages/nodes/src/shared/auto-fitting.ts @@ -11,7 +11,7 @@ import { ductPortDiameterIn, equivalentDiameterIn, ovalEquivalentDiameterIn, -} from '../duct-segment/geometry' +} from '../duct-segment/profile' import { pipeFittingLegLength } from '../pipe-fitting/ports' /** Turns shallower than this read as a straight continuation — butt-join diff --git a/packages/nodes/src/shared/automatic-run-end-cap.test.ts b/packages/nodes/src/shared/automatic-run-end-cap.test.ts index 7a8c80ac43..977833b841 100644 --- a/packages/nodes/src/shared/automatic-run-end-cap.test.ts +++ b/packages/nodes/src/shared/automatic-run-end-cap.test.ts @@ -72,6 +72,28 @@ describe('automatic run end caps', () => { expect(isRunEndCapPort({ ...inlet, nodeId: cap.id }, nodes)).toBe(true) }) + test('spiral ducts use sheet-metal end caps at both collars', () => { + const duct = DuctSegmentNode.parse({ + path: [ + [0, 1, 0], + [3, 1, 0], + ], + shape: 'round', + diameter: 6, + ductMaterial: 'spiral', + }) + for (const endpoint of ['start', 'end'] as const) { + const cap = createDuctRunEndCap(duct, endpoint)! + expect(cap.ductMaterial).toBe('sheet-metal') + expect(cap.diameter).toBe(6) + const inlet = getDuctFittingPorts(cap)[0]! + expect(inlet.position[0]).toBeCloseTo(endpoint === 'start' ? 0 : 3) + expect(inlet.position[1]).toBeCloseTo(1) + expect(inlet.position[2]).toBeCloseTo(0) + } + expect(duct.ductMaterial).toBe('spiral') + }) + test('closes a vertical vent pipe and preserves its material', () => { const pipe = PipeSegmentNode.parse({ path: [ diff --git a/packages/nodes/src/shared/automatic-run-end-cap.ts b/packages/nodes/src/shared/automatic-run-end-cap.ts index 7a34211234..70ae735fd7 100644 --- a/packages/nodes/src/shared/automatic-run-end-cap.ts +++ b/packages/nodes/src/shared/automatic-run-end-cap.ts @@ -9,7 +9,7 @@ import { import type { ScenePort } from '@pascal-app/editor/distribution' import { Euler, Quaternion, Vector3 } from 'three' import { localFittingPorts } from '../duct-fitting/ports' -import { ductPortDiameterIn } from '../duct-segment/geometry' +import { ductPortDiameterIn } from '../duct-segment/profile' import { localPipeFittingPorts } from '../pipe-fitting/ports' import { accessoryMateQuaternion } from './accessory-placement' @@ -83,7 +83,7 @@ export function createDuctRunEndCap( height2: duct.height, diameter: port.diameter, diameter2: port.diameter, - ductMaterial: duct.ductMaterial, + ductMaterial: duct.ductMaterial === 'spiral' ? 'sheet-metal' : duct.ductMaterial, system: duct.system, }) const rotation = accessoryMateQuaternion(cap, port, { @@ -214,3 +214,20 @@ export function planRunEndCapFollowUpdates( data: { position: placed.position, rotation: placed.rotation } as Partial, })) } + +/** A split transfers the far cap to the new tail without moving its collar. */ +export function transferRunEndCapOwnership( + nodes: Readonly>, + previousId: AnyNodeId, + nextId: AnyNodeId, + endpoint: 'start' | 'end', +): { id: AnyNodeId; data: Partial }[] { + return Object.values(nodes).flatMap((node) => + (node.type === 'pipe-fitting' || node.type === 'duct-fitting') && + node.fittingType === 'end-cap' && + node.metadata[END_CAP_OWNER_ID_KEY] === previousId && + node.metadata[END_CAP_ENDPOINT_KEY] === endpoint + ? [{ id: node.id, data: { metadata: { ...node.metadata, [END_CAP_OWNER_ID_KEY]: nextId } } }] + : [], + ) +} diff --git a/packages/nodes/src/shared/connection-feedback.tsx b/packages/nodes/src/shared/connection-feedback.tsx index b8d3c46dd4..7cdf2a975e 100644 --- a/packages/nodes/src/shared/connection-feedback.tsx +++ b/packages/nodes/src/shared/connection-feedback.tsx @@ -13,8 +13,11 @@ import { collectScenePorts, connectionCompatibility, findNearestPort3D, + type PortScreenPoint, type ScenePort, } from '@pascal-app/editor/distribution' +import { Html } from '@react-three/drei' +import { createPortal } from 'react-dom' const COLORS = { match: '#16a34a', adapter: '#d97706', incompatible: '#dc2626', unknown: '#d97706' } @@ -23,21 +26,62 @@ export function ConnectionFeedback({ profile, levelId, target, + screen, + detail, + error, }: { point: [number, number, number] | null profile: ConnectionProfile levelId: AnyNodeId + detail?: string + error?: string | null + screen?: PortScreenPoint | null target?: ScenePort | null }) { useEditor((state) => state.snappingModeByContext) - if (!point || !(isGridSnapActive() || isMagneticSnapActive() || isAngleSnapActive())) return null + if ( + !point || + (!error && !detail && !(isGridSnapActive() || isMagneticSnapActive() || isAngleSnapActive())) + ) + return null const port = target === undefined ? findNearestPort3D(point, collectScenePorts({ levelId }), 0.5) : target - if (!port) return null - const feedback = connectionCompatibility(profile, port) - const color = COLORS[feedback.status] + if (!port && !detail && !error) return null + const feedback = port + ? connectionCompatibility(profile, port) + : { status: 'adapter' as const, label: 'Route preview' } + const color = COLORS[error ? 'incompatible' : feedback.status] + const label = ( + + {error || feedback.label} + {detail && {detail}} + + ) return ( - + + + {screen + ? createPortal( + + {label} + , + document.body, + ) + : label} + {}}> diff --git a/packages/nodes/src/shared/duct-adapter.ts b/packages/nodes/src/shared/duct-adapter.ts index 39de6403e2..77e77116ec 100644 --- a/packages/nodes/src/shared/duct-adapter.ts +++ b/packages/nodes/src/shared/duct-adapter.ts @@ -2,7 +2,7 @@ import { DuctFittingNode } from '@pascal-app/core' import type { ScenePort } from '@pascal-app/editor/distribution' import { Euler, Matrix4, Vector3 } from 'three' import { fittingLegLength } from '../duct-fitting/ports' -import { rectSectionAxes } from '../duct-segment/geometry' +import { rectSectionAxes } from '../duct-segment/profile' import { type DuctProfile, profileDiameterIn } from './auto-fitting' export function ductProfilesMatch(a: DuctProfile, b: DuctProfile): boolean { diff --git a/packages/nodes/src/shared/duct-collar-inspector.tsx b/packages/nodes/src/shared/duct-collar-inspector.tsx new file mode 100644 index 0000000000..960712cbef --- /dev/null +++ b/packages/nodes/src/shared/duct-collar-inspector.tsx @@ -0,0 +1,65 @@ +'use client' + +import { type AnyNode, nodeRegistry, useScene } from '@pascal-app/core' +import { useEditor } from '@pascal-app/editor' +import { useViewer } from '@pascal-app/viewer' +import { Vector3 } from 'three' + +export default function DuctCollarInspector({ node }: { node: AnyNode }) { + const nodes = useScene((state) => state.nodes) + const ports = nodeRegistry.get(node.type)?.ports?.(node) ?? [] + const others = Object.values(nodes) + .filter((other) => other.id !== node.id && other.parentId === node.parentId) + .flatMap((other) => nodeRegistry.get(other.type)?.ports?.(other) ?? []) + const airPorts = ports.filter((port) => port.system === 'supply' || port.system === 'return') + if (!airPorts.length) return null + return ( + + Connect duct + {airPorts.map((port) => { + const occupied = others.some( + (other) => + new Vector3(...other.position).distanceTo(new Vector3(...port.position)) < 0.005 && + new Vector3(...other.direction).dot(new Vector3(...port.direction)) < -0.99, + ) + const size = + port.shape && port.shape !== 'round' + ? `${port.width} × ${port.height}` + : `${port.diameter}` + return ( + { + const editor = useEditor.getState() + editor.setToolDefaults('duct-segment', { + ...editor.toolDefaults['duct-segment'], + continuation: { nodeId: node.id, portId: port.id }, + shape: port.shape ?? 'round', + diameter: port.diameter, + width: port.width ?? 14, + height: port.height ?? 8, + system: port.system, + ductMaterial: 'sheet-metal', + elevation: port.position[1], + routingMode: + Math.hypot(port.direction[0], port.direction[2]) < 1e-6 + ? 'vertical' + : 'horizontal', + targetElevation: port.position[1] + Math.sign(port.direction[1] || 1), + crossingMode: 'connect', + }) + useViewer.getState().setSelection({ selectedIds: [] }) + editor.setTool('duct-segment') + }} + > + {port.system === 'return' ? 'Return' : 'Supply'} · {size} in ·{' '} + {occupied ? 'Connected' : 'Draw from collar'} + + ) + })} + + ) +} diff --git a/packages/nodes/src/shared/fitting-catalog-selection.test.ts b/packages/nodes/src/shared/fitting-catalog-selection.test.ts index 2ef3e40009..6f96c270b3 100644 --- a/packages/nodes/src/shared/fitting-catalog-selection.test.ts +++ b/packages/nodes/src/shared/fitting-catalog-selection.test.ts @@ -239,3 +239,55 @@ test('choosing a round transition inlet automatically selects a rectangular outl expect(defaults.inletShape).toBe('round') expect(defaults.outletShape).toBe('rect') }) + +test('run options retain independent settings and discard consumed continuation context', async () => { + const { ductSegmentDefinition, pipeSegmentDefinition } = await import('../index') + const { clearRunContinuation } = await import('./run-tool-options') + const previous = useEditor.getState().toolDefaults + try { + useEditor.setState({ toolDefaults: {} }) + const duct = ductSegmentDefinition.toolOptions! + const pipe = pipeSegmentDefinition.toolOptions! + duct.find((option) => option.id === 'shape')!.set('round') + duct.find((option) => option.id === 'diameter')!.set('10') + pipe.find((option) => option.id === 'diameter')!.set('4') + pipe.find((option) => option.id === 'fall')!.set('sloped') + useEditor.getState().setToolDefaults('duct-segment', { + ...useEditor.getState().toolDefaults['duct-segment'], + continuation: { nodeId: 'duct-segment_old', endpoint: 'end' }, + }) + clearRunContinuation('duct-segment') + expect(duct.find((option) => option.id === 'diameter')!.value()).toBe('10') + expect(pipe.find((option) => option.id === 'diameter')!.value()).toBe('4') + expect(pipe.find((option) => option.id === 'fall')!.value()).toBe('sloped') + expect(useEditor.getState().toolDefaults['duct-segment']?.continuation).toBeUndefined() + duct.find((option) => option.id === 'diameter')!.set('NaN') + duct.find((option) => option.id === 'diameter')!.set('100') + expect(duct.find((option) => option.id === 'diameter')!.value()).toBe('10') + } finally { + useEditor.setState({ toolDefaults: previous }) + } +}) + +test('duct presets apply a complete profile without resetting route preferences', async () => { + const { ductRunToolOptions } = await import('./run-tool-options') + useEditor.getState().setToolDefaults('duct-segment', { + routingMode: 'horizontal', + elevation: 2.4, + crossingMode: 'cross', + }) + const preset = ductRunToolOptions.find((option) => option.id === 'preset')! + preset.set('return') + expect(useEditor.getState().toolDefaults['duct-segment']).toMatchObject({ + shape: 'rect', + width: 20, + height: 10, + system: 'return', + ductMaterial: 'sheet-metal', + elevation: 2.4, + crossingMode: 'cross', + }) + expect(preset.value()).toBe('return') + ductRunToolOptions.find((option) => option.id === 'width')!.set('22') + expect(preset.value()).toBe('custom') +}) diff --git a/packages/nodes/src/shared/pipe-collar-inspector.tsx b/packages/nodes/src/shared/pipe-collar-inspector.tsx new file mode 100644 index 0000000000..bfc1efaee6 --- /dev/null +++ b/packages/nodes/src/shared/pipe-collar-inspector.tsx @@ -0,0 +1,60 @@ +'use client' + +import { type AnyNode, nodeRegistry, useScene } from '@pascal-app/core' +import { useEditor } from '@pascal-app/editor' +import { useViewer } from '@pascal-app/viewer' +import { pipeCollarOccupied } from '../pipe-segment/collar-connection' +import { pipeGrade } from '../pipe-segment/slope' + +export default function PipeCollarInspector({ node }: { node: AnyNode }) { + const nodes = useScene((state) => state.nodes) + const ports = nodeRegistry.get(node.type)?.ports?.(node) ?? [] + const pipePorts = ports.filter((port) => port.system === 'waste' || port.system === 'vent') + if (!pipePorts.length) return null + return ( + + Connect pipe + {pipePorts.map((port) => { + const occupied = pipeCollarOccupied(nodes, { ...port, nodeId: node.id }) + return ( + { + const editor = useEditor.getState() + editor.setToolDefaults('pipe-segment', { + ...editor.toolDefaults['pipe-segment'], + continuation: { nodeId: node.id, portId: port.id }, + diameter: port.diameter, + system: port.system, + pipeMaterial: 'pipeMaterial' in node ? node.pipeMaterial : 'pvc', + elevation: port.position[1], + routingMode: + Math.hypot(port.direction[0], port.direction[2]) < 1e-6 + ? 'vertical' + : 'horizontal', + targetElevation: port.position[1] + Math.sign(port.direction[1] || 1), + ...(() => { + const grade = pipeGrade([0, 0, 0], [...port.direction]) ?? 0 + return { + fall: Math.abs(grade) > 1e-6 ? 'sloped' : 'level', + gradePercent: Math.abs(grade) * 100, + flowDirection: grade < 0 ? 'reverse' : 'forward', + } + })(), + crossingMode: 'connect', + }) + useViewer.getState().setSelection({ selectedIds: [] }) + editor.setTool('pipe-segment') + }} + > + {port.id} · {port.diameter} in · {port.position[1].toFixed(3)} m ·{' '} + {occupied ? 'Connected' : 'Draw from collar'} + + ) + })} + + ) +} diff --git a/packages/nodes/src/shared/run-hangers.ts b/packages/nodes/src/shared/run-hangers.ts index 73d83d400b..e4472a1b91 100644 --- a/packages/nodes/src/shared/run-hangers.ts +++ b/packages/nodes/src/shared/run-hangers.ts @@ -26,7 +26,7 @@ import { Vector2, Vector3, } from 'three' -import { rectSectionAxes } from '../duct-segment/geometry' +import { rectSectionAxes } from '../duct-segment/profile' import { hasWallChildOverlap, resolveWallAttachmentAtPlanPoint } from './wall-attach-target' export type SupportedRun = DuctSegmentNode | PipeSegmentNode diff --git a/packages/nodes/src/shared/run-tool-options.ts b/packages/nodes/src/shared/run-tool-options.ts new file mode 100644 index 0000000000..466dfefb3a --- /dev/null +++ b/packages/nodes/src/shared/run-tool-options.ts @@ -0,0 +1,260 @@ +import type { ToolOption } from '@pascal-app/core' +import { useEditor } from '@pascal-app/editor' + +type RunKind = 'duct-segment' | 'pipe-segment' + +export function updateRunDefaults(kind: RunKind, patch: Record): void { + const editor = useEditor.getState() + editor.setToolDefaults(kind, { ...editor.toolDefaults[kind], ...patch }) +} + +export function clearRunContinuation(kind: RunKind): void { + const { continuation: _continuation, ...settings } = useEditor.getState().toolDefaults[kind] ?? {} + useEditor.getState().setToolDefaults(kind, settings) +} + +function choice( + kind: RunKind, + key: string, + label: string, + values: readonly [string, string, string?][], + fallback: string, +): ToolOption { + return { + id: key, + label, + choices: values.map(([value, label, description]) => ({ value, label, description })), + subscribe: useEditor.subscribe, + value: () => String(useEditor.getState().toolDefaults[kind]?.[key] ?? fallback), + set: (value) => updateRunDefaults(kind, { [key]: value }), + } +} + +function number( + kind: RunKind, + key: string, + label: string, + fallback: number, + input: NonNullable, +): ToolOption { + return { + ...choice(kind, key, label, [], String(fallback)), + input, + set: (value) => { + const next = Number(value) + if ( + !Number.isFinite(next) || + (input.min !== undefined && next < input.min) || + (input.max !== undefined && next > input.max) + ) + return + updateRunDefaults(kind, { [key]: next }) + }, + } +} + +function routing(kind: RunKind): ToolOption[] { + return [ + choice( + kind, + 'routingMode', + 'Route', + [ + ['surface', 'Follow surface', 'Follow the floor, wall, or ceiling under the pointer.'], + [ + 'horizontal', + kind === 'pipe-segment' ? 'Plan route' : 'Horizontal', + kind === 'pipe-segment' + ? 'Follow a plan direction, applying the chosen fall from the start elevation.' + : 'Keep the run at its starting elevation.', + ], + ['vertical', 'Vertical', 'Keep X and Z fixed. Enter the target elevation below.'], + ], + 'surface', + ), + { + ...number(kind, 'elevation', 'Start elevation above level', 0, { unit: 'm', step: 0.01 }), + visible: { + subscribe: useEditor.subscribe, + value: () => + ['horizontal', 'vertical'].includes( + String(useEditor.getState().toolDefaults[kind]?.routingMode), + ), + }, + }, + { + ...number(kind, 'targetElevation', 'Target elevation above level', 3, { + unit: 'm', + step: 0.01, + }), + visible: { + subscribe: useEditor.subscribe, + value: () => useEditor.getState().toolDefaults[kind]?.routingMode === 'vertical', + }, + }, + choice( + kind, + 'crossingMode', + 'Crossing another run', + [ + ['connect', 'Connect', 'Insert a fitting where runs meet.'], + [ + 'cross', + 'Cross without joining', + 'Keep the runs separate. This does not provide physical clearance.', + ], + ], + 'connect', + ), + ] +} + +const ductProfile = (round: boolean) => ({ + subscribe: useEditor.subscribe, + value: () => (useEditor.getState().toolDefaults['duct-segment']?.shape === 'round') === round, +}) + +const ductPresets = { + trunk: { shape: 'rect', width: 14, height: 8, ductMaterial: 'sheet-metal', system: 'supply' }, + branch: { shape: 'round', diameter: 6, ductMaterial: 'spiral', system: 'supply' }, + flex: { shape: 'round', diameter: 6, ductMaterial: 'flex', system: 'supply' }, + return: { shape: 'rect', width: 20, height: 10, ductMaterial: 'sheet-metal', system: 'return' }, +} as const + +export const ductRunToolOptions: ToolOption[] = [ + { + ...choice( + 'duct-segment', + 'preset', + 'Starting profile', + [ + ['custom', 'Custom'], + ['trunk', 'Supply trunk · 14 × 8 in'], + ['branch', 'Round branch · 6 in'], + ['flex', 'Flex connection · 6 in'], + ['return', 'Return trunk · 20 × 10 in'], + ], + 'custom', + ), + value: () => { + const current = useEditor.getState().toolDefaults['duct-segment'] ?? {} + return ( + Object.entries(ductPresets).find(([, preset]) => + Object.entries(preset).every(([key, value]) => current[key] === value), + )?.[0] ?? 'custom' + ) + }, + set: (value) => { + const preset = ductPresets[value as keyof typeof ductPresets] + if (preset) updateRunDefaults('duct-segment', preset) + }, + }, + choice( + 'duct-segment', + 'system', + 'System', + [ + ['supply', 'Supply'], + ['return', 'Return'], + ], + 'supply', + ), + choice( + 'duct-segment', + 'shape', + 'Profile', + [ + ['round', 'Round'], + ['rect', 'Rectangular'], + ['oval', 'Oval'], + ], + 'rect', + ), + { + ...number('duct-segment', 'diameter', 'Diameter', 6, { min: 2, max: 48, unit: 'in' }), + visible: ductProfile(true), + }, + { + ...number('duct-segment', 'width', 'Width', 14, { min: 4, max: 60, unit: 'in' }), + visible: ductProfile(false), + }, + { + ...number('duct-segment', 'height', 'Height', 8, { min: 3, max: 40, unit: 'in' }), + visible: ductProfile(false), + }, + choice( + 'duct-segment', + 'ductMaterial', + 'Material', + [ + ['flex', 'Flex'], + ['sheet-metal', 'Sheet metal'], + ['spiral', 'Spiral'], + ['duct-board', 'Ductboard'], + ], + 'flex', + ), + ...routing('duct-segment'), +] + +export const pipeRunToolOptions: ToolOption[] = [ + choice( + 'pipe-segment', + 'system', + 'System', + [ + ['waste', 'Waste'], + ['vent', 'Vent'], + ], + 'waste', + ), + number('pipe-segment', 'diameter', 'Diameter', 2, { min: 1.25, max: 8, unit: 'in' }), + choice( + 'pipe-segment', + 'pipeMaterial', + 'Material', + [ + ['pvc', 'PVC'], + ['abs', 'ABS'], + ['cast-iron', 'Cast iron'], + ], + 'pvc', + ), + { + ...choice( + 'pipe-segment', + 'fall', + 'Fall', + [ + ['level', 'Level'], + ['sloped', 'Graded', 'Apply the grade and flow direction below.'], + ], + 'level', + ), + visible: { + subscribe: useEditor.subscribe, + value: () => + (useEditor.getState().toolDefaults['pipe-segment']?.system ?? 'waste') === 'waste', + }, + }, + { + ...number('pipe-segment', 'gradePercent', 'Grade', 100 / 48, { min: 0, step: 0.1, unit: '%' }), + visible: { + subscribe: useEditor.subscribe, + value: () => + useEditor.getState().toolDefaults['pipe-segment']?.fall === 'sloped' && + (useEditor.getState().toolDefaults['pipe-segment']?.system ?? 'waste') === 'waste', + }, + }, + choice( + 'pipe-segment', + 'flowDirection', + 'Downhill flow', + [ + ['forward', 'Start → end'], + ['reverse', 'End → start'], + ], + 'forward', + ), + ...routing('pipe-segment'), +] diff --git a/packages/nodes/src/shared/vertical-offset.ts b/packages/nodes/src/shared/vertical-offset.ts index 1084f53948..4ed099d12a 100644 --- a/packages/nodes/src/shared/vertical-offset.ts +++ b/packages/nodes/src/shared/vertical-offset.ts @@ -8,7 +8,7 @@ import type { ScenePort } from '@pascal-app/editor/distribution' import { Vector3 } from 'three' import { fittingLegLength, getDuctFittingPorts } from '../duct-fitting/ports' import type { DuctFittingNode } from '../duct-fitting/schema' -import { rollToContinueAcrossElbow } from '../duct-segment/geometry' +import { rollToContinueAcrossElbow } from '../duct-segment/profile' import { type DuctProfile, type ElbowJointPlan, diff --git a/wiki/architecture/tools.md b/wiki/architecture/tools.md index 15869b07e9..1befb5260a 100644 --- a/wiki/architecture/tools.md +++ b/wiki/architecture/tools.md @@ -415,3 +415,106 @@ node, parent and context nodes. This supports tools whose ghosts never enter the committed scene. The helper merges that preview only for the notice query; moving nodes still use their kind's live-transform frame, and selected inspectors call `usePlacementNotice(id)` without adopting a tool's preview. + + +## Duct and pipe build settings + +Duct and DWV run definitions contribute `toolOptions` for system, profile/size, +material, routing and crossing intent. `ToolOption.input` lets a host render an +exact numeric field with the schema's limits instead of a fixed choice list. +The settings share `useEditor.toolDefaults` with keyboard shortcuts and survive +switching tools within the session. Continuation context is consumed separately; +returning to a tool must not resume an old endpoint. + +Follow surface keeps the existing floor/wall/ceiling behavior. Horizontal starts +at a level-local centreline elevation; the pipe fall setting still applies. +Vertical keeps X/Z fixed and uses an exact target elevation, available in either +view. Alt retains the existing temporary vertical-drag behavior. Sidebar changes +refresh the draft without requiring another pointer move. + +Connect retains automatic branch/cross fittings. Cross without joining disables +body snapping and automatic interior crosses while leaving endpoint connections +available. It creates no clearance or obstacle detour. Preview and commit consume +the same choice. Connection feedback includes text as well as color, with screen +coordinates for snapped-port labels in the plan view. + +Duct routing adds supply-trunk, round-branch, flex and return-trunk starting +profiles. These are editable dimensional presets, not airflow sizing calculations. +Equipment and terminal inspectors can start a run from an unoccupied air collar, +carrying its section and system. Transition feedback includes both sections and +the planned fitting length. + +Duct profile edits use the `duct_edit` operation in both the inspector and agent +hosts. Segment scope inserts transitions against fixed neighbours; branch scope +follows same-profile ducts through elbows, couplings, dampers and caps, stopping +at junctions, size changes and equipment. Changed fitting collars retarget the +joined run endpoints. Insufficient space refuses the entire edit. Face alignment +supports free straight runs; connected routes require center alignment because +current fittings do not represent eccentric transitions. There is no separate +node-lock contract for this operation. + +The same operation adds a measured vertical obstacle offset to a straight +horizontal run: four elbows and intervening ducts preserve both original +endpoints. The inspector previews a side elevation before applying. This is a +manual routing aid, not collision detection or an automatic obstacle solver. +Rolled non-round runs are refused because the offset cannot express the required +twist. Both operations apply one scene change batch and invalidate stale offset +rewind metadata. The inspector is shared by 2D and 3D. + +Pipe grade remains derived from path elevations; existing scenes need no new +fields. Drawing offers grade percentage and downhill direction, and reports +start/end centerline elevations above the level. Continuing at either end +inherits the source leg’s signed grade. Snapped connections that conflict with +the requested grade are refused, including fitting collar adjustments. + +`pipe_grade` provides the inspector and agent operation for applying grade with +a fixed start/end elevation, translating elevation without changing grades, +and editing a path point while preserving each leg’s grade. Vertical legs keep +their rise; a stack cannot become a diagonal by dragging one endpoint. Flow +arrows describe downhill geometry, not hydraulic simulation; level runs have no +gravity-flow direction. Plan selection shows downhill chevrons and grade labels. + +Plan point drags use live overrides and commit once. The 3D endpoint tools apply +the same grade constraint before their existing fitting planners. Connected +collars that cannot turn cleanly, or neighbours whose grade would change, refuse +the edit. Alt detaches a path-point edit while retaining the edited run’s grade. +Explicit grade edits may change the selected run’s grade; connected runs retain +theirs. Profile resizing is unchanged because diameter does not alter the stored +centerline path. + +Pipe size edits use the `pipe_resize` operation from both the inspector (plan and +3D views) and agent tools. Segment scope carries end caps; branch scope traverses +same-size, same-material pipes through elbows, couplings and cleanouts. Junctions, +reducers, size/material changes and fixture or equipment collars form boundaries. +The operation inserts reducers into the selected run at fixed boundaries, moves +run endpoints to resized fitting collars, and checks every leg's direction and +signed grade before returning one atomic batch. Ambiguous collars, incompatible +angles and insufficient straight length refuse the entire edit. “Check resize” +reports affected runs, fittings and new reducers without changing the scene. + +`pipe_offset` adds a user-controlled four-bend detour to a straight, non-vertical +pipe. The inspector exposes the same operation in plan and 3D with a side-profile +schematic. `from` and `to` measure horizontal distance from the start to the first +and last bend; `offset` is the signed vertical displacement. Each connector uses +`abs(offset)` horizontal travel. The three parallel sections retain the original +signed grade; the two connectors have their own grades. Boundary positions and +collar directions remain fixed. The original node becomes the first section and +four new runs plus four elbows form the rest, committed in one undo step. The far +automatic cap transfers ownership to the new tail without moving. + +Insufficient fitting space, vertical or polyline source runs, hosted children and +custom hanger overrides refuse without partial edits. Ordinary automatic hangers +regenerate on the new sections. Waste offsets report uphill connectors explicitly; +the operation does not certify continuous downhill drainage or check obstacles. + +Fixed waste/vent collars use `planPipeCollarConnection` in both drawing and the +`pipe_connect` agent operation. Trap and fitting inspectors offer “Draw from +collar”; plugins can reuse the exported `PipeCollarInspector` for fixtures with +registered ports. The seed inherits size, material, elevation and direction. +The first free section follows the collar axis; subsequent turns use ordinary +pipe continuation. Occupied collars are disabled and rechecked before commit. +Diameter changes preview and create a reducer entirely outside the fixed collar; +short, incompatible or stale connections refuse without moving the source. +`pipe_connect` extends to a free endpoint; interactive drawing can also join an +existing open collar. Decorative catalog fixtures without authored waste/vent +ports are not inferred from their mesh. diff --git a/wiki/assets/pr-1115/01-grade-3-percent.png b/wiki/assets/pr-1115/01-grade-3-percent.png new file mode 100644 index 0000000000..5cf48d0e48 Binary files /dev/null and b/wiki/assets/pr-1115/01-grade-3-percent.png differ diff --git a/wiki/assets/pr-1115/02-grade-undo.png b/wiki/assets/pr-1115/02-grade-undo.png new file mode 100644 index 0000000000..8297c2d849 Binary files /dev/null and b/wiki/assets/pr-1115/02-grade-undo.png differ diff --git a/wiki/assets/pr-1115/03-pipe-offset-3d.png b/wiki/assets/pr-1115/03-pipe-offset-3d.png new file mode 100644 index 0000000000..23169a14cb Binary files /dev/null and b/wiki/assets/pr-1115/03-pipe-offset-3d.png differ diff --git a/wiki/assets/pr-1115/04-connected-resize-plan.png b/wiki/assets/pr-1115/04-connected-resize-plan.png new file mode 100644 index 0000000000..dc4fe95467 Binary files /dev/null and b/wiki/assets/pr-1115/04-connected-resize-plan.png differ diff --git a/wiki/assets/pr-1115/05-connected-resize-3d.png b/wiki/assets/pr-1115/05-connected-resize-3d.png new file mode 100644 index 0000000000..9ec59ba979 Binary files /dev/null and b/wiki/assets/pr-1115/05-connected-resize-3d.png differ diff --git a/wiki/assets/pr-1115/06-connect-crossing-2d.png b/wiki/assets/pr-1115/06-connect-crossing-2d.png new file mode 100644 index 0000000000..12c7328185 Binary files /dev/null and b/wiki/assets/pr-1115/06-connect-crossing-2d.png differ diff --git a/wiki/assets/pr-1115/07-cross-without-joining-2d.png b/wiki/assets/pr-1115/07-cross-without-joining-2d.png new file mode 100644 index 0000000000..9d41dd98a1 Binary files /dev/null and b/wiki/assets/pr-1115/07-cross-without-joining-2d.png differ diff --git a/wiki/assets/pr-1115/08-crossings-3d.png b/wiki/assets/pr-1115/08-crossings-3d.png new file mode 100644 index 0000000000..32c8575bb8 Binary files /dev/null and b/wiki/assets/pr-1115/08-crossings-3d.png differ diff --git a/wiki/assets/pr-1115/09-duct-offset-reset.png b/wiki/assets/pr-1115/09-duct-offset-reset.png new file mode 100644 index 0000000000..97406bdd17 Binary files /dev/null and b/wiki/assets/pr-1115/09-duct-offset-reset.png differ diff --git a/wiki/assets/pr-1115/10-duct-offset-undo.png b/wiki/assets/pr-1115/10-duct-offset-undo.png new file mode 100644 index 0000000000..1a45bfa269 Binary files /dev/null and b/wiki/assets/pr-1115/10-duct-offset-undo.png differ
{activeChoice.description} diff --git a/packages/nodes/src/agent-operations/duct-tools.test.ts b/packages/nodes/src/agent-operations/duct-tools.test.ts new file mode 100644 index 0000000000..4e35f57eda --- /dev/null +++ b/packages/nodes/src/agent-operations/duct-tools.test.ts @@ -0,0 +1,398 @@ +import { afterEach, beforeEach, expect, test } from 'bun:test' +import { fileURLToPath } from 'node:url' +import { Client } from '@modelcontextprotocol/sdk/client/index.js' +import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js' +import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js' +import { + type AnyNode, + DuctFittingNode, + DuctSegmentNode, + LevelNode, + nodeRegistry, + registerNode, +} from '@pascal-app/core' +import { SceneBridge } from '@pascal-app/mcp/bridge' +import { createSceneOperations } from '@pascal-app/mcp/operations' +import { registerOperationTool } from '@pascal-app/mcp/tools/shared-tools' +import { ductFittingDefinition, ductSegmentDefinition } from '@pascal-app/nodes' +import { builtinAgentOperations } from '@pascal-app/nodes/agent-operations' +import { builtinAgentTools } from '@pascal-app/nodes/agent-tools' + +let restore: ReturnType +beforeEach(() => { + restore = nodeRegistry._snapshot() + registerNode(ductSegmentDefinition) + registerNode(ductFittingDefinition) +}) +afterEach(() => restore()) +const level = LevelNode.parse({}) +const run = (extra = {}) => + DuctSegmentNode.parse({ + parentId: level.id, + shape: 'round', + diameter: 6, + path: [ + [0, 0, 0], + [6, 0, 0], + ], + ...extra, + }) +const scene = (...nodes: AnyNode[]) => + Object.fromEntries([level, ...nodes].map((node) => [node.id, node])) +const edit = builtinAgentOperations.duct_edit +const context = { activeLevelId: level.id } + +test('duct operation is offered with dimensions and edit scopes', () => { + const contract = builtinAgentTools.tools.find((tool) => tool.name === 'duct_edit')! + expect(contract.runsIn).toBe('operation') + expect(contract.input).toHaveProperty('alignment') +}) + +test('face resize preserves the top of an unconnected rectangular run', () => { + const duct = run({ shape: 'rect', width: 14, height: 8 }) + const result = edit( + scene(duct), + { nodeId: duct.id, action: 'resize', height: 12, alignment: 'top' }, + context, + ) + const resized = { ...duct, ...result.changes!.update![0]!.data } as typeof duct + expect(resized.path[0]![1] + (resized.height * 0.0254) / 2).toBeCloseTo( + (duct.height * 0.0254) / 2, + 8, + ) + expect(duct.path[0]![1]).toBe(0) +}) + +test('branch resize follows an elbow and keeps the two collars joined', () => { + const elbow = DuctFittingNode.parse({ + parentId: level.id, + fittingType: 'elbow', + shape: 'round', + diameter: 6, + position: [3, 0, 0], + rotation: [0, 0, 0], + }) + const a = run({ + path: [ + [0, 0, 0], + [2.8095, 0, 0], + ], + }) + const b = run({ + path: [ + [3, 0, 0.1905], + [3, 0, 4], + ], + }) + const result = edit( + scene(a, b, elbow), + { nodeId: a.id, action: 'resize', scope: 'branch', diameter: 10 }, + context, + ) + const after = scene(a, b, elbow) + for (const update of result.changes!.update!) + after[update.id] = { ...after[update.id], ...update.data } as AnyNode + expect(result.changes!.update).toHaveLength(3) + expect((after[b.id] as typeof b).diameter).toBe(10) + const ports = ductFittingDefinition.ports!(after[elbow.id] as typeof elbow) + expect((after[a.id] as typeof a).path[1]).toEqual([...ports[0]!.position]) + expect((after[b.id] as typeof b).path[0]).toEqual([...ports[1]!.position]) +}) + +test('segment resize inserts a transition while leaving its neighbour fixed', () => { + const a = run({ + path: [ + [0, 0, 0], + [3, 0, 0], + ], + }) + const b = run({ + path: [ + [3, 0, 0], + [6, 0, 0], + ], + }) + const result = edit(scene(a, b), { nodeId: b.id, action: 'resize', diameter: 10 }, context) + expect(result.changes!.update!.map((entry) => entry.id)).toEqual([b.id]) + const adapter = result.changes!.create![0]!.node as typeof DuctFittingNode._output + expect(adapter.fittingType).toBe('reducer') + const ports = ductFittingDefinition.ports!(adapter) + expect([...ports[0]!.position]).toEqual(a.path[1]!) + expect((result.changes!.update![0]!.data as typeof b).path[0]).toEqual([...ports[1]!.position]) +}) + +test('branch resize stops at a tee without resizing its other branches', () => { + const tee = DuctFittingNode.parse({ + parentId: level.id, + fittingType: 'tee', + shape: 'round', + diameter: 6, + position: [0, 0, 0], + }) + const duct = run({ + path: [ + [0.1905, 0, 0], + [6, 0, 0], + ], + }) + const result = edit( + scene(duct, tee), + { nodeId: duct.id, action: 'resize', scope: 'branch', diameter: 10 }, + context, + ) + expect(result.changes!.update!.map((entry) => entry.id)).toEqual([duct.id]) + expect(result.changes!.create).toHaveLength(1) +}) + +test('face alignment refuses connected runs rather than separating collars', () => { + const a = run({ + path: [ + [0, 0, 0], + [3, 0, 0], + ], + }) + const b = run({ + path: [ + [3, 0, 0], + [6, 0, 0], + ], + }) + expect(() => + edit(scene(a, b), { nodeId: b.id, action: 'resize', diameter: 10, alignment: 'top' }, context), + ).toThrow('Face alignment') +}) + +test('resize refuses a transition that consumes the remaining run', () => { + const a = run({ + path: [ + [0, 0, 0], + [3, 0, 0], + ], + }) + const b = run({ + path: [ + [3, 0, 0], + [3.2, 0, 0], + ], + }) + expect(() => + edit(scene(a, b), { nodeId: b.id, action: 'resize', diameter: 10 }, context), + ).toThrow('Not enough straight duct') +}) + +for (const offset of [1, -1]) + test(`obstacle offset ${offset} keeps original endpoints and joins every new collar`, () => { + const duct = run() + const result = edit( + scene(duct), + { nodeId: duct.id, action: 'offset', offset, from: 1, to: 4 }, + context, + ) + const first = { ...duct, ...result.changes!.update![0]!.data } as typeof duct + const created = result.changes!.create!.map((entry) => entry.node) + const ducts = [first, ...created.filter((node) => node.type === 'duct-segment')] + expect(created.filter((node) => node.type === 'duct-fitting')).toHaveLength(4) + expect(first.path[0]).toEqual(duct.path[0]!) + expect(ducts.at(-1)!.path[1]).toEqual(duct.path[1]!) + expect(ducts[2]!.path[0]![1]).toBe(offset) + const ports = [first, ...created].flatMap((node) => + nodeRegistry.get(node.type)!.ports!(node).map((port) => ({ ...port, nodeId: node.id })), + ) + const open = ports.filter( + (port) => + !ports.some( + (other) => + other.nodeId !== port.nodeId && + Math.hypot(...port.position.map((n, i) => n - other.position[i]!)) < 1e-6, + ), + ) + expect(open).toHaveLength(2) + }) + +test('offset refuses insufficient space without mutating the scene', () => { + const duct = run() + const nodes = scene(duct) + const before = JSON.stringify(nodes) + expect(() => + edit(nodes, { nodeId: duct.id, action: 'offset', offset: 0.1, from: 1, to: 4 }, context), + ).toThrow('Allow') + expect(JSON.stringify(nodes)).toBe(before) +}) + +test('nearby ducts on a different level are not resized', () => { + const duct = run() + const other = run({ + parentId: LevelNode.parse({}).id, + path: [ + [6, 0, 0], + [9, 0, 0], + ], + }) + const result = edit( + scene(duct, other), + { nodeId: duct.id, action: 'resize', scope: 'branch', diameter: 10 }, + context, + ) + expect(result.changes!.update!.map((entry) => entry.id)).toEqual([duct.id]) +}) + +test('duct offset works through MCP and undoes in one step', async () => { + const duct = run() + const root = { ...level, children: [duct.id] } + const bridge = new SceneBridge() + bridge.setScene(scene(root, duct), [level.id]) + bridge.clearHistory() + const server = new McpServer({ name: 'duct-test', version: '0.0.0' }) + const contract = builtinAgentTools.tools.find((tool) => tool.name === 'duct_edit')! + registerOperationTool(server, createSceneOperations({ bridge }), { + contract, + operation: edit, + annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: false }, + }) + const client = new Client({ name: 'duct-test', version: '0.0.0' }) + const [serverTransport, clientTransport] = InMemoryTransport.createLinkedPair() + await Promise.all([server.connect(serverTransport), client.connect(clientTransport)]) + try { + const result = await client.callTool({ + name: 'duct_edit', + arguments: { nodeId: duct.id, action: 'offset', from: 1, to: 4, offset: 1 }, + }) + expect(result.isError).not.toBe(true) + expect( + Object.values(bridge.getNodes()).filter((node) => node.type === 'duct-fitting'), + ).toHaveLength(4) + bridge.undo() + expect(bridge.getNodes()[duct.id]?.path).toEqual(duct.path) + expect( + Object.values(bridge.getNodes()).filter((node) => node.type === 'duct-fitting'), + ).toHaveLength(0) + } finally { + await client.close() + await server.close() + } +}) + +test('face alignment moves automatic caps with the resized run', () => { + const duct = run({ shape: 'rect', width: 14, height: 8 }) + const cap = DuctFittingNode.parse({ + parentId: level.id, + fittingType: 'end-cap', + shape: 'rect', + width: 14, + height: 8, + position: [6.025, 0, 0], + }) + const result = edit( + scene(duct, cap), + { nodeId: duct.id, action: 'resize', height: 12, alignment: 'top' }, + context, + ) + expect(result.changes!.create).toHaveLength(0) + const resized = result.changes!.update!.find((entry) => entry.id === duct.id)!.data as typeof duct + const resizedCap = result.changes!.update!.find((entry) => entry.id === cap.id)! + .data as typeof cap + expect(resizedCap.height).toBe(12) + expect(resized.path[1]![1]).toBeCloseTo(-0.0508, 6) + expect(resizedCap.position[1]).toBeCloseTo(-0.0508, 6) +}) + +test('an obstacle offset transfers the far automatic cap to the tail section', () => { + const duct = run() + const cap = DuctFittingNode.parse({ + parentId: level.id, + fittingType: 'end-cap', + position: [6.025, 0, 0], + shape: 'round', + diameter: 6, + metadata: { automaticRunEndCapOwnerId: duct.id, automaticRunEndCapEndpoint: 'end' }, + }) + const before = scene(duct, cap) + const outcome = edit( + before, + { nodeId: duct.id, action: 'offset', from: 1, to: 5, offset: 1 }, + context, + ) + const next = { ...before } + for (const entry of outcome.changes!.create!) next[entry.node.id] = entry.node + for (const entry of outcome.changes!.update!) + next[entry.id] = { ...next[entry.id], ...entry.data } as AnyNode + const updatedCap = next[cap.id] as DuctFittingNode + expect(updatedCap.position).toEqual(cap.position) + const tail = next[updatedCap.metadata.automaticRunEndCapOwnerId as string] as DuctSegmentNode + expect(tail.id).not.toBe(duct.id) + expect(tail.path.at(-1)).toEqual(duct.path.at(-1)) + expect( + ductSegmentDefinition.parametrics!.onDeleteCascade!(tail, next, new Set(), new Set([tail.id])), + ).toContain(cap.id) +}) + +test('agent operations bundle for a headless host without editor or viewer dependencies', async () => { + const result = await Bun.build({ + entrypoints: [fileURLToPath(import.meta.resolve('@pascal-app/nodes/agent-operations'))], + target: 'bun', + write: false, + external: ['@pascal-app/core', '@pascal-app/core/*', 'three', 'zod'], + plugins: [ + { + name: 'headless-operation-boundary', + setup(build) { + build.onResolve( + { filter: /^(@pascal-app\/(viewer|editor)(\/|$)|react(-dom)?($|\/)|@react-three\/)/ }, + (args) => { + throw new Error(`Headless operations cannot load ${args.path} from ${args.importer}`) + }, + ) + }, + }, + ], + }) + expect(result.success).toBe(true) +}) + +test('duct offsets detach every split section from the original wall', () => { + const duct = run({ + wallAttachment: { + wallId: 'wall_offset_host', + side: 'front', + startUV: [0, 0], + endUV: [6, 0], + offset: 0.1, + }, + }) + const nodes = scene(duct) + const before = JSON.stringify(nodes) + const outcome = edit( + nodes, + { nodeId: duct.id, action: 'offset', from: 1, to: 4, offset: 1 }, + context, + ) + const patch = outcome.changes!.update!.find((entry) => entry.id === duct.id)!.data + const sections = [ + { ...duct, ...patch }, + ...outcome + .changes!.create!.map((entry) => entry.node) + .filter((node) => node.type === 'duct-segment'), + ] + expect(sections).toHaveLength(5) + for (const section of sections) { + expect(section.wallAttachment).toBeUndefined() + expect(section.hangerOverrides).toBeUndefined() + } + expect(JSON.stringify(nodes)).toBe(before) +}) + +test('duct offsets refuse custom hangers and hosted children without partial edits', () => { + const custom = run({ hangerOverrides: { '0:0': { fraction: 0.5 } } }) + const hosted = run() + const child = DuctFittingNode.parse({ parentId: hosted.id }) + for (const [duct, nodes] of [ + [custom, scene(custom)], + [hosted, scene(hosted, child)], + ] as const) { + const before = JSON.stringify(nodes) + expect(() => + edit(nodes, { nodeId: duct.id, action: 'offset', from: 1, to: 4, offset: 1 }, context), + ).toThrow('Remove custom hanger adjustments or hosted children') + expect(JSON.stringify(nodes)).toBe(before) + } +}) diff --git a/packages/nodes/src/agent-operations/index.ts b/packages/nodes/src/agent-operations/index.ts index 2702c42586..49aa41fd89 100644 --- a/packages/nodes/src/agent-operations/index.ts +++ b/packages/nodes/src/agent-operations/index.ts @@ -1,8 +1,18 @@ import type { AgentOperations } from '@pascal-app/core/agent-operations' import { checkKitchenClearance, finishKitchenRun } from '../cabinet/finish-operation' +import { editDuct } from '../duct-segment/edit-operation' +import { connectPipe } from '../pipe-segment/connect-operation' +import { editPipeGrade } from '../pipe-segment/grade-operation' +import { offsetPipe } from '../pipe-segment/offset-operation' +import { resizePipe } from '../pipe-segment/resize-operation' export { checkKitchenClearance, finishKitchenRun } export const builtinAgentOperations = { + pipe_connect: connectPipe, + pipe_offset: offsetPipe, + pipe_resize: resizePipe, + pipe_grade: editPipeGrade, + duct_edit: editDuct, kitchen_finish_run: finishKitchenRun, kitchen_check_clearance: checkKitchenClearance, } satisfies AgentOperations diff --git a/packages/nodes/src/agent-operations/pipe-connect.test.ts b/packages/nodes/src/agent-operations/pipe-connect.test.ts new file mode 100644 index 0000000000..34b63afb16 --- /dev/null +++ b/packages/nodes/src/agent-operations/pipe-connect.test.ts @@ -0,0 +1,161 @@ +import { afterEach, beforeEach, expect, test } from 'bun:test' +import { + type AnyNode, + LevelNode, + nodeRegistry, + type PipeFittingNode, + type PipeSegmentNode, + PipeTrapNode, + registerNode, +} from '@pascal-app/core' +import { + PipeCollarInspector, + pipeFittingDefinition, + pipeSegmentDefinition, + pipeTrapDefinition, +} from '@pascal-app/nodes' +import { builtinAgentOperations } from '@pascal-app/nodes/agent-operations' +import { createElement } from 'react' +import { renderToStaticMarkup } from 'react-dom/server' + +let restore: ReturnType +beforeEach(() => { + restore = nodeRegistry._snapshot() + registerNode(pipeSegmentDefinition) + registerNode(pipeFittingDefinition) + registerNode(pipeTrapDefinition) +}) +afterEach(() => restore()) +const level = LevelNode.parse({}) +const trap = () => + PipeTrapNode.parse({ + parentId: level.id, + position: [1, 2, 3], + rotation: Math.PI / 4, + diameter: 1.5, + pipeMaterial: 'abs', + }) +const scene = (...nodes: AnyNode[]) => Object.fromEntries([level, ...nodes].map((n) => [n.id, n])) +const edit = builtinAgentOperations.pipe_connect +const context = { activeLevelId: level.id } +const endpoint = (node: PipeTrapNode, portId = 'outlet', length = 2) => { + const port = pipeTrapDefinition.ports!(node).find((p) => p.id === portId)! + return port.position.map((v, i) => v + length * port.direction[i]!) as [number, number, number] +} +test('connects a rotated trap outlet using its profile and leaves the trap unchanged', () => { + const node = trap(), + nodes = scene(node), + before = JSON.stringify(nodes) + const result = edit(nodes, { nodeId: node.id, portId: 'outlet', end: endpoint(node) }, context) + expect(JSON.stringify(nodes)).toBe(before) + expect(result.changes!.update).toBeUndefined() + const pipe = result + .changes!.create!.map((entry) => entry.node) + .find((n): n is PipeSegmentNode => n.type === 'pipe-segment')! + expect(pipe.path[0]).toEqual([...pipeTrapDefinition.ports!(node)[1]!.position]) + expect(pipe.diameter).toBe(1.5) + expect(pipe.pipeMaterial).toBe('abs') + expect(pipe.parentId).toBe(level.id) + expect(result.result.reducers).toBe(0) +}) +test('a larger branch inserts a reducer with coincident, opposing collars', () => { + const node = trap(), + result = edit( + scene(node), + { nodeId: node.id, portId: 'outlet', end: endpoint(node), diameter: 3 }, + context, + ) + const created = result.changes!.create!.map((entry) => entry.node) + const reducer = created.find( + (n): n is PipeFittingNode => n.type === 'pipe-fitting' && n.fittingType === 'reducer', + )! + const pipe = created.find((n): n is PipeSegmentNode => n.type === 'pipe-segment')! + const source = pipeTrapDefinition.ports!(node)[1]!, + ports = pipeFittingDefinition.ports!(reducer) + for (let i = 0; i < 3; i++) { + expect(ports[0]!.position[i]).toBeCloseTo(source.position[i]!, 10) + expect(ports[1]!.position[i]).toBeCloseTo(pipe.path[0]![i]!, 10) + } + expect(ports[0]!.direction.reduce((sum, v, i) => sum + v * source.direction[i]!, 0)).toBeCloseTo( + -1, + 10, + ) + expect(ports.map((p) => p.diameter)).toEqual([1.5, 3]) +}) +test('vertical fixture-side connections follow the inlet axis', () => { + const node = trap(), + result = edit( + scene(node), + { nodeId: node.id, portId: 'inlet', end: endpoint(node, 'inlet') }, + context, + ) + const pipe = result.changes!.create![0]!.node as PipeSegmentNode + expect(pipe.path[0]![0]).toBe(pipe.path[1]![0]) + expect(pipe.path[0]![2]).toBe(pipe.path[1]![2]) + expect(pipe.path[1]![1] - pipe.path[0]![1]).toBeCloseTo(2) +}) +test('occupied, wrong-direction, stale and cramped collars refuse atomically', () => { + const node = trap(), + nodes = scene(node) + const first = edit(nodes, { nodeId: node.id, portId: 'outlet', end: endpoint(node) }, context) + const connected = scene(node, ...first.changes!.create!.map((entry) => entry.node)) + expect(() => + edit(connected, { nodeId: node.id, portId: 'outlet', end: endpoint(node) }, context), + ).toThrow('already connected') + for (const input of [ + { nodeId: node.id, portId: 'missing', end: endpoint(node) }, + { nodeId: node.id, portId: 'outlet', end: endpoint(node, 'outlet', -2) }, + { nodeId: node.id, portId: 'outlet', end: endpoint(node, 'outlet', 0.1), diameter: 8 }, + { nodeId: node.id, portId: 'outlet', end: endpoint(node), diameter: 10 }, + ]) + expect(() => edit(nodes, input, context)).toThrow() +}) +test('the inspector exposes collar size and elevation', () => { + const node = trap() + const html = renderToStaticMarkup(createElement(PipeCollarInspector, { node })) + expect(html).toContain('Draw from collar') + expect(html).toContain('1.5 in') + expect(html).toContain('2.030 m') +}) + +test('collar connection works through MCP and undoes as one edit', async () => { + const { Client } = await import('@modelcontextprotocol/sdk/client/index.js') + const { InMemoryTransport } = await import('@modelcontextprotocol/sdk/inMemory.js') + const { McpServer } = await import('@modelcontextprotocol/sdk/server/mcp.js') + const { SceneBridge } = await import('@pascal-app/mcp/bridge') + const { createSceneOperations } = await import('@pascal-app/mcp/operations') + const { registerOperationTool } = await import('@pascal-app/mcp/tools/shared-tools') + const { builtinAgentTools } = await import('@pascal-app/nodes/agent-tools') + const run = trap() + const bridge = new SceneBridge() + bridge.setScene(scene({ ...level, children: [run.id] }, run), [level.id]) + bridge.clearHistory() + const server = new McpServer({ name: 'pipe-connect-test', version: '0.0.0' }) + registerOperationTool(server, createSceneOperations({ bridge }), { + contract: builtinAgentTools.tools.find((tool) => tool.name === 'pipe_connect')!, + operation: edit, + annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: false }, + }) + const client = new Client({ name: 'pipe-connect-test', version: '0.0.0' }) + const [serverTransport, clientTransport] = InMemoryTransport.createLinkedPair() + await Promise.all([server.connect(serverTransport), client.connect(clientTransport)]) + try { + const result = await client.callTool({ + name: 'pipe_connect', + arguments: { nodeId: run.id, portId: 'outlet', end: endpoint(run), diameter: 3 }, + }) + expect(result.isError).not.toBe(true) + expect(bridge.getNodes()[run.id]).toEqual(run) + expect( + Object.values(bridge.getNodes()).filter((node) => node.type === 'pipe-fitting'), + ).toHaveLength(2) + bridge.undo() + expect(bridge.getNodes()[run.id]).toEqual(run) + expect( + Object.values(bridge.getNodes()).filter((node) => node.type === 'pipe-fitting'), + ).toHaveLength(0) + } finally { + await client.close() + await server.close() + } +}) diff --git a/packages/nodes/src/agent-operations/pipe-grade.test.ts b/packages/nodes/src/agent-operations/pipe-grade.test.ts new file mode 100644 index 0000000000..19f4c2d31a --- /dev/null +++ b/packages/nodes/src/agent-operations/pipe-grade.test.ts @@ -0,0 +1,249 @@ +import { afterEach, beforeEach, expect, test } from 'bun:test' +import { + type AnyNode, + LevelNode, + nodeRegistry, + PipeFittingNode, + PipeSegmentNode, + registerNode, + useLiveNodeOverrides, + useScene, +} from '@pascal-app/core' +import { pipeFittingDefinition, pipeSegmentDefinition } from '@pascal-app/nodes' +import { builtinAgentOperations } from '@pascal-app/nodes/agent-operations' + +let restore: ReturnType +beforeEach(() => { + restore = nodeRegistry._snapshot() + registerNode(pipeSegmentDefinition) + registerNode(pipeFittingDefinition) +}) +const originalRaf = globalThis.requestAnimationFrame +const originalCancelRaf = globalThis.cancelAnimationFrame +beforeEach(() => { + globalThis.requestAnimationFrame = () => 0 + globalThis.cancelAnimationFrame = () => {} +}) +afterEach(() => { + restore() + globalThis.requestAnimationFrame = originalRaf + globalThis.cancelAnimationFrame = originalCancelRaf +}) +const level = LevelNode.parse({}) +const makePipe = ( + path: number[][] = [ + [0, 2, 0], + [4, 1.92, 0], + ], +) => PipeSegmentNode.parse({ parentId: level.id, path, diameter: 2, system: 'waste' }) +const scene = (...nodes: AnyNode[]) => + Object.fromEntries([level, ...nodes].map((node) => [node.id, node])) +const edit = builtinAgentOperations.pipe_grade +const context = { activeLevelId: level.id } +function editedPath(pipe: PipeSegmentNode, input: Parameters[1]) { + const result = edit(scene(pipe), input, context) + return (result.changes!.update!.find((entry) => entry.id === pipe.id)!.data as PipeSegmentNode) + .path +} + +test('changing grade can preserve either endpoint elevation', () => { + const pipe = makePipe() + const start = editedPath(pipe, { + nodeId: pipe.id, + action: 'grade', + gradePercent: 3, + anchor: 'start', + }) + expect(start[0]![1]).toBe(2) + expect(start[1]![1]).toBeCloseTo(1.88) + const end = editedPath(pipe, { nodeId: pipe.id, action: 'grade', gradePercent: 3, anchor: 'end' }) + expect(end[1]![1]).toBeCloseTo(1.92) + expect(end[0]![1]).toBeCloseTo(2.04) +}) +test('reversing downhill flow changes elevation rather than only a label', () => { + const pipe = makePipe() + expect( + editedPath(pipe, { nodeId: pipe.id, action: 'grade', gradePercent: 2, flow: 'reverse' })[1]![1], + ).toBeCloseTo(2.08) +}) +test('extending either endpoint preserves signed grade and the opposite elevation', () => { + const pipe = makePipe() + const end = editedPath(pipe, { + nodeId: pipe.id, + action: 'endpoint', + pointIndex: 1, + point: [8, 1.92, 0], + }) + expect(end[1]![1]).toBeCloseTo(1.84) + const start = editedPath(pipe, { + nodeId: pipe.id, + action: 'endpoint', + pointIndex: 0, + point: [-4, 2, 0], + }) + expect(start[0]![1]).toBeCloseTo(2.08) + expect(start[1]![1]).toBe(1.92) +}) +test('elevation edits translate every vertex without flattening mixed grades', () => { + const pipe = makePipe([ + [0, 2, 0], + [2, 1.96, 0], + [2, 1.96, 3], + ]) + const path = editedPath(pipe, { nodeId: pipe.id, action: 'elevation', elevation: 4 }) + expect(path).toEqual([ + [0, 4, 0], + [2, 3.96, 0], + [2, 3.96, 3], + ]) +}) +test('polyline edits preserve each leg grade, rather than averaging the whole run', () => { + const pipe = makePipe([ + [0, 2, 0], + [2, 1.96, 0], + [2, 1.87, 3], + ]) + const path = editedPath(pipe, { + nodeId: pipe.id, + action: 'endpoint', + pointIndex: 1, + point: [4, 1.96, 0], + }) + expect(path[1]![1]).toBeCloseTo(1.92) + expect((path[1]![1] - path[2]![1]) / Math.hypot(2, 3)).toBeCloseTo(0.03) +}) +test('vertical legs retain their height when grading a mixed route', () => { + const pipe = makePipe([ + [0, 2, 0], + [4, 2, 0], + [4, 0, 0], + ]) + const path = editedPath(pipe, { nodeId: pipe.id, action: 'grade', gradePercent: 2 }) + expect(path[1]![1]).toBeCloseTo(1.92) + expect(path[2]![1]).toBeCloseTo(-0.08) +}) +test('tilting a vertical stack is refused', () => { + const pipe = makePipe([ + [0, 2, 0], + [0, 0, 0], + ]) + expect(() => + editedPath(pipe, { nodeId: pipe.id, action: 'endpoint', pointIndex: 1, point: [1, 0, 0] }), + ).toThrow('vertical stack') +}) +test('collapsed horizontal leg and invalid grade are refused without scene mutation', () => { + const pipe = makePipe() + const nodes = scene(pipe) + const before = JSON.stringify(nodes) + expect(() => + edit(nodes, { nodeId: pipe.id, action: 'endpoint', pointIndex: 1, point: [0, 2, 0] }, context), + ).toThrow() + expect(() => + edit(nodes, { nodeId: pipe.id, action: 'grade', gradePercent: NaN }, context), + ).toThrow() + expect(JSON.stringify(nodes)).toBe(before) +}) +test('turning a connected collar is refused instead of silently breaking it', () => { + const pipe = makePipe() + const fitting = PipeFittingNode.parse({ + parentId: level.id, + fittingType: 'elbow', + position: [4.14, 1.92, 0], + diameter: 2, + }) + const ports = pipeFittingDefinition.ports!(fitting) + const inlet = ports[0]! + pipe.path[1] = [...inlet.position] + expect(() => + edit(scene(pipe, fitting), { nodeId: pipe.id, action: 'grade', gradePercent: 5 }, context), + ).toThrow('collar') +}) +test('plan-view editing previews grade without writing the scene until commit', () => { + const pipe = makePipe() + const previous = useScene.getState().nodes + useScene.setState({ nodes: scene(pipe) }) + try { + const affordance = pipeSegmentDefinition.floorplanAffordances!['move-path-point']! + const session = affordance.start({ + node: pipe, + nodes: scene(pipe), + payload: { pointIndex: 1 }, + initialPlanPoint: [4, 0], + }) + session.apply({ + planPoint: [8, 0], + modifiers: { altKey: false, ctrlKey: false, metaKey: false, shiftKey: false }, + }) + expect(useScene.getState().nodes[pipe.id]).toEqual(pipe) + expect(session.canCommit()).toBe(true) + session.commit!() + const result = useScene.getState().nodes[pipe.id] as PipeSegmentNode + expect(result.path[1]![1]).toBeCloseTo(1.84) + } finally { + useLiveNodeOverrides.getState().clear(pipe.id) + useScene.setState({ nodes: previous }) + } +}) + +test('grade edits carry end caps and keep both collars coincident', () => { + const pipe = makePipe([ + [0, 2, 0], + [4, 2, 0], + ]) + const cap = PipeFittingNode.parse({ + parentId: level.id, + fittingType: 'end-cap', + position: [4.025, 2, 0], + diameter: 2, + }) + cap.position[0] += 4 - pipeFittingDefinition.ports!(cap)[0]!.position[0] + const result = edit( + scene(pipe, cap), + { nodeId: pipe.id, action: 'grade', gradePercent: 2 }, + context, + ) + const path = ( + result.changes!.update!.find((entry) => entry.id === pipe.id)!.data as PipeSegmentNode + ).path + const capUpdate = result.changes!.update!.find((entry) => entry.id === cap.id)! + const nextCap = { ...cap, ...capUpdate.data } as typeof cap + const port = pipeFittingDefinition.ports!(nextCap)[0]! + expect(port.position[0]).toBeCloseTo(path[1]![0]) + expect(port.position[1]).toBeCloseTo(path[1]![1]) +}) + +test('grade tool works through MCP and undoes as one edit', async () => { + const { Client } = await import('@modelcontextprotocol/sdk/client/index.js') + const { InMemoryTransport } = await import('@modelcontextprotocol/sdk/inMemory.js') + const { McpServer } = await import('@modelcontextprotocol/sdk/server/mcp.js') + const { SceneBridge } = await import('@pascal-app/mcp/bridge') + const { createSceneOperations } = await import('@pascal-app/mcp/operations') + const { registerOperationTool } = await import('@pascal-app/mcp/tools/shared-tools') + const { builtinAgentTools } = await import('@pascal-app/nodes/agent-tools') + const pipe = makePipe() + const bridge = new SceneBridge() + bridge.setScene(scene({ ...level, children: [pipe.id] }, pipe), [level.id]) + bridge.clearHistory() + const server = new McpServer({ name: 'pipe-grade-test', version: '0.0.0' }) + registerOperationTool(server, createSceneOperations({ bridge }), { + contract: builtinAgentTools.tools.find((tool) => tool.name === 'pipe_grade')!, + operation: edit, + annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: false }, + }) + const client = new Client({ name: 'pipe-grade-test', version: '0.0.0' }) + const [serverTransport, clientTransport] = InMemoryTransport.createLinkedPair() + await Promise.all([server.connect(serverTransport), client.connect(clientTransport)]) + try { + const result = await client.callTool({ + name: 'pipe_grade', + arguments: { nodeId: pipe.id, action: 'grade', gradePercent: 3 }, + }) + expect(result.isError).not.toBe(true) + expect((bridge.getNodes()[pipe.id] as PipeSegmentNode).path[1]![1]).toBeCloseTo(1.88) + bridge.undo() + expect(bridge.getNodes()[pipe.id]?.path).toEqual(pipe.path) + } finally { + await client.close() + await server.close() + } +}) diff --git a/packages/nodes/src/agent-operations/pipe-offset.test.ts b/packages/nodes/src/agent-operations/pipe-offset.test.ts new file mode 100644 index 0000000000..3f9afa2549 --- /dev/null +++ b/packages/nodes/src/agent-operations/pipe-offset.test.ts @@ -0,0 +1,199 @@ +import { afterEach, beforeEach, expect, test } from 'bun:test' +import { + type AnyNode, + LevelNode, + nodeRegistry, + PipeFittingNode, + PipeSegmentNode, + registerNode, +} from '@pascal-app/core' +import { pipeFittingDefinition, pipeSegmentDefinition } from '@pascal-app/nodes' +import { builtinAgentOperations } from '@pascal-app/nodes/agent-operations' + +let restore: ReturnType +beforeEach(() => { + restore = nodeRegistry._snapshot() + registerNode(pipeSegmentDefinition) + registerNode(pipeFittingDefinition) +}) +afterEach(() => restore()) +const level = LevelNode.parse({}) +const makePipe = (grade = 0.02) => + PipeSegmentNode.parse({ + parentId: level.id, + path: [ + [0, 2, 0], + [6, 2 - 10 * grade, 8], + ], + diameter: 4, + pipeMaterial: 'cast-iron', + autoHangers: true, + }) +const scene = (...nodes: AnyNode[]) => + Object.fromEntries([level, ...nodes].map((node) => [node.id, node])) +const edit = builtinAgentOperations.pipe_offset +const context = { activeLevelId: level.id } +const request = (pipe: PipeSegmentNode, offset = 0.5) => ({ + nodeId: pipe.id, + from: 2, + to: 8, + offset, +}) +function nextScene(before: Record, outcome: ReturnType) { + const next = { ...before } + for (const entry of outcome.changes?.update ?? []) + next[entry.id] = { ...next[entry.id], ...entry.data } as AnyNode + for (const entry of outcome.changes?.create ?? []) next[entry.node.id] = entry.node + return next +} +const gradeOf = (run: PipeSegmentNode) => + (run.path[0]![1] - run.path[1]![1]) / + Math.hypot(run.path[1]![0] - run.path[0]![0], run.path[1]![2] - run.path[0]![2]) + +for (const grade of [0, 0.02, -0.02]) + for (const offset of [0.5, -0.5]) { + test(`offset ${offset} preserves grade ${grade} and joins every fitting collar`, () => { + const pipe = makePipe(grade), + before = scene(pipe), + snapshot = JSON.stringify(before) + const outcome = edit(before, request(pipe, offset), context) + expect(JSON.stringify(before)).toBe(snapshot) + const next = nextScene(before, outcome) + const runs = Object.values(next).filter( + (node): node is PipeSegmentNode => node.type === 'pipe-segment', + ) + const fittings = Object.values(next).filter( + (node): node is PipeFittingNode => node.type === 'pipe-fitting', + ) + expect(runs).toHaveLength(5) + expect(fittings).toHaveLength(4) + expect(runs[0]!.path[0]).toEqual(pipe.path[0]) + expect(runs.at(-1)!.path.at(-1)).toEqual(pipe.path[1]) + for (const index of [0, 2, 4]) expect(gradeOf(runs[index]!)).toBeCloseTo(grade, 10) + for (const run of runs) { + expect(run.diameter).toBe(4) + expect(run.pipeMaterial).toBe('cast-iron') + expect(run.autoHangers).toBe(true) + } + const runPorts = runs.flatMap((run) => pipeSegmentDefinition.ports!(run)) + for (const fitting of fittings) { + expect(fitting.parentId).toBe(level.id) + for (const port of pipeFittingDefinition.ports!(fitting)) { + const mates = runPorts.filter( + (other) => Math.hypot(...port.position.map((v, i) => v - other.position[i]!)) < 1e-8, + ) + expect(mates).toHaveLength(1) + expect( + port.direction.reduce((sum, v, i) => sum + v * mates[0]!.direction[i]!, 0), + ).toBeCloseTo(-1, 10) + } + } + const center = runs[2]!.path[0]! + const distance = Math.hypot(center[0], center[2]) + expect(center[1] - (2 - distance * grade)).toBeCloseTo(offset, 10) + expect(outcome.result.uphill).toBe(true) + }) + } +test('fixed caps keep their geometry and the far cap follows ownership to the new tail', () => { + const pipe = makePipe() + const cap = PipeFittingNode.parse({ + parentId: level.id, + fittingType: 'end-cap', + position: [6, 1.8, 8], + metadata: { automaticRunEndCapOwnerId: pipe.id, automaticRunEndCapEndpoint: 'end' }, + }) + const before = scene(pipe, cap), + outcome = edit(before, request(pipe), context), + next = nextScene(before, outcome) + const nextCap = next[cap.id] as PipeFittingNode + expect(nextCap.position).toEqual(cap.position) + expect(nextCap.rotation).toEqual(cap.rotation) + const tail = next[nextCap.metadata.automaticRunEndCapOwnerId as string] as PipeSegmentNode + expect(tail.id).not.toBe(pipe.id) + expect(tail.path.at(-1)).toEqual(pipe.path.at(-1)) + expect( + pipeSegmentDefinition.parametrics!.onDeleteCascade!(tail, next, new Set(), new Set([tail.id])), + ).toContain(cap.id) +}) +test('invalid, vertical, polyline and cramped offsets refuse without edits', () => { + const pipe = makePipe(), + before = scene(pipe), + snapshot = JSON.stringify(before) + for (const patch of [ + { offset: 0 }, + { offset: NaN }, + { from: -1 }, + { to: 11 }, + { from: 7 }, + { offset: 0.01 }, + { from: 0.01 }, + { from: 8, to: 2 }, + ]) { + expect(() => edit(before, { ...request(pipe), ...patch }, context)).toThrow() + expect(JSON.stringify(before)).toBe(snapshot) + } + for (const path of [ + [ + [0, 0, 0], + [0, 3, 0], + ], + [ + [0, 0, 0], + [2, 0, 0], + [4, 0, 0], + ], + ]) { + const other = PipeSegmentNode.parse({ path }) + expect(() => edit(scene(other), request(other), context)).toThrow() + } +}) +test('custom hanger positions are not silently discarded by a split', () => { + const pipe = { ...makePipe(), hangerOverrides: { '0': { fraction: 0.5 } } } + expect(() => edit(scene(pipe), request(pipe), context)).toThrow('hanger') +}) +test('vent offsets do not report a waste-flow warning', () => { + const pipe = { ...makePipe(), system: 'vent' as const } + expect(edit(scene(pipe), request(pipe), context).result.uphill).toBe(false) +}) + +test('offset tool works through MCP and undoes as one edit', async () => { + const { Client } = await import('@modelcontextprotocol/sdk/client/index.js') + const { InMemoryTransport } = await import('@modelcontextprotocol/sdk/inMemory.js') + const { McpServer } = await import('@modelcontextprotocol/sdk/server/mcp.js') + const { SceneBridge } = await import('@pascal-app/mcp/bridge') + const { createSceneOperations } = await import('@pascal-app/mcp/operations') + const { registerOperationTool } = await import('@pascal-app/mcp/tools/shared-tools') + const { builtinAgentTools } = await import('@pascal-app/nodes/agent-tools') + const run = makePipe() + const bridge = new SceneBridge() + bridge.setScene(scene({ ...level, children: [run.id] }, run), [level.id]) + bridge.clearHistory() + const server = new McpServer({ name: 'pipe-offset-test', version: '0.0.0' }) + registerOperationTool(server, createSceneOperations({ bridge }), { + contract: builtinAgentTools.tools.find((tool) => tool.name === 'pipe_offset')!, + operation: edit, + annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: false }, + }) + const client = new Client({ name: 'pipe-offset-test', version: '0.0.0' }) + const [serverTransport, clientTransport] = InMemoryTransport.createLinkedPair() + await Promise.all([server.connect(serverTransport), client.connect(clientTransport)]) + try { + const result = await client.callTool({ + name: 'pipe_offset', + arguments: request(run), + }) + expect(result.isError).not.toBe(true) + expect((bridge.getNodes()[run.id] as PipeSegmentNode).path[0]).toEqual(run.path[0]) + expect( + Object.values(bridge.getNodes()).filter((node) => node.type === 'pipe-fitting'), + ).toHaveLength(4) + bridge.undo() + expect(bridge.getNodes()[run.id]).toEqual(run) + expect( + Object.values(bridge.getNodes()).filter((node) => node.type === 'pipe-fitting'), + ).toHaveLength(0) + } finally { + await client.close() + await server.close() + } +}) diff --git a/packages/nodes/src/agent-operations/pipe-resize.test.ts b/packages/nodes/src/agent-operations/pipe-resize.test.ts new file mode 100644 index 0000000000..c86e0477aa --- /dev/null +++ b/packages/nodes/src/agent-operations/pipe-resize.test.ts @@ -0,0 +1,197 @@ +import { afterEach, beforeEach, expect, test } from 'bun:test' +import { + type AnyNode, + LevelNode, + nodeRegistry, + PipeFittingNode, + PipeSegmentNode, + PipeTrapNode, + registerNode, +} from '@pascal-app/core' +import { pipeFittingDefinition, pipeSegmentDefinition, pipeTrapDefinition } from '@pascal-app/nodes' +import { builtinAgentOperations } from '@pascal-app/nodes/agent-operations' + +let restore: ReturnType +beforeEach(() => { + restore = nodeRegistry._snapshot() + registerNode(pipeSegmentDefinition) + registerNode(pipeFittingDefinition) + registerNode(pipeTrapDefinition) +}) +afterEach(() => restore()) +const level = LevelNode.parse({}) +const pipe = (path: number[][], diameter = 2) => + PipeSegmentNode.parse({ parentId: level.id, path, diameter }) +const fitting = (fittingType: PipeFittingNode['fittingType'], rotation = [0, 0, 0]) => + PipeFittingNode.parse({ parentId: level.id, fittingType, rotation }) +const ports = (node: AnyNode) => nodeRegistry.get(node.type)!.ports!(node) +const scene = (...nodes: AnyNode[]) => Object.fromEntries([level, ...nodes].map((n) => [n.id, n])) +const edit = builtinAgentOperations.pipe_resize +const context = { activeLevelId: level.id } +const attached = (f: PipeFittingNode, portIndex: number, length = 3) => { + const p = ports(f)[portIndex]! + return pipe([[...p.position], p.position.map((v, i) => v + p.direction[i]! * length)]) +} +const nextNode = (node: AnyNode, result: ReturnType) => + ({ ...node, ...result.changes?.update?.find((entry) => entry.id === node.id)?.data }) as AnyNode + +test('branch resize carries a sloped coupling and both runs without changing grades', () => { + const joint = fitting('coupling', [0, 0, -Math.atan(0.02)]) + const a = attached(joint, 0), + b = attached(joint, 1) + const result = edit(scene(a, b, joint), { nodeId: a.id, diameter: 4, scope: 'branch' }, context) + expect(result.result.runs).toBe(2) + expect(result.changes!.create).toHaveLength(0) + const newJoint = nextNode(joint, result) + for (const [i, run] of [a, b].entries()) { + const next = nextNode(run, result) as PipeSegmentNode + expect(next.diameter).toBe(4) + expect(next.path[0]).toEqual([...ports(newJoint)[i]!.position]) + expect(next.path[1]).toEqual(run.path[1]) + const grade = (p: PipeSegmentNode) => + (p.path[0]![1] - p.path[1]![1]) / Math.abs(p.path[0]![0] - p.path[1]![0]) + expect(grade(next)).toBeCloseTo(grade(run), 10) + } +}) +test('segment scope inserts a reducer while leaving its connected fitting and neighbor fixed', () => { + const joint = fitting('coupling', [0, 0, -Math.atan(0.02)]) + const a = attached(joint, 0), + b = attached(joint, 1) + const result = edit(scene(a, b, joint), { nodeId: a.id, diameter: 4 }, context) + expect(result.result.runs).toBe(1) + expect(result.changes!.create).toHaveLength(1) + expect(nextNode(joint, result)).toEqual(joint) + expect(nextNode(b, result)).toEqual(b) + const reducer = result.changes!.create![0]!.node + const reducerPorts = ports(reducer) + for (let i = 0; i < 3; i++) + expect(reducerPorts[0]!.position[i]).toBeCloseTo(ports(joint)[0]!.position[i]!, 10) + expect(reducerPorts[1]!.position).toEqual((nextNode(a, result) as PipeSegmentNode).path[0]!) + expect(reducerPorts.map((p) => p.diameter)).toEqual([2, 4]) +}) +test('branch traversal stops at junctions and existing size changes', () => { + for (const kind of ['wye', 'sanitary-tee', 'cross', 'reducer'] as const) { + const joint = fitting(kind) + const a = attached(joint, 0), + b = attached(joint, 1) + const result = edit(scene(a, b, joint), { nodeId: a.id, diameter: 4, scope: 'branch' }, context) + expect(result.result.runs).toBe(1) + expect(nextNode(joint, result)).toEqual(joint) + expect(nextNode(b, result)).toEqual(b) + expect(result.changes!.create).toHaveLength(1) + } +}) +test('a fitting beside a different-size pipe stays fixed', () => { + const joint = fitting('coupling'), + a = attached(joint, 0), + b = { ...attached(joint, 1), diameter: 3 } + const result = edit(scene(a, b, joint), { nodeId: a.id, diameter: 4, scope: 'branch' }, context) + expect(nextNode(joint, result)).toEqual(joint) + expect(nextNode(b, result)).toEqual(b) + expect(result.changes!.create).toHaveLength(1) +}) +test('resizing caps keeps pipe endpoints fixed', () => { + const cap = fitting('end-cap', [0, 0, -Math.atan(0.02)]), + run = attached(cap, 0) + const result = edit(scene(run, cap), { nodeId: run.id, diameter: 8 }, context) + expect(result.changes!.create).toHaveLength(0) + expect((nextNode(run, result) as PipeSegmentNode).path).toEqual(run.path) + const nextCap = nextNode(cap, result) + expect((nextCap as PipeFittingNode).diameter).toBe(8) + ports(cap)[0]!.position.forEach((v, i) => { + expect(ports(nextCap)[0]!.position[i]).toBeCloseTo(v, 10) + }) +}) +test('short runs and ambiguous connections are refused without mutation', () => { + const joint = fitting('coupling'), + short = attached(joint, 0, 0.15) + const nodes = scene(joint, short), + before = JSON.stringify(nodes) + expect(() => edit(nodes, { nodeId: short.id, diameter: 8 }, context)).toThrow('straight pipe') + expect(JSON.stringify(nodes)).toBe(before) + const a = attached(joint, 0), + duplicate = attached(joint, 0) + expect(() => edit(scene(joint, a, duplicate), { nodeId: a.id, diameter: 4 }, context)).toThrow( + 'overlapping', + ) +}) +test('same size is a no-op and invalid diameters are refused', () => { + const run = pipe([ + [0, 2, 0], + [3, 1.94, 0], + ]) + expect(edit(scene(run), { nodeId: run.id, diameter: 2 }, context).changes).toBeUndefined() + for (const diameter of [NaN, Infinity, 0, 9]) + expect(() => edit(scene(run), { nodeId: run.id, diameter }, context)).toThrow() +}) + +test('trap collars stay fixed and receive a reducer', () => { + const trap = PipeTrapNode.parse({ parentId: level.id }) + const collar = ports(trap)[1]! + const run = pipe([ + [...collar.position], + collar.position.map((v, i) => v + collar.direction[i]! * 3), + ]) + const result = edit(scene(run, trap), { nodeId: run.id, diameter: 4, scope: 'branch' }, context) + expect(nextNode(trap, result)).toEqual(trap) + expect(result.changes!.create).toHaveLength(1) + ports(result.changes!.create![0]!.node)[0]!.position.forEach((v, i) => { + expect(v).toBeCloseTo(collar.position[i]!, 10) + }) +}) +test('vertical stacks resize without tilting and branch traversal includes elbows', () => { + for (const kind of ['coupling', 'elbow'] as const) { + const joint = fitting(kind, [0, 0, Math.PI / 2]) + const a = attached(joint, 0), + b = attached(joint, 1) + const result = edit(scene(a, b, joint), { nodeId: a.id, diameter: 4, scope: 'branch' }, context) + expect(result.result.runs).toBe(2) + const next = nextNode(a, result) as PipeSegmentNode + expect(next.path[0]![0]).toBeCloseTo(next.path[1]![0], 10) + expect(next.path[0]![2]).toBeCloseTo(next.path[1]![2], 10) + expect(result.changes!.create).toHaveLength(0) + } +}) + +test('resize tool works through MCP and undoes as one edit', async () => { + const { Client } = await import('@modelcontextprotocol/sdk/client/index.js') + const { InMemoryTransport } = await import('@modelcontextprotocol/sdk/inMemory.js') + const { McpServer } = await import('@modelcontextprotocol/sdk/server/mcp.js') + const { SceneBridge } = await import('@pascal-app/mcp/bridge') + const { createSceneOperations } = await import('@pascal-app/mcp/operations') + const { registerOperationTool } = await import('@pascal-app/mcp/tools/shared-tools') + const { builtinAgentTools } = await import('@pascal-app/nodes/agent-tools') + const joint = fitting('coupling') + const run = attached(joint, 0) + const bridge = new SceneBridge() + bridge.setScene(scene({ ...level, children: [run.id, joint.id] }, run, joint), [level.id]) + bridge.clearHistory() + const server = new McpServer({ name: 'pipe-resize-test', version: '0.0.0' }) + registerOperationTool(server, createSceneOperations({ bridge }), { + contract: builtinAgentTools.tools.find((tool) => tool.name === 'pipe_resize')!, + operation: edit, + annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: false }, + }) + const client = new Client({ name: 'pipe-resize-test', version: '0.0.0' }) + const [serverTransport, clientTransport] = InMemoryTransport.createLinkedPair() + await Promise.all([server.connect(serverTransport), client.connect(clientTransport)]) + try { + const result = await client.callTool({ + name: 'pipe_resize', + arguments: { nodeId: run.id, diameter: 4 }, + }) + expect(result.isError).not.toBe(true) + expect((bridge.getNodes()[run.id] as PipeSegmentNode).diameter).toBe(4) + expect( + Object.values(bridge.getNodes()).filter((node) => node.type === 'pipe-fitting'), + ).toHaveLength(2) + bridge.undo() + expect(bridge.getNodes()[run.id]).toEqual(run) + expect( + Object.values(bridge.getNodes()).filter((node) => node.type === 'pipe-fitting'), + ).toHaveLength(1) + } finally { + await client.close() + await server.close() + } +}) diff --git a/packages/nodes/src/agent-tools/contracts.test.ts b/packages/nodes/src/agent-tools/contracts.test.ts index 643c38ff9a..77a10edbcb 100644 --- a/packages/nodes/src/agent-tools/contracts.test.ts +++ b/packages/nodes/src/agent-tools/contracts.test.ts @@ -6,15 +6,24 @@ import { builtinAgentTools } from '@pascal-app/nodes/agent-tools' // The plugin's contracts are declared where core's are, including the hosted chat's sandbox, // which rejects packages that depend on Node modules: they import zod and core's types only. -test('the kitchen tool contracts reach only zod', () => { +test('the built-in tool contracts use sandbox-safe entry points', () => { const source = readFileSync(resolve(import.meta.dir, 'index.ts'), 'utf8') const runtime = [ ...source.matchAll(/^(?:import|export)\s+(?!type\s)[^'"]*?from\s+['"]([^'"]+)['"]/gm), ].map((match) => match[1]) - expect(runtime).toEqual(['zod']) + expect(runtime).toEqual(['@pascal-app/core/agent-tools', 'zod']) }) -test('the kitchen tools take no bare length and show every default', () => { - expect(bareNumberPaths(builtinAgentTools.tools)).toEqual([]) +test('the built-in tools accept unit notation for lengths and show every default', () => { + expect(bareNumberPaths(builtinAgentTools.tools)).toEqual(['pipe_grade.gradePercent']) expect(unshownDefaultPaths(builtinAgentTools.tools)).toEqual([]) }) + +test('MEP length inputs normalize unit-bearing text before operations run', () => { + const resize = builtinAgentTools.tools.find((tool) => tool.name === 'pipe_resize')! + expect(resize.input.diameter.parse('0.5 ft')).toBe(6) + const offset = builtinAgentTools.tools.find((tool) => tool.name === 'pipe_offset')! + expect(offset.input.offset.parse('50 cm')).toBe(0.5) + const duct = builtinAgentTools.tools.find((tool) => tool.name === 'duct_edit')! + expect(duct.input.width.parse('2 ft')).toBe(24) +}) diff --git a/packages/nodes/src/agent-tools/index.ts b/packages/nodes/src/agent-tools/index.ts index a9c78de942..297bbc0c3d 100644 --- a/packages/nodes/src/agent-tools/index.ts +++ b/packages/nodes/src/agent-tools/index.ts @@ -1,4 +1,4 @@ -import type { PluginAgentTools } from '@pascal-app/core/agent-tools' +import { measurement, type PluginAgentTools } from '@pascal-app/core/agent-tools' import { z } from 'zod' export const finishKitchenRunTool = { @@ -17,9 +17,93 @@ export const checkKitchenClearanceTool = { input: { nodeId: z.string() }, runsIn: 'operation' as const, } +export const editDuctTool = { + name: 'duct_edit' as const, + title: 'Resize or offset duct', + description: + 'Resize a duct segment or its same-profile branch through elbows, couplings, dampers and caps. Stops at junctions, profile changes and equipment; inserts transitions at fixed boundary collars. Center alignment supports connected runs; face alignment supports free straight runs. Offset adds four elbows to a straight horizontal run while preserving endpoints. from and to are bend positions measured in metres from the start; offset is signed vertical displacement in metres. Does not detect obstacles: check clearance. Refuses insufficient fitting space without partial edits. One undo step.', + input: { + nodeId: z.string(), + action: z.enum(['resize', 'offset']), + scope: z.enum(['segment', 'branch']).optional(), + alignment: z.enum(['center', 'top', 'bottom', 'left', 'right']).optional(), + shape: z.enum(['round', 'rect', 'oval']).optional(), + diameter: measurement('length', 'in').optional(), + width: measurement('length', 'in').optional(), + height: measurement('length', 'in').optional(), + offset: measurement('length', 'm').optional(), + from: measurement('length', 'm').optional(), + to: measurement('length', 'm').optional(), + }, + runsIn: 'operation' as const, +} +export const pipeGradeTool = { + name: 'pipe_grade' as const, + title: 'Edit pipe grade and elevation', + description: + 'Set grade (percent fall over horizontal travel), flow direction, or an anchored elevation above the level. point is a numeric [x, y, z] tuple in level-local metres, not a unit-bearing length string. Endpoint edits preserve each existing leg grade; vertical elevation edits translate the run. Vertical legs retain their rise. Refuses edits that would regrade connected pipes or move fixed equipment. One undo step.', + input: { + nodeId: z.string(), + action: z.enum(['grade', 'endpoint', 'elevation']), + detach: z.boolean().optional(), + gradePercent: z.number().finite().nonnegative().optional(), + flow: z.enum(['forward', 'reverse']).optional(), + anchor: z.enum(['start', 'end']).optional(), + pointIndex: z.number().int().nonnegative().optional(), + point: z.tuple([z.number().finite(), z.number().finite(), z.number().finite()]).optional(), + elevation: measurement('length', 'm').optional(), + }, + runsIn: 'operation' as const, +} +export const pipeResizeTool = { + name: 'pipe_resize' as const, + title: 'Resize connected pipe', + description: + 'Resize a segment or same-size, same-material branch through elbows, couplings and cleanouts. Stops at junctions, reducers and fixed fixture/equipment collars. Resizes caps and inserts reducers at size boundaries while preserving each leg grade. Refuses ambiguous collars or insufficient straight length without partial edits. One undo step.', + input: { + nodeId: z.string(), + diameter: measurement('length', 'in', { min: 1.25, max: 8 }), + scope: z.enum(['segment', 'branch']).optional(), + }, + runsIn: 'operation' as const, +} +export const pipeOffsetTool = { + name: 'pipe_offset' as const, + title: 'Offset pipe around obstacle', + description: + 'Add four bends to a straight non-vertical pipe, keeping both boundary collars fixed and preserving grade on the parallel sections. from and to are horizontal distances in metres from the start to the first and last bend; offset is signed vertical displacement in metres. Connectors each consume abs(offset) horizontal travel. Refuses insufficient fitting space without partial edits. Reports uphill waste connectors; this is geometric routing, not drainage or obstacle-clearance validation. One undo step.', + input: { + nodeId: z.string(), + from: measurement('length', 'm'), + to: measurement('length', 'm'), + offset: measurement('length', 'm'), + }, + runsIn: 'operation' as const, +} +export const pipeConnectTool = { + name: 'pipe_connect' as const, + title: 'Connect a pipe to a fixed collar', + description: + 'Draw from an open registered waste/vent fixture, trap or fitting collar to a free endpoint. end is a numeric [x, y, z] tuple in level-local metres, not a unit-bearing length string. Inherits diameter, material and system. The first section must follow the collar direction; add subsequent bends from the new pipe. A different diameter inserts a reducer without moving the source. Refuses occupied collars, incompatible directions and insufficient reducer space. One undo step. Ordinary catalog models without authored ports are unsupported.', + input: { + nodeId: z.string(), + portId: z.string(), + end: z.tuple([z.number().finite(), z.number().finite(), z.number().finite()]), + diameter: measurement('length', 'in', { min: 1.25, max: 8 }).optional(), + }, + runsIn: 'operation' as const, +} export const builtinAgentTools = { pluginId: 'pascal:core', apiVersion: 1, - version: '1.0.0', - tools: [finishKitchenRunTool, checkKitchenClearanceTool], + version: '1.1.1', + tools: [ + finishKitchenRunTool, + checkKitchenClearanceTool, + editDuctTool, + pipeGradeTool, + pipeResizeTool, + pipeOffsetTool, + pipeConnectTool, + ], } satisfies PluginAgentTools diff --git a/packages/nodes/src/duct-fitting/floorplan.ts b/packages/nodes/src/duct-fitting/floorplan.ts index 60f5aef436..7b5eeb21dd 100644 --- a/packages/nodes/src/duct-fitting/floorplan.ts +++ b/packages/nodes/src/duct-fitting/floorplan.ts @@ -1,6 +1,6 @@ import type { FloorplanGeometry, GeometryContext } from '@pascal-app/core' import { MeshStandardMaterial } from 'three' -import { INCHES_TO_METERS } from '../duct-segment/geometry' +import { INCHES_TO_METERS } from '../duct-segment/profile' import { accessoryFloorplan } from '../shared/accessory-floorplan' import { buildDuctAccessory } from './accessory-geometry' import { buildDuctFittingGeometry } from './geometry' diff --git a/packages/nodes/src/duct-fitting/geometry.ts b/packages/nodes/src/duct-fitting/geometry.ts index b2ef94de62..2e042b57f8 100644 --- a/packages/nodes/src/duct-fitting/geometry.ts +++ b/packages/nodes/src/duct-fitting/geometry.ts @@ -19,8 +19,8 @@ import { buildRectSection, buildSection, createDuctMaterial, - INCHES_TO_METERS, } from '../duct-segment/geometry' +import { INCHES_TO_METERS } from '../duct-segment/profile' import { buildDuctAccessory } from './accessory-geometry' import { adapterShape, localFittingPorts } from './ports' import type { DuctFittingNode } from './schema' diff --git a/packages/nodes/src/duct-fitting/selection.tsx b/packages/nodes/src/duct-fitting/selection.tsx index dfd54dd551..a81fdc4155 100644 --- a/packages/nodes/src/duct-fitting/selection.tsx +++ b/packages/nodes/src/duct-fitting/selection.tsx @@ -40,7 +40,7 @@ import { Vector3, } from 'three' import { LineBasicNodeMaterial, MeshBasicNodeMaterial } from 'three/webgpu' -import { INCHES_TO_METERS } from '../duct-segment/geometry' +import { INCHES_TO_METERS } from '../duct-segment/profile' import { autoOffsetInvalidationUpdates } from '../shared/auto-offset-tag' import { AXIS_VECTORS, diff --git a/packages/nodes/src/duct-segment/continuation.test.ts b/packages/nodes/src/duct-segment/continuation.test.ts index 0787cd3629..6d5a4371ca 100644 --- a/packages/nodes/src/duct-segment/continuation.test.ts +++ b/packages/nodes/src/duct-segment/continuation.test.ts @@ -228,3 +228,31 @@ describe('duct continuation', () => { expect(points[1]?.[1]).toBeCloseTo(2) }) }) + +test('drafting from an equipment collar inherits its section and system', async () => { + const { hvacEquipmentDefinition } = await import('@pascal-app/nodes') + const { HvacEquipmentNode } = await import('@pascal-app/core') + const restore = nodeRegistry._snapshot() + try { + registerNode(hvacEquipmentDefinition) + const equipment = HvacEquipmentNode.parse({ + equipmentType: 'air-handler', + returnShape: 'rect', + returnWidth: 20, + returnHeight: 10, + }) + const port = hvacEquipmentDefinition.ports!(equipment).find((port) => port.system === 'return')! + const seed = resolveDuctContinuationSeed( + { continuation: { nodeId: equipment.id, portId: port.id } }, + { [equipment.id]: equipment }, + ) + expect(seed?.port?.position).toEqual(port.position) + expect(seed?.port?.nodeId).toBe(equipment.id) + expect(seed?.duct.shape).toBe('rect') + expect(seed?.duct.width).toBe(20) + expect(seed?.duct.height).toBe(10) + expect(seed?.duct.system).toBe('return') + } finally { + restore() + } +}) diff --git a/packages/nodes/src/duct-segment/continuation.ts b/packages/nodes/src/duct-segment/continuation.ts index 8c79df38be..92a4c391d8 100644 --- a/packages/nodes/src/duct-segment/continuation.ts +++ b/packages/nodes/src/duct-segment/continuation.ts @@ -2,7 +2,9 @@ import { type AnyNode, type AnyNodeId, type DuctFittingNode, + DuctSegmentNode, type FloorplanAffordance, + nodeRegistry, useScene, } from '@pascal-app/core' import { useEditor } from '@pascal-app/editor' @@ -15,8 +17,7 @@ import { type RunContinuationHandlePlan, resolveDuctContinuationHandle, } from '../shared/elbow-branch-continuation' -import { ductPortDiameterIn } from './geometry' -import type { DuctSegmentNode } from './schema' +import { ductPortDiameterIn } from './profile' export type DuctEndpoint = 'start' | 'end' @@ -30,6 +31,7 @@ export type DuctContinuationSeed = { type DuctContinuationDefaults = { continuation?: { nodeId?: unknown + portId?: unknown endpoint?: unknown fittingId?: unknown segmentIndex?: unknown @@ -86,6 +88,32 @@ export function resolveDuctContinuationSeed( nodes: Record, ): DuctContinuationSeed | null { const continuation = (defaults as DuctContinuationDefaults | null)?.continuation + if (typeof continuation?.portId === 'string' && typeof continuation.nodeId === 'string') { + const source = nodes[continuation.nodeId] + const port = + source && + nodeRegistry + .get(source.type) + ?.ports?.(source) + .find((p) => p.id === continuation.portId) + if (!port || (port.system !== 'supply' && port.system !== 'return')) return null + return { + duct: DuctSegmentNode.parse({ + parentId: source.parentId, + path: [ + [...port.position], + port.position.map((value, index) => value + port.direction[index]!), + ], + shape: port.shape ?? 'round', + diameter: port.diameter, + width: port.width ?? 14, + height: port.height ?? 8, + system: port.system, + }), + port: { ...port, nodeId: source.id }, + body: null, + } + } const endpoint = continuation?.endpoint const nodeId = continuation?.nodeId if (endpoint === 'branch' && typeof nodeId === 'string') { @@ -145,6 +173,9 @@ export function activateDuctBranch( if (!segment || !next) return const editor = useEditor.getState() editor.setToolDefaults('duct-segment', { + ...editor.toolDefaults['duct-segment'], + routingMode: 'surface', + crossingMode: 'connect', continuation: { nodeId: duct.id, endpoint: 'branch', segmentIndex, point }, shape: duct.shape, diameter: duct.diameter, @@ -168,6 +199,9 @@ export function activateDuctContinuation( if (!ductEndpointPort(duct, endpoint)) return const editor = useEditor.getState() editor.setToolDefaults('duct-segment', { + ...editor.toolDefaults['duct-segment'], + routingMode: 'surface', + crossingMode: 'connect', continuation: { nodeId: duct.id, endpoint, ...(fittingId ? { fittingId } : {}) }, shape: duct.shape, diameter: duct.diameter, diff --git a/packages/nodes/src/duct-segment/definition.ts b/packages/nodes/src/duct-segment/definition.ts index e39730bf8e..b56c7794fd 100644 --- a/packages/nodes/src/duct-segment/definition.ts +++ b/packages/nodes/src/duct-segment/definition.ts @@ -3,10 +3,12 @@ import { ductBodyPaint } from '../shared/duct-body-paint' import { createPathPointMoveAffordance } from '../shared/path-point-affordance' import { createSegmentMoveAffordance } from '../shared/path-segment-affordance' import { createRunHangerToolHint } from '../shared/run-hanger-mode' +import { ductRunToolOptions } from '../shared/run-tool-options' import { ductBranchAffordance, ductContinuationAffordance } from './continuation' import { buildDuctSegmentFloorplan } from './floorplan' -import { buildDuctSegmentGeometry, ductPortDiameterIn } from './geometry' +import { buildDuctSegmentGeometry } from './geometry' import { ductSegmentParametrics } from './parametrics' +import { ductPortDiameterIn } from './profile' import { DuctSegmentNode } from './schema' /** @@ -174,6 +176,7 @@ export const ductSegmentDefinition: NodeDefinition = { }, tool: () => import('./tool'), + toolOptions: ductRunToolOptions, toolHints: [ { key: 'Click', label: 'Start segment' }, { key: 'Click again', label: 'Place and continue' }, diff --git a/packages/nodes/src/duct-segment/draw-plan.test.ts b/packages/nodes/src/duct-segment/draw-plan.test.ts index 3effbcc3df..a881ceb2b4 100644 --- a/packages/nodes/src/duct-segment/draw-plan.test.ts +++ b/packages/nodes/src/duct-segment/draw-plan.test.ts @@ -1,5 +1,6 @@ import { expect, test } from 'bun:test' -import { DuctSegmentNode, useScene } from '@pascal-app/core' +import { DuctSegmentNode, HvacEquipmentNode, useScene } from '@pascal-app/core' +import { getHvacEquipmentPorts } from '../hvac-equipment/ports' import { ductSurfaceClearanceM, planDuctDraw } from './tool' const profile = { shape: 'round' as const, diameter: 6, width: 12, height: 8 } @@ -90,3 +91,99 @@ test('a short branch reports failure instead of omitting its tee', () => { useScene.setState({ nodes: original }) } }) + +test('cross without joining leaves the trunk intact while connect inserts a cross', () => { + const trunk = DuctSegmentNode.parse({ + parentId: 'level_test', + shape: 'round', + path: [ + [0, 2, -3], + [0, 2, 3], + ], + }) + const previous = useScene.getState().nodes + const nodes = { [trunk.id]: trunk } + useScene.setState({ nodes }) + const surface = { + kind: 'surface' as const, + levelId: 'level_test' as const, + frame: { + origin: [0, 2, 0] as [number, number, number], + normal: [0, 1, 0] as [number, number, number], + tangent: [1, 0, 0] as [number, number, number], + bitangent: [0, 0, 1] as [number, number, number], + }, + } + try { + const connected = planDuctDraw( + [-3, 2, 0], + [3, 2, 0], + null, + null, + null, + null, + profile, + nodes, + surface, + ) + expect(connected?.validationMessage).toBeNull() + expect(connected?.fittings.some((fitting) => fitting.fittingType === 'cross')).toBe(true) + expect(connected?.updates.some((update) => update.id === trunk.id)).toBe(true) + const defaults = { crossingMode: 'cross', shape: 'round' as const } + const separate = planDuctDraw( + [-3, 2, 0], + [3, 2, 0], + null, + null, + null, + null, + profile, + nodes, + surface, + false, + defaults, + ) + expect(separate?.validationMessage).toBeNull() + expect(separate?.fittings.some((fitting) => fitting.fittingType === 'cross')).toBe(false) + expect(separate?.updates.some((update) => update.id === trunk.id)).toBe(false) + expect(separate?.ducts).toHaveLength(1) + expect(useScene.getState().nodes[trunk.id]).toEqual(trunk) + } finally { + useScene.setState({ nodes: previous }) + } +}) + +test('fixed equipment collars require a straight, matching-system connection', () => { + const equipment = HvacEquipmentNode.parse({ + parentId: 'level_test', + supplyShape: 'round', + supplyDiameter: 6, + returnShape: 'round', + returnDiameter: 6, + }) + const nodes = { [equipment.id]: equipment } + for (const port of getHvacEquipmentPorts(equipment).filter((p) => p.system !== 'refrigerant')) { + const source = { ...port, nodeId: equipment.id } + const start: [number, number, number] = [...port.position] + const end = start.map((value, index) => value + port.direction[index]! * 2) as [ + number, + number, + number, + ] + const plan = planDuctDraw(start, end, source, null, null, null, profile, nodes)! + expect(plan.validationMessage).toBeNull() + expect(plan.ducts[0]!.system).toBe(port.system) + expect(plan.ducts[0]!.path[0]).toEqual(start) + const wrongAxis: [number, number, number] = [start[0], start[1], start[2] + 2] + for (const invalid of [ + planDuctDraw(start, wrongAxis, source, null, null, null, profile, nodes), + planDuctDraw(start, end, source, null, null, null, profile, nodes, null, false, { + system: port.system === 'supply' ? 'return' : 'supply', + }), + ]) { + expect(invalid?.validationMessage).toBeTruthy() + expect(invalid?.ducts).toHaveLength(0) + expect(invalid?.updates).toHaveLength(0) + } + } +}) diff --git a/packages/nodes/src/duct-segment/edit-inspector.tsx b/packages/nodes/src/duct-segment/edit-inspector.tsx new file mode 100644 index 0000000000..094b868453 --- /dev/null +++ b/packages/nodes/src/duct-segment/edit-inspector.tsx @@ -0,0 +1,226 @@ +'use client' + +import { type AnyNodeId, type DuctSegmentNode, useScene } from '@pascal-app/core' +import { useMemo, useState } from 'react' +import RunHangerInspector from '../shared/run-hanger-inspector' +import { type DuctEditInput, editDuct } from './edit-operation' + +export default function DuctEditInspector({ node }: { node: DuctSegmentNode }) { + return ( + <> + + + > + ) +} + +function DuctEditForm({ node }: { node: DuctSegmentNode }) { + const nodes = useScene((state) => state.nodes) + const [input, setInput] = useState({ + nodeId: node.id, + action: 'resize', + scope: 'segment', + alignment: 'center', + shape: node.shape, + diameter: node.diameter, + width: node.width, + height: node.height, + from: 1, + to: 2, + offset: 1, + }) + const [notice, setNotice] = useState('') + const preview = useMemo(() => { + try { + return { outcome: editDuct(nodes, input, { activeLevelId: node.parentId }), error: '' } + } catch (error) { + return { + outcome: null, + error: error instanceof Error ? error.message : 'Unable to plan this edit.', + } + } + }, [nodes, input, node.parentId]) + const update = (patch: Partial) => { + setInput((previous) => ({ ...previous, ...patch })) + setNotice('') + } + const numberField = ( + key: 'diameter' | 'width' | 'height' | 'from' | 'to' | 'offset', + label: string, + ) => ( + + {label} + update({ [key]: event.target.valueAsNumber })} + /> + + ) + const changes = preview.outcome?.changes + const count = (changes?.update?.length ?? 0) + (changes?.create?.length ?? 0) + const paths = + input.action === 'offset' && changes + ? [ + ...changes + .update!.filter((entry) => entry.id === node.id) + .map((entry) => (entry.data as DuctSegmentNode).path), + ...changes.create!.flatMap((entry) => + entry.node.type === 'duct-segment' ? [entry.node.path] : [], + ), + ] + : [] + const length = Math.hypot(...node.path[1]!.map((v, i) => v - node.path[0]![i]!)) + const elevation = Math.max(Math.abs(input.offset ?? 1), 0.1) + const project = (point: number[]) => { + const along = + point.reduce( + (sum, value, i) => + sum + (value - node.path[0]![i]!) * (node.path[1]![i]! - node.path[0]![i]!), + 0, + ) / (length || 1) + const baseline = (input.offset ?? 0) > 0 ? 90 : 26 + return `${16 + (along / (length || 1)) * 228},${baseline - ((point[1]! - node.path[0]![1]) / elevation) * 64}` + } + return ( + + Edit duct route + update({ action: event.target.value as DuctEditInput['action'] })} + > + Resize with connections + Offset around obstacle + + {input.action === 'resize' ? ( + <> + update({ scope: event.target.value as DuctEditInput['scope'] })} + > + This segment + Connected same-size branch + + + Branch stops at junctions, size changes and equipment. Boundary collars stay fixed. + + update({ shape: event.target.value as DuctEditInput['shape'] })} + > + Round + Rectangular + Oval + + {input.shape === 'round' ? ( + numberField('diameter', 'Diameter (in)') + ) : ( + <> + {numberField('width', 'Width (in)')} + {numberField('height', 'Height (in)')} + > + )} + + update({ alignment: event.target.value as DuctEditInput['alignment'] }) + } + > + Keep centerline + Keep top face + Keep bottom face + Keep left face + Keep right face + + + Face alignment applies to free straight runs. Left and right follow the run’s section + axes. + + > + ) : ( + <> + {numberField('from', 'First bend from start (m)')} + {numberField('to', 'Last bend from start (m)')} + {numberField('offset', 'Vertical offset (m)')} + + Positive moves up; negative moves down. Four elbows preserve both endpoints. Check the + obstacle’s clearance; this does not detect collisions. + + > + )} + {paths.length > 0 && ( + + + Offset side elevation preview + + + + + Side elevation · dashed line is the original route + + + )} + + {preview.error || + `${changes?.update?.length ?? 0} existing parts affected · ${changes?.create?.length ?? 0} new parts`} + + { + try { + const outcome = editDuct(useScene.getState().nodes, input, { + activeLevelId: node.parentId, + }) + const plan = outcome.changes + if (plan) + useScene.getState().applyNodeChanges({ + create: plan.create?.map((entry) => ({ + ...entry, + parentId: entry.parentId as AnyNodeId | undefined, + })), + update: plan.update?.map((entry) => ({ ...entry, id: entry.id as AnyNodeId })), + }) + setNotice(String(outcome.result.message)) + } catch (error) { + setNotice(error instanceof Error ? error.message : 'Unable to apply edit.') + } + }} + > + Apply {input.action === 'resize' ? 'resize' : 'offset'} + + {notice && {notice}} + + ) +} diff --git a/packages/nodes/src/duct-segment/edit-operation.ts b/packages/nodes/src/duct-segment/edit-operation.ts new file mode 100644 index 0000000000..1811562d19 --- /dev/null +++ b/packages/nodes/src/duct-segment/edit-operation.ts @@ -0,0 +1,351 @@ +import { + type AnyNode, + type AnyNodeId, + DuctFittingNode, + DuctSegmentNode, + nodeRegistry, +} from '@pascal-app/core' +import type { AgentOperation, SceneChanges, SceneNodes } from '@pascal-app/core/agent-operations' +import { refuse } from '@pascal-app/core/agent-tools' +import type { ScenePort } from '@pascal-app/editor/distribution' +import { Vector3 } from 'three' +import { fittingLegLength, getDuctFittingPorts } from '../duct-fitting/ports' +import { type DuctProfile, planElbowAtPort, profileDiameterIn } from '../shared/auto-fitting' +import { autoOffsetInvalidationUpdates } from '../shared/auto-offset-tag' +import { transferRunEndCapOwnership } from '../shared/automatic-run-end-cap' +import { ductProfilesMatch, planDuctAdapter } from '../shared/duct-adapter' +import { rectSectionAxes, rollToContinueAcrossElbow } from './profile' + +type Point = [number, number, number] +export type DuctEditInput = { + nodeId: string + action: 'resize' | 'offset' + scope?: 'segment' | 'branch' + alignment?: 'center' | 'top' | 'bottom' | 'left' | 'right' + shape?: 'round' | 'rect' | 'oval' + diameter?: number + width?: number + height?: number + offset?: number + from?: number + to?: number +} + +function portsOf(node: AnyNode): ScenePort[] { + const definition = nodeRegistry.get(node.type) + if (!definition?.ports) return [] + return definition.ports(node).map((port) => ({ ...port, nodeId: node.id })) +} +const distance = (a: readonly number[], b: readonly number[]) => + Math.hypot(a[0]! - b[0]!, a[1]! - b[1]!, a[2]! - b[2]!) +function mates(port: ScenePort, ports: ScenePort[]): ScenePort[] { + return ports.filter( + (other) => + other.nodeId !== port.nodeId && + other.system === port.system && + distance(port.position, other.position) < 0.005 && + new Vector3(...port.direction).dot(new Vector3(...other.direction)) < -0.99, + ) +} +function profileOf(node: AnyNode, port: ScenePort): DuctProfile { + if (node.type === 'duct-segment') return node + return { + shape: port.shape ?? 'round', + diameter: port.diameter, + width: port.width ?? port.diameter, + height: port.height ?? port.diameter, + } +} +function validPaths(before: SceneNodes, changes: SceneChanges) { + for (const entry of changes.update ?? []) { + const old = before[entry.id] + if (old?.type !== 'duct-segment' || !('path' in entry.data) || !entry.data.path) continue + const path = entry.data.path as Point[] + for (let i = 1; i < path.length; i++) { + const original = new Vector3(...old.path[i]!).sub(new Vector3(...old.path[i - 1]!)) + const next = new Vector3(...path[i]!).sub(new Vector3(...path[i - 1]!)) + if (next.length() < 0.08 || next.dot(original) <= 0) + refuse( + 'duct_clearance', + 'Not enough straight duct for the fittings. Use a longer run or a smaller size change.', + ) + } + } +} + +/** One plan is used by the inspector and agent hosts; neither writes a partial network. */ +export const editDuct: AgentOperation = (before, input) => { + const duct = before[input.nodeId] + if (duct?.type !== 'duct-segment') return refuse('duct_not_found', 'Select a duct run.') + if (!nodeRegistry.get('duct-segment')?.ports) + return refuse('node_capability_unavailable', 'Register duct node definitions before editing.') + const changes: SceneChanges = { create: [], update: [] } + if (input.action === 'offset') { + if ( + Object.values(before).some((node) => node.parentId === duct.id) || + Object.keys(duct.hangerOverrides ?? {}).length + ) + return refuse( + 'duct_offset_attachments', + 'Remove custom hanger adjustments or hosted children before splitting this run.', + ) + const { offset = 0, from = 0, to = 0 } = input + if ( + ![offset, from, to].every(Number.isFinite) || + duct.path.length !== 2 || + Math.abs(duct.path[0]![1] - duct.path[1]![1]) > 0.001 + ) + return refuse('duct_offset_route', 'Choose a straight horizontal run for an obstacle offset.') + const start = new Vector3(...duct.path[0]!) + const end = new Vector3(...duct.path[1]!) + const axis = end.clone().sub(start).normalize() + const length = start.distanceTo(end) + const leg = fittingLegLength(profileDiameterIn(duct)) + if ( + from < leg + 0.08 || + to > length - leg - 0.08 || + to - from < 2 * leg + 0.08 || + Math.abs(offset) < 2 * leg + 0.08 + ) + return refuse( + 'duct_offset_clearance', + `Allow ${(2 * leg + 0.08).toFixed(2)} m for the rise and offset span, and ${(leg + 0.08).toFixed(2)} m at each end.`, + ) + const up = new Vector3(0, Math.sign(offset), 0) + const a = start.clone().addScaledVector(axis, from) + const b = a.clone().add(new Vector3(0, offset, 0)) + const d = start.clone().addScaledVector(axis, to) + const c = d.clone().add(new Vector3(0, offset, 0)) + const corners = [a, b, c, d] + const incoming = [axis, up, axis, up.clone().negate()] + const outgoing = [up, axis, up.clone().negate(), axis] + const elbows = corners.map( + (corner, i) => + planElbowAtPort( + { + id: 'end', + nodeId: duct.id, + position: corner.toArray(), + direction: incoming[i]!.toArray(), + diameter: profileDiameterIn(duct), + system: duct.system, + }, + outgoing[i]!.toArray(), + duct, + )!, + ) + const paths: Point[][] = [ + [start.toArray(), elbows[0]!.trimmedPortPoint], + [elbows[0]!.collarPoint, elbows[1]!.trimmedPortPoint], + [elbows[1]!.collarPoint, elbows[2]!.trimmedPortPoint], + [elbows[2]!.collarPoint, elbows[3]!.trimmedPortPoint], + [elbows[3]!.collarPoint, end.toArray()], + ] + // Rolled rectangular sections require a twist, which the elbow schema cannot express. + if (duct.shape !== 'round' && Math.abs(duct.roll) > 0.001) + return refuse('duct_offset_roll', 'Reset the section roll before adding an obstacle offset.') + changes.update!.push({ + id: duct.id, + data: { path: paths[0], wallAttachment: undefined, hangerOverrides: undefined }, + }) + const { id: _id, ...defaults } = duct + for (const path of paths.slice(1)) + changes.create!.push({ + node: DuctSegmentNode.parse({ + ...defaults, + metadata: {}, + wallAttachment: undefined, + hangerOverrides: undefined, + path, + roll: + duct.shape === 'round' + ? 0 + : rollToContinueAcrossElbow( + axis, + duct.roll, + axis, + new Vector3(...path[1]!).sub(new Vector3(...path[0]!)).normalize(), + ), + }), + parentId: duct.parentId ?? undefined, + }) + const tail = changes.create!.at(-1)!.node + changes.update!.push(...transferRunEndCapOwnership(before, duct.id, tail.id, 'end')) + for (const elbow of elbows) + changes.create!.push({ node: elbow.fitting, parentId: duct.parentId ?? undefined }) + } else { + const targetResult = DuctSegmentNode.safeParse({ + ...duct, + shape: input.shape ?? duct.shape, + diameter: input.diameter ?? duct.diameter, + width: input.width ?? duct.width, + height: input.height ?? duct.height, + }) + if (!targetResult.success) + return refuse( + 'duct_profile_invalid', + 'Enter duct dimensions within the supported profile range.', + ) + const target = targetResult.data + if (ductProfilesMatch(duct, target)) + return { result: { message: 'The duct already has this profile.', affected: [] }, changes } + const levelNodes = Object.values(before).filter((node) => node.parentId === duct.parentId) + const ports = levelNodes.flatMap(portsOf) + const selected = new Set([duct.id]) + for (const port of ports.filter((p) => p.nodeId === duct.id)) { + for (const mate of mates(port, ports)) { + const owner = before[mate.nodeId] + if (owner?.type === 'duct-fitting' && owner.fittingType === 'end-cap') + selected.add(owner.id) + } + } + const queue: AnyNode[] = [duct] + if (input.scope === 'branch') { + while (queue.length) { + const current = queue.shift()! + for (const port of ports.filter((p) => p.nodeId === current.id)) { + for (const mate of mates(port, ports)) { + const owner = before[mate.nodeId]! + const traversable = + owner.type === 'duct-segment' || + (owner.type === 'duct-fitting' && + ['elbow', 'coupling', 'damper', 'end-cap'].includes(owner.fittingType) && + ports + .filter((p) => p.nodeId === owner.id) + .every((p) => + mates(p, ports).every((m) => before[m.nodeId]?.type === 'duct-segment'), + )) + if ( + !selected.has(owner.id) && + traversable && + owner.system === duct.system && + ductProfilesMatch(profileOf(owner, mate), duct) + ) { + selected.add(owner.id) + queue.push(owner) + } + } + } + } + } + const alignment = input.alignment ?? 'center' + const connected = ports.some( + (port) => + port.nodeId === duct.id && + mates(port, ports).some( + (mate) => + !selected.has(mate.nodeId) || + before[mate.nodeId]?.type !== 'duct-fitting' || + (before[mate.nodeId] as DuctFittingNode).fittingType !== 'end-cap', + ), + ) + if (alignment !== 'center' && (connected || duct.path.length !== 2)) + return refuse( + 'duct_alignment_anchored', + 'Face alignment requires a free straight run. Use center alignment to keep connected collars fixed.', + ) + const updated = new Map() + for (const id of selected) { + const node = before[id]! + if (node.type === 'duct-segment') { + let path = node.path.map((p) => [...p] as Point) + if (alignment !== 'center') { + const axes = rectSectionAxes( + new Vector3(...path[1]!).sub(new Vector3(...path[0]!)).normalize(), + node.roll, + ) + if (axes.height.y < 0) axes.height.negate() + const side = alignment === 'left' || alignment === 'right' + const dimension = (p: DuctProfile) => + p.shape === 'round' ? p.diameter : side ? p.width : p.height + const sign = alignment === 'top' || alignment === 'right' ? 1 : -1 + const delta = (side ? axes.width : axes.height) + .clone() + .multiplyScalar((sign * (dimension(node) - dimension(target)) * 0.0254) / 2) + path = path.map((p) => new Vector3(...p).add(delta).toArray()) + } + updated.set(id, { + ...node, + shape: target.shape, + diameter: target.diameter, + width: target.width, + height: target.height, + path, + ductMaterial: + node.ductMaterial === 'spiral' && target.shape !== 'round' + ? 'sheet-metal' + : node.ductMaterial, + }) + } else if (node.type === 'duct-fitting') { + updated.set( + id, + DuctFittingNode.parse({ + ...node, + shape: target.shape, + diameter: profileDiameterIn(target), + diameter2: profileDiameterIn(target), + width: target.width, + height: target.height, + }), + ) + } + } + if (alignment !== 'center') { + const resized = updated.get(duct.id) as DuctSegmentNode + const delta = new Vector3(...resized.path[0]!).sub(new Vector3(...duct.path[0]!)) + for (const id of selected) { + const cap = updated.get(id) + if (cap?.type === 'duct-fitting' && cap.fittingType === 'end-cap') + cap.position = new Vector3(...cap.position).add(delta).toArray() + } + } + for (const id of selected) { + const node = updated.get(id)! + if (node.type !== 'duct-segment') continue + for (const port of ports.filter((p) => p.nodeId === id)) { + const matches = mates(port, ports) + if (matches.length > 1) + return refuse( + 'duct_connection_ambiguous', + 'More than one collar shares an endpoint. Resolve the connection before resizing.', + ) + const mate = matches[0] + if (!mate) continue + const owner = before[mate.nodeId]! + let point: Point = [...port.position] + if (selected.has(owner.id)) { + const changed = updated.get(owner.id)! + if (changed.type === 'duct-fitting') + point = [...getDuctFittingPorts(changed).find((p) => p.id === mate.id)!.position] + } else { + const adapter = planDuctAdapter(mate, profileOf(owner, mate), target) + if (adapter) { + changes.create!.push({ node: adapter.fitting, parentId: duct.parentId ?? undefined }) + point = adapter.collarPoint + } + } + node.path[port.id === 'start' ? 0 : node.path.length - 1] = point + } + } + for (const [id, node] of updated) changes.update!.push({ id, data: node }) + validPaths(before, changes) + } + const touched = changes.update!.map((entry) => entry.id as AnyNodeId) + const invalidations = touched.flatMap((id) => autoOffsetInvalidationUpdates({ ...before }, id)) + for (const entry of invalidations) { + const existing = changes.update!.find((update) => update.id === entry.id) + if (existing) existing.data = { ...existing.data, ...entry.data } as Partial + else changes.update!.push(entry) + } + return { + result: { + message: + input.action === 'offset' + ? 'Offset with four elbows; original end connections stay fixed. Check obstacle clearance before applying.' + : 'Ducts resized; boundary collars stay fixed with transitions where needed.', + affected: changes.update!.map((entry) => entry.id), + created: changes.create!.length, + }, + changes, + } +} diff --git a/packages/nodes/src/duct-segment/floorplan.ts b/packages/nodes/src/duct-segment/floorplan.ts index 66cee29600..e3e815f275 100644 --- a/packages/nodes/src/duct-segment/floorplan.ts +++ b/packages/nodes/src/duct-segment/floorplan.ts @@ -1,7 +1,7 @@ import type { FloorplanGeometry, FloorplanPoint, GeometryContext } from '@pascal-app/core' import { runHangerFloorplan } from '../shared/run-hangers' import { ductContinuationHandlePlan, ductEndpointPort } from './continuation' -import { INCHES_TO_METERS } from './geometry' +import { INCHES_TO_METERS } from './profile' import type { DuctSegmentNode } from './schema' const SUPPLY_CENTERLINE = '#d4825a' diff --git a/packages/nodes/src/duct-segment/geometry.ts b/packages/nodes/src/duct-segment/geometry.ts index 8eec23845b..3c92463304 100644 --- a/packages/nodes/src/duct-segment/geometry.ts +++ b/packages/nodes/src/duct-segment/geometry.ts @@ -24,9 +24,9 @@ import { Vector3, } from 'three' import { buildRunHangers } from '../shared/run-hangers' +import { INCHES_TO_METERS, rectSectionAxes } from './profile' import type { DuctSegmentNode } from './schema' -export const INCHES_TO_METERS = 0.0254 // Insulation wraps the duct in a roughly uniform shell. A strictly physical // mapping (fiberglass ≈ R-3.2 per inch) makes low R-values nearly invisible // at screen scale — R-1 would add only ~8 mm over a 15 cm duct. So the shell @@ -45,96 +45,8 @@ function pickInsulationThickness(r: number): number { const SUPPLY_COLOR = '#d4825a' const RETURN_COLOR = '#5a8ad4' -const RADIAL_SEGMENTS = 24 - const UP = new Vector3(0, 1, 0) - -/** - * Area-equivalent round diameter (inches) for a rect cross-section — - * what a rect trunk advertises on its ports so round fittings / branches - * mate at a sensible size. - */ -export function equivalentDiameterIn(widthIn: number, heightIn: number): number { - return 2 * Math.sqrt((widthIn * heightIn) / Math.PI) -} - -/** - * Area-equivalent round diameter (inches) for a flat-oval cross-section: - * a rectangle of (width − height) × height plus the two semicircular caps. - */ -export function ovalEquivalentDiameterIn(widthIn: number, heightIn: number): number { - const minor = Math.min(widthIn, heightIn) - const major = Math.max(widthIn, heightIn) - const area = (major - minor) * minor + Math.PI * (minor / 2) ** 2 - return 2 * Math.sqrt(area / Math.PI) -} - -/** The diameter (inches) a duct segment presents at its ports. */ -export function ductPortDiameterIn(node: { - shape?: 'round' | 'rect' | 'oval' - diameter: number - width?: number - height?: number -}): number { - if (node.shape === 'rect' && node.width && node.height) { - return equivalentDiameterIn(node.width, node.height) - } - if (node.shape === 'oval' && node.width && node.height) { - return ovalEquivalentDiameterIn(node.width, node.height) - } - return node.diameter -} - -/** - * Cross-section axes for a rect run along `dir`, rolled `roll` radians - * about the run direction. At roll 0: width is the horizontal axis - * (UP × dir) and height the vertical one — vertical runs, where that - * cross product degenerates, fall back to world X/Z. `roll` rotates the - * pair in the plane perpendicular to `dir`, letting a riser carry the - * orientation of the run it turned off instead of the bare fallback. - */ -export function rectSectionAxes(dir: Vector3, roll = 0): { width: Vector3; height: Vector3 } { - const d = dir.clone().normalize() - const xBase = new Vector3().crossVectors(UP, d) - if (xBase.lengthSq() < 1e-8) xBase.set(1, 0, 0) - xBase.normalize() - const zBase = new Vector3().crossVectors(xBase, d) - const c = Math.cos(roll) - const s = Math.sin(roll) - const width = xBase.clone().multiplyScalar(c).addScaledVector(zBase, s) - const height = xBase.clone().multiplyScalar(-s).addScaledVector(zBase, c) - return { width, height } -} - -/** - * Roll (radians) that keeps a rect cross-section continuous across an - * elbow: the dimension lying along the joint's hinge — the bend-plane - * normal `portDir × newDir`, perpendicular to both legs — must stay on - * the same physical face on the new run as on the source run. Returns 0 - * for an in-plane (degenerate-normal) joint, so horizontal turns keep - * the natural width-horizontal orientation. - */ -export function rollToContinueAcrossElbow( - sourceDir: Vector3, - sourceRoll: number, - portDir: Vector3, - newDir: Vector3, -): number { - const n = new Vector3().crossVectors(portDir, newDir) - if (n.lengthSq() < 1e-8) return 0 - n.normalize() - const src = rectSectionAxes(sourceDir, sourceRoll) - const carriesWidth = Math.abs(src.width.dot(n)) >= Math.abs(src.height.dot(n)) - const d = newDir.clone().normalize() - const xBase = new Vector3().crossVectors(UP, d) - if (xBase.lengthSq() < 1e-8) xBase.set(1, 0, 0) - xBase.normalize() - const zBase = new Vector3().crossVectors(xBase, d) - // Place the hinge-aligned face on the same axis the source carries it. - return carriesWidth - ? Math.atan2(n.dot(zBase), n.dot(xBase)) - : Math.atan2(-n.dot(xBase), n.dot(zBase)) -} +const RADIAL_SEGMENTS = 24 /** * Rect box spanning `start`→`end`. Orientation comes from `rectSectionAxes` diff --git a/packages/nodes/src/duct-segment/move-tool.tsx b/packages/nodes/src/duct-segment/move-tool.tsx index 256ad6b9b2..a5256943c2 100644 --- a/packages/nodes/src/duct-segment/move-tool.tsx +++ b/packages/nodes/src/duct-segment/move-tool.tsx @@ -42,7 +42,7 @@ import { type RunTranslationOffsetPlan, } from '../shared/run-translation-offset' import { translateWallRun } from '../shared/wall-run-move' -import { rectSectionAxes } from './geometry' +import { rectSectionAxes } from './profile' type Vec3 = [number, number, number] diff --git a/packages/nodes/src/duct-segment/parametrics.ts b/packages/nodes/src/duct-segment/parametrics.ts index 4a4fbfec5f..1afa80f6f7 100644 --- a/packages/nodes/src/duct-segment/parametrics.ts +++ b/packages/nodes/src/duct-segment/parametrics.ts @@ -3,7 +3,7 @@ import { Vector3 } from 'three' import { getDuctFittingPorts } from '../duct-fitting/ports' import { findAutomaticRunEndCapIds } from '../shared/automatic-run-end-cap' import { fittingDeletionPlansForRun } from '../shared/fitting-deletion-cleanup' -import { rollToContinueAcrossElbow } from './geometry' +import { rollToContinueAcrossElbow } from './profile' import type { DuctSegmentNode } from './schema' /** A run endpoint sitting this close to a collar counts as mated. */ @@ -112,7 +112,7 @@ export const ductSegmentParametrics: ParametricDescriptor = { plan.deleteFitting ? [plan.fittingId, ...plan.cascadeDeleteIds] : [], ), ], - trailingSection: () => import('../shared/run-hanger-inspector'), + trailingSection: () => import('./edit-inspector'), groups: [ { label: 'Hangers', @@ -157,39 +157,6 @@ export const ductSegmentParametrics: ParametricDescriptor = { options: ['supply', 'return'], display: 'segmented', }, - { - key: 'shape', - kind: 'enum', - options: ['round', 'rect', 'oval'], - display: 'segmented', - }, - { - key: 'diameter', - kind: 'number', - unit: 'in', - min: 4, - max: 24, - step: 1, - visibleIf: (n) => n.shape === 'round', - }, - { - key: 'width', - kind: 'number', - unit: 'in', - min: 4, - max: 60, - step: 1, - visibleIf: (n) => n.shape !== 'round', - }, - { - key: 'height', - kind: 'number', - unit: 'in', - min: 3, - max: 40, - step: 1, - visibleIf: (n) => n.shape !== 'round', - }, ], }, { diff --git a/packages/nodes/src/duct-segment/profile.ts b/packages/nodes/src/duct-segment/profile.ts new file mode 100644 index 0000000000..b6b5a80952 --- /dev/null +++ b/packages/nodes/src/duct-segment/profile.ts @@ -0,0 +1,91 @@ +import { Vector3 } from 'three' + +export const INCHES_TO_METERS = 0.0254 +const UP = new Vector3(0, 1, 0) + +/** + * Area-equivalent round diameter (inches) for a rect cross-section — + * what a rect trunk advertises on its ports so round fittings / branches + * mate at a sensible size. + */ +export function equivalentDiameterIn(widthIn: number, heightIn: number): number { + return 2 * Math.sqrt((widthIn * heightIn) / Math.PI) +} + +/** + * Area-equivalent round diameter (inches) for a flat-oval cross-section: + * a rectangle of (width − height) × height plus the two semicircular caps. + */ +export function ovalEquivalentDiameterIn(widthIn: number, heightIn: number): number { + const minor = Math.min(widthIn, heightIn) + const major = Math.max(widthIn, heightIn) + const area = (major - minor) * minor + Math.PI * (minor / 2) ** 2 + return 2 * Math.sqrt(area / Math.PI) +} + +/** The diameter (inches) a duct segment presents at its ports. */ +export function ductPortDiameterIn(node: { + shape?: 'round' | 'rect' | 'oval' + diameter: number + width?: number + height?: number +}): number { + if (node.shape === 'rect' && node.width && node.height) { + return equivalentDiameterIn(node.width, node.height) + } + if (node.shape === 'oval' && node.width && node.height) { + return ovalEquivalentDiameterIn(node.width, node.height) + } + return node.diameter +} + +/** + * Cross-section axes for a rect run along `dir`, rolled `roll` radians + * about the run direction. At roll 0: width is the horizontal axis + * (UP × dir) and height the vertical one — vertical runs, where that + * cross product degenerates, fall back to world X/Z. `roll` rotates the + * pair in the plane perpendicular to `dir`, letting a riser carry the + * orientation of the run it turned off instead of the bare fallback. + */ +export function rectSectionAxes(dir: Vector3, roll = 0): { width: Vector3; height: Vector3 } { + const d = dir.clone().normalize() + const xBase = new Vector3().crossVectors(UP, d) + if (xBase.lengthSq() < 1e-8) xBase.set(1, 0, 0) + xBase.normalize() + const zBase = new Vector3().crossVectors(xBase, d) + const c = Math.cos(roll) + const s = Math.sin(roll) + const width = xBase.clone().multiplyScalar(c).addScaledVector(zBase, s) + const height = xBase.clone().multiplyScalar(-s).addScaledVector(zBase, c) + return { width, height } +} + +/** + * Roll (radians) that keeps a rect cross-section continuous across an + * elbow: the dimension lying along the joint's hinge — the bend-plane + * normal `portDir × newDir`, perpendicular to both legs — must stay on + * the same physical face on the new run as on the source run. Returns 0 + * for an in-plane (degenerate-normal) joint, so horizontal turns keep + * the natural width-horizontal orientation. + */ +export function rollToContinueAcrossElbow( + sourceDir: Vector3, + sourceRoll: number, + portDir: Vector3, + newDir: Vector3, +): number { + const n = new Vector3().crossVectors(portDir, newDir) + if (n.lengthSq() < 1e-8) return 0 + n.normalize() + const src = rectSectionAxes(sourceDir, sourceRoll) + const carriesWidth = Math.abs(src.width.dot(n)) >= Math.abs(src.height.dot(n)) + const d = newDir.clone().normalize() + const xBase = new Vector3().crossVectors(UP, d) + if (xBase.lengthSq() < 1e-8) xBase.set(1, 0, 0) + xBase.normalize() + const zBase = new Vector3().crossVectors(xBase, d) + // Place the hinge-aligned face on the same axis the source carries it. + return carriesWidth + ? Math.atan2(n.dot(zBase), n.dot(xBase)) + : Math.atan2(-n.dot(xBase), n.dot(zBase)) +} diff --git a/packages/nodes/src/duct-segment/selection.tsx b/packages/nodes/src/duct-segment/selection.tsx index c1a302d1e1..23098bc6ef 100644 --- a/packages/nodes/src/duct-segment/selection.tsx +++ b/packages/nodes/src/duct-segment/selection.tsx @@ -66,7 +66,7 @@ import { type DuctEndpoint, ductContinuationHandlePlan, } from './continuation' -import { INCHES_TO_METERS } from './geometry' +import { INCHES_TO_METERS } from './profile' /** Port-snap radius for dragged run endpoints (meters, XZ). */ const PORT_SNAP_RADIUS_M = 0.4 diff --git a/packages/nodes/src/duct-segment/tool.tsx b/packages/nodes/src/duct-segment/tool.tsx index 16e6608aa7..8e5f5d9af2 100644 --- a/packages/nodes/src/duct-segment/tool.tsx +++ b/packages/nodes/src/duct-segment/tool.tsx @@ -1,6 +1,6 @@ 'use client' -import { type AnyNode, type DuctFittingNode, DuctSegmentNode } from '@pascal-app/core' +import { type AnyNode, type DuctFittingNode, DuctSegmentNode, nodeRegistry } from '@pascal-app/core' import { EDITOR_LAYER, triggerSFX, @@ -21,7 +21,7 @@ import { stepNominalRunSize, useDistributionRunTool, } from '@pascal-app/editor/distribution' -import { useEffect, useMemo, useRef, useState } from 'react' +import { useEffect, useMemo, useRef } from 'react' import { Euler, type Group, Vector3 } from 'three' import { getDuctFittingPorts } from '../duct-fitting/ports' import { @@ -43,9 +43,10 @@ import { DuctSegmentGhost, FittingGhost } from '../shared/mep-ghost' import { DUCT_PORT_SYSTEMS, runSectionHalfSizeM } from '../shared/port-systems' import { RunHangerPreview } from '../shared/run-hanger-controls' import { useRunHangerMode } from '../shared/run-hanger-mode' +import { clearRunContinuation, updateRunDefaults } from '../shared/run-tool-options' import { currentDuctContinuationSeed, ductEndpointPort } from './continuation' import { ductSegmentDefinition } from './definition' -import { rectSectionAxes, rollToContinueAcrossElbow } from './geometry' +import { rectSectionAxes, rollToContinueAcrossElbow } from './profile' /** * Continuous placement tool for duct segments. @@ -343,6 +344,34 @@ export function planDuctDraw( updates: [], delete: [], }) + const system = toolDefaults.system ?? startPort?.system ?? endPort?.system ?? 'supply' + for (const [port, away] of [ + [startPort, dir], + [endPort, [-dir[0], -dir[1], -dir[2]]], + ] as const) { + if (!port) continue + const owner = nodes[port.nodeId] + if (!owner || owner.type === 'duct-segment' || owner.type === 'duct-fitting') continue + const occupied = Object.values(nodes).some( + (node) => + node.id !== owner.id && + node.parentId === owner.parentId && + (nodeRegistry.get(node.type)?.ports?.(node) ?? []).some( + (other) => + other.system === port.system && + dist2([...other.position], [...port.position]) < 0.005 ** 2, + ), + ) + const message = + port.system !== system + ? 'Use the same supply or return system as the collar.' + : occupied + ? 'This collar is already connected.' + : new Vector3(...away).dot(new Vector3(...port.direction).normalize()) < 0.9999 + ? 'Draw the first section straight out of the collar, then add a bend from the new duct endpoint.' + : null + if (message) return { ...invalidPlan(), validationMessage: message } + } if (startPlan?.hasClearance === false || endPlan?.hasClearance === false) return invalidPlan() const startRealign = startPlan ? null : realignPlanFor(startPort, dir, nodes) const endRealign = endPlan ? null : realignPlanFor(endPort, [-dir[0], -dir[1], -dir[2]], nodes) @@ -413,11 +442,12 @@ export function planDuctDraw( if (!endTee && endTeePlan) ductEnd = endRealign?.collarPoint ?? end const realigns = [startRealign, endRealign].filter((p) => p !== null) - const crossHit = surface - ? findRunBodyCrossingSurface(start, end, BODY_SNAP_RADIUS_M, surface, { - kinds: ['duct-segment'], - }) - : null + const crossHit = + surface && (toolDefaults as Record).crossingMode !== 'cross' + ? findRunBodyCrossingSurface(start, end, BODY_SNAP_RADIUS_M, surface, { + kinds: ['duct-segment'], + }) + : null const crossOwner = crossHit ? nodes[crossHit.nodeId] : null const crossTappedElsewhere = crossHit?.nodeId === trunkBody?.nodeId || crossHit?.nodeId === endTrunkBody?.nodeId @@ -453,6 +483,7 @@ export function planDuctDraw( DuctSegmentNode.parse({ ...defaults, ...toolDefaults, + system, autoHangers, hangerStyle, name: profile.shape === 'rect' ? 'Trunk' : 'Duct run', @@ -532,29 +563,55 @@ const DuctSegmentTool = () => { const autoHangersRef = useRef(autoHangers) autoHangersRef.current = autoHangers const pendingPromotionRef = useRef(continuationSeed?.promotedFitting ?? null) - const [profile, setProfile] = useState(() => { - const defaults = ductSegmentDefinition.defaults() as DraftProfile - const seeded = useEditor.getState().toolDefaults['duct-segment'] as - | Partial - | undefined - return { - shape: continuationSeed?.duct.shape ?? seeded?.shape ?? defaults.shape, - diameter: continuationSeed?.duct.diameter ?? seeded?.diameter ?? defaults.diameter, - width: continuationSeed?.duct.width ?? seeded?.width ?? defaults.width, - height: continuationSeed?.duct.height ?? seeded?.height ?? defaults.height, - } - }) + const initialProfile = useRef(null) + if (!initialProfile.current) + initialProfile.current = (() => { + const defaults = ductSegmentDefinition.defaults() as DraftProfile + const seeded = useEditor.getState().toolDefaults['duct-segment'] as + | Partial + | undefined + return { + shape: continuationSeed?.duct.shape ?? seeded?.shape ?? defaults.shape, + diameter: continuationSeed?.duct.diameter ?? seeded?.diameter ?? defaults.diameter, + width: continuationSeed?.duct.width ?? seeded?.width ?? defaults.width, + height: continuationSeed?.duct.height ?? seeded?.height ?? defaults.height, + } + })() + const profile = useMemo( + () => ({ + shape: toolDefaults?.shape ?? initialProfile.current!.shape, + diameter: toolDefaults?.diameter ?? initialProfile.current!.diameter, + width: toolDefaults?.width ?? initialProfile.current!.width, + height: toolDefaults?.height ?? initialProfile.current!.height, + }), + [toolDefaults?.shape, toolDefaults?.diameter, toolDefaults?.width, toolDefaults?.height], + ) + const setProfile = (value: DraftProfile | ((current: DraftProfile) => DraftProfile)) => + updateRunDefaults('duct-segment', typeof value === 'function' ? value(profile) : value) const profileRef = useRef(profile) profileRef.current = profile useEffect(() => { const mode = useRunHangerMode.getState() mode.setEnabled('duct-segment', initialAutoHangersRef.current) - return () => mode.setEnabled('duct-segment', false) + return () => { + updateRunDefaults('duct-segment', { + autoHangers: useRunHangerMode.getState().enabled['duct-segment'], + }) + mode.setEnabled('duct-segment', false) + } }, []) const run = useDistributionRunTool({ active: !!activeLevelId, levelId: activeLevelId, toolName: 'duct-segment', + routingMode: + hangerDefaults?.routingMode === 'horizontal' || hangerDefaults?.routingMode === 'vertical' + ? hangerDefaults.routingMode + : 'surface', + elevation: typeof hangerDefaults?.elevation === 'number' ? hangerDefaults.elevation : 0, + targetElevation: + typeof hangerDefaults?.targetElevation === 'number' ? hangerDefaults.targetElevation : 3, + connectCrossings: hangerDefaults?.crossingMode !== 'cross', initialStart: continuationSeed ? ([...(continuationSeed.port?.position ?? continuationSeed.body?.point ?? [0, 0, 0])] as [ number, @@ -574,6 +631,15 @@ const DuctSegmentTool = () => { surfaceClearance: (surface) => surface ? ductSurfaceClearanceM(profileRef.current, surface.kind === 'wall') : 0, minimumSegmentLength: 0.08, + resolveFreeEnd: (start, end, connection) => { + const port = connection.port + const owner = port ? sceneApi.get(port.nodeId) : null + if (!port || !owner || owner.type === 'duct-segment' || owner.type === 'duct-fitting') + return end + const axis = new Vector3(...port.direction).normalize() + const distance = Math.max(0, new Vector3(...end).sub(new Vector3(...start)).dot(axis)) + return new Vector3(...start).addScaledVector(axis, distance).toArray() + }, inheritFromConnection: ({ port }) => { if (!port) return const inherited = inheritProfile(port, sceneApi.nodes()) @@ -682,14 +748,8 @@ const DuctSegmentTool = () => { }) useEffect(() => { - if (!toolDefaults) return - setProfile((current) => ({ - shape: toolDefaults.shape ?? current.shape, - diameter: toolDefaults.diameter ?? current.diameter, - width: toolDefaults.width ?? current.width, - height: toolDefaults.height ?? current.height, - })) - }, [toolDefaults]) + updateRunDefaults('duct-segment', initialProfile.current!) + }, []) const previewPlan = useMemo(() => { if (!(activeLevelId && run.start && run.cursor)) return null @@ -720,6 +780,11 @@ const DuctSegmentTool = () => { run.surfaceTarget, sceneApi, ]) + // Profile changes alter the centreline clearance even with a stationary pointer. + // biome-ignore lint/correctness/useExhaustiveDependencies: the resolver reads the profile through a ref + useEffect(() => { + run.refreshCursor() + }, [profile, run.refreshCursor]) const ghostFittings = useMemo(() => previewPlan?.fittings ?? [], [previewPlan]) useEffect(() => { @@ -734,7 +799,7 @@ const DuctSegmentTool = () => { ) }, [autoHangers, hangerStyle, ghostFittings, profile, run.cursor, run.start]) useEffect(() => () => usePathDraftPreview.getState().clear('duct-segment'), []) - useEffect(() => () => useEditor.getState().setToolDefaults('duct-segment', null), []) + useEffect(() => () => clearRunContinuation('duct-segment'), []) if (!activeLevelId) return null const extraParts = @@ -748,8 +813,32 @@ const DuctSegmentTool = () => { return ( ['reducer', 'transition'].includes(fitting.fittingType)) + .map((fitting) => { + const size = (outlet: boolean) => { + const shape = outlet + ? (fitting.outletShape ?? fitting.shape2) + : (fitting.inletShape ?? fitting.shape) + return shape === 'round' + ? `Ø${outlet ? fitting.diameter2 : fitting.diameter} in` + : `${outlet ? fitting.width2 : fitting.width} × ${outlet ? fitting.height2 : fitting.height} in ${shape}` + } + const ports = getDuctFittingPorts(fitting) + const length = new Vector3(...ports[0]!.position).distanceTo( + new Vector3(...ports[1]!.position), + ) + return `${size(false)} → ${size(true)} · ${length.toFixed(2)} m long` + }) + .join('; ') || undefined + } point={run.cursor} target={run.endConnection.port} + screen={run.snapScreen ?? run.cursorScreen} + error={ + run.cursorScreen ? (previewPlan?.validationMessage ?? run.validationMessage) : undefined + } levelId={activeLevelId} profile={{ ...profile, @@ -761,6 +850,7 @@ const DuctSegmentTool = () => { cursor={run.cursor} cursorRef={cursorRef} directionMode={run.directionMode} + routingMode={run.routingMode} extraParts={extraParts} lengthInput={run.lengthInput} onLengthInputChange={run.onLengthInputChange} diff --git a/packages/nodes/src/duct-terminal/geometry.ts b/packages/nodes/src/duct-terminal/geometry.ts index 28475dfab2..e3321e9d89 100644 --- a/packages/nodes/src/duct-terminal/geometry.ts +++ b/packages/nodes/src/duct-terminal/geometry.ts @@ -7,7 +7,8 @@ import { MeshStandardMaterial, Vector3, } from 'three' -import { createOvalSectionGeometry, INCHES_TO_METERS } from '../duct-segment/geometry' +import { createOvalSectionGeometry } from '../duct-segment/geometry' +import { INCHES_TO_METERS } from '../duct-segment/profile' import { COLLAR_LENGTH, mountQuaternion, terminalSystem } from './ports' import type { DuctTerminalNode } from './schema' diff --git a/packages/nodes/src/duct-terminal/parametrics.ts b/packages/nodes/src/duct-terminal/parametrics.ts index 4df7760ef7..d905fb9db9 100644 --- a/packages/nodes/src/duct-terminal/parametrics.ts +++ b/packages/nodes/src/duct-terminal/parametrics.ts @@ -2,6 +2,7 @@ import type { ParametricDescriptor } from '@pascal-app/core' import type { DuctTerminalNode } from './schema' export const ductTerminalParametrics: ParametricDescriptor = { + trailingSection: () => import('../shared/duct-collar-inspector'), groups: [ { label: 'Terminal', diff --git a/packages/nodes/src/duct-terminal/ports.ts b/packages/nodes/src/duct-terminal/ports.ts index c53b81f786..045dc0a068 100644 --- a/packages/nodes/src/duct-terminal/ports.ts +++ b/packages/nodes/src/duct-terminal/ports.ts @@ -1,6 +1,6 @@ import type { NodePort } from '@pascal-app/core' import { Euler, Quaternion, Vector3 } from 'three' -import { equivalentDiameterIn, ovalEquivalentDiameterIn } from '../duct-segment/geometry' +import { equivalentDiameterIn, ovalEquivalentDiameterIn } from '../duct-segment/profile' import type { DuctTerminalNode } from './schema' /** Collar stub length in meters behind the face. */ diff --git a/packages/nodes/src/hvac-equipment/floorplan.ts b/packages/nodes/src/hvac-equipment/floorplan.ts index e15b850455..4870fcd23f 100644 --- a/packages/nodes/src/hvac-equipment/floorplan.ts +++ b/packages/nodes/src/hvac-equipment/floorplan.ts @@ -1,5 +1,5 @@ import type { FloorplanGeometry, FloorplanPoint, GeometryContext } from '@pascal-app/core' -import { INCHES_TO_METERS } from '../duct-segment/geometry' +import { INCHES_TO_METERS } from '../duct-segment/profile' import { getHvacEquipmentPorts } from './ports' import type { HvacEquipmentNode } from './schema' diff --git a/packages/nodes/src/hvac-equipment/geometry.ts b/packages/nodes/src/hvac-equipment/geometry.ts index 72fb612256..bcc193e5b1 100644 --- a/packages/nodes/src/hvac-equipment/geometry.ts +++ b/packages/nodes/src/hvac-equipment/geometry.ts @@ -12,11 +12,8 @@ import { TorusGeometry, Vector3, } from 'three' -import { - createOvalSectionGeometry, - INCHES_TO_METERS, - rectSectionAxes, -} from '../duct-segment/geometry' +import { createOvalSectionGeometry } from '../duct-segment/geometry' +import { INCHES_TO_METERS, rectSectionAxes } from '../duct-segment/profile' import { localEquipmentPorts, localRefrigerantPorts } from './ports' import type { HvacEquipmentNode } from './schema' diff --git a/packages/nodes/src/hvac-equipment/parametrics.ts b/packages/nodes/src/hvac-equipment/parametrics.ts index 9130f9ed0a..db6d1557ae 100644 --- a/packages/nodes/src/hvac-equipment/parametrics.ts +++ b/packages/nodes/src/hvac-equipment/parametrics.ts @@ -2,6 +2,7 @@ import type { ParametricDescriptor } from '@pascal-app/core' import type { HvacEquipmentNode } from './schema' export const hvacEquipmentParametrics: ParametricDescriptor = { + trailingSection: () => import('../shared/duct-collar-inspector'), groups: [ { label: 'Equipment', diff --git a/packages/nodes/src/hvac-equipment/ports.ts b/packages/nodes/src/hvac-equipment/ports.ts index 9bcfb21c29..55e8262f95 100644 --- a/packages/nodes/src/hvac-equipment/ports.ts +++ b/packages/nodes/src/hvac-equipment/ports.ts @@ -1,6 +1,6 @@ import type { NodePort } from '@pascal-app/core' import { Vector3 } from 'three' -import { equivalentDiameterIn, ovalEquivalentDiameterIn } from '../duct-segment/geometry' +import { equivalentDiameterIn, ovalEquivalentDiameterIn } from '../duct-segment/profile' import type { HvacEquipmentNode } from './schema' type CollarShape = 'round' | 'rect' | 'oval' diff --git a/packages/nodes/src/index.ts b/packages/nodes/src/index.ts index 85bbe690a8..7e79d88560 100644 --- a/packages/nodes/src/index.ts +++ b/packages/nodes/src/index.ts @@ -213,6 +213,7 @@ export { createRoofGlazingPreview } from './roof/glazing-preview' export { roofSegmentDefinition } from './roof-segment' export { scanDefinition } from './scan' export { separatorDefinition } from './separator/definition' +export { default as PipeCollarInspector } from './shared/pipe-collar-inspector' export { shelfDefinition } from './shelf' export { siteDefinition } from './site' export { skylightDefinition } from './skylight' diff --git a/packages/nodes/src/lineset/floorplan.ts b/packages/nodes/src/lineset/floorplan.ts index 7de546cc1d..4d6b118bea 100644 --- a/packages/nodes/src/lineset/floorplan.ts +++ b/packages/nodes/src/lineset/floorplan.ts @@ -1,5 +1,5 @@ import type { FloorplanGeometry, FloorplanPoint, GeometryContext } from '@pascal-app/core' -import { INCHES_TO_METERS } from '../duct-segment/geometry' +import { INCHES_TO_METERS } from '../duct-segment/profile' import type { LinesetNode } from './schema' const COPPER_LINE = '#b06b3f' diff --git a/packages/nodes/src/lineset/geometry.ts b/packages/nodes/src/lineset/geometry.ts index 154a7c3e60..ab2ba5f151 100644 --- a/packages/nodes/src/lineset/geometry.ts +++ b/packages/nodes/src/lineset/geometry.ts @@ -1,5 +1,5 @@ import { CylinderGeometry, Group, Mesh, MeshStandardMaterial, SphereGeometry, Vector3 } from 'three' -import { INCHES_TO_METERS } from '../duct-segment/geometry' +import { INCHES_TO_METERS } from '../duct-segment/profile' import type { LinesetNode } from './schema' const RADIAL_SEGMENTS = 16 diff --git a/packages/nodes/src/liquid-line/floorplan.ts b/packages/nodes/src/liquid-line/floorplan.ts index 13b03943a3..f87a3e6dec 100644 --- a/packages/nodes/src/liquid-line/floorplan.ts +++ b/packages/nodes/src/liquid-line/floorplan.ts @@ -1,5 +1,5 @@ import type { FloorplanGeometry, FloorplanPoint, GeometryContext } from '@pascal-app/core' -import { INCHES_TO_METERS } from '../duct-segment/geometry' +import { INCHES_TO_METERS } from '../duct-segment/profile' import type { LiquidLineNode } from './schema' const COPPER_LINE = '#b06b3f' diff --git a/packages/nodes/src/liquid-line/geometry.ts b/packages/nodes/src/liquid-line/geometry.ts index 6b7cd42771..db7e112db8 100644 --- a/packages/nodes/src/liquid-line/geometry.ts +++ b/packages/nodes/src/liquid-line/geometry.ts @@ -1,5 +1,5 @@ import { CylinderGeometry, Group, Mesh, MeshStandardMaterial, SphereGeometry, Vector3 } from 'three' -import { INCHES_TO_METERS } from '../duct-segment/geometry' +import { INCHES_TO_METERS } from '../duct-segment/profile' import type { LiquidLineNode } from './schema' const RADIAL_SEGMENTS = 16 diff --git a/packages/nodes/src/pipe-fitting/floorplan.ts b/packages/nodes/src/pipe-fitting/floorplan.ts index 15200d0935..c5b2983840 100644 --- a/packages/nodes/src/pipe-fitting/floorplan.ts +++ b/packages/nodes/src/pipe-fitting/floorplan.ts @@ -1,5 +1,5 @@ import type { FloorplanGeometry, GeometryContext } from '@pascal-app/core' -import { INCHES_TO_METERS } from '../duct-segment/geometry' +import { INCHES_TO_METERS } from '../duct-segment/profile' import { accessoryFloorplan } from '../shared/accessory-floorplan' import { buildPipeFittingGeometry } from './geometry' import { getPipeFittingPorts } from './ports' diff --git a/packages/nodes/src/pipe-fitting/geometry.ts b/packages/nodes/src/pipe-fitting/geometry.ts index dc1f18d47e..a9720e8669 100644 --- a/packages/nodes/src/pipe-fitting/geometry.ts +++ b/packages/nodes/src/pipe-fitting/geometry.ts @@ -11,7 +11,7 @@ import { TubeGeometry, Vector3, } from 'three' -import { INCHES_TO_METERS } from '../duct-segment/geometry' +import { INCHES_TO_METERS } from '../duct-segment/profile' import { createPipeMaterial } from '../pipe-segment/geometry' import { addPlug, addProfile } from '../shared/accessory-geometry' import { localPipeFittingPorts } from './ports' diff --git a/packages/nodes/src/pipe-fitting/parametrics.ts b/packages/nodes/src/pipe-fitting/parametrics.ts index 0d2946cc01..fa52d2fd36 100644 --- a/packages/nodes/src/pipe-fitting/parametrics.ts +++ b/packages/nodes/src/pipe-fitting/parametrics.ts @@ -57,6 +57,7 @@ export const pipeFittingParametrics: ParametricDescriptor = { return updates }, + trailingSection: () => import('../shared/pipe-collar-inspector'), groups: [ { label: 'Fitting', diff --git a/packages/nodes/src/pipe-fitting/ports.ts b/packages/nodes/src/pipe-fitting/ports.ts index 336efc3682..db9db1f574 100644 --- a/packages/nodes/src/pipe-fitting/ports.ts +++ b/packages/nodes/src/pipe-fitting/ports.ts @@ -1,6 +1,6 @@ import type { NodePort } from '@pascal-app/core' import { Euler, Vector3 } from 'three' -import { INCHES_TO_METERS } from '../duct-segment/geometry' +import { INCHES_TO_METERS } from '../duct-segment/profile' import type { PipeFittingNode } from './schema' /** Hub stub length in meters — pipe fittings are stubbier than duct diff --git a/packages/nodes/src/pipe-segment/collar-connection.ts b/packages/nodes/src/pipe-segment/collar-connection.ts new file mode 100644 index 0000000000..8f7e78924f --- /dev/null +++ b/packages/nodes/src/pipe-segment/collar-connection.ts @@ -0,0 +1,89 @@ +import { type AnyNode, nodeRegistry, PipeFittingNode } from '@pascal-app/core' +import { refuse } from '@pascal-app/core/agent-tools' +import type { ScenePort } from '@pascal-app/editor/distribution' +import { Euler, Quaternion, Vector3 } from 'three' +import { pipeFittingLegLength } from '../pipe-fitting/ports' + +type Point = [number, number, number] +export function pipeCollar( + nodes: Readonly>, + nodeId: string, + portId: string, +): ScenePort | null { + const node = nodes[nodeId] + const port = + node && + nodeRegistry + .get(node.type) + ?.ports?.(node) + .find((port) => port.id === portId) + return port && (port.system === 'waste' || port.system === 'vent') + ? { ...port, nodeId: node.id } + : null +} +export function pipeCollarOccupied( + nodes: Readonly>, + port: ScenePort, +): boolean { + const owner = nodes[port.nodeId] + return Object.values(nodes).some( + (node) => + node.id !== port.nodeId && + node.parentId === owner?.parentId && + (nodeRegistry.get(node.type)?.ports?.(node) ?? []).some( + (other) => + other.system === port.system && + new Vector3(...other.position).distanceTo(new Vector3(...port.position)) < 0.005, + ), + ) +} + +/** Fixed collars cannot be trimmed like pipe endpoints; leave straight along their axis. */ +export function planPipeCollarConnection( + nodes: Readonly>, + source: ScenePort, + toward: Point, + diameter: number, + system: string, + material: PipeFittingNode['pipeMaterial'], +) { + const port = pipeCollar(nodes, source.nodeId, source.id) + if (!port || new Vector3(...port.position).distanceTo(new Vector3(...source.position)) > 1e-6) + return refuse( + 'pipe_collar_changed', + 'The connection moved or disappeared. Select the collar again.', + ) + if (port.system !== system) + return refuse('pipe_collar_system', 'Use the same waste or vent system as the collar.') + if (pipeCollarOccupied(nodes, port)) + return refuse('pipe_collar_occupied', 'This collar is already connected.') + const axis = new Vector3(...port.direction).normalize() + const travel = new Vector3(...toward).sub(new Vector3(...port.position)) + if (travel.length() < 0.05 || axis.dot(travel.clone().normalize()) < 0.999999) + return refuse( + 'pipe_collar_direction', + 'Draw the first section straight out of the collar, then add a bend from the new pipe endpoint.', + ) + if (diameter === port.diameter) + return { point: [...port.position] as Point, fittings: [] as PipeFittingNode[] } + const leg = pipeFittingLegLength(Math.max(diameter, port.diameter)) + if (travel.length() < 2 * leg + 0.05) + return refuse('pipe_collar_space', 'Lengthen the pipe to leave room for the reducer.') + const rotation = new Euler().setFromQuaternion( + new Quaternion().setFromUnitVectors(new Vector3(1, 0, 0), axis), + ) + const fitting = PipeFittingNode.parse({ + parentId: nodes[source.nodeId]!.parentId, + fittingType: 'reducer', + diameter: port.diameter, + diameter2: diameter, + system: port.system, + pipeMaterial: material, + position: new Vector3(...port.position).addScaledVector(axis, leg).toArray(), + rotation: [rotation.x, rotation.y, rotation.z], + }) + return { + point: new Vector3(...port.position).addScaledVector(axis, 2 * leg).toArray() as Point, + fittings: [fitting], + } +} diff --git a/packages/nodes/src/pipe-segment/connect-operation.ts b/packages/nodes/src/pipe-segment/connect-operation.ts new file mode 100644 index 0000000000..1dd79f9333 --- /dev/null +++ b/packages/nodes/src/pipe-segment/connect-operation.ts @@ -0,0 +1,70 @@ +import { nodeRegistry, PipeSegmentNode } from '@pascal-app/core' +import type { AgentOperation } from '@pascal-app/core/agent-operations' +import { refuse } from '@pascal-app/core/agent-tools' +import { createPipeRunEndCap } from '../shared/automatic-run-end-cap' +import { pipeCollar, planPipeCollarConnection } from './collar-connection' + +export type PipeConnectInput = { + nodeId: string + portId: string + end: [number, number, number] + diameter?: number +} +export const connectPipe: AgentOperation = (nodes, input) => { + const owner = nodes[input.nodeId] + const port = pipeCollar(nodes, input.nodeId, input.portId) + if (!owner || !port || owner.type === 'pipe-segment') + return refuse('pipe_collar_missing', 'Choose a fixture, trap or fitting waste/vent collar.') + if (!input.end.every(Number.isFinite)) + return refuse('pipe_endpoint_invalid', 'Enter a finite endpoint.') + const diameter = input.diameter ?? port.diameter + const parsed = PipeSegmentNode.safeParse({ + parentId: owner.parentId, + path: [[...port.position], input.end], + diameter, + system: port.system, + pipeMaterial: 'pipeMaterial' in owner ? owner.pipeMaterial : 'pvc', + }) + if (!parsed.success) + return refuse('pipe_size_invalid', 'Use a supported pipe diameter between 1.25 and 8 inches.') + const pipe = parsed.data + const plan = planPipeCollarConnection( + nodes, + port, + input.end, + diameter, + pipe.system, + pipe.pipeMaterial, + ) + // An endpoint at another collar must use the draw tool's two-ended connection planning. + if ( + Object.values(nodes).some( + (node) => + node.parentId === owner.parentId && + (nodeRegistry.get(node.type)?.ports?.(node) ?? []).some( + (other) => + other.system === port.system && + Math.hypot(...other.position.map((v, i) => v - input.end[i]!)) < 0.005, + ), + ) + ) + return refuse( + 'pipe_endpoint_occupied', + 'Choose a free endpoint; use pipe drawing to join an existing collar.', + ) + pipe.path = [plan.point, input.end] + const cap = createPipeRunEndCap(pipe)! + return { + result: { + message: 'Pipe connected; source collar remains fixed.', + pipeId: pipe.id, + reducers: plan.fittings.length, + }, + changes: { + create: [pipe, ...plan.fittings, cap].map((node) => ({ + node, + parentId: owner.parentId ?? undefined, + })), + }, + } +} diff --git a/packages/nodes/src/pipe-segment/continuation.test.ts b/packages/nodes/src/pipe-segment/continuation.test.ts index 806a864864..0741fb4a57 100644 --- a/packages/nodes/src/pipe-segment/continuation.test.ts +++ b/packages/nodes/src/pipe-segment/continuation.test.ts @@ -179,3 +179,59 @@ describe('pipe continuation', () => { } }) }) + +test('continuing from either endpoint inherits the signed grade', async () => { + const { useEditor } = await import('@pascal-app/editor') + const { activatePipeContinuation } = await import('./continuation') + const previous = useEditor.getState() + const pipe = PipeSegmentNode.parse({ + path: [ + [0, 2, 0], + [4, 1.92, 0], + ], + system: 'waste', + }) + try { + activatePipeContinuation(pipe, 'end') + expect(useEditor.getState().toolDefaults['pipe-segment']).toMatchObject({ + fall: 'sloped', + flowDirection: 'forward', + }) + expect(Number(useEditor.getState().toolDefaults['pipe-segment']?.gradePercent)).toBeCloseTo(2) + activatePipeContinuation(pipe, 'start') + expect(useEditor.getState().toolDefaults['pipe-segment']?.flowDirection).toBe('reverse') + } finally { + useEditor.setState(previous) + } +}) + +test('an open trap collar seeds the exact elevation, direction and material', async () => { + const { PipeTrapNode } = await import('@pascal-app/core') + const { pipeTrapDefinition } = await import('@pascal-app/nodes') + const restore = nodeRegistry._snapshot() + try { + registerNode(pipeTrapDefinition) + registerNode(pipeSegmentDefinition) + const trap = PipeTrapNode.parse({ + position: [1, 2, 3], + rotation: Math.PI / 4, + diameter: 1.5, + pipeMaterial: 'abs', + }) + const port = pipeTrapDefinition.ports!(trap)[1]! + const defaults = { continuation: { nodeId: trap.id, portId: port.id } } + const seed = resolvePipeContinuationSeed(defaults, { [trap.id]: trap }) + expect(seed?.port).toEqual({ ...port, nodeId: trap.id }) + expect(seed?.pipe.diameter).toBe(1.5) + expect(seed?.pipe.pipeMaterial).toBe('abs') + const occupied = PipeSegmentNode.parse({ + path: [[...port.position], port.position.map((v, i) => v + port.direction[i]!)], + }) + expect( + resolvePipeContinuationSeed(defaults, { [trap.id]: trap, [occupied.id]: occupied }), + ).toBeNull() + expect(resolvePipeContinuationSeed(defaults, {})).toBeNull() + } finally { + restore() + } +}) diff --git a/packages/nodes/src/pipe-segment/continuation.ts b/packages/nodes/src/pipe-segment/continuation.ts index f7590e203f..cdf445a02e 100644 --- a/packages/nodes/src/pipe-segment/continuation.ts +++ b/packages/nodes/src/pipe-segment/continuation.ts @@ -10,7 +10,9 @@ import { type RunContinuationHandlePlan, resolvePipeContinuationHandle, } from '../shared/elbow-branch-continuation' -import type { PipeSegmentNode } from './schema' +import { pipeCollar, pipeCollarOccupied } from './collar-connection' +import { PipeSegmentNode } from './schema' +import { pipeGrade } from './slope' export type PipeEndpoint = 'start' | 'end' @@ -24,6 +26,7 @@ export type PipeContinuationSeed = { type PipeContinuationDefaults = { continuation?: { nodeId?: unknown + portId?: unknown endpoint?: unknown fittingId?: unknown segmentIndex?: unknown @@ -80,6 +83,19 @@ export function resolvePipeContinuationSeed( nodes: Record, ): PipeContinuationSeed | null { const continuation = (defaults as PipeContinuationDefaults | null)?.continuation + if (typeof continuation?.nodeId === 'string' && typeof continuation.portId === 'string') { + const source = nodes[continuation.nodeId] + const port = pipeCollar(nodes, continuation.nodeId, continuation.portId) + if (!source || !port || pipeCollarOccupied(nodes, port)) return null + const profile = PipeSegmentNode.safeParse({ + parentId: source.parentId, + diameter: port.diameter, + system: port.system, + pipeMaterial: 'pipeMaterial' in source ? source.pipeMaterial : 'pvc', + path: [[...port.position], port.position.map((value, i) => value + port.direction[i]!)], + }) + return profile.success ? { pipe: profile.data, port, body: null } : null + } const endpoint = continuation?.endpoint const nodeId = continuation?.nodeId if (endpoint === 'branch' && typeof nodeId === 'string') { @@ -137,6 +153,9 @@ export function activatePipeBranch( if (!pipe.path[segmentIndex] || !pipe.path[segmentIndex + 1]) return const editor = useEditor.getState() editor.setToolDefaults('pipe-segment', { + ...editor.toolDefaults['pipe-segment'], + routingMode: 'surface', + crossingMode: 'connect', continuation: { nodeId: pipe.id, endpoint: 'branch', segmentIndex, point }, }) useViewer.getState().setSelection({ selectedIds: [] }) @@ -151,7 +170,22 @@ export function activatePipeContinuation( if (!pipeEndpointPort(pipe, endpoint)) return const editor = useEditor.getState() editor.setToolDefaults('pipe-segment', { + ...editor.toolDefaults['pipe-segment'], + routingMode: 'surface', + crossingMode: 'connect', continuation: { nodeId: pipe.id, endpoint, ...(fittingId ? { fittingId } : {}) }, + ...(() => { + const a = endpoint === 'end' ? pipe.path.at(-2)! : pipe.path[1]! + const b = endpoint === 'end' ? pipe.path.at(-1)! : pipe.path[0]! + const grade = pipeGrade(a, b) + return grade === null + ? { fall: 'level' } + : { + fall: Math.abs(grade) > 1e-6 ? 'sloped' : 'level', + gradePercent: Math.abs(grade) * 100, + flowDirection: grade < 0 ? 'reverse' : 'forward', + } + })(), }) useViewer.getState().setSelection({ selectedIds: [] }) editor.setTool('pipe-segment') diff --git a/packages/nodes/src/pipe-segment/definition.ts b/packages/nodes/src/pipe-segment/definition.ts index 6384aecd1b..aad356664e 100644 --- a/packages/nodes/src/pipe-segment/definition.ts +++ b/packages/nodes/src/pipe-segment/definition.ts @@ -1,9 +1,10 @@ import type { NodeDefinition } from '@pascal-app/core' -import { createPathPointMoveAffordance } from '../shared/path-point-affordance' import { createRunHangerToolHint } from '../shared/run-hanger-mode' +import { pipeRunToolOptions } from '../shared/run-tool-options' import { pipeBranchAffordance, pipeContinuationAffordance } from './continuation' import { buildPipeSegmentFloorplan } from './floorplan' import { buildPipeSegmentGeometry } from './geometry' +import { pipeGradePointAffordance } from './grade-affordance' import { pipeSegmentParametrics } from './parametrics' import { PipeSegmentNode } from './schema' @@ -103,7 +104,7 @@ export const pipeSegmentDefinition: NodeDefinition = { // `affordanceTools.selection` handles. The builder emits an // `endpoint-handle` per path vertex; this drags the matching point. floorplanAffordances: { - 'move-path-point': createPathPointMoveAffordance('pipe-segment'), + 'move-path-point': pipeGradePointAffordance, 'continue-run': pipeContinuationAffordance, 'branch-run': pipeBranchAffordance, }, @@ -122,6 +123,7 @@ export const pipeSegmentDefinition: NodeDefinition = { }, tool: () => import('./tool'), + toolOptions: pipeRunToolOptions, toolHints: [ { key: 'Click', label: 'Start run' }, { key: 'Click again', label: 'Place and continue' }, @@ -135,7 +137,8 @@ export const pipeSegmentDefinition: NodeDefinition = { presentation: { label: 'DWV Pipe', - description: 'Drain / waste / vent pipe run — draw level or toggle a ¼″ per foot fall with S.', + description: + 'Drain / waste / vent pipe run — draw level or choose grade and downhill direction.', icon: { kind: 'url', src: '/icons/dwv-pipes.webp' }, paletteSection: 'structure', paletteOrder: 95, diff --git a/packages/nodes/src/pipe-segment/floorplan.ts b/packages/nodes/src/pipe-segment/floorplan.ts index db30a2f0c0..ecd71f81ec 100644 --- a/packages/nodes/src/pipe-segment/floorplan.ts +++ b/packages/nodes/src/pipe-segment/floorplan.ts @@ -1,8 +1,9 @@ import type { FloorplanGeometry, FloorplanPoint, GeometryContext } from '@pascal-app/core' -import { INCHES_TO_METERS } from '../duct-segment/geometry' +import { INCHES_TO_METERS } from '../duct-segment/profile' import { runHangerFloorplan } from '../shared/run-hangers' import { pipeContinuationHandlePlan, pipeEndpointPort } from './continuation' import type { PipeSegmentNode } from './schema' +import { pipeGrade } from './slope' const WASTE_COLOR = '#57534e' const VENT_COLOR = '#78716c' @@ -87,6 +88,41 @@ export function buildPipeSegmentFloorplan( // Selection chrome: one draggable handle per path vertex (2D twin of the // 3D selection handles). Routes to the shared `move-path-point` affordance. if (view?.selected) { + for (let i = 1; i < node.path.length; i++) { + const a = node.path[i - 1]!, + b = node.path[i]! + const grade = pipeGrade(a, b) + if (grade === null || Math.abs(grade) < 1e-6) continue + const length = Math.hypot(b[0] - a[0], b[2] - a[2]) + const sign = Math.sign(grade), + dx = ((b[0] - a[0]) / length) * sign, + dz = ((b[2] - a[2]) / length) * sign + const x = (a[0] + b[0]) / 2, + z = (a[2] + b[2]) / 2, + size = Math.min(0.12, length / 5) + children.push({ + kind: 'polyline', + points: [ + [x - dx * size - (dz * size) / 2, z - dz * size + (dx * size) / 2], + [x, z], + [x - dx * size + (dz * size) / 2, z - dz * size - (dx * size) / 2], + ], + stroke, + strokeWidth: 2, + vectorEffect: 'non-scaling-stroke', + }) + children.push({ + kind: 'text', + x: x - dz * 0.18, + y: z + dx * 0.18, + text: `${(Math.abs(grade) * 100).toFixed(2)}%`, + fontSize: 0.12, + fill: stroke, + textAnchor: 'middle', + upright: true, + }) + } + for (let k = 0; k < points.length; k++) { children.push({ kind: 'endpoint-handle', diff --git a/packages/nodes/src/pipe-segment/geometry.ts b/packages/nodes/src/pipe-segment/geometry.ts index 3b2263fd69..ab4f346bde 100644 --- a/packages/nodes/src/pipe-segment/geometry.ts +++ b/packages/nodes/src/pipe-segment/geometry.ts @@ -1,6 +1,7 @@ import type { GeometryContext } from '@pascal-app/core' import { Group, Mesh, MeshStandardMaterial, SphereGeometry, Vector3 } from 'three' -import { buildSection, INCHES_TO_METERS } from '../duct-segment/geometry' +import { buildSection } from '../duct-segment/geometry' +import { INCHES_TO_METERS } from '../duct-segment/profile' import { buildRunHangers } from '../shared/run-hangers' import type { PipeSegmentNode } from './schema' diff --git a/packages/nodes/src/pipe-segment/grade-affordance.ts b/packages/nodes/src/pipe-segment/grade-affordance.ts new file mode 100644 index 0000000000..1bef847ba9 --- /dev/null +++ b/packages/nodes/src/pipe-segment/grade-affordance.ts @@ -0,0 +1,72 @@ +import { + type AnyNode, + type AnyNodeId, + analyzePortConnectivity, + type FloorplanAffordance, + type PipeSegmentNode, + useLiveNodeOverrides, + useScene, +} from '@pascal-app/core' +import { isGridSnapActive, snapPointToGrid } from '@pascal-app/editor' +import { editPipeGrade } from './grade-operation' + +export const pipeGradePointAffordance: FloorplanAffordance = { + start({ node, payload, nodes }) { + const index = (payload as { pointIndex: number }).pointIndex + const point = node.path[index] + let updates: { id: AnyNodeId; data: Partial }[] = [] + const previewIds = new Set() + const clear = () => { + for (const id of previewIds) { + useLiveNodeOverrides.getState().clear(id) + useScene.getState().markDirty(id) + } + previewIds.clear() + } + return { + affectedIds: [ + node.id, + ...analyzePortConnectivity(node, nodes).connections.map((connection) => connection.nodeId), + ], + apply({ planPoint, modifiers }) { + clear() + updates = [] + if (!point) return + const [x, z] = isGridSnapActive() + ? snapPointToGrid([planPoint[0], planPoint[1]]) + : planPoint + try { + const outcome = editPipeGrade( + nodes, + { + nodeId: node.id, + action: 'endpoint', + pointIndex: index, + point: [x, point[1], z], + detach: modifiers.altKey, + }, + { activeLevelId: node.parentId }, + ) + updates = (outcome.changes?.update ?? []).map((entry) => ({ + ...entry, + id: entry.id as AnyNodeId, + })) + useLiveNodeOverrides + .getState() + .setMany(updates.map((entry) => [entry.id, entry.data as Record])) + for (const entry of updates) { + previewIds.add(entry.id) + useScene.getState().markDirty(entry.id) + } + } catch { + /* Invalid frames leave the committed route in place. */ + } + }, + canCommit: () => updates.length > 0, + commit() { + clear() + useScene.getState().updateNodes(updates) + }, + } + }, +} diff --git a/packages/nodes/src/pipe-segment/grade-inspector.tsx b/packages/nodes/src/pipe-segment/grade-inspector.tsx new file mode 100644 index 0000000000..5815148a29 --- /dev/null +++ b/packages/nodes/src/pipe-segment/grade-inspector.tsx @@ -0,0 +1,123 @@ +'use client' +import { type AnyNodeId, type PipeSegmentNode, useScene } from '@pascal-app/core' +import { useState } from 'react' +import RunHangerInspector from '../shared/run-hanger-inspector' +import { editPipeGrade, type PipeGradeInput } from './grade-operation' +import PipeOffsetInspector from './offset-inspector' +import PipeResizeInspector from './resize-inspector' +import { pipeGrade, pipeGradeLabel } from './slope' + +export default function PipeGradeInspector({ node }: { node: PipeSegmentNode }) { + return ( + <> + + + + + > + ) +} +function GradeForm({ node }: { node: PipeSegmentNode }) { + const initial = pipeGrade(node.path[0]!, node.path[1]!) ?? 0 + const [grade, setGrade] = useState(Math.abs(initial) * 100) + const [flow, setFlow] = useState<'forward' | 'reverse'>(initial < 0 ? 'reverse' : 'forward') + const [anchor, setAnchor] = useState<'start' | 'end'>('start') + const [elevation, setElevation] = useState(node.path[0]![1]) + const [message, setMessage] = useState('') + const apply = (input: Partial) => { + try { + const outcome = editPipeGrade( + useScene.getState().nodes, + { nodeId: node.id, action: 'grade', anchor, ...input }, + { activeLevelId: node.parentId }, + ) + useScene.getState().applyNodeChanges({ + update: outcome.changes?.update?.map((entry) => ({ + ...entry, + id: entry.id as AnyNodeId, + })), + }) + setMessage('Applied in one undo step.') + } catch (error) { + setMessage(error instanceof Error ? error.message : 'Unable to edit pipe.') + } + } + return ( + + Grade and flow + + Centerline elevations above level: start {node.path[0]![1].toFixed(3)} m · end{' '} + {node.path.at(-1)![1].toFixed(3)} m + + {node.path.slice(1).map((point, index) => ( + + Leg {index + 1}: {pipeGradeLabel(node.path[index]!, point)} + + ))} + + Arrows show downhill direction. Level runs have no gravity fall. Editing a path point + preserves each leg’s grade. + + + Grade (%) + setGrade(event.target.valueAsNumber)} + className="w-24 border bg-background p-1" + /> + + setFlow(event.target.value as typeof flow)} + > + Start → end + End → start + + { + const next = event.target.value as typeof anchor + setAnchor(next) + setElevation(next === 'start' ? node.path[0]![1] : node.path.at(-1)![1]) + }} + > + Keep start elevation + Keep end elevation + + apply({ gradePercent: grade, flow })} + > + Apply grade to horizontal legs + + + {anchor === 'start' ? 'Start' : 'End'} elevation (m) + setElevation(event.target.valueAsNumber)} + className="w-24 border bg-background p-1" + /> + + apply({ action: 'elevation', elevation })} + > + Move elevation, keep grades + + {message && {message}} + + ) +} diff --git a/packages/nodes/src/pipe-segment/grade-operation.ts b/packages/nodes/src/pipe-segment/grade-operation.ts new file mode 100644 index 0000000000..8887ec5653 --- /dev/null +++ b/packages/nodes/src/pipe-segment/grade-operation.ts @@ -0,0 +1,161 @@ +import { + type AnyNode, + type AnyNodeId, + analyzePortConnectivity, + nodeRegistry, + type PipeSegmentNode, + resolveConnectivityUpdates, +} from '@pascal-app/core' +import type { AgentOperation } from '@pascal-app/core/agent-operations' +import { refuse } from '@pascal-app/core/agent-tools' +import { planRunEndCapFollowUpdates } from '../shared/automatic-run-end-cap' +import { applyPipeGrade, pipeGradesMatch, preservePipeGrades } from './slope' + +type Point = [number, number, number] +export type PipeGradeInput = { + nodeId: string + action: 'grade' | 'endpoint' | 'elevation' + gradePercent?: number + flow?: 'forward' | 'reverse' + anchor?: 'start' | 'end' + pointIndex?: number + point?: Point + elevation?: number + detach?: boolean +} + +/** Refuse a connected edit that would silently regrade another run. */ +export function pipeUpdatesPreserveGrades( + nodes: Readonly>, + updates: { id: string; data: Partial }[], + exceptId?: string, +): boolean { + return updates.every((update) => { + const node = nodes[update.id] + return ( + update.id === exceptId || + node?.type !== 'pipe-segment' || + !('path' in update.data) || + !update.data.path || + pipeGradesMatch(node.path, update.data.path as Point[]) + ) + }) +} + +export const editPipeGrade: AgentOperation = (nodes, input) => { + const pipe = nodes[input.nodeId] + if (pipe?.type !== 'pipe-segment') return refuse('pipe_not_found', 'Select a pipe run.') + if (!nodeRegistry.get('pipe-segment')?.ports) + return refuse('node_capability_unavailable', 'Register pipe node definitions before editing.') + let path: Point[] = pipe.path.map((p) => [...p]) + if (input.action === 'grade') { + const grade = input.gradePercent + if (grade === undefined || !Number.isFinite(grade) || grade < 0) + return refuse('pipe_grade_invalid', 'Enter a finite, non-negative grade percentage.') + const signed = (grade / 100) * (input.flow === 'reverse' ? -1 : 1) + for (let i = 1; i < path.length; i++) { + const previous = pipe.path[i - 1]! + const current = pipe.path[i]! + // Vertical legs keep their height; grades describe horizontal travel only. + path[i] = + Math.hypot(current[0] - previous[0], current[2] - previous[2]) < 1e-6 + ? [current[0], path[i - 1]![1] + current[1] - previous[1], current[2]] + : applyPipeGrade(path[i - 1]!, current, signed) + } + if (input.anchor === 'end') { + const dy = pipe.path.at(-1)![1] - path.at(-1)![1] + path = path.map((p) => [p[0], p[1] + dy, p[2]]) + } + } else if (input.action === 'elevation') { + if (input.elevation === undefined || !Number.isFinite(input.elevation)) + return refuse('pipe_elevation_invalid', 'Enter a finite elevation above the level.') + const index = input.anchor === 'end' ? path.length - 1 : 0 + const dy = input.elevation - path[index]![1] + path = path.map((p) => [p[0], p[1] + dy, p[2]]) + } else { + const index = input.pointIndex + if ( + index === undefined || + !Number.isInteger(index) || + !path[index] || + !input.point || + input.point.some((v) => !Number.isFinite(v)) + ) + return refuse('pipe_endpoint_invalid', 'Choose a valid path point and finite coordinates.') + path[index] = input.point + const constrained = preservePipeGrades(pipe.path, path, index) + if (!constrained) + return refuse( + 'pipe_grade_conflict', + 'This edit collapses a run or tilts a vertical stack. Move the whole stack instead.', + ) + path = constrained + } + const detached = input.action === 'endpoint' && input.detach === true + const next: PipeSegmentNode = { ...pipe, path, wallAttachment: undefined } + const connectivity = analyzePortConnectivity(pipe, { ...nodes }) + for (const endpoint of ['start', 'end'] as const) { + if (detached) continue + const mates = connectivity.adjacency[pipe.id]?.[endpoint] ?? [] + if ( + !mates.some((mate) => { + const owner = nodes[mate.nodeId] + return owner?.type !== 'pipe-fitting' || owner.fittingType !== 'end-cap' + }) + ) + continue + const index = endpoint === 'start' ? 0 : path.length - 1 + const neighbor = endpoint === 'start' ? 1 : path.length - 2 + const oldDirection = pipe.path[index]!.map((v, i) => v - pipe.path[neighbor]![i]!) + const newDirection = path[index]!.map((v, i) => v - path[neighbor]![i]!) + const oldLength = Math.hypot(...oldDirection), + newLength = Math.hypot(...newDirection) + const dot = + oldDirection.reduce((sum, v, i) => sum + v * newDirection[i]!, 0) / (oldLength * newLength) + if (!Number.isFinite(dot) || dot < 0.999999) + return refuse( + 'pipe_connection_angle', + 'This would turn a connected collar. Adjust the fitting or detach the run before changing its direction or grade.', + ) + } + const follow = !detached && connectivity ? resolveConnectivityUpdates(connectivity, next) : [] + const caps = detached + ? [] + : (['start', 'end'] as const).flatMap((end) => + planRunEndCapFollowUpdates(pipe, next, end, { ...nodes }), + ) + const capIds = new Set(caps.map((cap) => cap.id)) + const update = [ + { id: pipe.id as AnyNodeId, data: { path, wallAttachment: undefined } as Partial }, + ...follow.filter((entry) => !capIds.has(entry.id)), + ...caps, + ] + if (!pipeUpdatesPreserveGrades(nodes, update, pipe.id)) + return refuse( + 'pipe_connected_grade', + 'This would change a connected pipe’s grade. Adjust the connected route explicitly first.', + ) + if ( + update.some((entry) => { + const owner = nodes[entry.id] + return ( + owner && + owner.id !== pipe.id && + owner.type !== 'pipe-segment' && + owner.type !== 'pipe-fitting' + ) + }) + ) + return refuse( + 'pipe_fixed_connection', + 'This edit would move a fixture or equipment connection. Keep that endpoint fixed.', + ) + return { + result: { + message: 'Pipe elevations updated; grades preserved on connected runs.', + startElevation: path[0]![1], + endElevation: path.at(-1)![1], + }, + changes: { update }, + } +} diff --git a/packages/nodes/src/pipe-segment/move-tool.tsx b/packages/nodes/src/pipe-segment/move-tool.tsx index 2ede3a9dae..23fefcb59f 100644 --- a/packages/nodes/src/pipe-segment/move-tool.tsx +++ b/packages/nodes/src/pipe-segment/move-tool.tsx @@ -33,6 +33,7 @@ import { } from '../shared/ghost-alignment' import { type RunMoveConnectivity, startRunMoveConnectivity } from '../shared/run-move-connectivity' import { translateWallRun } from '../shared/wall-run-move' +import { pipeUpdatesPreserveGrades } from './grade-operation' type Vec3 = [number, number, number] @@ -217,8 +218,10 @@ export const MovePipeSegmentTool: React.FC<{ node: AnyNode }> = ({ node }) => { event.nativeEvent?.stopPropagation?.() return } - committed = true const finalPath = previewPathRef.current + const gradeUpdates = connectivity?.commitUpdates({ path: finalPath }) ?? [] + if (!pipeUpdatesPreserveGrades(useScene.getState().nodes, gradeUpdates)) return + committed = true useScene.temporal.getState().resume() let selectId = nodeId diff --git a/packages/nodes/src/pipe-segment/offset-inspector.tsx b/packages/nodes/src/pipe-segment/offset-inspector.tsx new file mode 100644 index 0000000000..e854d31b75 --- /dev/null +++ b/packages/nodes/src/pipe-segment/offset-inspector.tsx @@ -0,0 +1,149 @@ +'use client' +import { type AnyNodeId, type PipeSegmentNode, useScene } from '@pascal-app/core' +import { useMemo, useState } from 'react' +import { offsetPipe, type PipeOffsetInput } from './offset-operation' + +type Point = [number, number, number] +export default function PipeOffsetInspector({ node }: { node: PipeSegmentNode }) { + const [open, setOpen] = useState(false) + return ( + + setOpen(!open)} + > + Offset around obstacle + + {open && } + + ) +} +function OffsetForm({ node }: { node: PipeSegmentNode }) { + const nodes = useScene((state) => state.nodes) + const start = node.path[0]!, + end = node.path.at(-1)! + const length = Math.hypot(end[0] - start[0], end[2] - start[2]) + const [input, setInput] = useState({ + nodeId: node.id, + from: Number((length / 4).toFixed(3)), + to: Number(((length * 3) / 4).toFixed(3)), + offset: Number(Math.min(0.5, length / 8).toFixed(3)), + }) + const [notice, setNotice] = useState('') + const [appliedPath, setAppliedPath] = useState(null) + const preview = useMemo(() => { + try { + return { outcome: offsetPipe(nodes, input, { activeLevelId: node.parentId }), error: '' } + } catch (error) { + return { + outcome: null, + error: error instanceof Error ? error.message : 'Unable to plan offset.', + } + } + }, [nodes, input, node.parentId]) + const paths = (preview.outcome?.result.paths ?? []) as Point[][] + const all = [start, end, ...paths.flat()] + const minY = Math.min(...all.map((p) => p[1])), + maxY = Math.max(...all.map((p) => p[1])) + const project = (p: Point) => { + const distance = + ((p[0] - start[0]) * (end[0] - start[0]) + (p[2] - start[2]) * (end[2] - start[2])) / + (length || 1) + return `${16 + (228 * distance) / (length || 1)},${100 - (80 * (p[1] - minY)) / (maxY - minY || 1)}` + } + const apply = () => { + try { + const outcome = offsetPipe(useScene.getState().nodes, input, { activeLevelId: node.parentId }) + useScene.getState().applyNodeChanges({ + create: outcome.changes?.create?.map((entry) => ({ + ...entry, + parentId: entry.parentId as AnyNodeId, + })), + update: outcome.changes?.update?.map((entry) => ({ ...entry, id: entry.id as AnyNodeId })), + }) + setNotice('Offset applied in one undo step. End connections stayed fixed.') + const appliedNode = useScene.getState().nodes[node.id] + setAppliedPath(appliedNode?.type === 'pipe-segment' ? JSON.stringify(appliedNode.path) : null) + } catch (error) { + setNotice(error instanceof Error ? error.message : 'Unable to apply offset.') + } + } + if (appliedPath === JSON.stringify(node.path)) return {notice} + return ( + + + Choose the first and last bend by horizontal distance from the start. Positive offset goes + up; negative goes down. Each connector uses the offset height in horizontal travel. + + {(['from', 'to', 'offset'] as const).map((key) => ( + + {{ from: 'First bend (m)', to: 'Last bend (m)', offset: 'Vertical offset (m)' }[key]} + { + setInput({ ...input, [key]: event.target.valueAsNumber }) + setNotice('') + }} + /> + + ))} + {paths.length > 0 && ( + <> + + + + {[start, end].map((point, index) => { + const [cx, cy] = project(point).split(',') + return + })} + + + Side profile (schematic). Four bends · five pipe sections. Parallel sections keep the + original grade; both end connections stay fixed. + + {preview.outcome?.result.uphill === true && ( + + This offset includes an uphill waste section. It does not provide continuous downhill + drainage. + + )} + > + )} + + Check obstacle clearance. The preview does not detect collisions. + + {preview.error && {preview.error}} + + Apply pipe offset + + {notice && {notice}} + + ) +} diff --git a/packages/nodes/src/pipe-segment/offset-operation.ts b/packages/nodes/src/pipe-segment/offset-operation.ts new file mode 100644 index 0000000000..2366eca507 --- /dev/null +++ b/packages/nodes/src/pipe-segment/offset-operation.ts @@ -0,0 +1,132 @@ +import { type AnyNode, type AnyNodeId, nodeRegistry, PipeSegmentNode } from '@pascal-app/core' +import type { AgentOperation, SceneChanges } from '@pascal-app/core/agent-operations' +import { refuse } from '@pascal-app/core/agent-tools' +import { Vector3 } from 'three' +import { planPipeElbowAtPort } from '../shared/auto-fitting' +import { autoOffsetInvalidationUpdates } from '../shared/auto-offset-tag' +import { transferRunEndCapOwnership } from '../shared/automatic-run-end-cap' +import { pipeGrade, pipeGradesMatch } from './slope' + +export type PipeOffsetInput = { nodeId: string; from: number; to: number; offset: number } +type Point = [number, number, number] + +export const offsetPipe: AgentOperation = (nodes, input) => { + const pipe = nodes[input.nodeId] + if (pipe?.type !== 'pipe-segment') return refuse('pipe_not_found', 'Select a pipe run.') + if (!nodeRegistry.get('pipe-segment')?.ports || !nodeRegistry.get('pipe-fitting')?.ports) + return refuse( + 'node_capability_unavailable', + 'Register pipe and fitting definitions before editing.', + ) + if (pipe.path.length !== 2 || ![input.from, input.to, input.offset].every(Number.isFinite)) + return refuse('pipe_offset_route', 'Choose a straight run and enter finite offset dimensions.') + if ( + Object.values(nodes).some((node) => node.parentId === pipe.id) || + Object.keys(pipe.hangerOverrides ?? {}).length + ) + return refuse( + 'pipe_offset_attachments', + 'Remove custom hanger adjustments or hosted children before splitting this run.', + ) + const start = new Vector3(...pipe.path[0]!), + end = new Vector3(...pipe.path[1]!) + const delta = end.clone().sub(start) + const length = Math.hypot(delta.x, delta.z) + if (length < 0.001 || Math.abs(input.offset) < 0.001) + return refuse('pipe_offset_route', 'Choose a non-vertical run and a non-zero vertical offset.') + const axis = delta.clone().divideScalar(length) + const at = (distance: number) => start.clone().addScaledVector(axis, distance) + const travel = Math.abs(input.offset) + const a = at(input.from), + b = at(input.from + travel).add(new Vector3(0, input.offset, 0)) + const d = at(input.to), + c = at(input.to - travel).add(new Vector3(0, input.offset, 0)) + const corners = [start, a, b, c, d, end] + if (input.from <= 0 || input.to >= length || input.to - input.from <= 2 * travel) + return refuse( + 'pipe_offset_space', + 'Place the bends inside the run and allow more than twice the offset height between the first and last bend.', + ) + const directions = corners.slice(1).map((point, i) => point.clone().sub(corners[i]!).normalize()) + const elbows = [a, b, c, d].map((corner, i) => { + const plan = planPipeElbowAtPort( + { + id: 'end', + nodeId: pipe.id, + position: corner.toArray(), + direction: directions[i]!.toArray(), + diameter: pipe.diameter, + system: pipe.system, + }, + directions[i + 1]!.toArray(), + pipe.diameter, + pipe.pipeMaterial, + ) + if (!plan) + return refuse('pipe_offset_angle', 'The requested bends cannot be formed on this route.') + return plan + }) + const paths: Point[][] = [ + [start.toArray(), elbows[0]!.trimmedPortPoint], + [elbows[0]!.collarPoint, elbows[1]!.trimmedPortPoint], + [elbows[1]!.collarPoint, elbows[2]!.trimmedPortPoint], + [elbows[2]!.collarPoint, elbows[3]!.trimmedPortPoint], + [elbows[3]!.collarPoint, end.toArray()], + ] + for (const [i, path] of paths.entries()) { + const segment = new Vector3(...path[1]!).sub(new Vector3(...path[0]!)) + if ( + !segment.toArray().every(Number.isFinite) || + segment.length() < 0.001 || + segment.normalize().dot(directions[i]!) < 0.999999 + ) + return refuse( + 'pipe_offset_space', + 'Not enough straight pipe between the bends. Increase the offset height or spacing, or move the bends away from the endpoints.', + ) + } + if ([0, 2, 4].some((i) => !pipeGradesMatch(pipe.path, paths[i]!))) + return refuse('pipe_offset_grade', 'This offset cannot preserve the existing grade.') + const { id: _id, ...defaults } = pipe + const newRuns = paths.slice(1).map((path) => + PipeSegmentNode.parse({ + ...defaults, + metadata: {}, + path, + wallAttachment: undefined, + hangerOverrides: undefined, + }), + ) + const changes: SceneChanges = { + update: [ + { + id: pipe.id, + data: { path: paths[0], wallAttachment: undefined, hangerOverrides: undefined }, + }, + ], + create: [ + ...newRuns, + ...elbows.map((elbow) => ({ ...elbow.fitting, parentId: pipe.parentId })), + ].map((node) => ({ node, parentId: pipe.parentId ?? undefined })), + } + changes.update!.push(...transferRunEndCapOwnership(nodes, pipe.id, newRuns.at(-1)!.id, 'end')) + for (const entry of autoOffsetInvalidationUpdates({ ...nodes }, pipe.id as AnyNodeId)) { + const existing = changes.update!.find((update) => update.id === entry.id) + if (existing) existing.data = { ...existing.data, ...entry.data } as Partial + else changes.update!.push(entry) + } + const grade = pipeGrade(pipe.path[0]!, pipe.path[1]!)! + const uphill = + grade === 0 || paths.some((path) => (path[1]![1] - path[0]![1]) * Math.sign(grade) > 1e-6) + return { + changes, + result: { + message: 'Four-bend offset; boundary connections and parallel-run grades preserved.', + paths, + uphill: pipe.system === 'waste' && uphill, + offset: input.offset, + fittings: 4, + runs: 5, + }, + } +} diff --git a/packages/nodes/src/pipe-segment/parametrics.ts b/packages/nodes/src/pipe-segment/parametrics.ts index 33e165a830..f11d161239 100644 --- a/packages/nodes/src/pipe-segment/parametrics.ts +++ b/packages/nodes/src/pipe-segment/parametrics.ts @@ -22,7 +22,7 @@ export const pipeSegmentParametrics: ParametricDescriptor = { plan.deleteFitting ? [plan.fittingId, ...plan.cascadeDeleteIds] : [], ), ], - trailingSection: () => import('../shared/run-hanger-inspector'), + trailingSection: () => import('./grade-inspector'), groups: [ { label: 'Hangers', @@ -67,14 +67,6 @@ export const pipeSegmentParametrics: ParametricDescriptor = { options: ['waste', 'vent'], display: 'segmented', }, - { - key: 'diameter', - kind: 'number', - unit: 'in', - min: 1.25, - max: 6, - step: 0.25, - }, ], }, { diff --git a/packages/nodes/src/pipe-segment/resize-inspector.tsx b/packages/nodes/src/pipe-segment/resize-inspector.tsx new file mode 100644 index 0000000000..034eb55645 --- /dev/null +++ b/packages/nodes/src/pipe-segment/resize-inspector.tsx @@ -0,0 +1,84 @@ +'use client' +import { type AnyNodeId, type PipeSegmentNode, useScene } from '@pascal-app/core' +import { useState } from 'react' +import { resizePipe } from './resize-operation' + +export default function PipeResizeInspector({ node }: { node: PipeSegmentNode }) { + const [diameter, setDiameter] = useState(node.diameter) + const [scope, setScope] = useState<'segment' | 'branch'>('segment') + const [message, setMessage] = useState('') + const apply = (preview: boolean) => { + try { + const outcome = resizePipe( + useScene.getState().nodes, + { nodeId: node.id, diameter, scope }, + { activeLevelId: node.parentId }, + ) + if (preview || !outcome.changes) { + setMessage( + outcome.changes + ? `${outcome.result.runs} runs, ${outcome.result.fittings} fittings, ${outcome.result.reducers} new reducers. Grades stay unchanged.` + : String(outcome.result.message), + ) + return + } + useScene.getState().applyNodeChanges({ + create: outcome.changes.create?.map((entry) => ({ + ...entry, + parentId: entry.parentId as AnyNodeId, + })), + update: outcome.changes.update?.map((entry) => ({ ...entry, id: entry.id as AnyNodeId })), + }) + setMessage('Resized in one undo step. Grades and boundary connections preserved.') + } catch (error) { + setMessage(error instanceof Error ? error.message : 'Unable to resize pipe.') + } + } + return ( + + Pipe size + Current diameter: {node.diameter} in + + Diameter (in) + { + setDiameter(event.target.valueAsNumber) + setMessage('') + }} + className="w-24 border bg-background p-1" + /> + + { + setScope(event.target.value as typeof scope) + setMessage('') + }} + className="w-full border bg-background p-1" + > + This segment + Connected branch + + + Branches stop at junctions, size or material changes, and fixture connections. Reducers keep + boundary collars fixed. + + + apply(true)}> + Check resize + + apply(false)}> + Apply pipe size + + + {message && {message}} + + ) +} diff --git a/packages/nodes/src/pipe-segment/resize-operation.ts b/packages/nodes/src/pipe-segment/resize-operation.ts new file mode 100644 index 0000000000..aaea86f09a --- /dev/null +++ b/packages/nodes/src/pipe-segment/resize-operation.ts @@ -0,0 +1,170 @@ +import { type AnyNode, nodeRegistry, PipeFittingNode, PipeSegmentNode } from '@pascal-app/core' +import type { AgentOperation, SceneChanges } from '@pascal-app/core/agent-operations' +import { refuse } from '@pascal-app/core/agent-tools' +import type { ScenePort } from '@pascal-app/editor/distribution' +import { Euler, Quaternion, Vector3 } from 'three' +import { pipeFittingLegLength } from '../pipe-fitting/ports' +import { pipeGradesMatch } from './slope' + +type Point = [number, number, number] +export type PipeResizeInput = { nodeId: string; diameter: number; scope?: 'segment' | 'branch' } +const portsOf = (node: AnyNode): ScenePort[] => + nodeRegistry + .get(node.type) + ?.ports?.(node) + .map((port) => ({ ...port, nodeId: node.id })) ?? [] +const vector = (point: readonly [number, number, number]) => new Vector3(...point) + +export const resizePipe: AgentOperation = (nodes, input) => { + const root = nodes[input.nodeId] + if (root?.type !== 'pipe-segment') return refuse('pipe_not_found', 'Select a pipe run.') + if (!nodeRegistry.get('pipe-segment')?.ports || !nodeRegistry.get('pipe-fitting')?.ports) + return refuse( + 'node_capability_unavailable', + 'Register pipe and fitting definitions before resizing.', + ) + if (!PipeSegmentNode.safeParse({ ...root, diameter: input.diameter }).success) + return refuse('pipe_size_invalid', 'Enter a pipe diameter between 1.25 and 8 inches.') + const ports = Object.values(nodes) + .filter((node) => node.parentId === root.parentId) + .flatMap(portsOf) + const mates = (port: ScenePort) => + ports.filter( + (other) => + other.nodeId !== port.nodeId && + other.system === port.system && + vector(other.position).distanceTo(vector(port.position)) < 0.005, + ) + const mateOf = (port: ScenePort) => { + const found = mates(port) + if (found.length > 1) + return refuse('pipe_ambiguous_connection', 'Resolve overlapping connections before resizing.') + const mate = found[0] + if (mate && vector(mate.direction).dot(vector(port.direction)) > -0.999999) + return refuse('pipe_connection_angle', 'Align the connected collars before resizing.') + return mate + } + const selected = new Set([root.id]) + const queue: AnyNode[] = [root] + for (const node of queue) { + for (const port of portsOf(node)) { + const mate = mateOf(port) + if (!mate || selected.has(mate.nodeId)) continue + const owner = nodes[mate.nodeId]! + const cap = owner.type === 'pipe-fitting' && owner.fittingType === 'end-cap' + const sameSize = 'diameter' in owner && owner.diameter === root.diameter + const sameMaterial = 'pipeMaterial' in owner && owner.pipeMaterial === root.pipeMaterial + const throughFitting = + owner.type === 'pipe-fitting' && + ['elbow', 'coupling', 'cleanout'].includes(owner.fittingType) && + portsOf(owner).every((collar) => + mates(collar).every((neighbor) => { + const run = nodes[neighbor.nodeId] + return ( + run?.type === 'pipe-segment' && + run.diameter === root.diameter && + run.pipeMaterial === root.pipeMaterial + ) + }), + ) + if ( + sameSize && + (cap || + (input.scope === 'branch' && + sameMaterial && + (owner.type === 'pipe-segment' || throughFitting))) + ) { + selected.add(owner.id) + queue.push(owner) + } + } + } + if (input.diameter === root.diameter) + return { result: { message: 'The branch already has this diameter.' } } + const changed = new Map() + for (const node of queue) { + if (node.type === 'pipe-segment') + changed.set(node.id, { + ...node, + diameter: input.diameter, + path: node.path.map((p) => [...p]), + wallAttachment: undefined, + }) + else if (node.type === 'pipe-fitting') { + const next = PipeFittingNode.parse({ + ...node, + diameter: input.diameter, + diameter2: input.diameter, + }) + if (portsOf(node).length === 1) { + // Keep a cap's inlet fixed while its body grows away from the run. + const delta = vector(portsOf(node)[0]!.position).sub(vector(portsOf(next)[0]!.position)) + next.position = vector(next.position).add(delta).toArray() + } + changed.set(node.id, next) + } + } + const create: NonNullable = [] + for (const node of queue) { + if (node.type !== 'pipe-segment') continue + const next = changed.get(node.id) as PipeSegmentNode + for (const port of portsOf(node)) { + const mate = mateOf(port) + if (!mate) continue + const index = port.id === 'start' ? 0 : next.path.length - 1 + if (selected.has(mate.nodeId)) { + const updatedMate = portsOf(changed.get(mate.nodeId)!).find((p) => p.id === mate.id)! + // Adjacent runs keep their shared point; only fitting collars move. + if ( + nodes[mate.nodeId]?.type === 'pipe-fitting' && + portsOf(changed.get(mate.nodeId)!).length > 1 + ) + next.path[index] = [...updatedMate.position] + continue + } + if (mate.diameter === input.diameter) continue + const axis = vector(mate.direction).normalize() + const leg = pipeFittingLegLength(Math.max(mate.diameter, input.diameter)) + const rotation = new Euler().setFromQuaternion( + new Quaternion().setFromUnitVectors(new Vector3(1, 0, 0), axis), + ) + const fitting = PipeFittingNode.parse({ + parentId: root.parentId, + fittingType: 'reducer', + system: root.system, + pipeMaterial: root.pipeMaterial, + diameter: mate.diameter, + diameter2: input.diameter, + position: vector(mate.position).addScaledVector(axis, leg).toArray(), + rotation: [rotation.x, rotation.y, rotation.z], + }) + create.push({ node: fitting, parentId: root.parentId! }) + next.path[index] = [...portsOf(fitting).find((p) => p.id === 'outlet')!.position] + } + for (let i = 1; i < next.path.length; i++) { + const before = vector(node.path[i]!) + .sub(vector(node.path[i - 1]!)) + .normalize() + const after = vector(next.path[i]!).sub(vector(next.path[i - 1]!)) + if (after.length() < 0.001 || before.dot(after.clone().normalize()) < 0.999999) + return refuse( + 'pipe_resize_space', + 'Not enough straight pipe for the new fittings. Extend the route first.', + ) + } + if (!pipeGradesMatch(node.path, next.path as Point[])) + return refuse( + 'pipe_resize_grade', + 'This resize would change the pipe grade. Adjust the fitting layout first.', + ) + } + return { + result: { + message: 'Pipe sizes updated; grades and boundary connections preserved.', + runs: queue.filter((n) => n.type === 'pipe-segment').length, + fittings: queue.filter((n) => n.type === 'pipe-fitting').length, + reducers: create.length, + }, + changes: { create, update: [...changed].map(([id, node]) => ({ id, data: node })) }, + } +} diff --git a/packages/nodes/src/pipe-segment/selection.tsx b/packages/nodes/src/pipe-segment/selection.tsx index abb7646e59..9e8cd0f4bb 100644 --- a/packages/nodes/src/pipe-segment/selection.tsx +++ b/packages/nodes/src/pipe-segment/selection.tsx @@ -46,6 +46,8 @@ import { type PipeEndpoint, pipeContinuationHandlePlan, } from './continuation' +import { pipeUpdatesPreserveGrades } from './grade-operation' +import { pipeGradesMatch, preservePipeGrades } from './slope' /** Port-snap radius for dragged run endpoints (meters, XZ). */ const PORT_SNAP_RADIUS_M = 0.4 @@ -153,6 +155,7 @@ const PipePointHandles = ({ pipe, target }: { pipe: PipeSegmentNode; target: Obj }) const unit = useViewer((s) => s.unit) const [draggingIndex, setDraggingIndex] = useState(null) + const [gradeNotice, setGradeNotice] = useState('') const [runMoving, setRunMoving] = useState(false) const [verticalGhost, setVerticalGhost] = useState<{ tint: 'valid' | 'invalid' @@ -280,6 +283,15 @@ const PipePointHandles = ({ pipe, target }: { pipe: PipeSegmentNode; target: Obj next: Point, detached: boolean, ): { id: AnyNodeId; data: Partial }[] | null => { + const constrained = preservePipeGrades( + drag.initialPath, + drag.initialPath.map((point, index) => (index === drag.index ? next : point)), + drag.index, + ) + if (!constrained) return null + next = constrained[drag.index]! + const checked = (updates: { id: AnyNodeId; data: Partial }[]) => + pipeUpdatesPreserveGrades(useScene.getState().nodes, updates) ? updates : null const wall = pipe.wallAttachment ? useScene.getState().nodes[pipe.wallAttachment.wallId] : undefined @@ -291,14 +303,9 @@ const PipePointHandles = ({ pipe, target }: { pipe: PipeSegmentNode; target: Obj path: Point[], updates: { id: AnyNodeId; data: Partial }[], ) => { - if (drag.index !== 0 && drag.index !== drag.initialPath.length - 1) return updates - const endpoint = drag.index === 0 ? 'start' : 'end' const nextPipe = { ...pipe, path } as PipeSegmentNode - const capUpdates = planRunEndCapFollowUpdates( - pipe, - nextPipe, - endpoint, - useScene.getState().nodes, + const capUpdates = (['start', 'end'] as const).flatMap((endpoint) => + planRunEndCapFollowUpdates(pipe, nextPipe, endpoint, useScene.getState().nodes), ) const capIds = new Set(capUpdates.map((update) => update.id)) return [...updates.filter((update) => !capIds.has(update.id)), ...capUpdates] @@ -306,37 +313,39 @@ const PipePointHandles = ({ pipe, target }: { pipe: PipeSegmentNode; target: Obj if (!detached && drag.fittingEndpoint) { const plan = planFittingEndpointReaim(drag.fittingEndpoint, drag.index, next) // Out of the elbow's buildable turn range — hold this frame. - if (!plan) return null - return withEndCapFollow(plan.path, [ - { - id: pipe.id as AnyNodeId, - data: { path: plan.path, wallAttachment: attachmentFor(plan.path) }, - }, - { id: plan.fittingUpdate.id, data: plan.fittingUpdate.data }, - ...(drag.jointPartner - ? [ - { - id: drag.jointPartner!.id, - data: { - path: drag.jointPartner!.startPath.map((p, i) => - i === (drag.index === 0 ? drag.jointPartner!.startPath.length - 1 : 0) - ? drag.index === 0 - ? plan.path[plan.path.length - 1]! - : plan.path[0]! - : p, - ), - } as Partial, - }, - ] - : []), - ]) + if (!plan || !pipeGradesMatch(drag.initialPath, plan.path)) return null + return checked( + withEndCapFollow(plan.path, [ + { + id: pipe.id as AnyNodeId, + data: { path: plan.path, wallAttachment: attachmentFor(plan.path) }, + }, + { id: plan.fittingUpdate.id, data: plan.fittingUpdate.data }, + ...(drag.jointPartner + ? [ + { + id: drag.jointPartner!.id, + data: { + path: drag.jointPartner!.startPath.map((p, i) => + i === (drag.index === 0 ? drag.jointPartner!.startPath.length - 1 : 0) + ? drag.index === 0 + ? plan.path[plan.path.length - 1]! + : plan.path[0]! + : p, + ), + } as Partial, + }, + ] + : []), + ]), + ) } - const path = drag.initialPath.map((p, i) => (i === drag.index ? next : p)) as Point[] + const path = constrained const updates = [ { id: pipe.id as AnyNodeId, data: { path, wallAttachment: attachmentFor(path) } }, ...(detached ? [] : connectivityUpdatesForPath(drag.connectivity, path)), ] - return detached ? updates : withEndCapFollow(path, updates) + return checked(detached ? updates : withEndCapFollow(path, updates)) } /** World-space position of a local path point. */ @@ -465,7 +474,13 @@ const PipePointHandles = ({ pipe, target }: { pipe: PipeSegmentNode; target: Obj if (next[0] === drag.current[0] && next[1] === drag.current[1] && next[2] === drag.current[2]) return const batch = buildDragBatch(drag, next, detached) - if (!batch) return + if (!batch) { + setGradeNotice( + 'This edit cannot preserve the pipe grade and connected collars. Adjust the fitting or use Grade and flow.', + ) + return + } + setGradeNotice('') drag.current = next drag.detached = detached if (step > 0) triggerSFX('sfx:grid-snap') @@ -556,6 +571,7 @@ const PipePointHandles = ({ pipe, target }: { pipe: PipeSegmentNode; target: Obj } const livePreviewIds = new Set() const publishLivePreview = (updates: { id: AnyNodeId; data: Partial }[]) => { + if (!pipeUpdatesPreserveGrades(nodesById, updates)) return const scene = useScene.getState() const entries = updates .filter((update) => scene.nodes[update.id]) @@ -724,6 +740,7 @@ const PipePointHandles = ({ pipe, target }: { pipe: PipeSegmentNode; target: Obj ...plan.updates.filter((u) => scene.nodes[u.id]), ...followUpdates, ] + if (!pipeUpdatesPreserveGrades(nodesById, updates)) return scene.applyNodeChanges({ create: minted.map((node) => ({ node: node as AnyNode, parentId })), delete: (plan.delete ?? []).filter((id) => scene.nodes[id]), @@ -756,6 +773,7 @@ const PipePointHandles = ({ pipe, target }: { pipe: PipeSegmentNode; target: Obj }, ...translationPlan.updates, ] + if (!pipeUpdatesPreserveGrades(nodesById, updates)) return scene.applyNodeChanges({ create: created.map((node) => ({ node: node as AnyNode, @@ -770,6 +788,7 @@ const PipePointHandles = ({ pipe, target }: { pipe: PipeSegmentNode; target: Obj return } const updates = batchFor(finalPath) + if (!pipeUpdatesPreserveGrades(nodesById, updates)) return useScene.getState().updateNodes(updates) ensureSceneObjectsVisible(updates.map((update) => update.id)) } @@ -844,6 +863,16 @@ const PipePointHandles = ({ pipe, target }: { pipe: PipeSegmentNode; target: Obj return ( + {gradeNotice && runCenter && ( + + + {gradeNotice} + + + )} {verticalGhost?.fittings.map((f) => ( ))} diff --git a/packages/nodes/src/pipe-segment/slope.ts b/packages/nodes/src/pipe-segment/slope.ts index 7a97cfe058..1584d48b65 100644 --- a/packages/nodes/src/pipe-segment/slope.ts +++ b/packages/nodes/src/pipe-segment/slope.ts @@ -10,3 +10,60 @@ export function applyPipeGrade(start: Point, end: Point, grade: number): [number if (horizontal < 1e-6 || !Number.isFinite(grade)) return [...end] return [end[0], start[1] - horizontal * grade, end[2]] } + +/** Preserve each leg's grade, including vertical rises, while anchoring one endpoint. */ +export function preservePipeGrades( + initial: readonly Point[], + proposed: readonly Point[], + movedIndex: number, +): [number, number, number][] | null { + if (initial.length !== proposed.length || initial.length < 2) return null + const path = proposed.map((p) => [...p] as [number, number, number]) + const original = initial[movedIndex] + const moved = path[movedIndex] + if (!original || !moved || path.some((p) => p.some((v) => !Number.isFinite(v)))) return null + if (Math.hypot(moved[0] - original[0], moved[2] - original[2]) < 1e-8) { + const dy = moved[1] - original[1] + return initial.map((p) => [p[0], p[1] + dy, p[2]]) + } + const drops: number[] = [] + for (let i = 1; i < path.length; i++) { + const grade = pipeGrade(initial[i - 1]!, initial[i]!) + const length = Math.hypot(path[i]![0] - path[i - 1]![0], path[i]![2] - path[i - 1]![2]) + if (grade === null && length > 1e-6) return null + if (grade !== null && length < 0.001) return null + drops.push(grade === null ? initial[i - 1]![1] - initial[i]![1] : grade * length) + } + if (movedIndex === 0) { + path.at(-1)![1] = initial.at(-1)![1] + for (let i = path.length - 2; i >= 0; i--) path[i]![1] = path[i + 1]![1] + drops[i]! + } else { + path[0]![1] = initial[0]![1] + for (let i = 1; i < path.length; i++) path[i]![1] = path[i - 1]![1] - drops[i - 1]! + } + return path +} + +export function pipeGradesMatch(initial: readonly Point[], next: readonly Point[]): boolean { + if ( + initial.length !== next.length || + next.some((point) => point.some((value) => !Number.isFinite(value))) + ) + return false + for (let i = 1; i < initial.length; i++) { + const before = pipeGrade(initial[i - 1]!, initial[i]!) + const after = pipeGrade(next[i - 1]!, next[i]!) + if (before === null ? after !== null : after === null || Math.abs(before - after) > 1e-6) + return false + } + return true +} + +export function pipeGradeLabel(start: Point, end: Point): string { + if (Math.hypot(...start.map((v, i) => v - end[i]!)) < 1e-6) return 'Choose an endpoint' + const grade = pipeGrade(start, end) + if (grade === null) + return `Vertical · ${start[1] > end[1] ? 'start → end' : 'end → start'} (down)` + if (Math.abs(grade) < 1e-6) return 'Level · no gravity fall' + return `${(Math.abs(grade) * 100).toFixed(2)}% · 1:${(1 / Math.abs(grade)).toFixed(1)} · ${grade > 0 ? 'start → end' : 'end → start'} (down)` +} diff --git a/packages/nodes/src/pipe-segment/tool.tsx b/packages/nodes/src/pipe-segment/tool.tsx index 8063dd9f02..149a4b3454 100644 --- a/packages/nodes/src/pipe-segment/tool.tsx +++ b/packages/nodes/src/pipe-segment/tool.tsx @@ -23,7 +23,7 @@ import { stepNominalRunSize, useDistributionRunTool, } from '@pascal-app/editor/distribution' -import { useEffect, useRef, useState } from 'react' +import { useEffect, useRef } from 'react' import { Vector3 } from 'three' import { planPipeBranchTap, @@ -42,9 +42,11 @@ import { PipeFittingGhost } from '../shared/mep-ghost' import { DWV_PORT_SYSTEMS, runSectionHalfSizeM } from '../shared/port-systems' import { RunHangerPreview } from '../shared/run-hanger-controls' import { useRunHangerMode } from '../shared/run-hanger-mode' +import { clearRunContinuation, updateRunDefaults } from '../shared/run-tool-options' +import { planPipeCollarConnection } from './collar-connection' import { currentPipeContinuationSeed, pipeEndpointPort } from './continuation' import { pipeSegmentDefinition } from './definition' -import { applyPipeGrade } from './slope' +import { applyPipeGrade, pipeGrade, pipeGradeLabel } from './slope' const PIPE_DIAMETERS_IN = [1.25, 1.5, 2, 3, 4, 6] as const const BODY_SNAP_RADIUS_M = 0.3 @@ -87,20 +89,29 @@ const PipeSegmentTool = () => { pipeMaterial: PipeSegmentNode['pipeMaterial'] system: PipeSegmentNode['system'] } - const [system, setSystem] = useState<'waste' | 'vent'>( - continuationSeed?.pipe.system ?? toolDefaults?.system ?? defaults.system, - ) - const [sloped, setSloped] = useState(false) - const slopePercent = 100 / 48 - const slopeDirection = 1 + const system = toolDefaults?.system ?? continuationSeed?.pipe.system ?? defaults.system + const setSystem = ( + value: + | PipeSegmentNode['system'] + | ((current: PipeSegmentNode['system']) => PipeSegmentNode['system']), + ) => + updateRunDefaults('pipe-segment', { + system: typeof value === 'function' ? value(system) : value, + }) + const sloped = hangerDefaults?.fall === 'sloped' + const setSloped = (value: (current: boolean) => boolean) => + updateRunDefaults('pipe-segment', { fall: value(sloped) ? 'sloped' : 'level' }) + const slopePercent = + typeof hangerDefaults?.gradePercent === 'number' ? hangerDefaults.gradePercent : 100 / 48 + const slopeDirection = hangerDefaults?.flowDirection === 'reverse' ? -1 : 1 const gradeRef = useRef(slopePercent / 100) gradeRef.current = (slopeDirection * slopePercent) / 100 - const [diameter, setDiameter] = useState( - continuationSeed?.pipe.diameter ?? toolDefaults?.diameter ?? defaults.diameter, - ) - const [pipeMaterial, setPipeMaterial] = useState( - continuationSeed?.pipe.pipeMaterial ?? toolDefaults?.pipeMaterial ?? defaults.pipeMaterial, - ) + const diameter = toolDefaults?.diameter ?? continuationSeed?.pipe.diameter ?? defaults.diameter + const setDiameter = (diameter: number) => updateRunDefaults('pipe-segment', { diameter }) + const pipeMaterial = + toolDefaults?.pipeMaterial ?? continuationSeed?.pipe.pipeMaterial ?? defaults.pipeMaterial + const setPipeMaterial = (pipeMaterial: PipeSegmentNode['pipeMaterial']) => + updateRunDefaults('pipe-segment', { pipeMaterial }) const systemRef = useRef(system) systemRef.current = system const slopedRef = useRef(sloped) @@ -113,15 +124,22 @@ const PipeSegmentTool = () => { useEffect(() => { const mode = useRunHangerMode.getState() mode.setEnabled('pipe-segment', initialAutoHangersRef.current) - return () => mode.setEnabled('pipe-segment', false) + return () => { + updateRunDefaults('pipe-segment', { + autoHangers: useRunHangerMode.getState().enabled['pipe-segment'], + }) + mode.setEnabled('pipe-segment', false) + } }, []) useEffect(() => { - if (!toolDefaults) return - if (toolDefaults.system) setSystem(toolDefaults.system) - if (typeof toolDefaults.diameter === 'number') setDiameter(toolDefaults.diameter) - if (toolDefaults.pipeMaterial) setPipeMaterial(toolDefaults.pipeMaterial) - }, [toolDefaults]) + if (continuationSeed) + updateRunDefaults('pipe-segment', { + system: continuationSeed.pipe.system, + diameter: continuationSeed.pipe.diameter, + pipeMaterial: continuationSeed.pipe.pipeMaterial, + }) + }, [continuationSeed]) const commitSegment = ({ start: rawStart, @@ -180,16 +198,47 @@ const PipeSegmentTool = () => { const startBend = bendPlanFor(promotedFitting ? null : startConnection.port, direction) const endBend = bendPlanFor(endConnection.port, [-direction[0], -direction[1], -direction[2]]) - const invalidPlan = () => + const invalidPlan = (message = FITTING_CLEARANCE_MESSAGE) => previewOnly ? { - validationMessage: FITTING_CLEARANCE_MESSAGE, + validationMessage: message, nextStart: rawStart, nextConnection: startConnection, previewPipes: [] as PipeSegmentNode[], previewFittings: [] as PipeFittingNode[], } : null + const fixedConnection = (port: ScenePort | null, toward: RunPoint) => { + const owner = port && sceneApi.get(port.nodeId) + return port && owner && owner.type !== 'pipe-segment' + ? planPipeCollarConnection( + sceneApi.nodes(), + port, + toward, + diameterRef.current, + systemRef.current, + pipeMaterialRef.current, + ) + : null + } + let startCollar: ReturnType, + endCollar: ReturnType + try { + startCollar = fixedConnection(promotedFitting ? null : startConnection.port, end) + endCollar = fixedConnection(endConnection.port, start) + } catch (error) { + return invalidPlan(error instanceof Error ? error.message : 'Unable to connect collar.') + } + const actualGrade = pipeGrade(start, end) + if ( + slopedRef.current && + systemRef.current === 'waste' && + actualGrade !== null && + Math.abs(actualGrade - gradeRef.current) > 1e-5 + ) + return invalidPlan( + 'The connection elevation conflicts with the chosen grade. Adjust the grade or target elevation.', + ) if (startBend?.hasClearance === false || endBend?.hasClearance === false) return invalidPlan() const startBody = startBend ? null : startConnection.body const startOwner = startBody ? sceneApi.get(startBody.nodeId) : null @@ -210,14 +259,16 @@ const PipeSegmentTool = () => { : null if (endBody?.nodeId === startBody?.nodeId) endTap = null - const pipeStart = startBend?.collarPoint ?? startTap?.branchCollar ?? start - const pipeEnd = endBend?.collarPoint ?? endTap?.branchCollar ?? end + const pipeStart = + startBend?.collarPoint ?? startTap?.branchCollar ?? startCollar?.point ?? start + const pipeEnd = endBend?.collarPoint ?? endTap?.branchCollar ?? endCollar?.point ?? end const bends = [startBend, endBend].filter((plan) => plan !== null) - const crossHit = surfaceTarget - ? findRunBodyCrossingSurface(start, end, BODY_SNAP_RADIUS_M, surfaceTarget, { - kinds: ['pipe-segment'], - }) - : null + const crossHit = + surfaceTarget && hangerDefaults?.crossingMode !== 'cross' + ? findRunBodyCrossingSurface(start, end, BODY_SNAP_RADIUS_M, surfaceTarget, { + kinds: ['pipe-segment'], + }) + : null const crossOwner = crossHit ? sceneApi.get(crossHit.nodeId) : null const cross = crossHit && @@ -282,6 +333,17 @@ const PipeSegmentTool = () => { return { ...pipe, wallAttachment } } const attachedPipes = pipes.map(attachPipe) + if ( + slopedRef.current && + systemRef.current === 'waste' && + attachedPipes.some((pipe) => { + const grade = pipeGrade(pipe.path[0]!, pipe.path.at(-1)!) + return grade !== null && Math.abs(grade - gradeRef.current) > 1e-5 + }) + ) + return invalidPlan( + 'The fitting collars cannot maintain the chosen grade. Adjust the connection or grade.', + ) const sceneNodes = sceneApi.nodes() const consumedEndCapIds = Array.from( new Set([ @@ -300,6 +362,10 @@ const PipeSegmentTool = () => { const changes = { create: [ + ...[...(startCollar?.fittings ?? []), ...(endCollar?.fittings ?? [])].map((node) => ({ + node, + parentId: activeLevelId, + })), ...bends.map((plan) => ({ node: plan.fitting, parentId: activeLevelId, @@ -379,6 +445,14 @@ const PipeSegmentTool = () => { active: !!activeLevelId, levelId: activeLevelId, toolName: 'pipe-segment', + routingMode: + hangerDefaults?.routingMode === 'horizontal' || hangerDefaults?.routingMode === 'vertical' + ? hangerDefaults.routingMode + : 'surface', + elevation: typeof hangerDefaults?.elevation === 'number' ? hangerDefaults.elevation : 0, + targetElevation: + typeof hangerDefaults?.targetElevation === 'number' ? hangerDefaults.targetElevation : 3, + connectCrossings: hangerDefaults?.crossingMode !== 'cross', initialStart: continuationSeed ? ([ ...(continuationSeed.port?.position ?? continuationSeed.body?.point ?? [0, 0, 0]), @@ -396,16 +470,49 @@ const PipeSegmentTool = () => { surfaceClearance: (surface) => (surface ? runSectionHalfSizeM(diameterRef.current) : 0), minimumSegmentLength: 0.05, resolveFreeEnd: (start, end, startConnection) => { + const port = startConnection.port + if ( + port && + sceneApi.get(port.nodeId)?.type !== 'pipe-segment' && + !pendingPromotionRef.current + ) { + const axis = new Vector3(...port.direction).normalize() + const distance = Math.max(0, new Vector3(...end).sub(new Vector3(...start)).dot(axis)) + return new Vector3(...start).addScaledVector(axis, distance).toArray() as RunPoint + } if (!slopedRef.current || systemRef.current !== 'waste') return end return applyPipeGrade(start, end, gradeRef.current) }, inheritFromConnection: ({ port, body }) => { const ownerId = port?.nodeId ?? body?.nodeId const owner = ownerId ? sceneApi.get(ownerId) : null - if (owner?.type !== 'pipe-segment') return + if (owner?.type !== 'pipe-segment') { + if (port && (port.system === 'waste' || port.system === 'vent')) { + setDiameter(port.diameter) + setSystem(port.system) + if (owner && 'pipeMaterial' in owner) setPipeMaterial(owner.pipeMaterial) + const grade = pipeGrade([0, 0, 0], [...port.direction]) ?? 0 + updateRunDefaults('pipe-segment', { + fall: Math.abs(grade) > 1e-6 ? 'sloped' : 'level', + gradePercent: Math.abs(grade) * 100, + flowDirection: grade < 0 ? 'reverse' : 'forward', + }) + } + return + } setDiameter(owner.diameter) setPipeMaterial(owner.pipeMaterial) setSystem(owner.system) + const index = body?.segmentIndex ?? (port?.id === 'start' ? 0 : owner.path.length - 2) + const grade = pipeGrade(owner.path[index]!, owner.path[index + 1]!) + if (grade !== null) { + const inherited = port?.id === 'start' ? -grade : grade + updateRunDefaults('pipe-segment', { + fall: Math.abs(grade) > 1e-6 ? 'sloped' : 'level', + gradePercent: Math.abs(grade) * 100, + flowDirection: inherited < 0 ? 'reverse' : 'forward', + }) + } }, commit: commitSegment, onShortcut: (event) => { @@ -439,7 +546,7 @@ const PipeSegmentTool = () => { // biome-ignore lint/correctness/useExhaustiveDependencies: settings must refresh a stationary cursor useEffect(() => { if (!run.altActive) refreshCursor() - }, [sloped, system, run.altActive, refreshCursor]) + }, [sloped, slopePercent, slopeDirection, system, diameter, run.altActive, refreshCursor]) const displayStart = run.start const previewPlan = @@ -465,14 +572,23 @@ const PipeSegmentTool = () => { }) }, [autoHangers, hangerStyle, diameter, displayStart, run.cursor, system]) useEffect(() => () => usePathDraftPreview.getState().clear('pipe-segment'), []) - useEffect(() => () => useEditor.getState().setToolDefaults('pipe-segment', null), []) + useEffect(() => () => clearRunContinuation('pipe-segment'), []) if (!activeLevelId) return null return ( @@ -480,6 +596,7 @@ const PipeSegmentTool = () => { altActive={run.altActive} cursor={run.cursor} directionMode={run.directionMode} + routingMode={run.routingMode} extraParts={[{ key: 'diameter', prefix: 'Ø', value: diameter * 0.0254 }]} lengthInput={run.lengthInput} onLengthInputChange={run.onLengthInputChange} diff --git a/packages/nodes/src/pipe-trap/geometry.ts b/packages/nodes/src/pipe-trap/geometry.ts index d0f85a8ae4..dcea7e2cd3 100644 --- a/packages/nodes/src/pipe-trap/geometry.ts +++ b/packages/nodes/src/pipe-trap/geometry.ts @@ -1,5 +1,6 @@ import { DoubleSide, Group, Mesh, SphereGeometry, TorusGeometry, Vector3 } from 'three' -import { buildSection, INCHES_TO_METERS } from '../duct-segment/geometry' +import { buildSection } from '../duct-segment/geometry' +import { INCHES_TO_METERS } from '../duct-segment/profile' import { createPipeMaterial } from '../pipe-segment/geometry' import type { PipeTrapNode } from './schema' diff --git a/packages/nodes/src/pipe-trap/parametrics.ts b/packages/nodes/src/pipe-trap/parametrics.ts index 502377cb6c..f060c95fdd 100644 --- a/packages/nodes/src/pipe-trap/parametrics.ts +++ b/packages/nodes/src/pipe-trap/parametrics.ts @@ -2,6 +2,7 @@ import type { ParametricDescriptor } from '@pascal-app/core' import type { PipeTrapNode } from './schema' export const pipeTrapParametrics: ParametricDescriptor = { + trailingSection: () => import('../shared/pipe-collar-inspector'), groups: [ { label: 'Trap', diff --git a/packages/nodes/src/shared/accessory-placement.ts b/packages/nodes/src/shared/accessory-placement.ts index 464f7da39f..6f6021ab4c 100644 --- a/packages/nodes/src/shared/accessory-placement.ts +++ b/packages/nodes/src/shared/accessory-placement.ts @@ -2,7 +2,7 @@ import type { AnyNode, AnyNodeId, DuctFittingNode, PipeFittingNode } from '@pasc import type { ScenePort } from '@pascal-app/editor/distribution' import { Euler, Matrix4, Quaternion, Vector3 } from 'three' import { adapterShape } from '../duct-fitting/ports' -import { rectSectionAxes } from '../duct-segment/geometry' +import { rectSectionAxes } from '../duct-segment/profile' import { reducerOutletDiameter } from './reducer-size' export function inheritFittingProfile( diff --git a/packages/nodes/src/shared/auto-fitting.ts b/packages/nodes/src/shared/auto-fitting.ts index 4952968a5f..a5b7a89efc 100644 --- a/packages/nodes/src/shared/auto-fitting.ts +++ b/packages/nodes/src/shared/auto-fitting.ts @@ -11,7 +11,7 @@ import { ductPortDiameterIn, equivalentDiameterIn, ovalEquivalentDiameterIn, -} from '../duct-segment/geometry' +} from '../duct-segment/profile' import { pipeFittingLegLength } from '../pipe-fitting/ports' /** Turns shallower than this read as a straight continuation — butt-join diff --git a/packages/nodes/src/shared/automatic-run-end-cap.test.ts b/packages/nodes/src/shared/automatic-run-end-cap.test.ts index 7a8c80ac43..977833b841 100644 --- a/packages/nodes/src/shared/automatic-run-end-cap.test.ts +++ b/packages/nodes/src/shared/automatic-run-end-cap.test.ts @@ -72,6 +72,28 @@ describe('automatic run end caps', () => { expect(isRunEndCapPort({ ...inlet, nodeId: cap.id }, nodes)).toBe(true) }) + test('spiral ducts use sheet-metal end caps at both collars', () => { + const duct = DuctSegmentNode.parse({ + path: [ + [0, 1, 0], + [3, 1, 0], + ], + shape: 'round', + diameter: 6, + ductMaterial: 'spiral', + }) + for (const endpoint of ['start', 'end'] as const) { + const cap = createDuctRunEndCap(duct, endpoint)! + expect(cap.ductMaterial).toBe('sheet-metal') + expect(cap.diameter).toBe(6) + const inlet = getDuctFittingPorts(cap)[0]! + expect(inlet.position[0]).toBeCloseTo(endpoint === 'start' ? 0 : 3) + expect(inlet.position[1]).toBeCloseTo(1) + expect(inlet.position[2]).toBeCloseTo(0) + } + expect(duct.ductMaterial).toBe('spiral') + }) + test('closes a vertical vent pipe and preserves its material', () => { const pipe = PipeSegmentNode.parse({ path: [ diff --git a/packages/nodes/src/shared/automatic-run-end-cap.ts b/packages/nodes/src/shared/automatic-run-end-cap.ts index 7a34211234..70ae735fd7 100644 --- a/packages/nodes/src/shared/automatic-run-end-cap.ts +++ b/packages/nodes/src/shared/automatic-run-end-cap.ts @@ -9,7 +9,7 @@ import { import type { ScenePort } from '@pascal-app/editor/distribution' import { Euler, Quaternion, Vector3 } from 'three' import { localFittingPorts } from '../duct-fitting/ports' -import { ductPortDiameterIn } from '../duct-segment/geometry' +import { ductPortDiameterIn } from '../duct-segment/profile' import { localPipeFittingPorts } from '../pipe-fitting/ports' import { accessoryMateQuaternion } from './accessory-placement' @@ -83,7 +83,7 @@ export function createDuctRunEndCap( height2: duct.height, diameter: port.diameter, diameter2: port.diameter, - ductMaterial: duct.ductMaterial, + ductMaterial: duct.ductMaterial === 'spiral' ? 'sheet-metal' : duct.ductMaterial, system: duct.system, }) const rotation = accessoryMateQuaternion(cap, port, { @@ -214,3 +214,20 @@ export function planRunEndCapFollowUpdates( data: { position: placed.position, rotation: placed.rotation } as Partial, })) } + +/** A split transfers the far cap to the new tail without moving its collar. */ +export function transferRunEndCapOwnership( + nodes: Readonly>, + previousId: AnyNodeId, + nextId: AnyNodeId, + endpoint: 'start' | 'end', +): { id: AnyNodeId; data: Partial }[] { + return Object.values(nodes).flatMap((node) => + (node.type === 'pipe-fitting' || node.type === 'duct-fitting') && + node.fittingType === 'end-cap' && + node.metadata[END_CAP_OWNER_ID_KEY] === previousId && + node.metadata[END_CAP_ENDPOINT_KEY] === endpoint + ? [{ id: node.id, data: { metadata: { ...node.metadata, [END_CAP_OWNER_ID_KEY]: nextId } } }] + : [], + ) +} diff --git a/packages/nodes/src/shared/connection-feedback.tsx b/packages/nodes/src/shared/connection-feedback.tsx index b8d3c46dd4..7cdf2a975e 100644 --- a/packages/nodes/src/shared/connection-feedback.tsx +++ b/packages/nodes/src/shared/connection-feedback.tsx @@ -13,8 +13,11 @@ import { collectScenePorts, connectionCompatibility, findNearestPort3D, + type PortScreenPoint, type ScenePort, } from '@pascal-app/editor/distribution' +import { Html } from '@react-three/drei' +import { createPortal } from 'react-dom' const COLORS = { match: '#16a34a', adapter: '#d97706', incompatible: '#dc2626', unknown: '#d97706' } @@ -23,21 +26,62 @@ export function ConnectionFeedback({ profile, levelId, target, + screen, + detail, + error, }: { point: [number, number, number] | null profile: ConnectionProfile levelId: AnyNodeId + detail?: string + error?: string | null + screen?: PortScreenPoint | null target?: ScenePort | null }) { useEditor((state) => state.snappingModeByContext) - if (!point || !(isGridSnapActive() || isMagneticSnapActive() || isAngleSnapActive())) return null + if ( + !point || + (!error && !detail && !(isGridSnapActive() || isMagneticSnapActive() || isAngleSnapActive())) + ) + return null const port = target === undefined ? findNearestPort3D(point, collectScenePorts({ levelId }), 0.5) : target - if (!port) return null - const feedback = connectionCompatibility(profile, port) - const color = COLORS[feedback.status] + if (!port && !detail && !error) return null + const feedback = port + ? connectionCompatibility(profile, port) + : { status: 'adapter' as const, label: 'Route preview' } + const color = COLORS[error ? 'incompatible' : feedback.status] + const label = ( + + {error || feedback.label} + {detail && {detail}} + + ) return ( - + + + {screen + ? createPortal( + + {label} + , + document.body, + ) + : label} + {}}> diff --git a/packages/nodes/src/shared/duct-adapter.ts b/packages/nodes/src/shared/duct-adapter.ts index 39de6403e2..77e77116ec 100644 --- a/packages/nodes/src/shared/duct-adapter.ts +++ b/packages/nodes/src/shared/duct-adapter.ts @@ -2,7 +2,7 @@ import { DuctFittingNode } from '@pascal-app/core' import type { ScenePort } from '@pascal-app/editor/distribution' import { Euler, Matrix4, Vector3 } from 'three' import { fittingLegLength } from '../duct-fitting/ports' -import { rectSectionAxes } from '../duct-segment/geometry' +import { rectSectionAxes } from '../duct-segment/profile' import { type DuctProfile, profileDiameterIn } from './auto-fitting' export function ductProfilesMatch(a: DuctProfile, b: DuctProfile): boolean { diff --git a/packages/nodes/src/shared/duct-collar-inspector.tsx b/packages/nodes/src/shared/duct-collar-inspector.tsx new file mode 100644 index 0000000000..960712cbef --- /dev/null +++ b/packages/nodes/src/shared/duct-collar-inspector.tsx @@ -0,0 +1,65 @@ +'use client' + +import { type AnyNode, nodeRegistry, useScene } from '@pascal-app/core' +import { useEditor } from '@pascal-app/editor' +import { useViewer } from '@pascal-app/viewer' +import { Vector3 } from 'three' + +export default function DuctCollarInspector({ node }: { node: AnyNode }) { + const nodes = useScene((state) => state.nodes) + const ports = nodeRegistry.get(node.type)?.ports?.(node) ?? [] + const others = Object.values(nodes) + .filter((other) => other.id !== node.id && other.parentId === node.parentId) + .flatMap((other) => nodeRegistry.get(other.type)?.ports?.(other) ?? []) + const airPorts = ports.filter((port) => port.system === 'supply' || port.system === 'return') + if (!airPorts.length) return null + return ( + + Connect duct + {airPorts.map((port) => { + const occupied = others.some( + (other) => + new Vector3(...other.position).distanceTo(new Vector3(...port.position)) < 0.005 && + new Vector3(...other.direction).dot(new Vector3(...port.direction)) < -0.99, + ) + const size = + port.shape && port.shape !== 'round' + ? `${port.width} × ${port.height}` + : `${port.diameter}` + return ( + { + const editor = useEditor.getState() + editor.setToolDefaults('duct-segment', { + ...editor.toolDefaults['duct-segment'], + continuation: { nodeId: node.id, portId: port.id }, + shape: port.shape ?? 'round', + diameter: port.diameter, + width: port.width ?? 14, + height: port.height ?? 8, + system: port.system, + ductMaterial: 'sheet-metal', + elevation: port.position[1], + routingMode: + Math.hypot(port.direction[0], port.direction[2]) < 1e-6 + ? 'vertical' + : 'horizontal', + targetElevation: port.position[1] + Math.sign(port.direction[1] || 1), + crossingMode: 'connect', + }) + useViewer.getState().setSelection({ selectedIds: [] }) + editor.setTool('duct-segment') + }} + > + {port.system === 'return' ? 'Return' : 'Supply'} · {size} in ·{' '} + {occupied ? 'Connected' : 'Draw from collar'} + + ) + })} + + ) +} diff --git a/packages/nodes/src/shared/fitting-catalog-selection.test.ts b/packages/nodes/src/shared/fitting-catalog-selection.test.ts index 2ef3e40009..6f96c270b3 100644 --- a/packages/nodes/src/shared/fitting-catalog-selection.test.ts +++ b/packages/nodes/src/shared/fitting-catalog-selection.test.ts @@ -239,3 +239,55 @@ test('choosing a round transition inlet automatically selects a rectangular outl expect(defaults.inletShape).toBe('round') expect(defaults.outletShape).toBe('rect') }) + +test('run options retain independent settings and discard consumed continuation context', async () => { + const { ductSegmentDefinition, pipeSegmentDefinition } = await import('../index') + const { clearRunContinuation } = await import('./run-tool-options') + const previous = useEditor.getState().toolDefaults + try { + useEditor.setState({ toolDefaults: {} }) + const duct = ductSegmentDefinition.toolOptions! + const pipe = pipeSegmentDefinition.toolOptions! + duct.find((option) => option.id === 'shape')!.set('round') + duct.find((option) => option.id === 'diameter')!.set('10') + pipe.find((option) => option.id === 'diameter')!.set('4') + pipe.find((option) => option.id === 'fall')!.set('sloped') + useEditor.getState().setToolDefaults('duct-segment', { + ...useEditor.getState().toolDefaults['duct-segment'], + continuation: { nodeId: 'duct-segment_old', endpoint: 'end' }, + }) + clearRunContinuation('duct-segment') + expect(duct.find((option) => option.id === 'diameter')!.value()).toBe('10') + expect(pipe.find((option) => option.id === 'diameter')!.value()).toBe('4') + expect(pipe.find((option) => option.id === 'fall')!.value()).toBe('sloped') + expect(useEditor.getState().toolDefaults['duct-segment']?.continuation).toBeUndefined() + duct.find((option) => option.id === 'diameter')!.set('NaN') + duct.find((option) => option.id === 'diameter')!.set('100') + expect(duct.find((option) => option.id === 'diameter')!.value()).toBe('10') + } finally { + useEditor.setState({ toolDefaults: previous }) + } +}) + +test('duct presets apply a complete profile without resetting route preferences', async () => { + const { ductRunToolOptions } = await import('./run-tool-options') + useEditor.getState().setToolDefaults('duct-segment', { + routingMode: 'horizontal', + elevation: 2.4, + crossingMode: 'cross', + }) + const preset = ductRunToolOptions.find((option) => option.id === 'preset')! + preset.set('return') + expect(useEditor.getState().toolDefaults['duct-segment']).toMatchObject({ + shape: 'rect', + width: 20, + height: 10, + system: 'return', + ductMaterial: 'sheet-metal', + elevation: 2.4, + crossingMode: 'cross', + }) + expect(preset.value()).toBe('return') + ductRunToolOptions.find((option) => option.id === 'width')!.set('22') + expect(preset.value()).toBe('custom') +}) diff --git a/packages/nodes/src/shared/pipe-collar-inspector.tsx b/packages/nodes/src/shared/pipe-collar-inspector.tsx new file mode 100644 index 0000000000..bfc1efaee6 --- /dev/null +++ b/packages/nodes/src/shared/pipe-collar-inspector.tsx @@ -0,0 +1,60 @@ +'use client' + +import { type AnyNode, nodeRegistry, useScene } from '@pascal-app/core' +import { useEditor } from '@pascal-app/editor' +import { useViewer } from '@pascal-app/viewer' +import { pipeCollarOccupied } from '../pipe-segment/collar-connection' +import { pipeGrade } from '../pipe-segment/slope' + +export default function PipeCollarInspector({ node }: { node: AnyNode }) { + const nodes = useScene((state) => state.nodes) + const ports = nodeRegistry.get(node.type)?.ports?.(node) ?? [] + const pipePorts = ports.filter((port) => port.system === 'waste' || port.system === 'vent') + if (!pipePorts.length) return null + return ( + + Connect pipe + {pipePorts.map((port) => { + const occupied = pipeCollarOccupied(nodes, { ...port, nodeId: node.id }) + return ( + { + const editor = useEditor.getState() + editor.setToolDefaults('pipe-segment', { + ...editor.toolDefaults['pipe-segment'], + continuation: { nodeId: node.id, portId: port.id }, + diameter: port.diameter, + system: port.system, + pipeMaterial: 'pipeMaterial' in node ? node.pipeMaterial : 'pvc', + elevation: port.position[1], + routingMode: + Math.hypot(port.direction[0], port.direction[2]) < 1e-6 + ? 'vertical' + : 'horizontal', + targetElevation: port.position[1] + Math.sign(port.direction[1] || 1), + ...(() => { + const grade = pipeGrade([0, 0, 0], [...port.direction]) ?? 0 + return { + fall: Math.abs(grade) > 1e-6 ? 'sloped' : 'level', + gradePercent: Math.abs(grade) * 100, + flowDirection: grade < 0 ? 'reverse' : 'forward', + } + })(), + crossingMode: 'connect', + }) + useViewer.getState().setSelection({ selectedIds: [] }) + editor.setTool('pipe-segment') + }} + > + {port.id} · {port.diameter} in · {port.position[1].toFixed(3)} m ·{' '} + {occupied ? 'Connected' : 'Draw from collar'} + + ) + })} + + ) +} diff --git a/packages/nodes/src/shared/run-hangers.ts b/packages/nodes/src/shared/run-hangers.ts index 73d83d400b..e4472a1b91 100644 --- a/packages/nodes/src/shared/run-hangers.ts +++ b/packages/nodes/src/shared/run-hangers.ts @@ -26,7 +26,7 @@ import { Vector2, Vector3, } from 'three' -import { rectSectionAxes } from '../duct-segment/geometry' +import { rectSectionAxes } from '../duct-segment/profile' import { hasWallChildOverlap, resolveWallAttachmentAtPlanPoint } from './wall-attach-target' export type SupportedRun = DuctSegmentNode | PipeSegmentNode diff --git a/packages/nodes/src/shared/run-tool-options.ts b/packages/nodes/src/shared/run-tool-options.ts new file mode 100644 index 0000000000..466dfefb3a --- /dev/null +++ b/packages/nodes/src/shared/run-tool-options.ts @@ -0,0 +1,260 @@ +import type { ToolOption } from '@pascal-app/core' +import { useEditor } from '@pascal-app/editor' + +type RunKind = 'duct-segment' | 'pipe-segment' + +export function updateRunDefaults(kind: RunKind, patch: Record): void { + const editor = useEditor.getState() + editor.setToolDefaults(kind, { ...editor.toolDefaults[kind], ...patch }) +} + +export function clearRunContinuation(kind: RunKind): void { + const { continuation: _continuation, ...settings } = useEditor.getState().toolDefaults[kind] ?? {} + useEditor.getState().setToolDefaults(kind, settings) +} + +function choice( + kind: RunKind, + key: string, + label: string, + values: readonly [string, string, string?][], + fallback: string, +): ToolOption { + return { + id: key, + label, + choices: values.map(([value, label, description]) => ({ value, label, description })), + subscribe: useEditor.subscribe, + value: () => String(useEditor.getState().toolDefaults[kind]?.[key] ?? fallback), + set: (value) => updateRunDefaults(kind, { [key]: value }), + } +} + +function number( + kind: RunKind, + key: string, + label: string, + fallback: number, + input: NonNullable, +): ToolOption { + return { + ...choice(kind, key, label, [], String(fallback)), + input, + set: (value) => { + const next = Number(value) + if ( + !Number.isFinite(next) || + (input.min !== undefined && next < input.min) || + (input.max !== undefined && next > input.max) + ) + return + updateRunDefaults(kind, { [key]: next }) + }, + } +} + +function routing(kind: RunKind): ToolOption[] { + return [ + choice( + kind, + 'routingMode', + 'Route', + [ + ['surface', 'Follow surface', 'Follow the floor, wall, or ceiling under the pointer.'], + [ + 'horizontal', + kind === 'pipe-segment' ? 'Plan route' : 'Horizontal', + kind === 'pipe-segment' + ? 'Follow a plan direction, applying the chosen fall from the start elevation.' + : 'Keep the run at its starting elevation.', + ], + ['vertical', 'Vertical', 'Keep X and Z fixed. Enter the target elevation below.'], + ], + 'surface', + ), + { + ...number(kind, 'elevation', 'Start elevation above level', 0, { unit: 'm', step: 0.01 }), + visible: { + subscribe: useEditor.subscribe, + value: () => + ['horizontal', 'vertical'].includes( + String(useEditor.getState().toolDefaults[kind]?.routingMode), + ), + }, + }, + { + ...number(kind, 'targetElevation', 'Target elevation above level', 3, { + unit: 'm', + step: 0.01, + }), + visible: { + subscribe: useEditor.subscribe, + value: () => useEditor.getState().toolDefaults[kind]?.routingMode === 'vertical', + }, + }, + choice( + kind, + 'crossingMode', + 'Crossing another run', + [ + ['connect', 'Connect', 'Insert a fitting where runs meet.'], + [ + 'cross', + 'Cross without joining', + 'Keep the runs separate. This does not provide physical clearance.', + ], + ], + 'connect', + ), + ] +} + +const ductProfile = (round: boolean) => ({ + subscribe: useEditor.subscribe, + value: () => (useEditor.getState().toolDefaults['duct-segment']?.shape === 'round') === round, +}) + +const ductPresets = { + trunk: { shape: 'rect', width: 14, height: 8, ductMaterial: 'sheet-metal', system: 'supply' }, + branch: { shape: 'round', diameter: 6, ductMaterial: 'spiral', system: 'supply' }, + flex: { shape: 'round', diameter: 6, ductMaterial: 'flex', system: 'supply' }, + return: { shape: 'rect', width: 20, height: 10, ductMaterial: 'sheet-metal', system: 'return' }, +} as const + +export const ductRunToolOptions: ToolOption[] = [ + { + ...choice( + 'duct-segment', + 'preset', + 'Starting profile', + [ + ['custom', 'Custom'], + ['trunk', 'Supply trunk · 14 × 8 in'], + ['branch', 'Round branch · 6 in'], + ['flex', 'Flex connection · 6 in'], + ['return', 'Return trunk · 20 × 10 in'], + ], + 'custom', + ), + value: () => { + const current = useEditor.getState().toolDefaults['duct-segment'] ?? {} + return ( + Object.entries(ductPresets).find(([, preset]) => + Object.entries(preset).every(([key, value]) => current[key] === value), + )?.[0] ?? 'custom' + ) + }, + set: (value) => { + const preset = ductPresets[value as keyof typeof ductPresets] + if (preset) updateRunDefaults('duct-segment', preset) + }, + }, + choice( + 'duct-segment', + 'system', + 'System', + [ + ['supply', 'Supply'], + ['return', 'Return'], + ], + 'supply', + ), + choice( + 'duct-segment', + 'shape', + 'Profile', + [ + ['round', 'Round'], + ['rect', 'Rectangular'], + ['oval', 'Oval'], + ], + 'rect', + ), + { + ...number('duct-segment', 'diameter', 'Diameter', 6, { min: 2, max: 48, unit: 'in' }), + visible: ductProfile(true), + }, + { + ...number('duct-segment', 'width', 'Width', 14, { min: 4, max: 60, unit: 'in' }), + visible: ductProfile(false), + }, + { + ...number('duct-segment', 'height', 'Height', 8, { min: 3, max: 40, unit: 'in' }), + visible: ductProfile(false), + }, + choice( + 'duct-segment', + 'ductMaterial', + 'Material', + [ + ['flex', 'Flex'], + ['sheet-metal', 'Sheet metal'], + ['spiral', 'Spiral'], + ['duct-board', 'Ductboard'], + ], + 'flex', + ), + ...routing('duct-segment'), +] + +export const pipeRunToolOptions: ToolOption[] = [ + choice( + 'pipe-segment', + 'system', + 'System', + [ + ['waste', 'Waste'], + ['vent', 'Vent'], + ], + 'waste', + ), + number('pipe-segment', 'diameter', 'Diameter', 2, { min: 1.25, max: 8, unit: 'in' }), + choice( + 'pipe-segment', + 'pipeMaterial', + 'Material', + [ + ['pvc', 'PVC'], + ['abs', 'ABS'], + ['cast-iron', 'Cast iron'], + ], + 'pvc', + ), + { + ...choice( + 'pipe-segment', + 'fall', + 'Fall', + [ + ['level', 'Level'], + ['sloped', 'Graded', 'Apply the grade and flow direction below.'], + ], + 'level', + ), + visible: { + subscribe: useEditor.subscribe, + value: () => + (useEditor.getState().toolDefaults['pipe-segment']?.system ?? 'waste') === 'waste', + }, + }, + { + ...number('pipe-segment', 'gradePercent', 'Grade', 100 / 48, { min: 0, step: 0.1, unit: '%' }), + visible: { + subscribe: useEditor.subscribe, + value: () => + useEditor.getState().toolDefaults['pipe-segment']?.fall === 'sloped' && + (useEditor.getState().toolDefaults['pipe-segment']?.system ?? 'waste') === 'waste', + }, + }, + choice( + 'pipe-segment', + 'flowDirection', + 'Downhill flow', + [ + ['forward', 'Start → end'], + ['reverse', 'End → start'], + ], + 'forward', + ), + ...routing('pipe-segment'), +] diff --git a/packages/nodes/src/shared/vertical-offset.ts b/packages/nodes/src/shared/vertical-offset.ts index 1084f53948..4ed099d12a 100644 --- a/packages/nodes/src/shared/vertical-offset.ts +++ b/packages/nodes/src/shared/vertical-offset.ts @@ -8,7 +8,7 @@ import type { ScenePort } from '@pascal-app/editor/distribution' import { Vector3 } from 'three' import { fittingLegLength, getDuctFittingPorts } from '../duct-fitting/ports' import type { DuctFittingNode } from '../duct-fitting/schema' -import { rollToContinueAcrossElbow } from '../duct-segment/geometry' +import { rollToContinueAcrossElbow } from '../duct-segment/profile' import { type DuctProfile, type ElbowJointPlan, diff --git a/wiki/architecture/tools.md b/wiki/architecture/tools.md index 15869b07e9..1befb5260a 100644 --- a/wiki/architecture/tools.md +++ b/wiki/architecture/tools.md @@ -415,3 +415,106 @@ node, parent and context nodes. This supports tools whose ghosts never enter the committed scene. The helper merges that preview only for the notice query; moving nodes still use their kind's live-transform frame, and selected inspectors call `usePlacementNotice(id)` without adopting a tool's preview. + + +## Duct and pipe build settings + +Duct and DWV run definitions contribute `toolOptions` for system, profile/size, +material, routing and crossing intent. `ToolOption.input` lets a host render an +exact numeric field with the schema's limits instead of a fixed choice list. +The settings share `useEditor.toolDefaults` with keyboard shortcuts and survive +switching tools within the session. Continuation context is consumed separately; +returning to a tool must not resume an old endpoint. + +Follow surface keeps the existing floor/wall/ceiling behavior. Horizontal starts +at a level-local centreline elevation; the pipe fall setting still applies. +Vertical keeps X/Z fixed and uses an exact target elevation, available in either +view. Alt retains the existing temporary vertical-drag behavior. Sidebar changes +refresh the draft without requiring another pointer move. + +Connect retains automatic branch/cross fittings. Cross without joining disables +body snapping and automatic interior crosses while leaving endpoint connections +available. It creates no clearance or obstacle detour. Preview and commit consume +the same choice. Connection feedback includes text as well as color, with screen +coordinates for snapped-port labels in the plan view. + +Duct routing adds supply-trunk, round-branch, flex and return-trunk starting +profiles. These are editable dimensional presets, not airflow sizing calculations. +Equipment and terminal inspectors can start a run from an unoccupied air collar, +carrying its section and system. Transition feedback includes both sections and +the planned fitting length. + +Duct profile edits use the `duct_edit` operation in both the inspector and agent +hosts. Segment scope inserts transitions against fixed neighbours; branch scope +follows same-profile ducts through elbows, couplings, dampers and caps, stopping +at junctions, size changes and equipment. Changed fitting collars retarget the +joined run endpoints. Insufficient space refuses the entire edit. Face alignment +supports free straight runs; connected routes require center alignment because +current fittings do not represent eccentric transitions. There is no separate +node-lock contract for this operation. + +The same operation adds a measured vertical obstacle offset to a straight +horizontal run: four elbows and intervening ducts preserve both original +endpoints. The inspector previews a side elevation before applying. This is a +manual routing aid, not collision detection or an automatic obstacle solver. +Rolled non-round runs are refused because the offset cannot express the required +twist. Both operations apply one scene change batch and invalidate stale offset +rewind metadata. The inspector is shared by 2D and 3D. + +Pipe grade remains derived from path elevations; existing scenes need no new +fields. Drawing offers grade percentage and downhill direction, and reports +start/end centerline elevations above the level. Continuing at either end +inherits the source leg’s signed grade. Snapped connections that conflict with +the requested grade are refused, including fitting collar adjustments. + +`pipe_grade` provides the inspector and agent operation for applying grade with +a fixed start/end elevation, translating elevation without changing grades, +and editing a path point while preserving each leg’s grade. Vertical legs keep +their rise; a stack cannot become a diagonal by dragging one endpoint. Flow +arrows describe downhill geometry, not hydraulic simulation; level runs have no +gravity-flow direction. Plan selection shows downhill chevrons and grade labels. + +Plan point drags use live overrides and commit once. The 3D endpoint tools apply +the same grade constraint before their existing fitting planners. Connected +collars that cannot turn cleanly, or neighbours whose grade would change, refuse +the edit. Alt detaches a path-point edit while retaining the edited run’s grade. +Explicit grade edits may change the selected run’s grade; connected runs retain +theirs. Profile resizing is unchanged because diameter does not alter the stored +centerline path. + +Pipe size edits use the `pipe_resize` operation from both the inspector (plan and +3D views) and agent tools. Segment scope carries end caps; branch scope traverses +same-size, same-material pipes through elbows, couplings and cleanouts. Junctions, +reducers, size/material changes and fixture or equipment collars form boundaries. +The operation inserts reducers into the selected run at fixed boundaries, moves +run endpoints to resized fitting collars, and checks every leg's direction and +signed grade before returning one atomic batch. Ambiguous collars, incompatible +angles and insufficient straight length refuse the entire edit. “Check resize” +reports affected runs, fittings and new reducers without changing the scene. + +`pipe_offset` adds a user-controlled four-bend detour to a straight, non-vertical +pipe. The inspector exposes the same operation in plan and 3D with a side-profile +schematic. `from` and `to` measure horizontal distance from the start to the first +and last bend; `offset` is the signed vertical displacement. Each connector uses +`abs(offset)` horizontal travel. The three parallel sections retain the original +signed grade; the two connectors have their own grades. Boundary positions and +collar directions remain fixed. The original node becomes the first section and +four new runs plus four elbows form the rest, committed in one undo step. The far +automatic cap transfers ownership to the new tail without moving. + +Insufficient fitting space, vertical or polyline source runs, hosted children and +custom hanger overrides refuse without partial edits. Ordinary automatic hangers +regenerate on the new sections. Waste offsets report uphill connectors explicitly; +the operation does not certify continuous downhill drainage or check obstacles. + +Fixed waste/vent collars use `planPipeCollarConnection` in both drawing and the +`pipe_connect` agent operation. Trap and fitting inspectors offer “Draw from +collar”; plugins can reuse the exported `PipeCollarInspector` for fixtures with +registered ports. The seed inherits size, material, elevation and direction. +The first free section follows the collar axis; subsequent turns use ordinary +pipe continuation. Occupied collars are disabled and rechecked before commit. +Diameter changes preview and create a reducer entirely outside the fixed collar; +short, incompatible or stale connections refuse without moving the source. +`pipe_connect` extends to a free endpoint; interactive drawing can also join an +existing open collar. Decorative catalog fixtures without authored waste/vent +ports are not inferred from their mesh. diff --git a/wiki/assets/pr-1115/01-grade-3-percent.png b/wiki/assets/pr-1115/01-grade-3-percent.png new file mode 100644 index 0000000000..5cf48d0e48 Binary files /dev/null and b/wiki/assets/pr-1115/01-grade-3-percent.png differ diff --git a/wiki/assets/pr-1115/02-grade-undo.png b/wiki/assets/pr-1115/02-grade-undo.png new file mode 100644 index 0000000000..8297c2d849 Binary files /dev/null and b/wiki/assets/pr-1115/02-grade-undo.png differ diff --git a/wiki/assets/pr-1115/03-pipe-offset-3d.png b/wiki/assets/pr-1115/03-pipe-offset-3d.png new file mode 100644 index 0000000000..23169a14cb Binary files /dev/null and b/wiki/assets/pr-1115/03-pipe-offset-3d.png differ diff --git a/wiki/assets/pr-1115/04-connected-resize-plan.png b/wiki/assets/pr-1115/04-connected-resize-plan.png new file mode 100644 index 0000000000..dc4fe95467 Binary files /dev/null and b/wiki/assets/pr-1115/04-connected-resize-plan.png differ diff --git a/wiki/assets/pr-1115/05-connected-resize-3d.png b/wiki/assets/pr-1115/05-connected-resize-3d.png new file mode 100644 index 0000000000..9ec59ba979 Binary files /dev/null and b/wiki/assets/pr-1115/05-connected-resize-3d.png differ diff --git a/wiki/assets/pr-1115/06-connect-crossing-2d.png b/wiki/assets/pr-1115/06-connect-crossing-2d.png new file mode 100644 index 0000000000..12c7328185 Binary files /dev/null and b/wiki/assets/pr-1115/06-connect-crossing-2d.png differ diff --git a/wiki/assets/pr-1115/07-cross-without-joining-2d.png b/wiki/assets/pr-1115/07-cross-without-joining-2d.png new file mode 100644 index 0000000000..9d41dd98a1 Binary files /dev/null and b/wiki/assets/pr-1115/07-cross-without-joining-2d.png differ diff --git a/wiki/assets/pr-1115/08-crossings-3d.png b/wiki/assets/pr-1115/08-crossings-3d.png new file mode 100644 index 0000000000..32c8575bb8 Binary files /dev/null and b/wiki/assets/pr-1115/08-crossings-3d.png differ diff --git a/wiki/assets/pr-1115/09-duct-offset-reset.png b/wiki/assets/pr-1115/09-duct-offset-reset.png new file mode 100644 index 0000000000..97406bdd17 Binary files /dev/null and b/wiki/assets/pr-1115/09-duct-offset-reset.png differ diff --git a/wiki/assets/pr-1115/10-duct-offset-undo.png b/wiki/assets/pr-1115/10-duct-offset-undo.png new file mode 100644 index 0000000000..1a45bfa269 Binary files /dev/null and b/wiki/assets/pr-1115/10-duct-offset-undo.png differ
+ Branch stops at junctions, size changes and equipment. Boundary collars stay fixed. +
+ Face alignment applies to free straight runs. Left and right follow the run’s section + axes. +
+ Positive moves up; negative moves down. Four elbows preserve both endpoints. Check the + obstacle’s clearance; this does not detect collisions. +
+ {preview.error || + `${changes?.update?.length ?? 0} existing parts affected · ${changes?.create?.length ?? 0} new parts`} +
{notice}
+ Centerline elevations above level: start {node.path[0]![1].toFixed(3)} m · end{' '} + {node.path.at(-1)![1].toFixed(3)} m +
+ Leg {index + 1}: {pipeGradeLabel(node.path[index]!, point)} +
+ Arrows show downhill direction. Level runs have no gravity fall. Editing a path point + preserves each leg’s grade. +
{message}
+ Choose the first and last bend by horizontal distance from the start. Positive offset goes + up; negative goes down. Each connector uses the offset height in horizontal travel. +
+ Side profile (schematic). Four bends · five pipe sections. Parallel sections keep the + original grade; both end connections stay fixed. +
+ This offset includes an uphill waste section. It does not provide continuous downhill + drainage. +
+ Check obstacle clearance. The preview does not detect collisions. +
{preview.error}
Current diameter: {node.diameter} in
+ Branches stop at junctions, size or material changes, and fixture connections. Reducers keep + boundary collars fixed. +