diff --git a/packages/core/src/services/port-connectivity.test.ts b/packages/core/src/services/port-connectivity.test.ts index 7ab328a709..f22ffa940e 100644 --- a/packages/core/src/services/port-connectivity.test.ts +++ b/packages/core/src/services/port-connectivity.test.ts @@ -309,7 +309,7 @@ describe('port connectivity — joint follow (stretch vs translate)', () => { expectPointClose(path[1]!, [3, 0, 1.200025]) }) - test('a fitting reached from incompatible collars merges constraints deterministically', () => { + test('a fitting its own collars pull apart cannot follow', () => { const moved = makeNode('duct-segment', { path: [ [-0.2, 0, 0], @@ -328,12 +328,7 @@ describe('port connectivity — joint follow (stretch vs translate)', () => { ], } as AnyNode - const updates = resolveConnectivityUpdates(connectivity, preview) - - expectPointClose( - (updates.find((u) => u.id === fitting.id)!.data as { position: Point }).position, - [0, 0, 0], - ) + expect(resolveConnectivityUpdates(connectivity, preview)).toBeNull() }) test('an unrelated run not on the fitting is left alone', () => { @@ -490,6 +485,142 @@ describe('port connectivity — closed loops', () => { }) }) +/** Largest distance from any port of `after` to its nearest mate, for the + * joints that coincided in `before`. */ +function widestJointGap(before: Record, after: Record): number { + const portsOf = (node: AnyNode) => + nodeRegistry.get(node.type)!.ports!(node as never) as Array<{ id: string; position: Point }> + const distance = (a: Point, b: Point) => Math.hypot(a[0] - b[0], a[1] - b[1], a[2] - b[2]) + let widest = 0 + for (const a of Object.values(before)) { + for (const b of Object.values(before)) { + if (a.id >= b.id) continue + for (const pa of portsOf(a)) { + for (const pb of portsOf(b)) { + if (distance(pa.position, pb.position) > 1e-6) continue + const na = portsOf(after[a.id]!).find((p) => p.id === pa.id)! + const nb = portsOf(after[b.id]!).find((p) => p.id === pb.id)! + widest = Math.max(widest, distance(na.position, nb.position)) + } + } + } + } + return widest +} + +describe('port connectivity — polyline runs between fittings', () => { + const corner = (position: Point) => + makeNode('test:corner-elbow', { + position, + collars: [ + [-0.07, 0, 0], + [0, 0, 0.07], + ], + system: 'supply', + }) + const run = (path: Point[]) => makeNode('duct-segment', { path, system: 'supply' }) + + // A straight run, a corner, an L-shaped polyline run, a corner and a tail: + // the far corner only ever follows the L, so it echoes the L's own move. + function chain() { + const south = run([ + [0.07, 1, 0], + [3.93, 1, 0], + ]) + const l = run([ + [4, 1, 0.07], + [4, 1, 2], + [6.93, 1, 2], + ]) + const nodes = sceneOf( + south, + corner([4, 1, 0]), + l, + corner([7, 1, 2]), + run([ + [7, 1, 2.07], + [7, 1, 5], + ]), + ) + return { south, l, nodes } + } + + function moved(node: AnyNode, path: Point[]): AnyNode { + return { ...(node as Record), path } as AnyNode + } + + function applied( + nodes: Record, + preview: AnyNode, + updates: { id: AnyNodeId; data: Partial }[], + ): Record { + const after: Record = { ...nodes, [preview.id]: preview } + for (const update of updates) after[update.id] = { ...after[update.id]!, ...update.data } + return after + } + + test.each([ + [0.3, 0, 0.4], + [0.05, 0, 0.05], + [0.3, 0.2, 0.4], + ] as Point[])('a diagonal move (%p, %p, %p) carries the L without stretching it', (...delta) => { + const { south, l, nodes } = chain() + const preview = moved( + south, + (south as unknown as { path: Point[] }).path.map( + (p) => [p[0] + delta[0], p[1] + delta[1], p[2] + delta[2]] as Point, + ), + ) + + const updates = resolveConnectivityUpdates(analyzePortConnectivity(south, nodes), preview) + + expect(updates).not.toBeNull() + const after = applied(nodes, preview, updates!) + expect(widestJointGap(nodes, after)).toBeLessThan(1e-6) + const lPath = (after[l.id] as unknown as { path: Point[] }).path + expect(Math.hypot(lPath[2]![0] - lPath[1]![0], lPath[2]![2] - lPath[1]![2])).toBeCloseTo( + 2.93, + 6, + ) + }) + + test('a loop back to the moved run refuses a drag that would pull its start corner off', () => { + // The run's end corner leads around a U-shaped run back to its start corner. + const looped = run([ + [0.07, 1, 0], + [3.93, 1, 0], + ]) + const nodes = sceneOf( + makeNode('test:corner-elbow', { + position: [0, 1, 0], + collars: [ + [0.07, 0, 0], + [0, 0, 0.07], + ], + system: 'supply', + }), + looped, + corner([4, 1, 0]), + run([ + [4, 1, 0.07], + [4, 1, 2], + [0, 1, 2], + [0, 1, 0.07], + ]), + ) + const connectivity = analyzePortConnectivity(looped, nodes) + const endAt = (end: Point) => moved(looped, [[0.07, 1, 0], end]) + + // Across the run, the end corner slides the U's first leg; nothing else moves. + const across = resolveConnectivityUpdates(connectivity, endAt([3.93, 1, 0.3])) + expect(across).not.toBeNull() + expect(widestJointGap(nodes, applied(nodes, endAt([3.93, 1, 0.3]), across!))).toBeLessThan(1e-6) + // Along the run, the U translates whole and would carry the start corner + // off the run's fixed start. + expect(resolveConnectivityUpdates(connectivity, endAt([4.43, 1, 0]))).toBeNull() + }) +}) + test('kind-owned connectivity keeps fixed neighbors and snapshots custom move followers', () => { registerNode({ kind: 'test:connected-equipment', diff --git a/packages/core/src/services/port-connectivity.ts b/packages/core/src/services/port-connectivity.ts index b3fee20ecb..2dc22fc579 100644 --- a/packages/core/src/services/port-connectivity.ts +++ b/packages/core/src/services/port-connectivity.ts @@ -38,7 +38,9 @@ import type { AnyNode, AnyNodeId } from '../schema' * pushes it receives per port. In a closed loop whose legs split a push * differently (e.g. one sloped leg), every averaging round re-broadcasts * through both collars of each fitting, so each joint edge holds only its - * newest pending push and the walk has a fixed step budget. + * newest pending push and the walk has a fixed step budget. A follow that + * still leaves a joint open resolves to `null`, so the edit holds its last + * welded frame instead of committing the split. */ type Point = readonly [number, number, number] @@ -53,11 +55,16 @@ const COINCIDENT_EPS_M = 0.05 const DELTA_EPS_M = 1e-4 const PROPAGATION_EPS_M = 1e-9 -/** Walks allowed per joint edge before the resolver keeps its last averaged - * state. Loops settle within a few walks per edge; this only bounds one whose - * averaging never gets below `PROPAGATION_EPS_M`. */ +/** Walk steps per joint edge, pooled across the component. Loops settle within + * a few steps per edge; this only bounds one whose averaging never gets below + * `PROPAGATION_EPS_M`. */ const MAX_WALKS_PER_EDGE = 64 +/** Widest a joint may open (meters) and still count as welded: above + * `DELTA_EPS_M`, the residue the walk stops chasing, and well inside + * `COINCIDENT_EPS_M`, so the next edit still finds the joint. */ +const WELD_EPS_M = 1e-3 + /** A node carried by the edit, plus the snapshot needed to revert it. Kept * deliberately small: the move tools read only `kind` + `nodeId` and the * matching start snapshot to revert before the single tracked commit. */ @@ -368,6 +375,18 @@ function runPathFromPortDeltas(startPath: Point[], portDeltas: Record add(p, startDelta)) } + // A fitting that follows only this run's far end pushes that end's move + // back. Driving the run from one end alone already satisfies such a push; + // the compromise below would shift the end again, and the fitting would + // echo every shift. + for (const [driven, far] of [ + ['start', 'end'], + ['end', 'start'], + ] as const) { + const path = runPathFromSinglePortDelta(startPath, driven, portDeltas[driven]!) + if (nearlyEqual(runEndpointDeltas(startPath, path)[far]!, portDeltas[far]!)) return path + } + const startParts = decompose(startDelta, endpointAxis(startPath, 'start')) const endParts = decompose(endDelta, endpointAxis(startPath, 'end')) const commonPerp = average([startParts.perp, endParts.perp]) @@ -395,11 +414,15 @@ function runPathFromPortDeltas(startPath: Point[], portDeltas: Record }[] { +): { id: AnyNodeId; data: Partial }[] | null { if (connectivity.customResolver) return connectivity.customResolver(previewNode) const { graph, adjacency, startMovedPorts, movedNodeId } = connectivity if (Object.keys(graph).length === 0) return [] @@ -506,5 +529,27 @@ export function resolveConnectivityUpdates( } } + const portDelta = (nodeId: string, portId: string): Point => { + if (nodeId === movedNodeId) { + const start = startMovedPorts[portId] + const now = newMovedPos[portId] + return start && now ? sub(now, start) : [0, 0, 0] + } + const node = graph[nodeId] + const data = results[nodeId]?.data as { position?: Point; path?: Point[] } | undefined + if (!node || !data) return [0, 0, 0] + if (node.role === 'fitting') return sub(data.position!, node.startPosition!) + return runEndpointDeltas(node.startPath!, data.path!)[portId === 'start' ? 'start' : 'end']! + } + for (const [nodeId, byPort] of Object.entries(adjacency)) { + for (const [portId, mates] of Object.entries(byPort)) { + const delta = portDelta(nodeId, portId) + for (const mate of mates) { + const gap = sub(delta, portDelta(mate.nodeId, mate.portId)) + if (lenSq(gap) > WELD_EPS_M * WELD_EPS_M) return null + } + } + } + return Object.values(results) } 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 e5bc9f81a6..6031f1cc1a 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 @@ -297,6 +297,83 @@ test.each(['duct-segment', 'pipe-segment'] as const)( }, ) +test.each(['duct-segment', 'pipe-segment'] as const)( + '%s drawn from a collar rises to each panel target without a pointer event', + 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') + const keyTarget = Object.assign(new EventTarget(), { closest: () => null }) + Object.defineProperty(globalThis, 'window', { + value: keyTarget, + 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 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: 'vertical', + elevation: 2, + targetElevation, + initialStart: [1, 2, 0], + getPorts: () => [], + findBody: () => null, + commit: ({ end }) => { + commits.push(end) + return { nextStart: end, nextConnection: { port: null, body: null } } + }, + }) + return null + } + const pressEnter = () => + act(async () => { + keyTarget.dispatchEvent(Object.assign(new Event('keydown'), { key: 'Enter' })) + }) + let renderer: Awaited> | undefined + try { + useEditor.setState({ snappingModeByContext: { wall: 'off', polygon: 'off', item: 'off' } }) + renderer = await create() + expect(tool?.cursor).toEqual([1, 4, 0]) + targetElevation = 5 + await renderer.update() + expect(tool?.cursor).toEqual([1, 5, 0]) + await pressEnter() + expect(commits).toEqual([[1, 5, 0]]) + + targetElevation = 3 + await renderer.update() + expect(tool?.cursor).toEqual([1, 3, 0]) + await pressEnter() + expect(commits).toEqual([ + [1, 5, 0], + [1, 3, 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') + } + }, +) + test('a sloped horizontal route connects at the height its fall reaches', async () => { const previousScene = useScene.getState() const previousEditor = useEditor.getState() 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 0b8f5b648a..0e641dcd13 100644 --- a/packages/editor/src/components/tools/distribution/distribution-run-tool.tsx +++ b/packages/editor/src/components/tools/distribution/distribution-run-tool.tsx @@ -627,6 +627,22 @@ export function useDistributionRunTool(config: DistributionRunToolConfig) { } } + // A vertical route rises from its start to the target elevation wherever the + // pointer is, so it resolves without a pointer event. + const verticalTarget = (currentStart: RunPoint): ResolvedRunPoint => ({ + point: [ + currentStart[0], + configRef.current.targetElevation ?? currentStart[1], + currentStart[2], + ], + frame: createRunSurfaceFrame(currentStart), + surfaceTarget: null, + snapped: null, + directionMode: 'vertical', + port: null, + body: null, + }) + const resolvePoint = (event: GridEvent): ResolvedRunPoint => { const adapter = configRef.current const hit = surfacePointFromEvent(event, adapter.levelId) @@ -670,17 +686,7 @@ export function useDistributionRunTool(config: DistributionRunToolConfig) { const routeElevation = currentStart?.[1] ?? adapter.elevation ?? 0 if (explicitRoute) { resolved.point[1] = routeElevation - 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, - } - } + if (currentStart && adapter.routingMode === 'vertical') return verticalTarget(currentStart) } const bypass = event.nativeEvent?.altKey === true const gridStep = !bypass && isGridSnapActive() ? useEditor.getState().gridSnapStep : 0 @@ -1073,7 +1079,8 @@ export function useDistributionRunTool(config: DistributionRunToolConfig) { setEndConnection({ port: null, body: null }) // A vertical route ends at the target, not under the pointer: show that // riser now so the next click or Enter places what the preview shows. - if (configRef.current.routingMode === 'vertical') updateCursor(resolvePoint(event)) + if (configRef.current.routingMode === 'vertical') + updateCursor(verticalTarget(resolved.point)) return } const typedResolved = applyTypedLength(resolved) @@ -1194,7 +1201,10 @@ export function useDistributionRunTool(config: DistributionRunToolConfig) { } refreshCursorRef.current = () => { - if (lastPointerRef.current) + const currentStart = startRef.current + if (currentStart && configRef.current.routingMode === 'vertical') + updateCursor(verticalTarget(currentStart)) + else if (lastPointerRef.current) updateCursor(applyTypedLength(resolvePoint(lastPointerRef.current))) else if (lastResolvedRef.current) updateCursor(applyTypedLength(lastResolvedRef.current)) } diff --git a/packages/editor/src/components/tools/registry/move-registry-node-tool.tsx b/packages/editor/src/components/tools/registry/move-registry-node-tool.tsx index e6fd5c8460..d7dccdbc4a 100644 --- a/packages/editor/src/components/tools/registry/move-registry-node-tool.tsx +++ b/packages/editor/src/components/tools/registry/move-registry-node-tool.tsx @@ -534,14 +534,19 @@ export function MoveRegistryNodeTool({ node: source }: { node: AnyNode }) { // them through `useLiveNodeOverrides` (transient — no history churn; // GeometrySystem merges overrides via getEffectiveNode). Each connected // node is re-dirtied so its geometry rebuilds against the new override. - const previewConnectivity = (position: [number, number, number], rotationY: number) => { + // False, previewing nothing, when the connected joints cannot follow. + const previewConnectivity = ( + position: [number, number, number], + rotationY: number, + ): boolean => { const connectivity = connectivityRef.current - if (!connectivity) return + if (!connectivity) return true const updates = resolveConnectivityUpdates( connectivity, buildPreviewNode(position, rotationY), ) - if (updates.length === 0) return + if (!updates) return false + if (updates.length === 0) return true useLiveNodeOverrides .getState() .setMany(updates.map((u) => [u.id, u.data as Record] as const)) @@ -549,6 +554,7 @@ export function MoveRegistryNodeTool({ node: source }: { node: AnyNode }) { for (const u of updates) { if (useScene.getState().nodes[u.id]) useScene.getState().markDirty(u.id) } + return true } const clearConnectivityOverrides = () => { @@ -1027,6 +1033,10 @@ export function MoveRegistryNodeTool({ node: source }: { node: AnyNode }) { ).position } position = keepStartingElevation(position, rotationRef.current) + // Carry connected ductwork along (preview only — committed on drop). A + // position the connected joints cannot follow holds the last frame, + // which is what the drop commits. + if (!previewConnectivity(position, rotationRef.current)) return const visualPosition = getVisualPosition(position) hasMovedRef.current = true setCursorPosition(visualPosition) @@ -1054,8 +1064,6 @@ export function MoveRegistryNodeTool({ node: source }: { node: AnyNode }) { }) syncParentFramePreview(position) markMovedNodeDirty() - // Carry connected ductwork along (preview only — committed on drop). - previewConnectivity(position, rotationRef.current) const soundStep = { coords: [x, z], @@ -1171,8 +1179,9 @@ export function MoveRegistryNodeTool({ node: source }: { node: AnyNode }) { ? resolveConnectivityUpdates( connectivityRef.current, buildPreviewNode(position, rotationRef.current), - ).filter((u) => useScene.getState().nodes[u.id]) + )?.filter((u) => useScene.getState().nodes[u.id]) : [] + if (!connectivityUpdates) return const surfaceId = surfaceAttachmentId(effectiveNode) itemSurfaceMove?.restore() useScene.temporal.getState().resume() @@ -1298,7 +1307,6 @@ export function MoveRegistryNodeTool({ node: source }: { node: AnyNode }) { attachmentRotationRef.current, ) if (nextFreeRotation === null) return - sfxEmitter.emit('sfx:item-rotate') const hostedPose = itemSurfaceMove?.rotate(nextFreeRotation) let position = hostedPose?.position ?? lastCursorRef.current if ( @@ -1319,10 +1327,16 @@ export function MoveRegistryNodeTool({ node: source }: { node: AnyNode }) { ) position = canonicalPositionFromPlan(planOrigin[0], position[1], planOrigin[2]) } - position = keepStartingElevation(position, hostedPose?.rotationY ?? nextFreeRotation) + const rotationY = hostedPose?.rotationY ?? nextFreeRotation + position = keepStartingElevation(position, rotationY) + // Rotating the fitting swings its collars — connected ducts follow. A + // swing they cannot follow holds the last frame; a surface-hosted node + // has already turned with its host, so its drop refuses instead. + if (!previewConnectivity(position, rotationY) && !hostedPose) return + sfxEmitter.emit('sfx:item-rotate') lastCursorRef.current = position - freeRotationRef.current = hostedPose?.rotationY ?? nextFreeRotation - rotationRef.current = freeRotationRef.current + freeRotationRef.current = rotationY + rotationRef.current = rotationY setCursorRotationY(previewRotationY(rotationRef.current)) const visualPosition = getVisualPosition(position) setCursorPosition(visualPosition) @@ -1335,8 +1349,6 @@ export function MoveRegistryNodeTool({ node: source }: { node: AnyNode }) { }) syncParentFramePreview(position) markMovedNodeDirty() - // Rotating the fitting swings its collars — connected ducts follow. - previewConnectivity(position, rotationRef.current) // Rotation changes the footprint's collision span — re-check validity. if (!itemSurfaceMove?.hosted && itemSurfaceMove?.rejection && lastSurfaceEvent) onItemMove(lastSurfaceEvent) diff --git a/packages/nodes/src/agent-operations/pipe-grade.test.ts b/packages/nodes/src/agent-operations/pipe-grade.test.ts index 8b2d25c7d9..ff85e27225 100644 --- a/packages/nodes/src/agent-operations/pipe-grade.test.ts +++ b/packages/nodes/src/agent-operations/pipe-grade.test.ts @@ -296,7 +296,7 @@ describe('plan-view endpoint drag on a run whose far end sits on an elbow', () = expect(useFloorplanMode.getState().notice).toBeNull() }) - test('a turn the elbow cannot make holds the last valid frame and says why', () => { + test('a turn the elbow cannot make holds the last valid frame and says why until placed', () => { const pipe = run() const fitting = elbow() const session = drag(pipe, fitting) @@ -310,6 +310,7 @@ describe('plan-view endpoint drag on a run whose far end sits on an elbow', () = expect(session.canCommit()).toBe(true) session.commit!() expect((useScene.getState().nodes[pipe.id] as PipeSegmentNode).path[0]).toEqual([0.07, 1, -1]) + expect(useFloorplanMode.getState().notice).toBeNull() }) }) @@ -406,6 +407,44 @@ test('raising one leg of a closed loop with sloped legs is refused rather than h ).toThrow('would change a connected pipe') }) +test('stretching a run whose U loops back to its own start corner is refused, not split', () => { + const run = PipeSegmentNode.parse({ + ...pipeSegmentDefinition.defaults(), + parentId: level.id, + path: [ + [0.07, 1, 0], + [3.93, 1, 0], + ], + }) + const corner = (position: number[], rotationY: number) => + PipeFittingNode.parse({ + ...pipeFittingDefinition.defaults(), + parentId: level.id, + position, + rotation: [0, rotationY, 0], + }) + const u = PipeSegmentNode.parse({ + ...pipeSegmentDefinition.defaults(), + parentId: level.id, + path: [ + [4, 1, 0.07], + [4, 1, 2], + [0, 1, 2], + [0, 1, 0.07], + ], + }) + const nodes = scene(run, corner([4, 1, 0], 0), u, corner([0, 1, 0], Math.PI / 2)) + // The U translates with the run's end and would drag the start corner off + // the run's start, which this edit keeps fixed. + expect(() => + edit( + nodes, + { nodeId: run.id, action: 'endpoint', pointIndex: 1, point: [4.43, 1, 0] }, + context, + ), + ).toThrow('pulling a joint apart') +}) + test('grade tool works through MCP and undoes as one edit', async () => { const { Client } = await import('@modelcontextprotocol/client') const { InMemoryTransport, McpServer } = await import('@modelcontextprotocol/server') diff --git a/packages/nodes/src/agent-tools/index.ts b/packages/nodes/src/agent-tools/index.ts index 83d971edf2..2f1147b51e 100644 --- a/packages/nodes/src/agent-tools/index.ts +++ b/packages/nodes/src/agent-tools/index.ts @@ -41,7 +41,7 @@ export const pipeGradeTool = { name: 'pipe_grade' as const, title: 'Edit pipe grade and elevation', description: - "Set a pipe run's grade or flow direction, move one of its path points, or change its elevation, keeping connected pipes and fittings joined. grade: gradePercent is the percent fall over horizontal travel; flow defaults to forward (falling from start to end), and reverse falls toward the start; anchor defaults to start, the end that keeps its elevation. endpoint: moves path point pointIndex to point, a numeric [x, y, z] tuple in level-local metres (not a unit-bearing length string), preserving each existing leg grade; connected runs and end caps follow unless detach is true (default false), which leaves them in place. elevation: sets the anchor end (default start) to elevation above the level and translates the whole run without changing grades. Vertical legs keep their rise. Refuses pipe_not_found, node_capability_unavailable, pipe_grade_invalid, pipe_elevation_invalid, pipe_endpoint_invalid, pipe_grade_conflict, pipe_connection_angle, pipe_connected_grade or pipe_fixed_connection without partial edits. One undo step.", + "Set a pipe run's grade or flow direction, move one of its path points, or change its elevation, keeping connected pipes and fittings joined. grade: gradePercent is the percent fall over horizontal travel; flow defaults to forward (falling from start to end), and reverse falls toward the start; anchor defaults to start, the end that keeps its elevation. endpoint: moves path point pointIndex to point, a numeric [x, y, z] tuple in level-local metres (not a unit-bearing length string), preserving each existing leg grade; connected runs and end caps follow unless detach is true (default false), which leaves them in place. elevation: sets the anchor end (default start) to elevation above the level and translates the whole run without changing grades. Vertical legs keep their rise. Refuses pipe_not_found, node_capability_unavailable, pipe_grade_invalid, pipe_elevation_invalid, pipe_endpoint_invalid, pipe_grade_conflict, pipe_connection_angle, pipe_connection_split, pipe_connected_grade or pipe_fixed_connection without partial edits. One undo step.", input: { nodeId: z.string(), action: z.enum(['grade', 'endpoint', 'elevation']), diff --git a/packages/nodes/src/duct-fitting/move-tool.tsx b/packages/nodes/src/duct-fitting/move-tool.tsx index 1225b8d59d..9343805499 100644 --- a/packages/nodes/src/duct-fitting/move-tool.tsx +++ b/packages/nodes/src/duct-fitting/move-tool.tsx @@ -229,14 +229,15 @@ export const MoveDuctFittingTool: React.FC<{ node: AnyNode }> = ({ node }) => { (next[0] !== lastPos[0] || next[2] !== lastPos[2]) ) triggerSFX('sfx:grid-snap') + // Detached: keep the followers at their origin (drop any live overrides + // from a prior non-detached frame). Otherwise preview the follow; joints + // that cannot follow hold the last shown frame. + if (detached) connectivity?.clear() + else if (connectivity && !connectivity.preview({ position: next })) return lastPos = next lastDetached = detached hasMoved = true setCursorPos(next) - // Detached: keep the followers at their origin (drop any live overrides - // from a prior non-detached frame). Otherwise preview the follow. - if (detached) connectivity?.clear() - else connectivity?.preview({ position: next }) } const commit = (event: GridEvent, fromDragRelease = false) => { @@ -252,11 +253,23 @@ export const MoveDuctFittingTool: React.FC<{ node: AnyNode }> = ({ node }) => { event.nativeEvent?.stopPropagation?.() return } + const creating = isNew && !useScene.getState().nodes[nodeId] + // Fold connected-duct / sibling-run follow-updates into the SAME batch + // as the moved fitting so the whole joint is one undo step. Detached + // (Alt on the final frame): the joint is broken, so nothing follows. + const followUpdates = + creating || lastDetached || !connectivity + ? [] + : connectivity.commitUpdates({ position: lastPos }) + if (!followUpdates) { + event.nativeEvent?.stopPropagation?.() + return + } committed = true useScene.temporal.getState().resume() let selectId = nodeId - if (isNew && !useScene.getState().nodes[nodeId]) { + if (creating) { const created = DuctFittingNode.parse({ ...(node as Record), position: lastPos, @@ -272,12 +285,6 @@ export const MoveDuctFittingTool: React.FC<{ node: AnyNode }> = ({ node }) => { ]) selectId = created.id as AnyNodeId } else { - // Fold connected-duct / sibling-run follow-updates into the SAME batch - // as the moved fitting so the whole joint is one undo step. Detached - // (Alt on the final frame): the joint is broken, so nothing follows. - const followUpdates = lastDetached - ? [] - : (connectivity?.commitUpdates({ position: lastPos }) ?? []) const scene = useScene.getState() scene.updateNodes([ { id: nodeId, data: { position: lastPos } as Partial }, diff --git a/packages/nodes/src/duct-fitting/selection.tsx b/packages/nodes/src/duct-fitting/selection.tsx index 9b7d010a1f..ef4e9d74bf 100644 --- a/packages/nodes/src/duct-fitting/selection.tsx +++ b/packages/nodes/src/duct-fitting/selection.tsx @@ -408,15 +408,18 @@ const FittingHandles = ({ fitting, target }: { fitting: DuctFittingNode; target: } // Follow-updates for runs / fittings mated to this fitting, given a preview - // transform. Endpoints whose ports didn't move resolve to a zero delta. + // transform. Endpoints whose ports didn't move resolve to a zero delta. Null + // when the mated joints cannot follow the transform. const connectivityUpdates = ( connectivity: PortConnectivity | null, transform: FittingTransform, - ): { id: AnyNodeId; data: Partial }[] => { + ): { id: AnyNodeId; data: Partial }[] | null => { if (!connectivity) return [] const preview = { ...(fitting as Record), ...transform } as AnyNode const nodes = useScene.getState().nodes - return resolveConnectivityUpdates(connectivity, preview) + const updates = resolveConnectivityUpdates(connectivity, preview) + if (!updates) return null + return updates .filter((u) => nodes[u.id]) .map((u) => { const node = nodes[u.id] @@ -457,19 +460,29 @@ const FittingHandles = ({ fitting, target }: { fitting: DuctFittingNode; target: document.body.style.cursor = cursor let current: FittingTransform | null = null - const buildBatch = (t: FittingTransform): { id: AnyNodeId; data: Partial }[] => [ - { - id: fitting.id as AnyNodeId, - data: preserveFittingParameters(fitting, t as Partial), - }, - ...connectivityUpdates(connectivity, t), - ] + const buildBatch = ( + t: FittingTransform, + ): { id: AnyNodeId; data: Partial }[] | null => { + const followers = connectivityUpdates(connectivity, t) + return ( + followers && [ + { + id: fitting.id as AnyNodeId, + data: preserveFittingParameters(fitting, t as Partial), + }, + ...followers, + ] + ) + } const onMove = (event: PointerEvent) => { const next = compute(event) if (!next) return + // Joints that cannot follow hold the last frame, which release commits. + const batch = buildBatch(next) + if (!batch) return current = next - useScene.getState().updateNodes(buildBatch(next)) + useScene.getState().updateNodes(batch) } const cleanup = () => { @@ -518,10 +531,11 @@ const FittingHandles = ({ fitting, target }: { fitting: DuctFittingNode; target: ...reverts.filter((u) => useScene.getState().nodes[u.id]), ]) resumeSceneHistory(useScene) - if (current) { + const batch = current && buildBatch(current) + if (batch) { const scene = useScene.getState() scene.updateNodes([ - ...buildBatch(current), + ...batch, ...autoOffsetInvalidationUpdates(scene.nodes, fitting.id as AnyNodeId), ]) } diff --git a/packages/nodes/src/duct-segment/move-tool.tsx b/packages/nodes/src/duct-segment/move-tool.tsx index a5256943c2..bf47860178 100644 --- a/packages/nodes/src/duct-segment/move-tool.tsx +++ b/packages/nodes/src/duct-segment/move-tool.tsx @@ -173,9 +173,20 @@ export const MoveDuctSegmentTool: React.FC<{ node: AnyNode }> = ({ node }) => { width: duct.width, height: duct.height, } - let lastTranslationPlan: RunTranslationOffsetPlan | null = null + const translationPlanFor = (path: Vec3[]) => + portConnectivity + ? planRunTranslationOffsets({ + duct, + translatedPath: path, + profile, + connections: portConnectivity.connections, + scenePorts, + nodesById, + }) + : null const setPreview = (path: Vec3[]) => { + hasMovedRef.current = true previewPathRef.current = path setPreviewPath(path) } @@ -187,10 +198,10 @@ export const MoveDuctSegmentTool: React.FC<{ node: AnyNode }> = ({ node }) => { if (duct.wallAttachment && attachedWall?.type === 'wall') { const wallMove = translateWallRun(originalPath, duct.wallAttachment, attachedWall, event) if (wallMove) { - hasMovedRef.current = true + // Connected joints that cannot follow hold the last shown frame. + if (connectivity && !connectivity.preview({ path: wallMove.path })) return previewAttachmentRef.current = wallMove.attachment setPreview(wallMove.path) - connectivity?.preview({ path: wallMove.path }) setTranslationGhost(null) return } @@ -229,23 +240,12 @@ export const MoveDuctSegmentTool: React.FC<{ node: AnyNode }> = ({ node }) => { triggerSFX('sfx:grid-snap') } prevSnapRef.current = cur - hasMovedRef.current = true const nextPath = originalPath.map(([x, y, z]) => [x + dx, y, z + dz] as Vec3) + const translationPlan = translationPlanFor(nextPath) + if (translationPlan) connectivity?.clear() + else if (connectivity && !connectivity.preview({ path: nextPath })) return setPreview(nextPath) - lastTranslationPlan = - existedAtStart && portConnectivity - ? planRunTranslationOffsets({ - duct, - translatedPath: nextPath, - profile, - connections: portConnectivity.connections, - scenePorts, - nodesById, - }) - : null - if (lastTranslationPlan) connectivity?.clear() - else connectivity?.preview({ path: nextPath }) - setTranslationGhost(lastTranslationPlan) + setTranslationGhost(translationPlan) } const commit = (event: GridEvent, fromDragRelease = false) => { @@ -261,12 +261,24 @@ export const MoveDuctSegmentTool: React.FC<{ node: AnyNode }> = ({ node }) => { event.nativeEvent?.stopPropagation?.() return } - committed = true const finalPath = previewPathRef.current + const creating = isNew && !useScene.getState().nodes[nodeId] + const translationPlan = creating ? null : translationPlanFor(finalPath) + // Fold connected-fitting / sibling-run follow-updates into the SAME + // batch as the moved run so the whole joint is one undo step. + const followUpdates = + creating || translationPlan || !connectivity + ? [] + : connectivity.commitUpdates({ path: finalPath }) + if (!followUpdates) { + event.nativeEvent?.stopPropagation?.() + return + } + committed = true useScene.temporal.getState().resume() let selectId = nodeId - if (isNew && !useScene.getState().nodes[nodeId]) { + if (creating) { const created = DuctSegmentNode.parse({ ...(node as Record), path: finalPath, @@ -283,16 +295,6 @@ export const MoveDuctSegmentTool: React.FC<{ node: AnyNode }> = ({ node }) => { ]) selectId = created.id as AnyNodeId } else { - const translationPlan = - portConnectivity && - planRunTranslationOffsets({ - duct, - translatedPath: finalPath, - profile, - connections: portConnectivity.connections, - scenePorts, - nodesById, - }) if (translationPlan) { useScene.getState().applyNodeChanges({ create: [...translationPlan.fittings, ...translationPlan.connectors].map((created) => ({ @@ -311,9 +313,6 @@ export const MoveDuctSegmentTool: React.FC<{ node: AnyNode }> = ({ node }) => { ], }) } else { - // Fold connected-fitting / sibling-run follow-updates into the SAME - // batch as the moved run so the whole joint is one undo step. - const followUpdates = connectivity?.commitUpdates({ path: finalPath }) ?? [] useScene.getState().updateNodes([ { id: nodeId, diff --git a/packages/nodes/src/duct-segment/selection.tsx b/packages/nodes/src/duct-segment/selection.tsx index 23098bc6ef..2dff6a5c6c 100644 --- a/packages/nodes/src/duct-segment/selection.tsx +++ b/packages/nodes/src/duct-segment/selection.tsx @@ -446,9 +446,11 @@ const DuctPointHandles = ({ duct, target }: { duct: DuctSegmentNode; target: Obj ]) } const path = drag.initialPath.map((p, i) => (i === drag.index ? next : p)) as Point[] + const followers = detached ? [] : connectivityUpdatesForPath(drag.connectivity, path) + if (!followers) return null const updates = [ { id: duct.id as AnyNodeId, data: { path, wallAttachment: attachmentFor(path) } }, - ...(detached ? [] : connectivityUpdatesForPath(drag.connectivity, path)), + ...followers, ] return detached ? updates : withEndCapFollow(path, updates) } @@ -463,15 +465,18 @@ const DuctPointHandles = ({ duct, target }: { duct: DuctSegmentNode; target: Obj // Follow-updates for fittings / ducts mated to this run's endpoints, given // the run's live path. Endpoints whose position didn't change resolve to a - // zero delta, so only the dragged endpoint's partner actually moves. + // zero delta, so only the dragged endpoint's partner actually moves. Null + // when the mated joints cannot follow the path. const connectivityUpdatesForPath = ( connectivity: PortConnectivity | null, path: Point[], - ): { id: AnyNodeId; data: Partial }[] => { + ): { id: AnyNodeId; data: Partial }[] | null => { if (!connectivity) return [] const preview = { ...(duct as Record), path } as AnyNode - return resolveConnectivityUpdates(connectivity, preview).filter( - (u) => useScene.getState().nodes[u.id], + return ( + resolveConnectivityUpdates(connectivity, preview)?.filter( + (u) => useScene.getState().nodes[u.id], + ) ?? null ) } @@ -924,10 +929,10 @@ const DuctPointHandles = ({ duct, target }: { duct: DuctSegmentNode; target: Obj } return next }) - const batchFor = (path: Point[]): { id: AnyNodeId; data: Partial }[] => [ - { id: duct.id as AnyNodeId, data: { path } }, - ...connectivityUpdatesForPath(connectivity, path), - ] + const batchFor = (path: Point[]): { id: AnyNodeId; data: Partial }[] | null => { + const followers = connectivityUpdatesForPath(connectivity, path) + return followers && [{ id: duct.id as AnyNodeId, data: { path } }, ...followers] + } // Patches restoring every connected partner to its post-rewind (logical-L) // pose — runs by path, fittings by position (+ a re-aimed elbow's rotation / @@ -1031,15 +1036,13 @@ const DuctPointHandles = ({ duct, target }: { duct: DuctSegmentNode; target: Obj const step = isGridSnapActive() ? useEditor.getState().gridSnapStep : 0 const next = snap(s - startSample, step) if (next === delta) return - delta = next - if (step > 0) triggerSFX('sfx:grid-snap') const dyEff = baseDy + next // Vertical move: connected ends stay welded to their (stationary) // partner via an auto-routed elbow → riser → elbow offset, planned from // the LOGICAL L by the accumulated lift. The planner returns valid (offset // fits), invalid (connected but no clean offset at this height), or null // (no connections, or dyEff 0 → back at the L → plain translate). - offsetResult = + const result: VerticalOffsetResult = isVertical && dyEff !== 0 ? planVerticalOffsets({ duct: logicalDuct, @@ -1050,6 +1053,19 @@ const DuctPointHandles = ({ duct, target }: { duct: DuctSegmentNode; target: Obj nodesById, }) : null + const followUpdates = + result?.status === 'invalid' + ? [] + : connectivityUpdatesForPath( + connectivity, + result?.status === 'valid' ? result.plan.followPath : shiftedPath(next), + ) + // Joints that cannot follow hold the last shown frame, which is what + // release commits. + if (!followUpdates) return + delta = next + offsetResult = result + if (step > 0) triggerSFX('sfx:grid-snap') if (offsetResult?.status === 'valid') { applyLogicalBasePreview() // Lift the run to the offset path; trim run-offset partners back one @@ -1061,7 +1077,6 @@ const DuctPointHandles = ({ duct, target }: { duct: DuctSegmentNode; target: Obj const scene = useScene.getState() const deletePreview = (plan.delete ?? []).filter((id) => scene.nodes[id]) setPreviewHidden([...mintedIds, ...deletePreview]) - const followUpdates = connectivityUpdatesForPath(connectivity, plan.followPath) const updates = [ { id: duct.id as AnyNodeId, data: { path: plan.ductPath } }, ...plan.updates.filter((u) => scene.nodes[u.id]), @@ -1087,8 +1102,10 @@ const DuctPointHandles = ({ duct, target }: { duct: DuctSegmentNode; target: Obj } else { applyLogicalBasePreview() setVerticalGhost(null) - const updates = batchFor(shiftedPath(next)) - publishLivePreview(updates) + publishLivePreview([ + { id: duct.id as AnyNodeId, data: { path: shiftedPath(next) } }, + ...followUpdates, + ]) } } @@ -1128,6 +1145,7 @@ const DuctPointHandles = ({ duct, target }: { duct: DuctSegmentNode; target: Obj base, } const followUpdates = connectivityUpdatesForPath(connectivity, plan.followPath) + if (!followUpdates) return const updates = [ { id: duct.id as AnyNodeId, @@ -1212,6 +1230,7 @@ const DuctPointHandles = ({ duct, target }: { duct: DuctSegmentNode; target: Obj return } const updates = batchFor(finalPath) + if (!updates) return if (isVertical && existingTag) { updates[0] = { ...updates[0]!, diff --git a/packages/nodes/src/lineset/move-tool.tsx b/packages/nodes/src/lineset/move-tool.tsx index 71e2fda9bd..0985f33cad 100644 --- a/packages/nodes/src/lineset/move-tool.tsx +++ b/packages/nodes/src/lineset/move-tool.tsx @@ -188,10 +188,11 @@ export const MoveLinesetTool: React.FC<{ node: AnyNode }> = ({ node }) => { triggerSFX('sfx:grid-snap') } prevSnapRef.current = cur - hasMovedRef.current = true const nextPath = originalPath.map(([x, y, z]) => [x + dx, y, z + dz] as Vec3) + // Connected joints that cannot follow hold the last shown frame. + if (connectivity && !connectivity.preview({ path: nextPath })) return + hasMovedRef.current = true setPreview(nextPath) - connectivity?.preview({ path: nextPath }) } const commit = (event: GridEvent) => { @@ -204,12 +205,21 @@ export const MoveLinesetTool: React.FC<{ node: AnyNode }> = ({ node }) => { event.nativeEvent?.stopPropagation?.() return } - committed = true const finalPath = previewPathRef.current + const creating = isNew && !useScene.getState().nodes[nodeId] + // Fold connected-fitting / sibling-run follow-updates into the SAME + // batch as the moved run so the whole joint is one undo step. + const followUpdates = + creating || !connectivity ? [] : connectivity.commitUpdates({ path: finalPath }) + if (!followUpdates) { + event.nativeEvent?.stopPropagation?.() + return + } + committed = true useScene.temporal.getState().resume() let selectId = nodeId - if (isNew && !useScene.getState().nodes[nodeId]) { + if (creating) { const created = LinesetNode.parse({ ...(node as Record), path: finalPath, @@ -225,9 +235,6 @@ export const MoveLinesetTool: React.FC<{ node: AnyNode }> = ({ node }) => { ]) selectId = created.id as AnyNodeId } else { - // Fold connected-fitting / sibling-run follow-updates into the SAME - // batch as the moved run so the whole joint is one undo step. - const followUpdates = connectivity?.commitUpdates({ path: finalPath }) ?? [] useScene .getState() .updateNodes([ diff --git a/packages/nodes/src/pipe-fitting/move-tool.tsx b/packages/nodes/src/pipe-fitting/move-tool.tsx index 73ed2f9d6a..7071d555df 100644 --- a/packages/nodes/src/pipe-fitting/move-tool.tsx +++ b/packages/nodes/src/pipe-fitting/move-tool.tsx @@ -15,6 +15,7 @@ import { DragBoundingBox, EDITOR_LAYER, isAlignmentGuideActive, + isGridSnapActive, isMagneticSnapActive, markToolCancelConsumed, stripPlacementMetadataFlags, @@ -105,7 +106,7 @@ function rotatedBounds(box: Box3, rotation: Vec3): { size: Vec3; offset: Vec3 } * on its own, leaving every mated run where it sits. * - **Ctrl / Cmd** switches to vertical movement (stack / riser editing): XZ * holds and the cursor's screen-Y drives the riser height. - * - **Shift** bypasses grid snapping / alignment. + * - Snapping follows the active editor snapping mode. * * Wired via `def.affordanceTools.move`. */ @@ -210,7 +211,6 @@ export const MovePipeFittingTool: React.FC<{ node: AnyNode }> = ({ node }) => { let verticalAnchor: { clientY: number; baseY: number } | null = null const onMove = (event: GridEvent) => { - const bypass = event.nativeEvent?.shiftKey === true // Alt = detach: drop the connected-pipe follow so the fitting moves on // its own, leaving every mated run where it sits. const detached = event.nativeEvent?.altKey === true @@ -218,7 +218,7 @@ export const MovePipeFittingTool: React.FC<{ node: AnyNode }> = ({ node }) => { // screen-Y drives the riser height (connected pipes still follow). const vertical = event.nativeEvent?.ctrlKey === true || event.nativeEvent?.metaKey === true const clientY = (event.nativeEvent as { clientY?: number } | undefined)?.clientY - const snap = bypass ? (v: number) => v : snapToGridStep + const snap = isGridSnapActive() ? snapToGridStep : (v: number) => v let next: Vec3 if (vertical && typeof clientY === 'number') { @@ -237,10 +237,10 @@ export const MovePipeFittingTool: React.FC<{ node: AnyNode }> = ({ node }) => { let z = snap(event.localPosition[2]) // Alignment: snap the footprint box edges onto nearby geometry and - // publish guides (Alt / Shift bypass). Guides are DISPLAYED in every - // snapping mode (isAlignmentGuideActive); the magnetic pull toward them - // applies only in 'lines' mode (isMagneticSnapActive). - if (!bypass && isAlignmentGuideActive()) { + // publish guides. Guides are DISPLAYED in every snapping mode + // (isAlignmentGuideActive); the magnetic pull toward them applies only + // in 'lines' mode (isMagneticSnapActive). + if (isAlignmentGuideActive()) { const proposed: Aabb2D = { minX: x + ox - hx, maxX: x + ox + hx, @@ -259,17 +259,21 @@ export const MovePipeFittingTool: React.FC<{ node: AnyNode }> = ({ node }) => { next = [x, lastPos[1], z] } - if (next[0] !== lastPos[0] || next[1] !== lastPos[1] || next[2] !== lastPos[2]) { + if ( + (isGridSnapActive() || isMagneticSnapActive()) && + (next[0] !== lastPos[0] || next[1] !== lastPos[1] || next[2] !== lastPos[2]) + ) { triggerSFX('sfx:grid-snap') } + // Detached: keep the followers at their origin (drop any live overrides + // from a prior non-detached frame). Otherwise preview the follow; joints + // that cannot follow hold the last shown frame. + if (detached) connectivity?.clear() + else if (connectivity && !connectivity.preview({ position: next })) return lastPos = next lastDetached = detached hasMoved = true setCursorPos(next) - // Detached: keep the followers at their origin (drop any live overrides - // from a prior non-detached frame). Otherwise preview the follow. - if (detached) connectivity?.clear() - else connectivity?.preview({ position: next }) } const commit = (event: GridEvent) => { @@ -282,11 +286,23 @@ export const MovePipeFittingTool: React.FC<{ node: AnyNode }> = ({ node }) => { event.nativeEvent?.stopPropagation?.() return } + const creating = isNew && !useScene.getState().nodes[nodeId] + // Fold connected-pipe / sibling-run follow-updates into the SAME batch + // as the moved fitting so the whole joint is one undo step. Detached + // (Alt on the final frame): the joint is broken, so nothing follows. + const followUpdates = + creating || lastDetached || !connectivity + ? [] + : connectivity.commitUpdates({ position: lastPos }) + if (!followUpdates) { + event.nativeEvent?.stopPropagation?.() + return + } committed = true useScene.temporal.getState().resume() let selectId = nodeId - if (isNew && !useScene.getState().nodes[nodeId]) { + if (creating) { const created = PipeFittingNode.parse({ ...(node as Record), position: lastPos, @@ -302,12 +318,6 @@ export const MovePipeFittingTool: React.FC<{ node: AnyNode }> = ({ node }) => { ]) selectId = created.id as AnyNodeId } else { - // Fold connected-pipe / sibling-run follow-updates into the SAME batch - // as the moved fitting so the whole joint is one undo step. Detached - // (Alt on the final frame): the joint is broken, so nothing follows. - const followUpdates = lastDetached - ? [] - : (connectivity?.commitUpdates({ position: lastPos }) ?? []) useScene .getState() .updateNodes([ diff --git a/packages/nodes/src/pipe-fitting/selection.tsx b/packages/nodes/src/pipe-fitting/selection.tsx index e1709235a0..982f4badf7 100644 --- a/packages/nodes/src/pipe-fitting/selection.tsx +++ b/packages/nodes/src/pipe-fitting/selection.tsx @@ -16,6 +16,8 @@ import { import { ARROW_COLOR, EDITOR_LAYER, + isAngleSnapActive, + isGridSnapActive, isTypingTarget, swallowNextClick, triggerSFX, @@ -355,14 +357,17 @@ const FittingHandles = ({ fitting }: { fitting: PipeFittingNode }) => { return axis === 'x' ? local.x : local.z } + /** Null when the mated joints cannot follow the transform. */ const connectivityUpdates = ( connectivity: PortConnectivity | null, transform: FittingTransform, - ): { id: AnyNodeId; data: Partial }[] => { + ): { id: AnyNodeId; data: Partial }[] | null => { if (!connectivity) return [] const preview = { ...(fitting as Record), ...transform } as AnyNode const nodes = useScene.getState().nodes - return resolveConnectivityUpdates(connectivity, preview) + const updates = resolveConnectivityUpdates(connectivity, preview) + if (!updates) return null + return updates .filter((u) => nodes[u.id]) .map((u) => { const node = nodes[u.id] @@ -396,19 +401,29 @@ const FittingHandles = ({ fitting }: { fitting: PipeFittingNode }) => { document.body.style.cursor = cursor let current: FittingTransform | null = null - const buildBatch = (t: FittingTransform): { id: AnyNodeId; data: Partial }[] => [ - { - id: fitting.id as AnyNodeId, - data: preserveFittingParameters(fitting, t as Partial), - }, - ...connectivityUpdates(connectivity, t), - ] + const buildBatch = ( + t: FittingTransform, + ): { id: AnyNodeId; data: Partial }[] | null => { + const followers = connectivityUpdates(connectivity, t) + return ( + followers && [ + { + id: fitting.id as AnyNodeId, + data: preserveFittingParameters(fitting, t as Partial), + }, + ...followers, + ] + ) + } const onMove = (event: PointerEvent) => { const next = compute(event) if (!next) return + // Joints that cannot follow hold the last frame, which release commits. + const batch = buildBatch(next) + if (!batch) return current = next - useScene.getState().updateNodes(buildBatch(next)) + useScene.getState().updateNodes(batch) } const cleanup = () => { @@ -451,7 +466,8 @@ const FittingHandles = ({ fitting }: { fitting: PipeFittingNode }) => { ...reverts.filter((u) => useScene.getState().nodes[u.id]), ]) resumeSceneHistory(useScene) - if (current) useScene.getState().updateNodes(buildBatch(current)) + const batch = current && buildBatch(current) + if (batch) useScene.getState().updateNodes(batch) } window.addEventListener('pointermove', onMove) @@ -471,7 +487,7 @@ const FittingHandles = ({ fitting }: { fitting: PipeFittingNode }) => { if (start === null) return null const s = sampleAxis(axis, event.clientX, event.clientY, anchorWorld) if (s === null) return null - const step = event.shiftKey ? 0 : useEditor.getState().gridSnapStep + const step = isGridSnapActive() ? useEditor.getState().gridSnapStep : 0 const delta = snap(s - start, step) if (delta === lastDelta) return null lastDelta = delta @@ -510,8 +526,9 @@ const FittingHandles = ({ fitting }: { fitting: PipeFittingNode }) => { const b = bearing(event.clientX, event.clientY) if (b === null) return null const raw = b - startBearing - const delta = event.shiftKey ? raw : Math.round(raw / ROTATE_STEP_RAD) * ROTATE_STEP_RAD - if (!event.shiftKey) { + const snapped = isAngleSnapActive() + const delta = snapped ? Math.round(raw / ROTATE_STEP_RAD) * ROTATE_STEP_RAD : raw + if (snapped) { const step = Math.round(raw / ROTATE_STEP_RAD) if (step !== lastStep) { lastStep = step @@ -559,11 +576,12 @@ const FittingHandles = ({ fitting }: { fitting: PipeFittingNode }) => { sampleAxisParameter(event.clientX, event.clientY, centerWorld, axisWorld) - start const deltaIn = (rawDeltaM / INCHES_TO_METERS) * 2 const nextRaw = baseValue + deltaIn - const nextValue = clamp(event.shiftKey ? nextRaw : snap(nextRaw, RESIZE_STEP_IN), 1.25, 8) + const snapped = isGridSnapActive() + const nextValue = clamp(snapped ? snap(nextRaw, RESIZE_STEP_IN) : nextRaw, 1.25, 8) if (nextValue === lastValue) return lastValue = nextValue current = dimensionPatch(fitting, dimension, nextValue) - if (!event.shiftKey) triggerSFX('sfx:grid-snap') + if (snapped) triggerSFX('sfx:grid-snap') apply(current) } diff --git a/packages/nodes/src/pipe-segment/grade-affordance.ts b/packages/nodes/src/pipe-segment/grade-affordance.ts index a883e650f3..5b6622ea59 100644 --- a/packages/nodes/src/pipe-segment/grade-affordance.ts +++ b/packages/nodes/src/pipe-segment/grade-affordance.ts @@ -134,6 +134,7 @@ export const pipeGradePointAffordance: FloorplanAffordance = { }, canCommit: () => updates.length > 0, commit() { + dismissNotice() clear() useScene.getState().updateNodes(updates) }, diff --git a/packages/nodes/src/pipe-segment/grade-operation.ts b/packages/nodes/src/pipe-segment/grade-operation.ts index 206320eb9e..528af6e237 100644 --- a/packages/nodes/src/pipe-segment/grade-operation.ts +++ b/packages/nodes/src/pipe-segment/grade-operation.ts @@ -119,6 +119,11 @@ export const editPipeGrade: AgentOperation = (nodes, input) => { ) } const follow = !detached && connectivity ? resolveConnectivityUpdates(connectivity, next) : [] + if (!follow) + return refuse( + 'pipe_connection_split', + 'Connected pipes and fittings cannot follow this edit without pulling a joint apart. Adjust the connected route explicitly first.', + ) const caps = detached ? [] : (['start', 'end'] as const).flatMap((end) => diff --git a/packages/nodes/src/pipe-segment/move-tool.tsx b/packages/nodes/src/pipe-segment/move-tool.tsx index 9416f12247..59b33a1bb2 100644 --- a/packages/nodes/src/pipe-segment/move-tool.tsx +++ b/packages/nodes/src/pipe-segment/move-tool.tsx @@ -154,14 +154,16 @@ export const MovePipeSegmentTool: React.FC<{ node: AnyNode }> = ({ node }) => { ? startRunMoveConnectivity(node) : null - const setPreview = (path: Vec3[]) => { + // A frame the connected joints cannot follow is not shown: the ghost holds + // its last frame, which is what a click commits. + const showFrame = (path: Vec3[]): boolean => { + const followers = connectivity ? connectivity.preview({ path }) : [] + if (!followers) return false + hasMovedRef.current = true previewPathRef.current = path setPreviewPath(path) - } - - const previewFollowers = (path: Vec3[]) => { - const updates = connectivity?.preview({ path }) ?? [] - setGradeBlocked(!pipeUpdatesPreserveGrades(useScene.getState().nodes, updates)) + setGradeBlocked(!pipeUpdatesPreserveGrades(useScene.getState().nodes, followers)) + return true } const onMove = (event: GridEvent) => { @@ -171,10 +173,7 @@ export const MovePipeSegmentTool: React.FC<{ node: AnyNode }> = ({ node }) => { if (pipe.wallAttachment && attachedWall?.type === 'wall') { const wallMove = translateWallRun(originalPath, pipe.wallAttachment, attachedWall, event) if (wallMove) { - hasMovedRef.current = true - previewAttachmentRef.current = wallMove.attachment - setPreview(wallMove.path) - previewFollowers(wallMove.path) + if (showFrame(wallMove.path)) previewAttachmentRef.current = wallMove.attachment return } } @@ -212,10 +211,7 @@ export const MovePipeSegmentTool: React.FC<{ node: AnyNode }> = ({ node }) => { triggerSFX('sfx:grid-snap') } prevSnapRef.current = cur - hasMovedRef.current = true - const nextPath = originalPath.map(([x, y, z]) => [x + dx, y, z + dz] as Vec3) - setPreview(nextPath) - previewFollowers(nextPath) + showFrame(originalPath.map(([x, y, z]) => [x + dx, y, z + dz] as Vec3)) } const commit = (event: GridEvent) => { @@ -229,8 +225,12 @@ export const MovePipeSegmentTool: React.FC<{ node: AnyNode }> = ({ node }) => { return } const finalPath = previewPathRef.current - const followUpdates = connectivity?.commitUpdates({ path: finalPath }) ?? [] + const followUpdates = connectivity ? connectivity.commitUpdates({ path: finalPath }) : [] // The drag stays live (history paused, Esc cancels) so the run can be placed elsewhere. + if (!followUpdates) { + event.nativeEvent?.stopPropagation?.() + return + } if (!pipeUpdatesPreserveGrades(useScene.getState().nodes, followUpdates)) { setGradeBlocked(true) event.nativeEvent?.stopPropagation?.() diff --git a/packages/nodes/src/pipe-segment/run-move.ts b/packages/nodes/src/pipe-segment/run-move.ts index f20873b533..a951433366 100644 --- a/packages/nodes/src/pipe-segment/run-move.ts +++ b/packages/nodes/src/pipe-segment/run-move.ts @@ -27,7 +27,8 @@ export type PipeRunMoveChange = { create: AnyNode[]; delete: AnyNodeId[]; update /** * One frame of a selected run's arrow move. A `valid` frame previews exactly the * change it commits; `invalid` is a vertical offset that cannot be formed (red - * ghost, nothing to commit); `blocked` would regrade a connected run. + * ghost, nothing to commit); `blocked` would regrade a connected run or pull a + * joint apart. */ export type PipeRunMoveFrame = | { @@ -56,9 +57,10 @@ export function planPipeRunMoveFrame(args: RunMoveArgs & { delta: number }): Pip const profile = { diameter: pipe.diameter, pipeMaterial: pipe.pipeMaterial } const connections = connectivity?.connections ?? [] const exists = (update: Update) => !!nodesById[update.id] - const follow = (path: Point[]): Update[] => + const follow = (path: Point[]): Update[] | null => connectivity - ? resolveConnectivityUpdates(connectivity, { ...pipe, path } as AnyNode).filter(exists) + ? (resolveConnectivityUpdates(connectivity, { ...pipe, path } as AnyNode)?.filter(exists) ?? + null) : [] const path = pipe.path.map( (p): Point => @@ -84,10 +86,12 @@ export function planPipeRunMoveFrame(args: RunMoveArgs & { delta: number }): Pip } if (offsets?.status === 'valid') { const { plan } = offsets + const followers = follow(plan.followPath) + if (!followers) return { status: 'blocked' } const update = [ { id: pipe.id as AnyNodeId, data: { path: plan.pipePath } }, ...plan.updates.filter(exists), - ...follow(plan.followPath), + ...followers, ] const hidden = (plan.delete ?? []).filter((id) => nodesById[id]) return guarded({ @@ -126,7 +130,9 @@ export function planPipeRunMoveFrame(args: RunMoveArgs & { delta: number }): Pip }) } } - const update = [{ id: pipe.id as AnyNodeId, data: { path } }, ...follow(path)] + const followers = follow(path) + if (!followers) return { status: 'blocked' } + const update = [{ id: pipe.id as AnyNodeId, data: { path } }, ...followers] return guarded({ status: 'valid', preview: update, diff --git a/packages/nodes/src/pipe-segment/selection.tsx b/packages/nodes/src/pipe-segment/selection.tsx index 008ae6e350..e8a0ac65e7 100644 --- a/packages/nodes/src/pipe-segment/selection.tsx +++ b/packages/nodes/src/pipe-segment/selection.tsx @@ -337,9 +337,11 @@ const PipePointHandles = ({ pipe, target }: { pipe: PipeSegmentNode; target: Obj ) } const path = constrained + const followers = detached ? [] : connectivityUpdatesForPath(drag.connectivity, path) + if (!followers) return null const updates = [ { id: pipe.id as AnyNodeId, data: { path, wallAttachment: attachmentFor(path) } }, - ...(detached ? [] : connectivityUpdatesForPath(drag.connectivity, path)), + ...followers, ] return checked(detached ? updates : withEndCapFollow(path, updates)) } @@ -354,15 +356,18 @@ const PipePointHandles = ({ pipe, target }: { pipe: PipeSegmentNode; target: Obj // Follow-updates for fittings / pipes mated to this run's endpoints, given // the run's live path. Endpoints whose position didn't change resolve to a - // zero delta, so only the dragged endpoint's partner actually moves. + // zero delta, so only the dragged endpoint's partner actually moves. Null + // when the mated joints cannot follow the path. const connectivityUpdatesForPath = ( connectivity: PortConnectivity | null, path: Point[], - ): { id: AnyNodeId; data: Partial }[] => { + ): { id: AnyNodeId; data: Partial }[] | null => { if (!connectivity) return [] const preview = { ...(pipe as Record), path } as AnyNode - return resolveConnectivityUpdates(connectivity, preview).filter( - (u) => useScene.getState().nodes[u.id], + return ( + resolveConnectivityUpdates(connectivity, preview)?.filter( + (u) => useScene.getState().nodes[u.id], + ) ?? null ) } diff --git a/packages/nodes/src/shared/path-point-affordance.ts b/packages/nodes/src/shared/path-point-affordance.ts index 0025736f06..a4d5e505e0 100644 --- a/packages/nodes/src/shared/path-point-affordance.ts +++ b/packages/nodes/src/shared/path-point-affordance.ts @@ -108,9 +108,10 @@ export function createPathPointMoveAffordance), path: nextPath, } as AnyNode - const updates = resolveConnectivityUpdates(connectivity, preview).filter( + const updates = resolveConnectivityUpdates(connectivity, preview)?.filter( (u) => useScene.getState().nodes[u.id], ) + if (!updates) return null const capUpdates = endCapUpdates(nextPath) const capIds = new Set(capUpdates.map((update) => update.id)) return [...updates.filter((update) => !capIds.has(update.id)), ...capUpdates] @@ -150,12 +151,15 @@ export function createPathPointMoveAffordance (i === pointIndex ? dragged : p)) + const follow = detached ? [] : followUpdates(nextPath) + // Joints that cannot follow hold the frame, like an out-of-range turn. + if (!follow) return useScene.getState().updateNodes([ { id: node.id, data: { path: nextPath, wallAttachment: undefined } as Partial as never, }, - ...(detached ? [] : followUpdates(nextPath)).map((u) => ({ + ...follow.map((u) => ({ id: u.id, data: u.data as Partial as never, })), diff --git a/packages/nodes/src/shared/path-segment-affordance.ts b/packages/nodes/src/shared/path-segment-affordance.ts index 9d1a3b747c..c734026784 100644 --- a/packages/nodes/src/shared/path-segment-affordance.ts +++ b/packages/nodes/src/shared/path-segment-affordance.ts @@ -8,7 +8,7 @@ import { resolveConnectivityUpdates, useScene, } from '@pascal-app/core' -import { snapPointToGrid, type WallPlanPoint } from '@pascal-app/editor' +import { isGridSnapActive, snapPointToGrid, type WallPlanPoint } from '@pascal-app/editor' /** * Shared "side-move a path segment" floor-plan affordance for polyline @@ -19,7 +19,8 @@ import { snapPointToGrid, type WallPlanPoint } from '@pascal-app/editor' * - **move-segment**: slide one segment perpendicular to itself. Both its * vertices translate by the same plan-normal offset (the offset is the * cursor's projection onto the segment normal); neighbours stretch and any - * mated joint follows via port connectivity. Grid-snapped (Shift bypasses). + * mated joint follows via port connectivity. Grid-snapped while grid + * snapping is on. * * The vertices' Y (elevation) is always held — plan editing never changes * height, matching the path-point affordance. Behavioral parity with the 3D @@ -59,7 +60,8 @@ function makeConnectivity( ): { connectivity: PortConnectivity | null affectedIds: AnyNodeId[] - followUpdates: (nextPath: Point[]) => { id: AnyNodeId; data: Partial }[] + /** Null when the mated joints cannot follow `nextPath`. */ + followUpdates: (nextPath: Point[]) => { id: AnyNodeId; data: Partial }[] | null } { const connectivity = analyze ? analyzePortConnectivity(node as unknown as AnyNode, nodes) : null const affectedIds: AnyNodeId[] = [ @@ -72,8 +74,10 @@ function makeConnectivity( ...(node as unknown as Record), path: nextPath, } as AnyNode - return resolveConnectivityUpdates(connectivity, preview).filter( - (u) => useScene.getState().nodes[u.id], + return ( + resolveConnectivityUpdates(connectivity, preview)?.filter( + (u) => useScene.getState().nodes[u.id], + ) ?? null ) } return { connectivity, affectedIds, followUpdates } @@ -97,14 +101,13 @@ export function createSegmentMoveAffordance( return { affectedIds, - apply({ planPoint, modifiers }) { + apply({ planPoint }) { // Project the cursor onto the segment normal — that signed distance - // is how far the whole segment slides. Grid-snap the magnitude - // (Shift bypasses) so the slide lands on the same lattice as the - // other plan tools. + // is how far the whole segment slides. Grid-snap the magnitude so the + // slide lands on the same lattice as the other plan tools. const signedRaw = (planPoint[0] - mid[0]) * normal[0] + (planPoint[1] - mid[1]) * normal[1] - const signed = modifiers.shiftKey ? signedRaw : snapPointToGrid([signedRaw, 0])[0] + const signed = isGridSnapActive() ? snapPointToGrid([signedRaw, 0])[0] : signedRaw const ox = normal[0] * signed const oz = normal[1] * signed const nextPath = initialPath.map((p, i) => @@ -112,9 +115,12 @@ export function createSegmentMoveAffordance( ? ([p[0] + ox, p[1], p[2] + oz] as Point) : p, ) + const follow = followUpdates(nextPath) + // Joints that cannot follow hold the frame. + if (!follow) return useScene.getState().updateNodes([ { id: node.id, data: { path: nextPath } as Partial as never }, - ...followUpdates(nextPath).map((u) => ({ + ...follow.map((u) => ({ id: u.id, data: u.data as Partial as never, })), diff --git a/packages/nodes/src/shared/port-connectivity-pipe.test.ts b/packages/nodes/src/shared/port-connectivity-pipe.test.ts index 3173e6b10c..4e9af8bd4e 100644 --- a/packages/nodes/src/shared/port-connectivity-pipe.test.ts +++ b/packages/nodes/src/shared/port-connectivity-pipe.test.ts @@ -148,3 +148,97 @@ describe('port connectivity — DWV pipe family', () => { expect(trapConnectivity.connections.find((c) => c.nodeId === run.id)).toBeDefined() }) }) + +type Point = [number, number, number] + +function widestJointGap(before: Record, after: Record): number { + const distance = (a: Point, b: Point) => Math.hypot(a[0] - b[0], a[1] - b[1], a[2] - b[2]) + let widest = 0 + for (const a of Object.values(before)) { + for (const b of Object.values(before)) { + if (a.id >= b.id) continue + for (const pa of portsOf(a.type, a)) { + for (const pb of portsOf(b.type, b)) { + if (distance(pa.position, pb.position) > 1e-6) continue + const na = portsOf(a.type, after[a.id]!).find((p) => p.id === pa.id)! + const nb = portsOf(b.type, after[b.id]!).find((p) => p.id === pb.id)! + widest = Math.max(widest, distance(na.position, nb.position)) + } + } + } + } + return widest +} + +describe('port connectivity — pipe runs carried through elbows', () => { + beforeEach(async () => { + nodeRegistry._reset() + await loadPlugin(builtinPlugin) + }) + + afterEach(() => { + nodeRegistry._reset() + }) + + const elbowAt = (position: Point) => + PipeFittingNode.parse({ + ...nodeRegistry.get('pipe-fitting')!.defaults!(), + parentId: null, + position, + rotation: [0, 0, 0], + }) + const runAlong = (path: Point[]) => + PipeSegmentNode.parse({ + ...nodeRegistry.get('pipe-segment')!.defaults!(), + parentId: null, + path, + }) + + // A straight run into an elbow, an L run to a second elbow, and a tail run. + const lChain = () => { + const first = runAlong([ + [0.07, 1, 0], + [3.93, 1, 0], + ]) + const l = runAlong([ + [4, 1, 0.07], + [4, 1, 2], + [6.93, 1, 2], + ]) + const chain = [ + first, + elbowAt([4, 1, 0]), + l, + elbowAt([7, 1, 2]), + runAlong([ + [7, 1, 2.07], + [7, 1, 5], + ]), + ] as AnyNode[] + return { first, l, nodes: Object.fromEntries(chain.map((node) => [node.id, node])) } + } + + test.each([ + [0.3, 0, 0.4], + [0.05, 0, 0.05], + [0.3, 0.2, 0.4], + ])('dragging the first run by (%p, %p, %p) keeps every joint welded', (dx, dy, dz) => { + const { first, l, nodes } = lChain() + const moved = { + ...first, + path: first.path.map(([x, y, z]) => [x + dx, y + dy, z + dz]), + } as AnyNode + const updates = resolveConnectivityUpdates( + analyzePortConnectivity(first as AnyNode, nodes), + moved, + ) + expect(updates).not.toBeNull() + + const after: Record = { ...nodes, [first.id]: moved } + for (const update of updates!) + after[update.id] = { ...after[update.id]!, ...update.data } as AnyNode + expect(widestJointGap(nodes, after)).toBeLessThan(1e-6) + const [, corner, end] = (after[l.id] as PipeSegmentNode).path + expect(Math.hypot(end![0] - corner![0], end![2] - corner![2])).toBeCloseTo(2.93, 6) + }) +}) diff --git a/packages/nodes/src/shared/refrigerant-line-selection.tsx b/packages/nodes/src/shared/refrigerant-line-selection.tsx index d3153db432..7170bbcb19 100644 --- a/packages/nodes/src/shared/refrigerant-line-selection.tsx +++ b/packages/nodes/src/shared/refrigerant-line-selection.tsx @@ -14,7 +14,13 @@ import { sceneRegistry, useScene, } from '@pascal-app/core' -import { DimensionPill, swallowNextClick, triggerSFX, useEditor } from '@pascal-app/editor' +import { + DimensionPill, + isGridSnapActive, + swallowNextClick, + triggerSFX, + useEditor, +} from '@pascal-app/editor' import { collectScenePorts, findNearestPortXZ } from '@pascal-app/editor/distribution' import { useViewer } from '@pascal-app/viewer' import { Html } from '@react-three/drei' @@ -134,14 +140,17 @@ function RefrigerantLineEndpointHandles({ detached: boolean } | null>(null) + /** Null when the mated joints cannot follow `path`. */ const followUpdates = ( connectivity: PortConnectivity | null, path: Point[], - ): { id: AnyNodeId; data: Partial }[] => { + ): { id: AnyNodeId; data: Partial }[] | null => { if (!connectivity) return [] const preview = { ...(line as unknown as Record), path } as AnyNode - return resolveConnectivityUpdates(connectivity, preview).filter( - (u) => useScene.getState().nodes[u.id], + return ( + resolveConnectivityUpdates(connectivity, preview)?.filter( + (u) => useScene.getState().nodes[u.id], + ) ?? null ) } @@ -252,7 +261,7 @@ function RefrigerantLineEndpointHandles({ const onMove = (event: PointerEvent) => { const drag = dragRef.current if (!drag) return - const step = event.shiftKey ? 0 : useEditor.getState().gridSnapStep + const step = isGridSnapActive() ? useEditor.getState().gridSnapStep : 0 const detached = event.altKey let next: Point | null = null if (canSwing && pivot) { @@ -291,16 +300,16 @@ function RefrigerantLineEndpointHandles({ } if (next[0] === drag.current[0] && next[1] === drag.current[1] && next[2] === drag.current[2]) return + const path = line.path.map((p, i) => (i === drag.index ? next! : p)) as Point[] + const follow = detached ? [] : followUpdates(drag.connectivity, path) + // Joints that cannot follow hold the last frame, which release commits. + if (!follow) return drag.current = next drag.detached = detached if (step > 0) triggerSFX('sfx:grid-snap') - const path = line.path.map((p, i) => (i === drag.index ? next! : p)) as Point[] useScene .getState() - .updateNodes([ - { id: line.id as AnyNodeId, data: { path } as Partial }, - ...(detached ? [] : followUpdates(drag.connectivity, path)), - ]) + .updateNodes([{ id: line.id as AnyNodeId, data: { path } as Partial }, ...follow]) } const onUp = () => { @@ -331,12 +340,13 @@ function RefrigerantLineEndpointHandles({ const moved = finalPath[drag.index]!.some( (v, axis) => v !== drag.initialPath[drag.index]![axis], ) - if (moved) { + const follow = moved && (detached ? [] : followUpdates(drag.connectivity, finalPath)) + if (follow) { useScene .getState() .updateNodes([ { id: line.id as AnyNodeId, data: { path: finalPath } as Partial }, - ...(detached ? [] : followUpdates(drag.connectivity, finalPath)), + ...follow, ]) } } diff --git a/packages/nodes/src/shared/run-move-connectivity.test.ts b/packages/nodes/src/shared/run-move-connectivity.test.ts new file mode 100644 index 0000000000..59606d7120 --- /dev/null +++ b/packages/nodes/src/shared/run-move-connectivity.test.ts @@ -0,0 +1,83 @@ +import { afterEach, beforeEach, expect, test } from 'bun:test' +import { + type AnyNode, + LevelNode, + nodeRegistry, + PipeFittingNode, + PipeSegmentNode, + registerNode, + useLiveNodeOverrides, + useScene, +} from '@pascal-app/core' +import { pipeFittingDefinition } from '../pipe-fitting/definition' +import { pipeSegmentDefinition } from '../pipe-segment/definition' +import { startRunMoveConnectivity } from './run-move-connectivity' + +type Point = [number, number, number] + +let restore: ReturnType +let previous: ReturnType['nodes'] +beforeEach(() => { + restore = nodeRegistry._snapshot() + registerNode(pipeSegmentDefinition) + registerNode(pipeFittingDefinition) + previous = useScene.getState().nodes +}) +afterEach(() => { + useLiveNodeOverrides.getState().clearAll() + useScene.setState({ nodes: previous }) + restore() +}) + +/** A run whose end corner turns into a U that loops back to the corner at its start. */ +function loopedRun() { + const level = LevelNode.parse({}) + const run = PipeSegmentNode.parse({ + ...pipeSegmentDefinition.defaults(), + parentId: level.id, + path: [ + [0.07, 1, 0], + [3.93, 1, 0], + ], + }) + const corner = (position: Point, rotationY: number) => + PipeFittingNode.parse({ + ...pipeFittingDefinition.defaults(), + parentId: level.id, + position, + rotation: [0, rotationY, 0], + }) + const u = PipeSegmentNode.parse({ + ...pipeSegmentDefinition.defaults(), + parentId: level.id, + path: [ + [4, 1, 0.07], + [4, 1, 2], + [0, 1, 2], + [0, 1, 0.07], + ], + }) + const nodes = [level, run, corner([4, 1, 0], 0), u, corner([0, 1, 0], Math.PI / 2)] + useScene.setState({ + nodes: Object.fromEntries(nodes.map((node) => [node.id, node as AnyNode])), + } as never) + return run +} + +test('a transform the followers cannot follow keeps the last preview and commits nothing', () => { + const run = loopedRun() + const connectivity = startRunMoveConnectivity(run as AnyNode)! + const shifted = run.path.map(([x, y, z]) => [x, y, z + 0.2] as Point) + const shown = connectivity.preview({ path: shifted }) + expect(shown).not.toBeNull() + const overrides = new Map(useLiveNodeOverrides.getState().overrides) + expect(overrides.size).toBeGreaterThan(0) + + // Stretching the end along the run would carry the U with it and drag the + // start corner off the run's start. + const stretched: Point[] = [run.path[0]!, [4.43, 1, 0]] + expect(connectivity.preview({ path: stretched })).toBeNull() + expect(new Map(useLiveNodeOverrides.getState().overrides)).toEqual(overrides) + expect(connectivity.commitUpdates({ path: stretched })).toBeNull() + expect(connectivity.commitUpdates({ path: shifted })).toEqual(shown!) +}) diff --git a/packages/nodes/src/shared/run-move-connectivity.ts b/packages/nodes/src/shared/run-move-connectivity.ts index 7f313eda24..88c009d115 100644 --- a/packages/nodes/src/shared/run-move-connectivity.ts +++ b/packages/nodes/src/shared/run-move-connectivity.ts @@ -33,7 +33,9 @@ type MovedTransform = { path?: Vec3[]; position?: Vec3 } * through `useLiveNodeOverrides` (transient — no history churn; * `getEffectiveNode` merges overrides so the connected geometry rebuilds at * pointer rate), then fold into the commit's single tracked `updateNodes` - * batch. + * batch. A transform the followers cannot follow without pulling a joint + * apart resolves to `null`: the tool holds its last shown frame, so release + * commits what is on screen. * * Returns `null` when nothing is connected, so callers skip all the work. */ @@ -51,18 +53,25 @@ export class RunMoveConnectivity { private readonly connectivity: PortConnectivity, ) {} - /** Patches that keep the connected nodes attached for a given live transform. */ - private updatesFor(transform: MovedTransform): { id: AnyNodeId; data: Partial }[] { + /** Patches that keep the connected nodes attached for a given live transform, + * or null when they cannot all stay attached. */ + private updatesFor( + transform: MovedTransform, + ): { id: AnyNodeId; data: Partial }[] | null { const preview = { ...(this.node as Record), ...transform } as AnyNode - return resolveConnectivityUpdates(this.connectivity, preview).filter( - (u) => useScene.getState().nodes[u.id], + return ( + resolveConnectivityUpdates(this.connectivity, preview)?.filter( + (u) => useScene.getState().nodes[u.id], + ) ?? null ) } /** Live-preview the followers for the moved node's current drag transform, - * returning the follower patches it shows. */ - preview(transform: MovedTransform): { id: AnyNodeId; data: Partial }[] { + * returning the follower patches it shows. Null leaves the previous preview + * in place: the followers cannot follow this transform. */ + preview(transform: MovedTransform): { id: AnyNodeId; data: Partial }[] | null { const updates = this.updatesFor(transform) + if (!updates) return null const overrides = useLiveNodeOverrides.getState() const nextIds = updates.map((u) => u.id) // Drop overrides on nodes that fell out of this frame's update set (e.g. a @@ -83,8 +92,9 @@ export class RunMoveConnectivity { return updates } - /** Follower patches to fold into the commit `updateNodes` batch. */ - commitUpdates(transform: MovedTransform): { id: AnyNodeId; data: Partial }[] { + /** Follower patches to fold into the commit `updateNodes` batch, or null when + * they cannot follow `transform`. */ + commitUpdates(transform: MovedTransform): { id: AnyNodeId; data: Partial }[] | null { return this.updatesFor(transform) } diff --git a/wiki/architecture/interaction-scope.md b/wiki/architecture/interaction-scope.md index c7f4bd0d56..1083dc7b0f 100644 --- a/wiki/architecture/interaction-scope.md +++ b/wiki/architecture/interaction-scope.md @@ -157,11 +157,11 @@ There is no per-kind snapping switch. spots not yet touched (the `event.altKey` alignment bypass and pre-scope `useEditor` flags). A PR that **touches** one must migrate it to the model above, not extend the legacy path: -1. **`event.shiftKey` as a snap bypass with hardcoded steps** — the pipe-fitting and refrigerant-line - handles (`packages/nodes/src/pipe-fitting/selection.tsx`, `packages/nodes/src/shared/refrigerant-line-selection.tsx`) - and the 2D path-segment and polygon-centroid drags - (`packages/nodes/src/shared/{path-segment-affordance,polygon-centroid-move}.ts`). Migrated handles read - `isGridSnapActive()` / `isAngleSnapActive()` instead (`duct-segment/selection.tsx`, `duct-fitting/selection.tsx`). +1. **`event.shiftKey` as a snap bypass with hardcoded steps** — the 2D polygon-centroid drag + (`packages/nodes/src/shared/polygon-centroid-move.ts`). Migrated handles read + `isGridSnapActive()` / `isAngleSnapActive()` instead (`{duct,pipe}-segment/selection.tsx`, + `{duct,pipe}-fitting/{selection,move-tool}.tsx`, `shared/refrigerant-line-selection.tsx`, + `shared/path-segment-affordance.ts`). Opening a `moving` scope from a bespoke mover is **not** the migration — `useMovingNode()` reads the scope, so `tool-manager` re-mounts the generic `MoveRegistryNodeTool` alongside it (the dual-path FPS/teleport bug). Resolve the mode without a global `moving`/`reshaping` scope; see the plan's dual-path note.