feat(roof-system): six roof-accessory kinds (chimney, dormer, skylight, solar-panel, ridge-vent, box-vent) on the registry model (#330)

* 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(box-vent): port to packages/nodes registry shape

Move box-vent from the legacy scattered layout (core schema +
viewer/systems/renderers + editor/tools/panels/sidebar) into a single
`packages/nodes/src/box-vent/` folder following the Phase 5 Stage E
pattern. The kind now self-registers via the built-in plugin.

- schema lives in `core/schema/nodes/box-vent.ts` (referenced by the
  hand-maintained AnyNode union) and re-exports from the kind folder.
- `def.renderer` reads the parent roof-segment from useScene, applies
  the slope tilt + segment yaw + node rotation stack, and follows the
  segment's useLiveTransforms override during a parent drag.
- geometry builder is pure and shared by renderer / preview / tool /
  unit tests. `computeBoxVentSlopeTilt` is lifted as a helper for
  future reuse by other roof-mounted kinds (skylight / solar-panel).
- placement tool listens to `roof:*` events, snaps to the segment
  under the cursor, creates a new BoxVentNode parented to that
  segment.
- BoxVentEvent + `NodeEvents<'box-vent', BoxVentEvent>` added to the
  event bus so `useNodeEvents(node, 'box-vent')` type-checks.

Verified: workspace `bun run build` + `bun run check-types` pass; 13
new unit tests in `__tests__/{schema,geometry}.test.ts` pass.

Worked example for porting the remaining roof-system kinds (ridge-vent,
chimney, solar-panel, skylight, dormer) — see `.claude/PORT-CHEATSHEET.md`.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(ridge-vent): port to packages/nodes registry shape

Same pattern as box-vent (`752ace83`): one folder under
`packages/nodes/src/ridge-vent/`, schema in core, registration via the
built-in plugin. No outside-the-folder edits beyond core schema/types,
the event bus, and the plugin index.

- pure geometry builder shared by renderer / preview / tool / tests,
  covering all three styles (curved cap / shingled / metal) and the
  optional end caps.
- custom `def.renderer` reads the parent roof-segment, follows
  useLiveTransforms during a parent drag. No slope tilt — the ridge
  IS the high line of the segment so the transform stack is one
  level shallower than box-vent.
- placement tool snaps the cursor to the ridge (segment-local Z=0)
  wherever the cursor lands on a segment, then commits on click with
  Z=0 baked into the new node's position.
- RidgeVentEvent + NodeEvents<'ridge-vent', ...> added to the event bus.

Verified: workspace build green, 9 new tests pass alongside the
13 box-vent tests.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(chimney): port to packages/nodes registry shape (Option C)

Same shape as box-vent (`752ace83`) and ridge-vent (`10d489d6`).

**Scope — Option C.** Chimney lands in the registry with solid
geometry; the CSG-driven decoration (cap flue holes, body cavity,
panels, bands, and the roof-trim that hides the chimney bottom inside
the deck) is preserved in the schema but NOT rendered yet. These
re-light when roof-segment migrates to Stage B and introduces a
`roofCutout` capability the parent segment can read.

Visual consequence: a placed chimney intersects the roof at the deck
line instead of having a clean CSG-cut hole around it. Placement,
move (via the legacy floating-vent-actions until the affordance tool
is ported), paint, inspector edits, undo, and delete all work
correctly.

- pure builder returns `{ body, cap, flues, cricket }` so each piece
  carries its own material (body/top split matches the schema's
  `material` vs `topMaterial`). Body height derived from the parent
  segment's `wallHeight + (flat ? 0 : roofHeight) + heightAboveRidge`.
- custom `def.renderer` reads the parent segment via `useScene`,
  follows `useLiveTransforms` during a parent drag.
- placement tool listens to `roof:*` events, creates a new
  ChimneyNode parented to the targeted segment with segment-local
  coordinates.
- ChimneyEvent + NodeEvents<'chimney', ChimneyEvent> added to the
  event bus.
- ChimneyMaterialRole helper re-exported from core (used by the
  paint-mode picker — keeps the legacy multi-surface signature).

Verified: workspace build green, 11 new tests pass (36 total across
box-vent / ridge-vent / chimney).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(solar-panel): port to packages/nodes registry shape (Option C)

Fourth roof-mounted kind, same shape as box-vent (`752ace83`),
ridge-vent (`10d489d6`), and chimney (`45038713`).

- pure builder generates the rows × columns cell grid as a single
  merged BufferGeometry with two render groups (frame + glass) so
  one mesh can take a `[frameMaterial, panelMaterial]` array.
- analytical roof-surface helpers (`getSurfaceY`, `getAnalyticalNormal`,
  `surfaceQuatFromNormal`) live alongside the geometry builder and
  drive both the renderer (when `surfaceNormal` is absent from the
  node) and the placement preview/commit.
- placement tool stores the analytical surfaceNormal on the new node
  so the runtime renderer and the placement preview produce the same
  orientation.
- `solar-panel-presets.ts` moved into core (it was already imported
  from the schema there) and re-exported through `@pascal-app/core`.
- inspector parametrics cover preset, grid, panel dims, mounting
  (flush/tilted with `tiltAngle` shown only when tilted), standoff,
  and frame.
- SolarPanelEvent + NodeEvents<'solar-panel', ...> on the bus.

**Option C still applies**: panels visually sit on the roof surface
but the roof is NOT cut beneath them; the legacy renderer's
useFrame-driven quaternion smoothing is replaced by a static
quaternion computed once per render. Surface tracking under live
parent rotation comes back when roof-segment migrates to Stage B.

Verified: workspace build green, 16 new tests (52 total across the
four ported kinds).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(skylight): port to packages/nodes registry shape (stub)

Fifth roof-mounted kind. Schema is complete, but the geometry and
animation surfaces are intentionally stubbed — this commit lands the
registration so the kind is present in palette / inspector / sidebar
/ undo, and follow-up commits flesh out the type-specific geometry
and the animation system.

**Scope.**
- Schema: every field from the archive ports verbatim (25 fields,
  five `skylightType` variants, opening/sliding state, lantern
  proportions, curb).
- Geometry: frame + glass rendered as plain boxes regardless of
  `skylightType`. Lantern slope, opening swing tilt, and sliding
  panel offset from the archive are not yet rebuilt.
- Animation: `operationState` and `slideFraction` round-trip via the
  inspector but don't drive geometry yet and don't interpolate over
  time. The legacy animation lived in `useInteractive.skylight
  Animations`, which doesn't exist on main — re-introducing that
  surface is a focused follow-up.
- Inherits Option C from chimney: no CSG cutout into the roof; no
  frame CSG (4 box rails instead).

**Why ship the stub now**: the framework wiring (schema in core,
event bus entry, plugin registration, inspector descriptor, custom
renderer with parent-segment lookup, placement tool) is the part
that's reusable across all five `skylightType` variants. Wiring
+ box geometry takes the kind from "doesn't exist" to "place / move
/ paint / delete / undo all work" without committing to the harder
type-specific geometry decisions.

Follow-up commits:
- type-specific geometry (lantern slope, opening tilt, sliding offset)
- animation system + `useInteractive.skylightAnimations` extension

Verified: workspace build green, 7 new tests (59 total across the
five ported kinds).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(dormer): port to packages/nodes registry shape (stub)

Sixth and final roof-mounted kind. Schema complete; geometry stubbed
as a house silhouette (box body + triangular gable). Same Option C
inheritance as chimney, solar-panel, and skylight.

**Key call: window is inlined, not a hosted child.** The archive's
dormer carries its window opening as parametric fields on its own
schema (`windowWidth`, `windowColumns`, `windowSill`, etc.) — not a
hosted `WindowNode` child. So `relations.hosts` stays unset and the
kind doesn't need a `children` field. The 17 window-* fields stay in
the schema; geometry beyond the silhouette stub picks them up later.

- per-surface material resolution (`getEffectiveDormerSurfaceMaterial`)
  ports verbatim into core with the same cross-fallback semantics
  (top → material, side ↔ wall, then legacy `material`).
- placement tool follows the established pattern (`roof:*` events,
  segment-local commit, analytical surfaceNormal stored).
- `RoofType` import resolved from the existing `roof-segment` schema
  on main (the archive's `./roof-type` file is consolidated there).
- DormerEvent + NodeEvents<'dormer', DormerEvent> on the bus.

**Stub scope.** Geometry renders gable-only regardless of `roofType`;
no window opening cutout, no window frame, no sill, no roof trim
where the dormer meets the host segment. The archive's geometry
relies on `getDormerExposedFaces` + `generateDormerGeometry` from
the legacy roof-system, neither of which exists in `packages/nodes`.
Follow-up commits add per-roofType dormer roofs, the window
opening+frame+sill, and the trim/CSG against the parent segment.

Verified: workspace build green, 12 new tests pass (71 total across
all six ported kinds; pre-existing spawn parity failures unrelated).

All six roof-system kinds now live in the registry shape.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* docs: porting cheat-sheet for the roof-system kind migrations

Reference doc kept alongside the six kind ports (box-vent, ridge-vent,
chimney, solar-panel, skylight, dormer) so future kind authors can
follow the same shape. Captures:

- the per-kind folder layout (13 files, what each one owns)
- the three-checkbox composition model (`geometry` / `renderer` / `system`)
- every `NodeDefinition` field with usage notes
- the wiring touch-points outside the kind folder
  (`packages/nodes/src/index.ts`, `packages/core/src/events/bus.ts`,
  the AnyNode union, the core schema exports)
- per-kind decisions for the six roof-system kinds (which checkboxes
  each one ticks, what gets stubbed, what's deferred)
- pitfalls hit while porting (material-cache leaks, group-transform
  mutation, host-kind children fields, Path 1 vs Path 2 floorplan
  move)
- a pre-PR checklist

Kept under `.claude/` (not `wiki/`) since it's a working note for the
in-flight migration, not authoritative project documentation. Move
into `wiki/architecture/` later if it earns its keep.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat: wire paint targets + skylight animation surface for new kinds

Two small additions cherry-picked from roof-system-archive that the
six kind ports depend on. Both are mechanical and unblock follow-up
work without changing existing behavior.

**Paint targets.** Add `chimney`, `skylight`, `dormer` to
`MaterialTarget` enum so the paint picker surfaces these kinds. Wire
`chimney` and `dormer` into the relevant material-library target
arrays (WALL_TARGETS, SLAB_TARGETS, WALL_AND_SLAB_TARGETS,
ROOF_TARGETS) so wall / slab / roof material catalog entries are
offered when painting a chimney or dormer. Without this the new
kinds' `material` / `materialPreset` fields can be set
programmatically but the user-facing paint flow has nothing to
target.

**Skylight animation surface.** Port `SkylightInteractiveState` +
`SkylightAnimationState` types, `skylights` / `skylightAnimations`
store fields, and four actions (`setSkylightOpenState`,
`removeSkylightOpenState`, `startSkylightAnimation`,
`cancelSkylightAnimation`) onto `useInteractive`. Mirrors the
existing door / window animation surfaces one-for-one. This is the
prerequisite the skylight stub commit (`6dcee1ee`) called out — the
follow-up commit that adds the skylight animation system component
+ wires `operationState` into the renderer's geometry now has
something to consume.

Neither change touches the six kind folders or their definitions —
the kinds will pick up the new paint targets automatically and the
skylight animation surface is dormant until a consumer ports
forward.

Verified: workspace build green, 71/71 kind tests pass.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(palette): surface the six roof accessories in StructureTools

Closes the UX gap from the kind ports: box-vent / ridge-vent /
chimney / solar-panel / skylight / dormer are registered in the
registry with `def.tool` and `presentation`, but the top palette
(`StructureTools`) is currently driven by a hand-coded `tools`
array, not by the registry. So the new kinds existed in the
codebase but had no entry point in the running editor — the user
had no way to add them.

- Extend `StructureTool` union in `use-editor.tsx` with the six new
  kind IDs so `setTool('chimney')` typechecks.
- Add six entries to the `tools` array in `structure-tools.tsx`.
  All use the existing `/icons/roof.png` (a kind-specific icon set
  is a follow-up).

The ToolManager already dispatches `nodeRegistry.get(tool)?.tool`
(`tool-manager.tsx:28`), so clicking a new palette button activates
the kind's registered `def.tool` automatically — no further wiring
needed.

Follow-up: a `parametrics.customPanel` on `roofDefinition` that
surfaces inline "Add Chimney / Skylight / Dormer / ..." buttons in
the roof inspector (matching the legacy `roof-panel.tsx` UX). For
now, top palette is the entry point.

Verified: workspace build green, 71/71 kind tests pass.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(roof): add inline "Add Element" section to the roof inspector

When a roof is selected, the inspector now shows six quick-add buttons
(Chimney, Dormer, Skylight, Solar Panel, Box Vent, Ridge Vent) in an
"Add element" section between Position and Actions. Closes the
discoverability gap from the kind ports — the user no longer has to
hunt for the kind in the top palette.

- Lives in `packages/nodes/src/roof/panel.tsx` (the roof's existing
  customPanel — it already escapes the auto-derived inspector to render
  Segments + Position + Actions).
- Each button calls `useEditor.getState().setTool(kind)` to activate
  the kind's registered `def.tool`. The ToolManager dispatches via
  `nodeRegistry.get(tool)?.tool` (`tool-manager.tsx:28`), so this
  reuses the same code path as clicking the kind in the top palette.
- Tools listen for `roof:*` events — after clicking "Add Chimney" the
  user clicks anywhere on a roof segment to commit the new node
  parented to that segment.

Mirrors the legacy `roof-panel.tsx` UX (which had inline Add buttons
that created hidden nodes + entered move mode); the registry-shaped
equivalent activates the placement tool instead so the user sees a
preview that follows the cursor.

Verified: workspace build green, 71/71 kind tests pass.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* ux(palette): remove roof accessories from the top palette

Six kinds (box-vent / ridge-vent / chimney / solar-panel / skylight /
dormer) only make sense in context of a selected roof segment — putting
them in the top palette clutters it for users not actively editing a
roof. They're entered through the roof inspector's "Add element"
section instead (added in 275af8f4), which routes to the same
registry-driven placement tools.

- Remove the six entries from the `tools` array in `structure-tools.tsx`.
- Keep `StructureTool` union additions in `use-editor.tsx` since
  `setTool('chimney')` etc. still need to typecheck from the roof
  panel's `activateTool` callback.

Verified: workspace build green.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(placement): always resolve a roof segment on click so add commits

Likely root cause of "Add Element clicks not adding anything." The
six roof-mounted placement tools each had a private
`resolveSegmentFromWorldPoint` that returned null when the click's
segment-local (x, z) fell outside `width/2 × depth/2` — but the
visible merged-roof mesh extends past those bounds by the segment's
overhang. Clicks landing anywhere in the eave band, or beyond every
segment's nominal footprint, silently no-op'd: `onClick` early-returned
on `if (!hit) return` and no node was created.

- Extract a shared `resolveRoofSegmentHit` into
  `packages/nodes/src/roof/segment-hit.ts`.
- Bounds check now includes `seg.overhang` on each side, matching the
  visible roof mesh.
- If no segment passes the exact check, fall back to the FIRST
  segment with the click point projected into its local frame. Same
  policy the legacy `roof-panel.tsx` used (it parented all add
  operations to `segments[0]` and let the user move afterward).
- Rewire box-vent, ridge-vent, chimney, solar-panel, skylight, and
  dormer placement tools to use the shared helper. Drop the per-tool
  copies (and the now-unused `RoofSegmentNode` import in 5 of them).

After this, clicking "Add Chimney" / etc. in the roof inspector
followed by a click anywhere on the visible roof commits the new
node every time.

Verified: workspace build green, 71/71 kind tests pass.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(roof): mount accessory children of roof-segments so Add actually adds

Closes "Add Element click adds nothing to the scene." After the click,
the new chimney/skylight/dormer/box-vent/ridge-vent/solar-panel node
was being created in `useScene.nodes` with `parentId: <segmentId>` —
but nothing mounted it visually. Two missing pieces:

1. RoofSegmentNode had no `children` array. `createNodesAction`
   appends `newNode.id` to `parent.children` only when the parent
   declares the field (`node-actions.ts:355`). Without it the
   parent-side write was a no-op, so the accessory existed in the
   store but nothing ever fired its `<NodeRenderer>` mount.

2. Even with the schema field, `roof-segment/renderer.tsx` was a leaf
   `<mesh>` — no recursive `<NodeRenderer>` mount of `node.children`.

Fix:
- `core/src/schema/nodes/roof-segment.ts`: add
  `children: z.array(z.string()).default([])`.
- `nodes/src/roof-segment/renderer.tsx`: emit a `<group>` alongside
  the placeholder mesh that iterates `node.children` and mounts each
  via `<NodeRenderer>`. The group carries the same transform as the
  mesh so accessories inherit the segment's local frame — matching
  the segment-local coordinates each accessory renderer assumes.
- `nodes/src/roof/renderer.tsx`: drop the `visible={false}` segments
  wrapper. `RoofSystem` only fills the parent roof's `merged-roof`
  mesh (`viewer/systems/roof/roof-system.tsx:172` via
  `getObjectByName('merged-roof')`), so segment placeholder meshes
  stay empty and don't z-fight with the visible roof. Mounting
  segments inside a visible wrapper is what lets accessory grand-
  children render at all.

Also unblocks the user's `roof/panel.tsx` accessory-list selectors
(which loop `seg.children` for chimneys/dormers/skylights/etc.) by
giving the schema the field they expect.

Verified: workspace build green, 71/71 kind tests pass.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(roof-accessories): drop double-applied segment transform from renderers

After the previous fix (segments host accessories via recursive
NodeRenderer), each accessory was being positioned at *twice* the
segment offset — the renderer's outer group still applied
`segment.position` and `segment.rotation`, and the React parent (the
segment's group) was already at that transform too. Result: chimneys,
skylights, dormers, etc. landed in the scene graph but rendered far
off-screen — invisible from any normal camera view.

Fix the six accessory renderers (box-vent, ridge-vent, chimney,
solar-panel, skylight, dormer) to assume the segment's transform is
inherited from the React tree:

- Drop the outer `<group position={segmentPosition} rotation-y={...}>`
  wrapper.
- Apply `node.position` (segment-local) directly to the ref'd outer
  group, with the kind-specific tilt / quaternion / yaw on inner
  groups.
- Drop `useLiveTransforms` lookup for the segment — React tree
  re-renders propagate parent transform changes automatically.
- Keep the `useScene` segment lookup; it's still needed for kind-
  specific math (slope tilt, analytical surface normal, base Y from
  wallHeight) that reads segment fields beyond just the transform.

Chimney's outer group sits at `[0, 0, 0]` because `applyNodeTransform`
in `geometry.ts` already bakes `node.position` and `node.rotation`
into the chimney's vertex positions (which also bake `baseY` from
`segment.wallHeight`). No double application there either.

After this, Add Element → click → place puts the accessory at the
clicked spot on the roof, visible and selectable.

Verified: workspace build green, 71/71 kind tests pass.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(scene): migrate existing roof-segments to add `children: []`

Closes "Add Element click adds to side panel but not to scene graph."
The previous fix added `children: z.array(z.string()).default([])`
to RoofSegmentNode, but that default only applies when zod parses
the segment fresh. Every roof-segment already in a loaded scene
(saved before the schema change) carries no `children` field at
runtime.

`createNodesAction` (`node-actions.ts:355`) appends the new child id
to `parent.children` only when `'children' in parent && Array.isArray(...)`
is true. For un-migrated segments that check fails — the chimney /
skylight / dormer / etc. is added to `useScene.nodes` (so it shows
up in the sidebar tree) but the parent-side write is a no-op, so
the segment's children array remains undefined, the segment
renderer's recursive `<NodeRenderer>` finds nothing to mount, and
nothing appears in the 3D scene.

Mirror the existing shelf migration (`use-scene.ts:351`): when the
scene loads, patch every roof-segment whose `children` isn't an
array to `children: []`. Existing scenes get the field on next
load; new segments get it from the schema default. After this the
"Add Element" click commits visibly.

Verified: workspace build green.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(chimney): port archive's bespoke tabbed panel as customPanel

The auto-derived inspector worked but couldn't reproduce the
archive's tabbed UI (Cap / Flues / Shoulder / Bands / Cricket /
Panels) where each sub-section gets its own dedicated controls
laid out as a grid of selectable cards. Users selecting a chimney
got a flat parametric form instead of the dense bespoke editor.

- Drop the legacy `packages/editor/src/components/ui/panels/chimney-panel.tsx`
  into `packages/nodes/src/chimney/panel.tsx` (the kind's customPanel
  slot). Rewrites:
  * Helper imports collapsed to one barrel from `@pascal-app/editor`
    (`ActionButton`, `ActionGroup`, `PanelSection`, `PanelWrapper`,
    `SegmentedControl`, `SliderControl`, `triggerSFX`).
  * `sfxEmitter.emit(...)` → `triggerSFX(...)` (same SFX, registry-
    safe export from `@pascal-app/editor`).
  * Inline a 3-line `cn` helper since editor doesn't re-export the
    legacy `lib/utils` one.
  * `ChimneyPanel` becomes `default export` so customPanel's lazy
    loader can pick it up.
- Wire `chimneyParametrics.customPanel = () => import('./panel')` so
  the registry's parametric inspector defers to the bespoke component.
- Keep `groups` in `chimneyParametrics` for MCP / fallback consumers
  (the parametric data is still authoritative).

User-visible: clicking a chimney now opens the tabbed inspector with
the exact category layout from the archive.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(chimney): CSG-trim the body against the roof so it carves cleanly

Closes "chimney is not getting trimmed just like in roof-system."
Previously the chimney mesh was rendered as solid geometry that
intersected the roof shell visually at the deck line — Option C
debt called out in `45038713`. Now the body is CSG-cut against the
parent segment so only the portion above the shingles is visible,
matching the archive's UX.

- `packages/viewer/src/lib/csg-utils.ts`: port `csgEvaluator`,
  `csgGeometry`, `csgMaterials`, `computeGeometryBoundsTree`,
  `prepareBrushForCSG`, and the `Brush` / `SUBTRACTION` re-exports
  from `roof-system-archive`. Lives in viewer because
  `three-bvh-csg` + `three-mesh-bvh` are viewer-only deps.
- `packages/viewer/src/index.ts`: expose the CSG primitives + the
  existing `getRoofSegmentBrushes` (which was already defined on
  main but not in the package surface). Adding `getRoofSegmentBrushes`
  to the export — internal already; this just opens it for kinds
  living in `@pascal-app/nodes`.
- `packages/nodes/src/chimney/roof-trim.ts`: new helper
  `trimChimneyBodyAgainstRoof(body, segment, node)`. Wraps the body
  in a `Brush`, runs a two-pass `SUBTRACTION` (chimney - wallBrush -
  shinSlab), returns the trimmed `BufferGeometry`. Returns the input
  unchanged on any CSG failure so the chimney still renders.
- `packages/nodes/src/chimney/renderer.tsx`: memoize a `trimmedBody`
  alongside the existing geo memo (keyed on the segment shape fields
  that drive the roof brushes) and pass it to the body mesh instead
  of `geo.body`. Disposal updated to release whichever buffer is
  actually live.

Deferred (Option C still): bands and panels CSG. They were the same
flow but operate on additional pieces; they re-light in a follow-up
once the chimney's bands / panels geometry comes back online.

Verified: workspace build green, chimney unit tests pass (14/14).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(skylight): port full v1 implementation (panel, 5-type 3D, CSG cut, animations)

Brings the skylight node from a box-only stub up to feature parity with the
roof-system branch. Mirrors the chimney port pattern established in 9fd42e33
and 65eec685.

UI
- packages/nodes/src/skylight/panel.tsx — bespoke tabbed inspector
  (type card picker + per-variant controls: lantern height/scale,
  opening angle/side/motor, sliding direction/track width, curb, frame,
  position, rotation). Wired via parametrics.customPanel.

3D
- packages/nodes/src/skylight/{renderer,geometry,frame-csg}.tsx —
  full 5-variant geometry (flat / walk-on / lantern / opening / sliding)
  with frame ring CSG and type-specific glass (lantern pyramid +
  cylindrical frame bars; opening hinged glass with optional motor
  housing; sliding two-pane on tracks).
- packages/nodes/src/skylight/preview.tsx — uses the real frame-csg
  builder so placement ghost matches the committed mesh.

Placement / move
- packages/nodes/src/skylight/tool.tsx — commits hit.localY so the
  skylight lands on the outer shingle surface, not the bare-rafter
  analytical Y (was sinking into the deck).
- packages/nodes/src/skylight/move-tool.tsx — kind-owned drag wired
  via def.affordanceTools.move. Uses SkylightPreview as the ghost so
  drag and duplicate both show the real frame following the roof
  raycast. Reparents across segments and dirties old+new for CSG
  re-cut.

CSG cutout
- packages/viewer/src/systems/roof/roof-system.tsx — buildSkylightCutBrush
  added; the per-child loop in updateMergedRoofGeometry subtracts every
  skylight from shin/deck/wall in segment-local before the segment
  transform stacks on (matches v1).
- Ported v1's getRoofOuterSurfaceFrameAtPoint helper (raycast against the
  actual outer-shingle module mesh) and made both the cut and the
  renderer read surface point + normal from it — keeps frame and cut
  aligned on every roof type incl. hip 4-faces, gambrel, mansard, dutch.
- mergeVertices on the cut box before computeBoundsTree — without it
  three-bvh-csg silently no-ops on the BoxGeometry after applyQuaternion
  tilts the cut ~90° about the surface normal (hip short faces).
- Renderer wraps content in an outer <group position={segment.position}
  rotation-y={segment.rotation}> so the frame inherits the same segment
  transform that applyTransform bakes into the cut brush (skylight is
  rendered under <group name="roof-elements"> at the roof level, not
  under the segment, so the renderer has to apply it explicitly).
- Skylight dirty propagation in RoofSystem: edits/moves dirty the host
  segment so the parent roof rebuilds.
- packages/viewer/src/index.ts — exposes getRoofOuterSurfaceFrameAtPoint,
  SurfaceFrame, getRoofSegmentBrushes, csg primitives so @pascal-app/nodes
  can compose roof-aware cuts without a layer violation.

Animations
- packages/editor/src/lib/skylight-interaction.ts — verbatim port of v1
  (toggleSkylightOpenState, closeSkylightOpenState, isOperableSkylightType,
  SKYLIGHT_TOGGLE_ANIMATION_MS = 520).
- packages/editor/src/hooks/use-keyboard.ts — R toggles, T closes
  operable skylights, mirroring door/window.
- packages/nodes/src/skylight/system.tsx — SkylightAnimationSystem
  ported as def.system; advances skylightAnimations and writes
  operationState back to useInteractive.skylights.
- Dropped the per-tick markSkylightDirty in the animation system. The
  renderer subscribes to useInteractive directly, so the glass swings/
  slides via Zustand re-renders without dirtying the scene — the cut
  geometry doesn't depend on operationState, so re-CSG'ing the merged
  roof on every animation frame was pure waste (caused visible lag).
- packages/core/src/index.ts — exports SkylightInteractiveState and
  SkylightAnimationState (interaction lib uses them).

Drag / duplicate ghost
- Floating action menu's setMovingNode → MoveTool → registry affordance
  now resolves to the kind-owned move tool. Duplicate already worked
  through structuredClone + def.schema.parse + setMovingNode; the new
  move-tool provides the ghost both flows use.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* Persist roof segment materials across refresh

* feat(solar-panel): full port from archive + placement/orientation fixes

Solar panel — ported from roof-system archive to registry shape:

**Inspector & presets**
- Custom panel (panel.tsx) with preset card grid (Residential / Residential
  Large / Compact / Frameless); picking a preset now writes all four dim
  fields (panelWidth / panelHeight / frameThickness / frameDepth) so the
  inspector immediately reflects the selection.
- Auto-fit to roof, Flip orientation, Custom label when no preset matches.
- Live preview: renderer subscribes to useLiveNodeOverrides so slider drags
  update the mesh before the value is committed to the Zustand store.
- Registered via parametrics.customPanel (same pattern as chimney).

**Texture / materials**
- Procedural cell texture (createSolarPanelTexture): chamfered cell shape,
  dark blue gradient, finger-line and busbar detail drawn on a 256×256
  canvas, tiled per cell via stretched UVs in buildSolarPanelGeometry.
- getDefaultPanelMaterial singleton uses MeshStandardNodeMaterial (WebGPU-
  native) so the material integrates with the MRT pass without triggering
  "Color target has no corresponding fragment stage output / writeMask not
  zero" GPU validation errors on segment reparent.
- defaultFrameMaterial and move-tool previewMaterial also switched to
  WebGPU-safe types (MeshStandardNodeMaterial / MeshBasicMaterial).

**Default grid size**
- Schema defaults changed from 4 rows × 5 columns → 2 rows × 3 columns.
- Placement ghost and move-tool ghost use a compact 2×3 footprint;
  committed panels also default to 2×3.

**Placement tool**
- Commit position uses raycast hit Y (hit.localY from segObj.worldToLocal)
  instead of analytical getSurfaceY so the panel lands exactly where the
  ghost was shown rather than sinking into the deck/shingle layers.
- Ghost orientation uses the same analytical-normal + explicit-yaw pattern
  as the placement tool for correctness on rotated segments.

**Move tool**
- Rewrote ghost to use resolveRoofSegmentHit + getAnalyticalNormal
  (segment-local) + explicit rotation-y group, matching the placement
  tool's ghost layout exactly. Dropped unreliable event.normal / world-
  space quat path that gave wrong tilt on any segment with rotation ≠ 0.
- Committed surfaceNormal is now segment-local (not world-space) so the
  renderer's surfaceQuat + outer segment.rotation group compose correctly
  without double-rotating the panel.
- Uses shared resolveRoofSegmentHit (with surface-Y disambiguation) instead
  of the private copy, so segment hopping respects the correct face.
- Reparents children arrays on segment hop.

**Renderer**
- Applies segment.position + segment.rotation explicitly (roof accessories
  are mounted under roof-elements group which has no transform, not under
  segment subtree).
- Merges useLiveNodeOverrides so slider drags update the 3D mesh in real
  time (same pattern as elevator/skylight renderers).

**Scene graph**
- SolarPanelTreeNode added; registered in tree-node.tsx type map so panels
  appear under their parent roof-segment in the sidebar.

**Segment-hit disambiguation**
- resolveRoofSegmentHit now scores all bbox-passing candidates by
  |localY − analyticalSurfaceY(localX, localZ)| and picks the smallest,
  fixing the long-standing bug where hip/gable segments at the same roof
  origin all pass the axis-aligned bbox test and the first-match (always
  segments[0]) was returned regardless of which slope was clicked.
  Benefits all roof-accessory placement tools (chimney, box-vent, skylight,
  dormer, solar-panel).

**Hip-roof normal fix**
- getAnalyticalNormal for hip now uses slopeReach = min(w,d)/2 for the Y
  component on all four faces. The old code used depth/2 for front/back and
  width/2 for sides, which was only correct for square (w==d) hips; for any
  other aspect ratio the long-axis faces tilted the panel at the wrong angle.

**Dormer, dormer move-tool, window-frame, ridge-vent, box-vent, skylight**
- Assorted in-progress work: dormer window-frame geometry, move-tool port,
  panel refinements, ridge-vent / box-vent panel additions, skylight CSG
  frame refinements, roof-system geometry improvements, material-paint
  support, post-processing cleanup.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* perf(chimney): fix hook order + share materials + memoise segment brushes

- renderer.tsx: hoist `surfaceArray` useMemo above the `!segment || !geo`
  early return so hook call order stays stable across renders (the
  previous order would have crashed React the first time segment or geo
  flipped to null mid-session).
- renderer.tsx: replace the module-scoped `bodyMaterial` / `topMaterial`
  singletons with per-instance fallback materials so a paint-mode or
  debug mutation on one chimney can't bleed into every other unpainted
  chimney on the scene; dispose them on unmount.
- renderer.tsx: collapse the 36-field hand-maintained dep array on the
  `geo` useMemo (and the 10-field one on `trimmedBody`) down to the
  memoised `node` / `segment` references — adding a new schema field
  no longer risks stale geometry from a forgotten dep, and the
  `eslint-disable react-hooks/exhaustive-deps` lines are gone.
- renderer.tsx + roof-trim.ts: memoise `getRoofSegmentBrushes(segment)`
  per-segment-shape in the renderer instead of rebuilding the four
  CSG-ready brushes inside `trimChimneyBodyAgainstRoof` on every call.
  A chimney slider drag changes `node.*` but not the segment, so the
  brushes now survive the entire drag instead of being rebuilt and
  disposed every frame.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* test(scene): pin reparent behavior for roof-mounted kinds under repeated A→B→A→B

Investigating a reported crash where moving a vent across roof
segments three times in a row crashes the scene. The hypothesis was
duplicate IDs in the host segments' `children` arrays. These tests
prove that's NOT the cause: at the store level, the auto-reparent
inside `updateNodesAction` leaves children lists clean under repeated
hopping for every roof-mounted kind (box-vent, chimney, skylight,
dormer, solar-panel, ridge-vent), and even the redundant manual-then-
auto pattern the vent move-tools use converges to the same correct
state.

Crash root cause still under investigation, but these pins prevent
the obvious-and-tempting regression where someone "fixes" reparent
by hand and accidentally lets duplicates through.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* refactor(chimney): give each sub-mesh its own name

Body, cap, flues, cricket, and bands were all named `chimney-surface`,
so hover/selection couldn't distinguish them and panel breadcrumbs
couldn't say "Chimney cap" vs "Chimney body". Rename to
`chimney-{body,cap,flues,cricket,bands}`. No code looked up the old
literal, so this is a pure naming improvement.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(chimney): smooth round shading, radial cap UVs, cap reveal, flue pots

Four visual upgrades to the chimney builder, all in `geometry.ts`:

- **Round chimneys now render smooth, not faceted.** The previous
  `pushCylinderFaces` emitted unindexed triangles, so
  `computeVertexNormals()` baked per-triangle face normals into every
  vertex — the 24 polygon segments of a round body / cap / band were
  visible as flats. Round paths now build per-tier
  `THREE.CylinderGeometry` (indexed, side vertices shared across
  radial segments) and merge via `mergeGeometries`. Crisp rim edges
  are preserved because CylinderGeometry uses separate cap vertices.

- **Radial cap UVs.** Old `pushCylinderFaces` pushed `(0,0)` for every
  vertex on the top/bottom fan, so any texture on a round chimney
  smeared to a point at the caps. CylinderGeometry gives proper
  radial UVs (0.5 ± 0.5·cos/sin) for free.

- **Cap reveal.** The cap used to sit flush on the body, reading as
  glued on. New `CAP_REVEAL = 0.003` (3 mm) air gap above the body
  catches a shadow line and sells the cap as a separate stone / metal
  piece. `capTopY` (used for flue placement) updates so flues still
  sit on the actual cap top.

- **Flue pots, not drainpipes.** Each flue was a single straight
  cylinder / box — visually a "drainpipe", not a chimney. New
  two-tier silhouette: a tall straight shaft topped by a short
  overhanging rim (12 % of height, capped at 4 cm; rim radius
  flares 12 %). Reads as a terracotta pot. Total height still
  equals `flueHeight`, so the bore cutter in `holes.ts` covers the
  whole envelope unchanged.

Removed the now-unused `pushCylinderFaces` helper. Slab path
unchanged — square chimneys keep their crisp 90° corners.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(chimney): cornerBevel for square bodies / caps / bands

Square chimneys read as plastic boxes at any distance because every
vertical edge is a perfect 90° corner that catches no light. New
`cornerBevel` field (default 0 → existing scenes unchanged) replaces
each corner with a 45° chamfer face. Real masonry chimneys often
ship the same detail — a small bevel (~1-2 cm) breaks up the
silhouette and reads as stone or chamfered brick.

- Schema: add `cornerBevel: z.number().default(0)` to ChimneyNode.
- Geometry: extend `pushSlabFaces` with an optional `bevel` param.
  When > 0, dispatch to a new `pushOctagonalSlabFaces` that emits
  an 8-vertex ring per y-level (axis-aligned faces + 45° chamfer
  faces) plus fan-triangulated octagonal caps. UVs follow the same
  physical-meter convention as the unchamfered path so a brick
  texture tiles at a consistent rate with and without bevel.
- Thread `node.cornerBevel` through `buildBodyGeometry`,
  `buildCapGeometry`, and `buildBandsGeometry` (square paths only —
  round bodies have no corners to bevel).
- Parametrics: expose under the Body group with `visibleIf` gating
  on square body for the MCP / fallback inspector.
- Panel: add a "Corner Bevel" SliderControl in the Footprint section,
  same conditional visibility, clamped at `min(width, depth) / 2`.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(chimney): style presets — Brick / Stone / Modern / Round

The chimney panel exposes 30+ sliders; landing on a coherent
silhouette (corbeled stone with a sloped cap and a cricket vs. a
straight brick with a double band) takes a dozen edits even when
you know what you want. New "Style" segmented control at the top
of the panel applies a curated bundle of fields in one click.

Presets only touch shape / silhouette / accessory fields:
`bodyShape`, `shoulderStyle*`, `cap*`, `band*`, `cricket*`,
`cornerBevel`, `panel*`, `flue*`. Dimensions (`width`, `depth`,
`heightAboveRidge`), placement (`position`, `rotation`,
`roofSegmentId`), and paint (`material*`, `topMaterial*`) are
deliberately left alone — applying a preset to an already-sized,
already-painted chimney resizes nothing and doesn't overwrite the
user's material choices.

- `presets.ts`: four preset bundles + `detectActiveChimneyPreset`
  helper for highlighting the matching preset in the segmented
  control.
- `panel.tsx`: new "Style" PanelSection above Footprint, segmented
  control wired to `commitProp(chimneyPresets[key])`. Renders with
  no segment highlighted ("custom") when the current node doesn't
  match any preset exactly.
- `__tests__/presets.test.ts`: round-trip each preset, confirm
  fresh-default chimneys are NOT detected as any preset, and
  confirm non-preset fields (dims / materials / placement) don't
  knock a chimney out of a preset.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* refactor(chimney): drop the Stone preset

Leaves Brick / Modern / Round. The parameterised round-trip test
auto-adjusts via `CHIMNEY_PRESET_KEYS`; no test code change needed.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(dormer): bugs, perf, UX, refactor + bundled pitch WIP

Dormer review-backlog batch across five passes. Plus the previously
unstaged pitch/roofHeight migration on RoofSegmentNode bundled in per
session continuity.

Dormer — bugs / dead code:
- implement the windowSill (toggle was UI-only before)
- ghost preview reads wallSkirtHeight and branches on roofType=flat
- live-override slider drag swaps the heavy CSG for the fallback
- consolidate arch/rounded shape builders between viewer CSG and frame
- drop unused surfaceNormal field
- collapse getEffectiveDormerSurfaceMaterial fall-through
- confine the panel's updateWorldMatrix into a single useMemo
- preserve position Y on panel commits (was being zeroed)

Dormer — schema hygiene:
- DORMER_DEFAULTS named constants replace inline magic numbers
- collapse windowCornerRadius + windowRadiusMode + windowCornerRadii
  into the tuple alone; "All vs Individual" is derived UI state
- drop the `as never` id casts; rely on objectId default factory

Dormer — tactile UX:
- R / Shift+R rotates the placement ghost by ±15°
- auto-number new dormer names ("Dormer N", smallest free integer)
- DORMER_PLACEMENT_SNAP_M + ROTATION_STEP constants extracted

Dormer — code shape:
- new use-dormer-placement hook dedupes tool + move-tool (~90% shared)
- new <DormerWindowAssembly> isolates the frame/glass/sill JSX
- panel.tsx 788 -> 295 lines; Position / Window / Actions sections
  extracted into per-file components

Bundled pitch WIP (pre-existing, unrelated to dormer):
- RoofSegmentNode.roofHeight removed; pitch (degrees) added
- new helpers in roof-segment: getActiveRoofHeight,
  getPitchFromActiveRoofHeight, getSegmentSlopeFrame,
  ROOF_SHAPE_DEFAULTS
- migration in use-scene.ts converts legacy roofHeight to pitch
- consumers updated: chimney, box-vent, ridge-vent, solar-panel,
  roof-segment, roof, segment-hit, roof-tool, mcp construction-tools

Verification: 12/12 dormer tests pass; targeted tsc on dormer files
clean. Workspace bun build of nodes is also affected by the pitch WIP,
which is included here per request.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(roof): per-segment top/edge/wall materials + restore legacy UV flow

- RoofSegmentNode gains optional topMaterial / edgeMaterial / wallMaterial
  fields mirroring the parent roof. getEffectiveSegmentSurfaceMaterial
  resolves through segment-role → segment-legacy → parent fallback.
- Segment renderer builds the 4-slot array per role with the parent's
  array as a fallback so paint at any level reaches the right surface.
- Painting a segment directly (segment edit mode hover) writes to the
  segment's role fields via buildRoofSegmentSurfaceMaterialPatch — the
  parent roof and other segments are untouched.
- Segments with any material override render as their own per-segment
  mesh inside a new always-visible 'painted-segments' group; the merged-
  roof CSG skips them (hasSegmentMaterialOverride) so we don't double-
  paint with the roof's default array.
- Paint preview now dispatches to a segment-aware path
  (applyRoofSegmentPaintPreview) so hover effects land on the visible
  per-segment mesh instead of the hidden merged-roof.
- Drop the createRoofUvGeometry post-CSG re-projection. UVs now flow
  through CSG (csgEvaluator.attributes includes 'uv') exactly as in the
  legacy roof-system branch.
- Drop the stray [skylight-cut] console.log left in the hot path.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* refactor(roof-system): registry capabilities for roof accessories, paint, and keyboard

Replace kind-name branches in framework code with registry-driven dispatch.
Three new NodeDefinition slots back the migration:

- capabilities.roofAccessory — host roof cascade + optional CSG cut.
  Lets viewer's RoofSystem iterate dirty children and call buildCut on
  any kind that declares it, instead of switching on node.type. Dormer
  + skylight cut builders moved into packages/nodes/<kind>/.
- capabilities.paint — resolveRole / buildPatch / applyPreview /
  getEffectiveMaterial. Chimney, dormer, and wall now route through it;
  per-kind arms deleted from selection-manager + material-paint.
- keyboardActions — R / T handlers contributed by the kind. Skylight's
  open/close logic moved from editor/lib to nodes/skylight/interaction.

Dormer + skylight kind code (geometry, fallback shape, exposed-face math,
window-dim resolver, CSG cut builders) now lives under packages/nodes/
src/<kind>/ instead of packages/viewer/src/systems/roof/roof-system.tsx.
The viewer keeps only roof-generic primitives (roof-segment brushes,
surface-frame query, CSG dummy mats, material-slot remap).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* review: remove PORT-CHEATSHEET, document roofAccessory/paint/keyboardActions, fix double registry lookup

- Remove .claude/PORT-CHEATSHEET.md (AI authoring aid, not for public repo)
- Document three new NodeDefinition capabilities in wiki/architecture/node-definitions.md:
  roofAccessory, paint, keyboardActions
- Fix double nodeRegistry.get() lookup in use-keyboard.ts: replace !.keyboardActions!.r!.run()
  with ?.keyboardActions?.r?.run() for both R and T arms

* fix(item-placement): memoize preview/dimension callbacks to stop placement loop

updatePreviewGeometry and updateDimensionGuides were declared as plain
functions in the component body, so they got a fresh identity every
render. Both sit in the placement setup effect's dependency array, which
made React tear the effect down and re-run it on every commit — its
teardown deletes the draft node while the setup re-creates it, producing
an infinite delete/recreate loop ("Maximum update depth exceeded") when
opening furnish mode.

Wrap both in useCallback with empty deps (they only close over stable
refs, module-level helpers, and the setDimensionBounds setter).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(item-placement): correct preview box dimensions and floor rotation

Two issues surfaced after the placement-loop memoization removed the
accidental every-render recompute that was masking them:

1. Preview box used stale (asset-default) dimensions at draft creation
   because nothing recomputed it once the imperative draft was made.
   Recompute the box from the freshly-created draft in `ensureDraft` and
   the chained next-draft path in `onGridClick`.

2. The green/red box (and the live transform the 2D floorplan mirrors)
   ignored the floor item's rotation:
   - `floorStrategy.move` returned a hardcoded `cursorRotationY: 0`; now
     returns the draft's rotation (`rotY`).
   - `onGridMove` never applied `result.cursorRotationY` to the cursor
     group; now it does, so box + floorplan track the draft on every move.
   - the init seed used the mesh world quaternion, which double-counts
     building rotation for floor items; floor now seeds from the node's
     local Y rotation (wall/ceiling keep the world-quaternion path).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
Co-authored-by: open-pascal <open@pascal.app>
Co-authored-by: Wassim SAMAD <wass08@gmail.com>
This commit is contained in:
Sudhir Yadav
2026-05-22 12:14:22 -04:00
committed by GitHub
co-authored by Claude Opus 4.7 open-pascal Wassim SAMAD
parent 3cb318e445
commit 87384cfbab
147 changed files with 17913 additions and 234 deletions
@@ -0,0 +1,43 @@
import { describe, expect, test } from 'bun:test'
import {
buildDormerGhostGeometry,
dormerSupportsArch,
dormerSupportsCornerRadii,
} from '../geometry'
import { DormerNode } from '../schema'
describe('buildDormerGhostGeometry (placement preview)', () => {
test('returns a buffer geometry with position attribute', () => {
const geo = buildDormerGhostGeometry(DormerNode.parse({}))
expect(geo.getAttribute('position').count).toBeGreaterThan(0)
})
test('width / depth drive the silhouette footprint', () => {
const geo = buildDormerGhostGeometry(DormerNode.parse({ width: 2, depth: 4, height: 1 }))
geo.computeBoundingBox()
const bb = geo.boundingBox!
expect(bb.max.x - bb.min.x).toBeCloseTo(2)
expect(bb.max.z - bb.min.z).toBeCloseTo(4)
})
test('roofHeight raises the gable peak', () => {
const a = buildDormerGhostGeometry(DormerNode.parse({ roofHeight: 0.5 }))
const b = buildDormerGhostGeometry(DormerNode.parse({ roofHeight: 1.5 }))
a.computeBoundingBox()
b.computeBoundingBox()
expect(b.boundingBox!.max.y).toBeGreaterThan(a.boundingBox!.max.y)
})
})
describe('windowShape predicates', () => {
test('dormerSupportsArch only when windowShape=arch', () => {
expect(dormerSupportsArch(DormerNode.parse({ windowShape: 'arch' }))).toBe(true)
expect(dormerSupportsArch(DormerNode.parse({ windowShape: 'rounded' }))).toBe(false)
expect(dormerSupportsArch(DormerNode.parse({ windowShape: 'rectangle' }))).toBe(false)
})
test('dormerSupportsCornerRadii only when windowShape=rounded', () => {
expect(dormerSupportsCornerRadii(DormerNode.parse({ windowShape: 'rounded' }))).toBe(true)
expect(dormerSupportsCornerRadii(DormerNode.parse({ windowShape: 'arch' }))).toBe(false)
expect(dormerSupportsCornerRadii(DormerNode.parse({ windowShape: 'rectangle' }))).toBe(false)
})
})
@@ -0,0 +1,56 @@
import { describe, expect, test } from 'bun:test'
import { getEffectiveDormerSurfaceMaterial } from '@pascal-app/core'
import { DormerNode } from '../schema'
describe('DormerNode schema', () => {
test('parses with defaults', () => {
const parsed = DormerNode.parse({})
expect(parsed.type).toBe('dormer')
expect(parsed.id).toMatch(/^dormer_/)
expect(parsed.width).toBe(1.21)
expect(parsed.depth).toBe(1.55)
expect(parsed.height).toBe(0)
expect(parsed.roofType).toBe('gable')
expect(parsed.windowShape).toBe('rectangle')
expect(parsed.windowSill).toBe(true)
})
test('windowColumns / windowRows clamped to [1, 8]', () => {
expect(() => DormerNode.parse({ windowColumns: 0 })).toThrow()
expect(() => DormerNode.parse({ windowColumns: 9 })).toThrow()
expect(() => DormerNode.parse({ windowRows: 1.5 })).toThrow()
})
test('windowCornerRadii round-trips as tuple of 4', () => {
const parsed = DormerNode.parse({ windowCornerRadii: [0.1, 0.2, 0.3, 0.4] })
expect(parsed.windowCornerRadii).toEqual([0.1, 0.2, 0.3, 0.4])
})
})
describe('getEffectiveDormerSurfaceMaterial', () => {
test('top role prefers topMaterialPreset, falls back to legacy materialPreset', () => {
const node = DormerNode.parse({
materialPreset: 'red',
topMaterialPreset: 'blue',
})
expect(getEffectiveDormerSurfaceMaterial(node, 'top').materialPreset).toBe('blue')
expect(getEffectiveDormerSurfaceMaterial(node, 'wall').materialPreset).toBe('red')
})
test('side role cross-falls-back to wallMaterialPreset', () => {
const node = DormerNode.parse({ wallMaterialPreset: 'wallpaper' })
expect(getEffectiveDormerSurfaceMaterial(node, 'side').materialPreset).toBe('wallpaper')
})
test('wall role cross-falls-back to sideMaterialPreset', () => {
const node = DormerNode.parse({ sideMaterialPreset: 'cedar' })
expect(getEffectiveDormerSurfaceMaterial(node, 'wall').materialPreset).toBe('cedar')
})
test('all three roles fall back to legacy materialPreset when nothing set', () => {
const node = DormerNode.parse({ materialPreset: 'stucco' })
expect(getEffectiveDormerSurfaceMaterial(node, 'top').materialPreset).toBe('stucco')
expect(getEffectiveDormerSurfaceMaterial(node, 'side').materialPreset).toBe('stucco')
expect(getEffectiveDormerSurfaceMaterial(node, 'wall').materialPreset).toBe('stucco')
})
})
+841
View File
@@ -0,0 +1,841 @@
import {
type DormerNode,
getActiveRoofHeight,
getPitchFromActiveRoofHeight,
ROOF_SHAPE_DEFAULTS,
type RoofSegmentNode,
} from '@pascal-app/core'
import {
ADDITION,
Brush,
computeGeometryBoundsTree,
csgEvaluator,
csgGeometry,
csgMaterials,
getRoofSegmentBrushes,
mapRoofGroupMaterialIndex,
prepareBrushForCSG,
remapRoofShellFaces,
roofCsgDummyMats,
SUBTRACTION,
} from '@pascal-app/viewer'
import * as THREE from 'three'
import {
mergeGeometries,
mergeVertices,
} from 'three/examples/jsm/utils/BufferGeometryUtils.js'
// Legacy default for the hung-wall (skirt) height. Used as a fallback
// when `dormer.wallSkirtHeight` is undefined (e.g. old saved scenes).
const DORMER_DROP_BELOW = 2
function dormerSkirtHeight(dormer: DormerNode): number {
return Math.max(0.05, dormer.wallSkirtHeight ?? DORMER_DROP_BELOW)
}
export const DORMER_GABLE_MATERIAL_INDEX = 4
const _yAxis = new THREE.Vector3(0, 1, 0)
const _scale = new THREE.Vector3(1, 1, 1)
/**
* Cheap silhouette geometry. Used as a fallback when CSG cannot run
* (missing host brushes, thrown exception, degenerate inputs) and as
* the live preview during slider drags so we don't re-run CSG on every
* pointer move. Also used by the placement / move-tool ghost.
*
* Builds a rectangular body + simple roof in dormer-mesh-local. For
* `flat` dormers the roof triangle is skipped. Other roof types use
* the gable approximation — it's a rough silhouette by design.
*
* The wall sits at material slot 0 and the roof at slot 3 so it picks
* up the same material array the renderer passes for the CSG output.
*/
export function buildDormerFallbackGeometry(dormer: DormerNode): THREE.BufferGeometry {
const w = Math.max(0.05, dormer.width)
const d = Math.max(0.05, dormer.depth)
const wallH = Math.max(0.05, dormer.height)
const roofH = Math.max(0, dormer.roofHeight)
const skirt = dormerSkirtHeight(dormer)
const isFlat = dormer.roofType === 'flat' || roofH === 0
// Body box: foot at y = -skirt, top at y = wallH.
const body = new THREE.BoxGeometry(w, wallH + skirt, d)
body.translate(0, (wallH - skirt) / 2, 0)
const bIdx = body.getIndex()?.count ?? 0
body.clearGroups()
body.addGroup(0, bIdx, 0)
if (isFlat) {
if (!body.getAttribute('normal')) body.computeVertexNormals()
return body
}
// Roof: extruded triangle from eave (y = wallH) to peak (y = wallH + roofH).
// Apex points along +Y, base spans the width. Extrude along Z (depth).
const roofShape = new THREE.Shape()
roofShape.moveTo(-w / 2, 0)
roofShape.lineTo(w / 2, 0)
roofShape.lineTo(0, roofH)
roofShape.lineTo(-w / 2, 0)
const roof = new THREE.ExtrudeGeometry(roofShape, { depth: d, bevelEnabled: false })
roof.translate(0, wallH, -d / 2)
const rIdx = roof.getIndex()?.count ?? 0
roof.clearGroups()
roof.addGroup(0, rIdx, 3)
const merged = mergeGeometries([body, roof], true) ?? body
body.dispose()
roof.dispose()
if (!merged.getAttribute('normal')) merged.computeVertexNormals()
return merged
}
export function createDormerArchShape(w: number, h: number, archHeight: number): THREE.Shape {
const hw = w / 2
const hh = h / 2
const clampedArch = Math.min(Math.max(archHeight, 0.01), Math.max(h, 0.01))
const springY = hh - clampedArch
const segments = 32
const shape = new THREE.Shape()
shape.moveTo(-hw, -hh)
shape.lineTo(hw, -hh)
shape.lineTo(hw, springY)
for (let i = 1; i <= segments; i++) {
const x = hw + (-hw - hw) * (i / segments)
const t = Math.min(Math.abs(x) / hw, 1)
const y = springY + clampedArch * Math.sqrt(Math.max(1 - t * t, 0))
shape.lineTo(x, y)
}
shape.lineTo(-hw, -hh)
shape.closePath()
return shape
}
export function normalizeDormerCornerRadii(
radii: [number, number, number, number],
w: number,
h: number,
): [number, number, number, number] {
const r = radii.map((v) => Math.max(v, 0)) as [number, number, number, number]
const scale = Math.min(
1,
Math.max(w, 0) / Math.max(r[0] + r[1], 1e-6),
Math.max(w, 0) / Math.max(r[3] + r[2], 1e-6),
Math.max(h, 0) / Math.max(r[0] + r[3], 1e-6),
Math.max(h, 0) / Math.max(r[1] + r[2], 1e-6),
)
if (scale >= 1) return r
return r.map((v) => v * scale) as [number, number, number, number]
}
export function createDormerRoundedShape(
w: number,
h: number,
radii: [number, number, number, number],
): THREE.Shape {
const hw = w / 2
const hh = h / 2
const [tl, tr, br, bl] = normalizeDormerCornerRadii(radii, w, h)
const shape = new THREE.Shape()
shape.moveTo(-hw + bl, -hh)
shape.lineTo(hw - br, -hh)
if (br > 0) shape.absarc(hw - br, -hh + br, br, -Math.PI / 2, 0, false)
else shape.lineTo(hw, -hh)
shape.lineTo(hw, hh - tr)
if (tr > 0) shape.absarc(hw - tr, hh - tr, tr, 0, Math.PI / 2, false)
else shape.lineTo(hw, hh)
shape.lineTo(-hw + tl, hh)
if (tl > 0) shape.absarc(-hw + tl, hh - tl, tl, Math.PI / 2, Math.PI, false)
else shape.lineTo(-hw, hh)
shape.lineTo(-hw, -hh + bl)
if (bl > 0) shape.absarc(-hw + bl, -hh + bl, bl, Math.PI, (3 * Math.PI) / 2, false)
else shape.lineTo(-hw, -hh)
shape.closePath()
return shape
}
function resolveDormerRadii(
dormer: DormerNode,
w: number,
h: number,
): [number, number, number, number] {
return normalizeDormerCornerRadii(dormer.windowCornerRadii, w, h)
}
function createDormerWindowCutGeometry(
dormer: DormerNode,
w: number,
h: number,
depth: number,
): THREE.BufferGeometry {
const shape = dormer.windowShape ?? 'rectangle'
if (shape === 'arch') {
const s = createDormerArchShape(w, h, dormer.windowArchHeight ?? 0.35)
const geo = new THREE.ExtrudeGeometry(s, { depth, bevelEnabled: false, curveSegments: 24 })
geo.translate(0, 0, -depth / 2)
return geo
}
if (shape === 'rounded') {
const radii = resolveDormerRadii(dormer, w, h)
const s = createDormerRoundedShape(w, h, radii)
const geo = new THREE.ExtrudeGeometry(s, { depth, bevelEnabled: false, curveSegments: 24 })
geo.translate(0, 0, -depth / 2)
return geo
}
return new THREE.BoxGeometry(w, h, depth)
}
/**
* Which faces of a dormer are exposed (not fully buried in the host
* roof). "front" = mesh-local +Z, "back" = mesh-local Z (after the
* +π/2 yaw bake for non-shed roofs). A face is exposed when the
* dormer's total wall top exceeds the host roof surface at that face's
* Z position.
*/
export function getDormerExposedFaces(
dormer: DormerNode,
hostSegment: RoofSegmentNode,
): { front: boolean; back: boolean } {
const halfDepth = dormer.depth / 2
const dormerZ = dormer.position[2] ?? 0
const dormerY = dormer.position[1] ?? 0
const rot = dormer.rotation ?? 0
// Gable-face centres in segment-local Z (accounts for dormer yaw).
const frontZ = dormerZ + halfDepth * Math.cos(rot)
const backZ = dormerZ - halfDepth * Math.cos(rot)
const dormerWallTop = dormerY + dormer.height
const hostWh = hostSegment.wallHeight ?? 0.5
const hostRh = getActiveRoofHeight(hostSegment)
const hostDepth = hostSegment.depth ?? 4
const roofHeightAtZ = (segZ: number): number => {
const hostType = hostSegment.roofType ?? 'gable'
if (hostType === 'flat') return hostWh
if (hostType === 'shed') {
const t = Math.max(0, Math.min(1, (segZ + hostDepth / 2) / Math.max(hostDepth, 0.01)))
return hostWh + hostRh * (1 - t)
}
const halfD = Math.max(hostDepth / 2, 0.01)
const t = Math.max(0, Math.min(1, Math.abs(segZ) / halfD))
return hostWh + hostRh * (1 - t)
}
// A face is "exposed" only if the dormer's wall actually pokes above
// the host roof there by a meaningful amount — otherwise the wall is
// CSG-buried and any window we render at that face will hover with
// no wall behind it. A 5cm threshold suppresses the borderline-cases
// where the wall top is essentially level with the slope.
const minPokeOut = 0.05
return {
front: dormerWallTop - roofHeightAtZ(frontZ) > minPokeOut,
back: dormerWallTop - roofHeightAtZ(backZ) > minPokeOut,
}
}
/**
* Computed dimensions for the window opening on a dormer's gable face.
* The skirt (the wall extension below the eave used for CSG-trim) is
* `DORMER_DROP_BELOW` tall, so the window sits within that band.
*/
export function getDormerSkirtWindowDims(dormer: DormerNode): {
width: number
height: number
centerY: number
offsetX: number
} {
const skirtH = dormerSkirtHeight(dormer)
const maxW = Math.max(dormer.width - 0.1, 0.1)
const maxH = Math.max(skirtH - 0.1, 0.1)
const width = Math.min(Math.max(dormer.windowWidth ?? 1.2, 0.1), maxW)
const height = Math.min(Math.max(dormer.windowHeight ?? 1.2, 0.1), maxH)
const offsetX = dormer.windowOffsetX ?? 0
const offsetY = dormer.windowOffsetY ?? 0
const centerY = -(skirtH / 2) + offsetY
return { width, height, centerY, offsetX }
}
/**
* Build the trimmed dormer geometry hosted on a roof segment. The
* dormer's own walls+roof are generated via `getRoofSegmentBrushes`
* on a virtual segment, then the host segment's filled solid is
* CSG-subtracted in dormer-mesh-local space. Window openings are then
* subtracted on each exposed gable face.
*/
export function generateDormerGeometry(
dormer: DormerNode,
hostSegment: RoofSegmentNode,
): THREE.BufferGeometry {
const isShed = dormer.roofType === 'shed'
const yawBake = isShed ? 0 : Math.PI / 2
const segWidth = isShed ? dormer.width : dormer.depth
const segDepth = isShed ? dormer.depth : dormer.width
const skirt = dormerSkirtHeight(dormer)
const vsWidth = Math.max(0.05, segWidth)
const vsDepth = Math.max(0.05, segDepth)
const vsActiveRh = Math.max(0, dormer.roofHeight)
const virtualSegment: RoofSegmentNode = {
object: 'node',
id: `rseg_dormer_${dormer.id}` as RoofSegmentNode['id'],
type: 'roof-segment',
parentId: null,
visible: true,
metadata: null,
children: [],
position: [0, 0, 0],
rotation: 0,
roofType: dormer.roofType,
width: vsWidth,
depth: vsDepth,
wallHeight: Math.max(0.05, dormer.height) + skirt,
// The dormer schema still expresses its roof as a height; translate
// to the pitch the segment math now expects so the virtual segment
// produces an identical peak.
pitch: getPitchFromActiveRoofHeight({
roofType: dormer.roofType,
width: vsWidth,
depth: vsDepth,
roofHeight: vsActiveRh,
}),
// Dormers don't expose multi-slope shape tuning; bake the schema
// defaults so the virtualSegment renders the canonical kink positions.
...ROOF_SHAPE_DEFAULTS,
wallThickness: 0.05,
deckThickness: 0.04,
overhang: 0.08,
shingleThickness: 0.02,
}
const dormerBrushes = getRoofSegmentBrushes(virtualSegment)
if (!dormerBrushes) {
// biome-ignore lint/suspicious/noConsole: keep diagnostic — fallback path.
console.warn('[dormer] getRoofSegmentBrushes returned null; using fallback silhouette.')
return buildDormerFallbackGeometry(dormer)
}
let resultGeo = new THREE.BufferGeometry()
let dormerSolid: Brush | null = null
let hostSolid: Brush | null = null
try {
const hollowWall = csgEvaluator.evaluate(
dormerBrushes.wallBrush,
dormerBrushes.innerBrush,
SUBTRACTION,
) as Brush
const shinDeck = csgEvaluator.evaluate(
dormerBrushes.shinSlab,
dormerBrushes.deckSlab,
ADDITION,
) as Brush
dormerSolid = csgEvaluator.evaluate(shinDeck, hollowWall, ADDITION) as Brush
hollowWall.geometry.dispose()
shinDeck.geometry.dispose()
const bakeMatrix = new THREE.Matrix4().compose(
new THREE.Vector3(0, -skirt, 0),
new THREE.Quaternion().setFromAxisAngle(_yAxis, yawBake),
_scale,
)
csgGeometry(dormerSolid).applyMatrix4(bakeMatrix)
prepareBrushForCSG(dormerSolid)
const hostBrushes = getRoofSegmentBrushes(hostSegment)
if (hostBrushes) {
const wallPlusDeck = csgEvaluator.evaluate(
hostBrushes.wallBrush,
hostBrushes.deckSlab,
ADDITION,
) as Brush
hostSolid = csgEvaluator.evaluate(wallPlusDeck, hostBrushes.shinSlab, ADDITION) as Brush
wallPlusDeck.geometry.dispose()
hostBrushes.deckSlab.geometry.dispose()
hostBrushes.shinSlab.geometry.dispose()
hostBrushes.wallBrush.geometry.dispose()
hostBrushes.innerBrush.geometry.dispose()
// Union a deep ground box covering the host footprint so the
// dormer's skirt (extending below y=0) has something to subtract.
const groundMargin = Math.max(hostSegment.width, hostSegment.depth) * 2 + 4
const groundBoxGeo = new THREE.BoxGeometry(groundMargin, 100, groundMargin)
groundBoxGeo.translate(0, -50, 0)
const indexCount = groundBoxGeo.getIndex()?.count ?? 0
groundBoxGeo.clearGroups()
groundBoxGeo.addGroup(0, indexCount, 0)
computeGeometryBoundsTree(groundBoxGeo)
const groundBrush = new Brush(groundBoxGeo, roofCsgDummyMats[0])
groundBrush.updateMatrixWorld()
const fullTrim = csgEvaluator.evaluate(hostSolid, groundBrush, ADDITION) as Brush
hostSolid.geometry.dispose()
groundBrush.geometry.dispose()
hostSolid = fullTrim
// Host brushes live in segment-local. Bring them into
// dormer-mesh-local by inverting T(node.position) · R_y(node.rotation).
const segToMesh = new THREE.Matrix4()
.compose(
new THREE.Vector3(
dormer.position[0] ?? 0,
dormer.position[1] ?? 0,
dormer.position[2] ?? 0,
),
new THREE.Quaternion().setFromAxisAngle(_yAxis, dormer.rotation),
_scale,
)
.invert()
csgGeometry(hostSolid).applyMatrix4(segToMesh)
prepareBrushForCSG(hostSolid)
const trimmed = csgEvaluator.evaluate(dormerSolid, hostSolid, SUBTRACTION) as Brush
dormerSolid.geometry.dispose()
hostSolid.geometry.dispose()
hostSolid = null
dormerSolid = trimmed
}
// Cut window openings on exposed gable faces.
const exposed = getDormerExposedFaces(dormer, hostSegment)
const skirtWin = getDormerSkirtWindowDims(dormer)
const gableHalfZ = dormer.depth / 2
const cutDepth = 0.4
const cutFace = (zSign: number) => {
const cutGeo = createDormerWindowCutGeometry(
dormer,
skirtWin.width,
skirtWin.height,
cutDepth,
)
cutGeo.translate(skirtWin.offsetX, skirtWin.centerY, zSign * gableHalfZ)
if (!cutGeo.getIndex()) {
const posCount = cutGeo.getAttribute('position').count
const idx = new Uint32Array(posCount)
for (let i = 0; i < posCount; i++) idx[i] = i
cutGeo.setIndex(new THREE.BufferAttribute(idx, 1))
}
const idxCount = cutGeo.getIndex()!.count
cutGeo.clearGroups()
cutGeo.addGroup(0, idxCount, 0)
computeGeometryBoundsTree(cutGeo)
const brush = new Brush(cutGeo, roofCsgDummyMats[0])
brush.updateMatrixWorld()
const result = csgEvaluator.evaluate(dormerSolid!, brush, SUBTRACTION) as Brush
dormerSolid!.geometry.dispose()
brush.geometry.dispose()
dormerSolid = result
}
if (exposed.front) cutFace(+1)
if (exposed.back) cutFace(-1)
resultGeo = csgGeometry(dormerSolid)
const resultMaterials = csgMaterials(dormerSolid)
const matToIndex = new Map<THREE.Material, number>([
[roofCsgDummyMats[0], 0],
[roofCsgDummyMats[1], 1],
[roofCsgDummyMats[2], 2],
[roofCsgDummyMats[3], 3],
])
for (const group of resultGeo.groups) {
group.materialIndex = mapRoofGroupMaterialIndex(
group.materialIndex,
resultMaterials,
matToIndex,
)
}
remapRoofShellFaces(resultGeo, virtualSegment)
splitDormerGableMaterial(resultGeo, dormer.height, DORMER_GABLE_MATERIAL_INDEX)
} catch (e) {
// biome-ignore lint/suspicious/noConsole: dormer CSG can throw; keep diagnostic.
console.error('[dormer] CSG failed, falling back to silhouette:', e)
if (dormerSolid) {
try {
dormerSolid.geometry.dispose()
} catch {}
}
if (hostSolid) {
try {
hostSolid.geometry.dispose()
} catch {}
}
return buildDormerFallbackGeometry(dormer)
}
// If CSG produced zero triangles (host fully buried it, or one of the
// boolean ops collapsed to empty), fall back to the silhouette so the
// dormer is at least visible.
const triCount = resultGeo.getIndex()?.count ?? resultGeo.getAttribute('position')?.count ?? 0
if (triCount === 0) {
// biome-ignore lint/suspicious/noConsole: keep diagnostic — empty CSG.
console.warn('[dormer] CSG produced empty geometry; using fallback silhouette.')
return buildDormerFallbackGeometry(dormer)
}
resultGeo.computeVertexNormals()
ensureUv2Attribute(resultGeo)
return resultGeo
}
/**
* Build the dormer cut shape in dormer-mesh-local coordinates. The
* returned geometry is centered at X=Z=0 and spans Y ∈ [-skirt, peak]
* — the caller layers on the dormer's yaw + position to bring it into
* segment-local space.
*
* Shapes per roof type:
* - **flat**: a plain box (top flush with the eave; the
* dormer body has no roof above wallH).
* - **shed**: trapezoid in YZ, extruded along X. Eave
* at z=+d/2 (y=wallH), peak at z=-d/2
* (y=wallH+roofH) — matches the slope
* direction the dormer body uses.
* - **gable / gambrel**: pentagon (rectangle + symmetric triangle)
* in XY, extruded along Z. Ridge runs
* along Z (mesh-Z = virtualSegment-X after
* the yaw bake).
* - **hip / dutch / mansard**: pyramid — rectangular base, single
* apex at the peak. Narrows on all four
* sides.
*
* Gambrel / dutch / mansard fall back to gable / hip rather than the
* legacy CSG-derived geometry, because three-bvh-csg's three-way
* subtraction in the merged-roof loop can't accept CSG-derived
* brushes without corrupting the result. The dormer body itself still
* carries the precise per-type shape; the cut just needs to clear
* enough of the host shell for the body to sit cleanly.
*/
export function buildDormerCutShape(
roofType: DormerNode['roofType'],
innerW: number,
innerD: number,
skirt: number,
wallH: number,
roofH: number,
): THREE.BufferGeometry {
const hw = innerW / 2
const hd = innerD / 2
if (roofType === 'flat') {
const geo = new THREE.BoxGeometry(innerW, skirt + wallH, innerD)
geo.translate(0, (wallH - skirt) / 2, 0)
return geo
}
if (roofType === 'shed') {
// Trapezoid in shape XY → extruded along Z (shape's natural
// extrude axis) → rotated +π/2 around Y so the shape's X axis
// ends up along mesh-(-Z) and the extrusion ends up along mesh-X.
//
// `getRoofSegmentBrushes`'s shed slope puts the peak at z=-d/2
// and the eave at z=+d/2 (matching the `roofHeightAtZ` helper).
// After the +π/2 rotation, shape-X=+hd → mesh-Z=-hd, so place the
// PEAK at shape-X=+hd and the EAVE at shape-X=-hd to keep the cut
// aligned with the dormer body's actual slope direction.
const shape = new THREE.Shape()
shape.moveTo(-hd, -skirt)
shape.lineTo(hd, -skirt)
shape.lineTo(hd, wallH + roofH) // peak (lands at mesh-Z = -d/2)
shape.lineTo(-hd, wallH) // eave (lands at mesh-Z = +d/2)
shape.closePath()
const geo = new THREE.ExtrudeGeometry(shape, {
depth: innerW,
bevelEnabled: false,
})
geo.rotateY(Math.PI / 2)
geo.translate(-innerW / 2, 0, 0) // centre along X
return geo
}
if (roofType === 'hip' || roofType === 'dutch' || roofType === 'mansard') {
// Truncated pyramid: rectangular base + eave rect + a top ridge
// along the longer axis. Mirrors `getRoofSegmentBrushes`'s hip:
// run = min(w, d) / 2
// ridge length = |w - d| (zero when w == d → degenerates to a
// single apex point)
//
// For non-shed dormers, `virtualSegment.width = dormer.depth` runs
// along mesh-Z, so the longer-axis ridge direction follows the
// larger of innerD vs. innerW.
//
// Triangle windings below are CCW from outside (verified
// case-by-case via cross-product test); three-bvh-csg uses the
// normals to determine inside/outside for SUBTRACTION, so an
// inverted winding here would make the cut subtract the
// complement of the dormer footprint — a hand-built pyramid is
// the only shape in this file that does NOT get its windings from
// Three.js geometry primitives, so we have to wind it carefully.
const longerIsZ = innerD >= innerW
const ridgeHalfLen = Math.max(0, (Math.max(innerW, innerD) - Math.min(innerW, innerD)) / 2)
const peakY = wallH + roofH
// Ridge endpoints in mesh frame.
const ridgeA = longerIsZ
? ([0, peakY, -ridgeHalfLen] as const)
: ([-ridgeHalfLen, peakY, 0] as const)
const ridgeB = longerIsZ
? ([0, peakY, ridgeHalfLen] as const)
: ([ridgeHalfLen, peakY, 0] as const)
const positions = new Float32Array([
// 0..3 = bottom rect (y = -skirt) — NW, NE, SE, SW
-hw, -skirt, -hd,
hw, -skirt, -hd,
hw, -skirt, hd,
-hw, -skirt, hd,
// 4..7 = eave rect (y = wallH) — NW, NE, SE, SW
-hw, wallH, -hd,
hw, wallH, -hd,
hw, wallH, hd,
-hw, wallH, hd,
// 8 = ridge endpoint A (- end along the ridge axis)
ridgeA[0], ridgeA[1], ridgeA[2],
// 9 = ridge endpoint B (+ end along the ridge axis)
ridgeB[0], ridgeB[1], ridgeB[2],
])
// Triangles (CCW from outside). Windings verified by computing
// `(v1-v0) × (v2-v0)` for each triangle and checking the normal
// points along the expected outward direction.
const indices: number[] = [
// Bottom (normal -Y).
0, 1, 2, 0, 2, 3,
// -Z wall (normal -Z) — eave 4,5 on top, base 0,1 below.
1, 0, 4, 1, 4, 5,
// +X wall (normal +X) — eave 5,6 on top, base 1,2 below.
2, 1, 5, 2, 5, 6,
// +Z wall (normal +Z) — eave 6,7 on top, base 2,3 below.
3, 2, 6, 3, 6, 7,
// -X wall (normal -X) — eave 7,4 on top, base 3,0 below.
0, 3, 7, 0, 7, 4,
]
if (longerIsZ) {
// Ridge along Z. A=8 at -Z end, B=9 at +Z end.
// -Z end face (triangle, normal -Z/+Y): 4, 8, 5
// +X side face (quad, normal +X/+Y): 5, 9, 6 + 5, 8, 9
// +Z end face (triangle, normal +Z/+Y): 6, 9, 7
// -X side face (quad, normal -X/+Y): 7, 8, 4 + 7, 9, 8
indices.push(4, 8, 5)
indices.push(5, 9, 6, 5, 8, 9)
indices.push(6, 9, 7)
indices.push(7, 8, 4, 7, 9, 8)
} else {
// Ridge along X. A=8 at -X end, B=9 at +X end.
// -X end face (triangle, normal -X/+Y): 4, 7, 8
// -Z side face (quad, normal -Z/+Y): 4, 9, 5 + 4, 8, 9
// +X end face (triangle, normal +X/+Y): 5, 9, 6
// +Z side face (quad, normal +Z/+Y): 6, 8, 7 + 6, 9, 8
indices.push(4, 7, 8)
indices.push(4, 9, 5, 4, 8, 9)
indices.push(5, 9, 6)
indices.push(6, 8, 7, 6, 9, 8)
}
const geo = new THREE.BufferGeometry()
geo.setAttribute('position', new THREE.BufferAttribute(positions, 3))
geo.setIndex(new THREE.BufferAttribute(new Uint16Array(indices), 1))
// CSG evaluator requires 'uv'; cut brushes are never rendered so zeros are fine.
geo.setAttribute('uv', new THREE.BufferAttribute(new Float32Array((positions.length / 3) * 2), 2))
geo.computeVertexNormals()
return geo
}
if (roofType === 'gambrel') {
// Gambrel: two-segment slope per side. `getRoofSegmentBrushes`
// uses `run = depth / 4` and `rise = activeRh * 0.6` for the
// outer (steeper) portion. The cut profile in XY mirrors that —
// straight from eave up to a kink at (±hw/2, wallH + 0.6*roofH),
// then up to the ridge at (0, wallH + roofH). Extruded along Z.
const kinkX = hw / 2
const kinkY = wallH + roofH * 0.6
const shape = new THREE.Shape()
shape.moveTo(-hw, -skirt)
shape.lineTo(hw, -skirt)
shape.lineTo(hw, wallH)
shape.lineTo(kinkX, kinkY)
shape.lineTo(0, wallH + roofH)
shape.lineTo(-kinkX, kinkY)
shape.lineTo(-hw, wallH)
shape.closePath()
const geo = new THREE.ExtrudeGeometry(shape, {
depth: innerD,
bevelEnabled: false,
})
geo.translate(0, 0, -innerD / 2)
return geo
}
// gable (and any unrecognised type) — pentagon (rectangle +
// symmetric triangle peak), extruded along Z. Ridge runs along Z,
// matching mesh-Z which (for non-shed types) corresponds to the
// virtualSegment-X gable ridge direction after the +π/2 yaw bake
// the body geometry uses.
const shape = new THREE.Shape()
shape.moveTo(-hw, -skirt)
shape.lineTo(hw, -skirt)
shape.lineTo(hw, wallH)
shape.lineTo(0, wallH + roofH)
shape.lineTo(-hw, wallH)
shape.closePath()
const geo = new THREE.ExtrudeGeometry(shape, {
depth: innerD,
bevelEnabled: false,
})
geo.translate(0, 0, -innerD / 2)
return geo
}
/**
* Build the segment-local cut geometry the host roof's merge loop
* subtracts from its shin / deck / wall brushes so the dormer has a
* clean hole to poke through. Mirrors `generateDormerGeometry`'s
* virtual-segment + bake: build the inner shape in
* virtual-segment-local, apply the dormer's yaw + drop-below bake,
* then the dormer's segment-local position + rotation, so the
* geometry lives in host-segment-local — the same frame the
* merged-roof CSG loop operates in.
*
* Returns null on degenerate input so the caller can skip the cut.
*
* Coordinates are SEGMENT-LOCAL. The viewer welds vertices, attaches
* a single material group, and wraps the result in a Brush — see
* `wiki/architecture/node-definitions.md` (`capabilities.roofAccessory.buildCut`).
*/
export function buildDormerRoofCut(dormer: DormerNode): THREE.BufferGeometry | null {
// Defensive: bail on any non-finite or sub-millimeter dimension. A
// degenerate cut brush passed to three-bvh-csg can produce a result
// buffer with NaN positions / invalid indices, which the WebGPU
// renderer then refuses to submit ("Invalid CommandBuffer") and the
// error cascades to every subsequent submit.
const dims = [
dormer.width,
dormer.depth,
dormer.height,
dormer.roofHeight,
dormer.wallSkirtHeight,
dormer.position[0],
dormer.position[1],
dormer.position[2],
dormer.rotation,
]
for (const v of dims) {
if (!Number.isFinite(v)) return null
}
if (dormer.width < 0.01 || dormer.depth < 0.01) return null
const skirt = dormerSkirtHeight(dormer)
const wallThickness = 0.05
const innerW = Math.max(0.05, dormer.width - 2 * wallThickness)
const innerD = Math.max(0.05, dormer.depth - 2 * wallThickness)
const wallH = Math.max(0.05, dormer.height)
const roofH = Math.max(0, dormer.roofHeight)
// Cut footprint matches the dormer's INNER cavity (outer dim minus
// the 0.05m wall thickness on each side); the dormer's own outer
// wall sits over the resulting 5cm strip of host roof, hiding it
// and preventing the sub-pixel gap an exact outer-footprint cut
// would expose where dormer wall meets host roof.
//
// The shape ABOVE the eave varies per roof type so the host hole
// matches the dormer body's outline:
// - flat: box (no peak above the eave)
// - shed: trapezoid with one sloped top edge
// - hip / dutch / mansard: pyramid (narrows on all 4 sides)
// - gable / gambrel: pentagon (narrows along width axis)
const geo = buildDormerCutShape(dormer.roofType, innerW, innerD, skirt, wallH, roofH)
// Yaw in the geometry's own (un-translated) frame so the cut aligns
// with the dormer's footprint after rotation.
if (Math.abs(dormer.rotation) > 1e-4) {
geo.rotateY(dormer.rotation)
}
// Translate into segment-local. position[1] becomes the dormer's
// local Y = 0 (the wall foot / eave line); the shape's foot at
// local Y = -skirt then sits at world Y = position[1] - skirt.
geo.translate(dormer.position[0], dormer.position[1], dormer.position[2])
// The viewer's merge loop welds vertices, attaches a single material
// group, and wraps in a Brush before subtracting from the host
// segment's shin / deck / wall. Kinds only emit the raw shape.
return geo
}
/**
* Reassign slot-0 (wall) triangles whose entire footprint sits above
* `wallHeight` to a separate material slot — lets the renderer colour
* the rectangular wall and the gable triangle differently.
*/
function splitDormerGableMaterial(
geometry: THREE.BufferGeometry,
wallHeight: number,
gableMatIndex: number,
): void {
const position = geometry.getAttribute('position') as THREE.BufferAttribute | undefined
const index = geometry.getIndex()
if (!(position && index) || index.count === 0 || geometry.groups.length === 0) return
const triangleCount = index.count / 3
if (triangleCount === 0) return
const triangleMats = new Array<number>(triangleCount).fill(0)
for (const g of geometry.groups) {
const startTri = Math.floor(g.start / 3)
const endTri = Math.floor((g.start + g.count) / 3)
const mat = g.materialIndex ?? 0
for (let i = startTri; i < endTri; i++) triangleMats[i] = mat
}
const epsilon = 0.001
for (let i = 0; i < triangleCount; i++) {
if (triangleMats[i] !== 0) continue
const a = index.getX(i * 3)
const b = index.getX(i * 3 + 1)
const c = index.getX(i * 3 + 2)
const ya = position.getY(a)
const yb = position.getY(b)
const yc = position.getY(c)
if (ya > wallHeight + epsilon && yb > wallHeight + epsilon && yc > wallHeight + epsilon) {
triangleMats[i] = gableMatIndex
}
}
const sortedTri = Array.from({ length: triangleCount }, (_, i) => i)
sortedTri.sort((a, b) => (triangleMats[a] ?? 0) - (triangleMats[b] ?? 0))
const newIdx = new Uint32Array(index.count)
for (let i = 0; i < sortedTri.length; i++) {
const ti = sortedTri[i] as number
newIdx[i * 3] = index.getX(ti * 3)
newIdx[i * 3 + 1] = index.getX(ti * 3 + 1)
newIdx[i * 3 + 2] = index.getX(ti * 3 + 2)
}
geometry.setIndex(new THREE.BufferAttribute(newIdx, 1))
geometry.clearGroups()
let groupStart = 0
let curMat = triangleMats[sortedTri[0] as number] as number
for (let i = 1; i < sortedTri.length; i++) {
const mat = triangleMats[sortedTri[i] as number] as number
if (mat !== curMat) {
geometry.addGroup(groupStart, i * 3 - groupStart, curMat)
groupStart = i * 3
curMat = mat
}
}
geometry.addGroup(groupStart, sortedTri.length * 3 - groupStart, curMat)
}
function ensureUv2Attribute(geometry: THREE.BufferGeometry) {
const uv = geometry.getAttribute('uv')
if (!uv) return
geometry.setAttribute('uv2', new THREE.Float32BufferAttribute(Array.from(uv.array), 2))
}
+96
View File
@@ -0,0 +1,96 @@
import {
type AnyNode,
type DormerNode as DormerNodeType,
type NodeDefinition,
DormerNode as DormerNodeSchema,
} from '@pascal-app/core'
import { buildDormerRoofCut } from './csg-geometry'
import { dormerPaint } from './paint'
import { dormerParametrics } from './parametrics'
import { DormerNode } from './schema'
/**
* Dormer — a small house-shaped protrusion sitting on top of a roof
* segment. The window opening is inlined into the dormer's schema
* (window* fields drive parametric geometry on the front face), not
* a hosted child node — so `relations.hosts` stays unset.
*
* **Scope of this port — stub.** Schema is complete (every field from
* the archive, including the four per-surface material slots and the
* full window-opening field set). Geometry renders a simple house
* silhouette (box body + triangular gable roof) for all `roofType`
* variants — the archive's variant-specific dormer roof shapes,
* window opening + frame, sill, and the CSG trim where the dormer
* meets the host roof are deferred. Per-surface paints (`topMaterial`,
* `sideMaterial`, `wallMaterial`) resolve via the shared helper from
* core but only roof / wall surfaces are emitted by the stub geometry.
*/
export const dormerDefinition: NodeDefinition<typeof DormerNode> = {
kind: 'dormer',
schemaVersion: 1,
schema: DormerNode,
category: 'structure',
defaults: () => {
// Zod fills in id/type via their .default() factories; we strip
// both so the returned shape is a partial template a consumer can
// spread into createNode() with a fresh id.
const stub = DormerNodeSchema.parse({})
const { id: _id, type: _type, ...rest } = stub
return rest
},
capabilities: {
selectable: { hitVolume: 'bbox' },
duplicable: true,
deletable: true,
// Mounts on a roof segment via `roofSegmentId`. Dirty marks
// cascade to the host segment's parent roof so its merged shell
// re-CSGs with the new cut. `buildCut` returns the segment-local
// geometry the merge loop subtracts from shin / deck / wall.
roofAccessory: {
buildCut: (node: AnyNode, _hostSegment: AnyNode) =>
buildDormerRoofCut(node as DormerNodeType),
},
// Paint dispatch for the wall / side / top surface split. The
// editor's selection-manager routes paint hover / click /
// preview through this entry rather than carrying a kind-name
// arm.
paint: dormerPaint,
},
affordanceTools: {
// Drag-to-place tool for duplicate + move. Reuses the placement
// ghost preview but seeds it from the moving (cloned) node so the
// duplicate keeps the source's dimensions, materials, and window
// options.
move: () => import('./move-tool'),
},
parametrics: dormerParametrics,
renderer: {
kind: 'parametric',
module: () => import('./renderer'),
},
tool: () => import('./tool'),
toolHints: [
{ key: 'Left click', label: 'Place dormer on roof' },
{ key: 'R / Shift+R', label: 'Rotate ghost ±15°' },
{ key: 'Esc', label: 'Cancel' },
],
presentation: {
label: 'Dormer',
description: 'House-shaped protrusion on a roof segment.',
icon: { kind: 'url', src: '/icons/roof.png' },
paletteSection: 'structure',
paletteOrder: 125,
},
mcp: {
description:
'A dormer on a roof segment. Box body + gable roof + inlined window opening. Geometry beyond the stub silhouette coming later.',
},
}
+70
View File
@@ -0,0 +1,70 @@
import type { DormerNode } from '@pascal-app/core'
import * as THREE from 'three'
/**
* Grid-snap step (metres) applied to the world cursor position while a
* dormer placement / move ghost is in flight. Shared by both tools so
* the audible snap and the committed position step stay in lockstep.
*/
export const DORMER_PLACEMENT_SNAP_M = 0.05
/**
* Rotation step (radians) used by the keyboard rotate shortcuts (R /
* Shift+R) while a dormer placement / move ghost is in flight. 15° —
* lets the user reach the 90° cardinals in six taps and the 45°
* diagonals in three.
*/
export const DORMER_PLACEMENT_ROTATION_STEP = (15 * Math.PI) / 180
/**
* Lightweight silhouette geometry used by the placement / move-tool
* ghost preview only. Renders the dormer as an extruded pentagon
* (rectangle body + triangular gable) dropped by `wallSkirtHeight` below
* the anchor so the cursor sits at the floor of the dormer the way the
* committed CSG geometry does.
*
* For `roofType === 'flat'` (or `roofHeight === 0`) the gable apex is
* skipped and the shape collapses to a rectangle. Other roof types use
* the gable approximation — exact per-type silhouettes are a future
* improvement.
*
* Kept self-contained (no `@pascal-app/viewer` imports) so the geometry
* test doesn't drag in the CSG / BVH module graph, which fails to load
* outside of a browser/WebGL context. The viewer has its own
* `buildDormerFallbackGeometry` that mirrors this shape — used both as
* the CSG fallback when boolean ops fail and as the live-drag preview
* in the dormer renderer.
*/
export function buildDormerGhostGeometry(node: DormerNode): THREE.BufferGeometry {
const w = Math.max(0.05, node.width)
const wallH = Math.max(0.05, node.height)
const roofH = Math.max(0, node.roofHeight)
const d = Math.max(0.05, node.depth)
const skirt = Math.max(0.05, node.wallSkirtHeight)
const hw = w / 2
const isFlat = node.roofType === 'flat' || roofH === 0
const shape = new THREE.Shape()
shape.moveTo(-hw, -skirt)
shape.lineTo(hw, -skirt)
shape.lineTo(hw, wallH)
if (!isFlat) shape.lineTo(0, wallH + roofH)
shape.lineTo(-hw, wallH)
shape.closePath()
const geo = new THREE.ExtrudeGeometry(shape, { depth: d, bevelEnabled: false })
geo.translate(0, 0, -d / 2)
return geo
}
/**
* Inspector helper: which window-shape sub-controls to surface for the
* current dormer.
*/
export function dormerSupportsArch(node: DormerNode): boolean {
return node.windowShape === 'arch'
}
export function dormerSupportsCornerRadii(node: DormerNode): boolean {
return node.windowShape === 'rounded'
}
+11
View File
@@ -0,0 +1,11 @@
export { dormerDefinition } from './definition'
export {
buildDormerGhostGeometry,
dormerSupportsArch,
dormerSupportsCornerRadii,
} from './geometry'
export { DormerNode, getEffectiveDormerSurfaceMaterial } from './schema'
export type {
DormerSurfaceMaterialRole,
DormerSurfaceMaterialSpec,
} from './schema'
+158
View File
@@ -0,0 +1,158 @@
'use client'
import {
type AnyNodeId,
type DormerNode,
DormerNode as DormerNodeSchema,
type RoofSegmentNode,
sceneRegistry,
useScene,
} from '@pascal-app/core'
import { useEditor } from '@pascal-app/editor'
import { useViewer } from '@pascal-app/viewer'
import { useEffect, useMemo } from 'react'
import DormerPreview from './preview'
import { useDormerPlacement } from './use-dormer-placement'
/**
* Drag-to-place tool for dormer duplicate / move. Receives the moving
* node (a clone with `id` stripped + `metadata.isNew = true` after a
* Duplicate action) via `node` prop, shows the same ghost preview as
* placement, and on click commits the cloned dormer to the hit segment.
*
* On cancel, a duplicate clone is deleted and an existing dormer is
* restored to its original segment + position. Mounted via
* `def.affordanceTools.move`.
*/
const MoveDormerTool = ({ node }: { node: DormerNode }) => {
const setSelection = useViewer((s) => s.setSelection)
const setMovingNode = useEditor((s) => s.setMovingNode)
// Ghost data — same as the moving clone but pinned to position[0,0,0]
// (the outer groups place it on the roof). Reparse so Zod fills any
// defaults missing from the clone.
const previewNode = useMemo(() => {
const { id: _id, ...rest } = node
return DormerNodeSchema.parse({
...rest,
position: [0, 0, 0],
rotation: 0,
})
}, [node])
// Hide the moving dormer while dragging. Restored in cleanup or on
// commit. We also mark metadata.isTransient so any other consumer
// (e.g. the inspector) can short-circuit.
const meta =
typeof node.metadata === 'object' && node.metadata !== null
? (node.metadata as Record<string, unknown>)
: {}
const isNew = !!meta.isNew
const originalRotation = node.rotation ?? 0
const originalMetadata = node.metadata
useEffect(() => {
if (!isNew) {
useScene.getState().updateNode(node.id as AnyNodeId, {
metadata: { ...meta, isTransient: true },
})
}
const dormerObj = sceneRegistry.nodes.get(node.id)
const prevVisible = dormerObj?.visible
if (dormerObj) dormerObj.visible = false
return () => {
// Restore visibility + metadata if the move was cancelled.
const obj = sceneRegistry.nodes.get(node.id)
if (obj) obj.visible = prevVisible ?? true
if (!isNew) {
useScene.getState().updateNode(node.id as AnyNodeId, {
metadata: originalMetadata,
})
}
}
// biome-ignore lint/correctness/useExhaustiveDependencies: capture-on-mount; meta is intentionally not re-read on changes.
}, [node.id, isNew])
const { activeBuildingId, segmentXform, hitLocal, ghostRotation } = useDormerPlacement({
initialRotation: originalRotation,
onCommit: (hit, rotation) => {
const state = useScene.getState()
// Strip the `isNew` / `isTransient` flags — only used to mark a
// clone or in-flight move that hasn't been committed yet.
const cleanedMeta = (() => {
const m =
node.metadata && typeof node.metadata === 'object' && !Array.isArray(node.metadata)
? (node.metadata as Record<string, unknown>)
: {}
const { isNew: _isNew, isTransient: _isTransient, ...rest } = m as {
isNew?: boolean
isTransient?: boolean
}
return Object.keys(rest).length > 0 ? rest : undefined
})()
if (isNew || !node.id) {
const { id: _id, ...rest } = node
const committed = DormerNodeSchema.parse({
...rest,
roofSegmentId: hit.segment.id,
parentId: hit.segment.id,
position: [hit.localX, hit.localY, hit.localZ],
rotation,
metadata: cleanedMeta,
})
state.createNode(committed, hit.segment.id as AnyNodeId)
state.dirtyNodes.add(hit.segment.id as AnyNodeId)
setSelection({ selectedIds: [committed.id] })
} else {
const prevSegmentId = node.roofSegmentId as AnyNodeId | undefined
state.updateNode(node.id as AnyNodeId, {
roofSegmentId: hit.segment.id,
parentId: hit.segment.id,
position: [hit.localX, hit.localY, hit.localZ],
rotation,
metadata: cleanedMeta,
})
if (prevSegmentId) state.dirtyNodes.add(prevSegmentId)
state.dirtyNodes.add(hit.segment.id as AnyNodeId)
// Unlist from previous segment's children and add to the new one.
if (prevSegmentId && prevSegmentId !== (hit.segment.id as AnyNodeId)) {
const prevSeg = state.nodes[prevSegmentId] as RoofSegmentNode | undefined
if (prevSeg) {
state.updateNode(prevSegmentId, {
children: (prevSeg.children ?? []).filter((id) => id !== node.id),
})
}
const newSeg = state.nodes[hit.segment.id as AnyNodeId] as
| RoofSegmentNode
| undefined
if (newSeg && !(newSeg.children ?? []).includes(node.id)) {
state.updateNode(hit.segment.id as AnyNodeId, {
children: [...(newSeg.children ?? []), node.id],
})
}
}
setSelection({ selectedIds: [node.id] })
}
const dormerObj = sceneRegistry.nodes.get(node.id)
if (dormerObj) dormerObj.visible = true
setMovingNode(null)
},
})
if (!activeBuildingId || !segmentXform || !hitLocal) return null
return (
<group position={segmentXform.position} quaternion={segmentXform.quaternion}>
<group position={hitLocal}>
<group rotation-y={ghostRotation}>
<DormerPreview node={previewNode} />
</group>
</group>
</group>
)
}
export default MoveDormerTool
+120
View File
@@ -0,0 +1,120 @@
import type {
DormerNode,
DormerSurfaceMaterialRole,
MaterialSchema,
PaintCapability,
} from '@pascal-app/core'
import { getEffectiveDormerSurfaceMaterial } from '@pascal-app/core'
import { createMaterial, createMaterialFromPresetRef } from '@pascal-app/viewer'
import type { Material, Mesh } from 'three'
/**
* Resolve a dormer face click to its logical surface role.
*
* The dormer body mesh has 5 material slots (see
* `csg-geometry.ts:generateDormerGeometry`):
* 0 = wall (rectangular wall)
* 1 = side (deck along the slope)
* 2 = interior — paint as wall
* 3 = top (roof shingle)
* 4 = gable triangle — paint as wall
*
* Window-frame meshes are not in the body mesh; they're routed to
* 'side' separately by the editor when the click lands on them.
*/
export function resolveDormerRole(materialIndex: number | null): DormerSurfaceMaterialRole {
if (materialIndex === 3) return 'top'
if (materialIndex === 1) return 'side'
return 'wall'
}
export function buildDormerMaterialPatch(
role: DormerSurfaceMaterialRole,
material: MaterialSchema | undefined,
materialPreset: string | undefined,
): Partial<DormerNode> {
if (role === 'top') {
return { topMaterial: material, topMaterialPreset: materialPreset }
}
if (role === 'side') {
return { sideMaterial: material, sideMaterialPreset: materialPreset }
}
return { wallMaterial: material, wallMaterialPreset: materialPreset }
}
function buildPreviewMaterial(
material: MaterialSchema | undefined,
materialPreset: string | undefined,
): Material | null {
if (materialPreset) {
return createMaterialFromPresetRef(materialPreset)
}
if (material) {
return createMaterial(material)
}
return null
}
/**
* Apply a preview material to the dormer's `dormer-body` mesh at the
* slots that map to `role`:
* role='wall' → slots [0, 2, 4]
* role='side' → slot [1]
* role='top' → slot [3]
*/
function applyDormerPreview(
role: DormerSurfaceMaterialRole,
previewMaterial: Material,
root: import('three').Object3D,
): (() => void) | null {
const slotsToPaint = (() => {
if (role === 'top') return [3]
if (role === 'side') return [1]
return [0, 2, 4]
})()
const restores: Array<() => void> = []
root.traverse((object) => {
const mesh = object as Mesh
if (!mesh.isMesh) return
if (mesh.name !== 'dormer-body') return
const current = mesh.material as Material | Material[]
if (!Array.isArray(current)) return
const previousArray = [...current]
const nextArray = [...current]
for (const idx of slotsToPaint) {
if (current[idx]) nextArray[idx] = previewMaterial
}
mesh.material = nextArray
restores.push(() => {
mesh.material = previousArray
})
})
if (restores.length === 0) return null
return () => {
for (let i = restores.length - 1; i >= 0; i -= 1) restores[i]?.()
}
}
/**
* Capability binding for the dormer kind. The editor's
* selection-manager invokes these in place of the legacy
* `if (node.type === 'dormer') { ... }` arm.
*/
export const dormerPaint: PaintCapability = {
resolveRole: ({ materialIndex }) => resolveDormerRole(materialIndex),
buildPatch: ({ role, material, materialPreset }) =>
buildDormerMaterialPatch(role as DormerSurfaceMaterialRole, material, materialPreset),
applyPreview: ({ role, material, materialPreset, root }) => {
const previewMaterial = buildPreviewMaterial(material, materialPreset)
if (!previewMaterial) return null
return applyDormerPreview(role as DormerSurfaceMaterialRole, previewMaterial, root)
},
getEffectiveMaterial: ({ node, role }) => {
const spec = getEffectiveDormerSurfaceMaterial(
node as DormerNode,
role as DormerSurfaceMaterialRole,
)
return { material: spec.material, materialPreset: spec.materialPreset }
},
}
@@ -0,0 +1,37 @@
'use client'
import { ActionButton, ActionGroup, PanelSection } from '@pascal-app/editor'
import { Copy, Move, Trash2 } from 'lucide-react'
/**
* Move / Duplicate / Delete buttons at the bottom of the dormer
* inspector. Pure presentation — owners pass the three handlers.
*/
export function DormerActionsSection({
onMove,
onDuplicate,
onDelete,
}: {
onMove: () => void
onDuplicate: () => void
onDelete: () => void
}) {
return (
<PanelSection title="Actions">
<ActionGroup>
<ActionButton icon={<Move className="h-3.5 w-3.5" />} label="Move" onClick={onMove} />
<ActionButton
icon={<Copy className="h-3.5 w-3.5" />}
label="Duplicate"
onClick={onDuplicate}
/>
<ActionButton
className="hover:bg-red-500/20"
icon={<Trash2 className="h-3.5 w-3.5 text-red-400" />}
label="Delete"
onClick={onDelete}
/>
</ActionGroup>
</PanelSection>
)
}
@@ -0,0 +1,227 @@
'use client'
import {
type AnyNodeId,
type DormerNode,
type RoofNode,
type RoofSegmentNode,
sceneRegistry,
useScene,
} from '@pascal-app/core'
import { PanelSection, SliderControl } from '@pascal-app/editor'
import { useMemo } from 'react'
import { Vector3 } from 'three'
/**
* Position section: X, Z (world-space) and Rotation (world-space)
* sliders. Owns the read side of the dormer's world transform —
* confined to a single useMemo so the underlying `updateWorldMatrix`
* calls don't fire on unrelated re-renders. Also owns the segment-
* local commits, including the cross-segment reparent case.
*/
export function DormerPositionSection({
node,
segment,
roof,
selectedId,
previewProp,
commitProp,
}: {
node: DormerNode
segment: RoofSegmentNode | undefined
roof: RoofNode | undefined
selectedId: string
previewProp: (updates: Partial<DormerNode>) => void
commitProp: (updates: Partial<DormerNode>) => void
}) {
const px = node.position[0]
const py = node.position[1]
const pz = node.position[2]
const nodeRotation = node.rotation
const segmentId = segment?.id
const roofChildrenKey = (roof?.children ?? []).join(',')
const worldXform = useMemo(() => {
const dormerObj = sceneRegistry.nodes.get(selectedId)
let worldX = 0
let worldZ = 0
let worldRotation = nodeRotation ?? 0
if (dormerObj) {
dormerObj.updateWorldMatrix(true, false)
const localPt = new Vector3(px ?? 0, 0, pz ?? 0)
const worldPt = localPt.applyMatrix4(dormerObj.matrixWorld)
worldX = worldPt.x
worldZ = worldPt.z
const m = dormerObj.matrixWorld.elements
worldRotation = Math.atan2(-(m[2] ?? 0), m[0] ?? 1) + (nodeRotation ?? 0)
}
let bounds: { minX: number; maxX: number; minZ: number; maxZ: number } | null = null
if (roof) {
const state = useScene.getState()
let lo_x = Number.POSITIVE_INFINITY
let hi_x = Number.NEGATIVE_INFINITY
let lo_z = Number.POSITIVE_INFINITY
let hi_z = Number.NEGATIVE_INFINITY
for (const childId of roof.children ?? []) {
const seg = state.nodes[childId as AnyNodeId] as RoofSegmentNode | undefined
if (!seg) continue
const segObj = sceneRegistry.nodes.get(seg.id)
if (!segObj) continue
segObj.updateWorldMatrix(true, false)
const segWorldCenter = new Vector3().applyMatrix4(segObj.matrixWorld)
const r = Math.hypot(seg.width, seg.depth) / 2
lo_x = Math.min(lo_x, segWorldCenter.x - r)
hi_x = Math.max(hi_x, segWorldCenter.x + r)
lo_z = Math.min(lo_z, segWorldCenter.z - r)
hi_z = Math.max(hi_z, segWorldCenter.z + r)
}
if (Number.isFinite(lo_x)) bounds = { minX: lo_x, maxX: hi_x, minZ: lo_z, maxZ: hi_z }
}
return { worldX, worldZ, worldRotation, bounds }
// biome-ignore lint/correctness/useExhaustiveDependencies: roofChildrenKey is the stable signature of `roof.children`; intentionally omitting `roof` (object identity) in favor of the joined ids.
}, [selectedId, px, py, pz, nodeRotation, segmentId, roofChildrenKey])
const worldX_now = worldXform.worldX
const worldZ_now = worldXform.worldZ
const worldRotation_now = worldXform.worldRotation
const worldMinX = worldXform.bounds?.minX ?? worldX_now - 20
const worldMaxX = worldXform.bounds?.maxX ?? worldX_now + 20
const worldMinZ = worldXform.bounds?.minZ ?? worldZ_now - 20
const worldMaxZ = worldXform.bounds?.maxZ ?? worldZ_now + 20
const findSegmentForWorldPoint = (
wx: number,
wz: number,
): { segment: RoofSegmentNode; localX: number; localZ: number } | null => {
const state = useScene.getState()
const worldPt = new Vector3(wx, 0, wz)
for (const candidate of Object.values(state.nodes)) {
if (!candidate || candidate.type !== 'roof-segment') continue
const seg = candidate as RoofSegmentNode
const segObj = sceneRegistry.nodes.get(seg.id)
if (!segObj) continue
segObj.updateWorldMatrix(true, false)
const local = segObj.worldToLocal(worldPt.clone())
if (Math.abs(local.x) <= seg.width / 2 && Math.abs(local.z) <= seg.depth / 2) {
return { segment: seg, localX: local.x, localZ: local.z }
}
}
return null
}
const worldToSegLocal = (
wx: number,
wz: number,
seg: RoofSegmentNode,
): { localX: number; localZ: number } => {
const segObj = sceneRegistry.nodes.get(seg.id)
if (!segObj) return { localX: wx, localZ: wz }
segObj.updateWorldMatrix(true, false)
const local = segObj.worldToLocal(new Vector3(wx, 0, wz))
return { localX: local.x, localZ: local.z }
}
const commitWorldPosition = (newWorldX: number, newWorldZ: number) => {
if (!segment) return
const oldWorldRotation = worldRotation_now
const target = findSegmentForWorldPoint(newWorldX, newWorldZ)
if (target && target.segment.id !== segment.id) {
// Moving to a different segment — segment-local Y is meaningless
// across the change, so reset to 0 and let the new segment's
// slope-anchored geometry take over.
const newSegObj = sceneRegistry.nodes.get(target.segment.id)
let newAncestorWorldY = 0
if (newSegObj) {
newSegObj.updateWorldMatrix(true, false)
const m = newSegObj.matrixWorld.elements
newAncestorWorldY = Math.atan2(-(m[2] ?? 0), m[0] ?? 1)
}
const newSegLocalRot = oldWorldRotation - newAncestorWorldY
commitProp({
roofSegmentId: target.segment.id,
parentId: target.segment.id,
position: [target.localX, 0, target.localZ],
rotation: newSegLocalRot,
} as Partial<DormerNode>)
} else {
// Same segment — preserve the existing Y so the dormer doesn't
// snap back to the segment foot when the user only adjusts X/Z.
const local = worldToSegLocal(newWorldX, newWorldZ, segment)
commitProp({ position: [local.localX, py ?? 0, local.localZ] })
}
}
const commitWorldRotation = (newWorldRot: number) => {
if (!segment) return
let ancestorWorldY = 0
const segObj = sceneRegistry.nodes.get(segment.id)
if (segObj) {
segObj.updateWorldMatrix(true, false)
const m = segObj.matrixWorld.elements
ancestorWorldY = Math.atan2(-(m[2] ?? 0), m[0] ?? 1)
}
commitProp({ rotation: newWorldRot - ancestorWorldY })
}
return (
<PanelSection title="Position">
<SliderControl
label="X"
max={Math.round(worldMaxX * 10) / 10}
min={Math.round(worldMinX * 10) / 10}
onChange={(newWorldX) => {
if (!segment) return
const local = worldToSegLocal(newWorldX, worldZ_now, segment)
previewProp({ position: [local.localX, py ?? 0, local.localZ] })
}}
onCommit={(newWorldX) => commitWorldPosition(newWorldX, worldZ_now)}
precision={2}
restoreOnCommit={false}
step={0.05}
unit="m"
value={Math.round(worldX_now * 100) / 100}
/>
<SliderControl
label="Z"
max={Math.round(worldMaxZ * 10) / 10}
min={Math.round(worldMinZ * 10) / 10}
onChange={(newWorldZ) => {
if (!segment) return
const local = worldToSegLocal(worldX_now, newWorldZ, segment)
previewProp({ position: [local.localX, py ?? 0, local.localZ] })
}}
onCommit={(newWorldZ) => commitWorldPosition(worldX_now, newWorldZ)}
precision={2}
restoreOnCommit={false}
step={0.05}
unit="m"
value={Math.round(worldZ_now * 100) / 100}
/>
<SliderControl
label="Rotation"
max={180}
min={-180}
onChange={(degrees) => {
const newWorldRot = (degrees * Math.PI) / 180
let ancestorWorldY = 0
if (segment) {
const segObj = sceneRegistry.nodes.get(segment.id)
if (segObj) {
segObj.updateWorldMatrix(true, false)
const m = segObj.matrixWorld.elements
ancestorWorldY = Math.atan2(-(m[2] ?? 0), m[0] ?? 1)
}
}
previewProp({ rotation: newWorldRot - ancestorWorldY })
}}
onCommit={(degrees) => commitWorldRotation((degrees * Math.PI) / 180)}
precision={0}
restoreOnCommit={false}
step={1}
unit="°"
value={Math.round((worldRotation_now * 180) / Math.PI)}
/>
</PanelSection>
)
}
@@ -0,0 +1,321 @@
'use client'
import type { DormerNode } from '@pascal-app/core'
import {
PanelSection,
SegmentedControl,
SliderControl,
ToggleControl,
} from '@pascal-app/editor'
import { useState } from 'react'
type WindowShape = DormerNode['windowShape']
type WindowRadiusMode = 'all' | 'individual'
function maxSharedRadius(width: number, height: number): number {
return Math.max(0, Math.min(width / 2, height / 2))
}
/**
* The Window tab of the dormer inspector: Hung Wall, Opening, Shape
* (with rounded/arch sub-controls), Frame, Grid, Sill. Owns local UI
* state for the "All vs Individual" corner-radius view mode — derived
* from tuple uniformity by default.
*/
export function DormerWindowSection({
node,
previewProp,
commitProp,
handleUpdate,
}: {
node: DormerNode
previewProp: (updates: Partial<DormerNode>) => void
commitProp: (updates: Partial<DormerNode>) => void
handleUpdate: (updates: Partial<DormerNode>) => void
}) {
const [radiusViewMode, setRadiusViewMode] = useState<WindowRadiusMode>('all')
const windowShape: WindowShape = node.windowShape
const windowCornerRadii: [number, number, number, number] = [...node.windowCornerRadii]
const windowArchHeight = node.windowArchHeight
const maxRadius = Math.max(0.01, maxSharedRadius(node.windowWidth, node.windowHeight))
const tupleIsUniform =
windowCornerRadii[0] === windowCornerRadii[1] &&
windowCornerRadii[1] === windowCornerRadii[2] &&
windowCornerRadii[2] === windowCornerRadii[3]
const sharedRadius = windowCornerRadii[0]
const setCornerRadius = (index: number, value: number, commit: boolean) => {
const next = [...windowCornerRadii] as [number, number, number, number]
next[index] = value
if (commit) commitProp({ windowCornerRadii: next })
else previewProp({ windowCornerRadii: next })
}
const setAllCornerRadii = (value: number, commit: boolean) => {
const next: [number, number, number, number] = [value, value, value, value]
if (commit) commitProp({ windowCornerRadii: next })
else previewProp({ windowCornerRadii: next })
}
return (
<>
<PanelSection title="Hung Wall">
<SliderControl
label="Height"
max={6}
min={0.2}
onChange={(v) => previewProp({ wallSkirtHeight: v })}
onCommit={(v) => commitProp({ wallSkirtHeight: v })}
precision={2}
restoreOnCommit={false}
step={0.05}
unit="m"
value={Math.round(node.wallSkirtHeight * 100) / 100}
/>
</PanelSection>
<PanelSection title="Opening">
<SliderControl
label="Width"
max={Math.max(0.5, node.width - 0.1)}
min={0.2}
onChange={(v) => previewProp({ windowWidth: v })}
onCommit={(v) => commitProp({ windowWidth: v })}
precision={2}
restoreOnCommit={false}
step={0.05}
unit="m"
value={Math.round(node.windowWidth * 100) / 100}
/>
<SliderControl
label="Height"
max={Math.max(0.2, node.wallSkirtHeight - 0.1)}
min={0.2}
onChange={(v) => previewProp({ windowHeight: v })}
onCommit={(v) => commitProp({ windowHeight: v })}
precision={2}
restoreOnCommit={false}
step={0.05}
unit="m"
value={Math.round(node.windowHeight * 100) / 100}
/>
<SliderControl
label="Offset X"
max={1}
min={-1}
onChange={(v) => previewProp({ windowOffsetX: v })}
onCommit={(v) => commitProp({ windowOffsetX: v })}
precision={2}
restoreOnCommit={false}
step={0.05}
unit="m"
value={Math.round(node.windowOffsetX * 100) / 100}
/>
<SliderControl
label="Offset Y"
max={2}
min={0}
onChange={(v) => previewProp({ windowOffsetY: v })}
onCommit={(v) => commitProp({ windowOffsetY: v })}
precision={2}
restoreOnCommit={false}
step={0.05}
unit="m"
value={Math.round(node.windowOffsetY * 100) / 100}
/>
</PanelSection>
<PanelSection title="Shape">
<SegmentedControl
onChange={(v) =>
handleUpdate({
windowShape: v as WindowShape,
...(v === 'rounded'
? {
windowCornerRadii: windowCornerRadii.map((r) =>
Math.min(r, maxRadius),
) as [number, number, number, number],
}
: {}),
})
}
options={[
{ value: 'rectangle', label: 'Rect' },
{ value: 'rounded', label: 'Rounded' },
{ value: 'arch', label: 'Arch' },
]}
value={windowShape}
/>
{windowShape === 'rounded' && (
<div className="mt-2 flex flex-col gap-1">
<SegmentedControl
onChange={(v) => setRadiusViewMode(v as WindowRadiusMode)}
options={[
{ value: 'all', label: 'All' },
{ value: 'individual', label: 'Individual' },
]}
value={tupleIsUniform ? radiusViewMode : 'individual'}
/>
{tupleIsUniform && radiusViewMode === 'all' ? (
<SliderControl
label="Corner Radius"
max={maxRadius}
min={0}
onChange={(v) => setAllCornerRadii(v, false)}
onCommit={(v) => setAllCornerRadii(v, true)}
precision={2}
restoreOnCommit={false}
step={0.01}
unit="m"
value={Math.round(sharedRadius * 100) / 100}
/>
) : (
(
[
['Top Left', 0],
['Top Right', 1],
['Bottom Right', 2],
['Bottom Left', 3],
] as const
).map(([label, index]) => (
<SliderControl
key={label}
label={label}
max={maxRadius}
min={0}
onChange={(v) => setCornerRadius(index, v, false)}
onCommit={(v) => setCornerRadius(index, v, true)}
precision={2}
restoreOnCommit={false}
step={0.01}
unit="m"
value={Math.round((windowCornerRadii[index] ?? 0) * 100) / 100}
/>
))
)}
</div>
)}
{windowShape === 'arch' && (
<SliderControl
label="Arch Height"
max={Math.max(0.1, node.windowHeight)}
min={0.1}
onChange={(v) => previewProp({ windowArchHeight: v })}
onCommit={(v) => commitProp({ windowArchHeight: v })}
precision={2}
restoreOnCommit={false}
step={0.05}
unit="m"
value={Math.round(windowArchHeight * 100) / 100}
/>
)}
</PanelSection>
<PanelSection title="Frame">
<SliderControl
label="Thickness"
max={0.15}
min={0.01}
onChange={(v) => previewProp({ windowFrameThickness: v })}
onCommit={(v) => commitProp({ windowFrameThickness: v })}
precision={3}
restoreOnCommit={false}
step={0.005}
unit="m"
value={Math.round(node.windowFrameThickness * 1000) / 1000}
/>
<SliderControl
label="Depth"
max={0.15}
min={0.02}
onChange={(v) => previewProp({ windowFrameDepth: v })}
onCommit={(v) => commitProp({ windowFrameDepth: v })}
precision={3}
restoreOnCommit={false}
step={0.005}
unit="m"
value={Math.round(node.windowFrameDepth * 1000) / 1000}
/>
<SliderControl
label="Divider"
max={0.06}
min={0}
onChange={(v) => previewProp({ windowDividerThickness: v })}
onCommit={(v) => commitProp({ windowDividerThickness: v })}
precision={3}
restoreOnCommit={false}
step={0.002}
unit="m"
value={Math.round(node.windowDividerThickness * 1000) / 1000}
/>
</PanelSection>
<PanelSection title="Grid">
<SliderControl
label="Columns"
max={8}
min={1}
onChange={(v) =>
previewProp({ windowColumns: Math.max(1, Math.min(8, Math.round(v))) })
}
onCommit={(v) =>
commitProp({ windowColumns: Math.max(1, Math.min(8, Math.round(v))) })
}
precision={0}
restoreOnCommit={false}
step={1}
value={node.windowColumns}
/>
<SliderControl
label="Rows"
max={8}
min={1}
onChange={(v) => previewProp({ windowRows: Math.max(1, Math.min(8, Math.round(v))) })}
onCommit={(v) => commitProp({ windowRows: Math.max(1, Math.min(8, Math.round(v))) })}
precision={0}
restoreOnCommit={false}
step={1}
value={node.windowRows}
/>
</PanelSection>
<PanelSection title="Sill">
<ToggleControl
checked={node.windowSill}
label="Enable Sill"
onChange={(checked) => handleUpdate({ windowSill: checked })}
/>
{node.windowSill && (
<div className="mt-1 flex flex-col gap-1">
<SliderControl
label="Depth"
max={0.3}
min={0.02}
onChange={(v) => previewProp({ windowSillDepth: v })}
onCommit={(v) => commitProp({ windowSillDepth: v })}
precision={3}
restoreOnCommit={false}
step={0.01}
unit="m"
value={Math.round(node.windowSillDepth * 1000) / 1000}
/>
<SliderControl
label="Thickness"
max={0.1}
min={0.01}
onChange={(v) => previewProp({ windowSillThickness: v })}
onCommit={(v) => commitProp({ windowSillThickness: v })}
precision={3}
restoreOnCommit={false}
step={0.005}
unit="m"
value={Math.round(node.windowSillThickness * 1000) / 1000}
/>
</div>
)}
</PanelSection>
</>
)
}
+295
View File
@@ -0,0 +1,295 @@
'use client'
import {
type AnyNode,
type AnyNodeId,
type DormerNode,
type RoofNode,
type RoofSegmentNode,
useLiveNodeOverrides,
useScene,
} from '@pascal-app/core'
import {
cn,
PanelSection,
PanelWrapper,
SliderControl,
triggerSFX,
useEditor,
} from '@pascal-app/editor'
import { useViewer } from '@pascal-app/viewer'
import { useCallback, useState } from 'react'
import { DormerActionsSection } from './panel-actions-section'
import { DormerPositionSection } from './panel-position-section'
import { DormerWindowSection } from './panel-window-section'
type RoofType = DormerNode['roofType']
type DormerSection = 'dormer' | 'window'
const ROOF_TYPE_OPTIONS: Array<{ label: string; value: RoofType }> = [
{ label: 'Gable', value: 'gable' },
{ label: 'Hip', value: 'hip' },
{ label: 'Shed', value: 'shed' },
{ label: 'Gambrel', value: 'gambrel' },
{ label: 'Dutch', value: 'dutch' },
{ label: 'Mansard', value: 'mansard' },
{ label: 'Flat', value: 'flat' },
]
const SECTION_OPTIONS: Array<{ label: string; value: DormerSection }> = [
{ label: 'Dormer', value: 'dormer' },
{ label: 'Window', value: 'window' },
]
export default function DormerPanel() {
const [section, setSection] = useState<DormerSection>('dormer')
const selectedId = useViewer((s) => s.selection.selectedIds[0])
const setSelection = useViewer((s) => s.setSelection)
const updateNode = useScene((s) => s.updateNode)
const deleteNode = useScene((s) => s.deleteNode)
const setMovingNode = useEditor((s) => s.setMovingNode)
const storeNode = useScene((s) =>
selectedId ? (s.nodes[selectedId as AnyNode['id']] as DormerNode | undefined) : undefined,
)
const overrides = useLiveNodeOverrides((s) =>
selectedId ? (s.get(selectedId as AnyNodeId) as Partial<DormerNode> | undefined) : undefined,
)
const node =
storeNode && overrides ? ({ ...storeNode, ...overrides } as DormerNode) : storeNode
const handleUpdate = useCallback(
(updates: Partial<DormerNode>) => {
if (!selectedId) return
updateNode(selectedId as AnyNode['id'], updates)
},
[selectedId, updateNode],
)
// Slider drag → write live override; release → commit.
const previewProp = useCallback(
(updates: Partial<DormerNode>) => {
if (!selectedId) return
useLiveNodeOverrides.getState().set(selectedId as AnyNodeId, updates)
},
[selectedId],
)
const commitProp = useCallback(
(updates: Partial<DormerNode>) => {
if (!selectedId) return
updateNode(selectedId as AnyNode['id'], updates)
if (updates.roofSegmentId !== undefined) {
const state = useScene.getState()
const prev = node?.roofSegmentId
if (prev) state.dirtyNodes.add(prev as AnyNodeId)
state.dirtyNodes.add(updates.roofSegmentId as AnyNodeId)
state.dirtyNodes.add(selectedId as AnyNodeId)
}
useLiveNodeOverrides.getState().clear(selectedId as AnyNodeId)
},
[node, selectedId, updateNode],
)
const handleClose = useCallback(() => {
setSelection({ selectedIds: [] })
}, [setSelection])
const handleBack = useCallback(() => {
if (node?.roofSegmentId) {
setSelection({ selectedIds: [node.roofSegmentId as AnyNode['id']] })
}
}, [node?.roofSegmentId, setSelection])
const handleMove = useCallback(() => {
if (!(node && selectedId)) return
triggerSFX('sfx:item-pick')
setMovingNode(node)
setSelection({ selectedIds: [] })
}, [node, selectedId, setMovingNode, setSelection])
const handleDuplicate = useCallback(() => {
if (!(node && node.roofSegmentId)) return
triggerSFX('sfx:item-pick')
// Deep clone and strip the id so the move tool's onClick branch
// (`isNew || !node.id`) takes the "create fresh" path. Setting
// `metadata.isNew = true` is what gates the move tool from
// updating any existing node — the dormer is only added to the
// scene on click, not when the Duplicate button is pressed.
const cloned = structuredClone(node) as DormerNode & { id?: AnyNodeId }
delete (cloned as { id?: AnyNodeId }).id
const prevMeta =
cloned.metadata && typeof cloned.metadata === 'object' && !Array.isArray(cloned.metadata)
? (cloned.metadata as Record<string, unknown>)
: {}
cloned.metadata = { ...prevMeta, isNew: true }
setMovingNode(cloned as DormerNode)
setSelection({ selectedIds: [] })
}, [node, setMovingNode, setSelection])
const handleDelete = useCallback(() => {
if (!(selectedId && node)) return
triggerSFX('sfx:item-delete')
const segmentId = node.roofSegmentId
if (segmentId) {
const state = useScene.getState()
const segment = state.nodes[segmentId as AnyNodeId] as RoofSegmentNode | undefined
if (segment) {
state.updateNode(segmentId as AnyNode['id'], {
children: (segment.children ?? []).filter((id) => id !== selectedId),
})
}
}
deleteNode(selectedId as AnyNodeId)
if (segmentId) {
useScene.getState().dirtyNodes.add(segmentId as AnyNodeId)
setSelection({ selectedIds: [segmentId as AnyNode['id']] })
} else {
setSelection({ selectedIds: [] })
}
}, [selectedId, node, deleteNode, setSelection])
if (!(node && node.type === 'dormer' && selectedId)) return null
const scenestate = useScene.getState()
const segment = node.roofSegmentId
? (scenestate.nodes[node.roofSegmentId as AnyNodeId] as RoofSegmentNode | undefined)
: undefined
const roof = segment?.parentId
? (scenestate.nodes[segment.parentId as AnyNodeId] as RoofNode | undefined)
: undefined
return (
<PanelWrapper
icon="/icons/roof.png"
onBack={node.roofSegmentId ? handleBack : undefined}
onClose={handleClose}
title={node.name || 'Dormer'}
width={300}
>
<DormerPositionSection
commitProp={commitProp}
node={node}
previewProp={previewProp}
roof={roof}
segment={segment}
selectedId={selectedId}
/>
<PanelSection title="Section">
<div className="grid grid-cols-3 gap-1.5 px-1 pt-1">
{SECTION_OPTIONS.map((option) => {
const isSelected = section === option.value
return (
<button
className={cn(
'flex min-h-10 items-center justify-center rounded-lg border px-2 py-2 text-center text-xs transition-colors',
isSelected
? 'border-orange-400/60 bg-orange-400/10 text-foreground'
: 'border-border/50 bg-[#2C2C2E] text-muted-foreground hover:bg-[#3e3e3e] hover:text-foreground',
)}
key={option.value}
onClick={() => setSection(option.value)}
type="button"
>
<span className="truncate font-medium">{option.label}</span>
</button>
)
})}
</div>
</PanelSection>
{section === 'dormer' && (
<>
<PanelSection title="Dimensions">
<SliderControl
label="Width"
max={4}
min={0.5}
onChange={(v) => previewProp({ width: v })}
onCommit={(v) => commitProp({ width: v })}
precision={2}
restoreOnCommit={false}
step={0.05}
unit="m"
value={Math.round(node.width * 100) / 100}
/>
<SliderControl
label="Depth"
max={5}
min={0.5}
onChange={(v) => previewProp({ depth: v })}
onCommit={(v) => commitProp({ depth: v })}
precision={2}
restoreOnCommit={false}
step={0.05}
unit="m"
value={Math.round(node.depth * 100) / 100}
/>
<SliderControl
label="Wall Height"
max={5}
min={0}
onChange={(v) => previewProp({ height: v })}
onCommit={(v) => commitProp({ height: v })}
precision={2}
restoreOnCommit={false}
step={0.05}
unit="m"
value={Math.round(node.height * 100) / 100}
/>
<SliderControl
label="Roof Height"
max={3}
min={0}
onChange={(v) => previewProp({ roofHeight: v })}
onCommit={(v) => commitProp({ roofHeight: v })}
precision={2}
restoreOnCommit={false}
step={0.05}
unit="m"
value={Math.round(node.roofHeight * 100) / 100}
/>
</PanelSection>
<PanelSection title="Roof Type">
<div className="grid grid-cols-3 gap-1.5 px-1 pt-1">
{ROOF_TYPE_OPTIONS.map((option) => {
const isSelected = node.roofType === option.value
return (
<button
className={cn(
'flex min-h-10 items-center justify-center rounded-lg border px-2 py-2 text-xs transition-colors',
isSelected
? 'border-orange-400/60 bg-orange-400/10 text-foreground'
: 'border-border/50 bg-[#2C2C2E] text-muted-foreground hover:bg-[#3e3e3e] hover:text-foreground',
)}
key={option.value}
onClick={() => handleUpdate({ roofType: option.value })}
type="button"
>
<span className="truncate font-medium">{option.label}</span>
</button>
)
})}
</div>
</PanelSection>
</>
)}
{section === 'window' && (
<DormerWindowSection
commitProp={commitProp}
handleUpdate={handleUpdate}
node={node}
previewProp={previewProp}
/>
)}
<DormerActionsSection
onDelete={handleDelete}
onDuplicate={handleDuplicate}
onMove={handleMove}
/>
</PanelWrapper>
)
}
+101
View File
@@ -0,0 +1,101 @@
import type { ParametricDescriptor } from '@pascal-app/core'
import { dormerSupportsArch } from './geometry'
import type { DormerNode } from './schema'
export const dormerParametrics: ParametricDescriptor<DormerNode> = {
// Bespoke tabbed UI (Dormer / Window / Frame / Grid / Sill) — same
// pattern as chimney. `groups` stays for the MCP path / fallback
// consumer, but the inspector mounts the custom panel.
customPanel: () => import('./panel'),
groups: [
{
label: 'Dormer',
fields: [
{ key: 'width', kind: 'number', unit: 'm', min: 0.5, max: 4, step: 0.05 },
{ key: 'depth', kind: 'number', unit: 'm', min: 0.5, max: 5, step: 0.05 },
{ key: 'height', kind: 'number', unit: 'm', min: 0, max: 5, step: 0.05 },
],
},
{
label: 'Dormer roof',
fields: [
{
key: 'roofType',
kind: 'enum',
options: ['hip', 'gable', 'shed', 'gambrel', 'dutch', 'mansard', 'flat'],
display: 'select',
},
{ key: 'roofHeight', kind: 'number', unit: 'm', min: 0, max: 2, step: 0.05 },
],
},
{
label: 'Hung wall',
fields: [
{ key: 'wallSkirtHeight', kind: 'number', unit: 'm', min: 0.2, max: 6, step: 0.05 },
],
},
{
label: 'Window opening',
fields: [
{ key: 'windowWidth', kind: 'number', unit: 'm', min: 0.2, max: 3, step: 0.05 },
{ key: 'windowHeight', kind: 'number', unit: 'm', min: 0.2, max: 6, step: 0.05 },
{ key: 'windowOffsetX', kind: 'number', unit: 'm', min: -1, max: 1, step: 0.05 },
{ key: 'windowOffsetY', kind: 'number', unit: 'm', min: 0, max: 2, step: 0.05 },
],
},
{
label: 'Window grid',
fields: [
{ key: 'windowColumns', kind: 'number', min: 1, max: 8, step: 1 },
{ key: 'windowRows', kind: 'number', min: 1, max: 8, step: 1 },
],
},
{
label: 'Window frame',
fields: [
{ key: 'windowFrameThickness', kind: 'number', unit: 'm', min: 0.01, max: 0.15, step: 0.005 },
{ key: 'windowFrameDepth', kind: 'number', unit: 'm', min: 0.02, max: 0.15, step: 0.005 },
{ key: 'windowDividerThickness', kind: 'number', unit: 'm', min: 0, max: 0.06, step: 0.002 },
{
key: 'windowShape',
kind: 'enum',
options: ['rectangle', 'rounded', 'arch'],
display: 'segmented',
},
{
key: 'windowArchHeight',
kind: 'number',
unit: 'm',
min: 0.1,
max: 1,
step: 0.05,
visibleIf: dormerSupportsArch,
},
],
},
{
label: 'Sill',
fields: [
{ key: 'windowSill', kind: 'boolean' },
{
key: 'windowSillDepth',
kind: 'number',
unit: 'm',
min: 0.02,
max: 0.3,
step: 0.01,
visibleIf: (n) => n.windowSill === true,
},
{
key: 'windowSillThickness',
kind: 'number',
unit: 'm',
min: 0.01,
max: 0.1,
step: 0.005,
visibleIf: (n) => n.windowSill === true,
},
],
},
],
}
+26
View File
@@ -0,0 +1,26 @@
'use client'
import { useEffect, useMemo } from 'react'
import * as THREE from 'three'
import { buildDormerGhostGeometry } from './geometry'
import type { DormerNode } from './schema'
const ghostMaterial = new THREE.MeshStandardMaterial({
color: 0x88_88_88,
transparent: true,
opacity: 0.45,
depthWrite: false,
})
const DormerPreview = ({ node }: { node: DormerNode }) => {
const geo = useMemo(
() => buildDormerGhostGeometry(node),
[node.width, node.depth, node.height, node.roofHeight, node.roofType, node.wallSkirtHeight],
)
useEffect(() => () => geo.dispose(), [geo])
return <mesh geometry={geo} material={ghostMaterial} raycast={() => {}} />
}
export default DormerPreview
+200
View File
@@ -0,0 +1,200 @@
'use client'
import {
type AnyNodeId,
type DormerNode,
getEffectiveDormerSurfaceMaterial,
type RoofSegmentNode,
useLiveNodeOverrides,
useRegistry,
useScene,
} from '@pascal-app/core'
import {
createMaterial,
createMaterialFromPresetRef,
useNodeEvents,
} from '@pascal-app/viewer'
import {
buildDormerFallbackGeometry,
DORMER_GABLE_MATERIAL_INDEX,
generateDormerGeometry,
} from './csg-geometry'
import { useEffect, useMemo, useRef } from 'react'
import * as THREE from 'three'
import DormerWindowAssembly from './window-assembly'
// Three distinct default materials: wall, side, roof top.
// All three use FrontSide — chimney / skylight do the same, and
// DoubleSide on a MeshStandardMaterial inside the MRT scene pass
// generates a WebGPU pipeline whose fragment stage doesn't always
// declare an output for every MRT target, which the validator rejects
// with "target has no corresponding fragment stage output but
// writeMask is not zero".
const defaultWallMat = new THREE.MeshStandardMaterial({
color: 0xff_ff_ff,
roughness: 0.9,
side: THREE.FrontSide,
})
const defaultSideMat = new THREE.MeshStandardMaterial({
color: 0xff_ff_ff,
roughness: 0.9,
side: THREE.FrontSide,
})
const defaultRoofMat = new THREE.MeshStandardMaterial({
color: 0xff_ff_ff,
roughness: 0.85,
side: THREE.FrontSide,
})
// Geometry slots produced by `generateDormerGeometry`:
// 0 = Wall → wall material
// 1 = Deck (side) → side material
// 2 = Interior → wall material
// 3 = Roof shingle → roof material
// 4 = Gable wall → wall material (DORMER_GABLE_MATERIAL_INDEX)
const defaultDormerMaterials: THREE.Material[] = [
defaultWallMat,
defaultSideMat,
defaultWallMat,
defaultRoofMat,
defaultWallMat,
]
const DormerRenderer = ({ node: storeNode }: { node: DormerNode }) => {
const ref = useRef<THREE.Group>(null!)
useRegistry(storeNode.id, 'dormer', ref)
const handlers = useNodeEvents(storeNode, 'dormer')
// Live overrides so slider drag updates the dormer without committing
// to the store. While any override is live we render the cheap
// fallback silhouette — running the full CSG on every pointer move is
// far too expensive (multiple boolean ops + ground subtract +
// 32-segment arch curves). Commit clears the override and the real
// CSG mesh kicks back in.
const liveOverrides = useLiveNodeOverrides((state) => state.get(storeNode.id as AnyNodeId))
const isLiveDrag = !!liveOverrides && Object.keys(liveOverrides).length > 0
const node = useMemo(
() =>
liveOverrides ? ({ ...storeNode, ...liveOverrides } as DormerNode) : storeNode,
[storeNode, liveOverrides],
)
const segment = useScene((state) =>
node.roofSegmentId
? (state.nodes[node.roofSegmentId as AnyNodeId] as RoofSegmentNode | undefined)
: undefined,
)
const resolvedMaterials = useMemo(() => {
const top = getEffectiveDormerSurfaceMaterial(node, 'top')
const side = getEffectiveDormerSurfaceMaterial(node, 'side')
const wall = getEffectiveDormerSurfaceMaterial(node, 'wall')
const resolve = (spec: { material?: DormerNode['material']; materialPreset?: string }) => {
if (spec.materialPreset) return createMaterialFromPresetRef(spec.materialPreset)
if (spec.material) return createMaterial(spec.material)
return null
}
const topMat = resolve(top)
const sideMat = resolve(side)
const wallMat = resolve(wall)
if (!(topMat || sideMat || wallMat)) return null
const w = wallMat ?? defaultWallMat
const s = sideMat ?? defaultSideMat
const t = topMat ?? defaultRoofMat
return [w, s, w, t, w] as THREE.Material[]
}, [
node.material,
node.materialPreset,
node.topMaterial,
node.topMaterialPreset,
node.sideMaterial,
node.sideMaterialPreset,
node.wallMaterial,
node.wallMaterialPreset,
])
const material = resolvedMaterials ?? defaultDormerMaterials
const frameSideMat = resolvedMaterials ? resolvedMaterials[1]! : defaultSideMat
const geometry = useMemo(
() => {
if (!segment) return null
if (isLiveDrag) return buildDormerFallbackGeometry(node)
return generateDormerGeometry(node, segment)
},
[
isLiveDrag,
segment,
node.id,
node.roofType,
node.width,
node.depth,
node.height,
node.roofHeight,
node.wallSkirtHeight,
node.position[0],
node.position[1],
node.position[2],
node.rotation,
node.windowWidth,
node.windowHeight,
node.windowOffsetX,
node.windowOffsetY,
node.windowShape,
node.windowArchHeight,
node.windowCornerRadii[0],
node.windowCornerRadii[1],
node.windowCornerRadii[2],
node.windowCornerRadii[3],
],
)
useEffect(() => () => geometry?.dispose(), [geometry])
if (!(segment && geometry)) return null
// Dormers are mounted inside `RoofRenderer`'s `roof-elements` group
// (at the roof origin — NOT inside the host segment's transform), so
// we apply the segment's own position + rotation here. Mirrors how
// chimney / skylight render. The CSG geometry is built in
// dormer-mesh-local with `dormer.position` + `dormer.rotation`
// already accounted for by `segToMesh`, so we layer them as group
// transforms here too.
return (
<group
position={segment.position}
ref={ref}
rotation-y={segment.rotation ?? 0}
visible={node.visible}
>
<group
position={[node.position[0] ?? 0, node.position[1] ?? 0, node.position[2] ?? 0]}
>
<group rotation-y={node.rotation ?? 0} {...handlers}>
<mesh
castShadow
geometry={geometry}
material={material}
name="dormer-body"
receiveShadow
/>
<DormerWindowAssembly
frameMaterial={frameSideMat}
node={node}
segment={segment}
/>
</group>
</group>
</group>
)
}
// Re-export so consumers (e.g. tests) can reach the gable slot index
// without importing from `@pascal-app/viewer` directly.
export { DORMER_GABLE_MATERIAL_INDEX }
export default DormerRenderer
+5
View File
@@ -0,0 +1,5 @@
export { DormerNode, getEffectiveDormerSurfaceMaterial } from '@pascal-app/core'
export type {
DormerSurfaceMaterialRole,
DormerSurfaceMaterialSpec,
} from '@pascal-app/core'
+83
View File
@@ -0,0 +1,83 @@
'use client'
import { type AnyNodeId, DormerNode, useScene } from '@pascal-app/core'
import { useViewer } from '@pascal-app/viewer'
import { useMemo } from 'react'
import { dormerDefinition } from './definition'
import DormerPreview from './preview'
import { useDormerPlacement } from './use-dormer-placement'
/**
* Pick the smallest free integer suffix for a new dormer name so the
* scene tree doesn't end up with multiple `Dormer 3`s after deletes.
*/
function nextDormerNumber(nodes: Record<string, unknown>): number {
const used = new Set<number>()
for (const node of Object.values(nodes)) {
if (!node || typeof node !== 'object') continue
const n = node as { type?: string; name?: string }
if (n.type !== 'dormer') continue
const m = n.name?.match(/^Dormer (\d+)$/)
if (m?.[1]) used.add(Number.parseInt(m[1], 10))
}
let n = 1
while (used.has(n)) n++
return n
}
/**
* Placement tool for a fresh dormer. The dormer sits UPRIGHT on the
* host segment at segment-local `y = 0` (the host wall foot) — the
* CSG inside `generateDormerGeometry` carves the dormer against the
* host roof's slope, so we don't tilt or lift it here. The ghost is
* mounted on the hit segment's world transform (extracted via the
* registry) so the user sees exactly where the dormer will land.
*/
const DormerTool = () => {
const setSelection = useViewer((s) => s.setSelection)
const previewNode = useMemo(
() =>
DormerNode.parse({
...dormerDefinition.defaults(),
name: 'Dormer',
position: [0, 0, 0],
rotation: 0,
}),
[],
)
const { activeBuildingId, segmentXform, hitLocal, ghostRotation } = useDormerPlacement({
onCommit: (hit, rotation) => {
const state = useScene.getState()
const dormer = DormerNode.parse({
...dormerDefinition.defaults(),
name: `Dormer ${nextDormerNumber(state.nodes)}`,
roofSegmentId: hit.segment.id,
parentId: hit.segment.id,
// Anchor at the slope height so the renderer matches the ghost.
// The CSG still carves cleanly because it inverts T(position)
// when bringing the host into dormer-local.
position: [hit.localX, hit.localY, hit.localZ],
rotation,
})
state.createNode(dormer, hit.segment.id as AnyNodeId)
state.dirtyNodes.add(hit.segment.id as AnyNodeId)
setSelection({ selectedIds: [dormer.id] })
},
})
if (!activeBuildingId || !segmentXform || !hitLocal) return null
return (
<group position={segmentXform.position} quaternion={segmentXform.quaternion}>
<group position={hitLocal}>
<group rotation-y={ghostRotation}>
<DormerPreview node={previewNode} />
</group>
</group>
</group>
)
}
export default DormerTool
@@ -0,0 +1,171 @@
import {
type AnyNodeId,
emitter,
type RoofEvent,
type RoofNode,
type RoofSegmentNode,
sceneRegistry,
} from '@pascal-app/core'
import { triggerSFX } from '@pascal-app/editor'
import { useViewer } from '@pascal-app/viewer'
import { useEffect, useRef, useState } from 'react'
import * as THREE from 'three'
import { resolveRoofSegmentHit } from '../roof/segment-hit'
import {
DORMER_PLACEMENT_ROTATION_STEP,
DORMER_PLACEMENT_SNAP_M,
} from './geometry'
const tmpMatrix = new THREE.Matrix4()
const tmpInv = new THREE.Matrix4()
const tmpPos = new THREE.Vector3()
const tmpQuat = new THREE.Quaternion()
const tmpScale = new THREE.Vector3()
export type DormerSegmentTransform = {
position: [number, number, number]
quaternion: [number, number, number, number]
}
export type DormerPlacementHit = {
segment: RoofSegmentNode
localX: number
localY: number
localZ: number
}
/**
* Shared placement-tool plumbing for fresh-place and duplicate/move
* tools. Owns:
* - cursor → roof-segment hit resolution (delegated to the host
* RoofNode pointer events)
* - building-local segment transform extraction (for ghost mounting)
* - 5cm grid snap + SFX cue
* - keyboard rotate (R / Shift+R, ±15°)
*
* Does NOT own:
* - the ghost mesh (caller renders `<DormerPreview>`)
* - any node-lifecycle state (caller passes an `onCommit` that
* decides between createNode / updateNode / etc.)
*
* Returns the segment transform + cursor hit so the caller can mount
* the ghost, plus the live ghost rotation (driven by R / Shift+R).
*/
export function useDormerPlacement(opts: {
initialRotation?: number
onCommit: (hit: DormerPlacementHit, rotation: number) => void
}): {
activeBuildingId: string | undefined
segmentXform: DormerSegmentTransform | null
hitLocal: [number, number, number] | null
ghostRotation: number
} {
const activeBuildingId = useViewer((s) => s.selection.buildingId)
const [segmentXform, setSegmentXform] = useState<DormerSegmentTransform | null>(null)
const [hitLocal, setHitLocal] = useState<[number, number, number] | null>(null)
const [ghostRotation, setGhostRotation] = useState(opts.initialRotation ?? 0)
const lastSnapRef = useRef<[number, number] | null>(null)
// Mirror of `ghostRotation` so the click handler (registered once
// inside useEffect) can read the latest value at commit time.
const ghostRotationRef = useRef(opts.initialRotation ?? 0)
// Latest commit callback, captured via ref so the useEffect doesn't
// need it in its dep list (we don't want to re-register listeners
// every time the parent rerenders).
const onCommitRef = useRef(opts.onCommit)
onCommitRef.current = opts.onCommit
useEffect(() => {
if (!activeBuildingId) return
const computeSegmentXform = (segmentId: string): DormerSegmentTransform | null => {
const buildingObj = sceneRegistry.nodes.get(activeBuildingId as AnyNodeId)
const segObj = sceneRegistry.nodes.get(segmentId as AnyNodeId)
if (!(buildingObj && segObj)) return null
buildingObj.updateWorldMatrix(true, false)
segObj.updateWorldMatrix(true, false)
tmpInv.copy(buildingObj.matrixWorld).invert()
tmpMatrix.multiplyMatrices(tmpInv, segObj.matrixWorld)
tmpMatrix.decompose(tmpPos, tmpQuat, tmpScale)
return {
position: [tmpPos.x, tmpPos.y, tmpPos.z],
quaternion: [tmpQuat.x, tmpQuat.y, tmpQuat.z, tmpQuat.w],
}
}
const updatePreview = (event: RoofEvent) => {
const wx = event.position[0]
const wy = event.position[1]
const wz = event.position[2]
const sx = Math.round(wx / DORMER_PLACEMENT_SNAP_M) * DORMER_PLACEMENT_SNAP_M
const sz = Math.round(wz / DORMER_PLACEMENT_SNAP_M) * DORMER_PLACEMENT_SNAP_M
const prev = lastSnapRef.current
if (!prev || prev[0] !== sx || prev[1] !== sz) {
triggerSFX('sfx:grid-snap')
lastSnapRef.current = [sx, sz]
}
const hit = resolveRoofSegmentHit(event.node as RoofNode, wx, wy, wz)
if (!hit) return
const xform = computeSegmentXform(hit.segment.id)
if (!xform) return
setSegmentXform(xform)
// Lift the ghost to the actual roof-surface Y at the cursor so
// it tracks the mouse along the slope. The CSG inside
// `generateDormerGeometry` carves the dormer against the host
// roof regardless of `position[1]` — anchoring at the cursor
// height is purely a visual alignment.
setHitLocal([hit.localX, hit.localY, hit.localZ])
event.stopPropagation()
}
const onClick = (event: RoofEvent) => {
const hit = resolveRoofSegmentHit(
event.node as RoofNode,
event.position[0],
event.position[1],
event.position[2],
)
if (!hit) return
onCommitRef.current(hit, ghostRotationRef.current)
triggerSFX('sfx:item-place')
event.stopPropagation()
}
const onKeyDown = (e: KeyboardEvent) => {
if (e.key !== 'r' && e.key !== 'R') return
const target = e.target as HTMLElement | null
if (
target &&
(target.tagName === 'INPUT' ||
target.tagName === 'TEXTAREA' ||
target.isContentEditable)
)
return
const dir = e.shiftKey ? -1 : 1
ghostRotationRef.current += dir * DORMER_PLACEMENT_ROTATION_STEP
setGhostRotation(ghostRotationRef.current)
e.preventDefault()
}
emitter.on('roof:move', updatePreview)
emitter.on('roof:enter', updatePreview)
emitter.on('roof:click', onClick)
window.addEventListener('keydown', onKeyDown)
return () => {
emitter.off('roof:move', updatePreview)
emitter.off('roof:enter', updatePreview)
emitter.off('roof:click', onClick)
window.removeEventListener('keydown', onKeyDown)
}
}, [activeBuildingId])
return {
activeBuildingId: activeBuildingId ?? undefined,
segmentXform,
hitLocal,
ghostRotation,
}
}
@@ -0,0 +1,166 @@
'use client'
import type { DormerNode, RoofSegmentNode } from '@pascal-app/core'
import { glassMaterial } from '@pascal-app/viewer'
import { getDormerExposedFaces, getDormerSkirtWindowDims } from './csg-geometry'
import { useEffect, useMemo } from 'react'
import * as THREE from 'three'
import { buildDormerWindowGeometries, type DormerWindowShape } from './window-frame'
/**
* Renders the window opening assembly (frame bars, glass panes, sill)
* on each exposed gable face of a dormer. Owns its geometry lifecycle
* (build via `buildDormerWindowGeometries`, dispose on unmount) so the
* renderer doesn't have to.
*
* Mounted inside the dormer's rotation group, in dormer-mesh-local
* coordinates. The CSG cut on the wall is performed separately inside
* the viewer's `generateDormerGeometry`; the geometry built here is
* sized to match that cut.
*/
const DormerWindowAssembly = ({
node,
segment,
frameMaterial,
}: {
node: DormerNode
segment: RoofSegmentNode
frameMaterial: THREE.Material
}) => {
const skirtWin = useMemo(
() => getDormerSkirtWindowDims(node),
[
node.width,
node.windowWidth,
node.windowHeight,
node.windowOffsetX,
node.windowOffsetY,
node.wallSkirtHeight,
],
)
const winW = skirtWin.width
const winH = skirtWin.height
const winShape: DormerWindowShape = node.windowShape
const resolvedRadii: [number, number, number, number] = [...node.windowCornerRadii]
const winGeo = useMemo(
() =>
buildDormerWindowGeometries(
winW,
winH,
node.windowFrameThickness,
node.windowFrameDepth,
node.windowColumns,
node.windowRows,
node.windowDividerThickness,
winShape,
node.windowArchHeight,
resolvedRadii,
),
[
winW,
winH,
node.windowFrameThickness,
node.windowFrameDepth,
node.windowColumns,
node.windowRows,
node.windowDividerThickness,
winShape,
node.windowArchHeight,
...resolvedRadii,
],
)
useEffect(() => {
return () => {
const disposed = new Set<THREE.BufferGeometry>()
for (const bar of winGeo.frameBars) {
if (!disposed.has(bar.geo)) {
bar.geo.dispose()
disposed.add(bar.geo)
}
}
for (const pane of winGeo.glassPanes) {
if (!disposed.has(pane.geo)) {
pane.geo.dispose()
disposed.add(pane.geo)
}
}
}
}, [winGeo])
const sillEnabled = node.windowSill !== false
const sillT = Math.max(0.001, node.windowSillThickness)
const sillD = Math.max(0.001, node.windowSillDepth)
const sillW = winW + 0.06 // 3 cm overhang each side
const sillGeo = useMemo(
() => (sillEnabled ? new THREE.BoxGeometry(sillW, sillT, sillD) : null),
[sillEnabled, sillW, sillT, sillD],
)
useEffect(() => () => sillGeo?.dispose(), [sillGeo])
const exposed = useMemo(
() => getDormerExposedFaces(node, segment),
[
segment,
node.roofType,
node.width,
node.depth,
node.height,
node.roofHeight,
node.position[0],
node.position[1],
node.position[2],
],
)
const gableHalfZ = node.depth / 2
const winX = skirtWin.offsetX
const winY = skirtWin.centerY
const renderFace = (zPos: number, outDir: number, keyPrefix: string) => (
<group name={`dormer-window-${keyPrefix}`} position={[winX, winY, zPos]}>
{winGeo.glassPanes.map((pane, i) => (
<mesh
geometry={pane.geo}
// biome-ignore lint/suspicious/noArrayIndexKey: glass panes are derived from grid indices, no stable id.
key={`${keyPrefix}-glass-${i}`}
material={glassMaterial}
name={`dormer-glass-${keyPrefix}-${i}`}
position={pane.pos}
/>
))}
{winGeo.frameBars.map((bar, i) => (
<mesh
castShadow
geometry={bar.geo}
// biome-ignore lint/suspicious/noArrayIndexKey: frame bars are derived from grid indices, no stable id.
key={`${keyPrefix}-bar-${i}`}
material={frameMaterial}
name={`dormer-frame-${keyPrefix}-${i}`}
position={bar.pos}
/>
))}
{sillGeo && (
<mesh
castShadow
geometry={sillGeo}
material={frameMaterial}
name={`dormer-sill-${keyPrefix}`}
position={[0, -winH / 2 - sillT / 2, (outDir * sillD) / 2]}
receiveShadow
/>
)}
</group>
)
return (
<>
{exposed.front && renderFace(gableHalfZ, +1, 'front')}
{exposed.back && renderFace(-gableHalfZ, -1, 'back')}
</>
)
}
export default DormerWindowAssembly
+152
View File
@@ -0,0 +1,152 @@
import * as THREE from 'three'
import { createDormerArchShape, createDormerRoundedShape } from './csg-geometry'
/**
* Frame + glass geometry for the window opening on a dormer's gable
* face. The extruded frame profile uses the same shape builders as the
* CSG cut in the viewer (`generateDormerGeometry`), so the frame sits
* flush in the wall — keeping the cut and the frame visually in sync.
*
* Only the frame bars and glass panes are produced here; the wall
* opening itself is CSG-subtracted from the dormer body inside the
* viewer's `generateDormerGeometry`.
*/
export type DormerWindowShape = 'rectangle' | 'rounded' | 'arch'
export type WindowGeometries = {
frameBars: { geo: THREE.BufferGeometry; pos: [number, number, number] }[]
glassPanes: { geo: THREE.BufferGeometry; pos: [number, number, number] }[]
}
export function buildDormerWindowGeometries(
winW: number,
winH: number,
ft: number,
fd: number,
cols: number,
rows: number,
dt: number,
shape: DormerWindowShape = 'rectangle',
archHeight = 0.35,
cornerRadii: [number, number, number, number] = [0.15, 0.15, 0.15, 0.15],
): WindowGeometries {
const safeFt = Math.max(0.001, ft)
const safeDt = Math.max(0.001, dt)
const innerW = Math.max(0.01, winW - 2 * safeFt)
const innerH = Math.max(0.01, winH - 2 * safeFt)
const hw = winW / 2
const hh = winH / 2
const frameBars: WindowGeometries['frameBars'] = []
const glassPanes: WindowGeometries['glassPanes'] = []
if (shape === 'arch' || shape === 'rounded') {
const insetRadii = cornerRadii.map((r) => Math.max(r - safeFt, 0)) as [
number,
number,
number,
number,
]
const outerShape =
shape === 'arch'
? createDormerArchShape(winW, winH, archHeight)
: createDormerRoundedShape(winW, winH, cornerRadii)
const innerHole =
shape === 'arch'
? createDormerArchShape(winW - 2 * safeFt, winH - 2 * safeFt, Math.max(archHeight - safeFt, 0.01))
: createDormerRoundedShape(winW - 2 * safeFt, winH - 2 * safeFt, insetRadii)
outerShape.holes.push(innerHole)
const frameGeo = new THREE.ExtrudeGeometry(outerShape, {
depth: fd,
bevelEnabled: false,
curveSegments: 24,
})
frameGeo.translate(0, 0, -fd / 2)
frameBars.push({ geo: frameGeo, pos: [0, 0, 0] })
const colDividerCount = cols - 1
const totalColDividerW = colDividerCount * safeDt
const paneAreaW = Math.max(0.01, innerW - totalColDividerW)
const paneW = paneAreaW / cols
for (let c = 1; c < cols; c++) {
const x = -innerW / 2 + c * paneW + (c - 0.5) * safeDt
frameBars.push({ geo: new THREE.BoxGeometry(safeDt, innerH, fd), pos: [x, 0, 0] })
}
const rowDividerCount = rows - 1
const totalRowDividerH = rowDividerCount * safeDt
const paneAreaH = Math.max(0.01, innerH - totalRowDividerH)
const paneH = paneAreaH / rows
for (let r = 1; r < rows; r++) {
const y = -innerH / 2 + r * paneH + (r - 0.5) * safeDt
frameBars.push({ geo: new THREE.BoxGeometry(innerW, safeDt, fd), pos: [0, y, 0] })
}
const glassShape =
shape === 'arch'
? createDormerArchShape(winW - 2 * safeFt, winH - 2 * safeFt, Math.max(archHeight - safeFt, 0.01))
: createDormerRoundedShape(winW - 2 * safeFt, winH - 2 * safeFt, insetRadii)
const glassGeo = new THREE.ExtrudeGeometry(glassShape, {
depth: 0.008,
bevelEnabled: false,
curveSegments: 24,
})
glassGeo.translate(0, 0, -0.004)
glassPanes.push({ geo: glassGeo, pos: [0, 0, 0] })
} else {
frameBars.push({
geo: new THREE.BoxGeometry(winW, safeFt, fd),
pos: [0, hh - safeFt / 2, 0],
})
frameBars.push({
geo: new THREE.BoxGeometry(winW, safeFt, fd),
pos: [0, -hh + safeFt / 2, 0],
})
frameBars.push({
geo: new THREE.BoxGeometry(safeFt, innerH, fd),
pos: [-hw + safeFt / 2, 0, 0],
})
frameBars.push({
geo: new THREE.BoxGeometry(safeFt, innerH, fd),
pos: [hw - safeFt / 2, 0, 0],
})
const colDividerCount = cols - 1
const totalColDividerW = colDividerCount * safeDt
const paneAreaW = Math.max(0.01, innerW - totalColDividerW)
const paneW = paneAreaW / cols
for (let c = 1; c < cols; c++) {
const x = -innerW / 2 + c * paneW + (c - 0.5) * safeDt
frameBars.push({ geo: new THREE.BoxGeometry(safeDt, innerH, fd), pos: [x, 0, 0] })
}
const rowDividerCount = rows - 1
const totalRowDividerH = rowDividerCount * safeDt
const paneAreaH = Math.max(0.01, innerH - totalRowDividerH)
const paneH = paneAreaH / rows
for (let r = 1; r < rows; r++) {
const y = -innerH / 2 + r * paneH + (r - 0.5) * safeDt
frameBars.push({ geo: new THREE.BoxGeometry(innerW, safeDt, fd), pos: [0, y, 0] })
}
const glassW = Math.max(0.01, paneAreaW / cols)
const glassH = Math.max(0.01, paneAreaH / rows)
const glassGeo = new THREE.BoxGeometry(glassW, glassH, 0.008)
for (let c = 0; c < cols; c++) {
const cx = -innerW / 2 + paneAreaW / cols / 2 + c * (paneAreaW / cols + safeDt)
for (let r = 0; r < rows; r++) {
const cy = -innerH / 2 + paneAreaH / rows / 2 + r * (paneAreaH / rows + safeDt)
glassPanes.push({ geo: glassGeo, pos: [cx, cy, 0] })
}
}
}
return { frameBars, glassPanes }
}