Files
editor/wiki/architecture/tools.md
T
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

14 KiB

Tools

Editor tools structure in apps/editor.

Applies to: apps/editor/components/tools/**.

Tools are React components that capture user input (pointer, keyboard) and translate it into useScene mutations. They live exclusively in apps/editor/components/tools/.

Lifecycle

ToolManager reads useEditor (phase + mode + tool) and mounts the active tool component. When the tool changes, the old component unmounts, cleaning up any transient state.

See apps/editor/components/tools/tool-manager.tsx.

Tool Categories by Phase

Site

  • site-boundary-editor — draw/edit property boundary polygon

Structure

  • wall-tool — draw walls segment by segment
  • slab-tool + slab-boundary-editor + slab-hole-editor
  • ceiling-tool + ceiling-boundary-editor + ceiling-hole-editor
  • roof-tool
  • door-tool + door-move-tool
  • window-tool + window-move-tool
  • item-tool + item-move-tool
  • zone-tool + zone-boundary-editor

Furnish

  • item-tool — place furniture

Shared utilities

  • polygon-editor — reusable boundary/hole editing logic
  • cursor-sphere — 3D cursor visualisation

Pattern

// apps/editor/components/tools/my-tool/index.tsx
import { useScene } from '@pascal-app/core'
import { useEditor } from '../../store/use-editor'

export function MyTool() {
  const createNode = useScene(s => s.createNode)
  const setTool = useEditor(s => s.setTool)

  // Pointer handlers mutate the scene store directly.
  // No local geometry — use a renderer for any preview mesh.

  return (
    <mesh onPointerDown={handleDown} onPointerMove={handleMove}>
      {/* ghost / preview geometry only */}
    </mesh>
  )
}

Rules

  • Tools mutate useScene for committed changes and useLiveTransforms for ephemeral drag state. A tool's end-of-interaction write (click-to-commit, release-to-commit) goes to useScene and is captured in undo history. Per-mouse-move previews go to useLiveTransforms so history and subscribers aren't spammed.
  • Live-drag exception for direct mesh transforms. During an active drag a tool may apply a transform offset directly to sceneRegistry.nodes.get(id).position/rotation/scale when and only when the same offset is mirrored into useLiveTransforms for that node. This exception exists because the 3D renderers don't reconcile useLiveTransforms onto mesh.position yet; once a LiveTransformSystem does that, this exception goes away. Conditions:
    • The mesh offset must mirror the useLiveTransforms entry (same exact value, not "same conceptual translation"), so anything reading useLiveTransforms sees the same preview as the 3D view. ParametricNodeRenderer (used for every kind that ships def.geometry) binds <group position={liveTransform.position}> via React — every Zustand notification re-renders and reconciles the group's position back to whatever value useLiveTransforms holds. If mesh.position.set(delta) and useLiveTransforms.set({ position: someOtherValue }) disagree, the two writes fight every frame and the user sees jitter during the drag.
    • For position-based kinds (spawn / item / column): the position field on the node IS the group's local-frame position, so useLiveTransforms.position should hold the live world position of the node (matches the eventual scene.update).
    • For polygon-based kinds (slab / fence / ceiling / wall): the node has no position field — the canonical group position is [0,0,0] with geometry built in level-local coords. useLiveTransforms.position must hold the delta the tool wants to translate by ([deltaX, 0, deltaZ]), not the world location of the polygon's center. The cursor sphere position (which IS the translated polygon center) is tracked separately via React useState, not useLiveTransforms.
    • The offset must be cleared on tool unmount, cancel, and commit — both mesh.position.set(0, 0, 0) and useLiveTransforms.clear(id).
    • The tool must not generate or mutate geometry in this path — only transform writes. Geometry generation still belongs in a core system.
  • No business logic in tools — delegate geometry/constraint rules to core systems.
  • Preview geometry is local — transient meshes shown while a tool is active live in the tool component, not in the scene store.
  • Clean up on unmount — remove any pending/incomplete nodes and any live transforms/mesh offsets when the tool unmounts.
  • Tools must not import from @pascal-app/viewer — use the scene store and core hooks only. sceneRegistry is exported from @pascal-app/core and is the allowed door into the Three.js graph for the narrow purposes above.
  • Each tool should handle a single, well-scoped interaction. Split complex tools (e.g. "draw + move") into separate components selected by useEditor.

Adding a New Tool

  1. Create apps/editor/components/tools/<name>/index.tsx.
  2. Register the tool in ToolManager under the correct phase and mode.
  3. Add the tool identifier to the useEditor tool union type.
  4. If the tool requires new node types, add schema + renderer + system first.

Move coexistence: 2D FloorplanRegistryMoveOverlay + legacy 3D mover

While a kind is mid-migration its move can run through two paths at once: the registry-driven 2D FloorplanRegistryMoveOverlay (def.floorplanMoveTarget) and the legacy 3D mover (e.g. MoveItemContent). Both react to setMovingNode(node), both mount, both want to commit. Two pitfalls surfaced and have stable fixes; replicate the patterns when porting another kind to coexist.

Pitfall: the 2D cleanup clobbering the 3D commit

FloorplanRegistryMoveOverlay pauses scene history at mount and snapshots the moving node. If the user actually commits in 3D, the 3D path writes new state and clears movingNode. The 2D overlay then unmounts — and its cleanup useEffect would call updateNodes(snapshot), overwriting the just-committed 3D state with the original.

Fix in floorplan-registry-move-overlay.tsx: gate the cleanup revert on a hasMovedSinceStart flag that is only set inside onMove after the target.closest('[data-floorplan-scene]') guard. If no 2D apply ever ran, the divergence in scene state must be an external committer's — skip the revert, just resume history. Symptom when missing: items snap back to their pre-drag position / rotation on 3D commit.

Pitfall: useDraftNode.destroy() clobbering the 2D commit

Mirror problem in the other direction. The legacy 3D mover's usePlacementCoordinator cleanup unconditionally calls draftNode.destroy(), which for adopted moves writes the original position back to scene. If the 2D path committed first, the destroy reverts it.

Fix in use-draft-node.ts: in move-mode destroy(), compare the live scene position to the adopt()-time snapshot. If they diverge, an external committer has already written the new value — skip the restore (and the mesh reset). Cancellation paths (Escape) still revert, because they revert before unmount so live == snapshot at destroy time.

Pitfall: pointermove fires globally; treat 3D-canvas events as out of scope

FloorplanRegistryMoveOverlay listens to window pointermove. When the user drags in 3D the listener still fires — without a target check it converts 3D-canvas client coords through the floor-plan SVG's CTM, producing garbage plan coordinates that fight the 3D mover's mesh updates.

Always gate onMove (and onPointerUp) with target.closest('[data-floorplan-scene]') so the 2D path only acts when the pointer is actually over the floor plan scene.

useLiveTransforms contract is per-kind, not generic

The store name suggests a uniform contract; the writes in practice are not. Document the frame on the writer side; consumers must either know the kind or be narrowed.

Writer position frame rotation frame
usePlacementCoordinator (item floor / wall / ceiling) world plan (level-local) world Y
door / window move tools wall-local wall-local (0 or π)
slab / ceiling / fence / polygon-based movers position delta ([Δx, 0, Δz]) unused / 0
column / roof / elevator / spawn / single-position kinds world plan world Y

Anything that subscribes to useLiveTransforms to inform 2D rendering needs to handle these frames explicitly. The FloorplanRegistryLayer override currently branches by kind: item / shelf / column are treated as world-plan (it copies live.position onto the effective node and forces parentId: null so the resolver skips the parent-chain transform), while slab / ceiling / zone are treated as a polygon delta (it translates the polygon vertices by live.position). Each kind added to the live-drag path grows this consumer-side switch; the preferred long-term fix is to standardise the frame at the writer so the consumer stops branching by node.type.

Wall-attached node rotations must be wall-local

door / window / wall-attached item are children of the wall mesh in 3D. The wall's mesh.rotation.y = -atan2(dy, dx). The child node's rotation.y therefore lives in the wall's local frame and composes with the wall's rotation at render time.

The 3D source of truth is calculateItemRotation(normal) in editor/src/components/tools/item/placement-math.ts, which returns 0 (front face) or π (back face). Any 2D move helper that writes node.rotation[1] for wall-attached nodes must produce the same wall-local value. Writing a world-space rotation gets you orientation bugs that vary with wall direction — typically 90° on horizontal walls and 180° on vertical walls (which sometimes "looks OK" by symmetry, which is worse — silent corruption).

See nodes/src/shared/wall-attach-target.ts's WallHit.itemRotation. Side determination there is calibrated to the same convention: in wall-local space the wall extends along +X, the front-face normal is +Z, and perpRaw >= 0 is the front side.

Move / placement: disable raycast on the moved mesh

A 3D move tool that follows the cursor by writing mesh.position.set(x, 0, z) runs into a feedback loop: as the mesh tracks the cursor it sits between the camera and the grid plane, so R3F's raycaster hits the moved mesh first → only ${kind}:move fires → grid:move stops firing → the cursor snapshot (used as the commit position) freezes at its initial value. The user clicks at a new spot and the node commits at the starting one.

Fix in MoveRegistryNodeTool: at drag-start, traverse the moved mesh and overwrite child.raycast = () => {} on every descendant; restore the originals in the effect's cleanup. The ray now passes through the moved mesh, hits the grid plane, and grid:move keeps firing.

The same applies to placement previews — see nodes/src/shelf/preview.tsx for the (obj as { raycast: () => void }).raycast = () => {} pattern. A preview that captures rays starves the placement tool's own grid:move snapshot.

Move / placement: commit handlers listen to every ${kind}:click

R3F's pointer raycaster dispatches the click event to whichever mesh is closest, even when the user thinks they're clicking the ground. A tool that only listens to grid:click misses commits whenever the click ray lands on a wall face, a shelf side, an item, or the still-being-placed cursor mesh itself. Symptom: clicks visibly hit "near" the cursor but the tool does nothing.

The fix is the pattern used by ShelfTool and MoveRegistryNodeTool: keep the latest grid:move snapshot in a ref, then register one shared commit handler against grid:click and every common kind-click event:

const CLICK_TRIGGER_KINDS = [
  'shelf', 'item', 'slab', 'ceiling', 'wall',
  'fence', 'column', 'roof', 'roof-segment',
  'stair', 'stair-segment',
] as const

emitter.on('grid:click', commitAtCursor)
for (const kind of CLICK_TRIGGER_KINDS) {
  emitter.on(`${kind}:click` as `${typeof kind}:${EventSuffix}`, commitAtCursor as never)
}

The commit reads lastCursorRef.current (set by grid:move), not the click event's position — clicks on vertical surfaces carry the hit point on that surface, which can be metres away from the cursor the user was visually targeting.

Move tools must preserve the node's actual rotation in useLiveTransforms

A tool that writes useLiveTransforms.set(id, { position: [x, 0, z], rotation: 0 }) during drag wipes the node's true Y-rotation for the duration of the drag. ParametricNodeRenderer reads liveTransform.rotation and applies <group rotation={[0, liveTransform.rotation, 0]}>, so the moved node visually un-rotates to 0 the moment the tool mounts, then snaps back to its real rotation on commit when the live transform clears. Users perceive that snap as "the node went to a weird position."

Capture the original node.rotation[1] at mount time and forward it on every set:

const originalRotationY = useMemo(() => {
  const r = (node as { rotation?: unknown }).rotation
  return typeof r === 'number' ? r : Array.isArray(r) ? (r[1] ?? 0) : 0
}, [node])

// in onMove:
useLiveTransforms.getState().set(node.id, {
  position: [x, 0, z],
  rotation: originalRotationY,
})

If the tool also rotates the node during the drag, it should drive rotation from the current tool state — not from 0, not from the stale node value.

SVG fill="none" is click-through

When emitting a FloorplanGeometry polygon that should remain interactive but visually invisible (e.g. an item with a thumbnail image carrying the visual weight), use fill="transparent", not fill="none". The default pointer-events: visiblePainted only hit-tests the interior when there's a paint server — none is not paint, transparent is. Without this the floor-plan layer's wrapping <g> never sees the onPointerDown and clicks don't select the node.