feat: vertical building model — stored level heights, wall inversion, decks (#526)
* feat(core): stored storey heights groundwork — pure slab-support module + level height schema Extract pointInPolygon/computeWallSlabSupport and friends into a cycle-free packages/core/src/systems/slab/slab-support.ts (severs level-height -> spatial-grid-manager -> use-scene), add deriveLegacyLevelHeight as the pure mesh-free equivalent of the viewer's stacked level height, and add the optional LevelNode.height field plus the storey service (getStoredLevelHeight, getLevelElevations per-building prefix sums). No behavior change. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(editor): storey height badge + edit popover on level rows Each floating-level-selector row shows its storey height; clicking opens a popover with 2.5/3.0/3.5 presets and a free slider writing level.height. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(core): vertical-model load migration — stored heights, ordinal compaction, wall-top classification Pass 3 in migrateNodes: derive and store each legacy level's exact stacked height (never snapped), compact ordinals per building anchored at zero so basements stay basements, classify wall tops against the derived plane (|plane - top| < 0.20 strictly -> plane-bound, else explicit height materialized), and drop the blind totalRise 2.5 stair default on legacy scenes only. Epsilon and strictness validated by a prod census. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat: pin wall tops to the storey plane; stored heights become the only vertical truth Wall-top inversion: a wall without an explicit height now tops out at its storey plane (resolveWallTop); slabs lift only the base. Window/door caps resolve the real top through the same slab election instead of Infinity. All level stacking (viewer, elevator, first-person, stair openings, MCP scene queries) reads stored LevelNode.height; the four divergent live derivations and level.metadata.height are deleted. Stair totalRise becomes optional and derives from the storey height when absent. MCP create-level stops writing its elevation param into the ordinal. Level creation sites write explicit heights; templates carry their true derived heights. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat: clamp slabs/ceilings under the storey plane; sweep wall-height fallbacks; wall Top control Slab elevation writes clamp to plane − MIN_WALL_HEIGHT when plane-bound walls elect the slab (pure clampSlabElevationForWalls + registry handle bounds + shared panels for 2D/3D parity); ceiling heights clamp under the plane and auto-ceilings derive from resolved wall tops. Every remaining wall.height ?? 2.5 fallback resolves through resolveWallTop / resolveWallEffectiveHeight (panels, overlays, measurements, quantities, spatial grid, MCP reports); template walls matching their storey become plane-bound. Wall panel gains a Top control (Follows storey / Custom height) derived purely from height presence; the store update path now deletes keys passed as explicit undefined so plane-binding round-trips. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(core): persisted support hosts — schema, host-preferring election, rendered-polygon unification Floor-placed nodes and walls gain a nullable supportSlabId. Elections surface the winning slab (getSlabSupportForItem, candidates query) and prefer a still-valid persisted host, falling back silently when the host is gone or reshaped away; deleting the host strips references in the same undo commit. Item-side support now tests the rendered slab polygon (like walls) through a per-level cache invalidated by the spatial-grid sync. Also adds the resolveStairTotalRise unit tests from the stage-1 gates. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat: persist support hosts at commit; thread wall host preference everywhere Floor-placed commits (draft pipeline, per-kind creation tools, registry move tool) and wall create/move/endpoint commits persist supportSlabId via shared resolveSupportSlabPatch helpers — only when overlapping supports disagree on elevation, clearing it otherwise or when the node leaves the floor. WallSlabSupport surfaces electedSlabId; every wall support read site passes wall.supportSlabId as the preferred host. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat: split slab into placement + thickness; pools become explicit recess intent slab.elevation stays the walking surface; new thickness grows downward so the solid occupies [elevation − thickness, elevation]. Migration writes thickness := elevation for solids (byte-identical intervals, including degenerate zero) and recessed: true for legacy negative pools. Geometry branches on recessed instead of the elevation sign; presets keep today's intervals; free elevation edits move the body without coupling thickness (the deck semantic). Dead viewer SlabSystem component deleted. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat: clamp ceilings to covering-slab undersides across levels getLevelAbove + getCoveringSlabUndersideAt give the first cross-level query; ceiling writes clamp to min(storey plane, lowest covering underside) − 0.01, and the space-detection reconcile now clamps manual ceilings down (never up) when a deck above intrudes — a flush deck reactively lowers the ceiling below it. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat: mezzanine and balcony build-tab tools One-gesture composites over the kernel: draw a deck footprint and commit deck slab + railings + stair (mezzanine) or deck + railings (balcony) in a single undo step. Fences gain supportSlabId and lift onto their host deck; railing runs split around the stair mouth; edges near wall centerlines are treated as closed. Stairs target the deck via explicit totalRise with no level-to-level opening sync. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat: adaptive slab vertical editing; level vocabulary in UI copy Dragging a grounded slab's top stretches it (elevation and thickness move together — gaps impossible); floating decks move with thickness preserved and land grounded at zero; pools keep the drag-through-zero gesture. User-facing copy says level, not storey (Follows level, Level height). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat: clamp plane-bound wall tops to covering-slab undersides; fix vertical reactivity getWallPlaneTop samples the wall span against the level above's slabs, so a thick or flush upper floor shortens the walls below it instead of colliding (automatic attach, no dialog). Level-height edits now dirty the level's walls, stairs, ceilings, and fences; covering-slab changes dirty the level below. The effective-height helper triplicated across editor overlays moved to core. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat: ceilings follow the level top by default ceiling.height becomes optional — absent means the ceiling tracks min(level top, covering slab underside) − 0.01 live, so level-height edits no longer require ceiling fixes. Ceiling panel gains the same Follows level / Custom height control as walls; auto-from-walls ceilings are created height-less and their height-derivation machinery is deleted; migration drops stored heights within 0.20 of the bound on legacy scenes. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix: wall plane clamp missed max-side boundary walls Auto slabs derive their polygon from wall centerlines, so covering-clamp samples sat exactly on the boundary where ray-cast point-in-polygon is side-dependent (min edges in, max edges out) — walls clamped or not by orientation. getWallPlaneTop now clips the wall's thickness band against the covering polygon (boundary-inclusive, arc-aware) and the ceiling bound's point sampling gained an explicit on-boundary test. Verified against the reported repro scene. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat: stairs attach to decks; pointer-decided placement surface Stairs gain deckSlabId — rise follows the deck's elevation live (straight flights re-converge via a write-sync mirroring auto-openings), the panel shows a unified To destination with Follows deck / Custom rise, and the mezzanine tool attaches instead of baking a stale rise. Item placement under an elevated deck no longer flickers: grid events fed a feedback loop (the grid plane rode the ghost's elected height), so the support election is now capped at the surface the pointer ray actually hits, with a ground sentinel keeping under-deck commits deterministic. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * chore: remove the mezzanine/balcony composite tools Decks ship as catalog presets instead; the kernel the presets rely on (fence deck-hosting, stair deck attachment, clone remaps, pointer-decided placement) all stays. The tool code lives at e30042db for reference. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat: gate wall adoption to grounded slabs; panel moves, drag stretches then unsticks Floating decks keep their drawn polygon (and stop being seam candidates for grounded neighbors) instead of growing into nearby walls. Panel elevation edits are pure placement; the viewport drag stretches a grounded slab up to 0.4 m then unsticks it into a thin deck. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix: deck-attached stairs land flush with the deck surface The rise now subtracts the stair's own elected base (same election the visual lift uses), so base + rise always equals the deck walking surface; the auto-sync defers a microtask so it reads a settled spatial grid and re-converges on both deck and base-slab moves. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat: draw walls and fences on elevated decks Wall and fence draw tools now publish the pointed surface, so the draw plane rides the deck top (no more perspective-skewed floor hits) and previews sit on the deck. Fences gain real support election: a pure resolveFenceSupportSlabPatch persists the deck host at draw and reshape commits; wall commits thread the pointer cap so aiming under a deck elects the floor. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat: unit-aware height presets Level, ceiling, and slab preset buttons show clean values per display system (8/9/10 ft storeys, 8'-9' ceilings, whole-inch slab steps) instead of converted metric labels; metric presets unchanged. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat: stairs converge to their resolved rise; deck attachment disables the cutout syncStairRises now converges every follows-mode straight stair (level or deck) plus deck-attached custom rises — detaching a stair from a deck re-derives its height, and ordinary stairs finally track level-height changes. Attaching via the panel writes slabOpeningMode none and hides the cutout controls; detaching restores the destination cutout and clears the stale explicit rise. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix: stacked-slab move hopping — one ray, one surface, one XZ The hop was hysteresis: the election consumed the riding grid plane's perspective-skewed hit, giving two self-consistent fixed points for one pointer ray. getPointedSupportSurface now returns the ray's crossing of the pointed surface and both the support cap and the cursor XZ derive from that single computation, so items stay on the surface the pointer aims at and sit exactly under the cursor across storeys. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix: single stair per click; tools restore select mode on exit The stair tool subscribed to both node clicks (synthesized on pointerup) and the native-click grid event with none of the guards sibling tools carry — one physical click over any node surface committed twice. A commit gate + follow-up click swallow fix the double dispatch, and the stair and column tools now restore select mode on exit instead of leaving the dead build-mode-without-tool state that ignored every click. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat: compact multi-selection panel with host footer slot Selecting multiple nodes now docks the collapsed-by-default panel on the right: N selected header, kind breakdown, and Duplicate/Delete mirroring the floating pill. A new multiSelectionFooter slot lets the host app dock actions below it, exactly like inspectorFooter. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> --------- Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Fable 5
parent
34b601bb79
commit
bf89b5bcf2
@@ -0,0 +1,65 @@
|
||||
import { describe, expect, test } from 'bun:test'
|
||||
import { type AnyNode, FenceNode, SlabNode } from '@pascal-app/core'
|
||||
import { resolveFenceLiftElevation } from '../lift'
|
||||
|
||||
const LEVEL_ID = 'level-1'
|
||||
|
||||
function makeDeck(elevation: number, parentId: string | null = LEVEL_ID): SlabNode {
|
||||
return SlabNode.parse({
|
||||
parentId,
|
||||
polygon: [
|
||||
[0, 0],
|
||||
[4, 0],
|
||||
[4, 4],
|
||||
[0, 4],
|
||||
],
|
||||
elevation,
|
||||
thickness: 0.05,
|
||||
})
|
||||
}
|
||||
|
||||
function makeRailing(supportSlabId: string | undefined, parentId: string | null = LEVEL_ID) {
|
||||
return FenceNode.parse({
|
||||
parentId,
|
||||
start: [0, 0],
|
||||
end: [4, 0],
|
||||
supportSlabId,
|
||||
})
|
||||
}
|
||||
|
||||
function resolverFor(...nodes: AnyNode[]) {
|
||||
const byId = new Map(nodes.map((node) => [node.id as string, node]))
|
||||
return (id: string) => byId.get(id)
|
||||
}
|
||||
|
||||
describe('resolveFenceLiftElevation', () => {
|
||||
test('lifts onto the host slab walking surface', () => {
|
||||
const deck = makeDeck(1.25)
|
||||
const railing = makeRailing(deck.id)
|
||||
expect(resolveFenceLiftElevation(railing, resolverFor(deck))).toBe(1.25)
|
||||
})
|
||||
|
||||
test('unhosted fence stays on the level floor', () => {
|
||||
const railing = makeRailing(undefined)
|
||||
expect(resolveFenceLiftElevation(railing, resolverFor())).toBe(0)
|
||||
})
|
||||
|
||||
test('stale host (slab gone) falls back to the floor', () => {
|
||||
const deck = makeDeck(1.25)
|
||||
const railing = makeRailing(deck.id)
|
||||
expect(resolveFenceLiftElevation(railing, resolverFor())).toBe(0)
|
||||
})
|
||||
|
||||
test('host on another level does not lift the fence', () => {
|
||||
const deck = makeDeck(1.25, 'level-2')
|
||||
const railing = makeRailing(deck.id)
|
||||
expect(resolveFenceLiftElevation(railing, resolverFor(deck))).toBe(0)
|
||||
})
|
||||
|
||||
test('host id resolving to a non-slab node is ignored', () => {
|
||||
const deck = makeDeck(1.25)
|
||||
const impostor = makeRailing(undefined)
|
||||
const railing = makeRailing(impostor.id)
|
||||
expect(resolveFenceLiftElevation(railing, resolverFor(deck, impostor))).toBe(0)
|
||||
})
|
||||
})
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
type DragAction,
|
||||
type FenceNode,
|
||||
resolveAlignment,
|
||||
resolveFenceSupportSlabPatch,
|
||||
useScene,
|
||||
type WallNode,
|
||||
} from '@pascal-app/core'
|
||||
@@ -111,6 +112,26 @@ function snapshotLinked(
|
||||
return out
|
||||
}
|
||||
|
||||
/**
|
||||
* Re-elect the slab lift host for the given fences from their CURRENT
|
||||
* store state (call after the endpoint writes). Only writes when the host
|
||||
* actually changes, so unaffected drags stay patch-free.
|
||||
*/
|
||||
function applyFenceSupportPatches(
|
||||
ids: readonly AnyNodeId[],
|
||||
scene: { update(id: AnyNodeId, data: Partial<AnyNode>): void },
|
||||
) {
|
||||
const nodes = useScene.getState().nodes
|
||||
for (const id of ids) {
|
||||
const fence = nodes[id]
|
||||
if (fence?.type !== 'fence') continue
|
||||
const patch = resolveFenceSupportSlabPatch(fence as FenceNode, nodes)
|
||||
if (patch.supportSlabId !== (fence as FenceNode).supportSlabId) {
|
||||
scene.update(id, patch as Partial<AnyNode>)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function linkedCascade(
|
||||
linked: LinkedFenceSnapshot[],
|
||||
origin: FencePlanPoint,
|
||||
@@ -230,6 +251,10 @@ export const moveFenceEndpointDragAction: DragAction<MoveFenceEndpointCtx, MoveF
|
||||
)
|
||||
dirty.push(linked.id as AnyNodeId)
|
||||
}
|
||||
// Re-elect the lift host live: a fence dragged onto / off an elevated
|
||||
// deck rises or drops with the pointer instead of waiting for commit
|
||||
// (fences run no per-frame election — `supportSlabId` IS the lift).
|
||||
applyFenceSupportPatches(dirty, scene)
|
||||
return dirty
|
||||
},
|
||||
|
||||
@@ -250,6 +275,7 @@ export const moveFenceEndpointDragAction: DragAction<MoveFenceEndpointCtx, MoveF
|
||||
scene.restoreAll()
|
||||
scene.resumeHistory()
|
||||
scene.update(ctx.fenceId, { start: draft.start, end: draft.end } as Partial<AnyNode>)
|
||||
const patched: AnyNodeId[] = [ctx.fenceId]
|
||||
if (!draft.detached) {
|
||||
for (const linked of draft.linkedUpdates) {
|
||||
scene.update(
|
||||
@@ -259,8 +285,14 @@ export const moveFenceEndpointDragAction: DragAction<MoveFenceEndpointCtx, MoveF
|
||||
end: linked.end,
|
||||
} as Partial<AnyNode>,
|
||||
)
|
||||
patched.push(linked.id as AnyNodeId)
|
||||
}
|
||||
}
|
||||
// The restoreAll above reverted any live host patch — re-run the
|
||||
// election against the final endpoints so the committed fence stands
|
||||
// on (or leaves) its deck. Uncapped: an endpoint drag has no commit
|
||||
// pointer ray worth trusting, matching the wall move commits.
|
||||
applyFenceSupportPatches(patched, scene)
|
||||
return true
|
||||
},
|
||||
|
||||
|
||||
@@ -261,8 +261,13 @@ export const fenceDefinition: NodeDefinition<typeof FenceNode> = {
|
||||
|
||||
// Stage B: pure geometry function. Generic <GeometrySystem> rebuilds
|
||||
// on dirtyNodes; <ParametricNodeRenderer> mounts the empty group.
|
||||
// `renderer` + `system` fields dropped along with their files.
|
||||
geometry: buildFenceGeometry,
|
||||
// Dependency tracker only — a hosted railing (`supportSlabId`) renders at
|
||||
// its slab's elevation, so host elevation edits must re-dirty the fence.
|
||||
system: {
|
||||
module: () => import('./system'),
|
||||
priority: 4,
|
||||
},
|
||||
// Stage C: floor-plan rendering. FloorplanRegistryLayer iterates kinds
|
||||
// with `floorplan` set and renders via FloorplanGeometryRenderer.
|
||||
// Legacy `floorplanFenceEntries` short-circuits to [] when fence is
|
||||
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
getMaxWallCurveOffset,
|
||||
getWallChordFrame,
|
||||
normalizeWallCurveOffset,
|
||||
resolveFenceSupportSlabPatch,
|
||||
useLiveNodeOverrides,
|
||||
useScene,
|
||||
type WallNode,
|
||||
@@ -320,6 +321,21 @@ export const fenceMoveEndpointAffordance: FloorplanAffordance<FenceNode> = {
|
||||
data: { start: u.start, end: u.end },
|
||||
})),
|
||||
])
|
||||
// Re-elect the slab lift host as the endpoint drags (uncapped max
|
||||
// election — 2D has no camera ray). This legacy write path commits
|
||||
// via the dispatcher's snapshot diff, so patching per tick both
|
||||
// previews the lift and lands it in the committed diff. Fences run
|
||||
// no per-frame election: `supportSlabId` IS the lift.
|
||||
const patchedNodes = useScene.getState().nodes
|
||||
const supportPatches = [node.id, ...linkedUpdates.map((u) => u.id)].flatMap((id) => {
|
||||
const fence = patchedNodes[id]
|
||||
if (fence?.type !== 'fence') return []
|
||||
const patch = resolveFenceSupportSlabPatch(fence as FenceNode, patchedNodes)
|
||||
return patch.supportSlabId === (fence as FenceNode).supportSlabId
|
||||
? []
|
||||
: [{ id, data: patch }]
|
||||
})
|
||||
if (supportPatches.length > 0) useScene.getState().updateNodes(supportPatches)
|
||||
},
|
||||
canCommit() {
|
||||
// Pointer-up always runs canCommit — drop the alignment guide here
|
||||
|
||||
@@ -3,6 +3,7 @@ import {
|
||||
type FenceNode,
|
||||
type FloorplanMoveTarget,
|
||||
type FloorplanMoveTargetSession,
|
||||
resolveFenceSupportSlabPatch,
|
||||
useLiveNodeOverrides,
|
||||
useScene,
|
||||
} from '@pascal-app/core'
|
||||
@@ -179,6 +180,35 @@ export const fenceFloorplanMoveTarget: FloorplanMoveTarget<FenceNode> = ({ node
|
||||
// tracked change. Drop the override AFTER the scene write so
|
||||
// mid-commit reads still see the new position (override wins until
|
||||
// cleared; scene wins after).
|
||||
// The re-elected slab lift host rides in the same write (uncapped max
|
||||
// election — 2D has no camera ray): a fence moved onto / off an
|
||||
// elevated deck must land on the right surface, since fences run no
|
||||
// per-frame election (`supportSlabId` IS the lift). One updateNodes
|
||||
// keeps the whole move a single tracked change. Election runs on the
|
||||
// committed endpoints against the pre-write store (the patch only
|
||||
// reads the parent level + the slab grid).
|
||||
const baselineNodes = useScene.getState().nodes
|
||||
const supportFor = (
|
||||
start: PlanPoint,
|
||||
end: PlanPoint,
|
||||
path: PlanPoint[] | undefined,
|
||||
id: AnyNodeId,
|
||||
) => {
|
||||
const fence = baselineNodes[id]
|
||||
return fence?.type === 'fence'
|
||||
? resolveFenceSupportSlabPatch(
|
||||
{
|
||||
start,
|
||||
end,
|
||||
path,
|
||||
curveOffset: (fence as FenceNode).curveOffset,
|
||||
thickness: (fence as FenceNode).thickness,
|
||||
parentId: fence.parentId,
|
||||
},
|
||||
baselineNodes,
|
||||
)
|
||||
: {}
|
||||
}
|
||||
const fenceUpdate: { id: AnyNodeId; data: Partial<FenceNode> } = isNew
|
||||
? {
|
||||
id: fenceId,
|
||||
@@ -187,9 +217,18 @@ export const fenceFloorplanMoveTarget: FloorplanMoveTarget<FenceNode> = ({ node
|
||||
end: lastNextEnd,
|
||||
path: lastNextPath,
|
||||
metadata: { ...originalMetadata, isNew: false },
|
||||
...supportFor(lastNextStart, lastNextEnd, lastNextPath, fenceId),
|
||||
} as Partial<FenceNode>,
|
||||
}
|
||||
: { id: fenceId, data: { start: lastNextStart, end: lastNextEnd, path: lastNextPath } }
|
||||
: {
|
||||
id: fenceId,
|
||||
data: {
|
||||
start: lastNextStart,
|
||||
end: lastNextEnd,
|
||||
path: lastNextPath,
|
||||
...supportFor(lastNextStart, lastNextEnd, lastNextPath, fenceId),
|
||||
},
|
||||
}
|
||||
const linkedUpdates = linkedOriginals.map((l) => ({
|
||||
id: l.id,
|
||||
...projectLinked(l, lastNextStart, lastNextEnd, lastDelta[0], lastDelta[1]),
|
||||
@@ -198,7 +237,12 @@ export const fenceFloorplanMoveTarget: FloorplanMoveTarget<FenceNode> = ({ node
|
||||
fenceUpdate,
|
||||
...linkedUpdates.map((u) => ({
|
||||
id: u.id,
|
||||
data: { start: u.start, end: u.end, path: u.path },
|
||||
data: {
|
||||
start: u.start,
|
||||
end: u.end,
|
||||
path: u.path,
|
||||
...supportFor(u.start, u.end, u.path, u.id),
|
||||
},
|
||||
})),
|
||||
])
|
||||
const overrides = useLiveNodeOverrides.getState()
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { type GeometryContext, getMaterialPresetByRef } from '@pascal-app/core'
|
||||
import { type AnyNodeId, type GeometryContext, getMaterialPresetByRef } from '@pascal-app/core'
|
||||
import {
|
||||
applyMaterialPresetToMaterials,
|
||||
type ColorPreset,
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
resolveSlotDefaultMaterial,
|
||||
} from '@pascal-app/viewer'
|
||||
import { FrontSide, Group, type Material, Mesh, type Texture } from 'three'
|
||||
import { resolveFenceLiftElevation } from './lift'
|
||||
import type { FenceNode } from './schema'
|
||||
import { FENCE_SLOT_DEFAULTS, type FenceSlotId } from './slots'
|
||||
|
||||
@@ -110,6 +111,14 @@ export function buildFenceGeometry(
|
||||
const group = new Group()
|
||||
const geometries = generateFenceSlotGeometries(node)
|
||||
|
||||
// A hosted railing (`supportSlabId`) stands on its slab's walking surface.
|
||||
// The builder emits local-space children, so the lift lives on an inner
|
||||
// group rather than the registered (React-transformed) root.
|
||||
const lift = ctx ? resolveFenceLiftElevation(node, (id) => ctx.resolve(id as AnyNodeId)) : 0
|
||||
const meshParent = new Group()
|
||||
meshParent.position.y = lift
|
||||
group.add(meshParent)
|
||||
|
||||
for (const slotId of FENCE_SLOT_ORDER) {
|
||||
const geometry = geometries[slotId]
|
||||
if (geometry.getAttribute('position') === undefined) continue
|
||||
@@ -126,7 +135,7 @@ export function buildFenceGeometry(
|
||||
mesh.castShadow = true
|
||||
mesh.receiveShadow = true
|
||||
mesh.userData.slotId = slotId
|
||||
group.add(mesh)
|
||||
meshParent.add(mesh)
|
||||
}
|
||||
|
||||
return group
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
import type { AnyNode, SlabNode } from '@pascal-app/core'
|
||||
import type { FenceNode } from './schema'
|
||||
|
||||
/**
|
||||
* Elevation (meters above the level plane) a hosted fence stands at.
|
||||
*
|
||||
* A fence carrying `supportSlabId` is a railing on that slab's walking
|
||||
* surface (drawn onto a deck, or placed by a deck preset). The
|
||||
* host pins the lift only while it still exists as a slab on the fence's
|
||||
* own level — a stale host (deleted slab, reparented fence) silently
|
||||
* falls back to the level floor, mirroring the read-path rules of the
|
||||
* other `supportSlabId` carriers. Pure so it is unit-testable and
|
||||
* callable from the geometry builder with `ctx.resolve`.
|
||||
*/
|
||||
export function resolveFenceLiftElevation(
|
||||
node: Pick<FenceNode, 'supportSlabId' | 'parentId'>,
|
||||
resolve: (id: string) => AnyNode | undefined,
|
||||
): number {
|
||||
if (!node.supportSlabId) return 0
|
||||
const host = resolve(node.supportSlabId)
|
||||
if (host?.type !== 'slab') return 0
|
||||
if ((host.parentId ?? null) !== (node.parentId ?? null)) return 0
|
||||
const elevation = (host as SlabNode).elevation
|
||||
return Number.isFinite(elevation) ? elevation : 0
|
||||
}
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
isCurvedWall,
|
||||
isSplineFence,
|
||||
type LevelNode,
|
||||
resolveFenceSupportSlabPatch,
|
||||
useLiveNodeOverrides,
|
||||
useScene,
|
||||
type WallMoveAxis,
|
||||
@@ -224,11 +225,35 @@ export const MoveFenceTool: React.FC<{ node: FenceNode }> = ({ node }) => {
|
||||
path?: [number, number][]
|
||||
}>,
|
||||
) => {
|
||||
// Fold the re-elected slab lift host into the same write — a fence
|
||||
// moved onto / off an elevated deck must land on the right surface
|
||||
// (fences run no per-frame election; `supportSlabId` IS the lift),
|
||||
// and one updateNodes keeps the whole move a single undo step.
|
||||
// Election runs on the committed endpoints against the pre-write
|
||||
// store (the patch only reads the parent level + the slab grid).
|
||||
const baselineNodes = useScene.getState().nodes
|
||||
useScene.getState().updateNodes(
|
||||
updates.map((entry) => ({
|
||||
id: entry.id as AnyNodeId,
|
||||
data: { start: entry.start, end: entry.end, path: entry.path },
|
||||
})),
|
||||
updates.map((entry) => {
|
||||
const fence = baselineNodes[entry.id as AnyNodeId]
|
||||
const support =
|
||||
fence?.type === 'fence'
|
||||
? resolveFenceSupportSlabPatch(
|
||||
{
|
||||
start: entry.start,
|
||||
end: entry.end,
|
||||
path: entry.path,
|
||||
curveOffset: (fence as FenceNode).curveOffset,
|
||||
thickness: (fence as FenceNode).thickness,
|
||||
parentId: fence.parentId,
|
||||
},
|
||||
baselineNodes,
|
||||
)
|
||||
: {}
|
||||
return {
|
||||
id: entry.id as AnyNodeId,
|
||||
data: { start: entry.start, end: entry.end, path: entry.path, ...support },
|
||||
}
|
||||
}),
|
||||
)
|
||||
for (const entry of updates) {
|
||||
useScene.getState().markDirty(entry.id as AnyNodeId)
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
'use client'
|
||||
|
||||
import { type AnyNode, type AnyNodeId, useScene } from '@pascal-app/core'
|
||||
import { useEffect } from 'react'
|
||||
import { resolveFenceLiftElevation } from './lift'
|
||||
import type { FenceNode } from './schema'
|
||||
|
||||
/**
|
||||
* Hosted-railing dependency tracker. A fence with `supportSlabId` renders at
|
||||
* its host slab's elevation, but a store update only dirties the node that
|
||||
* changed — editing the slab's elevation (or restoring a deleted host) would
|
||||
* leave the railing floating at the stale height. Watch each hosted fence's
|
||||
* resolved lift and dirty the fence when it moves; `GeometrySystem` rebuilds
|
||||
* through `def.geometry` as usual. (Deleting the host needs no help here:
|
||||
* `deleteNodesAction` strips `supportSlabId` and dirties the fence itself.)
|
||||
*/
|
||||
|
||||
function fenceLiftSignatures(nodes: Record<string, AnyNode>): Map<string, number> {
|
||||
const signatures = new Map<string, number>()
|
||||
for (const node of Object.values(nodes)) {
|
||||
if (node.type !== 'fence') continue
|
||||
const fence = node as FenceNode
|
||||
if (!fence.supportSlabId) continue
|
||||
signatures.set(
|
||||
fence.id,
|
||||
resolveFenceLiftElevation(fence, (id) => nodes[id]),
|
||||
)
|
||||
}
|
||||
return signatures
|
||||
}
|
||||
|
||||
const FenceSystems = () => {
|
||||
useEffect(() => {
|
||||
let previous = fenceLiftSignatures(useScene.getState().nodes)
|
||||
|
||||
return useScene.subscribe((state) => {
|
||||
const current = fenceLiftSignatures(state.nodes)
|
||||
for (const [fenceId, lift] of current.entries()) {
|
||||
if (previous.get(fenceId) !== lift) {
|
||||
state.markDirty(fenceId as AnyNodeId)
|
||||
}
|
||||
}
|
||||
previous = current
|
||||
})
|
||||
}, [])
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
export default FenceSystems
|
||||
@@ -18,6 +18,7 @@ import {
|
||||
} from '@pascal-app/core'
|
||||
import {
|
||||
CursorSphere,
|
||||
clearPlacementSurface,
|
||||
createFenceOnCurrentLevel,
|
||||
createSplineFenceOnCurrentLevel,
|
||||
EDITOR_LAYER,
|
||||
@@ -33,6 +34,8 @@ import {
|
||||
isGridSnapActive,
|
||||
isMagneticSnapActive,
|
||||
markToolCancelConsumed,
|
||||
publishPlacementSurface,
|
||||
resolvePointerSupportSurface,
|
||||
type SegmentAngleReference,
|
||||
snapFenceDraftPoint,
|
||||
snapScalarToGrid,
|
||||
@@ -46,11 +49,34 @@ import {
|
||||
|
||||
import { getSceneTheme, useViewer } from '@pascal-app/viewer'
|
||||
import { Html } from '@react-three/drei'
|
||||
import { useThree } from '@react-three/fiber'
|
||||
import { useEffect, useMemo, useRef, useState } from 'react'
|
||||
import { BoxGeometry, BufferGeometry, DoubleSide, type Group, type Mesh, Vector3 } from 'three'
|
||||
import {
|
||||
BoxGeometry,
|
||||
BufferGeometry,
|
||||
type Camera,
|
||||
DoubleSide,
|
||||
type Group,
|
||||
type Mesh,
|
||||
Vector3,
|
||||
} from 'three'
|
||||
|
||||
const FENCE_PREVIEW_HEIGHT = 1.8
|
||||
const FENCE_PREVIEW_THICKNESS = 0.08
|
||||
// Grid-plane surface publish (pointer-decided): scratch + constant normal so
|
||||
// per-move publishes don't allocate.
|
||||
const SURFACE_UP = new Vector3(0, 1, 0)
|
||||
const surfacePointScratch = new Vector3()
|
||||
|
||||
// The walking surface the pointer actually aims at (deck top when over the
|
||||
// deck, floor/ground underneath it) — only for genuine 3D pointer events.
|
||||
// The 2D floor plan emits synthetic grid events with no camera ray behind
|
||||
// them; those keep the uncapped max election and leave the grid plane alone.
|
||||
function pointedSurfaceFor(camera: Camera, event: GridEvent) {
|
||||
return event.nativeEvent?.target instanceof HTMLCanvasElement
|
||||
? resolvePointerSupportSurface(camera, event.position)
|
||||
: null
|
||||
}
|
||||
/** Figma-style alignment-snap threshold (meters), matching the move tools. */
|
||||
const ALIGNMENT_THRESHOLD_M = 0.08
|
||||
// HUD label heights are measured from the top of the preview bar, so they
|
||||
@@ -460,6 +486,11 @@ const StraightFenceTool: React.FC = () => {
|
||||
previewHeightRef.current = previewHeight
|
||||
const previewThicknessRef = useRef(previewThickness)
|
||||
previewThicknessRef.current = previewThickness
|
||||
// Camera for the pointer-support resolution (deck top vs floor) — read
|
||||
// through a ref so the live event handlers see the current camera.
|
||||
const camera = useThree((state) => state.camera)
|
||||
const cameraRef = useRef(camera)
|
||||
cameraRef.current = camera
|
||||
const cursorRef = useRef<Group>(null)
|
||||
const previewRef = useRef<Mesh>(null!)
|
||||
const startingPoint = useRef(new Vector3(0, 0, 0))
|
||||
@@ -521,6 +552,18 @@ const StraightFenceTool: React.FC = () => {
|
||||
|
||||
const onGridMove = (event: GridEvent) => {
|
||||
if (!(cursorRef.current && previewRef.current)) return
|
||||
// Ride the grid event plane on the pointed surface: aiming at an
|
||||
// elevated deck lifts the plane to the deck top, so the draft's XZ
|
||||
// lands where the cursor points and the preview/cursor Y
|
||||
// (`event.localPosition[1]`) sits at the lift the committed fence
|
||||
// will get. Aiming past the deck edge drops it back to the floor.
|
||||
const pointed = pointedSurfaceFor(cameraRef.current, event)
|
||||
if (pointed) {
|
||||
publishPlacementSurface(
|
||||
surfacePointScratch.set(event.position[0], pointed.worldY, event.position[2]),
|
||||
SURFACE_UP,
|
||||
)
|
||||
}
|
||||
const { walls, fences } = getCurrentLevelElements()
|
||||
const localPoint: FencePlanPoint = [event.localPosition[0], event.localPosition[2]]
|
||||
// While drafting, the segment locks to 15° rays from its start.
|
||||
@@ -630,9 +673,11 @@ const StraightFenceTool: React.FC = () => {
|
||||
const dx = snappedEnd[0] - startingPoint.current.x
|
||||
const dz = snappedEnd[1] - startingPoint.current.z
|
||||
if (dx * dx + dz * dz < 0.01 * 0.01) return
|
||||
const pointed = pointedSurfaceFor(cameraRef.current, event)
|
||||
const createdFence = createFenceOnCurrentLevel(
|
||||
[startingPoint.current.x, startingPoint.current.z],
|
||||
snappedEnd,
|
||||
{ supportCap: pointed ? pointed.elevation : null },
|
||||
)
|
||||
if (!createdFence) return
|
||||
|
||||
@@ -681,6 +726,7 @@ const StraightFenceTool: React.FC = () => {
|
||||
emitter.off('grid:move', onGridMove)
|
||||
emitter.off('grid:click', onGridClick)
|
||||
emitter.off('tool:cancel', onCancel)
|
||||
clearPlacementSurface()
|
||||
useSegmentDraftChain.getState().clear('fence')
|
||||
useAlignmentGuides.getState().clear()
|
||||
const draftPreview = useFloorplanDraftPreview.getState()
|
||||
@@ -738,6 +784,16 @@ const SplineFenceDraft: React.FC = () => {
|
||||
: FENCE_PREVIEW_HEIGHT
|
||||
const [draftPoints, setDraftPoints] = useState<FencePlanPoint[]>([])
|
||||
const [cursor, setCursor] = useState<FencePlanPoint | null>(null)
|
||||
// Building-local Y of the grid plane (rides the pointed surface — see
|
||||
// `pointedSurfaceFor`), so the spline preview draws on the deck top when
|
||||
// the curve is being laid out on one.
|
||||
const [liftY, setLiftY] = useState(0)
|
||||
const camera = useThree((state) => state.camera)
|
||||
const cameraRef = useRef(camera)
|
||||
cameraRef.current = camera
|
||||
// Pointer cap for the commit (Enter / double-click carry no useful grid
|
||||
// event of their own) — last resolved on move/click.
|
||||
const supportCapRef = useRef<number | null>(null)
|
||||
const draftRef = useRef(draftPoints)
|
||||
|
||||
draftRef.current = draftPoints
|
||||
@@ -761,7 +817,9 @@ const SplineFenceDraft: React.FC = () => {
|
||||
const commit = () => {
|
||||
const points = draftRef.current
|
||||
if (points.length >= 2) {
|
||||
const created = createSplineFenceOnCurrentLevel(points)
|
||||
const created = createSplineFenceOnCurrentLevel(points, undefined, {
|
||||
supportCap: supportCapRef.current,
|
||||
})
|
||||
if (created) {
|
||||
triggerSFX('sfx:item-place')
|
||||
// Once the new curve fence is selected for direct editing, leave
|
||||
@@ -775,11 +833,24 @@ const SplineFenceDraft: React.FC = () => {
|
||||
setCursor(null)
|
||||
}
|
||||
|
||||
const trackPointedSurface = (event: GridEvent) => {
|
||||
const pointed = pointedSurfaceFor(cameraRef.current, event)
|
||||
if (!pointed) return
|
||||
supportCapRef.current = pointed.elevation
|
||||
publishPlacementSurface(
|
||||
surfacePointScratch.set(event.position[0], pointed.worldY, event.position[2]),
|
||||
SURFACE_UP,
|
||||
)
|
||||
setLiftY(event.localPosition[1])
|
||||
}
|
||||
|
||||
const onMove = (event: GridEvent) => {
|
||||
trackPointedSurface(event)
|
||||
setCursor(snapPoint([event.localPosition[0], event.localPosition[2]]))
|
||||
}
|
||||
|
||||
const onClick = (event: GridEvent) => {
|
||||
trackPointedSurface(event)
|
||||
if (event.nativeEvent.detail >= 2) {
|
||||
commit()
|
||||
return
|
||||
@@ -807,6 +878,7 @@ const SplineFenceDraft: React.FC = () => {
|
||||
emitter.off('grid:move', onMove)
|
||||
emitter.off('grid:click', onClick)
|
||||
emitter.off('tool:cancel', onCancel)
|
||||
clearPlacementSurface()
|
||||
window.removeEventListener('keydown', onKeyDown)
|
||||
}
|
||||
}, [])
|
||||
@@ -820,18 +892,18 @@ const SplineFenceDraft: React.FC = () => {
|
||||
SPLINE_PREVIEW_SEGMENTS,
|
||||
)
|
||||
return new BufferGeometry().setFromPoints(
|
||||
sampled.map((point) => new Vector3(point.x, previewHeight, point.y)),
|
||||
sampled.map((point) => new Vector3(point.x, liftY + previewHeight, point.y)),
|
||||
)
|
||||
}, [previewHeight, previewPoints])
|
||||
}, [liftY, previewHeight, previewPoints])
|
||||
|
||||
return (
|
||||
<group>
|
||||
{cursor && <CursorSphere height={previewHeight} position={[cursor[0], 0, cursor[1]]} />}
|
||||
{cursor && <CursorSphere height={previewHeight} position={[cursor[0], liftY, cursor[1]]} />}
|
||||
{draftPoints.map((point, index) => (
|
||||
<mesh
|
||||
key={`fence-spline-pt-${index}`}
|
||||
layers={EDITOR_LAYER}
|
||||
position={[point[0], previewHeight, point[1]]}
|
||||
position={[point[0], liftY + previewHeight, point[1]]}
|
||||
>
|
||||
<sphereGeometry args={[0.07, 16, 12]} />
|
||||
<meshBasicMaterial color={SPLINE_PREVIEW_COLOR} depthTest={false} />
|
||||
|
||||
Reference in New Issue
Block a user