feat: add outdoor snapping, terrain types and procedural textures

This commit is contained in:
jhartworks committed 2026-11-16 13:02:18 +01:00
1 parent 992c3e18f2
commit d8cf076019
30 files changed
+2251 -1549

No files matched your search

+11 -8
View File
@@ -77,7 +77,7 @@ import { LibraryState, renderLibrary, renderPreview, type LibraryActions } from
import { arcFreeWall, arcRoomEdge, insertCorner } from "./editor/ops/rooms.ts";
import type { ArcActions, ArcEdit } from "./editor/forms/arc.ts";
import { dragStep, facingAngle, gridPositionAfter, hasLeftStart, headingAngle, outlineWithCornerAt, shifted, steppedDelta, straightEnd } from "./editor/ops/drags.ts";
import { snapToPlan } from "./editor/ops/snapping.ts";
import { snapOutdoorMove, snapToPlan, type SnapOptions } from "./editor/ops/snapping.ts";
import { draftLayer, guidesLayer } from "./editor/canvas/draft.ts";
import { devicesLayer, furnitureLayer, notesLayer } from "./editor/canvas/items.ts";
import { dimensionsLayer } from "./editor/canvas/plan.ts";
@@ -1239,10 +1239,10 @@ export class NfEditor extends LitElement {
// ------------------------------------------------------------------ snapping
/** The place in the plan a point lands on: corners and walls of other rooms, then the grid. `free` skips all of that. */
private snap(p: Vec2, skip?: { roomId: string; index?: number }, free = false): Vec2 {
private snap(p: Vec2, skip?: SnapOptions["skip"], free = false, outdoor = false): Vec2 {
this._guides = {};
if (free) return p;
const snapped = snapToPlan(p, { rooms: this.floor?.rooms ?? [], grid: this._doc.settings.grid, reach: SNAP_PX / this._view.scale, skip });
const snapped = snapToPlan(p, { rooms: this.floor?.rooms ?? [], outdoor: outdoor ? this.floor?.outdoor : undefined, grid: this._doc.settings.grid, reach: SNAP_PX / this._view.scale, skip });
this._guides = snapped.guides;
return snapped.point;
}
@@ -1481,7 +1481,7 @@ export class NfEditor extends LitElement {
private pressDrawingTool(press: Press): Gesture | undefined {
const tool = this._tool;
if (tool === "rect" || tool === "outdoor" || tool === "hole" || tool === "stairs") {
const start = this.snap(press.world, undefined, press.fine);
const start = this.snap(press.world, undefined, press.fine, tool === "outdoor");
return { kind: "rect", start, end: start, outdoor: tool === "outdoor", hole: tool === "hole", stairs: tool === "stairs" };
}
if (tool === "polygon" || tool === "measure") return { kind: "tap", startScreen: press.local, last: press.local, panning: false };
@@ -1613,7 +1613,7 @@ export class NfEditor extends LitElement {
const world = this.toWorld(...local);
const drag = this.drag;
if (!drag) {
if (this._tool !== "select" && this._tool !== "furniture" && this.floor) this._cursor = this.snap(world, undefined, e.altKey);
if (this._tool !== "select" && this._tool !== "furniture" && this.floor) this._cursor = this.snap(world, undefined, e.altKey, this._tool === "outdoor");
return;
}
this.moveDrag(drag, { local, world, fine: e.altKey, straight: e.shiftKey });
@@ -1661,7 +1661,7 @@ export class NfEditor extends LitElement {
drag.last = local;
return;
case "rect":
drag.end = this.snap(world, undefined, fine);
drag.end = this.snap(world, undefined, fine, !!drag.outdoor);
this.requestUpdate();
return;
case "freewall":
@@ -1786,13 +1786,16 @@ export class NfEditor extends LitElement {
drag.moved = true;
const area = this.floorOf(drag)?.outdoor.find((o) => o.id === drag.id);
if (!area) return;
const by = steppedDelta(drag.start, world, dragStep(grid, fine));
const initial = this.floorOf(drag)!;
const snapped = fine ? { by: steppedDelta(drag.start, world, dragStep(grid, true)), guides: {} } : snapOutdoorMove(area.points, [world[0] - drag.start[0], world[1] - drag.start[1]], { rooms: initial.rooms, outdoor: initial.outdoor, grid, reach: SNAP_PX / this._view.scale, skip: { outdoorId: drag.id } });
const { by } = snapped;
this._guides = snapped.guides;
this.live(drag, (_, floor) => void (floor.outdoor.find((o) => o.id === drag.id)!.points = area.points.map((p) => shifted(p, by))));
return;
}
case "outvertex": {
drag.moved = true;
const to = this.snap(world, undefined, fine);
const to = this.snap(world, { outdoorId: drag.id }, fine, true);
const area = this.floorOf(drag)?.outdoor.find((o) => o.id === drag.id);
if (!area) return;
this.live(drag, (_, floor) => {
@@ -49,7 +49,7 @@ export function renderOutdoorForm(host: EditorHost, area: OutdoorArea, actions:
${checkField(host, t("outdoor_outline"), area.outline !== false, (on) => set({ outline: on ? undefined : false }), { title: t("outdoor_outline_hint") })}
${area.type === "fence" || area.type === "pergola" ? checkField(host, t("outdoor_open"), !!area.open, (on) => set({ open: on || undefined }), { title: t("outdoor_open_hint") }) : nothing}
${area.type === "pergola" ? checkField(host, t("outdoor_bracing"), !!area.bracing, (on) => set({ bracing: on || undefined })) : nothing}
${checkField(host, t("outdoor_cut"), cutsOut(area), (on) => set({ cut: on === (area.type === "pool") ? undefined : on }), { title: t("outdoor_cut_hint") })}
${checkField(host, t("outdoor_cut"), cutsOut(area), (on) => set({ cut: on === cutsOut({ ...area, cut: undefined }) ? undefined : on }), { title: t("outdoor_cut_hint") })}
</div>
${area.type === "fence" ? fenceGates(host, area, set) : nothing}
${host.admin
@@ -1,7 +1,8 @@
import assert from "node:assert/strict";
import { test } from "node:test";
import { box } from "../../../entities/fixtures.ts";
import { snapToPlan } from "./snapping.ts";
import type { Vec2 } from "../../../model.ts";
import { snapOutdoorMove, snapToPlan } from "./snapping.ts";
const options = (extra = {}) => ({ rooms: [box("a", 0, 0, 4, 3)], grid: 0.1, reach: 0.2, ...extra });
@@ -41,3 +42,47 @@ test("walls along an axis are held to the grid when snapped to", () => {
const snapped = snapToPlan([2.37, 3.12], options({ grid: 0.5, reach: 0.3 }));
assert.deepEqual(snapped.point, [2.5, 3]);
});
const rect = (id: string, x: number, z: number, w: number, d: number) => ({ id, points: [[x, z], [x + w, z], [x + w, z + d], [x, z + d]] as Vec2[] });
const neighbor = rect("neighbor", 4.03, 0.07, 3, 3);
const outside = { rooms: [], outdoor: [neighbor], grid: 0.5, reach: 0.2 };
test("outdoor drawing and corner resizing snap to off-grid corners and edges", () => {
assert.deepEqual(snapToPlan([4.12, 0.14], outside).point, [4.03, 0.07]);
assert.deepEqual(snapToPlan([4.12, 1.2], outside).point, [4.03, 1]);
const self = rect("self", 0, 0, 4, 3);
const o = { ...outside, outdoor: [self, neighbor], skip: { outdoorId: "self" } };
assert.deepEqual(snapToPlan([4.06, 0.08], o).point, [4.03, 0.07]);
assert.deepEqual(snapToPlan([0.04, 0.06], { ...o, outdoor: [self] }).guides, {});
});
test("whole outdoor areas snap corners before rounding the pointer delta to a coarse grid", () => {
const moving = rect("moving", 0, 0, 2, 2);
const result = snapOutdoorMove(moving.points, [2.12, 0.14], { ...outside, outdoor: [moving, neighbor], skip: { outdoorId: "moving" } });
assert.deepEqual(result.by, [2.03, 0.07]);
assert.deepEqual(result.guides, { point: [4.03, 0.07] });
assert.deepEqual(moving.points, rect("moving", 0, 0, 2, 2).points, "never mutate the drag snapshot");
});
test("whole-area edges snap without changing shape, including a long edge covering a shorter target", () => {
const moving = rect("m", 0, -4, 2, 10);
const result = snapOutdoorMove(moving.points, [2.12, 0.32], outside);
assert.deepEqual(result.by, [2.03, 0.5]);
assert.deepEqual(result.guides, { x: 4.03 });
const diagonal = { id: "d", points: [[5, -2], [11, 4], [11, -2]] as Vec2[] };
const atEdge = snapOutdoorMove(rect("m", 0, 0, 1, 1).points, [7.1, 0], { ...outside, outdoor: [diagonal] });
assert.deepEqual(atEdge.by, [7.05, 0.05]);
});
test("distant areas keep grid translation and IDs never collide across rooms and outdoor areas", () => {
assert.deepEqual(snapOutdoorMove(rect("m", 0, 0, 1, 1).points, [10.12, 12.3], outside), { by: [10, 12.5], guides: {} });
const r = rect("same", 4.03, 0.07, 3, 3);
assert.deepEqual(snapToPlan([4.1, 0.1], { ...outside, rooms: [r], outdoor: [r], skip: { outdoorId: "same" } }).point, [4.03, 0.07]);
});
test("an open outdoor outline has no phantom closing edge to snap to", () => {
const o = { ...outside, outdoor: [{ id: "fence", open: true, points: [[0, 0], [4, 0], [4, 4]] as Vec2[] }] };
assert.equal(snapToPlan([2.1, 2.14], o).guides.point, undefined);
const moving = o.outdoor[0];
assert.deepEqual(snapOutdoorMove(moving.points, [0, 0], { ...outside, outdoor: [moving, rect("target", 1.9, 2, 0.2, 0.2)], skip: { outdoorId: moving.id } }).guides, {});
});
+61 -11
View File
@@ -1,19 +1,19 @@
// Where a point drawn in the plan lands: on a corner of another room, on another room's wall (so walls can meet in a T), or on the
// grid, lined up with other corners along each axis.
// Plan snapping: room corners/walls, optional outdoor corners/edges, then the grid and axis guides.
import type { Room, Vec2 } from "../../../model.ts";
import type { OutdoorArea, Room, Vec2 } from "../../../model.ts";
import type { Guides } from "../canvas/draft.ts";
const thousandths = (v: number) => Math.round(v * 1000) / 1000;
export interface SnapOptions {
rooms: readonly Room[];
rooms: readonly Pick<Room, "id" | "points">[];
outdoor?: readonly Pick<OutdoorArea, "id" | "points" | "open">[];
/** The grid step in metres. */
grid: number;
/** How close a point must be to something to snap to it, in metres. */
reach: number;
/** A room (or one corner of it) that is being moved and so is not something to snap to. */
skip?: { roomId: string; index?: number };
/** Exclude the moving outline; rooms can also exclude just one corner. */
skip?: { roomId?: string; outdoorId?: string; index?: number };
}
export interface Snapped {
@@ -23,7 +23,7 @@ export interface Snapped {
const distance = (a: Vec2, b: Vec2) => Math.hypot(a[0] - b[0], a[1] - b[1]);
/** The nearest corner of the other rooms within reach, if any. */
/** The nearest corner within reach, if any. */
function nearestCorner(corners: readonly Vec2[], p: Vec2, reach: number): Vec2 | null {
let best: Vec2 | null = null;
let bestDistance = reach;
@@ -35,12 +35,12 @@ function nearestCorner(corners: readonly Vec2[], p: Vec2, reach: number): Vec2 |
}
/** The point on a wall of another room that is nearest to p, within reach. Walls along an axis are held to the grid. */
function nearestOnWall(rooms: readonly Room[], p: Vec2, o: SnapOptions): Vec2 | null {
function nearestOnWall(rooms: readonly { id: string; points: Vec2[]; open?: boolean }[], p: Vec2, o: SnapOptions): Vec2 | null {
let best: Vec2 | null = null;
let bestDistance = o.reach;
for (const room of rooms) {
if (o.skip && room.id === o.skip.roomId) continue;
room.points.forEach((a, i) => {
if (room.open && i === room.points.length - 1) return;
const b = room.points[(i + 1) % room.points.length];
const [dx, dz] = [b[0] - a[0], b[1] - a[1]];
const squared = dx * dx + dz * dz;
@@ -79,10 +79,60 @@ function gridOrAligned(corners: readonly Vec2[], p: Vec2, o: SnapOptions): Snapp
}
export function snapToPlan(p: Vec2, o: SnapOptions): Snapped {
const corners = o.rooms.flatMap((room) => room.points.filter((_, i) => !(o.skip && room.id === o.skip.roomId && (o.skip.index === undefined || o.skip.index === i))));
// Separate namespaces: imported room and outdoor IDs need not be unique across both collections.
const areas = (o.outdoor ?? []).filter((a) => a.id !== o.skip?.outdoorId);
const corners = [...o.rooms.flatMap((room) => room.points.filter((_, i) => !(o.skip && room.id === o.skip.roomId && (o.skip.index === undefined || o.skip.index === i)))), ...areas.flatMap((a) => a.points)];
const corner = nearestCorner(corners, p, o.reach);
if (corner) return { point: [corner[0], corner[1]], guides: { point: corner } };
const wall = nearestOnWall(o.rooms, p, o);
const wall = nearestOnWall([...o.rooms.filter((r) => r.id !== o.skip?.roomId), ...areas], p, { ...o, skip: undefined });
if (wall) return { point: [thousandths(wall[0]), thousandths(wall[1])], guides: { point: wall } };
return gridOrAligned(corners, p, o);
}
/** Translate an entire outline onto nearby corners/edges, preserving every length and angle. */
export function snapOutdoorMove(points: readonly Vec2[], delta: Vec2, o: SnapOptions): { by: Vec2; guides: Guides } {
const targets = [...o.rooms.filter((r) => r.id !== o.skip?.roomId), ...(o.outdoor ?? []).filter((a) => a.id !== o.skip?.outdoorId)];
const moved = points.map((p): Vec2 => [p[0] + delta[0], p[1] + delta[1]]);
const movingOpen = o.outdoor?.find((a) => a.id === o.skip?.outdoorId)?.open;
const grid: Vec2 = delta.map((v) => thousandths(Math.round(v / o.grid) * o.grid)) as Vec2;
let corner: { by: Vec2; point: Vec2 } | undefined;
let best = o.reach;
for (const p of moved) for (const area of targets) for (const q of area.points) {
const d = distance(p, q);
if (d < best) {
best = d;
corner = { by: [delta[0] + q[0] - p[0], delta[1] + q[1] - p[1]], point: q };
}
}
if (corner) return { by: corner.by.map(thousandths) as Vec2, guides: { point: corner.point } };
let x: { offset: number; at: number } | undefined;
let z: { offset: number; at: number } | undefined;
let diagonal: { correction: Vec2; point: Vec2; d: number } | undefined;
const inspect = (p: Vec2, a: Vec2, b: Vec2, reverse = false) => {
const dx = b[0] - a[0], dz = b[1] - a[1], squared = dx * dx + dz * dz;
if (squared < 1e-9) return;
const t = ((p[0] - a[0]) * dx + (p[1] - a[1]) * dz) / squared;
if (t < 0 || t > 1) return;
const foot: Vec2 = [a[0] + t * dx, a[1] + t * dz];
const d = distance(p, foot);
if (d >= o.reach) return;
const sign = reverse ? -1 : 1;
const correction: Vec2 = [sign * (foot[0] - p[0]), sign * (foot[1] - p[1])];
if (Math.abs(dx) < 1e-9) {
if (!x || d < Math.abs(x.offset)) x = { offset: correction[0], at: reverse ? p[0] : a[0] };
} else if (Math.abs(dz) < 1e-9) {
if (!z || d < Math.abs(z.offset)) z = { offset: correction[1], at: reverse ? p[1] : a[1] };
} else if (!diagonal || d < diagonal.d) diagonal = { correction, point: reverse ? p : foot, d };
};
for (const area of targets) {
const open = "open" in area && area.open;
for (let i = 0; i < area.points.length - (open ? 1 : 0); i++) {
const a = area.points[i], b = area.points[(i + 1) % area.points.length];
for (const p of moved) inspect(p, a, b);
}
// A longer moving edge can cover a shorter stationary edge without either moving corner projecting onto it.
for (const p of area.points) for (let i = 0; i < moved.length - (movingOpen ? 1 : 0); i++) inspect(p, moved[i], moved[(i + 1) % moved.length], true);
}
if (!x && !z && diagonal) return { by: [thousandths(delta[0] + diagonal.correction[0]), thousandths(delta[1] + diagonal.correction[1])], guides: { point: diagonal.point } };
return { by: [x ? thousandths(delta[0] + x.offset) : grid[0], z ? thousandths(delta[1] + z.offset) : grid[1]], guides: { ...(x ? { x: x.at } : {}), ...(z ? { z: z.at } : {}) } };
}
+13 -1
View File
@@ -962,13 +962,25 @@ export const editorStyles = css`
fill: rgba(61, 224, 160, 0.1);
stroke: rgba(61, 224, 160, 0.5);
}
.nf-out-pool polygon {
.nf-out-pool polygon,
.nf-out-river polygon,
.nf-out-stream polygon {
fill: color-mix(in srgb, var(--nf-accent) 18%, transparent);
stroke: var(--nf-accent);
}
.nf-out-terrace polygon {
fill: rgba(150, 130, 255, 0.12);
}
.nf-out-street polygon {
fill: rgba(100, 110, 125, 0.28);
}
.nf-out-sidewalk polygon {
fill: rgba(175, 185, 200, 0.24);
}
.nf-out-gravel polygon {
fill: rgba(184, 163, 130, 0.24);
stroke: rgba(184, 163, 130, 0.65);
}
.nf-free-wall {
cursor: grab;
}
+14 -4
View File
@@ -1127,12 +1127,17 @@ const DE = {
outdoor_opacity_hint: "100 = undurchsichtig. Weniger macht die Fläche durchsichtig, etwa eine Einfahrt über dem Keller; der Umriss bleibt.",
outdoor_outline: "Umrisslinie zeigen",
outdoor_outline_hint: "Ohne Haken zeichnet die Fläche keine Leuchtlinie an ihrem Rand – für große Grundstücke aus mehreren Rasenflächen.",
outdoor_corners_hint: "Ecken: ein + auf einer Kante fügt eine Ecke hinzu, Ziehen formt die Fläche, × entfernt eine Ecke.",
outdoor_corners_hint: "Ecken: ein + auf einer Kante fügt eine Ecke hinzu, Ziehen formt die Fläche, × entfernt eine Ecke. Beim Zeichnen und Verschieben rasten Flächen an benachbarten Ecken und Kanten ein. Alt unterdrückt das Einrasten.",
outdoor_hint: "Außenleuchten (Wegleuchte, Garten-Spot, Wandleuchte außen) beleuchten alle Außenflächen und die Fassade.",
out_lawn: "Rasen",
out_terrace: "Terrasse",
out_path: "Weg",
out_driveway: "Einfahrt",
out_street: "Straße",
out_sidewalk: "Gehweg",
out_gravel: "Schotterfläche",
out_river: "Fluss",
out_stream: "Bach",
out_pool: "Pool",
out_bed: "Beet",
out_hedge: "Hecke",
@@ -1155,7 +1160,7 @@ const DE = {
fence_gates_hint: "Ein Tor ist eine Lücke im Zaun mit Torpfosten und Flügel. Mit einem Antrieb (Cover, Schalter, Hilfsschalter, Schloss) und/oder Kontakt geht es in 3D auf: Garten- und Doppeltor schwingen nach innen, ein Schiebetor fährt hinter den Zaun.",
outdoor_bracing: "X-Verstrebung",
outdoor_cut: "Aus Flächen ausschneiden",
outdoor_cut_hint: "Jede Fläche, in der diese ganz liegt, bekommt hier ein Loch – ein Pool in der Terrasse, ein Teich oder eine Wildfläche im Rasen. Die Reihenfolge beim Zeichnen spielt keine Rolle. Ein Pool schneidet sich von selbst aus.",
outdoor_cut_hint: "Jede Fläche, in der diese ganz liegt, bekommt hier ein Loch – ein Pool in der Terrasse, ein Bach oder eine Wildfläche im Rasen. Die Reihenfolge beim Zeichnen spielt keine Rolle. Pool, Fluss und Bach schneiden sich von selbst aus.",
outdoor_area_hint: "Der Home-Assistant-Bereich dieser Fläche (Garten, Terrasse, Pool): seine Geräte und Sensoren stehen unter Draußen, und ein Pin auf der Fläche öffnet es.",
pool_temp: "Wassertemperatur (optional)",
pool_pump: "Pumpe / Filter (optional)",
@@ -3192,12 +3197,17 @@ const EN: Record<Key, string> = {
outdoor_opacity_hint: "100 = solid. Less makes the area see-through, such as a driveway above a cellar; the outline stays.",
outdoor_outline: "Show the outline",
outdoor_outline_hint: "Unticked, the area draws no glowing line along its edge – for large plots made of several lawns.",
outdoor_corners_hint: "Corners: a + on an edge adds a corner, dragging shapes the area, × removes a corner.",
outdoor_corners_hint: "Corners: a + on an edge adds a corner, dragging shapes the area, × removes a corner. Drawing and moving snap to nearby corners and edges. Hold Alt to bypass snapping.",
outdoor_hint: "Outdoor lights (path light, garden spot, outdoor wall light) light all outdoor areas and the facade.",
out_lawn: "Lawn",
out_terrace: "Terrace",
out_path: "Path",
out_driveway: "Driveway",
out_street: "Street",
out_sidewalk: "Sidewalk",
out_gravel: "Gravel",
out_river: "River",
out_stream: "Stream",
out_pool: "Pool",
out_bed: "Flower bed",
out_hedge: "Hedge",
@@ -3220,7 +3230,7 @@ const EN: Record<Key, string> = {
fence_gates_hint: "A gate is a gap in the fence with gate posts and a leaf. With a motor (cover, switch, input_boolean, lock) and/or a contact it opens in 3D: garden and double gates swing inwards, a sliding gate runs along the fence.",
outdoor_bracing: "X-bracing",
outdoor_cut: "Cut out of surrounding areas",
outdoor_cut_hint: "Every area that contains this one whole gets a hole here – a pool in the terrace, a pond or a wild patch in the lawn. The drawing order does not matter. A pool cuts itself out on its own.",
outdoor_cut_hint: "Every area that contains this one whole gets a hole here – a pool in the terrace, a stream or a wild patch in the lawn. The drawing order does not matter. Pools, rivers and streams cut themselves out by default.",
outdoor_area_hint: "The Home Assistant area of this surface (garden, terrace, pool): its devices and sensors are listed under Outside, and a pin on the surface opens it.",
pool_temp: "Water temperature (optional)",
pool_pump: "Pump / filter (optional)",
+9 -4
View File
@@ -909,7 +909,7 @@ export type WeatherEffect = (typeof WEATHER_EFFECTS)[number];
/** The effects shown when the plan does not say: everything but fog (fog greys the whole scene). */
export const DEFAULT_WEATHER_EFFECTS: WeatherEffect[] = ["rain", "snow", "clouds", "lightning", "sky"];
export const OUTDOOR_TYPES = ["lawn", "terrace", "path", "driveway", "pool", "bed", "wild", "hedge", "fence", "pergola"] as const;
export const OUTDOOR_TYPES = ["lawn", "terrace", "path", "driveway", "street", "sidewalk", "gravel", "river", "stream", "pool", "bed", "wild", "hedge", "fence", "pergola"] as const;
export type OutdoorType = (typeof OUTDOOR_TYPES)[number];
/** Top of each kind of outdoor area above ground level (pool: its water, below). */
@@ -918,6 +918,11 @@ export const OUTDOOR_TOP: Record<OutdoorType, number> = {
terrace: 0.12,
path: 0.02,
driveway: 0.02,
street: 0.02,
sidewalk: 0.12,
gravel: 0.018,
river: 0.008,
stream: 0.006,
pool: -0.25,
bed: 0.15,
wild: 0.03,
@@ -1013,7 +1018,7 @@ export interface OutdoorArea {
open?: boolean;
/** Pergola: diagonal X-bracing on every side. */
bracing?: boolean;
/** This area is cut out of every other area that contains it whole (a wild patch or pond inside a lawn). A pool does this by itself unless this is false. */
/** This area is cut out of every other area that contains it whole. Pools, rivers and streams do this by default unless this is false. */
cut?: boolean;
/** Fences: gates in the fence (gaps with a leaf that follows an entity). */
gates?: FenceGate[];
@@ -1036,8 +1041,8 @@ export interface FenceGate {
open?: boolean;
}
/** Whether an area leaves a hole in the areas around it: set by hand, and on by default for a pool. */
export const cutsOut = (a: OutdoorArea): boolean => a.cut ?? a.type === "pool";
/** Whether an area leaves a hole in the areas around it: water areas default to on. */
export const cutsOut = (a: OutdoorArea): boolean => a.cut ?? (a.type === "pool" || a.type === "river" || a.type === "stream");
/** Energy flow: meter position and power sensors (W). Grid positive = import, battery positive = discharging. */
export interface EnergySettings {
+1
View File
@@ -41,6 +41,7 @@ export function flipWinding(buf: GeoBuffer, from: number): void {
swapped(buf.f, tri * 3, 1);
swapped(buf.uv, tri * 6, 2);
swapped(buf.tile, tri * 6, 2);
swapped(buf.surface, tri * 3, 1);
}
}
+4
View File
@@ -26,6 +26,8 @@ export class GeoBuffer {
uv: number[] | null;
/** The pattern atlas tile per vertex (floors only). */
tile: number[] | null;
/** Outdoor material IDs, allocated only for buffers that contain outdoor geometry. */
surface: number[] | null = null;
constructor(uvs = false, tiles = false) {
this.uv = uvs ? [] : null;
@@ -39,6 +41,7 @@ export class GeoBuffer {
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);
this.surface?.push(0, 0, 0);
}
/** The number of triangles. */
@@ -53,6 +56,7 @@ export class GeoBuffer {
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));
if (this.surface) geometry.setAttribute("surface", attribute(this.surface, 1));
geometry.computeBoundingSphere();
return geometry;
}
+5 -1
View File
@@ -10,6 +10,7 @@ interface Vertex {
c: number[];
uv: number[] | null;
tile: number[] | null;
surface: number;
}
const blend = (a: number[], b: number[], t: number) => a.map((x, i) => x + (b[i] - x) * t);
@@ -17,7 +18,7 @@ const blend = (a: number[], b: number[], t: number) => a.map((x, i) => x + (b[i]
/** 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 };
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, surface: a.surface };
}
function readVertex(buf: GeoBuffer, v: number): Vertex {
@@ -26,6 +27,7 @@ function readVertex(buf: GeoBuffer, v: number): Vertex {
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,
surface: buf.surface?.[v] ?? 0,
};
}
@@ -37,6 +39,7 @@ function overwriteTriangle(buf: GeoBuffer, tri: number, corners: Vertex[], fold:
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;
if (buf.surface) buf.surface[v] = corner.surface;
});
}
@@ -47,6 +50,7 @@ function appendTriangle(buf: GeoBuffer, corners: Vertex[], fold: number): void {
buf.f.push(fold);
buf.uv?.push(...(corner.uv ?? [0.5, 0.5]));
buf.tile?.push(...(corner.tile ?? [0, 1]));
buf.surface?.push(corner.surface);
}
}
+15
View File
@@ -79,6 +79,21 @@ test("cutAbove keeps colours and uvs along the new edge", () => {
assert.ok(Math.abs(buf.uv![cutVertex * 2 + 1] - 0.5) < 1e-9, "halfway uv");
});
test("cutting geometry retains outdoor surface IDs and appending furniture uses a neutral material", () => {
const buf = new GeoBuffer();
buf.surface = [];
buf.tri([0, 0, 0], [1, 2, 0], [0, 0, 1], grey);
buf.surface.fill(12);
cutAbove(buf, 0, 1, FURN_OFFSET);
assert.equal(buf.surface.length, buf.p.length / 3);
assert.ok(buf.surface.every((id) => id === 12));
buf.tri([4, 0, 0], [5, 2, 0], [4, 0, 1], grey);
assert.deepEqual(buf.surface.slice(-3), [0, 0, 0]);
cutAbove(buf, buf.count - 1, 1, FURN_OFFSET);
assert.equal(buf.surface.length, buf.p.length / 3);
assert.deepEqual(buf.surface.slice(-6), [0, 0, 0, 0, 0, 0]);
});
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);
+5
View File
@@ -15,6 +15,11 @@ export const LOOKS: Record<OutdoorType, Look> = {
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 },
street: { color: 0x24272d, side: 0x15181e, edge: 0x9aa4b2, edgeAlpha: 0.25 },
sidewalk: { color: 0x48505b, side: 0x29313b, edge: 0xaebbc9, edgeAlpha: 0.28 },
gravel: { color: 0x514b3e, side: 0x2a2822, edge: 0xb8a882, edgeAlpha: 0.26 },
river: { color: 0x154350, side: 0x102d36, edge: 0x49afbb, edgeAlpha: 0.3 },
stream: { color: 0x205354, side: 0x173c3e, edge: 0x65c4c4, edgeAlpha: 0.3 },
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 },
+30 -1
View File
@@ -1,9 +1,10 @@
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 { newFloor, OUTDOOR_TOP, OUTDOOR_TYPES, 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";
import { OUTDOOR_MATERIAL } from "./textures.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;
@@ -43,6 +44,34 @@ test("a lawn is a flat block at ground level with an outline", () => {
assert.ok(Math.abs(top - ground - OUTDOOR_TOP.lawn) < 0.3, "a thin layer on the ground");
});
test("every outdoor type has a texture ID; later furniture stays untextured and buffer lengths agree", () => {
for (const type of OUTDOOR_TYPES) {
const { buf } = build(area(type, square(0, 0, 4, 3)));
assert.ok(buf.p.every(Number.isFinite), type);
assert.equal(buf.surface!.length, buf.p.length / 3, type);
assert.ok(buf.surface!.every((id) => id === OUTDOOR_MATERIAL[type] && id > 0), type);
pushPost(buf, [8, 8], 0.1, 0, 1, 0x555555, 0x777777);
assert.ok(buf.surface!.slice(-30).every((id) => id === 0), "later geometry never inherits the outdoor texture");
const g = buf.geometry();
assert.equal(g.getAttribute("surface").count, g.getAttribute("position").count);
g.dispose();
}
});
test("river and stream cut through a surrounding lawn, can be sloped, and preserve transparency", () => {
for (const type of ["river", "stream"] as const) {
const water = area(type, square(1, 1, 3, 2), { slope: 0.3, offset: 0.2, opacity: 0.4 });
const lawn = area("lawn", square(0, 0, 4, 4));
assert.equal(outdoorHoles([lawn, water], 0).length, 1);
assert.equal(outdoorHoles([lawn, { ...water, cut: false }], 0).length, 0);
const solid = new GeoBuffer(), lines = new LineBuffer(), ghosts = new Map<number, GeoBuffer>();
pushOutdoor(solid, lines, floorWith(lawn, water), ghosts, () => new GeoBuffer());
const ghost = ghosts.get(0.4)!;
assert.ok(ghost.surface!.every((id) => id === OUTDOOR_MATERIAL[type]));
assert.ok(Math.max(...ghost.p.filter((_, i) => i % 3 === 1)) - Math.min(...ghost.p.filter((_, i) => i % 3 === 1)) >= 0.3);
}
});
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);
+6
View File
@@ -10,6 +10,7 @@ import { ALWAYS, pushPrism, shade, triangulate, type GeoBuffer, type LineBuffer
import { counterClockwise, pushBeam, pushPost } from "./beams.ts";
import { gateLayout, gatesOnEdge } from "./gates.ts";
import { LOOKS } from "./looks.ts";
import { OUTDOOR_MATERIAL } from "./textures.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 {
@@ -191,6 +192,8 @@ export function outdoorOpacity(area: OutdoorArea): number {
* into `buf`; the outlines always stay solid.
*/
export function pushOutdoor(buf: GeoBuffer, lines: LineBuffer, floor: Floor, ghosts?: Map<number, GeoBuffer>, makeBuffer?: () => GeoBuffer): void {
// The shared wall shader also serves floors without outdoor areas: supply a neutral ID there.
buf.surface ??= Array(buf.p.length / 3).fill(0);
const ground = groundLevel(floor);
const areas = floor.outdoor ?? [];
areas.forEach((area, index) => {
@@ -205,6 +208,8 @@ export function pushOutdoor(buf: GeoBuffer, lines: LineBuffer, floor: Floor, gho
if (!ghosts.has(opacity)) ghosts.set(opacity, makeBuffer());
target = ghosts.get(opacity)!;
}
target.surface ??= Array(target.p.length / 3).fill(0);
const firstVertex = target.p.length / 3;
const context: Context = {
buf: target,
lines,
@@ -223,5 +228,6 @@ export function pushOutdoor(buf: GeoBuffer, lines: LineBuffer, floor: Floor, gho
else if (area.type === "fence") buildFence(context);
else if (area.type === "pergola") buildPergola(context);
else buildBlock(context, areas, index);
target.surface.fill(OUTDOOR_MATERIAL[area.type], firstVertex);
});
}
+121
View File
@@ -0,0 +1,121 @@
// Local, metre-scaled procedural textures: no downloads, image seams or geometry subdivisions.
import type { Material } from "three";
import type { OutdoorType } from "../../model.ts";
export const OUTDOOR_MATERIAL: Record<OutdoorType, number> = {
lawn: 1, terrace: 2, path: 3, driveway: 4, pool: 5, bed: 6, wild: 7,
hedge: 8, fence: 9, pergola: 9, street: 10, sidewalk: 11, gravel: 12, river: 13, stream: 14,
};
const TEXTURE = /* glsl */ `
varying vec3 vNfGround;
varying float vNfSurface;
float nfGrain(vec2 p) {
return fract(sin(dot(p, vec2(127.1, 311.7))) * 43758.5453);
}
float nfNoise(vec2 p) {
vec2 cell = floor(p), f = fract(p);
f = f * f * (3.0 - 2.0 * f);
return mix(mix(nfGrain(cell), nfGrain(cell + vec2(1, 0)), f.x),
mix(nfGrain(cell + vec2(0, 1)), nfGrain(cell + vec2(1, 1)), f.x), f.y);
}
// Suppress detail smaller than a pixel rather than letting it shimmer in the building overview.
float nfDetail(vec2 p) { return 1.0 - smoothstep(0.3, 1.2, max(fwidth(p.x), fwidth(p.y))); }
float nfJoint(float v, float width) {
float d = min(fract(v), 1.0 - fract(v));
float aa = max(fwidth(v), 0.001);
return 1.0 - smoothstep(width, width + aa, d);
}
// Keep the material recognizable in the day look: its general theme otherwise maps dark asphalt to near-white.
vec3 nfOutdoorDay(float kind) {
if (kind < 1.5 || (kind > 6.5 && kind < 8.5)) return kind > 7.5 ? vec3(0.055, 0.17, 0.07) : vec3(0.12, 0.28, 0.08);
if (kind < 2.5) return vec3(0.38, 0.32, 0.25);
if (kind < 4.5) return kind < 3.5 ? vec3(0.36, 0.34, 0.30) : vec3(0.23, 0.25, 0.27);
if ((kind > 4.5 && kind < 5.5) || kind > 12.5) return vec3(0.035, 0.22, 0.28);
if (kind < 6.5) return vec3(0.15, 0.09, 0.045);
if (kind < 9.5) return vec3(0.27, 0.15, 0.065);
if (kind < 10.5) return vec3(0.07, 0.075, 0.085);
if (kind < 11.5) return vec3(0.43, 0.43, 0.4);
return vec3(0.32, 0.30, 0.26);
}
vec3 nfPebbles(vec2 p, bool leaves) {
vec2 cell = floor(p), f = fract(p);
float nearest = 8.0, second = 8.0, tint = 0.0;
for (int y = -1; y <= 1; y++) for (int x = -1; x <= 1; x++) {
vec2 offset = vec2(float(x), float(y));
vec2 seed = cell + offset;
vec2 site = offset + 0.2 + 0.6 * vec2(nfGrain(seed), nfGrain(seed + 19.7));
float d = length(site - f);
if (d < nearest) { second = nearest; nearest = d; tint = nfGrain(seed + 4.3); }
else second = min(second, d);
}
float aa = max(length(fwidth(p)), 0.002);
float rim = smoothstep(0.015, 0.07 + aa, second - nearest);
float relief = (0.65 + tint * 0.9) * mix(0.4, 1.0, rim) * (1.15 - nearest * 0.35);
vec3 pebble = leaves ? vec3(0.88 + tint * 0.2, 1.08, 0.85) : mix(vec3(0.86, 0.88, 0.94), vec3(1.13, 1.06, 0.87), tint);
return mix(vec3(1), pebble * relief, nfDetail(p));
}
vec3 nfOutdoorTexture(vec3 position, float kind) {
// Project onto the dominant face, so raised beds, hedge sides and timber have texture too.
vec3 n = abs(cross(dFdx(position), dFdy(position)));
vec2 p = n.y >= max(n.x, n.z) ? position.xz : (n.x > n.z ? position.zy : position.xy);
float broad = nfNoise(p * 1.7);
if (kind < 1.5 || (kind > 6.5 && kind < 8.5)) {
if (kind > 7.5) return nfPebbles(p * 14.0, true);
float blades = nfNoise(p * vec2(65, 24));
float texture = mix(1.0, 0.6 + blades * 0.9, nfDetail(p * 50.0));
return vec3(0.85 + broad * 0.28, 0.9 + broad * 0.5, 0.78 + broad * 0.25) * texture;
}
if ((kind > 1.5 && kind < 4.5) || (kind > 10.5 && kind < 11.5)) {
// Terrace slabs, staggered path/driveway pavers and larger sidewalk slabs.
vec2 size = kind < 2.5 ? vec2(0.6) : (kind > 10.5 ? vec2(0.5) : vec2(0.24, 0.12));
vec2 tile = p / size;
if (kind > 2.5 && kind < 4.5) tile.x += mod(floor(tile.y), 2.0) * 0.5;
float joint = max(nfJoint(tile.x, 0.015), nfJoint(tile.y, 0.015));
float variation = 0.85 + nfGrain(floor(tile)) * 0.3;
float grain = mix(1.0, 0.88 + nfNoise(p * 80.0) * 0.24, nfDetail(p * 80.0));
return vec3(mix(variation, 0.35, joint * nfDetail(tile)) * grain);
}
if ((kind > 4.5 && kind < 5.5) || kind > 12.5) {
// Water: broad ripples and smaller crossing highlights, with a tighter scale in streams.
vec2 water = p * (kind > 13.5 ? 1.8 : 1.0);
float wave = sin(water.x * 8.0 + sin(water.y * 3.0) + broad * 3.0);
float ripple = pow(max(0.0, sin(water.y * 29.0 + water.x * 4.0 + wave)), 10.0) * nfDetail(water * 25.0);
return vec3(0.68, 1.04, 1.12) * (0.88 + wave * 0.12 + ripple * 0.6);
}
if (kind < 6.5) {
float earth = mix(1.0, 0.65 + nfNoise(p * 42.0) * 0.7, nfDetail(p * 42.0));
return vec3(1.08, 0.93, 0.78) * (0.78 + broad * 0.45) * earth;
}
if (kind < 9.5) {
float grain = sin(p.x * 130.0 + nfNoise(p * vec2(4, 0.8)) * 18.0);
float planks = nfJoint(p.x / 0.14, 0.012) * nfDetail(p / 0.14);
return vec3(1.15, 0.98, 0.76) * (0.95 + grain * 0.16 * nfDetail(p * 100.0)) * (1.0 - planks * 0.55);
}
if (kind < 10.5) {
float grit = mix(1.0, 0.58 + nfNoise(p * 110.0) * 0.85, nfDetail(p * 110.0));
return vec3(grit * (0.88 + broad * 0.22));
}
return nfPebbles(p * 22.0, false);
}
`;
/** Compose after the theme/fold patches so textures stay visible in neon, day and blueprint looks. */
export function outdoorTextured<T extends Material>(material: T): T {
const previous = material.onBeforeCompile.bind(material);
const previousKey = material.customProgramCacheKey.bind(material);
material.onBeforeCompile = (shader, renderer) => {
previous(shader, renderer);
shader.vertexShader = shader.vertexShader
.replace("#include <common>", "#include <common>\nattribute float surface;\nvarying vec3 vNfGround;\nvarying float vNfSurface;")
.replace("#include <begin_vertex>", "#include <begin_vertex>\nvNfGround = position;\nvNfSurface = surface;");
shader.fragmentShader = shader.fragmentShader.replace("#include <common>", `#include <common>\n${TEXTURE}`)
.replace("#include <opaque_fragment>", `if (vNfSurface > 0.5) {
if (uTheme == 2) outgoingLight = nfOutdoorDay(vNfSurface) * (0.7 + dot(outgoingLight, vec3(0.299, 0.587, 0.114)) * 0.4);
outgoingLight *= nfOutdoorTexture(vNfGround, vNfSurface);
}
#include <opaque_fragment>`);
};
material.customProgramCacheKey = () => `${previousKey()}-outdoor-textures-1`;
return material;
}
+2 -1
View File
@@ -4,6 +4,7 @@
import { AdditiveBlending, DoubleSide, LineBasicMaterial, MeshBasicMaterial, MultiplyBlending, PointsMaterial, type CanvasTexture, type Material } from "three";
import { makeFoldable, type FoldMasks } from "../fold.ts";
import { lineBlending, themed, type Theme, type ThemeUniform } from "../theme.ts";
import { outdoorTextured } from "../outdoor/textures.ts";
export interface FloorMaterials {
floor: MeshBasicMaterial;
@@ -63,7 +64,7 @@ export function makeFloorMaterials({ mask, look, theme, textures }: MaterialInpu
return {
floor: themed(solid(), look),
pattern: patternMaterial(textures.pattern),
wall: themed(foldable(solid(), "solid"), look),
wall: outdoorTextured(themed(foldable(solid(), "solid"), look)),
glassWall: foldable(solid({ transparent: true, depthWrite: false }), "glass"),
// the result is the floor colour times the vertex colour: white leaves the floor as it is
shadow: solid({ blending: MultiplyBlending, premultipliedAlpha: true, transparent: true, depthWrite: false, side: DoubleSide, polygonOffset: true, polygonOffsetFactor: -1 }),
+2 -1
View File
@@ -74,6 +74,7 @@ import { MapLayer } from "./live-map.ts";
import type { MapSettings } from "../model.ts";
import { applyFurnitureColors, type FurnitureColors } from "./furniture/palette.ts";
import { accentOnUniform, accentUniform, parseAccent, lineBlending, themed, themeIndex, type Theme, type ThemeUniform } from "./theme.ts";
import { outdoorTextured } from "./outdoor/textures.ts";
export type { Theme } from "./theme.ts";
import { ALWAYS, DEG, GeoBuffer, LineBuffer, pushPrism } from "./geo.ts";
@@ -1838,7 +1839,7 @@ export class NextFloorViewer {
);
// outdoor areas drawn see-through (an opacity set on the area), each opacity with a material of its own that fades with the floor
for (const ghost of geo.ghosts) {
const material = themed(new MeshBasicMaterial({ vertexColors: true, transparent: true, opacity: ghost.opacity, depthWrite: false, side: DoubleSide }), this.themeUniform);
const material = outdoorTextured(themed(new MeshBasicMaterial({ vertexColors: true, transparent: true, opacity: ghost.opacity, depthWrite: false, side: DoubleSide }), this.themeUniform));
materials.ghosts.push({ material, base: ghost.opacity });
const mesh = new Mesh(ghost.geometry, material);
mesh.renderOrder = 2;
+124
View File
@@ -0,0 +1,124 @@
// Built UI: actual pointer gestures, native type selection, persisted outlines and GPU texture compilation.
import assert from "node:assert/strict";
import { createServer } from "node:http";
import { existsSync, mkdirSync, readFileSync } from "node:fs";
import { extname, join, relative, resolve } from "node:path";
import puppeteer from "puppeteer-core";
const root = resolve(import.meta.dirname, ".."), out = join(root, "preview/screenshots");
mkdirSync(out, { recursive: true });
const server = createServer((req, res) => {
const file = resolve(root, `.${decodeURIComponent(new URL(req.url, "http://localhost").pathname)}`);
if (relative(root, file).startsWith("..") || !existsSync(file)) return res.writeHead(404).end();
res.writeHead(200, { "content-type": ({ ".html": "text/html", ".js": "text/javascript", ".json": "application/json" })[extname(file)] ?? "application/octet-stream" }).end(readFileSync(file));
});
await new Promise((done) => server.listen(0, "127.0.0.1", done));
let browser;
try {
const executablePath = [process.env.CHROME_PATH, "C:/Program Files/Google/Chrome/Application/chrome.exe", "C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe"].find((p) => p && existsSync(p));
browser = await puppeteer.launch({ executablePath, headless: true, args: ["--use-angle=swiftshader", "--enable-unsafe-swiftshader"] });
const page = await browser.newPage(), errors = [];
page.on("pageerror", (e) => errors.push(String(e)));
page.on("console", (m) => { if (m.type() === "error" && /THREE|WebGL|shader|GL_INVALID/i.test(m.text())) errors.push(m.text()); });
await page.setViewport({ width: 1440, height: 1000 });
await page.goto(`http://127.0.0.1:${server.address().port}/preview/index.html?noshowcase`, { waitUntil: "networkidle0" });
await page.waitForFunction(() => window.nfPanel?.data.building?.floors.length);
await page.evaluate(async () => {
const p = window.nfPanel, b = structuredClone(p.data.building), f = b.floors[0];
window.outdoorFloor = f.id;
b.floors = [f]; b.settings.grid = 0.5; b.settings.lock_plan = false; b.settings.roof.type = "none";
b.settings.start_view = null; f.start_view = null;
const rect = (id, x, z, w, d) => ({ id, type: "lawn", points: [[x, z], [x + w, z], [x + w, z + d], [x, z + d]] });
Object.assign(f, { rooms: [], openings: [], placements: [], furniture: [], outdoor: [rect("neighbor", 4.03, 0.07, 3, 3), rect("moving", 0, 0, 2, 2)], walls: [], background: null });
p.data.edit(b); p.hass = { ...p.hass, language: "de" }; await p.updateComplete;
[...p.shadowRoot.querySelectorAll("[role=tab]")].find((b) => b.textContent.trim() === "Editor").click();
});
await page.waitForFunction(() => window.nfPanel.shadowRoot.querySelector("nf-editor")?._doc?.floors.length);
await page.evaluate(async () => {
const e = window.outdoorEditor = window.nfPanel.shadowRoot.querySelector("nf-editor");
e._floorId = window.outdoorFloor; e._tool = "select"; e._view = { scale: 65, ox: 65, oy: 90 }; await e.updateComplete;
});
const at = (point) => page.evaluate((p) => {
const e = window.outdoorEditor, box = e.shadowRoot.querySelector("svg.nf-plan").getBoundingClientRect(), [x, y] = e.toScreen(p);
return { x: box.left + x, y: box.top + y };
}, point);
const drag = async (from, to, alt = false) => {
const a = await at(from), b = await at(to);
if (alt) await page.keyboard.down("Alt");
await page.mouse.move(a.x, a.y); await page.mouse.down(); await page.mouse.move(b.x, b.y, { steps: 10 }); await page.mouse.up();
if (alt) await page.keyboard.up("Alt");
await page.evaluate(() => window.outdoorEditor.updateComplete);
};
const polygon = (id) => page.evaluate((id) => window.outdoorEditor._doc.floors[0].outdoor.find((a) => a.id === id).points, id);
await drag([1, 1], [3.1, 1.1]);
assert.deepEqual(await polygon("moving"), [[2.03, 0.07], [4.03, 0.07], [4.03, 2.07], [2.03, 2.07]], "body drag joins exact off-grid corner without stretching");
await drag([4.03, 2.07], [7.12, 3.14]);
assert.deepEqual(await polygon("moving"), [[2.03, 0.07], [7.03, 0.07], [7.03, 3.07], [2.03, 3.07]], "corner handles resize the rectangle onto the neighboring corner");
// Reset the moved rectangle through the normal document edit path for an Alt drag and drawing.
await page.evaluate(async () => {
const e = window.outdoorEditor, b = structuredClone(e._doc);
b.floors[0].outdoor.find((a) => a.id === "moving").points = [[0, 0], [2, 0], [2, 2], [0, 2]];
e.setDoc(b); e.selectItem("outdoor", null); await e.updateComplete;
});
await drag([1, 1], [3.1, 1.1], true);
assert.deepEqual((await polygon("moving"))[0], [2.1, 0.1], "Alt bypasses magnets and the coarse grid");
await page.evaluate(async () => { window.outdoorEditor._tool = "outdoor"; await window.outdoorEditor.updateComplete; });
await drag([7.12, 0.14], [9.1, 2.2]);
const drawn = await page.evaluate(() => window.outdoorEditor._doc.floors[0].outdoor.at(-1));
assert.ok(drawn.points.some(([x, z]) => x === 7.03 && z === 0.07), "new rectangle starts at the adjacent exact corner");
for (const [type, label] of [["street", "Straße"], ["sidewalk", "Gehweg"], ["gravel", "Schotterfläche"], ["river", "Fluss"], ["stream", "Bach"]]) {
const stored = await page.evaluate(async ({ type, label, id }) => {
const e = window.outdoorEditor; e._tool = "select"; e.selectItem("outdoor", id); await e.updateComplete;
const input = [...e.shadowRoot.querySelectorAll("select")].find((s) => [...s.options].some((o) => o.value === type && o.textContent === label));
if (!input) throw new Error(`Missing outdoor type ${type}`);
input.value = type; input.dispatchEvent(new Event("change", { bubbles: true })); await e.updateComplete;
return e._doc.floors[0].outdoor.find((a) => a.id === id).type;
}, { type, label, id: drawn.id });
assert.equal(stored, type);
}
await page.screenshot({ path: join(out, "symcon-outdoor-editor.png") });
await page.evaluate(async () => {
const p = window.nfPanel, b = structuredClone(window.outdoorEditor._doc), f = b.floors[0];
const types = ["lawn", "terrace", "path", "driveway", "street", "sidewalk", "gravel", "river", "stream", "pool", "bed", "wild", "hedge", "fence", "pergola"];
f.outdoor = types.map((type, i) => {
const x = (i % 5) * 5, z = Math.floor(i / 5) * 4;
return { id: type, type, points: [[x, z], [x + 4, z], [x + 4, z + 3], [x, z + 3]], ...(type === "sidewalk" ? { slope: 0.25 } : {}), ...(type === "stream" ? { opacity: 0.6 } : {}) };
});
f.rooms = [{ id: "reference", name: "Referenz", points: [[-2, -2], [-1, -2], [-1, -1], [-2, -1]], area_id: null, floor_material: "plain" }];
f.furniture = []; p.data.edit(b); await p.updateComplete;
[...p.shadowRoot.querySelectorAll("[role=tab]")].find((b) => b.textContent.trim() === "3D").click();
});
await page.waitForFunction(() => window.nfPanel.shadowRoot.querySelector("nf-view3d")?.viewer).catch(async (e) => {
console.log("Viewer initialization", errors, await page.evaluate(() => window.nfPanel.shadowRoot.textContent.slice(-1500))); throw e;
});
await page.evaluate(() => {
window.outdoorView = window.nfPanel.shadowRoot.querySelector("nf-view3d");
window.nfPanel.openFloor(window.outdoorFloor);
window.outdoorView.viewer.showView({ target: { x: 12, y: 0, z: 5.5 }, radius: 25, phi: 0.65, theta: 0.1 }, 0);
});
for (const theme of ["neon", "day", "blueprint"]) {
await page.evaluate((theme) => { const v = window.outdoorView.viewer; v.setTheme(theme); v.invalidate(); }, theme);
await page.evaluate(() => new Promise((done) => requestAnimationFrame(() => requestAnimationFrame(done))));
await page.screenshot({ path: join(out, `symcon-outdoor-${theme}.png`) });
}
for (const [name, x, z] of [["street", 22, 1.5], ["gravel", 7, 5.5], ["lawn", 2, 1.5]]) {
await page.evaluate(({ x, z }) => {
const v = window.outdoorView.viewer; v.setTheme("day"); v.showView({ target: { x, y: 0, z }, radius: 5, phi: 0.65, theta: 0.1 }, 0);
}, { x, z });
await page.evaluate(() => new Promise((done) => requestAnimationFrame(() => requestAnimationFrame(done))));
await page.screenshot({ path: join(out, `symcon-outdoor-${name}-detail.png`) });
}
const gpu = await page.evaluate(() => {
const v = window.outdoorView.viewer;
let textured = 0, neutral = 0;
v.scene.traverse((o) => {
const ids = o.geometry?.getAttribute("surface");
if (ids) { for (const kind of ids.array) kind > 0 ? textured++ : neutral++; }
});
return { textured, neutral, programs: v.renderer.info.programs.map((p) => p.diagnostics?.runnable !== false) };
});
assert.ok(gpu.textured > 0); assert.ok(gpu.programs.every(Boolean)); assert.deepEqual(errors, []);
console.log("OK: pointer drawing/moving/corner snapping, Alt bypass, five persisted surface types, metre-scaled textures compiled in all three themes, sloped and transparent surfaces", gpu);
} finally {
await browser?.close(); await new Promise((done) => server.close(done));
}