* Add roof surface placement support for items Items (e.g. solar panels) can now be placed on sloped roof surfaces. The placement system computes euler rotation from the roof surface normal so items sit flush on the slope instead of going inside. - Add roofStrategy to placement-strategies with enter/move/click/leave - Wire roof:enter/move/click/leave events in the placement coordinator - Add calculateRoofRotation in placement-math using surface normals - Support full 3D cursor rotation for sloped surfaces - Items on roofs are parented to the level with world-space rotation Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fixed conflict * Snapshot: ridge vent locks to segment ridge during placement, free sliders after Placement tool clamps the cursor to the segment's ridge line for all roof types (gable, hip, shed, gambrel, dutch, mansard; flat rejected). Renderer re-derives Y from the live surface plus a small lift, and treats stored position[1] / position[2] as user offsets so the inspector sliders move the vent after placement. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * feat(roof): contribute outer silhouette to alignment-guide candidates Roof has no centred-box footprint (it's the union of its `roof-segment` children) so the capability bridge needs the resolved AABB directly. We build it from the children's corners in roof-local space, then transform to world coords. Roofs only contribute as static candidates — the move-roof tool drives them by origin, so the relocatable-box path never applies. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * feat(floorplan): upright text geometry that stays horizontal under scene rotation Floor-plan text labels were rotating with the 90° default scene rotation, making zone names read sideways. Add an `upright` flag to text geometry: when set, the registry layer counter-rotates the label by sceneRotationDeg around its anchor so it reads horizontally on screen. Zone labels opt in. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * feat(editor): redesign material-paint cursor badge and gate floor-plan paint mode Paint cursor swaps the inline icon+label chip for a stacked badge — a glowing accent stem pointing down to the hit point with the paint icon above — so the cue reads as "pointer" rather than "tooltip". Switches the accent to indigo. The 2D floor-plan now also shows the paint-icon overlay and routes pointer interactions to the painter when in material-paint mode. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * feat(editor): 90° rotate action on the floating building menu Adds a Rotate button to the building action menu (and a generic `onRotate` slot to NodeActionMenu). Each click rotates the building 90° CW around its world-bbox center, mirroring the offset compensation `MoveBuildingContent` uses during R/T-rotate drags — so the building spins in place instead of orbiting its (often off-centre) origin. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * feat(column,shelf): show cursor sphere during placement preview Matches the placement affordance other floor-placed tools already have so users see the snap point as a discrete dot alongside the ghost mesh. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * chore(ifc-converter): update next-env types path to .next/dev/types Next.js moved generated route types under `.next/dev/types/` — regenerate the reference so the type-check resolves them again. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix(ridge-vent): track parent segment's live overrides for real-time follow While dragging a roof-segment resize handle (width / depth / pitch / wallHeight / rotation), the new dimensions stream through useLiveNodeOverrides and only flush to the store on release — so the ridge vent was snapping to the new ridge only after the drag ended. Merge segment overrides into the renderer's segment view so the vent rides the resize in real time. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * feat(editor): step building rotation in 15° increments Cuts the floating building menu's rotate-step from 90° to 15° so each click nudges the building rather than slamming it to the next cardinal. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * feat(editor): world-frame alignment guides and grid snap under building rotation Brings the 2D floor-plan alignment + grid behaviour in line with 3D so guides and snap follow the world XZ grid regardless of how the active building is rotated. Core: adds resolveAlignmentInBuildingWorld + snapWorldXZToBuildingLocal, plus a shared BuildingPose type, so callers can resolve in world space while staying in building-local coords downstream. Editor: introduces packages/editor/src/lib/world-grid-snap.ts as the single entry point for tools that need world-frame alignment / grid snap (resolveAlignmentForActiveBuilding, getActiveBuildingPose, snapWorldXZForActiveBuilding, snapBuildingLocalToWorldGrid). Honours useLiveTransforms and resolves the active building via level.parentId first so the helper stays in sync with the floor-plan panel. Alignment store unification: applyFloorplanAlignment and the registry move overlay now publish guides in world XZ — the same frame the 3D tools already use — so the shared useAlignmentGuides store carries one consistent coordinate system. The 2D layer renders world XZ via the fixed world → SVG transform (a 90° rotation around the building's world position; independent of building rotation), so guides come out parallel to the world-axis-aligned floor-plan grid in every case. Drafting + move sessions across walls, fences, slabs, ceilings, columns, items, shelves, roofs, stairs, zones and elevators are re-routed through the new helpers so cursor placement, grid snap, draft endpoints, and move commits all land on the world XZ grid even when the building has been rotated. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * revert(editor): drop building drag-rotate and grid building-XZ chase Two behaviours added recently were causing the world grid to slide around during building edits. Reverts both, keeping the rest of the world-frame alignment work intact. - floating-building-action-menu / node-action-menu: roll the rotate button back to a single click that increments rotation by 15° around the bbox center (state at 3eb02fde). The drag-rotate from b50c0d5a streamed live position updates per frame, which the floor plan and grid both followed. - grid: stop chasing the active building's world XZ each frame (pre-c00a2469 behaviour). The grid stays anchored at world (0, 0) so it doesn't visibly sweep when the building origin moves — during a drag, an R/T rotation in the move tool, or a click rotate that re-anchors the origin to the bbox-pivot. Y still lerps to the active level's floor height. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * feat(editor): consistent building rotation pivot + 2D position sync Several connected fixes to building rotate/move so the 3D mesh, the 2D floor plan, and alignment guides all stay visually consistent across rotations and drags. Rotation-invariant pivot - New `getBuildingLocalBboxCenter` helper walks descendant mesh geometry bounds in the building's LOCAL frame, returning a centroid that doesn't depend on the building's current world rotation. The previous approach derived the pivot from the world AABB at the current rotation, which made the local pivot subtly drift each time the building was rotated. - Floating menu click-rotate and move-tool R/T rotation now seed their pivot from this helper, so successive rotations stay pinned at the same world point. Move-tool stability - R/T rotation always pivots around the current world bbox center, even before the cursor has moved onto the grid (previously it fell back to rotating around the origin in that case). - Commit (`onGridClick`) now writes the mesh's actual on-screen pose instead of recomputing it from the click event's grid coords, removing a one-cell snap on release. Alignment resolver - Tie-break is now perp-first, primary-second. The previous order was reliable when wall faces shared an exact axis-aligned coord (pre-rotation), but post-rotation float deltas meant primary never tied and the resolver could lock onto the far corner of a candidate. Perp-first picks the visually closest point. 2D ↔ 3D sync - The floor-plan SVG scene group now applies a live `translate(...)` derived from `(committedBuildingPosition → live buildingPosition)`, in addition to the existing live rotation. Building-local content slides in lockstep with the 3D mesh during a drag. - The alignment-guide layer projects from world XZ using the COMMITTED building position, so guides stay locked to their world coordinates while the building slides past them. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * Merge remote-tracking branch 'origin/main' into fix/fir-5-june * feat(wall): alt-click commits a single wall instead of chaining Holding Alt on the click that completes a segment now stops drafting instead of starting a new segment from the just-placed endpoint. Same behaviour wired in both the 3D wall tool and the 2D floor-plan placement hook (which already passed `singleWall: event.altKey` — the 2D handler was ignoring the flag). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * revert(editor): drop 15° rotate from floating building action menu Removes the rotate button on the floating building menu and the `getBuildingLocalBboxCenter` pivot helper that only existed to support it. The selected-group rotate handle remains the way to rotate a building. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * chore(ifc-converter): point next-env at .next/types instead of .next/dev/types Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * feat(editor): unify 3D move grip with floating-menu Move via tap-to-engage The translate gizmo on the 3D bounding box now hands the node to the registry move tool (same path as the floating action menu's Move button) instead of running its own plane-drag. One move flow — green bounding box, cursor follow, alignment guides, R/T rotation, click-to-commit — drives both entry points. Adds a `dragBounds` capability on the node registry so kinds whose rendered mesh contains extras (per-level landing assemblies on an elevator, etc.) can declare the box the user thinks of as "the thing being dragged." Elevator and stair opt in; everything else still auto-measures. `MoveRoofTool` now shows the green box for whole-stair and whole-roof moves, and aligns roofs by their footprint corners (previously only stairs did). Slab floor-plan moves clear `autoFromWalls` on commit so space-detection doesn't snap the slab back, via a new `extraCommitFields` hook on the polygon-centroid move target. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * feat(editor): 2D alignment guides in building-local frame + world-grid wall snap The 2D floor-plan alignment layer now mounts inside the rotated scene <g> and reads from an editor-local `useAlignmentGuides` store — guides are stored in building-local meters and follow the SVG transform that already carries the rest of the floor-plan geometry. Pill labels are counter-rotated by the scene rotation so they stay upright under building rotation. The 3D pipeline keeps its own world-frame store; the two surfaces no longer share frames. Wall drafting picks up an optional `gridSnap` override so the 2D floor-plan can snap drafts onto the world-XZ grid even when the active building is rotated — without it, a rotated building's drafted wall would chase the local grid and miss the visible lines. `snapPointTo45Degrees` and `snapWallDraftPointDetailed` route through the override when supplied; otherwise the prior local-axis grid snap is unchanged. The floor-plan panel wires `snapBuildingLocalToWorldGrid` through the placement hook and exports `WALL_GRID_STEP` to support it. Also fixes the minor/major grid stroke palette swap so minor lines render with the minor palette and majors with the major palette. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * chore(editor): drop dead onRotate slot, memoize dragBounds snapshot Removes the unreachable `onRotate` prop, `RotateCw` import, and rotate button from `NodeActionMenu` — its only caller was the floating building menu's 15° rotate, which was removed in d65fd5fe. Memoizes `MoveRegistryNodeTool`'s `dragBounds` lookup so it captures the scene snapshot once per node instead of re-reading `useScene.getState().nodes` on every render. Bounds depend only on `node` (locked for the tool's lifetime) and start-time sibling state (elevator shaft height from the level set), so a one-shot snapshot is the right semantics — and it avoids implying a live subscription that isn't there. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * chore: biome check --write (import order, formatting, unused import) Auto-fixes from `bun check:fix`: - import-order normalization in editor/nodes/core - unused `snapToGrid` / `useLayoutEffect` imports dropped - minor whitespace/wrapping tweaks No behavioural change. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
505 lines
19 KiB
TypeScript
505 lines
19 KiB
TypeScript
import {
|
|
type AnyNodeId,
|
|
collectAlignmentAnchors,
|
|
emitter,
|
|
type FenceNode,
|
|
type GridEvent,
|
|
type LevelNode,
|
|
movingAlignmentAnchors,
|
|
nodeRegistry,
|
|
type RoofNode,
|
|
type RoofSegmentNode,
|
|
resolveAlignment,
|
|
type StairNode,
|
|
type StairSegmentNode,
|
|
sceneRegistry,
|
|
useLiveTransforms,
|
|
useScene,
|
|
type WallNode,
|
|
} from '@pascal-app/core'
|
|
import {
|
|
CursorSphere,
|
|
commitFreshPlacementSubtree,
|
|
DragBoundingBox,
|
|
getFloorStackPreviewPosition,
|
|
resolvePlanarCursorPosition,
|
|
snapFenceDraftPoint,
|
|
stripPlacementMetadataFlags,
|
|
triggerSFX,
|
|
useAlignmentGuides,
|
|
useEditor,
|
|
useFreshPlacementVisibility,
|
|
type WallPlanPoint,
|
|
} from '@pascal-app/editor'
|
|
import { useViewer } from '@pascal-app/viewer'
|
|
import { useCallback, useEffect, useRef, useState } from 'react'
|
|
import * as THREE from 'three'
|
|
|
|
/** Figma-style alignment-snap threshold (meters), matching the other tools. */
|
|
const ALIGNMENT_THRESHOLD_M = 0.08
|
|
|
|
export const MoveRoofTool: React.FC<{
|
|
node: RoofNode | RoofSegmentNode | StairNode | StairSegmentNode
|
|
}> = ({ node: movingNode }) => {
|
|
const {
|
|
isFreshPlacement,
|
|
previewVisible: cursorVisible,
|
|
revealFreshPlacement,
|
|
useAbsoluteCursorPlacement,
|
|
} = useFreshPlacementVisibility({
|
|
node: movingNode,
|
|
enabled: movingNode.type === 'roof' || movingNode.type === 'stair',
|
|
})
|
|
const exitMoveMode = useCallback(() => {
|
|
useEditor.getState().setMovingNode(null)
|
|
}, [])
|
|
|
|
const previousGridPosRef = useRef<[number, number] | null>(null)
|
|
const dragAnchorRef = useRef<[number, number] | null>(null)
|
|
|
|
const [previewRotation, setPreviewRotation] = useState<number>(movingNode.rotation as number)
|
|
const [cursorWorldPos, setCursorWorldPos] = useState<[number, number, number]>(() => {
|
|
const obj = sceneRegistry.nodes.get(movingNode.id)
|
|
if (obj) {
|
|
const worldPos = obj.getWorldPosition(new THREE.Vector3())
|
|
// Cursor renders inside the building-local ToolManager group, so convert
|
|
// world → building-local to honor any building rotation.
|
|
const buildingId = useViewer.getState().selection.buildingId
|
|
const buildingObj = buildingId ? sceneRegistry.nodes.get(buildingId as AnyNodeId) : null
|
|
if (buildingObj) buildingObj.worldToLocal(worldPos)
|
|
return [worldPos.x, worldPos.y, worldPos.z]
|
|
}
|
|
// Fallback if not registered (e.g. newly created duplicate without mesh yet)
|
|
if (
|
|
(movingNode.type === 'roof-segment' || movingNode.type === 'stair-segment') &&
|
|
movingNode.parentId
|
|
) {
|
|
const parentNode = useScene.getState().nodes[movingNode.parentId as AnyNodeId]
|
|
if (parentNode && 'position' in parentNode && 'rotation' in parentNode) {
|
|
const parentAngle = parentNode.rotation as number
|
|
const px = parentNode.position[0] as number
|
|
const py = parentNode.position[1] as number
|
|
const pz = parentNode.position[2] as number
|
|
const lx = movingNode.position[0]
|
|
const ly = movingNode.position[1]
|
|
const lz = movingNode.position[2]
|
|
|
|
const wx = lx * Math.cos(parentAngle) - lz * Math.sin(parentAngle) + px
|
|
const wz = lx * Math.sin(parentAngle) + lz * Math.cos(parentAngle) + pz
|
|
return [wx, py + ly, wz]
|
|
}
|
|
}
|
|
return [movingNode.position[0], movingNode.position[1], movingNode.position[2]]
|
|
})
|
|
|
|
useEffect(() => {
|
|
useScene.temporal.getState().pause()
|
|
dragAnchorRef.current = null
|
|
previousGridPosRef.current = null
|
|
|
|
const isNew = isFreshPlacement
|
|
const committedMeta = stripPlacementMetadataFlags(movingNode.metadata) as RoofNode['metadata']
|
|
|
|
const original = {
|
|
position: [...movingNode.position] as [number, number, number],
|
|
rotation: movingNode.rotation,
|
|
parentId: movingNode.parentId,
|
|
metadata: movingNode.metadata,
|
|
}
|
|
|
|
// Track whether the move was committed so cleanup knows whether to revert.
|
|
// We avoid setting isTransient on the store to prevent RoofSystem from
|
|
// resetting the mesh position (it resets on dirty) and from triggering
|
|
// expensive merged-mesh CSG rebuilds on every frame.
|
|
let wasCommitted = false
|
|
let wasCancelled = false
|
|
let hasMoved = false
|
|
|
|
// Track pending rotation — no store updates during drag
|
|
let pendingRotation: number = movingNode.rotation as number
|
|
let lastLocalPosition: [number, number, number] = [
|
|
movingNode.position[0],
|
|
movingNode.position[1],
|
|
movingNode.position[2],
|
|
]
|
|
|
|
// For roof-segment moves: the selection was cleared before entering move mode,
|
|
// so isSelected=false on the parent roof, hiding individual segment meshes and
|
|
// showing only the merged mesh. We directly flip Three.js visibility so the
|
|
// user sees the individual segment tracking the cursor.
|
|
let segmentWrapperGroup: THREE.Object3D | null = null
|
|
let mergedRoofMesh: THREE.Object3D | null = null
|
|
if (movingNode.type === 'roof-segment' || movingNode.type === 'stair-segment') {
|
|
const segmentMesh = sceneRegistry.nodes.get(movingNode.id)
|
|
if (segmentMesh?.parent) {
|
|
// segmentMesh.parent = <group visible={isSelected}> wrapper in Roof/StairRenderer
|
|
// segmentMesh.parent.parent = the registered roof/stair group
|
|
segmentWrapperGroup = segmentMesh.parent
|
|
const mergedName = movingNode.type === 'stair-segment' ? 'merged-stair' : 'merged-roof'
|
|
mergedRoofMesh = segmentMesh.parent.parent?.getObjectByName(mergedName) ?? null
|
|
segmentWrapperGroup.visible = true
|
|
if (mergedRoofMesh) mergedRoofMesh.visible = false
|
|
}
|
|
}
|
|
|
|
const resolveLevelId = () => {
|
|
if (movingNode.type === 'roof' || movingNode.type === 'stair') {
|
|
return movingNode.parentId ?? null
|
|
}
|
|
|
|
if (
|
|
(movingNode.type === 'roof-segment' || movingNode.type === 'stair-segment') &&
|
|
movingNode.parentId
|
|
) {
|
|
const parentNode = useScene.getState().nodes[movingNode.parentId as AnyNodeId]
|
|
return parentNode && 'parentId' in parentNode ? (parentNode.parentId ?? null) : null
|
|
}
|
|
|
|
return null
|
|
}
|
|
|
|
const levelId = resolveLevelId()
|
|
const isFloorPlaced = nodeRegistry.get(movingNode.type)?.capabilities?.floorPlaced !== undefined
|
|
const getPreviewPosition = (
|
|
position: [number, number, number],
|
|
rotation = pendingRotation,
|
|
): [number, number, number] => {
|
|
if (!isFloorPlaced) return position
|
|
return getFloorStackPreviewPosition({
|
|
node: movingNode,
|
|
position,
|
|
rotation,
|
|
levelId,
|
|
nodes: useScene.getState().nodes,
|
|
})
|
|
}
|
|
const levelNode =
|
|
levelId && useScene.getState().nodes[levelId as AnyNodeId]?.type === 'level'
|
|
? (useScene.getState().nodes[levelId as AnyNodeId] as LevelNode)
|
|
: null
|
|
const levelChildren = levelNode?.children ?? []
|
|
const levelWalls = levelChildren
|
|
.map((childId) => useScene.getState().nodes[childId as AnyNodeId])
|
|
.filter((node): node is WallNode => node?.type === 'wall')
|
|
const levelFences = levelChildren
|
|
.map((childId) => useScene.getState().nodes[childId as AnyNodeId])
|
|
.filter((node): node is FenceNode => node?.type === 'fence')
|
|
const buildingId = useViewer.getState().selection.buildingId
|
|
const buildingObj = buildingId ? sceneRegistry.nodes.get(buildingId as AnyNodeId) : null
|
|
|
|
// Alignment for top-level stair / roof only. Segments live in parent-local
|
|
// space (a different frame from the building-local candidate pool / guide
|
|
// layer), so we leave them on the plain grid+corner snap. Both stair and
|
|
// roof align by their footprint bounding-box corners.
|
|
const alignTopLevel = movingNode.type === 'stair' || movingNode.type === 'roof'
|
|
const alignmentCandidates = alignTopLevel
|
|
? collectAlignmentAnchors(
|
|
useScene.getState().nodes,
|
|
movingNode.id,
|
|
movingNode.type === 'stair' ? levelId : undefined,
|
|
)
|
|
: []
|
|
const alignLocalPoint = (lx: number, lz: number, bypass: boolean): [number, number] => {
|
|
if (!alignTopLevel || bypass || alignmentCandidates.length === 0) {
|
|
useAlignmentGuides.getState().clear()
|
|
return [lx, lz]
|
|
}
|
|
const moving =
|
|
movingNode.type === 'stair' || movingNode.type === 'roof'
|
|
? movingAlignmentAnchors(movingNode, useScene.getState().nodes, lx, lz, pendingRotation)
|
|
: []
|
|
const ar = resolveAlignment({
|
|
moving:
|
|
moving.length > 0 ? moving : [{ nodeId: movingNode.id, kind: 'corner', x: lx, z: lz }],
|
|
candidates: alignmentCandidates,
|
|
threshold: ALIGNMENT_THRESHOLD_M,
|
|
})
|
|
useAlignmentGuides.getState().set(ar.guides)
|
|
return ar.snap ? [lx + ar.snap.dx, lz + ar.snap.dz] : [lx, lz]
|
|
}
|
|
|
|
const localToWorldPoint = (localPoint: WallPlanPoint, y: number): [number, number, number] => {
|
|
if (buildingObj) {
|
|
const worldPoint = buildingObj.localToWorld(
|
|
new THREE.Vector3(localPoint[0], y, localPoint[1]),
|
|
)
|
|
return [worldPoint.x, worldPoint.y, worldPoint.z]
|
|
}
|
|
|
|
return [localPoint[0], y, localPoint[1]]
|
|
}
|
|
|
|
const computeLocal = (
|
|
gridX: number,
|
|
gridZ: number,
|
|
y: number,
|
|
buildingLocalX: number,
|
|
buildingLocalZ: number,
|
|
): [number, number] => {
|
|
// Segments have a transformed parent (stair/roof). Convert world → parent-local
|
|
// via Three.js hierarchy so the segment's stored position stays parent-relative.
|
|
if (
|
|
(movingNode.type === 'roof-segment' || movingNode.type === 'stair-segment') &&
|
|
movingNode.parentId
|
|
) {
|
|
const parentNode = useScene.getState().nodes[movingNode.parentId as AnyNodeId]
|
|
if (parentNode && 'position' in parentNode && 'rotation' in parentNode) {
|
|
const parentObj = sceneRegistry.nodes.get(movingNode.parentId)
|
|
if (parentObj) {
|
|
const worldVec = new THREE.Vector3(gridX, y, gridZ)
|
|
parentObj.worldToLocal(worldVec)
|
|
return [worldVec.x, worldVec.z]
|
|
}
|
|
const dx = gridX - (parentNode.position[0] as number)
|
|
const dz = gridZ - (parentNode.position[2] as number)
|
|
const angle = -(parentNode.rotation as number)
|
|
return [
|
|
dx * Math.cos(angle) - dz * Math.sin(angle),
|
|
dx * Math.sin(angle) + dz * Math.cos(angle),
|
|
]
|
|
}
|
|
}
|
|
|
|
// Stair/roof live directly in the level — their stored position is building-local.
|
|
// event.localPosition is already building-local, so using it handles building rotation.
|
|
return [buildingLocalX, buildingLocalZ]
|
|
}
|
|
|
|
const localPositionToToolLocal = (
|
|
position: [number, number, number],
|
|
): [number, number, number] => {
|
|
if (
|
|
(movingNode.type === 'roof-segment' || movingNode.type === 'stair-segment') &&
|
|
movingNode.parentId
|
|
) {
|
|
const parentObj = sceneRegistry.nodes.get(movingNode.parentId)
|
|
if (parentObj) {
|
|
const point = parentObj.localToWorld(new THREE.Vector3(...position))
|
|
if (buildingObj) buildingObj.worldToLocal(point)
|
|
return [point.x, point.y, point.z]
|
|
}
|
|
}
|
|
|
|
return position
|
|
}
|
|
|
|
const onGridMove = (event: GridEvent) => {
|
|
hasMoved = true
|
|
revealFreshPlacement()
|
|
|
|
const y = event.position[1]
|
|
|
|
const snappedLocal = snapFenceDraftPoint({
|
|
point: [event.localPosition[0], event.localPosition[2]],
|
|
walls: levelWalls,
|
|
fences: levelFences,
|
|
})
|
|
const [rawGridX, , rawGridZ] = localToWorldPoint(snappedLocal, y)
|
|
const [rawLocalX, rawLocalZ] = computeLocal(
|
|
rawGridX,
|
|
rawGridZ,
|
|
y,
|
|
snappedLocal[0],
|
|
snappedLocal[1],
|
|
)
|
|
const resolved = resolvePlanarCursorPosition({
|
|
cursor: [rawLocalX, rawLocalZ],
|
|
original: [movingNode.position[0], movingNode.position[2]],
|
|
anchor: dragAnchorRef.current,
|
|
mode: useAbsoluteCursorPlacement ? 'absolute' : 'relative',
|
|
})
|
|
dragAnchorRef.current = resolved.anchor
|
|
let [localX, localZ] = resolved.point
|
|
|
|
if (alignTopLevel) {
|
|
const aligned = alignLocalPoint(localX, localZ, event.nativeEvent?.altKey === true)
|
|
localX = aligned[0]
|
|
localZ = aligned[1]
|
|
}
|
|
|
|
if (
|
|
previousGridPosRef.current &&
|
|
(localX !== previousGridPosRef.current[0] || localZ !== previousGridPosRef.current[1])
|
|
) {
|
|
triggerSFX('sfx:grid-snap')
|
|
}
|
|
|
|
previousGridPosRef.current = [localX, localZ]
|
|
|
|
lastLocalPosition = [localX, movingNode.position[1], localZ]
|
|
const previewPosition = getPreviewPosition(lastLocalPosition)
|
|
setCursorWorldPos(
|
|
isFloorPlaced ? previewPosition : localPositionToToolLocal(lastLocalPosition),
|
|
)
|
|
|
|
// Directly update the Three.js mesh — no store update during drag
|
|
const mesh = sceneRegistry.nodes.get(movingNode.id)
|
|
if (mesh) {
|
|
if (isFloorPlaced) {
|
|
mesh.position.set(...previewPosition)
|
|
} else {
|
|
mesh.position.x = localX
|
|
mesh.position.z = localZ
|
|
}
|
|
}
|
|
|
|
// Publish canonical position so the 2D floorplan can track the drag.
|
|
// Floor-placed parents (stairs) stay in their committed local frame;
|
|
// the lifted Y remains presentation-only in the 3D view.
|
|
useLiveTransforms.getState().set(movingNode.id, {
|
|
position: lastLocalPosition,
|
|
rotation: pendingRotation,
|
|
})
|
|
}
|
|
|
|
const onGridClick = (event: GridEvent) => {
|
|
if (!hasMoved) return
|
|
const [localX, , localZ] = lastLocalPosition
|
|
|
|
useAlignmentGuides.getState().clear()
|
|
wasCommitted = true
|
|
|
|
let committedId = movingNode.id as AnyNodeId
|
|
if (isNew) {
|
|
committedId =
|
|
commitFreshPlacementSubtree(movingNode.id as AnyNodeId, {
|
|
position: [localX, movingNode.position[1], localZ],
|
|
rotation: pendingRotation,
|
|
metadata: committedMeta,
|
|
visible: true,
|
|
}) ?? committedId
|
|
} else {
|
|
// The store still holds the original values (we didn't update during drag).
|
|
// Resume temporal and apply the final state as a single undoable step.
|
|
useScene.temporal.getState().resume()
|
|
useScene.getState().updateNode(movingNode.id, {
|
|
position: [localX, movingNode.position[1], localZ],
|
|
rotation: pendingRotation,
|
|
metadata: committedMeta,
|
|
})
|
|
useScene.temporal.getState().pause()
|
|
}
|
|
|
|
triggerSFX('sfx:item-place')
|
|
useViewer.getState().setSelection({ selectedIds: [committedId] })
|
|
useLiveTransforms.getState().clear(movingNode.id)
|
|
useEditor.getState().setMovingNodeOrigin('3d')
|
|
exitMoveMode()
|
|
event.nativeEvent?.stopPropagation?.()
|
|
}
|
|
|
|
const onCancel = () => {
|
|
wasCancelled = true
|
|
useLiveTransforms.getState().clear(movingNode.id)
|
|
useAlignmentGuides.getState().clear()
|
|
if (isNew) {
|
|
useScene.getState().deleteNode(movingNode.id)
|
|
} else {
|
|
useScene.getState().updateNode(movingNode.id, {
|
|
position: original.position,
|
|
rotation: original.rotation,
|
|
metadata: original.metadata,
|
|
})
|
|
}
|
|
useScene.temporal.getState().resume()
|
|
exitMoveMode()
|
|
}
|
|
|
|
const onKeyDown = (event: KeyboardEvent) => {
|
|
if (event.target instanceof HTMLInputElement || event.target instanceof HTMLTextAreaElement) {
|
|
return
|
|
}
|
|
|
|
const ROTATION_STEP = Math.PI / 4
|
|
let rotationDelta = 0
|
|
if (event.key === 'r' || event.key === 'R') rotationDelta = ROTATION_STEP
|
|
else if (event.key === 't' || event.key === 'T') rotationDelta = -ROTATION_STEP
|
|
|
|
if (rotationDelta !== 0) {
|
|
event.preventDefault()
|
|
triggerSFX('sfx:item-rotate')
|
|
|
|
pendingRotation += rotationDelta
|
|
setPreviewRotation(pendingRotation)
|
|
|
|
// Directly update the Three.js mesh — no store update during drag
|
|
const mesh = sceneRegistry.nodes.get(movingNode.id)
|
|
if (mesh) {
|
|
mesh.rotation.y = pendingRotation
|
|
if (isFloorPlaced) {
|
|
const previewPosition = getPreviewPosition(lastLocalPosition, pendingRotation)
|
|
mesh.position.set(...previewPosition)
|
|
setCursorWorldPos(previewPosition)
|
|
}
|
|
}
|
|
|
|
// Update live transform rotation for 2D floorplan
|
|
const currentLive = useLiveTransforms.getState().get(movingNode.id)
|
|
if (currentLive) {
|
|
useLiveTransforms.getState().set(movingNode.id, {
|
|
...currentLive,
|
|
rotation: pendingRotation,
|
|
})
|
|
}
|
|
}
|
|
}
|
|
|
|
emitter.on('grid:move', onGridMove)
|
|
emitter.on('grid:click', onGridClick)
|
|
emitter.on('tool:cancel', onCancel)
|
|
window.addEventListener('keydown', onKeyDown)
|
|
|
|
return () => {
|
|
// Restore segment wrapper visibility (React will re-sync on next render)
|
|
if (segmentWrapperGroup) segmentWrapperGroup.visible = false
|
|
if (mergedRoofMesh) mergedRoofMesh.visible = true
|
|
|
|
// Clear ephemeral live transform + any alignment guides
|
|
useLiveTransforms.getState().clear(movingNode.id)
|
|
useAlignmentGuides.getState().clear()
|
|
|
|
// Skip restore when the 2D floor-plan overlay claimed teardown
|
|
// ownership — same contract `FloorplanRegistryMoveOverlay` uses to
|
|
// decide whether to revert its own apply() writes. Without this,
|
|
// a stair / roof move committed in the floor plan unmounts this
|
|
// tool with `wasCommitted === false` (this tool's own grid-click
|
|
// never fired), and the restore below stomps the just-committed
|
|
// position back to the snapshot.
|
|
const finalisedBy2D = useEditor.getState().movingNodeOrigin === '2d'
|
|
|
|
if (!(wasCommitted || wasCancelled || isNew || finalisedBy2D)) {
|
|
useScene.getState().updateNode(movingNode.id, {
|
|
position: original.position,
|
|
rotation: original.rotation,
|
|
metadata: original.metadata,
|
|
})
|
|
}
|
|
useScene.temporal.getState().resume()
|
|
emitter.off('grid:move', onGridMove)
|
|
emitter.off('grid:click', onGridClick)
|
|
emitter.off('tool:cancel', onCancel)
|
|
window.removeEventListener('keydown', onKeyDown)
|
|
}
|
|
}, [movingNode, exitMoveMode, isFreshPlacement, revealFreshPlacement, useAbsoluteCursorPlacement])
|
|
|
|
// Green footprint box during whole-stair / whole-roof moves. Skipped for
|
|
// segments — their cursor lives in parent-local space and the bounding box
|
|
// would render in the wrong frame.
|
|
const showBoundingBox = movingNode.type === 'stair' || movingNode.type === 'roof'
|
|
|
|
return (
|
|
<group visible={cursorVisible}>
|
|
<CursorSphere position={cursorWorldPos} showTooltip={false} />
|
|
{showBoundingBox && (
|
|
<DragBoundingBox
|
|
nodeId={movingNode.id}
|
|
position={cursorWorldPos}
|
|
rotationY={previewRotation}
|
|
/>
|
|
)}
|
|
</group>
|
|
)
|
|
}
|
|
|
|
export default MoveRoofTool
|