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,14 +1,17 @@
|
||||
import {
|
||||
type AnyNodeId,
|
||||
collectAlignmentAnchors,
|
||||
emitter,
|
||||
type FenceNode,
|
||||
type GridEvent,
|
||||
type LevelNode,
|
||||
type RoofNode,
|
||||
type RoofSegmentNode,
|
||||
resolveAlignment,
|
||||
type StairNode,
|
||||
type StairSegmentNode,
|
||||
sceneRegistry,
|
||||
useAlignmentGuides,
|
||||
useLiveTransforms,
|
||||
useScene,
|
||||
type WallNode,
|
||||
@@ -25,6 +28,9 @@ import { useViewer } from '@pascal-app/viewer'
|
||||
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||
import * as THREE from 'three'
|
||||
|
||||
/** Figma-style alignment-snap threshold (meters), matching the other tools. */
|
||||
const ALIGNMENT_THRESHOLD_M = 0.08
|
||||
|
||||
export const MoveRoofTool: React.FC<{
|
||||
node: RoofNode | RoofSegmentNode | StairNode | StairSegmentNode
|
||||
}> = ({ node: movingNode }) => {
|
||||
@@ -158,6 +164,29 @@ export const MoveRoofTool: React.FC<{
|
||||
const buildingId = useViewer.getState().selection.buildingId
|
||||
const buildingObj = buildingId ? sceneRegistry.nodes.get(buildingId as AnyNodeId) : null
|
||||
|
||||
// Alignment for top-level stair / roof only. Segments live in parent-local
|
||||
// space (a different frame from the building-local candidate pool / guide
|
||||
// layer), so we leave them on the plain grid+corner snap. The moving node
|
||||
// is aligned by its ORIGIN point (how this tool positions it), snapped to
|
||||
// any other alignable object's anchors.
|
||||
const alignTopLevel = movingNode.type === 'stair' || movingNode.type === 'roof'
|
||||
const alignmentCandidates = alignTopLevel
|
||||
? collectAlignmentAnchors(useScene.getState().nodes, movingNode.id)
|
||||
: []
|
||||
const alignLocalPoint = (lx: number, lz: number, bypass: boolean): [number, number] => {
|
||||
if (!alignTopLevel || bypass || alignmentCandidates.length === 0) {
|
||||
useAlignmentGuides.getState().clear()
|
||||
return [lx, lz]
|
||||
}
|
||||
const ar = resolveAlignment({
|
||||
moving: [{ nodeId: movingNode.id, kind: 'corner', x: lx, z: lz }],
|
||||
candidates: alignmentCandidates,
|
||||
threshold: ALIGNMENT_THRESHOLD_M,
|
||||
})
|
||||
useAlignmentGuides.getState().set(ar.guides)
|
||||
return ar.snap ? [lx + ar.snap.dx, lz + ar.snap.dz] : [lx, lz]
|
||||
}
|
||||
|
||||
const localToWorldPoint = (localPoint: WallPlanPoint, y: number): [number, number, number] => {
|
||||
if (buildingObj) {
|
||||
const worldPoint = buildingObj.localToWorld(
|
||||
@@ -213,7 +242,15 @@ export const MoveRoofTool: React.FC<{
|
||||
walls: levelWalls,
|
||||
fences: levelFences,
|
||||
})
|
||||
const [gridX, , gridZ] = localToWorldPoint(snappedLocal, y)
|
||||
// Layer alignment snap on top (top-level stair/roof). Recompute the
|
||||
// world point from the aligned building-local point so it stays correct
|
||||
// under building rotation.
|
||||
const [lx, lz] = alignLocalPoint(
|
||||
snappedLocal[0],
|
||||
snappedLocal[1],
|
||||
event.nativeEvent?.altKey === true,
|
||||
)
|
||||
const [gridX, , gridZ] = localToWorldPoint([lx, lz], y)
|
||||
|
||||
if (
|
||||
previousGridPosRef.current &&
|
||||
@@ -223,7 +260,6 @@ export const MoveRoofTool: React.FC<{
|
||||
}
|
||||
|
||||
previousGridPosRef.current = [gridX, gridZ]
|
||||
const [lx, lz] = snappedLocal
|
||||
setCursorWorldPos([lx, event.localPosition[1], lz])
|
||||
|
||||
const [localX, localZ] = computeLocal(gridX, gridZ, y, lx, lz)
|
||||
@@ -249,11 +285,16 @@ export const MoveRoofTool: React.FC<{
|
||||
walls: levelWalls,
|
||||
fences: levelFences,
|
||||
})
|
||||
const [gridX, , gridZ] = localToWorldPoint(snappedLocal, y)
|
||||
const [lx, lz] = snappedLocal
|
||||
const [lx, lz] = alignLocalPoint(
|
||||
snappedLocal[0],
|
||||
snappedLocal[1],
|
||||
event.nativeEvent?.altKey === true,
|
||||
)
|
||||
const [gridX, , gridZ] = localToWorldPoint([lx, lz], y)
|
||||
|
||||
const [localX, localZ] = computeLocal(gridX, gridZ, y, lx, lz)
|
||||
|
||||
useAlignmentGuides.getState().clear()
|
||||
wasCommitted = true
|
||||
|
||||
// The store still holds the original values (we didn't update during drag).
|
||||
@@ -286,6 +327,7 @@ export const MoveRoofTool: React.FC<{
|
||||
const onCancel = () => {
|
||||
wasCancelled = true
|
||||
useLiveTransforms.getState().clear(movingNode.id)
|
||||
useAlignmentGuides.getState().clear()
|
||||
if (isNew) {
|
||||
useScene.getState().deleteNode(movingNode.id)
|
||||
} else {
|
||||
@@ -340,8 +382,9 @@ export const MoveRoofTool: React.FC<{
|
||||
if (segmentWrapperGroup) segmentWrapperGroup.visible = false
|
||||
if (mergedRoofMesh) mergedRoofMesh.visible = true
|
||||
|
||||
// Clear ephemeral live transform
|
||||
// Clear ephemeral live transform + any alignment guides
|
||||
useLiveTransforms.getState().clear(movingNode.id)
|
||||
useAlignmentGuides.getState().clear()
|
||||
|
||||
// Skip restore when the 2D floor-plan overlay claimed teardown
|
||||
// ownership — same contract `FloorplanRegistryMoveOverlay` uses to
|
||||
|
||||
@@ -0,0 +1,143 @@
|
||||
import {
|
||||
type AnyNode,
|
||||
type AnyNodeId,
|
||||
collectAlignmentAnchors,
|
||||
type FloorplanMoveTargetSession,
|
||||
polygonAnchors,
|
||||
resolveAlignment,
|
||||
sceneRegistry,
|
||||
useAlignmentGuides,
|
||||
useLiveTransforms,
|
||||
useScene,
|
||||
} from '@pascal-app/core'
|
||||
import { snapPointToGrid, type WallPlanPoint } from '@pascal-app/editor'
|
||||
import type * as THREE from 'three'
|
||||
|
||||
/**
|
||||
* Shared 2D floor-plan move for polygon-based kinds (slab / ceiling / zone).
|
||||
*
|
||||
* **Pivot semantics.** The move uses the polygon's **centroid** as the pivot:
|
||||
* the centroid snaps to the (grid-snapped, then Figma-aligned) cursor — the
|
||||
* same way a regular item's origin snaps to the cursor in both 3D and 2D.
|
||||
* This replaces the old grab-relative delta ("drag from wherever you first
|
||||
* touched"), so polygon kinds move consistently with every other item.
|
||||
*
|
||||
* **Why a delta in `useLiveTransforms`** (see `wiki/architecture/tools.md`):
|
||||
* polygon kinds carry their position in their vertices, not a `position`
|
||||
* field. The live preview translates the rendered `<group>` by the delta
|
||||
* (`ParametricNodeRenderer` consumes `useLiveTransforms.position` as the
|
||||
* group position) so the SVG follows the EXACT snapped result with no CSG
|
||||
* rebuild per tick. On commit we write the translated polygon once. Because
|
||||
* the live delta and the committed polygon are derived from the same
|
||||
* `lastDelta`, the visual and the commit always agree.
|
||||
*
|
||||
* `meshY` mirrors the value the kind's system sets on rebuild (slab: 0;
|
||||
* ceiling: `height − 0.01`) so the 3D mesh doesn't teleport vertically in a
|
||||
* split view during the drag.
|
||||
*/
|
||||
const GRID_STEP = 0.5
|
||||
|
||||
/** Figma-style alignment threshold (meters) — parity with the 3D move tools. */
|
||||
const ALIGNMENT_THRESHOLD_M = 0.08
|
||||
|
||||
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])
|
||||
}
|
||||
|
||||
/** Average of the polygon's vertices — matches the 3D `MoveSlabTool` pivot. */
|
||||
function polygonCentroid(polygon: ReadonlyArray<readonly [number, number]>): [number, number] {
|
||||
if (polygon.length === 0) return [0, 0]
|
||||
let sumX = 0
|
||||
let sumZ = 0
|
||||
for (const [x, z] of polygon) {
|
||||
sumX += x
|
||||
sumZ += z
|
||||
}
|
||||
return [sumX / polygon.length, sumZ / polygon.length]
|
||||
}
|
||||
|
||||
export function createPolygonCentroidMoveTarget(args: {
|
||||
node: {
|
||||
id: string
|
||||
type: string
|
||||
polygon: Array<[number, number]>
|
||||
holes?: Array<Array<[number, number]>>
|
||||
}
|
||||
nodes: Record<AnyNodeId, AnyNode>
|
||||
/** 3D mesh Y the kind's system parks the group at on rebuild. */
|
||||
meshY: number
|
||||
}): FloorplanMoveTargetSession {
|
||||
const { node, nodes, meshY } = args
|
||||
const id = node.id as AnyNodeId
|
||||
const typeGuard = node.type
|
||||
const originalPolygon = node.polygon.map(([x, z]) => [x, z] as [number, number])
|
||||
const hasHoles = Array.isArray(node.holes)
|
||||
const originalHoles = (node.holes ?? []).map((hole) =>
|
||||
hole.map(([x, z]) => [x, z] as [number, number]),
|
||||
)
|
||||
const originalCenter = polygonCentroid(originalPolygon)
|
||||
// Alignment candidates gathered once — the scene is stable during the drag.
|
||||
const candidates = collectAlignmentAnchors(nodes, id)
|
||||
let lastDelta: [number, number] = [0, 0]
|
||||
|
||||
return {
|
||||
affectedIds: [id],
|
||||
apply({ planPoint, modifiers }) {
|
||||
// Centroid → snapped cursor. Grid-snap the target centroid (Shift
|
||||
// drops the grid snap), then layer Figma alignment on the translated
|
||||
// polygon's vertices and fold its snap into the delta. Alt bypasses.
|
||||
const target: WallPlanPoint = modifiers.shiftKey
|
||||
? ([planPoint[0], planPoint[1]] as WallPlanPoint)
|
||||
: snapPointToGrid([planPoint[0], planPoint[1]] as WallPlanPoint, GRID_STEP)
|
||||
let dx = target[0] - originalCenter[0]
|
||||
let dz = target[1] - originalCenter[1]
|
||||
|
||||
if (!modifiers.altKey && candidates.length > 0) {
|
||||
const result = resolveAlignment({
|
||||
moving: polygonAnchors(id, translatePolygon(originalPolygon, dx, dz)),
|
||||
candidates,
|
||||
threshold: ALIGNMENT_THRESHOLD_M,
|
||||
})
|
||||
if (result.snap) {
|
||||
dx += result.snap.dx
|
||||
dz += result.snap.dz
|
||||
}
|
||||
useAlignmentGuides.getState().set(result.guides)
|
||||
} else {
|
||||
useAlignmentGuides.getState().clear()
|
||||
}
|
||||
|
||||
lastDelta = [dx, dz]
|
||||
// Live-drag exception: write the delta to BOTH `useLiveTransforms`
|
||||
// (React source of truth) and the mesh (direct Three.js) so they don't
|
||||
// fight per frame.
|
||||
useLiveTransforms.getState().set(id, { position: [dx, 0, dz], rotation: 0 })
|
||||
const mesh = sceneRegistry.nodes.get(id) as THREE.Object3D | undefined
|
||||
if (mesh) mesh.position.set(dx, meshY, dz)
|
||||
},
|
||||
canCommit() {
|
||||
const live = useScene.getState().nodes[id] as { type?: string } | undefined
|
||||
if (!live || live.type !== typeGuard) return false
|
||||
const [dx, dz] = lastDelta
|
||||
if (dx === 0 && dz === 0) return false
|
||||
// Sync commit: scene write → direct markDirty → clear live transform,
|
||||
// so the React render and the kind's geometry rebuild land in the same
|
||||
// paint (no original-position blink). Only write `holes` for kinds that
|
||||
// have them (zone has none).
|
||||
const data: { polygon: Array<[number, number]>; holes?: Array<Array<[number, number]>> } = {
|
||||
polygon: translatePolygon(originalPolygon, dx, dz),
|
||||
}
|
||||
if (hasHoles) {
|
||||
data.holes = originalHoles.map((h) => translatePolygon(h, dx, dz))
|
||||
}
|
||||
useScene.getState().updateNodes([{ id, data }])
|
||||
useScene.getState().markDirty(id)
|
||||
useLiveTransforms.getState().clear(id)
|
||||
return true
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,11 @@
|
||||
import { type AnyNode, type AnyNodeId, isCurvedWall, type WallNode } from '@pascal-app/core'
|
||||
import {
|
||||
type AnyNode,
|
||||
type AnyNodeId,
|
||||
getScaledDimensions,
|
||||
type ItemNode,
|
||||
isCurvedWall,
|
||||
type WallNode,
|
||||
} from '@pascal-app/core'
|
||||
|
||||
/**
|
||||
* Shared helpers for the kinds whose 2D move snaps onto a wall in plan
|
||||
@@ -127,3 +134,83 @@ export function findClosestWallInPlan(
|
||||
|
||||
return best
|
||||
}
|
||||
|
||||
/** Figma-style along-wall alignment threshold (meters) — parity with the
|
||||
* XZ placement / move threshold. */
|
||||
const ALONG_WALL_ALIGN_THRESHOLD_M = 0.08
|
||||
|
||||
/** The along-wall span of a wall-hosted node (door / window / wall item):
|
||||
* its centre `localX` and half-width. `null` for kinds with no along-wall
|
||||
* footprint. */
|
||||
function wallAttachmentSpan(node: AnyNode): { center: number; half: number } | null {
|
||||
if (node.type === 'door' || node.type === 'window') {
|
||||
const n = node as { position: [number, number, number]; width: number }
|
||||
return { center: n.position[0], half: n.width / 2 }
|
||||
}
|
||||
if (node.type === 'item') {
|
||||
const item = node as ItemNode
|
||||
const attachTo = item.asset.attachTo
|
||||
if (attachTo !== 'wall' && attachTo !== 'wall-side') return null
|
||||
const [w] = getScaledDimensions(item)
|
||||
return { center: item.position[0], half: w / 2 }
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/**
|
||||
* Figma-style alignment for a wall-hosted opening / item, along the wall
|
||||
* axis. Snaps the moving node's edges (or centre) to other attachments'
|
||||
* edges/centres on the same wall, plus the wall ends. Edge-to-edge first,
|
||||
* so two doors line up flush.
|
||||
*
|
||||
* Returns the adjusted `localX` when a neighbour stop is within threshold,
|
||||
* or `null` when nothing aligns — callers treat `null` as "no alignment,
|
||||
* fall back to the grid snap". This lets along-wall alignment COMPETE with
|
||||
* the 0.5m grid (openings have arbitrary widths rarely on the grid, so
|
||||
* layering on top of the grid snap would almost never trigger).
|
||||
*
|
||||
* Snap-only for v1 — no guide is published (the floor-plan guide layer
|
||||
* renders XZ guides; an along-wall guide on a diagonal wall needs extra
|
||||
* projection work, deferred).
|
||||
*/
|
||||
export function snapLocalXToNeighbors(args: {
|
||||
wall: WallNode
|
||||
localX: number
|
||||
width: number
|
||||
selfId: AnyNodeId
|
||||
nodes: Record<AnyNodeId, AnyNode>
|
||||
threshold?: number
|
||||
}): number | null {
|
||||
const { wall, localX, width, selfId, nodes, threshold = ALONG_WALL_ALIGN_THRESHOLD_M } = args
|
||||
const half = width / 2
|
||||
const wallLength = Math.hypot(wall.end[0] - wall.start[0], wall.end[1] - wall.start[1])
|
||||
|
||||
// Candidate stops along the wall: both ends + every other attachment's
|
||||
// edges and centre.
|
||||
const candidateStops: number[] = [0, wallLength]
|
||||
for (const node of Object.values(nodes)) {
|
||||
if (!node || node.id === selfId) continue
|
||||
if ((node as { parentId?: string }).parentId !== wall.id) continue
|
||||
const span = wallAttachmentSpan(node)
|
||||
if (!span) continue
|
||||
candidateStops.push(span.center - span.half, span.center, span.center + span.half)
|
||||
}
|
||||
|
||||
// Moving stops: our two edges (edge-to-edge alignment) + centre.
|
||||
const movingStops = [localX - half, localX, localX + half]
|
||||
|
||||
let bestDelta: number | null = null
|
||||
let bestAbs = threshold
|
||||
for (const ms of movingStops) {
|
||||
for (const cs of candidateStops) {
|
||||
const d = cs - ms
|
||||
const ad = Math.abs(d)
|
||||
if (ad <= bestAbs && (bestDelta === null || ad < bestAbs)) {
|
||||
bestAbs = ad
|
||||
bestDelta = d
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return bestDelta === null ? null : localX + bestDelta
|
||||
}
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
import {
|
||||
type AlignmentAnchor,
|
||||
resolveAlignment,
|
||||
useAlignmentGuides,
|
||||
type WallNode,
|
||||
} from '@pascal-app/core'
|
||||
import { snapToHalf } from '@pascal-app/editor'
|
||||
|
||||
/** Figma-style alignment-snap threshold (meters), matching the move tools. */
|
||||
export const WALL_OPENING_ALIGNMENT_THRESHOLD_M = 0.08
|
||||
/**
|
||||
* A wall opening (door / window) can only slide ALONG its host wall, so it can
|
||||
* only satisfy an x- or z-guide when the wall runs along that axis. Below this
|
||||
* |component| (≈ wall within 60° of the axis) the along-wall move needed to
|
||||
* reach the guide blows up, so we skip it rather than jump the opening across
|
||||
* the wall.
|
||||
*/
|
||||
const MIN_AXIS_COMPONENT = 0.5
|
||||
|
||||
/**
|
||||
* Resolve a wall opening's along-wall position with Figma-style alignment to
|
||||
* other objects, publishing the matching guide as a side effect.
|
||||
*
|
||||
* The probe is the RAW cursor position on the wall (not the 0.5m snap) so
|
||||
* off-grid anchors are caught; we then keep only the guide on an axis the wall
|
||||
* runs along and map it to the along-wall coordinate that lands the opening on
|
||||
* it. Falls back to the half-metre snap when nothing aligns, and clears the
|
||||
* guide on bypass / no-match. Returns the localX to use (X-clamped to the wall
|
||||
* given `width`). `bypass` (Alt) disables alignment.
|
||||
*/
|
||||
export function resolveWallSlideAlignment(args: {
|
||||
wallNode: WallNode
|
||||
rawLocalX: number
|
||||
width: number
|
||||
candidates: readonly AlignmentAnchor[]
|
||||
bypass: boolean
|
||||
}): number {
|
||||
const { wallNode, rawLocalX, width, candidates, bypass } = args
|
||||
const base = snapToHalf(rawLocalX)
|
||||
if (bypass || candidates.length === 0) {
|
||||
useAlignmentGuides.getState().clear()
|
||||
return base
|
||||
}
|
||||
|
||||
const dx = wallNode.end[0] - wallNode.start[0]
|
||||
const dz = wallNode.end[1] - wallNode.start[1]
|
||||
const wallLength = Math.sqrt(dx * dx + dz * dz)
|
||||
if (wallLength < 1e-6) {
|
||||
useAlignmentGuides.getState().clear()
|
||||
return base
|
||||
}
|
||||
const cos = dx / wallLength
|
||||
const sin = dz / wallLength
|
||||
const clampX = (localX: number) => Math.max(width / 2, Math.min(wallLength - width / 2, localX))
|
||||
|
||||
const probe = resolveAlignment({
|
||||
moving: [
|
||||
{
|
||||
nodeId: '__wall-opening-draft__',
|
||||
kind: 'corner',
|
||||
x: wallNode.start[0] + rawLocalX * cos,
|
||||
z: wallNode.start[1] + rawLocalX * sin,
|
||||
},
|
||||
],
|
||||
candidates,
|
||||
threshold: WALL_OPENING_ALIGNMENT_THRESHOLD_M,
|
||||
})
|
||||
|
||||
// Keep only a guide on an axis the wall runs along, mapped to the along-wall
|
||||
// position that satisfies it; pick the nearest such.
|
||||
let bestLocalX: number | null = null
|
||||
let bestDelta = Number.POSITIVE_INFINITY
|
||||
for (const guide of probe.guides) {
|
||||
const denom = guide.axis === 'x' ? cos : sin
|
||||
if (Math.abs(denom) < MIN_AXIS_COMPONENT) continue
|
||||
const origin = guide.axis === 'x' ? wallNode.start[0] : wallNode.start[1]
|
||||
const targetLocalX = (guide.coord - origin) / denom
|
||||
const delta = Math.abs(targetLocalX - rawLocalX)
|
||||
if (delta < bestDelta) {
|
||||
bestDelta = delta
|
||||
bestLocalX = targetLocalX
|
||||
}
|
||||
}
|
||||
if (bestLocalX === null) {
|
||||
useAlignmentGuides.getState().clear()
|
||||
return base
|
||||
}
|
||||
|
||||
const clampedX = clampX(bestLocalX)
|
||||
// Re-resolve from where the opening actually lands (post-clamp) so the
|
||||
// published guide connects to the opening, not the raw cursor.
|
||||
const published = resolveAlignment({
|
||||
moving: [
|
||||
{
|
||||
nodeId: '__wall-opening-draft__',
|
||||
kind: 'corner',
|
||||
x: wallNode.start[0] + clampedX * cos,
|
||||
z: wallNode.start[1] + clampedX * sin,
|
||||
},
|
||||
],
|
||||
candidates,
|
||||
threshold: WALL_OPENING_ALIGNMENT_THRESHOLD_M,
|
||||
})
|
||||
if (published.guides.length === 0) {
|
||||
useAlignmentGuides.getState().clear()
|
||||
} else {
|
||||
useAlignmentGuides.getState().set(published.guides)
|
||||
}
|
||||
return clampedX
|
||||
}
|
||||
Reference in New Issue
Block a user