editor: building rotation, alt-click single wall, world-grid alignment, tap-to-engage move (#388)

* 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>
This commit is contained in:
Sudhir Yadav
2026-06-09 11:05:27 -04:00
committed by GitHub
co-authored by Claude Opus 4.7
parent b620c9d502
commit 555cf06c12
43 changed files with 948 additions and 295 deletions
@@ -1,27 +1,29 @@
'use client'
import { useAlignmentGuides } from '@pascal-app/editor'
import { useViewer } from '@pascal-app/viewer'
import { memo } from 'react'
import useAlignmentGuides from '../../store/use-alignment-guides'
import { formatMeasurement } from '../editor/measurement-pill'
import { useFloorplanRender } from './floorplan-render-context'
/**
* Figma-style alignment guides for the 2D floor plan.
*
* Subscribes to `useAlignmentGuides` — populated by
* `FloorplanRegistryMoveOverlay` (Path 2) during a generic free-translate
* drag. Each guide renders as a red line between the moving and matched
* candidate anchors with small `×` end-caps. A distance pill is drawn at
* the line's midpoint when the perpendicular gap is non-zero.
* Subscribes to the editor-local `useAlignmentGuides` store (separate
* from the core store the 3D layer reads). Guides come in
* building-local meters, so the layer is mounted INSIDE the rotated
* `<g data-floorplan-scene>` — the SVG transform that takes the rest
* of the floor-plan geometry from local → screen carries the guide
* lines too. Pill labels are counter-rotated by `sceneRotationDeg`
* (from `FloorplanRenderProvider`) so they stay upright even when the
* scene `<g>` is rotated by building rotation.
*
* Each guide renders as a red line between the moving and matched
* candidate anchors with small `×` end-caps. A distance pill is drawn
* at the midpoint when the perpendicular gap is non-zero.
*
* Stroke widths and handle radii are scaled by `unitsPerPixel` so they
* stay a constant size on screen no matter the zoom. Text labels are
* counter-rotated by `sceneRotationDeg` so they read upright even when
* the building rotation rotates the scene `<g>`.
*
* Mounted inside the `data-floorplan-scene` group so coordinates match
* world meters 1:1 with the rest of the floor plan.
* stay a constant size on screen no matter the zoom.
*/
export const FloorplanAlignmentGuideLayer = memo(function FloorplanAlignmentGuideLayer() {
const guides = useAlignmentGuides((s) => s.guides)
@@ -76,6 +76,10 @@ export const FloorplanCursorIndicatorOverlay = memo(function FloorplanCursorIndi
return { kind: 'icon', icon: 'mdi:trash-can-outline' }
}
if (mode === 'material-paint') {
return { kind: 'asset', iconSrc: '/icons/paint.png' }
}
return null
}, [activeFloorplanToolConfig, floorplanSelectionTool, mode, structureLayer])
@@ -16,13 +16,13 @@ import {
useLiveTransforms,
useScene,
} from '@pascal-app/core'
import { useAlignmentGuides } from '@pascal-app/editor'
import { useViewer } from '@pascal-app/viewer'
import { useEffect } from 'react'
import { commitFreshPlacementSubtree } from '../../lib/fresh-planar-placement'
import { isFreshPlacementMetadata, stripPlacementMetadataFlags } from '../../lib/placement-metadata'
import { resolvePlanarCursorPosition } from '../../lib/planar-cursor-placement'
import { sfxEmitter } from '../../lib/sfx-bus'
import useAlignmentGuides from '../../store/use-alignment-guides'
import useEditor from '../../store/use-editor'
import { useWallMoveGhosts } from '../../store/use-wall-move-ghosts'
@@ -464,6 +464,11 @@ export function FloorplanRegistryMoveOverlay() {
movingLocalBBox.x + movingLocalBBox.width + dxProposed,
movingLocalBBox.y + movingLocalBBox.height + dzProposed,
)
// Local-frame resolve (anchors come from the building-local
// SVG `getBBox()`). Guides land in the editor-local alignment
// store, which the 2D FloorplanAlignmentGuideLayer renders
// inside the rotated scene <g>. The 3D pipeline uses a
// separate store, so frames stay isolated per surface.
const result = resolveAlignment({
moving: movingAnchors,
candidates: candidateAnchors,
@@ -1596,6 +1596,34 @@ function InteractiveGeometry({
</g>
)
}
case 'text': {
if (!g.upright) return <FloorplanGeometryRenderer geometry={g} key={keyHint} />
// Counter-rotate by the scene rotation so the label reads
// horizontally on screen even when the floor-plan view is
// rotated (default `sceneRotationDeg` is 90°).
return (
<g key={keyHint} transform={`translate(${g.x} ${g.y}) rotate(${-sceneRotationDeg})`}>
<text
dominantBaseline={g.dominantBaseline ?? 'middle'}
fill={g.fill ?? '#171717'}
fontFamily={g.fontFamily}
fontSize={g.fontSize}
fontWeight={g.fontWeight}
opacity={g.opacity}
paintOrder={g.paintOrder}
stroke={g.stroke}
strokeLinecap={g.stroke ? 'round' : undefined}
strokeLinejoin={g.stroke ? 'round' : undefined}
strokeWidth={g.strokeWidth}
textAnchor={g.textAnchor ?? 'start'}
x={0}
y={0}
>
{g.text}
</text>
</g>
)
}
default:
return (
<FloorplanGeometryRenderer
@@ -6,7 +6,7 @@ import { useViewer } from '@pascal-app/viewer'
import { Html } from '@react-three/drei'
import { useFrame } from '@react-three/fiber'
import { memo, useMemo, useRef } from 'react'
import { BoxGeometry, CircleGeometry, type Group } from 'three'
import { BoxGeometry, CircleGeometry, type Group, Vector3 } from 'three'
import { MeshBasicNodeMaterial } from 'three/webgpu'
import { EDITOR_LAYER } from '../../lib/constants'
import { formatMeasurement } from './measurement-pill'
@@ -22,11 +22,13 @@ import { formatMeasurement } from './measurement-pill'
* the design reference — so they're real 3D geometry, not screen billboards.
* Only the distance pill is screen-space (`<Html>`).
*
* Guide coordinates are XZ meters in the building-local frame; this layer is
* mounted inside ToolManager's building-local group so they render at the
* right world position (and line up with the cursor). The whole ribbon is
* lifted to the active level's building-local Y each frame so it lies on the
* floor being edited — not the building base — when floors are stacked.
* Guide coordinates are XZ meters in the WORLD frame — alignment now resolves
* on the world axes (via `resolveAlignmentForActiveBuilding`) so the guides
* stay parallel to the visible world grid even when the active building is
* rotated. This layer is mounted OUTSIDE the building-local ToolManager group
* for the same reason. The whole ribbon is lifted to the active level's WORLD
* Y each frame so it lies on the floor being edited — not the building base —
* when floors are stacked.
*/
const LINE_COLOR = 0x81_8c_f8 // indigo-400 — matches the editor's selection accent (box-select / wall highlights)
@@ -58,16 +60,17 @@ export const Alignment3DGuideLayer = memo(function Alignment3DGuideLayer() {
const unit = useViewer((s) => s.unit)
const groupRef = useRef<Group>(null)
// Guides carry only XZ (building-local plan coords); their Y has to track
// the active level so the ground ribbon lies on the floor being edited,
// not the building base. Read the level mesh's building-local Y each frame
// — the same source `grid.tsx` uses, so the ribbon stays locked to the
// grid plane (and lerps with it during a level switch).
// Guides carry only XZ in WORLD coords; their Y has to track the active
// level's world Y so the ground ribbon lies on the floor being edited,
// not the building base. `getWorldPosition` walks the level mesh's
// parents (building / site) so it stays correct even if the building has
// a Y offset.
const worldYWork = useMemo(() => new Vector3(), [])
useFrame(() => {
const group = groupRef.current
if (!group) return
const levelMesh = levelId ? sceneRegistry.nodes.get(levelId) : null
group.position.y = levelMesh ? levelMesh.position.y : 0
group.position.y = levelMesh ? levelMesh.getWorldPosition(worldYWork).y : 0
})
if (guides.length === 0) return null
@@ -77,6 +77,7 @@ import { guideEmitter } from '../../lib/guide-events'
import { sfxEmitter } from '../../lib/sfx-bus'
import { SITE_BOUNDARY_DRAG_LABEL } from '../../lib/site-boundary'
import { cn } from '../../lib/utils'
import { snapBuildingLocalToWorldGrid } from '../../lib/world-grid-snap'
import type { GuideUiState, NavigationSyncPose } from '../../store/use-editor'
import useEditor, { selectSiteFloorplanContext } from '../../store/use-editor'
import { FloorplanAlignmentGuideLayer } from '../editor-2d/floorplan-alignment-guide-layer'
@@ -3243,20 +3244,20 @@ const FloorplanGridLayer = memo(function FloorplanGridLayer({
<path
d={minorGridPath}
fill="none"
opacity={palette.majorGridOpacity}
opacity={palette.minorGridOpacity}
shapeRendering="crispEdges"
stroke={palette.majorGrid}
strokeWidth={FLOORPLAN_MAJOR_GRID_STROKE_WIDTH}
stroke={palette.minorGrid}
strokeWidth={FLOORPLAN_MINOR_GRID_STROKE_WIDTH}
vectorEffect="non-scaling-stroke"
/>
<path
d={majorGridPath}
fill="none"
opacity={palette.minorGridOpacity}
opacity={palette.majorGridOpacity}
shapeRendering="crispEdges"
stroke={palette.minorGrid}
strokeWidth={FLOORPLAN_MINOR_GRID_STROKE_WIDTH}
stroke={palette.majorGrid}
strokeWidth={FLOORPLAN_MAJOR_GRID_STROKE_WIDTH}
vectorEffect="non-scaling-stroke"
/>
</>
@@ -8831,7 +8832,7 @@ export function FloorplanPanel() {
)
const handleWallPlacementPoint = useCallback(
(point: WallPlanPoint) => {
(point: WallPlanPoint, options?: { singleWall?: boolean }) => {
if (!draftStart) {
setDraftStart(point)
setDraftEnd(point)
@@ -8859,6 +8860,16 @@ export function FloorplanPanel() {
// clearing it (the previous behaviour caused the 2nd-segment
// draft to silently break after click 2).
const createdWall = createWallOnCurrentLevel(draftStart, point)
// Alt commits a single wall: drop the draft so the next click
// starts a fresh segment instead of chaining off this endpoint.
if (options?.singleWall) {
setDraftStart(null)
setDraftEnd(null)
setCursorPoint(null)
return
}
const nextStart: WallPlanPoint = createdWall
? [createdWall.end[0], createdWall.end[1]]
: point
@@ -8934,6 +8945,11 @@ export function FloorplanPanel() {
snapWallDraftPoint: snapWallDraftPointMagnetic,
toPoint2D,
walls,
// World-axis grid snap so drafts land on the visible grid even
// when the active building is rotated. The helper resolves the
// active building's pose internally; this hook stays oblivious to
// building rotation / position.
worldGridSnap: snapBuildingLocalToWorldGrid,
})
const handleBackgroundClick = useCallback(
+11 -29
View File
@@ -1,10 +1,10 @@
'use client'
import { type AnyNodeId, emitter, type GridEvent, sceneRegistry } from '@pascal-app/core'
import { emitter, type GridEvent, sceneRegistry } from '@pascal-app/core'
import { GRID_LAYER, getSceneTheme, useViewer } from '@pascal-app/viewer'
import { useFrame } from '@react-three/fiber'
import { useEffect, useMemo, useRef, useState } from 'react'
import { MathUtils, type Mesh, PlaneGeometry, Vector2, Vector3 } from 'three'
import { MathUtils, type Mesh, PlaneGeometry, Vector2 } from 'three'
import { color, float, fract, fwidth, mix, positionLocal, uniform } from 'three/tsl'
import { MeshBasicNodeMaterial } from 'three/webgpu'
import { useCeilingEvents } from '../../hooks/use-ceiling-events'
@@ -143,23 +143,11 @@ export const Grid = ({
}
}, [])
const worldPosScratch = useMemo(() => new Vector3(), [])
useFrame((_, delta) => {
const { levelId, buildingId } = useViewer.getState().selection
// Align the grid's XZ origin to the active building so its visible cell
// lines pass through building-local snap points (walls snap in
// building-local coords; a building placed at world (0.25, 0.25) would
// otherwise leave snapped wall endpoints stranded between grid lines).
let targetX = 0
let targetZ = 0
if (buildingId) {
const buildingMesh = sceneRegistry.nodes.get(buildingId as AnyNodeId)
if (buildingMesh) {
buildingMesh.getWorldPosition(worldPosScratch)
targetX = worldPosScratch.x
targetZ = worldPosScratch.z
}
}
const { levelId } = useViewer.getState().selection
// Grid stays anchored to world XZ (0, 0) — never chases the active
// building. The Y origin still lerps to the active level so the grid
// sits at floor height when a level is open.
let targetY = 0
if (levelId) {
const levelMesh = sceneRegistry.nodes.get(levelId)
@@ -167,22 +155,16 @@ export const Grid = ({
targetY = levelMesh.position.y
}
}
const t = 12 * delta
gridRef.current.position.x = MathUtils.lerp(gridRef.current.position.x, targetX, t)
gridRef.current.position.z = MathUtils.lerp(gridRef.current.position.z, targetZ, t)
const newY = MathUtils.lerp(gridRef.current.position.y, targetY, t)
const newY = MathUtils.lerp(gridRef.current.position.y, targetY, 12 * delta)
gridRef.current.position.y = newY
setGridY(newY)
// Re-derive the local-frame cursor uniform after the grid's XZ has
// lerped this frame, so the reveal ring stays locked under the world
// cursor even when the grid origin is mid-transition.
// Grid XZ is fixed at world origin, so the local-frame cursor uniform
// is just the world cursor (mirrored on Z to match the -π/2 X-rotation
// of the plane).
const world = lastWorldCursorRef.current
if (world) {
cursorPositionRef.current.set(
world.x - gridRef.current.position.x,
-(world.z - gridRef.current.position.z),
)
cursorPositionRef.current.set(world.x, -world.z)
}
})
+37 -61
View File
@@ -8,15 +8,7 @@ import {
useScene,
} from '@pascal-app/core'
import { type HoverStyles, InteractiveSystem, useViewer, Viewer } from '@pascal-app/viewer'
import {
memo,
type ReactNode,
useCallback,
useEffect,
useLayoutEffect,
useRef,
useState,
} from 'react'
import { memo, type ReactNode, useCallback, useEffect, useRef, useState } from 'react'
import { ViewerOverlay } from '../../components/viewer-overlay'
import { ViewerZoneSystem } from '../../components/viewer-zone-system'
import { type SaveStatus, useAutoSave } from '../../hooks/use-auto-save'
@@ -76,7 +68,7 @@ const CAMERA_CONTROLS_HINT_DISMISSED_STORAGE_KEY = 'editor-camera-controls-hint-
const DELETE_CURSOR_BADGE_COLOR = '#ef4444'
const DELETE_CURSOR_BADGE_OFFSET_X = 14
const DELETE_CURSOR_BADGE_OFFSET_Y = 14
const PAINT_CURSOR_BADGE_COLOR = '#f59e0b'
const PAINT_CURSOR_BADGE_COLOR = '#818cf8'
const PAINT_CURSOR_BADGE_DISABLED_COLOR = '#94a3b8'
const PAINT_CURSOR_BADGE_OFFSET_X = 14
const PAINT_CURSOR_BADGE_OFFSET_Y = 14
@@ -536,43 +528,46 @@ function DeleteCursorBadge({ position }: { position: { x: number; y: number } })
function PaintCursorBadge({
position,
label,
disabled,
icon,
}: {
position: { x: number; y: number }
label: string
disabled: boolean
icon: string
}) {
const accentColor = disabled ? PAINT_CURSOR_BADGE_DISABLED_COLOR : PAINT_CURSOR_BADGE_COLOR
const lineHeight = 18
return (
<div
aria-hidden="true"
className="pointer-events-none absolute z-40"
style={{
left: position.x + PAINT_CURSOR_BADGE_OFFSET_X,
top: position.y + PAINT_CURSOR_BADGE_OFFSET_Y,
left: position.x,
top: position.y,
}}
>
<div
className="flex items-center gap-2 rounded-xl border border-white/5 bg-zinc-900/95 px-3 py-2 shadow-[0_8px_16px_-4px_rgba(0,0,0,0.3),0_4px_8px_-4px_rgba(0,0,0,0.2)]"
className="-translate-x-1/2 -translate-y-full absolute top-0 left-1/2"
style={{
backgroundColor: accentColor,
boxShadow: `0 0 12px ${accentColor}cc`,
height: lineHeight,
width: 2,
}}
/>
<div
className="absolute top-0 left-1/2 flex h-8 w-8 items-center justify-center rounded-xl border border-white/5 bg-zinc-900/95 shadow-[0_8px_16px_-4px_rgba(0,0,0,0.3),0_4px_8px_-4px_rgba(0,0,0,0.2)]"
style={{
boxShadow: `0 8px 16px -4px rgba(0,0,0,0.3), 0 4px 8px -4px rgba(0,0,0,0.2), 0 0 18px ${accentColor}22`,
transform: `translate(-50%, calc(-100% - ${lineHeight}px))`,
}}
>
<Icon
{/* eslint-disable-next-line @next/next/no-img-element */}
<img
alt=""
aria-hidden="true"
className="drop-shadow-[0_2px_4px_rgba(0,0,0,0.5)]"
color={accentColor}
height={16}
icon={icon}
width={16}
className="h-5 w-5 object-contain drop-shadow-[0_2px_4px_rgba(0,0,0,0.5)]"
src="/icons/paint.png"
/>
<span className="font-medium text-[11px]" style={{ color: accentColor }}>
{label}
</span>
</div>
</div>
)
@@ -702,7 +697,7 @@ function DeleteCursorLayer({
return (
<div
className="pointer-events-none"
className="pointer-events-none z-40"
ref={badgeRef}
style={{ display: 'none', position: 'absolute', left: 0, top: 0 }}
>
@@ -720,15 +715,12 @@ function PaintCursorLayer({
}) {
const mode = useEditor((s) => s.mode)
const activePaintMaterial = useEditor((s) => s.activePaintMaterial)
const activePaintTarget = useEditor((s) => s.activePaintTarget)
const badgeRef = useRef<HTMLDivElement>(null)
const [position, setPosition] = useState<{ x: number; y: number } | null>(null)
const active = mode === 'material-paint' && !isVersionPreviewMode
useEffect(() => {
if (!active) {
if (badgeRef.current) {
badgeRef.current.style.display = 'none'
}
setPosition(null)
return
}
const el = containerRef.current
@@ -736,20 +728,16 @@ function PaintCursorLayer({
let frame = 0
let nextX = 0
let nextY = 0
const badge = badgeRef.current
const flushPosition = () => {
frame = 0
if (!badge) return
badge.style.display = 'block'
badge.style.transform = `translate(${nextX + PAINT_CURSOR_BADGE_OFFSET_X}px, ${nextY + PAINT_CURSOR_BADGE_OFFSET_Y}px)`
setPosition({ x: nextX, y: nextY })
}
const onMove = (e: PointerEvent) => {
const updateFromEvent = (e: PointerEvent) => {
const rect = el.getBoundingClientRect()
nextX = e.clientX - rect.left
nextY = e.clientY - rect.top
if (frame === 0) {
frame = window.requestAnimationFrame(flushPosition)
}
@@ -759,17 +747,19 @@ function PaintCursorLayer({
window.cancelAnimationFrame(frame)
frame = 0
}
if (badge) {
badge.style.display = 'none'
}
setPosition(null)
}
el.addEventListener('pointermove', onMove)
el.addEventListener('pointermove', updateFromEvent)
el.addEventListener('pointerenter', updateFromEvent)
el.addEventListener('pointerdown', updateFromEvent)
el.addEventListener('pointerleave', onLeave)
return () => {
if (frame !== 0) {
window.cancelAnimationFrame(frame)
}
el.removeEventListener('pointermove', onMove)
el.removeEventListener('pointermove', updateFromEvent)
el.removeEventListener('pointerenter', updateFromEvent)
el.removeEventListener('pointerdown', updateFromEvent)
el.removeEventListener('pointerleave', onLeave)
}
}, [active, containerRef])
@@ -779,29 +769,15 @@ function PaintCursorLayer({
(activePaintMaterial.material !== undefined ||
activePaintMaterial.materialPreset !== undefined),
)
const label = hasMaterial ? `Paint ${activePaintTarget}` : 'Choose material'
const icon = 'mdi:format-color-fill'
useLayoutEffect(() => {
if (!active && badgeRef.current) {
badgeRef.current.style.display = 'none'
}
}, [active])
if (!active) return null
if (!active || !position) return null
return (
<div
className="pointer-events-none"
ref={badgeRef}
style={{ display: 'none', position: 'absolute', left: 0, top: 0 }}
className="pointer-events-none absolute z-40"
style={{ left: 0, top: 0, transform: `translate(${position.x}px, ${position.y}px)` }}
>
<PaintCursorBadge
disabled={!hasMaterial}
icon={icon}
label={label}
position={{ x: 0, y: 0 }}
/>
<PaintCursorBadge disabled={!hasMaterial} position={{ x: 0, y: 0 }} />
</div>
)
}
@@ -41,8 +41,8 @@ import { mergeGeometries } from 'three/examples/jsm/utils/BufferGeometryUtils.js
import { MeshBasicNodeMaterial } from 'three/webgpu'
import { EDITOR_LAYER } from '../../lib/constants'
import { createEditorApi } from '../../lib/editor-api'
import { sfxEmitter } from '../../lib/sfx-bus'
import useEditor from '../../store/use-editor'
import { snapToGrid } from '../tools/item/placement-math'
import { formatAngleRadians } from '../tools/shared/segment-angle'
import {
ARROW_COLOR,
@@ -1143,9 +1143,6 @@ function ArcArrow({
function TranslateArrow({
descriptor,
node,
handleIndex,
dragControls,
rideObject,
}: {
descriptor: TranslateHandle<AnyNode>
node: AnyNode
@@ -1154,7 +1151,6 @@ function TranslateArrow({
rideObject: Object3D
}) {
const [isHovered, setIsHovered] = useState(false)
const [isDragging, setIsDragging] = useState(false)
const { camera } = useThree()
const zoom = camera instanceof OrthographicCamera ? 1 / camera.zoom : 1
const baseScale = zoom * ARROW_SCALE
@@ -1166,67 +1162,17 @@ function TranslateArrow({
// local +Z). Its cross icon stands up into that plane (tilt about X).
const isWallPlane = descriptor.plane === 'node-normal'
const activate = useHandleDrag({
kind: 'drag',
cursor,
dragControls,
handleIndex,
node,
rideObject,
setIsDragging,
onStart: ({ event, initialNode, intersectPlane, rideObject: dragRideObject, sceneApi }) => {
const worldOrigin = new Vector3().setFromMatrixPosition(dragRideObject.matrixWorld)
const planeNormal = isWallPlane
? new Vector3().setFromMatrixColumn(dragRideObject.matrixWorld, 2).normalize()
: new Vector3(0, 1, 0)
const plane = new Plane().setFromNormalAndCoplanarPoint(planeNormal, worldOrigin)
const parent = dragRideObject.parent
const parentInverse = new Matrix4()
if (parent) {
parent.updateMatrixWorld()
parentInverse.copy(parent.matrixWorld).invert()
}
const hitWorld = new Vector3()
if (!intersectPlane(event.nativeEvent.clientX, event.nativeEvent.clientY, plane, hitWorld)) {
return null
}
const startLocal = hitWorld.clone().applyMatrix4(parentInverse)
const initialPos = (initialNode as { position?: readonly [number, number, number] })
.position ?? [0, 0, 0]
return {
markDirty: false,
move: ({ event: moveEvent, intersectPlane: intersectMovePlane }) => {
const hit = new Vector3()
if (!intersectMovePlane(moveEvent.clientX, moveEvent.clientY, plane, hit)) return null
const curLocal = hit.applyMatrix4(parentInverse)
const newPos: [number, number, number] = [initialPos[0], initialPos[1], initialPos[2]]
newPos[0] += curLocal.x - startLocal.x
if (isWallPlane) {
newPos[1] += curLocal.y - startLocal.y
} else {
newPos[2] += curLocal.z - startLocal.z
}
const extents = descriptor.snapExtents?.(initialNode as never, sceneApi)
if (extents) {
newPos[0] = snapToGrid(newPos[0], extents[0])
if (isWallPlane) {
newPos[1] = snapToGrid(newPos[1], extents[1])
} else {
newPos[2] = snapToGrid(newPos[2], extents[1])
}
}
return descriptor.apply(initialNode as never, newPos, sceneApi) as Partial<AnyNode>
},
}
},
})
// Suppress the unused `isDragging` lint — it only drives the React re-render
// that keeps hover/drag cursor state in sync.
void isDragging
// Same function as the floating action menu's Move button
// (`floating-action-menu.tsx` → `handleMove`): arm the registry move tool,
// which owns the cursor follow, grid + alignment snap, green guide overlay,
// and click-to-commit. Routes both entry points through one path so the
// 3D translate gizmo and the floating Move button behave identically.
const activate = (event: ThreeEvent<PointerEvent>) => {
event.stopPropagation()
sfxEmitter.emit('sfx:item-pick')
useEditor.getState().setMovingNode(node as never)
useViewer.getState().setSelection({ selectedIds: [] })
}
// The cross is built flat in the XZ plane. On a wall, tilt it up about X so
// it lies in the item-local XY plane (= the wall face).
@@ -5,7 +5,6 @@ import { type MouseEvent as ReactMouseEvent, useCallback } from 'react'
import { alignFloorplanDraftPoint, getPlanPointDistance } from '../../lib/floorplan'
import { snapFenceDraftPoint } from '../tools/fence/fence-drafting'
import {
snapPointToGrid as snapWallPointToGrid,
WALL_FINE_GRID_STEP,
WALL_GRID_STEP,
type WallPlanPoint,
@@ -41,7 +40,7 @@ type UseFloorplanBackgroundPlacementArgs = {
) => boolean
handleCeilingPlacementPoint: (point: WallPlanPoint) => void
handleSlabPlacementPoint: (point: WallPlanPoint) => void
handleWallPlacementPoint: (point: WallPlanPoint) => void
handleWallPlacementPoint: (point: WallPlanPoint, options?: { singleWall?: boolean }) => void
handleZonePlacementPoint: (point: WallPlanPoint) => void
isCeilingBuildActive: boolean
isCeilingItemPlacementActive: boolean
@@ -65,6 +64,7 @@ type UseFloorplanBackgroundPlacementArgs = {
start?: WallPlanPoint
angleSnap?: boolean
step?: number
gridSnap?: (point: WallPlanPoint) => WallPlanPoint
}) => WallPlanPoint
snapPolygonDraftPoint: (args: {
point: WallPlanPoint
@@ -73,6 +73,13 @@ type UseFloorplanBackgroundPlacementArgs = {
}) => WallPlanPoint
toPoint2D: (point: WallPlanPoint) => { x: number; y: number }
walls: WallNode[]
/**
* Snap a building-local plan point to the world XZ grid at `step`.
* Injected so the hook doesn't have to know the building's rotation
* or position — used by wall / fence branches that snap at variable
* step (Shift = fine).
*/
worldGridSnap: (point: WallPlanPoint, step: number) => WallPlanPoint
}
export function useFloorplanBackgroundPlacement({
@@ -111,6 +118,7 @@ export function useFloorplanBackgroundPlacement({
snapPolygonDraftPoint,
toPoint2D,
walls,
worldGridSnap,
}: UseFloorplanBackgroundPlacementArgs) {
const handleBackgroundPlacementClick = useCallback(
(
@@ -177,16 +185,17 @@ export function useFloorplanBackgroundPlacement({
if (isFenceBuildActive) {
// Fence draft: grid snap (+ existing-wall/fence endpoint snap), then
// Figma alignment — endpoint snap wins (same precedence as move).
// `gridSnap` keeps the snap on the world XZ grid even when the
// building is rotated.
const fenceStep = shiftPressed ? WALL_FINE_GRID_STEP : WALL_GRID_STEP
const fenceSnapped = snapFenceDraftPoint({
point: planPoint,
walls,
fences,
step: shiftPressed ? WALL_FINE_GRID_STEP : undefined,
gridSnap: (p) => worldGridSnap(p, fenceStep),
})
const fenceGridBase = snapWallPointToGrid(
planPoint,
shiftPressed ? WALL_FINE_GRID_STEP : WALL_GRID_STEP,
)
const fenceGridBase = worldGridSnap(planPoint, fenceStep)
const fenceLocked =
fenceSnapped[0] !== fenceGridBase[0] || fenceSnapped[1] !== fenceGridBase[1]
const snappedPoint = fenceLocked
@@ -249,22 +258,23 @@ export function useFloorplanBackgroundPlacement({
// Wall draft: grid snap (+ existing-wall endpoint/join snap), then
// Figma alignment — endpoint/join snap wins (same precedence as the
// move-preview branch), so committing onto a corner still works.
// `gridSnap` keeps the snap on the world XZ grid even when the
// building is rotated.
const wallStep = shiftPressed ? WALL_FINE_GRID_STEP : WALL_GRID_STEP
const wallSnapped = snapWallDraftPoint({
point: planPoint,
walls,
step: shiftPressed ? WALL_FINE_GRID_STEP : undefined,
gridSnap: (p) => worldGridSnap(p, wallStep),
})
const wallGridBase = snapWallPointToGrid(
planPoint,
shiftPressed ? WALL_FINE_GRID_STEP : WALL_GRID_STEP,
)
const wallGridBase = worldGridSnap(planPoint, wallStep)
const wallLocked = wallSnapped[0] !== wallGridBase[0] || wallSnapped[1] !== wallGridBase[1]
const snappedPoint = wallLocked
? wallSnapped
: alignFloorplanDraftPoint(wallSnapped, { bypass: event.altKey })
: alignFloorplanDraftPoint(wallSnapped, { bypass: false })
emitFloorplanGridEvent('click', snappedPoint, event)
handleWallPlacementPoint(snappedPoint)
handleWallPlacementPoint(snappedPoint, { singleWall: event.altKey })
return true
}
@@ -324,6 +334,7 @@ export function useFloorplanBackgroundPlacement({
toPoint2D,
walls,
handleWallPlacementPoint,
worldGridSnap,
],
)
@@ -181,6 +181,7 @@ export function useFloorplanSceneData({
return {
buildingPosition,
committedBuildingPosition,
buildingRotationY,
currentBuildingId,
ceilings,
@@ -134,14 +134,23 @@ export function snapFenceDraftPoint(args: {
ignoreFenceIds?: string[]
/** Override the grid step (e.g. `WALL_FINE_GRID_STEP` for precision mode). */
step?: number
/**
* Optional grid-snap function. When provided, replaces the default
* local-axis snap — lets the 2D floor-plan keep snapping to the
* world XZ grid even when the building is rotated. Wall / fence
* endpoint snap precedence is preserved.
*/
gridSnap?: (point: FencePlanPoint) => FencePlanPoint
}): FencePlanPoint {
const { point, walls, fences, start, angleSnap = false, ignoreFenceIds, step } = args
const { point, walls, fences, start, angleSnap = false, ignoreFenceIds, step, gridSnap } = args
const gridStep = step ?? getSegmentGridStep()
const angleStep = getWallAngleSnapStep(gridStep)
const basePoint =
start && angleSnap
? snapPointTo45Degrees(start, point, gridStep, angleStep)
: snapPointToGrid(point, gridStep)
? snapPointTo45Degrees(start, point, gridStep, angleStep, gridSnap)
: gridSnap
? gridSnap(point)
: snapPointToGrid(point, gridStep)
const fenceSnapTarget = findFenceSnapTarget(basePoint, fences, ignoreFenceIds)
return fenceSnapTarget ?? findWallSnapTarget(basePoint, walls) ?? basePoint
@@ -19,6 +19,7 @@ import {
useScene,
} from '@pascal-app/core'
import { Euler, Matrix3, Quaternion, Vector3 } from 'three'
import { snapWorldXZForActiveBuilding } from '../../../lib/world-grid-snap'
import {
calculateCursorRotation,
calculateItemRotation,
@@ -99,10 +100,15 @@ export const floorStrategy = {
const [dimX, , dimZ] = dims
const rotY = ctx.draftItem?.rotation?.[1] ?? 0
const swapDims = Math.abs(Math.sin(rotY)) > 0.9
// event.localPosition is building-local; the coordinator cursor group is inside the
// building-local ToolManager group, so local coords are correct for both data and visuals.
const x = snapToGrid(event.localPosition[0], swapDims ? dimZ : dimX)
const z = snapToGrid(event.localPosition[2], swapDims ? dimX : dimZ)
// Snap on the world XZ grid (the grid the editor renders) so the
// item edges land on the visible grid even when the active building
// is rotated; then project the world point back into building-local
// for storage. Without this, a rotated building drags placement off
// the world grid.
const snappedWorldX = snapToGrid(event.position[0], swapDims ? dimZ : dimX)
const snappedWorldZ = snapToGrid(event.position[2], swapDims ? dimX : dimZ)
const { local } = snapWorldXZForActiveBuilding(snappedWorldX, snappedWorldZ, 0)
const [x, z] = local
const y = ctx.gridPosition.y
return {
@@ -10,7 +10,6 @@ import {
getScaledDimensions,
type ItemEvent,
movingFootprintAnchors,
resolveAlignment,
resolveLevelId,
type ShelfEvent,
sceneRegistry,
@@ -42,6 +41,7 @@ import { distance, smoothstep, uv, vec2 } from 'three/tsl'
import { LineBasicNodeMaterial, MeshBasicNodeMaterial } from 'three/webgpu'
import { EDITOR_LAYER } from '../../../lib/constants'
import { sfxEmitter } from '../../../lib/sfx-bus'
import { resolveAlignmentForActiveBuilding } from '../../../lib/world-grid-snap'
import useEditor from '../../../store/use-editor'
import { getFloorStackPreviewPosition } from '../shared/floor-stack-preview'
import {
@@ -700,7 +700,7 @@ export function usePlacementCoordinator(config: PlacementCoordinatorConfig): Rea
draft.id,
useViewer.getState().selection.levelId,
)
const ar = resolveAlignment({
const ar = resolveAlignmentForActiveBuilding({
moving: movingFootprintAnchors(
draft as unknown as AnyNode,
result.gridPosition[0],
@@ -28,6 +28,7 @@ import { resolvePlanarCursorPosition } from '../../../lib/planar-cursor-placemen
import { sfxEmitter } from '../../../lib/sfx-bus'
import useEditor from '../../../store/use-editor'
import { CursorSphere } from '../shared/cursor-sphere'
import { DragBoundingBox } from '../shared/drag-bounding-box'
import { getFloorStackPreviewPosition } from '../shared/floor-stack-preview'
import { useFreshPlacementVisibility } from '../shared/fresh-placement-visibility'
import { PlacementBox } from '../shared/placement-box'
@@ -561,6 +562,18 @@ export function MoveRegistryNodeTool({ node }: { node: AnyNode }) {
useAbsoluteCursorPlacement,
])
// Snapshot the scene once at drag-start — bounds depend on `node` (locked
// for the lifetime of this tool) and any sibling state the kind reads. If a
// future kind needs live sibling state mid-drag, switch to a subscribed
// selector; for v1 (elevator shaft height from level set) start-time is
// correct and avoids subscribing the whole `nodes` map.
const dragBounds = useMemo(
() =>
nodeRegistry.get(node.type)?.capabilities?.dragBounds?.(node, useScene.getState().nodes) ??
null,
[node],
)
if (!previewVisible) return null
if (boxDimensions) {
@@ -574,5 +587,16 @@ export function MoveRegistryNodeTool({ node }: { node: AnyNode }) {
)
}
return <CursorSphere color="#a78bfa" height={2.5} position={cursorPosition} />
return (
<>
<CursorSphere color="#a78bfa" height={2.5} position={cursorPosition} />
<DragBoundingBox
centerY={dragBounds?.centerY}
nodeId={node.id}
position={cursorPosition}
rotationY={cursorRotationY}
size={dragBounds?.size}
/>
</>
)
}
@@ -7,7 +7,6 @@ import {
type LevelNode,
RoofNode,
RoofSegmentNode,
resolveAlignment,
sceneRegistry,
snapScalar,
useScene,
@@ -20,6 +19,10 @@ import { BufferGeometry, DoubleSide, type Group, type Line, Vector3 } from 'thre
import { markToolCancelConsumed } from '../../../hooks/use-keyboard'
import { EDITOR_LAYER } from '../../../lib/constants'
import { sfxEmitter } from '../../../lib/sfx-bus'
import {
resolveAlignmentForActiveBuilding,
snapWorldXZForActiveBuilding,
} from '../../../lib/world-grid-snap'
import useEditor from '../../../store/use-editor'
import { CursorSphere } from '../shared/cursor-sphere'
@@ -196,7 +199,7 @@ export const RoofTool: React.FC = () => {
useAlignmentGuides.getState().clear()
return [gridX, gridZ]
}
const ar = resolveAlignment({
const ar = resolveAlignmentForActiveBuilding({
moving: [{ nodeId: '__roof-draft__', kind: 'corner', x: rawX, z: rawZ }],
candidates: alignmentCandidates,
threshold: ALIGNMENT_THRESHOLD_M,
@@ -237,9 +240,16 @@ export const RoofTool: React.FC = () => {
const onGridMove = (event: GridEvent) => {
if (!cursorRef.current) return
// World-grid snap projected into building-local; rotated buildings
// used to drag every roof corner off the visible grid.
const snapped = snapWorldXZForActiveBuilding(
event.position[0],
event.position[2],
useEditor.getState().gridSnapStep,
).local
const [gridX, gridZ] = alignPoint(
snapToActiveGrid(event.localPosition[0]),
snapToActiveGrid(event.localPosition[2]),
snapped[0],
snapped[1],
event.localPosition[0],
event.localPosition[2],
event.nativeEvent?.altKey === true,
@@ -275,9 +285,16 @@ export const RoofTool: React.FC = () => {
const onGridClick = (event: GridEvent) => {
if (!currentLevelId) return
// World-grid snap projected into building-local; rotated buildings
// used to drag every roof corner off the visible grid.
const snapped = snapWorldXZForActiveBuilding(
event.position[0],
event.position[2],
useEditor.getState().gridSnapStep,
).local
const [gridX, gridZ] = alignPoint(
snapToActiveGrid(event.localPosition[0]),
snapToActiveGrid(event.localPosition[2]),
snapped[0],
snapped[1],
event.localPosition[0],
event.localPosition[2],
event.nativeEvent?.altKey === true,
@@ -64,6 +64,15 @@ interface DragBoundingBoxProps {
rotationY?: number
/** Declared `[width, height, depth]`, used until/if the mesh can't be measured. */
fallbackSize?: [number, number, number]
/**
* Hard override for the box extents — wins over both mesh measurement and
* `fallbackSize`. Use when the rendered mesh contains extras the user
* wouldn't read as "the thing being dragged" (e.g. an elevator whose mesh
* includes per-level landings outside the shaft footprint).
*/
size?: [number, number, number]
/** Y center of the box in the node's local frame. Defaults to `size[1] / 2`. */
centerY?: number
color?: number
}
@@ -80,15 +89,20 @@ export function DragBoundingBox({
position,
rotationY = 0,
fallbackSize = [0, 0, 0],
size,
centerY,
color = DEFAULT_COLOR,
}: DragBoundingBoxProps) {
const measured = useMemo(() => {
if (size) return null
const obj = sceneRegistry.nodes.get(nodeId)
return obj ? measureLocalBounds(obj) : null
}, [nodeId])
}, [nodeId, size])
const [w, h, d] = measured?.size ?? fallbackSize
const [cx, cy, cz] = measured?.center ?? [0, fallbackSize[1] / 2, 0]
const [w, h, d] = size ?? measured?.size ?? fallbackSize
const [cx, cy, cz] = size
? [0, centerY ?? size[1] / 2, 0]
: (measured?.center ?? [0, fallbackSize[1] / 2, 0])
const minY = cy - h / 2
const edgeGeometry = useMemo(() => {
@@ -68,17 +68,24 @@ export function snapPointTo45Degrees(
cursor: WallPlanPoint,
step = WALL_GRID_STEP,
angleStep = DEFAULT_WALL_ANGLE_SNAP_STEP,
/**
* Optional grid-snap callback. Lets the caller route the final
* snap through a world-XZ grid (or any other axis system) instead
* of the local-axis grid `snapPointToGrid` uses. When omitted,
* falls back to the local-axis snap at `step`.
*/
gridSnap?: (point: WallPlanPoint) => WallPlanPoint,
): WallPlanPoint {
const dx = cursor[0] - start[0]
const dz = cursor[1] - start[1]
const angle = Math.atan2(dz, dx)
const snappedAngle = Math.round(angle / angleStep) * angleStep
const distance = Math.sqrt(dx * dx + dz * dz)
return snapPointToGrid(
[start[0] + Math.cos(snappedAngle) * distance, start[1] + Math.sin(snappedAngle) * distance],
step,
)
const point: WallPlanPoint = [
start[0] + Math.cos(snappedAngle) * distance,
start[1] + Math.sin(snappedAngle) * distance,
]
return gridSnap ? gridSnap(point) : snapPointToGrid(point, step)
}
export function getWallAngleSnapStep(step = getSegmentGridStep()): number {
@@ -331,6 +338,13 @@ type SnapWallDraftArgs = {
* keep the prior behaviour.
*/
magnetic?: boolean
/**
* Optional grid-snap override. Lets the caller route grid snapping
* through a world-XZ aligned snap (so a rotated building's draft
* lands on the visible grid). When omitted, falls back to the
* local-axis grid at `step`.
*/
gridSnap?: (point: WallPlanPoint) => WallPlanPoint
}
export function snapWallDraftPointDetailed(args: SnapWallDraftArgs): WallDraftSnapResult {
@@ -342,6 +356,7 @@ export function snapWallDraftPointDetailed(args: SnapWallDraftArgs): WallDraftSn
ignoreWallIds,
step: overrideStep,
magnetic = true,
gridSnap,
} = args
// Discrete special points (corner / midpoint / crossing) are taken from the
@@ -356,8 +371,10 @@ export function snapWallDraftPointDetailed(args: SnapWallDraftArgs): WallDraftSn
const angleStep = getWallAngleSnapStep(step)
const basePoint =
start && angleSnap
? snapPointTo45Degrees(start, point, step, angleStep)
: snapPointToGrid(point, step)
? snapPointTo45Degrees(start, point, step, angleStep, gridSnap)
: gridSnap
? gridSnap(point)
: snapPointToGrid(point, step)
if (magnetic) {
const wallSnap = findWallSnapTarget(basePoint, walls, { ignoreWallIds })
@@ -4,6 +4,7 @@ import { useEffect, useMemo, useRef, useState } from 'react'
import { BufferGeometry, DoubleSide, type Group, type Line, Shape, Vector3 } from 'three'
import { EDITOR_LAYER } from './../../../lib/constants'
import { sfxEmitter } from './../../../lib/sfx-bus'
import { snapWorldXZForActiveBuilding } from './../../../lib/world-grid-snap'
import useEditor from './../../../store/use-editor'
import { CursorSphere } from '../shared/cursor-sphere'
@@ -178,9 +179,13 @@ export const ZoneTool: React.FC = () => {
const onGridMove = (event: GridEvent) => {
if (!cursorRef.current) return
// Snap to 0.5 grid
const gridX = Math.round(event.localPosition[0] * 2) / 2
const gridZ = Math.round(event.localPosition[2] * 2) / 2
// World-grid snap projected into building-local; rotated buildings
// used to pull the snap off the visible grid lines.
const [gridX, gridZ] = snapWorldXZForActiveBuilding(
event.position[0],
event.position[2],
0.5,
).local
cursorPosition = [gridX, gridZ]
levelYRef.current = event.localPosition[1]
@@ -209,8 +214,11 @@ export const ZoneTool: React.FC = () => {
const onGridClick = (event: GridEvent) => {
if (!currentLevelId) return
const gridX = Math.round(event.localPosition[0] * 2) / 2
const gridZ = Math.round(event.localPosition[2] * 2) / 2
const [gridX, gridZ] = snapWorldXZForActiveBuilding(
event.position[0],
event.position[2],
0.5,
).local
let clickPoint: [number, number] = [gridX, gridZ]
// Snap to axis from last point
+7
View File
@@ -104,6 +104,7 @@ export {
snapWallDraftPoint,
snapWallDraftPointDetailed,
WALL_FINE_GRID_STEP,
WALL_GRID_STEP,
type WallDraftSnapKind,
type WallDraftSnapResult,
type WallPlanPoint,
@@ -237,6 +238,12 @@ export {
// nodes` so they don't need their own copy / their own tailwind-merge
// dependency.
export { cn } from './lib/utils'
export {
getActiveBuildingPose,
resolveAlignmentForActiveBuilding,
snapBuildingLocalToWorldGrid,
snapWorldXZForActiveBuilding,
} from './lib/world-grid-snap'
export { default as useAlignmentGuides } from './store/use-alignment-guides'
export { default as useAudio } from './store/use-audio'
export { type CommandAction, useCommandRegistry } from './store/use-command-registry'
+199
View File
@@ -0,0 +1,199 @@
/**
* World-grid snap for tools that consume `grid:move` / `grid:click`.
*
* Tools historically snapped on `event.localPosition` (the cursor in the
* active building's local frame). After the floor-plan grid was pulled
* out of the rotated scene group, snapping has to follow the WORLD XZ
* grid — otherwise a rotated building drags every placement off the
* visible grid lines. This helper resolves the active building's pose
* and projects the world snap back into local coords for storage.
*/
import {
type AlignmentAnchor,
type AnyNodeId,
type BuildingPose,
type ResolveAlignmentInBuildingResult,
resolveAlignmentInBuildingWorld,
snapWorldXZToBuildingLocal,
useLiveTransforms,
useScene,
} from '@pascal-app/core'
import { useViewer } from '@pascal-app/viewer'
/**
* Look up the active building's pose, or null when we're at the site root.
* Used by tools that need to resolve alignment in world coords.
*
* Falls back through the active level's `parentId` because the 2D floor-plan
* often runs with `selection.buildingId === null` while still operating
* inside a specific building (the user is editing a level, not the building
* shell itself). Without the fallback, alignment in the floor plan saw a
* `buildingRotY === 0` pose and emitted world-axis guides — which appeared
* diagonal once the building was rotated.
*
* Honours `useLiveTransforms` overrides: while the building is being moved
* or rotated, the floor-plan scene <g> is driven by the live transform
* (see `use-floorplan-scene-data.ts`), so alignment has to read the same
* pose or the rotated anchors fall out of sync with the SVG transform and
* guides drift off the visible grid mid-drag (and through any post-drag
* frame where the live override is still set).
*/
export function getActiveBuildingPose(): BuildingPose | null {
const sel = useViewer.getState().selection
const nodes = useScene.getState().nodes
// Match `use-floorplan-scene-data.ts`: prefer the active level's
// owning building, fall back to selection.buildingId. If the user
// has a stale building selected from another scope while editing a
// different level, the level path is the authoritative one.
let buildingId: AnyNodeId | null = null
if (sel.levelId) {
const level = nodes[sel.levelId]
if (level && level.type === 'level' && level.parentId) {
buildingId = level.parentId as AnyNodeId
}
}
if (!buildingId) buildingId = sel.buildingId ?? null
const building = buildingId ? nodes[buildingId] : null
if (!building || building.type !== 'building') return null
const live = useLiveTransforms.getState().transforms.get(buildingId as string)
return {
position: live?.position ?? building.position,
rotationY: live?.rotation ?? building.rotation[1] ?? 0,
}
}
/**
* Resolve Figma-style alignment for tools whose anchors are in the active
* building's local frame, but where alignment must run on the WORLD axes
* (the frame the user sees the grid in). Wraps `resolveAlignmentInBuildingWorld`
* with the active building lookup so callers don't repeat the boilerplate.
*
* Returns:
* - `guides` in WORLD coords (renderer must live in a world-space group),
* - `snap` in BUILDING-LOCAL coords (ready to add to a local position).
*/
export function resolveAlignmentForActiveBuilding(args: {
moving: readonly AlignmentAnchor[]
candidates: readonly AlignmentAnchor[]
threshold: number
}): ResolveAlignmentInBuildingResult {
return resolveAlignmentInBuildingWorld({ ...args, pose: getActiveBuildingPose() })
}
/**
* Baseline rotation the floor-plan view applies on top of the building
* rotation. Mirrors `FLOORPLAN_VIEW_ROTATION_DEG = 90` in floorplan-panel.tsx —
* the scene group reads it via `floorplanSceneRotationDeg = FVR - buildingRot`.
*/
const FLOORPLAN_VIEW_ROTATION_RAD = Math.PI / 2
function rotateAnchorsBy(
anchors: readonly AlignmentAnchor[],
cos: number,
sin: number,
): AlignmentAnchor[] {
return anchors.map((a) => ({
nodeId: a.nodeId,
kind: a.kind,
x: a.x * cos - a.z * sin,
z: a.x * sin + a.z * cos,
}))
}
/**
* Resolve alignment in the 2D floor-plan view frame — the frame the user
* sees the (always axis-aligned) grid lines in, regardless of how the
* building has been rotated. Use this from EVERY 2D floor-plan path so
* alignment guides stay parallel to the visible grid.
*
* Why it differs from `resolveAlignmentForActiveBuilding`: the 3D viewport
* shows the world XZ grid, so world-frame alignment matches the visible
* grid there. The 2D floor plan, however, rotates the scene `<g>` by
* `floorplanSceneRotationDeg = FVR buildingRot` and renders the grid
* OUTSIDE that rotated group — so the visible axes are
* `R(FVR buildingRot) · local`. World-frame alignment would land on
* world axes, which appear diagonal in this view; view-frame alignment
* lands on the SVG axes the user actually reads.
*
* Returns guides in view-frame coords (correct input for the floor-plan
* alignment-guide layer, which is mounted outside the rotated scene
* group) and a snap delta projected back into building-local (so callers
* can add it to a local position as-is).
*/
export function resolveAlignmentForFloorplanView(args: {
moving: readonly AlignmentAnchor[]
candidates: readonly AlignmentAnchor[]
threshold: number
}): ResolveAlignmentInBuildingResult {
const pose = getActiveBuildingPose()
const buildingRotY = pose?.rotationY ?? 0
const rot = FLOORPLAN_VIEW_ROTATION_RAD - buildingRotY
const cos = Math.cos(rot)
const sin = Math.sin(rot)
const result = resolveAlignmentInBuildingWorld({
moving: rotateAnchorsBy(args.moving, cos, sin),
candidates: rotateAnchorsBy(args.candidates, cos, sin),
threshold: args.threshold,
// Pose `null` keeps `resolveAlignmentInBuildingWorld` in its no-op
// path: it just runs `resolveAlignment` on the already-rotated
// anchors and returns the snap delta in the same view frame.
pose: null,
})
if (!result.snap) return result
// View-frame delta → local-frame delta (transpose of R(rot)).
const { dx, dz } = result.snap
return {
guides: result.guides,
snap: { dx: dx * cos + dz * sin, dz: -dx * sin + dz * cos },
}
}
/**
* Snap a world XZ position to the grid, then express it in the active
* building's local frame. When no building is active, world == local.
*/
export function snapWorldXZForActiveBuilding(
worldX: number,
worldZ: number,
step: number,
): { world: [number, number]; local: [number, number] } {
const buildingId = useViewer.getState().selection.buildingId
const building = buildingId ? useScene.getState().nodes[buildingId] : null
if (!building || building.type !== 'building') {
if (step <= 0) return { world: [worldX, worldZ], local: [worldX, worldZ] }
const sx = Math.round(worldX / step) * step
const sz = Math.round(worldZ / step) * step
return { world: [sx, sz], local: [sx, sz] }
}
return snapWorldXZToBuildingLocal(
worldX,
worldZ,
building.position,
building.rotation[1] ?? 0,
step,
)
}
/**
* Snap a building-local plan point so the resulting position sits on the
* world XZ grid. The returned point is still in building-local coords —
* useful as a `gridSnap` callback for snapWallDraftPoint / snapFenceDraftPoint
* etc., which operate entirely in the local frame.
*/
export function snapBuildingLocalToWorldGrid(
local: readonly [number, number],
step: number,
): [number, number] {
const buildingId = useViewer.getState().selection.buildingId
const building = buildingId ? useScene.getState().nodes[buildingId] : null
if (!building || building.type !== 'building') {
if (step <= 0) return [local[0], local[1]]
return [Math.round(local[0] / step) * step, Math.round(local[1] / step) * step]
}
const rotY = building.rotation[1] ?? 0
const cos = Math.cos(rotY)
const sin = Math.sin(rotY)
const worldX = building.position[0] + local[0] * cos + local[1] * sin
const worldZ = building.position[2] - local[0] * sin + local[1] * cos
return snapWorldXZToBuildingLocal(worldX, worldZ, building.position, rotY, step).local
}