From 594fba1e166450d7903fbcebbb0d4ebd9c53d984 Mon Sep 17 00:00:00 2001 From: 8Maverik8 Date: Mon, 12 Oct 2026 10:22:54 +0300 Subject: [PATCH] roof: draw a roof by outline, shed/gable over any outline, canopies and overhangs PAR-1159 Roof by outline - Outline tool: draw a roof segment as a polygon; points snap to the building's outer contour (outer wall corners and faces of this storey and the one below, slab corners, posts), partitions excluded. - Shed and gable over an arbitrary outline: the slope planes cover the drawn polygon, not just its bounding rectangle. - Gable with a different pitch per side and a ridge step (split-level ridge); ridge height, ridge position and per-side attic walls are edited from a "Ridge" section in the panel and from plan handles, read against the house walls. - Canopies: pull any edge of a segment's covering outwards; the covering continues in the slope's plane while the walls stay on the house. Canopy edges snap to the building contour. - Overhang is drawn on every edge of the outline (eaves and rakes), with fascia and soffit geometry. Paint - Separate surface roles for the roof: gables, fascia, inside, covering and soffit, each in its own material slot (ROOF_SLOT_ROLES) and paintable separately on roofs and segments. - Print solids follow the new shapes: per-side pitches, the gable back and the per-pitch deck overhang. Walls and posts under a roof - Walls under a roof are cut to the roof's underside (and rise to it when the roof is higher than the storey); posts meet the underside. - Nothing passes through a roof: levels above are clipped by the roof below them. Fixes: a storey above a lower roof stays intact, removing a roof restores the clipped geometry, and the clip planes use the right frame. Panel fields - Metric and slider fields no longer change their value on mouse wheel, so scrolling the panel cannot edit a value by accident. Tests cover outline snapping, the outline tool, canopy snapping, gable ridge editing and handles, per-side pitches, ridge steps, canopies, abutments, fascia, footprint clipping, CSG robustness, paint slots, wall fit to the roof and the roof clip frame. Co-Authored-By: Claude Opus 5.5 --- .../core/src/contracts/reference-inventory.ts | 3 + packages/core/src/schema/index.ts | 21 + packages/core/src/schema/nodes/ridge-vent.ts | 8 +- .../src/schema/nodes/roof-segment-canopy.ts | 286 +++ .../src/schema/nodes/roof-segment-shape.ts | 171 +- .../src/schema/nodes/roof-segment-walls.ts | 78 +- .../core/src/schema/nodes/roof-segment.ts | 268 ++- .../src/schema/nodes/roof-surface-roles.ts | 63 + packages/core/src/schema/nodes/roof.ts | 56 +- .../src/components/editor/floorplan-panel.tsx | 20 +- .../components/editor/selection-manager.tsx | 35 +- .../systems/roof/roof-edit-system.tsx | 7 + .../components/ui/controls/metric-control.tsx | 35 +- .../components/ui/controls/slider-control.tsx | 20 +- .../src/lib/material-paint-roof-roles.test.ts | 36 + packages/editor/src/lib/material-paint.ts | 74 +- packages/editor/src/lib/print-roof-solids.ts | 75 +- .../src/store/use-floorplan-draft-preview.ts | 2 +- packages/nodes/src/chimney/preview.tsx | 3 + packages/nodes/src/column/renderer.tsx | 17 +- packages/nodes/src/dormer/csg-geometry.ts | 1 + packages/nodes/src/gutter/renderer.tsx | 3 + .../nodes/src/lean-to-extension/assembly.ts | 8 + packages/nodes/src/ridge-vent/renderer.tsx | 3 + .../src/roof-segment/canopy-snap.test.ts | 52 + .../nodes/src/roof-segment/canopy-snap.ts | 130 ++ packages/nodes/src/roof-segment/definition.ts | 193 +- .../src/roof-segment/floorplan-affordances.ts | 111 ++ packages/nodes/src/roof-segment/floorplan.ts | 61 +- .../src/roof-segment/gable-ridge-edit.test.ts | 170 ++ .../src/roof-segment/gable-ridge-edit.ts | 164 ++ .../roof-segment/gable-ridge-handles.test.ts | 59 + .../src/roof-segment/gable-ridge-section.tsx | 217 +++ packages/nodes/src/roof-segment/panel.tsx | 150 +- .../nodes/src/roof-segment/parametrics.ts | 20 + packages/nodes/src/roof-segment/renderer.tsx | 29 +- packages/nodes/src/roof/definition.ts | 46 +- packages/nodes/src/roof/floorplan.ts | 17 +- packages/nodes/src/roof/outline-snap.test.ts | 58 + packages/nodes/src/roof/outline-snap.ts | 170 ++ packages/nodes/src/roof/outline-tool.test.ts | 54 + packages/nodes/src/roof/outline-tool.tsx | 377 ++++ packages/nodes/src/roof/renderer.tsx | 5 +- .../nodes/src/roof/roof-footprint-source.ts | 6 +- packages/nodes/src/roof/tool.tsx | 20 +- packages/nodes/src/shared/roof-surface.ts | 25 +- packages/viewer/src/index.ts | 8 +- .../src/systems/roof/roof-abutment.test.ts | 96 + .../src/systems/roof/roof-canopy.test.ts | 268 +++ .../src/systems/roof/roof-clip-frame.test.ts | 138 ++ .../viewer/src/systems/roof/roof-clip.test.ts | 47 + packages/viewer/src/systems/roof/roof-clip.ts | 382 ++++ .../systems/roof/roof-csg-robustness.test.ts | 85 + .../src/systems/roof/roof-fascia.test.ts | 4 +- .../systems/roof/roof-footprint-clip.test.ts | 86 + .../systems/roof/roof-gable-pitches.test.ts | 422 +++++ .../src/systems/roof/roof-gable-step.test.ts | 318 ++++ .../viewer/src/systems/roof/roof-materials.ts | 123 +- .../src/systems/roof/roof-paint-slots.test.ts | 87 + .../src/systems/roof/roof-system.test.ts | 5 +- .../viewer/src/systems/roof/roof-system.tsx | 1636 ++++++++++++++--- .../viewer/src/systems/roof/roof-underside.ts | 256 +++ .../wall/wall-progressive-budget.test.ts | 2 +- .../src/systems/wall/wall-roof-fit.test.ts | 324 ++++ .../viewer/src/systems/wall/wall-roof-fit.ts | 371 ++++ .../viewer/src/systems/wall/wall-system.tsx | 121 +- 66 files changed, 7529 insertions(+), 677 deletions(-) create mode 100644 packages/core/src/schema/nodes/roof-segment-canopy.ts create mode 100644 packages/core/src/schema/nodes/roof-surface-roles.ts create mode 100644 packages/editor/src/lib/material-paint-roof-roles.test.ts create mode 100644 packages/nodes/src/roof-segment/canopy-snap.test.ts create mode 100644 packages/nodes/src/roof-segment/canopy-snap.ts create mode 100644 packages/nodes/src/roof-segment/gable-ridge-edit.test.ts create mode 100644 packages/nodes/src/roof-segment/gable-ridge-edit.ts create mode 100644 packages/nodes/src/roof-segment/gable-ridge-handles.test.ts create mode 100644 packages/nodes/src/roof-segment/gable-ridge-section.tsx create mode 100644 packages/nodes/src/roof/outline-snap.test.ts create mode 100644 packages/nodes/src/roof/outline-snap.ts create mode 100644 packages/nodes/src/roof/outline-tool.test.ts create mode 100644 packages/nodes/src/roof/outline-tool.tsx create mode 100644 packages/viewer/src/systems/roof/roof-abutment.test.ts create mode 100644 packages/viewer/src/systems/roof/roof-canopy.test.ts create mode 100644 packages/viewer/src/systems/roof/roof-clip-frame.test.ts create mode 100644 packages/viewer/src/systems/roof/roof-clip.test.ts create mode 100644 packages/viewer/src/systems/roof/roof-clip.ts create mode 100644 packages/viewer/src/systems/roof/roof-csg-robustness.test.ts create mode 100644 packages/viewer/src/systems/roof/roof-footprint-clip.test.ts create mode 100644 packages/viewer/src/systems/roof/roof-gable-pitches.test.ts create mode 100644 packages/viewer/src/systems/roof/roof-gable-step.test.ts create mode 100644 packages/viewer/src/systems/roof/roof-paint-slots.test.ts create mode 100644 packages/viewer/src/systems/roof/roof-underside.ts create mode 100644 packages/viewer/src/systems/wall/wall-roof-fit.test.ts create mode 100644 packages/viewer/src/systems/wall/wall-roof-fit.ts diff --git a/packages/core/src/contracts/reference-inventory.ts b/packages/core/src/contracts/reference-inventory.ts index 14976c28ef..544a14b6dc 100644 --- a/packages/core/src/contracts/reference-inventory.ts +++ b/packages/core/src/contracts/reference-inventory.ts @@ -80,11 +80,13 @@ const MATERIAL_FIELDS = [ 'material', 'edgeMaterial', 'exteriorMaterial', + 'fasciaMaterial', 'glassMaterial', 'interiorMaterial', 'panelMaterial', 'railingMaterial', 'sideMaterial', + 'soffitMaterial', 'topMaterial', 'treadMaterial', 'wallMaterial', @@ -918,6 +920,7 @@ export const METADATA_NON_REFERENCES: readonly { path: string; reason: string }[ 'floorOwnershipMigrated', 'floorReassignmentHeight', 'footprintApproximated', + 'gableLocks', 'generatedBy', 'ifcDerived', 'ifcSplit', diff --git a/packages/core/src/schema/index.ts b/packages/core/src/schema/index.ts index 81a914576f..d886a35e21 100644 --- a/packages/core/src/schema/index.ts +++ b/packages/core/src/schema/index.ts @@ -271,6 +271,7 @@ export type { RoofSupport, RoofSurfaceMaterialRole, RoofSurfaceMaterialSpec } fr export { getEffectiveRoofSurfaceMaterial, RoofNode } from './nodes/roof' export type { DutchRoofMetrics, + GableRidge, RoofSegmentSurfaceMaterialRole, RoofSegmentSurfaceMaterialSpec, RoofSegmentVisibleTopBounds, @@ -281,7 +282,9 @@ export { getConicalRoofCoverage, getDutchRoofMetrics, getEffectiveSegmentSurfaceMaterial, + getGableRidge, getPitchFromActiveRoofHeight, + getRoofSegmentBackSlopeTwin, getRoofSegmentSurfaceY, getRoofSegmentVisibleTopBounds, getSegmentSlopeFrame, @@ -293,11 +296,22 @@ export { RoofSegmentNode, RoofSegmentTrim, RoofType, + readGableRidgeStep, } from './nodes/roof-segment' +export type { RoofPlanRing } from './nodes/roof-segment-canopy' +export { + getGableWallInsets, + getRoofRingEdgeNormal, + getRoofSegmentCoverOutline, + getRoofSegmentWallOutline, + pullRoofSegmentCoverEdge, +} from './nodes/roof-segment-canopy' export type { DutchRoofShapeMetrics, + RoofModuleInput, RoofShapeEaveSide, RoofShapeFaceVertex, + RoofShapeGableBack, RoofShapeInsets, RoofShapeRatios, } from './nodes/roof-segment-shape' @@ -308,6 +322,7 @@ export { getRoofShapeEaveSides, getRoofShapeInsets, getRoofShapeRatios, + withRoofSegmentGableBack, } from './nodes/roof-segment-shape' export type { RoofSegmentWallFace, RoofWallFaceId } from './nodes/roof-segment-walls' export { @@ -320,6 +335,12 @@ export { roofFacePointToSegment, segmentPointToRoofWallFace, } from './nodes/roof-segment-walls' +export type { RoofSurfaceMaterialFields } from './nodes/roof-surface-roles' +export { + hasRoofRoleMaterial, + ROOF_SURFACE_MATERIAL_ROLES, + readRoofRoleMaterial, +} from './nodes/roof-surface-roles' export { CaptureSessionReference, type CaptureSessionReferenceInput, diff --git a/packages/core/src/schema/nodes/ridge-vent.ts b/packages/core/src/schema/nodes/ridge-vent.ts index 5b5925f32d..151327f302 100644 --- a/packages/core/src/schema/nodes/ridge-vent.ts +++ b/packages/core/src/schema/nodes/ridge-vent.ts @@ -5,6 +5,7 @@ import { MaterialSchema } from '../material' import { getDutchRoofMetrics, getRoofSegmentVisibleTopBounds, + getSegmentSlopeFrame, ROOF_SHAPE_DEFAULTS, type RoofSegmentNode, type RoofSegmentTrim, @@ -194,12 +195,13 @@ export function getRidgeVentLinesForSegment(segment: RoofSegmentNode): RidgeVent } if (segment.roofType !== 'hip') { - if (!ridgeZVisible) return [] + const ridgeZ = segment.roofType === 'gable' ? getSegmentSlopeFrame(segment).ridgeZ : 0 + if (!(minZ <= ridgeZ && maxZ >= ridgeZ)) return [] return [ { name: 'Ridge Vent', - start: [minX, 0], - end: [maxX, 0], + start: [minX, ridgeZ], + end: [maxX, ridgeZ], }, ] } diff --git a/packages/core/src/schema/nodes/roof-segment-canopy.ts b/packages/core/src/schema/nodes/roof-segment-canopy.ts new file mode 100644 index 0000000000..e2cc06abba --- /dev/null +++ b/packages/core/src/schema/nodes/roof-segment-canopy.ts @@ -0,0 +1,286 @@ +import { getGableRidge, type RoofSegmentNode } from './roof-segment' + +export type RoofPlanRing = [number, number][] + +type OutlineInput = Pick< + RoofSegmentNode, + 'width' | 'depth' | 'wallThickness' | 'footprint' | 'coverFootprint' +> + +/** + * The outer face of the walls a segment stands on, segment-local: its drawn + * outline, else its rectangle pushed out by half the wall thickness. + */ +export function getRoofSegmentWallOutline(node: OutlineInput): RoofPlanRing { + if (node.footprint && node.footprint.length >= 3) { + return node.footprint.map(([x, z]) => [x, z]) + } + const x = node.width / 2 + node.wallThickness / 2 + const z = node.depth / 2 + node.wallThickness / 2 + return [ + [-x, -z], + [x, -z], + [x, z], + [-x, z], + ] +} + +/** + * What the roof covers, segment-local: past the walls where it was pulled out + * as a canopy. A wall corner on one of its edges splits that edge there, so a + * canopy reaching on past the wall line has a side of its own to pull. + */ +export function getRoofSegmentCoverOutline(node: OutlineInput): RoofPlanRing { + if (!(node.coverFootprint && node.coverFootprint.length >= 3)) { + return getRoofSegmentWallOutline(node) + } + const cover = node.coverFootprint + const walls = getRoofSegmentWallOutline(node) + const ring: RoofPlanRing = [] + for (let i = 0; i < cover.length; i++) { + const [ax, az] = cover[i]! + const [bx, bz] = cover[(i + 1) % cover.length]! + ring.push([ax, az]) + const length = Math.hypot(bx - ax, bz - az) + if (length < 1e-9) continue + const ux = (bx - ax) / length + const uz = (bz - az) / length + const inner = walls + .map(([x, z]) => ({ t: (x - ax) * ux + (z - az) * uz, off: (x - ax) * uz - (z - az) * ux })) + .filter(({ t, off }) => Math.abs(off) < 1e-6 && t > 1e-6 && t < length - 1e-6) + .sort((p, q) => p.t - q.t) + for (const { t } of inner) ring.push([ax + ux * t, az + uz * t]) + } + return ring +} + +function signedArea(ring: readonly (readonly [number, number])[]): number { + let area = 0 + for (let i = 0; i < ring.length; i++) { + const [x1, z1] = ring[i]! + const [x2, z2] = ring[(i + 1) % ring.length]! + area += x1 * z2 - x2 * z1 + } + return area / 2 +} + +/** Unit outward normal of a ring edge (x, z), whichever way the ring winds. */ +export function getRoofRingEdgeNormal( + ring: readonly (readonly [number, number])[], + edgeIndex: number, +): [number, number] { + const [x1, z1] = ring[edgeIndex]! + const [x2, z2] = ring[(edgeIndex + 1) % ring.length]! + const length = Math.hypot(x2 - x1, z2 - z1) || 1 + const ccw = signedArea(ring) > 0 + const dx = (x2 - x1) / length + const dz = (z2 - z1) / length + return ccw ? [dz, -dx] : [-dz, dx] +} + +const RING_EPSILON = 1e-6 + +/** An edge's start, end, unit direction, outward normal and length. */ +function ringEdgeFrame(ring: RoofPlanRing, edgeIndex: number) { + const p = ring[edgeIndex]! + const q = ring[(edgeIndex + 1) % ring.length]! + const length = Math.hypot(q[0] - p[0], q[1] - p[1]) || 1 + const u: [number, number] = [(q[0] - p[0]) / length, (q[1] - p[1]) / length] + return { p, q, u, n: getRoofRingEdgeNormal(ring, edgeIndex), length } +} + +/** + * How far edge `edgeIndex` of `ring` may come in: up to the nearest of the + * obstacles' edges behind it, across its own span (what only touches its ends + * does not count). −Infinity when nothing is behind it. + */ +function inwardLimit( + ring: RoofPlanRing, + edgeIndex: number, + obstacles: { ring: RoofPlanRing; skip?: number }[], +): number { + const { p, u, n, length } = ringEdgeFrame(ring, edgeIndex) + const local = ([x, z]: [number, number]) => { + const dx = x - p[0] + const dz = z - p[1] + return { t: dx * u[0] + dz * u[1], s: dx * n[0] + dz * n[1] } + } + let limit = Number.NEGATIVE_INFINITY + for (const { ring: other, skip } of obstacles) { + for (let i = 0; i < other.length; i++) { + if (i === skip) continue + let a = local(other[i]!) + let b = local(other[(i + 1) % other.length]!) + if (a.t > b.t) [a, b] = [b, a] + const lo = Math.max(a.t, RING_EPSILON) + const hi = Math.min(b.t, length - RING_EPSILON) + if (lo > hi) continue + const at = (t: number) => + b.t - a.t < 1e-12 ? Math.max(a.s, b.s) : a.s + ((b.s - a.s) * (t - a.t)) / (b.t - a.t) + for (const s of [at(lo), at(hi)]) { + if (s <= RING_EPSILON) limit = Math.max(limit, Math.min(s, 0)) + } + } + } + return limit +} + +/** + * The ring with no repeated points and no point where it turns straight back + * on itself. Points on a straight run stay: a wall corner the covering was + * pulled out from is still where it was. + */ +function tidyRing(ring: RoofPlanRing): RoofPlanRing { + const points = ring.map(([x, z]) => [x, z] as [number, number]) + let changed = true + while (changed && points.length > 3) { + changed = false + for (let i = 0; i < points.length; i++) { + const prev = points[(i - 1 + points.length) % points.length]! + const point = points[i]! + const next = points[(i + 1) % points.length]! + const ax = point[0] - prev[0] + const az = point[1] - prev[1] + const bx = next[0] - point[0] + const bz = next[1] - point[1] + const repeated = Math.hypot(ax, az) < RING_EPSILON + const backtrack = + Math.abs(ax * bz - az * bx) < RING_EPSILON * Math.max(1, Math.hypot(ax, az)) && + ax * bx + az * bz < 0 + if (repeated || backtrack) { + points.splice(i, 1) + changed = true + break + } + } + } + return points +} + +/** + * The covering with edge `edgeIndex` pulled `distance` along its outward + * normal. An edge on the walls is pushed out as a new piece: its corners stay + * on the walls and the piece grows out of them. An edge out past the walls + * moves: at each end it slides along a neighbour running across it, and where + * the neighbour runs on in its line (a piece's side against a wall corner) + * that point stays and a new one leads out of it, so a piece's sides narrow or + * widen that piece alone. The pulled edge keeps its index. + */ +function pullCoverEdge( + cover: RoofPlanRing, + walls: RoofPlanRing, + edgeIndex: number, + distance: number, +): RoofPlanRing { + const count = cover.length + const { p, q, u, n } = ringEdgeFrame(cover, edgeIndex) + const onWalls = inwardLimit(cover, edgeIndex, [{ ring: walls }]) > -RING_EPSILON + const inLine = (from: [number, number], to: [number, number]) => + Math.abs((to[0] - from[0]) * u[1] - (to[1] - from[1]) * u[0]) < RING_EPSILON + const previous = cover[(edgeIndex - 1 + count) % count]! + const next = cover[(edgeIndex + 2) % count]! + const keepStart = onWalls || inLine(previous, p) + const keepEnd = onWalls || inLine(q, next) + + const moved: [[number, number], [number, number]] = [ + [p[0] + n[0] * distance, p[1] + n[1] * distance], + [q[0] + n[0] * distance, q[1] + n[1] * distance], + ] + // where the moved edge's line meets a neighbour's line + const meet = (a: [number, number], b: [number, number], fallback: [number, number]) => { + const [ex, ez] = [moved[1][0] - moved[0][0], moved[1][1] - moved[0][1]] + const [fx, fz] = [b[0] - a[0], b[1] - a[1]] + const denominator = ex * fz - ez * fx + if (Math.abs(denominator) < 1e-12) return fallback + const t = ((a[0] - moved[0][0]) * fz - (a[1] - moved[0][1]) * fx) / denominator + return [moved[0][0] + ex * t, moved[0][1] + ez * t] as [number, number] + } + const start = keepStart ? moved[0] : meet(previous, p, moved[0]) + const end = keepEnd ? moved[1] : meet(q, next, moved[1]) + + // the edge rebuilt at the head, then the rest of the ring from its end on + const rebuilt: RoofPlanRing = [...(keepStart ? [p] : []), start, end, ...(keepEnd ? [q] : [])] + for (let k = 2; k < count; k++) rebuilt.push(cover[(edgeIndex + k) % count]!) + // turned so the pulled edge sits at its index again + const head = keepStart ? 1 : 0 + const size = rebuilt.length + const turned = rebuilt.map((_, k) => rebuilt[(((k - edgeIndex + head) % size) + size) % size]!) + return tidyRing(turned) +} + +/** + * Pull one edge of what a gable covers out past the walls (or back toward + * them) by `distance`, as a canopy: the slopes run on in their own planes, + * the ridge keeps its place and height, and the roof's own walls stay on the + * building. The segment is rebuilt over the rectangle bounding the walls and + * the covering, so it moves and resizes with it. Null for anything but a + * sloped gable. + */ +export function pullRoofSegmentCoverEdge( + node: RoofSegmentNode, + edgeIndex: number, + distance: number, +): Partial | null { + const ridge = getGableRidge(node) + if (!ridge) return null + const walls = getRoofSegmentWallOutline(node) + const cover = getRoofSegmentCoverOutline(node) + if (edgeIndex < 0 || edgeIndex >= cover.length) return null + // never in past the walls, nor through the covering's far side + const limit = inwardLimit(cover, edgeIndex, [{ ring: walls }, { ring: cover, skip: edgeIndex }]) + const pulled = pullCoverEdge(cover, walls, edgeIndex, Math.max(limit, distance)) + + // the rectangle the roof is built over: bounding the walls and the covering + const points = [...walls, ...pulled] + const minX = Math.min(...points.map(([x]) => x)) + const maxX = Math.max(...points.map(([x]) => x)) + const minZ = Math.min(...points.map(([, z]) => z)) + const maxZ = Math.max(...points.map(([, z]) => z)) + const shiftX = (minX + maxX) / 2 + const shiftZ = (minZ + maxZ) / 2 + const width = maxX - minX + const depth = maxZ - minZ + + // the slope planes stay put: same ridge line and height, the +z eave moves + // with the rectangle's edge down (or up) the front slope + const ridgeZ = ridge.ridgeZ - shiftZ + const ridgeOffset = depth / 2 - ridgeZ + const wallHeight = ridge.height - ridgeOffset * Math.tan((ridge.frontPitch * Math.PI) / 180) + + // the segment's origin follows the rectangle's centre (rotation-y, as the roof renders it) + const rotation = node.rotation ?? 0 + const cos = Math.cos(rotation) + const sin = Math.sin(rotation) + const position: [number, number, number] = [ + node.position[0] + shiftX * cos + shiftZ * sin, + node.position[1], + node.position[2] - shiftX * sin + shiftZ * cos, + ] + const local = (ring: RoofPlanRing): RoofPlanRing => ring.map(([x, z]) => [x - shiftX, z - shiftZ]) + + return { + position, + width, + depth, + wallHeight, + ridgeOffset, + backPitch: ridge.backPitch, + footprint: local(walls), + coverFootprint: local(pulled), + } +} + +/** + * How far a gable's rectangle edges sit past the walls on its +z and −z + * sides (a canopy pulled out there): the ridge group is read and edited + * against the walls, not the canopy's edge. + */ +export function getGableWallInsets(node: OutlineInput): { front: number; back: number } { + const walls = getRoofSegmentWallOutline(node) + const maxZ = Math.max(...walls.map(([, z]) => z)) + const minZ = Math.min(...walls.map(([, z]) => z)) + return { + front: Math.max(0, node.depth / 2 - maxZ), + back: Math.max(0, node.depth / 2 + minZ), + } +} diff --git a/packages/core/src/schema/nodes/roof-segment-shape.ts b/packages/core/src/schema/nodes/roof-segment-shape.ts index ee5b7c065e..730e314bbb 100644 --- a/packages/core/src/schema/nodes/roof-segment-shape.ts +++ b/packages/core/src/schema/nodes/roof-segment-shape.ts @@ -1,4 +1,10 @@ -import { ROOF_SHAPE_DEFAULTS, type RoofType } from './roof-segment' +import { + getGableRidge, + getRoofSegmentBackSlopeTwin, + ROOF_SHAPE_DEFAULTS, + type RoofSegmentNode, + type RoofType, +} from './roof-segment' export type RoofShapeFaceVertex = { x: number @@ -30,6 +36,38 @@ export type RoofShapeInsets = { dutchI?: number } +/** + * The −z eave of a gable whose two slopes differ, taken from the same layer + * built at the −z pitch: its distance from the segment centre, its height, + * the slope's tangent and the inset of its bottom edge. + */ +export type RoofShapeGableBack = { + halfDepth: number + wh: number + tanTheta: number + inset: number + /** + * Segment-local z of a stepped ridge: each slope runs up to it at its own + * height and a vertical face closes the step. Absent, the ridge is where the + * two slope planes meet. + */ + stepZ?: number + /** + * With a stepped ridge, build only one slope's body: from that side's eave + * to `endZ` (segment-local z), its top the slope's plane carried on, its end + * plumb. The two slopes are built apart so the higher one can run on over + * the lower one. + */ + only?: 'front' | 'back' + endZ?: number + /** + * The one slope's end cut along a plane instead of plumb at `endZ`: through + * (`z`, `y`) with normal (`nz`, `ny`) in the segment's z–y plane, the body + * kept on the side the normal points away from. + */ + endCut?: { z: number; y: number; nz: number; ny: number } +} + export type RoofShapeRatios = { gambrelLowerWidthRatio: number mansardSteepWidthRatio: number @@ -296,6 +334,7 @@ export function getRoofModuleFaces(input: { dutchTopRakeThickness?: number conicalStartAngle?: number conicalSweepAngle?: number + gableBack?: RoofShapeGableBack }): RoofShapeFaceVertex[][] { const v = (x: number, y: number, z: number): RoofShapeFaceVertex => ({ x, y, z }) const { iF = 0, iB = 0, iL = 0, iR = 0 } = input.insets @@ -357,16 +396,64 @@ export function getRoofModuleFaces(input: { return sweepAngle > 0 ? faces.map((face) => [...face].reverse()) : faces } + const gableBack = input.type === 'gable' ? input.gableBack : undefined + const backZ = gableBack ? gableBack.halfDepth : input.d / 2 + const backWh = gableBack ? gableBack.wh : input.wh + const backInset = gableBack ? gableBack.inset : iB + + if (gableBack?.only && gableBack.endZ !== undefined && input.rh !== 0) { + // One slope of a stepped gable: a box from its eave to the end line, the + // top on the slope's plane. b/e 1–2 on the +z side, 3–4 on the −z side. + const frontZ = input.d / 2 + const endZ = gableBack.endZ + const front = gableBack.only === 'front' + const frontY = (z: number) => input.wh + (frontZ - z) * input.tanTheta + const backY = (z: number) => backWh + (backZ + z) * gableBack.tanTheta + // where the end plane meets the slope's top and the body's bottom + const cut = gableBack.endCut + const topEndZ = cut + ? front + ? (cut.nz * cut.z - cut.ny * (input.wh + frontZ * input.tanTheta - cut.y)) / + (cut.nz - cut.ny * input.tanTheta) + : (cut.nz * cut.z - cut.ny * (backWh + backZ * gableBack.tanTheta - cut.y)) / + (cut.nz + cut.ny * gableBack.tanTheta) + : endZ + const bottomEndZ = + cut && Math.abs(cut.nz) > 1e-9 ? cut.z - (cut.ny * (input.baseY - cut.y)) / cut.nz : topEndZ + const zF = front ? frontZ : topEndZ + const zB = front ? topEndZ : -backZ + const yF = front ? input.wh : backY(topEndZ) + const yB = front ? frontY(topEndZ) : backWh + const bF = front ? zF - iF : bottomEndZ + const bB = front ? bottomEndZ : zB + backInset + const p1 = v(-input.w / 2 + iL, input.baseY, bF) + const p2 = v(input.w / 2 - iR, input.baseY, bF) + const p3 = v(input.w / 2 - iR, input.baseY, bB) + const p4 = v(-input.w / 2 + iL, input.baseY, bB) + const q1 = v(-input.w / 2, yF, zF) + const q2 = v(input.w / 2, yF, zF) + const q3 = v(input.w / 2, yB, zB) + const q4 = v(-input.w / 2, yB, zB) + return [ + [p1, p2, q2, q1], + [p2, p3, q3, q2], + [p3, p4, q4, q3], + [p4, p1, q1, q4], + [p4, p3, p2, p1], + [q1, q2, q3, q4], + ] + } + const b1 = v(-input.w / 2 + iL, input.baseY, input.d / 2 - iF) const b2 = v(input.w / 2 - iR, input.baseY, input.d / 2 - iF) - const b3 = v(input.w / 2 - iR, input.baseY, -input.d / 2 + iB) - const b4 = v(-input.w / 2 + iL, input.baseY, -input.d / 2 + iB) + const b3 = v(input.w / 2 - iR, input.baseY, -backZ + backInset) + const b4 = v(-input.w / 2 + iL, input.baseY, -backZ + backInset) const bottom = [b4, b3, b2, b1] const e1 = v(-input.w / 2, input.wh, input.d / 2) const e2 = v(input.w / 2, input.wh, input.d / 2) - const e3 = v(input.w / 2, input.wh, -input.d / 2) - const e4 = v(-input.w / 2, input.wh, -input.d / 2) + const e3 = v(input.w / 2, backWh, -backZ) + const e4 = v(-input.w / 2, backWh, -backZ) const faces: RoofShapeFaceVertex[][] = [] faces.push([b1, b2, e2, e1], [b2, b3, e3, e2], [b3, b4, e4, e3], [b4, b1, e1, e4], bottom) @@ -376,8 +463,41 @@ export function getRoofModuleFaces(input: { if (input.type === 'flat' || input.rh === 0) { faces.push([e1, e2, e3, e4]) } else if (input.type === 'gable') { - const r1 = v(-input.w / 2, h, 0) - const r2 = v(input.w / 2, h, 0) + let ridgeZ = 0 + let ridgeY = h + if (gableBack?.stepZ !== undefined) { + // Each slope up to the step line at its own height; a vertical face between. + const frontZ = input.d / 2 + const z = Math.min(frontZ - 0.001, Math.max(-backZ + 0.001, gableBack.stepZ)) + const frontY = input.wh + (frontZ - z) * input.tanTheta + const backY = backWh + (backZ + z) * gableBack.tanTheta + const f1 = v(-input.w / 2, frontY, z) + const f2 = v(input.w / 2, frontY, z) + const k1 = v(-input.w / 2, backY, z) + const k2 = v(input.w / 2, backY, z) + faces.push([e1, e2, f2, f1], [e3, e4, k1, k2], [f1, f2, k2, k1]) + // The ends are concave on the lower side: fan them from the higher side's eave. + if (backY >= frontY) { + faces.push([e4, e1, f1], [e4, f1, k1], [e3, k2, f2], [e3, f2, e2]) + } else { + faces.push([e1, f1, k1], [e1, k1, e4], [e2, e3, k2], [e2, k2, f2]) + } + return faces + } + if (gableBack) { + // The ridge is where the +z and −z slope planes meet. + const frontZ = input.d / 2 + const tanFront = input.tanTheta + const tanSum = tanFront + gableBack.tanTheta + ridgeZ = + tanSum > 1e-9 + ? (input.wh + frontZ * tanFront - backWh - backZ * gableBack.tanTheta) / tanSum + : 0 + ridgeZ = Math.min(frontZ - 0.001, Math.max(-backZ + 0.001, ridgeZ)) + ridgeY = input.wh + (frontZ - ridgeZ) * tanFront + } + const r1 = v(-input.w / 2, ridgeY, ridgeZ) + const r2 = v(input.w / 2, ridgeY, ridgeZ) faces.push([e4, e1, r1], [e2, e3, r2], [e1, e2, r2, r1], [e3, e4, r1, r2]) } else if (input.type === 'hip') { if (Math.abs(input.w - input.d) < 0.01) { @@ -519,3 +639,40 @@ export function getRoofModuleFaces(input: { return faces } + +export type RoofModuleInput = Parameters[0] + +/** + * A roof layer's module input, with the −z eave of a gable whose slopes differ + * taken from the same layer built at the −z pitch. `build` is the layer's usual + * math for one pitch; the bottom sits under the lower of the two sides' bases + * and both eaves' bottom-edge insets are recomputed against it. + */ +export function withRoofSegmentGableBack< + N extends Pick & + Partial>, +>(node: N, build: (node: N) => RoofModuleInput): RoofModuleInput { + const input = build(node) + const twin = getRoofSegmentBackSlopeTwin(node) + if (!twin || input.type !== 'gable' || input.rh === 0) return input + const ridge = getGableRidge(node) + const back = build(twin) + const halfDepth = back.d / 2 + // One level bottom under both eaves: the lower of the two sides' bases. + const baseY = Math.min(input.baseY, back.baseY) + const maxInset = (input.d / 2 + halfDepth) / 2 - 0.005 + const squareCut = (inset: number | undefined, wh: number, tanTheta: number) => + (inset ?? 0) > 0 ? Math.min(Math.max(0, (wh - baseY) * tanTheta), maxInset) : 0 + return { + ...input, + baseY, + insets: { ...input.insets, iF: squareCut(input.insets.iF, input.wh, input.tanTheta) }, + gableBack: { + halfDepth, + wh: back.wh, + tanTheta: back.tanTheta, + inset: squareCut(input.insets.iB, back.wh, back.tanTheta), + ...(ridge && ridge.step !== 0 ? { stepZ: ridge.ridgeZ } : {}), + }, + } +} diff --git a/packages/core/src/schema/nodes/roof-segment-walls.ts b/packages/core/src/schema/nodes/roof-segment-walls.ts index 21bebe781b..9f03cc71ca 100644 --- a/packages/core/src/schema/nodes/roof-segment-walls.ts +++ b/packages/core/src/schema/nodes/roof-segment-walls.ts @@ -1,6 +1,11 @@ import { getWallFaceOffsets } from '../../systems/wall/wall-frame' import type { RoofSegmentNode } from './roof-segment' -import { getDutchRoofMetrics, getSegmentSlopeFrame } from './roof-segment' +import { + getDutchRoofMetrics, + getGableRidge, + getRoofSegmentBackSlopeTwin, + getSegmentSlopeFrame, +} from './roof-segment' /** * Wall-face math for roof segments — the vertical surfaces a wall-mounted @@ -50,6 +55,9 @@ type SegmentWallInputs = Pick< Partial< Pick< RoofSegmentNode, + | 'backPitch' + | 'ridgeOffset' + | 'ridgeStep' | 'gambrelLowerWidthRatio' | 'gambrelLowerHeightRatio' | 'mansardSteepWidthRatio' @@ -66,11 +74,17 @@ type WallVolumeFrame = { dV: number /** Eave height of the outer volume. */ eaveY: number - /** Ridge/peak height of the outer volume. */ + /** Ridge/peak height of the outer volume (gable: the +z slope's ridge). */ peakY: number + /** Gable: ridge height of the −z slope (differs from `peakY` with a ridge step). */ + backPeakY: number /** tan(pitch) of the primary slope. */ tanTheta: number hasSlope: boolean + /** Gable: eave height on the −z side (differs from `eaveY` with `backPitch`). */ + backEaveY: number + /** Gable: segment-local z of the ridge. */ + ridgeZ: number } function getWallVolumeFrame(node: SegmentWallInputs): WallVolumeFrame { @@ -85,13 +99,45 @@ function getWallVolumeFrame(node: SegmentWallInputs): WallVolumeFrame { rh = activeRh + autoDrop if (node.roofType === 'shed') rh = activeRh + 2 * autoDrop } + const backTwin = getRoofSegmentBackSlopeTwin(node) + if (backTwin && activeRh > 0) { + const backTan = getSegmentSlopeFrame(backTwin).tanTheta + const backEaveY = Math.max(0.05, backTwin.wallHeight - (wallThickness / 2) * backTan) + // Same as the module's gable ridge: where the two slope planes meet, or the step line. + const ridge = getGableRidge(node) + const stepped = ridge !== null && ridge.step !== 0 + const ridgeZ = Math.min( + dV / 2 - 0.001, + Math.max( + -dV / 2 + 0.001, + stepped + ? ridge.ridgeZ + : (eaveY + (dV / 2) * tanTheta - backEaveY - (dV / 2) * backTan) / (tanTheta + backTan), + ), + ) + const peakY = eaveY + (dV / 2 - ridgeZ) * tanTheta + return { + wV, + dV, + eaveY, + peakY, + backPeakY: stepped ? backEaveY + (dV / 2 + ridgeZ) * backTan : peakY, + tanTheta, + hasSlope: true, + backEaveY, + ridgeZ, + } + } return { wV, dV, eaveY, peakY: eaveY + Math.max(0.001, rh), + backPeakY: eaveY + Math.max(0.001, rh), tanTheta, hasSlope: activeRh > 0, + backEaveY: eaveY, + ridgeZ: 0, } } @@ -123,7 +169,7 @@ function buildFaceProfile( frame: WallVolumeFrame, id: RoofWallFaceId, ): [number, number][] { - const { wV, dV, eaveY, peakY, tanTheta, hasSlope } = frame + const { wV, dV, eaveY, peakY, backPeakY, tanTheta, hasSlope, backEaveY, ridgeZ } = frame const isEnd = id === 'right' || id === 'left' const length = isEnd ? dV : wV @@ -131,14 +177,26 @@ function buildFaceProfile( switch (node.roofType) { case 'gable': { + if (id === 'back') return rectProfile(length, backEaveY) if (!isEnd) return rectProfile(length, eaveY) - return [ - [0, 0], - [length, 0], - [length, eaveY], - [length / 2, peakY], - [0, eaveY], - ] + // u runs from +z to −z on the right face and from −z to +z on the left. + return id === 'right' + ? [ + [0, 0], + [length, 0], + [length, backEaveY], + ...(backPeakY !== peakY ? [[dV / 2 - ridgeZ, backPeakY] as [number, number]] : []), + [dV / 2 - ridgeZ, peakY], + [0, eaveY], + ] + : [ + [0, 0], + [length, 0], + [length, eaveY], + [dV / 2 + ridgeZ, peakY], + ...(backPeakY !== peakY ? [[dV / 2 + ridgeZ, backPeakY] as [number, number]] : []), + [0, backEaveY], + ] } case 'gambrel': { if (!isEnd) return rectProfile(length, eaveY) diff --git a/packages/core/src/schema/nodes/roof-segment.ts b/packages/core/src/schema/nodes/roof-segment.ts index 9ea6f5b14d..c64f45a1c1 100644 --- a/packages/core/src/schema/nodes/roof-segment.ts +++ b/packages/core/src/schema/nodes/roof-segment.ts @@ -1,8 +1,13 @@ import dedent from 'dedent' import { z } from 'zod' import { BaseNode, nodeType, objectId } from '../base' -import type { MaterialSchema as MaterialSchemaType } from '../material' import { MaterialSchema } from '../material' +import { + hasRoofRoleMaterial, + type RoofSurfaceMaterialRole, + type RoofSurfaceMaterialSpec, + readRoofRoleMaterial, +} from './roof-surface-roles' export const RoofType = z.enum([ 'hip', @@ -105,6 +110,10 @@ export const RoofSegmentNode = BaseNode.extend({ topMaterialPreset: z.string().optional(), edgeMaterial: MaterialSchema.optional(), edgeMaterialPreset: z.string().optional(), + soffitMaterial: MaterialSchema.optional(), + soffitMaterialPreset: z.string().optional(), + fasciaMaterial: MaterialSchema.optional(), + fasciaMaterialPreset: z.string().optional(), wallMaterial: MaterialSchema.optional(), wallMaterialPreset: z.string().optional(), position: z.tuple([z.number(), z.number(), z.number()]).default([0, 0, 0]), @@ -131,6 +140,22 @@ export const RoofSegmentNode = BaseNode.extend({ // boundary is projected vertically through the roof volume, so the // resulting edge follows the actual sloped roof surfaces. trim: RoofSegmentTrim, + // Segment-local plan outline (the wall line) the roof is cut to: the + // segment is built over its width × depth rectangle, then everything outside + // the outline (pushed out by the overhang) goes. The roof's own wall shell + // follows the outline itself, closing the gables along the walls. + footprint: z + .array(z.tuple([z.number(), z.number()])) + .min(3) + .optional(), + // Segment-local plan outline of what the roof covers, where it reaches past + // the walls as a canopy (over a terrace or a porch): the deck, shingles and + // soffit follow it (plus the overhang), the roof's own walls stay on + // `footprint`. Absent, the roof covers its footprint. + coverFootprint: z + .array(z.tuple([z.number(), z.number()])) + .min(3) + .optional(), // Wall height beneath the roof wallHeight: z.number().default(0.5), // Roof pitch in degrees — angle of the primary slope face. @@ -138,6 +163,19 @@ export const RoofSegmentNode = BaseNode.extend({ // it is the steep (lower) slope. The overall peak height is derived // from pitch + footprint + roofType via getActiveRoofHeight(). pitch: z.number().min(0).max(85).default(40), + // Gable only: pitch of the slope on the segment's −z side. Absent, both + // slopes take `pitch`. + backPitch: z.number().min(1).max(85).optional(), + // Gable only: plan distance from the +z wall line to the ridge — where the + // design puts it. The ridge stands at `wallHeight + ridgeOffset·tan(pitch)` + // and the −z eave hangs where the back slope reaches from it, so the two + // eaves (attic walls) may differ in height. Absent, both eaves stay at + // `wallHeight` and the ridge falls where the slopes meet. + ridgeOffset: z.number().positive().optional(), + // Gable only: how much higher the −z slope's ridge stands than the +z one's + // (negative: lower). Each slope keeps its own ridge height; at the ridge line + // a vertical step wall of the roof closes the gap. Absent, one ridge. + ridgeStep: z.number().optional(), // Structure thicknesses wallThickness: z.number().default(0.1), deckThickness: z.number().default(0.1), @@ -177,6 +215,15 @@ export const RoofSegmentNode = BaseNode.extend({ // shed, flat), built from the segment itself so they follow its pitch, // size, overhang and type. fascia: z.boolean().optional(), + // Edges of the covering cut square to the slope, as boards are, keeping how + // far the roof reaches: an eave keeps its outer face on the overhang line + // (the soffit draws back), a high edge its soffit. Off when absent: plumb. + squareEaves: z.boolean().optional(), + // With an eave below the wall top (a negative attic wall), cut the deck and + // shingles below the wall top inside the walls; outside, the eave + // overhangs. Off when absent: they stay (a ceiling following the slope). + // The roof's own walls end at the wall top either way. + cutAtWallTop: z.boolean().optional(), // Shed only: the board on the high edge. Off when that edge meets a wall // (a porch cover on a ledger); a lean-to never has one. fasciaHighEdge: z.boolean().optional(), @@ -243,11 +290,18 @@ export const RoofSegmentNode = BaseNode.extend({ - conicalStartAngle / conicalSweepAngle: angular extent of a conical sector (radians) - conicalFullCircle: temporarily render the complete cone while preserving the sector angles - trim: segment-local side cut distances + - footprint: segment-local outline the roof is cut to (overhang added outward) + - coverFootprint: segment-local outline the covering reaches, past the walls as a canopy (absent = footprint) - wallHeight: height of walls below the roof - - pitch: roof slope in degrees (angle of the primary slope face) + - pitch: roof slope in degrees (angle of the primary slope face; on a gable, the +z slope) + - backPitch: gable only — slope of the −z side in degrees (absent = pitch) + - ridgeOffset: gable only — plan distance from the +z wall line to the ridge (absent = where equal eaves meet) + - ridgeStep: gable only — how much higher the −z slope's ridge is than the +z one's; a step wall closes the gap (absent = one ridge) - wallThickness/deckThickness: structural thicknesses - overhang: eave overhang distance - shingleThickness: outer shingle layer thickness + - cutAtWallTop: with an eave below the wall top, cut the deck and shingles below it inside the walls (off when absent; the roof's own walls always end there) + - squareEaves: covering edges cut square to the slope, the overhang's reach kept (off when absent = plumb) - fascia: plumb fascia and rake boards on the eaves and rakes (gable, hip, shed, flat) (off when absent) - fasciaHighEdge: shed only — a board on the high edge (off when it meets a wall; on when absent) - gambrelLowerWidthRatio / gambrelLowerHeightRatio: kink position on gambrel roofs @@ -566,6 +620,116 @@ export type SegmentSlopeFrame = { sinTheta: number /** Overall eave-to-peak height of the assembled roof. */ activeRh: number + /** tan of the −z slope: differs from `tanTheta` only on a gable with `backPitch`. */ + backTanTheta: number + /** Segment-local z of the gable ridge; 0 unless the two slopes differ. */ + ridgeZ: number +} + +type GableRidgeInput = Partial> + +/** The gable's ridge step in metres: 0 when absent or not finite. */ +export function readGableRidgeStep(node: Pick | object): number { + const step = (node as { ridgeStep?: unknown }).ridgeStep + return typeof step === 'number' && Number.isFinite(step) ? step : 0 +} + +/** A gable whose two sides differ: in pitch, in eave height around a placed ridge, or in ridge height. */ +function isUnevenGable( + node: Pick & GableRidgeInput, +): boolean { + if (node.roofType !== 'gable' || !(node.pitch > 0)) return false + const distinctBack = + typeof node.backPitch === 'number' && + Number.isFinite(node.backPitch) && + node.backPitch > 0 && + node.backPitch !== node.pitch + const placedRidge = + typeof node.ridgeOffset === 'number' && + Number.isFinite(node.ridgeOffset) && + node.ridgeOffset > 0 + return distinctBack || placedRidge || readGableRidgeStep(node) !== 0 +} + +export type GableRidge = { + /** Plan distance from the +z wall line to the ridge. */ + offset: number + /** Segment-local z of the ridge. */ + ridgeZ: number + /** Ridge height of the +z slope above the segment base. */ + height: number + /** Ridge height of the −z slope: `height + step`. */ + backHeight: number + /** How much higher the −z ridge stands than the +z one; 0 for one ridge. */ + step: number + /** Eave (attic wall) height on the +z side — the segment's `wallHeight`. */ + frontWallHeight: number + /** Eave (attic wall) height on the −z side. */ + backWallHeight: number + frontPitch: number + backPitch: number +} + +/** + * The ridge of a sloped gable and the attic wall height it leaves on each side. + * Null for other roof types and for a flat gable. + */ +export function getGableRidge( + node: Pick & GableRidgeInput, +): GableRidge | null { + if (node.roofType !== 'gable' || !(node.pitch > 0)) return null + const depth = finitePositive(node.depth, DEFAULT_ROOF_SEGMENT_DEPTH) + const frontPitch = node.pitch + const backPitch = + typeof node.backPitch === 'number' && Number.isFinite(node.backPitch) && node.backPitch > 0 + ? node.backPitch + : frontPitch + const tanFront = Math.tan((frontPitch * Math.PI) / 180) + const tanBack = Math.tan((backPitch * Math.PI) / 180) + const minRun = Math.min(0.01, depth / 4) + // Without a placed ridge both eaves sit at the wall height: + // offset·tan(front) = (depth − offset)·tan(back). + const offset = + typeof node.ridgeOffset === 'number' && Number.isFinite(node.ridgeOffset) + ? Math.min(depth - minRun, Math.max(minRun, node.ridgeOffset)) + : (depth * tanBack) / (tanFront + tanBack) + const frontWallHeight = node.wallHeight + const height = frontWallHeight + offset * tanFront + const step = readGableRidgeStep(node) + const backHeight = height + step + return { + offset, + ridgeZ: depth / 2 - offset, + height, + backHeight, + step, + frontWallHeight, + backWallHeight: backHeight - (depth - offset) * tanBack, + frontPitch, + backPitch, + } +} + +/** + * The segment as if both its slopes were its −z side, or null when the two + * sides match. Every layer of a gable (wall shell, deck, shingles, boards) is + * built per side from that side's pitch and eave height alone, so a builder + * runs its usual math on this twin and keeps the −z eave; the ridge is where + * the two slope planes meet. + */ +export function getRoofSegmentBackSlopeTwin< + T extends Pick & GableRidgeInput, +>(node: T): T | null { + if (!isUnevenGable(node)) return null + const ridge = getGableRidge(node)! + return { + ...node, + pitch: ridge.backPitch, + backPitch: undefined, + ridgeOffset: undefined, + ridgeStep: undefined, + wallHeight: ridge.backWallHeight, + } } /** @@ -577,7 +741,9 @@ export type SegmentSlopeFrame = { * silently drifted when a new roof type was added. */ export function getSegmentSlopeFrame( - node: Pick & Partial, + node: Pick & + Partial & + GableRidgeInput, ): SegmentSlopeFrame { const ratios = withRatioDefaults(node) const run = getPrimarySlopeRun(ratios) @@ -586,15 +752,40 @@ export function getSegmentSlopeFrame( // resolves to a flat frame instead of computing `Math.tan(NaN)` → NaN geometry, // which poisons the merged-roof CSG ("Coplanar clip not handled" + NaN positions). if (node.roofType === 'flat' || !(node.pitch > 0)) { - return { run, rise: 0, tanTheta: 0, cosTheta: 1, sinTheta: 0, activeRh: 0 } + return { + run, + rise: 0, + tanTheta: 0, + cosTheta: 1, + sinTheta: 0, + activeRh: 0, + backTanTheta: 0, + ridgeZ: 0, + } } const pitchRad = (node.pitch * Math.PI) / 180 const tanTheta = Math.tan(pitchRad) const cosTheta = Math.cos(pitchRad) || 1 const sinTheta = Math.sin(pitchRad) + if (isUnevenGable(node)) { + // The eave height does not move the ridge in plan, so any wall height will do here. + const ridge = getGableRidge({ ...node, depth: ratios.depth, wallHeight: 0 })! + const backTanTheta = Math.tan((ridge.backPitch * Math.PI) / 180) + const rise = ridge.offset * tanTheta + return { + run: ridge.offset, + rise, + tanTheta, + cosTheta, + sinTheta, + activeRh: rise, + backTanTheta, + ridgeZ: ridge.ridgeZ, + } + } const rise = run * tanTheta const activeRh = rise / getPrimarySlopeRiseFraction(ratios) - return { run, rise, tanTheta, cosTheta, sinTheta, activeRh } + return { run, rise, tanTheta, cosTheta, sinTheta, activeRh, backTanTheta: tanTheta, ridgeZ: 0 } } /** @@ -624,10 +815,19 @@ export function getRoofSegmentVisibleTopBounds( const horizontalOverhang = finiteNonNegative(segment.overhang) * cosTheta const deckExt = finiteNonNegative(segment.wallThickness) / 2 + horizontalOverhang const shingleOverhang = finiteNonNegative(segment.shingleThickness) * sinTheta + const backTwin = getRoofSegmentBackSlopeTwin(segment) + const backFrame = backTwin ? getSegmentSlopeFrame(backTwin) : null + const backDeckExt = backFrame + ? finiteNonNegative(segment.wallThickness) / 2 + + finiteNonNegative(segment.overhang) * backFrame.cosTheta + : deckExt + const backShingleOverhang = backFrame + ? finiteNonNegative(segment.shingleThickness) * backFrame.sinTheta + : shingleOverhang let xExt = deckExt let frontExt = deckExt - let backExt = deckExt + let backExt = backDeckExt if ( segment.roofType === 'hip' || @@ -640,7 +840,7 @@ export function getRoofSegmentVisibleTopBounds( backExt += shingleOverhang } else if (segment.roofType === 'gable' || segment.roofType === 'gambrel') { frontExt += shingleOverhang - backExt += shingleOverhang + backExt += backShingleOverhang } else if (segment.roofType === 'shed' && activeRh > 0) { frontExt += shingleOverhang } @@ -698,6 +898,13 @@ export function getRoofSegmentSurfaceY( const peakY = node.wallHeight + activeRh if (activeRh === 0) return node.wallHeight + const ridge = isUnevenGable(node) ? getGableRidge(node) : null + if (ridge) { + return localZ >= ridge.ridgeZ + ? ridge.frontWallHeight + (node.depth / 2 - localZ) * slopeFrame.tanTheta + : ridge.backWallHeight + (node.depth / 2 + localZ) * slopeFrame.backTanTheta + } + if (node.roofType === 'gable' || node.roofType === 'gambrel' || node.roofType === 'mansard') { const t = node.depth > 0 ? Math.abs(localZ) / (node.depth / 2) : 0 return peakY - t * activeRh @@ -785,11 +992,8 @@ export function getPitchFromActiveRoofHeight(input: PitchInputs & { roofHeight: // Per-segment surface materials // ---------------------------------------------------------------------------- -export type RoofSegmentSurfaceMaterialRole = 'top' | 'edge' | 'wall' -export type RoofSegmentSurfaceMaterialSpec = { - material?: MaterialSchemaType - materialPreset?: string -} +export type RoofSegmentSurfaceMaterialRole = RoofSurfaceMaterialRole +export type RoofSegmentSurfaceMaterialSpec = RoofSurfaceMaterialSpec function getLegacyRoofSegmentSurfaceMaterial( node: RoofSegmentNode, @@ -801,8 +1005,8 @@ function getLegacyRoofSegmentSurfaceMaterial( } /** - * Resolve the segment-level material for one of the three surface roles. - * Falls back through: role-specific field → catch-all `material`. Pass the + * Resolve the segment-level material for one of the surface roles. + * Falls back through: role field (or the role it still follows) → catch-all `material`. Pass the * parent roof to `parentFallback` when you want the roof's role material * to fill in for an unset segment slot — typical from the renderer. */ @@ -811,31 +1015,8 @@ export function getEffectiveSegmentSurfaceMaterial( role: RoofSegmentSurfaceMaterialRole, parentFallback?: RoofSegmentSurfaceMaterialSpec, ): RoofSegmentSurfaceMaterialSpec { - if (role === 'top') { - if (node.topMaterial !== undefined || typeof node.topMaterialPreset === 'string') { - return { - material: node.topMaterial, - materialPreset: - typeof node.topMaterialPreset === 'string' ? node.topMaterialPreset : undefined, - } - } - } else if (role === 'edge') { - if (node.edgeMaterial !== undefined || typeof node.edgeMaterialPreset === 'string') { - return { - material: node.edgeMaterial, - materialPreset: - typeof node.edgeMaterialPreset === 'string' ? node.edgeMaterialPreset : undefined, - } - } - } else if (role === 'wall') { - if (node.wallMaterial !== undefined || typeof node.wallMaterialPreset === 'string') { - return { - material: node.wallMaterial, - materialPreset: - typeof node.wallMaterialPreset === 'string' ? node.wallMaterialPreset : undefined, - } - } - } + const own = readRoofRoleMaterial(node, role) + if (own) return own const legacy = getLegacyRoofSegmentSurfaceMaterial(node) if (legacy.material !== undefined || legacy.materialPreset !== undefined) return legacy @@ -845,7 +1026,7 @@ export function getEffectiveSegmentSurfaceMaterial( /** * Returns true when the segment has any segment-level material override — - * either the legacy catch-all or any of the three role-specific fields. + * either the legacy catch-all or any role field. * Used by `RoofRenderer` and `updateMergedRoofGeometry` to decide whether * the segment should be drawn as its own mesh or folded into the merged * shell. @@ -854,11 +1035,6 @@ export function hasSegmentMaterialOverride(node: RoofSegmentNode): boolean { return ( node.material !== undefined || typeof node.materialPreset === 'string' || - node.topMaterial !== undefined || - typeof node.topMaterialPreset === 'string' || - node.edgeMaterial !== undefined || - typeof node.edgeMaterialPreset === 'string' || - node.wallMaterial !== undefined || - typeof node.wallMaterialPreset === 'string' + hasRoofRoleMaterial(node) ) } diff --git a/packages/core/src/schema/nodes/roof-surface-roles.ts b/packages/core/src/schema/nodes/roof-surface-roles.ts new file mode 100644 index 0000000000..c6b6181e24 --- /dev/null +++ b/packages/core/src/schema/nodes/roof-surface-roles.ts @@ -0,0 +1,63 @@ +import type { MaterialSchema as MaterialSchemaType } from '../material' + +/** + * The surfaces of a roof that take their own paint: + * - top: the roof covering + * - edge: the gables — the roof's own walls (and step walls) + * - soffit: the underside of the overhang + * - fascia: the eave and rake ends of the overhang, and the fascia boards + * - wall: the inside of the roof + */ +export const ROOF_SURFACE_MATERIAL_ROLES = ['top', 'edge', 'soffit', 'fascia', 'wall'] as const + +export type RoofSurfaceMaterialRole = (typeof ROOF_SURFACE_MATERIAL_ROLES)[number] + +export type RoofSurfaceMaterialSpec = { + material?: MaterialSchemaType + materialPreset?: string +} + +/** + * The soffit and the fascia used to be painted with the gables (role `edge`). + * Until they are painted on their own they keep following it, so older roofs + * look as they did. + */ +const ROLE_FALLBACK: Partial> = { + soffit: 'edge', + fascia: 'edge', +} + +export type RoofSurfaceMaterialFields = { + topMaterial?: MaterialSchemaType + topMaterialPreset?: string + edgeMaterial?: MaterialSchemaType + edgeMaterialPreset?: string + soffitMaterial?: MaterialSchemaType + soffitMaterialPreset?: string + fasciaMaterial?: MaterialSchemaType + fasciaMaterialPreset?: string + wallMaterial?: MaterialSchemaType + wallMaterialPreset?: string +} + +/** The paint a node carries for one surface role (or the role it still follows), if any. */ +export function readRoofRoleMaterial( + node: RoofSurfaceMaterialFields, + role: RoofSurfaceMaterialRole, +): RoofSurfaceMaterialSpec | null { + const material = node[`${role}Material`] + const preset = node[`${role}MaterialPreset`] + if (material !== undefined || typeof preset === 'string') { + return { material, materialPreset: typeof preset === 'string' ? preset : undefined } + } + const fallback = ROLE_FALLBACK[role] + return fallback ? readRoofRoleMaterial(node, fallback) : null +} + +/** Whether a node carries paint of its own for any surface role. */ +export function hasRoofRoleMaterial(node: RoofSurfaceMaterialFields): boolean { + return ROOF_SURFACE_MATERIAL_ROLES.some( + (role) => + node[`${role}Material`] !== undefined || typeof node[`${role}MaterialPreset`] === 'string', + ) +} diff --git a/packages/core/src/schema/nodes/roof.ts b/packages/core/src/schema/nodes/roof.ts index e33ab76779..6f094bce42 100644 --- a/packages/core/src/schema/nodes/roof.ts +++ b/packages/core/src/schema/nodes/roof.ts @@ -2,15 +2,15 @@ import dedent from 'dedent' import { z } from 'zod' import { Assembly } from '../assembly' import { BaseNode, nodeType, objectId } from '../base' -import type { MaterialSchema as MaterialSchemaType } from '../material' import { MaterialSchema } from '../material' import { RoofSegmentNode } from './roof-segment' +import { + type RoofSurfaceMaterialRole, + type RoofSurfaceMaterialSpec, + readRoofRoleMaterial, +} from './roof-surface-roles' -export type RoofSurfaceMaterialRole = 'top' | 'edge' | 'wall' -export type RoofSurfaceMaterialSpec = { - material?: MaterialSchemaType - materialPreset?: string -} +export type { RoofSurfaceMaterialRole, RoofSurfaceMaterialSpec } from './roof-surface-roles' export const RoofSupport = z .discriminatedUnion('kind', [ @@ -36,6 +36,10 @@ export const RoofNode = BaseNode.extend({ topMaterialPreset: z.string().optional(), edgeMaterial: MaterialSchema.optional(), edgeMaterialPreset: z.string().optional(), + soffitMaterial: MaterialSchema.optional(), + soffitMaterialPreset: z.string().optional(), + fasciaMaterial: MaterialSchema.optional(), + fasciaMaterialPreset: z.string().optional(), wallMaterial: MaterialSchema.optional(), wallMaterialPreset: z.string().optional(), position: z.tuple([z.number(), z.number(), z.number()]).default([0, 0, 0]), @@ -74,39 +78,9 @@ export function getEffectiveRoofSurfaceMaterial( node: RoofNode, role: RoofSurfaceMaterialRole, ): RoofSurfaceMaterialSpec { - if (role === 'top') { - if (node.topMaterial !== undefined || typeof node.topMaterialPreset === 'string') { - return { - material: node.topMaterial, - materialPreset: - typeof node.topMaterialPreset === 'string' ? node.topMaterialPreset : undefined, - } - } - } - - if (role === 'edge') { - if (node.edgeMaterial !== undefined || typeof node.edgeMaterialPreset === 'string') { - return { - material: node.edgeMaterial, - materialPreset: - typeof node.edgeMaterialPreset === 'string' ? node.edgeMaterialPreset : undefined, - } - } - } - - if (role === 'wall') { - if (node.wallMaterial !== undefined || typeof node.wallMaterialPreset === 'string') { - return { - material: node.wallMaterial, - materialPreset: - typeof node.wallMaterialPreset === 'string' ? node.wallMaterialPreset : undefined, - } - } - } - - // No cross-role fallback: an unset role resolves only to the legacy - // catch-all (which covers all three roles for back-compat) and otherwise - // to the caller's theme default. Painting one surface must never bleed - // onto the others. - return getLegacyRoofSurfaceMaterial(node) + // No cross-role fallback beyond the roles a new surface still follows + // (see roof-surface-roles): an unset role resolves only to the legacy + // catch-all and otherwise to the caller's theme default. Painting one + // surface must never bleed onto the others. + return readRoofRoleMaterial(node, role) ?? getLegacyRoofSurfaceMaterial(node) } diff --git a/packages/editor/src/components/editor/floorplan-panel.tsx b/packages/editor/src/components/editor/floorplan-panel.tsx index 011165fa19..31bd0bcb8f 100644 --- a/packages/editor/src/components/editor/floorplan-panel.tsx +++ b/packages/editor/src/components/editor/floorplan-panel.tsx @@ -4435,6 +4435,13 @@ function FloorplanLinearDraftLayer({ const fenceDraftEnd = useFloorplanDraftPreview((s) => s.fenceDraftEnd) const roofDraftEnd = useFloorplanDraftPreview((s) => s.roofDraftEnd) const roofDraftQuarterTurn = useFloorplanDraftPreview((s) => s.roofDraftQuarterTurn) + // The roof tool's outline mode publishes its points; the cursor closes the ring. + const roofOutlineDraft = useFloorplanDraftPreview((s) => + s.polygonDraftType === 'roof' ? s.polygonDraftPoints : null, + ) + const roofOutlineCursor = useFloorplanDraftPreview((s) => + s.polygonDraftType === 'roof' && s.polygonDraftPoints.length > 0 ? s.cursorPoint : null, + ) const wallRectangleDraftStart = useFloorplanDraftPreview((s) => s.wallRectangleDraftStart) const wallPolygonDraftPoints = useFloorplanDraftPreview((s) => s.wallPolygonDraftPoints) // The live cursor is the rectangle's opposite corner; select it only while a @@ -4536,8 +4543,19 @@ function FloorplanLinearDraftLayer({ ]) } } + if (isRoofBuildActive && roofOutlineDraft && roofOutlineDraft.length > 0) { + const ring = roofOutlineCursor ? [...roofOutlineDraft, roofOutlineCursor] : roofOutlineDraft + if (ring.length >= 2) return formatPolygonPoints(ring.map(([x, y]) => ({ x, y }))) + } return draftPolygon ? formatPolygonPoints(draftPolygon) : null - }, [draftPolygon, isRoofBuildActive, roofDraftEnd, roofDraftStart]) + }, [ + draftPolygon, + isRoofBuildActive, + roofDraftEnd, + roofDraftStart, + roofOutlineCursor, + roofOutlineDraft, + ]) const roofDraftDirectionLine = useMemo(() => { if (!(isRoofBuildActive && roofDraftStart && roofDraftEnd)) return null diff --git a/packages/editor/src/components/editor/selection-manager.tsx b/packages/editor/src/components/editor/selection-manager.tsx index 2efca9c08e..f07599f4bc 100644 --- a/packages/editor/src/components/editor/selection-manager.tsx +++ b/packages/editor/src/components/editor/selection-manager.tsx @@ -19,6 +19,7 @@ import { type RoofNode, type RoofSegmentEvent, type RoofSegmentNode, + type RoofSurfaceMaterialRole, resolveLevelId, type SlabNode, type StairEvent, @@ -30,8 +31,10 @@ import { useScene, } from '@pascal-app/core' import { + buildRoofSlotMaterials, createMaterial, getRoofMaterialArray, + ROOF_SLOT_ROLES, registerMaterialCacheCleanup, resolveMaterialRef, useViewer, @@ -255,11 +258,10 @@ function resolveStairMaterialTarget( function resolveRoofMaterialTarget( event: RoofEvent | RoofSegmentEvent, -): 'top' | 'edge' | 'wall' | null { +): RoofSurfaceMaterialRole | null { const materialIndex = getIntersectionMaterialIndex(getEventObject(event), event.faceIndex) - if (materialIndex === 3) return 'top' - if (materialIndex === 0) return 'edge' - if (materialIndex === 1 || materialIndex === 2) return 'wall' + const slotRole = materialIndex === undefined ? undefined : ROOF_SLOT_ROLES[materialIndex] + if (slotRole) return slotRole const normalY = event.normal?.[1] if (normalY !== undefined && normalY > 0.35) return 'top' @@ -476,7 +478,7 @@ function previewCursor(cursor: string): PaintPreviewCleanup { function applyRoofPaintPreview( node: RoofNode, - role: 'top' | 'edge' | 'wall', + role: RoofSurfaceMaterialRole, material: ActivePaintMaterial, ): PaintPreviewCleanup | null { const root = getRegisteredNodeObject(node.id) @@ -504,22 +506,21 @@ function applyRoofPaintPreview( function applyRoofSegmentPaintPreview( node: RoofSegmentNode, parent: RoofNode | null, - role: 'top' | 'edge' | 'wall', + role: RoofSurfaceMaterialRole, material: ActivePaintMaterial, ): PaintPreviewCleanup | null { const mesh = getRegisteredMesh(node.id) if (!mesh) return null // Synthesise the segment node as if the paint had committed, then build - // the same 4-slot array the renderer would. Mirrors getRoofMaterialArray - // layout (slot 0 ← edge, 1 ← wall, 2 ← wall, 3 ← top) so the preview - // material lands on the matching CSG groups. + // the same per-slot array the renderer would (ROOF_SLOT_ROLES), so the + // preview material lands on the matching CSG groups. const previewNode: RoofSegmentNode = { ...node, ...buildRoofSegmentSurfaceMaterialPatch(node, role, material.material, material.materialPreset), } const sceneMaterials = useScene.getState().materials - const resolveSlot = (r: 'top' | 'edge' | 'wall'): Material | null => { + const resolveSlot = (r: RoofSurfaceMaterialRole): Material | null => { const parentSpec = parent ? getEffectiveRoofSurfaceMaterial(parent, r) : undefined const spec = getEffectiveSegmentSurfaceMaterial(previewNode, r, parentSpec) const resolved = resolveMaterialRef(spec.materialPreset, sceneMaterials) @@ -527,18 +528,18 @@ function applyRoofSegmentPaintPreview( if (spec.material !== undefined) return createMaterial(spec.material) return null } - const edge = resolveSlot('edge') - const wall = resolveSlot('wall') - const top = resolveSlot('top') - if (!(edge || wall || top)) return null + const resolved = new Map(ROOF_SLOT_ROLES.map((role) => [role, resolveSlot(role)] as const)) + if (![...resolved.values()].some(Boolean)) return null const fallback = parent ? getRoofMaterialArray(parent, undefined, undefined, undefined, undefined, null, sceneMaterials) : null - const fb = (n: number) => fallback?.[n] ?? null + if (!fallback) return null // Per-role only, then the parent's themed slot — matches the renderer so the // preview never bleeds a painted surface onto the segment's other surfaces. - const arr: Material[] = [edge ?? fb(0)!, wall ?? fb(1)!, wall ?? fb(2)!, top ?? fb(3)!] - if (arr.some((m) => !m)) return null + const arr = buildRoofSlotMaterials( + (role) => resolved.get(role) ?? null, + (slot) => fallback[slot]!, + ) return previewMeshMaterial(mesh, arr) } diff --git a/packages/editor/src/components/systems/roof/roof-edit-system.tsx b/packages/editor/src/components/systems/roof/roof-edit-system.tsx index bd4ba106a3..56af570110 100644 --- a/packages/editor/src/components/systems/roof/roof-edit-system.tsx +++ b/packages/editor/src/components/systems/roof/roof-edit-system.tsx @@ -508,6 +508,13 @@ function segmentShapeKey(segment: RoofSegmentNode): string { segment.depth, segment.wallHeight, segment.pitch, + segment.backPitch, + segment.ridgeOffset, + segment.ridgeStep, + segment.squareEaves, + segment.cutAtWallTop, + segment.footprint, + segment.coverFootprint, segment.wallThickness, segment.deckThickness, segment.overhang, diff --git a/packages/editor/src/components/ui/controls/metric-control.tsx b/packages/editor/src/components/ui/controls/metric-control.tsx index 797ea8e835..3c834c1227 100644 --- a/packages/editor/src/components/ui/controls/metric-control.tsx +++ b/packages/editor/src/components/ui/controls/metric-control.tsx @@ -63,7 +63,6 @@ export function MetricControl({ const [inputValue, setInputValue] = useState(displayValue.toFixed(precision)) const startXRef = useRef(0) const startValueRef = useRef(0) - const containerRef = useRef(null) const valueRef = useRef(value) valueRef.current = value @@ -85,38 +84,7 @@ export function MetricControl({ } }, [displayValue, precision, isEditing]) - useEffect(() => { - const container = containerRef.current - if (!container) return - - const handleWheel = (e: WheelEvent) => { - if (isEditing) return - - e.preventDefault() - - const direction = e.deltaY < 0 ? 1 : -1 - let scrollStep = toStoredValue(step) - if (e.shiftKey) scrollStep = toStoredValue(step * 10) - else if (e.altKey) scrollStep = toStoredValue(step * 0.1) - - const newValue = clamp(valueRef.current + direction * scrollStep) - const finalValue = roundStoredValueForDisplayPrecision(newValue) - - if (Math.abs(finalValue - valueRef.current) > 1e-6) { - applyCommittedValue(finalValue) - } - } - - container.addEventListener('wheel', handleWheel, { passive: false }) - return () => container.removeEventListener('wheel', handleWheel) - }, [ - isEditing, - step, - clamp, - applyCommittedValue, - toStoredValue, - roundStoredValueForDisplayPrecision, - ]) + // No wheel: it scrolls the panel; a scroll passing over must not change the value. useEffect(() => { if (!isHovered || isEditing) return @@ -315,7 +283,6 @@ export function MetricControl({ )} onMouseEnter={() => setIsHovered(true)} onMouseLeave={() => setIsHovered(false)} - ref={containerRef} >
(null) const shown = dragDisplay ?? value const valueRef = useRef(shown) valueRef.current = shown @@ -120,22 +119,8 @@ export function SliderControl({ } }, [value, precision, isEditing, toDisplay]) - // Wheel support on the label - useEffect(() => { - const el = labelRef.current - if (!el) return - const handleWheel = (e: WheelEvent) => { - if (isEditing) return - e.preventDefault() - const direction = e.deltaY < 0 ? 1 : -1 - const s = getAdjustedStep(step, e) - const final = applyDisplayDelta(valueRef.current, direction * s, s) - if (final !== valueRef.current) onChange(final) - onCommit?.(final) - } - el.addEventListener('wheel', handleWheel, { passive: false }) - return () => el.removeEventListener('wheel', handleWheel) - }, [isEditing, step, applyDisplayDelta, onChange, onCommit]) + // No wheel on the label: the wheel scrolls the panel, and a scroll passing + // over a label must not change its value (drag, arrows or typing do). // Arrow key support while hovered useEffect(() => { @@ -348,7 +333,6 @@ export function SliderControl({ onLostPointerCapture={() => { if (dragRef.current) cancelEdit() }} - ref={labelRef} > {/* Grip dots — 2×3 grid */}
({ + preset: 'custom' as const, + properties: { + color, + roughness: 0.5, + metalness: 0, + opacity: 1, + transparent: false, + side: 'front' as const, + }, +}) +const colour = (node: RoofNode, role: Parameters[1]) => + getEffectiveRoofSurfaceMaterial(node, role).material?.properties?.color + +describe('painting one roof surface', () => { + test('leaves the others as they look, even the ones that followed the gables', () => { + const red = paint('#ff0000') + const green = paint('#00ff00') + const roof = RoofNode.parse({ type: 'roof', edgeMaterial: red }) + const fascia = { ...roof, ...buildRoofSurfaceMaterialPatch(roof, 'fascia', green, undefined) } + expect(colour(fascia, 'fascia')).toBe(green.properties.color) + expect(colour(fascia, 'soffit')).toBe(red.properties.color) + expect(colour(fascia, 'edge')).toBe(red.properties.color) + + // repainting the gables no longer drags the soffit along + const blue = paint('#0000ff') + const gables = { ...fascia, ...buildRoofSurfaceMaterialPatch(fascia, 'edge', blue, undefined) } + expect(colour(gables, 'edge')).toBe(blue.properties.color) + expect(colour(gables, 'soffit')).toBe(red.properties.color) + expect(colour(gables, 'fascia')).toBe(green.properties.color) + }) +}) diff --git a/packages/editor/src/lib/material-paint.ts b/packages/editor/src/lib/material-paint.ts index 08737e0fd1..00daf782d8 100644 --- a/packages/editor/src/lib/material-paint.ts +++ b/packages/editor/src/lib/material-paint.ts @@ -17,6 +17,7 @@ import { type MaterialSchema, type MaterialTarget, nodeRegistry, + ROOF_SURFACE_MATERIAL_ROLES, type RoofNode, type RoofSegmentNode, type RoofSegmentSurfaceMaterialRole, @@ -87,28 +88,35 @@ export function buildRoofSurfaceMaterialPatch( material: MaterialSchema | undefined, materialPreset: string | undefined, ): Partial { - const nextSurfaceMaterial = { material, materialPreset } - const nextTop = - targetRole === 'top' ? nextSurfaceMaterial : getEffectiveRoofSurfaceMaterial(node, 'top') - const nextEdge = - targetRole === 'edge' ? nextSurfaceMaterial : getEffectiveRoofSurfaceMaterial(node, 'edge') - const nextWall = - targetRole === 'wall' ? nextSurfaceMaterial : getEffectiveRoofSurfaceMaterial(node, 'wall') + return buildRoleMaterialPatch(targetRole, { material, materialPreset }, (role) => + getEffectiveRoofSurfaceMaterial(node, role), + ) as Partial +} - return { - topMaterial: nextTop.material, - topMaterialPreset: nextTop.materialPreset, - edgeMaterial: nextEdge.material, - edgeMaterialPreset: nextEdge.materialPreset, - wallMaterial: nextWall.material, - wallMaterialPreset: nextWall.materialPreset, - material: undefined, - materialPreset: undefined, +/** + * Every surface role written out: the painted one takes the new paint, the + * others keep what they show now — so a role that still followed another + * (see roof-surface-roles) stays put instead of following the new paint. + */ +function buildRoleMaterialPatch( + targetRole: RoofSurfaceMaterialRole, + next: { material: MaterialSchema | undefined; materialPreset: string | undefined }, + current: (role: RoofSurfaceMaterialRole) => { + material?: MaterialSchema + materialPreset?: string + }, +): Record { + const patch: Record = { material: undefined, materialPreset: undefined } + for (const role of ROOF_SURFACE_MATERIAL_ROLES) { + const surface = role === targetRole ? next : current(role) + patch[`${role}Material`] = surface.material + patch[`${role}MaterialPreset`] = surface.materialPreset } + return patch } /** - * Build a per-segment paint patch for one of the three surface roles. The + * Build a per-segment paint patch for one of the surface roles. The * segment ends up with role-specific fields set (and the legacy catch-all * `material` cleared) so subsequent reads pick the role override over any * parent-roof fallback. @@ -119,24 +127,9 @@ export function buildRoofSegmentSurfaceMaterialPatch( material: MaterialSchema | undefined, materialPreset: string | undefined, ): Partial { - const nextSurfaceMaterial = { material, materialPreset } - const nextTop = - targetRole === 'top' ? nextSurfaceMaterial : getEffectiveSegmentSurfaceMaterial(node, 'top') - const nextEdge = - targetRole === 'edge' ? nextSurfaceMaterial : getEffectiveSegmentSurfaceMaterial(node, 'edge') - const nextWall = - targetRole === 'wall' ? nextSurfaceMaterial : getEffectiveSegmentSurfaceMaterial(node, 'wall') - - return { - topMaterial: nextTop.material, - topMaterialPreset: nextTop.materialPreset, - edgeMaterial: nextEdge.material, - edgeMaterialPreset: nextEdge.materialPreset, - wallMaterial: nextWall.material, - wallMaterialPreset: nextWall.materialPreset, - material: undefined, - materialPreset: undefined, - } + return buildRoleMaterialPatch(targetRole, { material, materialPreset }, (role) => + getEffectiveSegmentSurfaceMaterial(node, role), + ) as Partial } /** @@ -244,6 +237,10 @@ export function getEffectiveChimneyMaterial( return { material: node.material, materialPreset: node.materialPreset } } +function isRoofSurfaceRole(role: string): role is RoofSurfaceMaterialRole { + return (ROOF_SURFACE_MATERIAL_ROLES as readonly string[]).includes(role) +} + export function resolveActivePaintMaterialFromSelection(params: { materials?: Record nodes: Record @@ -295,12 +292,7 @@ export function resolveActivePaintMaterialFromSelection(params: { } } - if ( - selectedNode.type === 'roof' && - (selectedMaterialTarget.role === 'top' || - selectedMaterialTarget.role === 'edge' || - selectedMaterialTarget.role === 'wall') - ) { + if (selectedNode.type === 'roof' && isRoofSurfaceRole(selectedMaterialTarget.role)) { let surface = getEffectiveRoofSurfaceMaterial(selectedNode, selectedMaterialTarget.role) if ( selectedMaterialTarget.role === 'top' && diff --git a/packages/editor/src/lib/print-roof-solids.ts b/packages/editor/src/lib/print-roof-solids.ts index 44672ca0aa..56a859d59a 100644 --- a/packages/editor/src/lib/print-roof-solids.ts +++ b/packages/editor/src/lib/print-roof-solids.ts @@ -7,8 +7,10 @@ import { getSegmentSlopeFrame, nodeRegistry, normalizeRoofSegmentTrim, + type RoofModuleInput, type RoofSegmentNode, type RoofShapeFaceVertex, + withRoofSegmentGableBack, } from '@pascal-app/core' import * as THREE from 'three' import { mergeVertices } from 'three/examples/jsm/utils/BufferGeometryUtils.js' @@ -409,24 +411,36 @@ function buildRoofModuleGeometry( : { status: 'blocked', message: 'A canonical print face could not be triangulated.' } } -function getVolumeFaces( - node: RoofSegmentNode, - options: { widthExtension: number; verticalOffset: number; isVoid: boolean }, -): RoofFace[] { +type PrintVolume = 'wall-outer' | 'wall-inner' | 'roof-inner' + +function getVolumeFaces(node: RoofSegmentNode, volume: PrintVolume): RoofFace[] { + return getRoofModuleFaces( + withRoofSegmentGableBack(node, (pitched) => getVolumeModule(pitched, volume)), + ) +} + +/** The deck overhang follows the pitch, so each volume is worked out per pitch. */ +function getVolumeModule(node: RoofSegmentNode, volume: PrintVolume): RoofModuleInput { + const { activeRh, tanTheta, cosTheta } = getSegmentSlopeFrame(node) + const widthExtension = + volume === 'wall-outer' + ? node.wallThickness / 2 + : volume === 'wall-inner' + ? -node.wallThickness / 2 + : node.wallThickness / 2 + node.overhang * cosTheta const conicalCoverage = getConicalRoofCoverage(node) - const { activeRh, tanTheta } = getSegmentSlopeFrame(node) - const width = Math.max(0.01, node.width + options.widthExtension * 2) - const depth = Math.max(0.01, node.depth + options.widthExtension * 2) - const autoDrop = options.widthExtension * tanTheta - const wallHeight = Math.max(0.01, node.wallHeight - autoDrop + options.verticalOffset) + const width = Math.max(0.01, node.width + widthExtension * 2) + const depth = Math.max(0.01, node.depth + widthExtension * 2) + const autoDrop = widthExtension * tanTheta + const wallHeight = Math.max(0.01, node.wallHeight - autoDrop) const roofHeight = activeRh > 0 ? activeRh + autoDrop * (node.roofType === 'shed' ? 2 : 1) : activeRh const shapeRatios = getRoofShapeRatios(node) const dutchInset = Math.min(node.width, node.depth) * node.dutchHipWidthRatio + - (options.isVoid ? node.deckThickness : 0) + (volume === 'roof-inner' ? node.deckThickness : 0) - return getRoofModuleFaces({ + return { type: node.roofType, w: width, d: depth, @@ -441,10 +455,18 @@ function getVolumeFaces( dutchTopRakeThickness: node.dutchTopRakeThickness, conicalStartAngle: conicalCoverage.startAngle, conicalSweepAngle: conicalCoverage.sweepAngle, - }) + } } function getShingleOuterFaces(node: RoofSegmentNode): RoofFace[] { + const faces = getRoofModuleFaces(withRoofSegmentGableBack(node, getShingleOuterModule)) + // A shed's outer prism is built centred and shifted by half the shingle projection. + if (node.roofType !== 'shed') return faces + const translateZ = (node.shingleThickness * getSegmentSlopeFrame(node).sinTheta) / 2 + return faces.map((face) => face.map((point) => ({ ...point, z: point.z + translateZ }))) +} + +function getShingleOuterModule(node: RoofSegmentNode): RoofModuleInput { const conicalCoverage = getConicalRoofCoverage(node) const { activeRh, tanTheta, cosTheta, sinTheta } = getSegmentSlopeFrame(node) const shapeRatios = getRoofShapeRatios(node) @@ -461,7 +483,6 @@ function getShingleOuterFaces(node: RoofSegmentNode): RoofFace[] { activeRh > 0 ? activeRh + deckDrop * (node.roofType === 'shed' ? 2 : 1) : activeRh let width = baseWidth let depth = baseDepth - let translateZ = 0 if (['hip', 'mansard', 'dutch', 'conical'].includes(node.roofType)) { width += shingleHorizontalThickness * 2 @@ -470,7 +491,6 @@ function getShingleOuterFaces(node: RoofSegmentNode): RoofFace[] { depth += shingleHorizontalThickness * 2 } else if (node.roofType === 'shed') { depth += shingleHorizontalThickness - translateZ = shingleHorizontalThickness / 2 } const wallHeight = baseWallHeight + shingleVerticalThickness @@ -490,7 +510,7 @@ function getShingleOuterFaces(node: RoofSegmentNode): RoofFace[] { dutchHipWidthRatio: node.dutchHipWidthRatio, }) - const faces = getRoofModuleFaces({ + return { type: node.roofType, w: width, d: depth, @@ -505,10 +525,7 @@ function getShingleOuterFaces(node: RoofSegmentNode): RoofFace[] { dutchTopRakeThickness: node.dutchTopRakeThickness, conicalStartAngle: conicalCoverage.startAngle, conicalSweepAngle: conicalCoverage.sweepAngle, - }) - - if (translateZ === 0) return faces - return faces.map((face) => face.map((point) => ({ ...point, z: point.z + translateZ }))) + } } function blockingDiagnostics( @@ -582,23 +599,9 @@ export function buildPrintableRoofSegmentSolids( const diagnostics = blockingDiagnostics(node, nodes) if (diagnostics.length > 0) return { status: 'blocked', object: null, diagnostics } - const { cosTheta } = getSegmentSlopeFrame(node) - const wallOuter = getVolumeFaces(node, { - widthExtension: node.wallThickness / 2, - verticalOffset: 0, - isVoid: false, - }) - const wallInner = getVolumeFaces(node, { - widthExtension: -node.wallThickness / 2, - verticalOffset: 0, - isVoid: false, - }) - const deckExtension = node.wallThickness / 2 + node.overhang * cosTheta - const roofInner = getVolumeFaces(node, { - widthExtension: deckExtension, - verticalOffset: 0, - isVoid: true, - }) + const wallOuter = getVolumeFaces(node, 'wall-outer') + const wallInner = getVolumeFaces(node, 'wall-inner') + const roofInner = getVolumeFaces(node, 'roof-inner') const roofOuter = getShingleOuterFaces(node) const geometryResult = buildRoofModuleGeometry(wallOuter, wallInner, roofOuter, roofInner) if (geometryResult.status === 'blocked') { diff --git a/packages/editor/src/store/use-floorplan-draft-preview.ts b/packages/editor/src/store/use-floorplan-draft-preview.ts index 941afea2d7..1e0f5fbec2 100644 --- a/packages/editor/src/store/use-floorplan-draft-preview.ts +++ b/packages/editor/src/store/use-floorplan-draft-preview.ts @@ -17,7 +17,7 @@ import { create } from 'zustand' /** Screen-space (SVG-local px) cursor point — drives the coordinate badge. */ type SvgPoint = { x: number; y: number } -export type FloorplanPolygonDraftType = 'ceiling' | 'slab' | 'zone' +export type FloorplanPolygonDraftType = 'ceiling' | 'roof' | 'slab' | 'zone' type FloorplanDraftPreviewState = { /** Snapped plan-XZ point under the cursor; drives the crosshair + the diff --git a/packages/nodes/src/chimney/preview.tsx b/packages/nodes/src/chimney/preview.tsx index e50296c051..7ecdaf1e79 100644 --- a/packages/nodes/src/chimney/preview.tsx +++ b/packages/nodes/src/chimney/preview.tsx @@ -54,6 +54,9 @@ const ChimneyPreview = ({ [ effectiveSegment.wallHeight, effectiveSegment.pitch, + effectiveSegment.backPitch, + effectiveSegment.ridgeOffset, + effectiveSegment.ridgeStep, effectiveSegment.roofType, effectiveSegment.width, effectiveSegment.depth, diff --git a/packages/nodes/src/column/renderer.tsx b/packages/nodes/src/column/renderer.tsx index 1cb719a0cf..f15afdbad0 100644 --- a/packages/nodes/src/column/renderer.tsx +++ b/packages/nodes/src/column/renderer.tsx @@ -10,6 +10,7 @@ import { type ColumnSlotId, collectDescendants, createSceneApi, + getFloorStackedPosition, useLiveNodeOverrides, useLiveTransforms, useRegistry, @@ -27,6 +28,7 @@ import { createSurfaceRoleMaterial, NodeRenderer, type RenderShading, + resolveColumnRoofHeight, resolveMaterialRef, resolveSlotDefaultMaterial, useNodeEvents, @@ -2246,10 +2248,19 @@ export const ColumnRenderer = ({ node: rawNode }: { node: ColumnNode }) => { // hearing the commit on release. Subscribes narrowly to this node's // override entry; unrelated writes don't re-render. const liveOverride = useLiveNodeOverrides((s) => s.overrides.get(rawNode.id)) - const node = useMemo( - () => (liveOverride ? ({ ...rawNode, ...liveOverride } as ColumnNode) : rawNode), - [rawNode, liveOverride], + // A post under a roof meets its underside (see `resolveColumnRoofHeight`). + const roofHeight = useScene((s) => + resolveColumnRoofHeight( + rawNode, + s.nodes, + // The floor-elevation system lifts the column onto its slab; measure from there. + getFloorStackedPosition({ node: rawNode, nodes: s.nodes, position: rawNode.position })[1], + ), ) + const node = useMemo(() => { + const merged = liveOverride ? ({ ...rawNode, ...liveOverride } as ColumnNode) : rawNode + return roofHeight != null && roofHeight > 0 ? { ...merged, height: roofHeight } : merged + }, [rawNode, liveOverride, roofHeight]) const scriptedColumn = Boolean(node.source) const modelData = useMemo(() => ({ scriptedColumn }), [scriptedColumn]) const handlers = useNodeEvents(node, 'column') diff --git a/packages/nodes/src/dormer/csg-geometry.ts b/packages/nodes/src/dormer/csg-geometry.ts index 6aaf731328..93023ad38e 100644 --- a/packages/nodes/src/dormer/csg-geometry.ts +++ b/packages/nodes/src/dormer/csg-geometry.ts @@ -272,6 +272,7 @@ export function generateDormerGeometry( [roofCsgDummyMats[1], 1], [roofCsgDummyMats[2], 2], [roofCsgDummyMats[3], 3], + [roofCsgDummyMats[4], 4], ]) for (const group of resultGeo.groups) { group.materialIndex = mapRoofGroupMaterialIndex( diff --git a/packages/nodes/src/gutter/renderer.tsx b/packages/nodes/src/gutter/renderer.tsx index 39a3c73496..561e52581a 100644 --- a/packages/nodes/src/gutter/renderer.tsx +++ b/packages/nodes/src/gutter/renderer.tsx @@ -189,6 +189,9 @@ const GutterRenderer = ({ node: storeNode }: { node: GutterNode }) => { effectiveSegment?.wallHeight, effectiveSegment?.overhang, effectiveSegment?.pitch, + effectiveSegment?.backPitch, + effectiveSegment?.ridgeOffset, + effectiveSegment?.ridgeStep, effectiveSegment?.roofType, mitreNodes, ]) diff --git a/packages/nodes/src/lean-to-extension/assembly.ts b/packages/nodes/src/lean-to-extension/assembly.ts index 2bbe16a9a8..13781057f5 100644 --- a/packages/nodes/src/lean-to-extension/assembly.ts +++ b/packages/nodes/src/lean-to-extension/assembly.ts @@ -79,6 +79,10 @@ export type LeanToRoofMaterialPatch = Pick< | 'topMaterialPreset' | 'edgeMaterial' | 'edgeMaterialPreset' + | 'soffitMaterial' + | 'soffitMaterialPreset' + | 'fasciaMaterial' + | 'fasciaMaterialPreset' | 'wallMaterial' | 'wallMaterialPreset' > @@ -916,6 +920,10 @@ export function leanToRoofMaterialPatch(hostRoof: RoofNodeType): LeanToRoofMater topMaterialPreset: hostRoof.topMaterialPreset, edgeMaterial: hostRoof.edgeMaterial, edgeMaterialPreset: hostRoof.edgeMaterialPreset, + soffitMaterial: hostRoof.soffitMaterial, + soffitMaterialPreset: hostRoof.soffitMaterialPreset, + fasciaMaterial: hostRoof.fasciaMaterial, + fasciaMaterialPreset: hostRoof.fasciaMaterialPreset, wallMaterial: hostRoof.wallMaterial, wallMaterialPreset: hostRoof.wallMaterialPreset, } diff --git a/packages/nodes/src/ridge-vent/renderer.tsx b/packages/nodes/src/ridge-vent/renderer.tsx index 2a5b40500f..89e27983c5 100644 --- a/packages/nodes/src/ridge-vent/renderer.tsx +++ b/packages/nodes/src/ridge-vent/renderer.tsx @@ -37,6 +37,9 @@ function ridgeVentSegmentGeometryKey(segment: RoofSegmentNode | undefined): stri segment.depth, segment.wallHeight, segment.pitch, + segment.backPitch, + segment.ridgeOffset, + segment.ridgeStep, segment.wallThickness, segment.deckThickness, segment.overhang, diff --git a/packages/nodes/src/roof-segment/canopy-snap.test.ts b/packages/nodes/src/roof-segment/canopy-snap.test.ts new file mode 100644 index 0000000000..bdc07149f8 --- /dev/null +++ b/packages/nodes/src/roof-segment/canopy-snap.test.ts @@ -0,0 +1,52 @@ +import { describe, expect, test } from 'bun:test' +import { type AnyNode, RoofSegmentNode, SlabNode } from '@pascal-app/core' +import { CANOPY_SNAP_REACH, getCanopySnapPoints, snapCanopyReach } from './canopy-snap' + +const segment = RoofSegmentNode.parse({ + type: 'roof-segment', + roofType: 'gable', + width: 10, + depth: 8, + wallHeight: 0, + pitch: 30, + footprint: [ + [-5, -4], + [5, -4], + [5, 4], + [-5, 4], + ], +}) + +// a terrace slab in front of the +z wall, reaching 2 m out +const terrace = SlabNode.parse({ + type: 'slab', + polygon: [ + [-3, 4], + [3, 4], + [3, 6], + [-3, 6], + ], +}) + +const nodes = { [segment.id]: segment, [terrace.id]: terrace } as unknown as Record + +describe('canopy snap', () => { + // edge 2 runs [5,4] → [-5,4] and faces +z; its reach is its z + const points = getCanopySnapPoints(segment, 2, nodes) + + test('a pulled edge near the terrace edge lands on it', () => { + expect(snapCanopyReach(segment, 2, 5.9, points)).toBeCloseTo(6, 9) + expect(snapCanopyReach(segment, 2, 6.15, points)).toBeCloseTo(6, 9) + }) + + test('beyond the snap reach the edge goes where it is pulled', () => { + expect(snapCanopyReach(segment, 2, 6 + CANOPY_SNAP_REACH + 0.05, points)).toBeCloseTo( + 6 + CANOPY_SNAP_REACH + 0.05, + 9, + ) + }) + + test('the walls are a target too, so the edge can come back flush with them', () => { + expect(snapCanopyReach(segment, 2, 4.1, points)).toBeCloseTo(4, 9) + }) +}) diff --git a/packages/nodes/src/roof-segment/canopy-snap.ts b/packages/nodes/src/roof-segment/canopy-snap.ts new file mode 100644 index 0000000000..82c98ce19e --- /dev/null +++ b/packages/nodes/src/roof-segment/canopy-snap.ts @@ -0,0 +1,130 @@ +import { + type AnyNode, + type AnyNodeId, + getRoofRingEdgeNormal, + getRoofSegmentCoverOutline, + getRoofSegmentWallOutline, + type RoofNode, + type RoofSegmentNode, + type WallNode, +} from '@pascal-app/core' +import { buildingOutlines } from '../roof/outline-snap' + +type PlanPoint = [number, number] + +/** Metres: a pulled edge this close to a neighbouring line lands on it. */ +export const CANOPY_SNAP_REACH = 0.2 + +// three.js rotation-y in plan (x, z), as the roof and its segments render +const rotate = ([x, z]: PlanPoint, angle: number): PlanPoint => [ + x * Math.cos(angle) + z * Math.sin(angle), + -x * Math.sin(angle) + z * Math.cos(angle), +] + +function parentRoof(segment: RoofSegmentNode, nodes: Readonly>) { + const parent = segment.parentId ? nodes[segment.parentId as AnyNodeId] : undefined + return parent?.type === 'roof' ? (parent as RoofNode) : null +} + +/** Segment-local plan point → the level's plan. */ +function segmentToPlan( + segment: RoofSegmentNode, + roof: RoofNode | null, + point: PlanPoint, +): PlanPoint { + const [sx, sz] = rotate(point, segment.rotation ?? 0) + const inRoof: PlanPoint = [sx + segment.position[0], sz + segment.position[2]] + if (!roof) return inRoof + const [rx, rz] = rotate(inRoof, roof.rotation ?? 0) + return [rx + roof.position[0], rz + roof.position[2]] +} + +/** The level's plan → segment-local. */ +function planToSegment( + segment: RoofSegmentNode, + roof: RoofNode | null, + point: PlanPoint, +): PlanPoint { + const inRoof = roof + ? rotate([point[0] - roof.position[0], point[1] - roof.position[2]], -(roof.rotation ?? 0)) + : point + return rotate( + [inRoof[0] - segment.position[0], inRoof[1] - segment.position[2]], + -(segment.rotation ?? 0), + ) +} + +/** + * Plan points a canopy edge may line up with, segment-local: the outer corners + * of the house walls, the corners of slabs (a terrace, a porch), posts (centre + * and faces), the + * corners of every other roof's covering, and this roof's own walls and + * covering — all but the corners of the edge being pulled. + */ +export function getCanopySnapPoints( + segment: RoofSegmentNode, + edge: number, + nodes: Readonly>, +): PlanPoint[] { + const roof = parentRoof(segment, nodes) + const plan: PlanPoint[] = [] + const all = Object.values(nodes) + const walls = all.filter((node): node is WallNode => node?.type === 'wall') + for (const ring of buildingOutlines(walls)) plan.push(...ring) + for (const node of all) { + if (node?.type === 'slab') { + const polygon = (node as { polygon?: [number, number][] }).polygon ?? [] + plan.push(...polygon.map(([x, z]): PlanPoint => [x, z])) + } else if (node?.type === 'column') { + // a post: its centre and the faces of its box (a beam sits on either) + const post = node as { + position?: [number, number, number] + width?: number + depth?: number + } + if (post.position) { + const [x, , z] = post.position + const hx = (post.width ?? 0) / 2 + const hz = (post.depth ?? post.width ?? 0) / 2 + plan.push([x, z], [x - hx, z - hz], [x + hx, z + hz]) + } + } else if (node?.type === 'roof-segment' && node.id !== segment.id) { + const other = node as RoofSegmentNode + const otherRoof = parentRoof(other, nodes) + for (const point of getRoofSegmentCoverOutline(other)) { + plan.push(segmentToPlan(other, otherRoof, point)) + } + } + } + const local = plan.map((point) => planToSegment(segment, roof, point)) + + const cover = getRoofSegmentCoverOutline(segment) + const moving = new Set([edge, (edge + 1) % cover.length]) + local.push(...getRoofSegmentWallOutline(segment)) + local.push(...cover.filter((_, index) => !moving.has(index))) + return local +} + +/** + * The outward reach of a pulled edge, stuck to the nearest neighbouring line + * across its normal within CANOPY_SNAP_REACH; unchanged when none is near. + */ +export function snapCanopyReach( + segment: RoofSegmentNode, + edge: number, + reach: number, + points: readonly PlanPoint[], +): number { + const [nx, nz] = getRoofRingEdgeNormal(getRoofSegmentCoverOutline(segment), edge) + let best = reach + let bestDistance = CANOPY_SNAP_REACH + for (const [x, z] of points) { + const target = nx * x + nz * z + const distance = Math.abs(target - reach) + if (distance < bestDistance) { + best = target + bestDistance = distance + } + } + return best +} diff --git a/packages/nodes/src/roof-segment/definition.ts b/packages/nodes/src/roof-segment/definition.ts index 3f045c3a6c..af0da2654c 100644 --- a/packages/nodes/src/roof-segment/definition.ts +++ b/packages/nodes/src/roof-segment/definition.ts @@ -1,17 +1,27 @@ import { getActiveRoofHeight, + getGableRidge, + getGableWallInsets, getPitchFromActiveRoofHeight, + getRoofRingEdgeNormal, + getRoofSegmentCoverOutline, + getRoofSegmentSurfaceY, type HandleDescriptor, type NodeDefinition, + pullRoofSegmentCoverEdge, RoofSegmentNode as RoofSegmentNodeSchema, type RoofSegmentNode as RoofSegmentNodeType, } from '@pascal-app/core' -import { buildRoofSegmentFloorplan } from './floorplan' +import { getCanopySnapPoints, snapCanopyReach } from './canopy-snap' +import { buildRoofSegmentFloorplan, canPullCanopy } from './floorplan' import { roofSegmentMoveTarget, + roofSegmentPullAffordance, roofSegmentResizeAffordance, + roofSegmentRidgeAffordance, roofSegmentRotateAffordance, } from './floorplan-affordances' +import { applyGableRidgeEdit, type GableSide, readGableRidgeLocks } from './gable-ridge-edit' import { matchRoofSegmentMeasurementFeature, roofSegmentMeasurementFeatures } from './measurement' import { roofSegmentParametrics } from './parametrics' import { RoofSegmentNode } from './schema' @@ -253,6 +263,156 @@ function roofSegmentPitchHandle(): HandleDescriptor { } } +// Gable ridge: an arrow on the ridge slides it across the depth, a tracker +// over it lifts and lowers it. Both go through the ridge group's edit, so the +// locks decide what gives way (the attic walls by default); a locked ridge +// shows neither. +function gableRidgeVisible(n: RoofSegmentNodeType): boolean { + return !n.managedByParent && getGableRidge(n) !== null && !readGableRidgeLocks(n.metadata).ridge +} + +function gableRidgePositionHandle(): HandleDescriptor { + return { + kind: 'linear-resize', + axis: 'z', + anchor: 'min', + min: (n) => -n.depth / 2 + 0.05, + max: (n) => n.depth / 2 - 0.05, + gridSnap: true, + currentValue: (n) => getGableRidge(n)?.ridgeZ ?? 0, + visible: gableRidgeVisible, + apply: (initial, ridgeZ) => + applyGableRidgeEdit( + initial, + { + kind: 'position', + side: 'front', + value: initial.depth / 2 - ridgeZ - getGableWallInsets(initial).front, + }, + readGableRidgeLocks(initial.metadata), + ) ?? {}, + placement: { + position: (n) => { + const ridge = getGableRidge(n) + return [ + n.width / 4, + (ridge ? Math.max(ridge.height, ridge.backHeight) : getPeakHeight(n)) + + HEIGHT_HANDLE_OFFSET, + ridge?.ridgeZ ?? 0, + ] + }, + }, + } +} + +// Each slope's ridge height has its own tracker, on that slope just off the +// ridge line: lifting one apart from the other steps the ridge. +const RIDGE_HEIGHT_HANDLE_INSET = 0.4 + +function gableRidgeHeightHandle(side: GableSide): HandleDescriptor { + const heightOf = (n: RoofSegmentNodeType) => { + const ridge = getGableRidge(n) + if (!ridge) return getPeakHeight(n) + return side === 'front' ? ridge.height : ridge.backHeight + } + return { + kind: 'linear-resize', + axis: 'y', + anchor: 'min', + gridSnap: true, + currentValue: heightOf, + visible: gableRidgeVisible, + apply: (initial, height) => + applyGableRidgeEdit( + initial, + { kind: 'height', side, value: height }, + readGableRidgeLocks(initial.metadata), + ) ?? {}, + placement: { + position: (n) => { + const ridgeZ = getGableRidge(n)?.ridgeZ ?? 0 + const inset = Math.min( + RIDGE_HEIGHT_HANDLE_INSET, + (side === 'front' ? n.depth / 2 - ridgeZ : n.depth / 2 + ridgeZ) / 2, + ) + return [0, heightOf(n) + HEIGHT_HANDLE_OFFSET, ridgeZ + (side === 'front' ? inset : -inset)] + }, + }, + } +} + +// The canopy snap points depend only on the scene; keep them per scene record +// (weakly, so a scene left behind is not held) so a drag gathers them once +// rather than on every pointer move. +const canopySnapCache = new WeakMap>>() +function canopySnapPointsFor( + node: RoofSegmentNodeType, + edge: number, + nodes: Parameters[2], +) { + let byEdge = canopySnapCache.get(nodes) + if (!byEdge) { + byEdge = new Map() + canopySnapCache.set(nodes, byEdge) + } + const key = `${node.id}:${edge}` + let points = byEdge.get(key) + if (!points) { + points = getCanopySnapPoints(node, edge, nodes) + byEdge.set(key, points) + } + return points +} + +// Canopy pull: an arrow on the fascia of every edge of what the roof covers +// that runs along a local axis drags that edge out past the walls (or back), +// keeping the slopes in their planes (see `pullRoofSegmentCoverEdge`). The +// value is the edge's outward reach, so dragging outward always grows it. +function canopyPullHandles(node: RoofSegmentNodeType): HandleDescriptor[] { + const cover = getRoofSegmentCoverOutline(node) + return cover.flatMap((_, edge) => { + const [nx, nz] = getRoofRingEdgeNormal(cover, edge) + const axis = Math.abs(nx) > 0.999 ? 'x' : Math.abs(nz) > 0.999 ? 'z' : null + if (!axis) return [] + const sign = (axis === 'x' ? nx : nz) > 0 ? 1 : -1 + const reach = (n: RoofSegmentNodeType) => { + const ring = getRoofSegmentCoverOutline(n) + const [x, z] = ring[edge] ?? [0, 0] + return sign * (axis === 'x' ? x : z) + } + const handle: HandleDescriptor = { + kind: 'linear-resize', + axis, + anchor: sign > 0 ? 'min' : 'max', + gridSnap: true, + currentValue: reach, + apply: (initial, value) => + pullRoofSegmentCoverEdge(initial, edge, value - reach(initial)) ?? {}, + // lines the edge up with a neighbouring line within reach, in every + // snapping mode; Alt pulls freely + connectionSnap: (n, value, sceneApi) => + snapCanopyReach(n, edge, value, canopySnapPointsFor(n, edge, sceneApi.nodes())), + placement: { + position: (n) => { + const ring = getRoofSegmentCoverOutline(n) + const a = ring[edge] ?? [0, 0] + const b = ring[(edge + 1) % ring.length] ?? a + const x = (a[0] + b[0]) / 2 + const z = (a[1] + b[1]) / 2 + const out = n.overhang + SIDE_HANDLE_OFFSET + return [ + x + (axis === 'x' ? sign * out : 0), + getRoofSegmentSurfaceY(n, x, z), + z + (axis === 'z' ? sign * out : 0), + ] + }, + rotationY: () => (sign > 0 ? 0 : Math.PI), + }, + } + return [handle] + }) +} + // Whole-segment rotation gizmo — curved two-headed arrow at the +X / +Z // corner of the footprint, guide ring traces the corner-diagonal radius // on hover / drag. Same pattern as the elevator / column rotate gizmo; @@ -293,6 +453,19 @@ const roofSegmentHandles: HandleDescriptor[] = [ roofSegmentRotateHandle(), ] +// A gable's peak is its ridge: the ridge group's handles replace the pitch arrow. +const gableRoofSegmentHandles: HandleDescriptor[] = [ + roofSegmentWidthHandle('right'), + roofSegmentWidthHandle('left'), + roofSegmentDepthHandle('front'), + roofSegmentDepthHandle('back'), + roofSegmentWallHeightHandle(), + gableRidgeHeightHandle('front'), + gableRidgeHeightHandle('back'), + gableRidgePositionHandle(), + roofSegmentRotateHandle(), +] + const conicalRoofSegmentHandles: HandleDescriptor[] = [ conicalRoofSegmentRadiusHandle(), roofSegmentWallHeightHandle(), @@ -303,7 +476,21 @@ function resolveRoofSegmentHandles( node: RoofSegmentNodeType, ): HandleDescriptor[] { if (node.managedByParent) return [] - return node.roofType === 'conical' ? conicalRoofSegmentHandles : roofSegmentHandles + if (node.roofType === 'conical') return conicalRoofSegmentHandles + if (node.roofType !== 'gable') return roofSegmentHandles + // drawn over an outline: the covering's edges pull out as canopies instead + // of the rectangle resizing + if (canPullCanopy(node)) { + return [ + ...canopyPullHandles(node), + roofSegmentWallHeightHandle(), + gableRidgeHeightHandle('front'), + gableRidgeHeightHandle('back'), + gableRidgePositionHandle(), + roofSegmentRotateHandle(), + ] + } + return gableRoofSegmentHandles } /** @@ -375,6 +562,8 @@ export const roofSegmentDefinition: NodeDefinition = { // arrow emitted by `buildRoofSegmentFloorplan`. floorplanAffordances: { 'roof-segment-resize': roofSegmentResizeAffordance, + 'roof-segment-pull': roofSegmentPullAffordance, + 'roof-segment-ridge': roofSegmentRidgeAffordance, 'roof-segment-rotate': roofSegmentRotateAffordance, }, diff --git a/packages/nodes/src/roof-segment/floorplan-affordances.ts b/packages/nodes/src/roof-segment/floorplan-affordances.ts index 8de6640b57..9c381d62aa 100644 --- a/packages/nodes/src/roof-segment/floorplan-affordances.ts +++ b/packages/nodes/src/roof-segment/floorplan-affordances.ts @@ -2,6 +2,11 @@ import { type AnyNodeId, type FloorplanAffordance, type FloorplanMoveTarget, + getGableRidge, + getGableWallInsets, + getRoofRingEdgeNormal, + getRoofSegmentCoverOutline, + pullRoofSegmentCoverEdge, type RoofNode, type RoofSegmentNode, snapScalar, @@ -11,6 +16,8 @@ import { import { getSegmentGridStep, isAngleSnapActive, isGridSnapActive } from '@pascal-app/editor' import { createFloorplanCursorResolver } from '../shared/floorplan-cursor' import { rotateAffordanceDelta } from '../shared/rotate-affordance' +import { getCanopySnapPoints, snapCanopyReach } from './canopy-snap' +import { applyGableRidgeEdit, readGableRidgeLocks } from './gable-ridge-edit' const MIN_ROOF_DIM = 1 @@ -163,6 +170,110 @@ export const roofSegmentResizeAffordance: FloorplanAffordance = }, } +/** + * Gable ridge drag (floor-plan). Sister to the 3D ridge-position arrow: the + * plan cursor, projected onto the segment's local Z, slides the ridge across + * the depth through the ridge group's edit, so the locks decide what gives + * way. A locked ridge does not move. + */ +export const roofSegmentRidgeAffordance: FloorplanAffordance = { + start({ node, nodes, initialPlanPoint }) { + const segmentId = node.id as AnyNodeId + const ridge = getGableRidge(node) + const locks = readGableRidgeLocks(node.metadata) + const { cx, cz, effRot } = resolveSegmentFrame(node, nodes) + const cosEff = Math.cos(effRot) + const sinEff = Math.sin(effRot) + const projectLocalZ = (px: number, pz: number) => -(px - cx) * sinEff + (pz - cz) * cosEff + const initialLocal = projectLocalZ(initialPlanPoint[0], initialPlanPoint[1]) + let lastPatch: Partial | null = null + + return { + affectedIds: [segmentId], + apply({ planPoint }) { + if (!ridge || locks.ridge) return + const delta = projectLocalZ(planPoint[0], planPoint[1]) - initialLocal + const step = isGridSnapActive() ? getSegmentGridStep() : 0 + const rawZ = ridge.ridgeZ + delta + const ridgeZ = step > 0 ? snapScalar(rawZ, step) : rawZ + lastPatch = applyGableRidgeEdit( + node, + { + kind: 'position', + side: 'front', + value: node.depth / 2 - ridgeZ - getGableWallInsets(node).front, + }, + locks, + ) + if (!lastPatch) return + useLiveNodeOverrides.getState().set(segmentId, lastPatch) + useScene.getState().markDirty(segmentId) + }, + canCommit() { + return lastPatch !== null + }, + commit() { + useLiveNodeOverrides.getState().clear(segmentId) + if (lastPatch) useScene.getState().updateNode(segmentId, lastPatch) + }, + } + }, +} + +/** + * Canopy pull (floor-plan): drag an edge of what the roof covers out past the + * walls (or back to them). The plan cursor, projected onto the edge's outward + * normal, is how far the edge slides; `pullRoofSegmentCoverEdge` keeps the + * slopes in their planes and the roof's walls on the house. + */ +export const roofSegmentPullAffordance: FloorplanAffordance = { + start({ node, payload, nodes, initialPlanPoint }) { + const segmentId = node.id as AnyNodeId + const edge = (payload as { edge: number }).edge + const cover = getRoofSegmentCoverOutline(node) + const [nx, nz] = getRoofRingEdgeNormal(cover, edge) + const { effRot } = resolveSegmentFrame(node, nodes) + const cosEff = Math.cos(effRot) + const sinEff = Math.sin(effRot) + // the edge's outward normal in plan (local x → (cos, sin), local z → (−sin, cos)) + const planNx = nx * cosEff - nz * sinEff + const planNz = nx * sinEff + nz * cosEff + const along = (px: number, pz: number) => px * planNx + pz * planNz + const initialAlong = along(initialPlanPoint[0], initialPlanPoint[1]) + const [ex, ez] = cover[edge]! + const initialReach = nx * ex + nz * ez + // neighbouring lines to line the edge up with, gathered once per drag + const snapPoints = getCanopySnapPoints(node, edge, nodes) + let lastPatch: Partial | null = null + + return { + affectedIds: [segmentId], + apply({ planPoint, modifiers }) { + const raw = along(planPoint[0], planPoint[1]) - initialAlong + const step = isGridSnapActive() ? getSegmentGridStep() : 0 + let distance = step > 0 ? snapScalar(raw, step) : raw + // a neighbouring line within reach wins over the grid in every snapping + // mode (as the 3D arrow's connection snap); Alt pulls freely + if (!modifiers.altKey) { + const reach = snapCanopyReach(node, edge, initialReach + raw, snapPoints) + if (reach !== initialReach + raw) distance = reach - initialReach + } + lastPatch = pullRoofSegmentCoverEdge(node, edge, distance) + if (!lastPatch) return + useLiveNodeOverrides.getState().set(segmentId, lastPatch) + useScene.getState().markDirty(segmentId) + }, + canCommit() { + return lastPatch !== null + }, + commit() { + useLiveNodeOverrides.getState().clear(segmentId) + if (lastPatch) useScene.getState().updateNode(segmentId, lastPatch) + }, + } + }, +} + /** * Roof-segment rotation drag (floor-plan). Sister to the 3D `arc-resize` * handle. Same `- delta` convention as the 3D handle: the floor-plan diff --git a/packages/nodes/src/roof-segment/floorplan.ts b/packages/nodes/src/roof-segment/floorplan.ts index 64c3866c65..cbf7577a4a 100644 --- a/packages/nodes/src/roof-segment/floorplan.ts +++ b/packages/nodes/src/roof-segment/floorplan.ts @@ -4,9 +4,25 @@ import { type GeometryContext, getConicalRoofCoverage, getDutchRoofMetrics, + getGableRidge, + getRoofRingEdgeNormal, + getRoofSegmentCoverOutline, + getSegmentSlopeFrame, type RoofNode, type RoofSegmentNode, } from '@pascal-app/core' +import { readGableRidgeLocks } from './gable-ridge-edit' + +/** A sloped gable drawn over an outline can be pulled out past its walls as a canopy. */ +export function canPullCanopy(node: RoofSegmentNode): boolean { + return ( + node.roofType === 'gable' && + node.pitch > 0 && + Array.isArray(node.footprint) && + node.footprint.length >= 3 && + !node.managedByParent + ) +} /** * Stage C floor-plan builder for roof segment. Renders the segment as a @@ -174,6 +190,26 @@ export function buildRoofSegmentFloorplan( affordance: 'roof-segment-resize', payload: { mode: 'radial' }, }) + } else if (canPullCanopy(node)) { + // A roof drawn over an outline: an arrow on every edge of what it covers + // pulls that edge out as a canopy (or back to the walls). + const cover = getRoofSegmentCoverOutline(node) + cover.forEach((point, edge) => { + const next = cover[(edge + 1) % cover.length]! + const [nx, nz] = getRoofRingEdgeNormal(cover, edge) + const [ox, oz] = rotateLocal( + (point[0] + next[0]) / 2 + nx * sideArrowOffset, + (point[1] + next[1]) / 2 + nz * sideArrowOffset, + ) + const [tx, tz] = rotateLocal(nx, nz) + children.push({ + kind: 'move-arrow', + point: [cx + ox, cz + oz], + angle: Math.atan2(tz, tx), + affordance: 'roof-segment-pull', + payload: { edge }, + }) + }) } else { const sides: Array<{ local: [number, number] @@ -199,6 +235,21 @@ export function buildRoofSegmentFloorplan( } } + // Gable ridge: an arrow on the ridge line, a quarter way along it (clear + // of the centre move dot), slides the ridge across the depth. + const ridge = node.roofType === 'gable' ? getGableRidge(node) : null + if (ridge && !readGableRidgeLocks(node.metadata).ridge) { + const [ox, oz] = rotateLocal(halfW / 2, ridge.ridgeZ) + const [tx, tz] = rotateLocal(0, 1) + children.push({ + kind: 'move-arrow', + point: [cx + ox, cz + oz], + angle: Math.atan2(tz, tx), + affordance: 'roof-segment-ridge', + payload: {}, + }) + } + // Rotate-arrow at the +X / +Z corner. Local angle π/4 puts the // curved arrow's bow at the diagonal corner so it reads as a // rotation gizmo around the segment centre. @@ -293,13 +344,15 @@ export function getRoofSegmentPlanLinework(node: RoofSegmentNode): { case 'conical': case 'flat': break - case 'gable': - // Single ridge down the middle along the width axis. + case 'gable': { + // Single ridge along the width axis; off-centre when the slopes differ. + const { ridgeZ } = getSegmentSlopeFrame(node) ridges.push([ - [-hw, 0], - [hw, 0], + [-hw, ridgeZ], + [hw, ridgeZ], ]) break + } case 'shed': // 3D builder slopes from the high eave (lz = -hd) down to lz = +hd. slope = { tail: [0, -hd * 0.55], head: [0, hd * 0.55] } diff --git a/packages/nodes/src/roof-segment/gable-ridge-edit.test.ts b/packages/nodes/src/roof-segment/gable-ridge-edit.test.ts new file mode 100644 index 0000000000..be163764f2 --- /dev/null +++ b/packages/nodes/src/roof-segment/gable-ridge-edit.test.ts @@ -0,0 +1,170 @@ +import { describe, expect, test } from 'bun:test' +import { getGableRidge, RoofSegmentNode } from '@pascal-app/core' +import { applyGableRidgeEdit, type GableRidgeEdit, type GableRidgeLocks } from './gable-ridge-edit' + +const FREE: GableRidgeLocks = { pitches: false, ridge: false } + +function gable(extra: Partial = {}) { + return RoofSegmentNode.parse({ + type: 'roof-segment', + roofType: 'gable', + width: 10, + depth: 10, + wallHeight: 0.8, + pitch: 25, + backPitch: 15, + ridgeOffset: 4, + ...extra, + }) +} + +function edited(node: RoofSegmentNode, edit: GableRidgeEdit, locks = FREE) { + const update = applyGableRidgeEdit(node, edit, locks) + return update ? { ...node, ...update } : null +} + +describe('gable ridge group', () => { + test('an angle turns about the fixed ridge; only its own attic wall moves', () => { + const node = gable() + const before = getGableRidge(node)! + const front = getGableRidge(edited(node, { kind: 'pitch', side: 'front', value: 30 })!)! + expect(front.height).toBeCloseTo(before.height, 9) + expect(front.offset).toBeCloseTo(4, 9) + expect(front.frontPitch).toBe(30) + expect(front.frontWallHeight).toBeLessThan(before.frontWallHeight) + expect(front.backWallHeight).toBeCloseTo(before.backWallHeight, 9) + + const back = getGableRidge(edited(node, { kind: 'pitch', side: 'back', value: 20 })!)! + expect(back.height).toBeCloseTo(before.height, 9) + expect(back.frontWallHeight).toBeCloseTo(before.frontWallHeight, 9) + expect(back.backWallHeight).toBeLessThan(before.backWallHeight) + }) + + test('raising the ridge lifts the whole roof: angles hold, both attic walls grow', () => { + const node = gable() + const before = getGableRidge(node)! + const after = getGableRidge(edited(node, { kind: 'height', value: before.height + 0.5 })!)! + expect(after.frontPitch).toBe(25) + expect(after.backPitch).toBe(15) + expect(after.frontWallHeight).toBeCloseTo(before.frontWallHeight + 0.5, 9) + expect(after.backWallHeight).toBeCloseTo(before.backWallHeight + 0.5, 9) + }) + + test('moving the ridge splits the depth anew; one part grows as the other shrinks', () => { + const node = gable() + const after = getGableRidge(edited(node, { kind: 'position', side: 'back', value: 5 })!)! + expect(after.offset).toBeCloseTo(5, 9) + expect(after.height).toBeCloseTo(getGableRidge(node)!.height, 9) + }) + + test('an attic wall turns its slope while the ridge holds, or lifts the roof with locked angles', () => { + const node = gable() + const before = getGableRidge(node)! + const turned = getGableRidge(edited(node, { kind: 'wall', side: 'back', value: 1 })!)! + expect(turned.backWallHeight).toBeCloseTo(1, 9) + expect(turned.height).toBeCloseTo(before.height, 9) + + const lifted = getGableRidge( + edited(node, { kind: 'wall', side: 'back', value: 1 }, { pitches: true, ridge: false })!, + )! + expect(lifted.backWallHeight).toBeCloseTo(1, 9) + expect(lifted.backPitch).toBe(15) + expect(lifted.height - before.height).toBeCloseTo(1 - before.backWallHeight, 9) + }) + + test('locks refuse the edits they guard', () => { + const node = gable() + expect( + applyGableRidgeEdit( + node, + { kind: 'pitch', side: 'front', value: 30 }, + { pitches: true, ridge: false }, + ), + ).toBeNull() + expect( + applyGableRidgeEdit(node, { kind: 'height', value: 5 }, { pitches: false, ridge: true }), + ).toBeNull() + expect( + applyGableRidgeEdit( + node, + { kind: 'wall', side: 'front', value: 1 }, + { pitches: true, ridge: true }, + ), + ).toBeNull() + }) + + test('the first edit pins a derived ridge where it stood', () => { + const node = gable({ ridgeOffset: undefined, backPitch: undefined }) + const before = getGableRidge(node)! + expect(before.offset).toBeCloseTo(5, 9) + const update = applyGableRidgeEdit(node, { kind: 'pitch', side: 'back', value: 15 }, FREE)! + expect(update.ridgeOffset).toBeCloseTo(5, 9) + expect(getGableRidge({ ...node, ...update })!.height).toBeCloseTo(before.height, 9) + }) +}) + +describe('gable ridge heights per slope', () => { + test('raising one slope’s ridge steps it; the other ridge and both pitches hold', () => { + const node = gable() + const before = getGableRidge(node)! + const back = getGableRidge( + edited(node, { kind: 'height', side: 'back', value: before.height + 1.2 })!, + )! + expect(back.step).toBeCloseTo(1.2, 9) + expect(back.height).toBeCloseTo(before.height, 9) + expect(back.backHeight).toBeCloseTo(before.height + 1.2, 9) + expect(back.backPitch).toBe(15) + expect(back.backWallHeight).toBeCloseTo(before.backWallHeight + 1.2, 9) + expect(back.frontWallHeight).toBeCloseTo(before.frontWallHeight, 9) + + const front = getGableRidge( + edited(node, { kind: 'height', side: 'front', value: before.height - 0.7 })!, + )! + expect(front.height).toBeCloseTo(before.height - 0.7, 9) + expect(front.backHeight).toBeCloseTo(before.height, 9) + expect(front.step).toBeCloseTo(0.7, 9) + expect(front.frontPitch).toBe(25) + }) + + test('back to equal heights is one ridge again', () => { + const node = gable({ ridgeStep: 0.8 }) + const ridge = getGableRidge(node)! + const update = applyGableRidgeEdit( + node, + { kind: 'height', side: 'back', value: ridge.height + 0.001 }, + FREE, + )! + expect(update.ridgeStep).toBe(0) + }) + + test('a stepped ridge moves and lifts as a whole and keeps its step', () => { + const node = gable({ ridgeStep: 0.8 }) + const before = getGableRidge(node)! + const moved = getGableRidge(edited(node, { kind: 'position', side: 'front', value: 5 })!)! + expect(moved.height).toBeCloseTo(before.height, 9) + expect(moved.backHeight).toBeCloseTo(before.backHeight, 9) + const lifted = getGableRidge(edited(node, { kind: 'height', value: before.height + 0.5 })!)! + expect(lifted.backHeight).toBeCloseTo(before.backHeight + 0.5, 9) + }) + + test('an attic wall on the higher side turns its slope about its own ridge', () => { + const node = gable({ ridgeStep: 0.8 }) + const before = getGableRidge(node)! + const after = getGableRidge( + edited(node, { kind: 'wall', side: 'back', value: before.backWallHeight + 0.3 })!, + )! + expect(after.backHeight).toBeCloseTo(before.backHeight, 9) + expect(after.backWallHeight).toBeCloseTo(before.backWallHeight + 0.3, 6) + expect(after.backPitch).toBeLessThan(15) + + const locked = getGableRidge( + edited( + node, + { kind: 'wall', side: 'back', value: before.backWallHeight + 0.3 }, + { pitches: true, ridge: false }, + )!, + )! + expect(locked.backWallHeight).toBeCloseTo(before.backWallHeight + 0.3, 9) + expect(locked.step).toBeCloseTo(0.8, 9) + }) +}) diff --git a/packages/nodes/src/roof-segment/gable-ridge-edit.ts b/packages/nodes/src/roof-segment/gable-ridge-edit.ts new file mode 100644 index 0000000000..40ca9e95ce --- /dev/null +++ b/packages/nodes/src/roof-segment/gable-ridge-edit.ts @@ -0,0 +1,164 @@ +import { + type GableRidge, + getGableRidge, + getGableWallInsets, + type RoofSegmentNode, +} from '@pascal-app/core' + +/** + * Which values of a gable stay put while another one is edited. `pitches`: + * both slope angles; `ridge`: the ridge's place and height. With neither + * locked the ridge still stays put for an angle or an attic wall edit. + */ +export type GableRidgeLocks = { pitches: boolean; ridge: boolean } + +export type GableSide = 'front' | 'back' + +export type GableRidgeEdit = + /** Plan distance from that side's house wall to the ridge. */ + | { kind: 'position'; side: GableSide; value: number } + /** + * Ridge height above the segment base: of that side's slope only (the other + * keeps its own, a step wall closes the gap), or without a side the whole + * ridge, step and all. + */ + | { kind: 'height'; side?: GableSide; value: number } + | { kind: 'pitch'; side: GableSide; value: number } + /** Attic wall height on that side, at the house wall. */ + | { kind: 'wall'; side: GableSide; value: number } + +const MIN_PITCH = 1 +const MAX_PITCH = 85 +const MIN_RUN = 0.05 +/** A ridge step smaller than this is one ridge. */ +const MIN_STEP = 0.005 + +const tan = (deg: number) => Math.tan((deg * Math.PI) / 180) +const pitchFrom = (rise: number, run: number) => + Math.min(MAX_PITCH, Math.max(MIN_PITCH, (Math.atan2(rise, run) * 180) / Math.PI)) + +const stepOf = (step: number) => (Math.abs(step) < MIN_STEP ? 0 : step) + +export function readGableRidgeLocks(metadata: unknown): GableRidgeLocks { + const record = + typeof metadata === 'object' && metadata !== null && !Array.isArray(metadata) + ? (metadata as Record).gableLocks + : undefined + const locks = + typeof record === 'object' && record !== null ? (record as Record) : {} + return { pitches: locks.pitches === true, ridge: locks.ridge === true } +} + +type GableRidgeNode = Pick< + RoofSegmentNode, + | 'roofType' + | 'pitch' + | 'depth' + | 'width' + | 'wallHeight' + | 'wallThickness' + | 'backPitch' + | 'ridgeOffset' + | 'ridgeStep' + | 'footprint' + | 'coverFootprint' +> + +/** + * A gable's ridge group read against the house walls rather than the roof's + * own rectangle, which reaches past them where a canopy was pulled out: how + * far the ridge stands from each wall and how tall the attic wall is there. + */ +export type GableRidgeAtWalls = GableRidge & { + toFrontWall: number + toBackWall: number + frontAtticWall: number + backAtticWall: number +} + +export function readGableRidgeAtWalls(node: GableRidgeNode): GableRidgeAtWalls | null { + const ridge = getGableRidge(node) + if (!ridge) return null + const insets = getGableWallInsets(node) + return { + ...ridge, + toFrontWall: ridge.offset - insets.front, + toBackWall: node.depth - ridge.offset - insets.back, + frontAtticWall: ridge.frontWallHeight + insets.front * tan(ridge.frontPitch), + backAtticWall: ridge.backWallHeight + insets.back * tan(ridge.backPitch), + } +} + +/** + * The node fields one edit of a gable's ridge group writes, or null when the + * locks forbid it. Distances and attic walls are read at the house walls (see + * readGableRidgeAtWalls). The ridge's place and the back pitch are always + * written, so the roof stops deriving them and keeps them through later edits. + */ +export function applyGableRidgeEdit( + node: GableRidgeNode, + edit: GableRidgeEdit, + locks: GableRidgeLocks, +): Partial | null { + const ridge = readGableRidgeAtWalls(node) + if (!ridge) return null + const depth = node.depth + const frontRun = ridge.offset + const insets = getGableWallInsets(node) + const pinned = { ridgeOffset: ridge.offset, backPitch: ridge.backPitch } + + switch (edit.kind) { + case 'position': { + if (locks.ridge) return null + const offset = Math.min( + depth - MIN_RUN, + Math.max( + MIN_RUN, + edit.side === 'front' ? edit.value + insets.front : depth - edit.value - insets.back, + ), + ) + // the ridge keeps its height and the slopes their angles: the attic walls move + return { + ...pinned, + ridgeOffset: offset, + wallHeight: ridge.height - offset * tan(ridge.frontPitch), + } + } + case 'height': { + if (locks.ridge) return null + if (edit.side === 'back') { + // the +z ridge stays; only the step to the −z one changes + return { ...pinned, ridgeStep: stepOf(edit.value - ridge.height) } + } + const wallHeight = edit.value - frontRun * tan(ridge.frontPitch) + if (edit.side === 'front') { + // the −z ridge keeps its height + return { ...pinned, wallHeight, ridgeStep: stepOf(ridge.backHeight - edit.value) } + } + return { ...pinned, wallHeight } + } + case 'pitch': { + if (locks.pitches) return null + const pitch = Math.min(MAX_PITCH, Math.max(MIN_PITCH, edit.value)) + if (edit.side === 'back') return { ...pinned, backPitch: pitch } + return { ...pinned, pitch, wallHeight: ridge.height - frontRun * tan(pitch) } + } + case 'wall': { + if (locks.pitches && locks.ridge) return null + if (locks.pitches) { + // the angles hold, so the whole roof rides up or down with the wall + const height = + edit.side === 'front' + ? edit.value + ridge.toFrontWall * tan(ridge.frontPitch) + : edit.value + ridge.toBackWall * tan(ridge.backPitch) - ridge.step + return { ...pinned, wallHeight: height - frontRun * tan(ridge.frontPitch) } + } + // the ridge holds, so that side's slope turns + if (edit.side === 'back') { + return { ...pinned, backPitch: pitchFrom(ridge.backHeight - edit.value, ridge.toBackWall) } + } + const pitch = pitchFrom(ridge.height - edit.value, ridge.toFrontWall) + return { ...pinned, pitch, wallHeight: ridge.height - frontRun * tan(pitch) } + } + } +} diff --git a/packages/nodes/src/roof-segment/gable-ridge-handles.test.ts b/packages/nodes/src/roof-segment/gable-ridge-handles.test.ts new file mode 100644 index 0000000000..378ce2d9b5 --- /dev/null +++ b/packages/nodes/src/roof-segment/gable-ridge-handles.test.ts @@ -0,0 +1,59 @@ +import { describe, expect, test } from 'bun:test' +import { getGableRidge, type LinearResizeHandle, RoofSegmentNode } from '@pascal-app/core' +import { roofSegmentDefinition } from './definition' + +const gable = (extra: Partial = {}) => + RoofSegmentNode.parse({ + type: 'roof-segment', + roofType: 'gable', + width: 10, + depth: 10, + wallHeight: 0.8, + pitch: 25, + backPitch: 15, + ridgeOffset: 4, + ...extra, + }) + +type Handle = LinearResizeHandle +const sceneApi = {} as never + +function ridgeHandles(node: RoofSegmentNode) { + const handles = (roofSegmentDefinition.handles as (n: RoofSegmentNode) => Handle[])(node) + const ridge = getGableRidge(node)! + const height = handles.find( + (h) => h.kind === 'linear-resize' && h.axis === 'y' && h.currentValue(node) === ridge.height, + ) + const position = handles.find( + (h) => h.kind === 'linear-resize' && h.axis === 'z' && h.currentValue(node) === ridge.ridgeZ, + ) + return { height, position } +} + +describe('gable ridge handles', () => { + test('lifting the ridge raises the whole roof; the angles hold', () => { + const node = gable() + const { height } = ridgeHandles(node) + const before = getGableRidge(node)! + const after = getGableRidge({ ...node, ...height!.apply(node, before.height + 0.5, sceneApi) })! + expect(after.height).toBeCloseTo(before.height + 0.5, 9) + expect(after.frontPitch).toBe(25) + expect(after.backPitch).toBe(15) + }) + + test('sliding the ridge moves it across the depth at the same height', () => { + const node = gable() + const { position } = ridgeHandles(node) + const before = getGableRidge(node)! + const after = getGableRidge({ ...node, ...position!.apply(node, 0, sceneApi) })! + expect(after.ridgeZ).toBeCloseTo(0, 9) + expect(after.height).toBeCloseTo(before.height, 9) + }) + + test('a locked ridge hides both handles', () => { + const node = gable({ metadata: { gableLocks: { ridge: true } } }) + const { height, position } = ridgeHandles(node) + expect(height!.visible!(node, sceneApi)).toBe(false) + expect(position!.visible!(node, sceneApi)).toBe(false) + }) +}) diff --git a/packages/nodes/src/roof-segment/gable-ridge-section.tsx b/packages/nodes/src/roof-segment/gable-ridge-section.tsx new file mode 100644 index 0000000000..fc6b1be5a7 --- /dev/null +++ b/packages/nodes/src/roof-segment/gable-ridge-section.tsx @@ -0,0 +1,217 @@ +'use client' + +import type { RoofSegmentNode } from '@pascal-app/core' +import { ActionButton, PanelSection, SliderControl, ToggleControl } from '@pascal-app/editor' +import { Lock } from 'lucide-react' +import { + applyGableRidgeEdit, + type GableRidgeEdit, + type GableRidgeLocks, + readGableRidgeAtWalls, + readGableRidgeLocks, +} from './gable-ridge-edit' + +const COMPASS_POINTS = [ + 'North', + 'North-east', + 'East', + 'South-east', + 'South', + 'South-west', + 'West', + 'North-west', +] as const + +/** + * The side of the plan a slope falling toward local +z faces, for a segment + * turned by `rotation` (roof + segment). North is the top of the plan (−z). + */ +export function slopeFacing(rotation: number): string { + const bearing = Math.atan2(Math.sin(rotation), -Math.cos(rotation)) + const index = Math.round(bearing / (Math.PI / 4)) + return COMPASS_POINTS[((index % 8) + 8) % 8]! +} + +const PITCH_PRESETS: { label: string; deg: number }[] = [ + { label: '3/12', deg: 14.04 }, + { label: '6/12', deg: 26.57 }, + { label: '9/12', deg: 36.87 }, + { label: '12/12', deg: 45 }, +] + +function LockedRow({ label, value, unit }: { label: string; value: string; unit: string }) { + return ( +
+ + {label} +
+ {value} + {unit} +
+ ) +} + +/** + * A gable's ridge group: where the ridge splits the depth, how high each + * slope's ridge stands (apart, a step wall of the roof closes the gap), + * each slope's angle and the attic wall it leaves on each side. The values are + * tied together; the locks pick which of them hold while another one moves. + */ +export function GableRidgeSection({ + node, + rotation, + onUpdate, +}: { + node: RoofSegmentNode + /** Roof + segment rotation, to name each slope by the side it faces. */ + rotation: number + onUpdate: (updates: Partial) => void +}) { + const ridge = readGableRidgeAtWalls(node) + const locks = readGableRidgeLocks(node.metadata) + const front = slopeFacing(rotation) + const back = slopeFacing(rotation + Math.PI) + + const setLocks = (next: GableRidgeLocks) => { + const metadata = + typeof node.metadata === 'object' && node.metadata !== null ? node.metadata : {} + onUpdate({ metadata: { ...metadata, gableLocks: next } }) + } + const apply = (edit: GableRidgeEdit, from: RoofSegmentNode = node) => { + const update = applyGableRidgeEdit(from, edit, locks) + if (update) onUpdate(update) + return update ? { ...from, ...update } : from + } + + if (!ridge) { + return ( + + onUpdate({ pitch: v })} + precision={0} + step={1} + unit="°" + value={Math.round(node.pitch)} + /> + + ) + } + + const ridgeRow = (label: string, value: number, edit: (v: number) => GableRidgeEdit) => + locks.ridge ? ( + + ) : ( + apply(edit(v))} + precision={2} + step={0.05} + unit="m" + value={value} + /> + ) + const pitchRow = (label: string, value: number, side: 'front' | 'back') => + locks.pitches ? ( + + ) : ( + apply({ kind: 'pitch', side, value: v })} + precision={0} + step={1} + unit="°" + value={Math.round(value)} + /> + ) + const wallRow = (label: string, value: number, side: 'front' | 'back') => + locks.pitches && locks.ridge ? ( + + ) : ( + apply({ kind: 'wall', side, value: v })} + precision={2} + step={0.05} + unit="m" + value={value} + /> + ) + + return ( + <> + + {ridgeRow(`To ${front} wall`, ridge.toFrontWall, (v) => ({ + kind: 'position', + side: 'front', + value: v, + }))} + {ridgeRow(`To ${back} wall`, ridge.toBackWall, (v) => ({ + kind: 'position', + side: 'back', + value: v, + }))} + {ridgeRow(`${front} height`, ridge.height, (v) => ({ + kind: 'height', + side: 'front', + value: v, + }))} + {ridgeRow(`${back} height`, ridge.backHeight, (v) => ({ + kind: 'height', + side: 'back', + value: v, + }))} + setLocks({ ...locks, ridge: checked })} + /> + + + {pitchRow(front, ridge.frontPitch, 'front')} + {pitchRow(back, ridge.backPitch, 'back')} + {!locks.pitches && ( +
+ {PITCH_PRESETS.map((preset) => ( + { + const next = apply({ kind: 'pitch', side: 'front', value: preset.deg }) + apply({ kind: 'pitch', side: 'back', value: preset.deg }, next) + }} + /> + ))} + { + const next = apply({ kind: 'pitch', side: 'front', value: ridge.backPitch }) + apply({ kind: 'pitch', side: 'back', value: ridge.frontPitch }, next) + }} + /> +
+ )} + setLocks({ ...locks, pitches: checked })} + /> +
+ + {wallRow(`${front} wall`, ridge.frontAtticWall, 'front')} + {wallRow(`${back} wall`, ridge.backAtticWall, 'back')} + + + ) +} diff --git a/packages/nodes/src/roof-segment/panel.tsx b/packages/nodes/src/roof-segment/panel.tsx index a6f9d67722..0b96371353 100644 --- a/packages/nodes/src/roof-segment/panel.tsx +++ b/packages/nodes/src/roof-segment/panel.tsx @@ -30,6 +30,8 @@ import { import { useViewer } from '@pascal-app/viewer' import { Check, Copy, Move, Pencil, RotateCcw, Trash2 } from 'lucide-react' import { useCallback } from 'react' +import { canPullCanopy } from './floorplan' +import { GableRidgeSection } from './gable-ridge-section' const ROOF_TYPE_OPTIONS: { label: string; value: RoofType }[] = [ { label: 'Hip', value: 'hip' }, @@ -106,6 +108,10 @@ export default function RoofSegmentPanel() { const node = useScene((s) => selectedId ? (s.nodes[selectedId as AnyNode['id']] as RoofSegmentNode | undefined) : undefined, ) + const parentRoofRotation = useScene((s) => { + const parent = node?.parentId ? s.nodes[node.parentId as AnyNode['id']] : undefined + return parent?.type === 'roof' ? parent.rotation : 0 + }) const autoRidgeVentEnabled = useScene((s) => { const current = selectedId ? (s.nodes[selectedId as AnyNode['id']] as RoofSegmentNode | undefined) @@ -367,43 +373,47 @@ export default function RoofSegmentPanel() { )} - - {node.roofType === 'conical' ? ( - handleUpdate({ width: v, depth: v })} - precision={2} - step={0.5} - unit="m" - value={node.width} - /> - ) : ( - <> + {/* drawn over an outline the outline sets the size: its edges pull out as + canopies, a rectangle of its own would only cut it */} + {!canPullCanopy(node) && ( + + {node.roofType === 'conical' ? ( handleUpdate({ width: v })} + onChange={(v) => handleUpdate({ width: v, depth: v })} precision={2} step={0.5} unit="m" value={node.width} /> - handleUpdate({ depth: v })} - precision={2} - step={0.5} - unit="m" - value={node.depth} - /> - - )} - + ) : ( + <> + handleUpdate({ width: v })} + precision={2} + step={0.5} + unit="m" + value={node.width} + /> + handleUpdate({ depth: v })} + precision={2} + step={0.5} + unit="m" + value={node.depth} + /> + + )} + + )} {node.roofType === 'conical' && ( @@ -446,40 +456,50 @@ export default function RoofSegmentPanel() { )} - - handleUpdate({ wallHeight: v })} - precision={2} - step={0.1} - unit="m" - value={node.wallHeight} + {node.roofType === 'gable' ? ( + - + ) : ( + <> + + handleUpdate({ wallHeight: v })} + precision={2} + step={0.1} + unit="m" + value={node.wallHeight} + /> + - - handleUpdate({ pitch: v })} - precision={0} - step={1} - unit="°" - value={Math.round(node.pitch)} - /> -
- {PITCH_PRESETS.map((preset) => ( - handleUpdate({ pitch: preset.deg })} + + handleUpdate({ pitch: v })} + precision={0} + step={1} + unit="°" + value={Math.round(node.pitch)} /> - ))} -
-
+
+ {PITCH_PRESETS.map((preset) => ( + handleUpdate({ pitch: preset.deg })} + /> + ))} +
+ + + )} {node.roofType === 'gambrel' && ( @@ -631,6 +651,16 @@ export default function RoofSegmentPanel() { unit="m" value={node.shingleThickness} /> + handleUpdate({ squareEaves: checked })} + /> + handleUpdate({ cutAtWallTop: checked })} + /> diff --git a/packages/nodes/src/roof-segment/parametrics.ts b/packages/nodes/src/roof-segment/parametrics.ts index 56d2da33e1..fdb5e51c7f 100644 --- a/packages/nodes/src/roof-segment/parametrics.ts +++ b/packages/nodes/src/roof-segment/parametrics.ts @@ -30,6 +30,26 @@ export const roofSegmentParametrics: ParametricDescriptor = { step: 0.1, }, { key: 'pitch', kind: 'number', label: 'Pitch', unit: '°', min: 0, max: 85, step: 1 }, + { + key: 'backPitch', + kind: 'number', + label: 'Back pitch', + unit: '°', + min: 1, + max: 85, + step: 1, + visibleIf: (node) => node.roofType === 'gable', + }, + { + key: 'ridgeOffset', + kind: 'number', + label: 'Ridge offset', + unit: 'm', + min: 0.05, + max: 1000, + step: 0.05, + visibleIf: (node) => node.roofType === 'gable', + }, { key: 'conicalFullCircle', kind: 'boolean', diff --git a/packages/nodes/src/roof-segment/renderer.tsx b/packages/nodes/src/roof-segment/renderer.tsx index 00c1930d63..7f8d245fb5 100644 --- a/packages/nodes/src/roof-segment/renderer.tsx +++ b/packages/nodes/src/roof-segment/renderer.tsx @@ -11,9 +11,11 @@ import { useScene, } from '@pascal-app/core' import { + buildRoofSlotMaterials, createMaterial, getRoofMaterialArray, levelWallCladdingRef, + ROOF_SLOT_ROLES, resolveMaterialRef, useNodeEvents, useViewer, @@ -45,8 +47,8 @@ export const RoofSegmentRenderer = ({ node }: { node: RoofSegmentNode }) => { const parentNode = node.parentId ? (nodes[node.parentId as AnyNodeId] as RoofNode | undefined) : undefined - // 4 groups map 1:1 to the roof's 4-material array (see getRoofMaterialArray). - const placeholderGeometry = useMemo(() => createPlaceholderGeometry(4), []) + // groups map 1:1 to the roof's per-slot material array (see getRoofMaterialArray). + const placeholderGeometry = useMemo(() => createPlaceholderGeometry(ROOF_SLOT_ROLES.length), []) // Segment material precedence, per-role: // 1. Segment's role-specific override (topMaterial, edgeMaterial, wallMaterial). @@ -55,11 +57,7 @@ export const RoofSegmentRenderer = ({ node }: { node: RoofSegmentNode }) => { // 4. Parent roof's catch-all material. // 5. Default `roofMaterials` (handled at the `material =` line below). // - // The 4-slot layout matches getRoofMaterialArray: - // slot 0 → 'edge' (wall/trim & rake bands) - // slot 1 → 'wall' (deck top & shingle eave bands) - // slot 2 → 'wall' (interior) - // slot 3 → 'top' (shingle / roof surface) + // The slot layout matches getRoofMaterialArray (ROOF_SLOT_ROLES). // The gable band is clad like the walls below it (their assemblies). const wallCladdingRef = useScene((state) => parentNode ? levelWallCladdingRef(state.nodes, parentNode) : null, @@ -91,11 +89,8 @@ export const RoofSegmentRenderer = ({ node }: { node: RoofSegmentNode }) => { ) : null - const edge = resolveSlot('edge') - const wall = resolveSlot('wall') - const top = resolveSlot('top') - - if (!(edge || wall || top)) { + const resolved = new Map(ROOF_SLOT_ROLES.map((role) => [role, resolveSlot(role)] as const)) + if (![...resolved.values()].some(Boolean)) { return themedArray } @@ -103,8 +98,10 @@ export const RoofSegmentRenderer = ({ node }: { node: RoofSegmentNode }) => { // an untextured slot still picks up the scene-theme role colour, not blank white. // Per-role only, then the themed parent slot — no cross-role fallback, so // painting one segment surface never bleeds onto its other surfaces. - const slot = (i: number) => themedArray?.[i] ?? new THREE.MeshStandardMaterial() - return [edge ?? slot(0), wall ?? slot(1), wall ?? slot(2), top ?? slot(3)] as THREE.Material[] + return buildRoofSlotMaterials( + (role) => resolved.get(role) ?? null, + (i) => themedArray?.[i] ?? new THREE.MeshStandardMaterial(), + ) }, [ node.material, node.materialPreset, @@ -113,6 +110,10 @@ export const RoofSegmentRenderer = ({ node }: { node: RoofSegmentNode }) => { node.edgeMaterial, wallCladdingRef, node.edgeMaterialPreset, + node.soffitMaterial, + node.soffitMaterialPreset, + node.fasciaMaterial, + node.fasciaMaterialPreset, node.wallMaterial, node.wallMaterialPreset, parentNode, diff --git a/packages/nodes/src/roof/definition.ts b/packages/nodes/src/roof/definition.ts index a943897d9f..a47f6cd3ea 100644 --- a/packages/nodes/src/roof/definition.ts +++ b/packages/nodes/src/roof/definition.ts @@ -13,6 +13,7 @@ import { PANEL_MODEL_EXTENSION, } from '@pascal-app/editor' import { buildRoofFloorplan } from './floorplan' +import useRoofOutlineSnap from './outline-snap' import { roofPanelModel } from './panel-model' import { roofParametrics } from './parametrics' import useRoofFootprintSource from './roof-footprint-source' @@ -241,19 +242,62 @@ export const roofDefinition: NodeDefinition = { label: 'Room', description: 'Hover a room to preview its boundary, then click to place.', }, + { + value: 'outline', + label: 'Outline', + description: + 'Click points around the walls and close the outline at the first point (or Enter). The roof is built over the outline and cut to it.', + }, ], subscribe: (onChange) => useRoofFootprintSource.subscribe(onChange), value: () => useRoofFootprintSource.getState().source, set: (value) => - useRoofFootprintSource.getState().setSource(value === 'room' ? 'room' : 'draw'), + useRoofFootprintSource + .getState() + .setSource(value === 'room' || value === 'outline' ? value : 'draw'), // Conical roofs always build from a curved wall pick; the row would lie. visible: standardRoofToolHintVisibility, }, + { + id: 'outlineSnap', + label: 'Snap to', + choices: [ + { + value: 'building', + label: 'Building', + description: 'Points stick to the outer wall corners and faces of the building.', + }, + { + value: 'grid', + label: 'Grid', + description: 'Points follow the grid and the usual wall snapping.', + }, + ], + subscribe: (onChange) => useRoofOutlineSnap.subscribe(onChange), + value: () => useRoofOutlineSnap.getState().snap, + set: (value) => useRoofOutlineSnap.getState().setSnap(value === 'grid' ? 'grid' : 'building'), + visible: { + subscribe: (onChange) => { + const offSource = useRoofFootprintSource.subscribe(onChange) + const offKind = standardRoofToolHintVisibility.subscribe(onChange) + return () => { + offSource() + offKind() + } + }, + value: () => + standardRoofToolHintVisibility.value() && + useRoofFootprintSource.getState().source === 'outline', + }, + }, ], parametrics: roofParametrics, handles: resolveRoofHandles, floorplan: buildRoofFloorplan, + // The roof draws its segments' ridges, hips and slope arrows, so a segment + // edit (a moved ridge, a new pitch) must redraw the roof's plan too. + floorplanDependencies: (node) => node.children as AnyNodeId[], rendersChildren: false, renderer: { diff --git a/packages/nodes/src/roof/floorplan.ts b/packages/nodes/src/roof/floorplan.ts index 141f15b447..4d2eadc11e 100644 --- a/packages/nodes/src/roof/floorplan.ts +++ b/packages/nodes/src/roof/floorplan.ts @@ -3,6 +3,7 @@ import { type FloorplanPoint, type GeometryContext, getRoofSegmentVisibleTopBounds, + getSegmentSlopeFrame, type RoofNode, type RoofSegmentNode, roofPlanOverlapEntryOwns, @@ -73,7 +74,15 @@ function slopeArrows(node: RoofSegmentNode): { tail: [number, number]; head: [nu case 'shed': // Unchanged from the linework builder: the 3D shed falls −lz → +lz. return [{ tail: [0, -hd * 0.55], head: [0, hd * 0.55] }] - case 'gable': + case 'gable': { + const { ridgeZ } = getSegmentSlopeFrame(node) + const front = along(hd - ridgeZ) + const back = along(hd + ridgeZ) + return [ + { tail: [-hw * 0.35, ridgeZ + front.near], head: [-hw * 0.35, ridgeZ + front.far] }, + { tail: [hw * 0.35, ridgeZ - back.near], head: [hw * 0.35, ridgeZ - back.far] }, + ] + } case 'gambrel': { const z = along(hd) return [ @@ -158,6 +167,8 @@ function buildSegPlan(roof: RoofNode, seg: RoofSegmentNode, drafting: boolean): // faces, the shingle projection) to the footprint on each side. const edge = getRoofSegmentVisibleTopBounds(seg) const pitch = roofPitchLabel(seg.pitch) + // A gable's second arrow is its −z slope. + const backPitch = seg.roofType === 'gable' ? roofPitchLabel(seg.backPitch ?? seg.pitch) : pitch return { footprint, eave: [ @@ -169,10 +180,10 @@ function buildSegPlan(roof: RoofNode, seg: RoofSegmentNode, drafting: boolean): ridges, hips, breaks, - slopes: slopeArrows(seg).map((arrow) => ({ + slopes: slopeArrows(seg).map((arrow, index) => ({ tail: tp(arrow.tail[0], arrow.tail[1]), head: tp(arrow.head[0], arrow.head[1]), - pitch, + pitch: index === 1 ? backPitch : pitch, })), } } diff --git a/packages/nodes/src/roof/outline-snap.test.ts b/packages/nodes/src/roof/outline-snap.test.ts new file mode 100644 index 0000000000..e3a9618e1f --- /dev/null +++ b/packages/nodes/src/roof/outline-snap.test.ts @@ -0,0 +1,58 @@ +import { describe, expect, test } from 'bun:test' +import { WallNode } from '@pascal-app/core' +import { buildingOutlines, snapToBuildingOutline, squareFromFace } from './outline-snap' + +const wall = (start: [number, number], end: [number, number]) => + WallNode.parse({ type: 'wall', start, end, thickness: 0.2 }) + +/** A 10 × 6 box of walls (axes on its edges) with one partition across it. */ +const walls = [ + wall([0, 0], [10, 0]), + wall([10, 0], [10, 6]), + wall([10, 6], [0, 6]), + wall([0, 6], [0, 0]), + wall([5, 0], [5, 6]), +] + +describe('building outline snap', () => { + test('the outline is the outer faces of the walls, partitions excluded', () => { + const rings = buildingOutlines(walls) + expect(rings.length).toBe(1) + const xs = rings[0]!.map((point) => point[0]) + const zs = rings[0]!.map((point) => point[1]) + expect(Math.min(...xs)).toBeCloseTo(-0.1, 6) + expect(Math.max(...xs)).toBeCloseTo(10.1, 6) + expect(Math.min(...zs)).toBeCloseTo(-0.1, 6) + expect(Math.max(...zs)).toBeCloseTo(6.1, 6) + expect(rings[0]!.some(([x]) => Math.abs(x - 5) < 0.2)).toBe(false) + }) + + test('a point near a corner takes the corner, near a face lands on it, far away is left', () => { + const rings = buildingOutlines(walls) + const corner = snapToBuildingOutline([0.3, 0.2], rings)! + expect(corner.point[0]).toBeCloseTo(-0.1, 6) + expect(corner.point[1]).toBeCloseTo(-0.1, 6) + expect(corner.face).toBeNull() + const face = snapToBuildingOutline([4, 0.2], rings)! + expect(face.point[0]).toBeCloseTo(4, 6) + expect(face.point[1]).toBeCloseTo(-0.1, 6) + expect(face.face).not.toBeNull() + expect(snapToBuildingOutline([4, 3], rings)).toBeNull() + }) + + test('leaving a wall mid-face, the line goes square across to the opposite face', () => { + const rings = buildingOutlines(walls) + const start = snapToBuildingOutline([4, 0.2], rings)! + // The cursor drifts sideways by 0.6 m near the far wall: the point stays square. + const across = squareFromFace(start.point, start.face!, [4.6, 5.9], rings)! + expect(across.point[0]).toBeCloseTo(4, 6) + expect(across.point[1]).toBeCloseTo(6.1, 6) + expect(across.face).not.toBeNull() + // Half way across, the point still sits on the square line. + const middle = squareFromFace(start.point, start.face!, [4.5, 3], rings)! + expect(middle.point[0]).toBeCloseTo(4, 6) + expect(middle.face).toBeNull() + // Heading along the wall, the square lock lets go. + expect(squareFromFace(start.point, start.face!, [8, 0.5], rings)).toBeNull() + }) +}) diff --git a/packages/nodes/src/roof/outline-snap.ts b/packages/nodes/src/roof/outline-snap.ts new file mode 100644 index 0000000000..2314d34be8 --- /dev/null +++ b/packages/nodes/src/roof/outline-snap.ts @@ -0,0 +1,170 @@ +import { + calculateLevelMiters, + getWallPlanFootprint, + pointInPolygon2D, + unionPolygons, + type WallNode, +} from '@pascal-app/core' +import { create } from 'zustand' + +export type RoofOutlineSnapChoice = 'grid' | 'building' + +type RoofOutlineSnapState = { + snap: RoofOutlineSnapChoice + setSnap: (snap: RoofOutlineSnapChoice) => void +} + +/** + * What the points of a roof outline stick to: the grid, or the building's + * outer contour — its outer wall corners and faces. Ephemeral UI state owned by + * the kind, like `roof-footprint-source`. + */ +const useRoofOutlineSnap = create((set) => ({ + snap: 'building', + setSnap: (snap) => set({ snap }), +})) + +export default useRoofOutlineSnap + +type PlanPoint = [number, number] + +function signedArea(ring: readonly PlanPoint[]) { + let area = 0 + for (let i = 0; i < ring.length; i++) { + const [x0, z0] = ring[i]! + const [x1, z1] = ring[(i + 1) % ring.length]! + area += x0 * z1 - x1 * z0 + } + return area / 2 +} + +/** + * Outer contours of a set of walls: the union of their footprints without the + * holes — rooms are holes, so partitions never show up. + */ +export function buildingOutlines(walls: readonly WallNode[]): PlanPoint[][] { + if (walls.length === 0) return [] + const miters = calculateLevelMiters([...walls]) + const footprints = walls + .map((wall) => + getWallPlanFootprint(wall, miters).map((point) => [point.x, point.y] as PlanPoint), + ) + .filter((footprint) => footprint.length >= 3) + const rings = unionPolygons(footprints) + return rings.filter( + (ring, index) => + !rings.some( + (other, otherIndex) => + otherIndex !== index && + Math.abs(signedArea(other)) > Math.abs(signedArea(ring)) && + pointInPolygon2D(ring[0]!, other), + ), + ) +} + +// Metres: a point this close to an outer corner takes the corner, this close to +// an outer face lands on it. Wider than a grid step so a grid-snapped plan +// click still reaches the corner. +const CORNER_REACH = 0.75 +const FACE_REACH = 0.5 + +export type OutlineSnap = { + point: PlanPoint + /** The outer face the point lies on, unless it took a corner. */ + face: [PlanPoint, PlanPoint] | null +} + +/** The point stuck to the nearest outer corner, else the nearest outer face; null when neither is near. */ +export function snapToBuildingOutline( + point: PlanPoint, + outlines: readonly PlanPoint[][], +): OutlineSnap | null { + let corner: PlanPoint | null = null + let cornerDistance = CORNER_REACH + let face: OutlineSnap | null = null + let faceDistance = FACE_REACH + for (const ring of outlines) { + for (let i = 0; i < ring.length; i++) { + const a = ring[i]! + const b = ring[(i + 1) % ring.length]! + const toCorner = Math.hypot(point[0] - a[0], point[1] - a[1]) + if (toCorner < cornerDistance) { + cornerDistance = toCorner + corner = a + } + const dx = b[0] - a[0] + const dz = b[1] - a[1] + const lengthSq = dx * dx + dz * dz + if (lengthSq < 1e-12) continue + const t = Math.max( + 0, + Math.min(1, ((point[0] - a[0]) * dx + (point[1] - a[1]) * dz) / lengthSq), + ) + const onFace: PlanPoint = [a[0] + dx * t, a[1] + dz * t] + const toFace = Math.hypot(point[0] - onFace[0], point[1] - onFace[1]) + if (toFace < faceDistance) { + faceDistance = toFace + face = { point: onFace, face: [a, b] } + } + } + } + return corner ? { point: corner, face: null } : face +} + +// Within this angle of the wall's normal, a line leaving the middle of a wall +// is held square to it (radians). +const SQUARE_CAPTURE = (25 * Math.PI) / 180 + +/** + * A line that leaves an outer wall mid-face heads across the building square + * to that wall: while the cursor is within `SQUARE_CAPTURE` of the wall's + * normal, the point slides on that normal and lands on the first outer face it + * meets near the cursor. Null when the cursor heads elsewhere (along the wall). + */ +export function squareFromFace( + from: PlanPoint, + face: readonly [PlanPoint, PlanPoint], + cursor: PlanPoint, + outlines: readonly PlanPoint[][], +): OutlineSnap | null { + const dx = face[1][0] - face[0][0] + const dz = face[1][1] - face[0][1] + const length = Math.hypot(dx, dz) + if (length < 1e-9) return null + let nx = -dz / length + let nz = dx / length + const vx = cursor[0] - from[0] + const vz = cursor[1] - from[1] + const along = vx * nx + vz * nz + if (along < 0) { + nx = -nx + nz = -nz + } + const reach = Math.abs(along) + if (reach < 1e-6 || Math.acos(Math.min(1, reach / Math.hypot(vx, vz))) > SQUARE_CAPTURE) { + return null + } + const onRay: PlanPoint = [from[0] + nx * reach, from[1] + nz * reach] + // The first outer face the ray meets, if the cursor is near it. + let hit: OutlineSnap | null = null + let hitT = Number.POSITIVE_INFINITY + for (const ring of outlines) { + for (let i = 0; i < ring.length; i++) { + const a = ring[i]! + const b = ring[(i + 1) % ring.length]! + const ex = b[0] - a[0] + const ez = b[1] - a[1] + const denominator = nx * ez - nz * ex + if (Math.abs(denominator) < 1e-9) continue + const qx = a[0] - from[0] + const qz = a[1] - from[1] + const t = (qx * ez - qz * ex) / denominator + const u = (qx * nz - qz * nx) / denominator + if (t <= 1e-6 || u < 0 || u > 1 || t >= hitT) continue + hitT = t + hit = { point: [from[0] + nx * t, from[1] + nz * t], face: [a, b] } + } + } + if (hit && Math.hypot(hit.point[0] - onRay[0], hit.point[1] - onRay[1]) < CORNER_REACH) return hit + return { point: onRay, face: null } +} diff --git a/packages/nodes/src/roof/outline-tool.test.ts b/packages/nodes/src/roof/outline-tool.test.ts new file mode 100644 index 0000000000..410e3ce198 --- /dev/null +++ b/packages/nodes/src/roof/outline-tool.test.ts @@ -0,0 +1,54 @@ +import { describe, expect, test } from 'bun:test' +import { resolveOutlineRoofPlacement } from './outline-tool' + +const rotate = ([x, z]: [number, number], angle: number): [number, number] => [ + x * Math.cos(angle) + z * Math.sin(angle), + -x * Math.sin(angle) + z * Math.cos(angle), +] + +/** An L along +x: 12 m long, 8 m deep, the far corner cut away. */ +const L: [number, number][] = [ + [0, 0], + [12, 0], + [12, 4], + [6, 4], + [6, 8], + [0, 8], +] + +describe('outline roof placement', () => { + test('the rectangle bounds the outline along its longest side, ridge on the long span', () => { + const placement = resolveOutlineRoofPlacement(L, false) + expect(placement.rotation).toBeCloseTo(0, 9) + expect(placement.segmentRotation).toBe(0) + expect(placement.width).toBeCloseTo(12, 9) + expect(placement.depth).toBeCloseTo(8, 9) + expect(placement.center[0]).toBeCloseTo(6, 9) + expect(placement.center[1]).toBeCloseTo(4, 9) + // The footprint is the outline around the segment centre. + expect(placement.footprint[0]![0]).toBeCloseTo(-6, 9) + expect(placement.footprint[0]![1]).toBeCloseTo(-4, 9) + }) + + test('R turns the ridge across', () => { + const placement = resolveOutlineRoofPlacement(L, true) + expect(placement.segmentRotation).toBeCloseTo(Math.PI / 2, 9) + expect(placement.width).toBeCloseTo(8, 9) + expect(placement.depth).toBeCloseTo(12, 9) + }) + + test('a rotated outline gets a rotated roof that maps back onto it', () => { + const angle = 0.4 + const turned = L.map((point) => rotate(point, angle)) + const placement = resolveOutlineRoofPlacement(turned, false) + expect(placement.width).toBeCloseTo(12, 6) + expect(placement.depth).toBeCloseTo(8, 6) + // segment-local → roof-local → level reproduces the drawn points. + placement.footprint.forEach((point, index) => { + const roofLocal = rotate(point, placement.segmentRotation) + const level = rotate(roofLocal, placement.rotation) + expect(level[0] + placement.center[0]).toBeCloseTo(turned[index]![0], 6) + expect(level[1] + placement.center[1]).toBeCloseTo(turned[index]![1], 6) + }) + }) +}) diff --git a/packages/nodes/src/roof/outline-tool.tsx b/packages/nodes/src/roof/outline-tool.tsx new file mode 100644 index 0000000000..b1692702b2 --- /dev/null +++ b/packages/nodes/src/roof/outline-tool.tsx @@ -0,0 +1,377 @@ +'use client' + +import { + type AnyNode, + emitter, + findLevelAboveId, + type GridEvent, + getLevelElevations, + type LevelNode, + RoofNode, + RoofSegmentNode, + RoofType as RoofTypeSchema, + type SceneApi, +} from '@pascal-app/core' +import { + CursorSphere, + clearSurfacePlanSnapFeedback, + EDITOR_LAYER, + isGridSnapActive, + markToolCancelConsumed, + resolveSurfacePlanPointSnap, + snapWorldXZForActiveBuilding, + triggerSFX, + useEditor, + useFloorplanDraftPreview, + useRegistryToolContext, +} from '@pascal-app/editor' +import { useEffect, useMemo, useRef, useState } from 'react' +import { BufferGeometry, DoubleSide, type Group, type Line, Shape, Vector3 } from 'three' +import useRoofOutlineSnap, { + buildingOutlines, + type OutlineSnap, + snapToBuildingOutline, + squareFromFace, +} from './outline-snap' +import { collectRoofAlignmentAnchors, createRoofNodes, getRoofSnapWalls } from './tool' + +type PlanPoint = [number, number] + +const DEFAULT_PITCH_DEG = 40 +const Y_OFFSET = 0.02 +// A click this close to the first point closes the outline (metres). +const CLOSE_DISTANCE = 0.25 + +const rotatePlan = ([x, z]: PlanPoint, angle: number): PlanPoint => [ + x * Math.cos(angle) + z * Math.sin(angle), + -x * Math.sin(angle) + z * Math.cos(angle), +] + +/** + * Where a roof drawn over `outline` goes: its rectangle follows the longest + * side of the outline and bounds it; the ridge runs along the longer side of + * that rectangle unless `quarterTurn` swaps it. Pure, for the tool and tests. + */ +export function resolveOutlineRoofPlacement(outline: readonly PlanPoint[], quarterTurn: boolean) { + let longest = 0 + let direction = 0 + outline.forEach((point, index) => { + const next = outline[(index + 1) % outline.length]! + const length = Math.hypot(next[0] - point[0], next[1] - point[1]) + if (length > longest) { + longest = length + direction = Math.atan2(next[1] - point[1], next[0] - point[0]) + } + }) + // Roof frame: local x along the longest side (`rotatePlan(local, r)` → level). + const rotation = -direction + const local = outline.map((point) => rotatePlan(point, -rotation)) + const xs = local.map((point) => point[0]) + const zs = local.map((point) => point[1]) + const minX = Math.min(...xs) + const maxX = Math.max(...xs) + const minZ = Math.min(...zs) + const maxZ = Math.max(...zs) + const centerLocal: PlanPoint = [(minX + maxX) / 2, (minZ + maxZ) / 2] + const center = rotatePlan(centerLocal, rotation) + const spanX = maxX - minX + const spanZ = maxZ - minZ + // A gable's ridge runs along the segment's local x: put it on the longer span. + const turn = spanZ > spanX !== quarterTurn + const segmentRotation = turn ? Math.PI / 2 : 0 + return { + center, + rotation, + segmentRotation, + width: turn ? spanZ : spanX, + depth: turn ? spanX : spanZ, + footprint: local.map(([x, z]) => + rotatePlan([x - centerLocal[0], z - centerLocal[1]], -segmentRotation), + ), + } +} + +export function commitRoofOutline( + sceneApi: SceneApi, + levelId: LevelNode['id'], + outline: readonly PlanPoint[], + quarterTurn: boolean, +): AnyNode['id'] | null { + if (outline.length < 3) return null + const nodes = sceneApi.nodes() + const defaults = useEditor.getState().toolDefaults.roof ?? {} + const parsedRoofType = RoofTypeSchema.safeParse(defaults.roofType) + const roofType = parsedRoofType.success ? parsedRoofType.data : 'gable' + if (roofType === 'conical') return null + const placement = resolveOutlineRoofPlacement(outline, quarterTurn) + const segment = RoofSegmentNode.parse({ + pitch: DEFAULT_PITCH_DEG, + roofType: 'gable', + ...defaults, + // Seated on the walls, like a roof made from a room. + wallHeight: 0, + width: placement.width, + depth: placement.depth, + position: [0, 0, 0], + rotation: placement.segmentRotation, + footprint: placement.footprint, + }) + // A roof belongs to the storey above the walls it covers; the top floor keeps + // it on the walls' own level (same rule as a roof made from a room). + const parentLevelId = (findLevelAboveId(levelId, getLevelElevations(nodes)) ?? + levelId) as LevelNode['id'] + const roofCount = Object.values(nodes).filter((node) => node.type === 'roof').length + const roof = RoofNode.parse({ + ...defaults, + name: `Roof ${roofCount + 1}`, + position: [placement.center[0], 0, placement.center[1]], + rotation: placement.rotation, + // Follows the wall tops under it (`RoofElevationSystem`). + support: { kind: 'walls' }, + children: [segment.id], + }) + createRoofNodes(sceneApi, [ + { node: roof, parentId: parentLevelId }, + { node: segment, parentId: roof.id }, + ]) + triggerSFX('sfx:structure-build') + return roof.id +} + +/** + * Outline mode of the roof tool: each click adds a point (snapped to wall + * corners and faces like the other roof modes); clicking near the first point + * or pressing Enter closes the outline and builds the roof of the selected + * type over it. R turns the ridge 90°. + */ +export const RoofOutlineTool: React.FC = () => { + const { activeLevelId: currentLevelId, sceneApi, selectNode } = useRegistryToolContext() + const cursorRef = useRef(null) + const mainLineRef = useRef(null!) + const closingLineRef = useRef(null!) + const [points, setPoints] = useState([]) + // The outer face the last point sits on (null: a corner or a free point). + const lastFaceRef = useRef(null) + const [cursor, setCursor] = useState([0, 0]) + const [levelY, setLevelY] = useState(0) + const [quarterTurn, setQuarterTurn] = useState(false) + const roofDefaults = useEditor((state) => state.toolDefaults.roof) + const parsedRoofType = RoofTypeSchema.safeParse(roofDefaults?.roofType) + const roofType = parsedRoofType.success ? parsedRoofType.data : 'gable' + const outlineSnap = useRoofOutlineSnap((state) => state.snap) + + useEffect(() => { + useEditor.getState().setDraftVertexCount(points.length) + useFloorplanDraftPreview.getState().setPolygonDraft('roof', points) + }, [points]) + useEffect( + () => () => { + useEditor.getState().setDraftVertexCount(0) + const draftPreview = useFloorplanDraftPreview.getState() + if (draftPreview.polygonDraftType === 'roof') draftPreview.setPolygonDraft(null, []) + draftPreview.setCursorPoint(null) + clearSurfacePlanSnapFeedback() + }, + [], + ) + + useEffect(() => { + if (!currentLevelId) return + const alignmentCandidates = collectRoofAlignmentAnchors( + sceneApi.nodes(), + currentLevelId, + roofType, + ) + // The building's outer contour (this storey and the one below), partitions excluded. + const outlines = + outlineSnap === 'building' + ? buildingOutlines(getRoofSnapWalls(currentLevelId, sceneApi.nodes(), roofType)) + : [] + const resolveSnap = (event: GridEvent): OutlineSnap => { + const rawPoint: PlanPoint = [event.localPosition[0], event.localPosition[2]] + if (outlineSnap === 'building') { + const last = points[points.length - 1] + const square = + last && lastFaceRef.current + ? squareFromFace(last, lastFaceRef.current, rawPoint, outlines) + : null + return ( + square ?? snapToBuildingOutline(rawPoint, outlines) ?? { point: rawPoint, face: null } + ) + } + return { point: resolveGridPoint(event, rawPoint), face: null } + } + const resolvePoint = (event: GridEvent) => resolveSnap(event).point + const resolveGridPoint = (event: GridEvent, rawPoint: PlanPoint): PlanPoint => { + const gridFallback: PlanPoint = isGridSnapActive() + ? snapWorldXZForActiveBuilding( + event.position[0], + event.position[2], + useEditor.getState().gridSnapStep, + ).local + : rawPoint + return resolveSurfacePlanPointSnap({ + rawPoint, + fallbackPoint: gridFallback, + walls: getRoofSnapWalls(currentLevelId, sceneApi.nodes(), roofType), + candidates: alignmentCandidates, + movingId: '__roof-outline__', + highlightWalls: true, + }).point + } + + const finish = () => { + // a double-click lands its two clicks on the same point: one corner + const ring = points.filter((point, index) => { + const next = points[(index + 1) % points.length]! + return Math.hypot(next[0] - point[0], next[1] - point[1]) > 1e-6 + }) + if (ring.length < 3) return + const roofId = commitRoofOutline(sceneApi, currentLevelId, ring, quarterTurn) + if (roofId) selectNode(roofId) + setPoints([]) + lastFaceRef.current = null + } + + const onMove = (event: GridEvent) => { + const point = resolvePoint(event) + setCursor(point) + setLevelY(event.localPosition[1]) + useFloorplanDraftPreview.getState().setCursorPoint(point) + cursorRef.current?.position.set(point[0], event.localPosition[1], point[1]) + } + const onClick = (event: GridEvent) => { + const { point, face } = resolveSnap(event) + const first = points[0] + if ( + points.length >= 3 && + first && + Math.hypot(point[0] - first[0], point[1] - first[1]) < CLOSE_DISTANCE + ) { + finish() + return + } + triggerSFX('sfx:structure-build-start') + lastFaceRef.current = face + setPoints([...points, point]) + } + const onCancel = () => { + if (points.length > 0) markToolCancelConsumed() + setPoints([]) + lastFaceRef.current = null + } + const onKeyDown = (event: KeyboardEvent) => { + if (event.key === 'Enter') { + event.preventDefault() + finish() + } else if ((event.key === 'r' || event.key === 'R') && !event.metaKey && !event.ctrlKey) { + setQuarterTurn((value) => !value) + } + } + document.addEventListener('keydown', onKeyDown) + emitter.on('grid:move', onMove) + emitter.on('grid:click', onClick) + emitter.on('grid:double-click', finish) + emitter.on('tool:cancel', onCancel) + return () => { + document.removeEventListener('keydown', onKeyDown) + emitter.off('grid:move', onMove) + emitter.off('grid:click', onClick) + emitter.off('grid:double-click', finish) + emitter.off('tool:cancel', onCancel) + } + }, [currentLevelId, outlineSnap, points, quarterTurn, roofType, sceneApi, selectNode]) + + useEffect(() => { + if (!(mainLineRef.current && closingLineRef.current)) return + const y = levelY + Y_OFFSET + const line = [...points, cursor].map(([x, z]) => new Vector3(x, y, z)) + mainLineRef.current.visible = points.length > 0 + closingLineRef.current.visible = points.length >= 2 + if (points.length > 0) { + mainLineRef.current.geometry.dispose() + mainLineRef.current.geometry = new BufferGeometry().setFromPoints(line) + } + const first = points[0] + if (points.length >= 2 && first) { + closingLineRef.current.geometry.dispose() + closingLineRef.current.geometry = new BufferGeometry().setFromPoints([ + new Vector3(cursor[0], y, cursor[1]), + new Vector3(first[0], y, first[1]), + ]) + } + }, [points, cursor, levelY]) + + const previewShape = useMemo(() => { + if (points.length < 2) return null + const all = [...points, cursor] + const shape = new Shape() + shape.moveTo(all[0]![0], -all[0]![1]) + for (const [x, z] of all.slice(1)) shape.lineTo(x, -z) + shape.closePath() + return shape + }, [points, cursor]) + + return ( + + + {previewShape && ( + + + + + )} + {/* @ts-ignore */} + + + + + {/* @ts-ignore */} + + + + + {points.map(([x, z], index) => ( + + ))} + + ) +} diff --git a/packages/nodes/src/roof/renderer.tsx b/packages/nodes/src/roof/renderer.tsx index c9e3520169..ca9db50f73 100644 --- a/packages/nodes/src/roof/renderer.tsx +++ b/packages/nodes/src/roof/renderer.tsx @@ -13,6 +13,7 @@ import { getRoofMaterialArray, levelWallCladdingRef, NodeRenderer, + ROOF_SLOT_ROLES, useNodeEvents, useViewer, } from '@pascal-app/viewer' @@ -87,8 +88,8 @@ export const RoofRenderer = ({ node: rawNode }: { node: RoofNode }) => { }), ) - // 4 groups map 1:1 to the roof's 4-material array (see getRoofMaterialArray). - const placeholderGeometry = useMemo(() => createPlaceholderGeometry(4), []) + // groups map 1:1 to the roof's per-slot material array (see getRoofMaterialArray). + const placeholderGeometry = useMemo(() => createPlaceholderGeometry(ROOF_SLOT_ROLES.length), []) // The gable band is clad like the walls below it (their assemblies). const wallCladdingRef = useScene((state) => levelWallCladdingRef(state.nodes, node)) diff --git a/packages/nodes/src/roof/roof-footprint-source.ts b/packages/nodes/src/roof/roof-footprint-source.ts index 2d17d69550..000cb98e0c 100644 --- a/packages/nodes/src/roof/roof-footprint-source.ts +++ b/packages/nodes/src/roof/roof-footprint-source.ts @@ -1,6 +1,6 @@ import { create } from 'zustand' -export type RoofFootprintSourceChoice = 'draw' | 'room' +export type RoofFootprintSourceChoice = 'draw' | 'room' | 'outline' type RoofFootprintSourceState = { source: RoofFootprintSourceChoice @@ -8,8 +8,8 @@ type RoofFootprintSourceState = { } /** - * How the user wants the next roof footprint made — draw two corners, or pick - * a detected room ('walls' is conical-only and forced by + * How the user wants the next roof footprint made — draw two corners, pick + * a detected room, or place an outline point by point ('walls' is conical-only and forced by * `parseRoofFootprintSource`, so it never lives here). Ephemeral UI state * owned by the kind, like `roof-placement-mode`: deliberately OUTSIDE * `toolDefaults.roof`, which preset seeding nulls on every activation and the diff --git a/packages/nodes/src/roof/tool.tsx b/packages/nodes/src/roof/tool.tsx index b21780b2ca..219ed09642 100644 --- a/packages/nodes/src/roof/tool.tsx +++ b/packages/nodes/src/roof/tool.tsx @@ -54,6 +54,7 @@ import { } from 'three' import { createConicalRoofSectorAboveWall } from './conical-roof' import { resolveConicalRoofPlacement } from './conical-roof-placement' +import { RoofOutlineTool } from './outline-tool' import { isStandardRoofWallEligible, parseRoofFootprintSource, @@ -69,7 +70,7 @@ const DEFAULT_WALL_HEIGHT = 0.5 const DEFAULT_PITCH_DEG = 40 const GRID_OFFSET = 0.02 -function createRoofNodes( +export function createRoofNodes( sceneApi: SceneApi, ops: Parameters>[0], ): void { @@ -145,7 +146,7 @@ function getBelowLevelWalls( // Current-level + floor-below walls — the magnetic snap targets the roof draft // locks onto (corners, midpoints, crossings, wall bodies), matching the wall // tool. Same coordinate frame, so no transform is needed. -function getRoofSnapWalls( +export function getRoofSnapWalls( currentLevelId: string | null, nodes: Readonly>, roofType: RoofType, @@ -160,7 +161,7 @@ function getRoofSnapWalls( } // Current-level alignment anchors plus the floor-below wall corners. -function collectRoofAlignmentAnchors( +export function collectRoofAlignmentAnchors( nodes: Readonly>, currentLevelId: string | null, roofType: RoofType, @@ -588,7 +589,7 @@ function buildRoofGhostEdges( return geometry } -export const RoofTool: React.FC = () => { +const RoofRectTool: React.FC = () => { const { activeLevelId: currentLevelId, sceneApi, selectNode } = useRegistryToolContext() const cursorRef = useRef(null) const outlineRef = useRef(null!) @@ -1301,4 +1302,15 @@ export const RoofTool: React.FC = () => { ) } +/** + * The roof tool: two corners or a room ('draw' / 'room'), or an outline placed + * point by point ('outline'). + */ +export const RoofTool: React.FC = () => { + const source = useRoofFootprintSource((state) => state.source) + const roofType = RoofTypeSchema.safeParse(useEditor((state) => state.toolDefaults.roof)?.roofType) + const conical = roofType.success && roofType.data === 'conical' + return source === 'outline' && !conical ? : +} + export default RoofTool diff --git a/packages/nodes/src/shared/roof-surface.ts b/packages/nodes/src/shared/roof-surface.ts index 8b56cbf847..a06d721e3d 100644 --- a/packages/nodes/src/shared/roof-surface.ts +++ b/packages/nodes/src/shared/roof-surface.ts @@ -6,7 +6,9 @@ import { getRoofShapeRatios, getSegmentSlopeFrame, ROOF_SHAPE_DEFAULTS, + type RoofModuleInput, type RoofSegmentNode, + withRoofSegmentGableBack, } from '@pascal-app/core' import * as THREE from 'three' @@ -102,6 +104,9 @@ function roofSurfaceFaceCacheKey(segment: RoofSegmentNode): string { segment.overhang, segment.shingleThickness, segment.pitch, + segment.backPitch, + segment.ridgeOffset, + segment.ridgeStep, conicalCoverage.startAngle, conicalCoverage.sweepAngle, segment.gambrelLowerWidthRatio ?? ROOF_SHAPE_DEFAULTS.gambrelLowerWidthRatio, @@ -114,7 +119,7 @@ function roofSurfaceFaceCacheKey(segment: RoofSegmentNode): string { ].join('|') } -function buildRoofSurfaceFaces(segment: RoofSegmentNode): RoofSurfaceFace[] { +function getShingleTopModule(segment: RoofSegmentNode): RoofModuleInput { const conicalCoverage = getConicalRoofCoverage(segment) const { roofType, width, depth, wallHeight, wallThickness, deckThickness, overhang } = segment const { activeRh, tanTheta, cosTheta, sinTheta } = getSegmentSlopeFrame(segment) @@ -139,7 +144,6 @@ function buildRoofSurfaceFaces(segment: RoofSegmentNode): RoofSurfaceFace[] { let shinTopW = shinBotW let shinTopD = shinBotD - let transZ = 0 if ( roofType === 'hip' || @@ -153,7 +157,6 @@ function buildRoofSurfaceFaces(segment: RoofSegmentNode): RoofSurfaceFace[] { shinTopD += 2 * stSin } else if (roofType === 'shed') { shinTopD += stSin - transZ = stSin / 2 } const shinTopWh = shinBotWh + stCos @@ -188,7 +191,7 @@ function buildRoofSurfaceFaces(segment: RoofSegmentNode): RoofSurfaceFace[] { dutchGabletRake: segment.dutchGabletRake, }) - return getRoofModuleFaces({ + return { type: roofType, w: shinTopW, d: shinTopD, @@ -203,7 +206,16 @@ function buildRoofSurfaceFaces(segment: RoofSegmentNode): RoofSurfaceFace[] { dutchTopRakeThickness: segment.dutchTopRakeThickness, conicalStartAngle: conicalCoverage.startAngle, conicalSweepAngle: conicalCoverage.sweepAngle, - }) + } +} + +function buildRoofSurfaceFaces(segment: RoofSegmentNode): RoofSurfaceFace[] { + // A shed's outer prism is built centred and shifted by half the shingle projection. + const transZ = + segment.roofType === 'shed' + ? ((segment.shingleThickness ?? 0) * getSegmentSlopeFrame(segment).sinTheta) / 2 + : 0 + return getRoofModuleFaces(withRoofSegmentGableBack(segment, getShingleTopModule)) .filter((face) => faceNormalY(face) > SHINGLE_SURFACE_EPSILON) .map((face) => { const vertices = face.map((point) => ({ ...point, z: point.z + transZ })) @@ -438,7 +450,8 @@ export function getAnalyticalNormal( return buildSlopeNormal(0, lz >= 0 ? 1 : -1, upperTan, out) } } - return buildSlopeNormal(0, lz >= 0 ? 1 : -1, primaryTan, out) + if (lz >= slope.ridgeZ) return buildSlopeNormal(0, 1, primaryTan, out) + return buildSlopeNormal(0, -1, slope.backTanTheta, out) } // Single slope falling toward +Z (ridge at -Z, eave at +Z). diff --git a/packages/viewer/src/index.ts b/packages/viewer/src/index.ts index e8e264bd13..3adb6cbf53 100644 --- a/packages/viewer/src/index.ts +++ b/packages/viewer/src/index.ts @@ -274,7 +274,12 @@ export { getLevelPresentationY, snapLevelsToTruePositions, } from './systems/level/level-utils' -export { getRoofMaterialArray, levelWallCladdingRef } from './systems/roof/roof-materials' +export { + buildRoofSlotMaterials, + getRoofMaterialArray, + levelWallCladdingRef, + ROOF_SLOT_ROLES, +} from './systems/roof/roof-materials' // Generic roof-segment primitives. Kinds that compose CSG against // the roof shell (chimney's self-trim, dormer's virtual-segment cut) // read these through the public surface. No kind-specific helpers @@ -291,6 +296,7 @@ export { roofCsgDummyMats, type SurfaceFrame, } from './systems/roof/roof-system' +export { resolveColumnRoofHeight } from './systems/roof/roof-underside' export { ScanSystem } from './systems/scan/scan-system' // Pure slab geometry generator — composed into the registry-driven slab // definition's `def.geometry` in `@pascal-app/nodes`. diff --git a/packages/viewer/src/systems/roof/roof-abutment.test.ts b/packages/viewer/src/systems/roof/roof-abutment.test.ts new file mode 100644 index 0000000000..abed4496d1 --- /dev/null +++ b/packages/viewer/src/systems/roof/roof-abutment.test.ts @@ -0,0 +1,96 @@ +// @ts-expect-error — bun:test is provided by the Bun runtime; viewer does not +// depend on @types/bun so the import type is unresolved at compile time. +import { describe, expect, test } from 'bun:test' +import { type AnyNode, RoofNode, RoofSegmentNode } from '@pascal-app/core' +import * as THREE from 'three' +import { generateRoofSegmentGeometry } from './roof-system' + +type Point = [number, number] +const DEG = Math.PI / 180 + +/** A gable over a plan rectangle [x0, x1] × [z0, z1] drawn as an outline, its own roof on `level`. */ +function roofOver(id: string, x0: number, x1: number, z0: number, z1: number, extra = {}) { + const cx = (x0 + x1) / 2 + const cz = (z0 + z1) / 2 + const footprint: Point[] = [ + [x0 - cx, z0 - cz], + [x1 - cx, z0 - cz], + [x1 - cx, z1 - cz], + [x0 - cx, z1 - cz], + ] + const roof = RoofNode.parse({ + id: `roof_${id}`, + type: 'roof', + parentId: 'level_roofs', + position: [cx, 0, cz], + children: [`rseg_${id}`], + }) + const segment = RoofSegmentNode.parse({ + id: `rseg_${id}`, + type: 'roof-segment', + parentId: roof.id, + roofType: 'gable', + width: x1 - x0, + depth: z1 - z0, + pitch: 30, + wallHeight: 0.3, + overhang: 0.5, + wallThickness: 0.1, + deckThickness: 0.1, + shingleThickness: 0.05, + footprint, + ...extra, + }) + return { roof, segment } +} + +function extentOf(segment: RoofSegmentNode, nodes: Record) { + const geometry = generateRoofSegmentGeometry(segment, nodes) + geometry.computeBoundingBox() + const box = geometry.boundingBox!.clone() + geometry.dispose() + return box +} + +describe('roofs that meet', () => { + const west = roofOver('west', 0, 6, 0, 8) + const east = roofOver('east', 6, 14, 0, 8, { wallHeight: 1.2 }) + const nodes = Object.fromEntries( + [west.roof, west.segment, east.roof, east.segment].map((n) => [n.id, n]), + ) as Record + + test('the overhang is drawn on every side, the shared edge too', () => { + // it runs into the neighbour's attic and hides there; the Overhang field alone sets it + const reach = 0.5 * Math.cos(30 * DEG) + const w = extentOf(west.segment, nodes) + // the west roof's segment frame: x ∈ [-3, 3] + expect(w.max.x).toBeGreaterThan(3 + reach - 0.01) + expect(w.min.x).toBeLessThan(-3 - reach + 0.01) + const e = extentOf(east.segment, nodes) + // the east roof's segment frame: x ∈ [-4, 4] + expect(e.min.x).toBeLessThan(-4 - reach + 0.01) + expect(e.max.x).toBeGreaterThan(4 + reach - 0.01) + }) +}) + +describe('square eaves with little overhang', () => { + test('with none the eave ends plumb on the wall line and the soffit rests on the wall', () => { + const { roof, segment } = roofOver('solo', 0, 6, 0, 8, { overhang: 0, squareEaves: true }) + const nodes = { [roof.id]: roof, [segment.id]: segment } as Record + const geometry = generateRoofSegmentGeometry(segment, nodes) + geometry.computeBoundingBox() + // nothing past the walls: z ∈ [-4, 4] in the segment's frame + expect(geometry.boundingBox!.max.z).toBeLessThan(4 + 0.005) + // just above the soffit's line on the wall, looking in from outside: the + // roof's end stands on the wall line — no notch between wall and soffit + const mesh = new THREE.Mesh(geometry, new THREE.MeshBasicMaterial({ side: THREE.DoubleSide })) + const end = new THREE.Raycaster( + new THREE.Vector3(0, 0.3 + 0.01, 20), + new THREE.Vector3(0, 0, -1), + ) + .intersectObject(mesh) + .at(0)!.point.z + expect(end).toBeGreaterThan(4 - 0.01) + geometry.dispose() + }) +}) diff --git a/packages/viewer/src/systems/roof/roof-canopy.test.ts b/packages/viewer/src/systems/roof/roof-canopy.test.ts new file mode 100644 index 0000000000..faa2d6dbaa --- /dev/null +++ b/packages/viewer/src/systems/roof/roof-canopy.test.ts @@ -0,0 +1,268 @@ +// @ts-expect-error — bun:test is provided by the Bun runtime; viewer does not +// depend on @types/bun so the import type is unresolved at compile time. +import { describe, expect, test } from 'bun:test' +import { + getGableRidge, + getRoofSegmentCoverOutline, + getRoofSegmentSurfaceY, + pullRoofSegmentCoverEdge, + RoofSegmentNode, +} from '@pascal-app/core' +import * as THREE from 'three' +import { ROOF_SLOT_ROLES } from './roof-materials' +import { generateRoofSegmentGeometry } from './roof-system' + +/** A house 10 × 8 drawn as an outline; the roof's rectangle bounds it. */ +const house = RoofSegmentNode.parse({ + type: 'roof-segment', + squareEaves: true, + roofType: 'gable', + width: 10, + depth: 8, + wallHeight: 0, + pitch: 30, + backPitch: 20, + ridgeOffset: 3.5, + overhang: 0.4, + wallThickness: 0.2, + footprint: [ + [-5, -4], + [5, -4], + [5, 4], + [-5, 4], + ], +}) + +// the +z edge (index 2: [5,4] → [-5,4]) pulled 3 m out over a terrace +const pulled = { ...house, ...pullRoofSegmentCoverEdge(house, 2, 3)! } +// the segment's origin moved with its rectangle; a point at house-local (x, z) +// is at (x − shift.x, z − shift.z) in the pulled segment +const shift = { + x: pulled.position[0] - house.position[0], + z: pulled.position[2] - house.position[2], +} + +describe('canopy pulled out of a gable', () => { + test('the slopes stay in their planes and the ridge keeps its place and height', () => { + const before = getGableRidge(house)! + const after = getGableRidge(pulled)! + expect(after.height).toBeCloseTo(before.height, 9) + expect(after.ridgeZ + shift.z).toBeCloseTo(before.ridgeZ, 9) + for (const [x, z] of [ + [0, 3], + [2, -3], + [-4, 1], + ] as const) { + expect(getRoofSegmentSurfaceY(pulled, x - shift.x, z - shift.z)).toBeCloseTo( + getRoofSegmentSurfaceY(house, x, z), + 9, + ) + } + expect(pulled.depth).toBeCloseTo(11, 9) + }) + + test('the walls stay on the house; the covering reaches over the canopy', () => { + const walls = pulled.footprint!.map(([x, z]) => [x + shift.x, z + shift.z]) + expect(walls).toEqual(house.footprint!.map(([x, z]) => [x, z])) + const reach = Math.max(...pulled.coverFootprint!.map(([, z]) => z + shift.z)) + expect(reach).toBeCloseTo(7, 9) + }) + + test('over the canopy there is roof but no attic wall beneath it', () => { + const geometry = generateRoofSegmentGeometry(pulled) + const mesh = new THREE.Mesh( + geometry, + ROOF_SLOT_ROLES.map(() => new THREE.MeshBasicMaterial({ side: THREE.DoubleSide })), + ) + // above the terrace (house-local z = 5.5): the covering, in the slope's plane + const z = 5.5 - shift.z + const hits = new THREE.Raycaster( + new THREE.Vector3(0, 30, z), + new THREE.Vector3(0, -1, 0), + ).intersectObject(mesh) + expect(hits.length).toBeGreaterThan(0) + expect(ROOF_SLOT_ROLES[hits[0]!.face!.materialIndex]).toBe('top') + // nothing of the roof's own walls (the gables) out there + expect(hits.some((hit) => ROOF_SLOT_ROLES[hit.face!.materialIndex] === 'edge')).toBe(false) + geometry.dispose() + }) + + test('an edge does not come in past the walls', () => { + const back = pullRoofSegmentCoverEdge(house, 2, -2)! + const reach = + Math.max(...back.coverFootprint!.map(([, z]) => z)) + (back.position![2] - house.position[2]) + expect(reach).toBeCloseTo(4, 9) + }) + + test('a gable end pulls out along the ridge as an open gable over a porch', () => { + // edge 1: [5,-4] → [5,4], facing +x + const porch = { ...house, ...pullRoofSegmentCoverEdge(house, 1, 2)! } + const dx = porch.position[0] - house.position[0] + expect(porch.width).toBeCloseTo(12, 9) + expect(getGableRidge(porch)!.height).toBeCloseTo(getGableRidge(house)!.height, 9) + const geometry = generateRoofSegmentGeometry(porch) + const mesh = new THREE.Mesh( + geometry, + ROOF_SLOT_ROLES.map(() => new THREE.MeshBasicMaterial({ side: THREE.DoubleSide })), + ) + const hits = new THREE.Raycaster( + new THREE.Vector3(6 - dx, 30, 0), + new THREE.Vector3(0, -1, 0), + ).intersectObject(mesh) + expect(ROOF_SLOT_ROLES[hits[0]!.face!.materialIndex]).toBe('top') + expect(hits.some((hit) => ROOF_SLOT_ROLES[hit.face!.materialIndex] === 'edge')).toBe(false) + geometry.dispose() + }) +}) + +/** A segment's covering in house-local coordinates (undoing the rectangle's shift). */ +function coverInHouse(node: ReturnType) { + const dx = node.position[0] - house.position[0] + const dz = node.position[2] - house.position[2] + return node.coverFootprint!.map(([x, z]) => [+(x + dx).toFixed(6), +(z + dz).toFixed(6)]) +} + +describe('a canopy grows out of the edge it was pulled from', () => { + const pull = (node: ReturnType, edge: number, by: number) => + RoofSegmentNode.parse({ ...node, ...pullRoofSegmentCoverEdge(node, edge, by)! }) + const out = pull(house, 2, 3) + + test('the wall corners stay; the piece reaches out from them, the pulled edge keeps its index', () => { + const ring = coverInHouse(out) + expect(ring).toContainEqual([5, 4]) + expect(ring).toContainEqual([-5, 4]) + expect(ring).toContainEqual([5, 7]) + expect(ring).toContainEqual([-5, 7]) + expect(ring[2]).toEqual([5, 7]) + expect(ring[3]).toEqual([-5, 7]) + }) + + test("a side narrows the piece alone; the roof's own corners stay", () => { + // the piece's +x side runs [5,4] → [5,7] + const ring = coverInHouse(out) + const side = ring.findIndex( + (p, i) => p[0] === 5 && p[1] === 4 && ring[(i + 1) % ring.length]![1] === 7, + ) + const narrow = coverInHouse(pull(out, side, -4)) + expect(narrow).toContainEqual([5, -4]) + expect(narrow).toContainEqual([5, 4]) + expect(narrow).toContainEqual([1, 4]) + expect(narrow).toContainEqual([1, 7]) + expect(narrow).toContainEqual([-5, 7]) + expect(narrow).not.toContainEqual([5, 7]) + // no further in than the piece's other side: narrowed to nothing it is gone + expect(coverInHouse(pull(out, side, -50))).toHaveLength(4) + }) + + test('pulled back to the wall the piece is gone and the edge is whole again', () => { + const back = coverInHouse(pull(out, 2, -3)) + expect(back).toHaveLength(4) + for (const corner of house.footprint!) expect(back).toContainEqual(corner) + // and no further in than the walls + expect(coverInHouse(pull(out, 2, -10))).toHaveLength(4) + }) + + test('pulled further, the piece only grows longer', () => { + const longer = coverInHouse(pull(out, 2, 1)) + expect(longer).toContainEqual([5, 8]) + expect(longer).toContainEqual([-5, 8]) + expect(longer).toHaveLength(6) + }) +}) + +describe('a canopy pulled the old way, its edge slid whole', () => { + // the +z edge slid out to z = 7: the wall corners are not in the covering + const old = RoofSegmentNode.parse({ + ...house, + coverFootprint: [ + [-5, -4], + [5, -4], + [5, 7], + [-5, 7], + ], + }) + + test('its edges split at the wall corners, so the piece past the walls has sides', () => { + const ring = getRoofSegmentCoverOutline(old) + expect(ring).toContainEqual([5, 4]) + expect(ring).toContainEqual([-5, 4]) + }) + + test('a side narrows that piece alone', () => { + const ring = getRoofSegmentCoverOutline(old) + const side = ring.findIndex( + (p, i) => p[0] === 5 && p[1] === 4 && ring[(i + 1) % ring.length]![1] === 7, + ) + expect(side).toBeGreaterThanOrEqual(0) + const narrow = coverInHouse( + RoofSegmentNode.parse({ ...old, ...pullRoofSegmentCoverEdge(old, side, -4)! }), + ) + expect(narrow).toContainEqual([5, -4]) + expect(narrow).toContainEqual([5, 4]) + expect(narrow).toContainEqual([1, 4]) + expect(narrow).toContainEqual([1, 7]) + expect(narrow).toContainEqual([-5, 7]) + }) +}) + +describe('a canopy with a slot narrower than the overhang', () => { + test('the slot closes under the overhang; nothing hangs below the eaves', () => { + // pulled edge by edge on a house's annex, a 5.5 cm slot left at a wall corner + const slotted = RoofSegmentNode.parse({ + type: 'roof-segment', + roofType: 'gable', + width: 9.92, + depth: 10.82, + pitch: 23, + backPitch: 17, + ridgeOffset: 4.09, + wallHeight: 1.1139, + overhang: 0.5, + squareEaves: true, + fascia: true, + wallThickness: 0.1, + deckThickness: 0.1, + shingleThickness: 0.05, + footprint: [ + [-4.96, -2.96], + [3.115, -2.96], + [3.115, 1.19], + [4.71, 1.19], + [4.71, 5.41], + [0.005, 5.41], + [0.005, 3.91], + [-4.96, 3.91], + ], + coverFootprint: [ + [4.71, 1.19], + [4.71, 0.29], + [4.96, 0.29], + [4.96, 5.41], + [4.71, 5.41], + [0.005, 5.41], + [0.005, 3.91], + [-4.96, 3.91], + [-4.96, -2.96], + [-4.96, -5.41], + [4.655, -5.41], + [4.655, 1.19], + ], + }) + const lowest = Math.min( + ...slotted.coverFootprint!.map(([x, z]) => getRoofSegmentSurfaceY(slotted, x, z)), + ) + const geometry = generateRoofSegmentGeometry(slotted) + const position = geometry.getAttribute('position') + const index = geometry.index + let low = Number.POSITIVE_INFINITY + for (const group of geometry.groups) { + const role = ROOF_SLOT_ROLES[group.materialIndex!] + if (role === 'wall' || role === 'edge') continue + for (let i = group.start; i < group.start + group.count; i++) { + low = Math.min(low, position.getY(index ? index.getX(i) : i)) + } + } + geometry.dispose() + expect(low).toBeGreaterThan(lowest - slotted.overhang - 0.4) + }) +}) diff --git a/packages/viewer/src/systems/roof/roof-clip-frame.test.ts b/packages/viewer/src/systems/roof/roof-clip-frame.test.ts new file mode 100644 index 0000000000..cf28e5b90c --- /dev/null +++ b/packages/viewer/src/systems/roof/roof-clip-frame.test.ts @@ -0,0 +1,138 @@ +// @ts-expect-error — bun:test is provided by the Bun runtime; viewer does not +// depend on @types/bun so the import type is unresolved at compile time. +import { afterEach, describe, expect, test } from 'bun:test' +import { + type AnyNode, + type AnyNodeId, + BuildingNode, + LevelNode, + RoofNode, + RoofSegmentNode, + sceneRegistry, + useScene, +} from '@pascal-app/core' +import * as THREE from 'three' +import { runRoofClipFrame } from './roof-clip' + +const STOREY = 3.05 + +/** A ground storey under a low porch roof and an upper storey whose room stands over the porch. */ +function scene() { + const nodes: Record = {} + const add = (node: AnyNode) => { + nodes[node.id] = node + } + add(BuildingNode.parse({ id: 'building_a', type: 'building', children: ['level_0', 'level_1'] })) + add( + LevelNode.parse({ + id: 'level_0', + type: 'level', + parentId: 'building_a', + level: 0, + height: STOREY, + children: ['roof_porch'], + }), + ) + add( + LevelNode.parse({ + id: 'level_1', + type: 'level', + parentId: 'building_a', + level: 1, + height: 2.5, + children: [], + }), + ) + add( + RoofNode.parse({ + id: 'roof_porch', + type: 'roof', + parentId: 'level_0', + position: [0, 0, 0], + children: ['rseg_porch'], + }), + ) + add( + RoofSegmentNode.parse({ + id: 'rseg_porch', + type: 'roof-segment', + parentId: 'roof_porch', + roofType: 'shed', + width: 4, + depth: 4, + pitch: 17, + wallHeight: 2.2, + overhang: 0, + wallThickness: 0.1, + deckThickness: 0.2, + wallShell: 'omit', + }), + ) + useScene.setState({ nodes: nodes as Record }) + + const levels = (['level_0', 'level_1'] as const).map((id, index) => { + const object = new THREE.Group() + object.position.y = index * STOREY + sceneRegistry.nodes.set(id, object) + sceneRegistry.byType.level!.add(id) + return object + }) + const box = (level: THREE.Object3D, height: number) => { + const geometry = new THREE.BoxGeometry(0.2, height, 0.2) + geometry.translate(0, height / 2, 0) + const mesh = new THREE.Mesh(geometry, new THREE.MeshBasicMaterial()) + level.add(mesh) + return mesh + } + const post = box(levels[0]!, 3) + const upstairs = box(levels[1]!, 1) + for (const level of levels) level.updateMatrixWorld(true) + return { nodes, post, upstairs } +} + +afterEach(() => { + sceneRegistry.clear() + useScene.setState({ nodes: {} as Record }) +}) + +describe('roof clip frame', () => { + test('a room over a lower roof is left alone; the post under it is cut', () => { + const { post, upstairs } = scene() + const postSource = post.geometry + const upstairsSource = upstairs.geometry + runRoofClipFrame() + expect(post.geometry).not.toBe(postSource) + expect(upstairs.geometry).toBe(upstairsSource) + }) + + test('a roof that goes away gives the meshes it cut their own geometry back', () => { + const { nodes, post } = scene() + const source = post.geometry + runRoofClipFrame() + expect(post.geometry).not.toBe(source) + const { roof_porch: _roof, rseg_porch: _segment, ...rest } = nodes + useScene.setState({ + nodes: { + ...rest, + level_0: { ...nodes.level_0, children: [] }, + } as unknown as Record, + }) + runRoofClipFrame() + expect(post.geometry).toBe(source) + }) + + test('a mesh taken off the scene drops its cut copy', () => { + const { post } = scene() + const source = post.geometry + runRoofClipFrame() + const cut = post.geometry + let disposed = false + cut.addEventListener('dispose', () => { + disposed = true + }) + post.removeFromParent() + runRoofClipFrame() + expect(disposed).toBe(true) + expect(post.geometry).toBe(source) + }) +}) diff --git a/packages/viewer/src/systems/roof/roof-clip.test.ts b/packages/viewer/src/systems/roof/roof-clip.test.ts new file mode 100644 index 0000000000..638dfd730d --- /dev/null +++ b/packages/viewer/src/systems/roof/roof-clip.test.ts @@ -0,0 +1,47 @@ +// @ts-expect-error — bun:test is provided by the Bun runtime; viewer does not +// depend on @types/bun so the import type is unresolved at compile time. +import { describe, expect, test } from 'bun:test' +import * as THREE from 'three' +import { clipGeometryByRegions } from './roof-clip' + +/** Above y = 1 + 0.3 x, inside 0 ≤ x ≤ 4, 0 ≤ z ≤ 4. */ +const region = [ + new THREE.Plane(new THREE.Vector3(-0.3, 1, 0), -1), + new THREE.Plane(new THREE.Vector3(1, 0, 0), 0), + new THREE.Plane(new THREE.Vector3(-1, 0, 0), 4), + new THREE.Plane(new THREE.Vector3(0, 0, 1), 0), + new THREE.Plane(new THREE.Vector3(0, 0, -1), 4), +] + +function post(x: number, height = 3) { + const geometry = new THREE.BoxGeometry(0.2, height, 0.2) + geometry.translate(x, height / 2, 2) + return geometry +} + +describe('roof clip', () => { + test('a post under the slope loses everything above the underside', () => { + const clipped = clipGeometryByRegions(post(2), [region])! + expect(clipped).not.toBeNull() + const positions = clipped.getAttribute('position') + for (let i = 0; i < positions.count; i++) { + const x = positions.getX(i) + expect(positions.getY(i)).toBeLessThanOrEqual(1 + 0.3 * x + 1e-5) + } + clipped.computeBoundingBox() + expect(clipped.boundingBox!.max.y).toBeCloseTo(1 + 0.3 * 2.1, 4) + expect(clipped.boundingBox!.min.y).toBeCloseTo(0, 6) + }) + + test('a post outside the roof outline or below the underside stays as it is', () => { + expect(clipGeometryByRegions(post(6), [region])).toBeNull() + expect(clipGeometryByRegions(post(2, 0.8), [region])).toBeNull() + }) + + test('material groups survive the cut', () => { + const clipped = clipGeometryByRegions(post(2), [region])! + expect(new Set(clipped.groups.map((group) => group.materialIndex)).size).toBeGreaterThan(1) + const total = clipped.groups.reduce((sum, group) => sum + group.count, 0) + expect(total).toBe(clipped.getAttribute('position').count) + }) +}) diff --git a/packages/viewer/src/systems/roof/roof-clip.ts b/packages/viewer/src/systems/roof/roof-clip.ts new file mode 100644 index 0000000000..7f3a6667c1 --- /dev/null +++ b/packages/viewer/src/systems/roof/roof-clip.ts @@ -0,0 +1,382 @@ +import { + type AnyNode, + type AnyNodeId, + getLevelElevations, + sceneRegistry, + useScene, +} from '@pascal-app/core' +import * as THREE from 'three' +import { getRoofUndersidePatches, type RoofUndersidePatch } from './roof-underside' + +/** + * Nothing passes through a roof: every mesh of a building — furniture, posts, + * fences, pipes, ceilings — is cut at the underside of any roof above it. + * + * The cut is geometric, so it works for every material and loader: the + * triangles of a mesh lose whatever lies above a roof underside within that + * roof's outline. The cut face is left open: it sits against the underside of + * the deck and cannot be seen. Excluded: the roofs themselves and everything + * they host (chimneys and skylights on the slope), and walls, which the wall + * system cuts into closed solids (`wall-roof-fit`). Skinned and instanced + * meshes are left as they are: their vertices are placed on the GPU. + */ + +type ClipRegion = THREE.Plane[] + +type ClipState = { + source: THREE.BufferGeometry + /** The geometry on the mesh: the cut one, or `source` when nothing is cut. */ + clipped: THREE.BufferGeometry + /** Mesh-local → building transform and roof set the cut was made for. */ + placement: number[] + roofs: string +} + +const clipStates = new WeakMap() +// Meshes wearing a cut copy, so a roof that goes away gives them back their own geometry. +const clippedMeshes = new Set() + +function restore(mesh: THREE.Mesh) { + const state = clipStates.get(mesh) + if (state && state.clipped !== state.source) { + if (mesh.geometry === state.clipped) mesh.geometry = state.source + state.clipped.dispose() + } + clipStates.delete(mesh) + clippedMeshes.delete(mesh) +} + +function restoreWithin(root: THREE.Object3D | null) { + for (const mesh of [...clippedMeshes]) { + let inside = root === null + for (let current: THREE.Object3D | null = mesh; current && !inside; current = current.parent) { + inside = current === root + } + if (inside) restore(mesh) + } +} + +// A level is cut by the roofs of its own storey and of the storey right above +// it — not by a lower roof (a porch or a lower wing) its rooms stand over. +const storeyPatches = new WeakMap< + readonly RoofUndersidePatch[], + Map +>() +function patchesForStorey(patches: readonly RoofUndersidePatch[], ordinal: number, above: number) { + const byStorey = storeyPatches.get(patches) ?? new Map() + storeyPatches.set(patches, byStorey) + const key = `${ordinal}:${above}` + let filtered = byStorey.get(key) + if (!filtered) { + filtered = patches.filter((patch) => patch.ordinal === ordinal || patch.ordinal === above) + byStorey.set(key, filtered) + } + return filtered +} +// Tolerance for the plane splits (metres) and for "nothing to cut". +const SPLIT_EPSILON = 1e-6 + +/** + * Convex regions above the roof undersides in building space: each patch + * outline is triangulated, and each triangle with the patch plane bounds a + * prism open upwards. Inside a region every plane's distance is positive. + */ +function clipRegions(patches: readonly RoofUndersidePatch[]): ClipRegion[] { + const regions: ClipRegion[] = [] + for (const patch of patches) { + const contour = patch.polygon.map(([x, z]) => new THREE.Vector2(x, z)) + for (const triangle of THREE.ShapeUtils.triangulateShape(contour, [])) { + const corners = triangle.map((index) => patch.polygon[index]!) + // Each side faces the triangle's centre, whatever the winding of the outline. + const cx = (corners[0]![0] + corners[1]![0] + corners[2]![0]) / 3 + const cz = (corners[0]![1] + corners[1]![1] + corners[2]![1]) / 3 + const planes: THREE.Plane[] = [ + // Above the underside: y - a x - b z - c > 0. Normalised: `applyMatrix4` + // takes its point on the plane from a unit normal. + new THREE.Plane(new THREE.Vector3(-patch.a, 1, -patch.b), -patch.c).normalize(), + ] + for (let i = 0; i < 3; i++) { + const [x0, z0] = corners[i]! + const [x1, z1] = corners[(i + 1) % 3]! + const normal = new THREE.Vector3(-(z1 - z0), 0, x1 - x0) + if (normal.lengthSq() < 1e-18) continue + if (normal.x * (cx - x0) + normal.z * (cz - z0) < 0) normal.negate() + normal.normalize() + planes.push(new THREE.Plane(normal, -normal.dot(new THREE.Vector3(x0, 0, z0)))) + } + regions.push(planes) + } + } + return regions +} + +type Vertex = number[] + +/** Splits a polygon by a plane on the position slice (first three numbers). */ +function splitPolygon(polygon: Vertex[], plane: THREE.Plane): [Vertex[], Vertex[]] { + const front: Vertex[] = [] + const back: Vertex[] = [] + const distance = (v: Vertex) => + plane.normal.x * v[0]! + plane.normal.y * v[1]! + plane.normal.z * v[2]! + plane.constant + for (let i = 0; i < polygon.length; i++) { + const current = polygon[i]! + const next = polygon[(i + 1) % polygon.length]! + const dc = distance(current) + const dn = distance(next) + if (dc >= -SPLIT_EPSILON) front.push(current) + if (dc <= SPLIT_EPSILON) back.push(current) + if ( + (dc > SPLIT_EPSILON && dn < -SPLIT_EPSILON) || + (dc < -SPLIT_EPSILON && dn > SPLIT_EPSILON) + ) { + const t = dc / (dc - dn) + const point = current.map((value, k) => value + (next[k]! - value) * t) + front.push(point) + back.push(point) + } + } + return [front.length >= 3 ? front : [], back.length >= 3 ? back : []] +} + +/** The parts of a polygon outside a convex region; the polygon itself when it misses it. */ +function subtractRegion(polygon: Vertex[], region: ClipRegion): Vertex[][] { + const misses = region.some((plane) => + polygon.every( + (v) => + plane.normal.x * v[0]! + plane.normal.y * v[1]! + plane.normal.z * v[2]! + plane.constant < + SPLIT_EPSILON, + ), + ) + if (misses) return [polygon] + const kept: Vertex[][] = [] + let remaining = polygon + for (const plane of region) { + const [inside, outside] = splitPolygon(remaining, plane) + if (outside.length) kept.push(outside) + remaining = inside + if (!remaining.length) break + } + return kept +} + +/** + * The geometry with everything inside `regions` (mesh-local) removed, or null + * when nothing is cut. Attributes are interpolated along the cut; groups keep + * their materials. + */ +export function clipGeometryByRegions( + source: THREE.BufferGeometry, + regions: readonly ClipRegion[], +): THREE.BufferGeometry | null { + if (regions.length === 0) return null + const geometry = source.index ? source.toNonIndexed() : source + const position = geometry.getAttribute('position') + // Position first: the plane splits read the first three numbers of a vertex. + const names = [ + 'position', + ...Object.keys(geometry.attributes).filter((name) => name !== 'position'), + ] + const sizes = names.map((name) => geometry.getAttribute(name).itemSize) + const stride = sizes.reduce((sum, size) => sum + size, 0) + const groups = geometry.groups.length + ? geometry.groups + : [{ start: 0, count: position.count, materialIndex: 0 }] + + const vertexAt = (index: number): Vertex => { + const vertex: Vertex = [] + names.forEach((name) => { + const attribute = geometry.getAttribute(name) + for (let k = 0; k < attribute.itemSize; k++) vertex.push(attribute.getComponent(index, k)) + }) + return vertex + } + + const output: number[] = [] + const outputGroups: Array<{ start: number; count: number; materialIndex: number }> = [] + let changed = false + for (const group of groups) { + const start = output.length / stride + const end = Math.min(position.count, group.start + group.count) + for (let index = group.start; index + 2 < end; index += 3) { + let pieces: Vertex[][] = [[vertexAt(index), vertexAt(index + 1), vertexAt(index + 2)]] + for (const region of regions) { + const next: Vertex[][] = [] + for (const piece of pieces) { + const kept = subtractRegion(piece, region) + if (kept.length !== 1 || kept[0] !== piece) changed = true + next.push(...kept) + } + pieces = next + if (!pieces.length) break + } + for (const piece of pieces) { + for (let k = 1; k + 1 < piece.length; k++) { + for (const vertex of [piece[0]!, piece[k]!, piece[k + 1]!]) output.push(...vertex) + } + } + } + const count = output.length / stride - start + if (count > 0) outputGroups.push({ start, count, materialIndex: group.materialIndex ?? 0 }) + } + if (geometry !== source) geometry.dispose() + if (!changed) return null + + const result = new THREE.BufferGeometry() + const vertexCount = output.length / stride + let offset = 0 + names.forEach((name, n) => { + const size = sizes[n]! + const array = new Float32Array(vertexCount * size) + for (let v = 0; v < vertexCount; v++) { + for (let k = 0; k < size; k++) array[v * size + k] = output[v * stride + offset + k]! + } + result.setAttribute(name, new THREE.BufferAttribute(array, size)) + offset += size + }) + if (result.getAttribute('normal')) { + const normal = result.getAttribute('normal') as THREE.BufferAttribute + const vector = new THREE.Vector3() + for (let v = 0; v < normal.count; v++) { + vector.fromBufferAttribute(normal, v).normalize() + normal.setXYZ(v, vector.x, vector.y, vector.z) + } + } + if (source.groups.length) { + for (const group of outputGroups) result.addGroup(group.start, group.count, group.materialIndex) + } + result.computeBoundingBox() + result.computeBoundingSphere() + result.userData = { ...source.userData } + return result +} + +function isRoofOwned(object: THREE.Object3D, roofGroups: ReadonlySet) { + for (let current: THREE.Object3D | null = object; current; current = current.parent) { + if (roofGroups.has(current)) return true + } + return false +} + +const roofKeys = new WeakMap() +function roofKeyOf(patches: readonly RoofUndersidePatch[]) { + return patches + .map((patch) => `${patch.a},${patch.b},${patch.c}:${patch.polygon.flat().join(',')}`) + .join(';') +} + +const scratchMatrix = new THREE.Matrix4() +const scratchBox = new THREE.Box3() + +/** + * Cuts the meshes of every level at the roofs above them. Cheap when nothing + * changed: a mesh is re-cut only when its geometry, its placement or the roofs + * of its building change. + */ +export function runRoofClipFrame() { + const nodes = useScene.getState().nodes as Readonly> + // A mesh taken off the scene keeps no cut copy. + for (const mesh of clippedMeshes) if (!mesh.parent) restore(mesh) + const patchesByBuilding = getRoofUndersidePatches(nodes) + if (patchesByBuilding.size === 0) { + if (clippedMeshes.size > 0) restoreWithin(null) + return + } + const elevations = getLevelElevations(nodes as Record) + const roofGroups = new Set() + for (const id of sceneRegistry.byType.roof ?? []) { + const group = sceneRegistry.nodes.get(id) + if (group) roofGroups.add(group) + } + const wallMeshes = new Set() + for (const id of sceneRegistry.byType.wall ?? []) { + const mesh = sceneRegistry.nodes.get(id) + if (mesh) wallMeshes.add(mesh) + } + + for (const levelId of sceneRegistry.byType.level ?? []) { + const levelObject = sceneRegistry.nodes.get(levelId) + const level = elevations.get(levelId) + if (!levelObject || !level) continue + let above = Number.POSITIVE_INFINITY + for (const other of elevations.values()) { + if (other.buildingId === level.buildingId && other.ordinal > level.ordinal) { + above = Math.min(above, other.ordinal) + } + } + const buildingPatches = patchesByBuilding.get(level.buildingId) + const patches = buildingPatches && patchesForStorey(buildingPatches, level.ordinal, above) + if (!patches?.length) { + if (clippedMeshes.size > 0) restoreWithin(levelObject) + continue + } + const roofsKey = roofKeys.get(patches) ?? roofKeyOf(patches) + roofKeys.set(patches, roofsKey) + let buildingRegions: ClipRegion[] | null = null + const levelInverse = new THREE.Matrix4().copy(levelObject.matrixWorld).invert() + + levelObject.traverse((object) => { + const mesh = object as THREE.Mesh + if (!mesh.isMesh || (mesh as THREE.SkinnedMesh).isSkinnedMesh) return + if ((mesh as THREE.InstancedMesh).isInstancedMesh) return + if (wallMeshes.has(mesh) || wallMeshes.has(mesh.parent!)) return + if (isRoofOwned(mesh, roofGroups)) return + const state = clipStates.get(mesh) + const source = state && mesh.geometry === state.clipped ? state.source : mesh.geometry + if (!source?.getAttribute('position')) return + // Mesh-local → building space: through the level's frame, then up by its base. + scratchMatrix.multiplyMatrices(levelInverse, mesh.matrixWorld) + scratchMatrix.elements[13]! += level.baseY + if ( + state && + state.source === source && + mesh.geometry === state.clipped && + state.roofs === roofsKey && + state.placement.every((value, k) => Math.abs(value - scratchMatrix.elements[k]!) < 1e-6) + ) { + return + } + if (!source.boundingBox) source.computeBoundingBox() + scratchBox.copy(source.boundingBox!).applyMatrix4(scratchMatrix) + buildingRegions ??= clipRegions(patches) + const touching = patches.some( + (patch) => + patch.maxX >= scratchBox.min.x && + patch.minX <= scratchBox.max.x && + patch.maxZ >= scratchBox.min.z && + patch.minZ <= scratchBox.max.z && + scratchBox.max.y > + Math.min( + patch.a * scratchBox.min.x + patch.b * scratchBox.min.z, + patch.a * scratchBox.max.x + patch.b * scratchBox.max.z, + patch.a * scratchBox.min.x + patch.b * scratchBox.max.z, + patch.a * scratchBox.max.x + patch.b * scratchBox.min.z, + ) + + patch.c, + ) + let clipped: THREE.BufferGeometry | null = null + if (touching) { + const toLocal = scratchMatrix.clone().invert() + const regions = buildingRegions.map((region) => + region.map((plane) => plane.clone().applyMatrix4(toLocal)), + ) + clipped = clipGeometryByRegions(source, regions) + } + // Only the cut copy is ours; the source belongs to its renderer (GLB geometry is shared). + if (state && state.clipped !== state.source && state.clipped !== clipped) + state.clipped.dispose() + if (clipped) { + mesh.geometry = clipped + clippedMeshes.add(mesh) + } else { + if (mesh.geometry !== source) mesh.geometry = source + clippedMeshes.delete(mesh) + } + clipStates.set(mesh, { + source, + clipped: clipped ?? source, + placement: [...scratchMatrix.elements], + roofs: roofsKey, + }) + }) + } +} diff --git a/packages/viewer/src/systems/roof/roof-csg-robustness.test.ts b/packages/viewer/src/systems/roof/roof-csg-robustness.test.ts new file mode 100644 index 0000000000..c83e756c52 --- /dev/null +++ b/packages/viewer/src/systems/roof/roof-csg-robustness.test.ts @@ -0,0 +1,85 @@ +// @ts-expect-error — bun:test is provided by the Bun runtime; viewer does not +// depend on @types/bun so the import type is unresolved at compile time. +import { describe, expect, test } from 'bun:test' +import { RoofSegmentNode } from '@pascal-app/core' +import * as THREE from 'three' +import { generateRoofSegmentGeometry, offsetPlanRing } from './roof-system' + +type Point = [number, number] + +function crosses(a: Point, b: Point, c: Point, d: Point) { + const side = (p: Point, q: Point, r: Point) => + Math.sign((q[0] - p[0]) * (r[1] - p[1]) - (q[1] - p[1]) * (r[0] - p[0])) + return side(a, b, c) * side(a, b, d) < 0 && side(c, d, a) * side(c, d, b) < 0 +} + +function selfCrossings(ring: Point[]) { + let count = 0 + for (let i = 0; i < ring.length; i++) { + for (let j = i + 2; j < ring.length; j++) { + if (i === 0 && j === ring.length - 1) continue + if (crosses(ring[i]!, ring[(i + 1) % ring.length]!, ring[j]!, ring[(j + 1) % ring.length]!)) { + count++ + } + } + } + return count +} + +describe('roof outline robustness', () => { + test('repeated points do not upset the offset', () => { + const ring: Point[] = [ + [0, 0], + [4, 0], + [4, 0], + [4, 3], + [0, 3], + ] + const out = offsetPlanRing(ring, 0.5) + expect(out).toHaveLength(4) + expect(selfCrossings(out)).toBe(0) + }) + + test('an L-shaped gable has no slivers torn out of its soffit and deck', () => { + const L: Point[] = [ + [-5, -2.96], + [3.4, -2.96], + [3.4, 1.19], + [5, 1.19], + [5, 5.41], + [0.3, 5.41], + [0.3, 3.91], + [-5, 3.91], + ] + const node = RoofSegmentNode.parse({ + type: 'roof-segment', + roofType: 'gable', + width: 10, + depth: 10.82, + pitch: 30, + ridgeOffset: 4, + wallHeight: 0.5, + overhang: 0.5, + wallThickness: 0.1, + deckThickness: 0.1, + shingleThickness: 0.05, + footprint: L, + }) + const geometry = generateRoofSegmentGeometry(node) + geometry.computeBoundingBox() + const box = geometry.boundingBox! + const mesh = new THREE.Mesh(geometry, new THREE.MeshBasicMaterial({ side: THREE.DoubleSide })) + // from below, every ray meets the soffit (facing down) before anything facing up + let torn = 0 + for (let x = box.min.x + 0.01; x < box.max.x; x += 0.1) { + for (let z = box.min.z + 0.003; z < box.max.z; z += 0.006) { + const hit = new THREE.Raycaster(new THREE.Vector3(x, -30, z), new THREE.Vector3(0, 1, 0)) + .intersectObject(mesh) + .at(0) + if (hit && hit.face!.normal.y > 0.05) torn++ + } + } + expect(torn).toBe(0) + geometry.dispose() + }, 60000) +}) diff --git a/packages/viewer/src/systems/roof/roof-fascia.test.ts b/packages/viewer/src/systems/roof/roof-fascia.test.ts index 61b30b5318..839b4712d4 100644 --- a/packages/viewer/src/systems/roof/roof-fascia.test.ts +++ b/packages/viewer/src/systems/roof/roof-fascia.test.ts @@ -23,7 +23,7 @@ function segment(patch: Partial): RoofSegmentNode { } /** - * Vertices of the trim-slot triangles whose centre lies outside the deck + * Vertices of the fascia-slot triangles whose centre lies outside the deck * along `axis` and within the span across it: the boards on that edge, not * the ends of the boards that meet it. */ @@ -39,7 +39,7 @@ function boardPoints(node: RoofSegmentNode, axis: 'x' | 'z', side: 1 | -1): THRE const at = (i: number) => new THREE.Vector3().fromBufferAttribute(position, index ? index.getX(i) : i) for (const group of geometry.groups) { - if (group.materialIndex !== 2) continue + if (group.materialIndex !== 1) continue for (let i = group.start; i < group.start + group.count; i += 3) { const tri = [at(i), at(i + 1), at(i + 2)] const c = tri.reduce((sum, v) => sum.add(v), new THREE.Vector3()).multiplyScalar(1 / 3) diff --git a/packages/viewer/src/systems/roof/roof-footprint-clip.test.ts b/packages/viewer/src/systems/roof/roof-footprint-clip.test.ts new file mode 100644 index 0000000000..3df0ecacc3 --- /dev/null +++ b/packages/viewer/src/systems/roof/roof-footprint-clip.test.ts @@ -0,0 +1,86 @@ +// @ts-expect-error — bun:test is provided by the Bun runtime; viewer does not +// depend on @types/bun so the import type is unresolved at compile time. +import { describe, expect, test } from 'bun:test' +import { RoofSegmentNode } from '@pascal-app/core' +import * as THREE from 'three' +import { generateRoofSegmentGeometry, getRoofSegmentUndersidePolygons } from './roof-system' + +/** An L: the 10 × 8 rectangle without its +x / +z quarter (x > 2, z > 1). */ +const L: [number, number][] = [ + [-5, -4], + [5, -4], + [5, 1], + [2, 1], + [2, 4], + [-5, 4], +] + +function segment(footprint?: [number, number][]) { + return RoofSegmentNode.parse({ + type: 'roof-segment', + roofType: 'gable', + width: 10, + depth: 8, + wallHeight: 0, + pitch: 30, + overhang: 0.5, + wallThickness: 0.2, + footprint, + }) +} + +function hitsAt(geometry: THREE.BufferGeometry, x: number, z: number) { + const mesh = new THREE.Mesh(geometry, new THREE.MeshBasicMaterial({ side: THREE.DoubleSide })) + return new THREE.Raycaster( + new THREE.Vector3(x, 50, z), + new THREE.Vector3(0, -1, 0), + ).intersectObject(mesh).length +} + +describe('roof segment cut to a footprint', () => { + test('nothing over the cut-away corner, the roof everywhere else', () => { + const geometry = generateRoofSegmentGeometry(segment(L)) + expect(hitsAt(geometry, 4, 3)).toBe(0) + expect(hitsAt(geometry, -3, 3)).toBeGreaterThan(0) + expect(hitsAt(geometry, 4, -3)).toBeGreaterThan(0) + // Within the overhang beyond the inner walls, the eave still reaches. + expect(hitsAt(geometry, 2.3, 3)).toBeGreaterThan(0) + expect(hitsAt(geometry, 3, 1.3)).toBeGreaterThan(0) + geometry.dispose() + }) + + test('without a footprint the rectangle stays whole', () => { + const geometry = generateRoofSegmentGeometry(segment()) + expect(hitsAt(geometry, 4, 3)).toBeGreaterThan(0) + geometry.dispose() + }) + + test('the underside stops at the outline plus overhang', () => { + const polygons = getRoofSegmentUndersidePolygons(segment(L))! + const inside = (x: number, z: number) => + polygons.some((polygon) => { + let hit = false + for (let i = 0, j = polygon.length - 1; i < polygon.length; j = i++) { + const a = polygon[i]! + const b = polygon[j]! + if (a.z > z !== b.z > z && x < ((b.x - a.x) * (z - a.z)) / (b.z - a.z) + a.x) hit = !hit + } + return hit + }) + expect(inside(4, 3)).toBe(false) + expect(inside(-3, 3)).toBe(true) + expect(inside(4, -3)).toBe(true) + }) + + test('the gable stands inside the outline, flush with its face', () => { + const geometry = generateRoofSegmentGeometry(segment(L)) + const mesh = new THREE.Mesh(geometry, new THREE.MeshBasicMaterial({ side: THREE.DoubleSide })) + // Under the slope at z = -2 the gable is 2 tan 30° ≈ 1.15 m tall at x = 5. + const hit = new THREE.Raycaster( + new THREE.Vector3(9, 0.8, -2), + new THREE.Vector3(-1, 0, 0), + ).intersectObject(mesh)[0] + expect(hit?.point.x).toBeCloseTo(5, 3) + geometry.dispose() + }) +}) diff --git a/packages/viewer/src/systems/roof/roof-gable-pitches.test.ts b/packages/viewer/src/systems/roof/roof-gable-pitches.test.ts new file mode 100644 index 0000000000..78e3633818 --- /dev/null +++ b/packages/viewer/src/systems/roof/roof-gable-pitches.test.ts @@ -0,0 +1,422 @@ +// @ts-expect-error — bun:test is provided by the Bun runtime; viewer does not +// depend on @types/bun so the import type is unresolved at compile time. +import { describe, expect, test } from 'bun:test' +import { + getGableRidge, + getRoofSegmentSurfaceY, + getRoofSegmentWallFace, + getSegmentSlopeFrame, + RoofSegmentNode, +} from '@pascal-app/core' +import * as THREE from 'three' +import { generateRoofSegmentGeometry, getRoofSegmentUndersidePolygons } from './roof-system' + +const DEG = Math.PI / 180 +const TAN_FRONT = Math.tan(24 * DEG) +const TAN_BACK = Math.tan(17 * DEG) + +/** An L: the 10 × 8 rectangle without its +x / +z quarter (x > 2, z > 1). */ +const L: [number, number][] = [ + [-5, -4], + [5, -4], + [5, 1], + [2, 1], + [2, 4], + [-5, 4], +] + +function segment(extra: Partial = {}) { + return RoofSegmentNode.parse({ + type: 'roof-segment', + roofType: 'gable', + width: 10, + depth: 8, + wallHeight: 0.5, + pitch: 24, + backPitch: 17, + overhang: 0.5, + wallThickness: 0.2, + deckThickness: 0.1, + shingleThickness: 0.05, + ...extra, + }) +} + +/** Height of the topmost surface straight below (x, ·, z), or null when nothing is there. */ +function topAt(geometry: THREE.BufferGeometry, x: number, z: number): number | null { + const mesh = new THREE.Mesh(geometry, new THREE.MeshBasicMaterial({ side: THREE.DoubleSide })) + const hit = new THREE.Raycaster(new THREE.Vector3(x, 50, z), new THREE.Vector3(0, -1, 0)) + .intersectObject(mesh) + .at(0) + return hit ? hit.point.y : null +} + +/** The outer skin of one slope: its wall-line plane lifted by deck + shingles at that pitch. */ +function skinY(node: RoofSegmentNode, z: number) { + const lift = node.deckThickness + node.shingleThickness + const front = node.wallHeight + (node.depth / 2 - z) * TAN_FRONT + lift / Math.cos(24 * DEG) + const back = node.wallHeight + (node.depth / 2 + z) * TAN_BACK + lift / Math.cos(17 * DEG) + return Math.min(front, back) +} + +describe('gable with two pitches', () => { + test('both eaves stay at the wall height; the ridge moves toward the steeper slope', () => { + const node = segment() + const frame = getSegmentSlopeFrame(node) + const ridgeZ = (4 * (TAN_FRONT - TAN_BACK)) / (TAN_FRONT + TAN_BACK) + expect(frame.ridgeZ).toBeCloseTo(ridgeZ, 6) + expect(frame.ridgeZ).toBeGreaterThan(0) + expect(frame.activeRh).toBeCloseTo((4 - ridgeZ) * TAN_FRONT, 6) + expect(frame.activeRh).toBeCloseTo((4 + ridgeZ) * TAN_BACK, 6) + + expect(getRoofSegmentSurfaceY(node, 0, 4)).toBeCloseTo(0.5, 6) + expect(getRoofSegmentSurfaceY(node, 0, -4)).toBeCloseTo(0.5, 6) + expect(getRoofSegmentSurfaceY(node, 0, ridgeZ)).toBeCloseTo(0.5 + frame.activeRh, 6) + expect(getRoofSegmentSurfaceY(node, 0, 2)).toBeCloseTo(0.5 + 2 * TAN_FRONT, 6) + expect(getRoofSegmentSurfaceY(node, 0, -2)).toBeCloseTo(0.5 + 2 * TAN_BACK, 6) + }) + + test('without a back pitch, or with an equal one, the gable is symmetric as before', () => { + expect(getSegmentSlopeFrame(segment({ backPitch: undefined })).ridgeZ).toBe(0) + const plain = generateRoofSegmentGeometry(segment({ backPitch: undefined })) + const equal = generateRoofSegmentGeometry(segment({ backPitch: 24 })) + plain.computeBoundingBox() + equal.computeBoundingBox() + expect(equal.boundingBox!.equals(plain.boundingBox!)).toBe(true) + expect(equal.getAttribute('position').count).toBe(plain.getAttribute('position').count) + plain.dispose() + equal.dispose() + }) + + test('each slope of the built roof follows its own pitch', () => { + const node = segment() + const geometry = generateRoofSegmentGeometry(node) + for (const z of [3, 2, 1, -1, -2, -3]) { + expect(topAt(geometry, 0, z)).toBeCloseTo(skinY(node, z), 2) + } + geometry.computeBoundingBox() + const ridgeZ = getSegmentSlopeFrame(node).ridgeZ + expect(geometry.boundingBox!.max.y).toBeCloseTo(skinY(node, ridgeZ), 2) + geometry.dispose() + }) + + test('fascia and rake boards follow both slopes', () => { + const node = segment({ fascia: true }) + const geometry = generateRoofSegmentGeometry(node) + expect(geometry.getAttribute('position').count).toBeGreaterThan(0) + for (const z of [2, -2]) expect(topAt(geometry, 0, z)).toBeCloseTo(skinY(node, z), 2) + geometry.dispose() + }) + + test('cut to an outline, each slope keeps its pitch', () => { + const node = segment({ footprint: L }) + const geometry = generateRoofSegmentGeometry(node) + expect(topAt(geometry, 4, 3)).toBeNull() + expect(topAt(geometry, -3, 3)).toBeCloseTo(skinY(node, 3), 2) + expect(topAt(geometry, 4, -3)).toBeCloseTo(skinY(node, -3), 2) + geometry.dispose() + }) + + test('the underside under an outline lies on each slope', () => { + const node = segment({ footprint: L }) + const ridgeZ = getSegmentSlopeFrame(node).ridgeZ + const points = getRoofSegmentUndersidePolygons(node)!.flat() + const front = points.filter((point) => point.z > ridgeZ + 0.01) + const back = points.filter((point) => point.z < ridgeZ - 0.01) + expect(front.length).toBeGreaterThan(0) + expect(back.length).toBeGreaterThan(0) + // the deck bottom is the wall-line plane of each slope + for (const point of front) { + expect(point.y).toBeCloseTo(node.wallHeight + (4 - point.z) * TAN_FRONT, 4) + } + for (const point of back) { + expect(point.y).toBeCloseTo(node.wallHeight + (4 + point.z) * TAN_BACK, 4) + } + // nothing over the cut-away corner + expect(points.some((point) => point.x > 3 && point.z > 2)).toBe(false) + }) + + test('the gable end wall peaks under the moved ridge', () => { + const node = segment() + const ridgeZ = getSegmentSlopeFrame(node).ridgeZ + const right = getRoofSegmentWallFace(node, 'right') + const left = getRoofSegmentWallFace(node, 'left') + const apex = (profile: [number, number][]) => + profile.reduce((best, point) => (point[1] > best[1] ? point : best)) + // right: u runs from +z to −z; left: from −z to +z + expect(apex(right.profile)[0]).toBeCloseTo(right.length / 2 - ridgeZ, 2) + expect(apex(left.profile)[0]).toBeCloseTo(left.length / 2 + ridgeZ, 2) + }) +}) + +describe('gable with a placed ridge', () => { + const TAN_25 = Math.tan(25 * DEG) + const TAN_15 = Math.tan(15 * DEG) + // depth 10 split 4 : 6 by the ridge, 25° on the +z side, 15° on the −z side + const placed = (extra: Partial = {}) => + segment({ depth: 10, pitch: 25, backPitch: 15, ridgeOffset: 4, wallHeight: 0.8, ...extra }) + + test('the ridge stays where it is placed; the attic walls take up the pitches', () => { + const node = placed() + const ridge = getGableRidge(node)! + expect(ridge.ridgeZ).toBeCloseTo(1, 9) + expect(ridge.height).toBeCloseTo(0.8 + 4 * TAN_25, 9) + expect(ridge.backWallHeight).toBeCloseTo(ridge.height - 6 * TAN_15, 9) + expect(getSegmentSlopeFrame(node).ridgeZ).toBeCloseTo(1, 9) + expect(getRoofSegmentSurfaceY(node, 0, 5)).toBeCloseTo(0.8, 9) + expect(getRoofSegmentSurfaceY(node, 0, -5)).toBeCloseTo(ridge.backWallHeight, 9) + expect(getRoofSegmentSurfaceY(node, 0, 1)).toBeCloseTo(ridge.height, 9) + }) + + test('with equal pitches a placed ridge still splits the depth as placed', () => { + const ridge = getGableRidge(placed({ backPitch: undefined, pitch: 20 }))! + expect(ridge.ridgeZ).toBeCloseTo(1, 9) + expect(ridge.backWallHeight).toBeLessThan(ridge.frontWallHeight) + }) + + test('the built roof follows each slope from its own eave', () => { + const node = placed() + const ridge = getGableRidge(node)! + const lift = node.deckThickness + node.shingleThickness + const skin = (z: number) => + Math.min( + ridge.frontWallHeight + (5 - z) * TAN_25 + lift / Math.cos(25 * DEG), + ridge.backWallHeight + (5 + z) * TAN_15 + lift / Math.cos(15 * DEG), + ) + const geometry = generateRoofSegmentGeometry(node) + for (const z of [4, 2.5, 1.5, 0, -2, -4]) expect(topAt(geometry, 0, z)).toBeCloseTo(skin(z), 2) + geometry.dispose() + }) + + test('the end walls rise to each eave and peak under the ridge', () => { + const node = placed() + const ridge = getGableRidge(node)! + const right = getRoofSegmentWallFace(node, 'right') + const apex = right.profile.reduce((best, point) => (point[1] > best[1] ? point : best)) + expect(apex[0]).toBeCloseTo(right.length / 2 - ridge.ridgeZ, 2) + // u = 0 is the +z end, u = length the −z end + const eaves = right.profile.filter((point) => point[1] > 0 && point !== apex) + expect(Math.min(...eaves.map((p) => p[1]))).toBeLessThan(ridge.frontWallHeight) + }) +}) + +describe('gable with an eave below the plate', () => { + // ridge 4 m from the +z wall at 0.8 + 4·tan25 ≈ 2.67 m; the 25° back slope + // reaches 6 m and ends ≈ 0.13 m below the plate, the eave lower still + const node = segment({ + depth: 10, + pitch: 25, + backPitch: 30, + ridgeOffset: 4, + wallHeight: 0.8, + overhang: 0.5, + cutAtWallTop: true, + }) + + test('off (absent), the deck stays below the plate; the roof walls end at it', () => { + const geometry = generateRoofSegmentGeometry(segment({ ...node, cutAtWallTop: undefined })) + geometry.computeBoundingBox() + expect(geometry.boundingBox!.min.y).toBeLessThan(-0.05) + // the walls' faces (slot 2, the inside of the roof's walls) stop at the plate + const position = geometry.getAttribute('position') + const index = geometry.getIndex() + let lowest = Number.POSITIVE_INFINITY + for (const group of geometry.groups) { + if (group.materialIndex !== 2) continue + for (let i = group.start; i < group.start + group.count; i++) { + lowest = Math.min(lowest, position.getY(index ? index.getX(i) : i)) + } + } + expect(lowest).toBeGreaterThan(-0.005) + geometry.dispose() + }) + + test('the underside walls and posts are cut at follows the roof below the plate, unless it is cut there', () => { + const lowest = (n: RoofSegmentNode) => + Math.min(...getRoofSegmentUndersidePolygons(n)!.flatMap((p) => p.map((point) => point.y))) + // a ceiling following the slope: walls and posts meet it below the plate + expect(lowest(segment({ ...node, cutAtWallTop: undefined }))).toBeLessThan(-0.05) + // cut at the wall top: nothing bears below the plate + expect(lowest(node)).toBeGreaterThan(-0.001) + }) + + test('nothing of the roof stays below the plate inside the walls', () => { + expect(getGableRidge(node)!.backWallHeight).toBeLessThan(0) + const geometry = generateRoofSegmentGeometry(node) + const position = geometry.getAttribute('position') + const inner = 5 + node.wallThickness / 2 - 0.01 + for (let i = 0; i < position.count; i++) { + const x = position.getX(i) + const y = position.getY(i) + const z = position.getZ(i) + if (Math.abs(x) < inner && Math.abs(z) < inner) expect(y).toBeGreaterThanOrEqual(-1e-4) + } + geometry.dispose() + }) + + test('the eave still overhangs beyond the walls', () => { + const geometry = generateRoofSegmentGeometry(node) + const y = topAt(geometry, 0, -5.4) + expect(y).not.toBeNull() + expect(y!).toBeLessThan(0) + geometry.dispose() + }) + + test('walls beneath bear on no roof below the plate', () => { + const points = getRoofSegmentUndersidePolygons(node)!.flat() + expect(points.length).toBeGreaterThan(0) + for (const point of points) expect(point.y).toBeGreaterThanOrEqual(-1e-6) + }) +}) + +describe('low attic wall under a long overhang', () => { + test('the eave runs out along the slope, not sliced flat at the plate', () => { + const node = segment({ backPitch: undefined, wallHeight: 0.1, overhang: 0.8 }) + const geometry = generateRoofSegmentGeometry(node) + // past the wall the deck keeps falling with the slope below the plate + const lift = node.deckThickness + node.shingleThickness + const skin = (z: number) => node.wallHeight + (4 - z) * TAN_FRONT + lift / Math.cos(24 * DEG) + for (const z of [4.3, 4.6]) expect(topAt(geometry, 0, z)).toBeCloseTo(skin(z), 2) + // and its underside is the slope's own plane, not a flat cut at the plate + const mesh = new THREE.Mesh(geometry, new THREE.MeshBasicMaterial({ side: THREE.DoubleSide })) + const lowest = new THREE.Raycaster(new THREE.Vector3(0, -20, 4.6), new THREE.Vector3(0, 1, 0)) + .intersectObject(mesh) + .at(0)!.point.y + expect(lowest).toBeCloseTo(node.wallHeight + (4 - 4.6) * TAN_FRONT, 2) + geometry.dispose() + }) +}) + +describe('plate-seated roof with a thick deck', () => { + // the stand roof drawn by outline: wall 0, 40°, deck 0.2, overhang 0.6 + const node = segment({ + squareEaves: true, + backPitch: undefined, + depth: 8.37, + wallHeight: 0, + pitch: 40, + overhang: 0.6, + wallThickness: 0.05, + deckThickness: 0.2, + }) + const tan40 = Math.tan(40 * DEG) + const cos40 = Math.cos(40 * DEG) + const lowestAt = (geometry: THREE.BufferGeometry, z: number) => { + const mesh = new THREE.Mesh(geometry, new THREE.MeshBasicMaterial({ side: THREE.DoubleSide })) + return new THREE.Raycaster(new THREE.Vector3(-2, -20, z), new THREE.Vector3(0, 1, 0)) + .intersectObject(mesh) + .at(0)!.point.y + } + + test('the eave underside follows the slope, no flat cut', () => { + const geometry = generateRoofSegmentGeometry(node) + for (const z of [-4.4, -4.5]) expect(lowestAt(geometry, z)).toBeCloseTo((4.185 + z) * tan40, 2) + geometry.dispose() + }) + + test('square eaves: the outer face stays on the overhang line, the soffit draws back square', () => { + const geometry = generateRoofSegmentGeometry(node) + // the overhang line: the walls' outer face (the depth plus half the wall) and the overhang + const outerZ = -(4.185 + node.wallThickness / 2 + node.overhang * cos40) + const thickness = node.deckThickness + node.shingleThickness + // the cut, square to the slope from the outer face down, ends on the soffit this far in + const soffitZ = outerZ + thickness * Math.sin(40 * DEG) + const soffitY = (4.185 + soffitZ) * tan40 + expect(lowestAt(geometry, soffitZ + 0.01)).toBeCloseTo((4.185 + soffitZ + 0.01) * tan40, 2) + // past it the end rises square to the slope + for (const out of [0.03, 0.08]) { + expect(lowestAt(geometry, soffitZ - out)).toBeCloseTo(soffitY + out / tan40, 2) + } + // and the farthest point is the outer face, on the overhang line + geometry.computeBoundingBox() + expect(geometry.boundingBox!.min.z).toBeCloseTo(outerZ, 2) + geometry.dispose() + }) +}) + +describe('roof cut to an outline, square to the slope', () => { + test('an outline edge across the fall line keeps its reach; its soffit draws back square', () => { + const node = segment({ squareEaves: true, backPitch: undefined, footprint: L }) + const plumb = generateRoofSegmentGeometry(segment({ backPitch: undefined, footprint: L })) + const geometry = generateRoofSegmentGeometry(node) + const mesh = new THREE.Mesh(geometry, new THREE.MeshBasicMaterial({ side: THREE.DoubleSide })) + const sin = Math.sin(24 * DEG) + // the notch edge z = 1 (x > 2) faces down the +z slope like an eave: the + // outer face on the overhang line, the soffit drawn back by the thickness + // (plus the cut's 2 mm margin) + const outerZ = 1 + node.overhang * Math.cos(24 * DEG) + 0.002 + const soffitZ = outerZ - (node.deckThickness + node.shingleThickness) * sin + const soffitY = node.wallHeight + (4 - soffitZ) * TAN_FRONT + const lowestAt = (z: number) => + new THREE.Raycaster(new THREE.Vector3(3.5, -20, z), new THREE.Vector3(0, 1, 0)) + .intersectObject(mesh) + .at(0)?.point.y ?? null + expect(lowestAt(soffitZ - 0.01)).toBeCloseTo(soffitY + 0.01 * TAN_FRONT, 2) + expect(lowestAt(soffitZ + 0.02)).toBeCloseTo(soffitY + 0.02 / TAN_FRONT, 2) + expect(lowestAt(outerZ + 0.01)).toBeNull() + // the whole roof reaches exactly as far as with plumb eaves + geometry.computeBoundingBox() + plumb.computeBoundingBox() + for (const key of ['min', 'max'] as const) { + for (const axis of ['x', 'z'] as const) { + expect(geometry.boundingBox![key][axis]).toBeCloseTo(plumb.boundingBox![key][axis], 2) + } + } + geometry.dispose() + plumb.dispose() + }) +}) + +describe('square eaves are a switch', () => { + // the stand roof: wall 0, 40°, deck 0.2, no overhang + const flat = (extra: Partial = {}) => + segment({ + backPitch: undefined, + depth: 8.37, + wallHeight: 0, + pitch: 40, + overhang: 0, + wallThickness: 0.05, + deckThickness: 0.2, + ...extra, + }) + const reachZ = (node: RoofSegmentNode) => { + const geometry = generateRoofSegmentGeometry(node) + geometry.computeBoundingBox() + const box = geometry.boundingBox! + geometry.dispose() + return Math.max(box.max.z, -box.min.z) + } + + test('off (absent), a zero overhang leaves the roof at the walls on both sides', () => { + const node = flat() + // past the wall face only by the shingles' own thickness along the slope + const limit = node.depth / 2 + node.wallThickness / 2 + node.shingleThickness + 0.005 + expect(reachZ(node)).toBeLessThan(limit) + expect(reachZ(flat({ ridgeStep: 1 }))).toBeLessThan(limit) + }) + + test('off, cut to an outline with no overhang, the roof ends at the outline: outside and at a notch', () => { + for (const ridgeStep of [0, 1]) { + const node = segment({ footprint: L, overhang: 0, ridgeStep }) + const geometry = generateRoofSegmentGeometry(node) + const position = geometry.getAttribute('position') + const eps = 0.003 + for (let i = 0; i < position.count; i++) { + const x = position.getX(i) + const z = position.getZ(i) + expect(Math.abs(x)).toBeLessThan(5 + eps) + expect(Math.abs(z)).toBeLessThan(4 + eps) + // nothing over the notch (x > 2, z > 1) + expect(x > 2 + eps && z > 1 + eps).toBe(false) + } + geometry.dispose() + } + }) + + test('on, the roof reaches no farther: the cut only takes away', () => { + expect(reachZ(flat({ squareEaves: true, overhang: 0.6 }))).toBeLessThan( + reachZ(flat({ overhang: 0.6 })) + 0.003, + ) + }) +}) diff --git a/packages/viewer/src/systems/roof/roof-gable-step.test.ts b/packages/viewer/src/systems/roof/roof-gable-step.test.ts new file mode 100644 index 0000000000..6541bb9cce --- /dev/null +++ b/packages/viewer/src/systems/roof/roof-gable-step.test.ts @@ -0,0 +1,318 @@ +// @ts-expect-error — bun:test is provided by the Bun runtime; viewer does not +// depend on @types/bun so the import type is unresolved at compile time. +import { describe, expect, test } from 'bun:test' +import { + getGableRidge, + getRoofSegmentSurfaceY, + getRoofSegmentWallFace, + RoofSegmentNode, +} from '@pascal-app/core' +import * as THREE from 'three' +import { generateRoofSegmentGeometry, getRoofSegmentUndersidePolygons } from './roof-system' + +const DEG = Math.PI / 180 +/** The soffit's material slot (ROOF_SLOT_ROLES: edge, fascia, wall, top, soffit). */ +const ROOF_SOFFIT_SLOT = 4 +const TAN = Math.tan(30 * DEG) +const COS = Math.cos(30 * DEG) + +/** An L: the 10 × 8 rectangle without its +x / +z quarter (x > 2, z > 1). */ +const L: [number, number][] = [ + [-5, -4], + [5, -4], + [5, 1], + [2, 1], + [2, 4], + [-5, 4], +] + +/** 10 × 8, 30° both ways, the ridge across the middle; the −z slope's ridge 1 m higher. */ +function stepped(extra: Partial = {}) { + return RoofSegmentNode.parse({ + type: 'roof-segment', + roofType: 'gable', + width: 10, + depth: 8, + wallHeight: 0.5, + pitch: 30, + ridgeOffset: 4, + ridgeStep: 1, + overhang: 0.5, + wallThickness: 0.2, + deckThickness: 0.1, + shingleThickness: 0.05, + ...extra, + }) +} + +function hit(geometry: THREE.BufferGeometry, from: THREE.Vector3, dir: THREE.Vector3) { + const mesh = new THREE.Mesh(geometry, new THREE.MeshBasicMaterial({ side: THREE.DoubleSide })) + return new THREE.Raycaster(from, dir).intersectObject(mesh).at(0)?.point ?? null +} + +/** Height of the topmost surface straight below (x, ·, z), or null when nothing is there. */ +const topAt = (geometry: THREE.BufferGeometry, x: number, z: number) => + hit(geometry, new THREE.Vector3(x, 50, z), new THREE.Vector3(0, -1, 0))?.y ?? null + +/** The outer skin of a slope rising from `eave` at the z = ±4 wall line. */ +function skin(node: RoofSegmentNode, z: number) { + const ridge = getGableRidge(node)! + const lift = (node.deckThickness + node.shingleThickness) / COS + return z > 0 + ? ridge.frontWallHeight + (4 - z) * TAN + lift + : ridge.backWallHeight + (4 + z) * TAN + lift +} + +describe('gable with a stepped ridge', () => { + test('each slope keeps its own ridge height; the −z eave rides up with it', () => { + const node = stepped() + const ridge = getGableRidge(node)! + expect(ridge.ridgeZ).toBeCloseTo(0, 9) + expect(ridge.height).toBeCloseTo(0.5 + 4 * TAN, 9) + expect(ridge.backHeight).toBeCloseTo(ridge.height + 1, 9) + expect(ridge.backWallHeight).toBeCloseTo(1.5, 9) + expect(getRoofSegmentSurfaceY(node, 0, 2)).toBeCloseTo(0.5 + 2 * TAN, 9) + expect(getRoofSegmentSurfaceY(node, 0, -2)).toBeCloseTo(1.5 + 2 * TAN, 9) + }) + + test('without a step the gable is the same as before', () => { + const plain = generateRoofSegmentGeometry(stepped({ ridgeStep: undefined })) + const zero = generateRoofSegmentGeometry(stepped({ ridgeStep: 0 })) + plain.computeBoundingBox() + zero.computeBoundingBox() + expect(zero.boundingBox!.equals(plain.boundingBox!)).toBe(true) + expect(zero.getAttribute('position').count).toBe(plain.getAttribute('position').count) + plain.dispose() + zero.dispose() + }) + + for (const step of [1, -1]) { + // from the step line toward the lower slope + const toward = step > 0 ? 1 : -1 + // the overhang across the plan at 30° + const reach = 0.5 * COS + + test(`each slope follows its own plane; the higher runs on over the step (step ${step})`, () => { + const node = stepped({ ridgeStep: step }) + const geometry = generateRoofSegmentGeometry(node) + for (const z of [3, 1, -1, -3]) expect(topAt(geometry, 0, z)).toBeCloseTo(skin(node, z), 2) + // past the step line, the higher slope's own plane carried on — upward, in its plane + const over = toward * (reach - 0.05) + expect(topAt(geometry, 0, over)).toBeCloseTo( + skin(node, -toward * 0.001) + (Math.abs(over) + 0.001) * TAN, + 2, + ) + // past the overhang, the lower slope again + const past = toward * (reach + 0.05) + expect(topAt(geometry, 0, past)).toBeCloseTo(skin(node, past), 2) + geometry.dispose() + }) + + test(`the higher slope's run-on ends plumb at the overhang (step ${step})`, () => { + const node = stepped({ ridgeStep: step }) + const ridge = getGableRidge(node)! + const geometry = generateRoofSegmentGeometry(node) + const higherWall = step > 0 ? ridge.backWallHeight : ridge.frontWallHeight + // halfway up the run-on's deck at its end + const y = higherWall + (4 + reach) * TAN + 0.05 + const end = hit( + geometry, + new THREE.Vector3(0, y, toward * 20), + new THREE.Vector3(0, 0, -toward), + ) + expect(end).not.toBeNull() + expect(end!.z).toBeCloseTo(toward * reach, 2) + geometry.dispose() + }) + + test(`with no overhang the higher slope stops at the step line too (step ${step})`, () => { + const node = stepped({ ridgeStep: step, overhang: 0 }) + const geometry = generateRoofSegmentGeometry(node) + expect(topAt(geometry, 0, toward * 0.05)).toBeCloseTo(skin(node, toward * 0.05), 2) + geometry.dispose() + }) + + test(`a step wall closes the gap between the ridges (step ${step})`, () => { + const node = stepped({ ridgeStep: step }) + const ridge = getGableRidge(node)! + const geometry = generateRoofSegmentGeometry(node) + // halfway between the lower slope's top at the ridge and the higher one's underside + const low = Math.min(ridge.height, ridge.backHeight) + 0.15 / COS + const high = Math.max(ridge.height, ridge.backHeight) + const y = (low + high) / 2 + // looking from the lower side toward the higher one, the wall stands on the ridge line + const lowerSide = step > 0 ? 1 : -1 + const wall = hit( + geometry, + new THREE.Vector3(0, y, lowerSide * 20), + new THREE.Vector3(0, 0, -lowerSide), + ) + expect(wall).not.toBeNull() + expect(wall!.z).toBeCloseTo(0, 2) + geometry.dispose() + }) + } + + test('fascia and rake boards follow both slopes', () => { + const node = stepped({ fascia: true }) + const geometry = generateRoofSegmentGeometry(node) + for (const z of [2, -2]) expect(topAt(geometry, 0, z)).toBeCloseTo(skin(node, z), 2) + geometry.dispose() + }) + + test('cut to an outline, the step stays and each slope keeps its height', () => { + const node = stepped({ footprint: L }) + const geometry = generateRoofSegmentGeometry(node) + expect(topAt(geometry, 4, 3)).toBeNull() + expect(topAt(geometry, -3, 3)).toBeCloseTo(skin(node, 3), 2) + expect(topAt(geometry, 4, -3)).toBeCloseTo(skin(node, -3), 2) + expect(topAt(geometry, -3, -0.3)).toBeCloseTo(skin(node, -0.3), 2) + // over the step line the higher slope runs on by its overhang, then the lower one + expect(topAt(geometry, -3, 0.3)).toBeCloseTo(skin(node, -0.001) + 0.301 * TAN, 2) + expect(topAt(geometry, -3, 1)).toBeCloseTo(skin(node, 1), 2) + geometry.dispose() + }) + + test('an outline edge on the step line overhangs only the slope it bounds', () => { + // the higher (−z) side cut away for x > 2 right up to the step line + const notched: [number, number][] = [ + [-5, -4], + [2, -4], + [2, 0], + [5, 0], + [5, 4], + [-5, 4], + ] + const node = stepped({ footprint: notched }) + const geometry = generateRoofSegmentGeometry(node) + // where the higher slope is, it runs on over the step + expect(topAt(geometry, -3, 0.2)).toBeCloseTo(skin(node, -0.001) + 0.201 * TAN, 2) + // over the cut-away part: the lower slope only, nothing of the higher one past the line + expect(topAt(geometry, 4, 0.2)).toBeCloseTo(skin(node, 0.2), 2) + expect(topAt(geometry, 4, -0.2)).toBeNull() + // the higher slope's rake at the notch overhangs it like any rake + expect(topAt(geometry, 2 + 0.3, -2)).toBeCloseTo(skin(node, -2), 2) + expect(topAt(geometry, 2 + 0.6, -2)).toBeNull() + geometry.dispose() + }) + + test('every overhang of both slopes shows the soffit underneath, and nothing hangs below it', () => { + for (const step of [1, -1]) { + const node = stepped({ ridgeStep: step, footprint: L }) + const ridge = getGableRidge(node)! + const geometry = generateRoofSegmentGeometry(node) + const mesh = new THREE.Mesh(geometry, new THREE.MeshBasicMaterial({ side: THREE.DoubleSide })) + const slotOf = (face: number) => + geometry.groups.find((g) => face * 3 >= g.start && face * 3 < g.start + g.count) + ?.materialIndex + const fromBelow = (x: number, z: number) => + new THREE.Raycaster(new THREE.Vector3(x, -20, z), new THREE.Vector3(0, 1, 0)) + .intersectObject(mesh) + .at(0)! + // the eaves, the rakes and the higher slope's run-on over the step + const toward = step > 0 ? 1 : -1 + for (const [x, z, plane] of [ + [-3, 4.2, (zz: number) => ridge.frontWallHeight + (4 - zz) * TAN], + [3, -4.2, (zz: number) => ridge.backWallHeight + (4 + zz) * TAN], + [-5.2, 2, (zz: number) => ridge.frontWallHeight + (4 - zz) * TAN], + [-5.2, -2, (zz: number) => ridge.backWallHeight + (4 + zz) * TAN], + ] as const) { + const hit = fromBelow(x, z) + expect(slotOf(hit.faceIndex!)).toBe(ROOF_SOFFIT_SLOT) + // the deck's underside on the slope's plane: nothing of the deck below it + expect(hit.point.y).toBeCloseTo(plane(z), 2) + } + const over = fromBelow(-3, toward * 0.3) + expect(slotOf(over.faceIndex!)).toBe(ROOF_SOFFIT_SLOT) + geometry.dispose() + } + }) + + for (const step of [1, -1]) { + const toward = step > 0 ? 1 : -1 + const reach = 0.5 * COS + 0.002 + + test(`square eaves: the run-on over the step keeps its soffit on the overhang line (step ${step})`, () => { + const node = stepped({ ridgeStep: step, squareEaves: true }) + const ridge = getGableRidge(node)! + const geometry = generateRoofSegmentGeometry(node) + const higherWall = step > 0 ? ridge.backWallHeight : ridge.frontWallHeight + const soffitY = higherWall + (4 + reach) * TAN + // square to the 30° slope: the end leans back toward the step as it rises + for (const up of [0.02, 0.08]) { + const end = hit( + geometry, + new THREE.Vector3(0, soffitY + up, toward * 20), + new THREE.Vector3(0, 0, -toward), + ) + expect(end).not.toBeNull() + expect(end!.z).toBeCloseTo(toward * reach - toward * up * TAN, 2) + } + geometry.dispose() + }) + + test(`square eaves: the lower slope runs on under the step, cut square from its outer face (step ${step})`, () => { + const node = stepped({ ridgeStep: step, squareEaves: true }) + const geometry = generateRoofSegmentGeometry(node) + const mesh = new THREE.Mesh(geometry, new THREE.MeshBasicMaterial({ side: THREE.DoubleSide })) + // past the gable wall (rake overhang), just past the step line on the higher side + const outer = skin(node, toward * 0.001) + for (const past of [0.03, 0.06]) { + const z = -toward * past + const ys = new THREE.Raycaster(new THREE.Vector3(5.2, 50, z), new THREE.Vector3(0, -1, 0)) + .intersectObject(mesh) + .map((h) => h.point.y) + // the end face, square to the 30° slope from the outer face on the line + const cutY = outer - past / Math.tan(30 * DEG) + expect(ys.some((y) => Math.abs(y - cutY) < 0.006)).toBe(true) + } + geometry.dispose() + }) + + test(`square eaves only take away: the roof reaches as far as plumb (step ${step})`, () => { + const square = generateRoofSegmentGeometry( + stepped({ ridgeStep: step, squareEaves: true, footprint: L }), + ) + const plumb = generateRoofSegmentGeometry(stepped({ ridgeStep: step, footprint: L })) + square.computeBoundingBox() + plumb.computeBoundingBox() + // in plan it reaches exactly as far; in height it only gives way + for (const key of ['min', 'max'] as const) { + for (const axis of ['x', 'z'] as const) { + expect(square.boundingBox![key][axis]).toBeCloseTo(plumb.boundingBox![key][axis], 2) + } + } + expect(square.boundingBox!.max.y).toBeLessThan(plumb.boundingBox!.max.y + 0.003) + expect(square.boundingBox!.min.y).toBeGreaterThan(plumb.boundingBox!.min.y - 0.003) + square.dispose() + plumb.dispose() + }) + } + + test('the underside lies on each slope at its own height', () => { + const node = stepped({ footprint: L }) + const ridge = getGableRidge(node)! + const points = getRoofSegmentUndersidePolygons(node)!.flat() + const front = points.filter((point) => point.z > 0.01) + const back = points.filter((point) => point.z < -0.01) + expect(front.length).toBeGreaterThan(0) + expect(back.length).toBeGreaterThan(0) + for (const point of front) { + expect(point.y).toBeCloseTo(ridge.frontWallHeight + (4 - point.z) * TAN, 4) + } + for (const point of back) { + expect(point.y).toBeCloseTo(ridge.backWallHeight + (4 + point.z) * TAN, 4) + } + }) + + test('the gable end wall rises to both ridges at the step line', () => { + const node = stepped() + const ridge = getGableRidge(node)! + const right = getRoofSegmentWallFace(node, 'right') + const atRidge = right.profile.filter((point) => Math.abs(point[0] - right.length / 2) < 0.01) + expect(atRidge.length).toBe(2) + const tops = atRidge.map((point) => point[1]).sort((a, b) => a - b) + expect(tops[1]! - tops[0]!).toBeCloseTo(1, 2) + expect(tops[1]).toBeLessThan(ridge.backHeight + 0.01) + }) +}) diff --git a/packages/viewer/src/systems/roof/roof-materials.ts b/packages/viewer/src/systems/roof/roof-materials.ts index c4842c041c..0fcb43df6b 100644 --- a/packages/viewer/src/systems/roof/roof-materials.ts +++ b/packages/viewer/src/systems/roof/roof-materials.ts @@ -4,6 +4,7 @@ import { parseMaterialRef, type RoofNode, type RoofSegmentNode, + type RoofSurfaceMaterialRole, type SceneMaterial, type SceneMaterialId, wallAssemblyFinishRef, @@ -20,18 +21,47 @@ import { type SceneMaterials = Record | undefined -// Declared catalog defaults for an unpainted roof, per the 4-slot layout -// (0 wall/trim · 1 deck · 2 interior soffit · 3 shingle top). The wall/trim -// band mirrors the wall kind's default (WALL_SLOT_DEFAULT = concrete-drywall) -// so a roof reads as continuous with the walls below it. -const ROOF_DEFAULT_REFS: [string, string, string, string] = [ +/** + * The material slots of a roof's geometry and the surface role each one is + * painted with: 0 the gables (the roof's own walls), 1 the fascia (eave and + * rake ends of the overhang, fascia boards), 2 the inside, 3 the covering, + * 4 the soffit (the underside of the deck). + */ +export const ROOF_SLOT_ROLES = [ + 'edge', + 'fascia', + 'wall', + 'top', + 'soffit', +] as const satisfies readonly RoofSurfaceMaterialRole[] + +// Declared catalog defaults for an unpainted roof, per slot. The gables, the +// fascia and the soffit mirror the wall kind's default (WALL_SLOT_DEFAULT = +// concrete-drywall) so a roof reads as continuous with the walls below it. +const ROOF_DEFAULT_REFS: readonly string[] = [ + 'library:concrete-drywall', 'library:concrete-drywall', - 'library:preset-softwhite', 'library:preset-softwhite', 'library:roof-terracottatiles', + 'library:concrete-drywall', ] -export type RoofMaterialArray = [THREE.Material, THREE.Material, THREE.Material, THREE.Material] +export type RoofMaterialArray = THREE.Material[] + +/** + * A roof's per-slot material array from a per-role resolver: each slot takes + * its own role's paint, else the slot's fallback — never another role's. + */ +export function buildRoofSlotMaterials( + resolveRole: (role: RoofSurfaceMaterialRole) => THREE.Material | null, + fallback: (slot: number) => THREE.Material, +): RoofMaterialArray { + const byRole = new Map() + return ROOF_SLOT_ROLES.map((role, slot) => { + if (!byRole.has(role)) byRole.set(role, resolveRole(role)) + return byRole.get(role) ?? fallback(slot) + }) +} const roofMaterialArrayCache = new Map() @@ -108,9 +138,9 @@ export function getRoofMaterialArray( wallCladdingRef: string | null = null, sceneMaterials?: SceneMaterials, ): RoofMaterialArray | null { - const top = getEffectiveRoofSurfaceMaterial(node, 'top') - const edge = getEffectiveRoofSurfaceMaterial(node, 'edge') - const wall = getEffectiveRoofSurfaceMaterial(node, 'wall') + const specs = new Map( + ROOF_SLOT_ROLES.map((role) => [role, getEffectiveRoofSurfaceMaterial(node, role)] as const), + ) const cacheKey = JSON.stringify({ shading, @@ -118,25 +148,21 @@ export function getRoofMaterialArray( colorPreset, sceneTheme, wallCladdingRef, - top: getSurfaceMaterialSignature(top, sceneMaterials), - edge: getSurfaceMaterialSignature(edge, sceneMaterials), - wall: getSurfaceMaterialSignature(wall, sceneMaterials), + roles: [...specs.values()].map((spec) => getSurfaceMaterialSignature(spec, sceneMaterials)), }) const cached = roofMaterialArrayCache.get(cacheKey) if (cached) return cached - // Themed role colours: roof top/edge use the 'roof' role, the soffit/underside - // uses 'ceiling'. These also fill any untextured slot so an untextured roof is - // theme-coloured regardless of the textures toggle (no more white default). + // Themed role colours: the covering, gables, fascia and soffit use the + // 'roof' role, the inside uses 'ceiling'. These also fill any untextured + // slot so an untextured roof is theme-coloured regardless of the textures + // toggle (no more white default). const roofMaterial = createSurfaceRoleMaterial('roof', colorPreset, undefined, sceneTheme) const ceilingMaterial = createSurfaceRoleMaterial('ceiling', colorPreset, undefined, sceneTheme) - const roleArray: RoofMaterialArray = [ - roofMaterial, - ceilingMaterial, - ceilingMaterial, - roofMaterial, - ] + const roleArray: RoofMaterialArray = ROOF_SLOT_ROLES.map((role) => + role === 'wall' ? ceilingMaterial : roofMaterial, + ) // Textures-off (monochrome) is the guaranteed escape hatch: themed role // colours, no catalog finishes. @@ -146,38 +172,37 @@ export function getRoofMaterialArray( } // Textures-on default appearance: catalog finishes per slot (terracotta - // shingle, soft-white deck/soffit, wall-coloured trim). Used both when the - // roof is unpainted and to fill any individual unpainted slot below. - const defaultArray: RoofMaterialArray = [ - resolveSlotDefaultMaterial(wallCladdingRef ?? ROOF_DEFAULT_REFS[0], shading), - resolveSlotDefaultMaterial(ROOF_DEFAULT_REFS[1], shading), - resolveSlotDefaultMaterial(ROOF_DEFAULT_REFS[2], shading), - resolveSlotDefaultMaterial(ROOF_DEFAULT_REFS[3], shading), - ] - - const resolve = (spec: typeof top) => - createResolvedMaterial(spec.material, spec.materialPreset, sceneMaterials, shading) - const topMaterial = resolve(top) - const edgeMaterial = resolve(edge) - const wallMaterial = resolve(wall) - - if (!(topMaterial || edgeMaterial || wallMaterial)) { + // shingle, soft-white inside, wall-coloured gables, fascia and soffit). + // Used both when the roof is unpainted and to fill any unpainted slot below. + const defaultArray: RoofMaterialArray = ROOF_DEFAULT_REFS.map((ref, slot) => + resolveSlotDefaultMaterial( + slot === 0 || slot === 1 || slot === 4 ? (wallCladdingRef ?? ref) : ref, + shading, + ), + ) + + const resolved = new Map( + [...specs].map( + ([role, spec]) => + [ + role, + createResolvedMaterial(spec.material, spec.materialPreset, sceneMaterials, shading), + ] as const, + ), + ) + + if (![...resolved.values()].some(Boolean)) { roofMaterialArrayCache.set(cacheKey, defaultArray) return defaultArray } // Each slot resolves to its own role only, then the declared default — never - // another role. Cross-role fallback here used to splatter a single painted - // surface (e.g. the edge) across the shingle and soffit slots. The legacy - // catch-all still fills every role because `getEffectiveRoofSurfaceMaterial` - // returns it for top/edge/wall alike. - const materialArray: RoofMaterialArray = [ - edgeMaterial ?? defaultArray[0], - wallMaterial ?? defaultArray[1], - wallMaterial ?? defaultArray[2], - topMaterial ?? defaultArray[3], - ] - + // another role. The legacy catch-all still fills every role because + // `getEffectiveRoofSurfaceMaterial` returns it for every role alike. + const materialArray = buildRoofSlotMaterials( + (role) => resolved.get(role) ?? null, + (slot) => defaultArray[slot]!, + ) roofMaterialArrayCache.set(cacheKey, materialArray) return materialArray } diff --git a/packages/viewer/src/systems/roof/roof-paint-slots.test.ts b/packages/viewer/src/systems/roof/roof-paint-slots.test.ts new file mode 100644 index 0000000000..392e3009ea --- /dev/null +++ b/packages/viewer/src/systems/roof/roof-paint-slots.test.ts @@ -0,0 +1,87 @@ +// @ts-expect-error — bun:test is provided by the Bun runtime; viewer does not +// depend on @types/bun so the import type is unresolved at compile time. +import { describe, expect, test } from 'bun:test' +import { RoofNode, RoofSegmentNode } from '@pascal-app/core' +import * as THREE from 'three' +import { getRoofMaterialArray, ROOF_SLOT_ROLES } from './roof-materials' +import { generateRoofSegmentGeometry } from './roof-system' + +const segment = RoofSegmentNode.parse({ + type: 'roof-segment', + roofType: 'gable', + width: 8, + depth: 6, + wallHeight: 1, + pitch: 30, + overhang: 0.5, + wallThickness: 0.2, + deckThickness: 0.1, + shingleThickness: 0.05, +}) + +/** The slot of the first face a ray meets. */ +function slotHit(geometry: THREE.BufferGeometry, from: THREE.Vector3, direction: THREE.Vector3) { + const mesh = new THREE.Mesh( + geometry, + ROOF_SLOT_ROLES.map(() => new THREE.MeshBasicMaterial({ side: THREE.DoubleSide })), + ) + const hit = new THREE.Raycaster(from, direction.normalize()).intersectObject(mesh).at(0) + return hit?.face?.materialIndex +} + +describe('roof paint slots', () => { + const geometry = generateRoofSegmentGeometry(segment) + const role = (slot: number | undefined) => + slot === undefined ? undefined : ROOF_SLOT_ROLES[slot] + + test('the covering, the soffit, the fascia and the gable are each their own surface', () => { + // from above onto the slope + expect( + role(slotHit(geometry, new THREE.Vector3(0, 20, 1.5), new THREE.Vector3(0, -1, 0))), + ).toBe('top') + // from below into the overhang, outside the wall + expect( + role(slotHit(geometry, new THREE.Vector3(0, -20, 3.3), new THREE.Vector3(0, 1, 0))), + ).toBe('soffit') + // level onto the eave end, between the soffit edge and the shingle top + expect( + role(slotHit(geometry, new THREE.Vector3(0, 0.75, 10), new THREE.Vector3(0, 0, -1))), + ).toBe('fascia') + // from the side onto the gable above the plate + expect( + role(slotHit(geometry, new THREE.Vector3(20, 1.6, 0), new THREE.Vector3(-1, 0, 0))), + ).toBe('edge') + }) + + test('each surface takes its own paint; an unpainted soffit and fascia follow the gable', () => { + const paint = (color: string) => ({ preset: 'custom' as const, properties: { color } }) + const red = paint('#ff0000') + const blue = paint('#0000ff') + const green = paint('#00ff00') + const roof = RoofNode.parse({ + type: 'roof', + edgeMaterial: red, + soffitMaterial: blue, + fasciaMaterial: green, + }) + const materials = getRoofMaterialArray(roof, 'rendered', true)! + const colour = (slotRole: string) => + ( + materials[ + ROOF_SLOT_ROLES.indexOf(slotRole as (typeof ROOF_SLOT_ROLES)[number]) + ] as THREE.MeshStandardMaterial + ).color.getHexString() + expect(colour('edge')).toBe('ff0000') + expect(colour('soffit')).toBe('0000ff') + expect(colour('fascia')).toBe('00ff00') + + const older = getRoofMaterialArray(RoofNode.parse({ type: 'roof', edgeMaterial: red }))! + for (const slotRole of ['edge', 'soffit', 'fascia'] as const) { + expect( + ( + older[ROOF_SLOT_ROLES.indexOf(slotRole)] as THREE.MeshStandardMaterial + ).color.getHexString(), + ).toBe('ff0000') + } + }) +}) diff --git a/packages/viewer/src/systems/roof/roof-system.test.ts b/packages/viewer/src/systems/roof/roof-system.test.ts index e0773d4bcc..9c9db2588f 100644 --- a/packages/viewer/src/systems/roof/roof-system.test.ts +++ b/packages/viewer/src/systems/roof/roof-system.test.ts @@ -89,8 +89,6 @@ describe('roof system shed geometry', () => { const normal = new THREE.Vector3() const edge = new THREE.Vector3() - expect(geometry.groups.some((group) => group.materialIndex === 1)).toBe(false) - for (const group of geometry.groups) { for (let i = group.start; i < group.start + group.count; i += 3) { const ia = index!.getX(i) @@ -101,7 +99,8 @@ describe('roof system shed geometry', () => { c.fromBufferAttribute(position, ic) normal.subVectors(b, a).cross(edge.subVectors(c, a)).normalize() - if (group.materialIndex === 0 || group.materialIndex === 3) { + // the deck and shingle ends are fascia (slot 1), the covering slot 3 + if (group.materialIndex === 1 || group.materialIndex === 3) { roofSideX.push(Math.abs(a.x), Math.abs(b.x), Math.abs(c.x)) } diff --git a/packages/viewer/src/systems/roof/roof-system.tsx b/packages/viewer/src/systems/roof/roof-system.tsx index 1ace6ca742..f600615975 100644 --- a/packages/viewer/src/systems/roof/roof-system.tsx +++ b/packages/viewer/src/systems/roof/roof-system.tsx @@ -5,8 +5,10 @@ import { getDutchEndSlopeFaces, getDutchRoofShapeMetrics, getEffectiveNode, + getGableRidge, getRoofModuleFaces, getRoofPlanBounds, + getRoofSegmentBackSlopeTwin, getRoofSegmentSurfaceY, getRoofShapeInsets, getRoofShapeRatios, @@ -17,24 +19,29 @@ import { normalizeRoofSegmentTrim, pointInPolygon2D, ROOF_SHAPE_DEFAULTS, + type RoofModuleInput, type RoofNode, type RoofPlanBounds, type RoofSegmentNode, type RoofType, + readGableRidgeStep, roofOverlapEntryOwns, roofPlanBoundsOverlap, sceneRegistry, unionPolygons, useLiveNodeOverrides, useScene, + withRoofSegmentGableBack, } from '@pascal-app/core' import { useFrame } from '@react-three/fiber' import * as THREE from 'three' import { mergeGeometries, mergeVertices } from 'three/examples/jsm/utils/BufferGeometryUtils.js' -import { ADDITION, Brush, Evaluator, SUBTRACTION } from 'three-bvh-csg' +import { ADDITION, Brush, Evaluator, INTERSECTION, SUBTRACTION } from 'three-bvh-csg' import { computeBoundsTree } from 'three-mesh-bvh' import { applyWorldScaleBoxUVs } from '../../lib/box-uv' import { ensureRenderableGeometryAttributes, subtractCsgBrush } from '../../lib/csg-utils' +import { runRoofClipFrame } from './roof-clip' +import { ROOF_SLOT_ROLES } from './roof-materials' function csgGeometry(brush: Brush): THREE.BufferGeometry { return brush.geometry as unknown as THREE.BufferGeometry @@ -257,6 +264,7 @@ export const RoofSystem = () => { useLiveNodeOverrides((s) => s.overrides) useFrame(() => { + runRoofClipFrame() // Clear stale pending updates when the scene is unloaded if (rootNodeIds.length === 0) { pendingRoofUpdates.clear() @@ -728,6 +736,7 @@ function updateMergedRoofGeometry( [dummyMats[1], 1], [dummyMats[2], 2], [dummyMats[3], 3], + [dummyMats[4], 4], ]) for (const g of resultGeo.groups) { @@ -827,16 +836,29 @@ export const roofCsgDummyMats: [ THREE.MeshBasicMaterial, THREE.MeshBasicMaterial, THREE.MeshBasicMaterial, + THREE.MeshBasicMaterial, ] = [ new THREE.MeshBasicMaterial(), new THREE.MeshBasicMaterial(), new THREE.MeshBasicMaterial(), new THREE.MeshBasicMaterial(), + new THREE.MeshBasicMaterial(), ] // Internal alias kept so the surrounding file's many call sites don't churn. const dummyMats = roofCsgDummyMats -export const ROOF_MATERIAL_SLOT_COUNT = 4 +export const ROOF_MATERIAL_SLOT_COUNT = ROOF_SLOT_ROLES.length +const ROOF_FASCIA_MATERIAL_INDEX = 1 +/** Metres the roof's own walls stop under its deck (see the 'wall' volume layer). */ +const ROOF_WALL_UNDER_DECK = 0.001 +const ROOF_SOFFIT_MATERIAL_INDEX = 4 + +/** A deck or shingle face of a hand-built slab: covering on top, soffit beneath, fascia at the ends. */ +function roofSlabFaceSlot(normal: THREE.Vector3): number { + if (normal.y > SHINGLE_SURFACE_EPSILON) return 3 + if (normal.y < -SHINGLE_SURFACE_EPSILON) return ROOF_SOFFIT_MATERIAL_INDEX + return ROOF_FASCIA_MATERIAL_INDEX +} type RoofSegmentBrushSet = { deckSlab: Brush @@ -1024,8 +1046,6 @@ function remapDutchRakeBoardMaterials(geometry: THREE.BufferGeometry) { } const SHINGLE_SURFACE_EPSILON = 0.02 -const RAKE_FACE_NORMAL_EPSILON = 0.3 -const RAKE_FACE_ALIGNMENT_EPSILON = 0.35 const TRIM_CUT_EPSILON = 0.002 const ROOF_EDGE_MATERIAL_INDEX = 0 const ROOF_INSET_WALL_MATERIAL_INDEX = 2 @@ -1124,10 +1144,26 @@ function hasSegmentTrim(node: RoofSegmentNode): boolean { // slots. Accessories still clamp the slot via `useSegmentTrimClippedGeometry` // when they expose fewer material slots. const TRIM_CUT_MATERIAL_SLOT = 0 -function assignTrimCutterSlot(geometry: THREE.BufferGeometry): void { +function assignTrimCutterSlot( + geometry: THREE.BufferGeometry, + slot: number = TRIM_CUT_MATERIAL_SLOT, +): void { geometry.clearGroups() const count = geometry.index ? geometry.index.count : geometry.getAttribute('position').count - geometry.addGroup(0, count, TRIM_CUT_MATERIAL_SLOT) + geometry.addGroup(0, count, slot) +} + +/** The same cutter, its faces in another slot: a cut through the deck and shingles shows their ends. */ +function withCutterSlot(cut: Brush, slot: number): Brush { + const geometry = cut.geometry.clone() + assignTrimCutterSlot(geometry, slot) + computeGeometryBoundsTree(geometry) + const brush = new Brush(geometry, dummyMats) + brush.position.copy(cut.position) + brush.quaternion.copy(cut.quaternion) + brush.scale.copy(cut.scale) + brush.updateMatrixWorld() + return brush } function buildTrimCutBrush( @@ -1216,11 +1252,17 @@ function buildDiagonalTrimCutBrush( } function subtractCutFromSegmentBrushes(brushes: RoofSegmentBrushSet, cut: Brush) { - for (const key of ['shinSlab', 'deckSlab', 'wallBrush', 'innerBrush'] as const) { - const next = csgEvaluator.evaluate(brushes[key], cut, SUBTRACTION) as Brush - brushes[key].geometry.dispose() - prepareBrushForCSG(next) - brushes[key] = next + const slabCut = withCutterSlot(cut, ROOF_FASCIA_MATERIAL_INDEX) + try { + for (const key of ['shinSlab', 'deckSlab', 'wallBrush', 'innerBrush'] as const) { + const cutter = key === 'shinSlab' || key === 'deckSlab' ? slabCut : cut + const next = csgEvaluator.evaluate(brushes[key], cutter, SUBTRACTION) as Brush + brushes[key].geometry.dispose() + prepareBrushForCSG(next) + brushes[key] = next + } + } finally { + slabCut.geometry.dispose() } } @@ -1255,7 +1297,13 @@ function buildSegmentTrimCutBrushes(segment: RoofSegmentNode): Brush[] { const minZ = -segment.depth / 2 - extra const maxZ = segment.depth / 2 + extra const minY = -2 - const maxY = segment.wallHeight + activeRh + segment.deckThickness + segment.shingleThickness + 2 + const maxY = + segment.wallHeight + + activeRh + + Math.max(0, readGableRidgeStep(segment)) + + segment.deckThickness + + segment.shingleThickness + + 2 const cuts: Brush[] = [] @@ -1325,6 +1373,604 @@ function buildSegmentTrimCutBrushes(segment: RoofSegmentNode): Brush[] { return cuts } +type PlanPoint = [number, number] + +function planSignedArea(ring: readonly PlanPoint[]) { + let area = 0 + for (let i = 0; i < ring.length; i++) { + const [x0, z0] = ring[i]! + const [x1, z1] = ring[(i + 1) % ring.length]! + area += x0 * z1 - x1 * z0 + } + return area / 2 +} + +/** Part of a plan ring where `side(point) >= 0`. */ +function clipPlanRing(ring: readonly PlanPoint[], side: (point: PlanPoint) => number): PlanPoint[] { + const result: PlanPoint[] = [] + for (let i = 0; i < ring.length; i++) { + const current = ring[i]! + const next = ring[(i + 1) % ring.length]! + const a = side(current) + const b = side(next) + if (a >= 0) result.push(current) + if (a >= 0 !== b >= 0) { + const t = a / (a - b) + result.push([ + current[0] + (next[0] - current[0]) * t, + current[1] + (next[1] - current[1]) * t, + ]) + } + } + return result +} + +/** + * The parts of a plan ring on one side of the line z = `z0` (`side` +1: z > z0, + * −1: z < z0), each its own ring. A concave ring can fall apart into several. + */ +function splitPlanRingByLine(ring: readonly PlanPoint[], z0: number, side: 1 | -1): PlanPoint[][] { + const eps = 1e-9 + const r = planSignedArea(ring) > 0 ? [...ring] : [...ring].reverse() + const inside = (p: PlanPoint) => side * (p[1] - z0) > eps + if (r.every(inside)) return [r] + const start = r.findIndex((p) => !inside(p)) + if (start < 0) return [r] + const cross = (a: PlanPoint, b: PlanPoint): PlanPoint => { + const t = (z0 - a[1]) / (b[1] - a[1]) + return [a[0] + (b[0] - a[0]) * t, z0] + } + // chains through the kept side, each from the line back to the line + const chains: PlanPoint[][] = [] + let chain: PlanPoint[] | null = null + for (let k = 0; k < r.length; k++) { + const a = r[(start + k) % r.length]! + const b = r[(start + k + 1) % r.length]! + const ina = inside(a) + const inb = inside(b) + if (!ina && inb) chain = [cross(a, b), b] + else if (ina && inb) chain?.push(b) + else if (ina && !inb && chain) { + chain.push(cross(a, b)) + chains.push(chain) + chain = null + } + } + // Along the line the boundary runs with the kept side on its left: toward + // +x for z > z0, −x for z < z0. Each chain's end joins the nearest start + // that way on. + const used = new Set() + const rings: PlanPoint[][] = [] + for (let first = 0; first < chains.length; first++) { + if (used.has(first)) continue + used.add(first) + const out: PlanPoint[] = [...chains[first]!] + for (let guard = 0; guard < chains.length; guard++) { + const endX = out[out.length - 1]![0] + let next = -1 + let best = Number.POSITIVE_INFINITY + for (let c = 0; c < chains.length; c++) { + if (c !== first && used.has(c)) continue + const gap = side * (chains[c]![0]![0] - endX) + if (gap >= -1e-9 && gap < best) { + best = gap + next = c + } + } + if (next < 0 || next === first) break + used.add(next) + out.push(...chains[next]!) + } + if (out.length >= 3 && Math.abs(planSignedArea(out)) > 1e-9) rings.push(out) + } + return rings +} + +/** + * A plan ring pushed outward (negative: inward) by `distance`, edges kept + * parallel. Repeated points (a pulled canopy edge can leave one) are dropped + * first: an edge of no length has no direction to push. + */ +export function offsetPlanRing(ring: readonly PlanPoint[], distance: number): PlanPoint[] { + const clean = ring.filter((point, i) => { + const next = ring[(i + 1) % ring.length]! + return Math.hypot(next[0] - point[0], next[1] - point[1]) > 1e-9 + }) + if (clean.length < 3) return [...ring] + if (distance > 0 && isAxisRing(clean)) return growAxisRing(clean, distance) + const ccw = planSignedArea(clean) > 0 + const count = clean.length + const lines = clean.map((point, i) => { + const next = clean[(i + 1) % count]! + const dx = next[0] - point[0] + const dz = next[1] - point[1] + const length = Math.hypot(dx, dz) + // Outward normal: right of the direction for a counter-clockwise (x, z) ring. + const nx = (ccw ? dz : -dz) / length + const nz = (ccw ? -dx : dx) / length + return { x: point[0] + nx * distance, z: point[1] + nz * distance, dx, dz } + }) + return clean.map((point, i): PlanPoint => { + const a = lines[(i - 1 + count) % count]! + const b = lines[i]! + const denominator = a.dx * b.dz - a.dz * b.dx + if (Math.abs(denominator) < 1e-12) return [b.x, b.z] + const t = ((b.x - a.x) * b.dz - (b.z - a.z) * b.dx) / denominator + return [a.x + a.dx * t, a.z + a.dz * t] + }) +} + +/** Whether every edge of a ring runs along x or along z. */ +function isAxisRing(ring: readonly PlanPoint[]): boolean { + return ring.every((point, i) => { + const next = ring[(i + 1) % ring.length]! + return Math.abs(next[0] - point[0]) < 1e-9 || Math.abs(next[1] - point[1]) < 1e-9 + }) +} + +/** + * An axis-aligned ring grown outward by `distance`, as the edge-by-edge push + * would grow it, but sound where that push folds over: a notch or a slot + * narrower than twice the distance closes instead of turning inside out. + * The grown ring is everything within `distance` of the ring along x and z + * (its mitred corners are square), worked out on the grid of the pushed + * coordinates; a courtyard it would leave is filled. + */ +function growAxisRing(ring: readonly PlanPoint[], distance: number): PlanPoint[] { + const unique = (values: number[]) => + [...new Set(values.map((v) => Math.round(v * 1e9) / 1e9))].sort((a, b) => a - b) + const xs = unique(ring.flatMap(([x]) => [x - distance, x + distance])) + const zs = unique(ring.flatMap(([, z]) => [z - distance, z + distance])) + const inside = (x: number, z: number) => { + let hit = false + for (let i = 0, j = ring.length - 1; i < ring.length; j = i++) { + const [xi, zi] = ring[i]! + const [xj, zj] = ring[j]! + if (zi > z !== zj > z && x < ((xj - xi) * (z - zi)) / (zj - zi) + xi) hit = !hit + } + return hit + } + // a cell is covered when the square of half-size `distance` about its + // centre meets the ring's area: the centre is inside, or an edge crosses it + const near = (x: number, z: number) => { + if (inside(x, z)) return true + const d = distance - 1e-9 + for (let i = 0; i < ring.length; i++) { + const [ax, az] = ring[i]! + const [bx, bz] = ring[(i + 1) % ring.length]! + if ( + Math.max(ax, bx) >= x - d && + Math.min(ax, bx) <= x + d && + Math.max(az, bz) >= z - d && + Math.min(az, bz) <= z + d + ) { + return true + } + } + return false + } + const nx = xs.length - 1 + const nz = zs.length - 1 + const covered: boolean[] = [] + for (let j = 0; j < nz; j++) { + for (let i = 0; i < nx; i++) { + covered.push(near((xs[i]! + xs[i + 1]!) / 2, (zs[j]! + zs[j + 1]!) / 2)) + } + } + const at = (i: number, j: number) => i >= 0 && j >= 0 && i < nx && j < nz && covered[j * nx + i]! + // the boundary as directed edges between grid nodes, the covered cells on + // their left (x right, z down: counter-clockwise in the plan's signed area) + const next = new Map() + const key = (i: number, j: number) => `${i},${j}` + const link = (a: [number, number], b: [number, number]) => { + const list = next.get(key(...a)) ?? [] + list.push(b) + next.set(key(...a), list) + } + for (let j = 0; j < nz; j++) { + for (let i = 0; i < nx; i++) { + if (!at(i, j)) continue + if (!at(i, j - 1)) link([i, j], [i + 1, j]) + if (!at(i + 1, j)) link([i + 1, j], [i + 1, j + 1]) + if (!at(i, j + 1)) link([i + 1, j + 1], [i, j + 1]) + if (!at(i - 1, j)) link([i, j + 1], [i, j]) + } + } + // chain the loops; the outer one encloses the most + let best: PlanPoint[] = [] + let bestArea = 0 + for (const start of [...next.keys()]) { + while ((next.get(start)?.length ?? 0) > 0) { + const loop: [number, number][] = [] + let current = start.split(',').map(Number) as [number, number] + let previous: [number, number] | null = null + do { + loop.push(current) + const options = next.get(key(...current))! + // at a node where two corners touch, turn the tightest way + let pick = 0 + if (options.length > 1 && previous) { + const dx = current[0] - previous[0] + const dz = current[1] - previous[1] + pick = options.findIndex(([a, b]) => dx * (b - current[1]) - dz * (a - current[0]) > 0) + if (pick < 0) pick = 0 + } + const [following] = options.splice(pick, 1) + previous = current + current = following! + } while (key(...current) !== key(...loop[0]!) && loop.length <= covered.length * 4) + const points = loop.map(([i, j]): PlanPoint => [xs[i]!, zs[j]!]) + const area = Math.abs(planSignedArea(points)) + if (area > bestArea) { + bestArea = area + best = points + } + } + } + // straight runs as one edge + const corners = best.filter((point, i) => { + const a = best[(i - 1 + best.length) % best.length]! + const b = best[(i + 1) % best.length]! + return ( + Math.abs((point[0] - a[0]) * (b[1] - point[1]) - (point[1] - a[1]) * (b[0] - point[0])) > + 1e-12 + ) + }) + // the ring's own winding + return planSignedArea(corners) > 0 === planSignedArea(ring) > 0 ? corners : corners.reverse() +} + +function readSegmentFootprint(segment: RoofSegmentNode): PlanPoint[] | null { + return readPlanRing(segment.footprint) +} + +/** What the covering reaches: the canopy outline if pulled out, else the walls' outline. */ +function readSegmentCover(segment: RoofSegmentNode): PlanPoint[] | null { + return readPlanRing(segment.coverFootprint) ?? readSegmentFootprint(segment) +} + +function readPlanRing(footprint: RoofSegmentNode['footprint']): PlanPoint[] | null { + if (!Array.isArray(footprint) || footprint.length < 3) return null + const points = footprint.filter( + (point): point is PlanPoint => + Array.isArray(point) && Number.isFinite(point[0]) && Number.isFinite(point[1]), + ) + return points.length === footprint.length && Math.abs(planSignedArea(points)) > 1e-6 + ? points + : null +} + +/** Vertical prism over a plan ring, segment-local, tall enough for the whole segment. */ +function buildFootprintPrismBrush( + ring: readonly PlanPoint[], + minY: number, + maxY: number, + shear?: THREE.Matrix4, + slot: number = TRIM_CUT_MATERIAL_SLOT, +): Brush { + const shape = new THREE.Shape() + shape.moveTo(ring[0]![0], -ring[0]![1]) + for (let i = 1; i < ring.length; i++) shape.lineTo(ring[i]![0], -ring[i]![1]) + shape.closePath() + const geometry = new THREE.ExtrudeGeometry(shape, { depth: maxY - minY, bevelEnabled: false }) + geometry.rotateX(-Math.PI / 2) + geometry.translate(0, minY, 0) + if (shear) { + geometry.applyMatrix4(shear) + geometry.computeVertexNormals() + } + assignTrimCutterSlot(geometry, slot) + ensureRenderableGeometryAttributes(geometry) + computeGeometryBoundsTree(geometry) + const brush = new Brush(geometry, dummyMats) + brush.updateMatrixWorld() + return brush +} + +/** Square eaves (see cutSlabsSquare): on, and a sloped roof that is not a cone. */ +function hasSquareEaves(node: RoofSegmentNode): boolean { + return ( + node.squareEaves === true && + node.roofType !== 'conical' && + getSegmentSlopeFrame(node).activeRh > 0 + ) +} + +/** Whether either eave of the segment is set below its plate (y = 0). */ +function hasEaveBelowPlate(node: RoofSegmentNode): boolean { + const ridge = getGableRidge(node) + return ridge ? Math.min(ridge.frontWallHeight, ridge.backWallHeight) < 0 : node.wallHeight < 0 +} + +/** The outer face of the walls a segment stands on: its outline, else its rectangle. */ +function segmentWallOutline(node: RoofSegmentNode): PlanPoint[] { + const footprint = readSegmentFootprint(node) + if (footprint) return footprint + const x = node.width / 2 + node.wallThickness / 2 + const z = node.depth / 2 + node.wallThickness / 2 + return [ + [-x, -z], + [x, -z], + [x, z], + [-x, z], + ] +} + +/** + * With an eave below the plate, the roof's own walls end at the plate — below + * it they would only double the walls of the floor. With `cutAtWallTop` the + * deck and shingles under the plate inside the walls go too; otherwise they + * stay (a ceiling that follows the slope). Beyond the walls the eave + * overhangs as built. + */ +function clipSegmentBrushesBelowPlate(brushes: RoofSegmentBrushSet, node: RoofSegmentNode) { + if (!hasEaveBelowPlate(node)) return + const slabs = node.cutAtWallTop === true + const depthBelow = 50 + const outline = segmentWallOutline(node) + const reach = Math.max(node.width, node.depth) + 50 + const box: PlanPoint[] = [ + [-reach, -reach], + [reach, -reach], + [reach, reach], + [-reach, reach], + ] + const cuts: Array< + [keyof Pick, boolean] + > = [ + ['wallBrush', true], + ['innerBrush', true], + ] + if (slabs) cuts.push(['shinSlab', false], ['deckSlab', false]) + for (const [key, everywhere] of cuts) { + const cutter = buildFootprintPrismBrush( + everywhere ? box : outline, + -depthBelow, + 0, + undefined, + everywhere ? TRIM_CUT_MATERIAL_SLOT : ROOF_SOFFIT_MATERIAL_INDEX, + ) + try { + const next = csgEvaluator.evaluate(brushes[key], cutter, SUBTRACTION) as Brush + brushes[key].geometry.dispose() + prepareBrushForCSG(next) + brushes[key] = next + } catch (e) { + console.error('Roof below-plate CSG failed:', e) + } finally { + cutter.geometry.dispose() + } + } +} + +/** + * Cuts a segment to its outline: shingles and deck to the outline pushed out + * by the eave extension, the wall shell between the outline and the outline + * pulled in by the wall thickness — the roof's own walls (gables) stand + * flush with the outer face of the walls below. + */ +function clipSegmentBrushesToFootprint( + brushes: RoofSegmentBrushSet, + segment: RoofSegmentNode, + { slabs = true }: { slabs?: boolean } = {}, +) { + const footprint = readSegmentFootprint(segment) + const cover = readSegmentCover(segment) + if (!(footprint || cover)) return + const { activeRh, cosTheta } = getSegmentSlopeFrame(segment) + const minY = -10 + const maxY = + segment.wallHeight + + activeRh + + Math.max(0, readGableRidgeStep(segment)) + + segment.deckThickness + + segment.shingleThickness + + 10 + const half = segment.wallThickness / 2 + // The outline is the outer face of the walls: the covering overhangs it by + // the overhang alone, and with none it ends flush with that face. + const roofExtension = segment.overhang * cosTheta + TRIM_CUT_EPSILON + const clips: Array< + [ + keyof Pick, + readonly PlanPoint[], + number, + ] + > = [] + // The walls' outline is the outer face of the walls below: the gable stands + // inside it, flush with that face. Over a canopy the roof has no walls. + if (footprint) clips.push(['wallBrush', footprint, 0], ['innerBrush', footprint, -2 * half]) + // The covering follows what it covers: plumb here, or square to each slope + // (square eaves, cutSlabsSquare). + if (cover && slabs && !hasSquareEaves(segment)) { + clips.push(['shinSlab', cover, roofExtension], ['deckSlab', cover, roofExtension]) + } + for (const [key, ring, distance] of clips) { + const slab = key === 'shinSlab' || key === 'deckSlab' + const prism = buildFootprintPrismBrush( + offsetPlanRing(ring, distance), + minY, + maxY, + undefined, + slab ? ROOF_FASCIA_MATERIAL_INDEX : TRIM_CUT_MATERIAL_SLOT, + ) + try { + const next = csgEvaluator.evaluate(brushes[key], prism, INTERSECTION) as Brush + brushes[key].geometry.dispose() + prepareBrushForCSG(next) + brushes[key] = next + } catch (e) { + console.error('Roof footprint CSG failed:', e) + } finally { + prism.geometry.dispose() + } + } +} + +/** Outward normal of a module face (counter-clockwise seen from outside), or null if degenerate. */ +function faceNormal(face: readonly { x: number; y: number; z: number }[]): THREE.Vector3 | null { + const normal = new THREE.Vector3() + for (let index = 0; index < face.length; index++) { + const current = face[index]! + const next = face[(index + 1) % face.length]! + normal.x += (current.y - next.y) * (current.z + next.z) + normal.y += (current.z - next.z) * (current.x + next.x) + normal.z += (current.x - next.x) * (current.y + next.y) + } + return normal.length() > 1e-9 ? normal.normalize() : null +} + +/** + * Square eaves: cuts the deck and shingles square to each slope, the way + * boards are cut, without moving how far the roof reaches. Over every slope + * the outline (pushed out by the overhang) is swept plumb, and along the + * slope's normal twice — held at the roof's outer face and held at the + * soffit — and what falls outside any sweep goes. So every edge keeps its farthest point on + * the overhang line: an eave its outer face (the soffit draws back), a high + * edge its soffit (the face draws back); an edge along the fall line stays + * plumb, which is square to the slope as well. + */ +function cutSlabsSquare( + slabs: Pick, + segment: RoofSegmentNode, + rings: readonly (readonly PlanPoint[])[], + faces: readonly (readonly { x: number; y: number; z: number }[])[], +) { + const far = 50 + const thickness = segment.deckThickness + segment.shingleThickness + // Where the square cut holds the outer face: on the overhang line, but no + // nearer than the covering's lean, so the soffit never draws back inside + // the wall the roof rests on. The plumb cut below still stops everything on + // the overhang line: with little or no overhang the end comes out plumb. + const outerReach = (normal: THREE.Vector3) => + Math.max(segment.overhang * normal.y, thickness * Math.sqrt(Math.max(0, 1 - normal.y ** 2))) + // Plumb on the overhang line first — nothing reaches farther than with plumb + // eaves (the gentlest slope's overhang across the plan is the widest). + let widest = 0 + for (const face of faces) { + const n = faceNormal(face) + if (n && n.y >= 0.05) widest = Math.max(widest, segment.overhang * n.y) + } + let plumb: Brush | null = null + for (const ring of rings) { + const prism = buildFootprintPrismBrush( + offsetPlanRing(ring, widest + TRIM_CUT_EPSILON), + -far, + far, + undefined, + ROOF_FASCIA_MATERIAL_INDEX, + ) + if (plumb) { + const merged = csgEvaluator.evaluate(plumb, prism, ADDITION) as Brush + prepareBrushForCSG(merged) + plumb.geometry.dispose() + prism.geometry.dispose() + plumb = merged + } else plumb = prism + } + if (plumb) { + for (const key of ['shinSlab', 'deckSlab'] as const) { + const next = csgEvaluator.evaluate(slabs[key], plumb, INTERSECTION) as Brush + slabs[key].geometry.dispose() + prepareBrushForCSG(next) + slabs[key] = next + } + plumb.geometry.dispose() + } + for (const face of faces) { + const points = face.map((point) => new THREE.Vector3(point.x, point.y, point.z)) + const normal = faceNormal(face) + if (!normal) continue + // only the slopes; the module's walls and bottom face sideways or down + if (normal.y < 0.05) continue + const plan = points.map((point): PlanPoint => [point.x, point.z]) + if (Math.abs(planSignedArea(plan)) < 1e-6) continue + // the overhang across the plan at this slope's pitch: the soffit's line + // (a high edge keeps its soffit there), and the outer face's + const reach = segment.overhang * normal.y + TRIM_CUT_EPSILON + const outer = outerReach(normal) + TRIM_CUT_EPSILON + const a = normal.x / normal.y + const b = normal.z / normal.y + // a hair over the slope's own plan, so neighbouring cutters overlap + const region = buildFootprintPrismBrush(offsetPlanRing(plan, 0.001), -far, far) + try { + // The kept region: swept along the normal held at the outer face and at + // the soffit. The two simple sweeps meet first; the slabs are cut once. + const shearAt = (lift: number) => { + const anchor = points[0]!.clone().addScaledVector(normal, lift) + const k = normal.dot(anchor) / normal.y + return new THREE.Matrix4().set( + 1 + a * a, + a, + a * b, + -a * k, + 0, + 1, + 0, + 0, + a * b, + b, + 1 + b * b, + -b * k, + 0, + 0, + 0, + 1, + ) + } + // held at the outer face on its line, and at the soffit on the overhang line + const sweeps: Array<[THREE.Matrix4, number]> = [ + [shearAt(0), outer], + [shearAt(-thickness), reach], + ] + let sweep: Brush | null = null + for (const ring of rings) { + let kept: Brush | null = null + for (const [shear, distance] of sweeps) { + const prism = buildFootprintPrismBrush( + offsetPlanRing(ring, distance), + -far, + far, + shear, + ROOF_FASCIA_MATERIAL_INDEX, + ) + if (kept) { + const met = csgEvaluator.evaluate(kept, prism, INTERSECTION) as Brush + prepareBrushForCSG(met) + kept.geometry.dispose() + prism.geometry.dispose() + kept = met + } else kept = prism + } + if (!kept) continue + if (sweep) { + const merged = csgEvaluator.evaluate(sweep, kept, ADDITION) as Brush + prepareBrushForCSG(merged) + sweep.geometry.dispose() + kept.geometry.dispose() + sweep = merged + } else sweep = kept + } + if (sweep) { + const cutter = csgEvaluator.evaluate(region, sweep, SUBTRACTION) as Brush + prepareBrushForCSG(cutter) + sweep.geometry.dispose() + for (const key of ['shinSlab', 'deckSlab'] as const) { + const next = csgEvaluator.evaluate(slabs[key], cutter, SUBTRACTION) as Brush + slabs[key].geometry.dispose() + prepareBrushForCSG(next) + slabs[key] = next + } + cutter.geometry.dispose() + } + } catch (e) { + console.error('Roof square eaves CSG failed:', e) + } finally { + region.geometry.dispose() + } + } +} + function subtractSegmentTrimCuts(brushes: RoofSegmentBrushSet, segment: RoofSegmentNode) { const cuts = buildSegmentTrimCutBrushes(segment) for (const cut of cuts) { @@ -1390,7 +2036,7 @@ const FASCIA_EMBED = 0.002 * leaves it alone: the remap would send a plumb eave board to the wall band * and its top edge to the shingles. */ -const FASCIA_MATERIAL_INDEX = 2 +const FASCIA_MATERIAL_INDEX = ROOF_FASCIA_MATERIAL_INDEX /** * The fascia and rake boards a segment wears, in its own frame: a plumb 1x8 @@ -1400,17 +2046,40 @@ const FASCIA_MATERIAL_INDEX = 2 * trims, cuts and sibling roofs clip them like the deck. Gable, hip, shed * and flat; null for the other forms. */ +type DeckEave = { + /** Outward reach of the deck past the footprint. */ + deckExt: number + /** Height of the deck's top edge at an eave. */ + eaveTopY: number + tanTheta: number +} + +/** The deck's eave at the segment's own pitch, as `getRoofSegmentVolumeFaces` builds the deck. */ +function getDeckEave(node: RoofSegmentNode): DeckEave { + const { activeRh, tanTheta, cosTheta } = getSegmentSlopeFrame(node) + const deckExt = node.wallThickness / 2 + node.overhang * cosTheta + const verticalRt = activeRh > 0 ? node.deckThickness / cosTheta : node.deckThickness + const drop = deckExt * tanTheta + const eaveTopY = + drop > 0 + ? node.wallHeight - drop + verticalRt + : Math.max(0.05, node.wallHeight - drop + verticalRt) + return { deckExt, eaveTopY, tanTheta } +} + function buildFasciaBoards( node: RoofSegmentNode, - deckExt: number, - eaveTopY: number, - tanTheta: number, + front: DeckEave, + back: DeckEave, ): THREE.BufferGeometry | null { const { roofType, width, depth } = node + const { deckExt, eaveTopY, tanTheta } = front const { thickness: bt, height: bh } = FASCIA_BOARD const out = bt / 2 - FASCIA_EMBED + // the eave boards stand on the deck's edge const halfD = depth / 2 + deckExt const zE = halfD + out + // a gable's rake is no eave; a hip's and a flat roof's sides are const xE = width / 2 + deckExt + out // the eave boards run through the corners to the rake / side boards' // outer faces (a lapped return, no notch at the corner) @@ -1456,12 +2125,38 @@ function buildFasciaBoards( } if (roofType === 'gable') { - const ridgeY = eaveTopY + halfD * tanTheta + // −z eave at the back slope's own pitch; the ridge where the slopes meet + const backHalfD = depth / 2 + back.deckExt + const backZE = backHalfD + out + // a stepped ridge: each rake up to the step line at its own slope's height + const step = getGableRidge(node) + const ridgeZ = + step && step.step !== 0 + ? step.ridgeZ + : (eaveTopY + halfD * tanTheta - back.eaveTopY - backHalfD * back.tanTheta) / + (tanTheta + back.tanTheta || 1) + const frontTop = (z: number) => eaveTopY + (halfD - z) * tanTheta + const backTop = (z: number) => back.eaveTopY + (backHalfD + z) * back.tanTheta + // Over a step the higher slope runs on past the step line by the overhang + // (see buildSteppedGableSlabs): its rake boards go on to that end, and the + // end wears a board like an eave. + let frontEnd = ridgeZ + let backEnd = ridgeZ + if (step && step.step !== 0) { + const higherBack = step.step > 0 + const toward = higherBack ? 1 : -1 + const pitch = ((higherBack ? step.backPitch : step.frontPitch) * Math.PI) / 180 + const edgeZ = ridgeZ + toward * node.overhang * Math.cos(pitch) + const edgeY = higherBack ? backTop(edgeZ) : frontTop(edgeZ) + if (higherBack) backEnd = edgeZ + else frontEnd = edgeZ + board([-xL, edgeY, edgeZ + toward * out], [xL, edgeY, edgeZ + toward * out], [0, 1]) + } board([-xL, eaveTopY, zE], [xL, eaveTopY, zE], [0, 1]) - board([-xL, eaveTopY, -zE], [xL, eaveTopY, -zE], [0, 1]) + board([-xL, back.eaveTopY, -backZE], [xL, back.eaveTopY, -backZE], [0, 1]) for (const sx of [-1, 1]) { - board([sx * xE, eaveTopY, zE], [sx * xE, ridgeY, 0], [1, 0]) - board([sx * xE, ridgeY, 0], [sx * xE, eaveTopY, -zE], [1, 0]) + board([sx * xE, eaveTopY, zE], [sx * xE, frontTop(frontEnd), frontEnd], [1, 0]) + board([sx * xE, backTop(backEnd), backEnd], [sx * xE, back.eaveTopY, -backZE], [1, 0]) } } else if (roofType === 'hip' || roofType === 'flat') { for (const sz of [-1, 1]) board([-xL, eaveTopY, sz * zE], [xL, eaveTopY, sz * zE], [0, 1]) @@ -1469,11 +2164,13 @@ function buildFasciaBoards( for (const sx of [-1, 1]) board([sx * xE, eaveTopY, -zE + bt / 2], [sx * xE, eaveTopY, zE - bt / 2], [1, 0]) } else if (roofType === 'shed') { - // the low eave at +z, the slope rising to −z - const highY = eaveTopY + 2 * halfD * tanTheta + // the low eave at +z, the slope rising to −z; the high edge is no eave + const highHalfD = depth / 2 + deckExt + const highZ = highHalfD + out + const highY = eaveTopY + (halfD + highHalfD) * tanTheta board([-xL, eaveTopY, zE], [xL, eaveTopY, zE], [0, 1]) - if (node.fasciaHighEdge ?? true) board([-xL, highY, -zE], [xL, highY, -zE], [0, 1]) - for (const sx of [-1, 1]) board([sx * xE, eaveTopY, zE], [sx * xE, highY, -zE], [1, 0]) + if (node.fasciaHighEdge ?? true) board([-xL, highY, -highZ], [xL, highY, -highZ], [0, 1]) + for (const sx of [-1, 1]) board([sx * xE, eaveTopY, zE], [sx * xE, highY, -highZ], [1, 0]) } else return null return createGeometryFromFaces(faces, FASCIA_MATERIAL_INDEX) } @@ -1495,23 +2192,93 @@ function wearsFascia(node: RoofSegmentNode, parentRoof?: RoofNode): boolean { * `fascia`: build the segment's fascia boards into its deck. Only the roof * renderer asks; a dormer, a chimney or a sibling's clip takes the bare shell. */ -export function getRoofSegmentBrushes( +/** + * The prisms a segment is built from: its wall shell (`wall`), the shell's + * hollow (`inner`), and the deck slab's top and bottom (`deck-top`, + * `deck-bottom`). + */ +type RoofSegmentVolumeLayer = 'wall' | 'inner' | 'deck-top' | 'deck-bottom' + +type RoofSegmentVolumeOptions = { + /** Outward extension of the footprint on every side. */ + wExt: number + /** Vertical lift of the whole volume (the deck top rides `verticalRt` above the deck bottom). */ + vOffset: number + baseY: number + /** A void volume (the deck bottom) uses the deck-inset dutch waist. */ + isVoid: boolean + /** A plate-seated wall shell keeps its floored eave; see `getRoofSegmentBrushes`. */ + onPlate: boolean +} + +/** The overhang and slab lift of a layer follow the pitch, so they are worked out per pitch. */ +function getRoofSegmentVolumeOptions( node: RoofSegmentNode, - options: { fascia?: boolean } = {}, -): RoofSegmentBrushSet | null { - const { - roofType, - width, - depth, - wallHeight, - wallThickness, - deckThickness, - overhang, - shingleThickness, - } = node - const conicalCoverage = getConicalRoofCoverage(node) + layer: RoofSegmentVolumeLayer, +): RoofSegmentVolumeOptions { + const { activeRh, cosTheta } = getSegmentSlopeFrame(node) + const deckExt = node.wallThickness / 2 + node.overhang * cosTheta + switch (layer) { + case 'wall': + // a hair under the deck: their union then shares no face, which the CSG + // otherwise answers with slivers torn out of the soffit + return { + wExt: node.wallThickness / 2, + vOffset: -ROOF_WALL_UNDER_DECK, + baseY: 0, + isVoid: false, + onPlate: true, + } + case 'inner': + return { wExt: -node.wallThickness / 2, vOffset: 0, baseY: -5, isVoid: false, onPlate: true } + case 'deck-top': + return { + wExt: deckExt, + vOffset: activeRh > 0 ? node.deckThickness / cosTheta : node.deckThickness, + baseY: 0, + isVoid: false, + onPlate: false, + } + case 'deck-bottom': + return { wExt: deckExt, vOffset: 0, baseY: -5, isVoid: true, onPlate: false } + } +} - const { activeRh, tanTheta, cosTheta, sinTheta } = getSegmentSlopeFrame(node) +/** + * Faces of one roof-segment prism in segment-local space. Single source for + * the brush builder and for consumers that need the roof planes as data + * (walls fitted to the roof underside). + */ +export function getRoofSegmentVolumeFaces( + node: RoofSegmentNode, + layer: RoofSegmentVolumeLayer, +): THREE.Vector3[][] { + const input = withRoofSegmentGableBack(node, (pitched) => + getRoofSegmentVolumeModule(pitched, layer), + ) + // A stepped ridge's wall: the hollow's step stands a wall thickness into the + // higher side, so the shell keeps a wall there from the lower slope up. + const stepZ = input.gableBack?.stepZ + if (layer === 'inner' && stepZ !== undefined && input.gableBack) { + const higherBack = readGableRidgeStep(node) > 0 + input.gableBack = { + ...input.gableBack, + stepZ: stepZ + (higherBack ? -1 : 1) * node.wallThickness, + } + } + return getRoofModuleFaces(input).map((face) => + face.map((point) => new THREE.Vector3(point.x, point.y, point.z)), + ) +} + +function getRoofSegmentVolumeModule( + node: RoofSegmentNode, + layer: RoofSegmentVolumeLayer, +): RoofModuleInput { + const { roofType, width, depth, wallHeight, deckThickness } = node + const { wExt, vOffset, baseY, isVoid, onPlate } = getRoofSegmentVolumeOptions(node, layer) + const conicalCoverage = getConicalRoofCoverage(node) + const { activeRh, tanTheta } = getSegmentSlopeFrame(node) const shapeRatios = getRoofShapeRatios({ gambrelLowerWidthRatio: node.gambrelLowerWidthRatio, mansardSteepWidthRatio: node.mansardSteepWidthRatio, @@ -1520,91 +2287,243 @@ export function getRoofSegmentBrushes( dutchWaistLengthRatio: node.dutchWaistLengthRatio, dutchGabletRake: node.dutchGabletRake, }) - - const verticalRt = activeRh > 0 ? deckThickness / cosTheta : deckThickness // Gablet inset must track dutchHipWidthRatio so the 3D waist matches both // the 2D floorplan and the slope frame (which derives activeRh from the // same ratio). A hardcoded 0.25 desyncs the gablet from the parameter. const baseI = Math.min(width, depth) * node.dutchHipWidthRatio - const plateSeated = wallHeight <= 0 - const getVol = ( - wExt: number, - vOffset: number, - baseY: number, - matIndex: number, - isVoid: boolean, - materialRule?: (normal: THREE.Vector3) => number, - onPlate = false, - ) => { - const wV = Math.max(0.01, width + 2 * wExt) - const dV = Math.max(0.01, depth + 2 * wExt) - - const autoDrop = wExt * tanTheta - // Floor every prism at 5 cm so CSG never sees a degenerate volume — by - // raising the top, never by sinking the base (the base is the wall top). - // One floor for all volumes keeps each cutter level with the shell it carves. - // A plate-seated roof (wallHeight 0) is the exception for its sloped deck - // volumes: their eave hangs below the plate, and raising it lifted the - // whole roof off its walls, so their base sinks instead. - const eaveY = wallHeight - autoDrop + vOffset - const sinkBase = plateSeated && !onPlate && autoDrop !== 0 - const whV = sinkBase ? eaveY : Math.max(0.05, eaveY) - - let rhV = activeRh - if (activeRh > 0) { - rhV = activeRh + autoDrop - if (roofType === 'shed') rhV = activeRh + 2 * autoDrop - } + const wV = Math.max(0.01, width + 2 * wExt) + const dV = Math.max(0.01, depth + 2 * wExt) + + const autoDrop = wExt * tanTheta + // Floor every prism at 5 cm so CSG never sees a degenerate volume — by + // raising the top, never by sinking the base (the base is the wall top). + // One floor for all volumes keeps each cutter level with the shell it carves. + // The sloped deck volumes are the exception: when their eave hangs below + // that floor (a low wall under a long overhang), raising it would lift the + // roof off its walls and a base at the plate would slice the overhang flat, + // so their base sinks instead. An eave set below the plate (a gable's attic + // wall below zero) sinks every volume; the brush builder then cuts away + // what falls below the plate inside the walls. + const eaveY = wallHeight - autoDrop + vOffset + const sinkBase = wallHeight < 0 || (!onPlate && autoDrop !== 0 && eaveY < 0.05) + const whV = sinkBase ? eaveY : Math.max(0.05, eaveY) + + let rhV = activeRh + if (activeRh > 0) { + rhV = activeRh + autoDrop + if (roofType === 'shed') rhV = activeRh + 2 * autoDrop + } - const safeBaseY = sinkBase ? Math.min(baseY, whV - 0.05) : baseY + // A sunk deck top reaches below the deck's own bottom edge (`vOffset` lower), + // so the slab keeps its full eave instead of a flat cut. + const safeBaseY = sinkBase ? Math.min(baseY, whV - vOffset - 0.05) : baseY - let structuralI = baseI - if (isVoid) { - structuralI += deckThickness - } + let structuralI = baseI + if (isVoid) { + structuralI += deckThickness + } - const faces = getRoofModuleFaces({ - type: roofType, - w: wV, - d: dV, - wh: whV, - rh: rhV, - baseY: safeBaseY, - insets: { dutchI: structuralI }, - baseW: width, - baseD: depth, - tanTheta, - shapeRatios, - dutchTopRakeThickness: node.dutchTopRakeThickness, - conicalStartAngle: conicalCoverage.startAngle, - conicalSweepAngle: conicalCoverage.sweepAngle, - }).map((face) => face.map((point) => new THREE.Vector3(point.x, point.y, point.z))) - return createGeometryFromFaces(faces, materialRule ?? matIndex) + return { + type: roofType, + w: wV, + d: dV, + wh: whV, + rh: rhV, + baseY: safeBaseY, + insets: { dutchI: structuralI }, + baseW: width, + baseD: depth, + tanTheta, + shapeRatios, + dutchTopRakeThickness: node.dutchTopRakeThickness, + conicalStartAngle: conicalCoverage.startAngle, + conicalSweepAngle: conicalCoverage.sweepAngle, } +} - const wallGeo = getVol(wallThickness / 2, 0, 0, 0, false, undefined, true) - const innerGeo = getVol(-wallThickness / 2, 0, -5, 2, false, undefined, true) +/** + * Keeps the part of a planar polygon where `side(point) >= 0`. The roof faces + * are planar, so a straight plan cut interpolates their height exactly. + */ +function clipPlanarPolygon( + polygon: THREE.Vector3[], + side: (point: THREE.Vector3) => number, +): THREE.Vector3[] { + const result: THREE.Vector3[] = [] + for (let index = 0; index < polygon.length; index++) { + const current = polygon[index]! + const next = polygon[(index + 1) % polygon.length]! + const currentSide = side(current) + const nextSide = side(next) + if (currentSide >= 0) result.push(current) + if (currentSide >= 0 !== nextSide >= 0) { + result.push(current.clone().lerp(next, currentSide / (currentSide - nextSide))) + } + } + return result +} - const horizontalOverhang = overhang * cosTheta - const deckExt = wallThickness / 2 + horizontalOverhang +function getSegmentTrimHalfPlanes( + segment: RoofSegmentNode, +): Array<(point: THREE.Vector3) => number> { + const trim = normalizeRoofSegmentTrim(segment) + const leftX = -segment.width / 2 + trim.left + const rightX = segment.width / 2 - trim.right + const frontZ = segment.depth / 2 - trim.front + const backZ = -segment.depth / 2 + trim.back + const planes: Array<(point: THREE.Vector3) => number> = [] + if (trim.left > 0) planes.push((point) => point.x - leftX) + if (trim.right > 0) planes.push((point) => rightX - point.x) + if (trim.front > 0) planes.push((point) => frontZ - point.z) + if (trim.back > 0) planes.push((point) => point.z - backZ) + // The same corner lines as `buildSegmentTrimCutBrushes`, kept on the side + // away from the trimmed corner. + const diagonal = (a: TrimPlanPoint, b: TrimPlanPoint, outside: TrimPlanPoint) => { + const cross = (x: number, z: number) => (b[0] - a[0]) * (z - a[1]) - (b[1] - a[1]) * (x - a[0]) + const outsideSign = Math.sign(cross(outside[0], outside[1])) || 1 + planes.push((point) => -outsideSign * cross(point.x, point.z)) + } + if (trim.frontLeftX > 0 && trim.frontLeftZ > 0) { + diagonal([leftX + trim.frontLeftX, frontZ], [leftX, frontZ - trim.frontLeftZ], [-1e6, 1e6]) + } + if (trim.frontRightX > 0 && trim.frontRightZ > 0) { + diagonal([rightX, frontZ - trim.frontRightZ], [rightX - trim.frontRightX, frontZ], [1e6, 1e6]) + } + if (trim.backLeftX > 0 && trim.backLeftZ > 0) { + diagonal([leftX, backZ + trim.backLeftZ], [leftX + trim.backLeftX, backZ], [-1e6, -1e6]) + } + if (trim.backRightX > 0 && trim.backRightZ > 0) { + diagonal([rightX - trim.backRightX, backZ], [rightX, backZ + trim.backRightZ], [1e6, -1e6]) + } + return planes +} - // A shed's deck and shingle edges take the wall/trim slot, unless it wears - // fascia boards: then they are fascia like a gable's, in the deck slot. - const shedEdgesInTrimSlot = roofType === 'shed' && !options.fascia - const shedRoofSideMaterialRule = shedEdgesInTrimSlot - ? (normal: THREE.Vector3) => (normal.y > SHINGLE_SURFACE_EPSILON ? 3 : ROOF_EDGE_MATERIAL_INDEX) - : undefined - const deckTopGeo = getVol(deckExt, verticalRt, 0, 1, false, shedRoofSideMaterialRule) - const deckBotGeo = getVol(deckExt, 0, -5, 0, true) - // the deck's top edge at its outer plane, as `getVol` puts it - const deckEaveDrop = deckExt * tanTheta - const deckEaveTopY = - plateSeated && deckEaveDrop > 0 - ? wallHeight - deckEaveDrop + verticalRt - : Math.max(0.05, wallHeight - deckEaveDrop + verticalRt) - const fasciaGeo = options.fascia ? buildFasciaBoards(node, deckExt, deckEaveTopY, tanTheta) : null +/** + * The underside of a segment's deck — the surface a wall beneath the roof + * meets — as planar polygons in segment-local space: the upward faces of the + * deck-bottom void the brush builder subtracts (`deckBotGeo`), clipped by the + * segment trim. A shed built from footprint pieces uses those pieces under its + * slope plane. Null when the deck has no planar data here (a banded shed + * following an arc, an open conical sector). + */ +export function getRoofSegmentUndersidePolygons(node: RoofSegmentNode): THREE.Vector3[][] | null { + if (node.roofType === 'shed') { + if (isBandedShedSegment(node)) return null + const storedPieces = readShedFootprintPieces(node) + const pieces = + storedPieces.length > 0 + ? storedPieces + : node.managedByParent + ? [managedShedFootprint(node)] + : [] + if (pieces.length > 0) { + return pieces + .map((piece) => + sanitizeRoofPlanPolygon(piece).map( + ([x, z]) => new THREE.Vector3(x, getRoofSegmentSurfaceY(node, x, z), z), + ), + ) + .filter((polygon) => polygon.length >= 3) + } + } + if ( + node.roofType === 'conical' && + !hasSegmentTrim(node) && + !getConicalRoofCoverage(node).fullCircle + ) { + return null + } + const { cosTheta } = getSegmentSlopeFrame(node) + const faces = getRoofSegmentVolumeFaces(node, 'deck-bottom') + let minY = Number.POSITIVE_INFINITY + for (const face of faces) for (const point of face) minY = Math.min(minY, point.y) + const halfPlanes = getSegmentTrimHalfPlanes(node) + // cut at the wall top, the roof is gone below the plate inside the walls, so + // it bears on no wall there; otherwise it is a ceiling following the slope + const belowPlate = hasEaveBelowPlate(node) && node.cutAtWallTop === true + const cover = readSegmentCover(node) + // the covering reaches the outline plus the overhang (clipSegmentBrushesToFootprint) + const outline = cover ? offsetPlanRing(cover, node.overhang * cosTheta) : null + const polygons: THREE.Vector3[][] = [] + const normal = new THREE.Vector3() + for (const face of faces) { + if (face.length < 3 || face.every((point) => Math.abs(point.y - minY) <= 1e-6)) continue + // Newell normal: robust for the planar quads and triangles of a module. + normal.set(0, 0, 0) + for (let index = 0; index < face.length; index++) { + const current = face[index]! + const next = face[(index + 1) % face.length]! + normal.x += (current.y - next.y) * (current.z + next.z) + normal.y += (current.z - next.z) * (current.x + next.x) + normal.z += (current.x - next.x) * (current.y + next.y) + } + const length = normal.length() + if (!(length > 1e-9) || Math.abs(normal.y) / length < 0.05) continue + // Winding in plan (x, z): the Newell normal's y is minus the plan area sign. + const faceCcw = normal.y < 0 + let polygon = belowPlate ? clipPlanarPolygon(face, (point) => point.y) : face + for (const side of halfPlanes) { + if (polygon.length < 3) break + polygon = clipPlanarPolygon(polygon, side) + } + if (polygon.length < 3) continue + if (!outline) { + polygons.push(polygon) + continue + } + // The face is convex, the outline may not be: clip the outline by the face + // and lift the result onto the face plane. + let piece: PlanPoint[] = outline + for (let index = 0; index < polygon.length && piece.length >= 3; index++) { + const a = polygon[index]! + const b = polygon[(index + 1) % polygon.length]! + const inward = faceCcw ? 1 : -1 + piece = clipPlanRing( + piece, + ([x, z]) => inward * ((b.x - a.x) * (z - a.z) - (b.z - a.z) * (x - a.x)), + ) + } + if (piece.length < 3) continue + const [p0, p1, p2] = polygon + const plane = new THREE.Plane().setFromCoplanarPoints(p0!, p1!, p2!) + polygons.push( + piece.map(([x, z]) => { + const y = + Math.abs(plane.normal.y) > 1e-9 + ? -(plane.normal.x * x + plane.normal.z * z + plane.constant) / plane.normal.y + : p0!.y + return new THREE.Vector3(x, y, z) + }), + ) + } + return polygons +} + +/** + * The shingle layer's lower (`bottom`, on the deck) or outer (`top`) prism of + * a segment at its own pitch. A shed's outer prism is built centred; the + * brush builder shifts it by half the shingle projection. + */ +function getRoofSegmentShingleModule( + node: RoofSegmentNode, + side: 'bottom' | 'top', +): RoofModuleInput { + const { + roofType, + width, + depth, + wallHeight, + wallThickness, + deckThickness, + overhang, + shingleThickness, + } = node + const conicalCoverage = getConicalRoofCoverage(node) + const { activeRh, tanTheta, cosTheta, sinTheta } = getSegmentSlopeFrame(node) + const verticalRt = activeRh > 0 ? deckThickness / cosTheta : deckThickness + const deckExt = wallThickness / 2 + overhang * cosTheta const stSin = shingleThickness * sinTheta const stCos = shingleThickness * cosTheta @@ -1620,10 +2539,53 @@ export function getRoofSegmentBrushes( if (roofType === 'shed') shinBotRh = activeRh + 2 * deckDrop } + const availableR = (Math.min(shinBotW, shinBotD) / 2) * 0.95 + const maxDrop = tanTheta > 0.001 ? availableR / tanTheta : 2.0 + const common = { + type: roofType, + baseW: width, + baseD: depth, + tanTheta, + shapeRatios: getRoofShapeRatios({ + gambrelLowerWidthRatio: node.gambrelLowerWidthRatio, + mansardSteepWidthRatio: node.mansardSteepWidthRatio, + dutchHipWidthRatio: node.dutchHipWidthRatio, + dutchHipHeightRatio: node.dutchHipHeightRatio, + dutchWaistLengthRatio: node.dutchWaistLengthRatio, + dutchGabletRake: node.dutchGabletRake, + }), + dutchTopRakeThickness: node.dutchTopRakeThickness, + conicalStartAngle: conicalCoverage.startAngle, + conicalSweepAngle: conicalCoverage.sweepAngle, + } + + if (side === 'bottom') { + const botBaseY = shinBotWh - Math.min(2.0, maxDrop * 0.8) + return { + ...common, + w: shinBotW, + d: shinBotD, + wh: shinBotWh, + rh: shinBotRh, + baseY: botBaseY, + insets: getRoofShapeInsets({ + roofType, + width, + depth, + wh: shinBotWh, + baseY: botBaseY, + isVoid: true, + brushW: shinBotW, + brushD: shinBotD, + tanTheta, + shingleThickness, + dutchHipWidthRatio: node.dutchHipWidthRatio, + }), + } + } + let shinTopW = shinBotW let shinTopD = shinBotD - let transZ = 0 - if (['hip', 'mansard', 'dutch', 'conical'].includes(roofType)) { shinTopW += 2 * stSin shinTopD += 2 * stSin @@ -1631,91 +2593,271 @@ export function getRoofSegmentBrushes( shinTopD += 2 * stSin } else if (roofType === 'shed') { shinTopD += stSin - transZ = stSin / 2 } const shinTopWh = shinBotWh + stCos - - let shinTopRh = shinBotRh - if (activeRh > 0) { - shinTopRh = shinBotRh + stSin * tanTheta + const shinTopRh = activeRh > 0 ? shinBotRh + stSin * tanTheta : shinBotRh + const topBaseY = shinBotWh - Math.min(1.0, maxDrop * 0.4) + return { + ...common, + w: shinTopW, + d: shinTopD, + wh: shinTopWh, + rh: shinTopRh, + baseY: topBaseY, + insets: getRoofShapeInsets({ + roofType, + width, + depth, + wh: shinTopWh, + baseY: topBaseY, + isVoid: false, + brushW: shinTopW, + brushD: shinTopD, + tanTheta, + shingleThickness, + dutchHipWidthRatio: node.dutchHipWidthRatio, + }), } +} - const availableR = (Math.min(shinBotW, shinBotD) / 2) * 0.95 - const maxDrop = tanTheta > 0.001 ? availableR / tanTheta : 2.0 - const dropTop = Math.min(1.0, maxDrop * 0.4) - const dropBot = Math.min(2.0, maxDrop * 0.8) - - const topBaseY = shinBotWh - dropTop - const botBaseY = shinBotWh - dropBot +/** + * A stepped gable's deck and shingles, one slope at a time. Each slope's + * covering is its own plane carried on: the higher slope runs on past the + * step line by the overhang (over the lower one), the lower slope stops at + * the step. Under an outline each slope is cut, plumb, to its own part of it + * pushed out by the overhang — an outline edge on the step line overhangs + * only the slope it bounds. Null unless the gable is stepped. + */ +function buildSteppedGableSlabs( + node: RoofSegmentNode, + toBrush: (geometry: THREE.BufferGeometry) => Brush | null, +): { deckSlab: Brush; shinSlab: Brush } | null { + const ridge = getGableRidge(node) + if (!ridge || ridge.step === 0) return null + const higherBack = ridge.step > 0 + // from the step line toward the lower slope + const toward = higherBack ? 1 : -1 + const stepZ = ridge.ridgeZ + const cover = readSegmentCover(node) + const shingleRule = (normal: THREE.Vector3) => + normal.y > SHINGLE_SURFACE_EPSILON ? 3 : ROOF_FASCIA_MATERIAL_INDEX + type Build = (pitched: RoofSegmentNode) => RoofModuleInput + type Material = number | ((normal: THREE.Vector3) => number) + const layers: Array<{ + key: 'deckSlab' | 'shinSlab' + top: Build + bottom: Build + topMat: Material + bottomMat: Material + }> = [ + { + key: 'deckSlab', + top: (pitched) => getRoofSegmentVolumeModule(pitched, 'deck-top'), + bottom: (pitched) => getRoofSegmentVolumeModule(pitched, 'deck-bottom'), + topMat: ROOF_FASCIA_MATERIAL_INDEX, + bottomMat: ROOF_SOFFIT_MATERIAL_INDEX, + }, + { + key: 'shinSlab', + top: (pitched) => getRoofSegmentShingleModule(pitched, 'top'), + bottom: (pitched) => getRoofSegmentShingleModule(pitched, 'bottom'), + topMat: shingleRule, + bottomMat: shingleRule, + }, + ] + const maxY = + Math.max(ridge.height, ridge.backHeight) + node.deckThickness + node.shingleThickness + 10 + const toFaces = (input: RoofModuleInput) => + getRoofModuleFaces(input).map((face) => + face.map((point) => new THREE.Vector3(point.x, point.y, point.z)), + ) + const disposeAll = (brushes: Array) => { + for (const brush of brushes) brush?.geometry.dispose() + } + const square = hasSquareEaves(node) + const outline = cover ?? segmentWallOutline(node) + const joined: Partial> = {} + for (const side of ['front', 'back'] as const) { + const isHigher = (side === 'back') === higherBack + const pitch = ((side === 'front' ? ridge.frontPitch : ridge.backPitch) * Math.PI) / 180 + const endZ = isHigher ? stepZ + toward * node.overhang * Math.cos(pitch) : stepZ + // outward past the slope's end + const outward = isHigher ? toward : -toward + // With square eaves the lower slope's end, under the step wall, is cut + // square to it through the roof's outer face on the step line: the + // soffit reaches on under the wall, so nothing opens at the step. + let endCut: { z: number; y: number; nz: number; ny: number } | undefined + if (square && !isHigher) { + const outer = withRoofSegmentGableBack(node, (pitched) => + getRoofSegmentShingleModule(pitched, 'top'), + ) + const back = outer.gableBack + const y = + side === 'front' + ? outer.wh + (outer.d / 2 - stepZ) * outer.tanTheta + : back + ? back.wh + (back.halfDepth + stepZ) * back.tanTheta + : outer.wh + // the plane's normal: up the slope, toward the step + endCut = { z: stepZ, y, nz: outward * Math.cos(pitch), ny: Math.sin(pitch) } + } + const body = (build: Build, beyond: number): RoofModuleInput | null => { + const input = withRoofSegmentGableBack(node, build) + if (!input.gableBack) return null + const cut = endCut && beyond === 0 ? endCut : undefined + // a cut end runs on under the step: the bottom body goes well past it + const past = endCut && beyond > 0 ? 2 : beyond + return { + ...input, + gableBack: { + ...input.gableBack, + only: side, + endZ: endZ + outward * past, + ...(cut ? { endCut: cut } : {}), + }, + } + } + // this slope's deck and shingles: each its top body less its bottom body + const slabs: Partial> = {} + for (const layer of layers) { + const topInput = body(layer.top, 0) + // the bottom reaches a little past the top's end: no faces coincide + const bottomInput = body(layer.bottom, 0.05) + const top = topInput && toBrush(createGeometryFromFaces(toFaces(topInput), layer.topMat)) + const bottom = + bottomInput && toBrush(createGeometryFromFaces(toFaces(bottomInput), layer.bottomMat)) + if (!(top && bottom && bottomInput)) { + disposeAll([top, bottom, ...Object.values(slabs), ...Object.values(joined)]) + return null + } + // a hair larger across and along, as the one-piece build does + bottom.scale.set( + 1 + 0.002 / Math.max(0.01, bottomInput.w), + 1, + 1 + 0.002 / Math.max(0.01, bottomInput.d), + ) + bottom.updateMatrixWorld() + const slab = csgEvaluator.evaluate(top, bottom, SUBTRACTION) as Brush + prepareBrushForCSG(slab) + disposeAll([top, bottom]) + slabs[layer.key] = slab + } + let sideSlabs = slabs as Record<'deckSlab' | 'shinSlab', Brush> + // This slope's part of the outline: an edge on the step line overhangs + // only the slope it bounds. + const parts = splitPlanRingByLine(outline, stepZ, side === 'front' ? 1 : -1) + if (parts.length === 0) { + // no part of the outline on this side: no slope there + disposeAll(Object.values(sideSlabs)) + continue + } + if (square) { + const shinTopInput = body((pitched) => getRoofSegmentShingleModule(pitched, 'top'), 0) + if (shinTopInput) cutSlabsSquare(sideSlabs, node, parts, getRoofModuleFaces(shinTopInput)) + } else if (cover) { + const reach = node.overhang * Math.cos(pitch) + TRIM_CUT_EPSILON + let keep: Brush | null = null + for (const part of parts) { + const prism = buildFootprintPrismBrush( + offsetPlanRing(part, reach), + -10, + maxY, + undefined, + ROOF_FASCIA_MATERIAL_INDEX, + ) + if (keep) { + const merged = csgEvaluator.evaluate(keep, prism, ADDITION) as Brush + prepareBrushForCSG(merged) + disposeAll([keep, prism]) + keep = merged + } else keep = prism + } + const kept: Partial> = {} + for (const key of ['deckSlab', 'shinSlab'] as const) { + const cut = csgEvaluator.evaluate(sideSlabs[key], keep!, INTERSECTION) as Brush + prepareBrushForCSG(cut) + sideSlabs[key].geometry.dispose() + kept[key] = cut + } + keep!.geometry.dispose() + sideSlabs = kept as Record<'deckSlab' | 'shinSlab', Brush> + } + for (const key of ['deckSlab', 'shinSlab'] as const) { + const previous = joined[key] + if (previous) { + const merged = csgEvaluator.evaluate(previous, sideSlabs[key], ADDITION) as Brush + prepareBrushForCSG(merged) + disposeAll([previous, sideSlabs[key]]) + joined[key] = merged + } else joined[key] = sideSlabs[key] + } + } + if (!(joined.deckSlab && joined.shinSlab)) { + disposeAll(Object.values(joined)) + return null + } + return { deckSlab: joined.deckSlab, shinSlab: joined.shinSlab } +} - const insetsBot = getRoofShapeInsets({ - roofType, - width, - depth, - wh: shinBotWh, - baseY: botBaseY, - isVoid: true, - brushW: shinBotW, - brushD: shinBotD, - tanTheta, - shingleThickness, - dutchHipWidthRatio: node.dutchHipWidthRatio, - }) - const insetsTop = getRoofShapeInsets({ - roofType, - width, - depth, - wh: shinTopWh, - baseY: topBaseY, - isVoid: false, - brushW: shinTopW, - brushD: shinTopD, - tanTheta, - shingleThickness, +export function getRoofSegmentBrushes( + node: RoofSegmentNode, + options: { fascia?: boolean } = {}, +): RoofSegmentBrushSet | null { + const { roofType, width, depth, wallThickness, overhang, shingleThickness } = node + const { cosTheta, sinTheta } = getSegmentSlopeFrame(node) + const shapeRatios = getRoofShapeRatios({ + gambrelLowerWidthRatio: node.gambrelLowerWidthRatio, + mansardSteepWidthRatio: node.mansardSteepWidthRatio, dutchHipWidthRatio: node.dutchHipWidthRatio, + dutchHipHeightRatio: node.dutchHipHeightRatio, + dutchWaistLengthRatio: node.dutchWaistLengthRatio, + dutchGabletRake: node.dutchGabletRake, }) - const botFaces = getRoofModuleFaces({ - type: roofType, - w: shinBotW, - d: shinBotD, - wh: shinBotWh, - rh: shinBotRh, - baseY: botBaseY, - insets: insetsBot, - baseW: width, - baseD: depth, - tanTheta, - shapeRatios, - dutchTopRakeThickness: node.dutchTopRakeThickness, - conicalStartAngle: conicalCoverage.startAngle, - conicalSweepAngle: conicalCoverage.sweepAngle, - }).map((face) => face.map((point) => new THREE.Vector3(point.x, point.y, point.z))) - const topFaces = getRoofModuleFaces({ - type: roofType, - w: shinTopW, - d: shinTopD, - wh: shinTopWh, - rh: shinTopRh, - baseY: topBaseY, - insets: insetsTop, - baseW: width, - baseD: depth, - tanTheta, - shapeRatios, - dutchTopRakeThickness: node.dutchTopRakeThickness, - conicalStartAngle: conicalCoverage.startAngle, - conicalSweepAngle: conicalCoverage.sweepAngle, - }).map((face) => face.map((point) => new THREE.Vector3(point.x, point.y, point.z))) + const getVol = ( + layer: RoofSegmentVolumeLayer, + matIndex: number, + materialRule?: (normal: THREE.Vector3) => number, + ) => createGeometryFromFaces(getRoofSegmentVolumeFaces(node, layer), materialRule ?? matIndex) + + const wallGeo = getVol('wall', 0) + const innerGeo = getVol('inner', 2) + + const horizontalOverhang = overhang * cosTheta + const deckExt = wallThickness / 2 + horizontalOverhang + + const deckTopGeo = getVol('deck-top', ROOF_FASCIA_MATERIAL_INDEX) + const deckBotGeo = getVol('deck-bottom', ROOF_SOFFIT_MATERIAL_INDEX) + let fasciaGeo: THREE.BufferGeometry | null = null + if (options.fascia) { + const backTwin = getRoofSegmentBackSlopeTwin(node) + const frontEave = getDeckEave(node) + fasciaGeo = buildFasciaBoards(node, frontEave, backTwin ? getDeckEave(backTwin) : frontEave) + } + + const shinBot = withRoofSegmentGableBack(node, (pitched) => + getRoofSegmentShingleModule(pitched, 'bottom'), + ) + const shinTop = withRoofSegmentGableBack(node, (pitched) => + getRoofSegmentShingleModule(pitched, 'top'), + ) + const shinBotW = shinBot.w + const shinBotD = shinBot.d + const transZ = roofType === 'shed' ? (shingleThickness * sinTheta) / 2 : 0 + const toVectors = (faces: ReturnType) => + faces.map((face) => face.map((point) => new THREE.Vector3(point.x, point.y, point.z))) + const botFaces = toVectors(getRoofModuleFaces(shinBot)) + const topFaces = toVectors(getRoofModuleFaces(shinTop)) + const insetsTop = shinTop.insets let rakeBoards: THREE.BufferGeometry | null = null if (roofType === 'dutch' && insetsTop.dutchI !== undefined) { rakeBoards = buildDutchRakeBoards( - shinTopW, - shinTopD, - shinTopWh, - shinTopRh, + shinTop.w, + shinTop.d, + shinTop.wh, + shinTop.rh, insetsTop.dutchI, shapeRatios, node.dutchGabletRake ?? ROOF_SHAPE_DEFAULTS.dutchGabletRake, @@ -1723,12 +2865,11 @@ export function getRoofSegmentBrushes( ) } - const shedRoofSideMaterialIndex = shedEdgesInTrimSlot ? ROOF_EDGE_MATERIAL_INDEX : 1 const shinBotGeo = createGeometryFromFaces(botFaces, (normal) => - normal.y > SHINGLE_SURFACE_EPSILON ? 3 : shedRoofSideMaterialIndex, + normal.y > SHINGLE_SURFACE_EPSILON ? 3 : ROOF_FASCIA_MATERIAL_INDEX, ) const shinTopGeo = createGeometryFromFaces(topFaces, (normal) => - normal.y > SHINGLE_SURFACE_EPSILON ? 3 : shedRoofSideMaterialIndex, + normal.y > SHINGLE_SURFACE_EPSILON ? 3 : ROOF_FASCIA_MATERIAL_INDEX, ) if (transZ !== 0) { @@ -1791,7 +2932,10 @@ export function getRoofSegmentBrushes( if (deckTopBrush && deckBotBrush && wallBrush && innerBrush && shinTopBrush && shinBotBrush) { try { - let deckSlab = csgEvaluator.evaluate(deckTopBrush, deckBotBrush, SUBTRACTION) + const stepped = buildSteppedGableSlabs(node, toBrush) + let deckSlab = stepped + ? stepped.deckSlab + : csgEvaluator.evaluate(deckTopBrush, deckBotBrush, SUBTRACTION) prepareBrushForCSG(deckSlab) if (fasciaBrush) { const withFascia = csgEvaluator.evaluate(deckSlab, fasciaBrush, ADDITION) @@ -1800,7 +2944,9 @@ export function getRoofSegmentBrushes( fasciaBrush.geometry.dispose() deckSlab = withFascia } - const shinSlab = csgEvaluator.evaluate(shinTopBrush, shinBotBrush, SUBTRACTION) + const shinSlab = stepped + ? stepped.shinSlab + : csgEvaluator.evaluate(shinTopBrush, shinBotBrush, SUBTRACTION) prepareBrushForCSG(shinSlab) deckTopBrush.geometry.dispose() @@ -1826,6 +2972,16 @@ export function getRoofSegmentBrushes( remapDutchRakeBoardMaterials(brushes.rakeBoards) } } + clipSegmentBrushesToFootprint(brushes, node, { slabs: !stepped }) + if (!stepped && hasSquareEaves(node)) { + const transZ = + roofType === 'shed' ? (shingleThickness * getSegmentSlopeFrame(node).sinTheta) / 2 : 0 + const faces = getRoofModuleFaces(shinTop).map((face) => + face.map((point) => ({ x: point.x, y: point.y, z: point.z + transZ })), + ) + cutSlabsSquare(brushes, node, [readSegmentCover(node) ?? segmentWallOutline(node)], faces) + } + clipSegmentBrushesBelowPlate(brushes, node) return brushes } catch (e) { @@ -1915,12 +3071,9 @@ export function generateRoofSegmentGeometry( const resultMaterials = csgMaterials(combined) - const matToIndex = new Map([ - [dummyMats[0], 0], - [dummyMats[1], 1], - [dummyMats[2], 2], - [dummyMats[3], 3], - ]) + const matToIndex = new Map( + dummyMats.map((material, slot) => [material, slot]), + ) for (const group of resultGeo.groups) { group.materialIndex = mapRoofGroupMaterialIndex( @@ -1974,12 +3127,9 @@ function clipDirectRoofGeometryAgainstSiblings( const clipped = subtractCsgBrush(brush, siblingInterior, csgEvaluator) const clippedGeometry = csgGeometry(clipped) const clippedMaterials = csgMaterials(clipped) - const materialIndices = new Map([ - [dummyMats[0], 0], - [dummyMats[1], 1], - [dummyMats[2], 2], - [dummyMats[3], 3], - ]) + const materialIndices = new Map( + dummyMats.map((material, slot) => [material, slot]), + ) for (const group of clippedGeometry.groups) { group.materialIndex = mapRoofGroupMaterialIndex( group.materialIndex, @@ -2301,9 +3451,7 @@ function buildConcentricBandDeckGeometry(node: RoofSegmentNode): THREE.BufferGeo frontTop[last]!.clone(), ], ) - const merged = createGeometryFromFaces(faces, (normal) => - normal.y > SHINGLE_SURFACE_EPSILON ? 3 : ROOF_EDGE_MATERIAL_INDEX, - ) + const merged = createGeometryFromFaces(faces, (normal) => roofSlabFaceSlot(normal)) merged.computeVertexNormals() ensureRenderableGeometryAttributes(merged) return merged @@ -2412,9 +3560,10 @@ function buildDirectConicalSectorGeometry(node: RoofSegmentNode): THREE.BufferGe const deck = layerFaces(deckBottomRing, deckBottomApex, deckTopRing, deckTopApex) const shingles = layerFaces(deckTopRing, deckTopApex, shingleTopRing, shingleTopApex) const geometries = [ - createGeometryFromFaces([...deck.bottomFaces, ...deck.edgeFaces], ROOF_EDGE_MATERIAL_INDEX), + createGeometryFromFaces(deck.bottomFaces, ROOF_SOFFIT_MATERIAL_INDEX), + createGeometryFromFaces(deck.edgeFaces, ROOF_FASCIA_MATERIAL_INDEX), createGeometryFromFaces(shingles.topFaces, 3), - createGeometryFromFaces(shingles.edgeFaces, ROOF_EDGE_MATERIAL_INDEX), + createGeometryFromFaces(shingles.edgeFaces, ROOF_FASCIA_MATERIAL_INDEX), ] if (node.wallHeight > 0.001) { @@ -3097,11 +4246,7 @@ function buildCustomShedGeometry( } } } - geometries.push( - createGeometryFromFaces(faces, (normal) => - normal.y > SHINGLE_SURFACE_EPSILON ? 3 : ROOF_EDGE_MATERIAL_INDEX, - ), - ) + geometries.push(createGeometryFromFaces(faces, (normal) => roofSlabFaceSlot(normal))) if (jointTransitionFaces.length > 0) { geometries.push(createGeometryFromFaces(jointTransitionFaces, 3)) } @@ -3324,10 +4469,9 @@ export function remapRoofShellFaces(geometry: THREE.BufferGeometry, node: RoofSe materialIndex = 3 } else if (normal.y > SHINGLE_SURFACE_EPSILON) { materialIndex = 3 - } else if (isRakeFace(node, geometry, centroid, normal)) { - materialIndex = 1 } else { - materialIndex = 0 + // eave and rake ends of the deck and shingles alike: the fascia + materialIndex = ROOF_FASCIA_MATERIAL_INDEX } } @@ -3352,41 +4496,6 @@ export function remapRoofShellFaces(geometry: THREE.BufferGeometry, node: RoofSe geometry.addGroup(groupStart * 3, (triangleCount - groupStart) * 3, currentMaterial) } -function isRakeFace( - node: RoofSegmentNode, - geometry: THREE.BufferGeometry, - centroid: THREE.Vector3, - normal: THREE.Vector3, -) { - const rakeAxis = getRakeAxis(node) - const bounds = geometry.boundingBox - - if (!(rakeAxis && bounds)) return false - if (Math.abs(normal.y) > RAKE_FACE_NORMAL_EPSILON) return false - - const axisNormal = rakeAxis === 'x' ? Math.abs(normal.x) : Math.abs(normal.z) - if (axisNormal < RAKE_FACE_ALIGNMENT_EPSILON) return false - - const halfExtent = - rakeAxis === 'x' - ? Math.max(Math.abs(bounds.min.x), Math.abs(bounds.max.x)) - : Math.max(Math.abs(bounds.min.z), Math.abs(bounds.max.z)) - const axisCoord = rakeAxis === 'x' ? Math.abs(centroid.x) : Math.abs(centroid.z) - const planeTolerance = Math.max( - node.overhang + node.wallThickness + node.deckThickness + node.shingleThickness, - 0.25, - ) - - if (halfExtent - axisCoord > planeTolerance) return false - - return true -} - -function getRakeAxis(node: RoofSegmentNode): 'x' | 'z' | null { - if (node.roofType === 'gable' || node.roofType === 'gambrel') return 'x' - return null -} - type ShapeWidthRatios = { gambrelLowerWidthRatio: number mansardSteepWidthRatio: number @@ -4074,6 +5183,25 @@ export function getRoofOuterSurfaceFrameAtPoint( } } + const backTwin = getRoofSegmentBackSlopeTwin(segment) + if (backTwin) { + // Each slope's outer skin is its wall-line plane lifted by the deck and + // shingle thickness at that slope's pitch; the roof is the lower of the two. + const back = getSegmentSlopeFrame(backTwin) + const lift = deckThickness + shingleThickness + const frontY = wallHeight + (depth / 2 - lz) * tanTheta + lift / cosTheta + const backY = backTwin.wallHeight + (depth / 2 + lz) * back.tanTheta + lift / back.cosTheta + return frontY <= backY + ? { + point: new THREE.Vector3(lx, frontY, lz), + normal: new THREE.Vector3(0, cosTheta, sinTheta), + } + : { + point: new THREE.Vector3(lx, backY, lz), + normal: new THREE.Vector3(0, back.cosTheta, -back.sinTheta), + } + } + const verticalRt = deckThickness / cosTheta const horizontalOverhang = overhang * cosTheta const deckExt = wallThickness / 2 + horizontalOverhang @@ -4182,7 +5310,13 @@ export function getRoofOuterSurfaceFrameAtPoint( if (transZ !== 0) topGeo.translate(0, 0, transZ) topGeo.computeBoundingBox() - const topY = wallHeight + activeRh + deckThickness + shingleThickness + 10 + const topY = + wallHeight + + activeRh + + Math.max(0, readGableRidgeStep(segment)) + + deckThickness + + shingleThickness + + 10 _surfaceOrigin.set(lx, topY, lz) _surfaceRay.set(_surfaceOrigin, _surfaceDir) _surfaceHits.length = 0 diff --git a/packages/viewer/src/systems/roof/roof-underside.ts b/packages/viewer/src/systems/roof/roof-underside.ts new file mode 100644 index 0000000000..7ae62c2dbe --- /dev/null +++ b/packages/viewer/src/systems/roof/roof-underside.ts @@ -0,0 +1,256 @@ +import { + type AnyNode, + type AnyNodeId, + type ColumnNode, + getLevelElevations, + getSegmentSlopeFrame, + type RoofNode, + type RoofSegmentNode, + resolveLevelId, +} from '@pascal-app/core' +import * as THREE from 'three' +import { getRoofSegmentUndersidePolygons } from './roof-system' + +/** + * Roof undersides as data: the planar pieces of every roof's deck bottom in + * building space. Walls are cut at them (`wall-roof-fit`), every other mesh too + * (`roof-clip`), and posts reach them. + */ + +/** A planar piece of a roof underside in building plan space. */ +export type RoofUndersidePatch = { + /** Plan polygon (x, z). */ + polygon: Array<[number, number]> + /** Underside height in building space: `y = a * x + b * z + c`. */ + a: number + b: number + c: number + ordinal: number + roofId: string + /** Vertical depth of deck and shingles: the roof's top is `underside + thickness`. */ + thickness: number + minX: number + maxX: number + minZ: number + maxZ: number +} + +// Metres. A roof must clear a base by 1 mm to cap what stands on it (a deck +// lying on the base is under it, not over it). +export const ROOF_CLEARANCE = 1e-3 + +const patchMemo = new WeakMap>() + +export function rotatePlan(x: number, z: number, angle: number): [number, number] { + const cos = Math.cos(angle) + const sin = Math.sin(angle) + return [x * cos + z * sin, -x * sin + z * cos] +} + +function patchFromPolygon( + points: THREE.Vector3[], + owner: Pick, +): RoofUndersidePatch | null { + // Least-degenerate plane through the polygon (Newell normal + centroid). + const normal = new THREE.Vector3() + const centroid = new THREE.Vector3() + for (let index = 0; index < points.length; index++) { + const current = points[index]! + const next = points[(index + 1) % points.length]! + normal.x += (current.y - next.y) * (current.z + next.z) + normal.y += (current.z - next.z) * (current.x + next.x) + normal.z += (current.x - next.x) * (current.y + next.y) + centroid.add(current) + } + centroid.divideScalar(points.length) + if (!(Math.abs(normal.y) > 1e-9)) return null + const a = -normal.x / normal.y + const b = -normal.z / normal.y + const c = centroid.y - a * centroid.x - b * centroid.z + const polygon = points.map((point) => [point.x, point.z] as [number, number]) + return { + polygon, + a, + b, + c, + ...owner, + minX: Math.min(...polygon.map((point) => point[0])), + maxX: Math.max(...polygon.map((point) => point[0])), + minZ: Math.min(...polygon.map((point) => point[1])), + maxZ: Math.max(...polygon.map((point) => point[1])), + } +} + +/** + * Roof underside patches of every roof, grouped by building, in building + * space. Memoised on the immutable `nodes` record. + */ +export function getRoofUndersidePatches( + nodes: Readonly>, +): Map { + const memoized = patchMemo.get(nodes) + if (memoized) return memoized + const elevations = getLevelElevations(nodes as Record) + const byBuilding = new Map() + for (const node of Object.values(nodes)) { + // Hidden roofs still count: visibility is presentation, the walls are physical. + if (node?.type !== 'roof') continue + const roof = node as RoofNode + const levelId = resolveLevelId(roof, nodes as Record) + const level = elevations.get(levelId) + if (!level) continue + for (const childId of roof.children ?? []) { + const segment = nodes[childId] + if (segment?.type !== 'roof-segment') continue + const polygons = getRoofSegmentUndersidePolygons(segment as RoofSegmentNode) + if (!polygons) continue + const seg = segment as RoofSegmentNode + const { cosTheta } = getSegmentSlopeFrame(seg) + const thickness = + seg.deckThickness / Math.max(0.1, cosTheta) + seg.shingleThickness * cosTheta + for (const polygon of polygons) { + const points = polygon.map((point) => { + const [sx, sz] = rotatePlan(point.x, point.z, seg.rotation ?? 0) + const [rx, rz] = rotatePlan( + seg.position[0] + sx, + seg.position[2] + sz, + roof.rotation ?? 0, + ) + return new THREE.Vector3( + roof.position[0] + rx, + level.baseY + roof.position[1] + seg.position[1] + point.y, + roof.position[2] + rz, + ) + }) + const patch = patchFromPolygon(points, { + ordinal: level.ordinal, + roofId: roof.id, + thickness, + }) + if (!patch) continue + const list = byBuilding.get(level.buildingId) ?? [] + list.push(patch) + byBuilding.set(level.buildingId, list) + } + } + } + patchMemo.set(nodes, byBuilding) + return byBuilding +} + +export function pointInPolygon(x: number, z: number, polygon: Array<[number, number]>): boolean { + let inside = false + for (let i = 0, j = polygon.length - 1; i < polygon.length; j = i++) { + const [xi, zi] = polygon[i]! + const [xj, zj] = polygon[j]! + if (zi > z !== zj > z && x < ((xj - xi) * (z - zi)) / (zj - zi) + xi) inside = !inside + } + return inside +} + +export function distanceToSegment(x: number, z: number, a: [number, number], b: [number, number]) { + const dx = b[0] - a[0] + const dz = b[1] - a[1] + const lengthSq = dx * dx + dz * dz + const t = + lengthSq > 0 ? Math.min(1, Math.max(0, ((x - a[0]) * dx + (z - a[1]) * dz) / lengthSq)) : 0 + return Math.hypot(x - (a[0] + dx * t), z - (a[1] + dz * t)) +} + +export function patchHeight(patch: RoofUndersidePatch, x: number, z: number) { + return patch.a * x + patch.b * z + patch.c +} + +/** + * The lowest roof underside above `base` at a plan point, skipping `except`. + * Heights are in the patches' frame. + */ +export function capPatchAt( + patches: readonly RoofUndersidePatch[], + x: number, + z: number, + base: number, + except?: RoofUndersidePatch, +) { + let best: RoofUndersidePatch | null = null + let bestHeight = Number.POSITIVE_INFINITY + for (const patch of patches) { + if (patch === except) continue + if (x < patch.minX || x > patch.maxX || z < patch.minZ || z > patch.maxZ) continue + if (!pointInPolygon(x, z, patch.polygon)) continue + const height = patchHeight(patch, x, z) + if (height > base + ROOF_CLEARANCE && height < bestHeight) { + best = patch + bestHeight = height + } + } + return best ? { patch: best, height: bestHeight } : null +} + +/** Patches of the building that holds `levelId`, heights relative to that level's floor. */ +export function getLevelRoofPatches( + nodes: Readonly>, + levelId: string, +): { + patches: RoofUndersidePatch[] + level: { baseY: number; height: number; ordinal: number; buildingId: string | null } +} | null { + const level = getLevelElevations(nodes as Record).get(levelId) + if (!level) return null + const candidates = getRoofUndersidePatches(nodes).get(level.buildingId) + if (!candidates?.length) return null + return { patches: candidates.map((patch) => ({ ...patch, c: patch.c - level.baseY })), level } +} + +/** Plan parameter `t` on a→b where it crosses c→d, if the segments cross. */ +export function segmentCrossing( + a: [number, number], + b: [number, number], + c: [number, number], + d: [number, number], +): number | null { + const rx = b[0] - a[0] + const rz = b[1] - a[1] + const sx = d[0] - c[0] + const sz = d[1] - c[1] + const denominator = rx * sz - rz * sx + if (Math.abs(denominator) < 1e-12) return null + const qx = c[0] - a[0] + const qz = c[1] - a[1] + const t = (qx * sz - qz * sx) / denominator + const u = (qx * rz - qz * rx) / denominator + if (u < -1e-9 || u > 1 + 1e-9) return null + return t +} + +/** + * Height a column reaches to meet the roof above it: the lowest roof underside + * over the column's centre, above its base. A column under a roof is a post — + * it is cut by a lower roof and stretched to a higher one, whatever its own + * height. Only a roof of its own storey or of the one right above counts: a + * roof over a higher storey has floors between. Null when no roof is over it + * (the column keeps its height). + */ +export function resolveColumnRoofHeight( + column: Pick, + nodes: Readonly>, + /** Level-local Y the column stands on — its slab lift included. */ + base = column.position[1], +): number | null { + const levelId = resolveLevelId(column as AnyNode, nodes as Record) + const cover = getLevelRoofPatches(nodes, levelId) + if (!cover) return null + const { ordinal, buildingId } = cover.level + let above = Number.POSITIVE_INFINITY + for (const level of getLevelElevations(nodes as Record).values()) { + if (level.buildingId === buildingId && level.ordinal > ordinal) { + above = Math.min(above, level.ordinal) + } + } + const patches = cover.patches.filter( + (patch) => patch.ordinal === ordinal || patch.ordinal === above, + ) + const [x, , z] = column.position + const cap = capPatchAt(patches, x, z, base) + return cap ? cap.height - base : null +} diff --git a/packages/viewer/src/systems/wall/wall-progressive-budget.test.ts b/packages/viewer/src/systems/wall/wall-progressive-budget.test.ts index 7e8c494c41..45169b8582 100644 --- a/packages/viewer/src/systems/wall/wall-progressive-budget.test.ts +++ b/packages/viewer/src/systems/wall/wall-progressive-budget.test.ts @@ -693,7 +693,7 @@ test('a new hydration resets counters and pending neighbours; node stats preserv import { mock } from 'bun:test' const react = require('react') mock.module('react', () => ({ ...react, default: react, useEffect: (effect) => { globalThis.wallCleanup = effect() } })) -mock.module('@react-three/fiber', () => ({ useFrame: (frame) => { globalThis.wallFrame = frame } })) +mock.module('@react-three/fiber', () => ({ useFrame: (frame) => { globalThis.wallFrame = frame }, addAfterEffect: () => () => {}, invalidate: () => {} })) const core = require(${sourcePath('packages/core/src/index.ts')}) const storeWithoutHooks = (store) => Object.assign((selector) => selector(store.getState()), store) mock.module('@pascal-app/core', () => ({ ...core, useScene: storeWithoutHooks(core.useScene), useLiveNodeOverrides: storeWithoutHooks(core.useLiveNodeOverrides) })) diff --git a/packages/viewer/src/systems/wall/wall-roof-fit.test.ts b/packages/viewer/src/systems/wall/wall-roof-fit.test.ts new file mode 100644 index 0000000000..0b232080c7 --- /dev/null +++ b/packages/viewer/src/systems/wall/wall-roof-fit.test.ts @@ -0,0 +1,324 @@ +// @ts-expect-error — bun:test is provided by the Bun runtime; viewer does not +// depend on @types/bun so the import type is unresolved at compile time. +import { describe, expect, test } from 'bun:test' +import { + type AnyNode, + BuildingNode, + ColumnNode, + calculateLevelMiters, + LevelNode, + RoofNode, + RoofSegmentNode, + WallNode, +} from '@pascal-app/core' +import * as THREE from 'three' +import { resolveColumnRoofHeight } from '../roof/roof-underside' +import { resolveWallRoofCover, syncWallRoofFit, wallRoofCoverSignature } from './wall-roof-fit' +import { generateExtrudedWall } from './wall-system' + +const TAN17 = Math.tan((17 * Math.PI) / 180) +const TAN23 = Math.tan((23 * Math.PI) / 180) +const STOREY = 3.05 + +type SegmentInput = Partial & { id: string } +type WallInput = Partial & { id: string; start: [number, number]; end: [number, number] } + +/** + * One building: storey `level_0` (3.05 m) and an empty `level_1` holding the + * roofs flagged `upper` — a separate "roof level" above the storey. + */ +function scene(input: { + roofs: Array<{ + id: string + upper?: boolean + position?: [number, number, number] + segments: SegmentInput[] + }> + walls: Array +}): Record { + const nodes: Record = {} + const add = (node: AnyNode) => { + nodes[node.id] = node + } + const level0: string[] = [] + const level1: string[] = [] + for (const roof of input.roofs) { + ;(roof.upper ? level1 : level0).push(roof.id) + add( + RoofNode.parse({ + id: roof.id, + type: 'roof', + parentId: roof.upper ? 'level_1' : 'level_0', + position: roof.position ?? [0, 0, 0], + children: roof.segments.map((segment) => segment.id), + }), + ) + for (const segment of roof.segments) { + add( + RoofSegmentNode.parse({ + type: 'roof-segment', + parentId: roof.id, + roofType: 'shed', + overhang: 0, + wallThickness: 0.1, + deckThickness: 0.2, + wallShell: 'omit', + ...segment, + }), + ) + } + } + for (const wall of input.walls) { + const { upper, ...data } = wall + ;(upper ? level1 : level0).push(wall.id) + add( + WallNode.parse({ + type: 'wall', + thickness: 0.3, + parentId: upper ? 'level_1' : 'level_0', + ...data, + }), + ) + } + add(BuildingNode.parse({ id: 'building_a', type: 'building', children: ['level_0', 'level_1'] })) + add( + LevelNode.parse({ + id: 'level_0', + type: 'level', + parentId: 'building_a', + level: 0, + height: STOREY, + children: level0, + }), + ) + add( + LevelNode.parse({ + id: 'level_1', + type: 'level', + parentId: 'building_a', + level: 1, + height: 2.5, + children: level1, + }), + ) + return nodes +} + +function build(nodes: Record, wallId: string, storeyHeight = STOREY) { + const wall = nodes[wallId] as WallNode + const walls = Object.values(nodes).filter( + (node): node is WallNode => node.type === 'wall' && node.parentId === wall.parentId, + ) + return generateExtrudedWall( + wall, + [], + calculateLevelMiters(walls), + 0, + 0, + undefined, + storeyHeight, + undefined, + undefined, + undefined, + undefined, + resolveWallRoofCover(wall, nodes), + ) +} + +/** Wall top (mesh-local Y) at wall-local x along the axis, `z` across it. */ +function topAt(geometry: THREE.BufferGeometry, x: number, z = 0): number | null { + const mesh = new THREE.Mesh(geometry, new THREE.MeshBasicMaterial({ side: THREE.DoubleSide })) + const hits = new THREE.Raycaster( + new THREE.Vector3(x, 50, z), + new THREE.Vector3(0, -1, 0), + ).intersectObject(mesh) + return hits[0]?.point.y ?? null +} + +/** The addition: two sheds, 17° north / 23° south, eaves 0.5 m above the roof level. */ +function gableRoof(extraSouth: Partial = {}) { + return { + id: 'roof_gable', + upper: true, + position: [5, 0, 0] as [number, number, number], + segments: [ + { + id: 'rseg_north', + width: 10, + depth: 4, + pitch: 17, + wallHeight: 0.5, + rotation: Math.PI, + position: [0, 0, -2] as [number, number, number], + }, + { + id: 'rseg_south', + width: 10, + depth: 4, + pitch: 23, + wallHeight: 0.5, + position: [0, 0, 2] as [number, number, number], + ...extraSouth, + }, + ], + } +} + +const northUnderside = (z: number) => STOREY + 0.5 + (z + 4) * TAN17 +const southUnderside = (z: number) => STOREY + 0.5 + (4 - z) * TAN23 + +/** A closed rectangle of exterior walls 0.3 m thick, centred on x0..x1 × z0..z1. */ +function box(x0: number, z0: number, x1: number, z1: number): WallInput[] { + const sides = { frontSide: 'exterior' as const, backSide: 'interior' as const } + return [ + { id: 'wall_n', start: [x0, z0], end: [x1, z0], ...sides }, + { id: 'wall_e', start: [x1, z0], end: [x1, z1], ...sides }, + { id: 'wall_s', start: [x1, z1], end: [x0, z1], ...sides }, + { id: 'wall_w', start: [x0, z1], end: [x0, z0], ...sides }, + ] +} + +describe('walls cut by the roof above', () => { + test('a wall under a higher roof keeps the storey height', () => { + const nodes = scene({ roofs: [gableRoof()], walls: box(0, -3.5, 10, 3.5) }) + const geometry = build(nodes, 'wall_w') + geometry.computeBoundingBox() + expect(geometry.boundingBox!.max.y).toBeCloseTo(STOREY, 6) + geometry.dispose() + }) + + test('a low roof on the same level cuts every wall under it, half walls included', () => { + const nodes = scene({ + roofs: [ + { + id: 'roof_low', + position: [5, 0, 0], + segments: [ + { + id: 'rseg_low', + width: 10, + depth: 6, + pitch: 17, + wallHeight: 2.2, + rotation: Math.PI, + position: [0, 0, -1], + }, + ], + }, + ], + walls: [ + { + id: 'wall_front', + start: [0, -3], + end: [10, -3], + frontSide: 'exterior', + backSide: 'interior', + }, + { id: 'wall_partition', start: [5, -3.5], end: [5, 1.5], thickness: 0.1 }, + { id: 'wall_half', start: [2, -3.5], end: [2, -2], thickness: 0.1, height: 3 }, + ], + }) + // Eave at z = -4: underside 2.2 + (z + 4) tan 17°. + const low = (z: number) => 2.2 + (z + 4) * TAN17 + const front = build(nodes, 'wall_front') + expect(topAt(front, 3)).toBeCloseTo(low(-3), 3) + front.dispose() + const partition = build(nodes, 'wall_partition') + expect(topAt(partition, 0.5)).toBeCloseTo(low(-3), 3) + // Past z = -1.2 the roof is above the storey: the partition keeps 3.05. + expect(topAt(partition, 4.5)).toBeCloseTo(STOREY, 3) + partition.dispose() + const half = build(nodes, 'wall_half') + expect(topAt(half, 0.5)).toBeCloseTo(Math.min(3, low(-3)), 3) + half.dispose() + }) + + test('a wall outside every roof outline keeps its geometry', () => { + const nodes = scene({ + roofs: [gableRoof()], + walls: [ + { + id: 'wall_far', + start: [20, -4], + end: [20, 4], + frontSide: 'exterior', + backSide: 'interior', + }, + ], + }) + expect(resolveWallRoofCover(nodes.wall_far as WallNode, nodes)).toBeNull() + }) + + test('a roof edit marks only the walls whose cover changed', () => { + const nodes = scene({ + roofs: [ + { + id: 'roof_low', + position: [5, 0, 0], + segments: [ + { + id: 'rseg_low', + width: 10, + depth: 6, + pitch: 17, + wallHeight: 2.2, + rotation: Math.PI, + position: [0, 0, -1], + }, + ], + }, + ], + walls: [ + { id: 'wall_front', start: [0, -3], end: [10, -3] }, + { id: 'wall_far', start: [20, -4], end: [20, 4] }, + ], + }) + const dirty: string[] = [] + syncWallRoofFit(nodes, {}, (id) => dirty.push(id)) + expect(dirty).toEqual(['wall_front']) + expect(wallRoofCoverSignature(resolveWallRoofCover(nodes.wall_far as WallNode, nodes))).toBe('') + }) +}) + +describe('posts under a roof', () => { + test('a post under a roof reaches its underside, up or down', () => { + const nodes = scene({ roofs: [gableRoof()], walls: [] }) + const post = (x: number, z: number) => + ColumnNode.parse({ type: 'column', parentId: 'level_0', position: [x, 0, z], height: 3 }) + expect(resolveColumnRoofHeight(post(2, -3.8), nodes)).toBeCloseTo(northUnderside(-3.8), 4) + expect(resolveColumnRoofHeight(post(2, 3), nodes)).toBeCloseTo(southUnderside(3), 4) + expect(resolveColumnRoofHeight(post(20, 0), nodes)).toBeNull() + // On a 0.4 m slab the post is shorter by the lift, so its top still meets the underside. + expect(resolveColumnRoofHeight(post(2, 3), nodes, 0.4)).toBeCloseTo(southUnderside(3) - 0.4, 4) + }) + + test('a roof over a higher storey does not reach a post below: floors are between', () => { + // the roof on a third level, over a second storey + const nodes = scene({ roofs: [{ ...gableRoof(), upper: true }], walls: [] }) + const roofId = (nodes.level_1 as LevelNode).children[0]! + nodes.level_1 = { ...nodes.level_1, children: [] } as AnyNode + nodes.level_2 = LevelNode.parse({ + id: 'level_2', + type: 'level', + parentId: 'building_a', + level: 2, + height: 2.5, + children: [roofId], + }) + nodes.building_a = { + ...nodes.building_a, + children: ['level_0', 'level_1', 'level_2'], + } as AnyNode + nodes[roofId] = { ...nodes[roofId], parentId: 'level_2' } as AnyNode + const post = ColumnNode.parse({ + type: 'column', + parentId: 'level_0', + position: [2, 0, 3], + height: 3, + }) + expect(resolveColumnRoofHeight(post, nodes)).toBeNull() + // on the storey right under the roof it reaches it + const upper = ColumnNode.parse({ ...post, id: undefined, parentId: 'level_1' }) + expect(resolveColumnRoofHeight(upper, nodes)).not.toBeNull() + }) +}) diff --git a/packages/viewer/src/systems/wall/wall-roof-fit.ts b/packages/viewer/src/systems/wall/wall-roof-fit.ts new file mode 100644 index 0000000000..9c8ff808f4 --- /dev/null +++ b/packages/viewer/src/systems/wall/wall-roof-fit.ts @@ -0,0 +1,371 @@ +import { type AnyNode, resolveLevelId, type WallNode } from '@pascal-app/core' +import * as THREE from 'three' +import { + capPatchAt, + getLevelRoofPatches, + patchHeight, + ROOF_CLEARANCE, + type RoofUndersidePatch, + segmentCrossing, +} from '../roof/roof-underside' + +/** + * Walls cut by the roof above them. + * + * A roof whose underside (the bottom of the deck) covers a wall's centreline + * below the wall top cuts the wall there — every wall, explicit height or + * not, so nothing pokes through a roof. Walls never grow towards a roof: what + * closes the attic is the roof's business, not the room layout below. Every + * other mesh is cut by `roof-clip`. + * + * Any roof in the wall's building counts while its underside is above the + * wall's base. Only 3D geometry changes: the plan, stored heights, the spatial + * grid and the roof elevation that follows wall tops keep the storey height. + */ + +export type WallRoofCover = { + /** Patches near the wall, heights in the wall's level-local frame. */ + patches: RoofUndersidePatch[] +} + +export type WallRoofStation = { + /** Wall-local x (along the wall). */ + x: number + /** Cap heights (level-local) on the low-z and high-z cutter sides, just before `x`. */ + before: [number, number] + /** Same, just after `x`. */ + after: [number, number] +} + +export type WallRoofProfile = { + stations: WallRoofStation[] + /** Wall-local z of the two cutter sides. */ + zMin: number + zMax: number + /** Highest cap, level-local. */ + maxTop: number +} + +// Sampling offset either side of a station: well under any modelled feature, +// well above float noise at house coordinates. +const STATION_EPSILON = 1e-4 +const HEIGHT_EPSILON = 1e-4 +// The cutter overhangs the wall footprint so CSG never meets coplanar faces. +const CUTTER_SIDE_MARGIN = 0.02 +const CUTTER_END_MARGIN = 0.02 +const CUTTER_HEADROOM = 1 + +function wallPlanBounds(wall: WallNode) { + const pad = (wall.thickness ?? 0.2) + Math.abs(wall.curveOffset ?? 0) + 1 + return { + minX: Math.min(wall.start[0], wall.end[0]) - pad, + maxX: Math.max(wall.start[0], wall.end[0]) + pad, + minZ: Math.min(wall.start[1], wall.end[1]) - pad, + maxZ: Math.max(wall.start[1], wall.end[1]) + pad, + } +} + +/** + * The roofs that can cut `wall`, or null when no roof reaches it (the wall + * then builds exactly as before). + */ +export function resolveWallRoofCover( + wall: WallNode, + nodes: Readonly>, +): WallRoofCover | null { + const levelId = resolveLevelId(wall, nodes as Record) + const level = getLevelRoofPatches(nodes, levelId) + if (!level) return null + const bounds = wallPlanBounds(wall) + const patches = level.patches.filter( + (patch) => + patch.maxX >= bounds.minX && + patch.minX <= bounds.maxX && + patch.maxZ >= bounds.minZ && + patch.minZ <= bounds.maxZ, + ) + return patches.length > 0 ? { patches } : null +} + +/** + * Cap heights along the wall, sampled where the cap can change: wall ends, + * roof outline crossings of the centreline, and where two roof planes (or a + * roof plane and the wall top) cross along it. Between stations one plane + * (or the flat top) caps the wall, so the profile is exact for straight walls. + * + * `toPlan` maps wall-local (x, z) to building plan space; `xRange` / `zRange` + * bound the wall's local footprint; heights are level-local. + */ +export function buildWallRoofProfile(input: { + cover: WallRoofCover + toPlan: (x: number, z: number) => [number, number] + xRange: [number, number] + zRange: [number, number] + normalTop: number + base: number +}): WallRoofProfile | null { + const { cover, toPlan, normalTop, base } = input + const x0 = input.xRange[0] - CUTTER_END_MARGIN + const x1 = input.xRange[1] + CUTTER_END_MARGIN + const zMin = input.zRange[0] - CUTTER_SIDE_MARGIN + const zMax = input.zRange[1] + CUTTER_SIDE_MARGIN + const zMid = (input.zRange[0] + input.zRange[1]) / 2 + if (!(x1 - x0 > 1e-6)) return null + + const centerStart = toPlan(x0, zMid) + const centerEnd = toPlan(x1, zMid) + const xs = new Set([x0, x1]) + const addT = (t: number) => { + if (t > 0 && t < 1) xs.add(x0 + (x1 - x0) * t) + } + for (const patch of cover.patches) { + for (let index = 0; index < patch.polygon.length; index++) { + const t = segmentCrossing( + centerStart, + centerEnd, + patch.polygon[index]!, + patch.polygon[(index + 1) % patch.polygon.length]!, + ) + if (t !== null) addT(t) + } + } + // Height of a plane along the centreline is linear in t: h(t) = h0 + (h1 - h0) t. + const along = cover.patches.map( + (patch) => [patchHeight(patch, ...centerStart), patchHeight(patch, ...centerEnd)] as const, + ) + const levels = [normalTop, base + ROOF_CLEARANCE] + for (let i = 0; i < along.length; i++) { + const [hi0, hi1] = along[i]! + for (const level of levels) { + if (Math.abs(hi1 - hi0) > 1e-12) addT((level - hi0) / (hi1 - hi0)) + } + for (let j = i + 1; j < along.length; j++) { + const [hj0, hj1] = along[j]! + const slope = hi1 - hi0 - (hj1 - hj0) + if (Math.abs(slope) > 1e-12) addT((hj0 - hi0) / slope) + } + } + + const sampleCap = (x: number): [number, number] => { + const cap = capPatchAt(cover.patches, ...toPlan(x, zMid), base) + if (!cap || cap.height >= normalTop) return [normalTop, normalTop] + return [ + Math.min(patchHeight(cap.patch, ...toPlan(x, zMin)), normalTop), + Math.min(patchHeight(cap.patch, ...toPlan(x, zMax)), normalTop), + ] + } + + const sorted = [...xs].sort((a, b) => a - b) + const stations: WallRoofStation[] = [] + for (const x of sorted) { + if (stations.length > 0 && x - stations[stations.length - 1]!.x < STATION_EPSILON * 4) continue + stations.push({ + x, + before: x > x0 ? sampleCap(x - STATION_EPSILON) : sampleCap(x + STATION_EPSILON), + after: x < x1 ? sampleCap(x + STATION_EPSILON) : sampleCap(x - STATION_EPSILON), + }) + } + // The last kept station must close the cutter at the far end. + const last = stations[stations.length - 1]! + if (last.x < x1) { + last.x = x1 + last.before = sampleCap(x1 - STATION_EPSILON) + last.after = last.before + } + + const changed = stations.some((station) => + [...station.before, ...station.after].some( + (height) => Math.abs(height - normalTop) > HEIGHT_EPSILON, + ), + ) + return changed ? { stations, zMin, zMax, maxTop: normalTop } : null +} + +/** + * A closed solid holding everything above the profile, up to `maxTop` + * plus headroom, in wall-local space shifted by `yOffset` (level-local → + * mesh-local). Subtracting it from the wall prism leaves the roof-fitted wall. + */ +export function buildWallRoofCutterGeometry( + profile: WallRoofProfile, + yOffset: number, +): THREE.BufferGeometry { + const { stations, zMin, zMax } = profile + const top = profile.maxTop + CUTTER_HEADROOM + yOffset + const positions: number[] = [] + const v = (x: number, y: number, z: number) => new THREE.Vector3(x, y, z) + const scratchA = new THREE.Vector3() + const scratchB = new THREE.Vector3() + const pushTriangle = ( + a: THREE.Vector3, + b: THREE.Vector3, + c: THREE.Vector3, + out: THREE.Vector3, + ) => { + const normal = scratchA.subVectors(b, a).cross(scratchB.subVectors(c, a)) + if (normal.lengthSq() < 1e-16) return + if (normal.dot(out) < 0) [b, c] = [c, b] + positions.push(a.x, a.y, a.z, b.x, b.y, b.z, c.x, c.y, c.z) + } + const pushPolygon = (points: THREE.Vector3[], out: THREE.Vector3) => { + // Planar, axis-aligned faces: triangulate in the two in-plane axes. + const axisU = Math.abs(out.x) > 0.5 ? 'z' : 'x' + const axisV = Math.abs(out.y) > 0.5 ? 'z' : 'y' + const unique = points.filter( + (point, index) => point.distanceToSquared(points[(index + 1) % points.length]!) > 1e-14, + ) + if (unique.length < 3) return + const contour = unique.map((point) => new THREE.Vector2(point[axisU], point[axisV])) + for (const [a, b, c] of THREE.ShapeUtils.triangulateShape(contour, [])) { + pushTriangle(unique[a!]!, unique[b!]!, unique[c!]!, out) + } + } + const down = v(0, -1, 0) + const up = v(0, 1, 0) + const sideMin = v(0, 0, -1) + const sideMax = v(0, 0, 1) + + const bottom = (station: WallRoofStation, which: 'before' | 'after', side: 0 | 1) => + v(station.x, station[which][side] + yOffset, side === 0 ? zMin : zMax) + + for (let index = 0; index < stations.length - 1; index++) { + const a = stations[index]! + const b = stations[index + 1]! + const a0 = bottom(a, 'after', 0) + const a1 = bottom(a, 'after', 1) + const b0 = bottom(b, 'before', 0) + const b1 = bottom(b, 'before', 1) + pushTriangle(a0, a1, b1, down) + pushTriangle(a0, b1, b0, down) + pushPolygon([v(a.x, top, zMin), v(b.x, top, zMin), v(b.x, top, zMax), v(a.x, top, zMax)], up) + // Sides: include each station's other bottom vertex so the faces share + // every vertex with the risers (no T-junctions). + for (const side of [0, 1] as const) { + const z = side === 0 ? zMin : zMax + const ring = [bottom(a, 'after', side), bottom(b, 'before', side)] + if (index + 1 < stations.length - 1) { + const next = bottom(b, 'after', side) + if (next.y > ring[1]!.y) ring.push(next) + } + ring.push(v(b.x, top, z), v(a.x, top, z)) + if (index > 0) { + const previous = bottom(a, 'before', side) + if (previous.y > ring[0]!.y) ring.push(previous) + } + pushPolygon(ring, side === 0 ? sideMin : sideMax) + } + } + + // Risers where the cap steps at a station; outward is towards the higher side. + for (let index = 1; index < stations.length - 1; index++) { + const station = stations[index]! + const lb = bottom(station, 'before', 0) + const la = bottom(station, 'after', 0) + const rb = bottom(station, 'before', 1) + const ra = bottom(station, 'after', 1) + const dl = la.y - lb.y + const dr = ra.y - rb.y + if (Math.abs(dl) < 1e-9 && Math.abs(dr) < 1e-9) continue + if (dl * dr >= 0) { + const out = v(dl + dr > 0 ? 1 : -1, 0, 0) + pushTriangle(lb, la, ra, out) + pushTriangle(lb, ra, rb, out) + } else { + const t = dl / (dl - dr) + const cross = lb.clone().lerp(rb, t) + pushTriangle(lb, la, cross, v(dl > 0 ? 1 : -1, 0, 0)) + pushTriangle(cross, ra, rb, v(dr > 0 ? 1 : -1, 0, 0)) + } + } + + const first = stations[0]! + const last = stations[stations.length - 1]! + pushPolygon( + [ + bottom(first, 'after', 0), + bottom(first, 'after', 1), + v(first.x, top, zMax), + v(first.x, top, zMin), + ], + v(-1, 0, 0), + ) + pushPolygon( + [ + bottom(last, 'before', 0), + bottom(last, 'before', 1), + v(last.x, top, zMax), + v(last.x, top, zMin), + ], + v(1, 0, 0), + ) + + const geometry = new THREE.BufferGeometry() + geometry.setAttribute('position', new THREE.Float32BufferAttribute(positions, 3)) + geometry.computeVertexNormals() + return geometry +} + +const roofWallSignatures = new Map() + +/** Fingerprint of the roofs that can cut a wall: a change rebuilds the wall. */ +export function wallRoofCoverSignature(cover: WallRoofCover | null): string { + if (!cover) return '' + const round = (value: number) => value.toFixed(4) + return JSON.stringify( + cover.patches.map((patch) => [ + round(patch.a), + round(patch.b), + round(patch.c), + patch.polygon.map(([x, z]) => `${round(x)},${round(z)}`).join(' '), + ]), + ) +} + +export function rememberWallRoofSignature(wallId: string, signature: string) { + if (signature) roofWallSignatures.set(wallId, signature) + else roofWallSignatures.delete(wallId) +} + +function isRoofInput(node: AnyNode | undefined): boolean { + const type = node?.type + return type === 'roof' || type === 'roof-segment' || type === 'level' || type === 'building' +} + +/** Whether a scene change touched anything a roof underside is built from. */ +export function roofInputsChanged( + nodes: Readonly>, + previousNodes: Readonly>, +): boolean { + for (const id in nodes) { + if ( + nodes[id] !== previousNodes[id] && + (isRoofInput(nodes[id]) || isRoofInput(previousNodes[id])) + ) + return true + } + for (const id in previousNodes) { + if (!nodes[id] && isRoofInput(previousNodes[id])) return true + } + return false +} + +/** + * Marks the walls whose roof cover changed. Roof edits do not touch walls in + * the scene, so without this a wall would keep the cap of the roof it was + * built under. + */ +export function syncWallRoofFit( + nodes: Readonly>, + previousNodes: Readonly>, + markDirty: (id: string) => void, +) { + if (nodes === previousNodes || !roofInputsChanged(nodes, previousNodes)) return + for (const wallId of roofWallSignatures.keys()) { + if (nodes[wallId]?.type !== 'wall') roofWallSignatures.delete(wallId) + } + for (const node of Object.values(nodes)) { + if (node?.type !== 'wall') continue + const signature = wallRoofCoverSignature(resolveWallRoofCover(node as WallNode, nodes)) + if (signature !== (roofWallSignatures.get(node.id) ?? '')) markDirty(node.id) + } +} diff --git a/packages/viewer/src/systems/wall/wall-system.tsx b/packages/viewer/src/systems/wall/wall-system.tsx index 5e0ca25833..bed12db497 100644 --- a/packages/viewer/src/systems/wall/wall-system.tsx +++ b/packages/viewer/src/systems/wall/wall-system.tsx @@ -74,6 +74,15 @@ import { } from './wall-finish-data' import { sweepUnbuiltWalls, WALL_PLACEHOLDER_SWEEP_INTERVAL } from './wall-placeholder-sweep' import { notifyWallRebuilt } from './wall-rebuild-notifications' +import { + buildWallRoofCutterGeometry, + buildWallRoofProfile, + rememberWallRoofSignature, + resolveWallRoofCover, + syncWallRoofFit, + type WallRoofCover, + wallRoofCoverSignature, +} from './wall-roof-fit' export { isWallInitialBuildActive } from './wall-build-lifecycle' export { drainRebuiltWalls } from './wall-rebuild-notifications' @@ -733,6 +742,13 @@ export const WallSystem = ({ geometryAdapter }: { geometryAdapter?: WallGeometry }, [], ) + useEffect( + () => + useScene.subscribe((state, previous) => + syncWallRoofFit(state.nodes, previous.nodes, (id) => state.markDirty(id as AnyNodeId)), + ), + [], + ) useFrame(() => runWallBuildFrame(geometryAdapter), 4) return null } @@ -1177,6 +1193,8 @@ function updateWallGeometry( containsPoint(fillMasks, [x, z]) ? slabElevation : terrainSupportLift(nodes, levelId, x, z) : undefined + const roofCover = resolveWallRoofCover(node, nodes) + rememberWallRoofSignature(wallId, wallRoofCoverSignature(roofCover)) const builtGeo = generateExtrudedWall( node, prepared.envelopeChildren, @@ -1188,7 +1206,12 @@ function updateWallGeometry( terrainBottomAt, slabSupport.faceDatum, buildWallFinishLayout(node, getCachedLevelZones(node, nodes)), + undefined, + roofCover, ) + // Without children the collision body is the envelope itself: reuse it + // instead of running the extrusion (and its roof CSG) a second time. + const envelopeCopy = prepared.envelopeChildren.length === 0 ? builtGeo.clone() : null const wallAngle = Math.atan2(node.end[1] - node.start[1], node.end[0] - node.start[0]) // World transform the render mesh will apply (position + Y-rotation below). // Reproduce it here so the UVs can be projected in WORLD space — see @@ -1211,19 +1234,26 @@ function updateWallGeometry( // Update collision mesh const collisionMesh = mesh.getObjectByName('collision-mesh') as THREE.Mesh if (collisionMesh) { - const collisionGeo = generateExtrudedWall( - node, - [], - miterData, - slabElevation, - slabSupport.baseElevation, - slabSupport.baseSegments, - planeTop, - terrainBottomAt, - slabSupport.faceDatum, - ) + const collisionGeo = + envelopeCopy ?? + generateExtrudedWall( + node, + [], + miterData, + slabElevation, + slabSupport.baseElevation, + slabSupport.baseSegments, + planeTop, + terrainBottomAt, + slabSupport.faceDatum, + undefined, + undefined, + roofCover, + ) collisionMesh.geometry.dispose() collisionMesh.geometry = collisionGeo + } else { + envelopeCopy?.dispose() } mesh.position.set(node.start[0], slabElevation, node.start[1]) @@ -1535,6 +1565,45 @@ function buildWallFinishContext( return { layout, faceBase: { a: runs(faceBase.a), b: runs(faceBase.b) }, refs, foundation } } +/** + * The roof cap profile of a wall in its own local frame (see `wall-roof-fit`), + * or null when no roof changes the wall. + */ +function getWallRoofProfile( + wallNode: WallNode, + miterData: WallMiterData, + slabElevation: number, + storeyHeight: number, + roofCover: WallRoofCover | null | undefined, +) { + if (!roofCover) return null + const dx = wallNode.end[0] - wallNode.start[0] + const dz = wallNode.end[1] - wallNode.start[1] + const length = Math.hypot(dx, dz) + if (length < 1e-9) return null + const footprint = isCurvedWall(wallNode) + ? getWallSurfacePolygon(wallNode, 24) + : getWallPlanFootprint(wallNode, miterData) + if (footprint.length < 3) return null + const ux = dx / length + const uz = dz / length + // Same frame as the extruded prism: x along the wall, z = perp (start → end). + const toLocal = (point: Point2D) => { + const px = point.x - wallNode.start[0] + const pz = point.y - wallNode.start[1] + return { x: px * ux + pz * uz, z: -px * uz + pz * ux } + } + const local = footprint.map(toLocal) + return buildWallRoofProfile({ + cover: roofCover, + toPlan: (x, z) => [wallNode.start[0] + x * ux - z * uz, wallNode.start[1] + x * uz + z * ux], + xRange: [Math.min(...local.map((p) => p.x)), Math.max(...local.map((p) => p.x))], + zRange: [Math.min(...local.map((p) => p.z)), Math.max(...local.map((p) => p.z))], + normalTop: resolveWallTop(wallNode, storeyHeight, slabElevation), + base: slabElevation, + }) +} + export function generateExtrudedWall( wallNode: WallNode, childrenNodes: AnyNode[], @@ -1549,6 +1618,7 @@ export function generateExtrudedWall( faceBase?: { a: readonly WallSlabSupportSegment[]; b: readonly WallSlabSupportSegment[] }, finishLayout: WallFinishLayout = buildWallFinishLayout(wallNode, []), sceneNodes: Readonly> = useScene.getState().nodes, + roofCover?: WallRoofCover | null, ): THREE.BufferGeometry { const wallStart: Point2D = { x: wallNode.start[0], y: wallNode.start[1] } const wallEnd: Point2D = { x: wallNode.end[0], y: wallNode.end[1] } @@ -1576,7 +1646,15 @@ export function generateExtrudedWall( ) : Math.min(baseElevation, slabElevation) const localBottom = effectiveBaseElevation - slabElevation - const height = topElevation - effectiveBaseElevation + const roofProfile = getWallRoofProfile( + wallNode, + miterData, + slabElevation, + storeyHeight, + roofCover, + ) + const height = + Math.max(topElevation, roofProfile?.maxTop ?? topElevation) - effectiveBaseElevation // A slab at or above the storey plane leaves a plane-bound wall with no // body — bail before ExtrudeGeometry sees a non-positive depth. if (height <= 1e-9) { @@ -1802,7 +1880,7 @@ export function generateExtrudedWall( baseSegments, ), ] - if (cutoutBrushes.length === 0) { + if (cutoutBrushes.length === 0 && !roofProfile) { const splitGeometry = splitGeometryAtPlanes(geometry, finishPlanes.y, finishPlanes.x) splitGeometry.computeVertexNormals() assignWallMaterialGroups(splitGeometry, wallNode, boundaryEdges, finish) @@ -1822,6 +1900,7 @@ export function generateExtrudedWall( wallBrush.updateMatrixWorld() let mergedCutter: Brush | null = null + let roofCutter: Brush | null = null let resultBrush = wallBrush try { const properties: Array<[string, string]> = [] @@ -1845,12 +1924,28 @@ export function generateExtrudedWall( resultBrush = next } }) + if (roofProfile) { + // Separate from the opening union: the cutter spans the whole wall, so + // grouping it with openings would fold every opening into one union. + const cutterGeometry = buildWallRoofCutterGeometry(roofProfile, -slabElevation) + ensureRenderableGeometryAttributes(cutterGeometry) + computeGeometryBoundsTree(cutterGeometry) + roofCutter = new Brush(cutterGeometry) + prepareBrushForCSG(roofCutter) + const cutter = roofCutter + timeSpan('wall-roof-csg', () => { + const next = csgEvaluator.evaluate(resultBrush, cutter, SUBTRACTION) + if (resultBrush !== wallBrush) csgGeometry(resultBrush).dispose() + resultBrush = next + }) + } } catch (error) { if (resultBrush !== wallBrush) csgGeometry(resultBrush).dispose() throw error } finally { csgGeometry(wallBrush).dispose() if (mergedCutter) csgGeometry(mergedCutter).dispose() + if (roofCutter) csgGeometry(roofCutter).dispose() for (const brush of cutoutBrushes) csgGeometry(brush).dispose() }