ai-chatbot/packages/nodes/src/item/floorplan-move.ts
Sudhir Yadav 46f94b97b3
editor: alignment guides + floor-plan move/placement parity (#372)
* 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

* feat(editor): 3D alignment guides for item/wall/fence move + placement

Bring Figma-style alignment guides into the 3D editor, reusing the shared
pure resolver (`resolveAlignment`) and ephemeral guide store
(`useAlignmentGuides`) that previously only drove the 2D floor plan.

Core:
- `alignment-anchors.ts`: node→anchor adapters (footprint AABBs, corner
  anchors, wall/fence segment anchors) + `refineGuidesToGap` so a guide's
  line and distance read to the candidate's nearest edge, not the far side.
- `bboxCornerAnchors` + corner-only footprint anchors so alignment locks to
  item edges, never centrelines.
- `resolvePointSnap` (point-coincidence variant; kept for future use).

Editor:
- `Alignment3DGuideLayer`: dashed ribbon + flat floor dots + distance pill,
  in the project's indigo accent, mounted inside ToolManager's building-local
  group so guides render in the cursor's frame.
- Producers wired in the item move tool, item placement coordinator, and the
  wall + fence endpoint tools; walls and fences cross-align.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(editor): align guides snap to nearest real anchor, drop bbox re-span

The 3D alignment guide could place its end dot in empty space: a diagonal
wall (or any rotated / non-rectangular object) has bounding-box corners that
don't lie on the object, and `refineGuidesToGap` re-spanned the guide to
exactly those AABB edges — so the dot floated "along the coordinate" rather
than on the item.

- `resolveAlignment` now tie-breaks to the candidate anchor NEAREST on the
  perpendicular axis (after the tightest axis match). Anchors are real points
  (corners / endpoints / midpoints), so the guide always connects to the
  closest actual point — which also yields the facing-edge gap distance.
- All four producers (item move, item placement, wall + fence endpoints) now
  publish the raw resolver guides; the AABB nearest-edge re-span is gone.
- Removed the now-dead `refineGuidesToGap` and `resolvePointSnap` helpers
  (and their tests / exports).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* feat(editor): group move handle + shared group-transform core, move-tool polish

Add a group-move gizmo alongside the existing group-rotate handle, both
driven by a new shared `group-transform-shared` module (participant
classification, group-box + corner math, connected wall/fence component
expansion so attached structure transforms rigidly as one piece).

- core: refactor alignment-anchors collection + tests, extend handle registry
- editor: group-move-handle, group-transform-shared; rotate handle reuses them;
  node-arrow-handles gains click-swallow guard; box-select + placement tweaks
- nodes: move-tool updates across ceiling/column/slab/roof/registry; door math
  and panel adjustments; item definition cleanup
- nodes(fence): play `sfx:grid-snap` ticker on endpoint move, matching the
  wall endpoint tool (fixes missing audio feedback on fence side drag)

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(editor): keep autosave alive across page unload

The autosave debounces writes by 1s and relies on a `beforeunload` flush
for anything still pending. That flush fired a plain `fetch` PUT, which
the browser cancels the instant the page unloads — so refreshing right
after an edit (e.g. painting a roof material) silently dropped the change
and the reload showed the last persisted scene.

Thread a `{ keepalive }` option through the save callback and set it on
the unload flush so the request survives the unload. Also listen for
`pagehide` (fires where `beforeunload` does not, e.g. mobile Safari /
bfcache) and clear the dirty flag up front so the two listeners don't
double-send. Normal debounced saves omit `keepalive` (its 64KB body cap
only constrains the best-effort unload flush, not regular saves).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* feat(editor): paint eraser + reset-all, drop roof cross-role bleed

Material paint gains an eraser (clear a surface back to its default) and a
"Reset all" action that defaults every painted surface on a node — for a
roof that includes each child segment — via a generic
`buildResetSurfaceMaterialUpdates` that nulls catch-all and role-specific
material fields without per-kind knowledge.

Also stop a single painted roof surface from bleeding onto the others:
`getEffectiveRoofSurfaceMaterial`, `getRoofMaterialArray`, and the segment
renderer no longer cross-fall-back between top/edge/wall. An unset role
resolves only to the legacy catch-all (back-compat) or the theme default,
so painting just the shingle, trim, or soffit stays on that surface.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* feat(editor): alignment guides + drag bounding box across tools

Extend the Figma-style 3D alignment guides to the placement and move
tools for columns, elevators, roofs, stairs, ceilings, slabs, fences,
walls, doors, and windows: each collects alignment anchors from the
scene, resolves a snap within the shared threshold, and drives the
`useAlignmentGuides` overlay. Wall openings (doors/windows) only snap
along their host wall via the new `wall-opening-alignment` helper.

Add a shared `DragBoundingBox` overlay (exported from the editor barrel)
that renders the dragged object's bounds during a move, wired into the
column move tool alongside the alignment snap.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(editor): axis-stable resize-arrow drag plane + slimmer gizmo handles

Build the linear resize-arrow's drag plane so it always contains the
handle's axis (view direction minus its along-axis component) instead of
a plane that merely faces the camera. The old camera-facing normal
collapsed when the axis pointed toward the viewer — screen motion barely
changed the axis component, so the resize crawled or stopped tracking the
cursor. Also slim the extruded arrow/handle geometry (shared by the node
arrows, wall side handles, and polygon editor) for a lighter gizmo.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(editor): fill-block wall opening highlight + selected frameless openings

Draw the selected-wall opening highlight as a translucent block filling
the cutout volume (front-side culled) instead of a single vertical pane,
so it reads as an occupied slot from any angle — including a top-down
floorplan view where an edge-on pane was invisible. Also highlight a
directly-selected frameless opening (a `door` with openingKind
`'opening'`), which otherwise renders no geometry of its own, and reflect
live drag overrides via `useLiveNodeOverrides`.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(viewer): double-side slab hole side-walls

Build the slab in 3D rather than via ExtrudeGeometry so each hole-wall
quad is emitted twice with opposite winding. The slab material is forced
to FrontSide (DoubleSide poisons the MRT scene pass), under which
ExtrudeGeometry's single-sided hole walls get back-face culled and you
see straight through the cut. The doubled quads keep the cut's inner
thickness visible from any angle without z-fighting.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(editor): box-select building-scoped nodes like elevators

Building-scoped selectable nodes (e.g. elevators) are children of the
building, not the active level, so the level walk never reached them.
Also walk the level's building children and box-test any registry-
selectable kind by its rendered bounds, matching the column/stair/shelf
path.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* feat(editor): shelf placement alignment + column placement ghost

Shelf placement now snaps to Figma-style alignment guides by its
footprint edges (layered on grid snap, Alt bypasses), matching the
existing 3D move tool. Guides refresh after each drop and clear on
teardown.

Column placement migrates to the registry `def.tool` path so it can
render a translucent column ghost at the cursor (like the shelf build
tool) instead of a bare cursor sphere — the editor package can't import
the column geometry, so the tool now lives in packages/nodes:
- extract `ColumnBody` from the renderer and add a `ColumnPreview`
  (cloned translucent material, raycast disabled, origin-positioned)
- new `column/tool.tsx` registry placement tool with the same
  footprint-edge alignment as shelf / column move
- wire `def.tool` + tool hints; drop the now-unreachable legacy
  editor-side `ColumnTool` and its dead file

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* feat(editor): floor-plan alignment, pivot moves & placement ghosts

Bring the 3D editor's Figma-style alignment experience to the 2D floor
plan across every node kind, fix pivot semantics on move, and add 2D
placement ghosts.

Alignment
- Wall anchors now include ±thickness/2 face corners so columns/items/etc.
  snap flush to wall faces (fixes pillar↔wall); shared by 2D and 3D.
- Shared apply-alignment helper (applyFloorplanAlignment /
  alignFloorplanDraftPoint, with excludeIds) used by move sessions,
  structural drafting (wall/fence/slab/zone/ceiling/roof), and wall/fence
  endpoint drags.
- Door/window/wall-item moves get along-wall edge-to-edge snapping.
- Generic free-translate move path aligns by edges (corner anchors).

Pivot moves (2D)
- Polygon kinds (slab/ceiling/zone) move by centroid→cursor via a shared
  polygon-centroid mover; stair moves by origin→cursor; matching 3D.
- Shelf/column move targets write position directly (single source of
  truth) so the 3D group no longer sticks on commit.

Placement ghosts (2D)
- usePlacementPreview store + FloorplanPlacementPreviewLayer render a
  kind's def.floorplan footprint following the cursor; wired for column
  and elevator.

Fixes
- Elevator placement no longer deselects the active floor plan
  (preserve levelId through setSelection's hierarchy guard).
- Guides clear on every commit/cancel/unmount path.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* refactor(editor): address architecture review for floor-plan work

- Move usePlacementPreview store from core to editor: placement ghosts
  are an editor/tool concern the read-only viewer never needs. Rewire the
  column tool (via the @pascal-app/editor public surface) and the
  editor-internal elevator tool + preview layer (relative imports).
- FloorplanPlacementPreviewLayer: read scene lazily in ctx.resolve instead
  of bulk-reading the nodes map during render.
- wiki/architecture/tools.md: refresh the stale useLiveTransforms-per-kind
  note to reflect item/shelf/column (world-plan) + slab/ceiling/zone (delta).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(nodes): recreate window draft on wall:move when null after placement

After a successful click-to-place, the click handler deletes the
transient draft and relies on the wall-rebuild → R3F pointer-enter
cascade to create a fresh draft for the next placement. If that cascade
doesn't fire synchronously (e.g. async geometry rebuild) the next
wall:move receives a null draftRef and bails — requiring leave/re-enter
to place again.

Fix: in onWallMove, when draftRef.current is null but we're hovering a
valid wall, recreate the draft immediately (same WindowNode.parse +
createNode path as onWallEnter). This is idempotent: if wall:enter does
fire first, destroyDraft() in onWallEnter cleans up cleanly.

Preserves parity with door multi-place behaviour, matching #367's intent.

* fix(nodes): recreate door draft on wall:move when null after placement

Mirror of the window fix one commit back: after click-to-place the
DoorTool deletes its transient draft and relies on the wall-rebuild \u2192
R3F pointer-enter cascade to spawn a fresh draft for the next placement.
When that cascade doesn't fire synchronously, the next wall:move sees a
null draftRef and bails \u2014 forcing a leave/re-enter to place again.

Recreate the draft in onWallMove when null and over a valid wall on the
current level. Idempotent with onWallEnter (destroyDraft cleans up if
both fire).

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
Co-authored-by: Pascal <open@pascal.app>
2026-06-04 14:03:00 -04:00

288 lines
10 KiB
TypeScript

import {
type AnyNode,
type AnyNodeId,
type CeilingNode,
collectAlignmentAnchors,
type FloorplanMoveTarget,
type FloorplanMoveTargetSession,
getScaledDimensions,
type ItemNode,
movingFootprintAnchors,
useScene,
} from '@pascal-app/core'
import { applyFloorplanAlignment, snapPointToGrid, type WallPlanPoint } from '@pascal-app/editor'
import { findClosestWallInPlan, snapLocalXToNeighbors } from '../shared/wall-attach-target'
/**
* 2D floor-plan move handler for item. Branches on `asset.attachTo`:
*
* - `'wall'` / `'wall-side'`: pointer snaps to nearest wall (same
* math as door / window via `findClosestWallInPlan`). Position
* local-X is snapped to 0.5m grid; the wall-local Y carries over
* from the source position (2D has no vertical signal).
* - `'ceiling'`: pointer is point-in-polygon-tested against every
* ceiling on the level. If hit, the item reparents to that
* ceiling at the snapped local plan position.
* - undefined (floor): pointer is point-in-polygon-tested against
* every slab on the level. If hit, the item reparents to that
* slab; otherwise it stays parented to the level (free-floating)
* at the snapped plan position.
*
* Skipped vs the 3D `MoveItemContent` for now: attachTo *transitions*
* (drop a wall lamp on a ceiling and have it switch to ceiling-attach).
* The 3D path remains canonical for that — 2D only re-anchors within
* the item's current attach family.
*/
const GRID_STEP = 0.5
export const itemFloorplanMoveTarget: FloorplanMoveTarget<ItemNode> = ({ node, nodes }) => {
const attachTo = node.asset.attachTo
const startLevelId: AnyNodeId | null = (() => {
// Walk to the owning level depending on the item's current parent:
// - wall / ceiling parent → parent.parentId is the level
// - level parent (floor items) → parent.id IS the level
// - item / shelf parent → walk up until we hit a level
// Without the `parent.type === 'level'` short-circuit, floor items
// (whose immediate parent is the level itself) get `level.parentId`,
// which is the *building* — `findContainingSurface` would then
// iterate the building's children (levels, not slabs) and the
// fallback `parentId: startLevelId` would reparent the item to the
// building. The item drops out of the level→children DFS the floor
// plan walks and disappears mid-drag.
const nodes = useScene.getState().nodes
let current = nodes[node.parentId as AnyNodeId]
while (current) {
if (current.type === 'level') return current.id as AnyNodeId
if (!current.parentId) return null
current = nodes[current.parentId as AnyNodeId]
}
return null
})()
if (attachTo === 'wall' || attachTo === 'wall-side') {
return buildWallItemSession(node, startLevelId)
}
if (attachTo === 'ceiling') {
return buildSurfaceItemSession(node, startLevelId, 'ceiling')
}
return buildFloorItemSession(node, startLevelId, nodes)
}
function buildWallItemSession(
node: ItemNode,
startLevelId: AnyNodeId | null,
): FloorplanMoveTargetSession {
// Wall items use the same local-X snap pipeline as doors / windows.
// local-Y carries over from the source item's position (2D can't
// express vertical movement).
const startLocalY = node.position[1]
return {
affectedIds: [node.id as AnyNodeId],
apply({ planPoint, modifiers }) {
const nodes = useScene.getState().nodes
const hit = findClosestWallInPlan(planPoint, nodes, startLevelId)
if (!hit) return
const [width] = getScaledDimensions(node)
// Figma-style along-wall alignment (edge-to-edge with other openings /
// wall items / wall ends), winning over the 0.5m grid snap; falls back
// to grid when nothing aligns. Alt bypasses; Shift drops the grid snap.
const neighborX = modifiers.altKey
? null
: snapLocalXToNeighbors({
wall: hit.wall,
localX: hit.localX,
width,
selfId: node.id as AnyNodeId,
nodes,
})
const snappedLocalX =
neighborX ??
(modifiers.shiftKey ? hit.localX : Math.round(hit.localX / GRID_STEP) * GRID_STEP)
const halfW = width / 2
const clampedX = Math.max(halfW, Math.min(hit.wallLength - halfW, snappedLocalX))
useScene.getState().updateNodes([
{
id: node.id as AnyNodeId,
data: {
position: [clampedX, startLocalY, 0],
rotation: [0, hit.itemRotation, 0],
side: hit.side,
parentId: hit.wall.id,
},
},
])
},
canCommit() {
const live = useScene.getState().nodes[node.id as AnyNodeId] as ItemNode | undefined
return !!live && live.type === 'item' && !!live.parentId
},
}
}
/**
* Floor items live as level children — the slab is *not* a parent (slabs
* have no `children` field; only ceilings and the level itself do).
* Reparenting a floor item to a slab corrupts the parent-children
* bookkeeping and the item drops out of the level→children DFS the
* floor-plan layer walks → the polygon stops rendering mid-drag.
*
* For the 2D move we just translate `position` in level-local coords and
* leave the parent as the level (matching the 3D `detachItemSurfaceToFloor`
* in `use-placement-coordinator.tsx`). Snap to the 0.5m grid unless the
* user holds Shift.
*/
function buildFloorItemSession(
node: ItemNode,
startLevelId: AnyNodeId | null,
nodes: Record<AnyNodeId, AnyNode>,
): FloorplanMoveTargetSession {
const rotationY = node.rotation[1] ?? 0
// Alignment candidates gathered once — scene is stable during the drag.
const candidates = collectAlignmentAnchors(nodes, node.id)
return {
affectedIds: [node.id as AnyNodeId],
apply({ planPoint, modifiers }) {
const gridSnapped: WallPlanPoint = modifiers.shiftKey
? ([planPoint[0], planPoint[1]] as WallPlanPoint)
: snapPointToGrid([planPoint[0], planPoint[1]] as WallPlanPoint, GRID_STEP)
// Figma-style alignment layered on the grid snap (Alt bypasses).
const { point: snapped } = applyFloorplanAlignment(
gridSnapped,
movingFootprintAnchors(
node as unknown as AnyNode,
gridSnapped[0],
gridSnapped[1],
rotationY,
),
candidates,
{ bypass: modifiers.altKey },
)
const sourceY = node.position[1]
const nextPosition: [number, number, number] = [snapped[0], sourceY, snapped[1]]
useScene.getState().updateNodes([
{
id: node.id as AnyNodeId,
data: {
position: nextPosition,
// Keep parent as the level we resolved at session-start. If
// somehow it's null (e.g. orphaned item), fall back to the
// existing parent so we don't write `null` and detach.
parentId: startLevelId ?? node.parentId,
},
},
])
},
canCommit() {
const live = useScene.getState().nodes[node.id as AnyNodeId] as ItemNode | undefined
return !!live && live.type === 'item'
},
}
}
/**
* Ceiling items reparent to whichever ceiling polygon contains the
* pointer. Ceilings carry a `children` field on their schema so the
* parent-children bookkeeping in `updateNodes` works correctly when the
* item moves between ceilings. If the cursor drifts off every ceiling,
* the original parent is preserved (no detach back to the level — there
* is no canonical "free-floating ceiling item").
*/
function buildSurfaceItemSession(
node: ItemNode,
startLevelId: AnyNodeId | null,
targetKind: 'ceiling',
): FloorplanMoveTargetSession {
return {
affectedIds: [node.id as AnyNodeId],
apply({ planPoint, modifiers }) {
const nodes = useScene.getState().nodes
const snapped: WallPlanPoint = modifiers.shiftKey
? ([planPoint[0], planPoint[1]] as WallPlanPoint)
: snapPointToGrid([planPoint[0], planPoint[1]] as WallPlanPoint, GRID_STEP)
const surface = findContainingSurface(snapped, nodes, startLevelId, targetKind)
const sourceY = node.position[1]
const nextPosition: [number, number, number] = [snapped[0], sourceY, snapped[1]]
useScene.getState().updateNodes([
{
id: node.id as AnyNodeId,
data: {
position: nextPosition,
parentId: surface ? surface.id : node.parentId,
},
},
])
},
canCommit() {
const live = useScene.getState().nodes[node.id as AnyNodeId] as ItemNode | undefined
return !!live && live.type === 'item'
},
}
}
/**
* Walk every ceiling under the level and return the first one whose
* polygon contains the pointer. Holes are honoured — a point inside a
* hole counts as not inside the surface. Slabs are intentionally NOT a
* valid target: floor items are parented to the level, not the slab,
* because slabs don't carry a `children` field on their schema.
*/
function findContainingSurface(
point: readonly [number, number],
nodes: Record<AnyNodeId, AnyNode>,
parentLevelId: AnyNodeId | null,
targetKind: 'ceiling',
): CeilingNode | null {
if (!parentLevelId) return null
const level = nodes[parentLevelId]
const childIds = (level as unknown as { children?: AnyNodeId[] })?.children
if (!Array.isArray(childIds)) return null
for (const childId of childIds) {
const node = nodes[childId]
if (!node || node.type !== targetKind) continue
const surface = node as CeilingNode
const polygon = surface.polygon
if (!polygon || polygon.length < 3) continue
if (!pointInRing(point, polygon)) continue
const holes = surface.holes ?? []
let inHole = false
for (const hole of holes) {
if (hole.length >= 3 && pointInRing(point, hole)) {
inHole = true
break
}
}
if (!inHole) return surface
}
return null
}
/** Standard ray-cast point-in-polygon. Treats edges as inside. */
function pointInRing(
point: readonly [number, number],
ring: ReadonlyArray<readonly [number, number]>,
): boolean {
let inside = false
const [px, py] = point
for (let i = 0, j = ring.length - 1; i < ring.length; j = i++) {
const ax = ring[i]![0]
const ay = ring[i]![1]
const bx = ring[j]![0]
const by = ring[j]![1]
const intersects = ay > py !== by > py && px < ((bx - ax) * (py - ay)) / (by - ay) + ax
if (intersects) inside = !inside
}
return inside
}