first push

This commit is contained in:
jhartworks committed 2026-11-09 10:37:41 +01:00
commit 2a81b4a502
845 files changed
+356635

No files matched your search

+10
View File
@@ -0,0 +1,10 @@
// The merged geometry of one floor, split into modules in build/.
export { buildFloorGeometry, stairHoles } from "./build/build.ts";
export { FLOOR_LOOK, NEON, SLAB } from "./build/look.ts";
export { clipAlong, outlineOf } from "./build/outline.ts";
export { wallHeight } from "./build/placement.ts";
export type { FloorGeometry, OpeningInfo } from "./build/types.ts";
export type { WallPaint } from "./build/build.ts";
export { wallPaintOf } from "./build/solids.ts";
export { ALWAYS, CUT_OFFSET, GeoBuffer, LineBuffer, pushPrism, shade } from "./geo.ts";
+271
View File
@@ -0,0 +1,271 @@
import assert from "node:assert/strict";
import { test } from "node:test";
import type { BufferGeometry } from "three";
import { generateWalls } from "../../geometry/walls.ts";
import { newFloor, offsetAt, type Floor, type Furniture, type Opening, type Room, type Vec2 } from "../../model.ts";
import { ALWAYS, CUT_OFFSET, LOWER_OFFSET } from "../geo.ts";
import { buildFloorGeometry, stairHoles } from "./build.ts";
import { bucketWalls, placeOpenings, roofLimits, wallHeight, wallTops } from "./placement.ts";
import { clipAlong, counterClockwise, outlineOf, subtractSpans } from "./outline.ts";
import { mountBase } from "../../packs.ts";
const OUTER = 0.3;
const INNER = 0.1;
const room = (id: string, x0: number, z0: number, x1: number, z1: number): Room => ({ id, name: id, area_id: null, points: [[x0, z0], [x1, z0], [x1, z1], [x0, z1]], floor_material: "wood" });
const floorOf = (rooms: Room[], openings: Opening[] = [], furniture: Furniture[] = []): Floor => ({ ...newFloor("f", "F", 0), height: 2.6, cut_height: 1.2, rooms, openings, furniture });
const opening = (type: "door" | "window", roomId: string, edge: number, offset: number, width = 1): Opening =>
({ id: `${type}${edge}`, room_id: roomId, edge, offset, width, type, sill: type === "door" ? 0 : 0.9, height: type === "door" ? 2.05 : 1.3, hinge: "left", leaves: 1, swing: "in", cover: null, contact: null, contact2: null, tilt: null }) as Opening;
const near = (a: number, b: number, eps = 1e-6) => assert.ok(Math.abs(a - b) < eps, `${a} vs ${b}`);
type Seg = { from: number[]; to: number[]; fold: number };
const segments = (g: BufferGeometry): Seg[] => {
const p = g.getAttribute("position").array;
const f = g.getAttribute("fold").array;
return Array.from({ length: p.length / 6 }, (_, s) => ({ from: [p[s * 6], p[s * 6 + 1], p[s * 6 + 2]], to: [p[s * 6 + 3], p[s * 6 + 4], p[s * 6 + 5]], fold: f[s * 2] }));
};
const triangles = (g: BufferGeometry) => g.getAttribute("position").count / 3;
const horizontal = (s: Seg, y: number) => Math.abs(s.from[1] - y) < 1e-6 && Math.abs(s.to[1] - y) < 1e-6; // positions are 32-bit floats
const length = (s: Seg) => Math.hypot(s.to[0] - s.from[0], s.to[2] - s.from[2]);
test("walls fall into buckets: all interior walls in one, exterior walls by the direction they face", () => {
const { walls } = generateWalls([room("a", 0, 0, 4, 3), room("b", 4, 0, 8, 3)], { exterior: OUTER, interior: INNER });
const { buckets, wallBucket } = bucketWalls(walls);
const interior = walls.filter((w) => !w.exterior);
assert.equal(new Set(interior.map((w) => wallBucket.get(w))).size, 1);
const outside = walls.filter((w) => w.exterior);
assert.equal(buckets.filter((b) => b === null).length, 1);
assert.ok(new Set(outside.map((w) => wallBucket.get(w))).size >= 3, "north, south, east and west");
for (const b of buckets) if (b) near(Math.hypot(b[0], b[1]), 1);
assert.equal(buckets.length, new Set([...wallBucket.values()]).size);
});
test("a wall stands at the floor height, a low wall keeps its own height, a tall room's wall rises above the floor", () => {
const { walls } = generateWalls([room("a", 0, 0, 4, 3)], { exterior: OUTER, interior: INNER });
assert.equal(wallHeight(walls[0], 2.6), 2.6);
assert.equal(wallHeight({ ...walls[0], height: 1 }, 2.6), 1);
assert.equal(wallHeight({ ...walls[0], height: 5 }, 2.6), 5);
});
test("roof limits: the top of a wall is its height unless a lower roof is above", () => {
const free = roofLimits(undefined);
assert.equal(free.topAt(0, 0, 2.6), 2.6);
assert.equal(free.lowestTop([0, 0], [1, 0], 0, 3, 2.6), 2.6);
const under = roofLimits((x) => (x < 2 ? 1.8 : null));
assert.equal(under.topAt(1, 0, 2.6), 1.8);
assert.equal(under.topAt(3, 0, 2.6), 2.6);
assert.equal(roofLimits(() => 0.01).topAt(0, 0, 2.6), 0.05, "never below 5 cm");
assert.equal(under.lowestTop([0, 0], [1, 0], 0, 4, 2.6), 1.8);
});
test("an opening is placed on its wall: width, side of the room, sill and top", () => {
const f = floorOf([room("a", 0, 0, 6, 4)], [opening("window", "a", 0, 3, 1.2), opening("door", "a", 3, 2, 0.9)]);
const { walls } = generateWalls(f.rooms, { exterior: OUTER, interior: INNER });
const { wallBucket } = bucketWalls(walls);
const { openings, spans } = placeOpenings(f, walls, wallBucket, roofLimits(undefined));
assert.equal(openings.length, 2);
const win = openings.find((o) => o.opening.type === "window")!;
near(win.width, 1.2);
near(win.sill, 0.9);
near(win.top, 2.2);
assert.equal(win.exterior, true);
// the room is on the side the wall's normal points to
const towardsCentre = [3 - win.start[0], 2 - win.start[1]];
assert.ok(win.toRoom[0] * towardsCentre[0] + win.toRoom[1] * towardsCentre[1] > 0);
assert.equal([...spans.values()].flat().length, 2);
for (const list of spans.values()) for (const sp of list) assert.ok(sp.s1 - sp.s0 > 0.85);
});
test("an opening wider than its wall is shortened, one with no wall is dropped", () => {
const f = floorOf([room("a", 0, 0, 2, 2)], [opening("window", "a", 0, 1, 5), opening("window", "ghost", 0, 1)]);
const { walls } = generateWalls(f.rooms, { exterior: OUTER, interior: INNER });
const { openings } = placeOpenings(f, walls, bucketWalls(walls).wallBucket, roofLimits(undefined));
assert.equal(openings.length, 1);
assert.ok(openings[0].width <= 2 + 1e-9);
});
test("under a roof an opening's top stays below the roof", () => {
const f = floorOf([room("a", 0, 0, 6, 4)], [opening("window", "a", 0, 3, 1.2)]);
const { walls } = generateWalls(f.rooms, { exterior: OUTER, interior: INNER });
const { openings } = placeOpenings(f, walls, bucketWalls(walls).wallBucket, roofLimits(() => 1.6));
assert.ok(openings[0].top <= 1.6 - 0.02 + 1e-9);
assert.ok(openings[0].sill <= openings[0].top - 0.1 + 1e-9);
});
test("a polygon is clipped between two lines across a wall's axis", () => {
const square: Vec2[] = [[0, 0], [4, 0], [4, 1], [0, 1]];
const piece = clipAlong(square, [0, 0], [1, 0], 1, 3);
assert.deepEqual(piece.map((p) => p[0]).sort(), [1, 1, 3, 3]);
assert.equal(clipAlong(square, [0, 0], [1, 0], -Infinity, Infinity).length, 4);
assert.equal(clipAlong(square, [0, 0], [1, 0], 5, 6).length, 0);
assert.equal(clipAlong(square, [0, 0], [1, 0], -Infinity, 2).length, 4);
});
test("a ring is turned counter-clockwise", () => {
const ring: Vec2[] = [[0, 0], [0, 1], [1, 1], [1, 0]];
assert.deepEqual(counterClockwise(ring), [...ring].reverse());
assert.equal(counterClockwise([...ring].reverse()).length, 4);
});
test("a single room has corner lines at all eight corners of its walls' outline", () => {
const f = floorOf([room("a", 0, 0, 4, 3)]);
const g = buildFloorGeometry(f, OUTER, INNER);
const { walls } = generateWalls(f.rooms, { exterior: OUTER, interior: INNER });
assert.equal(outlineOf(walls, walls.flatMap((w) => w.footprint)).corners.length, 8);
const verticals = segments(g.lines).filter((s) => Math.abs(s.from[0] - s.to[0]) < 1e-9 && Math.abs(s.from[2] - s.to[2]) < 1e-9);
assert.ok(verticals.length >= 8);
});
test("a straight outer face across a T-joint gets no corner line", () => {
const { walls } = generateWalls([room("a", 0, 0, 4, 3), room("b", 4, 0, 8, 3)], { exterior: OUTER, interior: INNER });
const outline = outlineOf(walls, walls.flatMap((w) => w.footprint));
const onTopFace = outline.corners.filter((c) => Math.abs(c.p[0] - 4) < 1e-6 && c.p[1] < -0.1);
assert.equal(onTopFace.length, 0);
});
test("the baked shadow covers wall faces inside rooms and nothing outside", () => {
const g = buildFloorGeometry(floorOf([room("a", 0, 0, 4, 3)]), OUTER, INNER);
const p = Array.from(g.shadow.getAttribute("position").array);
const xs = p.filter((_, i) => i % 3 === 0);
const zs = p.filter((_, i) => i % 3 === 2);
assert.ok(Math.min(...xs) >= -1e-6 && Math.max(...xs) <= 4 + 1e-6, "inside the room");
assert.ok(Math.min(...zs) >= -1e-6 && Math.max(...zs) <= 3 + 1e-6);
assert.ok(triangles(g.shadow) >= 8);
});
test("a door interrupts the base line and the shadow; a window does not", () => {
const plain = buildFloorGeometry(floorOf([room("a", 0, 0, 6, 4)]), OUTER, INNER);
const withDoor = buildFloorGeometry(floorOf([room("a", 0, 0, 6, 4)], [opening("door", "a", 0, 3, 1)]), OUTER, INNER);
const withWindow = buildFloorGeometry(floorOf([room("a", 0, 0, 6, 4)], [opening("window", "a", 0, 3, 1)]), OUTER, INNER);
const baseLength = (g: ReturnType<typeof buildFloorGeometry>) => segments(g.lines).filter((s) => horizontal(s, 0.004)).reduce((sum, s) => sum + length(s), 0);
assert.ok(baseLength(plain) - baseLength(withDoor) > 0.9);
near(baseLength(plain), baseLength(withWindow), 1e-6);
assert.ok(triangles(plain.shadow) < triangles(withDoor.shadow) + 4);
const strip = (g: ReturnType<typeof buildFloorGeometry>) => Array.from(g.shadow.getAttribute("position").array).filter((_, i) => i % 3 === 0);
assert.ok(strip(withDoor).length > 0);
});
test("a window above the cut height keeps the cut line, one across it interrupts it", () => {
const cutLine = (g: ReturnType<typeof buildFloorGeometry>) => segments(g.lines).filter((s) => horizontal(s, 1.2) && s.fold >= CUT_OFFSET && s.fold < LOWER_OFFSET);
const high = { ...opening("window", "a", 0, 3, 1), sill: 1.5, height: 0.8 };
const across = opening("window", "a", 0, 3, 1);
const total = (g: ReturnType<typeof buildFloorGeometry>) => cutLine(g).reduce((sum, s) => sum + length(s), 0);
const plain = total(buildFloorGeometry(floorOf([room("a", 0, 0, 6, 4)]), OUTER, INNER));
near(total(buildFloorGeometry(floorOf([room("a", 0, 0, 6, 4)], [high]), OUTER, INNER)), plain, 1e-6);
assert.ok(plain - total(buildFloorGeometry(floorOf([room("a", 0, 0, 6, 4)], [across]), OUTER, INNER)) > 0.9);
});
test("an opening makes the wall around it: pieces beside, below and above, but none in the opening", () => {
const plain = triangles(buildFloorGeometry(floorOf([room("a", 0, 0, 6, 4)]), OUTER, INNER).walls);
const holed = triangles(buildFloorGeometry(floorOf([room("a", 0, 0, 6, 4)], [opening("window", "a", 0, 3, 1)]), OUTER, INNER).walls);
assert.ok(holed > plain, "a window cuts the wall into more pieces");
});
test("furniture is built into the walls buffer with its triangle range; lamps are left to the viewer", () => {
const sofa: Furniture = { id: "s", type: "sofa", x: 3, z: 2, rotation: 0, w: 2, d: 0.9, h: 0.8, variant: null, entity: null, power: null };
const lamp: Furniture = { ...sofa, id: "l", type: "lamp_ceiling" };
const g = buildFloorGeometry(floorOf([room("a", 0, 0, 6, 4)], [], [sofa, lamp]), OUTER, INNER);
assert.deepEqual(g.furnitureTris.map((t) => t.id), ["s"]);
assert.ok(g.furnitureTris[0].end > g.furnitureTris[0].start);
assert.equal(g.furnitureTris[0].end <= triangles(g.walls), true);
});
test("furniture reaching above the cut height is cut with the walls", () => {
const wardrobe: Furniture = { id: "w", type: "wardrobe", x: 3, z: 2, rotation: 0, w: 1, d: 0.6, h: 2.2, variant: null, entity: null, power: null };
const g = buildFloorGeometry(floorOf([room("a", 0, 0, 6, 4)], [], [wardrobe]), OUTER, INNER);
const folds = Array.from(g.walls.getAttribute("fold").array);
assert.ok(folds.some((f) => f >= 64), "pieces above the cut fold away");
assert.ok(folds.includes(ALWAYS));
});
test("a floor opening cuts a hole into the room floor and gets a rim line", () => {
const f = floorOf([room("a", 0, 0, 6, 4)]);
const whole = buildFloorGeometry(f, OUTER, INNER);
const holed = buildFloorGeometry(f, OUTER, INNER, [[[1, 1], [2, 1], [2, 2], [1, 2]]]);
assert.equal(whole.holes.length, 0);
assert.equal(holed.holes.length, 1);
assert.ok(triangles(holed.floor) > triangles(whole.floor));
assert.ok(segments(holed.lines).length > segments(whole.lines).length);
});
test("every room gets a range of floor triangles for picking, with its colour", () => {
const g = buildFloorGeometry(floorOf([room("a", 0, 0, 3, 3), { ...room("b", 3, 0, 6, 3), floor_material: "tiles" }]), OUTER, INNER);
assert.deepEqual(g.roomTris.map((r) => r.roomId), ["a", "b"]);
assert.ok(g.roomTris.every((r) => r.end > r.start));
assert.notEqual(g.roomTris[0].color, g.roomTris[1].color);
});
test("stairs and stairwells cut holes into the floor above", () => {
const stairs: Furniture = { id: "st", type: "stairs", x: 2, z: 2, rotation: 0, w: 1, d: 3, h: 2.6, variant: null, entity: null, power: null };
const lower = { ...floorOf([room("a", 0, 0, 6, 4)], [], [stairs]), id: "g", elevation: 0 };
const upper = { ...floorOf([room("b", 0, 0, 6, 4)]), id: "u", elevation: 2.7 };
assert.equal(stairHoles([lower, upper], upper).length, 1);
assert.equal(stairHoles([lower, upper], lower).length, 0);
const well: Furniture = { ...stairs, id: "w", type: "stairwell", h: 0.1 };
const withWell = { ...upper, furniture: [well] };
assert.equal(stairHoles([lower, withWell], withWell).length, 1, "a stairwell on its own floor");
assert.equal(stairHoles([lower, { ...withWell, furniture: [well, { ...well, id: "w2", x: 2.5 }] }], { ...withWell, furniture: [well, { ...well, id: "w2", x: 2.5 }] }).length, 1, "overlapping ones merge");
});
test("subtracting spans from an edge leaves the free parts, in the edge's direction", () => {
const { walls } = generateWalls([room("a", 0, 0, 6, 4)], { exterior: OUTER, interior: INNER });
const outline = outlineOf(walls, walls.flatMap((w) => w.footprint));
const edge = outline.edges.find((e) => Math.abs(e.a[1] - e.b[1]) < 1e-9 && Math.abs(Math.abs(e.a[0] - e.b[0]) - 6) < 0.7)!;
const fake = (s0: number, s1: number) => ({ s0, s1, sill: 0, top: 2, info: {} as never });
assert.equal(subtractSpans(edge, []).length, 1);
const parts = subtractSpans(edge, [fake(2, 3)]);
assert.equal(parts.length, 2);
const total = parts.reduce((sum, [a, b]) => sum + Math.hypot(b[0] - a[0], b[1] - a[1]), 0);
near(total, Math.hypot(edge.b[0] - edge.a[0], edge.b[1] - edge.a[1]) - 1, 1e-6);
assert.equal(subtractSpans(edge, [fake(-10, 100)]).length, 0, "everything covered");
});
test("a sloping wall: its top follows the slope, above the floor height too; openings stay under it", () => {
const sloped: Room = { ...room("a", 0, 0, 4, 3), wall_heights: [null, 2.5, null, null], wall_slopes: [null, 4.7, null, null] };
const f = floorOf([sloped]);
const { walls } = generateWalls(f.rooms, { exterior: OUTER, interior: INNER });
const wall = walls.find((w) => Math.abs(w.a[0] - 4) < 1e-6 && Math.abs(w.b[0] - 4) < 1e-6)!;
assert.equal(wallHeight(wall, 2.6), 4.7, "the highest point counts, even above the floor height");
const [lowEnd, highEnd] = wall.a[1] < wall.b[1] ? [wall.a, wall.b] : [wall.b, wall.a];
const tops = wallTops(wall, 2.6, roofLimits(undefined));
near(tops.topAt(lowEnd[0], lowEnd[1]), 2.5);
near(tops.topAt(highEnd[0], highEnd[1]), 4.7);
near(tops.topAt((lowEnd[0] + highEnd[0]) / 2, (lowEnd[1] + highEnd[1]) / 2), 3.6);
near(tops.lowestTop(0, 3), 2.5);
// a roof lower than the slope still wins
near(wallTops(wall, 2.6, roofLimits(() => 3)).topAt(highEnd[0], highEnd[1]), 3);
// a window near the high end may be taller than one near the low end
const windowOf = (offset: number) => ({ ...opening("window", "a", 1, offset, 0.8), sill: 1, height: 2.5 }) as Opening;
const { openings } = placeOpenings({ ...f, openings: [windowOf(0.5), windowOf(2.5)] }, walls, bucketWalls(walls).wallBucket, roofLimits(undefined));
const [first, second] = openings;
assert.ok(first.top < second.top, "the one at the high end reaches higher");
assert.ok(first.top <= 2.6 + 1e-6 && second.top <= 4.7);
// and the walls build without error
const geo = buildFloorGeometry(f, OUTER, INNER);
const ys = Array.from(geo.walls.getAttribute("position").array).filter((_, i) => i % 3 === 1);
assert.ok(Math.max(...ys) > 4.6, "the wall is drawn up to its high end");
});
test("a room on its own level: its floor, its walls' bottom and its doors move with it (#57)", () => {
const hall = { ...room("h", 0, 0, 3, 3), floor_offset: -0.39 };
const living = room("l", 3, 0, 7, 3);
const floor = { ...newFloor("g", "G", 0), rooms: [hall, living], openings: [{ id: "d", room_id: "h", edge: 3, offset: 1.5, width: 1, type: "door", sill: 0, height: 2.1, hinge: "left", leaves: 1, swing: "in", cover: null, contact: null, contact2: null, tilt: null } as Opening] };
const walls = generateWalls(floor.rooms, { exterior: OUTER, interior: INNER }).walls;
const { openings } = placeOpenings(floor, walls, new Map(walls.map((w, i) => [w, i])), roofLimits(undefined));
assert.equal(openings[0].sill, -0.39);
assert.ok(Math.abs(openings[0].top - (2.1 - 0.39)) < 1e-9);
assert.equal(offsetAt(floor, 1, 1), -0.39);
assert.equal(offsetAt(floor, 5, 1), 0);
assert.equal(mountBase(floor, { type: "sofa", x: 1, z: 1, h: 0.8 }), -0.39);
});
test("the floor of a room on its own level is drawn at its level, with the step to the rooms around it", () => {
const hall = { ...room("h", 0, 0, 3, 3), floor_offset: -0.39 };
const floor = { ...newFloor("g", "G", 0), rooms: [hall, room("l", 3, 0, 7, 3)] };
const g = buildFloorGeometry(floor, OUTER, INNER, []);
const pos = g.floor.getAttribute("position");
const hallTris = g.roomTris.find((r) => r.roomId === "h")!;
for (let i = hallTris.start * 3; i < hallTris.end * 3; i++) assert.ok(Math.abs(pos.getY(i) + 0.39) < 1e-6);
const living = g.roomTris.find((r) => r.roomId === "l")!;
assert.ok(Math.abs(pos.getY(living.start * 3)) < 1e-6);
});
+121
View File
@@ -0,0 +1,121 @@
// Builds the merged, vertex-coloured geometry of one floor: room floors with material patterns, walls with door and window
// openings, edge lines and baked wall shadows.
//
// Walls are grouped into buckets by the direction they face. Every vertex carries a "fold" value and a shader patch (see
// fold.ts) decides per bucket: in the cut view the upper parts disappear; in the tall view the walls turned towards the
// camera are drawn as tinted glass instead.
// fold = -1 always visible, never glass (furniture, lines of the lower part)
// fold = b upper wall part: visible while bucket b stands
// fold = 16 + b cut edge: visible while bucket b is cut
// fold = 32 + b lower wall part: always visible, glass when the bucket is
// fold = 48 + b top face of the lower part at the cut height: visible while bucket b is cut
import { generateWalls } from "../../geometry/walls.ts";
import { mergeHoles } from "../../geometry/holes.ts";
import { isShapedStair, stairOpeningInPlan } from "../../geometry/stairs.ts";
import { furnitureFootprint, isLamp, roomsReachingUp, type Floor, type SolarField, type Vec2 } from "../../model.ts";
import { hasMesh, mountBase, packItem } from "../../packs.ts";
import type { RoofFace } from "../../solar.ts";
import { cutAbove, cutLinesAbove, FURN_OFFSET, GeoBuffer, LineBuffer } from "../geo.ts";
import { pushFurniture } from "../furniture.ts";
import { pushOutdoor } from "../outdoor.ts";
import { pushModules } from "../roof.ts";
import { pushEdgeLines } from "./edges.ts";
import { buildFloors } from "./floors.ts";
import { outlineOf } from "./outline.ts";
import { bucketWalls, placeOpenings, roofLimits } from "./placement.ts";
import { buildShadow } from "./shadow.ts";
import { buildWallSolids, type WallPaint } from "./solids.ts";
import type { FloorGeometry } from "./types.ts";
export function buildFloorGeometry(
floor: Floor,
wallExterior: number,
wallInterior: number,
holes: Vec2[][] = [],
/** Solar fields standing in this floor's garden, with their ground. */
solar: { face: RoofFace; field: SolarField }[] = [],
/**
* The roof's underside above a plan point, relative to this floor (null = no roof there). Walls end there: knee walls
* at the eaves, gables up to the ridge, inner walls cut by the slope.
*/
roofUnder?: (x: number, z: number) => number | null,
/** Painted walls for the solid wall view (see WallPaint). */
paint?: WallPaint,
): FloorGeometry {
const { walls, open: openRooms } = generateWalls(floor.rooms, { exterior: wallExterior, interior: wallInterior }, floor.walls ?? []);
const limits = roofLimits(roofUnder);
const hasRoof = !!roofUnder;
const floors = buildFloors(floor, holes);
const { buckets, wallBucket } = bucketWalls(walls);
const { openings, spans } = placeOpenings(floor, walls, wallBucket, limits);
const wallBuf = new GeoBuffer();
buildWallSolids(wallBuf, floor, walls, wallBucket, spans, limits, hasRoof, paint);
const outline = outlineOf(walls, walls.flatMap((w) => w.footprint));
const lines = new LineBuffer();
lines.p.push(...floors.holeLines.p);
lines.c.push(...floors.holeLines.c);
lines.f.push(...floors.holeLines.f);
pushEdgeLines(lines, floor, outline, wallBucket, spans, limits, hasRoof);
const shadow = buildShadow(outline.edges, floor.rooms, spans);
const ghosts = new Map<number, GeoBuffer>();
pushOutdoor(wallBuf, lines, floor, ghosts, () => new GeoBuffer());
for (const s of solar) pushModules(wallBuf, lines, s.face, s.field, floor.elevation);
// lamps are drawn live by the viewer: they glow with their light
const cut = Math.min(floor.cut_height, floor.height);
const furnitureTris: FloorGeometry["furnitureTris"] = [];
for (const piece of floor.furniture.filter((f) => !isLamp(f.type))) {
const start = wallBuf.count;
const firstLine = lines.p.length / 6;
const base = mountBase(floor, piece);
// an owned 3D model replaces the parts: the viewer adds it as its own object
if (!hasMesh(piece.type)) pushFurniture(wallBuf, lines, shadow, piece, base);
// a wardrobe or a stair reaching above the cut height is cut with the walls, so it hides nothing behind it
if (base + piece.h > cut + 0.05) {
cutAbove(wallBuf, start, cut, FURN_OFFSET);
cutLinesAbove(lines, firstLine, cut, FURN_OFFSET);
}
furnitureTris.push({ id: piece.id, start, end: wallBuf.count });
}
return {
floor: floors.buffer.geometry(),
roomTris: floors.roomTris,
holes: floors.cutHoles,
walls: wallBuf.geometry(),
ghosts: [...ghosts].map(([opacity, buffer]) => ({ opacity, geometry: buffer.geometry() })),
lines: lines.geometry(),
shadow: shadow.geometry(),
buckets,
openings,
walls2d: walls,
openRooms,
wallBuckets: walls.map((w) => wallBucket.get(w)!),
furnitureTris,
roofUnder,
};
}
/** The ceiling openings of a floor: stairwells placed on it, stairs on the floor below that reach up to it, and rooms below that rise through it. */
export function stairHoles(floors: readonly Floor[], floor: Floor): Vec2[][] {
const voids = roomsReachingUp(floors, floor);
// stairwells, and the shaped stairs that lead down from this floor
const own = [
...floor.furniture.filter((f) => f.type === "stairwell").map(furnitureFootprint),
...floor.furniture.filter((f) => isShapedStair(f) && f.stair?.down).flatMap(stairOpeningInPlan),
].filter((ring) => ring.length >= 3);
const below = floors.filter((f) => f.elevation < floor.elevation).sort((p, q) => q.elevation - p.elevation)[0];
if (!below) return mergeHoles([...own, ...voids]);
const reaching = below.furniture.filter((f) => (f.type === "stairs" || packItem(f.type)?.hole) && !(isShapedStair(f) && f.stair?.down) && below.elevation + f.h >= floor.elevation - 0.3);
// a shaped stair opens the floor only where its treads lack headroom; old stairs and pack stairs open their whole footprint
const stairs = reaching.flatMap((f) => (isShapedStair(f) ? stairOpeningInPlan(f) : [furnitureFootprint(f)])).filter((ring) => ring.length >= 3);
// overlapping openings become one outline (an L-shaped stairwell made of two)
return mergeHoles([...own, ...stairs, ...voids]);
}
export type { WallPaint } from "./solids.ts";
+100
View File
@@ -0,0 +1,100 @@
// The edge lines of the walls and openings: base line, cut line, top line (following a roof), corner verticals, and the
// jambs, sills and lintels of openings on both wall faces.
import type { Wall } from "../../geometry/walls.ts";
import type { Floor, Vec2 } from "../../model.ts";
import { ALWAYS, CUT_OFFSET, EDGE_BASE, EDGE_CUT, EDGE_SOFT, EDGE_TOP, LOWER_OFFSET, type LineBuffer } from "../geo.ts";
import type { Outline } from "./outline.ts";
import { subtractSpans } from "./outline.ts";
import { alongWall, glassJoins, joinPositions, spanEnds } from "./glass-joins.ts";
import { wallTops, type roofLimits } from "./placement.ts";
import type { Span } from "./types.ts";
/** A 2 cm grid, so an outline corner and a glass join meet at the same key despite rounding. */
const pointKey = (p: readonly [number, number]) => `${Math.round(p[0] * 50)},${Math.round(p[1] * 50)}`;
/**
* Jambs, sill and lintel edges of an opening on both wall faces, split at the cut height. A piece that joins
* another piece of the same pane has no jamb at that end: the glass runs on.
*/
function pushOpeningLines(lines: LineBuffer, sp: Span, cut: number, hideStart = false, hideEnd = false): void {
const { info } = sp;
const bucket = info.bucket;
const at = (s: number, n: number, y: number) => [info.start[0] + info.axis[0] * (s - sp.s0) + info.toRoom[0] * n, y, info.start[1] + info.axis[1] * (s - sp.s0) + info.toRoom[1] * n];
const foldAt = (y: number) => (y > cut + 1e-6 ? bucket : ALWAYS);
// just above the floor the opening stands on (below 0 in a lowered room)
const bottom = sp.sill < 0 ? sp.sill + 0.004 : Math.max(sp.sill, 0.004);
for (const n of [info.faceRoom, -info.faceOut]) {
if (!hideStart) lines.segSplit(at(sp.s0, n, bottom), at(sp.s0, n, sp.top), EDGE_SOFT, cut, bucket);
if (!hideEnd) lines.segSplit(at(sp.s1, n, bottom), at(sp.s1, n, sp.top), EDGE_SOFT, cut, bucket);
lines.seg(at(sp.s0, n, sp.top), at(sp.s1, n, sp.top), EDGE_SOFT, foldAt(sp.top));
if (sp.sill > 0.01) lines.seg(at(sp.s0, n, sp.sill), at(sp.s1, n, sp.sill), EDGE_SOFT, foldAt(sp.sill));
}
// edges across the wall thickness (the reveals), and the cut section of the jambs
for (const [s, hide] of [[sp.s0, hideStart], [sp.s1, hideEnd]] as const) {
if (hide) continue;
lines.seg(at(s, info.faceRoom, sp.top), at(s, -info.faceOut, sp.top), EDGE_SOFT, foldAt(sp.top));
if (sp.sill > 0.01) lines.seg(at(s, info.faceRoom, sp.sill), at(s, -info.faceOut, sp.sill), EDGE_SOFT, foldAt(sp.sill));
if (sp.sill < cut && sp.top > cut) lines.seg(at(s, info.faceRoom, cut), at(s, -info.faceOut, cut), EDGE_CUT, CUT_OFFSET + bucket);
}
}
export function pushEdgeLines(
lines: LineBuffer,
floor: Floor,
outline: Outline,
wallBucket: Map<Wall, number>,
spans: Map<Wall, Span[]>,
limits: ReturnType<typeof roofLimits>,
hasRoof: boolean,
): void {
const cut = Math.min(floor.cut_height, floor.height);
const spansOf = (wall: Wall, keep: (sp: Span) => boolean) => (spans.get(wall) ?? []).filter(keep);
for (const edge of outline.edges) {
const bucket = wallBucket.get(edge.wall)!;
// the base line along the floor: not across doorways
for (const [p, q] of subtractSpans(edge, spansOf(edge.wall, (sp) => sp.sill <= 0.005))) lines.seg([p[0], 0.004, p[1]], [q[0], 0.004, q[1]], EDGE_BASE);
// the cut line: not where an opening crosses the cut height
for (const [p, q] of subtractSpans(edge, spansOf(edge.wall, (sp) => sp.sill < cut && sp.top > cut))) lines.seg([p[0], cut, p[1]], [q[0], cut, q[1]], EDGE_CUT, CUT_OFFSET + bucket);
// the top line: not where an opening reaches the top; a wall below the cut height keeps its top line; under a roof it follows the slope in short steps
const tops = wallTops(edge.wall, floor.height, limits);
const { H, topAt } = tops;
for (const [p, q] of subtractSpans(edge, spansOf(edge.wall, (sp) => sp.top >= H - 0.021))) {
if (!hasRoof && !tops.varies) {
lines.seg([p[0], H, p[1]], [q[0], H, q[1]], EDGE_TOP, H <= cut + 1e-6 ? LOWER_OFFSET + bucket : bucket);
continue;
}
const steps = Math.max(1, Math.ceil(Math.hypot(q[0] - p[0], q[1] - p[1]) / 0.3));
const at = (i: number): Vec2 => [p[0] + ((q[0] - p[0]) * i) / steps, p[1] + ((q[1] - p[1]) * i) / steps];
for (let i = 0; i < steps; i++) {
const [a, c] = [at(i), at(i + 1)];
const [ya, yc] = [topAt(a[0], a[1]), topAt(c[0], c[1])];
lines.seg([a[0], ya, a[1]], [c[0], yc, c[1]], EDGE_TOP, Math.max(ya, yc) <= cut + 1e-6 ? LOWER_OFFSET + bucket : bucket);
}
}
}
// where two pieces of one pane meet, the corner is not a jamb (glass-joins.ts is shared with the wall solids)
const joins = glassJoins(spans.values());
const insidePane = new Set(joins.points.map(pointKey));
// internal joins in wall coordinates: a footprint corner off the axis is not a point to compare with
const joinAt = new Map<Wall, number[]>();
for (const [wall, list] of spans) joinAt.set(wall, joinPositions(list, joins));
for (const corner of outline.corners) {
// a corner inside a continuous pane has no wall vertical running through the glass: the pane runs on
// over the bend, so the wall only turns behind it
const s = alongWall(corner.wall, corner.p);
const list = spans.get(corner.wall) ?? [];
const inPane = list.some((sp) => !!sp.info.opening.front && s > sp.s0 + 0.05 && s < sp.s1 - 0.05);
const atJoin = (joinAt.get(corner.wall) ?? []).some((j) => Math.abs(j - s) < 0.06);
if (inPane || atJoin || insidePane.has(pointKey(corner.p))) continue;
const height = wallTops(corner.wall, floor.height, limits).topAt(corner.p[0], corner.p[1]);
lines.segSplit([corner.p[0], 0.004, corner.p[1]], [corner.p[0], height, corner.p[1]], EDGE_SOFT, Math.min(cut, height), wallBucket.get(corner.wall)!);
}
for (const list of spans.values()) {
for (const sp of list) {
const front = sp.info.opening.front;
const [p0, p1] = spanEnds(sp);
pushOpeningLines(lines, sp, cut, front ? joins.at(front, p0) : false, front ? joins.at(front, p1) : false);
}
}
}
+71
View File
@@ -0,0 +1,71 @@
// Room floors with their material pattern, the slab below them, and the rims of openings cut into the floor (stairwells).
import { Color } from "three";
import { holeInRoom, insetHole } from "../../geometry/holes.ts";
import { roomOffset, type Floor, type Vec2 } from "../../model.ts";
import { ALWAYS, EDGE_SOFT, EDGE_TOP, GeoBuffer, LineBuffer, triangulate } from "../geo.ts";
import { counterClockwise } from "./outline.ts";
import { FLOOR_LOOK, NEON, SLAB } from "./look.ts";
import type { FloorGeometry } from "./types.ts";
export interface FloorParts {
buffer: GeoBuffer;
roomTris: FloorGeometry["roomTris"];
/** The rims of the openings, to be added to the line buffer first. */
holeLines: LineBuffer;
/** The openings that were actually cut into some room. */
cutHoles: Vec2[][];
}
export function buildFloors(floor: Floor, holes: Vec2[][]): FloorParts {
const buffer = new GeoBuffer(true, true);
const roomTris: FloorGeometry["roomTris"] = [];
const holeLines = new LineBuffer();
const cutHoles: Vec2[][] = [];
const slab = new Color(NEON.slab);
/** The slab's side faces along a ring, from `y0` up to `y1`. */
const slabSides = (ring: Vec2[], y1 = 0, y0 = y1 - SLAB) => {
ring.forEach((a, i) => {
const b = ring[(i + 1) % ring.length];
buffer.tri([a[0], y0, a[1]], [a[0], y1, a[1]], [b[0], y1, b[1]], slab);
buffer.tri([a[0], y0, a[1]], [b[0], y1, b[1]], [b[0], y0, b[1]], slab);
});
};
for (const room of floor.rooms) {
if (room.points.length < 3) continue;
const outline = counterClockwise(room.points);
const look = FLOOR_LOOK[room.floor_material] ?? FLOOR_LOOK.wood;
const top = new Color(look.color);
// an opening snapped to the room's edge is still cut, a few millimetres in from it
const inside = holes.filter((h) => holeInRoom(h, outline)).map((h) => insetHole(h, 0.003));
cutHoles.push(...inside);
const corners = [...outline, ...inside.flat()];
const start = buffer.count;
// a room on its own level (a sunken entrance, a split level): its floor lies lower or higher
const y = roomOffset(room);
for (const [i, j, k] of triangulate(outline, inside)) {
const [a, b, c] = [corners[i], corners[j], corners[k]];
buffer.tri([a[0], y, a[1]], [c[0], y, c[1]], [b[0], y, b[1]], top, top, top, [a[0], a[1], c[0], c[1], b[0], b[1]], ALWAYS, look.tile);
}
roomTris.push({ roomId: room.id, start, end: buffer.count, color: look.color });
slabSides(outline, y);
// the step between it and the floor's level, seen from both sides (from the lower room and from the rooms around it)
if (Math.abs(y) > 0.005) {
slabSides(outline, Math.max(0, y), Math.min(0, y));
slabSides([...outline].reverse(), Math.max(0, y), Math.min(0, y));
}
for (const hole of inside) {
// the hole's inner faces look into the hole
slabSides([...counterClockwise(hole)].reverse());
hole.forEach((a, i) => {
const b = hole[(i + 1) % hole.length];
// a bright rim like the walls' tops, so the opening reads from above
holeLines.seg([a[0], y + 0.006, a[1]], [b[0], y + 0.006, b[1]], EDGE_TOP);
holeLines.seg([a[0], y - SLAB, a[1]], [b[0], y - SLAB, b[1]], EDGE_SOFT);
});
}
}
return { buffer, roomTris, holeLines, cutHoles };
}
@@ -0,0 +1,219 @@
// The joins between the pieces of one pane: no jamb, no wall vertical and no wall surface may stand there,
// or the pane reads as several windows again. The same fixture without a `front` is the control: it must
// still show those, so the test can fail.
//
// What used to stand there is a mitre wedge: a wall's footprint runs up to the mitre line, a few centimetres
// past the wall's own end, so cutting the wall into pieces leaves a full-height wedge piece beyond the last
// opening. Its end face, outer sliver and mitre face are the bright vertical line seen through the glass.
import assert from "node:assert/strict";
import { test } from "node:test";
import { generateWalls } from "../../geometry/walls.ts";
import { newFloor, type Floor, type Opening, type Room, type Vec2 } from "../../model.ts";
import { GeoBuffer, LineBuffer } from "../geo.ts";
import { pushEdgeLines } from "./edges.ts";
import { alongWall, glassJoins, joinPositions } from "./glass-joins.ts";
import { outlineOf } from "./outline.ts";
import { bucketWalls, placeOpenings, roofLimits } from "./placement.ts";
import { buildWallSolids } from "./solids.ts";
const OUTER = 0.3;
const INNER = 0.1;
/** The height band a glass wall leaves empty: nothing solid may stand in it at a join. */
const BAND: [number, number] = [0.1, 2.3];
/** A room whose outer side is an arc of `n` edges of `seg` metres, each turning `turn` degrees, closed by one straight edge. */
function arcRoom(n = 8, seg = 1, turn = 30): Room {
const points: Vec2[] = [[0, 0]];
let [x, z] = [0, 0];
let a = 0;
for (let i = 0; i < n; i++) {
a += (turn * Math.PI) / 180;
x += Math.cos(a) * seg;
z += Math.sin(a) * seg;
points.push([x, z]);
}
return { id: "r", name: "r", area_id: null, points, floor_material: "wood" };
}
const glass = (id: string, edge: number, front: string | null): Opening =>
({
id,
room_id: "r",
edge,
offset: 0.5,
width: 1,
type: "window",
style: "glass_wall",
sill: 0,
height: 2.4,
hinge: "left",
leaves: 1,
swing: "in",
cover: null,
contact: null,
contact2: null,
tilt: null,
...(front ? { front } : {}),
}) as Opening;
/** Three 1 m pieces on the first three edges of the arc, either one pane (a shared front) or three windows. */
function scene(front: string | null) {
const room = arcRoom();
const floor: Floor = {
...newFloor("f", "F", 0),
height: 2.6,
cut_height: 1.2,
rooms: [room],
openings: [glass("a", 0, front), glass("b", 1, front), glass("c", 2, front)],
furniture: [],
};
const { walls } = generateWalls(floor.rooms, { exterior: OUTER, interior: INNER }, []);
const limits = roofLimits(() => null);
const { wallBucket } = bucketWalls(walls);
const { spans } = placeOpenings(floor, walls, wallBucket, limits);
const outline = outlineOf(walls, walls.flatMap((w) => w.footprint));
const lines = new LineBuffer();
pushEdgeLines(lines, floor, outline, wallBucket, spans, limits, false);
const solids = new GeoBuffer();
buildWallSolids(solids, floor, walls, wallBucket, spans, limits, false);
return { room, floor, walls, spans, lines, solids };
}
/** Vertical line segments whose plan position is within 5 cm of `p`. */
function verticalLinesAt(lines: LineBuffer, p: Vec2): number {
const v: number[] = (lines as unknown as { p: number[] }).p;
let found = 0;
for (let i = 0; i + 5 < v.length; i += 6) {
const [x0, y0, z0, x1, y1, z1] = [v[i], v[i + 1], v[i + 2], v[i + 3], v[i + 4], v[i + 5]];
if (Math.abs(y1 - y0) < 0.6) continue;
if (Math.hypot(x0 - p[0], z0 - p[1]) > 0.05 && Math.hypot(x1 - p[0], z1 - p[1]) > 0.05) continue;
found++;
}
return found;
}
/** Distance in plan from `p` to the triangle `abc`, zero inside it. */
function planDistance(p: Vec2, a: Vec2, b: Vec2, c: Vec2): number {
const cross = (o: Vec2, u: Vec2, v: Vec2) => (u[0] - o[0]) * (v[1] - o[1]) - (u[1] - o[1]) * (v[0] - o[0]);
const [s1, s2, s3] = [cross(a, b, p), cross(b, c, p), cross(c, a, p)];
if ((s1 >= 0 && s2 >= 0 && s3 >= 0) || (s1 <= 0 && s2 <= 0 && s3 <= 0)) return 0;
const toSegment = (u: Vec2, w: Vec2) => {
const [dx, dz] = [w[0] - u[0], w[1] - u[1]];
const len2 = dx * dx + dz * dz;
const t = len2 < 1e-12 ? 0 : Math.max(0, Math.min(1, ((p[0] - u[0]) * dx + (p[1] - u[1]) * dz) / len2));
return Math.hypot(p[0] - (u[0] + dx * t), p[1] - (u[1] + dz * t));
};
return Math.min(toSegment(a, b), toSegment(b, c), toSegment(c, a));
}
/** The axis of the wall that ends at `p`: a face is a divider when it runs across that wall. */
function axisAt(walls: { a: Vec2; b: Vec2 }[], p: Vec2): Vec2 {
const w = walls.find((x) => Math.hypot(x.b[0] - p[0], x.b[1] - p[1]) < 1e-6) ?? walls.find((x) => Math.hypot(x.a[0] - p[0], x.a[1] - p[1]) < 1e-6)!;
const len = Math.hypot(w.b[0] - w.a[0], w.b[1] - w.a[1]) || 1;
return [(w.b[0] - w.a[0]) / len, (w.b[1] - w.a[1]) / len];
}
/**
* Wall faces that read as a divider in the glass at `p`: the face runs across the wall — a jamb, or the
* seam beside a mitre — its plan projection covers `p`, and it reaches into the height band the pane
* leaves empty. A face along the wall is the wall surface and no divider, a sliver of no length is no
* surface, and the wall above a 2.4 m pane is out of the band.
*/
function facesInGlass(solids: GeoBuffer, p: Vec2, axis: Vec2, band: [number, number] = BAND): number {
const v: number[] = (solids as unknown as { p: number[] }).p;
let found = 0;
for (let i = 0; i + 8 < v.length; i += 9) {
const ys = [v[i + 1], v[i + 4], v[i + 7]];
const [lo, hi] = [Math.min(...ys), Math.max(...ys)];
if (lo > band[1] || hi < band[0] || hi - lo < 0.05) continue;
const [a, b, c]: Vec2[] = [
[v[i], v[i + 2]],
[v[i + 3], v[i + 5]],
[v[i + 6], v[i + 8]],
];
const across = Math.max(Math.hypot(b[0] - a[0], b[1] - a[1]), Math.hypot(c[0] - b[0], c[1] - b[1]), Math.hypot(c[0] - a[0], c[1] - a[1]));
if (across < 0.01) continue;
if (Math.abs(((c[0] - a[0]) * axis[0] + (c[1] - a[1]) * axis[1]) / across) > 0.5) continue;
if (planDistance(p, a, b, c) > 0.02) continue;
found++;
}
return found;
}
/**
* How much wall surface stands in the glass band around `p`, in square metres. Unlike `facesInGlass`
* this counts every face, whatever way it runs: the strip that shows from outside at a bend runs along
* the wall, so a test that only looks at cross-sections cannot see it.
*/
function wallInGlass(solids: GeoBuffer, p: Vec2, radius = 0.35, band: [number, number] = BAND): number {
const v: number[] = (solids as unknown as { p: number[] }).p;
let area = 0;
for (let i = 0; i + 8 < v.length; i += 9) {
const ys = [v[i + 1], v[i + 4], v[i + 7]];
const [lo, hi] = [Math.min(...ys), Math.max(...ys)];
if (lo > band[1] || hi < band[0] || hi - lo < 0.05) continue;
const pts: Vec2[] = [
[v[i], v[i + 2]],
[v[i + 3], v[i + 5]],
[v[i + 6], v[i + 8]],
];
const cx = (pts[0][0] + pts[1][0] + pts[2][0]) / 3;
const cz = (pts[0][1] + pts[1][1] + pts[2][1]) / 3;
if (Math.hypot(cx - p[0], cz - p[1]) > radius) continue;
const across = Math.max(
Math.hypot(pts[1][0] - pts[0][0], pts[1][1] - pts[0][1]),
Math.hypot(pts[2][0] - pts[1][0], pts[2][1] - pts[1][1]),
Math.hypot(pts[2][0] - pts[0][0], pts[2][1] - pts[0][1]),
);
if (across < 0.01) continue; // a degenerate sliver is no surface at all
area += across * (hi - lo);
}
return area;
}
test("where two pieces of one pane meet, no jamb and no wall surface stand in the glass", () => {
const { room, walls, spans, lines, solids } = scene("F");
const joins = glassJoins(spans.values());
assert.equal(joins.points.length, 2, "two internal joins for three pieces");
for (const p of joins.points) {
assert.equal(verticalLinesAt(lines, p), 0, `no vertical line at ${p}`);
assert.equal(facesInGlass(solids, p, axisAt(walls, p)), 0, `no wall face in the glass at ${p}`);
// the mitre of a bend leaves a strip of wall on the outer face, a few centimetres wide and full
// height: from outside it stands in front of the glass and reads as a white line at every bend
assert.ok(wallInGlass(solids, p) < 0.02, `no wall surface in the glass at ${p}`);
}
// the same points in wall coordinates, which is what the solids and the corner filter use
for (const wall of [...spans.keys()]) {
const positions = joinPositions(spans.get(wall)!, joins);
for (const s of positions) assert.ok(s >= -0.001 && s <= 1.5, `join at ${s} m on its wall`);
}
assert.ok(room.points.length > 3);
});
test("the control: three separate glass walls do show a jamb and a wall surface at the same points", () => {
const { room, walls, lines, solids } = scene(null);
const corner = room.points[1];
assert.ok(verticalLinesAt(lines, corner) > 0, "a separate glass wall keeps its jamb");
assert.ok(facesInGlass(solids, corner, axisAt(walls, corner)) > 0, "and the wall end stands in the glass");
assert.ok(wallInGlass(solids, corner) > 1, "lots of it, so the measure above can fail");
});
test("joinPosition is the wall coordinate of a piece end, not a guessed distance", () => {
const { walls, spans } = scene("F");
const joins = glassJoins(spans.values());
let seen = 0;
for (const [wall, list] of spans) {
const at = joinPositions(list, joins);
seen += at.length;
for (const sp of list) {
for (const s of at) {
// a join is either the span's start or its end on this wall
assert.ok(Math.abs(s - sp.s0) < 1e-9 || Math.abs(s - sp.s1) < 1e-9, "a join sits on a span end");
assert.ok(alongWall(wall, wall.a) < 1e-9, "wall coordinates start at wall.a");
}
}
}
assert.equal(seen, 4, "two joints, each seen from both of its walls");
assert.equal(walls.length, 9, "eight arc edges and the closing one");
});
+74
View File
@@ -0,0 +1,74 @@
// Pieces of one glass pane that follows a curved wall are placed as separate spans that share a `front` id.
// Where two of them meet, the wall must not draw a jamb or a solid end face: the glass is continuous there.
// The edge-line layer and the wall-solid layer both use this one definition, so they cannot disagree about
// which corners are internal.
import type { Vec2 } from "../../model.ts";
import type { Wall } from "../../geometry/walls.ts";
import type { Span } from "./types.ts";
type Point = readonly [number, number];
/** The two ends of an opening span in plan coordinates. */
export function spanEnds(sp: Span): [Point, Point] {
const { start, axis, width } = sp.info;
return [
[start[0], start[1]],
[start[0] + axis[0] * width, start[1] + axis[1] * width],
];
}
/** A 2 cm grid, so two pieces of one pane meet at the same key despite rounding. */
const key = (front: string, p: Point): string => `${front}|${Math.round(p[0] * 50)},${Math.round(p[1] * 50)}`;
export interface GlassJoins {
/** World positions where two pieces of the same pane meet. */
points: Vec2[];
/** Whether this end of a span is an internal join of its own pane. */
at(front: string, p: Point): boolean;
}
/**
* Where along `wall` a piece of a pane ends at an internal join. The wall solids and the edge lines work
* in wall coordinates (`s` from `wall.a`), so they use this instead of comparing world points: the corner
* of a footprint sits half a wall thickness off the axis, and a distance test there is a guess.
*/
export function joinPositions(list: readonly Span[], joins: GlassJoins): number[] {
const out: number[] = [];
for (const sp of list) {
const front = sp.info.opening.front;
if (!front) continue;
const [p0, p1] = spanEnds(sp);
if (joins.at(front, p0)) out.push(sp.s0);
if (joins.at(front, p1)) out.push(sp.s1);
}
return out;
}
/** How far `p` lies along `wall` from its start, in metres. */
export function alongWall(wall: Wall, p: Vec2): number {
const length = Math.hypot(wall.b[0] - wall.a[0], wall.b[1] - wall.a[1]) || 1;
return ((p[0] - wall.a[0]) * (wall.b[0] - wall.a[0]) + (p[1] - wall.a[1]) * (wall.b[1] - wall.a[1])) / length;
}
/** Every place where two spans of the same pane share an end. */
export function glassJoins(lists: Iterable<Iterable<Span>>): GlassJoins {
const count = new Map<string, number>();
const pos = new Map<string, Vec2>();
for (const list of lists) {
for (const sp of list) {
const front = sp.info.opening.front;
if (!front) continue;
for (const p of spanEnds(sp)) {
const k = key(front, p);
count.set(k, (count.get(k) ?? 0) + 1);
if (!pos.has(k)) pos.set(k, [p[0], p[1]]);
}
}
}
const points = [...count]
.filter(([, n]) => n > 1)
.map(([k]) => pos.get(k))
.filter((p): p is Vec2 => !!p);
return { points, at: (front, p) => (count.get(key(front, p)) ?? 0) > 1 };
}
+26
View File
@@ -0,0 +1,26 @@
// Colours and sizes of the floor geometry.
/** The base colours of the neon look. */
export const NEON = {
floor: 0x0e1629,
slab: 0x0a1120,
wall: 0x131d31,
wallTop: 0x14303f,
edge: 0x37e0ff,
edgeSoft: 0x5b7cff,
};
/** The floor tint and the pattern tile (column, row in the pattern atlas) per floor material. */
export const FLOOR_LOOK: Record<string, { color: number; tile: [number, number] }> = {
wood: { color: 0x111a2e, tile: [0, 0] },
oak: { color: 0x131b2d, tile: [1, 0] },
tiles: { color: 0x0e182f, tile: [2, 0] },
carpet: { color: 0x10152b, tile: [0, 1] },
stone: { color: 0x0f172b, tile: [1, 1] },
concrete: { color: 0x111827, tile: [2, 1] },
};
/** The thickness of the floor slab below the floor. */
export const SLAB = 0.2;
/** Exterior walls are sorted into this many compass sectors; each sector is one fold bucket. */
export const SECTORS = 8;
+141
View File
@@ -0,0 +1,141 @@
// The outline of the walls' footprints, and helpers to cut and clip along a wall.
import type { Wall } from "../../geometry/walls.ts";
import type { Vec2 } from "../../model.ts";
import type { Span } from "./types.ts";
export const unit = (v: Vec2): Vec2 => {
const length = Math.hypot(v[0], v[1]) || 1;
return [v[0] / length, v[1] / length];
};
/** A ring running counter-clockwise, whichever way it was given. */
export function counterClockwise(points: Vec2[]): Vec2[] {
const area = points.reduce((sum, p, i) => sum + p[0] * points[(i + 1) % points.length][1] - points[(i + 1) % points.length][0] * p[1], 0);
return area >= 0 ? points : [...points].reverse();
}
/** Keeps the part of a polygon on the positive side of a line (Sutherland-Hodgman against one half-plane). */
function clipHalfPlane(poly: Vec2[], distance: (p: Vec2) => number): Vec2[] {
const kept: Vec2[] = [];
poly.forEach((a, i) => {
const b = poly[(i + 1) % poly.length];
const [da, db] = [distance(a), distance(b)];
if (da >= 0) kept.push(a);
if (da >= 0 !== db >= 0) {
const k = da / (da - db);
kept.push([a[0] + (b[0] - a[0]) * k, a[1] + (b[1] - a[1]) * k]);
}
});
return kept;
}
/** The part of a polygon between two lines perpendicular to `axis` (t is measured from `origin`). */
export function clipAlong(poly: Vec2[], origin: Vec2, axis: Vec2, t0: number, t1: number): Vec2[] {
const t = (p: Vec2) => (p[0] - origin[0]) * axis[0] + (p[1] - origin[1]) * axis[1];
let kept = poly;
if (Number.isFinite(t0)) kept = clipHalfPlane(kept, (p) => t(p) - t0);
if (Number.isFinite(t1)) kept = clipHalfPlane(kept, (p) => t1 - t(p));
return kept;
}
export interface OutlineEdge {
a: Vec2;
b: Vec2;
wall: Wall;
}
export interface Outline {
/** The edges of the merged wall footprints (joints between walls left out), counter-clockwise per wall. */
edges: OutlineEdge[];
/** The vertices where the outline turns a corner, with a wall they belong to. */
corners: { p: Vec2; wall: Wall }[];
}
const millimetres = (v: number) => Math.round(v * 1000);
const vertexKey = (p: Vec2) => `${millimetres(p[0])},${millimetres(p[1])}`;
const edgeKey = (a: Vec2, b: Vec2) => {
const [s, t] = [vertexKey(a), vertexKey(b)];
return s < t ? `${s}|${t}` : `${t}|${s}`;
};
/** The edges of a polygon, split wherever one of `points` lies on them, so T-joints line up. */
function splitAtPoints(poly: Vec2[], points: Vec2[]): [Vec2, Vec2][] {
const pieces: [Vec2, Vec2][] = [];
poly.forEach((a, i) => {
const b = poly[(i + 1) % poly.length];
const [dx, dz] = [b[0] - a[0], b[1] - a[1]];
const squared = dx * dx + dz * dz;
if (squared < 1e-8) return;
const cuts = points
.map((p) => ({ t: ((p[0] - a[0]) * dx + (p[1] - a[1]) * dz) / squared, off: Math.abs((p[0] - a[0]) * dz - (p[1] - a[1]) * dx) / Math.sqrt(squared) }))
.filter(({ t, off }) => t > 1e-6 && t < 1 - 1e-6 && off < 1e-4)
.map(({ t }) => t)
.sort((p, q) => p - q);
let previous = a;
for (const t of cuts) {
const cut: Vec2 = [a[0] + dx * t, a[1] + dz * t];
if (vertexKey(cut) !== vertexKey(previous)) pieces.push([previous, cut]);
previous = cut;
}
pieces.push([previous, b]);
});
return pieces;
}
/**
* The outline of the walls' footprints: the edges no other footprint shares, and the vertices where those edges change
* direction. Edges are split at `points` first, so an edge partly covered by another wall (a T-joint) keeps only its free part.
*/
export function outlineOf(walls: Wall[], points: Vec2[]): Outline {
const pieces = walls.map((wall) => ({ wall, edges: splitAtPoints(wall.footprint, points) }));
const uses = new Map<string, number>();
for (const { edges } of pieces) for (const [a, b] of edges) uses.set(edgeKey(a, b), (uses.get(edgeKey(a, b)) ?? 0) + 1);
const edges: OutlineEdge[] = [];
const directions = new Map<string, { p: Vec2; wall: Wall; d: Vec2[] }>();
const note = (p: Vec2, wall: Wall, d: Vec2) => {
const key = vertexKey(p);
if (!directions.has(key)) directions.set(key, { p, wall, d: [] });
directions.get(key)!.d.push(d);
};
for (const { wall, edges: list } of pieces) {
for (const [a, b] of list) {
const length = Math.hypot(b[0] - a[0], b[1] - a[1]);
if (uses.get(edgeKey(a, b)) !== 1 || length < 1e-4) continue;
edges.push({ a, b, wall });
const d: Vec2 = [(b[0] - a[0]) / length, (b[1] - a[1]) / length];
note(a, wall, d);
note(b, wall, d);
}
}
// a vertex where the outline just continues straight (a T-joint seen from outside) is no corner
const corners = [...directions.values()].filter(({ d }) => d.some((u) => d.some((v) => Math.abs(u[0] * v[1] - u[1] * v[0]) > 0.05))).map(({ p, wall }) => ({ p, wall }));
return { edges, corners };
}
/** The parts of an outline edge outside the given opening spans (only for edges along the wall axis). */
export function subtractSpans(edge: OutlineEdge, spans: Span[]): [Vec2, Vec2][] {
if (spans.length === 0) return [[edge.a, edge.b]];
const axis = unit([edge.wall.b[0] - edge.wall.a[0], edge.wall.b[1] - edge.wall.a[1]]);
const along = unit([edge.b[0] - edge.a[0], edge.b[1] - edge.a[1]]);
if (Math.abs(axis[0] * along[0] + axis[1] * along[1]) < 0.99) return [[edge.a, edge.b]];
const t = (p: Vec2) => (p[0] - edge.wall.a[0]) * axis[0] + (p[1] - edge.wall.a[1]) * axis[1];
const [ta, tb] = [t(edge.a), t(edge.b)];
let parts: [number, number][] = [[Math.min(ta, tb), Math.max(ta, tb)]];
for (const span of spans) {
parts = parts.flatMap(([p, q]): [number, number][] => {
if (span.s1 <= p || span.s0 >= q) return [[p, q]];
const remaining: [number, number][] = [];
if (span.s0 > p) remaining.push([p, span.s0]);
if (span.s1 < q) remaining.push([span.s1, q]);
return remaining;
});
}
const pointAt = (value: number): Vec2 => {
const k = (value - ta) / (tb - ta || 1);
return [edge.a[0] + (edge.b[0] - edge.a[0]) * k, edge.a[1] + (edge.b[1] - edge.a[1]) * k];
};
// keep the edge's direction: its normal tells which side the room is on
return parts.filter(([p, q]) => q - p > 1e-4).map(([p, q]) => (ta <= tb ? [pointAt(p), pointAt(q)] : [pointAt(q), pointAt(p)]));
}
+37
View File
@@ -0,0 +1,37 @@
import assert from "node:assert/strict";
import { test } from "node:test";
import type { Vec2 } from "../../model.ts";
import { paintOfSide, wallPaintOf, type WallPaint } from "./solids.ts";
// a wall 0.2 m thick along z = 0 (from x = 0 to 4): the room "a" lies north of it (z < 0), the room "b" south (z > 0)
const wall: Vec2[] = [[0, -0.1], [4, -0.1], [4, 0.1], [0, 0.1]];
const roomA = { points: [[0, -3], [4, -3], [4, 0], [0, 0]] as Vec2[] };
const roomB = { points: [[0, 0], [4, 0], [4, 3], [0, 3]] as Vec2[] };
test("a wall face takes the paint of the room in front of it, the inside colour without one, the outside colour outdoors", () => {
const paint: WallPaint = { outside: 0x111111, inside: 0x222222, rooms: [{ points: roomB.points, color: 0x333333 }] };
const north = paintOfSide(wall, [0, -0.1], [4, -0.1], paint, [roomA, roomB]);
const south = paintOfSide(wall, [4, 0.1], [0, 0.1], paint, [roomA, roomB]);
assert.equal(north, 0x222222, "room a has no colour of its own: the inside colour");
assert.equal(south, 0x333333, "room b has its own colour");
// the same wall with only room a: its south face looks outdoors
assert.equal(paintOfSide(wall, [4, 0.1], [0, 0.1], { ...paint, rooms: [] }, [roomA]), 0x111111);
// the face direction does not depend on how the polygon edge is walked
assert.equal(paintOfSide(wall, [4, -0.1], [0, -0.1], paint, [roomA, roomB]), 0x222222);
});
test("a floor with an outside colour of its own paints its outer walls in it, the others keep the building's (#110)", () => {
const settings = { wall_paint_outside: "#aa0000", wall_paint_inside: "#eeeeee" };
assert.equal(wallPaintOf(settings, { rooms: [], wall_paint_outside: "#808080" }).outside, 0x808080, "the plinth in grey");
assert.equal(wallPaintOf(settings, { rooms: [] }).outside, 0xaa0000, "the storeys above stay red");
assert.equal(wallPaintOf(settings, { rooms: [], wall_paint_outside: "nonsense" }).outside, 0xaa0000, "no colour is no override");
});
test("only the floor's own rooms paint its walls: a room upstairs leaves the wall below it alone (#110)", () => {
const upstairs = { rooms: [{ ...roomB, wall_paint: "#00ff00" }] };
const downstairs = { rooms: [roomB] };
const settings = { wall_paint_inside: "#222222" };
assert.deepEqual(wallPaintOf(settings, upstairs).rooms.map((r) => r.color), [0x00ff00]);
const below = wallPaintOf(settings, downstairs);
assert.equal(paintOfSide(wall, [0, 0.1], [4, 0.1], below, downstairs.rooms), 0x222222, "the inside colour, not the green from upstairs");
});
+134
View File
@@ -0,0 +1,134 @@
// Fold buckets of the walls, and the openings resolved onto their walls.
import { locateOpening, openingHost, type Wall } from "../../geometry/walls.ts";
import { roomOffset, type Floor, type Vec2 } from "../../model.ts";
import { SECTORS } from "./look.ts";
import { unit } from "./outline.ts";
import type { OpeningInfo, Span } from "./types.ts";
/**
* How tall a wall stands: its own height (a low wall, a counter), else the floor height. It may rise above the floor height:
* the wall of a room whose ceiling reaches into the floor above (#55), or a sloping wall, whose highest point this is.
*/
export const wallHeight = (wall: Wall, floorHeight: number): number =>
wall.heightEnd === undefined ? (wall.height ?? floorHeight) : Math.max(wall.height ?? floorHeight, wall.heightEnd);
/**
* Sorts the walls into buckets by the direction they face: all interior walls are one bucket, exterior walls fall into
* compass sectors. A bucket is what folds away together.
*/
export function bucketWalls(walls: Wall[]): { buckets: (Vec2 | null)[]; wallBucket: Map<Wall, number> } {
const indexOfKey = new Map<string, number>();
const buckets: (Vec2 | null)[] = [];
const wallBucket = new Map<Wall, number>();
for (const wall of walls) {
let key = "interior";
let normal: Vec2 | null = null;
if (wall.exterior) {
const [dx, dz] = [wall.b[0] - wall.a[0], wall.b[1] - wall.a[1]];
const length = Math.hypot(dx, dz) || 1;
const out: Vec2 = [dz / length, -dx / length]; // the right normal: away from the room
const sector = ((Math.round((Math.atan2(out[1], out[0]) / (2 * Math.PI)) * SECTORS) % SECTORS) + SECTORS) % SECTORS;
key = `s${sector}`;
const angle = (sector / SECTORS) * 2 * Math.PI;
normal = [Math.cos(angle), Math.sin(angle)];
}
if (!indexOfKey.has(key)) {
indexOfKey.set(key, buckets.length);
buckets.push(normal);
}
wallBucket.set(wall, indexOfKey.get(key)!);
}
return { buckets, wallBucket };
}
/** The roof limits of a floor's walls: the top of a wall at a point, and the lowest top along a stretch of a wall. */
export function roofLimits(roofUnder?: (x: number, z: number) => number | null) {
/** The top of a wall at a point: its own height, or the roof above when that is lower. */
const topAt = (x: number, z: number, height: number): number => {
const roof = roofUnder ? roofUnder(x, z) : null;
return roof === null ? height : Math.max(0.05, Math.min(height, roof));
};
/** The lowest wall top along a stretch of a wall (sampled), for openings and the top edge line. */
const lowestTop = (a: Vec2, axis: Vec2, s0: number, s1: number, height: number): number => {
if (!roofUnder) return height;
const samples = Math.max(2, Math.ceil((s1 - s0) / 0.25) + 1);
let lowest = height;
for (let i = 0; i < samples; i++) {
const s = s0 + ((s1 - s0) * i) / (samples - 1);
lowest = Math.min(lowest, topAt(a[0] + axis[0] * s, a[1] + axis[1] * s, height));
}
return lowest;
};
return { topAt, lowestTop };
}
/** The tops of one wall: its highest point, the top at a point, and the lowest top along a stretch, with a sloping wall's slope and the roof above both counted. */
export function wallTops(wall: Wall, floorHeight: number, limits: ReturnType<typeof roofLimits>) {
const H = wallHeight(wall, floorHeight);
const length = Math.hypot(wall.b[0] - wall.a[0], wall.b[1] - wall.a[1]);
const axis = unit([wall.b[0] - wall.a[0], wall.b[1] - wall.a[1]]);
if (wall.heightEnd === undefined) return { H, varies: false, topAt: (x: number, z: number) => limits.topAt(x, z, H), lowestTop: (s0: number, s1: number) => limits.lowestTop(wall.a, axis, s0, s1, H) };
const [h0, h1] = [wall.height ?? floorHeight, wall.heightEnd];
/** The height of the sloping top above a point: straight from h0 at a to h1 at b. */
const slopeAt = (x: number, z: number): number => {
const t = length > 1e-9 ? ((x - wall.a[0]) * axis[0] + (z - wall.a[1]) * axis[1]) / length : 0;
return h0 + (h1 - h0) * Math.max(0, Math.min(1, t));
};
const topAt = (x: number, z: number) => limits.topAt(x, z, slopeAt(x, z));
const lowestTop = (s0: number, s1: number): number => {
const samples = Math.max(2, Math.ceil((s1 - s0) / 0.25) + 1);
let lowest = Infinity;
for (let i = 0; i < samples; i++) {
const s = s0 + ((s1 - s0) * i) / (samples - 1);
lowest = Math.min(lowest, topAt(wall.a[0] + axis[0] * s, wall.a[1] + axis[1] * s));
}
return lowest;
};
return { H, varies: true, topAt, lowestTop };
}
/** Puts every opening onto its wall: its span along the wall, the side the room is on, its sill and top. */
export function placeOpenings(floor: Floor, walls: Wall[], wallBucket: Map<Wall, number>, limits: ReturnType<typeof roofLimits>): { openings: OpeningInfo[]; spans: Map<Wall, Span[]> } {
const spans = new Map<Wall, Span[]>();
const openings: OpeningInfo[] = [];
for (const o of floor.openings) {
const host = openingHost(o, floor.rooms, floor.walls ?? []);
const hit = host && locateOpening(walls, o, host);
if (!host || !hit) continue;
const { wall, s } = hit;
const axis = unit([wall.b[0] - wall.a[0], wall.b[1] - wall.a[1]]);
const length = Math.hypot(wall.b[0] - wall.a[0], wall.b[1] - wall.a[1]);
const width = Math.min(o.width, length);
const s0 = Math.max(0, Math.min(length - width, s - width / 2));
// in a free wall the "room" side is the left of the wall as drawn
const hp = host.room.points;
const roomOnLeft = wall.free ? axis[0] * (hp[1][0] - hp[0][0]) + axis[1] * (hp[1][1] - hp[0][1]) > 0 : wall.roomLeft === o.room_id;
const leftNormal: Vec2 = [-axis[1], axis[0]];
const toRoom: Vec2 = roomOnLeft ? leftNormal : [-leftNormal[0], -leftNormal[1]];
// sill and top count from the floor of the opening's room, which may lie on its own level (#57)
const level = roomOffset(floor.rooms.find((r) => r.id === o.room_id));
const top = Math.min(wallTops(wall, floor.height, limits).lowestTop(s0, s0 + width) - 0.02, level + o.sill + o.height);
const sill = Math.max(Math.min(0, level), Math.min(level + o.sill, top - 0.1));
// looking at the wall from the room, "right" is (toRoom.z, -toRoom.x)
const right: Vec2 = [toRoom[1], -toRoom[0]];
const startIsLeft = axis[0] * right[0] + axis[1] * right[1] > 0;
const info: OpeningInfo = {
opening: o,
bucket: wallBucket.get(wall)!,
start: [wall.a[0] + axis[0] * s0, wall.a[1] + axis[1] * s0],
axis,
width,
toRoom,
faceRoom: roomOnLeft ? wall.left : wall.right,
faceOut: roomOnLeft ? wall.right : wall.left,
sill,
top,
hingeAtStart: (o.hinge === "left") === startIsLeft,
exterior: wall.exterior,
};
openings.push(info);
spans.set(wall, [...(spans.get(wall) ?? []), { s0, s1: s0 + width, sill, top, info }]);
}
return { openings, spans };
}
+35
View File
@@ -0,0 +1,35 @@
// The baked shadow on the floor: strips along every wall face that borders a room (not across doorways).
import { Color } from "three";
import { pointInPolygon, type Room, type Vec2 } from "../../model.ts";
import type { Wall } from "../../geometry/walls.ts";
import { GeoBuffer } from "../geo.ts";
import { subtractSpans, type OutlineEdge } from "./outline.ts";
import type { Span } from "./types.ts";
const SHADOW_WIDTH = 0.42;
const SHADOW_DARK = 0.42;
export function buildShadow(edges: OutlineEdge[], rooms: readonly Room[], spans: Map<Wall, Span[]>): GeoBuffer {
const buf = new GeoBuffer();
const dark = new Color(SHADOW_DARK, SHADOW_DARK, SHADOW_DARK);
const clear = new Color(1, 1, 1);
const y = 0.002;
for (const edge of edges) {
for (const [a, b] of subtractSpans(edge, (spans.get(edge.wall) ?? []).filter((sp) => sp.sill <= 0.005))) {
const [dx, dz] = [b[0] - a[0], b[1] - a[1]];
const length = Math.hypot(dx, dz);
if (length < 0.05) continue;
// footprints are counter-clockwise, so the right normal points away from the wall
const n: Vec2 = [dz / length, -dx / length];
const probe: Vec2 = [(a[0] + b[0]) / 2 + n[0] * 0.05, (a[1] + b[1]) / 2 + n[1] * 0.05];
if (!rooms.some((r) => r.points.length >= 3 && pointInPolygon(probe, r.points))) continue;
const a2: Vec2 = [a[0] + n[0] * SHADOW_WIDTH, a[1] + n[1] * SHADOW_WIDTH];
const b2: Vec2 = [b[0] + n[0] * SHADOW_WIDTH, b[1] + n[1] * SHADOW_WIDTH];
// the layer is drawn double-sided, so the winding does not matter
buf.tri([a[0], y, a[1]], [a2[0], y, a2[1]], [b2[0], y, b2[1]], dark, clear, clear);
buf.tri([a[0], y, a[1]], [b2[0], y, b2[1]], [b[0], y, b[1]], dark, clear, dark);
}
}
return buf;
}
+186
View File
@@ -0,0 +1,186 @@
// The wall solids: every wall cut into pieces at its openings, built as prisms that fold away above the cut height.
import type { Wall } from "../../geometry/walls.ts";
import { DEFAULT_PAINT_INSIDE, DEFAULT_PAINT_OUTSIDE, pointInPolygon, roomOffset, type BuildingSettings, type Floor, type Vec2 } from "../../model.ts";
import { CAP_OFFSET, LOWER_OFFSET, PAINT_OFFSET, pushPrism, type GeoBuffer } from "../geo.ts";
import { NEON, SLAB } from "./look.ts";
import { clipAlong, unit } from "./outline.ts";
import { glassJoins } from "./glass-joins.ts";
import { wallTops, type roofLimits } from "./placement.ts";
import type { Span } from "./types.ts";
interface Piece {
t0: number;
t1: number;
/** The height ranges the wall fills at this piece (between and around openings). */
ranges: [number, number][];
}
/** Wall paint for the solid wall view: outside, inside, and the rooms with a colour of their own. */
export interface WallPaint {
outside: number;
inside: number;
rooms: { points: Vec2[]; color: number }[];
}
/** A "#rrggbb" paint as a number, or the fallback when it is missing or not a colour. */
const paintHex = (v: string | null | undefined, fallback: string): number => Number.parseInt(/^#?([0-9a-f]{6})$/i.exec(v?.trim() ?? "")?.[1] ?? fallback.slice(1), 16);
const isPaint = (v: string | null | undefined): v is string => /^#?[0-9a-f]{6}$/i.test(v?.trim() ?? "");
/**
* The paint of one floor's walls: the floor's own outside colour if it has one (a plinth, a garage, #110), else the
* building's; and only this floor's rooms, so a room upstairs does not paint the wall below it in the same spot.
*/
export function wallPaintOf(settings: Pick<BuildingSettings, "wall_paint_outside" | "wall_paint_inside">, floor: { rooms: readonly { points: Vec2[]; wall_paint?: string | null }[]; wall_paint_outside?: string | null }): WallPaint {
return {
outside: paintHex(isPaint(floor.wall_paint_outside) ? floor.wall_paint_outside : settings.wall_paint_outside, DEFAULT_PAINT_OUTSIDE),
inside: paintHex(settings.wall_paint_inside, DEFAULT_PAINT_INSIDE),
rooms: floor.rooms.filter((r) => r.wall_paint && r.points.length >= 3).map((r) => ({ points: r.points, color: paintHex(r.wall_paint, DEFAULT_PAINT_INSIDE) })),
};
}
/** The top of a painted wall, where it is cut or ends: a plain light grey, like plaster seen in section. */
const PAINT_TOP = 0xd9d5cd;
/**
* The paint of one side face of a wall: the colour of the room in front of it, the inside colour when a room without one
* of its own is there, the outside colour when no room is.
*/
export function paintOfSide(poly: Vec2[], a: Vec2, b: Vec2, paint: WallPaint, rooms: { points: Vec2[] }[]): number {
const len = Math.hypot(b[0] - a[0], b[1] - a[1]) || 1;
const m: Vec2 = [(a[0] + b[0]) / 2, (a[1] + b[1]) / 2];
let n: Vec2 = [(b[1] - a[1]) / len, -(b[0] - a[0]) / len];
// the normal that points away from the wall body
if (pointInPolygon([m[0] + n[0] * 0.01, m[1] + n[1] * 0.01], poly)) n = [-n[0], -n[1]];
const front: Vec2 = [m[0] + n[0] * 0.06, m[1] + n[1] * 0.06];
const own = paint.rooms.find((r) => pointInPolygon(front, r.points));
if (own) return own.color;
return rooms.some((r) => r.points.length >= 3 && pointInPolygon(front, r.points)) ? paint.inside : paint.outside;
}
/**
* Pieces along the wall's axis, cut at every opening edge. Each piece leaves out all openings above it (two windows one
* above the other, a window over a door), and the wall fills what remains.
*/
function piecesOf(spans: Span[], height: number, bottom = -SLAB): Piece[] {
const stops = [-Infinity, ...new Set(spans.flatMap((sp) => [sp.s0, sp.s1])).values(), Infinity].sort((a, b) => a - b);
const pieces: Piece[] = [];
for (let i = 0; i + 1 < stops.length; i++) {
const [t0, t1] = [stops[i], stops[i + 1]];
if (t1 - t0 < 1e-6) continue;
const middle = Number.isFinite(t0) && Number.isFinite(t1) ? (t0 + t1) / 2 : Number.isFinite(t0) ? t0 + 1 : t1 - 1;
const covering = spans.filter((sp) => sp.s0 < middle && sp.s1 > middle).map((sp) => [sp.sill, sp.top] as [number, number]).sort((a, b) => a[0] - b[0]);
const ranges: [number, number][] = [];
let y = bottom;
for (const [lower, upper] of covering) {
if (lower > y + 1e-4) ranges.push([y, lower]);
y = Math.max(y, upper);
}
if (height > y + 1e-4) ranges.push([y, height]);
pieces.push({ t0, t1, ranges });
}
return pieces;
}
export function buildWallSolids(
buf: GeoBuffer,
floor: Floor,
walls: Wall[],
wallBucket: Map<Wall, number>,
spans: Map<Wall, Span[]>,
limits: ReturnType<typeof roofLimits>,
hasRoof: boolean,
/** Painted walls (solid wall view): each face in its colour, and marked so every look keeps that colour. */
paint?: WallPaint,
): void {
const cut = Math.min(floor.cut_height, floor.height);
const offset = paint ? PAINT_OFFSET : 0;
const sideColor = paint ? (poly: Vec2[]) => (a: Vec2, b: Vec2) => paintOfSide(poly, a, b, paint, floor.rooms) : null;
const top = paint ? PAINT_TOP : NEON.wallTop;
// the two wall ends at an internal join of one pane are not a jamb: without this, a full-height wall
// face stays there, which reads as a frame across the glass
const joins = glassJoins(spans.values());
// At a join the pane runs on to the next wall, so what stands beyond the end of the opening is the
// mitre overflow of the footprint only — a few centimetres of wall, full height. In the height band of
// the pane it stands in front of the glass, on the outer face: that strip, 1 to 5 cm wide and as tall
// as the room, is the white line seen at a bend from outside. The band stays empty there, exactly as it
// does between two openings; above and below the pane the overflow is still the wall that fills the
// corner of the mitre, so the bend does not open into a hole.
const nearJoin = (p: Vec2) => joins.points.some((j) => Math.hypot(j[0] - p[0], j[1] - p[1]) < 0.03);
const bandOf = (sp: Span | undefined) => (sp && sp.info.opening.front ? ([sp.sill, sp.top] as [number, number]) : null);
const cutBand = (ranges: [number, number][], band: [number, number]): [number, number][] => {
const out: [number, number][] = [];
for (const [a, b] of ranges) {
if (band[0] > a + 1e-4) out.push([a, Math.min(b, band[0])]);
if (b > band[1] + 1e-4) out.push([Math.max(a, band[1]), b]);
}
return out;
};
for (const wall of walls) {
const bucket = wallBucket.get(wall)!;
const axis = unit([wall.b[0] - wall.a[0], wall.b[1] - wall.a[1]]);
const list = (spans.get(wall) ?? []).sort((p, q) => p.s0 - q.s0);
const tops = wallTops(wall, floor.height, limits);
const { H, topAt } = tops;
// a wall beside a room on a lower level reaches down to that room's floor
const lowest = Math.min(0, ...[wall.roomLeft, wall.roomRight].map((id) => roomOffset(floor.rooms.find((r) => r.id === id))));
const pieces = piecesOf(list, H, lowest - SLAB);
// under a roof the pieces are cut into short steps, so each step's top lies in one roof plane
const length = Math.hypot(wall.b[0] - wall.a[0], wall.b[1] - wall.a[1]);
// (a sloping wall is cut into steps the same way: its top then lies in one plane per step)
const underRoof = (hasRoof || tops.varies) && tops.lowestTop(0, length) < H - 1e-3;
const steps = underRoof
? pieces.flatMap((piece) => {
const from = Math.max(piece.t0, -0.5);
const to = Math.min(piece.t1, length + 0.5);
const count = Math.max(1, Math.ceil((to - from) / 0.3));
return Array.from({ length: count }, (_, i) => ({
t0: i === 0 ? piece.t0 : from + ((to - from) * i) / count,
t1: i === count - 1 ? piece.t1 : from + ((to - from) * (i + 1)) / count,
ranges: piece.ranges,
inner0: i > 0,
inner1: i < count - 1,
}));
})
: pieces.map((piece) => ({ ...piece, inner0: false, inner1: false }));
const along = (p: Vec2) => (p[0] - wall.a[0]) * axis[0] + (p[1] - wall.a[1]) * axis[1];
// the overflow before the start of the wall, and beyond its end, only where the pane runs on
const bandStart = nearJoin(wall.a) ? bandOf(list[0]) : null;
const bandEnd = nearJoin(wall.b) ? bandOf(list[list.length - 1]) : null;
for (const step of steps) {
const poly = clipAlong(wall.footprint, wall.a, axis, step.t0, step.t1);
if (poly.length < 3) continue;
const overflow = step.t1 <= 1e-6 && step.t0 < 0 ? bandStart : step.t0 >= length - 1e-6 ? bandEnd : null;
const ranges = overflow ? cutBand(step.ranges, overflow) : step.ranges;
// the faces between two steps of one piece lie inside the wall: leave them out, or they show as stripes through see-through walls
const at = (p: Vec2, t: number) => Math.abs(along(p) - t) < 1e-4;
const roofSide = (p: Vec2, q: Vec2) => (step.inner0 && at(p, step.t0) && at(q, step.t0)) || (step.inner1 && at(p, step.t1) && at(q, step.t1));
// a short end face that starts at an internal join is the wall showing through the bend; a real wall
// face is longer than half a metre, so it is never taken for one
const paneSide = (p: Vec2, q: Vec2) => {
if (!joins.points.length || Math.hypot(p[0] - q[0], p[1] - q[1]) > 0.5) return false;
return joins.points.some((j) => Math.min(Math.hypot(j[0] - p[0], j[1] - p[1]), Math.hypot(j[0] - q[0], j[1] - q[1])) < 0.05);
};
const skipSide = (p: Vec2, q: Vec2) => roofSide(p, q) || paneSide(p, q);
// the roof over this step: the lowest point of its footprint decides what is left of each range
const roofTop = underRoof ? Math.min(...poly.map(([x, z]) => topAt(x, z))) : H;
for (const [y0, y1raw] of ranges) {
const y1 = Math.min(y1raw, underRoof ? Math.max(...poly.map(([x, z]) => topAt(x, z))) : y1raw);
if (y1 - y0 < 1e-4 || roofTop - y0 < 0.01) continue;
const lintel = y0 > 0.01;
const sloped = underRoof && y1raw > roofTop;
const topOf = (x: number, z: number) => Math.min(y1raw, topAt(x, z));
if (y0 < cut - 1e-6) {
// the top face at the cut height is only seen while the wall is cut
const topFold = y1 > cut + 1e-6 ? CAP_OFFSET + bucket : LOWER_OFFSET + bucket;
const capped = sloped && roofTop < cut ? (x: number, z: number) => Math.min(cut, topOf(x, z)) : Math.min(y1, cut);
pushPrism(buf, poly, y0, capped, NEON.wall, top, { aoFrom: 0, bottom: lintel, fold: offset + LOWER_OFFSET + bucket, topFold: offset + topFold, skipSide, sideColor: sideColor?.(poly) });
}
if (y1 > cut + 1e-6 && roofTop > cut + 1e-6) {
pushPrism(buf, poly, Math.max(y0, cut), sloped ? topOf : y1, NEON.wall, top, { aoFrom: 0, fold: offset + bucket, bottom: lintel && y0 >= cut, skipSide, sideColor: sideColor?.(poly) });
}
}
}
}
}
+60
View File
@@ -0,0 +1,60 @@
import type { BufferGeometry } from "three";
import type { Wall } from "../../geometry/walls.ts";
import type { Opening, Vec2 } from "../../model.ts";
/** An opening resolved onto its wall, as frames, sashes and blinds need it. */
export interface OpeningInfo {
opening: Opening;
/** The fold bucket of the wall it sits in. */
bucket: number;
/** The start of the opening on the wall axis, and the axis direction (x, z). */
start: Vec2;
axis: Vec2;
width: number;
/** The unit normal pointing into the opening's room. */
toRoom: Vec2;
/** The distance from the wall axis to the room-side face and to the other face. */
faceRoom: number;
faceOut: number;
sill: number;
top: number;
/** True when the sash hinge is at the start of the opening (as seen along the axis). */
hingeAtStart: boolean;
exterior: boolean;
}
export interface FloorGeometry {
floor: BufferGeometry;
/** Triangle ranges of room tops (for picking and highlighting) with their base colour. */
roomTris: { roomId: string; start: number; end: number; color: number }[];
/** Openings cut into the floor (stairwells, galleries): the light surface leaves them out. */
holes: Vec2[][];
/** Walls (with folding upper parts) and furniture. */
walls: BufferGeometry;
/** Outdoor areas drawn see-through, one geometry per opacity (0.1 … 0.95). */
ghosts: { opacity: number; geometry: BufferGeometry }[];
lines: BufferGeometry;
/** A multiply layer darkening the floor along walls and under furniture (baked occlusion). */
shadow: BufferGeometry;
/** The outward direction (x, z) of each fold bucket; null for interior walls. The index is the bucket id. */
buckets: (Vec2 | null)[];
openings: OpeningInfo[];
walls2d: Wall[];
/** Pairs of rooms joined by "no wall": one space, also for the light. */
openRooms: [string, string][];
/** The fold bucket of each wall in walls2d. */
wallBuckets: number[];
/** Triangle ranges of furniture in `walls`, for tapping furniture in 3D. */
furnitureTris: { id: string; start: number; end: number }[];
/** Under roof slopes: the roof's underside above a plan point in floor coordinates (null: no roof there). */
roofUnder?: (x: number, z: number) => number | null;
}
/** An opening on a wall as a span along its axis (metres from wall.a). */
export interface Span {
s0: number;
s1: number;
sill: number;
top: number;
info: OpeningInfo;
}
+4
View File
@@ -0,0 +1,4 @@
// The orbit camera, split into modules in controls/: the view maths and the pointer handling.
export { OrbitControls, type ControlEvents } from "./controls/controls.ts";
export type { OrbitView } from "./controls/view.ts";
@@ -0,0 +1,19 @@
import assert from "node:assert/strict";
import { test } from "node:test";
import { walkKey } from "./controls.ts";
test("walking keys go by their place on the keyboard, so AZERTY walks with Z Q S D", () => {
// QWERTY and QWERTZ
assert.equal(walkKey({ code: "KeyW", key: "w" }), "w");
assert.equal(walkKey({ code: "KeyA", key: "a" }), "a");
// AZERTY: Z sits where W is, Q where A is, A where Q is
assert.equal(walkKey({ code: "KeyW", key: "z" }), "w");
assert.equal(walkKey({ code: "KeyA", key: "q" }), "a");
assert.equal(walkKey({ code: "KeyQ", key: "a" }), "q");
// arrows, and a browser without code
assert.equal(walkKey({ code: "ArrowUp", key: "ArrowUp" }), "arrowup");
assert.equal(walkKey({ key: "D" }), "d");
// other keys
assert.equal(walkKey({ code: "KeyZ", key: "w" }), null);
assert.equal(walkKey({ code: "Space", key: " " }), null);
});
+339
View File
@@ -0,0 +1,339 @@
// The orbit camera's pointer handling: turning, panning, pinch zoom, taps, holds, and handing pointers over to objects.
// The owner calls update() each frame; it returns true while something still moves.
import type { PerspectiveCamera } from "three";
import { Vector3 } from "three";
import { blendViews, cameraPosition, clamp, coast, copyView, flightGoal, orbitView, panView, type OrbitView } from "./view.ts";
export interface ControlEvents {
change(): void;
tap(x: number, y: number): void;
doubleTap(x: number, y: number): void;
/** A press without moving for HOLD_MS; the release that follows is no tap. */
hold(x: number, y: number): void;
/** A pointer went down: return true to take it (drag an object instead of turning the view). */
grab?(x: number, y: number): boolean;
drag?(x: number, y: number): void;
drop?(): void;
/**
* A one-finger drag starts at (x, y) and moves by (dx, dy): return true to take it as a swipe on an object (dimming a
* lamp, moving a blind) rather than turning the view. Moves then report the vertical distance from the start (pixels,
* down is positive).
*/
swipeStart?(x: number, y: number, dx: number, dy: number): boolean;
swipeMove?(dy: number): void;
swipeEnd?(): void;
}
/** Walking keys by their place on the keyboard (W A S D on QWERTY is Z Q S D on AZERTY), and the arrows. */
const WALK_CODES: Record<string, string> = { KeyW: "w", KeyA: "a", KeyS: "s", KeyD: "d", KeyQ: "q", KeyE: "e" };
const WALK_KEYS = new Set(["w", "a", "s", "d", "q", "e", "arrowup", "arrowdown", "arrowleft", "arrowright"]);
/** The walking key a key press stands for (null: none). The place of the key wins over its letter. */
export function walkKey(e: { code?: string; key: string }): string | null {
// a letter key is known by its place; other keys (the arrows), and browsers without a code, by their name
const name = e.code?.startsWith("Key") ? (WALK_CODES[e.code] ?? null) : e.key.toLowerCase();
return name && WALK_KEYS.has(name) ? name : null;
}
const HOLD_MS = 500;
const TAP_MAX_MS = 400;
const DOUBLE_TAP_MS = 320;
const DRAG_THRESHOLD = 6;
interface PointerInfo {
x: number;
y: number;
button: number;
}
/** Walking speed (m/s) and turning speed (rad/s). */
const WALK_SPEED = 1.5;
const TURN_SPEED = 1.8;
export interface Walk {
eye: Vector3;
/** Heading like the orbit's theta: the eye looks along (-sin yaw, 0, -cos yaw). */
yaw: number;
/** Up (+) or down (-) from the horizon, radians. */
pitch: number;
/** The touch stick: x turns or steps sideways, y walks (-1 … 1 each). */
stick: [number, number];
keys: Set<string>;
bounds: { x0: number; x1: number; z0: number; z1: number };
last: number;
}
/** One step of walking: moves the eye by keys and stick over dt milliseconds, kept in its bounds. Returns whether it moved. */
export function stepWalk(w: Walk, dt: number): boolean {
const k = w.keys;
const ahead = (k.has("w") || k.has("arrowup") ? 1 : 0) - (k.has("s") || k.has("arrowdown") ? 1 : 0) - w.stick[1];
const side = (k.has("d") ? 1 : 0) - (k.has("a") ? 1 : 0);
const turn = (k.has("arrowleft") || k.has("q") ? 1 : 0) - (k.has("arrowright") || k.has("e") ? 1 : 0) - w.stick[0];
if (!ahead && !side && !turn) return false;
const s = dt / 1000;
w.yaw += turn * TURN_SPEED * s;
const [fx, fz] = [-Math.sin(w.yaw), -Math.cos(w.yaw)];
const [rx, rz] = [Math.cos(w.yaw), -Math.sin(w.yaw)];
w.eye.x = clamp(w.eye.x + (fx * ahead + rx * side) * WALK_SPEED * s, w.bounds.x0, w.bounds.x1);
w.eye.z = clamp(w.eye.z + (fz * ahead + rz * side) * WALK_SPEED * s, w.bounds.z0, w.bounds.z1);
return true;
}
export class OrbitControls {
view: OrbitView = { target: new Vector3(), radius: 16, theta: -0.6, phi: 0.85 };
minRadius = 2;
maxRadius = 80;
/** A wall tablet's 3D lock: the camera does not turn, pan or zoom by hand; taps, holds and swipes on devices still work. */
locked = false;
/** Walking at eye level: where the eye is, which way it looks, the stick and keys that move it, and the area it stays in. Null while orbiting. */
walk: Walk | null = null;
private readonly pointers = new Map<number, PointerInfo>();
private velocity = { theta: 0, phi: 0 };
private flight: { from: OrbitView; to: OrbitView; start: number; duration: number } | null = null;
private press: { x: number; y: number; time: number; moved: boolean } | null = null;
private lastTap = 0;
private holdTimer: ReturnType<typeof setTimeout> | undefined;
private held = false;
/** An object is being dragged: moves go to events.drag and not to the camera. */
private grabbing = false;
/** A swipe on an object is going on: vertical moves go to events.swipeMove. */
private swiping: { startY: number } | null = null;
private pinch: { dist: number; mid: [number, number] } | null = null;
private readonly listeners: [string, EventListener][] = [];
private readonly el: HTMLElement;
private readonly camera: PerspectiveCamera;
private readonly events: ControlEvents;
constructor(el: HTMLElement, camera: PerspectiveCamera, events: ControlEvents) {
this.el = el;
this.camera = camera;
this.events = events;
const listen = <K extends keyof HTMLElementEventMap>(type: K, handler: (e: HTMLElementEventMap[K]) => void, options?: AddEventListenerOptions) => {
el.addEventListener(type, handler as EventListener, options);
this.listeners.push([type, handler as EventListener]);
};
listen("pointerdown", (e) => this.onDown(e));
listen("pointermove", (e) => this.onMove(e));
listen("pointerup", (e) => this.onUp(e));
listen("pointercancel", (e) => this.onUp(e));
listen("wheel", (e) => this.onWheel(e), { passive: false });
listen("contextmenu", (e) => e.preventDefault());
// keys walk while walking (not while typing into a field)
const key = (down: boolean) => (e: KeyboardEvent) => {
if (!this.walk || (e.target as HTMLElement | null)?.closest?.("input, textarea, select")) return;
const name = walkKey(e);
if (!name) return;
e.preventDefault();
if (down) this.walk.keys.add(name);
else this.walk.keys.delete(name);
this.events.change();
};
const keydown = key(true);
const keyup = key(false);
window.addEventListener("keydown", keydown);
window.addEventListener("keyup", keyup);
this.listeners.push(["__window_keydown", keydown as EventListener], ["__window_keyup", keyup as EventListener]);
}
dispose(): void {
clearTimeout(this.holdTimer);
for (const [type, handler] of this.listeners) {
if (type.startsWith("__window_")) window.removeEventListener(type.slice("__window_".length), handler);
else this.el.removeEventListener(type, handler);
}
}
/** A finger or the mouse holds the view, or a flight runs (an automatic orbit waits meanwhile). */
get active(): boolean {
return this.pointers.size > 0 || this.flight !== null;
}
get busy(): boolean {
return this.active;
}
/** Applies the view to the camera. Returns true while inertia or a flight is running. */
update(now: number): boolean {
if (this.walk) {
const w = this.walk;
const moved = stepWalk(w, w.last ? Math.min(100, now - w.last) : 16);
w.last = moved ? now : 0;
const dir = new Vector3(-Math.sin(w.yaw) * Math.cos(w.pitch), Math.sin(w.pitch), -Math.cos(w.yaw) * Math.cos(w.pitch));
// the orbit view follows, so labels and anything that asks for the target still work
this.view.target.copy(w.eye).add(dir);
this.camera.position.copy(w.eye);
this.camera.lookAt(this.view.target);
return moved;
}
let moving = false;
if (this.flight) {
const { from, to, start, duration } = this.flight;
const fraction = Math.min(1, (now - start) / duration);
this.view = blendViews(from, to, fraction);
if (fraction >= 1) this.flight = null;
moving = true;
} else if (this.pointers.size === 0) {
moving = coast(this.view, this.velocity);
}
this.camera.position.copy(cameraPosition(this.view));
this.camera.lookAt(this.view.target);
return moving;
}
flyTo(to: Partial<OrbitView>, duration = 700): void {
const goal = flightGoal(this.view, to);
const from = copyView(this.view);
this.velocity = { theta: 0, phi: 0 };
if (duration <= 0 || matchMedia("(prefers-reduced-motion: reduce)").matches) {
this.view = goal;
this.flight = null;
} else {
this.flight = { from, to: goal, start: performance.now(), duration };
}
this.events.change();
}
private local(e: { clientX: number; clientY: number }): [number, number] {
const rect = this.el.getBoundingClientRect();
return [e.clientX - rect.left, e.clientY - rect.top];
}
private stopMotion(): void {
this.flight = null;
this.velocity = { theta: 0, phi: 0 };
}
private onDown(e: PointerEvent): void {
this.el.setPointerCapture(e.pointerId);
const first = this.pointers.size === 0;
this.pointers.set(e.pointerId, { x: e.clientX, y: e.clientY, button: e.button });
this.stopMotion();
if (first && e.button === 0 && this.events.grab?.(...this.local(e))) {
this.grabbing = true;
return;
}
clearTimeout(this.holdTimer);
this.held = false;
if (this.pointers.size === 1) {
this.press = { x: e.clientX, y: e.clientY, time: performance.now(), moved: false };
const [x, y] = this.local(e);
this.holdTimer = setTimeout(() => {
if (!this.press || this.press.moved || this.pointers.size !== 1) return;
this.held = true;
this.events.hold(x, y);
}, HOLD_MS);
} else {
this.press = null;
this.pinch = this.pinchState();
}
}
private onMove(e: PointerEvent): void {
const pointer = this.pointers.get(e.pointerId);
if (!pointer) return;
if (this.grabbing) return void this.events.drag?.(...this.local(e));
if (this.swiping) return void this.events.swipeMove?.(e.clientY - this.swiping.startY);
const [dx, dy] = [e.clientX - pointer.x, e.clientY - pointer.y];
if (this.press && !this.press.moved && Math.hypot(e.clientX - this.press.x, e.clientY - this.press.y) > DRAG_THRESHOLD) {
this.press.moved = true;
clearTimeout(this.holdTimer);
const [sx, sy] = this.local({ clientX: this.press.x, clientY: this.press.y });
const swipe = this.pointers.size === 1 && pointer.button === 0 && !e.shiftKey && this.events.swipeStart?.(sx, sy, e.clientX - this.press.x, e.clientY - this.press.y);
if (swipe) {
this.swiping = { startY: this.press.y };
this.velocity = { theta: 0, phi: 0 };
return void this.events.swipeMove?.(e.clientY - this.press.y);
}
}
if (this.locked) {
[pointer.x, pointer.y] = [e.clientX, e.clientY];
return;
}
if (this.walk) {
// walking: a drag looks around
if (!(this.press && !this.press.moved) && this.pointers.size === 1) {
const h = this.el.clientHeight || 1;
this.walk.yaw += (dx / h) * 2.4;
this.walk.pitch = clamp(this.walk.pitch + (dy / h) * 1.8, -1.1, 1.1);
this.events.change();
}
[pointer.x, pointer.y] = [e.clientX, e.clientY];
return;
}
if (this.pointers.size === 1) {
if (!(this.press && !this.press.moved)) {
if (pointer.button === 1 || pointer.button === 2 || e.shiftKey) panView(this.view, dx, dy, this.el.clientHeight, this.camera.fov);
else this.velocity = orbitView(this.view, dx, dy, this.el.clientHeight);
}
[pointer.x, pointer.y] = [e.clientX, e.clientY];
} else {
[pointer.x, pointer.y] = [e.clientX, e.clientY];
const now = this.pinchState();
if (this.pinch && now) {
this.zoom(this.pinch.dist / Math.max(1, now.dist));
panView(this.view, now.mid[0] - this.pinch.mid[0], now.mid[1] - this.pinch.mid[1], this.el.clientHeight, this.camera.fov);
}
this.pinch = now;
}
if (!(this.pointers.size === 1 && this.press && !this.press.moved)) this.events.change();
}
private onUp(e: PointerEvent): void {
if (!this.pointers.has(e.pointerId)) return;
this.pointers.delete(e.pointerId);
if (this.grabbing) {
this.grabbing = false;
return void this.events.drop?.();
}
if (this.swiping) {
this.swiping = null;
this.press = null;
return void this.events.swipeEnd?.();
}
if (this.pointers.size < 2) this.pinch = null;
clearTimeout(this.holdTimer);
if (this.held) {
this.held = false;
this.press = null;
} else if (this.press && !this.press.moved && e.type === "pointerup" && performance.now() - this.press.time < TAP_MAX_MS) {
const [x, y] = this.local(e);
const now = performance.now();
const isDouble = now - this.lastTap < DOUBLE_TAP_MS;
this.lastTap = isDouble ? 0 : now;
if (isDouble) this.events.doubleTap(x, y);
else this.events.tap(x, y);
}
if (this.pointers.size === 0) this.press = null;
this.events.change();
}
private onWheel(e: WheelEvent): void {
e.preventDefault();
if (this.locked) return;
if (this.walk) {
// the wheel takes a step forward or back
const step = clamp(-e.deltaY * (e.deltaMode === 1 ? 0.05 : 0.002), -0.6, 0.6);
const w = this.walk;
w.eye.x = clamp(w.eye.x - Math.sin(w.yaw) * step, w.bounds.x0, w.bounds.x1);
w.eye.z = clamp(w.eye.z - Math.cos(w.yaw) * step, w.bounds.z0, w.bounds.z1);
this.events.change();
return;
}
this.flight = null;
this.zoom(Math.exp(e.deltaY * (e.deltaMode === 1 ? 0.05 : 0.0015)));
this.events.change();
}
private zoom(factor: number): void {
this.view.radius = clamp(this.view.radius * factor, this.minRadius, this.maxRadius);
}
private pinchState(): { dist: number; mid: [number, number] } | null {
const [a, b] = [...this.pointers.values()];
return b ? { dist: Math.hypot(a.x - b.x, a.y - b.y), mid: [(a.x + b.x) / 2, (a.y + b.y) / 2] } : null;
}
}
+111
View File
@@ -0,0 +1,111 @@
import assert from "node:assert/strict";
import { test } from "node:test";
import { Vector3 } from "three";
import { blendViews, cameraPosition, clamp, coast, copyView, ease, flightGoal, MAX_PHI, MIN_PHI, orbitView, panView, type OrbitView } from "./view.ts";
const near = (a: number, b: number, eps = 1e-9) => assert.ok(Math.abs(a - b) < eps, `${a} vs ${b}`);
const view = (extra: Partial<OrbitView> = {}): OrbitView => ({ target: new Vector3(1, 2, 3), radius: 10, theta: 0, phi: Math.PI / 2, ...extra });
test("clamp keeps a value inside its limits", () => {
assert.equal(clamp(5, 0, 3), 3);
assert.equal(clamp(-1, 0, 3), 0);
assert.equal(clamp(2, 0, 3), 2);
});
test("easing starts at 0, ends at 1, is slow at both ends and symmetric", () => {
near(ease(0), 0);
near(ease(1), 1);
near(ease(0.5), 0.5);
assert.ok(ease(0.1) < 0.1 && ease(0.9) > 0.9);
near(ease(0.25) + ease(0.75), 1);
});
test("the camera sits at the radius from the target, in the direction the angles say", () => {
const p = cameraPosition(view());
near(p.distanceTo(new Vector3(1, 2, 3)), 10);
near(p.y, 2, 1e-9); // phi = 90°: level with the target
near(p.z, 13); // theta = 0: in front, along +z
const above = cameraPosition(view({ phi: 0 }));
near(above.y, 12);
const side = cameraPosition(view({ theta: Math.PI / 2 }));
near(side.x, 11);
});
test("a blend between two views runs from the first to the second", () => {
const a = view();
const b = view({ target: new Vector3(5, 6, 7), radius: 20, theta: 1, phi: 1 });
const start = blendViews(a, b, 0);
const end = blendViews(a, b, 1);
near(start.radius, 10);
near(end.radius, 20);
assert.ok(end.target.equals(b.target));
const middle = blendViews(a, b, 0.5);
near(middle.radius, 15);
near(middle.theta, 0.5);
});
test("a flight turns the short way round and keeps what it is not told to change", () => {
const from = view({ theta: 3 });
assert.ok(Math.abs(flightGoal(from, { theta: -3 }).theta - 3) < 1, "from 3 to -3 goes through π, not back through 0");
const goal = flightGoal(from, { radius: 4 });
assert.equal(goal.radius, 4);
assert.equal(goal.theta, 3);
assert.equal(goal.phi, from.phi);
assert.notEqual(goal.target, from.target, "the target is copied");
});
test("copying a view copies its target", () => {
const a = view();
const b = copyView(a);
b.target.x = 99;
assert.equal(a.target.x, 1);
});
test("dragging turns the view, limits the tilt, and reports the turn for inertia", () => {
const v = view({ phi: 1 });
const turn = orbitView(v, 100, 0, 500);
assert.ok(v.theta < 0 && turn.theta < 0, "dragging right turns the view clockwise");
near(turn.theta, (-100 / 500) * 3.2);
orbitView(v, 0, 10000, 500);
assert.equal(v.phi, MIN_PHI);
orbitView(v, 0, -10000, 500);
assert.equal(v.phi, MAX_PHI);
});
test("inertia fades out and then stops", () => {
const v = view();
const velocity = { theta: 0.1, phi: 0 };
let steps = 0;
while (coast(v, velocity) && steps < 1000) steps++;
assert.ok(steps > 20 && steps < 200);
assert.ok(v.theta > 0.3 && v.theta < 1.1, "keeps turning a little");
assert.equal(coast(v, { theta: 0, phi: 0 }), false);
});
test("panning moves the target sideways, and further when zoomed out", () => {
const close = view({ radius: 5 });
const far = view({ radius: 20 });
panView(close, 100, 0, 500, 50);
panView(far, 100, 0, 500, 50);
assert.ok(close.target.x < 1 && far.target.x < close.target.x, "dragging right moves the scene right, so the target left");
const forward = view();
panView(forward, 0, 100, 500, 50);
assert.ok(forward.target.z < 3 || forward.target.z > 3, "dragging down moves the target along the view direction");
near(forward.target.x, 1);
});
test("walking moves the eye along its heading, turns with the stick and stays inside the floor", async () => {
const { stepWalk } = await import("./controls.ts");
const { Vector3 } = await import("three");
const walk = { eye: new Vector3(0, 1.6, 0), yaw: 0, pitch: 0, stick: [0, 0] as [number, number], keys: new Set(["w"]), bounds: { x0: -1, x1: 1, z0: -1, z1: 1 }, last: 0 };
assert.ok(stepWalk(walk, 400));
assert.equal(Math.round(walk.eye.z * 100) / 100, -0.6, "yaw 0 looks towards -z, 1.5 m/s for 0.4 s");
walk.keys = new Set();
assert.equal(stepWalk(walk, 400), false, "no key, no stick: no step");
walk.stick = [-1, 0];
stepWalk(walk, 500);
assert.ok(walk.yaw > 0.8, "the stick to the left turns left");
walk.stick = [0, -1];
for (let i = 0; i < 50; i++) stepWalk(walk, 100);
assert.ok(Math.abs(walk.eye.x) <= 1 && Math.abs(walk.eye.z) <= 1, "never leaves the floor");
});
+73
View File
@@ -0,0 +1,73 @@
// The camera's orbit view and the maths that moves it: flights, inertia, panning, zooming. No DOM in here.
import { Vector3 } from "three";
export interface OrbitView {
target: Vector3;
radius: number;
/** The azimuth around +y, in radians. */
theta: number;
/** The polar angle from +y, in radians. */
phi: number;
}
export const MIN_PHI = 0.12;
export const MAX_PHI = 1.35;
export const clamp = (v: number, lo: number, hi: number): number => Math.min(hi, Math.max(lo, v));
/** Ease in and out (cubic). */
export const ease = (t: number): number => (t < 0.5 ? 4 * t * t * t : 1 - (-2 * t + 2) ** 3 / 2);
export const copyView = (v: OrbitView): OrbitView => ({ ...v, target: v.target.clone() });
/** The camera position that looks at the target from the view's angles and distance. */
export function cameraPosition({ target, radius, theta, phi }: OrbitView): Vector3 {
return new Vector3(target.x + radius * Math.sin(phi) * Math.sin(theta), target.y + radius * Math.cos(phi), target.z + radius * Math.sin(phi) * Math.cos(theta));
}
/** A view blended between two views by an eased fraction. */
export function blendViews(from: OrbitView, to: OrbitView, fraction: number): OrbitView {
const k = ease(fraction);
return {
target: new Vector3().lerpVectors(from.target, to.target, k),
radius: from.radius + (to.radius - from.radius) * k,
theta: from.theta + (to.theta - from.theta) * k,
phi: from.phi + (to.phi - from.phi) * k,
};
}
/** The goal of a flight, turning the short way round in azimuth. */
export function flightGoal(from: OrbitView, to: Partial<OrbitView>): OrbitView {
let theta = to.theta ?? from.theta;
while (theta - from.theta > Math.PI) theta -= 2 * Math.PI;
while (theta - from.theta < -Math.PI) theta += 2 * Math.PI;
return { target: (to.target ?? from.target).clone(), radius: to.radius ?? from.radius, theta, phi: to.phi ?? from.phi };
}
/** Moves the target sideways and forwards by a drag of (dx, dy) pixels on a viewport of the given height. */
export function panView(view: OrbitView, dx: number, dy: number, viewportHeight: number, fovDegrees: number): void {
const perPixel = (2 * view.radius * Math.tan((fovDegrees * Math.PI) / 360)) / (viewportHeight || 1);
const right = new Vector3(Math.cos(view.theta), 0, -Math.sin(view.theta));
const forward = new Vector3(-Math.sin(view.theta), 0, -Math.cos(view.theta));
view.target.addScaledVector(right, -dx * perPixel);
view.target.addScaledVector(forward, (dy * perPixel) / Math.max(0.35, Math.cos(view.phi)));
}
/** Turns the view by a one-finger drag; returns the turn so it can carry on as inertia. */
export function orbitView(view: OrbitView, dx: number, dy: number, viewportHeight: number): { theta: number; phi: number } {
const h = viewportHeight || 1;
const turn = { theta: (-dx / h) * 3.2, phi: (-dy / h) * 2.4 };
view.theta += turn.theta;
view.phi = clamp(view.phi + turn.phi, MIN_PHI, MAX_PHI);
return turn;
}
/** One step of inertia: the turn continues and fades. Returns whether anything still moves. */
export function coast(view: OrbitView, velocity: { theta: number; phi: number }): boolean {
if (Math.abs(velocity.theta) <= 1e-4 && Math.abs(velocity.phi) <= 1e-4) return false;
view.theta += velocity.theta;
view.phi = clamp(view.phi + velocity.phi, MIN_PHI, MAX_PHI);
velocity.theta *= 0.9;
velocity.phi *= 0.9;
return true;
}
+24
View File
@@ -0,0 +1,24 @@
import assert from "node:assert/strict";
import { test } from "node:test";
import { buildStl } from "./stl.ts";
test("a triangle becomes 84 header bytes and one 50-byte record, scaled and lifted, z mirrored into y", () => {
const bytes = buildStl([{ positions: [0, 0, 0, 2, 0, 0, 0, 0, 1], lift: 3 }], 10);
assert.equal(bytes.length, 84 + 50);
const view = new DataView(bytes.buffer);
assert.equal(view.getUint32(80, true), 1);
const f = (o: number) => Math.round(view.getFloat32(o, true) * 1000) / 1000 + 0;
// vertices after the normal: (0,0,30) (0,-10,30) (20,0,30) – all at height (0 + 3) m × 10
const verts = [0, 1, 2].map((k) => [f(96 + k * 12), f(100 + k * 12), f(104 + k * 12)]);
assert.ok(verts.every((v) => v[2] === 30), JSON.stringify(verts));
assert.deepEqual(new Set(verts.map((v) => `${v[0]},${v[1]}`)), new Set(["0,0", "20,0", "0,-10"]));
assert.deepEqual(verts[0].slice(0, 2), [0, 0], "the corners keep their order");
assert.ok(f(92) < -0.99, "the winding is kept: this one faces down, as it did in the plan");
const n = [f(84), f(88), f(92)];
assert.ok(Math.abs(Math.hypot(...n) - 1) < 0.01 && Math.abs(n[2]) > 0.99, "a flat triangle has an up or down normal");
});
test("degenerate triangles are skipped and an empty house gives only the header", () => {
assert.equal(buildStl([{ positions: [1, 1, 1, 1, 1, 1, 2, 2, 2], lift: 0 }]).length, 84);
assert.equal(buildStl([]).length, 84);
});
+37
View File
@@ -0,0 +1,37 @@
// A binary STL of the house for 3D printing or a slicer: the triangles of every floor's walls (which carry furniture and outdoor
// areas as well) and floors, lifted to the floor's height and scaled; the glass, lights and blinds are left out.
/** One batch of triangles: positions (three numbers per vertex) and the height the batch stands at. */
export interface StlPart {
positions: ArrayLike<number>;
/** Added to every y, in metres. */
lift: number;
}
/**
* The bytes of a binary STL. Plan x/z become x/y of the print (z down the plan becomes y towards the back), the height stays the
* height; `scale` multiplies metres (10 = 1:100 when a slicer reads millimetres). Degenerate triangles are skipped.
*/
export function buildStl(parts: readonly StlPart[], scale = 10, name = "NextFloor"): Uint8Array {
const tris: number[][] = [];
for (const { positions, lift } of parts) {
for (let i = 0; i + 8 < positions.length; i += 9) {
const v = [0, 3, 6].map((o) => [positions[i + o] * scale, -positions[i + o + 2] * scale, (positions[i + o + 1] + lift) * scale]);
const [a, b, c] = v;
const n = [(b[1] - a[1]) * (c[2] - a[2]) - (b[2] - a[2]) * (c[1] - a[1]), (b[2] - a[2]) * (c[0] - a[0]) - (b[0] - a[0]) * (c[2] - a[2]), (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0])];
const length = Math.hypot(n[0], n[1], n[2]);
if (length < 1e-9) continue;
// (x, y, z) → (x, -z, y) is a turn, not a mirror, so the winding and the normal stay as they were
tris.push([n[0] / length, n[1] / length, n[2] / length, ...a, ...b, ...c]);
}
}
const out = new Uint8Array(84 + tris.length * 50);
const view = new DataView(out.buffer);
out.set(new TextEncoder().encode(`${name} STL`.slice(0, 79)), 0);
view.setUint32(80, tris.length, true);
tris.forEach((t, k) => {
const o = 84 + k * 50;
t.forEach((n, j) => view.setFloat32(o + j * 4, n, true));
});
return out;
}
+94
View File
@@ -0,0 +1,94 @@
// Shader patch that shows or hides wall parts on the GPU. Geometry carries a "fold" attribute (see
// build.ts); per floor, one bit mask says which wall buckets stand (the others are cut) and another
// which buckets are drawn as glass. Hidden vertices are moved outside the clip volume, so their
// triangles and lines are dropped before rasterising.
//
// Roles: "plain" (lines, window and door parts) only follows standing/cut; "solid" (walls) also leaves
// out glass buckets; "glass" draws only the wall parts of glass buckets, as tinted glass.
//
// The sloped view lowers every wall part (not furniture) to a plane that leans away from the camera: low on the near
// side, full height on the far side. Painted wall parts (fold value + 128) keep their own colour in every look.
import type { Material, Vector2, Vector4 } from "three";
export interface FoldMask {
value: number;
}
export interface FoldMasks {
standing: FoldMask;
glass: FoldMask;
/**
* The sloped view: x, z = the direction away from the camera, then the plan distance along it where the walls are lowest
* and where they are full height; and the lowest and the highest wall top (floor coordinates). Off while the first two are 0.
*/
slope?: { value: Vector4 };
slopeY?: { value: Vector2 };
/** How opaque glass walls are (0 … 1, default 0.2); one object shared by every floor, so one setting changes them all. */
glassAlpha?: { value: number };
}
export type FoldRole = "plain" | "solid" | "glass";
export function makeFoldable<T extends Material>(material: T, masks: FoldMasks, role: FoldRole = "plain"): T {
material.onBeforeCompile = (shader) => {
shader.uniforms.uStanding = masks.standing;
shader.uniforms.uGlass = masks.glass;
shader.uniforms.uSlope = masks.slope ?? { value: { x: 0, y: 0, z: 0, w: 0 } };
shader.uniforms.uSlopeY = masks.slopeY ?? { value: { x: 0, y: 0 } };
shader.uniforms.uGlassAlpha = masks.glassAlpha ?? { value: 0.2 };
shader.vertexShader = shader.vertexShader
.replace("#include <common>", "#include <common>\nattribute float fold;\nuniform int uStanding;\nuniform int uGlass;\nuniform vec4 uSlope;\nuniform vec2 uSlopeY;\nvarying float vNfPaint;")
.replace(
"#include <begin_vertex>",
`#include <begin_vertex>
vNfPaint = fold > 127.5 ? 1.0 : 0.0;
if (fold > -0.5 && (uSlope.x != 0.0 || uSlope.y != 0.0) && int(mod(fold, 128.0) + 0.5) / 16 != 4) {
float nfAlong = clamp((dot(transformed.xz, uSlope.xy) - uSlope.z) / max(uSlope.w - uSlope.z, 0.001), 0.0, 1.0);
transformed.y = min(transformed.y, mix(uSlopeY.x, uSlopeY.y, nfAlong));
}`,
)
.replace(
"#include <project_vertex>",
`#include <project_vertex>
{
bool nfShow = ${role === "glass" ? "false" : "true"};
if (fold > -0.5) {
int nfFold = int(mod(fold, 128.0) + 0.5);
int nfKind = nfFold / 16;
int nfBucket = nfFold - nfKind * 16;
bool nfStanding = ((uStanding >> nfBucket) & 1) == 1;
bool nfGlass = ((uGlass >> nfBucket) & 1) == 1;
// kinds: 0 upper part, 1 cut edge, 2 lower part, 3 cap at the cut height, 4 furniture above the cut
nfShow = nfKind == 0 || nfKind == 4 ? nfStanding : nfKind == 1 || nfKind == 3 ? !nfStanding : true;
bool nfWall = nfKind == 0 || nfKind == 2;
${role === "solid" ? "if (nfGlass && nfWall) nfShow = false;" : ""}
${role === "glass" ? "nfShow = nfShow && nfGlass && nfWall;" : ""}
}
if (!nfShow) gl_Position = vec4(2.0, 2.0, 2.0, 1.0);
}`,
);
shader.fragmentShader = shader.fragmentShader.replace("#include <common>", "#include <common>\nvarying float vNfPaint;\nuniform float uGlassAlpha;");
if (role !== "glass") {
// painted walls: their own colour, after the look has mapped everything else (see theme.ts)
shader.fragmentShader = shader.fragmentShader.replace(
"#include <color_fragment>",
`#include <color_fragment>
#ifdef USE_COLOR
if (vNfPaint > 0.5) diffuseColor.rgb = vColor.rgb;
#endif`,
);
}
if (role === "glass") {
// dark walls become a faint cyan-tinted glass, as opaque as the setting says
shader.fragmentShader = shader.fragmentShader.replace(
"#include <color_fragment>",
`#include <color_fragment>
diffuseColor.rgb = diffuseColor.rgb * 1.7 + vec3(0.015, 0.05, 0.075);
diffuseColor.a *= uGlassAlpha;`,
);
}
};
material.customProgramCacheKey = () => `nf-fold-${role}`;
return material;
}
+7
View File
@@ -0,0 +1,7 @@
// Procedural low-poly furniture in the neon look, split into modules in furniture/.
export { flipWinding } from "./furniture/builder.ts";
export { pushFurniture } from "./furniture/furniture.ts";
export { FRIDGE_DOOR, RADIATOR_Y, pushFridgeDoors } from "./furniture/kitchen.ts";
export { pushPackGlow, pushPackLamp, pushPackMoving } from "./furniture/packs.ts";
export { batteryBar, pictureRect, screenRect } from "./furniture/screens.ts";
+206
View File
@@ -0,0 +1,206 @@
// The drawing tool for furniture models. A model is built from boxes, lofts, cylinders and sweeps in local coordinates (x
// across, z in depth with the front at +z, y up), which the builder turns and moves into the plan.
import { Color } from "three";
import type { Vec2 } from "../../model.ts";
import { ALWAYS, DEG, pushLoft, pushLyingCyl, pushPrism, pushSkin, type GeoBuffer, type LineBuffer } from "../geo.ts";
import { counterClockwise } from "../build/outline.ts";
import { EDGE_FURN, type Material } from "./palette.ts";
/** Maps a local (x, z) to a plan point. */
export type Plan = (x: number, z: number) => Vec2;
/** A box as ranges along the three local axes. */
export interface Block {
x: [number, number];
y: [number, number];
z: [number, number];
}
/** Whether a plan transform mirrors (its determinant is negative). */
export function mirrors(plan: Plan): boolean {
const origin = plan(0, 0);
const ex = plan(1, 0);
const ez = plan(0, 1);
return (ex[0] - origin[0]) * (ez[1] - origin[1]) - (ex[1] - origin[1]) * (ez[0] - origin[0]) < 0;
}
/** Swaps the second and third vertex of every triangle from `from` on (positions, colours, folds, uvs, tiles). */
export function flipWinding(buf: GeoBuffer, from: number): void {
const swapped = (values: number[] | null, start: number, size: number) => {
if (!values) return;
for (let k = 0; k < size; k++) {
const [i, j] = [start + size + k, start + 2 * size + k];
[values[i], values[j]] = [values[j], values[i]];
}
};
for (let i = from; i < buf.p.length; i += 9) {
const tri = i / 9;
swapped(buf.p, i, 3);
swapped(buf.c, i, 3);
swapped(buf.f, tri * 3, 1);
swapped(buf.uv, tri * 6, 2);
swapped(buf.tile, tri * 6, 2);
}
}
export class Builder {
/** The transform mirrors: parts that do not wind themselves counter-clockwise come out inside out. */
readonly mirrored: boolean;
private readonly buf: GeoBuffer;
private readonly lines: LineBuffer;
readonly plan: Plan;
constructor(buf: GeoBuffer, lines: LineBuffer, plan: Plan) {
this.buf = buf;
this.lines = lines;
this.plan = plan;
this.mirrored = mirrors(plan);
}
/** The same buffers with the local coordinates turned by `deg` around (cx, cz): turned parts of pack items. */
turned(cx: number, cz: number, deg: number): Builder {
const [c, s] = [Math.cos(deg * DEG), Math.sin(deg * DEG)];
return new Builder(this.buf, this.lines, (x, z) => this.plan(cx + (x - cx) * c - (z - cz) * s, cz + (x - cx) * s + (z - cz) * c));
}
/** A line between two local points at the heights ya and yb. */
seg(xa: number, ya: number, za: number, xb: number, yb: number, zb: number, color: Color = EDGE_FURN): void {
this.edge(this.plan(xa, za), this.plan(xb, zb), ya, yb, color);
}
private edge(a: Vec2, b: Vec2, ya: number, yb: number, color: Color): void {
this.lines.seg([a[0], ya, a[1]], [b[0], yb, b[1]], color, ALWAYS);
}
/** An axis-aligned box. `edges` draws its outline. */
block({ x: [x0, x1], y: [y0, y1], z: [z0, z1] }: Block, material: Material, edges: Color | null = null): void {
if (x1 - x0 < 1e-4 || z1 - z0 < 1e-4 || y1 - y0 < 1e-4) return;
const footprint = [this.plan(x0, z0), this.plan(x0, z1), this.plan(x1, z1), this.plan(x1, z0)];
pushPrism(this.buf, counterClockwise(footprint), y0, y1, material.side, material.top, { aoFrom: 0, bottom: y0 > 0.05 });
if (edges) {
footprint.forEach((a, i) => {
this.edge(a, footprint[(i + 1) % 4], y1, y1, edges);
this.edge(a, a, y0, y1, edges);
});
}
}
/** An upright prism over any outline given in local coordinates (stair treads, winders, landings). */
prism(outline: readonly Vec2[], y0: number, y1: number, material: Material, edges: Color | null = null): void {
if (outline.length < 3 || y1 - y0 < 1e-4) return;
const footprint = outline.map(([x, z]) => this.plan(x, z));
pushPrism(this.buf, counterClockwise(footprint), y0, y1, material.side, material.top, { aoFrom: Math.min(0, y0), bottom: true });
if (edges) footprint.forEach((a, i) => this.edge(a, footprint[(i + 1) % footprint.length], y1, y1, edges));
}
/** A box whose top face is another rectangle (sloped sides): hoods, windscreens, tapered shades. Rectangles are [x0, x1, z0, z1]. */
loft(base: [number, number, number, number], top: [number, number, number, number], y0: number, y1: number, material: Material, edges: Color | null = null): void {
if (y1 - y0 < 1e-4) return;
const corners = (r: [number, number, number, number]): Vec2[] => [this.plan(r[0], r[2]), this.plan(r[0], r[3]), this.plan(r[1], r[3]), this.plan(r[1], r[2])];
const lo = corners(base);
const hi = corners(top);
if (lo !== counterClockwise(lo)) {
lo.reverse();
hi.reverse();
}
pushLoft(this.buf, lo, hi, y0, y1, material.side, material.top);
if (edges) {
for (let i = 0; i < 4; i++) {
this.edge(hi[i], hi[(i + 1) % 4], y1, y1, edges);
this.edge(lo[i], hi[i], y0, y1, edges);
}
}
}
/**
* A smooth body swept along z: at every station a rounded cross section from y0 to y1, `hw` wide to each side of the centre
* x (cars, boats, anything with a curved hull). `exp` shapes the section: 2 is an ellipse, higher is boxier. `edges` draws
* the ridge along the top.
*/
sweep(stations: { x: number; z: number; y0: number; y1: number; hw: number }[], material: Material, sides = 16, exp = 2.6, edges: Color | null = null): void {
if (stations.length < 2) return;
const rings = stations.map((st) => {
const [halfHeight, halfWidth] = [Math.max(0.004, (st.y1 - st.y0) / 2), Math.max(0.004, st.hw)];
const middle = (st.y0 + st.y1) / 2;
return Array.from({ length: sides }, (_, i) => {
const angle = (i / sides) * Math.PI * 2;
const [c, s] = [Math.cos(angle), Math.sin(angle)];
const [wx, wz] = this.plan(st.x + halfWidth * Math.sign(c) * Math.abs(c) ** (2 / exp), st.z);
return [wx, middle + halfHeight * Math.sign(s) * Math.abs(s) ** (2 / exp), wz];
});
});
pushSkin(this.buf, rings, material.side, material.top);
if (edges) {
const ridge = Math.round(sides / 4);
for (let s = 0; s + 1 < rings.length; s++) this.lines.seg(rings[s][ridge], rings[s + 1][ridge], edges, ALWAYS);
}
}
/** A box with bevelled top and bottom edges (cushions, mattresses, arm rests). */
pad(block: Block, material: Material, radius = 0.03, edges: Color | null = null): void {
const { x: [x0, x1], y: [y0, y1], z: [z0, z1] } = block;
const r = Math.min(radius, (x1 - x0) / 2 - 0.005, (z1 - z0) / 2 - 0.005, (y1 - y0) / 2);
if (r < 0.008) return this.block(block, material, edges);
const side = { side: material.side, top: material.side };
this.loft([x0 + r, x1 - r, z0 + r, z1 - r], [x0, x1, z0, z1], y0, y0 + r, side);
if (y1 - y0 - 2 * r > 0.005) this.block({ x: [x0, x1], y: [y0 + r, y1 - r], z: [z0, z1] }, side, edges);
this.loft([x0, x1, z0, z1], [x0 + r, x1 - r, z0 + r, z1 - r], y1 - r, y1, material);
}
/** A cylinder lying along x or z (wheels, rollers). `edges` draws both rims. */
lyingCylinder(axis: "x" | "z", cx: number, cz: number, y0: number, y1: number, length: number, diameter: number, material: Material, sides = 12, edges: Color | null = null): void {
const r = Math.min(diameter, y1 - y0) / 2;
if (r < 1e-4 || length < 1e-4) return;
const cy = (y0 + y1) / 2;
const [along, across] = axis === "x" ? [cx, cz] : [cz, cx];
const at = (a: number, c: number): Vec2 => (axis === "x" ? this.plan(a, c) : this.plan(c, a));
const first = this.buf.p.length;
pushLyingCyl(this.buf, at, along - length / 2, along + length / 2, across, cy, r, material.side, material.top, sides);
if (this.mirrored) flipWinding(this.buf, first);
if (!edges) return;
for (const a of [along - length / 2, along + length / 2]) {
for (let i = 0; i < sides; i++) {
const [t0, t1] = [(i / sides) * Math.PI * 2, ((i + 1) / sides) * Math.PI * 2];
this.edge(at(a, across + Math.sin(t0) * r), at(a, across + Math.sin(t1) * r), cy + Math.cos(t0) * r, cy + Math.cos(t1) * r, edges);
}
}
}
/** An upright cylinder with `sides` sides. */
cylinder(cx: number, cz: number, r: number, y0: number, y1: number, material: Material, sides = 10, edges: Color | null = null): void {
const footprint = Array.from({ length: sides }, (_, i) => this.plan(cx + Math.cos((i / sides) * Math.PI * 2) * r, cz + Math.sin((i / sides) * Math.PI * 2) * r));
pushPrism(this.buf, counterClockwise(footprint), y0, y1, material.side, material.top, { aoFrom: 0, bottom: y0 > 0.05 });
if (edges) footprint.forEach((a, i) => this.edge(a, footprint[(i + 1) % sides], y1, y1, edges));
}
/** A ring of line on a front face (z = front): dials, fans, door outlines. */
ring(cx: number, cy: number, r: number, z: number, segments = 20, color: Color = EDGE_FURN): void {
for (let i = 0; i < segments; i++) {
const [a0, a1] = [(i / segments) * Math.PI * 2, ((i + 1) / segments) * Math.PI * 2];
this.seg(cx + Math.cos(a0) * r, cy + Math.sin(a0) * r, z, cx + Math.cos(a1) * r, cy + Math.sin(a1) * r, z, color);
}
}
}
/** The soft contact shadow under an item: a dark core that fades out beyond its footprint. */
export function contactShadow(shadow: GeoBuffer, plan: Plan, w: number, d: number, strength: number): void {
const grow = Math.min(0.14, Math.max(0.06, Math.min(w, d) * 0.15));
const dark = new Color(1 - strength, 1 - strength, 1 - strength);
const clear = new Color(1, 1, 1);
const y = 0.003;
const ring = (g: number): Vec2[] => [plan(-w / 2 - g, -d / 2 - g), plan(w / 2 + g, -d / 2 - g), plan(w / 2 + g, d / 2 + g), plan(-w / 2 - g, d / 2 + g)];
const [inner, outer] = [ring(0), ring(grow)];
const at = (p: Vec2) => [p[0], y, p[1]];
const first = shadow.p.length;
shadow.tri(at(inner[0]), at(inner[1]), at(inner[2]), dark);
shadow.tri(at(inner[0]), at(inner[2]), at(inner[3]), dark);
for (let i = 0; i < 4; i++) {
const j = (i + 1) % 4;
shadow.tri(at(inner[i]), at(outer[i]), at(outer[j]), dark, clear, clear);
shadow.tri(at(inner[i]), at(outer[j]), at(inner[j]), dark, clear, dark);
}
if (mirrors(plan)) flipWinding(shadow, first);
}
@@ -0,0 +1,227 @@
import assert from "node:assert/strict";
import { test } from "node:test";
import { Color } from "three";
import { FURNITURE_SIZE, FURNITURE_TYPES, newFloor, type Furniture } from "../../model.ts";
import { setPacks } from "../../packs.ts";
import { GeoBuffer, LineBuffer } from "../geo.ts";
import { Builder, contactShadow, flipWinding, mirrors, type Plan } from "./builder.ts";
import { pushFurniture } from "./furniture.ts";
import { FRIDGE_DOOR, pushFridgeDoors, RADIATOR_Y } from "./kitchen.ts";
import { M } from "./palette.ts";
import { pushPackGlow, pushPackLamp } from "./packs.ts";
import { legs } from "./parts.ts";
import { screenRect } from "./screens.ts";
const identity: Plan = (x, z) => [x, z];
const mirrored: Plan = (x, z) => [-x, z];
const tools = (plan: Plan = identity) => {
const buf = new GeoBuffer();
const lines = new LineBuffer();
return { buf, lines, b: new Builder(buf, lines, plan) };
};
const ys = (buf: GeoBuffer) => buf.p.filter((_, i) => i % 3 === 1);
const piece = (type: string, extra: Partial<Furniture> = {}): Furniture => {
const size = (FURNITURE_SIZE as Record<string, number[]>)[type] ?? [1, 0.6, 0.8];
return { id: "f", type, x: 2, z: 1, rotation: 0, w: size[0], d: size[1], h: size[2], variant: null, entity: null, power: null, ...extra };
};
function draw(f: Furniture, base = 0) {
const [buf, lines, shadow] = [new GeoBuffer(), new LineBuffer(), new GeoBuffer()];
pushFurniture(buf, lines, shadow, f, base);
return { buf, lines, shadow };
}
test("a mirroring transform is told apart from a plain one", () => {
assert.equal(mirrors(identity), false);
assert.equal(mirrors(mirrored), true);
assert.equal(mirrors((x, z) => [z, x]), true);
assert.equal(mirrors((x, z) => [z, -x]), false);
});
test("a box adds a prism with a top, an outline when asked, and nothing when it is flat", () => {
const { buf, lines, b } = tools();
b.block({ x: [0, 1], y: [0, 1], z: [0, 1] }, M.wood);
assert.equal(buf.count, 10);
assert.equal(lines.p.length, 0);
const withEdges = tools();
withEdges.b.block({ x: [0, 1], y: [0, 1], z: [0, 1] }, M.wood, new Color(1, 1, 1));
assert.equal(withEdges.lines.p.length / 6, 8, "four top edges and four verticals");
const flat = tools();
flat.b.block({ x: [0, 1], y: [0.5, 0.5], z: [0, 1] }, M.wood);
assert.equal(flat.buf.count, 0);
});
test("a box above the floor also gets a bottom face", () => {
const low = tools();
low.b.block({ x: [0, 1], y: [0, 1], z: [0, 1] }, M.wood);
const lifted = tools();
lifted.b.block({ x: [0, 1], y: [0.5, 1.5], z: [0, 1] }, M.wood);
assert.equal(lifted.buf.count, low.buf.count + 2);
});
test("a turned builder rotates its parts around the given centre", () => {
const { buf, b } = tools();
b.turned(0, 0, 90).block({ x: [1, 2], y: [0, 1], z: [0, 0.5] }, M.wood);
const xs = buf.p.filter((_, i) => i % 3 === 0);
const zs = buf.p.filter((_, i) => i % 3 === 2);
assert.ok(Math.min(...zs) >= 0.99 && Math.max(...zs) <= 2.01, "x along became z");
assert.ok(Math.min(...xs) >= -0.51 && Math.max(...xs) <= 0.01);
});
test("a loft, a pad and a sweep add geometry; a pad too small to bevel is a plain box", () => {
const loft = tools();
loft.b.loft([0, 1, 0, 1], [0.2, 0.8, 0.2, 0.8], 0, 1, M.wood);
assert.ok(loft.buf.count > 8);
const pad = tools();
pad.b.pad({ x: [0, 1], y: [0, 0.3], z: [0, 1] }, M.fabric, 0.05);
const box = tools();
box.b.block({ x: [0, 1], y: [0, 0.3], z: [0, 1] }, M.fabric);
assert.ok(pad.buf.count > box.buf.count);
const tiny = tools();
tiny.b.pad({ x: [0, 1], y: [0, 0.3], z: [0, 1] }, M.fabric, 0.001);
assert.equal(tiny.buf.count, box.buf.count);
const sweep = tools();
sweep.b.sweep([{ x: 0, z: -1, y0: 0, y1: 1, hw: 0.4 }, { x: 0, z: 1, y0: 0, y1: 0.5, hw: 0.3 }], M.metal);
assert.ok(sweep.buf.count > 16);
const none = tools();
none.b.sweep([{ x: 0, z: 0, y0: 0, y1: 1, hw: 1 }], M.metal);
assert.equal(none.buf.count, 0);
});
test("cylinders: upright with n sides, lying along either axis, flipped when mirrored", () => {
const upright = tools();
upright.b.cylinder(0, 0, 0.5, 0, 1, M.metal, 8);
assert.equal(upright.buf.count, 8 - 2 + 8 * 2, "a top fan and two triangles per side");
for (const axis of ["x", "z"] as const) {
const lying = tools();
lying.b.lyingCylinder(axis, 0, 0, 0, 0.5, 1, 0.5, M.metal, 8);
assert.equal(lying.buf.count, 8 * 2 + 8 * 2);
const span = (i: number) => Math.max(...lying.buf.p.filter((_, k) => k % 3 === i)) - Math.min(...lying.buf.p.filter((_, k) => k % 3 === i));
assert.ok(Math.abs(span(axis === "x" ? 0 : 2) - 1) < 1e-9, "the length along its axis");
}
const normal = tools(identity);
const flipped = tools(mirrored);
normal.b.lyingCylinder("x", 0, 0, 0, 0.5, 1, 0.5, M.metal, 6);
flipped.b.lyingCylinder("x", 0, 0, 0, 0.5, 1, 0.5, M.metal, 6);
assert.equal(normal.buf.count, flipped.buf.count);
});
test("flipping the winding swaps the second and third vertex of each triangle", () => {
const buf = new GeoBuffer(true);
buf.tri([0, 0, 0], [1, 0, 0], [0, 0, 1], new Color(0.1, 0.2, 0.3), new Color(0.4, 0.5, 0.6), new Color(0.7, 0.8, 0.9), [0, 0, 1, 0, 0, 1], 5);
flipWinding(buf, 0);
assert.deepEqual(buf.p, [0, 0, 0, 0, 0, 1, 1, 0, 0]);
assert.ok(Math.abs(buf.c[3] - 0.7) < 1e-6 && Math.abs(buf.c[5] - 0.9) < 1e-6);
assert.deepEqual(buf.uv, [0, 0, 0, 1, 1, 0]);
});
test("a ring draws its segments, and a contact shadow fades out beyond the footprint", () => {
const { lines, b } = tools();
b.ring(0, 1, 0.3, 0, 16);
assert.equal(lines.p.length / 6, 16);
const shadow = new GeoBuffer();
contactShadow(shadow, identity, 1, 1, 0.5);
assert.equal(shadow.count, 2 + 8);
assert.ok(shadow.c.some((v) => v === 0.5) && shadow.c.some((v) => v === 1));
});
test("legs stand in the corners of the footprint", () => {
const { buf, b } = tools();
legs(b, 2, 1, 0.5, 0.1, 0.05);
assert.equal(buf.count / 10, 4);
assert.ok(Math.max(...buf.p.filter((_, i) => i % 3 === 0)) <= 1 + 1e-9);
});
test("every built-in type draws something, except the stairwell opening", () => {
for (const type of FURNITURE_TYPES) {
const { buf, lines } = draw(piece(type));
if (type === "stairwell") assert.equal(buf.count + lines.p.length, 0);
else assert.ok(buf.count + lines.p.length > 0, type);
}
});
test("free-standing furniture casts a contact shadow, wall-mounted and flat things do not", () => {
for (const type of ["sofa", "table", "fridge", "plant", "bed"]) assert.ok(draw(piece(type)).shadow.count > 0, type);
for (const type of ["rug", "kitchen_wall", "tv_wall", "radiator", "parking", "wallbox", "meter", "inverter"]) assert.equal(draw(piece(type)).shadow.count, 0, type);
});
test("an item lifted by its mount height moves up as a whole and loses its floor shadow", () => {
const onFloor = draw(piece("shelf"), 0);
const lifted = draw(piece("shelf"), 1.0);
assert.equal(lifted.shadow.count, 0);
assert.ok(Math.min(...ys(lifted.buf)) > Math.min(...ys(onFloor.buf)) + 0.5);
});
test("mirroring keeps the model but turns it around its own axis", () => {
const plain = draw(piece("sofa", { x: 0, z: 0 }));
const flipped = draw(piece("sofa", { x: 0, z: 0, mirror: true }));
assert.equal(plain.buf.count, flipped.buf.count);
const xs = (buf: GeoBuffer) => buf.p.filter((_, i) => i % 3 === 0);
assert.ok(Math.abs(Math.min(...xs(plain.buf)) + Math.max(...xs(flipped.buf))) < 1e-9);
});
test("a sofa gets one more seat for every 62 cm of width", () => {
const small = draw(piece("sofa", { w: 1.2 })).buf.count;
const large = draw(piece("sofa", { w: 2.8 })).buf.count;
assert.ok(large > small);
});
test("a smart fridge's doors swing open and turn red", () => {
const f = { x: 0, z: 0, rotation: 0, w: 0.9, d: 0.7, h: 1.8 };
const closed = new GeoBuffer();
const open = new GeoBuffer();
pushFridgeDoors(closed, f, 0, 0, 0);
pushFridgeDoors(open, f, 0, 1, 0);
assert.equal(closed.count, open.count);
assert.ok(closed.count > 20);
const redness = (buf: GeoBuffer) => buf.c.filter((_, i) => i % 3 === 0).reduce((a, c) => a + c, 0) - buf.c.filter((_, i) => i % 3 === 1).reduce((a, c) => a + c, 0);
assert.ok(redness(open) > redness(closed));
const zs = (buf: GeoBuffer) => Math.max(...buf.p.filter((_, i) => i % 3 === 2));
assert.ok(zs(open) > zs(closed), "an open door reaches out into the room");
assert.ok(FRIDGE_DOOR > 0 && RADIATOR_Y > 0);
});
test("screens: where a TV or an appliance's glowing front is, with and without a mount, mirrored or not", () => {
const floor = newFloor("f", "F", 0);
const board = screenRect(piece("tv_board", { w: 1.6, d: 0.4, h: 0.5 }), floor)!;
assert.ok(board.x1 > board.x0 && board.y1 > board.y0);
const mirroredBoard = screenRect(piece("tv_board", { w: 1.6, d: 0.4, h: 0.5, mirror: true }), floor)!;
assert.ok(Math.abs(mirroredBoard.x0 + board.x1) < 1e-9);
assert.equal(screenRect(piece("sofa"), floor), null);
assert.ok(screenRect(piece("washer"), floor)!.y1 > 0);
assert.ok(screenRect(piece("radiator"), floor)!.y0 > RADIATOR_Y);
const wall = screenRect(piece("tv_wall", { w: 1.2, d: 0.1, h: 0.7 }), floor)!;
assert.ok(wall.y0 > 0.9 && wall.y1 < 1.7);
});
test("pack items: parts scaled to the size, a chosen colour for painted parts, lamps and glow layers", () => {
const part = (extra: object) => ({ shape: "box", x: 0, z: 0, w: 1, d: 1, y: 0, h: 1, color: "body", ...extra });
setPacks([{ id: "t", name: "T", publisher: "t", items: [
{ id: "thing", name: { en: "Thing" }, size: [1, 1, 1], colors: [{ id: "red", name: { en: "r" }, hex: "#ff0000" }, { id: "blue", name: { en: "b" }, hex: "#0000ff" }], parts: [part({ paint: true }), part({ shape: "cyl", w: 0.4, d: 0.4 }), part({ shape: "sweep", stations: [[-0.5, 0, 1, 1], [0.5, 0, 0.5, 0.5]] })] },
{ id: "lamp", name: { en: "Lamp" }, size: [0.3, 0.3, 0.5], light: "pendant", parts: [part({ glow: true }), part({ color: "#445566" })] },
] } as never]);
const red = draw(piece("pack:t:thing", { variant: "red", w: 2, d: 1, h: 1 }));
const blue = draw(piece("pack:t:thing", { variant: "blue", w: 2, d: 1, h: 1 }));
assert.notDeepEqual(red.buf.c, blue.buf.c);
assert.ok(Math.max(...red.buf.p.filter((_, i) => i % 3 === 0)) - Math.min(...red.buf.p.filter((_, i) => i % 3 === 0)) >= 2 - 1e-9, "scaled to 2 m wide");
assert.equal(draw(piece("pack:t:thing"), 1).shadow.count, 0, "above the floor: no shadow");
assert.ok(draw(piece("pack:t:thing"), 0).shadow.count > 0);
const lit = new GeoBuffer();
const dark = new GeoBuffer();
const item = { id: "lamp", name: {}, size: [0.3, 0.3, 0.5], parts: [part({ glow: true }), part({ color: "#445566" })] } as never;
pushPackLamp(lit, item, piece("x", { w: 0.3, d: 0.3, h: 0.5 }), 0, 0xffee88);
pushPackGlow(dark, item, piece("x", { w: 0.3, d: 0.3, h: 0.5 }), 0, 0xff0000);
assert.ok(lit.count > dark.count, "a lamp draws all parts, a glow layer only the glowing ones");
assert.ok(lit.c.some((v) => Math.abs(v - 1) < 1e-6) || lit.c.length > 0);
const unknown = draw(piece("pack:gone:thing"));
assert.ok(unknown.buf.count > 0, "a missing pack item stays a plain box");
});
test("a TV set to no glow loses its bright blue rim, with the same shape", () => {
const brightest = (l: LineBuffer) => (l as unknown as { c: number[] }).c.reduce((a, v) => a + v, 0);
for (const type of ["tv_board", "tv_wall"]) {
const lit = draw(piece(type, { w: 1.6, d: 0.4, h: 0.5 }));
const dark = draw(piece(type, { w: 1.6, d: 0.4, h: 0.5, ambilight: 0 }));
assert.equal(dark.buf.count, lit.buf.count, type);
assert.ok(brightest(dark.lines) < brightest(lit.lines), type);
}
});
+266
View File
@@ -0,0 +1,266 @@
// Procedural low-poly furniture in the neon look. Every model is built from boxes and cylinders in local coordinates (x
// across, z in depth with the front at +z, y up) scaled to the item's size, then turned and moved into place. Solids go into
// the floor's wall buffer, main outlines into its line buffer and a soft contact shadow into the shadow layer, so furniture
// adds no draw calls.
import { builtinBase, type Furniture } from "../../model.ts";
import { packItem } from "../../packs.ts";
import { GeoBuffer, type LineBuffer } from "../geo.ts";
import { Builder, contactShadow } from "./builder.ts";
import { bunkBed, barStool, bed, bench, chair, officeChair, shapedSofa, sofa, stool } from "./seating.ts";
import { bathtub, dishwasher, fridge, fridgeSmart, island, kitchenTall, kitchenUnit, kitchenWall, laundry, radiator, shower, sink, stove, washbasin, wc, worktopOnly } from "./kitchen.ts";
import { coatRack, coffeeTable, desk, dresser, nightstand, plant, roundTable, rug, shelf, sideboard, stairs, table, tvBoard, tvWall } from "./living.ts";
import { gridCabinet, homeBattery, inverter, meterCabinet, wallbox } from "./technical.ts";
import { packModel, placement } from "./packs.ts";
import { shapedStairs } from "./stairs.ts";
import { cabinet } from "./parts.ts";
import { EDGE_FAINT, EDGE_FURN, M } from "./palette.ts";
/** What a model returns to say whether it casts a contact shadow on the floor. */
type Shadow = "yes" | "no";
/** Draws one built-in model. Returns "no" for items that hang on a wall or lie flat, "yes" for those standing on the floor. */
function drawBuiltIn(b: Builder, f: Furniture, w: number, d: number, h: number, base: number): Shadow {
switch (f.type) {
case "sofa":
if (f.variant === "l" || f.variant === "u") shapedSofa(b, w, d, h, f.variant);
else sofa(b, w, d, h, Math.max(1, Math.round((w - 0.4) / 0.62)));
return "yes";
case "armchair":
sofa(b, w, d, h, 1);
return "yes";
case "bed":
bed(b, w, d, h);
return "yes";
case "chair":
chair(b, w, d, h);
return "yes";
case "table":
table(b, w, d, h);
return "yes";
case "desk":
desk(b, w, d, h);
return "yes";
case "nightstand":
nightstand(b, w, d, h);
return "yes";
case "wardrobe":
cabinet(b, w, d, h, Math.max(2, Math.round(w / 0.5)), h * 0.5);
return "yes";
case "tall_cabinet":
cabinet(b, w, d, h, 1, h * 0.5);
return "yes";
case "shelf":
shelf(b, w, d, h);
return "yes";
case "kitchen":
kitchenUnit(b, w, d, h);
return "yes";
case "fridge":
fridge(b, w, d, h);
return "yes";
case "fridge_smart":
fridgeSmart(b, w, d, h);
return "yes";
case "stove":
stove(b, w, d, h);
return "yes";
case "sink":
sink(b, w, d, h);
return "yes";
case "bathtub":
bathtub(b, w, d, h);
return "yes";
case "shower":
shower(b, w, d, h);
return "yes";
case "wc":
wc(b, w, d, h);
return "yes";
case "washbasin":
washbasin(b, w, d, h);
return "yes";
case "tv_board":
tvBoard(b, w, d, h, f.ambilight === 0 ? EDGE_FURN : undefined);
return "yes";
case "plant":
plant(b, w, d, h);
return "yes";
case "rug":
rug(b, w, d);
return "no";
case "stairs":
if (f.stair) {
shapedStairs(b, f, w, d, h);
return f.stair.down ? "no" : "yes";
}
stairs(b, w, d, h);
return "yes";
case "stairwell":
return "no"; // only a hole in the floor (see stairHoles in build.ts), nothing to draw
case "sideboard":
sideboard(b, w, d, h);
return "yes";
case "dresser":
dresser(b, w, d, h);
return "yes";
case "coat_rack":
coatRack(b, w, d, h);
return "yes";
case "bench":
bench(b, w, d, h, false);
return "yes";
case "corner_bench":
bench(b, w, d, h, true);
return "yes";
case "bar_stool":
barStool(b, w, d, h);
return "yes";
case "office_chair":
officeChair(b, w, d, h);
return "yes";
case "stool":
stool(b, w, d, h);
return "yes";
case "kitchen_wall":
kitchenWall(b, w, d, h);
return "no"; // hangs on the wall
case "kitchen_tall":
kitchenTall(b, w, d, h);
return "yes";
case "island":
island(b, w, d, h);
return "yes";
case "worktop":
worktopOnly(b, w, d, h);
return "no";
case "dishwasher":
dishwasher(b, w, d, h);
return "yes";
case "washer":
laundry(b, w, d, h, false);
return "yes";
case "dryer":
laundry(b, w, d, h, true);
return "yes";
case "bunk_bed":
bunkBed(b, w, d, h);
return "yes";
case "table_round":
roundTable(b, w, d, h);
return "yes";
case "coffee_table":
coffeeTable(b, w, d, h);
return "yes";
case "tv_wall":
tvWall(b, w, d, h, f.ambilight === 0 ? EDGE_FURN : undefined);
return "no";
case "parking": {
// only the marking of the spot: a vehicle standing in it is added by the viewer
const y = 0.012;
const corners: [number, number][] = [[-w / 2, -d / 2], [w / 2, -d / 2], [w / 2, d / 2], [-w / 2, d / 2]];
corners.forEach(([x, z], i) => b.seg(x, y, z, corners[(i + 1) % 4][0], y, corners[(i + 1) % 4][1], EDGE_FAINT));
// an arrow head at the front: the direction the vehicle faces
b.seg(-w * 0.15, y, d / 2 - 0.45, 0, y, d / 2 - 0.2, EDGE_FURN);
b.seg(0, y, d / 2 - 0.2, w * 0.15, y, d / 2 - 0.45, EDGE_FURN);
return "no";
}
case "robot_vacuum":
// only the dock: the robot itself is drawn (and moved) by the viewer
b.block({ x: [-w * 0.45, w * 0.45], y: [0, h], z: [-d / 2, -d / 2 + d * 0.3] }, M.white, EDGE_FURN);
b.block({ x: [-w * 0.2, w * 0.2], y: [h * 0.5, h * 0.62], z: [-d / 2 + d * 0.3, -d / 2 + d * 0.31] }, M.accent);
return "no";
case "radiator":
radiator(b, w, d, h);
return "no"; // on the wall
case "inverter":
inverter(b, w, d, h, f.variant ?? null);
return "no";
case "grid_point":
gridCabinet(b, w, d, h);
return "yes";
case "wallbox":
wallbox(b, w, d, h);
return "no";
case "meter":
meterCabinet(b, w, d, h);
return "no";
case "home_battery":
homeBattery(b, w, d, h, f.variant ?? null);
return f.variant === "wall" ? "no" : "yes";
default: {
const item = packItem(f.type);
if (!item) {
b.block({ x: [-w / 2, w / 2], y: [0, h], z: [-d / 2, d / 2] }, M.body, EDGE_FURN);
return "yes";
}
// a pet is drawn by the view's own layer, where it walks around
if (item.pet) return "no";
packModel(b, item, w, d, h, base, null, null, f.variant ?? null);
// items on furniture, walls or ceilings cast no shadow on the floor
return base > 0.05 ? "no" : "yes";
}
}
}
function buildFurniture(buf: GeoBuffer, lines: LineBuffer, shadow: GeoBuffer, f: Furniture, base: number): void {
const plan = placement(f);
const b = new Builder(buf, lines, plan);
const [w, d, h] = [Math.max(0.05, f.w), Math.max(0.05, f.d), Math.max(0.005, f.h)];
if (drawBuiltIn(b, f, w, d, h, base) === "yes") contactShadow(shadow, plan, w, d, f.type === "plant" ? 0.35 : 0.5);
}
/**
* Draws a piece of furniture. A mirrored item needs no rewinding here: boxes, lofts and upright cylinders wind themselves
* counter-clockwise, and lying cylinders and the contact shadow rewind themselves when the transform mirrors.
*/
/** Turns a vector about a unit axis by `angle` radians (Rodrigues). */
function turn(v: [number, number, number], k: [number, number, number], angle: number): [number, number, number] {
const [c, s] = [Math.cos(angle), Math.sin(angle)];
const dot = k[0] * v[0] + k[1] * v[1] + k[2] * v[2];
const cross: [number, number, number] = [k[1] * v[2] - k[2] * v[1], k[2] * v[0] - k[0] * v[2], k[0] * v[1] - k[1] * v[0]];
return [v[0] * c + cross[0] * s + k[0] * dot * (1 - c), v[1] * c + cross[1] * s + k[1] * dot * (1 - c), v[2] * c + cross[2] * s + k[2] * dot * (1 - c)];
}
/**
* Tilts what was just built (the vertices and lines from the given starts on) about the item's own axes, round the middle of its
* underside: `tilt_x` about its width axis, `tilt_z` about its depth axis, both after its turn about the vertical axis.
*/
export function tiltBuilt(buf: GeoBuffer, lines: LineBuffer, from: { vertex: number; line: number }, f: Pick<Furniture, "x" | "z" | "rotation" | "tilt_x" | "tilt_z">, y: number): void {
const [px, pz] = [f.tilt_x ?? 0, f.tilt_z ?? 0];
if (!px && !pz) return;
const yaw = (f.rotation * Math.PI) / 180;
const widthAxis: [number, number, number] = [Math.cos(yaw), 0, Math.sin(yaw)];
const depthAxis: [number, number, number] = [-Math.sin(yaw), 0, Math.cos(yaw)];
const move = (p: number[], start: number) => {
for (let i = start; i + 2 < p.length; i += 3) {
let v: [number, number, number] = [p[i] - f.x, p[i + 1] - y, p[i + 2] - f.z];
if (px) v = turn(v, widthAxis, (px * Math.PI) / 180);
if (pz) v = turn(v, depthAxis, (pz * Math.PI) / 180);
p[i] = f.x + v[0];
p[i + 1] = y + v[1];
p[i + 2] = f.z + v[2];
}
};
move(buf.p, from.vertex);
move(lines.p, from.line);
}
export function pushFurniture(buf: GeoBuffer, lines: LineBuffer, shadow: GeoBuffer, f: Furniture, base = 0): void {
const start = { vertex: buf.p.length, line: lines.p.length };
pushUpright(buf, lines, shadow, f, base);
tiltBuilt(buf, lines, start, f, base);
}
function pushUpright(buf: GeoBuffer, lines: LineBuffer, shadow: GeoBuffer, f: Furniture, base = 0): void {
// pack items place their parts at `base` themselves; built-in models are drawn on the floor and lifted as a whole (a dryer on the
// washer, a shelf on the wall), without a shadow on the floor. The mount height is absolute: a wall cabinet drawn at 1.45 m
// moves by the difference, up or down.
const lift = packItem(f.type) ? 0 : base - builtinBase(f);
if (packItem(f.type) || Math.abs(lift) < 0.001) return buildFurniture(buf, lines, shadow, f, base);
const [firstVertex, firstLine] = [buf.p.length, lines.p.length];
buildFurniture(buf, lines, base < 0.05 ? shadow : new GeoBuffer(), f, 0);
for (let i = firstVertex + 1; i < buf.p.length; i += 3) buf.p[i] += lift;
for (let i = firstLine + 1; i < lines.p.length; i += 3) lines.p[i] += lift;
}
+237
View File
@@ -0,0 +1,237 @@
// Kitchen units, appliances, bathroom fittings and radiators.
import { Color } from "three";
import type { Furniture } from "../../model.ts";
import { DEG, type GeoBuffer } from "../geo.ts";
import { flipWinding, type Builder } from "./builder.ts";
import { cabinet, fronts } from "./parts.ts";
import { C, EDGE_FAINT, EDGE_FURN, EDGE_GLOW, M, material } from "./palette.ts";
const worktop = (b: Builder, w: number, d: number, h: number) => b.block({ x: [-w / 2, w / 2], y: [h - 0.04, h], z: [-d / 2, d / 2] }, M.worktop, EDGE_FURN);
/** A base unit with a worktop. */
export function kitchenUnit(b: Builder, w: number, d: number, h: number): void {
cabinet(b, w, d - 0.02, h - 0.04, Math.max(1, Math.round(w / 0.6)), h - 0.2);
worktop(b, w, d, h);
}
/** Just the worktop, 4 cm thick at its height, with nothing below it. */
export function worktopOnly(b: Builder, w: number, d: number, h: number): void {
b.block({ x: [-w / 2, w / 2], y: [Math.max(0, h - 0.04), h], z: [-d / 2, d / 2] }, M.worktop, EDGE_FURN);
}
export function fridge(b: Builder, w: number, d: number, h: number): void {
b.block({ x: [-w / 2, w / 2], y: [0, h], z: [-d / 2, d / 2] }, M.white, EDGE_FURN);
const split = h * 0.62;
b.seg(-w / 2, split, d / 2, w / 2, split, d / 2, EDGE_FAINT);
const x = w / 2 - 0.06;
b.seg(x, split + 0.08, d / 2 + 0.015, x, split + 0.4, d / 2 + 0.015, EDGE_GLOW);
b.seg(x, split - 0.4, d / 2 + 0.015, x, split - 0.08, d / 2 + 0.015, EDGE_GLOW);
}
/** The thickness of a smart fridge's doors. */
export const FRIDGE_DOOR = 0.06;
/** A smart side-by-side fridge without its doors (they move, see pushFridgeDoors): the body and, behind the doors, shelves. */
export function fridgeSmart(b: Builder, w: number, d: number, h: number): void {
const front = d / 2 - FRIDGE_DOOR;
b.block({ x: [-w / 2, w / 2], y: [0.02, h], z: [-d / 2, front] }, M.body, EDGE_FURN);
b.block({ x: [-w / 2 + 0.05, w / 2 - 0.05], y: [0, 0.02], z: [-d / 2 + 0.05, front - 0.05] }, M.dark);
// shelves of both compartments, seen when a door stands open
for (const y of [0.35, 0.7, 1.05, 1.4]) {
if (y > h - 0.15) continue;
b.seg(-w / 2 + 0.03, y, front + 0.001, -0.03, y, front + 0.001, EDGE_FAINT);
b.seg(0.03, y, front + 0.001, w / 2 - 0.03, y, front + 0.001, EDGE_FAINT);
}
}
type DoorGeometry = Pick<Furniture, "x" | "z" | "rotation" | "w" | "d" | "h" | "mirror">;
const OPENING_ANGLE = 1.83; // about 105°
function fridgeDoorsUnflipped(buf: GeoBuffer, f: DoorGeometry, base: number, left: number, right: number): void {
const [c, s] = [Math.cos(f.rotation * DEG), Math.sin(f.rotation * DEG)];
const mx = f.mirror ? -1 : 1;
const plan = (lx: number, lz: number): [number, number] => [f.x + mx * lx * c - lz * s, f.z + mx * lx * s + lz * c];
const [y0, y1] = [base + 0.05, base + f.h - 0.02];
const red = new Color(0.75, 0.1, 0.14);
const dark = new Color(C.dark);
const accent = new Color(C.accent);
const doorWidth = f.w / 2 - 0.006;
// a door: u runs from the hinge along the door (positive to the right), v through its thickness (0 = front face)
const door = (hingeX: number, sign: 1 | -1, angle: number) => {
const open = angle / OPENING_ANGLE;
const frontColor = new Color(0x1f2d4c).lerp(red, open);
const sideColor = new Color(C.body).lerp(red, open * 0.8);
const [ca, sa] = [Math.cos(angle), Math.sin(angle)];
const at = (u: number, v: number): [number, number] => plan(hingeX + sign * (u * ca - v * sa), f.d / 2 + u * sa + v * ca);
const quad = (p: [number, number][], ya: number, yb: number, color: Color) => {
const [p0, p1, p2, p3] = p;
buf.tri([p0[0], ya, p0[1]], [p1[0], ya, p1[1]], [p2[0], yb, p2[1]], color);
buf.tri([p0[0], ya, p0[1]], [p2[0], yb, p2[1]], [p3[0], yb, p3[1]], color);
};
const box = (u0: number, u1: number, ya: number, yb: number, v0: number, v1: number, color: Color, face = color) => {
const q = [at(u0, v1), at(u1, v1), at(u1, v0), at(u0, v0)];
// the front (v1 side), the back, the sides, the top and the bottom
quad([q[0], q[1], q[1], q[0]], ya, yb, face);
quad([q[3], q[2], q[2], q[3]], ya, yb, color);
quad([q[0], q[3], q[3], q[0]], ya, yb, color);
quad([q[1], q[2], q[2], q[1]], ya, yb, color);
quad([q[0], q[1], q[2], q[3]], yb, yb, color);
quad([q[3], q[2], q[1], q[0]], ya, ya, color);
};
box(0, doorWidth, y0, y1, -FRIDGE_DOOR, 0, sideColor, frontColor);
// the handle at the free edge
box(doorWidth - 0.05, doorWidth - 0.03, base + f.h * 0.45, base + f.h * 0.75, 0.005, 0.025, accent);
return box;
};
const leftDoor = door(-f.w / 2, 1, left * OPENING_ANGLE);
// the water dispenser: a dark recess in the left door
leftDoor(0.12, 0.3, base + f.h * 0.5, base + f.h * 0.68, 0.001, 0.005, dark);
const rightDoor = door(f.w / 2, -1, right * OPENING_ANGLE);
// the screen: a dark panel on the right door (a picture rule puts its picture over it)
rightDoor(0.06, doorWidth - 0.06, base + f.h * 0.52, base + f.h * 0.86, 0.001, 0.005, dark);
}
/**
* The two doors of a smart fridge, each swung open by a fraction (0 closed to 1 wide open) around its outer hinge: the left
* one carries the water dispenser, the right one the screen. An open door turns red, as it should not stay open for long.
*/
export function pushFridgeDoors(buf: GeoBuffer, f: DoorGeometry, base: number, left: number, right: number): void {
const first = buf.p.length;
fridgeDoorsUnflipped(buf, f, base, left, right);
if (f.mirror) flipWinding(buf, first);
}
export function stove(b: Builder, w: number, d: number, h: number): void {
cabinet(b, w, d - 0.02, h - 0.04, 1, h - 0.24, true);
b.block({ x: [-w / 2, w / 2], y: [h - 0.04, h], z: [-d / 2, d / 2] }, M.dark, EDGE_FURN);
const plates: [number, number, number][] = [[-0.14, -0.13, 0.09], [0.14, -0.13, 0.07], [-0.14, 0.13, 0.07], [0.14, 0.13, 0.09]];
for (const [x, z, r] of plates) b.cylinder((x * w) / 0.6, (z * d) / 0.62, r, h, h + 0.004, material(C.dark, 0x16263f), 12, EDGE_GLOW);
}
export function sink(b: Builder, w: number, d: number, h: number): void {
cabinet(b, w, d - 0.02, h - 0.04, Math.max(1, Math.round(w / 0.45)), h - 0.2);
const basin = Math.min(0.5, w - 0.2);
const top = (x0: number, x1: number, z0: number, z1: number, edges = false) => b.block({ x: [x0, x1], y: [h - 0.04, h], z: [z0, z1] }, M.worktop, edges ? EDGE_FURN : null);
top(-w / 2, -basin / 2, -d / 2, d / 2, true);
top(basin / 2, w / 2, -d / 2, d / 2, true);
top(-basin / 2, basin / 2, -d / 2, -d / 2 + 0.1);
top(-basin / 2, basin / 2, d / 2 - 0.08, d / 2);
b.block({ x: [-basin / 2, basin / 2], y: [h - 0.2, h - 0.17], z: [-d / 2 + 0.1, d / 2 - 0.08] }, M.metal, EDGE_GLOW);
b.cylinder(0, -d / 2 + 0.05, 0.02, h, h + 0.28, M.metal, 8);
b.block({ x: [-0.015, 0.015], y: [h + 0.24, h + 0.28], z: [-d / 2 + 0.05, -d / 2 + 0.22] }, M.metal);
}
export function kitchenWall(b: Builder, w: number, d: number, h: number): void {
// hangs above the worktop
const y0 = 1.45;
b.block({ x: [-w / 2, w / 2], y: [y0, y0 + h], z: [-d / 2, d / 2 - 0.02] }, M.body, EDGE_FURN);
fronts(b, -w / 2, w / 2, y0, y0 + h, d / 2 - 0.02, Math.max(1, Math.round(w / 0.5)), y0 + 0.08);
}
export function kitchenTall(b: Builder, w: number, d: number, h: number): void {
b.block({ x: [-w / 2, w / 2], y: [0.02, h], z: [-d / 2, d / 2 - 0.02] }, M.body, EDGE_FURN);
b.block({ x: [-w / 2 + 0.02, w / 2 - 0.02], y: [0, 0.08], z: [-d / 2 + 0.02, d / 2 - 0.06] }, M.dark);
const z = d / 2 - 0.02;
// an oven with a dark glass door and a glowing handle, fronts above and below
b.block({ x: [-w / 2 + 0.03, w / 2 - 0.03], y: [0.85, 1.45], z: [z, z + 0.01] }, M.dark, EDGE_GLOW);
b.seg(-w / 2 + 0.08, 1.4, z + 0.02, w / 2 - 0.08, 1.4, z + 0.02, EDGE_GLOW);
for (const y of [0.85, 1.45]) b.seg(-w / 2, y, z, w / 2, y, z, EDGE_FAINT);
b.seg(w / 2 - 0.06, 0.5, z + 0.012, w / 2 - 0.06, 0.7, z + 0.012, EDGE_GLOW);
b.seg(w / 2 - 0.06, 1.6, z + 0.012, w / 2 - 0.06, 1.8, z + 0.012, EDGE_GLOW);
}
export function island(b: Builder, w: number, d: number, h: number): void {
const inner = d - 0.3;
b.block({ x: [-w / 2 + 0.05, w / 2 - 0.05], y: [0.08, h - 0.04], z: [-d / 2 + 0.02, -d / 2 + inner] }, M.body, EDGE_FURN);
b.block({ x: [-w / 2 + 0.07, w / 2 - 0.07], y: [0, 0.08], z: [-d / 2 + 0.04, -d / 2 + inner - 0.04] }, M.dark);
fronts(b, -w / 2 + 0.05, w / 2 - 0.05, 0.08, h - 0.04, -d / 2 + inner, Math.max(2, Math.round(w / 0.6)), h - 0.2);
// the worktop overhangs at the front, for bar stools
worktop(b, w, d, h);
}
export function dishwasher(b: Builder, w: number, d: number, h: number): void {
b.block({ x: [-w / 2, w / 2], y: [0.02, h - 0.04], z: [-d / 2, d / 2 - 0.02] }, M.body, EDGE_FURN);
b.block({ x: [-w / 2 + 0.02, w / 2 - 0.02], y: [0, 0.08], z: [-d / 2 + 0.02, d / 2 - 0.06] }, M.dark);
b.seg(-w / 2 + 0.08, h - 0.12, d / 2 - 0.008, w / 2 - 0.08, h - 0.12, d / 2 - 0.008, EDGE_GLOW);
worktop(b, w, d, h);
}
/** A washing machine, or a dryer (`dryer`): a control panel line and a round door drawn on the front. */
export function laundry(b: Builder, w: number, d: number, h: number, dryer: boolean): void {
b.block({ x: [-w / 2, w / 2], y: [0, h], z: [-d / 2, d / 2 - 0.02] }, M.white, EDGE_FURN);
const z = d / 2 - 0.012;
b.seg(-w / 2, h - 0.14, z, w / 2, h - 0.14, z, EDGE_FAINT);
b.seg(w / 2 - 0.16, h - 0.07, z, w / 2 - 0.08, h - 0.07, z, EDGE_GLOW);
const cy = (h - 0.14) / 2 + 0.04;
const r = Math.min(w * 0.36, (h - 0.2) * 0.42);
// the door ring (and an inner ring on a washer), drawn segment by segment
const sides = 20;
for (let i = 0; i < sides; i++) {
const [a0, a1] = [(i / sides) * Math.PI * 2, ((i + 1) / sides) * Math.PI * 2];
const arc = (scale: number, color: typeof EDGE_GLOW) => b.seg(Math.cos(a0) * r * scale, cy + Math.sin(a0) * r * scale, z, Math.cos(a1) * r * scale, cy + Math.sin(a1) * r * scale, z, color);
arc(1, EDGE_GLOW);
if (!dryer) arc(0.72, EDGE_FAINT);
}
}
export function bathtub(b: Builder, w: number, d: number, h: number): void {
const rim = 0.07;
b.block({ x: [-w / 2, w / 2], y: [0, h - 0.02], z: [-d / 2, d / 2] }, M.white, EDGE_FURN);
const lip = (x0: number, x1: number, z0: number, z1: number) => b.block({ x: [x0, x1], y: [h - 0.02, h], z: [z0, z1] }, M.worktop);
lip(-w / 2, w / 2, -d / 2, -d / 2 + rim);
lip(-w / 2, w / 2, d / 2 - rim, d / 2);
lip(-w / 2, -w / 2 + rim, -d / 2 + rim, d / 2 - rim);
lip(w / 2 - rim, w / 2, -d / 2 + rim, d / 2 - rim);
b.block({ x: [-w / 2 + rim, w / 2 - rim], y: [h - 0.03, h - 0.02], z: [-d / 2 + rim, d / 2 - rim] }, M.glass, EDGE_GLOW);
b.cylinder(-w / 2 + 0.04, 0, 0.02, h, h + 0.12, M.metal, 8);
}
export function shower(b: Builder, w: number, d: number, h: number): void {
b.block({ x: [-w / 2, w / 2], y: [0, 0.05], z: [-d / 2, d / 2] }, M.worktop, EDGE_FURN);
b.cylinder(0, 0, 0.04, 0.05, 0.052, M.metal, 8);
// glass walls at the front and one side: only edges, the glass itself stays clear
for (const [xa, za, xb, zb] of [[-w / 2, d / 2, w / 2, d / 2], [w / 2, -d / 2, w / 2, d / 2]]) {
b.seg(xa, 0.05, za, xb, 0.05, zb, EDGE_GLOW);
b.seg(xa, h, za, xb, h, zb, EDGE_GLOW);
b.seg(xb, 0.05, zb, xb, h, zb, EDGE_GLOW);
}
b.cylinder(-w / 2 + 0.06, -d / 2 + 0.06, 0.015, 0.05, h - 0.05, M.metal, 6);
b.cylinder(-w / 2 + 0.2, -d / 2 + 0.2, 0.1, h - 0.08, h - 0.06, M.metal, 12, EDGE_GLOW);
}
export function wc(b: Builder, w: number, d: number, h: number): void {
const tank = Math.min(0.18, d * 0.3);
b.block({ x: [-w / 2, w / 2], y: [0.45, h], z: [-d / 2, -d / 2 + tank] }, M.white, EDGE_FURN);
b.block({ x: [-w * 0.3, w * 0.3], y: [0, 0.36], z: [-d / 2 + tank - 0.02, d / 2 - 0.12] }, M.white);
b.cylinder(0, d / 2 - 0.26, Math.min(w / 2, 0.19), 0.36, 0.41, M.white, 12, EDGE_FURN);
b.block({ x: [-w / 2 + 0.02, w / 2 - 0.02], y: [0.41, 0.43], z: [-d / 2 + tank, -d / 2 + tank + 0.05] }, M.worktop);
}
export function washbasin(b: Builder, w: number, d: number, h: number): void {
cabinet(b, w, d - 0.02, h - 0.12, w > 0.8 ? 2 : 1, h - 0.3);
b.block({ x: [-w / 2, w / 2], y: [h - 0.12, h], z: [-d / 2, d / 2] }, M.white, EDGE_FURN);
b.block({ x: [-w / 2 + 0.07, w / 2 - 0.07], y: [h - 0.005, h], z: [-d / 2 + 0.12, d / 2 - 0.06] }, M.glass, EDGE_GLOW);
b.cylinder(0, -d / 2 + 0.06, 0.018, h, h + 0.2, M.metal, 8);
// the mirror above
b.block({ x: [-w / 2 + 0.04, w / 2 - 0.04], y: [h + 0.35, h + 1], z: [-d / 2, -d / 2 + 0.02] }, M.glass, EDGE_GLOW);
}
/** The height of the underside of a radiator. */
export const RADIATOR_Y = 0.12;
/** A radiator on the wall (back at -z): a panel with vertical fins, standing on short brackets. */
export function radiator(b: Builder, w: number, d: number, h: number): void {
const y0 = RADIATOR_Y;
b.block({ x: [-w / 2 + 0.05, -w / 2 + 0.08], y: [0, y0], z: [-d / 2, -d / 2 + 0.03] }, M.metal);
b.block({ x: [w / 2 - 0.08, w / 2 - 0.05], y: [0, y0], z: [-d / 2, -d / 2 + 0.03] }, M.metal);
b.block({ x: [-w / 2, w / 2], y: [y0, y0 + h], z: [-d / 2 + 0.02, d / 2] }, M.white, EDGE_FURN);
const fins = Math.max(3, Math.round(w / 0.1));
for (let i = 1; i < fins; i++) {
const x = -w / 2 + (w / fins) * i;
b.seg(x, y0 + 0.03, d / 2 + 0.002, x, y0 + h - 0.03, d / 2 + 0.002, EDGE_FAINT);
}
}
+158
View File
@@ -0,0 +1,158 @@
// Tables, storage, decoration and stairs.
import type { Builder } from "./builder.ts";
import { cabinet, fronts, legs } from "./parts.ts";
import { C, EDGE_FAINT, EDGE_FURN, EDGE_GLOW, M, material } from "./palette.ts";
export function table(b: Builder, w: number, d: number, h: number): void {
legs(b, w, d, h - 0.04, 0.06, 0.05, C.wood, true);
b.block({ x: [-w / 2, w / 2], y: [h - 0.04, h], z: [-d / 2, d / 2] }, M.wood, EDGE_GLOW);
b.block({ x: [-w / 2 + 0.08, w / 2 - 0.08], y: [h - 0.1, h - 0.04], z: [-d / 2 + 0.08, d / 2 - 0.08] }, material(C.body));
}
export function roundTable(b: Builder, w: number, d: number, h: number): void {
const r = Math.min(w, d) / 2;
b.cylinder(0, 0, r * 0.4, 0, 0.03, M.metal, 12);
b.cylinder(0, 0, 0.05, 0.03, h - 0.04, material(C.wood), 8);
b.cylinder(0, 0, r, h - 0.04, h, M.wood, 20, EDGE_FURN);
}
export function coffeeTable(b: Builder, w: number, d: number, h: number): void {
legs(b, w, d, h - 0.03, 0.04, 0.03, C.wood);
b.block({ x: [-w / 2, w / 2], y: [h - 0.03, h], z: [-d / 2, d / 2] }, M.wood, EDGE_FURN);
b.block({ x: [-w / 2 + 0.05, w / 2 - 0.05], y: [0.1, 0.13], z: [-d / 2 + 0.05, d / 2 - 0.05] }, M.body, EDGE_FAINT);
}
export function desk(b: Builder, w: number, d: number, h: number): void {
const [x0, x1] = [-w / 2, w / 2];
b.block({ x: [x0, x1], y: [h - 0.035, h], z: [-d / 2, d / 2] }, M.wood, EDGE_FURN);
b.block({ x: [x0, x0 + 0.03], y: [0, h - 0.035], z: [-d / 2 + 0.03, d / 2 - 0.03] }, M.metal);
const drawers = Math.min(0.42, w * 0.32);
b.block({ x: [x1 - drawers, x1], y: [0, h - 0.035], z: [-d / 2 + 0.03, d / 2 - 0.02] }, M.body, EDGE_FURN);
const front = d / 2 - 0.02;
for (const y of [h * 0.35, h * 0.66]) b.seg(x1 - drawers, y, front, x1, y, front, EDGE_FAINT);
for (const y of [h * 0.2, h * 0.5, h * 0.82]) b.seg(x1 - drawers / 2 - 0.07, y, front + 0.012, x1 - drawers / 2 + 0.07, y, front + 0.012, EDGE_GLOW);
// the screen on its foot
b.block({ x: [-0.3, 0.3], y: [h + 0.08, h + 0.42], z: [-d / 2 + 0.08, -d / 2 + 0.11] }, M.dark, EDGE_GLOW);
b.block({ x: [-0.03, 0.03], y: [h, h + 0.1], z: [-d / 2 + 0.09, -d / 2 + 0.13] }, M.metal);
}
export function nightstand(b: Builder, w: number, d: number, h: number): void {
cabinet(b, w, d, h, 1, h * 0.72, true);
b.seg(-w / 2, h * 0.5, d / 2 - 0.02, w / 2, h * 0.5, d / 2 - 0.02, EDGE_FAINT);
}
export function shelf(b: Builder, w: number, d: number, h: number): void {
const t = 0.025;
b.block({ x: [-w / 2, -w / 2 + t], y: [0, h], z: [-d / 2, d / 2] }, M.wood, EDGE_FURN);
b.block({ x: [w / 2 - t, w / 2], y: [0, h], z: [-d / 2, d / 2] }, M.wood, EDGE_FURN);
b.block({ x: [-w / 2 + t, w / 2 - t], y: [0, h], z: [-d / 2, -d / 2 + 0.015] }, material(C.body));
const boards = Math.max(2, Math.round(h / 0.38));
for (let i = 0; i <= boards; i++) {
const y = Math.min(h - t, (h / boards) * i);
b.block({ x: [-w / 2 + t, w / 2 - t], y: [y, y + t], z: [-d / 2 + 0.015, d / 2] }, M.wood, EDGE_FAINT);
if (i === boards) continue; // no books on the top board
// a few books on every other shelf, in varying widths and heights
let x = -w / 2 + t + 0.04;
let k = i * 3;
while (x < w / 2 - t - 0.12) {
const bookWidth = 0.03 + ((k * 7) % 5) * 0.008;
const bookHeight = h / boards - t - 0.08 - ((k * 5) % 4) * 0.025;
if ((k * 11) % 7 !== 0) b.block({ x: [x, x + bookWidth], y: [y + t, y + t + bookHeight], z: [-d / 2 + 0.04, d / 2 - 0.05] }, k % 3 ? M.fabric : material(C.cushion, C.fabricTop));
x += bookWidth + 0.006;
k++;
}
}
}
export function sideboard(b: Builder, w: number, d: number, h: number): void {
legs(b, w, d, 0.12, 0.03, 0.04, C.metal);
b.block({ x: [-w / 2, w / 2], y: [0.12, h], z: [-d / 2, d / 2 - 0.02] }, M.wood, EDGE_FURN);
fronts(b, -w / 2, w / 2, 0.12, h, d / 2 - 0.02, Math.max(2, Math.round(w / 0.45)), h - 0.1, true);
}
export function dresser(b: Builder, w: number, d: number, h: number): void {
b.block({ x: [-w / 2, w / 2], y: [0.06, h], z: [-d / 2, d / 2 - 0.02] }, M.wood, EDGE_FURN);
b.block({ x: [-w / 2 + 0.02, w / 2 - 0.02], y: [0, 0.06], z: [-d / 2 + 0.02, d / 2 - 0.06] }, M.dark);
const drawers = Math.max(3, Math.round((h - 0.06) / 0.22));
const front = d / 2 - 0.02;
const step = (h - 0.06) / drawers;
for (let i = 1; i < drawers; i++) b.seg(-w / 2, 0.06 + step * i, front, w / 2, 0.06 + step * i, front, EDGE_FAINT);
for (let i = 0; i < drawers; i++) b.seg(-0.08, 0.06 + step * (i + 0.5), front + 0.012, 0.08, 0.06 + step * (i + 0.5), front + 0.012, EDGE_GLOW);
}
/** A shoe bench with a back panel, hooks and a hat shelf. */
export function coatRack(b: Builder, w: number, d: number, h: number): void {
b.block({ x: [-w / 2, w / 2], y: [0, 0.45], z: [-d / 2, d / 2] }, M.wood, EDGE_FURN);
fronts(b, -w / 2, w / 2, 0.02, 0.45, d / 2, Math.max(2, Math.round(w / 0.5)), 0.38, true);
b.block({ x: [-w / 2, w / 2], y: [0.45, h], z: [-d / 2, -d / 2 + 0.03] }, M.body, EDGE_FURN);
b.block({ x: [-w / 2, w / 2], y: [h - 0.04, h], z: [-d / 2, d / 2] }, M.wood, EDGE_FURN);
const hooks = Math.max(2, Math.round(w / 0.25));
for (let i = 0; i < hooks; i++) {
const x = -w / 2 + (w / hooks) * (i + 0.5);
b.block({ x: [x - 0.015, x + 0.015], y: [h - 0.32, h - 0.28], z: [-d / 2 + 0.03, -d / 2 + 0.1] }, M.metal);
}
}
/** A potted plant: a pot, a stem and foliage as stacked, slightly shifted octagonal layers. */
export function plant(b: Builder, w: number, d: number, h: number): void {
const r = Math.min(w, d) / 2;
const pot = Math.min(0.4, h * 0.34);
b.cylinder(0, 0, r * 0.62, 0, pot, M.pot, 10, EDGE_FURN);
b.cylinder(0, 0, r * 0.08, pot, h * 0.55, material(C.wood), 6);
const layers = 4;
for (let i = 0; i < layers; i++) {
const radius = r * (0.95 - 0.55 * (i / (layers - 1)));
const y0 = pot + (h - pot) * (0.18 + 0.2 * i);
b.cylinder(Math.sin(i * 2.1) * 0.03, Math.cos(i * 1.7) * 0.03, radius, y0, y0 + (h - pot) * 0.16, M.plant, 8, i === layers - 1 ? EDGE_FAINT : null);
}
}
/** A flat rug with a line inset from its edge. */
export function rug(b: Builder, w: number, d: number): void {
b.block({ x: [-w / 2, w / 2], y: [0, 0.012], z: [-d / 2, d / 2] }, M.fabric);
const i = Math.min(0.12, Math.min(w, d) * 0.08);
const [x0, x1, z0, z1] = [-w / 2 + i, w / 2 - i, -d / 2 + i, d / 2 - i];
for (const [xa, za, xb, zb] of [[x0, z0, x1, z0], [x1, z0, x1, z1], [x1, z1, x0, z1], [x0, z1, x0, z0]]) b.seg(xa, 0.014, za, xb, 0.014, zb, EDGE_FURN);
}
/** A straight stair rising towards -z (the back), with a handrail on the +x side. */
export function stairs(b: Builder, w: number, d: number, h: number): void {
const steps = Math.max(3, Math.round(h / 0.18));
const rise = h / steps;
const run = d / steps;
for (let i = 0; i < steps; i++) {
const z1 = d / 2 - run * i;
const y1 = rise * (i + 1);
b.block({ x: [-w / 2, w / 2], y: [0, y1], z: [z1 - run, z1] }, M.wood);
b.seg(-w / 2, y1, z1, w / 2, y1, z1, EDGE_FURN);
}
b.seg(-w / 2, 0, d / 2, -w / 2, rise, d / 2, EDGE_FURN);
// stringer lines along both sides
for (const x of [-w / 2, w / 2]) b.seg(x, rise, d / 2, x, h, -d / 2 + run, EDGE_FAINT);
// the handrail and its posts; the rail ends where the stair passes through the ceiling opening
const railHeight = 0.9;
const x = w / 2 - 0.03;
const last = Math.max(1, steps - 4);
b.seg(x, rise + railHeight, d / 2 - run / 2, x, rise * last + railHeight, d / 2 - run * (last - 0.5), EDGE_GLOW);
for (let i = 0; i < last; i += 3) {
const z = d / 2 - run * (i + 0.5);
b.seg(x, rise * (i + 1), z, x, rise * (i + 1) + railHeight, z, EDGE_FAINT);
}
}
/** A TV on a low unit with a stand. */
export function tvBoard(b: Builder, w: number, d: number, h: number, rim: Parameters<Builder["block"]>[2] = EDGE_GLOW): void {
cabinet(b, w, d, h, Math.max(2, Math.round(w / 0.6)), h * 0.55, true);
const screen = Math.min(w * 0.8, 1.45);
b.block({ x: [-0.1, 0.1], y: [h, h + 0.02], z: [-d / 2 + 0.08, -d / 2 + 0.24] }, M.metal);
b.block({ x: [-0.02, 0.02], y: [h + 0.02, h + 0.12], z: [-d / 2 + 0.14, -d / 2 + 0.18] }, M.metal);
b.block({ x: [-screen / 2, screen / 2], y: [h + 0.1, h + 0.1 + screen * 0.56], z: [-d / 2 + 0.12, -d / 2 + 0.16] }, M.dark, rim);
}
/** A flat screen on a wall bracket, centred at 1.3 m. */
export function tvWall(b: Builder, w: number, d: number, h: number, rim: Parameters<Builder["block"]>[2] = EDGE_GLOW): void {
const y0 = 1.3 - h / 2;
b.block({ x: [-0.12, 0.12], y: [y0 + h * 0.3, y0 + h * 0.7], z: [-d / 2, -d / 2 + 0.03] }, M.metal);
b.block({ x: [-w / 2, w / 2], y: [y0, y0 + h], z: [-d / 2 + 0.03, d / 2] }, M.dark, rim);
}
+82
View File
@@ -0,0 +1,82 @@
// Furniture from packs: the parts of a pack item scaled to the item's size, as lamps with glowing parts, and as glow layers.
import type { Furniture } from "../../model.ts";
import { fittedParts, movedParts, type PackItem, type PackPart } from "../../packs.ts";
import { DEG, EDGE_TOP, LineBuffer, shade, type GeoBuffer } from "../geo.ts";
import { Builder, flipWinding, type Plan } from "./builder.ts";
import { C, EDGE_FAINT, EDGE_FURN, material } from "./palette.ts";
/** The colour of a pack part: a palette role (so packs follow the look) or "#rrggbb". */
function partColor(value: string | undefined, top: boolean): number | null {
if (!value) return null;
if (value.startsWith("#")) return Number.parseInt(value.slice(1), 16);
const palette = C as Record<string, number>;
return (top ? palette[`${value}Top`] : undefined) ?? palette[value] ?? null;
}
/** The model of a pack item: its parts scaled to the item's size. Glowing parts take `glow` (a lit lamp). */
export function packModel(b: Builder, item: PackItem, w: number, d: number, h: number, base: number, glow: number | null, only: ((p: PackPart) => boolean) | null = null, variant: string | null = null, reach: number | null = null): void {
// the colour picked for the item (its first by default), for the parts that carry paint
const paint = item.colors?.length ? (item.colors.find((c) => c.id === variant) ?? item.colors[0]).hex : null;
// moving parts (a curtain, an awning) are drawn apart, at their reach; the item itself leaves them out
const fitted = fittedParts(item, w, d, h);
for (const raw of reach === null ? fitted : movedParts(fitted, reach)) {
if (reach === null && raw.move) continue;
if (only && !only(raw)) continue;
// selected parts (the glowing ones of a speaker, a car's windows) come out a hair larger, so they cover the item's own
const part = only ? { ...raw, glow: true, w: raw.w + 0.006 / w, d: raw.d + 0.006 / d, y: Math.max(0, raw.y - 0.002 / h), h: raw.h + 0.004 / h } : raw;
const lit = part.glow && glow !== null;
const painted = !!(part.paint && paint);
const body = painted ? paint! : part.color;
const side = lit ? glow : (partColor(body, false) ?? C.body);
// without a top colour, the top is the role's top shade or a little lighter
const top = lit ? glow : (partColor(painted ? undefined : part.top, false) ?? partColor(body, true) ?? shade(side, 1.25).getHex());
const look = material(side, top);
const [y0, y1] = [base + part.y * h, base + Math.min(h, (part.y + part.h) * h)];
// "glow" lines are as bright as the wall lines, so a pack item can be drawn like the walls
const edges = part.edges === "glow" ? EDGE_TOP : part.edges === "faint" ? EDGE_FAINT : part.edges ? EDGE_FURN : null;
// a turned part draws through a builder whose coordinates turn around the part's centre
const target = part.rot ? b.turned(part.x * w, part.z * d, part.rot) : b;
const [cx, cz] = [part.x * w, part.z * d];
if (part.shape === "cyl" && (part.axis === "x" || part.axis === "z")) {
target.lyingCylinder(part.axis, cx, cz, y0, y1, part.axis === "x" ? part.w * w : part.d * d, part.axis === "x" ? part.d * d : part.w * w, look, 14, edges);
} else if (part.shape === "cyl") {
target.cylinder(cx, cz, Math.min(part.w * w, part.d * d) / 2, y0, y1, look, 14, edges);
} else if (part.shape === "loft") {
const [tx, tz, tw, td] = [part.tx ?? part.x, part.tz ?? part.z, part.tw ?? part.w, part.td ?? part.d];
target.loft([(part.x - part.w / 2) * w, (part.x + part.w / 2) * w, (part.z - part.d / 2) * d, (part.z + part.d / 2) * d], [(tx - tw / 2) * w, (tx + tw / 2) * w, (tz - td / 2) * d, (tz + td / 2) * d], y0, y1, look, edges);
} else if (part.shape === "sweep") {
const stations = (part.stations ?? []).map(([z, sy0, sy1, sw]) => ({ x: cx, z: z * d, y0: base + sy0 * h, y1: base + sy1 * h, hw: (sw * w) / 2 }));
target.sweep(stations, look, part.n ?? 16, part.exp ?? 2.6, edges);
} else target.block({ x: [(part.x - part.w / 2) * w, (part.x + part.w / 2) * w], y: [y0, y1], z: [(part.z - part.d / 2) * d, (part.z + part.d / 2) * d] }, look, edges);
}
}
type Placed = Pick<Furniture, "x" | "z" | "rotation" | "w" | "d" | "h" | "mirror">;
/** The plan transform of a placed item: turned by its rotation, and mirrored when asked (its own x runs the other way). */
export function placement(f: Pick<Furniture, "x" | "z" | "rotation" | "mirror">): Plan {
const [c, s] = [Math.cos(f.rotation * DEG), Math.sin(f.rotation * DEG)];
const mx = f.mirror ? -1 : 1;
return (x, z) => [f.x + mx * x * c - z * s, f.z + mx * x * s + z * c];
}
const sizeOf = (f: Placed): [number, number, number] => [Math.max(0.05, f.w), Math.max(0.05, f.d), Math.max(0.005, f.h)];
/** The glowing parts of a pack item that is no lamp (a smart speaker's light ring) in `color`, for the screen layer. */
export function pushPackGlow(buf: GeoBuffer, item: PackItem, f: Placed, base: number, color: number, pick: (p: PackPart) => boolean = (p) => !!p.glow): void {
packModel(new Builder(buf, new LineBuffer(), placement(f)), item, ...sizeOf(f), base, color, pick);
}
/** The moving parts of a pack item (curtain, roller screen, awning, gate) at their reach (0 drawn in … 1 out). */
export function pushPackMoving(buf: GeoBuffer, item: PackItem, f: Placed & { variant?: string | null }, base: number, reach: number): void {
const first = buf.p.length;
packModel(new Builder(buf, new LineBuffer(), placement(f)), item, ...sizeOf(f), base, null, null, f.variant ?? null, reach);
if (f.mirror) flipWinding(buf, first);
}
/** A pack lamp into the lamp buffer: glowing parts in the light's colour (`glow`), or dark when off. Lamps have no outlines. */
export function pushPackLamp(buf: GeoBuffer, item: PackItem, f: Placed, base: number, glow: number): void {
packModel(new Builder(buf, new LineBuffer(), placement(f)), item, ...sizeOf(f), base, glow);
}
@@ -0,0 +1,21 @@
import assert from "node:assert/strict";
import { test } from "node:test";
import { applyFurnitureColors, C, M } from "./palette.ts";
import { FURNITURE_ROLES, STOCK_ROLE_HEX } from "../../furniture-colors.ts";
test("chosen role colours reach the palette and its materials, and go back to stock", () => {
const stockBody = C.body;
for (const role of FURNITURE_ROLES) assert.equal(STOCK_ROLE_HEX[role], `#${C[role].toString(16).padStart(6, "0")}`);
assert.equal(applyFurnitureColors({ body: "#804020", fabric: "#00ff00", metal: "nope" }), true);
assert.equal(C.body, 0x804020);
assert.equal(M.body.side, 0x804020);
assert.notEqual(M.body.top, 0x804020);
assert.equal(M.cushion.side, 0x00ff00);
assert.equal(M.cushionSoft.top, C.fabricTop);
assert.equal(C.metal, 0x2a3a60);
// the same colours again change nothing
assert.equal(applyFurnitureColors({ body: "#804020", fabric: "#00ff00" }), false);
assert.equal(applyFurnitureColors(null), true);
assert.equal(C.body, stockBody);
assert.equal(M.body.side, stockBody);
});
+98
View File
@@ -0,0 +1,98 @@
// Colours of the furniture in the neon look.
import { shade } from "../geo.ts";
import { FURNITURE_ROLES, type FurnitureColors, type FurnitureRole } from "../../furniture-colors.ts";
/** The palette roles furniture and pack items are painted with. */
export const C = {
body: 0x172238,
bodyTop: 0x1d2b47,
fabric: 0x1a2644,
fabricTop: 0x22325a,
cushion: 0x243661,
wood: 0x19233c,
woodTop: 0x202d4b,
white: 0x1d2946,
whiteTop: 0x26375e,
metal: 0x2a3a60,
dark: 0x0b111f,
glass: 0x1c3a52,
plant: 0x12302e,
plantTop: 0x1a4540,
pot: 0x1d2640,
accent: 0x2b8fb3,
};
/** A surface material: the colour of the sides and of the top. */
export interface Material {
side: number;
top: number;
}
const material = (side: number, top = side): Material => ({ side, top });
export const M = {
body: material(C.body, C.bodyTop),
fabric: material(C.fabric, C.fabricTop),
cushion: material(C.cushion),
cushionSoft: material(C.cushion, C.fabricTop),
wood: material(C.wood, C.woodTop),
white: material(C.white, C.whiteTop),
worktop: material(C.whiteTop),
metal: material(C.metal),
dark: material(C.dark),
darkBody: material(C.dark, C.body),
glass: material(C.glass),
accent: material(C.accent),
pot: material(C.pot),
plant: material(C.plant, C.plantTop),
bedding: material(C.white, C.whiteTop),
pillow: material(C.whiteTop),
};
export { material };
export const EDGE_FURN = shade(0x5b7cff, 0.3);
export const EDGE_FAINT = shade(0x5b7cff, 0.17);
export const EDGE_GLOW = shade(0x37e0ff, 0.45);
export { FURNITURE_ROLES, type FurnitureColors, type FurnitureRole };
const STOCK_C = { ...C };
const stockMaterials = Object.fromEntries(Object.entries(M).map(([k, m]) => [k, { ...m }])) as Record<keyof typeof M, Material>;
let appliedKey = "";
const hexOf = (v: string | null | undefined): number | null => (typeof v === "string" && /^#[0-9a-f]{6}$/i.test(v) ? Number.parseInt(v.slice(1), 16) : null);
/**
* Sets the colours of the roles before furniture is built: every builder and pack item reads `C` and `M` while it
* builds, so the next rebuild takes them. Returns whether anything changed. The top of a role is a shade lighter.
*/
export function applyFurnitureColors(colors: FurnitureColors | null | undefined): boolean {
const own = Object.fromEntries(FURNITURE_ROLES.map((r) => [r, hexOf(colors?.[r])]).filter(([, v]) => v !== null)) as Partial<Record<FurnitureRole, number>>;
const key = JSON.stringify(own);
if (key === appliedKey) return false;
appliedKey = key;
Object.assign(C, STOCK_C);
for (const [k, m] of Object.entries(stockMaterials)) Object.assign(M[k as keyof typeof M], m);
const top = (v: number) => shade(v, 1.25).getHex();
const set = (role: FurnitureRole, entries: (keyof typeof C)[], tops: (keyof typeof C)[], mats: (keyof typeof M)[]) => {
const v = own[role];
if (v === undefined) return;
for (const e of entries) C[e] = v;
for (const e of tops) C[e] = top(v);
// a material whose side or top was one of the role's stock colours takes the new one
const swap = new Map<number, number>([...entries.map((e) => [STOCK_C[e], v] as [number, number]), ...tops.map((e) => [STOCK_C[e], top(v)] as [number, number])]);
for (const m of mats) {
const stock = stockMaterials[m];
M[m].side = swap.get(stock.side) ?? M[m].side;
M[m].top = swap.get(stock.top) ?? M[m].top;
}
};
set("body", ["body"], ["bodyTop"], ["body", "darkBody"]);
set("wood", ["wood"], ["woodTop"], ["wood"]);
set("fabric", ["fabric", "cushion"], ["fabricTop"], ["fabric", "cushion", "cushionSoft"]);
set("white", ["white"], ["whiteTop"], ["white", "worktop", "bedding", "pillow"]);
set("metal", ["metal"], [], ["metal"]);
set("dark", ["dark"], [], ["dark", "darkBody"]);
return true;
}
+44
View File
@@ -0,0 +1,44 @@
// Parts that many models share: legs, door and drawer fronts.
import { Builder } from "./builder.ts";
import { C, EDGE_FAINT, EDGE_FURN, EDGE_GLOW, M, material, type Material } from "./palette.ts";
/** Four legs inside a w × d footprint; `taper` makes them narrower at the foot. */
export function legs(b: Builder, w: number, d: number, h: number, thickness: number, inset: number, color = C.metal, taper = false): void {
const [x, z] = [w / 2 - inset - thickness, d / 2 - inset - thickness];
const leg = material(color);
for (const sx of [-1, 1]) {
for (const sz of [-1, 1]) {
const [cx, cz] = [sx * x, sz * z];
if (taper) b.loft([cx - thickness * 0.3, cx + thickness * 0.3, cz - thickness * 0.3, cz + thickness * 0.3], [cx - thickness / 2, cx + thickness / 2, cz - thickness / 2, cz + thickness / 2], 0, h, leg);
else b.block({ x: [cx - thickness / 2, cx + thickness / 2], y: [0, h], z: [cz - thickness / 2, cz + thickness / 2] }, leg);
}
}
}
/** Door or drawer fronts on the front face (+z): division lines and small glowing handles. */
export function fronts(b: Builder, x0: number, x1: number, y0: number, y1: number, z: number, count: number, handleY: number | null = null, horizontal = false): void {
const width = (x1 - x0) / count;
for (let i = 1; i < count; i++) b.seg(x0 + width * i, y0, z, x0 + width * i, y1, z, EDGE_FAINT);
for (let i = 0; i < count; i++) {
const centre = x0 + width * (i + 0.5);
const y = handleY ?? y1 - 0.08;
if (horizontal) {
const half = Math.min(0.1, width / 4);
b.seg(centre - half, y, z + 0.012, centre + half, y, z + 0.012, EDGE_GLOW);
} else {
// vertical handles alternate sides, so neighbouring doors have theirs next to each other
const x = count > 1 ? centre + (i % 2 ? -width / 2 + 0.06 : width / 2 - 0.06) : centre + width / 2 - 0.06;
b.seg(x, y - 0.08, z + 0.012, x, y + 0.08, z + 0.012, EDGE_GLOW);
}
}
}
/** A carcass with a plinth and fronts: the basis of cabinets, kitchen units and wardrobes. */
export function cabinet(b: Builder, w: number, d: number, h: number, doors: number, handleY: number | null = null, horizontal = false, body: Material = M.body): void {
b.block({ x: [-w / 2, w / 2], y: [0.02, h], z: [-d / 2, d / 2 - 0.02] }, body, EDGE_FURN);
b.block({ x: [-w / 2 + 0.02, w / 2 - 0.02], y: [0, 0.08], z: [-d / 2 + 0.02, d / 2 - 0.06] }, material(C.dark));
fronts(b, -w / 2, w / 2, 0.08, h, d / 2 - 0.02, doors, handleY, horizontal);
}
+92
View File
@@ -0,0 +1,92 @@
// Where the screen of a TV or monitor is, for the glow shown while the linked device is on.
import { builtinBase, type Floor, type Furniture } from "../../model.ts";
import { fittedParts, mountBase, packItem } from "../../packs.ts";
import { RADIATOR_Y } from "./kitchen.ts";
export interface ScreenRect {
x0: number;
x1: number;
y0: number;
y1: number;
z: number;
}
function builtInScreen(f: Furniture, w: number, d: number, h: number, floor?: Floor): ScreenRect | null {
switch (f.type) {
case "tv_board": {
const width = Math.min(w * 0.8, 1.45);
return { x0: -width / 2 + 0.02, x1: width / 2 - 0.02, y0: h + 0.12, y1: h + 0.08 + width * 0.56, z: -d / 2 + 0.165 };
}
case "tv_wall": {
const y0 = 1.3 - h / 2;
return { x0: -w / 2 + 0.02, x1: w / 2 - 0.02, y0: y0 + 0.02, y1: y0 + h - 0.02, z: d / 2 + 0.003 };
}
case "desk":
return { x0: -0.28, x1: 0.28, y0: h + 0.1, y1: h + 0.4, z: -d / 2 + 0.115 };
case "fridge_smart": {
// the screen sits on the right door (mirrored: the door's u runs to the left from its hinge at +w/2)
const base = floor ? mountBase(floor, f) : 0;
return { x0: 0.06, x1: w / 2 - 0.06, y0: base + h * 0.52 + 0.01, y1: base + h * 0.86 - 0.01, z: d / 2 + 0.006 };
}
// glowing fronts of appliances that run, and of a radiator that heats
case "radiator":
return { x0: -w / 2 + 0.02, x1: w / 2 - 0.02, y0: RADIATOR_Y + 0.02, y1: RADIATOR_Y + h - 0.02, z: d / 2 + 0.004 };
case "washer":
case "dryer": {
const cy = (h - 0.14) / 2 + 0.04;
const r = Math.min(w * 0.36, (h - 0.2) * 0.42) * 0.8;
return { x0: -r, x1: r, y0: cy - r, y1: cy + r, z: d / 2 - 0.004 };
}
case "dishwasher":
return { x0: -w / 2 + 0.06, x1: w / 2 - 0.06, y0: h - 0.16, y1: h - 0.08, z: d / 2 - 0.004 };
default:
return null;
}
}
function unmirrored(f: Furniture, floor?: Floor): ScreenRect | null {
const [w, d, h] = [Math.max(0.05, f.w), Math.max(0.05, f.d), Math.max(0.005, f.h)];
const item = packItem(f.type);
const part = item && fittedParts(item, w, d, h).find((p) => p.screen);
if (part) {
// the screen part's front face, at the item's mount height
const base = floor ? mountBase(floor, f) : 0;
const [x0, x1] = [(part.x - part.w / 2) * w, (part.x + part.w / 2) * w];
const inset = Math.min(0.02, (x1 - x0) * 0.05);
return { x0: x0 + inset, x1: x1 - inset, y0: base + part.y * h + inset, y1: base + (part.y + part.h) * h - inset, z: (part.z + part.d / 2) * d };
}
// built-in models are lifted as a whole by their mount height
const lift = floor && f.type !== "fridge_smart" ? mountBase(floor, f) - builtinBase(f) : 0;
const rect = builtInScreen(f, w, d, h, floor);
return rect && { ...rect, y0: rect.y0 + lift, y1: rect.y1 + lift };
}
/** The screen of a TV or monitor in local coordinates (x across, y up, z = its front face). Null for furniture without one. */
export function screenRect(f: Furniture, floor?: Floor): ScreenRect | null {
const rect = unmirrored(f, floor);
return rect && f.mirror ? { ...rect, x0: -rect.x1, x1: -rect.x0 } : rect;
}
/** The picture part of a frame (a pack item's part marked `picture`) in local coordinates, mirrored like the item; null without one. */
export function pictureRect(f: Furniture, floor?: Floor): ScreenRect | null {
const [w, d, h] = [Math.max(0.05, f.w), Math.max(0.05, f.d), Math.max(0.005, f.h)];
const item = packItem(f.type);
const part = item && fittedParts(item, w, d, h).find((p) => p.picture);
if (!part) return null;
const base = floor ? mountBase(floor, f) : 0;
const [x0, x1] = [(part.x - part.w / 2) * w, (part.x + part.w / 2) * w];
const rect = { x0, x1, y0: base + part.y * h, y1: base + (part.y + part.h) * h, z: (part.z + part.d / 2) * d };
return f.mirror ? { ...rect, x0: -rect.x1, x1: -rect.x0 } : rect;
}
/** The charge bar on the front of a home battery (local coordinates) and whether it fills upwards (a tower) or sideways (wall unit, cube). */
export function batteryBar(f: Furniture, floor?: Floor): { rect: ScreenRect; vertical: boolean } | null {
if (f.type !== "home_battery") return null;
const [w, d, h] = [Math.max(0.05, f.w), Math.max(0.05, f.d), Math.max(0.05, f.h)];
const lift = floor ? mountBase(floor, f) - builtinBase(f) : 0;
const z = d / 2 + 0.005;
if (f.variant === "wall") return { rect: { x0: -w * 0.3, x1: w * 0.3, y0: lift + 0.5 + h * 0.84, y1: lift + 0.5 + h * 0.9, z }, vertical: false };
if (f.variant === "cube") return { rect: { x0: -w * 0.35, x1: w * 0.35, y0: lift + h * 0.8, y1: lift + h * 0.86, z }, vertical: false };
return { rect: { x0: -w * 0.05, x1: w * 0.05, y0: lift + 0.06 + h * 0.16, y1: lift + h - 0.12, z }, vertical: true };
}
+159
View File
@@ -0,0 +1,159 @@
// Seating and beds.
import type { Builder } from "./builder.ts";
import { legs } from "./parts.ts";
import { C, EDGE_FAINT, EDGE_FURN, M, material } from "./palette.ts";
/** A sofa (`seats` cushions across) or, with one seat, an armchair. */
export function sofa(b: Builder, w: number, d: number, h: number, seats: number): void {
const [x0, x1, z0, z1] = [-w / 2, w / 2, -d / 2, d / 2];
const arm = Math.min(0.2, w * 0.12);
const seat = h * 0.5;
const back = Math.min(0.24, d * 0.28);
legs(b, w, d, 0.07, 0.05, 0.05, C.wood, true);
b.pad({ x: [x0, x1], y: [0.07, seat - 0.08], z: [z0 + 0.02, z1] }, M.fabric, 0.04, EDGE_FURN);
// the back leans a little: its top is thinner than its base
b.loft([x0, x1, z0, z0 + back], [x0 + 0.01, x1 - 0.01, z0, z0 + back * 0.5], seat - 0.08, h, M.fabric, EDGE_FURN);
for (const [a, c] of [[x0, x0 + arm], [x1 - arm, x1]]) b.pad({ x: [a, c], y: [seat - 0.08, h * 0.72], z: [z0 + 0.02, z1 - 0.02] }, M.fabric, 0.04, EDGE_FURN);
// seat cushions with a small gap, and back cushions leaning against the back
const cushionWidth = (x1 - arm - (x0 + arm)) / seats;
for (let i = 0; i < seats; i++) {
const from = x0 + arm + cushionWidth * i + 0.02;
const to = from + cushionWidth - 0.04;
b.pad({ x: [from, to], y: [seat - 0.08, seat + 0.05], z: [z0 + back + 0.02, z1 - 0.06] }, M.cushion, 0.04);
b.loft([from + 0.01, to - 0.01, z0 + back * 0.55, z0 + back + 0.14], [from + 0.03, to - 0.03, z0 + back * 0.4, z0 + back * 0.4 + 0.06], seat + 0.03, h * 0.93, M.cushion);
}
}
/**
* An L- or U-shaped sofa: the back runs along the rear, a chaise reaches forward at the right end (an L; mirrored, the left) or at
* both ends (a U). The seat depth stays that of a sofa, whatever the depth of the whole.
*/
export function shapedSofa(b: Builder, w: number, d: number, h: number, shape: "l" | "u"): void {
const [x0, x1, z0, z1] = [-w / 2, w / 2, -d / 2, d / 2];
const seat = h * 0.5;
const back = Math.min(0.24, d * 0.2);
const depth = Math.min(0.95, d * 0.55);
const chaise = Math.min(0.9, w * (shape === "u" ? 0.28 : 0.34));
const arm = 0.16;
legs(b, w, d, 0.07, 0.05, 0.05, C.wood, true);
// the main bench along the back, and the chaise(s) reaching forward
b.pad({ x: [x0, x1], y: [0.07, seat - 0.08], z: [z0 + 0.02, z0 + depth] }, M.fabric, 0.04, EDGE_FURN);
const ends: [number, number][] = shape === "u" ? [[x0, x0 + chaise], [x1 - chaise, x1]] : [[x1 - chaise, x1]];
for (const [a, c] of ends) b.pad({ x: [a, c], y: [0.07, seat - 0.08], z: [z0 + depth - 0.04, z1] }, M.fabric, 0.04, EDGE_FURN);
b.loft([x0, x1, z0, z0 + back], [x0 + 0.01, x1 - 0.01, z0, z0 + back * 0.5], seat - 0.08, h, M.fabric, EDGE_FURN);
// arms: on the open end of an L, and along the outer sides of the chaises
if (shape === "l") b.pad({ x: [x0, x0 + arm], y: [seat - 0.08, h * 0.72], z: [z0 + 0.02, z0 + depth - 0.02] }, M.fabric, 0.04, EDGE_FURN);
for (const [a, c] of ends) {
const outer = a <= x0 + 1e-6 ? [a, a + arm] : [c - arm, c];
b.pad({ x: [outer[0], outer[1]], y: [seat - 0.08, h * 0.62], z: [z0 + 0.02, z1 - 0.02] }, M.fabric, 0.04, EDGE_FURN);
}
// cushions on the bench between the chaises, and one long cushion on each chaise
const from = shape === "u" ? x0 + chaise : x0 + arm;
const to = x1 - chaise;
const seats = Math.max(1, Math.round((to - from) / 0.62));
const cw = (to - from) / seats;
for (let i = 0; i < seats; i++) {
const a = from + cw * i + 0.02;
const c = a + cw - 0.04;
b.pad({ x: [a, c], y: [seat - 0.08, seat + 0.05], z: [z0 + back + 0.02, z0 + depth - 0.06] }, M.cushion, 0.04);
b.loft([a + 0.01, c - 0.01, z0 + back * 0.55, z0 + back + 0.14], [a + 0.03, c - 0.03, z0 + back * 0.4, z0 + back * 0.4 + 0.06], seat + 0.03, h * 0.93, M.cushion);
}
for (const [a, c] of ends) {
const inner = a <= x0 + 1e-6 ? [a + arm + 0.02, c - 0.02] : [a + 0.02, c - arm - 0.02];
b.pad({ x: [inner[0], inner[1]], y: [seat - 0.08, seat + 0.05], z: [z0 + back + 0.02, z1 - 0.06] }, M.cushion, 0.04);
}
}
export function bed(b: Builder, w: number, d: number, h: number): void {
const [x0, x1, z0, z1] = [-w / 2, w / 2, -d / 2, d / 2];
const frame = Math.min(0.32, h * 0.36);
legs(b, w, d, 0.08, 0.06, 0.03, C.wood, true);
b.block({ x: [x0, x1], y: [0.08, frame], z: [z0 + 0.06, z1] }, M.wood, EDGE_FURN);
b.pad({ x: [x0 + 0.03, x1 - 0.03], y: [frame, frame + 0.2], z: [z0 + 0.08, z1 - 0.03] }, M.bedding, 0.03);
// head board, and its cap
b.block({ x: [x0, x1], y: [0.08, h - 0.05], z: [z0, z0 + 0.07] }, M.wood, EDGE_FURN);
b.block({ x: [x0, x1], y: [h - 0.05, h], z: [z0, z0 + 0.09] }, M.wood, EDGE_FAINT);
// a duvet over the lower two thirds with a folded-back edge, puffy pillows at the head
const mattress = frame + 0.2;
const fold = z0 + (d - 0.1) * 0.36;
b.pad({ x: [x0 + 0.01, x1 - 0.01], y: [mattress - 0.1, mattress + 0.05], z: [fold, z1 - 0.01] }, M.cushionSoft, 0.025, EDGE_FAINT);
b.lyingCylinder("x", 0, fold + 0.05, mattress - 0.02, mattress + 0.09, w - 0.02, 0.1, M.cushionSoft, 8);
const pillows = w > 1.2 ? 2 : 1;
const pillowWidth = (w - 0.2) / pillows;
for (let i = 0; i < pillows; i++) {
const px = x0 + 0.1 + pillowWidth * i;
const pz = z0 + 0.12;
const depth = Math.min(0.42, d * 0.2);
const k = 0.1;
b.loft([px + 0.03 + k, px + pillowWidth - 0.03 - k, pz + k * 0.5, pz + depth - k * 0.5], [px + 0.03, px + pillowWidth - 0.03, pz, pz + depth], mattress, mattress + 0.06, M.pillow);
b.loft([px + 0.03, px + pillowWidth - 0.03, pz, pz + depth], [px + 0.03 + k, px + pillowWidth - 0.03 - k, pz + k * 0.5, pz + depth - k * 0.5], mattress + 0.06, mattress + 0.12, M.pillow, EDGE_FAINT);
}
}
export function chair(b: Builder, w: number, d: number, h: number): void {
const seat = Math.min(0.46, h * 0.52);
legs(b, w, d, seat - 0.04, 0.035, 0.02, C.wood, true);
b.block({ x: [-w / 2, w / 2], y: [seat - 0.04, seat], z: [-d / 2, d / 2] }, M.wood, EDGE_FURN);
b.pad({ x: [-w / 2 + 0.02, w / 2 - 0.02], y: [seat, seat + 0.04], z: [-d / 2 + 0.05, d / 2 - 0.03] }, M.cushion, 0.015);
b.loft([-w / 2, w / 2, -d / 2 + 0.02, -d / 2 + 0.07], [-w / 2 + 0.02, w / 2 - 0.02, -d / 2, -d / 2 + 0.03], seat, h, M.wood, EDGE_FURN);
}
export function barStool(b: Builder, w: number, d: number, h: number): void {
const r = Math.min(w, d) / 2;
b.cylinder(0, 0, r * 0.8, 0, 0.02, M.metal, 12);
b.cylinder(0, 0, 0.025, 0.02, h - 0.05, M.metal, 6);
b.cylinder(0, 0, r * 0.75, h * 0.35, h * 0.35 + 0.015, M.metal, 12, EDGE_FAINT);
b.cylinder(0, 0, r, h - 0.05, h, M.cushionSoft, 14, EDGE_FURN);
}
export function officeChair(b: Builder, w: number, d: number, h: number): void {
const r = Math.min(w, d) / 2;
// a star base as two crossed bars and a hub, a gas lift, seat and back
b.block({ x: [-r, r], y: [0.04, 0.08], z: [-0.03, 0.03] }, M.metal);
b.block({ x: [-0.03, 0.03], y: [0.04, 0.08], z: [-r, r] }, M.metal);
b.cylinder(0, 0, 0.06, 0.02, 0.1, M.dark, 8);
b.cylinder(0, 0, 0.025, 0.1, 0.44, M.metal, 6);
b.block({ x: [-r * 0.75, r * 0.75], y: [0.44, 0.52], z: [-r * 0.7, r * 0.75] }, material(C.fabric, C.cushion), EDGE_FURN);
b.block({ x: [-r * 0.7, r * 0.7], y: [0.58, h], z: [-r * 0.78, -r * 0.62] }, M.fabric, EDGE_FURN);
b.block({ x: [-0.03, 0.03], y: [0.5, 0.62], z: [-r * 0.72, -r * 0.62] }, M.metal);
}
export function stool(b: Builder, w: number, d: number, h: number): void {
legs(b, w, d, 0.08, 0.04, 0.05, C.wood);
b.block({ x: [-w / 2, w / 2], y: [0.08, h], z: [-d / 2, d / 2] }, material(C.fabric, C.cushion), EDGE_FURN);
}
/** A bench with a back along the rear; `corner` adds the second arm along -x. */
export function bench(b: Builder, w: number, d: number, h: number, corner: boolean): void {
const seat = 0.45;
const depth = Math.min(0.5, corner ? d * 0.4 : d);
const back = 0.08;
const cushion = material(C.cushion);
// the rear arm
b.block({ x: [-w / 2, w / 2], y: [0, seat - 0.06], z: [-d / 2, -d / 2 + depth] }, M.wood, EDGE_FURN);
b.block({ x: [-w / 2, w / 2], y: [0, h], z: [-d / 2, -d / 2 + back] }, M.wood, EDGE_FURN);
b.block({ x: [-w / 2 + (corner ? depth : 0.02), w / 2 - 0.02], y: [seat - 0.06, seat + 0.02], z: [-d / 2 + back, -d / 2 + depth] }, cushion, EDGE_FAINT);
if (!corner) return;
// the side arm along -x, meeting the rear arm in the corner
b.block({ x: [-w / 2, -w / 2 + depth], y: [0, seat - 0.06], z: [-d / 2 + depth, d / 2] }, M.wood, EDGE_FURN);
b.block({ x: [-w / 2, -w / 2 + back], y: [0, h], z: [-d / 2 + back, d / 2] }, M.wood, EDGE_FURN);
b.block({ x: [-w / 2 + back, -w / 2 + depth], y: [seat - 0.06, seat + 0.02], z: [-d / 2 + back, d / 2 - 0.02] }, cushion, EDGE_FAINT);
}
export function bunkBed(b: Builder, w: number, d: number, h: number): void {
const t = 0.05;
for (const sx of [-1, 1]) {
for (const sz of [-1, 1]) b.block({ x: [sx * (w / 2) - (sx > 0 ? t : 0), sx * (w / 2) + (sx < 0 ? t : 0)], y: [0, h], z: [sz * (d / 2) - (sz > 0 ? t : 0), sz * (d / 2) + (sz < 0 ? t : 0)] }, M.wood);
}
for (const y of [0.25, h - 0.55]) {
b.block({ x: [-w / 2, w / 2], y: [y, y + 0.08], z: [-d / 2, d / 2] }, M.wood, EDGE_FURN);
b.block({ x: [-w / 2 + 0.04, w / 2 - 0.04], y: [y + 0.08, y + 0.24], z: [-d / 2 + 0.05, d / 2 - 0.05] }, M.bedding, EDGE_FAINT);
b.block({ x: [-w / 2 + 0.05, w / 2 - 0.05], y: [y + 0.24, y + 0.33], z: [-d / 2 + 0.08, -d / 2 + 0.4] }, M.pillow);
}
// a guard rail on top and a ladder at the front
b.block({ x: [-w / 2, w / 2], y: [h - 0.2, h - 0.15], z: [d / 2 - t, d / 2] }, M.wood);
const ladder = w / 2 - 0.35;
for (const x of [ladder - 0.18, ladder + 0.18]) b.seg(x, 0, d / 2 + 0.02, x, h - 0.15, d / 2 + 0.02, EDGE_FURN);
for (let y = 0.3; y < h - 0.2; y += 0.28) b.seg(ladder - 0.18, y, d / 2 + 0.02, ladder + 0.18, y, d / 2 + 0.02, EDGE_FAINT);
}
+80
View File
@@ -0,0 +1,80 @@
// Shaped stairs: straight, winding (a quarter or half turn), L and U with a landing, and spiral stairs, built as a solid
// mass, on two stringers, on one spine or as steps out of the wall, going up or down. The treads come from the layout in
// geometry/stairs.ts, so the 3D model, the plan symbol and the floor opening always agree.
import type { Vec2 } from "../../model.ts";
import { stairConfig, stairLayout, treadCentre, type StairConfig, type Tread } from "../../geometry/stairs.ts";
import type { Builder } from "./builder.ts";
import { EDGE_FAINT, EDGE_FURN, EDGE_GLOW, M } from "./palette.ts";
const RAIL_HEIGHT = 0.9;
/** A thin upright plate along the segment a-b, moved `inset` towards `inside`: risers and stringers. */
function plate(b: Builder, a: Vec2, c: Vec2, inside: Vec2, y0: number, y1: number, thickness: number, material = M.wood): void {
const [dx, dz] = [c[0] - a[0], c[1] - a[1]];
const length = Math.hypot(dx, dz);
if (length < 0.01 || y1 - y0 < 0.005) return;
let [nx, nz] = [-dz / length, dx / length];
// the normal points into the tread
const mid: Vec2 = [(a[0] + c[0]) / 2, (a[1] + c[1]) / 2];
if ((inside[0] - mid[0]) * nx + (inside[1] - mid[1]) * nz < 0) [nx, nz] = [-nx, -nz];
const off = (p: Vec2, s: number): Vec2 => [p[0] + nx * s, p[1] + nz * s];
b.prism([a, c, off(c, thickness), off(a, thickness)], y0, y1, material, EDGE_FAINT);
}
/** Pairs of neighbouring points of a side, leaving out the zero-length ones of a winder's pivot. */
const segments = (side: Vec2[]): [Vec2, Vec2][] =>
side.slice(1).map((p, i): [Vec2, Vec2] => [side[i], p]).filter(([p, q]) => Math.hypot(q[0] - p[0], q[1] - p[1]) > 0.01);
function treadsAndBody(b: Builder, cfg: StairConfig, treads: Tread[], rise: number, floor: number): void {
const thick = cfg.build === "cantilever" ? 0.07 : 0.05;
treads.forEach((t, i) => {
const centre = treadCentre(t);
const previous = i === 0 ? 0 : treads[i - 1].top;
if (cfg.build === "solid") {
// a solid (concrete) stair: every tread is a block down to the floor the stair stands on
b.prism(t.poly, Math.min(floor, t.top), t.top, M.body, EDGE_FURN);
return;
}
b.prism(t.poly, t.top - thick, t.top, M.wood, EDGE_FURN);
if (cfg.risers && !t.landing) {
const [lo, hi] = [Math.min(previous, t.top), Math.max(previous, t.top) - thick];
plate(b, t.left[0], t.right[0], centre, lo, hi, 0.02);
}
if (cfg.build === "stringer") {
for (const side of [t.left, t.right]) for (const [p, q] of segments(side)) plate(b, p, q, centre, t.top - rise - 0.2, t.top + 0.05, 0.04);
} else if (cfg.build === "mono") {
const s = 0.07;
b.block({ x: [centre[0] - s, centre[0] + s], y: [t.top - rise - 0.12, t.top - thick], z: [centre[1] - s, centre[1] + s] }, M.metal);
}
});
}
function rails(b: Builder, cfg: StairConfig, treads: Tread[]): void {
const sides: ("left" | "right")[] = cfg.rail === "both" ? ["left", "right"] : cfg.rail === "none" ? [] : [cfg.rail];
for (const side of sides) {
const nodes: [number, number, number][] = [];
for (const t of treads) for (const p of t[side]) nodes.push([p[0], t.top + RAIL_HEIGHT, p[1]]);
// a post at the start of every second tread and of the top one (one per tread is a fence on a spiral)
for (const [i, t] of treads.entries()) {
if (i % 2 && i !== treads.length - 1) continue;
const p = t[side][0];
b.cylinder(p[0], p[1], 0.012, t.top, t.top + RAIL_HEIGHT, M.metal, 6);
}
for (let i = 1; i < nodes.length; i++) {
const [p, q] = [nodes[i - 1], nodes[i]];
b.seg(p[0], p[1], p[2], q[0], q[1], q[2], EDGE_GLOW);
b.seg(p[0], p[1] - RAIL_HEIGHT * 0.55, p[2], q[0], q[1] - RAIL_HEIGHT * 0.55, q[2], EDGE_FAINT);
}
}
}
/** Draws a shaped stair of size w × d that climbs h (or goes down h, then everything lies below the floor). */
export function shapedStairs(b: Builder, item: { stair?: Partial<StairConfig> | null }, w: number, d: number, h: number): void {
const cfg = stairConfig(item);
const layout = stairLayout(cfg, w, d, h);
const floor = cfg.down ? -h : 0;
if (layout.column > 0) b.cylinder(0, 0, layout.column, Math.min(0, floor), cfg.down ? 0 : h, M.metal, 12, EDGE_FURN);
treadsAndBody(b, cfg, layout.treads, layout.rise, floor);
rails(b, cfg, layout.treads);
}
@@ -0,0 +1,92 @@
// Energy and building technology: inverters, batteries, wallboxes, meters, the grid cabinet.
import { Builder } from "./builder.ts";
import { EDGE_FAINT, EDGE_FURN, EDGE_GLOW, M } from "./palette.ts";
/**
* A solar inverter on the wall (from 1.1 m): a flat box with a display and a status line. "slim" is a tall narrow one with a
* vertical light strip, "hybrid" one with a round dial and two fans below.
*/
export function inverter(b: Builder, w: number, d: number, h: number, variant: string | null): void {
const y0 = 1.1;
const z = d / 2;
const housing = (side: typeof M.white) => b.block({ x: [-w / 2, w / 2], y: [y0, y0 + h], z: [-d / 2, d / 2] }, side, EDGE_FURN);
if (variant === "slim") {
housing(M.darkBody);
b.seg(-w * 0.25, y0 + h * 0.15, z + 0.004, -w * 0.25, y0 + h * 0.85, z + 0.004, EDGE_GLOW);
b.block({ x: [-w * 0.1, w * 0.3], y: [y0 + h * 0.7, y0 + h * 0.85], z: [z, z + 0.005] }, M.dark);
return;
}
housing(M.white);
if (variant === "hybrid") {
b.ring(0, y0 + h * 0.66, Math.min(w, h) * 0.22, z + 0.004, 20, EDGE_GLOW);
b.seg(-w * 0.08, y0 + h * 0.66, z + 0.005, w * 0.08, y0 + h * 0.66, z + 0.005, EDGE_GLOW);
for (const s of [-1, 1]) b.ring(s * w * 0.22, y0 + h * 0.2, Math.min(w, h) * 0.1, -d / 2 - 0.002, 12, EDGE_GLOW);
return;
}
b.block({ x: [-w * 0.28, w * 0.28], y: [y0 + h * 0.58, y0 + h * 0.82], z: [d / 2, d / 2 + 0.006] }, M.dark);
b.seg(-w * 0.3, y0 + h * 0.45, d / 2 + 0.004, w * 0.3, y0 + h * 0.45, d / 2 + 0.004, EDGE_GLOW);
// cooling fins at the sides
for (const s of [-1, 1]) for (let i = 1; i < 6; i++) b.seg((s * w) / 2 + s * 0.002, y0 + (h * i) / 6, -d / 2 + 0.03, (s * w) / 2 + s * 0.002, y0 + (h * i) / 6, d / 2 - 0.03, EDGE_FAINT);
}
/** The grid connection at the edge of the plot: a small dark street cabinet with a glowing lid edge. */
export function gridCabinet(b: Builder, w: number, d: number, h: number): void {
b.block({ x: [-w / 2, w / 2], y: [0, h], z: [-d / 2, d / 2] }, M.darkBody, EDGE_FURN);
b.block({ x: [-w / 2 - 0.01, w / 2 + 0.01], y: [h, h + 0.03], z: [-d / 2 - 0.01, d / 2 + 0.01] }, M.darkBody);
b.seg(-w / 2, h + 0.032, d / 2 + 0.01, w / 2, h + 0.032, d / 2 + 0.01, EDGE_GLOW);
b.seg(-w * 0.3, h * 0.55, d / 2 + 0.003, w * 0.3, h * 0.55, d / 2 + 0.003, EDGE_FAINT);
}
/** A wallbox (from 1.0 m): a compact box with a glowing ring and the charging cable hanging below. */
export function wallbox(b: Builder, w: number, d: number, h: number): void {
const y0 = 1;
b.block({ x: [-w / 2, w / 2], y: [y0, y0 + h], z: [-d / 2, d / 2] }, M.darkBody, EDGE_FURN);
b.ring(0, y0 + h * 0.58, Math.min(w, h) * 0.28, d / 2 + 0.003, 16, EDGE_GLOW);
// the cable below the box, and its holster
b.block({ x: [-0.015, 0.015], y: [y0 - 0.35, y0], z: [d / 2 - 0.03, d / 2] }, M.dark);
b.block({ x: [-0.06, 0.06], y: [y0 - 0.42, y0 - 0.35], z: [d / 2 - 0.05, d / 2] }, M.darkBody);
}
/** A meter cabinet on the wall (from 0.4 m): a tall box with the meter window and the glowing pulse LED. */
export function meterCabinet(b: Builder, w: number, d: number, h: number): void {
const y0 = 0.4;
b.block({ x: [-w / 2, w / 2], y: [y0, y0 + h], z: [-d / 2, d / 2] }, M.white, EDGE_FURN);
// the door's edge and handle
b.seg(-w / 2 + 0.025, y0 + 0.025, d / 2 + 0.003, -w / 2 + 0.025, y0 + h - 0.025, d / 2 + 0.003, EDGE_FAINT);
b.seg(-w / 2 + 0.025, y0 + h - 0.025, d / 2 + 0.003, w / 2 - 0.025, y0 + h - 0.025, d / 2 + 0.003, EDGE_FAINT);
b.block({ x: [w / 2 - 0.06, w / 2 - 0.035], y: [y0 + h * 0.5 - 0.05, y0 + h * 0.5 + 0.05], z: [d / 2, d / 2 + 0.012] }, M.dark);
// the meter behind its window, with the display line
b.block({ x: [-w * 0.3, w * 0.3], y: [y0 + h * 0.6, y0 + h * 0.8], z: [d / 2, d / 2 + 0.005] }, M.dark);
b.seg(-w * 0.22, y0 + h * 0.7, d / 2 + 0.008, w * 0.22, y0 + h * 0.7, d / 2 + 0.008, EDGE_GLOW);
}
/**
* A home battery: a tower of stacked modules with a charge bar. "wall" is a flat battery hanging at hip height with a light
* bar, "cube" a compact box (a balcony battery) with a light bar and a handle.
*/
export function homeBattery(b: Builder, w: number, d: number, h: number, variant: string | null): void {
if (variant === "wall") {
const y0 = 0.5;
b.block({ x: [-w / 2, w / 2], y: [y0, y0 + h], z: [-d / 2, d / 2] }, M.white, EDGE_FURN);
b.seg(-w * 0.3, y0 + h * 0.9, d / 2 + 0.004, w * 0.3, y0 + h * 0.9, d / 2 + 0.004, EDGE_GLOW);
b.seg(-w * 0.3, y0 + h * 0.08, d / 2 + 0.003, w * 0.3, y0 + h * 0.08, d / 2 + 0.003, EDGE_FAINT);
return;
}
if (variant === "cube") {
b.block({ x: [-w / 2 + 0.01, w / 2 - 0.01], y: [0, 0.03], z: [-d / 2 + 0.01, d / 2 - 0.01] }, M.dark);
b.block({ x: [-w / 2, w / 2], y: [0.03, h], z: [-d / 2, d / 2] }, M.darkBody, EDGE_FURN);
b.seg(-w * 0.35, h * 0.85, d / 2 + 0.004, w * 0.35, h * 0.85, d / 2 + 0.004, EDGE_GLOW);
b.block({ x: [-w * 0.15, w * 0.15], y: [h, h + 0.025], z: [-0.012, 0.012] }, M.dark);
return;
}
b.block({ x: [-w / 2 + 0.02, w / 2 - 0.02], y: [0, 0.06], z: [-d / 2 + 0.02, d / 2 - 0.02] }, M.dark);
const modules = Math.max(2, Math.round((h - 0.06) / 0.3));
const height = (h - 0.06) / modules;
for (let i = 0; i < modules; i++) b.block({ x: [-w / 2, w / 2], y: [0.06 + i * height + 0.004, 0.06 + (i + 1) * height], z: [-d / 2, d / 2] }, M.white, EDGE_FURN);
// the charge bar: five short segments
for (let k = 0; k < 5; k++) {
const y = 0.06 + h * 0.18 + k * ((h - 0.3) / 5);
b.seg(-w * 0.04, y, d / 2 + 0.003, w * 0.04, y, d / 2 + 0.003, EDGE_GLOW);
}
}
@@ -0,0 +1,34 @@
import assert from "node:assert/strict";
import { test } from "node:test";
import { GeoBuffer, LineBuffer } from "../geo.ts";
import { pushFurniture, tiltBuilt } from "./furniture.ts";
import type { Furniture } from "../../model.ts";
const piece = (extra: Partial<Furniture> = {}): Furniture => ({ id: "t", type: "table", x: 2, z: 3, rotation: 0, w: 1.6, d: 0.8, h: 0.75, variant: null, ...extra });
const topOf = (buf: GeoBuffer) => Math.max(...buf.p.filter((_, i) => i % 3 === 1));
test("without a tilt nothing moves; a tilt about the width axis leans the top towards the front", () => {
const upright = new GeoBuffer();
pushFurniture(upright, new LineBuffer(), new GeoBuffer(), piece());
const same = new GeoBuffer();
pushFurniture(same, new LineBuffer(), new GeoBuffer(), piece({ tilt_x: 0, tilt_z: null }));
assert.deepEqual(same.p, upright.p);
const leaning = new GeoBuffer();
pushFurniture(leaning, new LineBuffer(), new GeoBuffer(), piece({ tilt_x: 30 }));
assert.notDeepEqual(leaning.p, upright.p);
const zs = (b: GeoBuffer) => b.p.filter((_, i) => i % 3 === 2);
assert.ok(Math.max(...zs(leaning)) - Math.min(...zs(leaning)) > Math.max(...zs(upright)) - Math.min(...zs(upright)) - 1e-9 || topOf(leaning) < topOf(upright), "its top is no longer straight above its base");
assert.ok(Math.abs(topOf(leaning) - topOf(upright)) > 0.01, "the height changed");
});
test("tilting turns about the middle of the underside and keeps lengths", () => {
const buf = new GeoBuffer();
const lines = new LineBuffer();
buf.p.push(2, 0, 3, 3, 0, 3, 2, 1, 3);
lines.p.push(2, 1, 3, 2, 0, 3);
tiltBuilt(buf, lines, { vertex: 0, line: 0 }, { x: 2, z: 3, rotation: 0, tilt_x: 0, tilt_z: 90 }, 0);
// a roll of 90° about the depth axis (z) lays the up direction onto the width direction: (2,1,3) → (1,0,3)
assert.ok(Math.abs(buf.p[6] - 1) < 1e-9 && Math.abs(buf.p[7]) < 1e-9 && Math.abs(buf.p[8] - 3) < 1e-9, `${buf.p.slice(6, 9)}`);
assert.ok(Math.abs(lines.p[0] - 1) < 1e-9, "lines turn with the geometry");
assert.deepEqual(buf.p.slice(0, 3), [2, 0, 3], "the pivot stays");
});
+7
View File
@@ -0,0 +1,7 @@
// Geometry primitives for walls, furniture and opening parts: merged vertex-coloured buffers with a per-vertex fold value
// (see build.ts), line buffers, cutting at a height, and shapes. Split into modules in geo/.
export { DEG, EDGE_BASE, EDGE_CUT, EDGE_SOFT, EDGE_TOP, shade } from "./geo/colors.ts";
export { ALWAYS, CAP_OFFSET, CUT_OFFSET, FURN_OFFSET, GeoBuffer, LineBuffer, LOWER_OFFSET, PAINT_OFFSET } from "./geo/buffers.ts";
export { cutAbove, cutLinesAbove } from "./geo/cut.ts";
export { pushLoft, pushLyingCyl, pushPrism, pushSkin, triangulate, type PrismOptions } from "./geo/shapes.ts";
+90
View File
@@ -0,0 +1,90 @@
// Growing vertex buffers for merged geometry. Every vertex carries a colour and a "fold" value that tells the shader when
// to hide it (see build.ts).
import { BufferGeometry, Color, Float32BufferAttribute } from "three";
import { EDGE_TOP } from "./colors.ts";
/** Fold value of geometry that is always shown. */
export const ALWAYS = -1;
/** Fold kinds: the value is kind * 16 + bucket (see build.ts). */
export const CUT_OFFSET = 16;
export const LOWER_OFFSET = 32;
export const CAP_OFFSET = 48;
/** The part of tall furniture above the cut height: it folds away with the walls. */
export const FURN_OFFSET = 64;
/** Added to the fold value of painted wall parts (solid wall view): the shader shows their own colour in every look. */
export const PAINT_OFFSET = 128;
const attribute = (values: number[], size: number) => new Float32BufferAttribute(values, size);
export class GeoBuffer {
/** Positions, colours (three numbers per vertex), and one fold value per vertex. */
p: number[] = [];
c: number[] = [];
f: number[] = [];
/** Texture coordinates; only kept when asked for. */
uv: number[] | null;
/** The pattern atlas tile per vertex (floors only). */
tile: number[] | null;
constructor(uvs = false, tiles = false) {
this.uv = uvs ? [] : null;
this.tile = tiles ? [] : null;
}
/** Adds a triangle. Without uvs it points at an empty spot of the texture. */
tri(a: number[], b: number[], c: number[], ca: Color, cb: Color = ca, cc: Color = ca, uv?: number[], fold = ALWAYS, tile: [number, number] = [0, 1]): void {
this.p.push(...a, ...b, ...c);
for (const color of [ca, cb, cc]) this.c.push(color.r, color.g, color.b);
this.f.push(fold, fold, fold);
this.uv?.push(...(uv ?? [0.5, 0.5, 0.5, 0.5, 0.5, 0.5]));
this.tile?.push(...tile, ...tile, ...tile);
}
/** The number of triangles. */
get count(): number {
return this.p.length / 9;
}
geometry(): BufferGeometry {
const geometry = new BufferGeometry();
geometry.setAttribute("position", attribute(this.p, 3));
geometry.setAttribute("color", attribute(this.c, 3));
geometry.setAttribute("fold", attribute(this.f, 1));
if (this.uv) geometry.setAttribute("uv", attribute(this.uv, 2));
if (this.tile) geometry.setAttribute("tile", attribute(this.tile, 2));
geometry.computeBoundingSphere();
return geometry;
}
}
export class LineBuffer {
p: number[] = [];
c: number[] = [];
f: number[] = [];
seg(a: number[], b: number[], color: Color = EDGE_TOP, fold = ALWAYS): void {
this.p.push(...a, ...b);
this.c.push(color.r, color.g, color.b, color.r, color.g, color.b);
this.f.push(fold, fold);
}
/** A vertical or sloped segment split at the cut height: below it always shown, above it with the bucket (negative bucket: never split). */
segSplit(a: number[], b: number[], color: Color, cut: number, bucket: number): void {
const [low, high] = a[1] <= b[1] ? [a, b] : [b, a];
if (high[1] <= cut + 1e-6 || bucket < 0) return this.seg(low, high, color, ALWAYS);
if (low[1] >= cut - 1e-6) return this.seg(low, high, color, bucket);
const t = (cut - low[1]) / (high[1] - low[1]);
const middle = [low[0] + (high[0] - low[0]) * t, cut, low[2] + (high[2] - low[2]) * t];
this.seg(low, middle, color, ALWAYS);
this.seg(middle, high, color, bucket);
}
geometry(): BufferGeometry {
const geometry = new BufferGeometry();
geometry.setAttribute("position", attribute(this.p, 3));
geometry.setAttribute("color", attribute(this.c, 3));
geometry.setAttribute("fold", attribute(this.f, 1));
return geometry;
}
}
+30
View File
@@ -0,0 +1,30 @@
// Colours and the fake light of the 3D scene.
import { Color } from "three";
import type { Vec2 } from "../../model.ts";
export const DEG = Math.PI / 180;
/** A colour scaled by k, each channel capped at 1 (Color.multiplyScalar alone can overflow). */
export function shade(hex: number, k: number): Color {
const c = new Color(hex).multiplyScalar(k);
return c.setRGB(Math.min(1, c.r), Math.min(1, c.g), Math.min(1, c.b));
}
/** Edge lines are added on top of the scene, so their colours are pre-scaled to the strength they should end up at. */
export const EDGE_TOP = shade(0x37e0ff, 0.95);
export const EDGE_CUT = shade(0x37e0ff, 1);
export const EDGE_SOFT = shade(0x5b7cff, 0.34);
export const EDGE_BASE = shade(0x5b7cff, 0.22);
/** The direction (x, z) the fake light comes from: faces turned towards it come out a bit brighter. */
export const LIGHT: Vec2 = [-0.55, 0.83];
/** Brightness of a wall side by height: dark at the foot (baked occlusion), full from 1.6 m up. */
export const heightShade = (y: number): number => 0.5 + 0.5 * Math.min(1, Math.max(0, y / 1.6));
/** How strongly a vertical face along (dx, dz) is lit, between 0.8 and 1.08. Neighbouring faces differ a little, so they separate. */
export function sideLight(dx: number, dz: number): number {
const length = Math.hypot(dx, dz);
return 0.8 + 0.28 * (((dz / length) * LIGHT[0] - (dx / length) * LIGHT[1] + 1) / 2);
}
+106
View File
@@ -0,0 +1,106 @@
// Cutting finished buffers at a height: what lies above the cut gets another fold value, so it can fold away.
import type { GeoBuffer, LineBuffer } from "./buffers.ts";
const EPS = 1e-6;
/** One vertex read back from a buffer. */
interface Vertex {
p: number[];
c: number[];
uv: number[] | null;
tile: number[] | null;
}
const blend = (a: number[], b: number[], t: number) => a.map((x, i) => x + (b[i] - x) * t);
/** The point where an edge crosses the height `cut`; colours and uvs are interpolated. */
function crossing(a: Vertex, b: Vertex, cut: number): Vertex {
const t = (cut - a.p[1]) / (b.p[1] - a.p[1]);
return { p: blend(a.p, b.p, t), c: blend(a.c, b.c, t), uv: a.uv && b.uv ? blend(a.uv, b.uv, t) : null, tile: a.tile };
}
function readVertex(buf: GeoBuffer, v: number): Vertex {
return {
p: buf.p.slice(v * 3, v * 3 + 3),
c: buf.c.slice(v * 3, v * 3 + 3),
uv: buf.uv ? buf.uv.slice(v * 2, v * 2 + 2) : null,
tile: buf.tile ? buf.tile.slice(v * 2, v * 2 + 2) : null,
};
}
function overwriteTriangle(buf: GeoBuffer, tri: number, corners: Vertex[], fold: number): void {
corners.forEach((corner, k) => {
const v = tri * 3 + k;
corner.p.forEach((x, i) => (buf.p[v * 3 + i] = x));
corner.c.forEach((x, i) => (buf.c[v * 3 + i] = x));
if (buf.uv && corner.uv) corner.uv.forEach((x, i) => (buf.uv![v * 2 + i] = x));
if (buf.tile && corner.tile) corner.tile.forEach((x, i) => (buf.tile![v * 2 + i] = x));
buf.f[v] = fold;
});
}
function appendTriangle(buf: GeoBuffer, corners: Vertex[], fold: number): void {
for (const corner of corners) {
buf.p.push(...corner.p);
buf.c.push(...corner.c);
buf.f.push(fold);
buf.uv?.push(...(corner.uv ?? [0.5, 0.5]));
buf.tile?.push(...(corner.tile ?? [0, 1]));
}
}
/**
* Cuts the triangles from `fromTri` on at the height `cut`: pieces above get `fold`, pieces below keep theirs, and a
* triangle across the plane is split. New triangles go to the end of the buffer, so the range stays contiguous.
* Meant for tall furniture in the cut view.
*/
export function cutAbove(buf: GeoBuffer, fromTri: number, cut: number, fold: number): void {
const total = buf.count;
for (let tri = fromTri; tri < total; tri++) {
const corners = [0, 1, 2].map((k) => readVertex(buf, tri * 3 + k));
const isAbove = corners.map((v) => v.p[1] > cut + EPS);
const isBelow = corners.map((v) => v.p[1] < cut - EPS);
if (!isAbove.some(Boolean)) continue;
if (!isBelow.some(Boolean)) {
for (let k = 0; k < 3; k++) buf.f[tri * 3 + k] = fold;
continue;
}
const kept = buf.f[tri * 3];
const upCount = isAbove.filter(Boolean).length;
// rotate so the odd vertex out comes first, keeping the cyclic order (and so the winding)
const odd = upCount === 1 ? isAbove.indexOf(true) : isAbove.indexOf(false);
const [a, b, c] = [corners[odd], corners[(odd + 1) % 3], corners[(odd + 2) % 3]];
const onAB = crossing(a, b, cut);
const onCA = crossing(c, a, cut);
// the small triangle at the odd vertex goes on the side it lies on, the quad (two triangles) on the other
const [small, quad] = upCount === 1 ? [fold, kept] : [kept, fold];
overwriteTriangle(buf, tri, [a, onAB, onCA], small);
appendTriangle(buf, [onAB, b, c], quad);
appendTriangle(buf, [onAB, c, onCA], quad);
}
}
/** The same for edge lines: segments from `fromSeg` on are split at the cut height, and the upper part gets `fold`. */
export function cutLinesAbove(lines: LineBuffer, fromSeg: number, cut: number, fold: number): void {
const total = lines.p.length / 6;
for (let s = fromSeg; s < total; s++) {
const a = lines.p.slice(s * 6, s * 6 + 3);
const b = lines.p.slice(s * 6 + 3, s * 6 + 6);
const [low, high] = a[1] <= b[1] ? [a, b] : [b, a];
if (high[1] <= cut + EPS) continue;
if (low[1] >= cut - EPS) {
lines.f[s * 2] = fold;
lines.f[s * 2 + 1] = fold;
continue;
}
const t = (cut - low[1]) / (high[1] - low[1]);
const middle = [low[0] + (high[0] - low[0]) * t, cut, low[2] + (high[2] - low[2]) * t];
const color = lines.c.slice(s * 6, s * 6 + 3);
// the lower part stays in place, the upper part is appended
lines.p.splice(s * 6, 6, ...low, ...middle);
lines.p.push(...middle, ...high);
lines.c.push(...color, ...color);
lines.f.push(fold, fold);
}
}
+163
View File
@@ -0,0 +1,163 @@
import assert from "node:assert/strict";
import { test } from "node:test";
import { Color } from "three";
import type { Vec2 } from "../../model.ts";
import { ALWAYS, FURN_OFFSET, GeoBuffer, LineBuffer } from "./buffers.ts";
import { heightShade, shade, sideLight } from "./colors.ts";
import { cutAbove, cutLinesAbove } from "./cut.ts";
import { pushLoft, pushLyingCyl, pushPrism, pushSkin, triangulate } from "./shapes.ts";
const grey = new Color(0x808080);
const heights = (buf: GeoBuffer) => Array.from({ length: buf.p.length / 3 }, (_, v) => buf.p[v * 3 + 1]);
const square: Vec2[] = [[0, 0], [2, 0], [2, 2], [0, 2]];
test("a triangle adds three vertices with their colours and fold values", () => {
const buf = new GeoBuffer();
buf.tri([0, 0, 0], [1, 0, 0], [0, 0, 1], grey, new Color(1, 0, 0));
assert.equal(buf.count, 1);
assert.equal(buf.p.length, 9);
assert.deepEqual(buf.f, [ALWAYS, ALWAYS, ALWAYS]);
assert.equal(buf.c[3], 1, "the second corner's own red");
assert.equal(buf.uv, null);
});
test("uvs and tiles are only kept when asked for, and show up in the geometry", () => {
const buf = new GeoBuffer(true, true);
buf.tri([0, 0, 0], [1, 0, 0], [0, 0, 1], grey, grey, grey, [0, 0, 1, 0, 0, 1], 5, [2, 3]);
const g = buf.geometry();
assert.ok(g.getAttribute("uv") && g.getAttribute("tile") && g.getAttribute("fold"));
assert.equal(g.getAttribute("position").count, 3);
assert.deepEqual(buf.tile, [2, 3, 2, 3, 2, 3]);
assert.equal(new GeoBuffer().geometry().getAttribute("uv"), undefined);
});
test("shading never exceeds 1 per channel, and light and height change the brightness", () => {
const bright = shade(0xffffff, 3);
assert.deepEqual([bright.r, bright.g, bright.b], [1, 1, 1]);
assert.ok(heightShade(0) < heightShade(0.8) && heightShade(0.8) < heightShade(1.6));
assert.equal(heightShade(5), heightShade(1.6));
const faces = [sideLight(1, 0), sideLight(0, 1), sideLight(-1, 0), sideLight(0, -1)];
assert.ok(Math.max(...faces) <= 1.08 + 1e-9 && Math.min(...faces) >= 0.8 - 1e-9);
assert.ok(new Set(faces.map((f) => f.toFixed(3))).size > 1, "faces in different directions differ");
});
test("line segments are split at the cut height only when they cross it", () => {
const lines = new LineBuffer();
lines.segSplit([0, 0, 0], [0, 3, 0], grey, 1, 7);
assert.equal(lines.f.length, 4);
assert.deepEqual(lines.f, [ALWAYS, ALWAYS, 7, 7]);
lines.segSplit([0, 0, 0], [0, 0.5, 0], grey, 1, 7);
assert.deepEqual(lines.f.slice(4), [ALWAYS, ALWAYS], "wholly below: always shown");
lines.segSplit([0, 2, 0], [1, 2, 0], grey, 1, 7);
assert.deepEqual(lines.f.slice(6), [7, 7], "wholly above: the bucket");
lines.segSplit([0, 0, 0], [0, 3, 0], grey, 1, -1);
assert.deepEqual(lines.f.slice(8), [ALWAYS, ALWAYS], "a negative bucket never splits");
});
test("cutAbove: pieces above get the fold, a crossing triangle is split, the rest is left alone", () => {
const buf = new GeoBuffer();
buf.tri([0, 0, 0], [1, 0, 0], [1, 0.5, 0], grey); // below
buf.tri([0, 2, 0], [1, 2, 0], [1, 2.5, 0], grey); // above
buf.tri([0, 0, 0], [1, 0, 0], [1, 2, 0], grey); // one corner above
buf.tri([0, 2, 0], [1, 2, 0], [1, 0, 0], grey); // two corners above
cutAbove(buf, 0, 1.2, FURN_OFFSET);
assert.deepEqual(buf.f.slice(0, 3), [ALWAYS, ALWAYS, ALWAYS]);
assert.deepEqual(buf.f.slice(3, 6), [FURN_OFFSET, FURN_OFFSET, FURN_OFFSET]);
assert.equal(buf.count, 4 + 2 + 2, "each crossing triangle became three");
heights(buf).forEach((y, v) => {
if (buf.f[v] === FURN_OFFSET) assert.ok(y >= 1.2 - 1e-9, `upper vertex at ${y}`);
else assert.ok(y <= 1.2 + 1e-9, `lower vertex at ${y}`);
});
});
test("cutAbove keeps colours and uvs along the new edge", () => {
const buf = new GeoBuffer(true);
buf.tri([0, 0, 0], [0, 2, 0], [1, 0, 0], new Color(0, 0, 0), new Color(1, 1, 1), new Color(0, 0, 0), [0, 0, 0, 1, 1, 0]);
cutAbove(buf, 0, 1, 64);
const cutVertex = Array.from({ length: buf.count * 3 }, (_, v) => v).find((v) => Math.abs(buf.p[v * 3 + 1] - 1) < 1e-9 && buf.p[v * 3] === 0)!;
assert.ok(Math.abs(buf.c[cutVertex * 3] - 0.5) < 1e-9, "halfway colour");
assert.ok(Math.abs(buf.uv![cutVertex * 2 + 1] - 0.5) < 1e-9, "halfway uv");
});
test("cutAbove only touches triangles from the given one on", () => {
const buf = new GeoBuffer();
buf.tri([0, 2, 0], [1, 2, 0], [1, 3, 0], grey);
buf.tri([0, 2, 0], [1, 2, 0], [1, 3, 0], grey);
cutAbove(buf, 1, 1, 64);
assert.deepEqual(buf.f, [ALWAYS, ALWAYS, ALWAYS, 64, 64, 64]);
});
test("cutLinesAbove splits a vertical edge at the cut and leaves low ones alone", () => {
const lines = new LineBuffer();
lines.seg([0, 0, 0], [0, 2, 0]);
lines.seg([0, 0, 0], [1, 0, 0]);
lines.seg([0, 2, 0], [1, 2, 0]);
cutLinesAbove(lines, 0, 1.2, FURN_OFFSET);
assert.equal(lines.p.length / 6, 4);
assert.deepEqual(lines.p.slice(0, 6), [0, 0, 0, 0, 1.2, 0]);
assert.deepEqual(lines.f, [ALWAYS, ALWAYS, ALWAYS, ALWAYS, FURN_OFFSET, FURN_OFFSET, FURN_OFFSET, FURN_OFFSET]);
assert.deepEqual(lines.p.slice(18, 24), [0, 1.2, 0, 0, 2, 0]);
});
test("triangulating a square gives two triangles, with a hole it gives more", () => {
assert.equal(triangulate(square).length, 2);
const hole: Vec2[] = [[0.5, 0.5], [0.5, 1.5], [1.5, 1.5], [1.5, 0.5]];
assert.ok(triangulate(square, [hole]).length > 4);
});
test("a prism has a top, four sides of two triangles each, and optionally a bottom", () => {
const plain = new GeoBuffer();
pushPrism(plain, square, 0, 1, 0x888888, 0xcccccc);
assert.equal(plain.count, 2 + 8);
const closed = new GeoBuffer();
pushPrism(closed, square, 0, 1, 0x888888, 0xcccccc, { bottom: true });
assert.equal(closed.count, 2 + 8 + 2);
const open = new GeoBuffer();
pushPrism(open, square, 0, 1, 0x888888, 0xcccccc, { topFace: false });
assert.equal(open.count, 8);
});
test("a prism's top can follow a height function and its sides can be skipped or folded", () => {
const sloped = new GeoBuffer();
pushPrism(sloped, square, 0, (x) => 1 + x, 0x888888, 0xcccccc);
assert.equal(Math.max(...heights(sloped)), 3);
const skipped = new GeoBuffer();
pushPrism(skipped, square, 0, 1, 0x888888, 0xcccccc, { skipSide: (a, b) => a[1] === 0 && b[1] === 0 });
assert.equal(skipped.count, 2 + 6);
const folded = new GeoBuffer();
pushPrism(folded, square, 0, 1, 0x888888, 0xcccccc, { fold: 20, topFold: 33 });
assert.ok(folded.f.includes(33) && folded.f.includes(20));
});
test("a prism with a hole gets inner sides facing the hole", () => {
const hole: Vec2[] = [[0.5, 0.5], [1.5, 0.5], [1.5, 1.5], [0.5, 1.5]];
const buf = new GeoBuffer();
pushPrism(buf, square, 0, 1, 0x888888, 0xcccccc, { holes: [hole] });
assert.ok(buf.count > 2 + 8 + 8 - 1);
});
test("a loft has sloped sides and a top of the smaller rectangle", () => {
const buf = new GeoBuffer();
pushLoft(buf, square, [[0.5, 0.5], [1.5, 0.5], [1.5, 1.5], [0.5, 1.5]], 0, 1, 0x888888, 0xcccccc);
assert.equal(buf.count, 8 + 2);
const flatTop = new GeoBuffer();
pushLoft(flatTop, square, square.map(([x, z]) => [x, z] as Vec2), 0, 1, 0x888888, 0xcccccc);
assert.equal(flatTop.count, 8 + 2);
});
test("a skin joins rings into a closed body", () => {
const ring = (z: number, r: number) => [0, 1, 2, 3, 4, 5].map((i) => [Math.cos((i / 6) * 6.2832) * r, 1 + Math.sin((i / 6) * 6.2832) * r, z]);
const buf = new GeoBuffer();
pushSkin(buf, [ring(0, 0.5), ring(1, 0.8), ring(2, 0.5)], 0x888888, 0xcccccc);
assert.equal(buf.count, 2 * 6 * 2 + 2 * 6);
const none = new GeoBuffer();
pushSkin(none, [ring(0, 1)], 0x888888, 0xcccccc);
assert.equal(none.count, 0);
});
test("a lying cylinder has n sides of two triangles and n triangles per end cap", () => {
const buf = new GeoBuffer();
pushLyingCyl(buf, (along, across) => [along, across], 0, 1, 0, 0.5, 0.5, 0x333333, 0x666666, 8);
assert.equal(buf.count, 8 * 2 + 8 * 2);
assert.ok(Math.max(...heights(buf)) <= 1 + 1e-9 && Math.min(...heights(buf)) >= -1e-9);
});
+192
View File
@@ -0,0 +1,192 @@
// Solid shapes pushed into a buffer: prisms, lofts, smooth skins and lying cylinders.
import { Color, ShapeUtils, Vector2 } from "three";
import type { Vec2 } from "../../model.ts";
import { ALWAYS, type GeoBuffer } from "./buffers.ts";
import { heightShade, LIGHT, shade, sideLight } from "./colors.ts";
/** The signed area of a ring in (x, z), doubled: positive when counter-clockwise. */
const ringArea = (ring: Vec2[]): number => ring.reduce((sum, p, i) => sum + p[0] * ring[(i + 1) % ring.length][1] - ring[(i + 1) % ring.length][0] * p[1], 0);
const toVector = ([x, z]: Vec2) => new Vector2(x, z);
/** Triangles (index triples into the outline followed by the holes) that fill a polygon with holes. */
export function triangulate(outline: Vec2[], holes: Vec2[][] = []): number[][] {
return ShapeUtils.triangulateShape(outline.map(toVector), holes.map((h) => h.map(toVector)));
}
type Rgb3 = number[];
const subtract = (a: Rgb3, b: Rgb3): Rgb3 => [a[0] - b[0], a[1] - b[1], a[2] - b[2]];
const crossProduct = (a: Rgb3, b: Rgb3): Rgb3 => [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]];
const dotProduct = (a: Rgb3, b: Rgb3): number => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
const normalized = (a: Rgb3): Rgb3 => {
const length = Math.hypot(a[0], a[1], a[2]) || 1;
return [a[0] / length, a[1] / length, a[2] / length];
};
/**
* A box whose top rectangle differs from its bottom one (sloped sides). `lo` and `hi` are the four corners in the same
* order. Faces that lean upwards blend towards the top colour.
*/
export function pushLoft(buf: GeoBuffer, lo: Vec2[], hi: Vec2[], y0: number, y1: number, side: number, top: number): void {
const topColor = new Color(top);
for (let i = 0; i < 4; i++) {
const [a, b] = [lo[i], lo[(i + 1) % 4]];
const [A, B] = [hi[i], hi[(i + 1) % 4]];
const [dx, dz] = [b[0] - a[0], b[1] - a[1]];
const length = Math.hypot(dx, dz);
if (length < 1e-6) continue;
// how far the face leans back: its top edge moved inwards (the outward normal is (dz, -dx))
const lean = ((A[0] + B[0] - a[0] - b[0]) / 2) * (-dz / length) + ((A[1] + B[1] - a[1] - b[1]) / 2) * (dx / length);
const blendUp = Math.max(0, Math.min(1, lean / Math.max(1e-6, Math.hypot(lean, y1 - y0))));
const light = sideLight(dx, dz);
const lower = shade(side, heightShade(y0) * light).lerp(topColor, blendUp);
const upper = shade(side, heightShade(y1) * light).lerp(topColor, blendUp);
buf.tri([a[0], y0, a[1]], [A[0], y1, A[1]], [B[0], y1, B[1]], lower, upper, upper);
buf.tri([a[0], y0, a[1]], [B[0], y1, B[1]], [b[0], y0, b[1]], lower, upper, lower);
}
const [h0, h1, h2, h3] = hi;
if (Math.hypot(h2[0] - h0[0], h2[1] - h0[1]) > 1e-4) {
buf.tri([h0[0], y1, h0[1]], [h2[0], y1, h2[1]], [h1[0], y1, h1[1]], topColor);
buf.tri([h0[0], y1, h0[1]], [h3[0], y1, h3[1]], [h2[0], y1, h2[1]], topColor);
}
}
/**
* A smooth body: `rings` are cross sections along it (the same number of points each, going round the section), joined
* into a skin with a shade per point taken from its own surface direction, so curves look round. Both ends are closed.
* The winding follows from the geometry, so mirrored items need no extra care.
*/
export function pushSkin(buf: GeoBuffer, rings: number[][][], side: number, top: number): void {
const count = rings.length;
if (count < 2) return;
const around = rings[0].length;
const topColor = new Color(top);
const centres = rings.map((ring) => [0, 1, 2].map((k) => ring.reduce((sum, p) => sum + p[k], 0) / around));
// an outward normal for every point of every ring
const normals = rings.map((ring, s) =>
ring.map((p, i) => {
const lengthways = subtract(rings[Math.min(count - 1, s + 1)][i], rings[Math.max(0, s - 1)][i]);
const roundAbout = subtract(ring[(i + 1) % around], ring[(i + around - 1) % around]);
const normal = normalized(crossProduct(lengthways, roundAbout));
return dotProduct(normal, subtract(p, centres[s])) < 0 ? normal.map((v) => -v) : normal;
}),
);
const colorAt = (p: Rgb3, normal: Rgb3) => {
const lit = (normal[0] * LIGHT[0] + normal[2] * LIGHT[1] + 1) / 2;
return shade(side, heightShade(p[1]) * (0.8 + 0.28 * lit)).lerp(topColor, Math.max(0, normal[1]) * 0.9);
};
// a triangle turned so that it faces `outward` (the average outward normal)
const faceOut = (a: Rgb3, b: Rgb3, c: Rgb3, outward: Rgb3, ca: Color, cb: Color, cc: Color) => {
if (dotProduct(crossProduct(subtract(b, a), subtract(c, a)), outward) >= 0) buf.tri(a, b, c, ca, cb, cc);
else buf.tri(a, c, b, ca, cc, cb);
};
for (let s = 0; s + 1 < count; s++) {
for (let i = 0; i < around; i++) {
const j = (i + 1) % around;
const corners = [rings[s][i], rings[s][j], rings[s + 1][j], rings[s + 1][i]];
const cornerNormals = [normals[s][i], normals[s][j], normals[s + 1][j], normals[s + 1][i]];
const [ca, cb, cc, cd] = corners.map((p, k) => colorAt(p, cornerNormals[k]));
const outward = [0, 1, 2].map((k) => cornerNormals.reduce((sum, n) => sum + n[k], 0));
faceOut(corners[0], corners[1], corners[2], outward, ca, cb, cc);
faceOut(corners[0], corners[2], corners[3], outward, ca, cc, cd);
}
}
// close both ends with a fan around the centre
for (const [s, direction] of [[0, -1], [count - 1, 1]] as const) {
const ring = rings[s];
const lengthways = subtract(rings[s === 0 ? 1 : count - 2][0], ring[0]);
const outward = normalized(lengthways.map((v) => v * -direction));
const color = colorAt(centres[s], outward);
for (let i = 0; i < around; i++) faceOut(ring[i], ring[(i + 1) % around], centres[s], outward, color, color, color);
}
}
/**
* A cylinder lying along the x or z axis (wheels, rollers, pipes). `at` maps an along-axis value and an across value to
* world (x, z); `c` is the centre across, `cy` the centre height, `n` the number of sides.
*/
export function pushLyingCyl(buf: GeoBuffer, at: (along: number, across: number) => Vec2, a0: number, a1: number, c: number, cy: number, r: number, side: number, cap: number, n: number): void {
const capColor = new Color(cap);
const round = Array.from({ length: n }, (_, i) => {
const angle = (i / n) * Math.PI * 2;
return { y: cy + Math.cos(angle) * r, across: c + Math.sin(angle) * r };
});
const point = (along: number, i: number): Rgb3 => {
const { y, across } = round[i % n];
const [x, z] = at(along, across);
return [x, y, z];
};
for (let i = 0; i < n; i++) {
const color = shade(side, 0.62 + 0.4 * Math.max(0, Math.cos(((i + 0.5) / n) * Math.PI * 2)));
buf.tri(point(a0, i), point(a1, i + 1), point(a1, i), color);
buf.tri(point(a0, i), point(a0, i + 1), point(a1, i + 1), color);
}
for (const along of [a0, a1]) {
const [x, z] = at(along, c);
for (let i = 0; i < n; i++) buf.tri([x, cy, z], point(along, i), point(along, i + 1), capColor);
}
}
export interface PrismOptions {
/** Height from which the baked darkening towards the floor starts (default: the bottom). */
aoFrom?: number;
fold?: number;
topFold?: number;
bottom?: boolean;
topFace?: boolean;
/** Cut-outs in the area: their rings are turned so the inner sides face the hole. */
holes?: Vec2[][];
skipSide?: (a: Vec2, b: Vec2) => boolean;
/** The colour of each side face instead of `side` (painted walls: each face in the colour of the room it faces). */
sideColor?: (a: Vec2, b: Vec2) => number;
}
/**
* A vertical prism over a counter-clockwise polygon. The side colours darken towards the floor (baked occlusion) and
* vary slightly with the direction the face points to. The top can follow a height function (a wall ending under a roof
* slope), which stays flat for a wall piece inside one roof plane.
*/
export function pushPrism(buf: GeoBuffer, poly: Vec2[], y0: number, y1: number | ((x: number, z: number) => number), side: number, top: number, opts: PrismOptions = {}): void {
const topAt = typeof y1 === "number" ? () => y1 : (p: Vec2) => Math.max(y0 + 0.002, y1(p[0], p[1]));
const aoFrom = opts.aoFrom ?? y0;
const fold = opts.fold ?? ALWAYS;
const occlusion = (y: number) => heightShade(y - aoFrom);
const holes = (opts.holes ?? []).map((h) => (ringArea(h) > 0 ? [...h].reverse() : h));
const corners = holes.length ? [...poly, ...holes.flat()] : poly;
const withTop = opts.topFace !== false;
const triangles = !withTop && !opts.bottom ? [] : triangulate(poly, holes);
if (withTop) {
const color = new Color(top);
for (const [i, j, k] of triangles) {
// the polygon is counter-clockwise in (x, z), which is clockwise seen from above (+y): swap two corners
const [a, b, c] = [corners[i], corners[j], corners[k]];
buf.tri([a[0], topAt(a), a[1]], [c[0], topAt(c), c[1]], [b[0], topAt(b), b[1]], color, color, color, undefined, opts.topFold ?? fold);
}
}
if (opts.bottom) {
const color = shade(side, 0.55);
for (const [i, j, k] of triangles) {
const [a, b, c] = [corners[i], corners[j], corners[k]];
buf.tri([a[0], y0, a[1]], [b[0], y0, b[1]], [c[0], y0, c[1]], color, color, color, undefined, fold);
}
}
for (const ring of [poly, ...holes]) {
ring.forEach((a, i) => {
const b = ring[(i + 1) % ring.length];
if (Math.hypot(b[0] - a[0], b[1] - a[1]) < 1e-6 || opts.skipSide?.(a, b)) return;
const light = sideLight(b[0] - a[0], b[1] - a[1]);
const [ya, yb] = [topAt(a), topAt(b)];
const own = opts.sideColor ? opts.sideColor(a, b) : side;
const foot = shade(own, occlusion(y0) * light);
const headA = shade(own, occlusion(ya) * light);
const headB = shade(own, occlusion(yb) * light);
buf.tri([a[0], y0, a[1]], [a[0], ya, a[1]], [b[0], yb, b[1]], foot, headA, headB, undefined, fold);
buf.tri([a[0], y0, a[1]], [b[0], yb, b[1]], [b[0], y0, b[1]], foot, headB, foot, undefined, fold);
});
}
}
+26
View File
@@ -0,0 +1,26 @@
import assert from "node:assert/strict";
import { test } from "node:test";
import { recolorLamps, shadeFactors } from "./lamp-colors.ts";
test("sentinel vertices become shade factors, body vertices stay at 0", () => {
// two triangles: a shaded side (factor 0.7), a top (factor 1), a body vertex and a dark body vertex
const colors = [0, 0.7, 0, 0, 1, 0, 0.16, 0.22, 0.38, 0, 0, 0, 0.04, 0.1, 0.2, 0, 0.55, 0];
const f = shadeFactors(colors);
assert.deepEqual([...f].map((v) => Math.round(v * 100) / 100), [0.7, 1, 0, 0, 0, 0.55]);
});
test("recolouring writes the light's colour times the factor into the lamp's range only", () => {
const colors = new Float32Array([0, 0.5, 0, 0, 1, 0, 0.1, 0.1, 0.1, 0, 1, 0, 0, 1, 0, 0, 1, 0]);
const factors = shadeFactors(colors);
// range in triangles: the first triangle (vertices 0..2) belongs to the lamp, the second to another
recolorLamps(colors, factors, { start: 0, end: 1 }, [1, 0.5, 0.2]);
assert.deepEqual([...colors.slice(0, 3)].map((v) => Math.round(v * 100) / 100), [0.5, 0.25, 0.1]);
assert.deepEqual([...colors.slice(3, 6)].map((v) => Math.round(v * 100) / 100), [1, 0.5, 0.2]);
// the body vertex keeps its colour
assert.deepEqual([...colors.slice(6, 9)].map((v) => Math.round(v * 100) / 100), [0.1, 0.1, 0.1]);
// the other lamp is untouched
assert.deepEqual([...colors.slice(9, 12)], [0, 1, 0]);
// channels never exceed 1
recolorLamps(colors, factors, { start: 1, end: 2 }, [1.5, 1.2, 1]);
assert.deepEqual([...colors.slice(9, 12)], [1, 1, 1]);
});
+27
View File
@@ -0,0 +1,27 @@
// Lamp shades are built with a sentinel colour, so the colour of the light can be written into the
// merged lamp mesh later without rebuilding it (colour effects change several times per second).
/** Pure green: no body colour has r = b = 0, so sentinel vertices are told apart by that. */
export const SHADE_SENTINEL = 0x00ff00;
/** Shade factor per vertex: the green channel of sentinel-coloured vertices (r = b = 0), else 0. */
export function shadeFactors(colors: ArrayLike<number>): Float32Array {
const n = colors.length / 3;
const out = new Float32Array(n);
for (let v = 0; v < n; v++) {
const g = colors[v * 3 + 1];
if (colors[v * 3] === 0 && colors[v * 3 + 2] === 0 && g > 0) out[v] = g;
}
return out;
}
/** Write a shade colour into a lamp's triangle range, scaled by each vertex's factor; bodies stay. */
export function recolorLamps(colors: Float32Array, factors: Float32Array, range: { start: number; end: number }, color: [number, number, number]): void {
for (let v = range.start * 3; v < range.end * 3; v++) {
const f = factors[v];
if (f <= 0) continue;
colors[v * 3] = Math.min(1, color[0] * f);
colors[v * 3 + 1] = Math.min(1, color[1] * f);
colors[v * 3 + 2] = Math.min(1, color[2] * f);
}
}
+5
View File
@@ -0,0 +1,5 @@
// Room lighting without real-time lights, split into modules in lighting/: the surface the light is painted on, and the
// light that falls on it.
export { buildLightSurface, type LightSurface } from "./lighting/surface.ts";
export { lightColors, roomIndexAt, zoneOf, type LightKind, type LightSource } from "./lighting/light.ts";
+125
View File
@@ -0,0 +1,125 @@
// The light itself: how much light a lamp sends to a point, and the colours of the light surface for a set of lamps.
import { pointInPolygon, type Floor } from "../../model.ts";
import type { LightSurface } from "./surface.ts";
/** How a lamp spreads its light. */
export type LightKind = "omni" | "ceiling" | "spot" | "pendant" | "up" | "wall";
export interface LightSource {
x: number;
y: number;
z: number;
/** Linear colour, 0..1 per channel. */
color: [number, number, number];
/** Brightness, 0..1. */
level: number;
kind: LightKind;
/** The index of the room (floor.rooms) the lamp is in. */
room: number;
}
/** The share of its light a lamp sends in a direction; dy is the vertical part of the unit vector from the lamp to the point. */
function characteristic(kind: LightKind, dy: number): number {
const down = Math.max(0, -dy);
const up = Math.max(0, dy);
switch (kind) {
case "ceiling":
return 0.3 + 0.7 * down;
case "spot":
return 0.06 + 0.94 * down ** 5;
case "pendant":
return 0.25 + 0.85 * down ** 2 + 0.2 * up;
case "up":
return 0.25 + 0.75 * up;
case "wall":
return 0.45 + 0.35 * Math.abs(dy);
default:
return 1;
}
}
/** The distance at which a lamp's light has fallen to half. */
function reachOf(lamp: { level: number; kind: LightKind }): number {
const base = lamp.kind === "spot" ? 2 : lamp.kind === "wall" ? 1.4 : 2.4;
return base * (0.55 + 0.45 * lamp.level);
}
type Triple = readonly [number, number, number];
/** The brightness one lamp gives a surface point with a normal. */
function contribution(lamp: LightSource, at: Triple, normal: Triple): number {
const [dx, dy, dz] = [at[0] - lamp.x, at[1] - lamp.y, at[2] - lamp.z];
const squared = dx * dx + dy * dy + dz * dz;
const distance = Math.sqrt(squared) || 1e-6;
const reach = reachOf(lamp);
// a squared falloff keeps a bright pool under the lamp and dark corners: the neon look lives on contrast
const falloff = 1 / (1 + squared / (reach * reach));
const attenuation = falloff * Math.sqrt(falloff);
// surfaces facing the lamp get more light; a floor right below a lamp faces it fully
const facing = Math.max(0, -(dx * normal[0] + dy * normal[1] + dz * normal[2]) / distance);
return lamp.level * attenuation * (0.2 + 0.8 * facing) * characteristic(lamp.kind, dy / distance);
}
/** Light a room passes on through an open door: the doorway acts as a lamp for the room on the other side. */
function lampsThroughDoors(surface: LightSurface, sources: LightSource[], doorOpen: number[]): LightSource[] {
const passed: LightSource[] = [];
surface.doors.forEach((door, i) => {
const open = doorOpen[i] ?? 0.5;
if (open <= 0.01) return;
for (const [from, to] of [[door.a, door.b], [door.b, door.a]]) {
const sum: [number, number, number] = [0, 0, 0];
for (const lamp of sources.filter((s) => s.room === from)) {
// the doorway takes the light as if it faced the lamp
const toLamp: Triple = [lamp.x - door.x, lamp.y - door.y, lamp.z - door.z];
const length = Math.hypot(...toLamp) || 1;
const k = contribution(lamp, [door.x, door.y, door.z], [toLamp[0] / length, toLamp[1] / length, toLamp[2] / length]);
for (let c = 0; c < 3; c++) sum[c] += lamp.color[c] * k;
}
const level = Math.max(...sum);
if (level < 0.01) continue;
passed.push({ x: door.x, y: door.y, z: door.z, color: [sum[0] / level, sum[1] / level, sum[2] / level], level: Math.min(1, level * 0.9 * (0.35 + 0.65 * open)), kind: "wall", room: to });
}
});
return passed;
}
/**
* The colours (r, g, b per vertex) of the light surface for the lamps. A lamp lights its own room; through a door a room
* passes on part of the light that reaches the doorway (`doorOpen` is 0..1 per door index, default half open).
*/
export function lightColors(surface: LightSurface, sources: LightSource[], strength = 0.7, doorOpen: number[] = []): Float32Array {
const lampsByRoom = new Map<number, LightSource[]>();
for (const lamp of [...sources, ...lampsThroughDoors(surface, sources, doorOpen)]) {
// warm light stays warm on the blue floor
const curved = { ...lamp, color: lamp.color.map((v) => v ** 1.5) as [number, number, number] };
lampsByRoom.set(lamp.room, [...(lampsByRoom.get(lamp.room) ?? []), curved]);
}
const { pos, normal, room } = surface;
const colors = new Float32Array(pos.length);
for (let v = 0; v < room.length; v++) {
const lamps = lampsByRoom.get(room[v]);
if (!lamps) continue;
const i = v * 3;
const sum = [0, 0, 0];
for (const lamp of lamps) {
const k = contribution(lamp, [pos[i], pos[i + 1], pos[i + 2]], [normal[i], normal[i + 1], normal[i + 2]]);
for (let c = 0; c < 3; c++) sum[c] += lamp.color[c] * k;
}
// soft saturation: several lamps add up without clipping to flat white
for (let c = 0; c < 3; c++) colors[i + c] = 1 - Math.exp(-sum[c] * strength * 1.6);
}
return colors;
}
/** The index of the room a point lies in; outside every room it is the outside zone (rooms.length). */
export function roomIndexAt(floor: Floor, x: number, z: number): number {
const index = floor.rooms.findIndex((r) => r.points.length >= 3 && pointInPolygon([x, z], r.points));
return index < 0 ? floor.rooms.length : index;
}
/**
* The light zone a room index belongs to. Indices past the zone list (the outside zone, rooms.length) and -1 keep their
* own number, so outdoor lamps still light the lawn when rooms are joined.
*/
export const zoneOf = (zones: number[] | null, room: number): number => (zones && room >= 0 && room < zones.length ? zones[room] : room);
@@ -0,0 +1,126 @@
import assert from "node:assert/strict";
import { test } from "node:test";
import { newFloor, type Floor, type Opening, type Room } from "../../model.ts";
import { buildFloorGeometry } from "../build.ts";
import { lightColors, roomIndexAt, zoneOf, type LightSource } from "./light.ts";
import { buildLightSurface, type LightSurface } from "./surface.ts";
const room = (id: string, x0: number, z0: number, x1: number, z1: number): Room => ({ id, name: id, area_id: null, points: [[x0, z0], [x1, z0], [x1, z1], [x0, z1]], floor_material: "wood" });
const door = (id: string, roomId: string, edge: number, offset: number): Opening =>
({ id, room_id: roomId, edge, offset, width: 0.9, type: "door", sill: 0, height: 2.05, hinge: "left", leaves: 1, swing: "in", cover: null, contact: null, contact2: null, tilt: null }) as Opening;
function surfaceOf(floor: Floor, cell = 0.5, holes: [number, number][][] = []): LightSurface {
const geometry = buildFloorGeometry(floor, 0.3, 0.1);
return buildLightSurface(floor, geometry.walls2d, geometry.wallBuckets, geometry.openings, cell, holes);
}
const lamp = (x: number, z: number, color: [number, number, number], roomIndex = 0, extra: Partial<LightSource> = {}): LightSource => ({ x, y: 2.4, z, color, level: 1, kind: "ceiling", room: roomIndex, ...extra });
/** The colour of the floor vertex nearest to (x, z). */
function floorColor(surface: LightSurface, colors: Float32Array, x: number, z: number): number[] {
let best = -1;
let bestDistance = Infinity;
for (let v = 0; v < surface.room.length; v++) {
if (surface.normal[v * 3 + 1] !== 1) continue;
const distance = Math.hypot(surface.pos[v * 3] - x, surface.pos[v * 3 + 2] - z);
if (distance < bestDistance) [best, bestDistance] = [v, distance];
}
return [colors[best * 3], colors[best * 3 + 1], colors[best * 3 + 2]];
}
const quadCount = (s: LightSurface) => s.room.length / 6;
const floorQuads = (s: LightSurface) => [...Array(quadCount(s)).keys()].filter((q) => s.normal[q * 18 + 1] === 1).length;
test("the surface covers the floor in cells and puts strips on the room side of the walls", () => {
const floor = { ...newFloor("f", "F", 0), rooms: [room("a", 0, 0, 4, 3)] };
const s = surfaceOf(floor);
assert.equal(floorQuads(s), 8 * 6);
assert.ok(quadCount(s) > floorQuads(s));
assert.ok(s.room.every((r) => r === 0 || r === 1), "room 0 and the outside zone (index 1) only");
assert.equal(s.pos.length, s.room.length * 3);
assert.equal(s.fold.length, s.room.length);
});
test("a floor opening leaves no light under it", () => {
const floor = { ...newFloor("f", "F", 0), rooms: [room("a", 0, 0, 4, 3)] };
const whole = floorQuads(surfaceOf(floor));
const holed = floorQuads(surfaceOf(floor, 0.5, [[[1, 1], [2, 1], [2, 2], [1, 2]]]));
assert.equal(whole - holed, 4);
});
/** The total area of the wall quads (those not facing up). */
function wallArea(s: LightSurface): number {
let area = 0;
for (let t = 0; t < s.room.length / 3; t++) {
if (s.normal[t * 9 + 1] === 1) continue;
const p = (k: number) => [s.pos[t * 9 + k * 3], s.pos[t * 9 + k * 3 + 1], s.pos[t * 9 + k * 3 + 2]];
const [a, b, c] = [p(0), p(1), p(2)];
const [u, v] = [[b[0] - a[0], b[1] - a[1], b[2] - a[2]], [c[0] - a[0], c[1] - a[1], c[2] - a[2]]];
area += 0.5 * Math.hypot(u[1] * v[2] - u[2] * v[1], u[2] * v[0] - u[0] * v[2], u[0] * v[1] - u[1] * v[0]);
}
return area;
}
test("a door leaves a hole in the lit face of its wall: about its width times its height less light surface", () => {
const plain = { ...newFloor("f", "F", 0), rooms: [room("a", 0, 0, 4, 3)] };
const withDoor = { ...plain, openings: [door("d", "a", 0, 1.5)] };
const lost = wallArea(surfaceOf(plain)) - wallArea(surfaceOf(withDoor));
// an exterior wall is lit on both faces, so the door is missing twice
assert.ok(Math.abs(lost - 2 * 0.9 * 2.05) < 0.4, String(lost));
});
test("a lamp lights its own room only, brightest below it, with its own colour", () => {
const floor = { ...newFloor("f", "F", 0), rooms: [room("a", 0, 0, 4, 3), room("b", 6, 0, 10, 3)] };
const s = surfaceOf(floor);
const colors = lightColors(s, [lamp(2, 1.5, [1, 0, 0])]);
const below = floorColor(s, colors, 2, 1.5);
const corner = floorColor(s, colors, 0.3, 0.3);
assert.ok(below[0] > corner[0] && corner[0] > 0);
assert.ok(below[1] === 0 && below[2] === 0, "a red lamp gives red light");
assert.deepEqual(floorColor(s, colors, 8, 1.5), [0, 0, 0], "the other room stays dark");
});
test("lamps add up without exceeding 1", () => {
const floor = { ...newFloor("f", "F", 0), rooms: [room("a", 0, 0, 4, 3)] };
const s = surfaceOf(floor);
const many = Array.from({ length: 12 }, () => lamp(2, 1.5, [1, 1, 1]));
const colors = lightColors(s, many, 1);
assert.ok(Math.max(...colors) < 1 && Math.max(...colors) > 0.9);
const one = lightColors(s, [lamp(2, 1.5, [1, 1, 1])], 1);
assert.ok(floorColor(s, colors, 2, 1.5)[0] > floorColor(s, one, 2, 1.5)[0]);
});
test("the lamp kinds spread differently: a spot is narrow, an up-light points up", () => {
const floor = { ...newFloor("f", "F", 0), rooms: [room("a", 0, 0, 8, 6)] };
const s = surfaceOf(floor);
const spread = (kind: LightSource["kind"]) => {
const colors = lightColors(s, [lamp(4, 3, [1, 1, 1], 0, { kind })]);
return floorColor(s, colors, 4, 3)[0] / floorColor(s, colors, 6.5, 3)[0];
};
assert.ok(spread("spot") > spread("ceiling"));
assert.ok(spread("ceiling") >= spread("omni") * 0.5);
});
test("light leaks into the next room through an open door, not through a closed one", () => {
const floor = { ...newFloor("f", "F", 0), rooms: [room("a", 0, 0, 4, 3), room("b", 4, 0, 8, 3)], openings: [door("d", "a", 1, 1.5)] };
const s = surfaceOf(floor);
assert.equal(s.doors.length, 1);
assert.deepEqual([s.doors[0].a, s.doors[0].b].sort(), [0, 1]);
const sources = [lamp(2, 1.5, [1, 1, 1], 0)];
const closed = floorColor(s, lightColors(s, sources, 0.7, [0]), 6, 1.5);
const open = floorColor(s, lightColors(s, sources, 0.7, [1]), 6, 1.5);
const half = floorColor(s, lightColors(s, sources), 6, 1.5);
assert.equal(closed[0], 0);
assert.ok(open[0] > half[0] && half[0] > 0);
});
test("the room under a point, and the zone a room belongs to", () => {
const floor = { ...newFloor("f", "F", 0), rooms: [room("a", 0, 0, 4, 3), room("b", 4, 0, 8, 3)] };
assert.equal(roomIndexAt(floor, 1, 1), 0);
assert.equal(roomIndexAt(floor, 5, 1), 1);
assert.equal(roomIndexAt(floor, 20, 20), 2, "outside every room: the outside zone");
assert.equal(zoneOf(null, 1), 1);
assert.equal(zoneOf([0, 0], 1), 0, "joined rooms share a zone");
assert.equal(zoneOf([0, 0], 2), 2, "the outside zone keeps its own number");
assert.equal(zoneOf([0, 0], -1), -1);
});
+193
View File
@@ -0,0 +1,193 @@
// The light surface: floors and the room side of wall faces are covered by a fine grid of quads. Every vertex knows its
// room and the direction it faces. The surface is built once per floor plan; the light colours are recomputed when a lamp
// changes (see light.ts).
import type { Wall } from "../../geometry/walls.ts";
import { outdoorStanding, pointInPolygon, type Floor, type Vec2 } from "../../model.ts";
import type { OpeningInfo } from "../build.ts";
import { LOWER_OFFSET } from "../geo.ts";
import { outdoorHoles, outdoorSurface } from "../outdoor.ts";
export interface LightSurface {
/** Vertex positions (x, y, z), six vertices per quad. */
pos: Float32Array;
/** The direction each vertex faces (x, y, z). */
normal: Float32Array;
/** The room index of each vertex. */
room: Int16Array;
/** The fold value of each vertex (see build.ts), so light on walls follows the cut and glass walls. */
fold: Float32Array;
/** Doors between two rooms: light leaks through them. */
doors: { id: string; a: number; b: number; x: number; y: number; z: number }[];
}
/** Floor quads lie this high above the floor, wall quads this far in front of the wall face. */
const FLOOR_LIFT = 0.012;
const FACE_GAP = 0.012;
/** Collects quads (two triangles each) with their attributes. */
function quadCollector() {
const pos: number[] = [];
const normal: number[] = [];
const room: number[] = [];
const fold: number[] = [];
return {
add(a: number[], b: number[], c: number[], d: number[], n: number[], roomIndex: number, foldValue: number) {
for (const v of [a, b, c, a, c, d]) {
pos.push(v[0], v[1], v[2]);
normal.push(n[0], n[1], n[2]);
room.push(roomIndex);
fold.push(foldValue);
}
},
finish: (doors: LightSurface["doors"]): LightSurface => ({ pos: new Float32Array(pos), normal: new Float32Array(normal), room: Int16Array.from(room), fold: new Float32Array(fold), doors }),
};
}
/** Whether a door or window stands on a wall: on its line and running along it. */
function standsOn(wall: Wall, o: OpeningInfo): boolean {
const [dx, dz] = [wall.b[0] - wall.a[0], wall.b[1] - wall.a[1]];
const length = Math.hypot(dx, dz) || 1;
const offLine = Math.abs((o.start[0] - wall.a[0]) * dz - (o.start[1] - wall.a[1]) * dx) / length;
return offLine < 0.02 && Math.abs((o.axis[0] * dx + o.axis[1] * dz) / length) > 0.99;
}
interface Span {
s0: number;
s1: number;
y0: number;
y1: number;
}
/** The areas of doors and windows on a wall: along it (s from wall.a) and in height. */
function openingSpans(wall: Wall, along: Vec2, length: number, openings: OpeningInfo[]): Span[] {
const spans: Span[] = [];
for (const o of openings.filter((candidate) => standsOn(wall, candidate))) {
const s = (o.start[0] - wall.a[0]) * along[0] + (o.start[1] - wall.a[1]) * along[1];
const s0 = o.axis[0] * along[0] + o.axis[1] * along[1] > 0 ? s : s - o.width;
if (s0 > length || s0 + o.width < 0) continue;
spans.push({ s0, s1: s0 + o.width, y0: o.sill - 0.01, y1: o.top + 0.01 });
}
return spans;
}
/** Sorted, de-duplicated break points between `lo` and `hi`, including both ends. */
function breaks(values: number[], lo: number, hi: number): number[] {
const sorted = [lo, hi, ...values.filter((v) => v > lo + 0.005 && v < hi - 0.005)].sort((a, b) => a - b);
return sorted.filter((v, i) => i === 0 || v > sorted[i - 1] + 0.005);
}
/** Floor quads over a polygon, one per grid cell whose centre lies inside it. */
function gridCells(points: Vec2[], cell: number, isOff: (cx: number, cz: number) => boolean = () => false): { a: number; b: number }[] {
const xs = points.map((p) => p[0]);
const zs = points.map((p) => p[1]);
const [x0, z0] = [Math.min(...xs), Math.min(...zs)];
const [columns, rows] = [Math.max(1, Math.ceil((Math.max(...xs) - x0) / cell)), Math.max(1, Math.ceil((Math.max(...zs) - z0) / cell))];
const cells: { a: number; b: number }[] = [];
for (let i = 0; i < columns; i++) {
for (let j = 0; j < rows; j++) {
const [cx, cz] = [x0 + (i + 0.5) * cell, z0 + (j + 0.5) * cell];
if (pointInPolygon([cx, cz], points) && !isOff(cx, cz)) cells.push({ a: x0 + i * cell, b: z0 + j * cell });
}
}
return cells;
}
/**
* Builds the light surface of a floor: a grid of `cell` metres on every room floor, and strips on the room side of every
* wall face, split at the cut height and left out where doors and windows are.
*/
export function buildLightSurface(
floor: Floor,
walls: Wall[],
wallBuckets: number[],
openings: OpeningInfo[],
cell: number,
holes: Vec2[][] = [],
roofUnder?: (x: number, z: number) => number | null,
): LightSurface {
const quads = quadCollector();
const flatQuad = (a: number, b: number, y: number, roomIndex: number) => quads.add([a, y, b], [a, y, b + cell], [a + cell, y, b + cell], [a + cell, y, b], [0, 1, 0], roomIndex, -1);
// room floors; no light over a floor opening, one looks through it
floor.rooms.forEach((room, ri) => {
if (room.points.length < 3) return;
for (const { a, b } of gridCells(room.points, cell, (cx, cz) => holes.some((h) => pointInPolygon([cx, cz], h)))) flatQuad(a, b, FLOOR_LIFT, ri);
});
// outside is one zone (index rooms.length) for all outdoor areas and the outer faces of the walls
const outside = floor.rooms.length;
const areas = floor.outdoor ?? [];
areas.forEach((area, ai) => {
if (area.points.length < 3 || outdoorStanding(area.type)) return;
const y = outdoorSurface(floor, area) + FLOOR_LIFT;
// the patches cut out of an area (a pool in a terrace) carry no light of this area
const holes = outdoorHoles(areas, ai);
for (const { a, b } of gridCells(area.points, cell, (cx, cz) => holes.some((h) => pointInPolygon([cx, cz], h)))) flatQuad(a, b, y, outside);
});
const cut = Math.min(floor.cut_height, floor.height);
walls.forEach((wall, wi) => {
// a sloping wall reaches its higher end here; its lit face is trimmed along the slope below
const slope = wall.heightEnd === undefined ? null : ([wall.height ?? floor.height, wall.heightEnd] as const);
const top = slope ? Math.max(...slope) : (wall.height ?? floor.height);
const cutAt = Math.min(cut, top - 0.02);
const [dx, dz] = [wall.b[0] - wall.a[0], wall.b[1] - wall.a[1]];
const length = Math.hypot(dx, dz);
if (length < 0.05) return;
const along: Vec2 = [dx / length, dz / length];
const leftNormal: Vec2 = [-along[1], along[0]];
const bucket = wallBuckets[wi];
const spans = openingSpans(wall, along, length, openings);
// cells break at the cut and at every sill, top and side of an opening, so the hole a window leaves in the lit face
// matches the window (a cell is lit or dark as a whole)
const heights = breaks([cutAt, (cutAt + top) / 2, ...spans.flatMap((g) => [g.y0 + 0.01, g.y1 - 0.01])], 0.02, top - 0.02);
const stations = breaks(spans.flatMap((g) => [g.s0, g.s1]), 0, length);
for (const side of [1, -1] as const) {
const roomId = side > 0 ? wall.roomLeft : wall.roomRight;
// the outer face of an exterior wall belongs to the outside zone (facade lighting)
const ri = roomId ? floor.rooms.findIndex((r) => r.id === roomId) : wall.exterior ? outside : -1;
if (ri < 0) continue;
const faceDistance = (side > 0 ? wall.left : wall.right) + FACE_GAP;
const normal: Vec2 = [leftNormal[0] * side, leftNormal[1] * side];
const point = (s: number, y: number) => [wall.a[0] + along[0] * s + normal[0] * faceDistance, y, wall.a[1] + along[1] * s + normal[1] * faceDistance];
// under a roof slope the lit face ends where the wall does
const ceilingAt = (s: number) => {
const p = point(s, 0);
const roof = roofUnder?.(p[0], p[2]);
const sloped = slope ? slope[0] + ((slope[1] - slope[0]) * s) / length - 0.02 : Infinity;
return Math.min(sloped, roof == null ? Infinity : roof - 0.02);
};
for (let p = 0; p + 1 < stations.length; p++) {
const span = stations[p + 1] - stations[p];
const steps = Math.max(1, Math.ceil(span / cell));
for (let k = 0; k < steps; k++) {
const s0 = stations[p] + (span / steps) * k;
const s1 = stations[p] + (span / steps) * (k + 1);
for (let h = 0; h + 1 < heights.length; h++) {
const [y0, y1] = [heights[h], heights[h + 1]];
if (y1 - y0 < 0.01) continue;
const [sm, ym] = [(s0 + s1) / 2, (y0 + y1) / 2];
if (spans.some((g) => sm > g.s0 && sm < g.s1 && ym > g.y0 && ym < g.y1)) continue;
const [topA, topB] = [Math.min(y1, ceilingAt(s0)), Math.min(y1, ceilingAt(s1))];
if (topA <= y0 + 0.005 && topB <= y0 + 0.005) continue;
quads.add(point(s0, y0), point(s1, y0), point(s1, Math.max(y0, topB)), point(s0, Math.max(y0, topA)), [normal[0], 0, normal[1]], ri, y0 >= cut - 1e-6 ? bucket : LOWER_OFFSET + bucket);
}
}
}
}
});
// doors between two rooms let light through
const doors: LightSurface["doors"] = [];
for (const o of openings.filter((candidate) => candidate.opening.type === "door")) {
const wall = walls.find((w) => standsOn(w, o));
if (!wall?.roomLeft || !wall.roomRight) continue;
const [a, b] = [floor.rooms.findIndex((r) => r.id === wall.roomLeft), floor.rooms.findIndex((r) => r.id === wall.roomRight)];
if (a < 0 || b < 0) continue;
doors.push({ id: o.opening.id, a, b, x: o.start[0] + o.axis[0] * (o.width / 2), y: Math.min(1.1, o.top * 0.55), z: o.start[1] + o.axis[1] * (o.width / 2) });
}
return quads.finish(doors);
}
+298
View File
@@ -0,0 +1,298 @@
/**
* NextFloor's energy layer: where the power goes, drawn as glowing particles flying in arcs between the
* devices (solar fields, inverter, battery, grid connection, house, consumers), and solar modules that sparkle
* with their production.
*
* Each arc joins two points of the plan (each on its floor, so it follows when the floors are pulled apart). The
* particles fly in the direction the power flows; more power means more and faster particles. A faint line shows
* the arc itself. A connection with a cable route follows its points instead of the arc (a cable shown as such is drawn
* stronger).
*/
import { AdditiveBlending, BufferGeometry, CanvasTexture, Color, Float32BufferAttribute, Group, Line, LineBasicMaterial, Points, PointsMaterial, Vector3, type Scene } from "three";
/** A point of the plan: floor (null = the ground / the roof above the top floor), plan x/z, height above that floor. */
export interface PlanPoint {
floorId: string | null;
x: number;
y: number;
z: number;
}
export interface EnergyArc {
key: string;
from: PlanPoint;
to: PlanPoint;
/** Power carried (W, > 0); the particles fly from `from` to `to`. */
power: number;
/** Particle colour (r, g, b 0…255). */
color: [number, number, number];
/** Where the cable runs between `from` and `to` (the flow follows these points instead of an arc). */
via?: PlanPoint[];
/** The route is drawn as a visible cable. */
cable?: boolean;
}
/** A solar field's modules (corners in building coordinates) and how much it produces right now (0…1). */
export interface SparkField {
floorId: string | null;
quads: [number, number, number][][];
level: number;
}
/** Where a floor is right now: the height of its floor (elevation plus how far it is pulled apart), that pull
* alone (for points given in building heights), and whether it shows. */
export type FloorLift = (floorId: string | null) => { y: number; dy: number; visible: boolean };
const MAX_PER_ARC = 46;
/** Points of an arc's line: the arc's samples, or a route's points (at most 30 between its ends). */
const LINE_POINTS = 33;
const SPARKS = 900;
/** A soft round dot for point sprites (sparks, droplets). */
export function dotTexture(): CanvasTexture {
const c = document.createElement("canvas");
c.width = c.height = 32;
const g = c.getContext("2d")!;
const r = g.createRadialGradient(16, 16, 0, 16, 16, 16);
r.addColorStop(0, "rgba(255,255,255,1)");
r.addColorStop(0.35, "rgba(255,255,255,0.7)");
r.addColorStop(1, "rgba(255,255,255,0)");
g.fillStyle = r;
g.fillRect(0, 0, 32, 32);
return new CanvasTexture(c);
}
interface ArcView {
arc: EnergyArc;
line: Line;
points: Points;
phase: Float32Array;
count: number;
speed: number;
a: Vector3;
b: Vector3;
c: Vector3;
/** A routed arc: its corners in the world and how far along it each one lies; null for an arc. */
path: Vector3[] | null;
along: number[];
}
export class EnergyLayer {
readonly group = new Group();
private readonly scene: Scene;
private readonly lift: FloorLift;
private readonly tex = dotTexture();
private arcs = new Map<string, ArcView>();
private sparkFields: SparkField[] = [];
private readonly sparks: Points;
private readonly sparkBase = new Float32Array(SPARKS * 3);
private readonly sparkField = new Int16Array(SPARKS);
private readonly sparkPhase = new Float32Array(SPARKS);
private sparkCount = 0;
private last = 0;
constructor(scene: Scene, lift: FloorLift) {
this.scene = scene;
this.lift = lift;
this.group.name = "live-energy";
const g = new BufferGeometry();
g.setAttribute("position", new Float32BufferAttribute(new Float32Array(SPARKS * 3), 3));
g.setAttribute("color", new Float32BufferAttribute(new Float32Array(SPARKS * 3), 3));
this.sparks = new Points(g, new PointsMaterial({ size: 0.4, map: this.tex, vertexColors: true, transparent: true, depthWrite: false, blending: AdditiveBlending }));
this.sparks.frustumCulled = false;
this.group.add(this.sparks);
scene.add(this.group);
}
get active(): boolean {
return this.arcs.size > 0 || this.sparkCount > 0;
}
setArcs(list: EnergyArc[]): void {
const keep = new Set(list.map((a) => a.key));
for (const [key, v] of this.arcs) {
if (keep.has(key)) continue;
this.group.remove(v.line, v.points);
v.line.geometry.dispose();
(v.line.material as LineBasicMaterial).dispose();
v.points.geometry.dispose();
(v.points.material as PointsMaterial).dispose();
this.arcs.delete(key);
}
for (const arc of list) {
let v = this.arcs.get(arc.key);
if (!v) {
const lg = new BufferGeometry();
lg.setAttribute("position", new Float32BufferAttribute(new Float32Array(LINE_POINTS * 3), 3));
const line = new Line(lg, new LineBasicMaterial({ transparent: true, opacity: 0.4, depthWrite: false, blending: AdditiveBlending }));
const pg = new BufferGeometry();
pg.setAttribute("position", new Float32BufferAttribute(new Float32Array(MAX_PER_ARC * 3), 3));
const points = new Points(pg, new PointsMaterial({ size: 0.55, map: this.tex, transparent: true, depthWrite: false, blending: AdditiveBlending }));
line.frustumCulled = points.frustumCulled = false;
const phase = new Float32Array(MAX_PER_ARC);
for (let i = 0; i < MAX_PER_ARC; i++) phase[i] = Math.random();
v = { arc, line, points, phase, count: 0, speed: 0, a: new Vector3(), b: new Vector3(), c: new Vector3(), path: null, along: [] };
this.arcs.set(arc.key, v);
this.group.add(line, points);
}
v.arc = arc;
const col = new Color(arc.color[0] / 255, arc.color[1] / 255, arc.color[2] / 255);
(v.line.material as LineBasicMaterial).color.copy(col);
(v.line.material as LineBasicMaterial).opacity = arc.via?.length && arc.cable ? 0.9 : 0.4;
v.path = arc.via?.length ? Array.from({ length: arc.via.length + 2 }, () => new Vector3()) : null;
(v.points.material as PointsMaterial).color.copy(col);
// more power: more particles, a bit faster (a kettle and a heat pump look different, a 10 kW car still fits)
// a cable without power (a car plugged in that does not charge) shows the cable alone
v.count = arc.power <= 0 ? 0 : Math.max(3, Math.min(MAX_PER_ARC, Math.round(3 + Math.sqrt(arc.power) / 2.2)));
v.speed = 0.18 + Math.min(0.5, Math.log10(1 + arc.power) * 0.1);
v.points.geometry.setDrawRange(0, v.count);
}
this.place();
}
setSparks(fields: SparkField[]): void {
this.sparkFields = fields;
// spread the sparks over the modules in proportion to each field's production
const total = fields.reduce((s, f) => s + f.quads.length * f.level, 0);
let n = 0;
if (total > 0) {
fields.forEach((f, fi) => {
if (f.level <= 0) return;
const share = Math.round((SPARKS * f.quads.length * f.level) / Math.max(total, fields.reduce((s, x) => s + x.quads.length, 0)));
for (let k = 0; k < share && n < SPARKS; k++, n++) {
const q = f.quads[Math.floor(Math.random() * f.quads.length)];
const u = Math.random(), w = Math.random();
// a point on the module: bilinear between its corners, a hand above the surface
for (let i = 0; i < 3; i++) {
const top = q[0][i] + (q[1][i] - q[0][i]) * u;
const bot = q[3][i] + (q[2][i] - q[3][i]) * u;
this.sparkBase[n * 3 + i] = top + (bot - top) * w + (i === 1 ? 0.12 : 0);
}
this.sparkField[n] = fi;
this.sparkPhase[n] = Math.random() * Math.PI * 2;
}
});
}
this.sparkCount = n;
this.sparks.geometry.setDrawRange(0, n);
this.sparks.visible = n > 0;
}
/** World position of a plan point right now. */
private world(p: PlanPoint, out: Vector3): boolean {
const l = this.lift(p.floorId);
out.set(p.x, l.y + p.y, p.z);
return l.visible;
}
/** The arcs' start, end and bend for where the floors are now. */
private place(): void {
for (const v of this.arcs.values()) {
if (v.path) {
this.placeRoute(v, v.path);
continue;
}
const va = this.world(v.arc.from, v.a);
const vb = this.world(v.arc.to, v.b);
const len = v.a.distanceTo(v.b);
v.c.copy(v.a).add(v.b).multiplyScalar(0.5);
v.c.y = Math.max(v.a.y, v.b.y) + 0.6 + len * 0.22;
const show = va && vb;
v.line.visible = v.points.visible = show;
const pos = v.line.geometry.getAttribute("position") as Float32BufferAttribute;
for (let i = 0; i < LINE_POINTS; i++) {
const t = i / (LINE_POINTS - 1);
pos.setXYZ(i, ...this.bezier(v, t));
}
v.line.geometry.setDrawRange(0, LINE_POINTS);
pos.needsUpdate = true;
}
}
/** A routed connection: from its start through the route's points to its end; hidden while any of them is on a hidden floor. */
private placeRoute(v: ArcView, path: Vector3[]): void {
const plan = [v.arc.from, ...(v.arc.via ?? []), v.arc.to];
let show = true;
plan.forEach((p, i) => (show = this.world(p, path[i]) && show));
v.line.visible = v.points.visible = show;
v.along = [0];
for (let i = 1; i < path.length; i++) v.along.push(v.along[i - 1] + path[i].distanceTo(path[i - 1]));
const pos = v.line.geometry.getAttribute("position") as Float32BufferAttribute;
path.forEach((p, i) => pos.setXYZ(i, p.x, p.y, p.z));
v.line.geometry.setDrawRange(0, path.length);
pos.needsUpdate = true;
}
/** Where a particle `t` (0…1) of the way along an arc or a route is. */
private at(v: ArcView, t: number): [number, number, number] {
if (!v.path) return this.bezier(v, t);
const total = v.along[v.along.length - 1] || 1;
const s = t * total;
let i = 1;
while (i < v.along.length - 1 && v.along[i] < s) i++;
const [p, q] = [v.path[i - 1], v.path[i]];
const span = v.along[i] - v.along[i - 1] || 1;
const k = Math.max(0, Math.min(1, (s - v.along[i - 1]) / span));
return [p.x + (q.x - p.x) * k, p.y + (q.y - p.y) * k, p.z + (q.z - p.z) * k];
}
private bezier(v: ArcView, t: number): [number, number, number] {
const u = 1 - t;
return [
u * u * v.a.x + 2 * u * t * v.c.x + t * t * v.b.x,
u * u * v.a.y + 2 * u * t * v.c.y + t * t * v.b.y,
u * u * v.a.z + 2 * u * t * v.c.z + t * t * v.b.z,
];
}
/** One frame. True while anything moves. */
step(now: number): boolean {
if (!this.active || !this.group.visible) {
this.last = 0;
return false;
}
const dt = this.last ? Math.min(0.1, (now - this.last) / 1000) : 0;
this.last = now;
this.place();
for (const v of this.arcs.values()) {
if (!v.points.visible) continue;
const pos = v.points.geometry.getAttribute("position") as Float32BufferAttribute;
for (let i = 0; i < v.count; i++) {
v.phase[i] = (v.phase[i] + v.speed * dt) % 1;
pos.setXYZ(i, ...this.at(v, v.phase[i]));
}
pos.needsUpdate = true;
}
if (this.sparkCount) {
const pos = this.sparks.geometry.getAttribute("position") as Float32BufferAttribute;
const col = this.sparks.geometry.getAttribute("color") as Float32BufferAttribute;
const t = now / 1000;
for (let i = 0; i < this.sparkCount; i++) {
const f = this.sparkFields[this.sparkField[i]];
const l = this.lift(f?.floorId ?? null);
// sparks of a hidden floor's field are put far below the ground (dark points would still show)
pos.setXYZ(i, this.sparkBase[i * 3], l.visible ? this.sparkBase[i * 3 + 1] + l.dy : -1000, this.sparkBase[i * 3 + 2]);
// each spark twinkles on its own beat, brighter on a strong field
const tw = Math.max(0, Math.sin(t * 2.4 + this.sparkPhase[i] * 3)) ** 6;
// a field whose floor is hidden (another floor opened) goes dark
const b = l.visible ? (0.15 + 0.85 * tw) * (0.4 + 0.6 * (f?.level ?? 0)) : 0;
col.setXYZ(i, b, b * 0.86, b * 0.35);
}
pos.needsUpdate = true;
col.needsUpdate = true;
}
return true;
}
setVisible(on: boolean): void {
this.group.visible = on;
}
dispose(): void {
this.setArcs([]);
this.sparks.geometry.dispose();
(this.sparks.material as PointsMaterial).dispose();
this.tex.dispose();
this.scene.remove(this.group);
}
}
+108
View File
@@ -0,0 +1,108 @@
/**
* The real map under the plan: map tiles drawn into one canvas and laid on the ground as a dimmed plane, turned by the plan's north.
* The tiles come from a tile server through the browser (plain image requests); nothing is loaded while the map is off.
*/
import { CanvasTexture, DoubleSide, Mesh, MeshBasicMaterial, PlaneGeometry, SRGBColorSpace, type Scene } from "three";
import { mapLook, mapShown, mapTiles, planOfMap, templateOf, tileUrl, type MapTile } from "../map-geo.ts";
import { tileBlob } from "../tiles.ts";
import type { MapSettings } from "../model.ts";
const TILE_PX = 256;
const DEG = Math.PI / 180;
export class MapLayer {
private readonly mesh = new Mesh(new PlaneGeometry(1, 1), new MeshBasicMaterial({ transparent: true, depthWrite: false, side: DoubleSide }));
private canvas: HTMLCanvasElement | null = null;
private texture: CanvasTexture | null = null;
/** What the loaded tiles are for: place, zoom and tile address. */
private key = "";
/** A newer set of tiles makes the pictures of an older one that still arrive be dropped. */
private generation = 0;
/** The centre of the tile grid in the map frame (metres east / north of the anchor). */
private centre: [number, number] = [0, 0];
/** Called when more tiles have arrived, so the view draws again. */
onChange: () => void = () => {};
private readonly scene: Scene;
constructor(scene: Scene) {
this.scene = scene;
this.mesh.rotation.order = "YXZ";
this.mesh.renderOrder = -2;
this.mesh.visible = false;
this.mesh.name = "live-map";
scene.add(this.mesh);
}
/** Shows, moves or hides the map: `y` is the height of the ground, `north` the plan's north in degrees, `brightness` dims the tiles. */
set(map: MapSettings | null | undefined, north: number, y: number, brightness = 1): void {
if (!mapShown(map)) {
this.mesh.visible = false;
this.generation++;
this.key = "";
return;
}
const look = mapLook(map);
const template = templateOf(map);
const key = `${map.lat},${map.lon},${look.zoom},${template}`;
if (key !== this.key) this.load(key, map, look.zoom, template);
const [east, northM] = this.centre;
const [x, z] = planOfMap(east, northM, north, look);
this.mesh.position.set(x, y, z);
// the texture's right is east and its top is north; a plan turned by `north` clockwise turns the plane the other way round about +y
this.mesh.rotation.set(-Math.PI / 2, -north * DEG, 0);
const material = this.mesh.material as MeshBasicMaterial;
material.opacity = look.opacity;
// on the dark themes the pale tiles are dimmed as well, so the neon plan stays the brightest thing
material.color.setScalar(brightness);
this.mesh.visible = this.canvas !== null;
}
private load(key: string, map: MapSettings, zoom: number, template: string): void {
this.key = key;
const generation = ++this.generation;
const tiles = mapTiles(map.lat, map.lon, zoom);
if (!tiles.length) return;
const size = tiles[0].size;
const minEast = Math.min(...tiles.map((t) => t.east));
const maxNorth = Math.max(...tiles.map((t) => t.north));
const columns = Math.round((Math.max(...tiles.map((t) => t.east)) - minEast) / size) + 1;
const rows = Math.round((maxNorth - Math.min(...tiles.map((t) => t.north))) / size) + 1;
const canvas = document.createElement("canvas");
canvas.width = columns * TILE_PX;
canvas.height = rows * TILE_PX;
this.canvas = canvas;
this.texture?.dispose();
this.texture = new CanvasTexture(canvas);
this.texture.colorSpace = SRGBColorSpace;
this.texture.anisotropy = 4;
const material = this.mesh.material as MeshBasicMaterial;
material.map = this.texture;
material.needsUpdate = true;
this.mesh.geometry.dispose();
this.mesh.geometry = new PlaneGeometry(columns * size, rows * size);
this.centre = [minEast + (columns * size) / 2, maxNorth - (rows * size) / 2];
const ctx = canvas.getContext("2d");
if (!ctx) return;
for (const tile of tiles) this.draw(ctx, tile, template, generation, Math.round((tile.east - minEast) / size), Math.round((maxNorth - tile.north) / size));
}
private draw(ctx: CanvasRenderingContext2D, tile: MapTile, template: string, generation: number, col: number, row: number): void {
void tileBlob(tileUrl(template, tile))
.then((blob) => (blob ? createImageBitmap(blob) : null))
.then((bitmap) => {
if (!bitmap || generation !== this.generation) return;
ctx.drawImage(bitmap, col * TILE_PX, row * TILE_PX, TILE_PX, TILE_PX);
if (this.texture) this.texture.needsUpdate = true;
this.onChange();
});
}
dispose(): void {
this.generation++;
this.scene.remove(this.mesh);
this.mesh.geometry.dispose();
(this.mesh.material as MeshBasicMaterial).dispose();
this.texture?.dispose();
}
}
+164
View File
@@ -0,0 +1,164 @@
/**
* Picture frames: an own photo (a stored picture, a URL, an image or camera entity) shown in a frame's picture part, with an
* adjustable white mat around it. The picture is cropped to fill the opening, or fitted whole on the mat.
*/
import { CanvasTexture, Group, Mesh, MeshBasicMaterial, PlaneGeometry, SRGBColorSpace, type Scene } from "three";
import type { FloorLift } from "./live-energy.ts";
export interface LivePicture {
id: string;
floorId: string;
x: number;
z: number;
rotation: number;
/** The picture part in the furniture's frame (x across, y up from the floor, z its front face). */
rect: { x0: number; x1: number; y0: number; y1: number; z: number };
url: string;
/** Mat around the picture in % of the shorter side (0 = none). */
border: number;
/** "contain": the whole picture on the mat; "cover" (default): it fills the opening. */
fit: "cover" | "contain";
}
const DEG = Math.PI / 180;
const MAT = "#f4f1ea";
interface PictureView {
p: LivePicture;
sig: string;
mesh: Mesh;
canvas: HTMLCanvasElement;
texture: CanvasTexture;
image: HTMLImageElement | null;
}
export class PictureLayer {
readonly group = new Group();
private readonly scene: Scene;
private readonly lift: FloorLift;
private views = new Map<string, PictureView>();
/** Called when a picture has loaded (the host renders a frame). */
onChange: (() => void) | null = null;
constructor(scene: Scene, lift: FloorLift) {
this.scene = scene;
this.lift = lift;
this.group.name = "live-pictures";
scene.add(this.group);
}
set(list: LivePicture[]): void {
const keep = new Set(list.map((p) => p.id));
for (const [id, v] of this.views) if (!keep.has(id)) this.drop(id, v);
for (const p of list) {
let v = this.views.get(p.id);
if (!v) {
const canvas = document.createElement("canvas");
const texture = new CanvasTexture(canvas);
texture.colorSpace = SRGBColorSpace;
const mesh = new Mesh(new PlaneGeometry(1, 1), new MeshBasicMaterial({ map: texture, toneMapped: false }));
mesh.renderOrder = 5;
this.group.add(mesh);
v = { p, sig: "", mesh, canvas, texture, image: null };
this.views.set(p.id, v);
}
const urlChanged = v.p.url !== p.url || !v.sig;
v.p = p;
const w = p.rect.x1 - p.rect.x0;
const h = p.rect.y1 - p.rect.y0;
const sig = [p.url, p.border, p.fit, w.toFixed(3), h.toFixed(3)].join("|");
if (sig !== v.sig) {
v.sig = sig;
if (urlChanged) this.load(v);
this.draw(v);
}
this.place(v);
}
}
private load(v: PictureView): void {
v.image = null;
const url = v.p.url;
const img = new Image();
img.crossOrigin = "anonymous";
img.onload = () => {
if (v.p.url !== url || !this.views.has(v.p.id)) return;
v.image = img;
this.draw(v);
this.onChange?.();
};
img.src = url;
}
/** The mat, and the picture cropped (or fitted) into the opening the mat leaves. */
private draw(v: PictureView): void {
const p = v.p;
const w = Math.max(0.01, p.rect.x1 - p.rect.x0);
const h = Math.max(0.01, p.rect.y1 - p.rect.y0);
// about 600 px on the longer side: sharp enough on a wall, light on old tablets
const k = 600 / Math.max(w, h);
const W = (v.canvas.width = Math.max(16, Math.round(w * k)));
const H = (v.canvas.height = Math.max(16, Math.round(h * k)));
const g = v.canvas.getContext("2d")!;
g.fillStyle = p.border > 0 ? MAT : "#20242c";
g.fillRect(0, 0, W, H);
const m = Math.round((Math.min(W, H) * Math.min(40, Math.max(0, p.border))) / 100);
const [ox, oy, ow, oh] = [m, m, W - 2 * m, H - 2 * m];
if (v.image && ow > 4 && oh > 4) {
const iw = v.image.naturalWidth || 1;
const ih = v.image.naturalHeight || 1;
if (p.fit === "contain") {
const s = Math.min(ow / iw, oh / ih);
g.drawImage(v.image, ox + (ow - iw * s) / 2, oy + (oh - ih * s) / 2, iw * s, ih * s);
} else {
const s = Math.max(ow / iw, oh / ih);
const sw = ow / s;
const sh = oh / s;
g.drawImage(v.image, (iw - sw) / 2, (ih - sh) / 2, sw, sh, ox, oy, ow, oh);
}
if (m > 0) {
// a thin shadow line where the mat's bevel would be
g.strokeStyle = "rgba(0,0,0,0.25)";
g.lineWidth = Math.max(1, m * 0.04);
g.strokeRect(ox, oy, ow, oh);
}
} else if (ow > 4 && oh > 4) {
g.fillStyle = "#3a4250";
g.fillRect(ox, oy, ow, oh);
}
v.texture.needsUpdate = true;
}
/** Puts the picture onto the front face of the frame's picture part. */
private place(v: PictureView): void {
const p = v.p;
const r = p.rect;
const a = p.rotation * DEG;
const l = this.lift(p.floorId);
const cx = (r.x0 + r.x1) / 2;
const lz = r.z + 0.004;
v.mesh.position.set(p.x + cx * Math.cos(a) - lz * Math.sin(a), l.y + (r.y0 + r.y1) / 2, p.z + cx * Math.sin(a) + lz * Math.cos(a));
v.mesh.rotation.set(0, -a, 0);
v.mesh.scale.set(r.x1 - r.x0, r.y1 - r.y0, 1);
v.mesh.visible = l.visible;
}
/** Follows the floors as they lift and hide; pictures never animate on their own. */
step(): boolean {
for (const v of this.views.values()) this.place(v);
return false;
}
private drop(id: string, v: PictureView): void {
this.group.remove(v.mesh);
v.mesh.geometry.dispose();
(v.mesh.material as MeshBasicMaterial).dispose();
v.texture.dispose();
this.views.delete(id);
}
dispose(): void {
for (const [id, v] of this.views) this.drop(id, v);
this.scene.remove(this.group);
}
}
+218
View File
@@ -0,0 +1,218 @@
/**
* NextFloor's TV screens: a TV or monitor that plays shows a picture of what runs – the cover art, the title and
* the artist or series, and the app – drawn onto its screen, on a gradient in the app's colour. Behind it an
* ambilight glows on the wall in the same colour, breathing slowly while it plays.
*/
import { AdditiveBlending, CanvasTexture, Color, DoubleSide, Group, Mesh, MeshBasicMaterial, PlaneGeometry, SRGBColorSpace, type Scene } from "three";
import type { FloorLift } from "./live-energy.ts";
export interface LiveScreen {
id: string;
floorId: string;
/** Where the furniture stands and how it is turned (degrees), mirrored or not. */
x: number;
z: number;
rotation: number;
/** The screen's rectangle in the furniture's frame (x across, y up from the floor, z the front face). */
rect: { x0: number; x1: number; y0: number; y1: number; z: number };
color: [number, number, number];
title: string;
subtitle: string;
app: string | null;
picture: string | null;
playing: boolean;
/** Strength of the glow on the wall behind the screen: 1 is the usual, 0 switches it off. */
ambilight?: number;
}
const DEG = Math.PI / 180;
interface ScreenView {
s: LiveScreen;
sig: string;
screen: Mesh;
glow: Mesh;
canvas: HTMLCanvasElement;
texture: CanvasTexture;
image: HTMLImageElement | null;
}
function glowTexture(): CanvasTexture {
const c = document.createElement("canvas");
c.width = c.height = 64;
const g = c.getContext("2d")!;
const r = g.createRadialGradient(32, 32, 4, 32, 32, 32);
r.addColorStop(0, "rgba(255,255,255,0.9)");
r.addColorStop(0.5, "rgba(255,255,255,0.35)");
r.addColorStop(1, "rgba(255,255,255,0)");
g.fillStyle = r;
g.fillRect(0, 0, 64, 64);
return new CanvasTexture(c);
}
export class ScreenLayer {
readonly group = new Group();
private readonly scene: Scene;
private readonly lift: FloorLift;
private readonly glowTex = glowTexture();
private views = new Map<string, ScreenView>();
/** Called when a picture has loaded (the host renders a frame). */
onChange: (() => void) | null = null;
constructor(scene: Scene, lift: FloorLift) {
this.scene = scene;
this.lift = lift;
this.group.name = "live-screens";
scene.add(this.group);
}
get active(): boolean {
return [...this.views.values()].some((v) => v.s.playing);
}
set(list: LiveScreen[]): void {
const keep = new Set(list.map((s) => s.id));
for (const [id, v] of this.views) if (!keep.has(id)) this.drop(id, v);
for (const s of list) {
let v = this.views.get(s.id);
if (!v) {
const canvas = document.createElement("canvas");
canvas.width = 512;
canvas.height = 288;
const texture = new CanvasTexture(canvas);
texture.colorSpace = SRGBColorSpace;
const screen = new Mesh(new PlaneGeometry(1, 1), new MeshBasicMaterial({ map: texture, transparent: true, toneMapped: false }));
screen.renderOrder = 6;
const glow = new Mesh(new PlaneGeometry(1, 1), new MeshBasicMaterial({ map: this.glowTex, transparent: true, depthWrite: false, blending: AdditiveBlending, side: DoubleSide }));
glow.renderOrder = 2;
this.group.add(screen, glow);
v = { s, sig: "", screen, glow, canvas, texture, image: null };
this.views.set(s.id, v);
}
v.s = s;
const sig = [s.title, s.subtitle, s.app, s.picture, s.color.join(","), s.playing].join("|");
if (sig !== v.sig) {
const pictureChanged = v.sig.split("|")[3] !== (s.picture ?? "");
v.sig = sig;
if (pictureChanged) this.loadPicture(v);
this.draw(v);
}
this.place(v);
}
}
private loadPicture(v: ScreenView): void {
v.image = null;
const url = v.s.picture;
if (!url) return;
const img = new Image();
img.crossOrigin = "anonymous";
img.onload = () => {
if (v.s.picture !== url || !this.views.has(v.s.id)) return;
v.image = img;
this.draw(v);
this.onChange?.();
};
img.src = url;
}
/** The screen's picture: a gradient in the app's colour, the cover, title, artist and the app's name. */
private draw(v: ScreenView): void {
const s = v.s;
const g = v.canvas.getContext("2d")!;
const W = v.canvas.width, H = v.canvas.height;
const [r, gr, b] = s.color;
const bg = g.createLinearGradient(0, 0, W, H);
bg.addColorStop(0, `rgb(${Math.round(r * 0.35)},${Math.round(gr * 0.35)},${Math.round(b * 0.35)})`);
bg.addColorStop(1, "rgb(6,9,18)");
g.fillStyle = bg;
g.fillRect(0, 0, W, H);
const pad = 22;
let tx = pad;
if (v.image) {
// the cover, square, on the left, with a soft shadow in the app's colour
const size = H - pad * 2 - 30;
g.save();
g.shadowColor = `rgba(${r},${gr},${b},0.7)`;
g.shadowBlur = 24;
const iw = v.image.naturalWidth || 1, ih = v.image.naturalHeight || 1;
const k = Math.max(size / iw, size / ih);
const sw = size / k, sh = size / k;
g.drawImage(v.image, (iw - sw) / 2, (ih - sh) / 2, sw, sh, pad, pad, size, size);
g.restore();
tx = pad * 2 + size;
}
g.fillStyle = "#ffffff";
g.font = "600 34px Figtree, Roboto, sans-serif";
this.text(g, s.title || s.app || "", tx, H / 2 - 18, W - tx - pad);
g.fillStyle = "rgba(230,240,255,0.75)";
g.font = "26px Figtree, Roboto, sans-serif";
this.text(g, s.subtitle, tx, H / 2 + 22, W - tx - pad);
// the app's name in its colour, and a thin bar in the colour along the bottom
if (s.app) {
g.fillStyle = `rgb(${r},${gr},${b})`;
g.font = "700 22px Figtree, Roboto, sans-serif";
this.text(g, (s.playing ? "▶ " : "❚❚ ") + s.app, tx, H - pad - 14, W - tx - pad);
}
g.fillStyle = `rgba(${r},${gr},${b},0.9)`;
g.fillRect(0, H - 6, W * (s.playing ? 1 : 0.4), 6);
v.texture.needsUpdate = true;
}
private text(g: CanvasRenderingContext2D, text: string, x: number, y: number, max: number): void {
let t = text;
while (t.length > 1 && g.measureText(t).width > max) t = t.slice(0, -2);
g.fillText(t === text ? t : `${t}…`, x, y);
}
/** Puts the picture on the screen's front and the glow on the wall behind the TV. */
private place(v: ScreenView): void {
const s = v.s;
const r = s.rect;
const a = s.rotation * DEG;
const l = this.lift(s.floorId);
const cx = (r.x0 + r.x1) / 2;
const at = (lx: number, lz: number): [number, number] => [s.x + lx * Math.cos(a) - lz * Math.sin(a), s.z + lx * Math.sin(a) + lz * Math.cos(a)];
const w = r.x1 - r.x0, h = r.y1 - r.y0;
const [sx, sz] = at(cx, r.z + 0.012);
v.screen.position.set(sx, l.y + (r.y0 + r.y1) / 2, sz);
v.screen.rotation.set(0, -a, 0);
v.screen.scale.set(w, h, 1);
// the glow sits a little behind the screen, larger than it
const [gx, gz] = at(cx, r.z - 0.18);
v.glow.position.set(gx, l.y + (r.y0 + r.y1) / 2, gz);
v.glow.rotation.set(0, -a, 0);
v.glow.scale.set(w * 2.4, h * 2.6, 1);
(v.glow.material as MeshBasicMaterial).color = new Color(s.color[0] / 255, s.color[1] / 255, s.color[2] / 255);
v.screen.visible = l.visible;
v.glow.visible = l.visible && (s.ambilight ?? 1) > 0;
}
step(now: number): boolean {
let moving = false;
for (const v of this.views.values()) {
this.place(v);
// the ambilight breathes while it plays, and rests dim while paused
const m = v.glow.material as MeshBasicMaterial;
m.opacity = (v.s.playing ? 0.55 + 0.25 * Math.sin(now / 900 + v.s.x) : 0.25) * Math.min(1.5, v.s.ambilight ?? 1);
moving ||= v.s.playing;
}
return moving;
}
private drop(id: string, v: ScreenView): void {
this.group.remove(v.screen, v.glow);
v.screen.geometry.dispose();
(v.screen.material as MeshBasicMaterial).dispose();
v.texture.dispose();
v.glow.geometry.dispose();
(v.glow.material as MeshBasicMaterial).dispose();
this.views.delete(id);
}
dispose(): void {
for (const [id, v] of this.views) this.drop(id, v);
this.glowTex.dispose();
this.scene.remove(this.group);
}
}
+125
View File
@@ -0,0 +1,125 @@
/**
* NextFloor's sound layer: rings of sound spreading from every speaker that plays (in the colour of the app that
* plays, wider and brighter the louder it is), and glowing threads between speakers that play together
* (multiroom groups).
*/
import { AdditiveBlending, BufferGeometry, Color, DoubleSide, Float32BufferAttribute, Group, Line, LineBasicMaterial, Mesh, MeshBasicMaterial, RingGeometry, type Scene } from "three";
import type { FloorLift, PlanPoint } from "./live-energy.ts";
export interface SoundSpot {
id: string;
at: PlanPoint;
/** Ring colour (r, g, b 0…255). */
color: [number, number, number];
/** Volume 0…1. */
level: number;
/** Size of the rings (1 = as usual; a small speaker can have smaller ones). */
size?: number;
}
const RINGS = 3;
interface SpotView {
spot: SoundSpot;
rings: Mesh[];
}
export class SoundLayer {
readonly group = new Group();
private readonly scene: Scene;
private readonly lift: FloorLift;
private readonly ringGeo = new RingGeometry(0.92, 1, 48);
private spots = new Map<string, SpotView>();
private links: { a: PlanPoint; b: PlanPoint; line: Line }[] = [];
constructor(scene: Scene, lift: FloorLift) {
this.scene = scene;
this.lift = lift;
this.group.name = "live-sound";
scene.add(this.group);
}
get active(): boolean {
return this.spots.size > 0;
}
set(spots: SoundSpot[], groups: [PlanPoint, PlanPoint][]): void {
const keep = new Set(spots.map((s) => s.id));
for (const [id, v] of this.spots) {
if (keep.has(id)) continue;
for (const r of v.rings) {
this.group.remove(r);
(r.material as MeshBasicMaterial).dispose();
}
this.spots.delete(id);
}
for (const spot of spots) {
let v = this.spots.get(spot.id);
if (!v) {
const rings = Array.from({ length: RINGS }, () => {
const m = new Mesh(this.ringGeo, new MeshBasicMaterial({ transparent: true, opacity: 0, depthWrite: false, blending: AdditiveBlending, side: DoubleSide }));
m.rotation.x = -Math.PI / 2;
m.frustumCulled = false;
this.group.add(m);
return m;
});
v = { spot, rings };
this.spots.set(spot.id, v);
}
v.spot = spot;
const c = new Color(spot.color[0] / 255, spot.color[1] / 255, spot.color[2] / 255);
for (const r of v.rings) (r.material as MeshBasicMaterial).color.copy(c);
}
for (const l of this.links) {
this.group.remove(l.line);
l.line.geometry.dispose();
(l.line.material as LineBasicMaterial).dispose();
}
this.links = groups.map(([a, b]) => {
const g = new BufferGeometry();
g.setAttribute("position", new Float32BufferAttribute(new Float32Array(17 * 3), 3));
const line = new Line(g, new LineBasicMaterial({ color: 0xc084fc, transparent: true, opacity: 0.55, depthWrite: false, blending: AdditiveBlending }));
line.frustumCulled = false;
this.group.add(line);
return { a, b, line };
});
}
step(now: number): boolean {
if (!this.spots.size && !this.links.length) return false;
const t = now / 1000;
for (const v of this.spots.values()) {
const l = this.lift(v.spot.at.floorId);
const reach = 0.9 + 1.6 * v.spot.level;
v.rings.forEach((r, i) => {
// each ring grows from the speaker and fades, the next one follows a third of a beat later
const k = (t * 0.55 + i / RINGS) % 1;
r.visible = l.visible;
r.position.set(v.spot.at.x, l.y + v.spot.at.y, v.spot.at.z);
r.scale.setScalar((0.25 + k * reach) * (v.spot.size ?? 1));
(r.material as MeshBasicMaterial).opacity = (1 - k) * (0.35 + 0.5 * v.spot.level);
});
}
for (const link of this.links) {
const la = this.lift(link.a.floorId), lb = this.lift(link.b.floorId);
link.line.visible = la.visible && lb.visible;
const pos = link.line.geometry.getAttribute("position") as Float32BufferAttribute;
const ay = la.y + link.a.y, by = lb.y + link.b.y;
const dist = Math.hypot(link.a.x - link.b.x, link.a.z - link.b.z);
for (let i = 0; i <= 16; i++) {
const s = i / 16;
// a soft sag between the two, with a slow shimmer along it
const lift = Math.sin(Math.PI * s) * (0.3 + dist * 0.12) + Math.sin(t * 3 + s * 12) * 0.03;
pos.setXYZ(i, link.a.x + (link.b.x - link.a.x) * s, ay + (by - ay) * s + lift, link.a.z + (link.b.z - link.a.z) * s);
}
pos.needsUpdate = true;
}
return true;
}
dispose(): void {
this.set([], []);
this.ringGeo.dispose();
this.scene.remove(this.group);
}
}
+28
View File
@@ -0,0 +1,28 @@
import assert from "node:assert/strict";
import { test } from "node:test";
import { DROPS, dropAt, JETS } from "./live-water.ts";
test("droplets fly out on arcs within the reach, start at the nozzle and land on its height", () => {
for (let i = 0; i < DROPS; i++) {
for (const t of [0, 0.4, 1.3, 7.9]) {
const [x, y, z] = dropAt(i, t, 3);
assert.ok(Math.hypot(x, z) <= 3 + 1e-9, "inside the reach");
assert.ok(y >= 0 && y <= 1 + 1e-9, "the arc peaks at a third of the reach");
}
}
// a short reach keeps the arc low, a long one at most 1.2 m
assert.ok(Math.max(...Array.from({ length: 50 }, (_, k) => dropAt(0, k / 50 / 0.7, 0.9)[1])) <= 0.3 + 1e-9);
assert.ok(Math.max(...Array.from({ length: 50 }, (_, k) => dropAt(0, k / 50 / 0.7, 12)[1])) <= 1.2 + 1e-9);
});
test("the jets spread all round the sprinkler, each a stream of droplets along one direction", () => {
const angles = Array.from({ length: DROPS }, (_, i) => {
const [x, , z] = dropAt(i, 0.5, 3);
return Math.atan2(z, x);
});
const quadrants = new Set(angles.map((a) => Math.floor(((a + Math.PI) / (Math.PI / 2)) % 4)));
assert.equal(quadrants.size, 4);
// the droplets of one jet point the same way (within a small spread)
const jet0 = angles.filter((_, i) => i % JETS === 0);
assert.ok(Math.max(...jet0) - Math.min(...jet0) < 0.1);
});
+106
View File
@@ -0,0 +1,106 @@
/**
* NextFloor's water layer: lawn sprinklers that water while their valve or switch is on throw droplets in arcs around
* them, turning slowly, as far as the sprinkler reaches. Points only, so a wall tablet keeps up.
*/
import { BufferGeometry, Float32BufferAttribute, Group, Points, PointsMaterial, type Scene } from "three";
import { dotTexture, type FloorLift, type PlanPoint } from "./live-energy.ts";
export interface SpraySpot {
id: string;
at: PlanPoint;
/** How far the water reaches (m). */
reach: number;
}
/** A sprinkler throws its water in a few jets; each jet is a stream of droplets along its arc. */
export const JETS = 6;
const PER_JET = 24;
/** Droplets per sprinkler: enough to read as water, few enough for old tablets. */
export const DROPS = JETS * PER_JET;
interface SprayView {
spot: SpraySpot;
points: Points;
}
/**
* Where droplet `i` of a sprinkler is at time `t` (seconds), relative to the nozzle: droplets follow each other along their
* jet's arc, which peaks at a third of the reach (at most 1.2 m); the jets turn slowly round the sprinkler.
*/
export function dropAt(i: number, t: number, reach: number): [number, number, number] {
const jet = i % JETS;
const k = Math.floor(i / JETS);
const s = (k / PER_JET + t * 0.7) % 1;
// a little spread across the jet, so a stream is not a thin line
const angle = (jet / JETS) * Math.PI * 2 + t * 0.35 + (((k * 7) % 5) - 2) * 0.012;
const d = s * reach;
const peak = Math.min(1.2, reach / 3);
return [Math.cos(angle) * d, 4 * peak * s * (1 - s), Math.sin(angle) * d];
}
export class WaterLayer {
readonly group = new Group();
private readonly scene: Scene;
private readonly lift: FloorLift;
private readonly tex = dotTexture();
private readonly material = new PointsMaterial({ color: 0xa8e2ff, size: 0.09, map: this.tex, transparent: true, opacity: 0.9, depthWrite: false });
private sprays = new Map<string, SprayView>();
constructor(scene: Scene, lift: FloorLift) {
this.scene = scene;
this.lift = lift;
this.group.name = "live-water";
scene.add(this.group);
}
get active(): boolean {
return this.sprays.size > 0;
}
set(spots: SpraySpot[]): void {
const keep = new Set(spots.map((s) => s.id));
for (const [id, v] of this.sprays) {
if (keep.has(id)) continue;
this.group.remove(v.points);
v.points.geometry.dispose();
this.sprays.delete(id);
}
for (const spot of spots) {
const v = this.sprays.get(spot.id);
if (v) {
v.spot = spot;
continue;
}
const g = new BufferGeometry();
g.setAttribute("position", new Float32BufferAttribute(new Float32Array(DROPS * 3), 3));
const points = new Points(g, this.material);
points.frustumCulled = false;
this.group.add(points);
this.sprays.set(spot.id, { spot, points });
}
}
step(now: number): boolean {
if (!this.sprays.size) return false;
const t = now / 1000;
for (const v of this.sprays.values()) {
const l = this.lift(v.spot.at.floorId);
v.points.visible = l.visible;
v.points.position.set(v.spot.at.x, l.y + v.spot.at.y, v.spot.at.z);
const pos = v.points.geometry.getAttribute("position") as Float32BufferAttribute;
for (let i = 0; i < DROPS; i++) {
const [x, y, z] = dropAt(i, t, v.spot.reach);
pos.setXYZ(i, x, y, z);
}
pos.needsUpdate = true;
}
return true;
}
dispose(): void {
this.set([]);
this.material.dispose();
this.tex.dispose();
this.scene.remove(this.group);
}
}
+516
View File
@@ -0,0 +1,516 @@
/**
* NextFloor's weather layer: what the sky does over the plot, drawn into the 3D scene.
*
* - rain as streaks and snow as drifting flakes, falling at an angle along the real wind (direction and strength)
* - a band of clouds on the horizon around the plot, turning slowly with the wind, and their soft shadows
* travelling over the ground and the house (clouds above the house would hide it from the raised camera)
* - fog that thickens with distance
* - lightning: a jagged bolt from the clouds down beside the house, with a short flash of the whole stage
* - the sun by day and the moon by night as a glowing disc in their real direction, paler behind clouds
* - stars on a clear night, and the ground under the house white with snow or dark and wet after rain
*
* Everything sits in one group; the layer only animates while something moves (rain, snow, clouds, a bolt),
* and draws fewer particles on the tablet level.
*/
import {
AdditiveBlending,
BufferGeometry,
CanvasTexture,
Color,
Float32BufferAttribute,
FogExp2,
Group,
LineBasicMaterial,
LineSegments,
Mesh,
MeshBasicMaterial,
NormalBlending,
PlaneGeometry,
Points,
PointsMaterial,
Sprite,
SpriteMaterial,
Vector3,
type Scene,
} from "three";
/** The weather to show, each amount 0…1. */
export interface SkyWeather {
rain: number;
snow: number;
hail: number;
fog: number;
cloud: number;
/** Wind strength 0…1 (about 0 = calm, 1 = storm). */
wind: number;
/** Where the wind comes from, degrees clockwise from north (null = unknown: it blows from the west). */
windFrom: number | null;
lightning: boolean;
}
export interface SkyView {
weather: SkyWeather | null;
/** Sun from sun.sun (null = unknown). */
sun: { elevation: number; azimuth: number } | null;
/** The plan's north (degrees, as in the building settings). */
north: number;
/** Background colour of the stage (fog melts into it). */
sky: [number, number, number];
/** The sun or moon disc shows. */
disc: boolean;
/** Fewer particles (tablet level). */
low: boolean;
}
export interface Bounds {
x0: number;
x1: number;
z0: number;
z1: number;
y0: number;
y1: number;
}
const DEG = Math.PI / 180;
const RAIN_MAX = 2400;
const SNOW_MAX = 1600;
const CLOUDS = 9;
const STARS = 360;
function softTexture(stops: [number, string][], size = 64): CanvasTexture {
const c = document.createElement("canvas");
c.width = c.height = size;
const g = c.getContext("2d")!;
const r = g.createRadialGradient(size / 2, size / 2, 0, size / 2, size / 2, size / 2);
for (const [at, col] of stops) r.addColorStop(at, col);
g.fillStyle = r;
g.fillRect(0, 0, size, size);
return new CanvasTexture(c);
}
/** A cloud: a few overlapping soft blobs, so no two clouds look the same. */
function cloudTexture(seed: number): CanvasTexture {
const size = 128;
const c = document.createElement("canvas");
c.width = size;
c.height = size / 2;
const g = c.getContext("2d")!;
let s = seed * 9301 + 49297;
const rnd = () => ((s = (s * 9301 + 49297) % 233280) / 233280);
for (let i = 0; i < 7; i++) {
const x = size * (0.2 + 0.6 * rnd());
const y = size / 2 * (0.45 + 0.25 * rnd());
const r = size * (0.12 + 0.14 * rnd());
const grad = g.createRadialGradient(x, y, 0, x, y, r);
grad.addColorStop(0, "rgba(255,255,255,0.9)");
grad.addColorStop(0.6, "rgba(255,255,255,0.45)");
grad.addColorStop(1, "rgba(255,255,255,0)");
g.fillStyle = grad;
g.fillRect(0, 0, size, size / 2);
}
return new CanvasTexture(c);
}
interface CloudPuff {
sprite: Sprite;
shadow: Mesh;
/** Place on the horizon ring: angle (radians), distance factor and height factor. */
angle: number;
ring: number;
lift: number;
scale: number;
speed: number;
/** Its shadow on the plot (plan coordinates). */
sx: number;
sz: number;
}
export class WeatherLayer {
readonly group = new Group();
private readonly scene: Scene;
private bounds: Bounds = { x0: -10, x1: 10, z0: -10, z1: 10, y0: 0, y1: 8 };
private view: SkyView | null = null;
private readonly rain: LineSegments;
private readonly rainVel = new Float32Array(RAIN_MAX * 3);
private readonly snow: Points;
private readonly snowPhase = new Float32Array(SNOW_MAX);
private readonly hail: Points;
private readonly clouds: CloudPuff[] = [];
private readonly bolt: LineSegments;
private readonly disc: Sprite;
private readonly halo: Sprite;
private readonly stars: Points;
private readonly cover: Mesh;
private last = 0;
private nextBolt = 0;
private boltUntil = 0;
/** The stage flashes with a bolt (the host listens). */
onFlash: ((on: boolean) => void) | null = null;
constructor(scene: Scene) {
this.scene = scene;
this.group.name = "live-weather";
this.group.renderOrder = 5;
const rg = new BufferGeometry();
rg.setAttribute("position", new Float32BufferAttribute(new Float32Array(RAIN_MAX * 6), 3));
this.rain = new LineSegments(rg, new LineBasicMaterial({ color: 0xa9cdf5, transparent: true, opacity: 0.5, depthWrite: false }));
const flake = softTexture([[0, "rgba(255,255,255,1)"], [0.5, "rgba(255,255,255,0.6)"], [1, "rgba(255,255,255,0)"]], 32);
const sg = new BufferGeometry();
sg.setAttribute("position", new Float32BufferAttribute(new Float32Array(SNOW_MAX * 3), 3));
this.snow = new Points(sg, new PointsMaterial({ color: 0xf6f9ff, size: 0.16, map: flake, transparent: true, opacity: 0.9, depthWrite: false }));
for (let i = 0; i < SNOW_MAX; i++) this.snowPhase[i] = Math.random() * Math.PI * 2;
const hg = new BufferGeometry();
hg.setAttribute("position", new Float32BufferAttribute(new Float32Array(600 * 3), 3));
this.hail = new Points(hg, new PointsMaterial({ color: 0xe9f1ff, size: 0.09, transparent: true, opacity: 0.95, depthWrite: false }));
const shadowTex = softTexture([[0, "rgba(0,0,0,0.55)"], [0.7, "rgba(0,0,0,0.25)"], [1, "rgba(0,0,0,0)"]]);
for (let i = 0; i < CLOUDS; i++) {
const sprite = new Sprite(new SpriteMaterial({ map: cloudTexture(i + 1), transparent: true, opacity: 0, depthWrite: false, fog: false }));
const shadow = new Mesh(new PlaneGeometry(1, 1), new MeshBasicMaterial({ map: shadowTex, transparent: true, opacity: 0, depthWrite: false, blending: NormalBlending }));
shadow.rotation.x = -Math.PI / 2;
shadow.renderOrder = -1;
this.clouds.push({ sprite, shadow, angle: 0, ring: 1, lift: 1, scale: 1, speed: 0.6 + Math.random() * 0.8, sx: 0, sz: 0 });
this.group.add(sprite, shadow);
}
const bg = new BufferGeometry();
bg.setAttribute("position", new Float32BufferAttribute(new Float32Array(24 * 6), 3));
this.bolt = new LineSegments(bg, new LineBasicMaterial({ color: 0xdfe8ff, transparent: true, opacity: 1, blending: AdditiveBlending, depthWrite: false }));
this.bolt.visible = false;
const glow = softTexture([[0, "rgba(255,255,255,1)"], [0.25, "rgba(255,255,255,0.9)"], [0.32, "rgba(255,255,255,0.35)"], [1, "rgba(255,255,255,0)"]]);
this.disc = new Sprite(new SpriteMaterial({ map: glow, transparent: true, depthWrite: false, blending: AdditiveBlending, fog: false }));
this.halo = new Sprite(new SpriteMaterial({ map: softTexture([[0, "rgba(255,255,255,0.35)"], [1, "rgba(255,255,255,0)"]]), transparent: true, depthWrite: false, blending: AdditiveBlending, fog: false }));
// stars on a dome over the plot (unit sphere, scaled to the plot), dimmer towards the horizon
const starAt = new Float32Array(STARS * 3);
for (let i = 0; i < STARS; i++) {
const a = i * 2.39996;
const up = 0.08 + 0.92 * ((i * 0.618034) % 1);
const r = Math.sqrt(1 - up * up);
starAt.set([Math.cos(a) * r, up, Math.sin(a) * r], i * 3);
}
const stg = new BufferGeometry();
stg.setAttribute("position", new Float32BufferAttribute(starAt, 3));
this.stars = new Points(stg, new PointsMaterial({ color: 0xeef3ff, size: 1.6, sizeAttenuation: false, transparent: true, opacity: 0, depthWrite: false, fog: false }));
this.cover = new Mesh(new PlaneGeometry(1, 1), new MeshBasicMaterial({ color: 0xffffff, transparent: true, opacity: 0, depthWrite: false }));
this.cover.rotation.x = -Math.PI / 2;
this.cover.renderOrder = -1;
for (const o of [this.rain, this.snow, this.hail, this.bolt, this.disc, this.halo, this.stars, this.cover]) {
o.frustumCulled = false;
this.group.add(o);
}
this.group.visible = false;
scene.add(this.group);
}
/** How cloudy it is (0…1): the sunlight through the windows dims with it. */
get cloud(): number {
return this.view?.weather?.cloud ?? 0;
}
/** The area the weather covers: the plot and a margin around it. */
setBounds(b: Bounds): void {
this.bounds = b;
this.seed();
this.placeNight();
}
/** Stars when the sun is well below the horizon and the sky is clear; snow lying or wet ground under the house. */
private placeNight(): void {
const v = this.view;
const w = v?.weather;
const b = this.bounds;
const span = Math.max(b.x1 - b.x0, b.z1 - b.z0);
const night = v?.sun && v.disc ? Math.min(1, Math.max(0, (-v.sun.elevation - 4) / 8)) : 0;
const starMaterial = this.stars.material as PointsMaterial;
starMaterial.opacity = night * (1 - (w?.cloud ?? 0)) * 0.9;
this.stars.visible = starMaterial.opacity > 0.02;
this.stars.position.set((b.x0 + b.x1) / 2, b.y0, (b.z0 + b.z1) / 2);
this.stars.scale.setScalar(span * 3);
const coverMaterial = this.cover.material as MeshBasicMaterial;
const snowy = (w?.snow ?? 0) + (w?.hail ?? 0) * 0.5;
const wet = w?.rain ?? 0;
coverMaterial.color.setHex(snowy > 0.05 ? 0xf4f8ff : 0x1c3550);
coverMaterial.opacity = snowy > 0.05 ? 0.3 + 0.45 * Math.min(1, snowy) : wet > 0.1 ? 0.25 * Math.min(1, wet) : 0;
this.cover.visible = coverMaterial.opacity > 0.02;
this.cover.position.set((b.x0 + b.x1) / 2, b.y0 - 0.18, (b.z0 + b.z1) / 2);
this.cover.scale.set(b.x1 - b.x0, b.z1 - b.z0, 1);
}
set(view: SkyView | null): void {
const before = this.view;
this.view = view;
this.group.visible = !!view;
const w = view?.weather ?? null;
// fog thickens with distance and melts into the stage colour
if (view && w && w.fog > 0.02 && !view.low) {
const color = new Color(view.sky[0] / 255, view.sky[1] / 255, view.sky[2] / 255);
this.scene.fog = new FogExp2(color, 0.008 + 0.04 * w.fog);
} else if (this.scene.fog instanceof FogExp2) this.scene.fog = null;
if (!before || before.low !== view?.low || !!before.weather !== !!w) this.seed();
this.placeDisc();
this.placeNight();
if (!w?.lightning) this.endBolt();
}
/** Wind as a horizontal velocity in plan coordinates (x right, z down), metres per second. */
private windVector(): [number, number] {
const w = this.view?.weather;
if (!w) return [0, 0];
const from = (w.windFrom ?? 270) + (this.view?.north ?? 0);
// the wind blows towards the opposite side of where it comes from
const to = (from + 180) * DEG;
const speed = 0.4 + 7 * w.wind;
return [Math.sin(to) * speed, -Math.cos(to) * speed];
}
private count(amount: number, max: number): number {
const low = this.view?.low ?? false;
return Math.round(Math.min(1, amount) * max * (low ? 0.3 : 1));
}
/** New random positions for everything that falls or drifts (after a change of the area or of the amounts). */
private seed(): void {
const b = this.bounds;
const w = this.view?.weather;
const rx = () => b.x0 + Math.random() * (b.x1 - b.x0);
const rz = () => b.z0 + Math.random() * (b.z1 - b.z0);
const ry = () => b.y0 + Math.random() * (b.y1 - b.y0);
const rp = this.rain.geometry.getAttribute("position") as Float32BufferAttribute;
for (let i = 0; i < RAIN_MAX; i++) {
const x = rx(), y = ry(), z = rz();
rp.setXYZ(i * 2, x, y, z);
rp.setXYZ(i * 2 + 1, x, y - 0.4, z);
this.rainVel[i * 3 + 1] = 8.5 + Math.random() * 3;
}
rp.needsUpdate = true;
const sp = this.snow.geometry.getAttribute("position") as Float32BufferAttribute;
for (let i = 0; i < SNOW_MAX; i++) sp.setXYZ(i, rx(), ry(), rz());
sp.needsUpdate = true;
const hp = this.hail.geometry.getAttribute("position") as Float32BufferAttribute;
for (let i = 0; i < hp.count; i++) hp.setXYZ(i, rx(), ry(), rz());
hp.needsUpdate = true;
this.rain.geometry.setDrawRange(0, this.count(w?.rain ?? 0, RAIN_MAX) * 2);
this.snow.geometry.setDrawRange(0, this.count(w?.snow ?? 0, SNOW_MAX));
this.hail.geometry.setDrawRange(0, this.count(w?.hail ?? 0, 600));
this.rain.visible = !!w && w.rain > 0.01;
this.snow.visible = !!w && w.snow > 0.01;
this.hail.visible = !!w && w.hail > 0.01;
// clouds on a ring around the plot, their shadows anywhere over it
this.clouds.forEach((c, i) => {
c.angle = (i / CLOUDS) * Math.PI * 2 + Math.random() * 0.5;
c.ring = 1.7 + Math.random() * 0.9;
c.lift = 0.35 + Math.random() * 0.35;
c.scale = 0.55 + Math.random() * 0.45;
c.sx = b.x0 + Math.random() * (b.x1 - b.x0);
c.sz = b.z0 + Math.random() * (b.z1 - b.z0);
});
this.placeClouds(0);
}
private placeClouds(dt: number): void {
const v = this.view;
const w = v?.weather;
const amount = w?.cloud ?? 0;
const b = this.bounds;
const cx = (b.x0 + b.x1) / 2, cz = (b.z0 + b.z1) / 2;
const span = Math.max(b.x1 - b.x0, b.z1 - b.z0);
const [vx, vz] = this.windVector();
const shown = Math.round(amount * CLOUDS);
// the clouds take the colour of the stage: dark slate on a night stage, white on a bright one
const sky = v?.sky ?? [20, 28, 44];
const bright = (sky[0] + sky[1] + sky[2]) / (3 * 255);
const storm = w?.rain || w?.lightning ? 0.3 : 0;
const tone = Math.max(0.12, Math.min(1, 0.28 + bright * 0.9 - storm - 0.25 * Math.max(0, amount - 0.6)));
// the ring turns slowly in the direction the wind blows
const turn = (Math.hypot(vx, vz) / Math.max(20, span * 4)) * dt * Math.sign(vx || 1);
this.clouds.forEach((c, i) => {
const on = i < shown;
c.angle += turn * c.speed;
const r = span * c.ring;
const sm = c.sprite.material as SpriteMaterial;
sm.color.setRGB(tone, tone * 1.02, Math.min(1, tone * 1.12));
sm.opacity = on ? 0.3 + 0.45 * amount : 0;
c.sprite.visible = on;
c.sprite.position.set(cx + Math.cos(c.angle) * r, b.y0 + span * c.lift, cz + Math.sin(c.angle) * r);
c.sprite.scale.set(span * c.scale * 1.6, span * c.scale * 0.6, 1);
// the shadows drift over the plot with the wind and come back on the far side
c.sx += vx * 0.45 * c.speed * dt;
c.sz += vz * 0.45 * c.speed * dt;
const m = span * 0.4;
if (c.sx > b.x1 + m) c.sx = b.x0 - m;
if (c.sx < b.x0 - m) c.sx = b.x1 + m;
if (c.sz > b.z1 + m) c.sz = b.z0 - m;
if (c.sz < b.z0 - m) c.sz = b.z1 + m;
const shm = c.shadow.material as MeshBasicMaterial;
shm.opacity = on ? 0.12 + 0.2 * amount : 0;
c.shadow.visible = on;
c.shadow.position.set(c.sx, b.y0 + 0.03, c.sz);
c.shadow.scale.set(span * c.scale * 0.55, span * c.scale * 0.35, 1);
});
}
/** The sun by day, the moon by night, far out in their direction; paler (or gone) behind clouds. */
private placeDisc(): void {
const v = this.view;
const sun = v?.sun;
const cloud = v?.weather?.cloud ?? 0;
const night = !sun || sun.elevation < -3;
if (!v || !sun || !v.disc || cloud > 0.9 || (!night && sun.elevation < 0.5)) {
this.disc.visible = this.halo.visible = false;
return;
}
const b = this.bounds;
const center = new Vector3((b.x0 + b.x1) / 2, b.y0, (b.z0 + b.z1) / 2);
const r = Math.max(70, Math.max(b.x1 - b.x0, b.z1 - b.z0) * 3.5);
// the moon stands roughly opposite the sun
const az = ((night ? sun.azimuth + 180 : sun.azimuth) + v.north) * DEG;
const el = Math.max(8, Math.abs(sun.elevation)) * DEG;
const dir = new Vector3(Math.sin(az) * Math.cos(el), Math.sin(el), -Math.cos(az) * Math.cos(el));
const pos = center.addScaledVector(dir, r);
const size = r * (night ? 0.07 : 0.1);
this.disc.position.copy(pos);
this.halo.position.copy(pos);
this.disc.scale.setScalar(size);
this.halo.scale.setScalar(size * 3.2);
const dm = this.disc.material as SpriteMaterial;
const hm = this.halo.material as SpriteMaterial;
// a low sun is orange, a high one pale yellow
const low = !night ? Math.max(0, 1 - sun.elevation / 20) : 0;
dm.color.set(night ? 0xd5def2 : new Color(1, 0.9 - 0.25 * low, 0.6 - 0.35 * low));
hm.color.copy(dm.color);
dm.opacity = (night ? 0.7 : 0.95) * (1 - cloud);
hm.opacity = (night ? 0.35 : 0.6) * (1 - cloud);
this.disc.visible = this.halo.visible = true;
}
private endBolt(): void {
if (this.bolt.visible) {
this.bolt.visible = false;
this.onFlash?.(false);
}
}
/** A jagged bolt from the cloud base down to the ground somewhere beside the house. */
private strike(now: number): void {
const b = this.bounds;
const side = Math.random() < 0.5 ? -1 : 1;
let x = side < 0 ? b.x0 - 2 - Math.random() * 6 : b.x1 + 2 + Math.random() * 6;
let z = b.z0 + Math.random() * (b.z1 - b.z0);
const top = b.y1 + 4;
const p = this.bolt.geometry.getAttribute("position") as Float32BufferAttribute;
const steps = 24;
let y = top;
for (let i = 0; i < steps; i++) {
const ny = top - ((i + 1) / steps) * (top - b.y0);
const nx = x + (Math.random() - 0.5) * 1.6;
const nz = z + (Math.random() - 0.5) * 1.6;
p.setXYZ(i * 2, x, y, z);
p.setXYZ(i * 2 + 1, nx, ny, nz);
x = nx;
z = nz;
y = ny;
}
p.needsUpdate = true;
this.bolt.visible = true;
this.boltUntil = now + 90 + Math.random() * 120;
this.onFlash?.(true);
}
/** One frame: let it rain, snow, drift and flash. True while anything moves. */
step(now: number): boolean {
const v = this.view;
const w = v?.weather;
if (!v || !w) {
this.last = 0;
return false;
}
const dt = this.last ? Math.min(0.1, (now - this.last) / 1000) : 0;
this.last = now;
const b = this.bounds;
const height = b.y1 - b.y0;
const [vx, vz] = this.windVector();
if (this.rain.visible && dt) {
const p = this.rain.geometry.getAttribute("position") as Float32BufferAttribute;
const a = p.array as Float32Array;
const n = this.count(w.rain, RAIN_MAX);
for (let i = 0; i < n; i++) {
const k = i * 6;
const fall = this.rainVel[i * 3 + 1];
let x = a[k] + vx * dt, y = a[k + 1] - fall * dt, z = a[k + 2] + vz * dt;
if (y < b.y0) {
y += height;
x = b.x0 + Math.random() * (b.x1 - b.x0) - vx * 0.4;
z = b.z0 + Math.random() * (b.z1 - b.z0) - vz * 0.4;
}
// the streak points back along the drop's path: slanted in the wind
const len = 0.05;
a[k] = x; a[k + 1] = y; a[k + 2] = z;
a[k + 3] = x - vx * len; a[k + 4] = y + fall * len; a[k + 5] = z - vz * len;
}
p.needsUpdate = true;
}
if (this.snow.visible && dt) {
const p = this.snow.geometry.getAttribute("position") as Float32BufferAttribute;
const a = p.array as Float32Array;
const n = this.count(w.snow, SNOW_MAX);
const t = now / 1000;
for (let i = 0; i < n; i++) {
const k = i * 3;
const ph = this.snowPhase[i];
let x = a[k] + (vx * 0.35 + Math.sin(t * 1.3 + ph) * 0.35) * dt;
let y = a[k + 1] - (0.7 + 0.5 * ((ph * 7) % 1)) * dt;
let z = a[k + 2] + (vz * 0.35 + Math.cos(t * 1.1 + ph) * 0.35) * dt;
if (y < b.y0) {
y += height;
x = b.x0 + Math.random() * (b.x1 - b.x0);
z = b.z0 + Math.random() * (b.z1 - b.z0);
}
a[k] = x; a[k + 1] = y; a[k + 2] = z;
}
p.needsUpdate = true;
}
if (this.hail.visible && dt) {
const p = this.hail.geometry.getAttribute("position") as Float32BufferAttribute;
const a = p.array as Float32Array;
const n = this.count(w.hail, 600);
for (let i = 0; i < n; i++) {
const k = i * 3;
let y = a[k + 1] - 14 * dt;
if (y < b.y0) y += height;
a[k] += vx * 0.5 * dt;
a[k + 1] = y;
a[k + 2] += vz * 0.5 * dt;
}
p.needsUpdate = true;
}
if (w.cloud > 0.01) this.placeClouds(dt);
if (w.lightning && !v.low) {
if (!this.nextBolt) this.nextBolt = now + 2500 + Math.random() * 6000;
if (now >= this.nextBolt) {
this.strike(now);
this.nextBolt = now + 3500 + Math.random() * 9000;
}
if (this.bolt.visible && now > this.boltUntil) this.endBolt();
} else this.nextBolt = 0;
return this.rain.visible || this.snow.visible || this.hail.visible || w.cloud > 0.01 || w.lightning;
}
dispose(): void {
this.endBolt();
this.group.traverse((o) => {
const m = o as Mesh;
m.geometry?.dispose();
const mat = m.material as MeshBasicMaterial | undefined;
mat?.map?.dispose();
mat?.dispose();
});
this.scene.remove(this.group);
if (this.scene.fog instanceof FogExp2) this.scene.fog = null;
}
}
+174
View File
@@ -0,0 +1,174 @@
// Owned 3D models (binary glTF) shown instead of a pack item's simple parts.
//
// The files live on the user's Home Assistant, never in NextFloor. A model is loaded once per page and shared
// by all viewers; every placed item gets a light copy of its own, so its paint colour can differ.
import {
Box3,
Color,
DirectionalLight,
Group,
HemisphereLight,
Mesh,
MeshStandardMaterial,
PMREMGenerator,
type BufferGeometry,
type Material,
type Object3D,
type Texture,
type WebGLRenderer,
} from "three";
import { RoomEnvironment } from "three/examples/jsm/environments/RoomEnvironment.js";
import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader.js";
import { toCreasedNormals } from "three/examples/jsm/utils/BufferGeometryUtils.js";
import { getMeshSource, markMeshReady } from "../packs.ts";
interface LoadedMesh {
root: Object3D;
/** Size of the model as it is (width, height, depth in metres). */
size: [number, number, number];
}
const cache = new Map<string, Promise<LoadedMesh | null>>();
const loaded = new Map<string, LoadedMesh>();
/** Smooth shading with creases: the model comes without normals (they are cheap to recompute and keep the file small). */
const CREASE = (50 * Math.PI) / 180;
function prepare(root: Object3D): void {
root.traverse((o) => {
const mesh = o as Mesh;
if (!mesh.isMesh) return;
const g = mesh.geometry as BufferGeometry;
const m = mesh.material as MeshStandardMaterial;
const name = m.name ?? "";
// paint: the body colour is swapped per item
mesh.userData.paint = !!m.userData?.paint || /^Paint/.test(name);
if (!g.getAttribute("normal")) {
// the body is one smooth skin; everything else keeps its edges
if (mesh.userData.paint) g.computeVertexNormals();
else mesh.geometry = toCreasedNormals(g, CREASE);
}
// the loader flags models without normals as flat-shaded: ours get smooth ones below
m.flatShading = false;
const glass = /glass/i.test(name);
m.metalness = mesh.userData.paint ? 0.55 : glass ? 0 : Math.min(m.metalness ?? 0, 0.4);
m.roughness = mesh.userData.paint ? 0.28 : glass ? 0.05 : Math.max(m.roughness ?? 0.6, 0.45);
if (glass) {
m.transparent = true;
m.depthWrite = false;
m.opacity = Math.max(m.opacity, 0.9);
}
});
}
/** Load a model (once); false when the host has none or it is broken. */
export function loadMesh(id: string): Promise<boolean> {
let p = cache.get(id);
if (!p) {
const source = getMeshSource();
if (!source) return Promise.resolve(false);
p = source(id)
.then(
(data) =>
data &&
new Promise<LoadedMesh | null>((resolve) => {
new GLTFLoader().parse(
data,
"",
(gltf) => {
prepare(gltf.scene);
const box = new Box3().setFromObject(gltf.scene);
const size: [number, number, number] = [box.max.x - box.min.x, box.max.y - box.min.y, box.max.z - box.min.z];
// feet on the floor, centred on its footprint
gltf.scene.position.set(-(box.max.x + box.min.x) / 2, -box.min.y, -(box.max.z + box.min.z) / 2);
const root = new Group();
root.add(gltf.scene);
loaded.set(id, { root, size });
markMeshReady(id);
resolve({ root, size });
},
() => resolve(null),
);
}),
)
.catch(() => null);
cache.set(id, p);
}
return p.then((m) => !!m);
}
/** Forget models that could not be loaded, to try again (the host's login may have changed). */
export function retryMeshes(): void {
for (const [id, p] of cache) if (!loaded.has(id)) void p.then(() => cache.delete(id));
}
export interface MeshPlacement {
x: number;
z: number;
y: number;
/** Turn around the vertical axis in degrees (as furniture.rotation). */
rotation: number;
mirror?: boolean;
w: number;
d: number;
h: number;
/** Colour of the body paint (hex like "#c01020"), or null for the model's own. */
paint: string | null;
}
/** A copy of a loaded model for one placed item (null while it is not loaded). */
export function instantiateMesh(id: string, at: MeshPlacement): Group | null {
const m = loaded.get(id);
if (!m) return null;
const root = m.root.clone(true);
const own: Material[] = [];
root.traverse((o) => {
const mesh = o as Mesh;
if (!mesh.isMesh) return;
const mat = (mesh.material as MeshStandardMaterial).clone();
if (mesh.userData.paint && at.paint) mat.color = new Color(at.paint);
mesh.material = mat;
own.push(mat);
});
const g = new Group();
g.add(root);
// the item's box is the model's: it stretches to the width, depth and height of the furniture
g.scale.set((at.mirror ? -1 : 1) * (at.w / m.size[0]), at.h / m.size[1], at.d / m.size[2]);
g.position.set(at.x, at.y, at.z);
g.rotation.y = (-at.rotation * Math.PI) / 180;
g.userData.own = own;
return g;
}
/** Free the materials of a copy made by instantiateMesh (geometry and textures belong to the shared model). */
export function disposeMeshInstance(g: Object3D): void {
for (const m of (g.userData.own ?? []) as Material[]) m.dispose();
}
/** Light and reflections for the models; the rest of the scene is unlit, so they only touch these. */
export function addMeshLighting(parent: Object3D, renderer: WebGLRenderer): { env: Texture; dispose: () => void } {
const pmrem = new PMREMGenerator(renderer);
const env = pmrem.fromScene(new RoomEnvironment(), 0.04).texture;
pmrem.dispose();
const sky = new HemisphereLight(0xffffff, 0x8a93a6, 0.9);
const sun = new DirectionalLight(0xffffff, 1.6);
sun.position.set(-4, 9, 6);
parent.add(sky, sun);
return {
env,
dispose: () => {
env.dispose();
sky.removeFromParent();
sun.removeFromParent();
},
};
}
/** Set the reflection map on every material of a copy. */
export function applyEnvironment(g: Object3D, env: Texture): void {
for (const m of (g.userData.own ?? []) as MeshStandardMaterial[]) {
m.envMap = env;
m.envMapIntensity = 0.9;
}
}
@@ -0,0 +1,32 @@
import assert from "node:assert/strict";
import { test } from "node:test";
import { guessPaint, paintName, shareBudget, turnsToFront, type MaterialSummary } from "./choices.ts";
const material = (name: string, area: number, extra: Partial<MaterialSummary> = {}): MaterialSummary => ({ name, area, opacity: 1, lightness: 0.5, ...extra });
test("materials named like paint are the paint", () => {
assert.deepEqual(guessPaint([material("Glass", 2, { opacity: 0.3 }), material("Paint_Body", 5), material("Carpaint2", 1), material("Tyre", 3, { lightness: 0.05 })]), ["Paint_Body", "Carpaint2"]);
});
test("without a telling name the largest solid, not-dark material is guessed", () => {
assert.deepEqual(guessPaint([material("Tyre", 9, { lightness: 0.05 }), material("Glass", 8, { opacity: 0.2 }), material("m1", 6), material("m2", 2)]), ["m1"]);
assert.deepEqual(guessPaint([material("Window_glass", 9), material("lamp", 7), material("m3", 1)]), ["m3"]);
assert.deepEqual(guessPaint([]), []);
});
test("a model within budget keeps everything, a heavier one is cut in proportion", () => {
assert.deepEqual(shareBudget([100, 50], 200), [100, 50]);
assert.deepEqual(shareBudget([300, 100], 200), [150, 50]);
assert.deepEqual(shareBudget([1, 1000], 10), [1, 9]);
});
test("paint names get the prefix once", () => {
assert.equal(paintName("Body"), "Paint_Body");
assert.equal(paintName("Paint_Body"), "Paint_Body");
assert.equal(paintName("PaintMetal"), "PaintMetal");
assert.equal(paintName(""), "Paint_body");
});
test("the turns bring the front to +z", () => {
assert.deepEqual(["+z", "-x", "-z", "+x"].map((f) => turnsToFront(f as never)), [0, 1, 2, 3]);
});
+45
View File
@@ -0,0 +1,45 @@
// The decisions made while preparing a model that need no 3D: how the triangle budget is shared between materials, and which
// material is most likely the body paint.
export interface MaterialSummary {
name: string;
/** Surface area in square metres. */
area: number;
opacity: number;
/** Brightness of its colour from 0 (black) to 1 (white). */
lightness: number;
}
/** Names that body paint usually has in models of cars and appliances. */
const PAINT_NAME = /^paint|carpaint|body|lack|lacquer|exterior/i;
/**
* The materials that are most likely the body paint: those named like paint, else the one with the largest surface among the solid
* ones that are not nearly black (tyres, trim) or see-through (glass).
*/
export function guessPaint(materials: readonly MaterialSummary[]): string[] {
const named = materials.filter((m) => PAINT_NAME.test(m.name)).map((m) => m.name);
if (named.length > 0) return named;
const solid = materials.filter((m) => m.opacity >= 0.9 && m.lightness > 0.12 && !/glass|window|light|lamp/i.test(m.name));
const largest = [...solid].sort((a, b) => b.area - a.area)[0];
return largest ? [largest.name] : [];
}
/**
* How many triangles each part may keep so that all together stay within `total`. Parts that already fit keep all of theirs, and what
* they leave over is shared among the larger ones in proportion to their size.
*/
export function shareBudget(counts: readonly number[], total: number): number[] {
const sum = counts.reduce((a, b) => a + b, 0);
if (sum <= total) return [...counts];
const share = total / sum;
return counts.map((n) => Math.max(1, Math.floor(n * share)));
}
/** A name for a paint material so that NextFloor recognises it: the original name behind a "Paint_" prefix, once. */
export const paintName = (name: string): string => (/^Paint/.test(name) ? name : `Paint_${name || "body"}`);
/** The quarter turns (0 to 3) that bring a model whose front points along the given axis direction to +z. */
export function turnsToFront(front: "+x" | "-x" | "+z" | "-z"): 0 | 1 | 2 | 3 {
return { "+z": 0, "-x": 1, "-z": 2, "+x": 3 }[front] as 0 | 1 | 2 | 3;
}
@@ -0,0 +1,76 @@
import assert from "node:assert/strict";
import { test } from "node:test";
import { decimate, triangleCount, type Mesh3 } from "./decimate.ts";
/** A flat grid of n × n squares, two triangles each, in the x-z plane. */
function grid(n: number): Mesh3 {
const positions = new Float32Array((n + 1) * (n + 1) * 3);
for (let z = 0; z <= n; z++) for (let x = 0; x <= n; x++) positions.set([x / n, 0, z / n], (z * (n + 1) + x) * 3);
const indices: number[] = [];
for (let z = 0; z < n; z++) {
for (let x = 0; x < n; x++) {
const a = z * (n + 1) + x;
indices.push(a, a + n + 1, a + 1, a + 1, a + n + 1, a + n + 2);
}
}
return { positions, indices: Uint32Array.from(indices) };
}
/** A box made of 12 triangles, subdivided by repeating its faces as grids. */
function sphere(rings: number, segments: number): Mesh3 {
const positions: number[] = [];
for (let r = 0; r <= rings; r++) {
for (let s = 0; s < segments; s++) {
const [phi, theta] = [(r / rings) * Math.PI, (s / segments) * Math.PI * 2];
positions.push(Math.sin(phi) * Math.cos(theta), Math.cos(phi), Math.sin(phi) * Math.sin(theta));
}
}
const indices: number[] = [];
for (let r = 0; r < rings; r++) {
for (let s = 0; s < segments; s++) {
const [a, b] = [r * segments + s, r * segments + ((s + 1) % segments)];
const [c, d] = [a + segments, b + segments];
indices.push(a, c, b, b, c, d);
}
}
return { positions: Float32Array.from(positions), indices: Uint32Array.from(indices) };
}
test("a mesh that is light enough comes back as it is", () => {
const mesh = grid(4);
assert.equal(decimate(mesh, 100), mesh);
assert.equal(decimate(mesh, 32), mesh);
});
test("a heavy mesh gets close to the target without going over it", () => {
const mesh = grid(60);
assert.equal(triangleCount(mesh), 7200);
const light = decimate(mesh, 1000);
assert.ok(triangleCount(light) <= 1000, `${triangleCount(light)}`);
assert.ok(triangleCount(light) > 500, `too much taken away: ${triangleCount(light)}`);
});
test("the lighter mesh stays in the shape of the original", () => {
const light = decimate(sphere(40, 60), 600);
assert.ok(triangleCount(light) <= 600);
for (let v = 0; v < light.positions.length; v += 3) {
const r = Math.hypot(light.positions[v], light.positions[v + 1], light.positions[v + 2]);
assert.ok(r > 0.75 && r <= 1.0001, `a vertex off the sphere: ${r}`);
}
});
test("every triangle refers to existing vertices and has three different corners", () => {
const light = decimate(sphere(30, 40), 300);
const vertices = light.positions.length / 3;
for (let i = 0; i < light.indices.length; i += 3) {
const [a, b, c] = [light.indices[i], light.indices[i + 1], light.indices[i + 2]];
assert.ok(a < vertices && b < vertices && c < vertices);
assert.ok(a !== b && b !== c && a !== c);
}
assert.equal(light.indices.length % 3, 0);
});
test("an empty mesh is left alone", () => {
const empty: Mesh3 = { positions: new Float32Array(0), indices: new Uint32Array(0) };
assert.equal(decimate(empty, 10), empty);
});
+112
View File
@@ -0,0 +1,112 @@
// Making a heavy 3D model lighter by vertex clustering: the model is laid over a grid, every grid cell becomes one vertex (the average
// of the vertices in it), and triangles that fall into a single cell or two disappear. A coarser grid gives fewer triangles, so the
// grid is chosen to land just under the wanted number. It is fast, needs no extra libraries, and keeps the shape of a car or a sofa.
export interface Mesh3 {
/** x, y, z of every vertex. */
positions: Float32Array;
/** Three vertex numbers per triangle. */
indices: Uint32Array;
}
/** The number of triangles. */
export const triangleCount = (mesh: Mesh3): number => mesh.indices.length / 3;
interface Bounds {
min: [number, number, number];
size: [number, number, number];
}
function boundsOf(positions: Float32Array): Bounds {
const min: [number, number, number] = [Infinity, Infinity, Infinity];
const max: [number, number, number] = [-Infinity, -Infinity, -Infinity];
for (let i = 0; i < positions.length; i += 3) {
for (let k = 0; k < 3; k++) {
min[k] = Math.min(min[k], positions[i + k]);
max[k] = Math.max(max[k], positions[i + k]);
}
}
return { min, size: [max[0] - min[0], max[1] - min[1], max[2] - min[2]] };
}
/** The cell number of every vertex for a grid of cells `cell` wide. Cells are numbered by their coordinates, packed into one number. */
function cellsOf(positions: Float32Array, bounds: Bounds, cell: number): Float64Array {
const count = positions.length / 3;
const counts = bounds.size.map((s) => Math.floor(s / cell) + 1);
const cells = new Float64Array(count);
for (let v = 0; v < count; v++) {
const x = Math.floor((positions[v * 3] - bounds.min[0]) / cell);
const y = Math.floor((positions[v * 3 + 1] - bounds.min[1]) / cell);
const z = Math.floor((positions[v * 3 + 2] - bounds.min[2]) / cell);
cells[v] = (x * counts[1] + y) * counts[2] + z;
}
return cells;
}
/** The triangles that survive clustering: all three corners in different cells. Counted without building anything. */
function survivors(indices: Uint32Array, cells: Float64Array): number {
let kept = 0;
for (let i = 0; i < indices.length; i += 3) {
const [a, b, c] = [cells[indices[i]], cells[indices[i + 1]], cells[indices[i + 2]]];
if (a !== b && b !== c && a !== c) kept++;
}
return kept;
}
/** Builds the lighter mesh for a given grid: one vertex per used cell, and the surviving triangles without duplicates. */
function cluster(mesh: Mesh3, cells: Float64Array): Mesh3 {
const vertexOfCell = new Map<number, number>();
const sums: number[] = [];
const members: number[] = [];
const mapped = new Uint32Array(cells.length);
for (let v = 0; v < cells.length; v++) {
let id = vertexOfCell.get(cells[v]);
if (id === undefined) {
id = members.length;
vertexOfCell.set(cells[v], id);
members.push(0);
sums.push(0, 0, 0);
}
mapped[v] = id;
members[id]++;
for (let k = 0; k < 3; k++) sums[id * 3 + k] += mesh.positions[v * 3 + k];
}
const positions = new Float32Array(members.length * 3);
for (let id = 0; id < members.length; id++) for (let k = 0; k < 3; k++) positions[id * 3 + k] = sums[id * 3 + k] / members[id];
const seen = new Set<string>();
const indices: number[] = [];
for (let i = 0; i < mesh.indices.length; i += 3) {
const [a, b, c] = [mapped[mesh.indices[i]], mapped[mesh.indices[i + 1]], mapped[mesh.indices[i + 2]]];
if (a === b || b === c || a === c) continue;
// the same triangle with the same winding, written starting at its smallest corner, is a duplicate
const start = Math.min(a, b, c);
const key = start === a ? `${a},${b},${c}` : start === b ? `${b},${c},${a}` : `${c},${a},${b}`;
if (seen.has(key)) continue;
seen.add(key);
indices.push(a, b, c);
}
return { positions, indices: Uint32Array.from(indices) };
}
/**
* A lighter copy of the mesh with at most `target` triangles. A mesh that is light enough is returned as it is. The grid is found by
* halving the search between a very fine and a very coarse one.
*/
export function decimate(mesh: Mesh3, target: number): Mesh3 {
if (triangleCount(mesh) <= target || mesh.positions.length === 0) return mesh;
const bounds = boundsOf(mesh.positions);
const longest = Math.max(...bounds.size, 1e-9);
let fine = longest / 4096;
let coarse = longest;
let best = cellsOf(mesh.positions, bounds, coarse);
for (let step = 0; step < 14; step++) {
const middle = Math.sqrt(fine * coarse);
const cells = cellsOf(mesh.positions, bounds, middle);
if (survivors(mesh.indices, cells) > target) fine = middle;
else {
coarse = middle;
best = cells;
}
}
return cluster(mesh, best);
}
+195
View File
@@ -0,0 +1,195 @@
// Getting a 3D model you own ready for NextFloor, in the browser: a binary glTF is read, its parts are merged by material, turned so
// that the front points to +z, made lighter, the body paint is marked, and the result is written again as plain binary glTF without
// textures. This is what tools/prepare-model.mjs did by hand.
import {
AmbientLight,
Box3,
BufferAttribute,
BufferGeometry,
Color,
DirectionalLight,
HemisphereLight,
Matrix4,
Mesh,
MeshStandardMaterial,
OrthographicCamera,
Scene,
Vector3,
WebGLRenderer,
type Material,
type Object3D,
} from "three";
import { GLTFExporter } from "three/examples/jsm/exporters/GLTFExporter.js";
import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader.js";
import { guessPaint, paintName, shareBudget, type MaterialSummary } from "./choices.ts";
import { decimate, triangleCount, type Mesh3 } from "./decimate.ts";
export interface ModelInfo {
triangles: number;
/** Width, height and depth in metres as the model comes. */
size: [number, number, number];
materials: MaterialSummary[];
/** The materials that are probably the body paint. */
paint: string[];
}
export interface PrepareOptions {
/** Quarter turns about the vertical axis that bring the front to +z. */
turns: 0 | 1 | 2 | 3;
/** Names of the materials that are body paint. */
paint: readonly string[];
/** Most triangles the result may have. */
maxTriangles: number;
}
/** What goes wrong when a file cannot be used, so the page can say it in words. */
export class ModelError extends Error {
readonly reason: "not_glb" | "compressed" | "empty" | "unreadable";
constructor(reason: ModelError["reason"], message: string) {
super(message);
this.reason = reason;
}
}
const MAGIC = 0x46546c67; // "glTF"
/** The whole file is read as binary glTF; anything else is refused before three.js sees it. */
function check(data: ArrayBuffer): void {
if (data.byteLength < 20 || new DataView(data).getUint32(0, true) !== MAGIC) throw new ModelError("not_glb", "not a binary glTF (.glb) file");
}
async function parse(data: ArrayBuffer): Promise<Object3D> {
check(data);
return new Promise((resolve, reject) => {
new GLTFLoader().parse(
data,
"",
(gltf) => resolve(gltf.scene),
(error) => {
const message = String((error as { message?: string })?.message ?? error);
reject(/draco|meshopt|ktx/i.test(message) ? new ModelError("compressed", message) : new ModelError("unreadable", message));
},
);
});
}
/** One material's share of the model: its triangles with the placement of the parts already applied. */
interface Part {
material: MeshStandardMaterial;
mesh: Mesh3;
}
const asStandard = (m: Material): MeshStandardMaterial => (m instanceof MeshStandardMaterial ? m : Object.assign(new MeshStandardMaterial(), { color: (m as { color?: Color }).color?.clone() ?? new Color(0x888888), name: m.name, opacity: m.opacity, transparent: m.transparent }));
/** Every mesh of the scene in world coordinates, grouped by material. */
function collect(root: Object3D, extra: Matrix4): Part[] {
root.updateMatrixWorld(true);
const byMaterial = new Map<MeshStandardMaterial, { positions: number[]; indices: number[] }>();
root.traverse((object) => {
const mesh = object as Mesh;
if (!mesh.isMesh) return;
const geometry = mesh.geometry as BufferGeometry;
const position = geometry.getAttribute("position");
if (!position) return;
const material = asStandard(Array.isArray(mesh.material) ? mesh.material[0] : mesh.material);
const target = byMaterial.get(material) ?? { positions: [], indices: [] };
byMaterial.set(material, target);
const placement = new Matrix4().multiplyMatrices(extra, mesh.matrixWorld);
const first = target.positions.length / 3;
const v = new Vector3();
for (let i = 0; i < position.count; i++) {
v.fromBufferAttribute(position, i).applyMatrix4(placement);
target.positions.push(v.x, v.y, v.z);
}
const index = geometry.getIndex();
const count = index ? index.count : position.count;
for (let i = 0; i < count; i++) target.indices.push(first + (index ? index.getX(i) : i));
});
return [...byMaterial].map(([material, g]) => ({ material, mesh: { positions: Float32Array.from(g.positions), indices: Uint32Array.from(g.indices) } }));
}
const surfaceArea = (m: Mesh3): number => {
let area = 0;
const [a, b, c] = [new Vector3(), new Vector3(), new Vector3()];
for (let i = 0; i < m.indices.length; i += 3) {
a.fromArray(m.positions, m.indices[i] * 3);
b.fromArray(m.positions, m.indices[i + 1] * 3);
c.fromArray(m.positions, m.indices[i + 2] * 3);
area += b.sub(a).cross(c.sub(a)).length() / 2;
}
return area;
};
const lightness = (c: Color): number => 0.299 * c.r + 0.587 * c.g + 0.114 * c.b;
/** What is in the model: size, triangles, materials with their area, and a guess at the paint. */
export async function inspectModel(data: ArrayBuffer): Promise<ModelInfo> {
const parts = collect(await parse(data), new Matrix4());
if (parts.length === 0) throw new ModelError("empty", "the file has no 3D parts");
const box = new Box3();
for (const p of parts) box.union(new Box3().setFromArray(p.mesh.positions as unknown as number[]));
const size = box.getSize(new Vector3());
const materials = parts.map((p): MaterialSummary => ({ name: p.material.name || "material", area: surfaceArea(p.mesh), opacity: p.material.opacity, lightness: lightness(p.material.color) }));
return { triangles: parts.reduce((n, p) => n + triangleCount(p.mesh), 0), size: [size.x, size.y, size.z], materials, paint: guessPaint(materials) };
}
/** The model lighter, turned and marked, as plain binary glTF. */
export async function prepareModel(data: ArrayBuffer, options: PrepareOptions): Promise<{ glb: ArrayBuffer; triangles: number }> {
const turn = new Matrix4().makeRotationY((options.turns * Math.PI) / 2);
const parts = collect(await parse(data), turn);
if (parts.length === 0) throw new ModelError("empty", "the file has no 3D parts");
const budgets = shareBudget(parts.map((p) => triangleCount(p.mesh)), options.maxTriangles);
const scene = new Scene();
let triangles = 0;
parts.forEach((part, i) => {
const light = decimate(part.mesh, budgets[i]);
if (triangleCount(light) === 0) return;
triangles += triangleCount(light);
const geometry = new BufferGeometry();
geometry.setAttribute("position", new BufferAttribute(light.positions, 3));
geometry.setIndex(new BufferAttribute(light.indices, 1));
const name = part.material.name || "material";
const isPaint = options.paint.includes(name);
const material = new MeshStandardMaterial({ color: part.material.color.clone(), name: isPaint ? paintName(name) : name, metalness: part.material.metalness, roughness: part.material.roughness, opacity: part.material.opacity, transparent: part.material.opacity < 1 });
if (isPaint) material.userData.paint = true;
scene.add(new Mesh(geometry, material));
});
const glb = await new Promise<ArrayBuffer>((resolve, reject) => {
new GLTFExporter().parse(scene, (result) => (result instanceof ArrayBuffer ? resolve(result) : reject(new ModelError("unreadable", "export gave no binary"))), (e) => reject(new ModelError("unreadable", String(e))), { binary: true });
});
return { glb, triangles };
}
/** A picture of a prepared model from the front right, with the paint in the given colour, as a PNG data URL. */
export async function previewModel(glb: ArrayBuffer, paint: string, size = 220): Promise<string> {
const root = await parse(glb);
const box = new Box3().setFromObject(root);
const centre = box.getCenter(new Vector3());
const extent = box.getSize(new Vector3());
root.traverse((o) => {
const mesh = o as Mesh;
if (!mesh.isMesh) return;
const material = mesh.material as MeshStandardMaterial;
if (material.userData?.paint || /^Paint/.test(material.name)) material.color.set(paint);
material.metalness = Math.min(material.metalness ?? 0, 0.5);
});
const scene = new Scene();
const sun = new DirectionalLight(0xffffff, 1.6);
sun.position.set(-4, 9, 6);
scene.add(root, new AmbientLight(0xffffff, 0.5), new HemisphereLight(0xffffff, 0x667088, 1.1), sun);
const half = Math.max(extent.x, extent.y, extent.z) * 0.75;
const camera = new OrthographicCamera(-half, half, half, -half, 0.01, 100);
camera.position.copy(centre).add(new Vector3(0.9, 0.7, 1.2).normalize().multiplyScalar(20));
camera.lookAt(centre);
const renderer = new WebGLRenderer({ alpha: true, antialias: true, preserveDrawingBuffer: true });
renderer.setSize(size, size, false);
renderer.render(scene, camera);
const url = renderer.domElement.toDataURL("image/png");
renderer.dispose();
scene.traverse((o) => {
const mesh = o as Mesh;
if (mesh.isMesh) mesh.geometry.dispose();
});
return url;
}
+4
View File
@@ -0,0 +1,4 @@
// Moving and state-dependent parts of doors and windows, split into modules in openings/.
export { buildOpeningParts } from "./openings/parts.ts";
export { CLOSED, type OpeningParts, type OpeningState } from "./openings/types.ts";
+54
View File
@@ -0,0 +1,54 @@
// The blind of a window: a roller shutter outside (a box above the opening and slats down to the closed fraction), a venetian blind
// outside whose slats turn with the cover's tilt, or a roller blind inside the room. A wide window can have a second blind for its
// right half.
import { Color } from "three";
import { ALWAYS } from "../geo.ts";
import type { Ctx } from "./context.ts";
import { BLIND_BOX, FRAME_TOP } from "./palette.ts";
import { panel, splitBox } from "./primitives.ts";
/** Colours of the kinds of blinds: the white shutter, the aluminium of a venetian blind, the light fabric of an inside blind. */
const SHUTTER = 0xffffff;
const VENETIAN = 0xc9ced6;
const FABRIC = 0xefe7d8;
/** Spacing and depth of venetian slats (m). */
const SLAT_STEP = 0.08;
const SLAT_DEPTH = 0.085;
export function blind(c: Ctx): void {
const { info, state, frame, fold } = c;
if (state.cover === null) return;
const [W, S, T] = [info.width, info.sill, info.top];
const kind = info.opening.blind ?? "roller";
const outside = -info.faceOut;
const inside = info.faceRoom;
// the cassette above the opening: a big box outside, a slim one on the room side for an inside blind
if (kind === "inside") splitBox(c.frames, frame, { x0: -0.03, x1: W + 0.03, n0: inside, n1: inside + 0.07, y0: T - 0.02, y1: T + 0.07 }, new Color(0xf2f2f2), new Color(0xf7f7f7), fold);
else splitBox(c.frames, frame, { x0: -0.05, x1: W + 0.05, n0: outside - 0.15, n1: outside, y0: T, y1: T + 0.2 }, new Color(BLIND_BOX), new Color(FRAME_TOP), fold);
const halves: [number, number, number][] = state.cover2 != null ? [[0, W / 2, state.cover], [W / 2, W, state.cover2]] : [[0, W, state.cover]];
for (const [x0, x1, cover] of halves) {
const closed = Math.min(1, Math.max(0, cover));
if (closed <= 0.01) continue;
const bottom = T - closed * (T - S);
if (kind === "inside") panel(c.blinds, frame, x0 + 0.01, x1 - 0.01, inside + 0.04, bottom, T - 0.02, new Color(FABRIC), fold);
else if (kind === "venetian") slats(c, x0, x1, outside - 0.07, bottom, T, state.slats ?? 0);
else panel(c.blinds, frame, x0, x1, outside - 0.07, bottom, T, new Color(SHUTTER), fold, 0.045);
}
}
/** Venetian slats from the top down to `bottom`, turned by how far they are open: level (1) shows the gaps, shut (0) a closed face. */
function slats(c: Ctx, x0: number, x1: number, n: number, bottom: number, top: number, open: number): void {
const { frame, fold } = c;
const color = new Color(VENETIAN);
// the slat's angle from upright: shut slats hang almost upright and overlap, open ones lie level
const a = (Math.PI / 2) * (0.12 + 0.88 * Math.min(1, Math.max(0, open)));
const dn = (Math.sin(a) * SLAT_DEPTH) / 2;
const dy = (Math.cos(a) * SLAT_DEPTH) / 2;
for (let y = top - SLAT_STEP / 2; y > bottom; y -= SLAT_STEP) {
const bucket = y >= fold.cut ? fold.bucket : ALWAYS;
const [p, q, r, s] = [frame(x0, n - dn, y + dy), frame(x1, n - dn, y + dy), frame(x1, n + dn, y - dy), frame(x0, n + dn, y - dy)];
c.blinds.tri(p, q, r, color, color, color, [0, 0.5, 1, 0.5, 1, 0.5], bucket);
c.blinds.tri(p, r, s, color, color, color, [0, 0.5, 1, 0.5, 0, 0.5], bucket);
}
}
+28
View File
@@ -0,0 +1,28 @@
import type { OpeningInfo } from "../build.ts";
import type { GeoBuffer } from "../geo.ts";
import type { Fold, Frame } from "./primitives.ts";
import type { OpeningState } from "./types.ts";
/** Everything the builders of one opening need. */
export interface Ctx {
info: OpeningInfo;
state: OpeningState;
frame: Frame;
/** The middle between the room face and the outer face of the wall (in n). */
mid: number;
/** Highlighted while closed (and a sensor knows), instead of while open. */
markClosed: boolean;
fold: Fold;
frames: GeoBuffer;
glass: GeoBuffer;
blinds: GeoBuffer;
/** For a piece of a pane over several edges: whether it is the first or the last one, which carry the jambs. */
first: boolean;
last: boolean;
/**
* How far the glass runs past each end of the piece, in metres, to meet the next piece of the pane:
* `[at its start, at its end]`. The glass sits in the middle of the wall, and two walls at an angle have
* two different middles, so the ends would otherwise stand a few centimetres apart and leave a slot.
*/
over: [number, number];
}
+118
View File
@@ -0,0 +1,118 @@
// Doors and garage doors: the door frame, leaves that turn on their hinges or slide, sidelights, handles, sectional garage doors.
import { Color } from "three";
import { isFrontDoor, openingStyle, sidelightLayout } from "../../model.ts";
import { ALWAYS, DEG, shade } from "../geo.ts";
import type { Ctx } from "./context.ts";
import { DOOR_ANGLE, FRAME, FRAME_TOP, GLASS, HANDLE, HANDLE_TOP, LEAF, LEAF_FRONT, LEAF_FRONT_TOP, LEAF_TOP, OPEN_WARM, SILL, UNLOCKED } from "./palette.ts";
import { flatPanel, panel, splitBox, type Frame } from "./primitives.ts";
/** The frame (Zarge) around a door or garage opening, covering the reveal on both faces. An open garage door glows warm. */
export function doorFrame(c: Ctx): void {
const { info, state, frame, fold } = c;
// B: the floor the door stands on – below 0 in a room set lower than its floor (floor_offset)
const [W, T, B] = [info.width, info.top, Math.min(0, info.sill)];
const garageOpen = info.opening.type === "garage" && (c.markClosed ? !!state.sensed && (state.cover ?? 1) >= 0.95 : (state.cover ?? 1) < 0.95);
const side = garageOpen ? shade(OPEN_WARM, 0.8) : new Color(FRAME);
const top = garageOpen ? shade(OPEN_WARM, 1) : new Color(FRAME_TOP);
const [n0, n1] = [-info.faceOut - 0.012, info.faceRoom + 0.012];
const piece = (x0: number, x1: number, y0: number) => splitBox(c.frames, frame, { x0, x1, n0, n1, y0, y1: T + 0.045 }, side, top, fold);
piece(-0.045, 0.02, B);
piece(W - 0.02, W + 0.045, B);
piece(0.02, W - 0.02, T - 0.02);
}
/** A door: one leaf or two, each turning around its hinge (or sliding), with sidelights, a threshold and handles. */
export function doorLeaves(c: Ctx): void {
const { info, state, frame, fold, mid } = c;
const [W, T, B] = [info.width, info.top, Math.min(0, info.sill)];
const H = T - B;
const style = openingStyle(info.opening, info.exterior);
const passage = style === "passage";
const front = isFrontDoor(style);
const swing = info.opening.swing === "out" ? -1 : 1;
// the leaves are flush with the face they swing towards (the room, or the other side)
const face = swing > 0 ? info.faceRoom : -info.faceOut;
const double = info.opening.leaves === 2;
const frameColor = new Color(FRAME);
const frameTop = new Color(FRAME_TOP);
// fixed glass beside the leaf: one sidelight opposite the hinge, or one on each side
let x0 = 0.02;
let x1 = W - 0.02;
const lights = sidelightLayout(W, style, info.hingeAtStart, info.opening);
if (lights) {
for (const [a, b] of lights.panels) {
const post = (xa: number, xb: number, ya: number, yb: number) => splitBox(c.frames, frame, { x0: xa, x1: xb, n0: mid - 0.03, n1: mid + 0.03, y0: ya, y1: yb }, frameColor, frameTop, fold);
post(a, a + 0.04, B + 0.02, T - 0.02);
post(b - 0.04, b, B + 0.02, T - 0.02);
post(a, b, B + 0.02, B + 0.1);
panel(c.glass, frame, a + 0.04, b - 0.04, mid, B + 0.1, T - 0.02, GLASS, fold);
}
x0 = lights.x0;
x1 = lights.x1;
}
const leafWidth = double ? (x1 - x0) / 2 - 0.004 : x1 - x0;
const thickness = front ? 0.06 : 0.04;
if (front) {
// a threshold across the wall, and a small light over the door outside
splitBox(c.frames, frame, { x0: 0.02, x1: W - 0.02, n0: -info.faceOut - 0.02, n1: info.faceRoom, y0: B, y1: B + 0.02 }, new Color(SILL), frameTop, fold);
if (info.exterior) splitBox(c.frames, frame, { x0: W / 2 - 0.08, x1: W / 2 + 0.08, n0: -info.faceOut - 0.1, n1: -info.faceOut, y0: T + 0.1, y1: T + 0.17 }, shade(OPEN_WARM, 0.55), shade(OPEN_WARM, 0.85), { cut: fold.cut, bucket: ALWAYS });
}
// the leaf's full swing: its own opening angle, else the usual one
const swingAngle = info.opening.open_angle ? Math.min(180, Math.max(5, info.opening.open_angle)) * DEG : DOOR_ANGLE;
const leaves: [boolean, number][] = passage ? [] : [[info.hingeAtStart, state.open]];
if (double && !passage) leaves.push([!info.hingeAtStart, state.open2 ?? 0]);
for (const [atStart, openness] of leaves) {
const open = Math.min(1, Math.max(0, openness));
const theta = style === "sliding" ? 0 : open * swingAngle;
// a sliding leaf runs along the wall face past the hinge side instead of turning
const slide = style === "sliding" ? open * leafWidth : 0;
const leafFrame: Frame = (u, n, y) => {
const along = u * Math.cos(theta) - n * Math.sin(theta) - slide;
const across = face + swing * (n * Math.cos(theta) + u * Math.sin(theta) + (slide ? 0.05 : 0));
return frame(atStart ? x0 + along : x1 - along, across, y);
};
// an open leaf has left its wall: keep it visible when the wall folds away
const leafFold = { cut: fold.cut, bucket: open > 0.05 ? ALWAYS : fold.bucket };
const warm = c.markClosed ? !!state.sensed && open < 0.05 : open > 0.9 && !(atStart === info.hingeAtStart && state.assumed);
const side = warm ? shade(OPEN_WARM, 0.7) : new Color(front ? LEAF_FRONT : LEAF);
const top = warm ? shade(OPEN_WARM, 0.9) : new Color(front ? LEAF_FRONT_TOP : LEAF_TOP);
const part = (xa: number, xb: number, ya: number, yb: number, na = -thickness, nb = 0) => splitBox(c.frames, leafFrame, { x0: xa, x1: xb, n0: na, n1: nb, y0: ya, y1: yb }, side, top, leafFold);
if (style === "glass") {
// a glass door: slim stiles and rails around a pane
part(0, 0.05, B + 0.01, T - 0.01);
part(leafWidth - 0.05, leafWidth, B + 0.01, T - 0.01);
part(0.05, leafWidth - 0.05, B + 0.01, B + 0.12);
part(0.05, leafWidth - 0.05, T - 0.08, T - 0.01);
panel(c.glass, leafFrame, 0.05, leafWidth - 0.05, -thickness / 2, B + 0.12, T - 0.08, GLASS, leafFold);
} else part(0, leafWidth, B + 0.01, T - 0.01);
if (style === "front_glass") panel(c.glass, leafFrame, 0.12, leafWidth - 0.12, 0.001, B + H * 0.55, T - 0.18, GLASS, leafFold);
else if (front) panel(c.glass, leafFrame, 0.1, 0.18, 0.001, B + 0.3, T - 0.3, GLASS, leafFold);
// a handle on both sides: a knob on a room door, a bar on a front door
const height = B + Math.min(1.05, H * 0.5);
const half = front ? 0.3 : 0.012;
const [hx0, hx1] = front ? [leafWidth - 0.11, leafWidth - 0.08] : [leafWidth - 0.16, leafWidth - 0.05];
const handle = (na: number, nb: number) => splitBox(c.frames, leafFrame, { x0: hx0, x1: hx1, n0: na, n1: nb, y0: height - half, y1: height + half }, new Color(HANDLE), new Color(HANDLE_TOP), leafFold);
handle(0.004, 0.05);
handle(-thickness - 0.05, -thickness - 0.004);
// an unlocked smart lock: the leaf's free edge glows in the accent (cyan follows the user's accent colour)
if (state.unlocked) {
const glow = new Color(UNLOCKED);
splitBox(c.frames, leafFrame, { x0: leafWidth - 0.012, x1: leafWidth + 0.004, n0: -thickness - 0.004, n1: 0.004, y0: B + 0.06, y1: T - 0.06 }, glow, glow, { cut: fold.cut, bucket: ALWAYS });
}
}
}
/** A sectional garage door: the closed part hangs in the opening, the open part lies under the ceiling. */
export function garageDoor(c: Ctx): void {
const { info, state, frame, fold } = c;
const [W, T, B] = [info.width, info.top, Math.min(0, info.sill)];
const closed = Math.min(1, Math.max(0, state.cover ?? 1));
const color = new Color(0xd4e0ff);
const plane = info.faceRoom - 0.03;
if (closed > 0.01) panel(c.blinds, frame, 0.02, W - 0.02, plane, B + (T - B) * (1 - closed), T, color, fold, 0.5);
const lifted = (1 - closed) * (T - B);
if (lifted > 0.01) flatPanel(c.blinds, frame, 0.02, W - 0.02, plane, plane + lifted, T + 0.03, color, fold.bucket, 0.5);
}
@@ -0,0 +1,46 @@
// The light well in front of a cellar window: a concrete pit outside the window from below its sill up to the ground, with a grating
// on top at ground level. It comes by itself for an outer window whose sill lies below the ground, and can be switched off per window.
import { Color } from "three";
import { ALWAYS } from "../geo.ts";
import type { Ctx } from "./context.ts";
import { splitBox } from "./primitives.ts";
const CONCRETE = 0x4b5262;
const CONCRETE_TOP = 0x6b7386;
const GRATING = 0x2a303c;
const GRATING_TOP = 0x8a94a8;
/** Whether a window gets a light well: outside, its sill below the ground (ground is in the floor's own coordinates). */
export function needsLightWell(ctx: Pick<Ctx, "info">, ground: number): boolean {
const { info } = ctx;
if (info.opening.type !== "window" || !info.exterior || info.opening.light_well === false) return false;
return info.opening.light_well === true || info.sill < ground - 0.02;
}
/** A light well outside the window: three concrete walls, a floor and a grating at ground level. */
export function lightWell(c: Ctx, ground: number): void {
const { info, frame } = c;
const fold = { cut: c.fold.cut, bucket: ALWAYS };
const [w0, w1] = [-0.12, info.width + 0.12];
const outer = -info.faceOut;
const depth = 0.7;
const bottom = Math.min(info.sill - 0.25, ground - 0.3);
const top = ground;
const side = new Color(CONCRETE);
const cap = new Color(CONCRETE_TOP);
const t = 0.07;
const wall = (x0: number, x1: number, n0: number, n1: number) => splitBox(c.frames, frame, { x0, x1, n0, n1, y0: bottom, y1: top }, side, cap, fold);
wall(w0 - t, w0, outer - depth, outer);
wall(w1, w1 + t, outer - depth, outer);
wall(w0 - t, w1 + t, outer - depth - t, outer - depth);
splitBox(c.frames, frame, { x0: w0, x1: w1, n0: outer - depth, n1: outer, y0: bottom - t, y1: bottom }, side, cap, fold);
// the grating: bars across the pit at ground level
const bar = (x0: number, x1: number) => splitBox(c.frames, frame, { x0, x1, n0: outer - depth, n1: outer, y0: top - 0.025, y1: top }, new Color(GRATING), new Color(GRATING_TOP), fold);
const bars = Math.max(3, Math.round((w1 - w0) / 0.06));
for (let i = 0; i <= bars; i++) {
const x = w0 + ((w1 - w0) * i) / bars;
bar(x - 0.008, x + 0.008);
}
splitBox(c.frames, frame, { x0: w0, x1: w1, n0: outer - depth - 0.01, n1: outer - depth + 0.02, y0: top - 0.03, y1: top }, new Color(GRATING), new Color(GRATING_TOP), fold);
}
@@ -0,0 +1,301 @@
import assert from "node:assert/strict";
import { test } from "node:test";
import { newFloor, type Opening } from "../../model.ts";
import { buildFloorGeometry } from "../build.ts";
import { buildOpeningParts, CLOSED, type OpeningState } from "../openings.ts";
import { slidingPanes } from "./windows.ts";
import { frontPieces } from "../../geometry/glass-front.ts";
const room = { id: "a", name: "a", area_id: null, points: [[0, 0], [6, 0], [6, 5], [0, 5]] as [number, number][], floor_material: "wood" as const };
function infosFor(opening: Partial<Opening>) {
const full = { id: "o", room_id: "a", edge: 0, offset: 1.5, width: 1.2, type: "window", sill: 0.9, height: 1.3, hinge: "left", leaves: 1, swing: "in", cover: null, contact: null, contact2: null, tilt: null, ...opening } as Opening;
return buildFloorGeometry({ ...newFloor("f", "F", 0), rooms: [room], openings: [full] }, 0.3, 0.1).openings;
}
const triangles = (g: { getAttribute(n: string): { count: number } | undefined }) => (g.getAttribute("position")?.count ?? 0) / 3;
const build = (opening: Partial<Opening>, state: Partial<OpeningState> = {}, cut = 1.2) => buildOpeningParts(infosFor(opening), new Map([["o", { ...CLOSED, ...state }]]), cut);
const positions = (g: { getAttribute(n: string): { array: ArrayLike<number> } | undefined }) => Array.from(g.getAttribute("position")?.array ?? []);
test("a window has frame parts and glass, and no blind without a cover", () => {
const parts = build({});
assert.ok(triangles(parts.frames) > 20);
assert.ok(triangles(parts.glass) >= 2);
assert.equal(triangles(parts.blinds), 0);
});
test("a blind adds a box above the window and slats down to the closed fraction", () => {
const without = build({});
const up = build({}, { cover: 0 });
const half = build({}, { cover: 0.5 });
assert.ok(triangles(up.frames) > triangles(without.frames), "the blind box");
assert.equal(triangles(up.blinds), 0, "raised: no slats");
assert.ok(triangles(half.blinds) > 0);
const lowest = (parts: ReturnType<typeof build>) => Math.min(...positions(parts.blinds).filter((_, i) => i % 3 === 1));
assert.ok(lowest(build({}, { cover: 1 })) < lowest(half), "further down when more closed");
});
test("an open window swings its sash into the room, and a tilted one leans", () => {
const closed = positions(build({}).frames);
const open = positions(build({}, { open: 1 }).frames);
const tilted = positions(build({}, { tilt: 1 }).frames);
assert.equal(closed.length, open.length);
assert.notDeepEqual(closed, open);
assert.notDeepEqual(closed, tilted);
// the swung-open sash reaches into the room: further from the wall than any part of the closed window
const depth = (p: number[]) => Math.max(...p.filter((_, i) => i % 3 === 2));
assert.ok(depth(open) > depth(closed));
});
test("a double window has two sashes that move on their own", () => {
const single = triangles(build({ leaves: 1 }).frames);
const double = triangles(build({ leaves: 2 }).frames);
assert.ok(double > single);
assert.notDeepEqual(positions(build({ leaves: 2 }, { open: 1, open2: 0 }).frames), positions(build({ leaves: 2 }, { open: 0, open2: 1 }).frames));
});
test("glazing bars add to the sash, a glass wall has mullions instead of sashes", () => {
assert.ok(triangles(build({ style: "bars" }).frames) > triangles(build({}).frames));
const wall = build({ style: "glass_wall", width: 2.7, sill: 0, height: 2.4 });
assert.ok(triangles(wall.glass) >= 3 * 2, "three panes");
});
test("a door has a frame, a leaf and handles; a passage only a gap", () => {
const door = build({ type: "door", width: 0.9, sill: 0, height: 2.05 });
assert.ok(triangles(door.frames) > 50);
const passage = build({ type: "door", style: "passage", width: 0.9, sill: 0, height: 2.05 });
assert.equal(triangles(passage.frames), 0);
assert.equal(triangles(passage.glass), 0);
});
test("a door leaf swings around its hinge, a sliding one slides along the wall", () => {
const door = (state: Partial<OpeningState>, extra: Partial<Opening> = {}) => positions(build({ type: "door", width: 0.9, sill: 0, height: 2.05, ...extra }, state).frames);
assert.notDeepEqual(door({ open: 0 }), door({ open: 1 }));
const closed = door({ open: 0 }, { style: "sliding" });
const slid = door({ open: 1 }, { style: "sliding" });
const depth = (p: number[]) => Math.max(...p.filter((_, i) => i % 3 === 2)) - Math.min(...p.filter((_, i) => i % 3 === 2));
assert.ok(Math.abs(depth(closed) - depth(slid)) < 0.1, "a sliding leaf stays in the wall's depth");
});
test("front doors and glass doors have glass; room doors have none", () => {
const glassOf = (style: string) => triangles(build({ type: "door", style: style as never, width: 0.9, sill: 0, height: 2.05 }).glass);
assert.equal(glassOf("interior"), 0);
assert.ok(glassOf("front") > 0);
assert.ok(glassOf("front_glass") >= glassOf("front"));
assert.ok(glassOf("glass") > 0);
assert.ok(glassOf("sidelight") > 0, "a fixed pane beside the leaf");
});
test("a garage door shows panels while closed and lifts them under the ceiling when open", () => {
const garage = (cover: number) => build({ type: "garage", width: 2.5, sill: 0, height: 2.1 }, { cover });
assert.ok(triangles(garage(1).blinds) > 0);
assert.ok(triangles(garage(0).blinds) > 0, "the lifted part lies flat under the ceiling");
assert.ok(triangles(garage(1).frames) > 0);
});
test("the triangle ranges say which opening each part belongs to", () => {
const infos = infosFor({});
const parts = buildOpeningParts(infos, new Map(), 1.2);
assert.deepEqual(parts.frameTris.map((r) => r.id), ["o"]);
assert.equal(parts.frameTris[0].start, 0);
assert.equal(parts.frameTris[0].end, triangles(parts.frames));
assert.equal(parts.glassTris[0].end, triangles(parts.glass));
});
test("parts above the cut height carry the wall's fold bucket, the rest are always shown", () => {
const folds = (cut: number) => Array.from(build({}, {}, cut).frames.getAttribute("fold")!.array);
assert.ok(new Set(folds(10)).size === 1, "everything below the cut: always shown");
assert.ok(new Set(folds(0.1)).size >= 1);
assert.ok(folds(1.2).includes(-1));
assert.ok(folds(1.2).some((f) => f !== -1), "the part above the cut folds with the wall");
});
test("an open window glows warm; with 'mark closed' the closed one does", () => {
const colorSum = (parts: ReturnType<typeof build>) => Array.from(parts.frames.getAttribute("color")!.array).reduce((a, b) => a + b, 0);
assert.ok(colorSum(build({}, { open: 1 })) > colorSum(build({})));
const marked = (open: number) => colorSum(build({ mark: "closed" } as never, { open, sensed: true }));
assert.ok(marked(0) > marked(1));
});
test("a sliding window: the pane at the hinge side slides in front of the fixed one; four panes with two leaves", () => {
const one = slidingPanes(2.4, 0.06, true, 1, 1, 0);
assert.equal(one.length, 2);
assert.ok(one[0].slide! > 1, "the moving pane runs about half the width");
assert.equal(one[1].slide, 0);
assert.ok(one[0].x1 > one[1].x0, "the panes overlap in the middle");
const four = slidingPanes(3.2, 0.06, true, 2, 1, 1);
assert.deepEqual(four.map((p) => Math.sign(p.slide!)), [0, -1, 1, 0]);
const mirrored = slidingPanes(2.4, 0.06, false, 1, 1, 0);
assert.ok(mirrored[1].slide! < 0 && mirrored[0].slide === 0);
});
test("an open sliding door stays in the wall and moves along it; a top-hung window swings out at the bottom", () => {
const door = { opens: "slide" as const, sill: 0, height: 2.15, width: 2.4 };
const closed = positions(build(door).frames);
const open = positions(build(door, { open: 1 }).frames);
const depth = (p: number[]) => Math.max(...p.filter((_, i) => i % 3 === 2));
assert.notDeepEqual(closed, open);
assert.ok(depth(open) <= depth(closed) + 1e-6, "no part reaches into the room");
const top = { opens: "top" as const };
const out = (p: number[]) => Math.min(...p.filter((_, i) => i % 3 === 2));
assert.ok(out(positions(build(top, { open: 1 }).frames)) < out(positions(build(top).frames)) - 0.1, "the bottom leaves the wall towards outside");
// a tilt sensor opens a top-hung window as well
assert.notDeepEqual(positions(build(top, { tilt: 1 }).frames), positions(build(top).frames));
});
test("a door in a lowered room stands on that room's floor, not on the floor level", () => {
const lowered = { ...room, floor_offset: -0.39 };
const opening = { id: "o", room_id: "a", edge: 0, offset: 1.5, width: 0.9, type: "door", sill: 0, height: 1.87, hinge: "left", leaves: 1, swing: "in", cover: null, contact: null, contact2: null, tilt: null } as Opening;
const infos = buildFloorGeometry({ ...newFloor("f", "F", 0), rooms: [lowered], openings: [opening] }, 0.3, 0.1).openings;
const parts = buildOpeningParts(infos, new Map([["o", CLOSED]]), 1.2);
const ys = positions(parts.frames).filter((_, i) => i % 3 === 1);
assert.ok(Math.abs(Math.min(...ys) - -0.39) < 0.02, `lowest part at ${Math.min(...ys)}`);
});
test("a glass wall divides into about 0.9 m panes unless it is told how many", () => {
const wall = (panes?: number | null) => build({ type: "window", sill: 0, height: 2.4, width: 3.6, style: "glass_wall", ...(panes === undefined ? {} : { panes }) });
const auto = wall();
const one = wall(0);
const three = wall(3);
// one pane: no mullion at all, so fewer frame boxes and a single sheet of glass
assert.ok(triangles(one.frames) < triangles(auto.frames), "a single pane has no mullions");
assert.equal(triangles(one.glass), 4, "one pane is one quad, glazed on both sides");
// a number of its own wins over the automatic spacing
assert.ok(triangles(three.frames) < triangles(auto.frames));
assert.ok(triangles(three.frames) > triangles(one.frames), "three panes have two mullions");
assert.equal(triangles(three.glass), 12, "three panes");
// an unchanged plan keeps exactly what it drew before: the automatic spacing
assert.equal(triangles(auto.glass), 16, "3.6 m gives four panes of about 0.88 m");
});
/** A curved wall: ten edges of 1 m, each turning 10 degrees the same way, closed by one back edge. */
function curvedRoom() {
const points: [number, number][] = [[0, 0]];
let [x, z, a] = [0, 0, 0];
for (let i = 0; i < 10; i++) {
a += (10 * Math.PI) / 180;
x += Math.cos(a);
z += Math.sin(a);
points.push([x, z]);
}
return { ...room, points };
}
/** Six pieces of one pane on that wall, in the order the plan lists them. */
function pane(backwards = false) {
const curved = curvedRoom();
const pieces = frontPieces(curved, 0, 6)!;
const list = pieces.map(
(p, k) =>
({
id: `g${k}`,
room_id: "a",
edge: p.edge,
offset: p.offset,
width: p.width,
front: "f",
type: "window",
sill: 0,
height: 2.4,
style: "glass_wall",
hinge: "left",
leaves: 1,
swing: "in",
cover: null,
contact: null,
contact2: null,
tilt: null,
}) as Opening,
);
// the order the openings are listed in is the order the plan happens to hold them, which on a curved
// wall is not necessarily the order along the outline
return buildFloorGeometry({ ...newFloor("f", "F", 0), rooms: [curved], openings: backwards ? list.reverse() : list }, 0.3, 0.1).openings;
}
/** The plan points where two pieces of one pane meet, and the two outer ends of the pane. */
function paneEnds(infos: readonly { start: [number, number]; axis: [number, number]; width: number }[]) {
const key = (p: [number, number]) => `${Math.round(p[0] * 50)},${Math.round(p[1] * 50)}`;
const end = (i: number): [number, number] => [infos[i].start[0] + infos[i].axis[0] * infos[i].width, infos[i].start[1] + infos[i].axis[1] * infos[i].width];
const count = new Map<string, number>();
const at = new Map<string, [number, number]>();
infos.forEach((_, i) => {
for (const p of [infos[i].start as [number, number], end(i)]) {
count.set(key(p), (count.get(key(p)) ?? 0) + 1);
at.set(key(p), p);
}
});
const joins = [...count].filter(([, n]) => n > 1).map(([k]) => at.get(k)!);
const outer = [...count].filter(([, n]) => n === 1).map(([k]) => at.get(k)!);
return { joins, outer };
}
/** One pane must be one sheet: no slot between its pieces and no frame standing in it. */
function assertOneSheet(infos: ReturnType<typeof pane>) {
const joined = buildOpeningParts(infos, new Map([["f", CLOSED]]), 1.2);
const gp = positions(joined.glass);
const fp = positions(joined.frames);
const { joins, outer } = paneEnds(infos);
assert.equal(joins.length, infos.length - 1, "one join between each two pieces, and none at the outer ends");
assert.equal(outer.length, 2, "a pane has two outer ends");
for (const [jx, jz] of joins) {
// the glass sits in the middle of the wall, so two walls at an angle have two different middles, and
// ends that stop at their own middle stand 2.6 cm apart on a 10 degree bend — a slot through the pane
const near: [number, number, number][] = [];
// the glass stands in the middle of the wall, half a thickness off the axis the join sits on
for (let i = 0; i + 2 < gp.length; i += 3) if (Math.hypot(gp[i] - jx, gp[i + 2] - jz) < 0.2) near.push([gp[i], gp[i + 1], gp[i + 2]]);
let worst = 0;
// in plan only: two vertices on one vertical line are the same point of the sheet, whatever their height
for (const a of near) for (const b of near) worst = Math.max(worst, Math.hypot(a[0] - b[0], a[2] - b[2]));
assert.ok(near.length > 0, "the pieces reach the join");
assert.ok(worst < 0.002, `the two pieces meet at (${jx.toFixed(2)},${jz.toFixed(2)}), not ${worst.toFixed(3)} m apart`);
// a jamb drawn at a join is a 4 cm post standing in the middle of the glass
let post = 0;
for (let i = 0; i + 2 < fp.length; i += 3) {
if (fp[i + 1] < 0.1 || fp[i + 1] > 2.3) continue;
if (Math.hypot(fp[i] - jx, fp[i + 2] - jz) < 0.2) post++;
}
assert.equal(post, 0, "no frame stands in the glass at a join");
}
for (const [ox, oz] of outer) {
let jamb = 0;
for (let i = 0; i + 2 < fp.length; i += 3) {
if (fp[i + 1] < 0.1 || fp[i + 1] > 2.3) continue;
if (Math.hypot(fp[i] - ox, fp[i + 2] - oz) < 0.2) jamb++;
}
assert.ok(jamb > 0, "the outer ends of a pane do carry a jamb");
}
}
test("a pane over several edges is glazed as one, without jambs where its pieces meet", () => {
const infos = pane();
// every piece finds its own wall: none is dropped
assert.equal(infos.length, 6);
const joined = buildOpeningParts(infos, new Map([["f", CLOSED]]), 1.2);
const apart = buildOpeningParts(
infos.map((i) => ({ ...i, opening: { ...i.opening, front: null } })),
new Map(),
1.2,
);
assert.ok(triangles(joined.frames) < triangles(apart.frames), "no jamb where two pieces of one pane meet");
// the glass itself stays the same, however the pieces are grouped
assert.equal(triangles(joined.glass), triangles(apart.glass));
assertOneSheet(infos);
});
test("the order the plan lists the pieces in does not decide where the jambs go", () => {
// the openings of a curved wall are stored in the order the plan holds them, which is not always the
// order along the outline. Taking the first and the last of that list as the pane's ends puts both
// jambs of a two-piece pane right where the two pieces meet.
const infos = pane(true);
assert.equal(infos.length, 6);
assertOneSheet(infos);
});
test("a garage door with a cover gets no roller blind in front of it (#85)", () => {
const door = build({ type: "garage", width: 2.5, sill: 0, height: 2.1 }, { cover: 1 });
const panelOnly = build({ type: "garage", width: 2.5, sill: 0, height: 2.1 }, { cover: 1, cover2: null });
assert.equal(triangles(door.blinds), triangles(panelOnly.blinds));
// the outside blind box (cassette above the opening) is not drawn: no frame part reaches 0.2 m above the top
const ys = positions(door.frames).filter((_, i) => i % 3 === 1);
assert.ok(Math.max(...ys) < 2.1 + 0.15, "no blind cassette above a garage door");
});
+27
View File
@@ -0,0 +1,27 @@
// Colours and angles of doors and windows.
import { shade } from "../geo.ts";
export const FRAME = 0x1f3052;
export const FRAME_TOP = 0x2a4270;
export const SASH = 0x22375f;
export const SILL = 0x1c2a47;
export const BLIND_BOX = 0x16223a;
/** The warm glow of a window or door that is open, or that should be closed. */
export const OPEN_WARM = 0xffb547;
export const LEAF = 0x1c2c4d;
export const LEAF_TOP = 0x27406b;
export const LEAF_FRONT = 0x111a30;
export const LEAF_FRONT_TOP = 0x1c2a47;
/** The free edge of a door whose smart lock is unlocked: the stock cyan, which the neon look turns into the user's accent. */
export const UNLOCKED = 0x37e0ff;
export const HANDLE = 0x5b7cff;
export const HANDLE_TOP = 0x8aa2ff;
export const GLASS = shade(0x37e0ff, 0.08);
/** How far a window sash swings open, how far a door leaf, and how far a tilted sash leans (radians). */
export const OPEN_ANGLE = 1.2;
export const DOOR_ANGLE = 1.5;
export const TILT_ANGLE = 0.2;
/** How far a top-hung sash swings out at the bottom when open (about 30°). */
export const TOP_HUNG_ANGLE = 0.52;
+114
View File
@@ -0,0 +1,114 @@
// The moving and state-dependent parts of doors and windows: fixed frames, sashes with glass (open or tilted, from contact
// sensors), window sills, door frames, blind boxes and blind slats. They are rebuilt as merged geometry whenever a state
// changes (and during the short open/close animation), so all windows of a floor stay three draw calls: frames, glass and blinds.
import { openingStyle, type Vec2 } from "../../model.ts";
import type { OpeningInfo } from "../build.ts";
import { GeoBuffer } from "../geo.ts";
import { blind } from "./blinds.ts";
import type { Ctx } from "./context.ts";
import { doorFrame, doorLeaves, garageDoor } from "./doors.ts";
import { lightWell, needsLightWell } from "./light-well.ts";
import { CLOSED, type OpeningParts, type OpeningState, type TriRange } from "./types.ts";
import { glassWall, window } from "./windows.ts";
/** The id that groups the pieces of one glass pane; a normal opening is a group of its own. */
const paneOf = (info: OpeningInfo): string => info.opening.front ?? info.opening.id;
export function buildOpeningParts(infos: readonly OpeningInfo[], states: ReadonlyMap<string, OpeningState>, cut: number, ground = -Infinity): OpeningParts {
const frames = new GeoBuffer();
const glass = new GeoBuffer();
const blinds = new GeoBuffer(true);
const frameTris: TriRange[] = [];
const glassTris: TriRange[] = [];
const blindTris: TriRange[] = [];
// pieces of one pane that follows a curved wall: only the two outer ends get a jamb, so the glass is
// continuous where two of them meet. Every other opening is a group of one and keeps both jambs.
const groups = new Map<string, number[]>();
infos.forEach((info, i) => {
const key = paneOf(info);
groups.set(key, [...(groups.get(key) ?? []), i]);
});
// Which end is an outer end does not follow from the order of the plan: the pieces of one pane are
// stored in whatever order the openings happen to be listed, and on a curved wall that is often not the
// order along the outline. It follows from the geometry instead — an end that another piece of the same
// pane meets is a join, not the end of the pane. Getting this wrong draws both jambs of a two-piece
// pane right at the join between them, which is a 4 cm post standing in the middle of the glass.
const endsOf = (info: OpeningInfo): [Vec2, Vec2] => [
[info.start[0], info.start[1]],
[info.start[0] + info.axis[0] * info.width, info.start[1] + info.axis[1] * info.width],
];
const keyOf = (p: Vec2) => `${Math.round(p[0] * 50)},${Math.round(p[1] * 50)}`;
const ends = new Map<number, [boolean, boolean]>();
// Two walls at an angle have two different middles, so the ends of two pieces of one pane stand
// 2 * mid * sin(angle/2) apart — 2.6 cm on a 10 degree bend, which reads as a slot through the glass.
// Running each piece into the bisector of the bend (mid * tan(angle/2)) puts both end edges on the same
// vertical line, and the pane is one surface again. A real corner is left alone: there the miter would
// be longer than the wall is thick, and a corner is allowed to look like a corner.
const over = new Map<number, [number, number]>();
for (const list of groups.values()) {
const startsAt = new Map<string, number[]>();
const endsAt = new Map<string, number[]>();
for (const i of list) {
const [s, e] = endsOf(infos[i]);
startsAt.set(keyOf(s), [...(startsAt.get(keyOf(s)) ?? []), i]);
endsAt.set(keyOf(e), [...(endsAt.get(keyOf(e)) ?? []), i]);
}
const reach = (i: number, other: number | undefined) => {
if (other == null || other === i) return 0;
const mid = Math.abs((infos[i].faceRoom - infos[i].faceOut) / 2);
const [a, b] = [infos[i].axis, infos[other].axis];
const cos = Math.max(-1, Math.min(1, a[0] * b[0] + a[1] * b[1]));
const angle = Math.acos(cos);
return angle < Math.PI / 2 ? Math.min(mid * Math.tan(angle / 2), mid) : 0;
};
for (const i of list) {
const [s, e] = endsOf(infos[i]);
const before = (endsAt.get(keyOf(s)) ?? []).find((j) => j !== i);
const after = (startsAt.get(keyOf(e)) ?? []).find((j) => j !== i);
ends.set(i, [before == null, after == null]);
over.set(i, [reach(i, before), reach(i, after)]);
}
}
for (let i = 0; i < infos.length; i++) {
const info = infos[i];
const starts = { frames: frames.count, glass: glass.count, blinds: blinds.count };
const type = info.opening.type;
const style = openingStyle(info.opening, info.exterior);
const [first, last] = ends.get(i) ?? [true, true];
const ctx: Ctx = {
info,
state: states.get(paneOf(info)) ?? CLOSED,
// local frame: x from the opening's start along the wall, n from the wall axis towards the room
frame: (x, n, y) => [info.start[0] + info.axis[0] * x + info.toRoom[0] * n, y, info.start[1] + info.axis[1] * x + info.toRoom[1] * n],
mid: (info.faceRoom - info.faceOut) / 2,
// highlighted while open, or while closed when the opening asks for it (and a sensor knows)
markClosed: info.opening.mark === "closed",
fold: { cut, bucket: info.bucket },
frames,
glass,
blinds,
first,
last,
over: over.get(i) ?? [0, 0],
};
// a passage (a wall opening without a door) shows nothing but the gap in the wall
if ((type === "door" && style !== "passage") || type === "garage") doorFrame(ctx);
if (type === "door") doorLeaves(ctx);
else if (type === "garage") garageDoor(ctx);
else if (style === "glass_wall") glassWall(ctx);
else window(ctx);
// a cellar window below the ground gets its light well
if (needsLightWell(ctx, ground)) lightWell(ctx, ground);
// a garage door's cover moves the door itself; it has no blind in front of it (#85)
if (type !== "garage") blind(ctx);
// picking returns the id the model knows, not a piece id
const id = paneOf(info);
frameTris.push({ id, start: starts.frames, end: frames.count });
glassTris.push({ id, start: starts.glass, end: glass.count });
blindTris.push({ id, start: starts.blinds, end: blinds.count });
}
return { frames: frames.geometry(), glass: glass.geometry(), blinds: blinds.geometry(), frameTris, glassTris, blindTris };
}
@@ -0,0 +1,74 @@
// Building blocks for the moving parts of doors and windows. Everything is placed in a local frame of an opening: x runs
// along the opening from its start, n points from the wall axis towards the room, y is up.
import { Color } from "three";
import { ALWAYS, shade, type GeoBuffer } from "../geo.ts";
/** Maps a local (x, n, y) to world coordinates. */
export type Frame = (x: number, n: number, y: number) => number[];
export interface Box {
x0: number;
x1: number;
n0: number;
n1: number;
y0: number;
y1: number;
}
/** A box with all six faces; the lower, near and side faces are a little darker than the top and the far face. */
export function box(buf: GeoBuffer, frame: Frame, b: Box, side: Color, top: Color, fold: number): void {
const p = (x: number, n: number, y: number) => frame(x, n, y);
const { x0, x1, n0, n1, y0, y1 } = b;
const tint = (k: number) => shade(side.getHex(), k);
const faces: [number[], number[], number[], number[], Color][] = [
[p(x0, n0, y1), p(x1, n0, y1), p(x1, n1, y1), p(x0, n1, y1), top],
[p(x0, n0, y0), p(x1, n0, y0), p(x1, n1, y0), p(x0, n1, y0), tint(0.6)],
[p(x0, n1, y0), p(x1, n1, y0), p(x1, n1, y1), p(x0, n1, y1), side],
[p(x0, n0, y0), p(x1, n0, y0), p(x1, n0, y1), p(x0, n0, y1), tint(0.85)],
[p(x0, n0, y0), p(x0, n1, y0), p(x0, n1, y1), p(x0, n0, y1), tint(0.92)],
[p(x1, n0, y0), p(x1, n1, y0), p(x1, n1, y1), p(x1, n0, y1), tint(0.92)],
];
for (const [a, b2, c, d, color] of faces) {
buf.tri(a, b2, c, color, color, color, undefined, fold);
buf.tri(a, c, d, color, color, color, undefined, fold);
}
}
/** The cut height and the fold bucket of the wall a part sits in: what lies above the cut folds away with the wall. */
export interface Fold {
cut: number;
bucket: number;
}
/** A box split at the cut height: the part above folds away with its wall. */
export function splitBox(buf: GeoBuffer, frame: Frame, b: Box, side: Color, top: Color, { cut, bucket }: Fold): void {
if (b.y1 <= cut + 1e-6) return box(buf, frame, b, side, top, ALWAYS);
if (b.y0 >= cut - 1e-6) return box(buf, frame, b, side, top, bucket);
box(buf, frame, { ...b, y1: cut }, side, top, ALWAYS);
box(buf, frame, { ...b, y0: cut }, side, top, bucket);
}
/** A flat upright quad in a local plane (glass, slats), split at the cut height, with optional uvs (`vScale` metres per texture repeat). */
export function panel(buf: GeoBuffer, frame: Frame, x0: number, x1: number, n: number, y0: number, y1: number, color: Color, { cut, bucket }: Fold, vScale = 0): void {
const piece = (ya: number, yb: number, fold: number) => {
const v = (y: number) => (vScale ? (y1 - y) / vScale : 0.5);
const [a, b, c, d] = [frame(x0, n, ya), frame(x1, n, ya), frame(x1, n, yb), frame(x0, n, yb)];
buf.tri(a, b, c, color, color, color, [0, v(ya), 1, v(ya), 1, v(yb)], fold);
buf.tri(a, c, d, color, color, color, [0, v(ya), 1, v(yb), 0, v(yb)], fold);
};
if (y1 <= cut + 1e-6) piece(y0, y1, ALWAYS);
else if (y0 >= cut - 1e-6) piece(y0, y1, bucket);
else {
piece(y0, cut, ALWAYS);
piece(cut, y1, bucket);
}
}
/** A horizontal quad in the local frame at height y (the open part of a garage door). */
export function flatPanel(buf: GeoBuffer, frame: Frame, x0: number, x1: number, n0: number, n1: number, y: number, color: Color, fold: number, vScale: number): void {
const [a, b, c, d] = [frame(x0, n0, y), frame(x1, n0, y), frame(x1, n1, y), frame(x0, n1, y)];
const v1 = (n1 - n0) / vScale;
buf.tri(a, b, c, color, color, color, [0, 0, 1, 0, 1, v1], fold);
buf.tri(a, c, d, color, color, color, [0, 0, 1, v1, 0, v1], fold);
}
+42
View File
@@ -0,0 +1,42 @@
import type { BufferGeometry } from "three";
export interface OpeningState {
/** A window sash or door leaf: 0 closed, 1 swung open. */
open: number;
/** The second leaf of a double door or window. */
open2?: number;
/** 0 closed, 1 tilted. */
tilt: number;
/** The second leaf tilted. */
tilt2?: number;
/** The closed fraction of the blind or garage door (0 up, 1 down); null: no blind. */
cover: number | null;
/** A sensor reports the state (contact, tilt sensor or cover); without one "closed" is a guess. */
sensed?: boolean;
/** A door with a smart lock that stands unlocked: its free edge glows. */
unlocked?: boolean;
/** The door leaf stands where it is assumed to, as no sensor tells: it does not glow as open. */
assumed?: boolean;
/** The second blind of a wide window (its right half): its closed fraction. */
cover2?: number | null;
/** Venetian blinds: how far the slats are open (0 shut, 1 level). */
slats?: number | null;
}
export const CLOSED: OpeningState = { open: 0, open2: 0, tilt: 0, tilt2: 0, cover: null };
export interface TriRange {
id: string;
start: number;
end: number;
}
export interface OpeningParts {
frames: BufferGeometry;
glass: BufferGeometry;
blinds: BufferGeometry;
/** The triangle ranges per opening in frames, glass and blinds, so they can be tapped in 3D. */
frameTris: TriRange[];
glassTris: TriRange[];
blindTris: TriRange[];
}
+169
View File
@@ -0,0 +1,169 @@
// Windows: the fixed frame, sill and board, sashes that turn into the room or tilt, slide (a lift-and-slide door) or swing out
// at the bottom (top-hung), glazing bars, and indoor glass walls.
import { Color } from "three";
import { openingStyle } from "../../model.ts";
import { ALWAYS, shade } from "../geo.ts";
import type { Ctx } from "./context.ts";
import { FRAME, FRAME_TOP, GLASS, OPEN_ANGLE, OPEN_WARM, SASH, SILL, TILT_ANGLE, TOP_HUNG_ANGLE } from "./palette.ts";
import { panel, splitBox, type Frame } from "./primitives.ts";
/**
* An indoor glass wall: a slim frame, glass from the floor up, no sashes. The mullions divide it into as many panes as the
* opening asks for; without a number they come about every 0.9 m, and none at all for a single full pane.
*/
export function glassWall(c: Ctx): void {
const { info, frame, fold, mid } = c;
const [W, S, T] = [info.width, info.sill, info.top];
const [fw, fd] = [0.04, 0.025];
const frameColor = new Color(FRAME);
const frameTop = new Color(FRAME_TOP);
const bar = (x0: number, x1: number, y0: number, y1: number) => splitBox(c.frames, frame, { x0, x1, n0: mid - fd, n1: mid + fd, y0, y1 }, frameColor, frameTop, fold);
// a pane over several edges has jambs only at its two outer ends; where two pieces meet, the glass runs on
if (c.first) bar(0, fw, S, T);
if (c.last) bar(W - fw, W, S, T);
// the 4 cm at each end is the rebate of a jamb. A piece of a pane that does not end here has no jamb, so
// its rails and its glass reach the wall end — and run past it into the bisector of the bend, where the
// next piece begins: two pieces whose ends stop at their own wall's middle stand a slot apart.
const [xa, xb] = [c.first ? fw : -c.over[0], c.last ? W - fw : W + c.over[1]];
bar(xa, xb, S, S + 0.03);
bar(xa, xb, T - fw, T);
// a piece of a pane over several edges is part of one sheet: it gets no mullions of its own, and a pane
// that is to be divided is placed as separate openings instead (their jambs are the divisions)
const asked = info.opening.front ? 0 : info.opening.panes;
const panes = Math.max(1, asked == null ? Math.max(1, Math.round((xb - xa) / 0.9)) : Math.round(asked));
const paneWidth = (xb - xa) / panes;
for (let k = 1; k < panes; k++) bar(xa + k * paneWidth - 0.02, xa + k * paneWidth + 0.02, S + 0.03, T - fw);
for (let k = 0; k < panes; k++) {
const x0 = xa + k * paneWidth + (k ? 0.02 : 0);
const x1 = xa + (k + 1) * paneWidth - (k < panes - 1 ? 0.02 : 0);
panel(c.glass, frame, x0, x1, mid, S + 0.03, T - fw, GLASS, fold);
}
}
interface Sash {
atStart: boolean;
x0: number;
x1: number;
open: number;
tilt: number;
/** A sliding window's pane: how far it moves along the wall when fully open, and its track (0: the fixed panes, further out). */
slide?: number;
track?: 0 | 1;
}
/**
* The panes of a sliding window or lift-and-slide door. One leaf: the pane at the hinge side slides in front of the fixed one.
* Two leaves: four panes, the middle two slide outwards in front of the fixed outer ones, each on its own contact.
*/
export function slidingPanes(W: number, fw: number, hingeAtStart: boolean, leaves: 1 | 2, open: number, open2: number): Sash[] {
const inner = W - 2 * fw;
const overlap = 0.04;
if (leaves === 2) {
const pane = inner / 4 + overlap / 2;
const run = pane - overlap - 0.02;
return [
{ atStart: true, x0: fw, x1: fw + pane, open: 0, tilt: 0, slide: 0, track: 0 },
{ atStart: true, x0: fw + inner / 4 - overlap / 2, x1: fw + inner / 2, open: hingeAtStart ? open : open2, tilt: 0, slide: -run, track: 1 },
{ atStart: false, x0: fw + inner / 2, x1: W - fw - inner / 4 + overlap / 2, open: hingeAtStart ? open2 : open, tilt: 0, slide: run, track: 1 },
{ atStart: false, x0: W - fw - pane, x1: W - fw, open: 0, tilt: 0, slide: 0, track: 0 },
];
}
const half = inner / 2;
const run = half - overlap - 0.02;
// the moving pane at the hinge side slides towards the fixed one
return hingeAtStart
? [
{ atStart: true, x0: fw, x1: fw + half + overlap / 2, open, tilt: 0, slide: run, track: 1 },
{ atStart: false, x0: fw + half - overlap / 2, x1: W - fw, open: 0, tilt: 0, slide: 0, track: 0 },
]
: [
{ atStart: true, x0: fw, x1: fw + half + overlap / 2, open: 0, tilt: 0, slide: 0, track: 0 },
{ atStart: false, x0: fw + half - overlap / 2, x1: W - fw, open, tilt: 0, slide: -run, track: 1 },
];
}
/** A normal window: the fixed frame in the middle of the wall, a board inside and a sill outside, and one or two sashes. */
export function window(c: Ctx): void {
const { info, state, frame, fold, mid } = c;
const [W, S, T] = [info.width, info.sill, info.top];
const [fw, fd] = [0.06, 0.035];
const frameColor = new Color(FRAME);
const frameTop = new Color(FRAME_TOP);
const sillColor = new Color(SILL);
const bar = (x0: number, x1: number, y0: number, y1: number) => splitBox(c.frames, frame, { x0, x1, n0: mid - fd, n1: mid + fd, y0, y1 }, frameColor, frameTop, fold);
const lowerBar = S + (S > 0.05 ? fw : 0.03);
bar(0, fw, S, T);
bar(W - fw, W, S, T);
bar(fw, W - fw, S, lowerBar);
bar(fw, W - fw, T - fw, T);
// a window board inside and a sill outside (automatic: both above 30 cm; or as chosen for this window)
const boards = info.opening.sill_boards ?? "auto";
if (boards !== "none" && (boards !== "auto" || S > 0.3)) {
if (boards !== "outside") splitBox(c.frames, frame, { x0: -0.04, x1: W + 0.04, n0: mid + fd, n1: info.faceRoom + 0.07, y0: S - 0.03, y1: S }, sillColor, frameTop, fold);
if (info.exterior && boards !== "inside") splitBox(c.frames, frame, { x0: -0.03, x1: W + 0.03, n0: -info.faceOut - 0.06, n1: mid - fd, y0: S - 0.04, y1: S - 0.02 }, sillColor, frameTop, fold);
}
// sashes rotate into the room around their hinge, or tilt around their bottom edge; a double window (or French door) has
// two sashes meeting in the middle, each tilting on its own
const barWidth = 0.055;
const [sy0, sy1] = [lowerBar, T - fw];
const [n0, n1] = [mid + fd, mid + fd + 0.06];
const hinge = info.hingeAtStart;
const opens = info.opening.opens ?? "turn";
const sashes: Sash[] =
opens === "slide"
? slidingPanes(W, fw, hinge, info.opening.leaves, state.open, state.open2 ?? 0)
: info.opening.leaves === 2
? [
{ atStart: hinge, x0: hinge ? fw : W / 2, x1: hinge ? W / 2 : W - fw, open: state.open, tilt: state.tilt },
{ atStart: !hinge, x0: hinge ? W / 2 : fw, x1: hinge ? W - fw : W / 2, open: state.open2 ?? 0, tilt: state.tilt2 ?? 0 },
]
: [{ atStart: hinge, x0: fw, x1: W - fw, open: state.open, tilt: state.tilt }];
const style = openingStyle(info.opening, info.exterior);
for (const sash of sashes) {
// a top-hung sash opens with its contact or a tilt sensor alike; a fixed pane never glows
const swingOut = opens === "top" ? Math.max(sash.open, sash.tilt) * TOP_HUNG_ANGLE : 0;
const moves = opens !== "slide" || !!sash.slide;
const ajar = moves && (sash.open > 0.02 || sash.tilt > 0.02);
const alert = c.markClosed ? !!state.sensed && !ajar : ajar;
const side = alert ? shade(OPEN_WARM, 0.75) : new Color(SASH);
const top = alert ? shade(OPEN_WARM, 0.95) : frameTop;
const sashWidth = sash.x1 - sash.x0;
const turning = opens === "turn";
const theta = turning ? sash.open * OPEN_ANGLE : 0;
const lean = turning ? sash.tilt * TILT_ANGLE : 0;
// a sliding pane runs in the sash plane; the fixed panes of a sliding window sit one track further out, so it passes in front of them
const shift = (sash.slide ?? 0) * sash.open;
const track = opens === "slide" && sash.track === 0 ? -0.065 : 0;
// sash coordinates: u from the hinge across the sash, then n and y
const sashFrame: Frame = (u, n, y) => {
if (swingOut > 0) {
// top-hung: turned about the sash's top edge, so its bottom swings out of the wall (towards -n)
const [dn, dy] = [n - n0, y - sy1];
const [c, s] = [Math.cos(swingOut), Math.sin(swingOut)];
return frame(sash.atStart ? sash.x0 + u : sash.x1 - u, n0 + dn * c + dy * s, sy1 - dn * s + dy * c);
}
const dy = y - sy0;
const tilted = n + dy * Math.sin(lean) + track;
const yy = sy0 + dy * Math.cos(lean);
const along = u * Math.cos(theta) - (tilted - n0) * Math.sin(theta);
const across = n0 + (tilted - n0) * Math.cos(theta) + u * Math.sin(theta);
return frame((sash.atStart ? sash.x0 + along : sash.x1 - along) + shift, across, yy);
};
// a sash that has swung into the room (or out of the wall) belongs to no wall: keep it visible
const sashFold = { cut: fold.cut, bucket: theta > 0.05 || swingOut > 0.05 ? ALWAYS : fold.bucket };
const part = (xa: number, xb: number, ya: number, yb: number, na = n0, nb = n1) => splitBox(c.frames, sashFrame, { x0: xa, x1: xb, n0: na, n1: nb, y0: ya, y1: yb }, side, top, sashFold);
part(0, barWidth, sy0, sy1);
part(sashWidth - barWidth, sashWidth, sy0, sy1);
part(barWidth, sashWidth - barWidth, sy0, sy0 + barWidth);
part(barWidth, sashWidth - barWidth, sy1 - barWidth, sy1);
panel(c.glass, sashFrame, barWidth, sashWidth - barWidth, (n0 + n1) / 2, sy0 + barWidth, sy1 - barWidth, alert ? shade(OPEN_WARM, 0.16) : GLASS, sashFold);
if (style === "bars") {
// glazing bars: a cross over the pane
const [ym, nm] = [(sy0 + sy1) / 2, (n0 + n1) / 2];
part(barWidth, sashWidth - barWidth, ym - 0.012, ym + 0.012, nm - 0.012, nm + 0.012);
part(sashWidth / 2 - 0.012, sashWidth / 2 + 0.012, sy0 + barWidth, sy1 - barWidth, nm - 0.012, nm + 0.012);
}
}
}
+3
View File
@@ -0,0 +1,3 @@
// Areas outside the house in the neon look, split into modules in outdoor/.
export { outdoorHoles, outdoorOpacity, outdoorSurface, pushOutdoor } from "./outdoor/outdoor.ts";
+44
View File
@@ -0,0 +1,44 @@
// Posts and beams for fences and pergolas.
import { Color } from "three";
import type { Vec2 } from "../../model.ts";
import { signedArea } from "../../model.ts";
import { ALWAYS, pushPrism, shade, type GeoBuffer } from "../geo.ts";
/** A ring running counter-clockwise, whichever way it was given. */
export const counterClockwise = (points: Vec2[]): Vec2[] => (signedArea(points) >= 0 ? points : [...points].reverse());
/** An upright square post of the given half width, from y0 up to y1. */
export function pushPost(buf: GeoBuffer, [x, z]: Vec2, half: number, y0: number, y1: number, side: number, top: number): void {
pushPrism(buf, counterClockwise([[x - half, z - half], [x + half, z - half], [x + half, z + half], [x - half, z + half]]), y0, y1, side, top);
}
/**
* A thin box along the segment p to q (a beam, a rafter), `width` wide, from y0 up to y1 at p. `rise` lifts the q end by that
* much, so a beam on a sloped pergola follows the slope.
*/
export function pushBeam(buf: GeoBuffer, p: Vec2, q: Vec2, width: number, y0: number, y1: number, side: number, top: number, rise = 0): void {
const [dx, dz] = [q[0] - p[0], q[1] - p[1]];
const length = Math.hypot(dx, dz);
if (length < 1e-6) return;
const [nx, nz] = [(-dz / length) * width * 0.5, (dx / length) * width * 0.5];
if (Math.abs(rise) < 1e-4) {
pushPrism(buf, counterClockwise([[p[0] + nx, p[1] + nz], [q[0] + nx, q[1] + nz], [q[0] - nx, q[1] - nz], [p[0] - nx, p[1] - nz]]), y0, y1, side, top, { aoFrom: y0 - 1 });
return;
}
// a sloped box: both faces of every quad, so it shows from any side without caring about the winding
const nearEnd = (y: number, s: number): number[] => [p[0] + nx * s, y, p[1] + nz * s];
const farEnd = (y: number, s: number): number[] => [q[0] + nx * s, y + rise, q[1] + nz * s];
const face = (v: number[][], color: Color) => {
for (const [a, b, c] of [[0, 1, 2], [0, 2, 3], [0, 2, 1], [0, 3, 2]]) buf.tri(v[a], v[b], v[c], color, color, color, undefined, ALWAYS);
};
const topColor = new Color(top);
const sideColor = shade(side, 0.9);
const underColor = shade(side, 0.6);
face([nearEnd(y1, 1), farEnd(y1, 1), farEnd(y1, -1), nearEnd(y1, -1)], topColor);
face([nearEnd(y0, 1), farEnd(y0, 1), farEnd(y0, -1), nearEnd(y0, -1)], underColor);
face([nearEnd(y0, 1), farEnd(y0, 1), farEnd(y1, 1), nearEnd(y1, 1)], sideColor);
face([nearEnd(y0, -1), farEnd(y0, -1), farEnd(y1, -1), nearEnd(y1, -1)], sideColor);
face([nearEnd(y0, 1), nearEnd(y0, -1), nearEnd(y1, -1), nearEnd(y1, 1)], sideColor);
face([farEnd(y0, 1), farEnd(y0, -1), farEnd(y1, -1), farEnd(y1, 1)], sideColor);
}
+39
View File
@@ -0,0 +1,39 @@
import assert from "node:assert/strict";
import { test } from "node:test";
import { gateLayout, gatesOnEdge } from "./gates.ts";
import type { OutdoorArea } from "../../model.ts";
const fence = (gates: OutdoorArea["gates"]): OutdoorArea => ({ id: "f", type: "fence", points: [[0, 0], [8, 0], [8, 4], [0, 4]], gates }) as OutdoorArea;
const near = (a: number, b: number) => Math.abs(a - b) < 1e-9;
test("a gate on an edge is found whichever way the outline runs, with its offset from the walking start", () => {
const area = fence([{ id: "g", edge: 0, offset: 2, width: 1, kind: "single" }]);
assert.deepEqual(gatesOnEdge(area, [0, 0], [8, 0]).map((g) => g.offset), [2]);
assert.deepEqual(gatesOnEdge(area, [8, 0], [0, 0]).map((g) => g.offset), [6], "from the other end it is 6 m in");
assert.equal(gatesOnEdge(area, [8, 0], [8, 4]).length, 0);
});
test("a closed single gate has one leaf across the gap; an open one swings 90° to the inside", () => {
const closed = gateLayout([0, 0], [8, 0], { width: 1.2, kind: "single" }, 4, false)!;
assert.ok(near(closed.from, 3.4) && near(closed.to, 4.6));
assert.deepEqual(closed.leaves.map((l) => [l.a, l.b]), [[[3.4, 0], [4.6, 0]]]);
const open = gateLayout([0, 0], [8, 0], { width: 1.2, kind: "single" }, 4, true)!;
assert.deepEqual(open.leaves[0].a, [3.4, 0]);
assert.ok(near(open.leaves[0].b[0], 3.4) && near(open.leaves[0].b[1], 1.2), "inside of a counter-clockwise outline is to the left of the walking direction");
});
test("a double gate meets in the middle when closed and opens both leaves; a sliding gate runs behind the far post", () => {
const closed = gateLayout([0, 0], [8, 0], { width: 3, kind: "double" }, 4, false)!;
assert.equal(closed.leaves.length, 2);
assert.deepEqual(closed.leaves.map((l) => l.b), [[4, 0], [4, 0]]);
const open = gateLayout([0, 0], [8, 0], { width: 3, kind: "double" }, 4, true)!;
assert.deepEqual(open.leaves.map((l) => l.b[1]), [1.5, 1.5]);
const slid = gateLayout([0, 0], [8, 0], { width: 3, kind: "sliding" }, 4, true)!;
assert.ok(near(slid.leaves[0].a[0], 5.5) && near(slid.leaves[0].a[1], -0.12) && near(slid.leaves[0].b[0], 8.5));
});
test("a gate that does not fit the edge is left out or narrowed", () => {
assert.equal(gateLayout([0, 0], [0.2, 0], { width: 1, kind: "single" }, 0.1, false), null);
const wide = gateLayout([0, 0], [2, 0], { width: 5, kind: "single" }, 1, false)!;
assert.ok(wide.to - wide.from <= 1.9 + 1e-9);
});
+61
View File
@@ -0,0 +1,61 @@
// Gates in fences: a gap in one edge of the fence, the gate posts at its ends and the leaf or leaves, closed in the gap or swung
// open (single and double gates swing 90° to the inside, a sliding gate runs along the fence behind the gap's far end).
import type { FenceGate, OutdoorArea, Vec2 } from "../../model.ts";
export interface GateLeaf {
/** The hinge (or the fixed end) and the free end of one leaf, in plan metres. */
a: Vec2;
b: Vec2;
}
export interface GateLayout {
/** The gap along the edge p → q, in metres from p. */
from: number;
to: number;
/** Where the two gate posts stand. */
posts: Vec2[];
leaves: GateLeaf[];
}
/** The gates of an area that sit on the edge p → q (whichever way the outline runs), with their offset counted from p. */
export function gatesOnEdge(area: OutdoorArea, p: Vec2, q: Vec2): { gate: FenceGate; offset: number }[] {
const same = (a: Vec2, b: Vec2) => Math.abs(a[0] - b[0]) < 1e-6 && Math.abs(a[1] - b[1]) < 1e-6;
const length = Math.hypot(q[0] - p[0], q[1] - p[1]);
const out: { gate: FenceGate; offset: number }[] = [];
for (const gate of area.gates ?? []) {
const a = area.points[gate.edge];
const b = area.points[(gate.edge + 1) % area.points.length];
if (!a || !b) continue;
if (same(a, p) && same(b, q)) out.push({ gate, offset: gate.offset });
else if (same(a, q) && same(b, p)) out.push({ gate, offset: length - gate.offset });
}
return out.sort((x, y) => x.offset - y.offset);
}
/** The gap, posts and leaves of one gate on the edge p → q. `offset` is the gate's middle from p; `open` swings or slides it. */
export function gateLayout(p: Vec2, q: Vec2, gate: Pick<FenceGate, "width" | "kind">, offset: number, open: boolean): GateLayout | null {
const length = Math.hypot(q[0] - p[0], q[1] - p[1]);
if (length < 0.3) return null;
const width = Math.min(gate.width, length - 0.1);
if (width < 0.3) return null;
const from = Math.max(0.05, Math.min(length - width - 0.05, offset - width / 2));
const to = from + width;
const [ux, uz] = [(q[0] - p[0]) / length, (q[1] - p[1]) / length];
// the inside of a counter-clockwise outline lies to the left of the walking direction p → q
const [nx, nz] = [-uz, ux];
const at = (t: number, side = 0): Vec2 => [p[0] + ux * t + nx * side, p[1] + uz * t + nz * side];
const [pa, pb] = [at(from), at(to)];
const leaves: GateLeaf[] = [];
if (gate.kind === "double") {
const mid = (from + to) / 2;
leaves.push(open ? { a: pa, b: at(from, width / 2) } : { a: pa, b: at(mid) });
leaves.push(open ? { a: pb, b: at(to, width / 2) } : { a: pb, b: at(mid) });
} else if (gate.kind === "sliding") {
// open: it rolls along the fence behind the far post, a hand's breadth outside the line
leaves.push(open ? { a: at(to, -0.12), b: at(to + width, -0.12) } : { a: pa, b: pb });
} else {
leaves.push(open ? { a: pa, b: at(from, width) } : { a: pa, b: pb });
}
return { from, to, posts: [pa, pb], leaves };
}
+24
View File
@@ -0,0 +1,24 @@
// How each kind of outdoor area looks in the neon scene: colours of the top, the sides, and the outline.
import type { OutdoorType } from "../../model.ts";
export interface Look {
color: number;
side: number;
edge: number;
/** How strong the outline is (its colour is scaled by this). */
edgeAlpha: number;
}
export const LOOKS: Record<OutdoorType, Look> = {
lawn: { color: 0x0e2822, side: 0x0b201b, edge: 0x3ee2a2, edgeAlpha: 0.16 },
terrace: { color: 0x1c1b30, side: 0x161628, edge: 0x5b7cff, edgeAlpha: 0.32 },
path: { color: 0x1b2234, side: 0x151b29, edge: 0x5b7cff, edgeAlpha: 0.22 },
driveway: { color: 0x171d2c, side: 0x121725, edge: 0x5b7cff, edgeAlpha: 0.18 },
pool: { color: 0x0b3b5b, side: 0x0d2539, edge: 0x37e0ff, edgeAlpha: 0.6 },
bed: { color: 0x1b1613, side: 0x15110f, edge: 0x3ee2a2, edgeAlpha: 0.2 },
wild: { color: 0x15221b, side: 0x101b15, edge: 0x9ad24f, edgeAlpha: 0.14 },
hedge: { color: 0x174130, side: 0x113125, edge: 0x3ee2a2, edgeAlpha: 0.35 },
fence: { color: 0x1e2a47, side: 0x1e2a47, edge: 0x5b7cff, edgeAlpha: 0.45 },
pergola: { color: 0x2b2339, side: 0x201b2d, edge: 0x5b7cff, edgeAlpha: 0.5 },
};
+160
View File
@@ -0,0 +1,160 @@
import assert from "node:assert/strict";
import { test } from "node:test";
import { newFloor, OUTDOOR_TOP, type Floor, type OutdoorArea, type Vec2 } from "../../model.ts";
import { GeoBuffer, LineBuffer } from "../geo.ts";
import { counterClockwise, pushBeam, pushPost } from "./beams.ts";
import { outdoorHoles, outdoorOpacity, outdoorSurface, pushOutdoor } from "./outdoor.ts";
const square = (x0: number, z0: number, x1: number, z1: number): Vec2[] => [[x0, z0], [x1, z0], [x1, z1], [x0, z1]];
const area = (type: OutdoorArea["type"], points: Vec2[], extra: Partial<OutdoorArea> = {}): OutdoorArea => ({ id: type, type, points, ...extra }) as OutdoorArea;
const floorWith = (...areas: OutdoorArea[]): Floor => ({ ...newFloor("g", "G", 0), outdoor: areas });
function build(...areas: OutdoorArea[]) {
const buf = new GeoBuffer();
const lines = new LineBuffer();
pushOutdoor(buf, lines, floorWith(...areas));
return { buf, lines, top: Math.max(...buf.p.filter((_, i) => i % 3 === 1), -Infinity) };
}
test("a ring is turned counter-clockwise whichever way it comes", () => {
const ring = square(0, 0, 2, 2);
assert.deepEqual(counterClockwise(ring), ring);
assert.deepEqual(counterClockwise([...ring].reverse()), ring);
});
test("a post and a beam add geometry; a beam of no length adds none", () => {
const buf = new GeoBuffer();
pushPost(buf, [1, 1], 0.05, 0, 2, 0x333333, 0x555555);
assert.equal(buf.count, 10);
pushBeam(buf, [0, 0], [3, 0], 0.1, 2, 2.2, 0x333333, 0x555555);
const level = buf.count;
assert.ok(level > 10);
pushBeam(buf, [0, 0], [0, 0], 0.1, 2, 2.2, 0x333333, 0x555555);
assert.equal(buf.count, level);
pushBeam(buf, [0, 0], [3, 0], 0.1, 2, 2.2, 0x333333, 0x555555, 0.5);
assert.equal(buf.count, level + 6 * 4, "a sloped beam: six faces, each drawn from both sides (four triangles)");
});
test("a lawn is a flat block at ground level with an outline", () => {
const { buf, lines, top } = build(area("lawn", square(0, 0, 4, 3)));
assert.ok(buf.count > 0);
assert.equal(lines.p.length / 6, 4);
const ground = Math.min(...buf.p.filter((_, i) => i % 3 === 1));
assert.ok(Math.abs(top - ground - OUTDOOR_TOP.lawn) < 0.3, "a thin layer on the ground");
});
test("the outline can be switched off", () => {
const { lines } = build(area("lawn", square(0, 0, 4, 3), { outline: false }));
assert.equal(lines.p.length, 0);
});
test("a hedge takes its own height", () => {
const low = build(area("hedge", square(0, 0, 4, 1)));
const tall = build(area("hedge", square(0, 0, 4, 1), { height: 2.5 }));
assert.ok(Math.abs(tall.top - low.top - (2.5 - OUTDOOR_TOP.hedge)) < 0.01);
});
test("a slope tilts the top of an area and lowers its base", () => {
const flat = build(area("terrace", square(0, 0, 4, 3)));
const sloped = build(area("terrace", square(0, 0, 4, 3), { slope: 0.5, slope_dir: "x" } as Partial<OutdoorArea>));
const lowest = (b: ReturnType<typeof build>) => Math.min(...b.buf.p.filter((_, i) => i % 3 === 1));
assert.ok(lowest(sloped) < lowest(flat));
});
test("a pool has water below the rim and inner sides", () => {
const { buf } = build(area("pool", square(0, 0, 4, 3)));
assert.ok(buf.count >= 2 + 8);
const ys = buf.p.filter((_, i) => i % 3 === 1);
assert.ok(Math.max(...ys) > Math.min(...ys));
});
test("a fence has posts about every two metres and two rails per edge", () => {
const { buf, lines } = build(area("fence", square(0, 0, 8, 4)));
assert.equal(lines.p.length / 6, 4 * 2, "two rails on each of the four edges");
const posts = buf.count / 10;
assert.ok(posts >= 8 && posts <= 14, String(posts));
});
test("a fence that is open leaves its closing edge out, but gets a post at the far end", () => {
const closed = build(area("fence", square(0, 0, 8, 4)));
const open = build(area("fence", square(0, 0, 8, 4), { open: true }));
assert.equal(open.lines.p.length / 6, 3 * 2);
assert.ok(open.buf.count > 0 && open.buf.count <= closed.buf.count + 10);
});
test("a pergola has corner posts and beams, rafters across a rectangle, and optional bracing", () => {
const plain = build(area("pergola", square(0, 0, 4, 3)));
const braced = build(area("pergola", square(0, 0, 4, 3), { bracing: true }));
assert.ok(plain.buf.count > 4 * 10 + 4 * 10, "posts and beams");
assert.equal(braced.lines.p.length / 6, plain.lines.p.length / 6 + 4 * 2);
const triangle = build(area("pergola", [[0, 0], [4, 0], [2, 3]]));
assert.ok(triangle.buf.count < plain.buf.count, "no rafters across a triangle");
});
test("areas marked cut inside another become holes in it, in either drawing order; standing areas and pools have none", () => {
const areas = [area("lawn", square(0, 0, 10, 10)), area("bed", square(2, 2, 3, 3), { cut: true }), area("bed", square(20, 20, 21, 21), { cut: true }), area("path", square(4, 4, 5, 5))];
assert.equal(outdoorHoles(areas, 0).length, 1);
assert.deepEqual(outdoorHoles([area("hedge", square(0, 0, 10, 10)), area("bed", square(2, 2, 3, 3), { cut: true })], 0), []);
assert.deepEqual(outdoorHoles([area("pool", square(0, 0, 10, 10)), area("bed", square(2, 2, 3, 3), { cut: true })], 0), []);
// a bed drawn before the lawn that contains it still leaves its hole
assert.equal(outdoorHoles([area("bed", square(2, 2, 3, 3), { cut: true }), area("lawn", square(0, 0, 10, 10))], 1).length, 1);
// a pool cuts itself out of a terrace, drawn before or after, unless cut is switched off
const terrace = area("terrace", square(0, 0, 10, 10));
assert.equal(outdoorHoles([terrace, area("pool", square(2, 2, 5, 5))], 0).length, 1);
assert.equal(outdoorHoles([area("pool", square(2, 2, 5, 5)), terrace], 1).length, 1);
assert.equal(outdoorHoles([terrace, area("pool", square(2, 2, 5, 5), { cut: false })], 0).length, 0);
const withHole = build(areas[0], areas[1]);
const without = build(areas[0]);
assert.ok(withHole.buf.count > without.buf.count);
// the terrace around a pool gets walls round the hole (more geometry) unless the pool does not cut itself out
const cutPool = build(terrace, area("pool", square(2, 2, 5, 5)));
const keptPool = build(terrace, area("pool", square(2, 2, 5, 5), { cut: false }));
assert.ok(cutPool.buf.count > keptPool.buf.count);
});
test("the surface height of an area follows its offset and type", () => {
const floor = floorWith();
const plain = outdoorSurface(floor, area("lawn", square(0, 0, 1, 1)));
assert.ok(Math.abs(outdoorSurface(floor, area("lawn", square(0, 0, 1, 1), { offset: 0.3 })) - plain - 0.3) < 1e-9);
assert.ok(outdoorSurface(floor, area("terrace", square(0, 0, 1, 1))) > plain);
assert.ok(outdoorSurface(floor, area("hedge", square(0, 0, 1, 1))) - plain < 0.1, "standing things count their base");
});
test("an area with fewer than three corners is skipped", () => {
const { buf, lines } = build(area("lawn", [[0, 0], [1, 1]]));
assert.equal(buf.count + lines.p.length, 0);
});
test("a gate cuts a gap into a fence: no rail across it, gate posts at its ends, and a leaf that moves when it opens", () => {
const plain = build(area("fence", square(0, 0, 8, 4)));
const gate = (open: boolean) => build(area("fence", square(0, 0, 8, 4), { gates: [{ id: "g", edge: 0, offset: 4, width: 1.2, kind: "single", open }] }));
const closed = gate(false);
assert.ok(closed.lines.p.length / 6 >= plain.lines.p.length / 6 + 2, "the long edge's two rails now come in two parts, plus the leaf's brace");
assert.ok(closed.buf.count > plain.buf.count, "gate posts and leaf geometry");
const open = gate(true);
assert.notDeepEqual(open.buf.p, closed.buf.p, "an open leaf stands somewhere else");
const zs = open.buf.p.filter((_, i) => i % 3 === 2);
assert.ok(Math.max(...zs) > 1.0, "it swings into the plot");
});
test("a see-through area goes into a buffer of its own per opacity, the outline stays in the lines", () => {
const solid = new GeoBuffer();
const lines = new LineBuffer();
const ghosts = new Map<number, GeoBuffer>();
const floor = floorWith(area("lawn", square(0, 0, 4, 4)), area("driveway", square(5, 0, 9, 4), { opacity: 0.4 }), area("terrace", square(10, 0, 12, 2), { opacity: 0.4 }), area("bed", square(13, 0, 14, 1), { opacity: 0.12 }));
pushOutdoor(solid, lines, floor, ghosts, () => new GeoBuffer());
assert.deepEqual([...ghosts.keys()].sort(), [0.1, 0.4]);
assert.ok(ghosts.get(0.4)!.count > 0 && solid.count > 0);
// without ghost buffers everything is drawn solid, as before
const all = new GeoBuffer();
pushOutdoor(all, new LineBuffer(), floor);
assert.equal(all.count, solid.count + ghosts.get(0.4)!.count + ghosts.get(0.1)!.count);
});
test("opacity of 1 or none means solid; very low values stop at 10 %", () => {
assert.equal(outdoorOpacity(area("lawn", square(0, 0, 1, 1))), 1);
assert.equal(outdoorOpacity(area("lawn", square(0, 0, 1, 1), { opacity: 1 })), 1);
assert.equal(outdoorOpacity(area("lawn", square(0, 0, 1, 1), { opacity: null })), 1);
assert.equal(outdoorOpacity(area("lawn", square(0, 0, 1, 1), { opacity: 0.02 })), 0.1);
assert.equal(outdoorOpacity(area("lawn", square(0, 0, 1, 1), { opacity: 0.43 })), 0.45);
});
+227
View File
@@ -0,0 +1,227 @@
// Areas outside the house: lawn, terrace, path, driveway, pool, bed, wild patch, hedge, fence and pergola, in the neon look.
// Flat areas lie at ground level (the underside of the ground floor slab), the terrace a little higher, the pool water
// below. Hedges are dark green blocks, fences posts with rails along the outline, a pergola corner posts with beams,
// rafters and optional X-bracing. An area can sit higher or lower (offset), fall along one direction (slope) and have
// patches cut out of it.
import { Color } from "three";
import { bounds, cutsOut, groundLevel, isAxisRect, OUTDOOR_TOP, outdoorDrop, outdoorStanding, pointInPolygon, type Floor, type OutdoorArea, type Vec2 } from "../../model.ts";
import { ALWAYS, pushPrism, shade, triangulate, type GeoBuffer, type LineBuffer } from "../geo.ts";
import { counterClockwise, pushBeam, pushPost } from "./beams.ts";
import { gateLayout, gatesOnEdge } from "./gates.ts";
import { LOOKS } from "./looks.ts";
/** The height of the visible surface of an area (for the lighting layer), at its high edge. */
export function outdoorSurface(floor: Floor, area: OutdoorArea): number {
return groundLevel(floor) + (area.offset ?? 0) + (outdoorStanding(area.type) ? 0.01 : OUTDOOR_TOP[area.type]);
}
/** The holes of an area: the other areas that cut themselves out (marked "cut", and pools) and lie entirely inside it, whatever order they were drawn in. */
export function outdoorHoles(areas: OutdoorArea[], index: number): Vec2[][] {
const area = areas[index];
if (outdoorStanding(area.type) || area.type === "pool") return [];
return areas
.filter((other, i) => i !== index && cutsOut(other) && other.points.length >= 3 && other.points.every((p) => pointInPolygon(p, area.points)))
.map((other) => counterClockwise(other.points));
}
/** What an area builder needs to know. */
interface Context {
buf: GeoBuffer;
lines: LineBuffer;
area: OutdoorArea;
/** The outline, counter-clockwise. */
poly: Vec2[];
/** The area's base height, and the ground height at a point (it falls along the slope). */
base: number;
groundAt: (x: number, z: number) => number;
/** The top height of the type, or the area's own for hedges, fences and pergolas. */
top: number;
look: (typeof LOOKS)[keyof typeof LOOKS];
edge: Color;
/** The index of the closing edge to leave out (a fence or pergola leaning on the house), or -1. */
openEdge: number;
}
const edgesOf = (poly: Vec2[], openEdge: number): [number, Vec2, Vec2][] => poly.map((p, i) => [i, p, poly[(i + 1) % poly.length]] as [number, Vec2, Vec2]).filter(([i]) => i !== openEdge);
function outline(c: Context, heightAt: (x: number, z: number) => number): void {
if (c.area.outline === false) return;
for (const [, p, q] of edgesOf(c.poly, c.openEdge)) c.lines.seg([p[0], heightAt(p[0], p[1]), p[1]], [q[0], heightAt(q[0], q[1]), q[1]], c.edge, ALWAYS);
}
function buildPool(c: Context): void {
const { buf, poly, base, top, look } = c;
const water = new Color(look.color);
// the water surface, below the rim
for (const [i, j, k] of triangulate(poly)) {
const [p, q, r] = [poly[i], poly[j], poly[k]];
buf.tri([p[0], base + top, p[1]], [r[0], base + top, r[1]], [q[0], base + top, q[1]], water, water, water, undefined, ALWAYS);
}
// the inner sides from the water up to the rim, seen from inside the pool
const sideColor = new Color(look.side);
for (const [, p, q] of edgesOf(poly, -1)) {
buf.tri([q[0], base + top, q[1]], [q[0], base + 0.06, q[1]], [p[0], base + 0.06, p[1]], sideColor, sideColor, sideColor, undefined, ALWAYS);
buf.tri([q[0], base + top, q[1]], [p[0], base + 0.06, p[1]], [p[0], base + top, p[1]], sideColor, sideColor, sideColor, undefined, ALWAYS);
}
outline(c, () => base + 0.06);
outline(c, () => base + top + 0.005);
}
function buildFence(c: Context): void {
const { buf, lines, poly, area, top, look, groundAt, edge, openEdge } = c;
// posts about every 2 m and two rails along the outline, following the ground
for (const [i, p, q] of edgesOf(poly, openEdge)) {
const length = Math.hypot(q[0] - p[0], q[1] - p[1]);
const sections = Math.max(1, Math.round(length / 2));
// gates cut gaps into the edge: no posts and no rails there, a gate post at each end and the leaves in between
const gates = gatesOnEdge(area, p, q)
.map(({ gate, offset }) => ({ gate, layout: gateLayout(p, q, gate, offset, !!gate.open) }))
.filter((g): g is { gate: typeof g.gate; layout: NonNullable<typeof g.layout> } => !!g.layout);
const inGap = (t: number) => gates.some((g) => t > g.layout.from - 0.15 && t < g.layout.to + 0.15);
// an open fence also gets the post at its far end
const lastPost = openEdge >= 0 && i === openEdge - 1 ? sections : sections - 1;
for (let k = 0; k <= lastPost; k++) {
if (inGap((length * k) / sections)) continue;
const x = p[0] + ((q[0] - p[0]) * k) / sections;
const z = p[1] + ((q[1] - p[1]) * k) / sections;
const ground = groundAt(x, z);
pushPost(buf, [x, z], 0.04, ground, ground + top, look.side, look.color);
}
// the rails run between the gaps
const cuts: [number, number][] = [];
let at = 0;
for (const g of gates) {
cuts.push([at, g.layout.from]);
at = g.layout.to;
}
cuts.push([at, length]);
const along = (t: number): Vec2 => [p[0] + ((q[0] - p[0]) * t) / length, p[1] + ((q[1] - p[1]) * t) / length];
for (const [t0, t1] of cuts) {
if (t1 - t0 < 0.02) continue;
const [a, b] = [along(t0), along(t1)];
for (const rail of [0.35, 0.85]) lines.seg([a[0], groundAt(a[0], a[1]) + rail * top, a[1]], [b[0], groundAt(b[0], b[1]) + rail * top, b[1]], edge, ALWAYS);
}
for (const { layout } of gates) {
for (const post of layout.posts) {
const ground = groundAt(post[0], post[1]);
pushPost(buf, post, 0.07, ground, ground + top * 1.05, look.side, look.color);
}
for (const leaf of layout.leaves) pushGateLeaf(c, leaf.a, leaf.b);
}
}
}
/** One gate leaf: two rails, pickets and a diagonal brace between a (the hinge) and b. */
function pushGateLeaf(c: Context, a: Vec2, b: Vec2): void {
const { buf, lines, top, look, groundAt, edge } = c;
const length = Math.hypot(b[0] - a[0], b[1] - a[1]);
if (length < 0.05) return;
const [ga, gb] = [groundAt(a[0], a[1]), groundAt(b[0], b[1])];
const rise = gb - ga;
for (const [lo, hi] of [[0.12, 0.2], [0.78, 0.86]]) pushBeam(buf, a, b, 0.05, ga + lo * top, ga + hi * top, look.side, look.color, rise);
const pickets = Math.max(2, Math.round(length / 0.18));
for (let k = 0; k <= pickets; k++) {
const t = k / pickets;
const x = a[0] + (b[0] - a[0]) * t;
const z = a[1] + (b[1] - a[1]) * t;
const ground = ga + rise * t;
pushPost(buf, [x, z], k === 0 || k === pickets ? 0.03 : 0.012, ground + 0.1 * top, ground + 0.9 * top, look.side, look.color);
}
lines.seg([a[0], ga + 0.2 * top, a[1]], [b[0], gb + 0.78 * top, b[1]], edge, ALWAYS);
}
function buildPergola(c: Context): void {
const { buf, lines, poly, area, top, look, groundAt, edge, openEdge } = c;
// corner posts, beams along the edges, rafters across a rectangle, optional X-bracing on the sides
for (const corner of poly) {
const ground = groundAt(corner[0], corner[1]);
pushPost(buf, corner, 0.06, ground, ground + top, look.side, look.color);
}
for (const [, p, q] of edgesOf(poly, openEdge)) {
const [gp, gq] = [groundAt(p[0], p[1]), groundAt(q[0], q[1])];
pushBeam(buf, p, q, 0.12, gp + top - 0.16, gp + top, look.side, look.color, gq - gp);
if (area.bracing) {
lines.seg([p[0], gp + 0.25, p[1]], [q[0], gq + top - 0.25, q[1]], edge, ALWAYS);
lines.seg([q[0], gq + 0.25, q[1]], [p[0], gp + top - 0.25, p[1]], edge, ALWAYS);
}
}
if (isAxisRect(poly)) {
const box = bounds(poly);
const alongX = box.x1 - box.x0 >= box.z1 - box.z0;
const [start, span] = alongX ? [box.x0, box.x1 - box.x0] : [box.z0, box.z1 - box.z0];
const rafters = Math.max(1, Math.round(span / 0.6));
for (let k = 1; k < rafters; k++) {
const t = start + (span * k) / rafters;
const p: Vec2 = alongX ? [t, box.z0 + 0.06] : [box.x0 + 0.06, t];
const q: Vec2 = alongX ? [t, box.z1 - 0.06] : [box.x1 - 0.06, t];
const gp = groundAt(p[0], p[1]);
pushBeam(buf, p, q, 0.06, gp + top - 0.04, gp + top + 0.08, look.side, look.color, groundAt(q[0], q[1]) - gp);
}
}
outline(c, (x, z) => groundAt(x, z) + top + 0.004);
}
/** Everything else: a flat area is a thin prism; terrace, bed and hedge are raised blocks. A slope tilts the top and the block reaches down to the lowest point. */
function buildBlock(c: Context, areas: OutdoorArea[], index: number): void {
const { buf, lines, poly, area, top, look, groundAt, base, edge } = c;
const lowest = base - (area.slope ?? 0);
const topAt = (x: number, z: number) => groundAt(x, z) + top;
const holes = outdoorHoles(areas, index);
pushPrism(buf, poly, lowest, area.slope ? topAt : base + top, look.side, look.color, { aoFrom: lowest, holes });
outline(c, (x, z) => topAt(x, z) + 0.004);
if (area.type === "hedge") outline(c, (x, z) => groundAt(x, z) + 0.004);
if (area.outline === false) return;
for (const hole of holes) {
hole.forEach((p, i) => {
const q = hole[(i + 1) % hole.length];
lines.seg([p[0], topAt(p[0], p[1]) + 0.004, p[1]], [q[0], topAt(q[0], q[1]) + 0.004, q[1]], edge, ALWAYS);
});
}
}
/** The opacity an area is drawn with, in whole percent steps (100 = solid). */
export function outdoorOpacity(area: OutdoorArea): number {
const o = area.opacity;
return o == null || !(o < 1) ? 1 : Math.max(0.1, Math.round(o * 20) / 20);
}
/**
* Builds the outdoor areas of a floor. Areas that are drawn see-through go into a buffer of their own per opacity (`ghosts`), the others
* into `buf`; the outlines always stay solid.
*/
export function pushOutdoor(buf: GeoBuffer, lines: LineBuffer, floor: Floor, ghosts?: Map<number, GeoBuffer>, makeBuffer?: () => GeoBuffer): void {
const ground = groundLevel(floor);
const areas = floor.outdoor ?? [];
areas.forEach((area, index) => {
if (area.points.length < 3) return;
// an area may sit above or below the ground (a driveway down to a lower garage) and fall along one direction
const base = ground + (area.offset ?? 0);
const look = LOOKS[area.type];
const poly = counterClockwise(area.points);
const opacity = outdoorOpacity(area);
let target = buf;
if (opacity < 1 && ghosts && makeBuffer) {
if (!ghosts.has(opacity)) ghosts.set(opacity, makeBuffer());
target = ghosts.get(opacity)!;
}
const context: Context = {
buf: target,
lines,
area,
poly,
base,
groundAt: (x, z) => base - outdoorDrop(area, x, z),
// hedges, fences and pergolas take their own height; the outline can be switched off per area
top: outdoorStanding(area.type) && area.height ? area.height : OUTDOOR_TOP[area.type],
look,
edge: shade(look.edge, look.edgeAlpha),
// fences and pergolas may leave their closing edge out (leaning against the house)
openEdge: area.open && (area.type === "fence" || area.type === "pergola") ? poly.length - 1 : -1,
};
if (area.type === "pool") buildPool(context);
else if (area.type === "fence") buildFence(context);
else if (area.type === "pergola") buildPergola(context);
else buildBlock(context, areas, index);
});
}
+64
View File
@@ -0,0 +1,64 @@
import assert from "node:assert/strict";
import { test } from "node:test";
import { advancePet, freeSpot, nextTarget, seededRandom, stepPet, type PetMotion, type PetRoom } from "./pets.ts";
const room: PetRoom = {
points: [[0, 0], [5, 0], [5, 4], [0, 4]],
obstacles: [[[2, 1], [3, 1], [3, 3], [2, 3]]], // a table in the middle
speed: 0.5,
};
test("free spots are inside the room, off the walls and outside the furniture", () => {
assert.ok(freeSpot(room, [1, 1]));
assert.ok(!freeSpot(room, [2.5, 2]), "under the table");
assert.ok(!freeSpot(room, [0.1, 2]), "against the wall");
assert.ok(!freeSpot(room, [6, 2]), "outside");
});
test("the next spot is free and the way there does not cross the furniture", () => {
const random = seededRandom("cat");
for (let i = 0; i < 40; i++) {
const t = nextTarget(room, [1, 2], random);
assert.ok(t && freeSpot(room, t));
assert.ok(t![0] < 2 || t![1] < 1 || t![1] > 3, "never straight through the table");
}
});
test("a pet walks to its spot, rests there and walks on, never leaving the room", () => {
const random = seededRandom("dog");
const m: PetMotion = { pos: [1, 1], heading: 0, target: null, rest: 0 };
let walked = 0;
for (let i = 0; i < 2000; i++) {
if (stepPet(m, room, 0.1, random)) walked++;
assert.ok(freeSpot(room, m.pos, 0.2) || Math.hypot(m.pos[0] - 1, m.pos[1] - 1) < 1e-9, `left the free floor at ${m.pos}`);
}
assert.ok(walked > 200 && walked < 1990, "it walks, and it rests in between");
});
test("the same pet walks the same way after a reload", () => {
const a = seededRandom("rabbit-1");
const b = seededRandom("rabbit-1");
assert.deepEqual([a(), a(), a()], [b(), b(), b()]);
});
test("a pet placed under the table walks out of it", () => {
const t = nextTarget(room, [2.5, 2], seededRandom("under"));
assert.ok(t && freeSpot(room, t));
});
test("a resting pet walks on after its rest, whether frames come every 16 ms or after one long sleep (#97)", () => {
const random = seededRandom("cat");
const busy: PetMotion = { pos: [1, 1], heading: 0, target: null, rest: 3 };
let t = 0;
while (!busy.target && t < 10) {
advancePet(busy, room, 0.016, random);
t += 0.016;
}
assert.ok(busy.target, "frames of other animations count the rest down");
assert.ok(t > 2.9 && t < 3.1, `walked on after about 3 s, not ${t.toFixed(2)} s`);
const asleep: PetMotion = { pos: [1, 1], heading: 0, target: null, rest: 3 };
const before = [...asleep.pos];
advancePet(asleep, room, 3.05, random);
assert.ok(asleep.target, "a frame after a 3 s sleep counts the whole sleep");
assert.ok(Math.hypot(asleep.pos[0] - before[0], asleep.pos[1] - before[1]) <= room.speed * 0.2 + 1e-9, "but walks at most 0.2 s at once");
});
+111
View File
@@ -0,0 +1,111 @@
// Pets that roam their room: a cat, a dog or a rabbit walks to a free spot of the room, looks around for a few seconds, and walks
// on. They keep away from the walls and walk round the furniture. Pure motion; the viewer draws them and moves their group.
import { pointInPolygon, type Vec2 } from "../model.ts";
export interface PetMotion {
pos: Vec2;
heading: number;
target: Vec2 | null;
/** Seconds left to rest before the next walk. */
rest: number;
}
export interface PetRoom {
points: Vec2[];
/** Footprints of the furniture standing in the room, which the pet walks round. */
obstacles: Vec2[][];
/** Walking speed in m/s. */
speed: number;
}
/** A tiny seeded random generator, so every pet walks its own but repeatable way. */
export function seededRandom(seed: string): () => number {
let h = 2166136261;
for (let i = 0; i < seed.length; i++) h = Math.imul(h ^ seed.charCodeAt(i), 16777619);
return () => {
h = Math.imul(h ^ (h >>> 15), 2246822507);
h = Math.imul(h ^ (h >>> 13), 3266489909);
h ^= h >>> 16;
return (h >>> 0) / 4294967296;
};
}
const distToSegment = (p: Vec2, a: Vec2, b: Vec2) => {
const [dx, dz] = [b[0] - a[0], b[1] - a[1]];
const l2 = dx * dx + dz * dz || 1e-9;
const t = Math.max(0, Math.min(1, ((p[0] - a[0]) * dx + (p[1] - a[1]) * dz) / l2));
return Math.hypot(p[0] - a[0] - dx * t, p[1] - a[1] - dz * t);
};
/** Whether a pet can stand at p: inside the room, a little off the walls, not inside furniture. */
export function freeSpot(room: PetRoom, p: Vec2, margin = 0.25): boolean {
if (!pointInPolygon(p, room.points)) return false;
const pts = room.points;
for (let i = 0; i < pts.length; i++) if (distToSegment(p, pts[i], pts[(i + 1) % pts.length]) < margin) return false;
return !room.obstacles.some((o) => pointInPolygon(p, o));
}
/** The way from a to b is free of furniture (checked every 10 cm). */
function clearWay(room: PetRoom, a: Vec2, b: Vec2): boolean {
// a pet placed under a table walks out of it: only the other furniture blocks its way
const blocking = room.obstacles.filter((o) => !pointInPolygon(a, o));
const steps = Math.max(1, Math.ceil(Math.hypot(b[0] - a[0], b[1] - a[1]) / 0.1));
for (let i = 1; i <= steps; i++) {
const p: Vec2 = [a[0] + ((b[0] - a[0]) * i) / steps, a[1] + ((b[1] - a[1]) * i) / steps];
if (blocking.some((o) => pointInPolygon(p, o))) return false;
}
return true;
}
/** A free spot of the room the pet can walk to in a straight line, or null after a few tries. */
export function nextTarget(room: PetRoom, from: Vec2, random: () => number): Vec2 | null {
const xs = room.points.map((p) => p[0]);
const zs = room.points.map((p) => p[1]);
const [x0, x1, z0, z1] = [Math.min(...xs), Math.max(...xs), Math.min(...zs), Math.max(...zs)];
for (let i = 0; i < 24; i++) {
const p: Vec2 = [x0 + (x1 - x0) * random(), z0 + (z1 - z0) * random()];
if (Math.hypot(p[0] - from[0], p[1] - from[1]) > 0.6 && freeSpot(room, p) && clearWay(room, from, p)) return p;
}
return null;
}
/** One step of dt seconds: walk towards the target and turn into the way, or rest and then pick the next spot. True while it walks. */
export function stepPet(m: PetMotion, room: PetRoom, dt: number, random: () => number): boolean {
if (!m.target) {
m.rest -= dt;
if (m.rest > 0) return false;
m.target = nextTarget(room, m.pos, random);
if (!m.target) {
m.rest = 2;
return false;
}
}
const [dx, dz] = [m.target[0] - m.pos[0], m.target[1] - m.pos[1]];
const dist = Math.hypot(dx, dz);
// the heading turns smoothly towards the way (the pet's nose points along +z of its model)
const want = Math.atan2(dx, dz);
let turn = want - m.heading;
while (turn > Math.PI) turn -= 2 * Math.PI;
while (turn < -Math.PI) turn += 2 * Math.PI;
m.heading += Math.max(-4 * dt, Math.min(4 * dt, turn));
const step = room.speed * dt * (Math.abs(turn) > 1.2 ? 0.3 : 1);
if (dist <= step) {
m.pos = [m.target[0], m.target[1]];
m.target = null;
m.rest = 2 + random() * 6;
return true;
}
m.pos = [m.pos[0] + (dx / dist) * step, m.pos[1] + (dz / dist) * step];
return true;
}
/**
* One frame of a pet with the real time since its last frame: the walk moves by at most 0.2 s at once (no jumps after
* a pause), but a rest counts the whole time down, so a pet walks on whether the view draws every frame or slept (#97).
*/
export function advancePet(m: PetMotion, room: PetRoom, elapsed: number, random: () => number): boolean {
const dt = Math.min(0.2, Math.max(0, elapsed));
if (!m.target) m.rest -= Math.max(0, elapsed) - dt;
return stepPet(m, room, dt, random);
}
+90
View File
@@ -0,0 +1,90 @@
// Small pictures of furniture and lamps for the editor's library. One offscreen renderer draws the same low-poly models as the 3D
// view, seen from the front at an angle, into a PNG data URL.
import { Box3, Color, LineBasicMaterial, LineSegments, Mesh, MeshBasicMaterial, OrthographicCamera, Scene, Vector3, WebGLRenderer } from "three";
import type { Furniture } from "../model.ts";
import { packItem, setPacks, type FurniturePack } from "../packs.ts";
import { pushFurniture, pushPackLamp } from "./furniture.ts";
import { GeoBuffer, LineBuffer } from "./geo.ts";
import { pushLampModel, type LampModel } from "./viewer3d.ts";
let renderer: WebGLRenderer | null = null;
const cache = new Map<string, string>();
export interface PreviewItem {
type: string;
w: number;
d: number;
h: number;
variant?: string | null;
/** The lamp model for lamp types: they are drawn by the lamp code, lit. */
lamp?: LampModel | null;
}
const LAMP_LIGHT = 0xffb547;
/** Draws the item into the buffers: a pack lamp, a built-in lamp, or ordinary furniture. */
function drawItem(item: PreviewItem, solids: GeoBuffer, lines: LineBuffer): void {
const packed = packItem(item.type);
if (packed?.light) {
pushPackLamp(solids, packed, { x: 0, z: 0, rotation: 0, w: item.w, d: item.d, h: item.h }, 0, LAMP_LIGHT);
} else if (item.lamp) {
// hanging lamps hang from a ceiling just above them
pushLampModel(solids, { x: 0, z: 0, size: [item.w, item.d, item.h], base: 0, rotation: 0, variant: item.variant ?? null, lamp: item.lamp }, Math.max(item.h + 0.15, 0.6), LAMP_LIGHT);
} else {
const piece: Furniture = { id: "preview", type: item.type, x: 0, z: 0, rotation: 0, w: item.w, d: item.d, h: item.h, variant: item.variant ?? null, entity: null, power: null };
pushFurniture(solids, lines, new GeoBuffer(), piece);
}
}
/** A camera that looks from the front right, a little from above, with the item's box fitted into the picture. */
function fitCamera(box: Box3): OrthographicCamera {
const centre = box.getCenter(new Vector3());
const camera = new OrthographicCamera(-1, 1, 1, -1, 0.01, 100);
camera.position.copy(centre).add(new Vector3(0.9, 0.75, 1.3).normalize().multiplyScalar(20));
camera.lookAt(centre);
camera.updateMatrixWorld();
// the camera looks at the centre, so the corners' distances in view space give the picture's extent
let reach = 0.05;
for (const x of [box.min.x, box.max.x]) {
for (const y of [box.min.y, box.max.y]) {
for (const z of [box.min.z, box.max.z]) {
const p = new Vector3(x, y, z).applyMatrix4(camera.matrixWorldInverse);
reach = Math.max(reach, Math.abs(p.x), Math.abs(p.y));
}
}
}
const half = reach * 1.12;
Object.assign(camera, { left: -half, right: half, top: half, bottom: -half });
camera.updateProjectionMatrix();
return camera;
}
/** A PNG data URL of an item (cached per type and size). `packs` are needed for pack furniture. */
export function furniturePreview(item: PreviewItem, size = 180, packs?: FurniturePack[], brightness = 1.3): string {
const key = [item.type, item.w, item.d, item.h, item.variant ?? "", size, brightness].join("|");
const cached = cache.get(key);
if (cached) return cached;
if (packs) setPacks(packs);
renderer ??= new WebGLRenderer({ alpha: true, antialias: true, preserveDrawingBuffer: true });
renderer.setPixelRatio(Math.min(2, window.devicePixelRatio || 1));
renderer.setSize(size, size, false);
renderer.setClearColor(0x000000, 0);
const [solids, lines] = [new GeoBuffer(), new LineBuffer()];
drawItem(item, solids, lines);
// the neon palette is made for a dark room: pictures get a little more light and brighter edges
const mesh = new Mesh(solids.geometry(), new MeshBasicMaterial({ vertexColors: true, color: new Color(brightness, brightness, brightness) }));
const edges = new LineSegments(lines.geometry(), new LineBasicMaterial({ vertexColors: true, color: new Color(brightness * 1.8, brightness * 1.8, brightness * 1.8) }));
const scene = new Scene();
scene.add(mesh, edges);
renderer.render(scene, fitCamera(new Box3().setFromObject(mesh)));
const url = renderer.domElement.toDataURL("image/png");
for (const part of [mesh, edges]) {
part.geometry.dispose();
(part.material as MeshBasicMaterial | LineBasicMaterial).dispose();
}
cache.set(key, url);
return url;
}
@@ -0,0 +1,42 @@
import assert from "node:assert/strict";
import { test } from "node:test";
import { QualityGovernor } from "./quality-governor.ts";
/** Feeds `n` frames of `dt` ms and collects the steps asked for. */
function run(g: QualityGovernor, dt: number, n: number, start = 0) {
const steps = [];
for (let i = 0; i < n; i++) {
const s = g.frame(dt, start + i * dt);
if (s) steps.push(s);
}
return steps;
}
test("a fast tablet keeps its pixels", () => {
assert.deepEqual(run(new QualityGovernor(2), 16, 600), []);
});
test("a slow tablet loses pixels step by step, then gets the simple look", () => {
const g = new QualityGovernor(2);
// 80 ms frames: 12 frames a second
const steps = run(g, 80, 2000);
assert.deepEqual(steps.slice(0, 4), [{ ratio: 1.75 }, { ratio: 1.5 }, { ratio: 1.25 }, { ratio: 1 }]);
assert.deepEqual(steps.at(-1), { low: true });
});
test("a tablet that is only a bit slow stays at fewer pixels, and gets them back when it is fast again", () => {
const g = new QualityGovernor(2);
// 30 ms frames (33 fps) are fine: nothing changes
assert.deepEqual(run(g, 30, 500), []);
run(g, 45, 200);
assert.ok(g.pixelRatio < 2);
const lowered = g.pixelRatio;
// fast again, but only after half a minute
assert.deepEqual(run(g, 10, 200, 1_000_000)[0], { ratio: lowered + 0.25 });
});
test("one hiccup does not count", () => {
const g = new QualityGovernor(2);
const frames = Array.from({ length: 300 }, (_, i) => (i % 20 === 0 ? 90 : 16));
assert.deepEqual(frames.map((dt, i) => g.frame(dt, i * 16)).filter(Boolean), []);
});
+68
View File
@@ -0,0 +1,68 @@
// Quality by itself: while the picture moves, the frame times are watched; a tablet that keeps drawing too slowly gets fewer pixels,
// step by step, and the simple look when even one pixel per point is too much. With plenty of room left the pixels come back slowly.
/** What the governor asks for: another pixel ratio, or the low quality level. */
export type QualityStep = { ratio: number } | { low: true } | null;
const WINDOW = 45;
const SLOW_FPS = 26;
const VERY_SLOW_FPS = 16;
const FAST_FPS = 55;
const STEP = 0.25;
/** Frames after a change before the next measurement counts (the new size settles). */
const SETTLE = 30;
/** No step up within this long after a step down (ms): no flicker between two levels. */
const UP_DELAY = 30_000;
export class QualityGovernor {
private times: number[] = [];
private settle = SETTLE;
private ratio: number;
private lastDown = -Infinity;
private slowAtFloor = 0;
private readonly max: number;
private readonly min: number;
constructor(max: number, min = 1) {
this.max = max;
this.min = min;
this.ratio = max;
}
get pixelRatio(): number {
return this.ratio;
}
/** One frame while something moves (`dt` in ms, `now` the frame's time). Returns a step when one is due. */
frame(dt: number, now: number): QualityStep {
if (this.settle > 0) {
this.settle--;
return null;
}
if (dt <= 0 || dt >= 100) return null;
this.times.push(dt);
if (this.times.length < WINDOW) return null;
const sorted = [...this.times].sort((a, b) => a - b);
this.times = [];
// the median frame: one hiccup (a garbage collection) does not count
const fps = 1000 / sorted[Math.floor(sorted.length / 2)];
if (fps < SLOW_FPS && this.ratio > this.min + 1e-6) {
this.ratio = Math.max(this.min, Math.round((this.ratio - STEP) * 100) / 100);
this.lastDown = now;
this.settle = SETTLE;
return { ratio: this.ratio };
}
if (fps < VERY_SLOW_FPS && this.ratio <= this.min + 1e-6) {
// two slow windows in a row at the lowest ratio: the simple look
if (++this.slowAtFloor >= 2) return { low: true };
return null;
}
this.slowAtFloor = 0;
if (fps > FAST_FPS && this.ratio < this.max - 1e-6 && now - this.lastDown > UP_DELAY) {
this.ratio = Math.min(this.max, Math.round((this.ratio + STEP) * 100) / 100);
this.settle = SETTLE;
return { ratio: this.ratio };
}
return null;
}
}
+51
View File
@@ -0,0 +1,51 @@
import assert from "node:assert/strict";
import { test } from "node:test";
import { TRAIL_FADE_MS, TRAIL_HOLD_MS, trailGeometry, trailOpacity } from "./robot-trail.ts";
const positions = (g: ReturnType<typeof trailGeometry>) => Array.from(g.getAttribute("position").array as ArrayLike<number>);
test("a straight trail of one segment is a quad at the given width and height", () => {
const g = trailGeometry([[[0, 0], [2, 0]]], 0.16, 0.01);
const p = positions(g);
assert.equal(p.length / 3, 6, "two triangles");
// a float32 buffer, so every comparison here allows for its rounding
assert.ok(p.filter((_, i) => i % 3 === 1).every((y) => Math.abs(y - 0.01) < 1e-6), "every vertex at the given height");
const zs = p.filter((_, i) => i % 3 === 2);
assert.ok(Math.abs(Math.min(...zs) + 0.08) < 1e-6 && Math.abs(Math.max(...zs) - 0.08) < 1e-6, "0.16 m wide");
const xs = p.filter((_, i) => i % 3 === 0);
assert.ok(Math.abs(Math.min(...xs)) < 1e-6 && Math.abs(Math.max(...xs) - 2) < 1e-6, "from end to end");
});
test("a bend gets a disc, a joint that barely turns does not", () => {
const quad = positions(trailGeometry([[[0, 0], [1, 0]]], 0.16, 0)).length;
const straight = positions(trailGeometry([[[0, 0], [1, 0], [2, 0]]], 0.16, 0)).length;
assert.equal(straight, quad * 2, "two steps, and a joint that does not turn adds nothing");
const bent = trailGeometry([[[0, 0], [1, 0], [1, 1]]], 0.16, 0);
assert.ok(positions(bent).length > straight, "a real bend adds the disc that fills the notch");
const slight = trailGeometry([[[0, 0], [1, 0], [2, 0.1]]], 0.16, 0);
assert.equal(positions(slight).length, straight, "five degrees is not a notch worth a disc");
});
test("a trail of dots leaves nothing to draw", () => {
assert.equal(positions(trailGeometry([[[0, 0], [0, 0]]], 0.16, 0)).length, 0, "a zero-length step");
assert.equal(positions(trailGeometry([], 0.16, 0)).length, 0, "no segments at all");
assert.equal(positions(trailGeometry([[[1, 1]]], 0.16, 0)).length, 0, "one point is no way");
});
test("several segments are drawn one after another", () => {
const one = positions(trailGeometry([[[0, 0], [1, 0]]], 0.16, 0)).length;
const two = positions(trailGeometry([[[0, 0], [1, 0]], [[2, 0], [3, 0]]], 0.16, 0)).length;
assert.equal(two, one * 2);
});
test("the pad stays full for ten minutes after the robot stops, then fades", () => {
const docked = 1_000_000;
assert.equal(trailOpacity(null, docked), 1, "still cleaning: full");
assert.equal(trailOpacity(docked, docked), 1, "just docked");
assert.equal(trailOpacity(docked, docked + TRAIL_HOLD_MS - 1), 1, "one millisecond before the hold ends");
assert.equal(trailOpacity(docked, docked + TRAIL_HOLD_MS), 1, "the hold ends where the fade starts");
const half = trailOpacity(docked, docked + TRAIL_HOLD_MS + TRAIL_FADE_MS / 2);
assert.ok(Math.abs(half - 0.5) < 1e-9, `halfway through the fade: ${half}`);
assert.equal(trailOpacity(docked, docked + TRAIL_HOLD_MS + TRAIL_FADE_MS), 0, "gone at the end");
assert.equal(trailOpacity(docked, docked + 10 * TRAIL_HOLD_MS), 0, "and stays gone");
});
+71
View File
@@ -0,0 +1,71 @@
/**
* The pad a robot has driven on, drawn flat on the floor: a ribbon along its trail, with a disc at every
* bend so the turns do not fray. The robot's own app draws the same thing, and it is what makes "where has
* it been" readable in the plan rather than a hairline.
*/
import { BufferGeometry, Float32BufferAttribute } from "three";
import type { Vec2 } from "../model.ts";
/** How long the pad stays after the robot stopped cleaning: ten minutes, then it fades. */
export const TRAIL_HOLD_MS = 10 * 60 * 1000;
/** How long the fade itself takes. */
export const TRAIL_FADE_MS = 3000;
/**
* How strongly the pad still shows, 1 while it drives and for ten minutes after it stopped, then fading to
* 0. The timeline is where the day's cleans stay, so the floor does not keep last night's pad forever.
*/
export function trailOpacity(settledAt: number | null | undefined, now: number): number {
if (settledAt == null) return 1;
const settled = now - settledAt;
if (!(settled > TRAIL_HOLD_MS)) return 1;
return Math.max(0, 1 - (settled - TRAIL_HOLD_MS) / TRAIL_FADE_MS);
}
/**
* A flat ribbon along `segments`, `width` metres wide, lying at height `y`. One quad per segment and a
* disc at every interior joint; a trail shorter than a millimetre leaves an empty geometry.
*/
export function trailGeometry(segments: readonly (readonly Vec2[])[], width: number, y: number): BufferGeometry {
const half = width / 2;
const pos: number[] = [];
const tri = (a: Vec2, b: Vec2, c: Vec2) => pos.push(a[0], y, a[1], b[0], y, b[1], c[0], y, c[1]);
for (const line of segments) {
for (let i = 0; i + 1 < line.length; i++) {
const [p, q] = [line[i], line[i + 1]];
const [dx, dz] = [q[0] - p[0], q[1] - p[1]];
const len = Math.hypot(dx, dz);
if (len < 1e-4) continue;
const [nx, nz] = [(-dz / len) * half, (dx / len) * half];
const [a, b]: [Vec2, Vec2] = [
[p[0] + nx, p[1] + nz],
[p[0] - nx, p[1] - nz],
];
const [c, d]: [Vec2, Vec2] = [
[q[0] + nx, q[1] + nz],
[q[0] - nx, q[1] - nz],
];
tri(a, b, c);
tri(b, d, c);
}
// a joint: a disc as wide as the ribbon, so two segments meeting at an angle leave no notch — a joint that
// barely turns needs none, and a dense trail is nearly all such joints
const steps = 6;
for (let i = 1; i + 1 < line.length; i++) {
const [b0, b1, b2] = [line[i - 1], line[i], line[i + 1]];
const [ax, az] = [b1[0] - b0[0], b1[1] - b0[1]];
const [bx, bz] = [b2[0] - b1[0], b2[1] - b1[1]];
const [la, lb] = [Math.hypot(ax, az), Math.hypot(bx, bz)];
// the sine of the angle between the two steps: below this the quads already meet
if (la < 1e-9 || lb < 1e-9 || Math.abs(ax * bz - az * bx) / (la * lb) < 0.2) continue;
const [cx, cz] = line[i];
for (let k = 0; k < steps; k++) {
const [a0, a1] = [(k / steps) * Math.PI * 2, ((k + 1) / steps) * Math.PI * 2];
tri([cx, cz], [cx + Math.cos(a0) * half, cz + Math.sin(a0) * half], [cx + Math.cos(a1) * half, cz + Math.sin(a1) * half]);
}
}
}
const geometry = new BufferGeometry();
geometry.setAttribute("position", new Float32BufferAttribute(pos, 3));
return geometry;
}
+87
View File
@@ -0,0 +1,87 @@
import assert from "node:assert/strict";
import { test } from "node:test";
import { pointInPolygon, type Vec2 } from "../model.ts";
import { circlePath, cleaningPath, ROBOT_SPEED, stepRobot, type RobotInfo, type RobotMotion } from "./robot.ts";
const hall: Vec2[] = [[0, 0], [6, 0], [6, 3], [0, 3]];
const info = (mode: RobotInfo["mode"], extra: Partial<RobotInfo> = {}): RobotInfo => ({ id: "r", floorId: "f", rest: [0, 0], restHeading: 0, mode, room: hall, ...extra });
const motion = (pos: Vec2, extra: Partial<RobotMotion> = {}): RobotMotion => ({ pos, heading: 0, path: [], next: 0, ...extra });
test("lanes run along the longer side, back and forth, and stay inside the room", () => {
const path = cleaningPath(hall);
assert.ok(path.length >= 16);
assert.ok(path.every((p) => pointInPolygon(p, hall)));
// along x: both ends of a lane share their z, and the next lane runs the other way
for (let i = 0; i + 1 < path.length; i += 2) assert.equal(path[i][1], path[i + 1][1]);
assert.ok(path[1][0] > path[0][0] && path[3][0] < path[2][0]);
// a tall room is cleaned along z
const tall: Vec2[] = [[0, 0], [3, 0], [3, 6], [0, 6]];
const lane = cleaningPath(tall);
assert.equal(lane[0][0], lane[1][0]);
});
test("a narrow room gives fewer lanes than a wide one, and a closet gives none", () => {
assert.ok(cleaningPath([[0, 0], [6, 0], [6, 1], [0, 1]]).length < cleaningPath(hall).length);
assert.deepEqual(cleaningPath([[0, 0], [0.3, 0], [0.3, 0.3], [0, 0.3]]), []);
});
test("lanes keep out of the missing corner of an L-shaped room", () => {
const l: Vec2[] = [[0, 0], [4, 0], [4, 2], [2, 2], [2, 4], [0, 4]];
assert.ok(cleaningPath(l).every((p) => pointInPolygon(p, l)));
});
test("lanes keep clear of furniture and never cross it when changing lanes", () => {
const room: Vec2[] = [[0, 0], [5, 0], [5, 4], [0, 4]];
const wardrobe: Vec2[] = [[0, 0], [2, 0], [2, 0.6], [0, 0.6]];
const sofa: Vec2[] = [[2, 1.8], [4, 1.8], [4, 2.7], [2, 2.7]];
const path = cleaningPath(room, 0.32, 0.22, [wardrobe, sofa]);
assert.ok(path.length >= 4);
for (let i = 1; i < path.length; i++) {
const [a, b] = [path[i - 1], path[i]];
for (let t = 0; t <= 1; t += 0.02) {
const p: Vec2 = [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t];
assert.ok(!pointInPolygon(p, wardrobe) && !pointInPolygon(p, sofa), `segment ${i} crosses furniture`);
}
}
});
test("the circle path surrounds its centre at the given radius", () => {
const circle = circlePath([1, 2], 0.5, 8);
assert.equal(circle.length, 8);
for (const p of circle) assert.ok(Math.abs(Math.hypot(p[0] - 1, p[1] - 2) - 0.5) < 1e-9);
assert.equal(circlePath([0, 0]).length, 12);
});
test("a returning robot turns on the spot first, then drives home and faces away from the dock", () => {
const m = motion([2, 0]);
const robot = info("returning");
stepRobot(m, robot, 0.1);
assert.deepEqual(m.pos, [2, 0], "facing +z while the dock lies at -x: only turning");
let steps = 0;
while (stepRobot(m, robot, 0.05) && steps++ < 600);
assert.ok(Math.hypot(...m.pos) < 0.03);
assert.ok(Math.abs(m.heading - robot.restHeading) < 0.05);
assert.equal(stepRobot(m, robot, 0.05), false, "at rest it stays");
});
test("it never drives faster than its speed", () => {
const m = motion([3, 0], { heading: -Math.PI / 2 });
const before = m.pos[0];
stepRobot(m, info("returning"), 1);
assert.ok(before - m.pos[0] <= ROBOT_SPEED + 1e-9);
});
test("a cleaning robot follows its path round and round; idle, error and path-less robots stay put", () => {
const path: Vec2[] = [[1, 1], [1, 2]];
const m = motion([1, 1], { path, heading: 0 });
const robot = info("cleaning");
const seen = new Set<number>();
for (let i = 0; i < 400; i++) {
stepRobot(m, robot, 0.05);
seen.add(m.next);
}
assert.deepEqual([...seen].sort(), [0, 1], "it keeps going between its two points");
assert.equal(stepRobot(motion([1, 1]), robot, 0.05), false, "no path: nothing to do");
assert.equal(stepRobot(motion([1, 1]), info("idle"), 0.05), false);
assert.equal(stepRobot(motion([1, 1]), info("error"), 0.05), false);
});
+153
View File
@@ -0,0 +1,153 @@
// Robot vacuums in 3D. Home Assistant reports the state (cleaning, returning, docked ...) but usually not where the robot is.
// So while it cleans it drives lanes through the room its dock stands in, returns to the dock when it goes home, and waits in
// front of the dock otherwise.
import { pointInPolygon, type Vec2 } from "../model.ts";
export type RobotMode = "cleaning" | "returning" | "docked" | "idle" | "error";
export interface RobotInfo {
/** The furniture item (the dock). */
id: string;
floorId: string;
/** Where the robot rests: in front of its dock, facing away from it (radians). */
rest: Vec2;
restHeading: number;
mode: RobotMode;
/** The outline of the room it cleans; null means circles near the dock. */
room: Vec2[] | null;
/** The id of that room: a new room starts new lanes. */
roomId?: string | null;
/** Footprints of the furniture in its way (cabinets, sofas, beds; not tables or chairs). */
obstacles?: Vec2[][];
/** Height it drives at above its floor (a robot mower on the lawn below the ground floor). */
y?: number;
/** The pad it has driven on, from its own map (segments in the plan); null keeps the drawn lanes. */
track?: Vec2[][] | null;
/** Where it really is, from its own map; null lets it drive the drawn lanes. */
pose?: { x: number; z: number; heading: number } | null;
/** When it stopped cleaning (ms since the epoch), so its pad can fade; null while it still drives. */
settledAt?: number | null;
/** A robot mower: a larger, green body. */
mower?: boolean;
}
/** Driving speed in m/s and turning speed in rad/s. */
export const ROBOT_SPEED = 0.3;
export const ROBOT_TURN = 2.6;
const SAMPLE = 0.05;
/** Whether a spot is free for the robot: clear of the walls on all four sides, and of furniture also on the diagonals. */
function spotIsFree(p: Vec2, room: Vec2[], obstacles: readonly Vec2[][], inset: number): boolean {
const diagonal = inset * 0.7071;
const sides: Vec2[] = [p, [p[0] + inset, p[1]], [p[0] - inset, p[1]], [p[0], p[1] + inset], [p[0], p[1] - inset]];
const corners: Vec2[] = [[p[0] + diagonal, p[1] + diagonal], [p[0] - diagonal, p[1] + diagonal], [p[0] + diagonal, p[1] - diagonal], [p[0] - diagonal, p[1] - diagonal]];
return sides.every((q) => pointInPolygon(q, room)) && !obstacles.some((o) => [...sides, ...corners].some((q) => pointInPolygon(q, o)));
}
/** Whether a straight drive from p to q stays free all the way. */
function driveIsClear(p: Vec2, q: Vec2, free: (spot: Vec2) => boolean): boolean {
const steps = Math.ceil(Math.hypot(q[0] - p[0], q[1] - p[1]) / SAMPLE);
for (let i = 1; i < steps; i++) if (!free([p[0] + ((q[0] - p[0]) * i) / steps, p[1] + ((q[1] - p[1]) * i) / steps])) return false;
return true;
}
/** The longest stretch of free samples across the room along one lane, or null. */
function longestRun(isFree: (b: number) => boolean, from: number, to: number): [number, number] | null {
let best: [number, number] | null = null;
let start: number | null = null;
for (let b = from; b <= to + 1e-6; b += SAMPLE) {
const free = isFree(b);
if (free) start ??= b;
if ((!free || b + SAMPLE > to + 1e-6) && start !== null) {
const end = free ? b : b - SAMPLE;
if (!best || end - start > best[1] - best[0]) best = [start, end];
start = null;
}
}
return best;
}
/**
* Lanes through a room, back and forth along its longer side, keeping `inset` from the walls and from furniture in the way.
* Each lane takes the longest free stretch; a lane that cannot be reached from the previous one without crossing furniture is
* left out.
*/
export function cleaningPath(room: Vec2[], lane = 0.32, inset = 0.22, obstacles: readonly Vec2[][] = []): Vec2[] {
const xs = room.map((p) => p[0]);
const zs = room.map((p) => p[1]);
const [x0, x1, z0, z1] = [Math.min(...xs), Math.max(...xs), Math.min(...zs), Math.max(...zs)];
// lanes run along the longer side, which means fewer turns
const alongZ = z1 - z0 >= x1 - x0;
const free = (p: Vec2) => spotIsFree(p, room, obstacles, inset);
const at = (a: number, b: number): Vec2 => (alongZ ? [a, b] : [b, a]);
const [a0, a1, b0, b1] = alongZ ? [x0, x1, z0, z1] : [z0, z1, x0, x1];
const path: Vec2[] = [];
let forward = true;
for (let a = a0 + inset; a <= a1 - inset + 1e-6; a += lane) {
const run = longestRun((b) => free(at(a, b)), b0, b1);
if (!run || run[1] - run[0] < 0.2) continue;
const ends = (towardsEnd: boolean): [Vec2, Vec2] => (towardsEnd ? [at(a, run[0]), at(a, run[1])] : [at(a, run[1]), at(a, run[0])]);
let lanePoints = ends(forward);
const previous = path[path.length - 1];
if (previous && obstacles.length > 0 && !driveIsClear(previous, lanePoints[0], free)) {
// the other way round, or leave the lane out when furniture is in the way either way
const reversed = ends(!forward);
if (!driveIsClear(previous, reversed[0], free)) continue;
lanePoints = reversed;
forward = !forward;
}
path.push(...lanePoints);
forward = !forward;
}
return path;
}
/** A small circle in front of the dock, for robots outside any room. */
export function circlePath(center: Vec2, radius = 0.7, points = 12): Vec2[] {
return Array.from({ length: points }, (_, i): Vec2 => [center[0] + Math.cos((i / points) * Math.PI * 2) * radius, center[1] + Math.sin((i / points) * Math.PI * 2) * radius]);
}
/** The moving state of one robot. */
export interface RobotMotion {
pos: Vec2;
heading: number;
path: Vec2[];
next: number;
}
const wrapAngle = (a: number) => Math.atan2(Math.sin(a), Math.cos(a));
/** Advances a robot by `dt` seconds: it turns towards the next target and drives when it faces it. Returns whether it still moves. */
export function stepRobot(m: RobotMotion, info: RobotInfo, dt: number): boolean {
let target: Vec2;
if (info.mode === "cleaning") {
if (m.path.length === 0) return false;
target = m.path[m.next % m.path.length];
} else if (info.mode === "returning" || info.mode === "docked") target = info.rest;
else return false;
const [dx, dz] = [target[0] - m.pos[0], target[1] - m.pos[1]];
const distance = Math.hypot(dx, dz);
if (distance < 0.02) {
if (info.mode === "cleaning") {
m.next = (m.next + 1) % m.path.length;
return true;
}
// at home: turn to face away from the dock
const off = wrapAngle(info.restHeading - m.heading);
if (Math.abs(off) < 0.02) return false;
m.heading += Math.sign(off) * Math.min(Math.abs(off), ROBOT_TURN * dt);
return true;
}
// heading 0 faces +z; the robot turns on the spot before it drives
const off = wrapAngle(Math.atan2(dx, dz) - m.heading);
m.heading = wrapAngle(m.heading + Math.sign(off) * Math.min(Math.abs(off), ROBOT_TURN * dt));
if (Math.abs(off) < 0.35) {
const step = Math.min(distance, ROBOT_SPEED * dt);
m.pos = [m.pos[0] + (dx / distance) * step, m.pos[1] + (dz / distance) * step];
}
return true;
}
+7
View File
@@ -0,0 +1,7 @@
// The roof, split into modules in roof/: the single roof, roof sections, canopy frames, and what sits in a roof.
export { buildRoof } from "./roof/roof.ts";
export { roofFloor } from "./roof/single.ts";
export { pushSection } from "./roof/sections.ts";
export { pushModules, type RoofWindowState } from "./roof/fittings.ts";
export type { RoofGeometry } from "./roof/types.ts";
+64
View File
@@ -0,0 +1,64 @@
// The frame of a canopy: a beam under each free edge of the roof, posts at its corners and at most 3.5 m apart along the free sides.
// An edge against the house (no overhang) rests on the wall.
import type { SectionOverhang } from "../../roof-sections.ts";
import type { sectionFrame, sectionProfile } from "../../roof-sections.ts";
import { EAVE, FRAME, FRAME_TOP } from "./palette.ts";
import { pushPrism, type GeoBuffer, type LineBuffer } from "../geo.ts";
const POST = 0.12;
const BEAM = 0.16;
export function pushCanopyFrame(
solid: GeoBuffer,
lines: LineBuffer,
frame: ReturnType<typeof sectionFrame>,
profile: ReturnType<typeof sectionProfile>,
overhang: SectionOverhang,
point: (u: number, v: number, y: number) => number[],
levelOffset: number,
): void {
const w = frame.w;
const [freeA, freeB, freeStart, freeEnd] = [overhang.a > 0, overhang.b > 0, overhang.u0 > 0, overhang.u1 > 0];
const box = (u0: number, u1: number, v0: number, v1: number, y0: number, y1: number) => {
const ring = [frame.at(u0, v0), frame.at(u1, v0), frame.at(u1, v1), frame.at(u0, v1)];
// the frame may be flipped: keep the outline counter-clockwise
const turn = (ring[1][0] - ring[0][0]) * (ring[2][1] - ring[0][1]) - (ring[2][0] - ring[0][0]) * (ring[1][1] - ring[0][1]);
pushPrism(solid, turn < 0 ? [...ring].reverse() : ring, y0 - levelOffset, y1 - levelOffset, FRAME, FRAME_TOP, { bottom: true });
};
// beams along the free long sides, under the roof at its height there
for (const [v, free] of [[0, freeA], [w, freeB]] as const) {
if (!free) continue;
const y = profile.y(v) - 0.03;
const start = v === 0 ? 0 : w - POST;
box(frame.u0, frame.u1, start, start + POST, y - BEAM, y);
lines.seg(point(frame.u0, v, y - BEAM), point(frame.u1, v, y - BEAM), EAVE);
}
// beams along the free ends, following the slope in six steps
for (const [u, free] of [[frame.u0, freeStart], [frame.u1 - POST, freeEnd]] as const) {
if (!free) continue;
for (let i = 0; i < 6; i++) {
const [v0, v1] = [(w * i) / 6, (w * (i + 1)) / 6];
const y = Math.min(profile.y(v0), profile.y(v1)) - 0.03;
box(u, u + POST, v0, v1, y - BEAM, y);
}
}
// posts: at corners where both edges are free (a corner at the house wall rests on the wall), and along a free long side at most 3.5 m apart
const posts: [number, number][] = [];
for (const [v, free] of [[0, freeA], [w - POST, freeB]] as const) {
if (!free) continue;
const span = frame.u1 - frame.u0 - POST;
const count = Math.max(1, Math.ceil(span / 3.5));
for (let i = 0; i <= count; i++) {
if ((i === 0 && !freeStart) || (i === count && !freeEnd)) continue;
posts.push([frame.u0 + (span * i) / count, v]);
}
}
// a pent roof against the house with only its ends free still needs posts at its outer corners
if (!freeA && !freeB) {
if (freeStart) posts.push([frame.u0, w / 2 - POST / 2]);
if (freeEnd) posts.push([frame.u1 - POST, w / 2 - POST / 2]);
}
for (const [u, v] of posts) box(u, u + POST, v, v + POST, levelOffset, profile.y(v + POST / 2) - 0.03 - BEAM);
}
+165
View File
@@ -0,0 +1,165 @@
// What sits in a roof: solar modules and roof windows.
import type { Building, SolarField } from "../../model.ts";
import { chimneyPlace, chimneySize, fieldModules, roofFaces, windowCorners, type RoofFace } from "../../solar.ts";
import { DEG, pushPrism, type GeoBuffer, type LineBuffer } from "../geo.ts";
import type { Vec2 } from "../../model.ts";
import { CHIMNEY, CHIMNEY_CAP, CHIMNEY_EDGE, CHIMNEY_FLUE, CHIMNEY_STEEL, CHIMNEY_STEEL_TOP, CHIMNEY_TOP, PANEL_LOOKS, PANEL_POST, WINDOW_BLIND, WINDOW_FRAME, WINDOW_GLASS, WINDOW_WARM } from "./palette.ts";
import type { RoofGeometry } from "./types.ts";
/** How far a roof window's sash is open (1 = open, a tilt counts less) and how far its blind is down. */
export interface RoofWindowState {
open: number;
tilt: number;
cover: number;
}
type P3 = number[];
const lerp3 = (p: P3, q: P3, t: number): P3 => [p[0] + (q[0] - p[0]) * t, p[1] + (q[1] - p[1]) * t, p[2] + (q[2] - p[2]) * t];
const along = (p: P3, direction: readonly number[], k: number): P3 => [p[0] + direction[0] * k, p[1] + direction[1] * k, p[2] + direction[2] * k];
/** The part of the roof a face belongs to: the one carrying its section, or the first part for the single roof. */
const partOf = (parts: RoofGeometry[], face: RoofFace): RoofGeometry | undefined => (face.section ? parts.find((p) => p.sections?.includes(face.section!)) : parts[0]);
/** Roof windows: frame and glass in the slope; the sash swings out at the top when open, and the blind comes down. */
export function pushRoofWindows(b: Building, parts: RoofGeometry[], states: ReadonlyMap<string, RoofWindowState>): void {
const windows = b.settings.roof?.windows ?? [];
if (windows.length === 0 || parts.length === 0) return;
const faces = new Map(roofFaces(b).map((f) => [f.key, f]));
for (const w of windows) {
const face = faces.get(w.face);
const corners = face ? windowCorners(face, w) : null;
const part = face && corners ? partOf(parts, face) : undefined;
if (!face || !corners || !part) continue;
const shift = part.floor.elevation + part.base;
const [a, c, d, e] = corners.map((p): P3 => [p[0], p[1] - shift, p[2]]);
const state = states.get(w.id) ?? { open: 0, tilt: 0, cover: 0 };
const raised = (p: P3, k: number) => along(p, face.n, k);
// the fixed frame in the roof, glowing warm while the window is open or tilted
const frame = state.open > 0.02 || state.tilt > 0.02 ? WINDOW_WARM : WINDOW_FRAME;
const ring = [a, c, d, e].map((p) => raised(p, 0.06));
ring.forEach((p, i) => part.lines.seg(p, ring[(i + 1) % 4], frame));
// the sash is hinged at the top: its lower edge swings out along the normal (up to 30° open, as far as a motor reports; 12° tilted)
const angle = (state.open > 0.02 ? 30 * Math.min(1, state.open) : state.tilt > 0.5 ? 12 : 0) * DEG;
const height = Math.hypot(d[0] - c[0], d[1] - c[1], d[2] - c[2]);
const swing = (top: P3): P3 => along(along(top, face.es, -height * Math.cos(angle)), face.n, height * Math.sin(angle));
const [top0, top1] = [raised(e, 0.065), raised(d, 0.065)];
const [bottom0, bottom1] = [swing(top0), swing(top1)];
part.solid.tri(bottom0, bottom1, top1, WINDOW_GLASS);
part.solid.tri(bottom0, top1, top0, WINDOW_GLASS);
for (const [p, q] of [[bottom0, bottom1], [bottom1, top1], [top1, top0], [top0, bottom0]]) part.lines.seg(p, q, frame);
// the blind comes down from the top over the sash
if (state.cover > 0.02) {
const k = Math.min(1, state.cover);
const [b0, b1] = [raised(lerp3(top0, bottom0, k), 0.01), raised(lerp3(top1, bottom1, k), 0.01)];
const [t0, t1] = [raised(top0, 0.01), raised(top1, 0.01)];
part.solid.tri(b0, b1, t1, WINDOW_BLIND);
part.solid.tri(b0, t1, t0, WINDOW_BLIND);
}
}
}
/** The modules of a field (glass, frame, cell grid, stands on flat ground), lowered by `dy` into local coordinates. */
export function pushModules(solid: GeoBuffer, lines: LineBuffer, face: RoofFace, field: SolarField, dy: number): void {
const lower = (p: P3): P3 => [p[0], p[1] - dy, p[2]];
const look = PANEL_LOOKS[field.look === "blue" ? "blue" : "black"];
const [cellsAcross, cellsUp] = field.portrait === false ? [10, 6] : [6, 10];
for (const module of fieldModules(face, field)) {
const [a, c, d, e] = module.corners.map(lower);
// both sides: on a floor (garden, walls) only front faces are drawn, and a module may lean either way
for (const [p, q, r] of [[a, c, d], [a, d, e], [a, d, c], [a, e, d]]) solid.tri(p, q, r, look.glass);
// the frame a hair above the glass, and the cell grid
const lifted = (p: P3) => along(p, face.n, 0.004);
const ring = [a, c, d, e].map(lifted);
ring.forEach((p, i) => lines.seg(p, ring[(i + 1) % 4], look.edge));
for (let i = 1; i < cellsAcross; i++) lines.seg(lifted(lerp3(a, c, i / cellsAcross)), lifted(lerp3(e, d, i / cellsAcross)), look.cells);
for (let j = 1; j < cellsUp; j++) lines.seg(lifted(lerp3(a, e, j / cellsUp)), lifted(lerp3(c, d, j / cellsUp)), look.cells);
for (const [p, q] of module.posts) lines.seg(lower(p), lower(q), PANEL_POST);
}
}
/** Solar fields on the roof: every module on its face, in the coordinates of the roof part the face belongs to. */
export function pushSolar(b: Building, parts: RoofGeometry[]): void {
const fields = b.settings.roof?.solar ?? [];
if (fields.length === 0 || parts.length === 0) return;
const faces = new Map(roofFaces(b).map((f) => [f.key, f]));
for (const field of fields) {
const face = faces.get(field.face);
const part = face ? partOf(parts, face) : undefined;
// faces have heights above the ground; parts count from their floor's level plus their base
if (face && part) pushModules(part.solid, part.lines, face, field, part.floor.elevation + part.base);
}
}
/**
* Chimneys: upright from inside the roof to `h` above its upper side. Brick and wide ones get a cap and their black flues on
* top, a round one a flue in its middle, a steel pipe a rain cap held a little above it.
*/
export function pushChimneys(b: Building, parts: RoofGeometry[]): void {
const chimneys = b.settings.roof?.chimneys ?? [];
if (chimneys.length === 0 || parts.length === 0) return;
const faces = new Map(roofFaces(b).map((f) => [f.key, f]));
for (const c of chimneys) {
const face = faces.get(c.face);
const part = face ? partOf(parts, face) : undefined;
if (!face || !part) continue;
const shift = part.floor.elevation + part.base;
const { shape, w, d, h } = chimneySize(c);
const place = chimneyPlace(face, c);
const [y0, y1] = [place.low - shift - 0.1, place.high - shift + h];
const rect = (hw: number, hd: number): Vec2[] => {
const { center: m, along: a, across: x } = place;
const p = (su: number, sd: number): Vec2 => [m[0] + a[0] * hw * su + x[0] * hd * sd, m[1] + a[1] * hw * su + x[1] * hd * sd];
return [p(-1, -1), p(1, -1), p(1, 1), p(-1, 1)];
};
const circle = (r: number, n = 16): Vec2[] => Array.from({ length: n }, (_, i) => [place.center[0] + Math.cos((i / n) * 2 * Math.PI) * r, place.center[1] + Math.sin((i / n) * 2 * Math.PI) * r] as Vec2);
const outline = (poly: Vec2[], y: number) => poly.forEach((p, i) => part.lines.seg([p[0], y, p[1]], [poly[(i + 1) % poly.length][0], y, poly[(i + 1) % poly.length][1]], CHIMNEY_EDGE));
const prism = (poly: Vec2[], from: number, to: number, side: number, top: number) => pushPrism(part.solid, ensureCcw(poly), from, to, side, top);
if (shape === "steel") {
const r = Math.min(w, d) / 2;
prism(circle(r, 12), y0, y1, CHIMNEY_STEEL, CHIMNEY_STEEL_TOP);
prism(circle(r * 0.75, 12), y1, y1 + 0.001, CHIMNEY_FLUE, CHIMNEY_FLUE);
// the rain cap on its little stand
prism(circle(r * 0.25, 6), y1, y1 + 0.1, CHIMNEY_STEEL, CHIMNEY_STEEL_TOP);
const hat = circle(r * 1.9, 12);
prism(hat, y1 + 0.1, y1 + 0.13, CHIMNEY_STEEL, CHIMNEY_STEEL_TOP);
outline(hat, y1 + 0.13);
continue;
}
if (shape === "round") {
const r = Math.min(w, d) / 2;
const body = circle(r);
prism(body, y0, y1, CHIMNEY, CHIMNEY_TOP);
prism(circle(r * 0.55), y1, y1 + 0.002, CHIMNEY_FLUE, CHIMNEY_FLUE);
outline(body, y1);
continue;
}
// brick and wide: the shaft, a cap a little wider, and the flues on top
const body = rect(w / 2, d / 2);
prism(body, y0, y1, CHIMNEY, CHIMNEY_TOP);
const cap = rect(w / 2 + 0.04, d / 2 + 0.04);
prism(cap, y1, y1 + 0.06, CHIMNEY_CAP, CHIMNEY_CAP);
outline(cap, y1 + 0.06);
outline(body, y1 - 0.25);
const flue = Math.min(w, d) * 0.25;
const flues = shape === "wide" ? [-w / 4, w / 4] : [0];
for (const off of flues) {
const m: Vec2 = [place.center[0] + place.along[0] * off, place.center[1] + place.along[1] * off];
const pipe: Vec2[] = [[-1, -1], [1, -1], [1, 1], [-1, 1]].map(([su, sd]) => [m[0] + place.along[0] * flue * su + place.across[0] * flue * sd, m[1] + place.along[1] * flue * su + place.across[1] * flue * sd]);
prism(pipe, y1 + 0.06, y1 + 0.16, CHIMNEY_CAP, CHIMNEY_FLUE);
}
}
}
/** pushPrism wants its ring counter-clockwise in the plan (seen from above). */
function ensureCcw(poly: Vec2[]): Vec2[] {
let area = 0;
for (let i = 0; i < poly.length; i++) {
const [p, q] = [poly[i], poly[(i + 1) % poly.length]];
area += p[0] * q[1] - q[0] * p[1];
}
return area < 0 ? [...poly].reverse() : poly;
}
+39
View File
@@ -0,0 +1,39 @@
// Colours of the roof scene.
import { Color } from "three";
import { shade } from "../geo.ts";
export const ROOF = 0x1a2338;
export const ROOF_TOP = 0x222d48;
export const GABLE = 0x141d31;
export const RIDGE = shade(0x37e0ff, 0.9);
export const EAVE = shade(0x5b7cff, 0.45);
/** The thickness of the roof covering. */
export const THICK = 0.14;
/** A canopy has see-through panels and a light frame of posts and beams. */
export const GLASS = 0x8fd8ff;
export const FRAME = 0xc9d3e6;
export const FRAME_TOP = 0xe3e9f5;
/** Solar modules: all black (glass, frame, barely visible cells) or the classic blue. */
export const PANEL_LOOKS = {
black: { glass: new Color(0x05070b), edge: shade(0x8a96b0, 0.32), cells: shade(0x2a3550, 0.22) },
blue: { glass: new Color(0x15295a), edge: shade(0x9fb8ff, 0.55), cells: shade(0x3d6cff, 0.35) },
};
export const PANEL_POST = shade(0xc9d3e6, 0.5);
/** Roof windows: a light frame, glass and the blind. The frame of an open or tilted window glows warm, like a wall window. */
export const WINDOW_FRAME = shade(0xc9d3e6, 0.85);
export const WINDOW_WARM = shade(0xffb347, 0.95);
export const WINDOW_GLASS = new Color(0x2b6b8f);
export const WINDOW_BLIND = new Color(0x3a4258);
/** Chimneys: brick or render, a darker cap, the black flue, and steel for a flue pipe. */
export const CHIMNEY = 0x3a2b30;
export const CHIMNEY_TOP = 0x4a3840;
export const CHIMNEY_CAP = 0x2a3448;
export const CHIMNEY_FLUE = 0x05070b;
export const CHIMNEY_STEEL = 0x8b97ad;
export const CHIMNEY_STEEL_TOP = 0xb4c0d4;
export const CHIMNEY_EDGE = shade(0x5b7cff, 0.4);
+139
View File
@@ -0,0 +1,139 @@
import assert from "node:assert/strict";
import { test } from "node:test";
import { emptyBuilding, newFloor, type Building, type RoofSection, type Room } from "../../model.ts";
import { proposeChimney, proposeField } from "../../solar/placing.ts";
import { chimneyPlace, roofFaces } from "../../solar.ts";
import { buildRoof, pushModules, roofFloor, pushSection } from "../roof.ts";
import { GeoBuffer, LineBuffer } from "../geo.ts";
const room = (id: string, x0: number, z0: number, x1: number, z1: number): Room => ({ id, name: id, area_id: null, points: [[x0, z0], [x1, z0], [x1, z1], [x0, z1]], floor_material: "wood" });
function house(roof: Building["settings"]["roof"], floors: [string, number, Room[]][] = [["g", 0, [room("a", 0, 0, 10, 6)]]]): Building {
const b = emptyBuilding();
b.floors = floors.map(([id, elevation, rooms]) => ({ ...newFloor(id, id, elevation), height: 2.6, rooms }));
b.settings = { ...b.settings, wall_exterior: 0.3, roof };
return b;
}
const topOf = (buf: GeoBuffer) => Math.max(...buf.p.filter((_, i) => i % 3 === 1));
const section = (patch: Partial<RoofSection> = {}): RoofSection => ({ id: "s", x0: 0, z0: 0, x1: 10, z1: 6, shape: "gable", axis: "x", eave_a: 2.6, eave_b: 2.6, pitch_a: 35, pitch_b: 35, base: 2.6, overhang: 0.4, ...patch });
test("no roof gives no parts", () => {
assert.deepEqual(buildRoof(house({ type: "none", pitch: 35, overhang: 0.4 })), []);
assert.deepEqual(buildRoof(emptyBuilding()), []);
});
test("the roof sits on the highest floor with rooms", () => {
const b = house({ type: "gable", pitch: 35, overhang: 0.4 }, [["g", 0, [room("a", 0, 0, 5, 5)]], ["u", 2.7, [room("b", 0, 0, 5, 5)]], ["empty", 5.4, []]]);
assert.equal(roofFloor(b)?.id, "u");
const [part] = buildRoof(b);
assert.equal(part.floor.id, "u");
assert.equal(part.base, 2.6);
});
test("a gable rises to half the roof's depth times its slope, with the ridge along the longer side", () => {
const [part] = buildRoof(house({ type: "gable", pitch: 40, overhang: 0.5 }));
const depth = 6 + 2 * 0.8;
assert.ok(Math.abs(topOf(part.solid) - (depth / 2) * Math.tan((40 * Math.PI) / 180)) < 0.01);
const ridgeLine = [...Array(part.lines.p.length / 6).keys()].find((s) => part.lines.p[s * 6 + 1] > 1 && part.lines.p[s * 6 + 4] === part.lines.p[s * 6 + 1] && part.lines.p[s * 6 + 2] === part.lines.p[s * 6 + 5])!;
assert.ok(ridgeLine !== undefined, "a ridge line along x at constant z");
});
test("the ridge can run along the short side", () => {
const along = (ridge?: "short") => {
const [part] = buildRoof(house({ type: "gable", pitch: 40, overhang: 0.5, ridge }));
return topOf(part.solid);
};
assert.ok(along("short") > along(undefined), "a longer span across means a higher ridge");
});
test("a flat roof is a slab of 25 cm with an outline", () => {
const [part] = buildRoof(house({ type: "flat", pitch: 0, overhang: 0.4 }));
assert.ok(Math.abs(topOf(part.solid) - 0.25) < 1e-9);
assert.equal(part.lines.p.length / 6, 8);
});
test("sections: every shape draws something, and a canopy has glass instead of tiles", () => {
for (const shape of ["gable", "hip", "halfhip", "pyramid", "mansard", "pent", "flat", "parapet"] as const) {
const [part] = buildRoof(house({ type: "custom", pitch: 35, overhang: 0.4, sections: [section({ shape, pitch_a: shape === "mansard" ? 70 : 35, pitch_b: shape === "mansard" ? 70 : 35 })] }));
assert.ok(part.solid.count > 0, shape);
}
const [canopy] = buildRoof(house({ type: "custom", pitch: 35, overhang: 0.4, sections: [section({ open: true, shape: "pent", pitch_a: 5, pitch_b: 5, overhang: 0.5 })] }));
assert.ok(canopy.glass.count > 0);
assert.equal(canopy.lift, false);
assert.ok(canopy.solid.count > 0, "a frame of posts and beams");
});
test("sections are grouped by the floor they sit on, closed roofs before canopies", () => {
const sections = [section({ id: "low", base: 2.6 }), section({ id: "canopy", open: true, shape: "pent" }), section({ id: "high", base: 5.3, eave_a: 5.3, eave_b: 5.3, x0: 0, x1: 5 })];
const b = house({ type: "custom", pitch: 35, overhang: 0.4, sections }, [["g", 0, [room("a", 0, 0, 10, 6)]], ["u", 2.7, [room("b", 0, 0, 5, 6)]]]);
const parts = buildRoof(b);
assert.ok(parts.length >= 2);
assert.equal(parts[parts.length - 1].lift, false, "the canopy part last");
assert.ok(parts.some((p) => p.sections?.includes("high")));
});
test("tiny sections are ignored", () => {
assert.deepEqual(buildRoof(house({ type: "custom", pitch: 35, overhang: 0.4, sections: [section({ x1: 0.05 })] })), []);
});
test("a dormer on a section opens the slope and adds its own roof", () => {
const main = section({ id: "main" });
const dormer = section({ id: "dormer", x0: 4, x1: 6, z0: 0, z1: 2.5, axis: "z", eave_a: 4, eave_b: 4, pitch_a: 35, pitch_b: 35, base: 3.5, dormer: true, overhang: 0.15 });
const alone = buildRoof(house({ type: "custom", pitch: 35, overhang: 0.4, sections: [main] }))[0].solid.count;
const both = buildRoof(house({ type: "custom", pitch: 35, overhang: 0.4, sections: [main, dormer] }))[0].solid.count;
assert.ok(both > alone);
});
test("solar modules appear on the roof and a roof window draws its frame, glass and blind", () => {
const b = house({ type: "gable", pitch: 35, overhang: 0.4 });
const face = roofFaces(b)[1];
const field = proposeField(face, "f");
b.settings.roof.solar = [field];
const without = buildRoof(house({ type: "gable", pitch: 35, overhang: 0.4 }))[0].solid.count;
assert.ok(buildRoof(b)[0].solid.count > without);
b.settings.roof.windows = [{ id: "w", face: face.key, u: 2, v: 1, w: null, h: null, cover: null, contact: null, tilt: null }];
const closed = buildRoof(b, new Map([["w", { open: 0, tilt: 0, cover: 0 }]]))[0].solid.count;
const shaded = buildRoof(b, new Map([["w", { open: 1, tilt: 0, cover: 1 }]]))[0].solid.count;
assert.ok(closed > buildRoof(house({ type: "gable", pitch: 35, overhang: 0.4 }))[0].solid.count);
assert.equal(shaded, closed + 2, "the blind adds one quad");
});
test("the black and the blue module look differ, and modules use the part's level", () => {
const b = house({ type: "gable", pitch: 35, overhang: 0.4 });
const face = roofFaces(b)[1];
const field = { ...proposeField(face, "f") };
const black = new GeoBuffer();
const blue = new GeoBuffer();
pushModules(black, new LineBuffer(), face, field, 0);
pushModules(blue, new LineBuffer(), face, { ...field, look: "blue" }, 0);
assert.notDeepEqual(black.c.slice(0, 3), blue.c.slice(0, 3));
const lowered = new GeoBuffer();
pushModules(lowered, new LineBuffer(), face, field, 2);
assert.ok(Math.abs(black.p[1] - lowered.p[1] - 2) < 1e-9);
});
test("a section's attic leaves the walls under the roof to the floor", () => {
const solid = new GeoBuffer();
const solidAttic = new GeoBuffer();
pushSection(solid, new LineBuffer(), section({ base: 1.0, eave_a: 3, eave_b: 3 }), 0.4, 0);
pushSection(solidAttic, new LineBuffer(), section({ base: 1.0, eave_a: 3, eave_b: 3 }), 0.4, 0, undefined, true);
assert.ok(solid.count > solidAttic.count, "gable ends are drawn without an attic");
});
test("a chimney stands on the roof near the ridge and rises above it, in every shape", () => {
const plain = house({ type: "gable", pitch: 35, overhang: 0.4 });
const before = buildRoof(plain)[0];
const b = house({ type: "gable", pitch: 35, overhang: 0.4 });
const face = roofFaces(b)[0];
const chimney = proposeChimney(face, "c");
const place = chimneyPlace(face, chimney);
assert.ok(place.high > place.low, "the roof slopes under it");
assert.ok(place.high > 2.6 + 1.5, "near the ridge, well above the eave");
for (const shape of ["brick", "round", "wide", "steel"] as const) {
b.settings.roof.chimneys = [{ ...chimney, shape }];
const part = buildRoof(b)[0];
assert.ok(part.solid.count > before.solid.count, shape);
assert.ok(topOf(part.solid) > topOf(before.solid), `${shape} rises above the ridge`);
}
});
+19
View File
@@ -0,0 +1,19 @@
// The roof as the viewer draws it: either one roof over the top floor, or roof sections at their own heights. Drawn in the
// house view only; the viewer lifts it and fades it out when the camera zooms in.
import type { Building } from "../../model.ts";
import { pushChimneys, pushRoofWindows, pushSolar, type RoofWindowState } from "./fittings.ts";
import { buildSections } from "./sections.ts";
import { buildSingleRoof } from "./single.ts";
import type { RoofGeometry } from "./types.ts";
/** The roof in parts per floor; each part moves with its floor when the floors are pulled apart. */
export function buildRoof(b: Building, windows: ReadonlyMap<string, RoofWindowState> = new Map()): RoofGeometry[] {
const roof = b.settings.roof;
const single = roof?.type === "custom" ? null : buildSingleRoof(b);
const parts = roof?.type === "custom" ? buildSections(b, roof.sections ?? [], roof.overhang) : single ? [single] : [];
pushSolar(b, parts);
pushRoofWindows(b, parts, windows);
pushChimneys(b, parts);
return parts;
}
+218
View File
@@ -0,0 +1,218 @@
// Roofs made of sections: wings of an L- or T-shaped house, a barn with a catslide, a lean-to, canopies. Each section is
// drawn at its own height, and the sections are grouped by the floor they sit on.
import { Color } from "three";
import { polygonArea, type Building, type RoofSection, type Vec2 } from "../../model.ts";
import {
cutHole, dormerHoles, dormerParent, effectiveDormer, wingOf, offsetPolygon, sectionFloor, sectionFrame, sectionGeometry, sectionHeightAt, sectionOverhang, sectionPolygon, sectionProfile, sectionUV,
type Q, type SectionOverhang,
} from "../../roof-sections.ts";
import { roofFaces, windowCorners } from "../../solar.ts";
import { GeoBuffer, LineBuffer, pushPrism } from "../geo.ts";
import { pushCanopyFrame } from "./canopy.ts";
import { EAVE, GABLE, GLASS, RIDGE, ROOF, ROOF_TOP, THICK } from "./palette.ts";
import type { RoofGeometry } from "./types.ts";
type P3 = number[];
type Hole = { u0: number; u1: number; v0: number; v1: number };
/** The part of a roof profile (points across, with heights) above a level, as a closed polygon. */
function profileAbove(profile: [number, number][], level: number): [number, number][] {
const out: [number, number][] = [];
profile.forEach(([v, y], i) => {
if (y >= level) out.push([v, y]);
const next = profile[i + 1];
if (next && (y - level) * (next[1] - level) < 0) {
const t = (level - y) / (next[1] - y);
out.push([v + (next[0] - v) * t, level]);
}
});
if (out.length < 2) return [];
// close along the level
const [first, last] = [out[0], out[out.length - 1]];
if (last[1] > level) out.push([last[0], level]);
if (first[1] > level) out.unshift([first[0], level]);
return out;
}
const counterClockwise = (ring: Vec2[]): Vec2[] => (polygonArea(ring) >= 0 ? ring : [...ring].reverse());
/**
* One section: its slopes with their thickness and rim, the ridge (and hips), and the walls from the section's base up
* under the roof (gable ends and knee walls). `yOff` is the level of its floor.
*/
export function pushSection(
solid: GeoBuffer,
lines: LineBuffer,
s: RoofSection,
overhang: SectionOverhang | number,
yOff: number,
glass: GeoBuffer = solid,
attic = false,
holes: Hole[] = [],
/** A dormer: its gable only at this end (0 = u0, 1 = u1); null for an ordinary section. */
frontEnd: 0 | 1 | null = null,
): void {
const frame = sectionFrame(s);
const profile = sectionProfile(s);
const ov = typeof overhang === "number" ? { u0: overhang, u1: overhang, a: overhang, b: overhang } : overhang;
const [ovA, ovB] = [Math.max(0, ov.a), Math.max(0, ov.b)];
const w = frame.w;
const U0 = frame.u0 - Math.max(0, ov.u0);
const U1 = frame.u1 + Math.max(0, ov.u1);
const at = (u: number, v: number, y: number): P3 => {
const [x, z] = frame.at(u, v);
return [x, y - yOff, z];
};
const topColor = new Color(ROOF_TOP);
const underColor = new Color(ROOF);
const gableColor = new Color(GABLE);
const fan = (points: P3[], color: Color) => {
for (let i = 1; i + 1 < points.length; i++) solid.tri(points[0], points[i], points[i + 1], color);
};
const place = ([u, v, y]: Q, lower = 0) => at(u, v, y - lower);
// the roof planes as polygons in (u, v, height), the rim and the ridge lines; a flat roof is a slab
let faces: Q[][] = [];
let rim: Q[] = [];
let ridges: [Q, Q][] = [];
let gableProfile: [number, number][] | null = null;
let endProfiles: [[number, number][] | null, [number, number][] | null] | null = null;
if (s.shape === "flat" || s.shape === "parapet") {
const y = s.eave_a - yOff;
const parapet = s.shape === "parapet";
// a free shape takes its polygon (grown by the overhang), a plain section its rectangle; a parapet roof has no overhang
const outline =
s.points && s.points.length >= 3
? sectionPolygon(s, parapet ? 0 : Math.max(0, Math.min(ov.a, ov.b, ov.u0, ov.u1)))
: parapet
? [frame.at(frame.u0, 0), frame.at(frame.u1, 0), frame.at(frame.u1, w), frame.at(frame.u0, w)]
: [frame.at(U0, -ovA), frame.at(U1, -ovA), frame.at(U1, w + ovB), frame.at(U0, w + ovB)];
pushPrism(solid, outline, y, y + 0.25, ROOF, ROOF_TOP, { bottom: true });
outline.forEach((a, i) => {
const c = outline[(i + 1) % outline.length];
lines.seg([a[0], y + 0.252, a[1]], [c[0], y + 0.252, c[1]], RIDGE);
lines.seg([a[0], y, a[1]], [c[0], y, c[1]], EAVE);
});
if (parapet) {
// a 0.4 m high, 0.2 m thick wall ring along the edge, on the slab
const outer = counterClockwise(outline);
const inner = offsetPolygon(outer, -0.2);
outer.forEach((a, i) => {
const next = (i + 1) % outer.length;
pushPrism(solid, counterClockwise([a, outer[next], inner[next], inner[i]]), y + 0.25, y + 0.65, ROOF, ROOF_TOP);
lines.seg([a[0], y + 0.652, a[1]], [outer[next][0], y + 0.652, outer[next][1]], RIDGE);
lines.seg([inner[i][0], y + 0.652, inner[i][1]], [inner[next][0], y + 0.652, inner[next][1]], RIDGE);
});
}
} else {
const geometry = sectionGeometry(s, ov);
// dormers: the slope opens under them (a plane with a hole becomes pieces around it)
faces = holes.reduce((planes, hole) => planes.flatMap((plane) => cutHole(plane, hole)), geometry.faces);
rim = geometry.rim;
ridges = geometry.ridges;
gableProfile = geometry.gable;
endProfiles = geometry.endProfiles ?? null;
}
// a canopy has thin see-through panels; a closed roof its tiles with their thickness below
const open = !!s.open;
const pane = new Color(GLASS);
for (const face of faces) {
if (open) {
for (let i = 1; i + 1 < face.length; i++) glass.tri(place(face[0]), place(face[i]), place(face[i + 1]), pane);
} else {
fan(face.map((q) => place(q)), topColor);
fan(face.map((q) => place(q, THICK)), underColor);
}
}
// the rim: eaves and rakes with the roof's thickness
rim.forEach((a, i) => {
const b = rim[(i + 1) % rim.length];
if (!open) fan([place(a), place(b), place(b, THICK), place(a, THICK)], underColor);
lines.seg(place(a), place(b), open ? RIDGE : EAVE);
});
if (open) {
pushCanopyFrame(solid, lines, frame, profile, ov, (u, v, y) => at(u, v, y), yOff);
return;
}
for (const [a, b] of ridges) lines.seg(place([a[0], a[1], a[2] + 0.004]), place([b[0], b[1], b[2] + 0.004]), RIDGE);
// walls up under the roof from the section's base: the gable ends (not under a hip) ...
const base = s.base;
if (attic) return;
if (gableProfile) {
const ends = frontEnd === null ? [frame.u0, frame.u1] : [frontEnd === 0 ? frame.u0 : frame.u1];
for (const u of ends) {
// with an own shape per end, each end has its own wall under it (none under a hip)
const own = endProfiles ? endProfiles[u === frame.u0 ? 0 : 1] : gableProfile;
const polygon = own ? profileAbove(own, base - THICK) : [];
if (polygon.length >= 3) fan(polygon.map(([v, y]) => at(u, v, y)), gableColor);
}
}
// ... and the knee walls along the eaves where the roof starts above the walls (the high back wall of a pent roof)
if (s.shape !== "flat" && s.shape !== "parapet") {
for (const v of [0, w]) {
const y = profile.y(v) - THICK;
if (y > base + 0.02) fan([at(frame.u0, v, base), at(frame.u1, v, base), at(frame.u1, v, y), at(frame.u0, v, y)], gableColor);
}
} else if (s.eave_a > base + 0.02) {
const corners: [number, number][] = [[frame.u0, 0], [frame.u1, 0], [frame.u1, w], [frame.u0, w]];
corners.forEach(([ua, va], i) => {
const [ub, vb] = corners[(i + 1) % 4];
fan([at(ua, va, base), at(ub, vb, base), at(ub, vb, s.eave_a), at(ua, va, s.eave_a)], gableColor);
});
}
}
/** Roof sections, grouped by the floor whose wall tops are nearest below each section's base. */
export function buildSections(b: Building, sections: readonly RoofSection[], overhang: number): RoofGeometry[] {
const floors = b.floors.filter((f) => f.rooms.length > 0).sort((p, q) => p.elevation - q.elevation);
if (floors.length === 0) return [];
const parts = new Map<string, RoofGeometry>();
const faceByKey = new Map(roofFaces(b).map((f) => [f.key, f]));
for (const section of sections) {
if (Math.abs(section.x1 - section.x0) < 0.1 || Math.abs(section.z1 - section.z0) < 0.1) continue;
// the floor the section sits on: the highest one that starts below the top of its walls
const floor = sectionFloor(b, section) ?? floors[0];
// canopies get a part of their own: it rides with the floor but never lifts off like a roof
const key = section.open ? `${floor.id}:open` : floor.id;
let part = parts.get(key);
if (!part) parts.set(key, (part = { floor, base: 0, solid: new GeoBuffer(), lines: new LineBuffer(), glass: new GeoBuffer(), sections: [], lift: !section.open }));
part.sections!.push(section.id);
// a dormer or cross gable (a smaller section on a bigger one) keeps its cheeks and front gable. An attic: the floor's
// walls rise above the section's base, so they end under the slopes themselves and the roof draws none of its own.
// a wing butting against a bigger roof at a right angle reaches into it like a cross gable, so the valleys form there
const wing = wingOf(sections, section);
const parent = dormerParent(sections, section) ?? wing?.parent ?? null;
const attic = floor.elevation + floor.height > section.base + 0.05 && !section.dormer && !parent;
// the slope opens under every dormer and cross gable sitting on this section, and under its roof windows
const holes: Hole[] = sections
.filter((d) => d !== section)
.flatMap((d) => (dormerParent(sections, d) === section ? dormerHoles(section, d) : wingOf(sections, d)?.parent === section ? dormerHoles(section, wingOf(sections, d)!.extended) : []));
for (const w of b.settings.roof.windows ?? []) {
const face = faceByKey.get(w.face);
const corners = face && face.section === section.id ? windowCorners(face, w) : null;
if (!corners) continue;
const uv = corners.map((p) => sectionUV(section, p[0], p[2]));
holes.push({ u0: Math.min(...uv.map((q) => q[0])), u1: Math.max(...uv.map((q) => q[0])), v0: Math.min(...uv.map((q) => q[1])), v1: Math.max(...uv.map((q) => q[1])) });
}
// a dormer only goes as deep as its ridge needs to meet the slope; its gable is only at the front (the lower end of the slope)
const drawn = wing ? wing.extended : parent ? effectiveDormer(parent, section) : section;
let frontEnd: 0 | 1 | null = null;
if (parent) {
const frame = sectionFrame(drawn);
const parentPlanes = sectionGeometry(parent, { u0: 0, u1: 0, a: 0, b: 0 });
const heightAt = (u: number) => {
const [x, z] = frame.at(u, frame.w / 2);
const [pu, pv] = sectionUV(parent, x, z);
return sectionHeightAt(parentPlanes, pu, pv) ?? sectionProfile(parent).y(pv);
};
frontEnd = heightAt(frame.u0) <= heightAt(frame.u1) ? 0 : 1;
}
pushSection(part.solid, part.lines, drawn, sectionOverhang(b, drawn, drawn.overhang ?? overhang), floor.elevation, part.glass, attic, holes, frontEnd);
}
// the closed roofs first: the first part is the one the main roof's solar fields belong to
return [...parts.values()].sort((p, q) => Number(p.lift === false) - Number(q.lift === false));
}
+76
View File
@@ -0,0 +1,76 @@
// The single roof over the top floor: flat or gable, over the bounding box of its rooms plus the outer walls and the overhang.
import { Color } from "three";
import type { Building, Floor } from "../../model.ts";
import { DEG, GeoBuffer, LineBuffer, pushPrism } from "../geo.ts";
import { EAVE, GABLE, RIDGE, ROOF, ROOF_TOP, THICK } from "./palette.ts";
import type { RoofGeometry } from "./types.ts";
/** The floor the single roof sits on: the highest one with rooms. */
export function roofFloor(b: Building): Floor | null {
return b.floors.filter((f) => f.rooms.some((r) => r.points.length >= 3)).sort((p, q) => q.elevation - p.elevation)[0] ?? null;
}
type P3 = number[];
/** One roof over the top floor, in floor coordinates with y = 0 at the top of the floor's walls. */
export function buildSingleRoof(b: Building): RoofGeometry | null {
const roof = b.settings.roof;
const floor = roofFloor(b);
if (!floor || !roof || roof.type === "none" || roof.type === "custom") return null;
const xs = floor.rooms.flatMap((r) => r.points.map((p) => p[0]));
const zs = floor.rooms.flatMap((r) => r.points.map((p) => p[1]));
const margin = b.settings.wall_exterior + roof.overhang;
const [x0, x1] = [Math.min(...xs) - margin, Math.max(...xs) + margin];
const [z0, z1] = [Math.min(...zs) - margin, Math.max(...zs) + margin];
const solid = new GeoBuffer();
const lines = new LineBuffer();
const result: RoofGeometry = { floor, base: floor.height, solid, lines, glass: new GeoBuffer() };
if (roof.type === "flat") {
const corners: [number, number][] = [[x0, z0], [x1, z0], [x1, z1], [x0, z1]];
pushPrism(solid, corners, 0, 0.25, ROOF, ROOF_TOP, { bottom: true });
corners.forEach(([ax, az], i) => {
const [bx, bz] = corners[(i + 1) % 4];
lines.seg([ax, 0.252, az], [bx, 0.252, bz], RIDGE);
lines.seg([ax, 0, az], [bx, 0, bz], EAVE);
});
return result;
}
// a gable: the ridge runs along the longer side, or along the shorter one (terraced houses)
const longerAlongX = x1 - x0 >= z1 - z0;
const alongX = roof.ridge === "short" ? !longerAlongX : longerAlongX;
const half = (alongX ? z1 - z0 : x1 - x0) / 2;
const slope = Math.tan(roof.pitch * DEG);
const rise = half * slope;
// coordinates: u along the ridge, v across (from -half to +half)
const at = (u: number, v: number, y: number): P3 => (alongX ? [u, y, (z0 + z1) / 2 + v] : [(x0 + x1) / 2 + v, y, u]);
const [u0, u1] = alongX ? [x0, x1] : [z0, z1];
const topColor = new Color(ROOF_TOP);
const underColor = new Color(ROOF);
const quad = (a: P3, b2: P3, c: P3, d: P3, color: Color) => {
solid.tri(a, b2, c, color);
solid.tri(a, c, d, color);
};
for (const side of [-1, 1]) {
// the upper and lower face of the slope, and the eave and rake faces of its thickness
quad(at(u0, side * half, 0), at(u1, side * half, 0), at(u1, 0, rise), at(u0, 0, rise), topColor);
quad(at(u0, side * half, -THICK), at(u0, 0, rise - THICK), at(u1, 0, rise - THICK), at(u1, side * half, -THICK), underColor);
quad(at(u0, side * half, -THICK), at(u1, side * half, -THICK), at(u1, side * half, 0), at(u0, side * half, 0), underColor);
for (const u of [u0, u1]) quad(at(u, side * half, -THICK), at(u, side * half, 0), at(u, 0, rise), at(u, 0, rise - THICK), underColor);
lines.seg(at(u0, side * half, 0), at(u1, side * half, 0), EAVE);
for (const u of [u0, u1]) lines.seg(at(u, side * half, 0), at(u, 0, rise), EAVE);
}
// gable walls above the outer walls, set back by the overhang
const inset = roof.overhang;
const gableColor = new Color(GABLE);
const gableHalf = half - inset;
const gableRise = gableHalf * slope;
for (const u of [u0 + inset, u1 - inset]) {
solid.tri(at(u, -gableHalf, -THICK), at(u, gableHalf, -THICK), at(u, 0, gableRise - THICK), gableColor);
solid.tri(at(u, gableHalf, -THICK), at(u, -gableHalf, -THICK), at(u, 0, gableRise - THICK), gableColor);
}
lines.seg(at(u0, 0, rise + 0.004), at(u1, 0, rise + 0.004), RIDGE);
return result;
}
+16
View File
@@ -0,0 +1,16 @@
import type { Floor } from "../../model.ts";
import type { GeoBuffer, LineBuffer } from "../geo.ts";
/** Roof geometry that sits on a floor: y = 0 is `base` above the floor's own level. */
export interface RoofGeometry {
floor: Floor;
base: number;
solid: GeoBuffer;
lines: LineBuffer;
/** See-through roof panels of canopies, drawn with their own, fainter material. */
glass: GeoBuffer;
/** The roof sections in this part (sections roofs only). */
sections?: string[];
/** False for canopies: they stand on posts on their floor and do not lift off with the roof when the floors are pulled apart. */
lift?: boolean;
}
@@ -0,0 +1,43 @@
import assert from "node:assert/strict";
import { test } from "node:test";
import { MeshBasicMaterial, LineBasicMaterial, PointsMaterial } from "three";
import { BELOW_OPACITY, EXPLODE_GAP, easeFloor, fadeMaterials, floorTarget } from "./floor-motion.ts";
import type { FloorMaterials } from "./materials.ts";
test("in the house view floors are pulled apart or stacked", () => {
assert.deepEqual(floorTarget(2, undefined, true, "dim"), { y: 2 * EXPLODE_GAP, opacity: 1 });
assert.deepEqual(floorTarget(2, undefined, false, "dim"), { y: 0, opacity: 1 });
});
test("a chosen floor stays, the floors above fly away, those below depend on the stack mode", () => {
assert.deepEqual(floorTarget(1, 1, true, "dim"), { y: 0, opacity: 1 });
assert.deepEqual(floorTarget(2, 1, true, "dim"), { y: 7, opacity: 0 });
assert.deepEqual(floorTarget(0, 1, true, "dim"), { y: -0.4, opacity: BELOW_OPACITY });
assert.deepEqual(floorTarget(0, 1, true, "single"), { y: -0.4, opacity: 0 });
assert.deepEqual(floorTarget(0, 1, true, "stacked"), { y: 0, opacity: 1 });
});
test("a floor eases towards its target and settles exactly", () => {
const pose = { y: 0, o: 1, ty: 2, to: 0 };
const first = easeFloor(pose, 0.5);
assert.deepEqual(first, { moving: true, settled: false });
assert.deepEqual([pose.y, pose.o], [1, 0.5]);
let last = first;
for (let i = 0; i < 30 && last.moving; i++) last = easeFloor(pose, 0.5);
assert.deepEqual(last, { moving: false, settled: true });
assert.deepEqual([pose.y, pose.o], [2, 0]);
assert.deepEqual(easeFloor(pose, 0.5), { moving: false, settled: false }, "nothing more to do");
});
test("fading switches see-through materials off again at full opacity", () => {
const mesh = () => new MeshBasicMaterial();
const m = { floor: mesh(), wall: mesh(), frames: mesh(), blinds: mesh(), lamps: mesh(), pattern: mesh(), glow: mesh(), glass: mesh(), glassWall: mesh(), cones: mesh(), screens: mesh(), lines: new LineBasicMaterial(), halos: new PointsMaterial(), shadow: mesh(), ghosts: [] } as unknown as FloorMaterials;
fadeMaterials(m, 0.5);
assert.equal(m.floor.transparent, true);
assert.equal(m.floor.depthWrite, false);
assert.equal(m.halos.opacity, 0.5);
fadeMaterials(m, 1);
assert.equal(m.floor.transparent, false);
assert.equal(m.floor.depthWrite, true);
assert.equal(m.lines.opacity, 1);
});
Loaded 100 of 845 files, more files were not shown because too many files have changed in this diff. Show more