Sudhir Yadav 555cf06c12
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>
2026-06-09 11:05:27 -04:00

305 lines
10 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* Pure alignment-guide resolver — no React, no DOM, no scene access.
*
* Given a moving object's anchor points at its proposed position and a
* pool of candidate anchors from nearby static objects, returns:
* - the best per-axis matches as `Guide` rendering primitives, and
* - an optional `{ dx, dz }` snap delta the caller can apply.
*
* Anchors are 2D points on the floor plane (XZ, in world meters). The
* resolver picks at most one match per axis: the smallest |Δx| match
* snaps X; the smallest |Δz| match snaps Z. This mirrors Figma's
* behaviour — guides appear along the matched axes, regardless of how
* many neighbours could have matched.
*
* Two guides max per call keeps the visual signal sharp at the cost of
* not surfacing every possible alignment at once. Multi-guide ("this
* lines up with three things") is intentionally out of scope for v1.
*/
export type AnchorKind = 'corner' | 'edge-mid' | 'center'
export type AlignmentAnchor = {
/** Owning node id — informational; resolver does not use it. */
nodeId: string
kind: AnchorKind
x: number
z: number
}
export type AlignmentGuideAxis = 'x' | 'z'
/**
* Rendering primitive — a guide line on the floor plane.
*
* `axis === 'x'`: vertical guide. Both endpoints share `coord` as their X.
* `axis === 'z'`: horizontal guide. Both endpoints share `coord` as their Z.
*
* The line spans from the matched candidate anchor to the moving anchor
* after snap. Renderers extend visually beyond the endpoints if they want
* Figma-style "infinite line" feel.
*/
export type AlignmentGuide = {
axis: AlignmentGuideAxis
coord: number
from: { x: number; z: number }
to: { x: number; z: number }
movingAnchorKind: AnchorKind
candidateAnchorKind: AnchorKind
candidateNodeId: string
/** Perpendicular distance between the two anchors (used by the distance pill). */
distance: number
}
export type ResolveAlignmentInput = {
/** Anchors of the moving node, positioned at the proposed (pre-snap) location. */
moving: readonly AlignmentAnchor[]
/** Anchors from every other candidate node the caller has already filtered. */
candidates: readonly AlignmentAnchor[]
/**
* Max |Δ| (meters) for an anchor pair to count as a match. Typically
* derived from a screen-pixel budget × current units-per-pixel so the
* snap feel is zoom-invariant.
*/
threshold: number
}
export type ResolveAlignmentResult = {
guides: AlignmentGuide[]
/**
* Delta the caller should add to the moving node's planar position so
* its anchors land on the matched axes. `null` when no axis matched.
*/
snap: { dx: number; dz: number } | null
}
const EMPTY: ResolveAlignmentResult = { guides: [], snap: null }
/** Forward rotation: local XZ → world XZ for a node whose parent has
* position `bx,_,bz` and rotation-Y `rotY` (radians). Matches the
* transform used throughout the editor's tools / floor-plan. */
function localToWorld(
x: number,
z: number,
bx: number,
bz: number,
cos: number,
sin: number,
): { x: number; z: number } {
return {
x: bx + x * cos + z * sin,
z: bz - x * sin + z * cos,
}
}
function transformAnchorToWorld(
anchor: AlignmentAnchor,
bx: number,
bz: number,
cos: number,
sin: number,
): AlignmentAnchor {
const w = localToWorld(anchor.x, anchor.z, bx, bz, cos, sin)
return { nodeId: anchor.nodeId, kind: anchor.kind, x: w.x, z: w.z }
}
export type BuildingPose = {
position: readonly [number, number, number]
rotationY: number
}
export type ResolveAlignmentInBuildingResult = {
/** Guides in WORLD coordinates. Renderers must be in a world-space group. */
guides: AlignmentGuide[]
/** Snap delta in the BUILDING-LOCAL frame, ready to add to a local position. */
snap: { dx: number; dz: number } | null
}
/**
* Resolve alignment in WORLD space while accepting BUILDING-LOCAL anchors.
*
* Why this exists: the floor-plan grid lives in world XZ (rendered outside
* the rotated scene group), so alignment must follow the same axes —
* otherwise rotating a building drags the alignment guides off the visible
* grid and onto the rotated wall's local axes (the bug the user hit). The
* resolver itself is frame-agnostic; this wrapper just transforms anchors
* to world, resolves, then rotates the snap delta back into building-local
* so callers can add it to a local position without further math.
*
* `pose === null` → resolve in the caller's frame as-is (no transform).
*/
export function resolveAlignmentInBuildingWorld(input: {
moving: readonly AlignmentAnchor[]
candidates: readonly AlignmentAnchor[]
threshold: number
pose: BuildingPose | null
}): ResolveAlignmentInBuildingResult {
const { moving, candidates, threshold, pose } = input
if (!pose) {
return resolveAlignment({ moving, candidates, threshold })
}
const cos = Math.cos(pose.rotationY)
const sin = Math.sin(pose.rotationY)
const bx = pose.position[0]
const bz = pose.position[2]
const movingWorld = moving.map((a) => transformAnchorToWorld(a, bx, bz, cos, sin))
const candidatesWorld = candidates.map((a) => transformAnchorToWorld(a, bx, bz, cos, sin))
const result = resolveAlignment({
moving: movingWorld,
candidates: candidatesWorld,
threshold,
})
if (!result.snap) return { guides: result.guides, snap: null }
// World → local rotation (orthogonal matrix → transpose). The inverse of
// `localToWorld` above maps (dx_world, dz_world) → (dx_local, dz_local).
const dxW = result.snap.dx
const dzW = result.snap.dz
const dxL = dxW * cos - dzW * sin
const dzL = dxW * sin + dzW * cos
return { guides: result.guides, snap: { dx: dxL, dz: dzL } }
}
export function resolveAlignment(input: ResolveAlignmentInput): ResolveAlignmentResult {
const { moving, candidates, threshold } = input
if (threshold <= 0 || moving.length === 0 || candidates.length === 0) return EMPTY
// Best match per axis: among all candidate anchors within `threshold` of
// the moving anchor on the matched axis, pick the one CLOSEST in the
// perpendicular direction — so the guide always connects to the visually
// nearest actual point of the candidate. Primary delta only breaks perp
// ties.
//
// Why perp-first: a wall pre-rotation contributes anchors that share an
// exact X (vertical wall) or Z (horizontal wall), so primary deltas tie
// and perp picks the nearer endpoint. Post-rotation, the same wall's
// anchors are at slightly-different world coordinates after a float
// rotation — primary deltas differ by tiny amounts and a primary-first
// tie-break would lock onto whichever happens to be marginally tighter,
// often the far endpoint. Perp-first keeps the "closest point of
// reference" behaviour stable through rotation.
type Best = {
delta: number
primary: number
perp: number
m: AlignmentAnchor
c: AlignmentAnchor
}
let bestX: Best | null = null
let bestZ: Best | null = null
for (const m of moving) {
for (const c of candidates) {
const dx = c.x - m.x
const dz = c.z - m.z
const adx = Math.abs(dx)
const adz = Math.abs(dz)
if (
adx <= threshold &&
(bestX === null || adz < bestX.perp || (adz === bestX.perp && adx < bestX.primary))
) {
bestX = { delta: dx, primary: adx, perp: adz, m, c }
}
if (
adz <= threshold &&
(bestZ === null || adx < bestZ.perp || (adx === bestZ.perp && adz < bestZ.primary))
) {
bestZ = { delta: dz, primary: adz, perp: adx, m, c }
}
}
}
if (!bestX && !bestZ) return EMPTY
const dxSnap = bestX?.delta ?? 0
const dzSnap = bestZ?.delta ?? 0
const guides: AlignmentGuide[] = []
if (bestX) {
// X-axis match: vertical guide at x = bestX.c.x. The moving anchor
// ends up at (c.x, m.z + dzSnap). Span the line between them.
const snappedMz = bestX.m.z + dzSnap
const z1 = Math.min(bestX.c.z, snappedMz)
const z2 = Math.max(bestX.c.z, snappedMz)
guides.push({
axis: 'x',
coord: bestX.c.x,
from: { x: bestX.c.x, z: z1 },
to: { x: bestX.c.x, z: z2 },
movingAnchorKind: bestX.m.kind,
candidateAnchorKind: bestX.c.kind,
candidateNodeId: bestX.c.nodeId,
distance: Math.abs(snappedMz - bestX.c.z),
})
}
if (bestZ) {
const snappedMx = bestZ.m.x + dxSnap
const x1 = Math.min(bestZ.c.x, snappedMx)
const x2 = Math.max(bestZ.c.x, snappedMx)
guides.push({
axis: 'z',
coord: bestZ.c.z,
from: { x: x1, z: bestZ.c.z },
to: { x: x2, z: bestZ.c.z },
movingAnchorKind: bestZ.m.kind,
candidateAnchorKind: bestZ.c.kind,
candidateNodeId: bestZ.c.nodeId,
distance: Math.abs(snappedMx - bestZ.c.x),
})
}
return { guides, snap: { dx: dxSnap, dz: dzSnap } }
}
// ─── Anchor extractors (pure) ─────────────────────────────────────────
/**
* Produces the 9 standard anchors for an axis-aligned bounding box on the
* floor plane: 4 corners, 4 edge midpoints, 1 center. Suitable for any
* floor-plan entity whose footprint can be expressed as a bbox.
*
* Caller is responsible for computing the bbox — the resolver doesn't
* care how (per-kind dimensions, SVG getBBox(), etc.).
*/
export function bboxAnchors(
nodeId: string,
minX: number,
minZ: number,
maxX: number,
maxZ: number,
): AlignmentAnchor[] {
const cx = (minX + maxX) / 2
const cz = (minZ + maxZ) / 2
return [
{ nodeId, kind: 'corner', x: minX, z: minZ },
{ nodeId, kind: 'corner', x: maxX, z: minZ },
{ nodeId, kind: 'corner', x: maxX, z: maxZ },
{ nodeId, kind: 'corner', x: minX, z: maxZ },
{ nodeId, kind: 'edge-mid', x: cx, z: minZ },
{ nodeId, kind: 'edge-mid', x: maxX, z: cz },
{ nodeId, kind: 'edge-mid', x: cx, z: maxZ },
{ nodeId, kind: 'edge-mid', x: minX, z: cz },
{ nodeId, kind: 'center', x: cx, z: cz },
]
}
/**
* The 4 corner anchors of a bbox — edges only, no edge-midpoints or center.
* Used where alignment should lock to an object's edges (left/right/front/
* back), never its centreline.
*/
export function bboxCornerAnchors(
nodeId: string,
minX: number,
minZ: number,
maxX: number,
maxZ: number,
): AlignmentAnchor[] {
return [
{ nodeId, kind: 'corner', x: minX, z: minZ },
{ nodeId, kind: 'corner', x: maxX, z: minZ },
{ nodeId, kind: 'corner', x: maxX, z: maxZ },
{ nodeId, kind: 'corner', x: minX, z: maxZ },
]
}