Phase 5 Stage E: full kind migration into packages/nodes

Wholesale move of every remaining kind into its own subdirectory under
`packages/nodes/src/`, finishing the registry-driven migration. Each
kind now ships its definition, schema (re-exported from core), and any
of `geometry` / `renderer` / `system` / `floorplan` / `tool` /
`move-tool` / `panel` / `floorplan-move` / `floorplan-affordances` /
`parametrics` / `preview` it needs — no per-kind code remains under
`packages/editor/src/components/tools/` or
`packages/viewer/src/components/renderers/`.

Deleted (replaced by registry-driven equivalents):
- `tools/{ceiling,column,door,fence,item,slab,spawn,wall,window}/...`
  (boundary editors, hole editors, placement tools, move tools,
  endpoint movers, curve tools, helpers, math libs)
- `ui/helpers/{ceiling,slab,wall}-helper.tsx`
- `ui/panels/{column,door,elevator,item,roof,roof-segment,spawn,
  stair,stair-segment,wall,window}-panel.tsx`
- `viewer/src/components/renderers/{building,ceiling,column,door,
  elevator,fence,guide,item,level,roof,roof-segment,scan,site,slab,
  spawn,stair,stair-segment,wall,window,zone}-renderer.tsx`
- `viewer/src/components/viewer/legacy-system.tsx`

Added under `packages/nodes/src/`:
- `building/`, `column/`, `elevator/`, `guide/`, `level/`, `roof/`,
  `roof-segment/`, `scan/`, `shared/`, `site/`, `stair/`,
  `stair-segment/` packages with definition + schema + renderer / system
  / floorplan / panel as appropriate.
- New `floorplan-move.ts` for every kind that supports 2D moves
  (ceiling, door, item, shelf, slab, window) — single registry-driven
  dispatch path via `def.floorplanMoveTarget`.
- New `floorplan-affordances.ts` for kinds with polygon / endpoint
  drags (ceiling, fence, slab, wall) — using the shared
  `polygon-vertex-affordance` factories.
- New per-kind `panel.tsx` for kinds with custom inspector content
  (door, item, shelf, spawn, wall, window).
- New per-kind `tool.tsx` for placement (door, item, shelf, window).
- New per-kind `move-tool.tsx` for kinds with custom 3D move flows
  (door, item, slab, window).

Coordinator + manager updates in `packages/editor/`:
- `tool-manager.tsx` resolves tools from the registry only — no
  hardcoded type→component map.
- `panel-manager.tsx` resolves inspector panels the same way.
- `placement-{coordinator,strategies,types}.ts` extended with
  shelf-surface placement.
- `selection-manager.tsx` adds the registry-selectable fallback.
- `floorplan-panel.tsx`, `floorplan-background-placement.ts`,
  `floorplan-render-context.tsx` updated for the registry layer's new
  contract (props, affordance dispatch, render context).

Viewer updates:
- `viewer/index.tsx` drops legacy renderer mounts.
- `node-renderer.tsx` resolves by registry only.
- `scene-bvh.tsx`, `use-node-events.ts`, `level-system.tsx`,
  `wall-cutout.tsx`, `zone-system.tsx`, `materials.ts` adjusted for
  the registry-only world.

Sidebar tree nodes for ceiling / fence / slab / shelf / tree-node
updated to read from the registered nodes instead of the deleted
legacy renderer trees.

Wiki: new `plugin-authoring.md` page, README index updated.

Tests in `packages/nodes/src/index.test.ts` validate every registered
kind has the required shape.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
Wassim SAMAD
2026-05-19 15:14:12 -04:00
co-authored by Claude Opus 4.7
parent 11015ea1ed
commit d747d2f0ea
204 changed files with 6888 additions and 7877 deletions
+24 -1
View File
@@ -1,5 +1,6 @@
import type { ItemNode as ItemNodeType, NodeDefinition } from '@pascal-app/core'
import { buildItemFloorplan } from './floorplan'
import { itemFloorplanMoveTarget } from './floorplan-move'
import { itemParametrics } from './parametrics'
import { ItemNode } from './schema'
@@ -79,9 +80,31 @@ export const itemDefinition: NodeDefinition<typeof ItemNode> = {
// Same priority as the legacy ItemSystem.
priority: 2,
},
// Catalog placement tool — mounted when `useEditor.tool === 'item'`.
// Wraps the same placement coordinator the move-tool uses (surface
// strategies for floor / wall / ceiling / item-surface). Replaces
// the legacy `editor/src/components/tools/item/item-tool.tsx`.
tool: () => import('./tool'),
// Stage D — 3D move-tool (registry-driven). Adopts the moving node
// and runs the placement coordinator with surface strategies for
// floor / wall / ceiling / item-surface, including attachTo
// *transitions* (drop a wall item on a ceiling and have it switch).
// Replaces the legacy `MoveItemContent` in editor's dispatcher; the
// `getRegistryAffordanceTool('item', 'move')` lookup picks this up.
affordanceTools: {
move: () => import('./move-tool'),
},
// Stage C: floor-plan polygon. ctx.resolve walks the parent chain
// (wall / nested item / level) to compute the world-space transform.
floorplan: buildItemFloorplan,
// 2D move-on-floorplan handler. Branches on `asset.attachTo`:
// wall items snap to walls (like door / window), ceiling items
// snap to ceiling polygons, floor items snap to slabs. attachTo
// *transitions* (drop a wall item on a ceiling) remain canonical
// in the 3D path; 2D only re-anchors within the same family.
floorplanMoveTarget: itemFloorplanMoveTarget,
toolHints: [
{ key: 'Left click', label: 'Place item' },
@@ -94,7 +117,7 @@ export const itemDefinition: NodeDefinition<typeof ItemNode> = {
presentation: {
label: 'Item',
description: 'A catalog-backed item (furniture, fixtures, decorations).',
icon: { kind: 'iconify', name: 'lucide:armchair' },
icon: { kind: 'url', src: '/icons/item.png' },
paletteSection: 'furnish',
paletteOrder: 10,
},
+78 -8
View File
@@ -6,6 +6,7 @@ import {
type GeometryContext,
getScaledDimensions,
type ItemNode,
useLiveTransforms,
} from '@pascal-app/core'
/**
@@ -25,10 +26,17 @@ import {
*/
type Transform = { x: number; y: number; rotation: number }
// Plan-space rotation convention used by the legacy `rotatePlanVector`
// in `editor/src/lib/floorplan/geometry.ts`. This is a CLOCKWISE rotation
// — the registry-side equivalent of the canonical floor-plan transform
// math. Don't switch to a standard counter-clockwise rotation; the wall
// items math (wallRotation = -atan2(dy, dx)) is calibrated against this
// convention, and the legacy item floor-plan stack reads from these
// offsets across many sites.
function rotateVec(x: number, y: number, angle: number): [number, number] {
const c = Math.cos(angle)
const s = Math.sin(angle)
return [x * c - y * s, x * s + y * c]
return [x * c + y * s, -x * s + y * c]
}
function resolveItemTransform(
@@ -75,6 +83,35 @@ function resolveItemTransform(
rotation: parentT.rotation + localRotation,
}
}
} else if (parentNode?.type === 'shelf') {
// Shelf-hosted item: `item.position` is in shelf-local coords. The
// shelf has its own `position` + `rotation[1]` in its parent (level)
// frame, so the item's plan-space position composes the shelf's
// pose with the item's local offset. Without this branch the
// `else` below would treat shelf-local coords as level-local and
// the item would render at the wrong spot whenever the shelf is
// anywhere other than (0, 0, 0).
//
// We also check `useLiveTransforms` for the shelf — if the shelf is
// mid-move (3D or 2D), its scene-state `position` is still at the
// pre-move spot but the live transform carries the cursor-tracked
// position. Reading the live value here keeps the hosted item
// following the shelf in 2D throughout the drag, mirroring how the
// shelf's own entry follows via the layer's effectiveNode override.
const shelf = parentNode as AnyNode & {
position: [number, number, number]
rotation: [number, number, number]
}
const live = useLiveTransforms.getState().get(shelf.id as AnyNodeId)
const shelfX = live?.position[0] ?? shelf.position[0]
const shelfZ = live?.position[2] ?? shelf.position[2]
const shelfRotationY = live?.rotation ?? shelf.rotation[1] ?? 0
const [offsetX, offsetY] = rotateVec(item.position[0], item.position[2], shelfRotationY)
result = {
x: shelfX + offsetX,
y: shelfZ + offsetY,
rotation: shelfRotationY + localRotation,
}
} else {
// Level / slab / ceiling parent — item.position is level-local.
result = {
@@ -116,12 +153,45 @@ export function buildItemFloorplan(node: ItemNode, ctx: GeometryContext): Floorp
return [cx + rx, cy + ry] as FloorplanPoint
})
return {
kind: 'polygon',
points,
fill: '#fef3c7',
stroke: '#92400e',
strokeWidth: 0.012,
opacity: 0.85,
const isSelected = ctx.viewState?.selected ?? false
const floorPlanUrl = node.asset.floorPlanUrl
const children: FloorplanGeometry[] = [
{
kind: 'polygon',
points,
// When an asset thumbnail is present, the polygon is a transparent
// hit-target — the image carries the visual weight. Without a
// thumbnail the polygon needs a light fill to read at all.
//
// `transparent` (not `none`) so the interior remains hit-testable —
// the registry layer's wrapping `<g>` only fires onPointerDown when
// the child renders a paintable surface. `fill="none"` would make
// clicks pass through to whatever's beneath, breaking selection.
fill: floorPlanUrl ? 'transparent' : '#fef3c7',
stroke: '#92400e',
strokeWidth: 0.012,
opacity: 0.85,
},
]
// Asset thumbnail — top-down PNG capture from the asset modal. Drawn
// inside the footprint with the item's rotation applied. Matches the
// legacy `FloorplanItemImage` overlay.
if (floorPlanUrl) {
children.push({
kind: 'image',
url: floorPlanUrl,
center: [cx, cy],
width,
height: depth,
rotation: transform.rotation,
})
}
// Move handle — orange dot at the item center. Only when selected.
if (isSelected) {
children.push({
kind: 'move-handle',
point: [cx, cy],
})
}
return { kind: 'group', children }
}
+118
View File
@@ -0,0 +1,118 @@
'use client'
import type { ItemNode } from '@pascal-app/core'
import {
type PlacementState,
triggerSFX,
useDraftNode,
useEditor,
usePlacementCoordinator,
} from '@pascal-app/editor'
import { Vector3 } from 'three'
/**
* Phase 5 Stage D — item's registry-driven 3D move affordance.
*
* Replaces the legacy `MoveItemContent` in `editor/src/components/tools/
* item/move-tool.tsx`. Behaviour is identical: it adopts the moving node
* (or creates a draft for duplicates flagged `isNew`), runs the placement
* coordinator with surface strategies for floor / wall / ceiling / item-
* surface, and commits via `useScene.updateNode` on click.
*
* Registered via `def.affordanceTools.move`. The editor's
* `MoveTool` dispatcher picks this up through `getRegistryAffordance
* Tool('item', 'move')` before its legacy chain reaches `<MoveItemContent>`
* — so the legacy fallback can now go away.
*
* Closes the 2D ↔ 3D coexistence bugs from last session: when both
* paths mounted, the legacy mover's `destroy()` would clobber the 2D
* commit; with this tool owning the move, only one path is alive at a
* time.
*
* Placement primitives (`useDraftNode`, `usePlacementCoordinator`,
* `PlacementState`) are re-exported from `@pascal-app/editor` — same
* hooks the legacy code used. When `ItemTool` (item placement, not
* move) also ports to `def.tool`, the primitives can be inlined here
* and dropped from editor.
*/
function getInitialState(node: ItemNode): PlacementState {
const attachTo = node.asset.attachTo
if (attachTo === 'wall' || attachTo === 'wall-side') {
return {
surface: 'wall',
wallId: node.parentId,
ceilingId: null,
surfaceItemId: null,
shelfId: null,
}
}
if (attachTo === 'ceiling') {
return {
surface: 'ceiling',
wallId: null,
ceilingId: node.parentId,
surfaceItemId: null,
shelfId: null,
}
}
return {
surface: 'floor',
wallId: null,
ceilingId: null,
surfaceItemId: null,
shelfId: null,
}
}
export function MoveItemTool({ node }: { node: ItemNode }) {
const draftNode = useDraftNode()
const meta =
typeof node.metadata === 'object' && node.metadata !== null
? (node.metadata as Record<string, unknown>)
: {}
const isNew = !!meta.isNew
const cursor = usePlacementCoordinator({
asset: node.asset,
draftNode,
// Duplicates start fresh in floor mode; wall/ceiling draft is created lazily by ensureDraft.
initialState: isNew
? {
surface: 'floor',
wallId: null,
ceilingId: null,
surfaceItemId: null,
shelfId: null,
}
: getInitialState(node),
// Preserve the original item's scale so Y-position calculations use the correct height.
defaultScale: isNew ? node.scale : undefined,
initDraft: (gridPosition) => {
if (isNew) {
// Duplicate: floor items get a draft immediately; wall/ceiling
// items are created lazily on surface entry.
gridPosition.copy(new Vector3(...node.position))
if (!node.asset.attachTo) {
draftNode.create(gridPosition, node.asset, node.rotation, node.scale)
}
} else {
draftNode.adopt(node)
gridPosition.copy(new Vector3(...node.position))
}
},
onCommitted: () => {
triggerSFX('sfx:item-place')
useEditor.getState().setMovingNode(null)
return false
},
onCancel: () => {
draftNode.destroy()
useEditor.getState().setMovingNode(null)
},
})
return <>{cursor}</>
}
export default MoveItemTool
+328
View File
@@ -0,0 +1,328 @@
'use client'
import { type AnyNode, getScaledDimensions, ItemNode, useScene } from '@pascal-app/core'
import {
ActionButton,
ActionGroup,
CollectionsPopover,
PanelSection,
PanelWrapper,
SliderControl,
triggerSFX,
useEditor,
} from '@pascal-app/editor'
import { useViewer } from '@pascal-app/viewer'
import { Copy, Link, Link2Off, Move, Trash2 } from 'lucide-react'
import { useCallback, useRef, useState } from 'react'
/**
* Stage E inspector for item. 1:1 port of the legacy
* `editor/components/ui/panels/item-panel.tsx`, relocated into the
* kind's folder so `parametrics.customPanel` mounts it through the
* registry inspector. The catalog popover (`<CollectionsPopover>`) is
* the only kind-specific UI that can't be expressed via the generic
* auto-inspector today — kept inline.
*
* Slider-drag fix recipe applied: scale / position / rotation slider
* `onChange` callbacks read from a `useRef(node)` instead of the
* closure-captured node, which would re-render every panel-driven
* update mid-drag and exceed React's update-depth budget on big scenes
* (see the wiki / plan recipe).
*/
export default function ItemPanel() {
const selectedId = useViewer((s) => s.selection.selectedIds[0])
const setSelection = useViewer((s) => s.setSelection)
const deleteNode = useScene((s) => s.deleteNode)
const setMovingNode = useEditor((s) => s.setMovingNode)
const node = useScene((s) =>
selectedId ? (s.nodes[selectedId as AnyNode['id']] as ItemNode | undefined) : undefined,
)
const [uniformScale, setUniformScale] = useState(true)
const nodeRef = useRef(node)
nodeRef.current = node
const handleUpdate = useCallback(
(updates: Partial<ItemNode>) => {
if (!selectedId) return
const n = nodeRef.current
if (!n) return
useScene.getState().updateNode(selectedId as AnyNode['id'], updates)
// When an item is mounted on a wall, dirty the wall so the next
// frame regenerates its cutout geometry around the moved item.
if (n.asset.attachTo === 'wall' && n.parentId) {
requestAnimationFrame(() => {
useScene.getState().dirtyNodes.add(n.parentId as AnyNode['id'])
})
}
},
[selectedId],
)
const handleClose = useCallback(() => {
setSelection({ selectedIds: [] })
}, [setSelection])
const handleMove = useCallback(() => {
if (node) {
triggerSFX('sfx:item-pick')
setMovingNode(node)
setSelection({ selectedIds: [] })
}
}, [node, setMovingNode, setSelection])
const handleDuplicate = useCallback(() => {
if (!node) return
triggerSFX('sfx:item-pick')
const proto = ItemNode.parse({
position: [...node.position] as [number, number, number],
rotation: [...node.rotation] as [number, number, number],
name: node.name,
asset: node.asset,
parentId: node.parentId,
side: node.side,
metadata: { isNew: true },
})
setMovingNode(proto)
setSelection({ selectedIds: [] })
}, [node, setMovingNode, setSelection])
const handleDelete = useCallback(() => {
if (!selectedId) return
triggerSFX('sfx:item-delete')
deleteNode(selectedId as AnyNode['id'])
setSelection({ selectedIds: [] })
}, [selectedId, deleteNode, setSelection])
if (!(node && node.type === 'item' && selectedId)) return null
return (
<PanelWrapper
icon={node.asset.thumbnail || '/icons/furniture.png'}
onClose={handleClose}
title={node.name || node.asset.name}
width={300}
>
<PanelSection title="Position">
<SliderControl
label={
<>
X<sub className="ml-[1px] text-[11px] opacity-70">pos</sub>
</>
}
max={node.position[0] + 2}
min={node.position[0] - 2}
onChange={(value) =>
handleUpdate({ position: [value, node.position[1], node.position[2]] })
}
precision={2}
step={0.01}
unit="m"
value={Math.round(node.position[0] * 100) / 100}
/>
<SliderControl
label={
<>
Y<sub className="ml-[1px] text-[11px] opacity-70">pos</sub>
</>
}
max={node.position[1] + 2}
min={node.position[1] - 2}
onChange={(value) =>
handleUpdate({ position: [node.position[0], value, node.position[2]] })
}
precision={2}
step={0.01}
unit="m"
value={Math.round(node.position[1] * 100) / 100}
/>
<SliderControl
label={
<>
Z<sub className="ml-[1px] text-[11px] opacity-70">pos</sub>
</>
}
max={node.position[2] + 2}
min={node.position[2] - 2}
onChange={(value) =>
handleUpdate({ position: [node.position[0], node.position[1], value] })
}
precision={2}
step={0.01}
unit="m"
value={Math.round(node.position[2] * 100) / 100}
/>
</PanelSection>
<PanelSection title="Rotation">
<SliderControl
label={
<>
Y<sub className="ml-[1px] text-[11px] opacity-70">rot</sub>
</>
}
max={Math.round((node.rotation[1] * 180) / Math.PI) + 45}
min={Math.round((node.rotation[1] * 180) / Math.PI) - 45}
onChange={(degrees) => {
const radians = (degrees * Math.PI) / 180
handleUpdate({ rotation: [node.rotation[0], radians, node.rotation[2]] })
}}
precision={0}
step={1}
unit="°"
value={Math.round((node.rotation[1] * 180) / Math.PI)}
/>
<div className="flex gap-1.5 px-1 pt-2 pb-1">
<ActionButton
label="-45°"
onClick={() => {
triggerSFX('sfx:item-rotate')
const currentDegrees = (node.rotation[1] * 180) / Math.PI
const radians = ((currentDegrees - 45) * Math.PI) / 180
handleUpdate({ rotation: [node.rotation[0], radians, node.rotation[2]] })
}}
/>
<ActionButton
label="+45°"
onClick={() => {
triggerSFX('sfx:item-rotate')
const currentDegrees = (node.rotation[1] * 180) / Math.PI
const radians = ((currentDegrees + 45) * Math.PI) / 180
handleUpdate({ rotation: [node.rotation[0], radians, node.rotation[2]] })
}}
/>
</div>
</PanelSection>
<PanelSection title="Scale">
<div className="flex items-center justify-between px-2 pb-2">
<span className="font-medium text-[10px] text-muted-foreground/80 uppercase tracking-wider">
Uniform Scale
</span>
<button
className={
uniformScale
? 'flex h-6 w-6 items-center justify-center rounded-md bg-[#3e3e3e] text-muted-foreground transition-colors hover:text-foreground'
: 'flex h-6 w-6 items-center justify-center rounded-md bg-[#2C2C2E] text-muted-foreground transition-colors hover:bg-[#3e3e3e] hover:text-foreground'
}
onClick={() => setUniformScale((v) => !v)}
type="button"
>
{uniformScale ? <Link className="h-3.5 w-3.5" /> : <Link2Off className="h-3.5 w-3.5" />}
</button>
</div>
{uniformScale ? (
<SliderControl
label={
<>
XYZ<sub className="ml-[1px] text-[11px] opacity-70">scale</sub>
</>
}
max={10}
min={0.01}
onChange={(value) => {
const v = Math.max(0.01, value)
handleUpdate({ scale: [v, v, v] })
}}
precision={2}
step={0.1}
value={Math.round(node.scale[0] * 100) / 100}
/>
) : (
<>
<SliderControl
label={
<>
X<sub className="ml-[1px] text-[11px] opacity-70">scale</sub>
</>
}
max={10}
min={0.01}
onChange={(value) =>
handleUpdate({ scale: [Math.max(0.01, value), node.scale[1], node.scale[2]] })
}
precision={2}
step={0.1}
value={Math.round(node.scale[0] * 100) / 100}
/>
<SliderControl
label={
<>
Y<sub className="ml-[1px] text-[11px] opacity-70">scale</sub>
</>
}
max={10}
min={0.01}
onChange={(value) =>
handleUpdate({ scale: [node.scale[0], Math.max(0.01, value), node.scale[2]] })
}
precision={2}
step={0.1}
value={Math.round(node.scale[1] * 100) / 100}
/>
<SliderControl
label={
<>
Z<sub className="ml-[1px] text-[11px] opacity-70">scale</sub>
</>
}
max={10}
min={0.01}
onChange={(value) =>
handleUpdate({ scale: [node.scale[0], node.scale[1], Math.max(0.01, value)] })
}
precision={2}
step={0.1}
value={Math.round(node.scale[2] * 100) / 100}
/>
</>
)}
</PanelSection>
<PanelSection title="Info">
<div className="flex items-center justify-between px-2 py-1 text-muted-foreground text-sm">
<span>Dimensions</span>
{(() => {
const [w, h, d] = getScaledDimensions(node)
return (
<span className="font-mono text-white">
{Math.round(w * 100) / 100}×{Math.round(h * 100) / 100}×{Math.round(d * 100) / 100}
</span>
)
})()}
</div>
</PanelSection>
<PanelSection title="Collections">
<ActionGroup>
<CollectionsPopover
collectionIds={node.collectionIds}
nodeId={selectedId as AnyNode['id']}
>
<ActionButton label="Manage collections…" />
</CollectionsPopover>
</ActionGroup>
</PanelSection>
<PanelSection title="Actions">
<ActionGroup>
<ActionButton icon={<Move className="h-3.5 w-3.5" />} label="Move" onClick={handleMove} />
<ActionButton
icon={<Copy className="h-3.5 w-3.5" />}
label="Duplicate"
onClick={handleDuplicate}
/>
<ActionButton
className="hover:bg-red-500/20"
icon={<Trash2 className="h-3.5 w-3.5 text-red-400" />}
label="Delete"
onClick={handleDelete}
/>
</ActionGroup>
</PanelSection>
</PanelWrapper>
)
}
+7 -10
View File
@@ -2,17 +2,14 @@ import type { ParametricDescriptor } from '@pascal-app/core'
import type { ItemNode } from './schema'
/**
* Minimal inspector descriptor for item. Items have catalog-driven
* properties (asset.id, asset.dimensions, asset.interactive controls,
* etc.) that don't fit the auto-inspector at Stage A — those are edited
* via the legacy `<ItemPanel>` which renders the catalog-defined
* controls dynamically. Auto-inspector covers only the per-instance
* transform (uniform scale).
*
* Phase 5 Stage E (drop legacy panel) probably uses
* `parametrics.customPanel` to render the catalog-driven controls in
* a registry-aware way.
* Inspector descriptor for item. The fields shape (position / rotation /
* scale sliders, catalog popover, move / duplicate / delete actions)
* can't be expressed via the auto-inspector — they need the kind-owned
* `<ItemPanel>` for layout, the catalog popover, and the move-on-pick
* behaviour. `customPanel` mounts `panel.tsx` through
* `<ParametricInspector>`'s lazy-load slot.
*/
export const itemParametrics: ParametricDescriptor<ItemNode> = {
groups: [],
customPanel: () => import('./panel'),
}
+287 -17
View File
@@ -1,21 +1,291 @@
'use client'
import { ItemRenderer } from '@pascal-app/viewer'
import {
type AnimationEffect,
type AnyNodeId,
type Interactive,
type ItemNode,
type LightEffect,
useInteractive,
useRegistry,
useScene,
} from '@pascal-app/core'
import {
baseMaterial,
ErrorBoundary,
glassMaterial,
NodeRenderer,
resolveCdnUrl,
useItemLightPool,
useNodeEvents,
} from '@pascal-app/viewer'
import { useAnimations } from '@react-three/drei'
import { Clone } from '@react-three/drei/core/Clone'
import { useGLTF } from '@react-three/drei/core/Gltf'
import { useFrame } from '@react-three/fiber'
import { Suspense, useEffect, useMemo, useRef } from 'react'
import type { AnimationAction, Group, Material, Mesh } from 'three'
import { MathUtils } from 'three'
import { positionLocal, smoothstep, time } from 'three/tsl'
import { MeshStandardNodeMaterial } from 'three/webgpu'
const getMaterialForOriginal = (original: Material): Material => {
if (original.name.toLowerCase() === 'glass') {
return glassMaterial
}
return baseMaterial
}
const BrokenItemFallback = ({ node }: { node: ItemNode }) => {
const handlers = useNodeEvents(node, 'item')
const [w, h, d] = node.asset.dimensions
return (
<mesh position-y={h / 2} {...handlers}>
<boxGeometry args={[w, h, d]} />
<meshStandardMaterial color="#ef4444" opacity={0.6} transparent wireframe />
</mesh>
)
}
export const ItemRenderer = ({ node }: { node: ItemNode }) => {
const ref = useRef<Group>(null!)
useRegistry(node.id, node.type, ref)
return (
<group position={node.position} ref={ref} rotation={node.rotation} visible={node.visible}>
<ErrorBoundary fallback={<BrokenItemFallback node={node} />}>
<Suspense fallback={<PreviewModel node={node} />}>
<ModelRenderer node={node} />
</Suspense>
</ErrorBoundary>
{node.children?.map((childId) => (
<NodeRenderer key={childId} nodeId={childId} />
))}
</group>
)
}
const previewMaterial = new MeshStandardNodeMaterial({
color: '#cccccc',
roughness: 1,
metalness: 0,
depthTest: false,
})
const previewOpacity = smoothstep(0.42, 0.55, positionLocal.y.add(time.mul(-0.2)).mul(10).fract())
previewMaterial.opacityNode = previewOpacity
previewMaterial.transparent = true
const PreviewModel = ({ node }: { node: ItemNode }) => {
return (
<mesh material={previewMaterial} position-y={node.asset.dimensions[1] / 2}>
<boxGeometry
args={[node.asset.dimensions[0], node.asset.dimensions[1], node.asset.dimensions[2]]}
/>
</mesh>
)
}
const multiplyScales = (
a: [number, number, number],
b: [number, number, number],
): [number, number, number] => [a[0] * b[0], a[1] * b[1], a[2] * b[2]]
const ModelRenderer = ({ node }: { node: ItemNode }) => {
const { scene, nodes, animations } = useGLTF(resolveCdnUrl(node.asset.src) || '')
const ref = useRef<Group>(null!)
const { actions } = useAnimations(animations, ref)
// Freeze the interactive definition at mount — asset schemas don't change at runtime
const interactiveRef = useRef(node.asset.interactive)
if (nodes.cutout) {
nodes.cutout.visible = false
}
const handlers = useNodeEvents(node, 'item')
useEffect(() => {
if (!node.parentId) return
useScene.getState().dirtyNodes.add(node.parentId as AnyNodeId)
}, [node.parentId])
useEffect(() => {
const interactive = interactiveRef.current
if (!interactive) return
useInteractive.getState().initItem(node.id, interactive)
return () => useInteractive.getState().removeItem(node.id)
}, [node.id])
useMemo(() => {
scene.traverse((child) => {
if ((child as Mesh).isMesh) {
const mesh = child as Mesh
if (mesh.name === 'cutout') {
child.visible = false
return
}
let hasGlass = false
// Handle both single material and material array cases
if (Array.isArray(mesh.material)) {
mesh.material = mesh.material.map((mat) => getMaterialForOriginal(mat))
hasGlass = mesh.material.some((mat) => mat.name === 'glass')
// Fix geometry groups that reference materialIndex beyond the material
// array length — this causes three-mesh-bvh to crash with
// "Cannot read properties of undefined (reading 'side')"
const matCount = mesh.material.length
if (mesh.geometry.groups.length > 0) {
for (const group of mesh.geometry.groups) {
if (group.materialIndex !== undefined && group.materialIndex >= matCount) {
group.materialIndex = 0
}
}
}
} else {
mesh.material = getMaterialForOriginal(mesh.material)
hasGlass = mesh.material.name === 'glass'
}
mesh.castShadow = !hasGlass
mesh.receiveShadow = !hasGlass
}
})
}, [scene])
const interactive = interactiveRef.current
const animEffect =
interactive?.effects.find((e): e is AnimationEffect => e.kind === 'animation') ?? null
const lightEffects =
interactive?.effects.filter((e): e is LightEffect => e.kind === 'light') ?? []
// useGLTF caches scenes, and Clone shares child geometry/material references.
// Undo can unmount one item while another clone of the same asset still needs them.
return (
<>
<Clone
dispose={null}
object={scene}
position={node.asset.offset}
ref={ref}
rotation={node.asset.rotation}
scale={multiplyScales(node.asset.scale || [1, 1, 1], node.scale || [1, 1, 1])}
{...handlers}
/>
{animations.length > 0 && (
<ItemAnimation
actions={actions}
animations={animations}
animEffect={animEffect}
interactive={interactive ?? null}
nodeId={node.id}
/>
)}
{lightEffects.map((effect, i) => (
<ItemLightRegistrar
effect={effect}
index={i}
interactive={interactive!}
key={i}
nodeId={node.id}
/>
))}
</>
)
}
const ItemAnimation = ({
nodeId,
animEffect,
interactive,
actions,
animations,
}: {
nodeId: AnyNodeId
animEffect: AnimationEffect | null
interactive: Interactive | null
actions: Record<string, AnimationAction | null>
animations: { name: string }[]
}) => {
const activeClipRef = useRef<string | null>(null)
const fadingOutRef = useRef<AnimationAction | null>(null)
// Reactive: derive target clip name — only re-renders when the clip name itself changes
const targetClip = useInteractive((s) => {
const values = s.items[nodeId]?.controlValues
if (!animEffect) return animations[0]?.name ?? null
const toggleIndex = interactive!.controls.findIndex((c) => c.kind === 'toggle')
const isOn = toggleIndex >= 0 ? Boolean(values?.[toggleIndex]) : false
return isOn
? (animEffect.clips.on ?? null)
: (animEffect.clips.off ?? animEffect.clips.loop ?? null)
})
// When target clip changes: kick off the transition
useEffect(() => {
// Cancel any ongoing fade-out immediately
if (fadingOutRef.current) {
fadingOutRef.current.timeScale = 0
fadingOutRef.current = null
}
// Move current clip to fade-out
if (activeClipRef.current && activeClipRef.current !== targetClip) {
const old = actions[activeClipRef.current]
if (old?.isRunning()) fadingOutRef.current = old
}
// Start new clip at timeScale 0.01 (as 0 would cause isRunning to be false and thus not play at all), then fade in to 1
activeClipRef.current = targetClip
if (targetClip) {
const next = actions[targetClip]
if (next) {
next.timeScale = 0.01
next.play()
}
}
}, [targetClip, actions])
// useFrame: only lerping — no logic
useFrame((_, delta) => {
if (fadingOutRef.current) {
const action = fadingOutRef.current
action.timeScale = MathUtils.lerp(action.timeScale, 0, Math.min(delta * 5, 1))
if (action.timeScale < 0.01) {
action.timeScale = 0
fadingOutRef.current = null
}
}
if (activeClipRef.current) {
const action = actions[activeClipRef.current]
if (action?.isRunning() && action.timeScale < 1) {
action.timeScale = MathUtils.lerp(action.timeScale, 1, Math.min(delta * 5, 1))
if (1 - action.timeScale < 0.01) action.timeScale = 1
}
}
})
return null
}
const ItemLightRegistrar = ({
nodeId,
effect,
interactive,
index,
}: {
nodeId: AnyNodeId
effect: LightEffect
interactive: Interactive
index: number
}) => {
useEffect(() => {
const key = `${nodeId}:${index}`
useItemLightPool.getState().register(key, nodeId, effect, interactive)
return () => useItemLightPool.getState().unregister(key)
}, [nodeId, index, effect, interactive])
return null
}
/**
* Wrap-export of the legacy `ItemRenderer`.
*
* Item's renderer is ~280 lines using `useGLTF` from `@react-three/drei`
* to load GLB assets from the CDN. It also handles asset-loaded
* `interactive` widgets (clickable hot-spots, sliders inside the
* scene), surface mounting, attachment offsets — too much code to
* duplicate at Stage A. Phase 5 Stage F (cleanup) moves it into this
* folder if useful, or leaves it in viewer with the public re-export.
*
* Item is also the first kind to demonstrate the "custom def.renderer"
* escape hatch documented in plans/editor-node-registry.md — kinds with
* GLB loaders, drei helpers, `useGLTF`, etc., set `def.renderer` to a
* full React component rather than trying to express geometry as a
* pure builder.
*/
export default ItemRenderer
-3
View File
@@ -9,9 +9,6 @@ import { ItemLightSystem, ItemSystem } from '@pascal-app/viewer'
* (wall-side z-offset, slab elevation, ceiling mounting).
* - **`ItemLightSystem`** — manages light sources attached to items
* (lamps, ceiling lights, etc.).
*
* Both are wrapped in `<LegacySystem kind="item">` legacy mounts; with
* item registered, those short-circuit and this bundle takes over.
*/
const ItemSystems = () => {
return (
+54
View File
@@ -0,0 +1,54 @@
'use client'
import type { AssetInput } from '@pascal-app/core'
import { triggerSFX, useDraftNode, useEditor, usePlacementCoordinator } from '@pascal-app/editor'
/**
* Registry-driven item placement tool. Mounted by `ToolManager` when
* `useEditor.tool === 'item'` (the catalog picker is what selects which
* asset; this tool handles the cursor follow + click-to-commit flow).
*
* Wraps the same `usePlacementCoordinator` + `useDraftNode` primitives
* the move-tool uses. The placement coordinator runs surface strategies
* (floor / wall / ceiling / item-surface) so the same cursor logic
* handles wall-mounted artwork, floor furniture, ceiling fans, and
* nested items on tables.
*
* Replaces the legacy `editor/src/components/tools/item/item-tool.tsx`.
* The `tools` map in `tool-manager.tsx` no longer needs an `item:` entry
* — `getRegistryTool('item')` finds this through `def.tool`.
*/
function ItemPlacementContent({ selectedItem }: { selectedItem: AssetInput }) {
const draftNode = useDraftNode()
const cursor = usePlacementCoordinator({
asset: selectedItem,
draftNode,
initDraft: (gridPosition) => {
// Only floor items get a draft on mount; wall / ceiling items are
// created lazily by the placement coordinator when the cursor
// enters a surface (so the draft doesn't appear at world origin
// before the first move event).
if (selectedItem && !selectedItem.attachTo) {
draftNode.create(gridPosition, selectedItem)
}
},
onCommitted: () => {
triggerSFX('sfx:item-place')
// Returning `true` tells the coordinator to immediately spawn the
// next draft so the user can keep placing copies — matches the
// "repeat-on-click" UX of the legacy tool.
return true
},
})
return <>{cursor}</>
}
function ItemTool() {
const selectedItem = useEditor((state) => state.selectedItem)
if (!selectedItem) return null
return <ItemPlacementContent selectedItem={selectedItem} />
}
export default ItemTool