feat: add location and branch topology with scoped navigation
This commit is contained in:
1 parent
4a8da8ad0c
commit
bffc4d0acc
30 files changed
+3172
-2491
No files matched your search
+25
-4
@@ -21,6 +21,7 @@ import type { HomeAssistant } from "./types.ts";
|
||||
import { withCoverControls } from "./entities/cover-controls.ts";
|
||||
import { withSymconWeather } from "./symcon-weather.ts";
|
||||
import { isSymcon } from "./entities/symcon-values.ts";
|
||||
import { ALL_TOPOLOGY, floorSelection, topologyOutsideFloors, topologyParent, type TopologySelection } from "./topology.ts";
|
||||
import type { WallMode } from "./viewer/viewer3d.ts";
|
||||
import { lookNow } from "./themes.ts";
|
||||
|
||||
@@ -44,6 +45,7 @@ export class NextFloorCard extends LitElement {
|
||||
hass: { attribute: false },
|
||||
_config: { state: true },
|
||||
_roomId: { state: true },
|
||||
_topologyGroup: { state: true },
|
||||
_floorId: { state: true },
|
||||
_walls: { state: true },
|
||||
_heat: { state: true },
|
||||
@@ -64,6 +66,7 @@ export class NextFloorCard extends LitElement {
|
||||
/** The configured start room has been opened once the building arrived. */
|
||||
private roomApplied = false;
|
||||
/** The floor chosen in the card: null is the house, undefined means none was chosen so the configured floor applies. */
|
||||
private declare _topologyGroup: TopologySelection;
|
||||
private declare _floorId: string | null | undefined;
|
||||
/** Choices made with the card's own switches; null means as configured. */
|
||||
private declare _walls: WallMode | null;
|
||||
@@ -93,6 +96,7 @@ export class NextFloorCard extends LitElement {
|
||||
super();
|
||||
this._roomId = null;
|
||||
this._floorId = undefined;
|
||||
this._topologyGroup=ALL_TOPOLOGY;
|
||||
this._walls = null;
|
||||
this._heat = null;
|
||||
this._explode = null;
|
||||
@@ -111,6 +115,7 @@ export class NextFloorCard extends LitElement {
|
||||
private returnHome(): void {
|
||||
this._roomId = this._config?.room ?? null;
|
||||
this._floorId = undefined;
|
||||
this._topologyGroup=ALL_TOPOLOGY;
|
||||
this.view3d()?.resetView();
|
||||
if (this._config?.idle_orbit) this._orbit = true;
|
||||
}
|
||||
@@ -156,6 +161,7 @@ export class NextFloorCard extends LitElement {
|
||||
this._own = config;
|
||||
this._config = withTemplate(config, this.data.building?.settings.card_templates as CardTemplates | undefined);
|
||||
this._floorId = undefined;
|
||||
this._topologyGroup=ALL_TOPOLOGY;
|
||||
this._walls = null;
|
||||
this._heat = null;
|
||||
this._explode = null;
|
||||
@@ -199,8 +205,20 @@ export class NextFloorCard extends LitElement {
|
||||
}
|
||||
|
||||
/** One level up: room, then floor, then the house. */
|
||||
private topologySelection(): TopologySelection {
|
||||
const b=this.plan(),id=this.stage().floorId;
|
||||
return b&&id?floorSelection(b,id,this._roomId===OUTSIDE?null:this._roomId):this._topologyGroup;
|
||||
}
|
||||
|
||||
private openTopology(s:TopologySelection):void {
|
||||
const b=this.plan();if(!b)return;
|
||||
this._floorId=s.kind==="room"?s.floorId??null:s.kind==="floor"?s.id??null:s.kind==="outside"?b.floors.find((f)=>f.outdoor_location_id===s.id)?.id??null:null;
|
||||
this._roomId=s.kind==="room"?s.id??null:null;this._topologyGroup=s;
|
||||
}
|
||||
|
||||
private back(): void {
|
||||
if (this._roomId) this._roomId = null;
|
||||
else if(this.plan()?.topology)this.openTopology(topologyParent(this.plan()!,this.topologySelection()));
|
||||
else if (this.canSwitch) this._floorId = null;
|
||||
}
|
||||
|
||||
@@ -224,7 +242,7 @@ export class NextFloorCard extends LitElement {
|
||||
const c = this._config;
|
||||
// the configured floor is where the card starts; with floor pictures the user can switch
|
||||
const chosen = this._floorId === undefined ? (c?.floor ?? null) : this._floorId;
|
||||
const floorId = b && b.floors.length === 1 ? b.floors[0].id : b?.floors.some((f) => f.id === chosen) ? chosen : null;
|
||||
const floorId = b && !b.topology && b.floors.length === 1 ? b.floors[0].id : b?.floors.some((f) => f.id === chosen) ? chosen : null;
|
||||
// the floor pictures have a house button of their own; a room with its panel has a close button
|
||||
const panelOpen = !!this._roomId && c?.room_panel !== false;
|
||||
const canGoBack = (!!this._roomId && c?.room_panel === false) || (!this.thumbs && this.canSwitch && !this._roomId && !!floorId && (b?.floors.length ?? 0) > 1);
|
||||
@@ -270,6 +288,7 @@ export class NextFloorCard extends LitElement {
|
||||
private renderRoomButtons(s: Stage): TemplateResult | typeof nothing {
|
||||
const b = this.plan();
|
||||
if (!this._config?.room_buttons || !b || this._clean) return nothing;
|
||||
if(b.topology&&(!s.floorId||b.floors.find((f)=>f.id===s.floorId)?.outdoor_location_id))return nothing;
|
||||
const groups = roomButtons(b, s.floorId);
|
||||
if (!groups.length) return nothing;
|
||||
const several = groups.length > 1;
|
||||
@@ -278,7 +297,7 @@ export class NextFloorCard extends LitElement {
|
||||
this._roomId = roomId === this._roomId ? null : roomId;
|
||||
};
|
||||
// Outside: the house view with the garden's and the roof's devices in the panel
|
||||
const outside = outsideEntities(this.hass, b.floors).length > 0;
|
||||
const outside = !b.topology&&outsideEntities(this.hass, b.floors).length > 0;
|
||||
const openOutside = () => {
|
||||
if (this.canSwitch) this._floorId = null;
|
||||
this._roomId = this._roomId === OUTSIDE ? null : OUTSIDE;
|
||||
@@ -322,6 +341,7 @@ export class NextFloorCard extends LitElement {
|
||||
return html`<nf-view3d
|
||||
.hass=${withSymconWeather(withCoverControls(this.hass, b.floors), b.settings)}
|
||||
.building=${b}
|
||||
.topologySelection=${this.topologySelection()}
|
||||
.packs=${this.data.packs}
|
||||
.floorId=${s.floorId}
|
||||
.roomId=${this._roomId === OUTSIDE ? null : this._roomId}
|
||||
@@ -388,9 +408,10 @@ export class NextFloorCard extends LitElement {
|
||||
this._roomId = null;
|
||||
} else if (e.detail.roomId) this._roomId = e.detail.roomId === this._roomId ? null : e.detail.roomId;
|
||||
}}
|
||||
@topology-tap=${(e: CustomEvent<TopologySelection>)=>{if(this.canSwitch)this.openTopology(e.detail);}}
|
||||
@floor-tap=${(e: CustomEvent<{ floorId: string | null }>) => {
|
||||
this._floorId = e.detail.floorId;
|
||||
this._roomId = null;
|
||||
this._roomId = null;this._topologyGroup=ALL_TOPOLOGY;
|
||||
}}
|
||||
@back=${() => this.back()}
|
||||
></nf-view3d>`;
|
||||
@@ -404,7 +425,7 @@ export class NextFloorCard extends LitElement {
|
||||
.hass=${withCoverControls(this.hass, b.floors)}
|
||||
.room=${b.floors.flatMap((f) => f.rooms).find((r) => r.id === this._roomId) ?? null}
|
||||
.floor=${b.floors.find((f) => f.rooms.some((r) => r.id === this._roomId)) ?? null}
|
||||
.outside=${this._roomId === OUTSIDE ? outsideEntities(this.hass, b.floors) : null}
|
||||
.outside=${this._roomId === OUTSIDE ? outsideEntities(this.hass, topologyOutsideFloors(b,this.topologySelection())) : null}
|
||||
.confirmEntities=${confirmEntities(this.hass, b.floors)}
|
||||
.phrases=${b.settings.announce_phrases ?? null}
|
||||
@close=${() => (this._roomId = null)}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { floorSelection, normalizeTopology, topologyFloors } from "../topology.ts";
|
||||
// 2D editor: floors, rooms (rectangles and free shapes), snapping, undo, background template.
|
||||
|
||||
import { html, LitElement, nothing, svg, type PropertyValues, type TemplateResult } from "lit";
|
||||
@@ -1138,6 +1139,7 @@ export class NfEditor extends LitElement {
|
||||
/** Replace the document; `base` (the state before the change) goes into the undo history. */
|
||||
private setDoc(next: Building, base: Building | null = this._doc): void {
|
||||
if (base) this.history.record(base);
|
||||
if(next.topology)normalizeTopology(next);
|
||||
this._doc = next;
|
||||
this.syncHistoryButtons();
|
||||
this.dispatchEvent(new CustomEvent("building-changed", { detail: { building: next }, bubbles: true, composed: true }));
|
||||
@@ -2321,8 +2323,8 @@ export class NfEditor extends LitElement {
|
||||
|
||||
// ------------------------------------------------------------------ floors and rooms
|
||||
|
||||
private addFloor(from: HassFloor | null = null): void {
|
||||
const floor = newFloorFor(this._doc, from, { first: this.t("default_floor"), next: (n) => this.t("new_floor", { n }) });
|
||||
private addFloor(from: HassFloor | null = null, parent?: string): void {
|
||||
const floor = newFloorFor(this._doc, from, { first: this.t("default_floor"), next: (n) => this.t("new_floor", { n }) }, parent ?? this.floor?.building_id);
|
||||
const next = structuredClone(this._doc);
|
||||
next.floors = floorsWith(next.floors, floor);
|
||||
this.setDoc(next);
|
||||
@@ -2376,6 +2378,7 @@ export class NfEditor extends LitElement {
|
||||
},
|
||||
print: () => this.printPlan(),
|
||||
addFloor: (from) => this.addFloor(from),
|
||||
addFloorIn: (id) => this.addFloor(null,id),
|
||||
moveFloor: (direction) => this.moveFloor(direction),
|
||||
deleteFloor: () => this.deleteFloor(),
|
||||
duplicateFloor: (options) => this.duplicateFloor(options),
|
||||
@@ -2621,7 +2624,7 @@ export class NfEditor extends LitElement {
|
||||
}
|
||||
|
||||
private shiftScope(): Scope {
|
||||
return { floorId: this._floorId, allFloors: this.side.shiftAll };
|
||||
return { floorId: this._floorId, allFloors: this.side.shiftAll, ...(this._doc.topology&&this._floorId?{floorIds:topologyFloors(this._doc,floorSelection(this._doc,this._floorId),true).map((f)=>f.id)}:{}) };
|
||||
}
|
||||
|
||||
/** Moves everything on the floor (or on every floor) by the typed distance. */
|
||||
|
||||
@@ -13,11 +13,13 @@ import { formatArea } from "../../../units.ts";
|
||||
import type { EditorHost } from "../host.ts";
|
||||
import { freeHaFloors, linkableHaFloors, unplacedAreas } from "../ops/floors.ts";
|
||||
import type { SideState } from "../side-state.ts";
|
||||
import { renderFloorAssignment, renderTopologyForm } from "./topology.ts";
|
||||
|
||||
/** What the floor form makes the editor do. */
|
||||
export interface FloorActions {
|
||||
openFloor(id: string): void;
|
||||
addFloor(from: HassFloor | null): void;
|
||||
addFloorIn(buildingId: string): void;
|
||||
moveFloor(direction: -1 | 1): void;
|
||||
deleteFloor(): void;
|
||||
/** Copies the open floor on top of the house, with what the choices take along. */
|
||||
@@ -48,9 +50,10 @@ function areaRow(host: EditorHost, floor: Floor, floorActions: FloorActions): Te
|
||||
/** The chips of the floors, top floor first, and the button that adds one: straight away, or after choosing a floor of Home Assistant. */
|
||||
function floorChips(host: EditorHost, state: SideState, floorActions: FloorActions, selected: string | null): TemplateResult {
|
||||
const free = freeHaFloors(host.doc, host.hass?.floors);
|
||||
const shown=host.doc.floors.filter((f)=>!host.doc.topology||!host.floor||(host.floor.outdoor_location_id?f.outdoor_location_id===host.floor.outdoor_location_id:f.building_id===host.floor.building_id&&!f.outdoor_location_id));
|
||||
const addClicked = () => (free.length > 0 ? (state.floorMenu = !state.floorMenu) : floorActions.addFloor(null));
|
||||
return html`<div class="nf-floor-list">
|
||||
${[...host.doc.floors].reverse().map((f) => html`<button class="nf-chip" aria-pressed=${f.id === selected} @click=${() => floorActions.openFloor(f.id)}>${f.name}</button>`)}
|
||||
${[...shown].reverse().map((f) => html`<button class="nf-chip" aria-pressed=${f.id === selected} @click=${() => floorActions.openFloor(f.id)}>${f.name}</button>`)}
|
||||
${host.admin ? html`<button class="nf-btn" aria-expanded=${state.floorMenu} @click=${addClicked}>+ ${host.t("add_floor")}</button>` : nothing}
|
||||
</div>
|
||||
${host.admin && state.floorMenu
|
||||
@@ -75,7 +78,7 @@ function shiftRow(host: EditorHost, state: SideState, floorActions: FloorActions
|
||||
${floor.start_view ? html`<button class="nf-btn" title=${host.t("floor_start_view_reset")} @click=${() => host.change((_, f) => (f.start_view = null))}>↺</button>` : nothing}
|
||||
<label class="nf-check nf-wide" title=${host.t("floor_shift_all_hint")}
|
||||
><input type="checkbox" .checked=${state.shiftAll} @change=${(e: Event) => (state.shiftAll = (e.target as HTMLInputElement).checked)} />
|
||||
${host.t("floor_shift_all")}</label
|
||||
${host.doc.topology ? floor.outdoor_location_id ? "Gesamten Außenplan mitnehmen" : "Alle Stockwerke dieses Gebäudes mitnehmen" : host.t("floor_shift_all")}</label
|
||||
>
|
||||
</div>`;
|
||||
}
|
||||
@@ -120,6 +123,7 @@ function floorForm(host: EditorHost, state: SideState, floorActions: FloorAction
|
||||
const lacking = unplacedAreas(host.doc, floor, host.hass?.areas);
|
||||
const haChoices: [string, string][] = [["", t("no_ha_floor")], ...links.map((f): [string, string] => [f.floor_id, f.name])];
|
||||
return html`<div class="nf-form">
|
||||
${renderFloorAssignment(host)}
|
||||
${textField(host, t("floor_name"), floor.name, (v) => update({ name: v }), { wide: true })}
|
||||
${numberField(host, t("elevation"), floor.elevation, (v) => update({ elevation: v }))}
|
||||
${host.admin ? shiftRow(host, state, floorActions, floor) : nothing}
|
||||
@@ -150,6 +154,7 @@ function floorForm(host: EditorHost, state: SideState, floorActions: FloorAction
|
||||
export function renderFloors(host: EditorHost, state: SideState, floorActions: FloorActions, floor: Floor | undefined, selectedId: string | null): TemplateResult {
|
||||
return html`<section>
|
||||
<h3>${host.t("floors")}</h3>
|
||||
${isSymcon(host.hass)||host.doc.topology?renderTopologyForm(host,floorActions):nothing}
|
||||
${floorChips(host, state, floorActions, selectedId)} ${floor ? floorForm(host, state, floorActions, floor) : nothing}
|
||||
</section>`;
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
import { html, nothing } from "lit";
|
||||
import { uid } from "../../../model.ts";
|
||||
import { addLocationOutside, enableTopology, floorTopologyPath } from "../../../topology.ts";
|
||||
import { hint, selectField, textField } from "../fields.ts";
|
||||
import type { EditorHost } from "../host.ts";
|
||||
import type { FloorActions } from "./floor.ts";
|
||||
|
||||
export function renderTopologyForm(host:EditorHost,actions:FloorActions) {
|
||||
const t=host.doc.topology;
|
||||
const edit=(fn:(next:NonNullable<typeof t>)=>void)=>{
|
||||
const b=structuredClone(host.doc);fn(b.topology!);host.replace(b);
|
||||
};
|
||||
if(!t)return html`<button class="nf-btn nf-topology-enable" ?disabled=${!host.admin} @click=${()=>{const b=structuredClone(host.doc);enableTopology(b,host.hass?.symconTitle?.trim()||"Gebäude 1");host.replace(b);}}>Ort / Niederlassung / Gebäude einrichten</button>`;
|
||||
return html`<details class="nf-topology-form"><summary>Orte, Niederlassungen und Gebäude</summary>
|
||||
${hint("Die Topologie lautet Ort / Niederlassung / Gebäude / Stockwerk / Raum. Bestehende Stockwerke behalten beim Zuordnen ihre Geometrie, Datenpunkte und Freigaben. Unter jedem Ort kann ein eigener Außenplan angelegt werden. Leere Gruppen lassen sich entfernen. Stockwerke ordnest du im Feld Zuordnung zu.")}
|
||||
${t.locations.map((l)=>html`<details class="nf-topology-location" data-location=${l.id}><summary>${l.name}</summary><div class="nf-form">
|
||||
${textField(host,"Ort",l.name,(name)=>edit((n)=>{n.locations.find((s)=>s.id===l.id)!.name=name;}),{wide:true,maxlength:100})}
|
||||
${t.branches.filter((n)=>n.location_id===l.id).map((n)=>html`<details class="nf-wide nf-topology-branch" data-branch=${n.id}><summary>${n.name}</summary><div class="nf-form">
|
||||
${textField(host,"Niederlassung",n.name,(name)=>edit((p)=>{p.branches.find((s)=>s.id===n.id)!.name=name;}),{wide:true,maxlength:100})}
|
||||
${selectField(host,"Ort der Niederlassung",n.location_id,t.locations.map((s)=>[s.id,s.name]),(location_id)=>edit((p)=>{p.branches.find((s)=>s.id===n.id)!.location_id=location_id;}),{wide:true})}
|
||||
${t.buildings.filter((g)=>g.branch_id===n.id).map((g)=>html`<details class="nf-wide nf-topology-building" data-building=${g.id}><summary>${g.name}</summary><div class="nf-form">
|
||||
${textField(host,"Gebäude",g.name,(name)=>edit((p)=>{p.buildings.find((s)=>s.id===g.id)!.name=name;}),{wide:true,maxlength:100})}
|
||||
${selectField(host,"Niederlassung des Gebäudes",g.branch_id,t.branches.map((s)=>[s.id,`${t.locations.find((l)=>l.id===s.location_id)?.name??""} / ${s.name}`]),(branch_id)=>edit((p)=>{p.buildings.find((s)=>s.id===g.id)!.branch_id=branch_id;}),{wide:true})}
|
||||
<button class="nf-btn nf-topology-open-building" @click=${()=>{const f=host.doc.floors.find((f)=>f.building_id===g.id&&!f.outdoor_location_id);if(f)actions.openFloor(f.id);else if(host.admin)actions.addFloorIn(g.id);}}>Stockwerke öffnen</button>
|
||||
<button class="nf-btn nf-topology-add-floor" ?disabled=${!host.admin} @click=${()=>actions.addFloorIn(g.id)}>+ Stockwerk</button>
|
||||
<button class="nf-link nf-wide" ?disabled=${!host.admin||host.doc.floors.some((f)=>f.building_id===g.id)} @click=${()=>edit((p)=>{p.buildings=p.buildings.filter((s)=>s.id!==g.id);})}>Gebäude entfernen</button>
|
||||
</div></details>`)}
|
||||
<button class="nf-btn nf-topology-add-building" ?disabled=${!host.admin} @click=${()=>edit((p)=>{p.buildings.push({id:uid("building"),name:`Gebäude ${p.buildings.length+1}`,branch_id:n.id});})}>+ Gebäude</button>
|
||||
<button class="nf-link" ?disabled=${!host.admin||t.buildings.some((g)=>g.branch_id===n.id)} @click=${()=>edit((p)=>{p.branches=p.branches.filter((s)=>s.id!==n.id);})}>Niederlassung entfernen</button>
|
||||
</div></details>`)}
|
||||
<button class="nf-btn nf-topology-add-branch" ?disabled=${!host.admin} @click=${()=>edit((p)=>{p.branches.push({id:uid("branch"),name:`Niederlassung ${p.branches.length+1}`,location_id:l.id});})}>+ Niederlassung</button>
|
||||
<button class="nf-btn nf-topology-outside" ?disabled=${!host.admin} @click=${()=>{const b=structuredClone(host.doc),f=addLocationOutside(b,l.id);host.replace(b);actions.openFloor(f.id);}}>🌳 ${host.doc.floors.some((f)=>f.outdoor_location_id===l.id)?"Außen bearbeiten":"Außen anlegen"}</button>
|
||||
<button class="nf-link" ?disabled=${!host.admin||t.branches.some((n)=>n.location_id===l.id)||host.doc.floors.some((f)=>f.outdoor_location_id===l.id)} @click=${()=>edit((p)=>{p.locations=p.locations.filter((s)=>s.id!==l.id);})}>Ort entfernen</button>
|
||||
</div></details>`)}
|
||||
<button class="nf-btn nf-topology-add-location" ?disabled=${!host.admin} @click=${()=>edit((p)=>{p.locations.push({id:uid("location"),name:`Ort ${p.locations.length+1}`});})}>+ Ort</button>
|
||||
</details>`;
|
||||
}
|
||||
|
||||
export function renderFloorAssignment(host:EditorHost) {
|
||||
const t=host.doc.topology,f=host.floor;if(!t||!f)return nothing;
|
||||
const options:[string,string][]=[...t.buildings.map((g):[string,string]=>{const n=t.branches.find((n)=>n.id===g.branch_id);return [g.id,`${t.locations.find((l)=>l.id===n?.location_id)?.name??""} / ${n?.name??""} / ${g.name}`];}),...t.locations.map((l):[string,string]=>[`outside:${l.id}`,`${l.name} / Außen`])];
|
||||
return html`${selectField(host,"Zuordnung",f.outdoor_location_id?`outside:${f.outdoor_location_id}`:f.building_id??"",options,(id)=>host.change((_,floor)=>{
|
||||
floor.outdoor_location_id=id.startsWith("outside:")?id.slice(8):null;floor.building_id=floor.outdoor_location_id?null:id;
|
||||
}),{wide:true})}<span class="nf-sub nf-wide nf-topology-path" title=${floorTopologyPath(host.doc,f)}>${floorTopologyPath(host.doc,f)}</span>`;
|
||||
}
|
||||
@@ -5,10 +5,12 @@ import { floorElevation, newFloor, uid, type Building, type Floor, type Furnitur
|
||||
import type { HassArea, HassFloor } from "../../../types.ts";
|
||||
|
||||
/** A new floor, named after a Home Assistant floor when it comes from one, and placed at that floor's level or on top of the house. */
|
||||
export function newFloorFor(doc: Building, from: HassFloor | null, names: { first: string; next(n: number): string }): Floor {
|
||||
const count = doc.floors.length;
|
||||
export function newFloorFor(doc: Building, from: HassFloor | null, names: { first: string; next(n: number): string }, parent?: string | null): Floor {
|
||||
const building_id = doc.topology ? parent || doc.topology.buildings[0]?.id : undefined;
|
||||
const floors = doc.topology ? doc.floors.filter((f)=>!f.outdoor_location_id&&f.building_id===building_id) : doc.floors;
|
||||
const count = floors.length;
|
||||
const name = from?.name ?? (count === 0 ? names.first : names.next(count));
|
||||
return { ...newFloor(uid("floor"), name, floorElevation(doc.floors, from?.level)), ha_floor: from?.floor_id ?? null };
|
||||
return { ...newFloor(uid("floor"), name, floorElevation(floors, from?.level)), ha_floor: from?.floor_id ?? null, ...(building_id?{building_id}:{}) };
|
||||
}
|
||||
|
||||
/** The floors with a new one slotted in below the first floor that lies higher: floors are kept from bottom to top. */
|
||||
@@ -65,7 +67,7 @@ export interface FloorCopyOptions {
|
||||
*/
|
||||
export function copyOfFloor(doc: Building, floor: Floor, name: string, options: FloorCopyOptions, id: (prefix: string) => string = uid): Floor {
|
||||
const copy = structuredClone(floor);
|
||||
const top = doc.floors.reduce((max, f) => Math.max(max, f.elevation + f.height), floor.elevation + floor.height);
|
||||
const top = doc.floors.filter((f)=>!doc.topology||f.building_id===floor.building_id).reduce((max, f) => Math.max(max, f.elevation + f.height), floor.elevation + floor.height);
|
||||
const rooms = new Map<string, string>();
|
||||
const walls = new Map<string, string>();
|
||||
copy.id = id("floor");
|
||||
|
||||
@@ -44,12 +44,14 @@ function mapHouseExtras(doc: Building, at: PointMap): void {
|
||||
export interface Scope {
|
||||
floorId: string | null;
|
||||
allFloors: boolean;
|
||||
/** Optional building/location boundary for a multi-building project. */
|
||||
floorIds?: readonly string[];
|
||||
}
|
||||
|
||||
function apply(doc: Building, scope: Scope, at: PointMap, turns: boolean): void {
|
||||
if (scope.allFloors) {
|
||||
for (const floor of doc.floors) mapFloor(floor, at, turns);
|
||||
mapHouseExtras(doc, at);
|
||||
for (const floor of doc.floors) if (!scope.floorIds || scope.floorIds.includes(floor.id)) mapFloor(floor, at, turns);
|
||||
if (!scope.floorIds || doc.floors.every((f)=>scope.floorIds!.includes(f.id))) mapHouseExtras(doc, at);
|
||||
} else {
|
||||
const floor = doc.floors.find((f) => f.id === scope.floorId);
|
||||
if (floor) mapFloor(floor, at, turns);
|
||||
@@ -63,7 +65,7 @@ export function translate(doc: Building, scope: Scope, dx: number, dz: number):
|
||||
|
||||
/** The middle of the box around the rooms of the scope, or null when there are none. */
|
||||
export function pivotOf(doc: Building, scope: Scope): Vec2 | null {
|
||||
const floors = scope.allFloors ? doc.floors : doc.floors.filter((f) => f.id === scope.floorId);
|
||||
const floors = scope.allFloors ? doc.floors.filter((f)=>!scope.floorIds||scope.floorIds.includes(f.id)) : doc.floors.filter((f) => f.id === scope.floorId);
|
||||
const points = floors.flatMap((f) => f.rooms.flatMap((r) => r.points));
|
||||
if (points.length === 0) return null;
|
||||
const [xs, zs] = [points.map((p) => p[0]), points.map((p) => p[1])];
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { ALL_TOPOLOGY, floorSelection, topologyFloors, topologyItems, type TopologySelection } from "../topology.ts";
|
||||
import { topologyNavigation } from "./view3d/topology-navigation.ts";
|
||||
// Lit wrapper around the lazily loaded 3D viewer.
|
||||
|
||||
import { changeMoments, hassAt, loadHistory, replayable, type History } from "../live/time-travel.ts";
|
||||
@@ -157,6 +159,7 @@ export class NfView3d extends LitElement {
|
||||
buttons: { attribute: false },
|
||||
_thumbs: { state: true },
|
||||
floorThumbs: { attribute: false },
|
||||
topologySelection: { attribute: false },
|
||||
clean: { attribute: false },
|
||||
cleanButton: { attribute: false },
|
||||
clock: { attribute: false },
|
||||
@@ -289,6 +292,9 @@ export class NfView3d extends LitElement {
|
||||
private declare _blend: number;
|
||||
/** Floor switcher with small pictures of the floors (panel and card; off with a fixed floor). */
|
||||
declare floorThumbs: boolean;
|
||||
declare topologySelection: TopologySelection | null;
|
||||
private topologyImages = new Map<string,string>();
|
||||
private scopedFor: {source:Building;key:string;plan:Building}|null=null;
|
||||
/** Clean view: only the stage – no energy values, thumbnails, legend, scene chips or search (the host hides its own bars). */
|
||||
declare clean: boolean;
|
||||
/** Show the eye button that toggles the clean view (the host listens for "clean-toggle"). */
|
||||
@@ -493,6 +499,7 @@ export class NfView3d extends LitElement {
|
||||
this.buttons = null;
|
||||
this._thumbs = [];
|
||||
this.floorThumbs = true;
|
||||
this.topologySelection=null;
|
||||
this.clean = false;
|
||||
this.cleanButton = false;
|
||||
this.clock = null;
|
||||
@@ -698,13 +705,13 @@ export class NfView3d extends LitElement {
|
||||
// a feature pack may have arrived with them (Energiefluss): the cables and modules follow
|
||||
this.syncDevices(true);
|
||||
}
|
||||
if (changed.has("building") && this.building) {
|
||||
if (["building","topologySelection","floorId"].some((k)=>changed.has(k)) && this.building) {
|
||||
// a new start view (just remembered in the editor) shows right away in the house view
|
||||
const start = JSON.stringify(this.startViewOf());
|
||||
const startChanged = this.shownStartView !== undefined && this.shownStartView !== start;
|
||||
this.shownStartView = start;
|
||||
v.setStartView(this.startViewOf());
|
||||
v.setBuilding(this.shownBuilding(this.hass));
|
||||
v.setStartView(this.building.topology&&this.topologyFocus.kind!=="all"?null:this.startViewOf());
|
||||
const previous=this.shownFor?.shown,shown=this.shownBuilding(this.hass);if(shown!==previous)v.setBuilding(shown);
|
||||
v.setMap(this.building?.settings.map, this.building?.settings.north ?? 0);
|
||||
if (startChanged && this.floorId === null) v.resetView();
|
||||
}
|
||||
@@ -712,14 +719,14 @@ export class NfView3d extends LitElement {
|
||||
v.setStartView(this.startViewOf());
|
||||
if (this.floorId === null) v.resetView();
|
||||
}
|
||||
if (changed.has("building") || changed.has("theme") || changed.has("floorThumbs") || changed.has("packs")) this.scheduleThumbs();
|
||||
if (changed.has("building") || changed.has("theme") || changed.has("floorThumbs") || changed.has("packs") || changed.has("topologySelection") || changed.has("floorId") || changed.has("roomId")) this.scheduleThumbs();
|
||||
// markers shown by kind outside the opened room change with the room
|
||||
const byRoom = this.markersOutside ? ["markersOutside", "floorId", "roomId"] : ["markersOutside"];
|
||||
const forced = this.pluginsDirty || ["building", "markerMode", "heatMode", "flows", "alerts", "dimmed", "holograms", "roomLabels", "floorId", "roomId", ...byRoom].some((k) => changed.has(k));
|
||||
const forced = this.pluginsDirty || ["building", "topologySelection", "markerMode", "heatMode", "flows", "alerts", "dimmed", "holograms", "roomLabels", "floorId", "roomId", ...byRoom].some((k) => changed.has(k));
|
||||
this.pluginsDirty = false;
|
||||
if (forced || changed.has("hass")) this.syncDevices(forced);
|
||||
if (changed.has("autoOrbit")) v.setAutoOrbit(this.autoOrbit ? 0.06 : 0);
|
||||
if (changed.has("_thumbs") || changed.has("_narrowStage") || changed.has("_phoneStage")) v.setLabelInset(this._thumbs.length && !this._phoneStage ? (this.narrowThumbs ? 136 : 184) : 0);
|
||||
if (changed.has("_thumbs") || changed.has("_narrowStage") || changed.has("_phoneStage") || changed.has("building")) v.setLabelInset(this.building?.topology||(this._thumbs.length&&!this._phoneStage) ? (this.narrowThumbs ? 136 : 184) : 0);
|
||||
if (changed.has("floorId")) v.setFloor(this.floorId);
|
||||
if (changed.has("roomId") && (this.roomId || changed.get("roomId"))) v.selectRoom(this.roomId);
|
||||
if (changed.has("outsideOpen") && changed.get("outsideOpen") !== undefined) {
|
||||
@@ -796,8 +803,19 @@ export class NfView3d extends LitElement {
|
||||
}
|
||||
|
||||
/** The building as the 3D view draws it: without the pieces whose visibility condition is not met. */
|
||||
private get topologyFocus(): TopologySelection {
|
||||
return this.building&&this.floorId?floorSelection(this.building,this.floorId,this.roomId):this.topologySelection??ALL_TOPOLOGY;
|
||||
}
|
||||
|
||||
private scopeBuilding(): Building {
|
||||
const b=this.building!;if(!b.topology)return b;
|
||||
const floors=topologyFloors(b,this.topologyFocus,true),key=floors.map((f)=>f.id).join("|");
|
||||
if(this.scopedFor?.source!==b||this.scopedFor.key!==key)this.scopedFor={source:b,key,plan:{...b,floors}};
|
||||
return this.scopedFor.plan;
|
||||
}
|
||||
|
||||
private shownBuilding(hass: HomeAssistant | undefined): Building {
|
||||
const b = this.building!;
|
||||
const b = this.scopeBuilding();
|
||||
const hidden = hiddenFurniture(hass, b);
|
||||
const layers = b.floors.filter((f) => f.layer && this.hiddenLayers.has(f.id)).map((f) => f.id);
|
||||
const key = [...hidden, ...layers.map((id) => `layer:${id}`)].join(",");
|
||||
@@ -839,7 +857,7 @@ export class NfView3d extends LitElement {
|
||||
|
||||
private syncDevices(force: boolean): void {
|
||||
const v = this.viewer;
|
||||
const b = this.building;
|
||||
const b = this.building?this.scopeBuilding():null;
|
||||
if (!v || !b || !this.hass) return;
|
||||
// time travel: the same view, fed with the states of the moment shown
|
||||
const travel = this._travel;
|
||||
@@ -864,7 +882,7 @@ export class NfView3d extends LitElement {
|
||||
const changed = force || this.watched.some((id) => this.shownStates.get(id) !== hass.states[id]);
|
||||
if (!changed) return;
|
||||
// a piece shown only while a helper is on (seasonal decoration) comes and goes with it
|
||||
if (hiddenFurniture(hass, b).join(",") !== this.shownFor?.key) v.setBuilding(this.shownBuilding(hass));
|
||||
const previous=this.shownFor?.shown,shown=this.shownBuilding(hass);if(shown!==previous)v.setBuilding(shown);
|
||||
this.shownStates = new Map(this.watched.map((id) => [id, hass.states[id]]));
|
||||
this.syncHydronics(v, b, hass);
|
||||
this.refreshToday(b);
|
||||
@@ -1738,12 +1756,12 @@ export class NfView3d extends LitElement {
|
||||
private scheduleThumbs(delay = 600): void {
|
||||
clearTimeout(this.thumbTimer);
|
||||
const floors = this.building?.floors.filter((f) => f.rooms.length).length ?? 0;
|
||||
if (!this.floorThumbs || floors < 2) {
|
||||
if (!this.floorThumbs || (!this.building?.topology && floors < 2)) {
|
||||
this._thumbs = [];
|
||||
return;
|
||||
}
|
||||
// at most every few seconds, however often lamps change (the tablet level waits longer)
|
||||
const wait = Math.max(delay, this.thumbsAt + (this._low ? 8000 : 4000) - Date.now());
|
||||
const wait = this.building?.topology ? delay : Math.max(delay, this.thumbsAt + (this._low ? 8000 : 4000) - Date.now());
|
||||
this.thumbTimer = setTimeout(() => {
|
||||
// at night (kiosk) the pictures are drawn once and then rest
|
||||
if (!this.viewer || (this.dimmed && this._thumbs.length)) return;
|
||||
@@ -1753,7 +1771,11 @@ export class NfView3d extends LitElement {
|
||||
return;
|
||||
}
|
||||
this.thumbsAt = Date.now();
|
||||
this._thumbs = this.viewer.floorThumbnails(this.narrowThumbs ? 104 : 150, this.narrowThumbs ? 78 : 112);
|
||||
if(this.building?.topology){
|
||||
const nodes=topologyItems(this.building,this.topologyFocus);
|
||||
for(const t of this.viewer.scopeThumbnails(nodes,this.narrowThumbs?104:150,this.narrowThumbs?78:112))this.topologyImages.set(t.key,t.url);
|
||||
this.requestUpdate();
|
||||
}else this._thumbs = this.viewer.floorThumbnails(this.narrowThumbs ? 104 : 150, this.narrowThumbs ? 78 : 112);
|
||||
}, wait);
|
||||
}
|
||||
|
||||
@@ -1762,6 +1784,9 @@ export class NfView3d extends LitElement {
|
||||
}
|
||||
|
||||
private renderThumbs() {
|
||||
if(this.floorThumbs&&this.building?.topology){
|
||||
return topologyNavigation(this.building,this.topologyFocus,this.topologyImages,(s)=>this.fire("topology-tap",s),this._thumbsCompact,()=>{this._thumbsCompact=!this._thumbsCompact;try{localStorage.setItem("nextfloor.thumbs_compact",this._thumbsCompact?"1":"0");}catch{}},this.narrowThumbs,this._shortStage);
|
||||
}
|
||||
if (!this._thumbs.length || !this.building || this._phoneStage) return nothing;
|
||||
const names = new Map(this.building.floors.map((f) => [f.id, f.name]));
|
||||
// the highest floor on top
|
||||
@@ -2805,7 +2830,7 @@ export class NfView3d extends LitElement {
|
||||
|
||||
/** Native utility readings for the current building/floor scope. */
|
||||
private utilityOverview(inline: boolean) {
|
||||
const b = this.building;
|
||||
const b = this.building?this.scopeBuilding():null;
|
||||
if (!b || !isSymcon(this.hass) || !this.showEnergy || this.clean || this.roomId || this.panelOpen || (!inline && !this._utilityOverviewVisible)) return nothing;
|
||||
const rooms = b.floors.flatMap((f) => f.rooms), floors = this.floorId ? b.floors.filter((f) => f.id === this.floorId) : b.floors;
|
||||
if (!floors.some((f) => floorUtilityReadings(this.hass, f, rooms).length || floorUtilityAreas(this.hass, f, rooms, true).length)) return nothing;
|
||||
@@ -2826,7 +2851,7 @@ export class NfView3d extends LitElement {
|
||||
if (isSymcon(this.hass) && this.building?.settings.rain_sensor && this.building.settings.rain_sensor !== "none") weather.push(["Regensensor", this.building.settings.rain_sensor]);
|
||||
const weatherValues = weather.length ? html`<button class="nf-energy-item nf-flow-toggle nf-weather-values" aria-label="Wetterwerte anzeigen" title="Wetterwerte anzeigen" aria-haspopup="dialog" @click=${() => this.renderRoot.querySelector<HTMLDialogElement>(".nf-weather-dialog")?.showModal()}><span>Wetter</span><b aria-hidden="true">⛅</b></button>
|
||||
<dialog class="nf-weather-dialog" aria-label="Wetterwerte" @keydown=${(event: KeyboardEvent) => event.stopPropagation()}><header><b>Wetter</b><button type="button" class="nf-chip" aria-label="Schließen" @click=${() => this.renderRoot.querySelector<HTMLDialogElement>(".nf-weather-dialog")?.close()}>×</button></header>${weather.map(([label, id]) => html`<p><span>${label}</span><b>${nativeText(this.hass.states[id])}${trendButton(this.hass, [id], label)}</b></p>`)}</dialog>` : nothing;
|
||||
const floors = isSymcon(this.hass) ? (this.building?.floors ?? []).filter((f) => !this.floorId || f.id === this.floorId).map((f) => ({ floor: f, readings: floorUtilityReadings(this.hass, f, this.building?.floors.flatMap((x) => x.rooms)) })).filter((f) => f.readings.length) : [];
|
||||
const floors = isSymcon(this.hass) ? (this.building?this.scopeBuilding().floors:[]).filter((f) => !this.floorId || f.id === this.floorId).map((f) => ({ floor: f, readings: floorUtilityReadings(this.hass, f, this.building?.floors.flatMap((x) => x.rooms)) })).filter((f) => f.readings.length) : [];
|
||||
const utilities = floors.length ? html`<button class="nf-energy-item nf-flow-toggle nf-utility-toggle" aria-label="Stockwerkszähler anzeigen" title="Stockwerkszähler anzeigen" aria-haspopup="dialog" @click=${() => this.renderRoot.querySelector<HTMLDialogElement>(".nf-utility-dialog")?.showModal()}><span>Stockwerkszähler</span><b aria-hidden="true">⚡ 💧</b></button>
|
||||
<dialog class="nf-weather-dialog nf-utility-dialog" aria-label="Stockwerkszähler" @keydown=${(event: KeyboardEvent) => event.stopPropagation()}><header><b>Stockwerkszähler</b><button type="button" class="nf-chip" aria-label="Schließen" @click=${() => this.renderRoot.querySelector<HTMLDialogElement>(".nf-utility-dialog")?.close()}>×</button></header>${floors.map(({ floor, readings }) => html`<h3>${floor.name}</h3><nf-utility-report .hass=${this.hass} .readings=${readings}></nf-utility-report>`)}</dialog>` : nothing;
|
||||
return [overviewToggle, summary, ...people, weatherValues, utilities, ...ids
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
import { html, nothing } from "lit";
|
||||
import type { Building } from "../../model.ts";
|
||||
import { ALL_TOPOLOGY, topologyItems, topologyKey, topologyPath, type TopologySelection } from "../../topology.ts";
|
||||
|
||||
export function topologyNavigation(b:Building,selection:TopologySelection,images:ReadonlyMap<string,string>,select:(s:TopologySelection)=>void,compact:boolean,fold:()=>void,narrow:boolean,short:boolean) {
|
||||
const path=topologyPath(b,selection),items=topologyItems(b,selection);
|
||||
const symbols={all:"⌂",location:"⌖",branch:"◇",building:"▥",floor:"▤",room:"□",outside:"🌳"};
|
||||
return html`<nav class="nf-thumbs nf-topology-navigation ${narrow?"nf-thumbs-small":""} ${short?"nf-thumbs-short":""} ${compact?"nf-thumbs-compact":""}" aria-label="Topologie">
|
||||
<style>.nf-topology-crumbs{display:grid;gap:3px}.nf-topology-crumbs button{min-width:0;text-align:left;padding:5px 7px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:10px}.nf-topology-navigation .nf-thumb>span{max-width:100%;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.nf-topology-placeholder{height:74px;display:grid;place-items:center;font-size:25px;opacity:.45}.nf-topology-navigation{overflow:auto;overscroll-behavior:contain;max-height:calc(100% - 130px)}.nf-topology-navigation .nf-thumbs-fold{position:static;align-self:flex-start;flex-shrink:0}.nf-topology-navigation .nf-thumb-house{flex-shrink:0}.nf-topology-navigation .nf-thumb{flex-shrink:0}</style>
|
||||
<button class="nf-thumbs-fold" aria-label=${compact?"Topologie aufklappen":"Topologie einklappen"} @click=${fold}>${compact?"▸":"◂"}</button>
|
||||
<button class="nf-thumb nf-thumb-house" aria-pressed=${selection.kind==="all"} @click=${()=>select(ALL_TOPOLOGY)}>⌂ <span>Alle Orte</span></button>
|
||||
${path.length>1?html`<div class="nf-topology-crumbs">${path.slice(1).map((n)=>html`<button class="nf-chip" data-topology-key=${n.key} title=${path.slice(1,path.indexOf(n)+1).map((p)=>p.name).join(" / ")} aria-current=${n===path.at(-1)?"location":nothing} @click=${()=>select(n.selection)}>${symbols[n.selection.kind]} ${n.name}</button>`)}</div>`:nothing}
|
||||
${items.map((n)=>html`<button class="nf-thumb" data-topology-key=${n.key} data-topology-kind=${n.selection.kind} aria-pressed=${topologyKey(selection)===n.key} title=${n.name} @click=${()=>select(n.selection)}>
|
||||
${compact?nothing:images.get(n.key)?html`<img src=${images.get(n.key)!} alt=""/>`:html`<div class="nf-topology-placeholder" aria-hidden="true">${symbols[n.selection.kind]}</div>`}
|
||||
<span>${n.name}</span>
|
||||
</button>`)}
|
||||
</nav>`;
|
||||
}
|
||||
@@ -9,6 +9,7 @@ import type { LampModel } from "./viewer/viewer3d.ts";
|
||||
import type { FurnitureColors } from "./furniture-colors.ts";
|
||||
import type { ShowWhen } from "./entities/visibility.ts";
|
||||
import type { HydronicConfig } from "./hydronic-model.ts";
|
||||
import { normalizeTopology } from "./topology.ts";
|
||||
|
||||
export type Vec2 = [number, number];
|
||||
|
||||
@@ -434,6 +435,10 @@ export interface Background {
|
||||
export interface Floor {
|
||||
id: string;
|
||||
name: string;
|
||||
/** Logical parent; coordinates and IDs remain unchanged when a floor moves in the topology. */
|
||||
building_id?: string | null;
|
||||
/** A separate outdoor plan belonging directly to a location, outside the building/storey hierarchy. */
|
||||
outdoor_location_id?: string | null;
|
||||
elevation: number;
|
||||
height: number;
|
||||
cut_height: number;
|
||||
@@ -1118,8 +1123,14 @@ export interface PresenceLink {
|
||||
room?: string | null;
|
||||
}
|
||||
|
||||
export interface PlanLocation { id: string; name: string }
|
||||
export interface PlanBranch { id: string; name: string; location_id: string }
|
||||
export interface PlanBuilding { id: string; name: string; branch_id: string }
|
||||
export interface PlanTopology { locations: PlanLocation[]; branches: PlanBranch[]; buildings: PlanBuilding[] }
|
||||
|
||||
export interface Building {
|
||||
version: 1;
|
||||
topology?: PlanTopology;
|
||||
floors: Floor[];
|
||||
settings: BuildingSettings;
|
||||
energy: EnergySettings;
|
||||
@@ -1685,6 +1696,7 @@ export function normalizeBuilding(b: Building): Building {
|
||||
}));
|
||||
}
|
||||
uniqueIds(b);
|
||||
if (b.topology) normalizeTopology(b);
|
||||
return b;
|
||||
}
|
||||
|
||||
|
||||
+41
-4
@@ -24,6 +24,7 @@ import type { HomeAssistant } from "./types.ts";
|
||||
import { withCoverControls } from "./entities/cover-controls.ts";
|
||||
import { withSymconWeather } from "./symcon-weather.ts";
|
||||
import { isSymcon } from "./entities/symcon-values.ts";
|
||||
import { ALL_TOPOLOGY, floorSelection, topologyOutsideFloors, topologyParent, topologyPath, type TopologySelection } from "./topology.ts";
|
||||
import { allOffPlan, floorSwitchables, type ServiceCall } from "./live/all-off.ts";
|
||||
import type { FloorStack, Quality, WallMode } from "./viewer/viewer3d.ts";
|
||||
|
||||
@@ -38,6 +39,7 @@ export class NextFloorPanel extends LitElement {
|
||||
panel: { attribute: false },
|
||||
_mode: { state: true },
|
||||
_editorReady: { state: true },
|
||||
_topologyGroup: { state: true },
|
||||
_floorId: { state: true },
|
||||
_roomId: { state: true },
|
||||
_wallMode: { state: true },
|
||||
@@ -63,6 +65,7 @@ export class NextFloorPanel extends LitElement {
|
||||
private declare _mode: Mode;
|
||||
/** The editor bundle has been loaded (it is fetched when the editor or the extensions page opens first). */
|
||||
private declare _editorReady: boolean;
|
||||
private declare _topologyGroup: TopologySelection;
|
||||
private declare _floorId: string | null;
|
||||
private declare _roomId: string | null;
|
||||
private declare _wallMode: WallMode;
|
||||
@@ -98,6 +101,7 @@ export class NextFloorPanel extends LitElement {
|
||||
this._mode = "view";
|
||||
this._editorReady = !!customElements.get("nf-editor");
|
||||
this._floorId = null;
|
||||
this._topologyGroup=ALL_TOPOLOGY;
|
||||
this._roomId = null;
|
||||
this._wallMode = "auto";
|
||||
this._prefs = this.store.load(location.search);
|
||||
@@ -165,6 +169,7 @@ export class NextFloorPanel extends LitElement {
|
||||
const building = this.data.building;
|
||||
if (building && this._floorId && !building.floors.some((f) => f.id === this._floorId)) {
|
||||
this._floorId = null;
|
||||
this._topologyGroup=ALL_TOPOLOGY;
|
||||
this._roomId = null;
|
||||
}
|
||||
}
|
||||
@@ -180,7 +185,19 @@ export class NextFloorPanel extends LitElement {
|
||||
this._mode = mode;
|
||||
}
|
||||
|
||||
private topologySelection(building: Building): TopologySelection {
|
||||
return this._floorId ? floorSelection(building,this._floorId,this._roomId) : this._topologyGroup;
|
||||
}
|
||||
|
||||
private openTopology(selection: TopologySelection): void {
|
||||
const b=this.data.building;if(!b)return;
|
||||
this._roomId=selection.kind==="room"?selection.id??null:null;
|
||||
this._floorId=selection.kind==="room"?selection.floorId??null:selection.kind==="floor"?selection.id??null:selection.kind==="outside"?b.floors.find((f)=>f.outdoor_location_id===selection.id)?.id??null:null;
|
||||
this._topologyGroup=selection;this._outside=false;
|
||||
}
|
||||
|
||||
private openFloor(floorId: string | null): void {
|
||||
this._topologyGroup=ALL_TOPOLOGY;
|
||||
this._floorId = floorId;
|
||||
this._roomId = null;
|
||||
this._outside = false;
|
||||
@@ -188,6 +205,7 @@ export class NextFloorPanel extends LitElement {
|
||||
|
||||
/** The devices of Outside, worked out again only when the plan or the registry changes. */
|
||||
private outsideIds(building: Building): string[] {
|
||||
if(building.topology)return outsideEntities(this.hass,topologyOutsideFloors(building,this.topologySelection(building)),building.settings.outside_hidden);
|
||||
const m = this.outsideMemo;
|
||||
if (m && m.building === building && m.entities === this.hass.entities) return m.ids;
|
||||
const ids = outsideEntities(this.hass, building.floors, building.settings.outside_hidden);
|
||||
@@ -196,7 +214,15 @@ export class NextFloorPanel extends LitElement {
|
||||
}
|
||||
|
||||
/** Opens Outside over the house view (or closes it again). */
|
||||
private openOutside(): void {
|
||||
private openOutside(floorId?: string): void {
|
||||
const b=this.data.building;
|
||||
if(b?.topology){
|
||||
const location=topologyPath(b,floorId?floorSelection(b,floorId):this.topologySelection(b)).find((n)=>n.selection.kind==="location");
|
||||
if(!location)return;
|
||||
const f=b.floors.find((f)=>f.outdoor_location_id===location?.selection.id);
|
||||
if(f){const open=!this._outside;this.openTopology({kind:"outside",id:f.outdoor_location_id!});this._outside=open;return;}
|
||||
const open=!this._outside;this.openTopology(location.selection);this._outside=open;return;
|
||||
}
|
||||
const open = !this._outside;
|
||||
this.openFloor(null);
|
||||
this._outside = open;
|
||||
@@ -205,7 +231,7 @@ export class NextFloorPanel extends LitElement {
|
||||
private onRoomTap(e: CustomEvent<{ floorId: string; roomId: string | null }>): void {
|
||||
const { floorId, roomId } = e.detail;
|
||||
// an outdoor area's pin opens Outside
|
||||
if (roomId === "nf-outside") return this.openOutside();
|
||||
if (roomId === "nf-outside") return this.openOutside(floorId);
|
||||
// in the house view, or on another floor, a tap opens the whole floor first and the rooms come next
|
||||
if ((this.data.building?.floors.length ?? 0) > 1 && floorId && this._floorId !== floorId) return this.openFloor(floorId);
|
||||
if (roomId) {
|
||||
@@ -257,6 +283,7 @@ export class NextFloorPanel extends LitElement {
|
||||
private back(): void {
|
||||
if (this._outside) this._outside = false;
|
||||
else if (this._roomId) this._roomId = null;
|
||||
else if(this.data.building?.topology && this.topologySelection(this.data.building).kind!=="all")this.openTopology(topologyParent(this.data.building,this.topologySelection(this.data.building)));
|
||||
else if (this._floorId && (this.data.building?.floors.length ?? 0) > 1) this._floorId = null;
|
||||
else this.view3d()?.resetView();
|
||||
}
|
||||
@@ -487,6 +514,14 @@ export class NextFloorPanel extends LitElement {
|
||||
|
||||
/** The bar of floors and rooms above the stage. */
|
||||
private renderNav(building: Building) {
|
||||
if(building.topology){
|
||||
const floor=building.floors.find((f)=>f.id===this._floorId);
|
||||
if(!floor||floor.outdoor_location_id)return nothing;
|
||||
return html`<nav class="nf-nav nf-topology-floor-nav" aria-label=${floor.name}>
|
||||
${floor.rooms.map((room)=>html`<button class="nf-chip nf-room-chip" aria-pressed=${room.id===this._roomId} @click=${()=>{this._roomId=this._roomId===room.id?null:room.id;this._outside=false;}}>${room.name}</button>`)}
|
||||
${this.allOffChip(building)}
|
||||
</nav>`;
|
||||
}
|
||||
const shown: Floor[] = building.floors.filter((f) => !this._floorId || f.id === this._floorId);
|
||||
const several = building.floors.length > 1;
|
||||
const wrap = this._prefs.navWrap;
|
||||
@@ -573,7 +608,7 @@ export class NextFloorPanel extends LitElement {
|
||||
}
|
||||
|
||||
private renderView(building: Building) {
|
||||
if (!building.floors.some((f) => f.rooms.length)) {
|
||||
if (!building.floors.some((f) => f.rooms.length || f.outdoor.length || f.furniture.length)) {
|
||||
return html`<div class="nf-empty">
|
||||
<p>${this.t(this.isAdmin ? (building.floors.length ? "no_rooms_admin" : "no_building_admin") : "no_building")}</p>
|
||||
${this.isAdmin ? html`<button class="nf-btn nf-primary" @click=${() => this.setMode("editor")}>${this.t("open_editor")}</button>` : nothing}
|
||||
@@ -590,6 +625,7 @@ export class NextFloorPanel extends LitElement {
|
||||
class="nf-body"
|
||||
.hass=${withSymconWeather(withCoverControls(this.hass, building.floors), building.settings)}
|
||||
.building=${building}
|
||||
.topologySelection=${this.topologySelection(building)}
|
||||
.packs=${this.data.packs}
|
||||
.floorStack=${p.floorStack}
|
||||
.roomLabels=${p.roomNames}
|
||||
@@ -598,7 +634,7 @@ export class NextFloorPanel extends LitElement {
|
||||
@clean-toggle=${() => this.setPref("clean", !p.clean)}
|
||||
?weather=${p.weather}
|
||||
.panelOpen=${!!this._roomId || this._outside}
|
||||
.floorId=${building.floors.length > 1 ? this._floorId : (building.floors[0]?.id ?? null)}
|
||||
.floorId=${building.topology || building.floors.length > 1 ? this._floorId : (building.floors[0]?.id ?? null)}
|
||||
.roomId=${this._roomId}
|
||||
.outsideOpen=${this._outside}
|
||||
.wallMode=${this._wallMode}
|
||||
@@ -632,6 +668,7 @@ export class NextFloorPanel extends LitElement {
|
||||
.quality=${p.quality}
|
||||
?showStats=${p.stats}
|
||||
@room-tap=${this.onRoomTap}
|
||||
@topology-tap=${(e: CustomEvent<TopologySelection>) => this.openTopology(e.detail)}
|
||||
@floor-tap=${(e: CustomEvent<{ floorId: string | null }>) => this.openFloor(e.detail.floorId)}
|
||||
@back=${() => this.back()}
|
||||
></nf-view3d>
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { emptyBuilding, newFloor, normalizeBuilding } from "./model.ts";
|
||||
import { ALL_TOPOLOGY, addLocationOutside, enableTopology, floorSelection, floorTopologyPath, normalizeTopology, topologyFloors, topologyItems, topologyOutsideFloors, topologyParent, topologyPath, topologyTree } from "./topology.ts";
|
||||
import { copyOfFloor, newFloorFor } from "./components/editor/ops/floors.ts";
|
||||
import { translate } from "./components/editor/ops/transform.ts";
|
||||
import { box } from "./entities/fixtures.ts";
|
||||
import { buildRoof } from "./viewer/roof.ts";
|
||||
|
||||
function project(){
|
||||
const b=emptyBuilding();
|
||||
b.topology={locations:[{id:"urbach",name:"Urbach"},{id:"ulm",name:"Ulm"}],branches:[{id:"hq",name:"Zentrale",location_id:"urbach"},{id:"west",name:"West",location_id:"urbach"},{id:"south",name:"Süd",location_id:"ulm"}],buildings:[{id:"ras19",name:"RAS19",branch_id:"hq"},{id:"ras21",name:"RAS21",branch_id:"west"},{id:"ulm1",name:"RAS19",branch_id:"south"}]};
|
||||
b.floors=[{...newFloor("eg","EG",0),building_id:"ras19",rooms:[{...box("it",0,0,4,3),name:"IT"}]},{...newFloor("og","OG",3),building_id:"ras19"},{...newFloor("west-eg","EG",0),building_id:"ras21",rooms:[{...box("it-west",30,0,4,3),name:"IT"}]},{...newFloor("ulm-eg","EG",0),building_id:"ulm1",rooms:[{...box("it-ulm",60,0,4,3),name:"IT"}]}];
|
||||
return b;
|
||||
}
|
||||
|
||||
test("legacy plans are unchanged until topology is enabled; enabling preserves geometry, links and stable grant keys",()=>{
|
||||
const b=emptyBuilding();b.floors=[{...newFloor("old","EG",0),rooms:[{...box("room",0,0,4,3),area_id:"symcon-category-100"}]}];
|
||||
normalizeBuilding(b);const before=structuredClone(b);assert.equal(b.topology,undefined);
|
||||
enableTopology(b,"RAS19");assert.equal(b.topology!.buildings[0].name,"RAS19");
|
||||
assert.equal(b.floors[0].id,"old");assert.deepEqual(b.floors[0].rooms,before.floors[0].rooms);
|
||||
const t=structuredClone(b.topology);enableTopology(b);assert.deepEqual(b.topology,t);
|
||||
});
|
||||
|
||||
test("location / branch / building / floor / room is a full unambiguous path even with repeated labels",()=>{
|
||||
const b=project();
|
||||
assert.equal(floorTopologyPath(b,b.floors[0]),"Urbach / Zentrale / RAS19 / EG");
|
||||
assert.deepEqual(topologyPath(b,{kind:"room",id:"it",floorId:"eg"}).slice(1).map((n)=>n.name),["Urbach","Zentrale","RAS19","EG","IT"]);
|
||||
assert.deepEqual(topologyItems(b,{kind:"location",id:"urbach"}).map((n)=>n.name),["Zentrale","West"]);
|
||||
assert.deepEqual(topologyItems(b,{kind:"building",id:"ras19"}).map((n)=>n.name),["OG","EG"]);
|
||||
assert.deepEqual(topologyItems(b,{kind:"floor",id:"eg"}).map((n)=>n.name),["IT"]);
|
||||
assert.deepEqual(topologyParent(b,{kind:"building",id:"ras19"}),{kind:"branch",id:"hq"});
|
||||
assert.deepEqual(topologyParent(b,{kind:"location",id:"urbach"}),ALL_TOPOLOGY);
|
||||
});
|
||||
|
||||
test("scope membership excludes other branches and locations, and selected floor stacks stay inside their building",()=>{
|
||||
const b=project(),ids=(s:Parameters<typeof topologyFloors>[1],stack=false)=>topologyFloors(b,s,stack).map((f)=>f.id);
|
||||
assert.deepEqual(ids({kind:"location",id:"urbach"}),["eg","og","west-eg"]);
|
||||
assert.deepEqual(ids({kind:"branch",id:"hq"}),["eg","og"]);
|
||||
assert.deepEqual(ids({kind:"floor",id:"eg"}),["eg"]);
|
||||
assert.deepEqual(ids({kind:"room",id:"it",floorId:"eg"},true),["eg","og"]);
|
||||
assert.deepEqual(ids({kind:"building",id:"ulm1"}),["ulm-eg"]);
|
||||
assert.deepEqual(topologyPath(b,{kind:"building",id:"deleted"}).map((n)=>n.selection.kind),["all"]);
|
||||
});
|
||||
|
||||
test("each location has a separate outdoor plan, with no building parent or duplicated creation",()=>{
|
||||
const b=project(),a=addLocationOutside(b,"urbach"),z=addLocationOutside(b,"ulm");
|
||||
assert.notEqual(a.id,z.id);assert.equal(addLocationOutside(b,"urbach"),a);assert.equal(a.building_id,null);
|
||||
assert.deepEqual(topologyFloors(b,{kind:"outside",id:"urbach"}).map((f)=>f.id),[a.id]);
|
||||
assert.ok(!topologyFloors(b,{kind:"building",id:"ras19"}).includes(a));
|
||||
assert.ok(!topologyFloors(b,{kind:"location",id:"urbach"}).includes(z));
|
||||
assert.deepEqual(floorSelection(b,a.id),{kind:"outside",id:"urbach"});
|
||||
assert.equal(topologyItems(b,{kind:"location",id:"urbach"}).at(-1)!.selection.kind,"outside");
|
||||
a.rooms=[box("patio",0,0,4,3)];
|
||||
assert.equal(topologyPath(b,{kind:"room",id:"patio",floorId:a.id}).at(-1)!.name,"patio");
|
||||
assert.deepEqual(topologyFloors(b,{kind:"room",id:"patio",floorId:a.id},true).map((f)=>f.id),[a.id]);
|
||||
assert.deepEqual(topologyOutsideFloors(b,{kind:"outside",id:"urbach"}).map((f)=>f.id),["eg","og","west-eg",a.id]);
|
||||
assert.deepEqual(topologyOutsideFloors(b,{kind:"floor",id:"ulm-eg"}).map((f)=>f.id),["ulm-eg",z.id]);
|
||||
});
|
||||
|
||||
test("topology and memberships survive roundtrip; orphan parents are repaired without dropping a floor",()=>{
|
||||
const b=project();addLocationOutside(b,"urbach");
|
||||
const saved=normalizeBuilding(JSON.parse(JSON.stringify(b)));assert.deepEqual(saved.topology,b.topology);
|
||||
assert.equal(saved.floors[0].building_id,"ras19");
|
||||
saved.floors[0].building_id="removed-building";saved.topology!.branches[0].location_id="removed-location";
|
||||
normalizeTopology(saved);
|
||||
assert.ok(saved.topology!.buildings.some((g)=>g.id==="removed-building"));
|
||||
assert.ok(saved.topology!.locations.some((l)=>l.id==="removed-location"));
|
||||
assert.deepEqual(new Set(topologyTree(saved).floorIds),new Set(saved.floors.map((f)=>f.id)));
|
||||
});
|
||||
|
||||
test("new/copied floors use their own building's elevation; a whole-building move leaves other sites unchanged",()=>{
|
||||
const b=project();b.floors[3].elevation=50;
|
||||
const f=newFloorFor(b,null,{first:"EG",next:(n)=>`Etage ${n}`},"ras19");
|
||||
assert.equal(f.building_id,"ras19");assert.equal(f.elevation,5.75);
|
||||
assert.equal(copyOfFloor(b,b.floors[0],"Kopie",{furniture:false,devices:false,outdoor:false}).elevation,5.5);
|
||||
const other=structuredClone(b.floors[3]);
|
||||
translate(b,{floorId:"eg",allFloors:true,floorIds:topologyFloors(b,{kind:"building",id:"ras19"}).map((f)=>f.id)},10,20);
|
||||
assert.deepEqual(b.floors[0].rooms[0].points[0],[10,20]);assert.deepEqual(b.floors[3],other);
|
||||
});
|
||||
|
||||
test("automatic roofs cover each building independently and leave location outdoors uncovered",()=>{
|
||||
const b=project();b.settings.roof={type:"flat",pitch:0,overhang:.2};addLocationOutside(b,"urbach");
|
||||
assert.deepEqual(buildRoof(b).map((p)=>p.floor.building_id).sort(),["ras19","ras21","ulm1"]);
|
||||
assert.equal(buildRoof({...b,floors:b.floors.filter((f)=>!!f.outdoor_location_id)}).length,0);
|
||||
});
|
||||
@@ -0,0 +1,107 @@
|
||||
import { newFloor, uid, type Building, type Floor, type PlanTopology } from "./model.ts";
|
||||
|
||||
export type TopologyKind = "all" | "location" | "branch" | "building" | "floor" | "room" | "outside";
|
||||
export interface TopologySelection { kind: TopologyKind; id?: string; floorId?: string }
|
||||
export interface TopologyNode {
|
||||
key: string; name: string; selection: TopologySelection; floorIds: string[]; children: TopologyNode[];
|
||||
room?: { floorId: string; roomId: string };
|
||||
}
|
||||
export const ALL_TOPOLOGY: TopologySelection = { kind: "all" };
|
||||
export const topologyKey = (s: TopologySelection): string => [s.kind, s.floorId, s.id].filter(Boolean).join(":");
|
||||
|
||||
/** Enable the hierarchy without moving geometry or changing the stable floor/room IDs used by grants. */
|
||||
export function enableTopology(b: Building, name = "Gebäude 1"): void {
|
||||
if (b.topology) return;
|
||||
const location = uid("location"), branch = uid("branch"), building = uid("building");
|
||||
b.topology = { locations:[{id:location,name:"Ort 1"}], branches:[{id:branch,name:"Niederlassung 1",location_id:location}], buildings:[{id:building,name,branch_id:branch}] };
|
||||
for (const f of b.floors) f.building_id = building;
|
||||
}
|
||||
|
||||
/** Recover orphan parents rather than silently hiding their floors after an imported/older plan. */
|
||||
export function normalizeTopology(b: Building): void {
|
||||
const t = b.topology!;
|
||||
t.locations ??= []; t.branches ??= []; t.buildings ??= [];
|
||||
const location = (id?: string) => {
|
||||
id ||= t.locations[0]?.id || uid("location");
|
||||
if (!t.locations.some((x)=>x.id===id)) t.locations.push({id,name:"Ort"});
|
||||
return id;
|
||||
};
|
||||
const branch = (id?: string) => {
|
||||
id ||= t.branches[0]?.id || uid("branch");
|
||||
if (!t.branches.some((x)=>x.id===id)) t.branches.push({id,name:"Niederlassung",location_id:location()});
|
||||
return id;
|
||||
};
|
||||
const building = (id?: string | null) => {
|
||||
id ||= t.buildings[0]?.id || uid("building");
|
||||
if (!t.buildings.some((x)=>x.id===id)) t.buildings.push({id,name:"Gebäude",branch_id:branch()});
|
||||
return id;
|
||||
};
|
||||
for (const s of t.branches) s.location_id = location(s.location_id);
|
||||
for (const s of t.buildings) s.branch_id = branch(s.branch_id);
|
||||
for (const f of b.floors) {
|
||||
if (f.outdoor_location_id) { f.outdoor_location_id=location(f.outdoor_location_id); f.building_id=null; }
|
||||
else f.building_id=building(f.building_id);
|
||||
}
|
||||
}
|
||||
|
||||
export function addLocationOutside(b: Building, locationId: string): Floor {
|
||||
const found=b.floors.find((f)=>f.outdoor_location_id===locationId);
|
||||
if(found)return found;
|
||||
const f={...newFloor(uid("outside"),"Außen",0),outdoor_location_id:locationId,building_id:null};
|
||||
b.floors.push(f);return f;
|
||||
}
|
||||
|
||||
export function floorSelection(b: Building, floorId: string, roomId?: string | null): TopologySelection {
|
||||
const f=b.floors.find((f)=>f.id===floorId);
|
||||
return roomId ? {kind:"room",id:roomId,floorId} : f?.outdoor_location_id ? {kind:"outside",id:f.outdoor_location_id} : {kind:"floor",id:floorId};
|
||||
}
|
||||
|
||||
export function topologyTree(b: Building): TopologyNode {
|
||||
const make=(kind:TopologyKind,id:string|undefined,name:string,children:TopologyNode[]=[],floorIds=children.flatMap((c)=>c.floorIds),room?:TopologyNode["room"]):TopologyNode=>{
|
||||
const selection:TopologySelection={kind,...(id?{id}:{}),...(room?{floorId:room.floorId}:{})};
|
||||
return {key:topologyKey(selection),name,selection,floorIds:[...new Set(floorIds)],children,...(room?{room}:{})};
|
||||
};
|
||||
const floorNode=(f:Floor)=>make("floor",f.id,f.name,f.rooms.map((r)=>make("room",r.id,r.name,[],[f.id],{floorId:f.id,roomId:r.id})),[f.id]);
|
||||
if(!b.topology)return make("all",undefined,"Alle Etagen",[...b.floors].sort((a,z)=>z.elevation-a.elevation).map(floorNode));
|
||||
const t=b.topology;
|
||||
return make("all",undefined,"Alle Orte",t.locations.map((l)=>{
|
||||
const children=t.branches.filter((n)=>n.location_id===l.id).map((n)=>make("branch",n.id,n.name,t.buildings.filter((g)=>g.branch_id===n.id).map((g)=>make("building",g.id,g.name,b.floors.filter((f)=>!f.outdoor_location_id&&f.building_id===g.id).sort((a,z)=>z.elevation-a.elevation).map(floorNode)))));
|
||||
const outside=b.floors.filter((f)=>f.outdoor_location_id===l.id);
|
||||
if(outside.length)children.push(make("outside",l.id,"Außen",outside.flatMap((f)=>f.rooms.map((r)=>make("room",r.id,r.name,[],[f.id],{floorId:f.id,roomId:r.id}))),outside.map((f)=>f.id)));
|
||||
return make("location",l.id,l.name,children);
|
||||
}));
|
||||
}
|
||||
|
||||
export function topologyPath(b:Building,s:TopologySelection):TopologyNode[] {
|
||||
const root=topologyTree(b),key=topologyKey(s);
|
||||
const visit=(node:TopologyNode):TopologyNode[]|null=>{
|
||||
if(node.key===key)return [node];
|
||||
for(const c of node.children){const path=visit(c);if(path)return [node,...path];}
|
||||
return null;
|
||||
};
|
||||
return visit(root)??[root];
|
||||
}
|
||||
export const topologyNode=(b:Building,s:TopologySelection):TopologyNode=>topologyPath(b,s).at(-1)!;
|
||||
export const topologyParent=(b:Building,s:TopologySelection):TopologySelection=>topologyPath(b,s).at(-2)?.selection??ALL_TOPOLOGY;
|
||||
export function topologyItems(b:Building,s:TopologySelection):TopologyNode[] {
|
||||
const path=topologyPath(b,s),node=path.at(-1)!;
|
||||
return node.selection.kind==="room" ? path.at(-2)!.children : !node.children.length&&["floor","outside"].includes(node.selection.kind)?[node]:node.children;
|
||||
}
|
||||
/** A floor/room keeps its own building's stack; higher levels isolate exactly their descendants. */
|
||||
export function topologyFloors(b:Building,s:TopologySelection,withStack=false):Floor[] {
|
||||
if(!b.topology||s.kind==="all")return b.floors;
|
||||
const path=topologyPath(b,s);
|
||||
const node=(withStack&&(s.kind==="floor"||s.kind==="room")?path.find((n)=>n.selection.kind==="building"):null)??path.at(-1)!;
|
||||
const ids=new Set(node.floorIds);return b.floors.filter((f)=>ids.has(f.id));
|
||||
}
|
||||
export const topologyPlan=(b:Building,s:TopologySelection,withStack=false):Building=>({...b,floors:topologyFloors(b,s,withStack)});
|
||||
/** Outside readouts also include legacy outdoor devices drawn on a location's building floors. */
|
||||
export function topologyOutsideFloors(b:Building,s:TopologySelection):Floor[] {
|
||||
if(!b.topology)return b.floors;
|
||||
const location=topologyPath(b,s).find((n)=>n.selection.kind==="location");
|
||||
return location?topologyFloors(b,location.selection):[];
|
||||
}
|
||||
export function floorTopologyPath(b:Building,f:Floor):string {
|
||||
return b.topology?topologyPath(b,floorSelection(b,f.id)).slice(1).map((n)=>n.name).join(" / "):f.name;
|
||||
}
|
||||
export const emptyTopology=():PlanTopology=>({locations:[],branches:[],buildings:[]});
|
||||
@@ -10,6 +10,15 @@ 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;
|
||||
// Automatic roofs belong to independent buildings, never to a location's outdoor plan or the global highest storey.
|
||||
if (b.topology && roof?.type !== "custom") {
|
||||
const groups = new Map<string, typeof b.floors>();
|
||||
for (const f of b.floors) if (!f.outdoor_location_id) {
|
||||
const id = f.building_id ?? "legacy";
|
||||
groups.set(id, [...(groups.get(id) ?? []), f]);
|
||||
}
|
||||
return [...groups.values()].flatMap((floors) => buildRoof({ ...b, topology: undefined, floors }, windows));
|
||||
}
|
||||
const single = roof?.type === "custom" ? null : buildSingleRoof(b);
|
||||
const parts = roof?.type === "custom" ? buildSections(b, roof.sections ?? [], roof.overhang) : single ? [single] : [];
|
||||
pushSolar(b, parts);
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import type { TopologyNode } from "../topology.ts";
|
||||
// 3D view (separate bundle, loaded on demand). Renders only when something changes.
|
||||
//
|
||||
// Floors are shown in three levels: the whole house (floors pulled apart or stacked), one floor
|
||||
@@ -26,6 +27,7 @@ import {
|
||||
OrthographicCamera,
|
||||
PerspectiveCamera,
|
||||
Points,
|
||||
Plane,
|
||||
PlaneGeometry,
|
||||
Raycaster,
|
||||
RepeatWrapping,
|
||||
@@ -1911,7 +1913,7 @@ export class NextFloorViewer {
|
||||
}
|
||||
this.floors.push({
|
||||
floor,
|
||||
rank: ordered.indexOf(floor),
|
||||
rank: b.topology ? floor.outdoor_location_id ? 0 : ordered.filter((f)=>!f.outdoor_location_id&&f.building_id===floor.building_id).indexOf(floor) : ordered.indexOf(floor),
|
||||
group,
|
||||
geo,
|
||||
floorMesh,
|
||||
@@ -2486,6 +2488,12 @@ export class NextFloorViewer {
|
||||
const box = new Box3();
|
||||
for (const fv of this.activeFloors()) {
|
||||
const y0 = fv.floor.elevation + fv.ty;
|
||||
for (const area of fv.floor.outdoor) for (const [x,z] of area.points) {
|
||||
box.expandByPoint(new Vector3(x,y0,z));box.expandByPoint(new Vector3(x,y0+Math.max(1,area.height??0),z));
|
||||
}
|
||||
if(!fv.floor.rooms.length)for(const m of fv.floor.furniture){
|
||||
box.expandByPoint(new Vector3(m.x-m.w/2,y0,m.z-m.d/2));box.expandByPoint(new Vector3(m.x+m.w/2,y0+(m.mount_y??0)+m.h,m.z+m.d/2));
|
||||
}
|
||||
for (const room of fv.floor.rooms) {
|
||||
for (const [x, z] of room.points) {
|
||||
box.expandByPoint(new Vector3(x, y0, z));
|
||||
@@ -2941,93 +2949,52 @@ export class NextFloorViewer {
|
||||
* the same renderer, so nothing is uploaded twice; the view is restored afterwards.
|
||||
*/
|
||||
floorThumbnails(width = 200, height = 150): { floorId: string; url: string }[] {
|
||||
const floors = this.floors.filter((fv) => fv.floor.rooms.some((r) => r.points.length >= 3));
|
||||
if (!floors.length) return [];
|
||||
const scale = this.lowQuality ? 1 : Math.min(2, window.devicePixelRatio || 1);
|
||||
const w = Math.round(width * scale);
|
||||
const h = Math.round(height * scale);
|
||||
const target = new WebGLRenderTarget(w, h);
|
||||
target.texture.colorSpace = SRGBColorSpace;
|
||||
const camera = new OrthographicCamera(-1, 1, 1, -1, 0.1, 400);
|
||||
const saved = this.floors.map((fv) => ({ fv, visible: fv.group.visible, y: fv.y, o: fv.o, standing: fv.mask.standing.value, glass: fv.mask.glass.value }));
|
||||
const roofVisible = this.roof?.group.visible ?? false;
|
||||
const ghostVisible = this.ghost?.visible ?? false;
|
||||
const clear = this.renderer.getClearAlpha();
|
||||
const pixels = new Uint8Array(w * h * 4);
|
||||
const canvas = document.createElement("canvas");
|
||||
canvas.width = w;
|
||||
canvas.height = h;
|
||||
const ctx = canvas.getContext("2d")!;
|
||||
const out: { floorId: string; url: string }[] = [];
|
||||
return this.scopeThumbnails(this.floors.filter((fv)=>fv.floor.rooms.some((r)=>r.points.length>=3)).map((fv)=>({key:fv.floor.id,floorIds:[fv.floor.id]})),width,height).map((t)=>({floorId:t.key,url:t.url}));
|
||||
}
|
||||
|
||||
/** Draw only a topology node's floors and frame its own geometry; rooms additionally clip neighbouring geometry. */
|
||||
scopeThumbnails(nodes: readonly Pick<TopologyNode,"key"|"floorIds"|"room">[], width=150,height=112):{key:string;url:string}[] {
|
||||
if(!nodes.length||!this.floors.length)return [];
|
||||
const scale=this.lowQuality?1:Math.min(2,window.devicePixelRatio||1),w=Math.round(width*scale),h=Math.round(height*scale);
|
||||
const target=new WebGLRenderTarget(w,h);target.texture.colorSpace=SRGBColorSpace;
|
||||
const camera=new OrthographicCamera(-1,1,1,-1,.1,4000);
|
||||
const saved=this.floors.map((fv)=>({fv,visible:fv.group.visible,y:fv.y,o:fv.o,standing:fv.mask.standing.value,glass:fv.mask.glass.value}));
|
||||
const floorGroups=new Set(this.floors.map((f)=>f.group));
|
||||
const others=[...this.scene.children.filter((c)=>c!==this.root),...this.root.children.filter((c)=>!floorGroups.has(c as Group))].filter((c)=>!(c as Object3D & {isLight?:boolean}).isLight).map((node)=>({node,visible:node.visible}));
|
||||
const clear=this.renderer.getClearAlpha(),planes=this.renderer.clippingPlanes;
|
||||
const pixels=new Uint8Array(w*h*4),canvas=document.createElement("canvas");canvas.width=w;canvas.height=h;
|
||||
const ctx=canvas.getContext("2d")!,out:{key:string;url:string}[]=[];
|
||||
try {
|
||||
if (this.roof) this.roof.group.visible = false;
|
||||
if (this.ghost) this.ghost.visible = false;
|
||||
for(const x of others)x.node.visible=false;
|
||||
this.renderer.setClearAlpha(0);
|
||||
for (const fv of floors) {
|
||||
for (const other of this.floors) other.group.visible = other === fv;
|
||||
fv.y = 0;
|
||||
fv.o = 1;
|
||||
this.applyFloor(fv);
|
||||
fv.group.visible = true;
|
||||
fv.mask.standing.value = 0;
|
||||
fv.mask.glass.value = 0;
|
||||
// fit the floor's rooms (with the cut walls) into the picture
|
||||
const pts = fv.floor.rooms.flatMap((r) => r.points);
|
||||
const y0 = fv.floor.elevation;
|
||||
const box = new Box3(
|
||||
new Vector3(Math.min(...pts.map((p) => p[0])) - 0.3, y0, Math.min(...pts.map((p) => p[1])) - 0.3),
|
||||
new Vector3(Math.max(...pts.map((p) => p[0])) + 0.3, y0 + Math.min(fv.floor.cut_height, fv.floor.height), Math.max(...pts.map((p) => p[1])) + 0.3),
|
||||
);
|
||||
const center = box.getCenter(new Vector3());
|
||||
const theta = -0.6;
|
||||
const phi = 0.8;
|
||||
const dir = new Vector3(Math.sin(phi) * Math.sin(theta), Math.cos(phi), Math.sin(phi) * Math.cos(theta));
|
||||
camera.position.copy(center).addScaledVector(dir, 100);
|
||||
camera.lookAt(center);
|
||||
camera.updateMatrixWorld();
|
||||
let rx = 0.5;
|
||||
let ry = 0.5;
|
||||
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);
|
||||
rx = Math.max(rx, Math.abs(p.x));
|
||||
ry = Math.max(ry, Math.abs(p.y));
|
||||
}
|
||||
// keep the picture's aspect ratio
|
||||
const aspect = w / h;
|
||||
if (rx / ry > aspect) ry = rx / aspect;
|
||||
else rx = ry * aspect;
|
||||
camera.left = -rx * 1.05;
|
||||
camera.right = rx * 1.05;
|
||||
camera.top = ry * 1.05;
|
||||
camera.bottom = -ry * 1.05;
|
||||
camera.updateProjectionMatrix();
|
||||
this.renderer.setRenderTarget(target);
|
||||
this.renderer.clear();
|
||||
this.renderer.render(this.scene, camera);
|
||||
this.renderer.readRenderTargetPixels(target, 0, 0, w, h, pixels);
|
||||
// the target's rows start at the bottom
|
||||
const img = ctx.createImageData(w, h);
|
||||
for (let row = 0; row < h; row++) img.data.set(pixels.subarray((h - 1 - row) * w * 4, (h - row) * w * 4), row * w * 4);
|
||||
ctx.putImageData(img, 0, 0);
|
||||
out.push({ floorId: fv.floor.id, url: canvas.toDataURL("image/png") });
|
||||
for(const node of nodes){
|
||||
const ids=new Set(node.floorIds),selected=this.floors.filter((f)=>ids.has(f.floor.id));
|
||||
const box=new Box3();
|
||||
for(const fv of this.floors){
|
||||
const visible=ids.has(fv.floor.id);fv.group.visible=visible;if(!visible)continue;
|
||||
fv.y=0;fv.o=1;this.applyFloor(fv);fv.group.visible=true;fv.mask.standing.value=0;fv.mask.glass.value=0;
|
||||
const f=fv.floor,room=node.room&&node.room.floorId===f.id?f.rooms.find((r)=>r.id===node.room!.roomId):null;
|
||||
const points=room?room.points:[...f.rooms.flatMap((r)=>r.points),...f.outdoor.flatMap((a)=>a.points),...(f.walls??[]).flatMap((wall)=>[wall.a,wall.b]),...f.furniture.flatMap((m)=>[[m.x-m.w/2,m.z-m.d/2],[m.x+m.w/2,m.z+m.d/2]] as Vec2[])];
|
||||
for(const [x,z] of points){box.expandByPoint(new Vector3(x,f.elevation,z));box.expandByPoint(new Vector3(x,f.elevation+Math.min(f.cut_height,f.height),z));}
|
||||
}
|
||||
if(!selected.length||box.isEmpty())continue;
|
||||
box.expandByScalar(.25);
|
||||
this.renderer.clippingPlanes=node.room?[new Plane(new Vector3(1,0,0),-box.min.x),new Plane(new Vector3(-1,0,0),box.max.x),new Plane(new Vector3(0,0,1),-box.min.z),new Plane(new Vector3(0,0,-1),box.max.z)]:[];
|
||||
const center=box.getCenter(new Vector3()),theta=-.6,phi=.8,dir=new Vector3(Math.sin(phi)*Math.sin(theta),Math.cos(phi),Math.sin(phi)*Math.cos(theta));
|
||||
camera.position.copy(center).addScaledVector(dir,Math.max(100,box.getSize(new Vector3()).length()*2));camera.lookAt(center);camera.updateMatrixWorld();
|
||||
let rx=.5,ry=.5;
|
||||
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);rx=Math.max(rx,Math.abs(p.x));ry=Math.max(ry,Math.abs(p.y));}
|
||||
const aspect=w/h;if(rx/ry>aspect)ry=rx/aspect;else rx=ry*aspect;
|
||||
camera.left=-rx*1.05;camera.right=rx*1.05;camera.top=ry*1.05;camera.bottom=-ry*1.05;camera.updateProjectionMatrix();
|
||||
this.renderer.setRenderTarget(target);this.renderer.clear();this.renderer.render(this.scene,camera);this.renderer.readRenderTargetPixels(target,0,0,w,h,pixels);
|
||||
const img=ctx.createImageData(w,h);for(let row=0;row<h;row++)img.data.set(pixels.subarray((h-1-row)*w*4,(h-row)*w*4),row*w*4);ctx.putImageData(img,0,0);
|
||||
out.push({key:node.key,url:canvas.toDataURL("image/png")});
|
||||
}
|
||||
} finally {
|
||||
this.renderer.setRenderTarget(null);
|
||||
this.renderer.setClearAlpha(clear);
|
||||
for (const s of saved) {
|
||||
s.fv.y = s.y;
|
||||
s.fv.o = s.o;
|
||||
s.fv.mask.standing.value = s.standing;
|
||||
s.fv.mask.glass.value = s.glass;
|
||||
this.applyFloor(s.fv);
|
||||
s.fv.group.visible = s.visible;
|
||||
}
|
||||
if (this.roof) this.roof.group.visible = roofVisible;
|
||||
if (this.ghost) this.ghost.visible = ghostVisible;
|
||||
target.dispose();
|
||||
this.invalidate();
|
||||
}finally{
|
||||
this.renderer.setRenderTarget(null);this.renderer.setClearAlpha(clear);this.renderer.clippingPlanes=planes;
|
||||
for(const s of saved){s.fv.y=s.y;s.fv.o=s.o;s.fv.mask.standing.value=s.standing;s.fv.mask.glass.value=s.glass;this.applyFloor(s.fv);s.fv.group.visible=s.visible;}
|
||||
for(const x of others)x.node.visible=x.visible;
|
||||
target.dispose();this.invalidate();
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user