Skip to content

Commit 46f94b9

Browse files
sudhir9297claudeopen-pascal
authored
editor: alignment guides + floor-plan move/placement parity (pascalorg#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 pascalorg#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>
1 parent 86db5de commit 46f94b9

84 files changed

Lines changed: 4401 additions & 1023 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

apps/editor/components/scene-loader.tsx

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -102,7 +102,7 @@ export function SceneLoader({ initialScene, meta }: SceneLoaderProps) {
102102
const handleLoad = useCallback(async () => initialScene, [initialScene])
103103

104104
const handleSave = useCallback(
105-
async (graph: SceneGraph) => {
105+
async (graph: SceneGraph, options?: { keepalive?: boolean }) => {
106106
const graphJson = sceneGraphSignature(graph)
107107
const isRecentRemoteApply = Date.now() < suppressRemoteSaveUntilRef.current
108108
if (lastRemoteGraphJsonRef.current === graphJson) {
@@ -120,6 +120,11 @@ export function SceneLoader({ initialScene, meta }: SceneLoaderProps) {
120120
'If-Match': String(versionRef.current),
121121
},
122122
body: JSON.stringify({ name: meta.name, graph }),
123+
// `keepalive` lets the request outlive a page unload (the autosave
124+
// flush on refresh/close). Browsers cap keepalive bodies at 64KB, so
125+
// only the unload flush opts in — normal debounced saves omit it and
126+
// can carry arbitrarily large scenes.
127+
keepalive: options?.keepalive,
123128
})
124129

125130
if (response.status === 409) {

packages/core/src/registry/handles.ts

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,12 @@ export type EditorApi = {
4444
* or curving state so the move starts from a clean slate.
4545
*/
4646
engageMove: (node: AnyNode) => void
47+
/**
48+
* Like {@link engageMove}, but for a press-drag gizmo: the move commits on
49+
* pointer-release instead of waiting for a click, so the on-canvas move cross
50+
* behaves as press-drag-release while still showing the placement preview.
51+
*/
52+
engageMoveDrag: (node: AnyNode) => void
4753
/**
4854
* Engage endpoint drag for kinds that own start / end anchors (walls,
4955
* fences). No-ops for kinds without endpoints.
@@ -281,14 +287,25 @@ export type TapActionHandle<N = any> = {
281287
* trigger the desired action.
282288
*/
283289
onActivate: (node: N, scene: SceneApi, editor: EditorApi) => void
284-
/** Visual override; defaults to the standard chevron arrow. */
285-
shape?: 'arrow' | 'corner-picker'
290+
/**
291+
* Visual override; defaults to the standard chevron arrow. `'move-cross'`
292+
* reuses the 4-way move cross — a tap-to-engage grip that hands the node to
293+
* its move tool (via `onActivate`) instead of running the generic translate
294+
* drag, so the move tool's own preview / ticker feedback shows up.
295+
*/
296+
shape?: 'arrow' | 'corner-picker' | 'move-cross'
286297
/**
287298
* Required when `shape: 'corner-picker'` — controls the dashed leader's
288299
* vertical extent. Pure callback so the descriptor doesn't need to
289300
* import 3D libs.
290301
*/
291302
nodeHeight?: (node: N) => number
303+
/**
304+
* `shape: 'move-cross'` only — tilts the flat cross to lie in the right
305+
* plane. `'horizontal'` (default) leaves it flat on the floor; `'node-normal'`
306+
* stands it up against the node's facing plane (a wall face).
307+
*/
308+
plane?: 'horizontal' | 'node-normal'
292309
portal?: HandlePortal
293310
cursor?: Cursor
294311
}

packages/core/src/schema/nodes/roof.ts

Lines changed: 4 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -81,25 +81,9 @@ export function getEffectiveRoofSurfaceMaterial(
8181
}
8282
}
8383

84-
if (role === 'edge') {
85-
if (node.wallMaterial !== undefined || typeof node.wallMaterialPreset === 'string') {
86-
return {
87-
material: node.wallMaterial,
88-
materialPreset:
89-
typeof node.wallMaterialPreset === 'string' ? node.wallMaterialPreset : undefined,
90-
}
91-
}
92-
}
93-
94-
if (role === 'wall') {
95-
if (node.edgeMaterial !== undefined || typeof node.edgeMaterialPreset === 'string') {
96-
return {
97-
material: node.edgeMaterial,
98-
materialPreset:
99-
typeof node.edgeMaterialPreset === 'string' ? node.edgeMaterialPreset : undefined,
100-
}
101-
}
102-
}
103-
84+
// No cross-role fallback: an unset role resolves only to the legacy
85+
// catch-all (which covers all three roles for back-compat) and otherwise
86+
// to the caller's theme default. Painting one surface must never bleed
87+
// onto the others.
10488
return getLegacyRoofSurfaceMaterial(node)
10589
}
Lines changed: 217 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,217 @@
1+
import { beforeEach, describe, expect, test } from 'bun:test'
2+
import { z } from 'zod'
3+
import { nodeRegistry, registerNode } from '../registry'
4+
import type { AnyNodeDefinition } from '../registry/types'
5+
import type { AnyNode } from '../schema/types'
6+
import {
7+
collectAlignmentAnchors,
8+
footprintAABB,
9+
footprintAABBFrom,
10+
movingFootprintAnchors,
11+
polygonAnchors,
12+
wallSegmentAnchors,
13+
} from './alignment-anchors'
14+
15+
// Minimal floor-placed def whose footprint reads `dimensions` / `rotation`
16+
// straight off the node, so tests can drive the AABB math directly.
17+
function floorPlacedDef(kind: string, applies?: (n: AnyNode) => boolean): AnyNodeDefinition {
18+
return {
19+
kind,
20+
schemaVersion: 1,
21+
schema: z.object({ type: z.literal(kind) }) as any,
22+
category: 'utility',
23+
defaults: () => ({}) as any,
24+
capabilities: {
25+
floorPlaced: {
26+
footprint: (n: AnyNode) => ({
27+
dimensions: (n as { dimensions?: [number, number, number] }).dimensions ?? [1, 1, 1],
28+
rotation: (n as { rotation?: [number, number, number] }).rotation ?? [0, 0, 0],
29+
}),
30+
...(applies ? { applies } : {}),
31+
},
32+
},
33+
renderer: { kind: 'parametric', module: async () => ({ default: () => null }) },
34+
} as AnyNodeDefinition
35+
}
36+
37+
function plainDef(kind: string): AnyNodeDefinition {
38+
return {
39+
kind,
40+
schemaVersion: 1,
41+
schema: z.object({ type: z.literal(kind) }) as any,
42+
category: 'utility',
43+
defaults: () => ({}) as any,
44+
capabilities: {},
45+
renderer: { kind: 'parametric', module: async () => ({ default: () => null }) },
46+
} as AnyNodeDefinition
47+
}
48+
49+
const node = (over: Record<string, unknown>): AnyNode => over as unknown as AnyNode
50+
51+
describe('footprintAABBFrom', () => {
52+
test('unrotated box is centred at position', () => {
53+
const aabb = footprintAABBFrom([10, 0, 20], [2, 1, 4], 0)
54+
expect(aabb).toEqual({ minX: 9, minZ: 18, maxX: 11, maxZ: 22 })
55+
})
56+
57+
test('90° rotation swaps width and depth extents', () => {
58+
const aabb = footprintAABBFrom([0, 0, 0], [2, 1, 4], Math.PI / 2)
59+
expect(aabb.minX).toBeCloseTo(-2, 10)
60+
expect(aabb.maxX).toBeCloseTo(2, 10)
61+
expect(aabb.minZ).toBeCloseTo(-1, 10)
62+
expect(aabb.maxZ).toBeCloseTo(1, 10)
63+
})
64+
})
65+
66+
describe('footprintAABB', () => {
67+
beforeEach(() => nodeRegistry._reset())
68+
69+
test('reads dimensions + rotation from a floor-placed kind', () => {
70+
registerNode(floorPlacedDef('box'))
71+
const aabb = footprintAABB(
72+
node({ id: 'b1', type: 'box', position: [10, 0, 20], dimensions: [2, 1, 4] }),
73+
)
74+
expect(aabb).toEqual({ minX: 9, minZ: 18, maxX: 11, maxZ: 22 })
75+
})
76+
77+
test('returns null for a kind without a footprint', () => {
78+
registerNode(plainDef('wall'))
79+
expect(footprintAABB(node({ id: 'w1', type: 'wall', position: [0, 0, 0] }))).toBeNull()
80+
})
81+
82+
test('derives an elevator footprint from its width / depth (no floorPlaced needed)', () => {
83+
const aabb = footprintAABB(
84+
node({ id: 'e1', type: 'elevator', position: [10, 0, 20], width: 2, depth: 4, rotation: 0 }),
85+
)
86+
expect(aabb).toEqual({ minX: 9, minZ: 18, maxX: 11, maxZ: 22 })
87+
})
88+
89+
test('returns null when the kind predicate excludes the node', () => {
90+
registerNode(floorPlacedDef('lamp', (n) => !(n as { attached?: boolean }).attached))
91+
expect(
92+
footprintAABB(node({ id: 'l1', type: 'lamp', position: [0, 0, 0], attached: true })),
93+
).toBeNull()
94+
expect(
95+
footprintAABB(node({ id: 'l2', type: 'lamp', position: [0, 0, 0], attached: false })),
96+
).not.toBeNull()
97+
})
98+
})
99+
100+
describe('movingFootprintAnchors', () => {
101+
beforeEach(() => nodeRegistry._reset())
102+
103+
test('relocates the footprint corners around the proposed centre (edges only, no centre anchor)', () => {
104+
registerNode(floorPlacedDef('box'))
105+
const anchors = movingFootprintAnchors(
106+
node({ id: 'm', type: 'box', position: [0, 0, 0], dimensions: [2, 1, 4] }),
107+
10,
108+
20,
109+
)
110+
// 2×4 box centred at (10, 20): corners at x∈{9,11}, z∈{18,22}.
111+
expect(anchors).toHaveLength(4)
112+
expect(anchors.every((a) => a.kind === 'corner')).toBe(true)
113+
expect(new Set(anchors.map((a) => a.x))).toEqual(new Set([9, 11]))
114+
expect(new Set(anchors.map((a) => a.z))).toEqual(new Set([18, 22]))
115+
})
116+
117+
test('rotationY override drives the AABB regardless of node rotation', () => {
118+
registerNode(floorPlacedDef('box'))
119+
const anchors = movingFootprintAnchors(
120+
node({
121+
id: 'm',
122+
type: 'box',
123+
position: [0, 0, 0],
124+
dimensions: [2, 1, 4],
125+
rotation: [0, 0, 0],
126+
}),
127+
0,
128+
0,
129+
Math.PI / 2,
130+
)
131+
const xs = anchors.map((a) => a.x)
132+
// Rotated 90°, the 2×4 box spans ±2 in X (its depth) rather than ±1.
133+
expect(Math.max(...xs)).toBeCloseTo(2, 10)
134+
expect(Math.min(...xs)).toBeCloseTo(-2, 10)
135+
})
136+
137+
test('returns empty for a footprintless kind', () => {
138+
registerNode(plainDef('wall'))
139+
expect(
140+
movingFootprintAnchors(node({ id: 'w', type: 'wall', position: [0, 0, 0] }), 1, 1),
141+
).toEqual([])
142+
})
143+
})
144+
145+
describe('wallSegmentAnchors', () => {
146+
test('returns both endpoints as corners and the chord midpoint as center', () => {
147+
const anchors = wallSegmentAnchors('w', [0, 0], [4, 2])
148+
expect(anchors).toEqual([
149+
{ nodeId: 'w', kind: 'corner', x: 0, z: 0 },
150+
{ nodeId: 'w', kind: 'corner', x: 4, z: 2 },
151+
{ nodeId: 'w', kind: 'center', x: 2, z: 1 },
152+
])
153+
})
154+
155+
test('adds ±thickness/2 face corners on each endpoint when thickness is given', () => {
156+
// Horizontal wall along +X: perpendicular is ±Z, so faces sit at z = ±0.1.
157+
const anchors = wallSegmentAnchors('w', [0, 0], [4, 0], 0.2)
158+
expect(anchors).toEqual([
159+
{ nodeId: 'w', kind: 'corner', x: 0, z: 0 },
160+
{ nodeId: 'w', kind: 'corner', x: 4, z: 0 },
161+
{ nodeId: 'w', kind: 'center', x: 2, z: 0 },
162+
{ nodeId: 'w', kind: 'corner', x: 0, z: 0.1 },
163+
{ nodeId: 'w', kind: 'corner', x: 0, z: -0.1 },
164+
{ nodeId: 'w', kind: 'corner', x: 4, z: 0.1 },
165+
{ nodeId: 'w', kind: 'corner', x: 4, z: -0.1 },
166+
])
167+
})
168+
169+
test('skips face corners for zero/degenerate input', () => {
170+
expect(wallSegmentAnchors('w', [0, 0], [4, 0], 0)).toHaveLength(3)
171+
expect(wallSegmentAnchors('w', [1, 1], [1, 1], 0.2)).toHaveLength(3)
172+
})
173+
})
174+
175+
describe('polygonAnchors', () => {
176+
test('returns each vertex as a corner anchor', () => {
177+
expect(
178+
polygonAnchors('s', [
179+
[0, 0],
180+
[2, 0],
181+
[2, 3],
182+
]),
183+
).toEqual([
184+
{ nodeId: 's', kind: 'corner', x: 0, z: 0 },
185+
{ nodeId: 's', kind: 'corner', x: 2, z: 0 },
186+
{ nodeId: 's', kind: 'corner', x: 2, z: 3 },
187+
])
188+
})
189+
})
190+
191+
describe('collectAlignmentAnchors', () => {
192+
beforeEach(() => nodeRegistry._reset())
193+
194+
test('unions footprint corners, segment anchors and polygon vertices, excluding the moving node', () => {
195+
registerNode(floorPlacedDef('box'))
196+
const nodes = {
197+
moving: node({ id: 'moving', type: 'box', position: [0, 0, 0], dimensions: [1, 1, 1] }),
198+
box: node({ id: 'box', type: 'box', position: [5, 0, 5], dimensions: [2, 1, 2] }),
199+
wall: node({ id: 'wall', type: 'wall', start: [0, 0], end: [4, 0] }),
200+
slab: node({
201+
id: 'slab',
202+
type: 'slab',
203+
polygon: [
204+
[0, 0],
205+
[2, 0],
206+
[2, 2],
207+
],
208+
}),
209+
}
210+
const anchors = collectAlignmentAnchors(nodes, 'moving')
211+
const ids = anchors.map((a) => a.nodeId)
212+
expect(ids).not.toContain('moving')
213+
expect(ids.filter((id) => id === 'box')).toHaveLength(4) // corner anchors
214+
expect(ids.filter((id) => id === 'wall')).toHaveLength(7) // endpoints + midpoint + 4 face corners
215+
expect(ids.filter((id) => id === 'slab')).toHaveLength(3) // polygon vertices
216+
})
217+
})

0 commit comments

Comments
 (0)