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>
This commit is contained in:
co-authored by
Claude Opus 4.6
Pascal
parent
86db5decb8
commit
46f94b97b3
@@ -1,131 +1,14 @@
|
||||
import {
|
||||
type AnyNodeId,
|
||||
type FloorplanMoveTarget,
|
||||
type FloorplanMoveTargetSession,
|
||||
type SlabNode,
|
||||
sceneRegistry,
|
||||
useLiveTransforms,
|
||||
useScene,
|
||||
} from '@pascal-app/core'
|
||||
import { snapPointToGrid, type WallPlanPoint } from '@pascal-app/editor'
|
||||
import type * as THREE from 'three'
|
||||
import type { FloorplanMoveTarget, SlabNode } from '@pascal-app/core'
|
||||
import { createPolygonCentroidMoveTarget } from '../shared/polygon-centroid-move'
|
||||
|
||||
/**
|
||||
* 2D floor-plan move handler for slab — mirrors the 3D `MoveSlabTool`
|
||||
* live-drag pattern so the visual stays smooth in split view.
|
||||
* 2D floor-plan move handler for slab. Delegates to the shared polygon
|
||||
* centroid-pivot mover: the slab's centroid snaps to the (grid-snapped,
|
||||
* Figma-aligned) cursor — the same pivot semantics as a regular item's
|
||||
* origin — instead of the old grab-relative delta. See
|
||||
* `shared/polygon-centroid-move.ts` for the live-drag / commit rationale.
|
||||
*
|
||||
* **Why not write the polygon every tick?** Per-tick `scene.update` on
|
||||
* `polygon` triggers a CSG geometry rebuild in `GeometrySystem` every
|
||||
* frame. Even with a synchronous `markDirty`, the rebuild dispose/add
|
||||
* pair flickers in the 3D viewer and the slab visibly catches up to
|
||||
* the cursor one frame late — the same regression `commit f4ea07e` was
|
||||
* fixed for in the 3D mover. The fix there: don't touch `scene` during
|
||||
* the drag at all. Translate the rendered `<group>` via the live-drag
|
||||
* exception (`mesh.position` + `useLiveTransforms.position = delta`).
|
||||
* On commit, write the polygon once.
|
||||
*
|
||||
* **Delta semantics** (see `wiki/architecture/tools.md` — "useLiveTransforms
|
||||
* contract is per-kind, not generic"): polygon-based kinds carry their
|
||||
* "position" in the polygon vertices, not a node.position field. The
|
||||
* `useLiveTransforms.position` must be a translation **delta**
|
||||
* (`[Δx, 0, Δz]`), which `ParametricNodeRenderer` consumes as the group
|
||||
* position. Visual = group.position + group.children-in-original-coords
|
||||
* = (delta) + (original polygon vertices) = translated, with no
|
||||
* geometry rebuild.
|
||||
*
|
||||
* **Commit path**: `canCommit` is the only side-effectful write to
|
||||
* `scene`. The dispatcher captured snapshots before the first apply,
|
||||
* so its snapshot-diff after `canCommit` returns will see one update
|
||||
* (the translated polygon) and run the single-undo dance against it.
|
||||
* `MoveSlabTool`'s cleanup (fires when `setMovingNode(null)` runs after
|
||||
* the commit) handles the `useLiveTransforms.clear` + the React-render
|
||||
* that resets `group.position` to (0,0,0) — by then `GeometrySystem`
|
||||
* has rebuilt with the new polygon, so the visual lands at the same
|
||||
* world position with no teleport.
|
||||
* `meshY = 0`: `GeometrySystem` parks the slab group at y=0 on rebuild.
|
||||
*/
|
||||
const GRID_STEP = 0.5
|
||||
|
||||
function translatePolygon(
|
||||
polygon: ReadonlyArray<readonly [number, number]>,
|
||||
dx: number,
|
||||
dz: number,
|
||||
): Array<[number, number]> {
|
||||
return polygon.map(([x, z]) => [x + dx, z + dz] as [number, number])
|
||||
}
|
||||
|
||||
export const slabFloorplanMoveTarget: FloorplanMoveTarget<SlabNode> = ({ node }) => {
|
||||
const slabId = node.id as AnyNodeId
|
||||
const originalPolygon = node.polygon.map(([x, z]) => [x, z] as [number, number])
|
||||
const originalHoles = (node.holes ?? []).map((hole) =>
|
||||
hole.map(([x, z]) => [x, z] as [number, number]),
|
||||
)
|
||||
let anchor: [number, number] | null = null
|
||||
let lastDelta: [number, number] = [0, 0]
|
||||
|
||||
const session: FloorplanMoveTargetSession = {
|
||||
affectedIds: [slabId],
|
||||
apply({ planPoint, modifiers }) {
|
||||
const snapped: WallPlanPoint = modifiers.shiftKey
|
||||
? ([planPoint[0], planPoint[1]] as WallPlanPoint)
|
||||
: snapPointToGrid([planPoint[0], planPoint[1]] as WallPlanPoint, GRID_STEP)
|
||||
if (!anchor) {
|
||||
anchor = [snapped[0], snapped[1]]
|
||||
return
|
||||
}
|
||||
const dx = snapped[0] - anchor[0]
|
||||
const dz = snapped[1] - anchor[1]
|
||||
lastDelta = [dx, dz]
|
||||
// Live-drag exception (wiki/architecture/tools.md): write the
|
||||
// delta to BOTH `mesh.position` (direct Three.js mutation) and
|
||||
// `useLiveTransforms.position` (React-bound source of truth).
|
||||
// They MUST match — `ParametricNodeRenderer` re-renders on every
|
||||
// useLiveTransforms change and reconciles `<group position={...}>`,
|
||||
// so a divergence makes the two writes fight every frame.
|
||||
useLiveTransforms.getState().set(slabId, {
|
||||
position: [dx, 0, dz],
|
||||
rotation: 0,
|
||||
})
|
||||
const mesh = sceneRegistry.nodes.get(slabId) as THREE.Object3D | undefined
|
||||
if (mesh) mesh.position.set(dx, 0, dz)
|
||||
},
|
||||
canCommit() {
|
||||
const live = useScene.getState().nodes[slabId] as SlabNode | undefined
|
||||
if (!live || live.type !== 'slab') return false
|
||||
const [dx, dz] = lastDelta
|
||||
if (dx === 0 && dz === 0) return false
|
||||
// Side-effect commit sequence — mirrors `MoveSlabTool.onGridClick`
|
||||
// so the React render that clears `group.position` (via the
|
||||
// useLiveTransforms.clear below) and the `GeometrySystem` rebuild
|
||||
// (via the sync `markDirty`) land in the same paint cycle. Order
|
||||
// matters:
|
||||
// 1. Write the translated polygon to `scene`. The dispatcher's
|
||||
// snapshot-diff right after `canCommit` returns will pick
|
||||
// this up as the single tracked change for undo.
|
||||
// 2. `markDirty` directly — bypasses the rAF-deferred batch in
|
||||
// `updateNodesAction`, so `GeometrySystem` sees the dirty
|
||||
// flag synchronously and can rebuild this frame (without
|
||||
// this the rebuild slides into the next frame and the slab
|
||||
// visually pops to its original position for one paint).
|
||||
// 3. Clear `useLiveTransforms` — `ParametricNodeRenderer` then
|
||||
// re-renders `<group position={[0,0,0]}>` instead of the
|
||||
// live delta. Without the rebuild from step 2 also landing
|
||||
// this frame, the group would render at (0,0,0) over the
|
||||
// *unrebuilt* (still-original) geometry → original-position
|
||||
// blink. With step 2 in place, the rebuild and the React
|
||||
// render commit together → smooth.
|
||||
useScene.getState().updateNodes([
|
||||
{
|
||||
id: slabId,
|
||||
data: {
|
||||
polygon: translatePolygon(originalPolygon, dx, dz),
|
||||
holes: originalHoles.map((h) => translatePolygon(h, dx, dz)),
|
||||
},
|
||||
},
|
||||
])
|
||||
useScene.getState().markDirty(slabId)
|
||||
useLiveTransforms.getState().clear(slabId)
|
||||
return true
|
||||
},
|
||||
}
|
||||
return session
|
||||
}
|
||||
export const slabFloorplanMoveTarget: FloorplanMoveTarget<SlabNode> = ({ node, nodes }) =>
|
||||
createPolygonCentroidMoveTarget({ node, nodes, meshY: 0 })
|
||||
|
||||
@@ -2,12 +2,16 @@
|
||||
|
||||
import {
|
||||
type AnyNodeId,
|
||||
collectAlignmentAnchors,
|
||||
emitter,
|
||||
type FenceNode,
|
||||
type GridEvent,
|
||||
type LevelNode,
|
||||
polygonAnchors,
|
||||
resolveAlignment,
|
||||
type SlabNode,
|
||||
sceneRegistry,
|
||||
useAlignmentGuides,
|
||||
useLiveTransforms,
|
||||
useScene,
|
||||
type WallNode,
|
||||
@@ -40,6 +44,9 @@ import type * as THREE from 'three'
|
||||
* nothing for zundo to record. The single `scene.update` on commit
|
||||
* becomes the single undo step naturally.
|
||||
*/
|
||||
/** Figma-style alignment-snap threshold (meters), matching the other tools. */
|
||||
const ALIGNMENT_THRESHOLD_M = 0.08
|
||||
|
||||
function translatePolygon(
|
||||
polygon: Array<[number, number]>,
|
||||
deltaX: number,
|
||||
@@ -125,6 +132,10 @@ export const MoveSlabTool: React.FC<{ node: SlabNode }> = ({ node }) => {
|
||||
.map((childId) => useScene.getState().nodes[childId as AnyNodeId])
|
||||
.filter((child): child is FenceNode => child?.type === 'fence')
|
||||
|
||||
// Alignment candidates — every other alignable object's anchors,
|
||||
// gathered once (the scene graph is stable during the drag).
|
||||
const alignmentCandidates = collectAlignmentAnchors(useScene.getState().nodes, slabId)
|
||||
|
||||
let wasCommitted = false
|
||||
|
||||
const applyPreview = (deltaX: number, deltaZ: number) => {
|
||||
@@ -170,7 +181,29 @@ export const MoveSlabTool: React.FC<{ node: SlabNode }> = ({ node }) => {
|
||||
const anchor = dragAnchorRef.current ?? [localX, localZ]
|
||||
dragAnchorRef.current = anchor
|
||||
|
||||
applyPreview(localX - anchor[0], localZ - anchor[1])
|
||||
let deltaX = localX - anchor[0]
|
||||
let deltaZ = localZ - anchor[1]
|
||||
|
||||
// Figma-style alignment snap: align the slab's translated polygon
|
||||
// vertices to other objects' anchors; fold the snap into the delta and
|
||||
// publish a guide. Alt bypasses.
|
||||
const bypass = event.nativeEvent?.altKey === true
|
||||
if (!bypass && alignmentCandidates.length > 0) {
|
||||
const result = resolveAlignment({
|
||||
moving: polygonAnchors(slabId, translatePolygon(originalPolygon, deltaX, deltaZ)),
|
||||
candidates: alignmentCandidates,
|
||||
threshold: ALIGNMENT_THRESHOLD_M,
|
||||
})
|
||||
if (result.snap) {
|
||||
deltaX += result.snap.dx
|
||||
deltaZ += result.snap.dz
|
||||
}
|
||||
useAlignmentGuides.getState().set(result.guides)
|
||||
} else {
|
||||
useAlignmentGuides.getState().clear()
|
||||
}
|
||||
|
||||
applyPreview(deltaX, deltaZ)
|
||||
}
|
||||
|
||||
const onGridClick = (event: GridEvent) => {
|
||||
@@ -197,6 +230,7 @@ export const MoveSlabTool: React.FC<{ node: SlabNode }> = ({ node }) => {
|
||||
// GeometrySystem rebuild zeros it on the next frame, by which
|
||||
// point the new geometry is in place — visual stays smooth.
|
||||
useLiveTransforms.getState().clear(slabId)
|
||||
useAlignmentGuides.getState().clear()
|
||||
|
||||
triggerSFX('sfx:item-place')
|
||||
useViewer.getState().setSelection({ selectedIds: [slabId] })
|
||||
@@ -208,6 +242,7 @@ export const MoveSlabTool: React.FC<{ node: SlabNode }> = ({ node }) => {
|
||||
// No scene state to roll back — we never wrote anything. Just
|
||||
// restore the mesh visual.
|
||||
clearPreview()
|
||||
useAlignmentGuides.getState().clear()
|
||||
useViewer.getState().setSelection({ selectedIds: [slabId] })
|
||||
markToolCancelConsumed()
|
||||
exitMoveMode()
|
||||
@@ -218,6 +253,7 @@ export const MoveSlabTool: React.FC<{ node: SlabNode }> = ({ node }) => {
|
||||
emitter.on('tool:cancel', onCancel)
|
||||
|
||||
return () => {
|
||||
useAlignmentGuides.getState().clear()
|
||||
if (!wasCommitted) {
|
||||
clearPreview()
|
||||
} else {
|
||||
|
||||
@@ -1,6 +1,14 @@
|
||||
'use client'
|
||||
|
||||
import { emitter, type GridEvent, type LevelNode, useScene } from '@pascal-app/core'
|
||||
import {
|
||||
collectAlignmentAnchors,
|
||||
emitter,
|
||||
type GridEvent,
|
||||
type LevelNode,
|
||||
resolveAlignment,
|
||||
useAlignmentGuides,
|
||||
useScene,
|
||||
} from '@pascal-app/core'
|
||||
import {
|
||||
CursorSphere,
|
||||
EDITOR_LAYER,
|
||||
@@ -26,6 +34,8 @@ import { SlabNode } from './schema'
|
||||
*/
|
||||
|
||||
const Y_OFFSET = 0.02
|
||||
/** Figma-style alignment-snap threshold (meters), matching the move tools. */
|
||||
const ALIGNMENT_THRESHOLD_M = 0.08
|
||||
|
||||
function calculateSnapPoint(
|
||||
lastPoint: [number, number],
|
||||
@@ -80,21 +90,66 @@ export const SlabTool: React.FC = () => {
|
||||
// isn't built with a stale preset's parameters. Unmount-only.
|
||||
useEffect(() => () => useEditor.getState().setToolDefaults('slab', null), [])
|
||||
|
||||
// Clear alignment guides on unmount ONLY. The main drawing effect re-runs
|
||||
// on every cursor move (cursorPosition is in its deps), so clearing guides
|
||||
// in its cleanup would wipe the guide the instant after each move sets it.
|
||||
useEffect(() => () => useAlignmentGuides.getState().clear(), [])
|
||||
|
||||
useEffect(() => {
|
||||
if (!currentLevelId) return
|
||||
|
||||
// Alignment candidates — anchors of every OTHER alignable object. The
|
||||
// slab's own in-progress vertices are intentionally excluded (no
|
||||
// self-alignment while drawing).
|
||||
const alignmentCandidates = collectAlignmentAnchors(useScene.getState().nodes, '')
|
||||
// Snap the drafted vertex onto another object's nearest real anchor and
|
||||
// publish the guide. The probe is the RAW cursor, NOT the 0.5m-grid-snapped
|
||||
// point: resolving against the grid point would only ever catch anchors
|
||||
// that happen to sit on a grid line, so off-grid items (furniture, angled
|
||||
// walls) would never surface a guide. The matched axis locks exactly to the
|
||||
// candidate's coordinate; the other axis keeps its grid/ortho snap. Alt
|
||||
// bypasses.
|
||||
const alignPoint = (
|
||||
fallback: [number, number],
|
||||
raw: [number, number],
|
||||
bypass: boolean,
|
||||
): [number, number] => {
|
||||
if (bypass || alignmentCandidates.length === 0) {
|
||||
useAlignmentGuides.getState().clear()
|
||||
return fallback
|
||||
}
|
||||
const ar = resolveAlignment({
|
||||
moving: [{ nodeId: '__slab-draft__', kind: 'corner', x: raw[0], z: raw[1] }],
|
||||
candidates: alignmentCandidates,
|
||||
threshold: ALIGNMENT_THRESHOLD_M,
|
||||
})
|
||||
if (ar.guides.length === 0) {
|
||||
useAlignmentGuides.getState().clear()
|
||||
return fallback
|
||||
}
|
||||
useAlignmentGuides.getState().set(ar.guides)
|
||||
let [x, z] = fallback
|
||||
for (const guide of ar.guides) {
|
||||
if (guide.axis === 'x') x = guide.coord
|
||||
else z = guide.coord
|
||||
}
|
||||
return [x, z]
|
||||
}
|
||||
|
||||
const onGridMove = (event: GridEvent) => {
|
||||
if (!cursorRef.current) return
|
||||
const gridX = Math.round(event.localPosition[0] * 2) / 2
|
||||
const gridZ = Math.round(event.localPosition[2] * 2) / 2
|
||||
const rawPoint: [number, number] = [event.localPosition[0], event.localPosition[2]]
|
||||
const gridX = Math.round(rawPoint[0] * 2) / 2
|
||||
const gridZ = Math.round(rawPoint[1] * 2) / 2
|
||||
const gridPosition: [number, number] = [gridX, gridZ]
|
||||
setCursorPosition(gridPosition)
|
||||
setLevelY(event.localPosition[1])
|
||||
const lastPoint = points[points.length - 1]
|
||||
const displayPoint =
|
||||
const orthoPoint =
|
||||
shiftPressed.current || !lastPoint
|
||||
? gridPosition
|
||||
: calculateSnapPoint(lastPoint, gridPosition)
|
||||
const displayPoint = alignPoint(orthoPoint, rawPoint, event.nativeEvent?.altKey === true)
|
||||
setSnappedCursorPosition(displayPoint)
|
||||
if (
|
||||
points.length > 0 &&
|
||||
@@ -121,6 +176,7 @@ export const SlabTool: React.FC = () => {
|
||||
const slabId = commitSlabDrawing(currentLevelId, points)
|
||||
setSelection({ selectedIds: [slabId] })
|
||||
setPoints([])
|
||||
useAlignmentGuides.getState().clear()
|
||||
} else {
|
||||
setPoints([...points, clickPoint])
|
||||
}
|
||||
@@ -132,12 +188,14 @@ export const SlabTool: React.FC = () => {
|
||||
const slabId = commitSlabDrawing(currentLevelId, points)
|
||||
setSelection({ selectedIds: [slabId] })
|
||||
setPoints([])
|
||||
useAlignmentGuides.getState().clear()
|
||||
}
|
||||
}
|
||||
|
||||
const onCancel = () => {
|
||||
if (points.length > 0) markToolCancelConsumed()
|
||||
setPoints([])
|
||||
useAlignmentGuides.getState().clear()
|
||||
}
|
||||
|
||||
const onKeyDown = (e: KeyboardEvent) => {
|
||||
|
||||
Reference in New Issue
Block a user